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

Compile prepared Qamomile semantics through explicit target pipelines.

Design center

The stable user workflow remains circuit-first: an engine Transpiler accepts a qkernel, preserves compile-time bindings and runtime parameters, and returns an ExecutableProgram. Internally, compilation now separates frontend preparation from target lowering so circuit SDKs and program-graph targets do not have to pretend to consume the same abstraction.

Shared preparation

QamomileCompiler.prepare() performs the target-independent prefix:

::

QKernelLike
   │  trace + validate entrypoint
   │  substitute configured callables
   │  resolve parameter-array shapes
   ▼
PreparedModule
   ├─ hierarchical semantic entrypoint
   ├─ reachable callable definitions
   ├─ call graph
   └─ public classical ABI

PreparedModule deliberately preserves structured control flow and callable boundaries. It is the last representation shared by every target family.

Target families

Circuit-family SDKs such as Qiskit, QURI Parts, CUDA-Q, and PyQret retain the existing Transpiler execution UX and take the host-orchestrated path:

::

PreparedModule
   │  inline + recursion unroll + affine/borrow validation
   │  partial evaluation + classical lowering + shape validation
   │  segment into C → Q → C
   ▼
ProgramPlan
   │  lower quantum segments once
   ▼
CircuitProgram                (immutable engine-neutral codegen IR)
   │  verify ordered linear wires, regions, calls, and expressions
   │  legalize + verify target capability declarations
   │  materialize native SDK objects
   ▼
ExecutableProgram[ArtifactT]  (sampling/expectation orchestration)

Program-graph targets such as HUGR compile the preserved program structure directly instead of passing through circuit segmentation:

::

PreparedModule
   │  CompilationTarget.plan()
   │  CompilationTarget.compile()
   │  CompilationTarget.validate()
   ▼
CompiledProgram[ArtifactT]    (artifact + ABI + diagnostics + metadata)

The two results are intentionally different. ExecutableProgram represents Qamomile’s host-driven execution model; CompiledProgram packages a native module or graph whose runtime model belongs to the target.

Program-graph executables reuse the shared jobs, execution handles, capabilities, and public ABI exported by this facade. Targets retain control of native execution while presenting the same result and lifecycle contracts.

Design principles

Overview

FunctionDescription
aggregate_typed_resultsCombine counts whose converted public result values are equal.
dict_param_keyFormat the engine-parameter name for one entry of a Dict parameter.
flatten_user_bindingsFlatten public arrays and dictionaries into scalar ABI keys.
inline_callablesExpand inline-policy callables once with the compiler’s default policy.
lower_compile_time_ifs_preserving_loop_conditionsSpecialize compile-time branches without erasing loop conditions.
pair_block_operandsPair all block inputs with category-grouped call-site operands.
prepare_moduleCollect a hierarchical block into an immutable program-level view.
validate_program_graph_semanticsValidate shared semantics for a direct program-graph target.
ClassDescription
CallableDefinitionConflictErrorReport two incompatible definitions claiming one callable symbol.
ClassicalExecutorExecutes classical segments in Python.
ClassicalSegmentA segment of pure classical operations.
CompilationDiagnosticDescribe one target-independent or target-specific diagnostic.
CompilationMetadataRecord how a target artifact was produced.
CompilationTargetDefine the contract implemented by every compilation target.
CompiledProgramPackage an artifact with its ABI, diagnostics, and provenance.
CompilerConfigConfigure semantic preparation and target-independent rewrites.
CompletedExecutionHandleWrap an already available result for synchronous executors.
CompositeExecutionHandleAggregate several independently submitted executions.
DiagnosticSeverityClassify the severity of a compilation diagnostic.
EmitErrorReport an engine failure to emit one semantic operation.
ExactRequest an analytic expectation value without shot noise.
ExecutionCapabilitiesDeclare the execution features implemented by one executor.
ExecutionContextHolds global state during program execution.
ExecutionErrorError during program execution.
ExecutionHandleExpose an engine execution without forcing immediate result retrieval.
ExecutionReferenceStore secret-free identifiers needed to restore remote execution.
ExecutionSnapshotStore a remote leaf, a local value, or an ordered execution group.
ExecutionSnapshotKindIdentify the reconstruction contract of an execution snapshot node.
ExpvalJobJob for expectation value computation.
JobAbstract base class for quantum execution jobs.
JobKindIdentify the public operation needed to reconstruct a typed job.
JobSnapshotStore operation metadata and lossless raw execution reconstruction.
JobStatusDescribe a provider-independent execution state.
MappedExecutionHandleLazily transform another execution handle’s result.
PreparedModuleHold a prepared entrypoint and its reachable callable definitions.
ProgramABIRuntime-visible ABI for a segmented program.
QKernelLikeDescribe the frontend surface required by compiler entrypoints.
QamomileCompilerPrepare Qamomile semantics and dispatch explicit target compilation.
RunJobJob for single execution.
SampleResultResult of a sample() execution.
ShotBasedRequest a shot-based expectation value.
TargetCapabilityErrorA program requires a capability the selected target does not declare.
TargetPrecisionRequest an expectation value at a provider target precision.

Constants

Functions

aggregate_typed_results [source]

def aggregate_typed_results(results: Iterable[tuple[T, int]]) -> list[tuple[T, int]]

Combine counts whose converted public result values are equal.

Engine raw bitstrings can differ only on qubits that are not part of the program output. After result conversion those rows represent the same public value and must appear as one SampleResult entry.

Parameters:

NameTypeDescription
resultsIterable[tuple[T, int]]Converted result values and counts.

Returns:

list[tuple[T, int]] — list[tuple[T, int]]: Stable first-seen values with duplicate counts summed.


dict_param_key [source]

def dict_param_key(dict_name: str, key: Any) -> str

Format the engine-parameter name for one entry of a Dict parameter.

The key is formatted with repr rather than str so the helper is collision-proof on its own: str("0") and str(0) both yield "coeffs[0]", but repr keeps the string key distinct ("coeffs['0']"). Callers pass keys already normalized to plain int / tuple-of-int (see :func:normalize_dict_binding_key), for which repr and str produce identical text (repr(3) == '3', repr((0, 1)) == '(0, 1)'), so the emitted names are unchanged.

Parameters:

NameTypeDescription
dict_namestrThe kernel argument name of the Dict parameter.
keyAnyThe looked-up key, already normalized (a plain int or a tuple of plain ints — see :func:normalize_dict_binding_key).

Returns:

str — The engine parameter name, e.g. "coeffs[3]" for an int key or "coeffs[(0, 1)]" for a tuple key.


flatten_user_bindings [source]

def flatten_user_bindings(bindings: Mapping[str, Any] | None) -> dict[str, Any]

Flatten public arrays and dictionaries into scalar ABI keys.

Parameters:

NameTypeDescription
bindingsMapping[str, Any] | NoneRaw user bindings keyed by kernel parameter name.

Returns:

dict[str, Any] — dict[str, Any]: Scalar and dictionary entries keyed by emitted ABI names.


inline_callables [source]

def inline_callables(
    block: Block,
    *,
    body_selector: Callable[[InvokeOperation], Block | None] | None = None,
) -> Block

Expand inline-policy callables once with the compiler’s default policy.

Boxed calls, transformed calls, and recursive calls that remain after one pass are preserved. Direct program-graph targets use this narrow helper at target legalization boundaries without depending on the configurable compiler pass implementation.

Parameters:

NameTypeDescription
blockBlockHierarchical or traced semantic block to rewrite.
body_selectorCallable[[InvokeOperation], Block | None] | NoneOptional selector returning the body to inline, or None to retain a call boundary. Defaults to the ordinary effective body.

Returns:

Block — Block after one default callable-inlining pass.

Raises:


lower_compile_time_ifs_preserving_loop_conditions [source]

def lower_compile_time_ifs_preserving_loop_conditions(block: Block, bindings: dict[str, Any] | None = None) -> Block

Specialize compile-time branches without erasing loop conditions.

Parameters:

NameTypeDescription
blockBlockBlock whose resolvable compile-time branches should be lowered.
bindingsdict[str, Any] | NoneCompile-time input bindings used for condition resolution. Defaults to None.

Returns:

Block — Specialized block with loop-carried conditions preserved.

Raises:


pair_block_operands [source]

def pair_block_operands(
    block: Block,
    operands: Sequence[ValueBase],
) -> list[tuple[ValueBase, ValueBase]]

Pair all block inputs with category-grouped call-site operands.

Parameters:

NameTypeDescription
blockBlockOperation-owned block whose inputs are being bound.
operandsSequence[ValueBase]Call-site operands after any controls that are external to block have been removed.

Returns:

list[tuple[ValueBase, ValueBase]] — list[tuple[ValueBase, ValueBase]]: Formal/actual pairs in the block’s list[tuple[ValueBase, ValueBase]] — declaration order.


prepare_module [source]

def prepare_module(entrypoint: Block, bindings: Mapping[str, Any] | None = None) -> PreparedModule

Collect a hierarchical block into an immutable program-level view.

The collector follows calls in nested control-flow regions, SELECT case Blocks, and every body carried by a callable definition. Definitions remain Qamomile semantic IR; this function does not inline, clone, or lower operations.

Parameters:

NameTypeDescription
entrypointBlockHierarchical entrypoint after target-independent frontend preparation.
bindingsMapping[str, Any] | NoneCompile-time values that cannot be embedded in scalar value metadata, such as Hamiltonians. Defaults to None.

Returns:

PreparedModule — Entrypoint, reachable definitions, call graph, and public ABI. :class:QamomileCompiler creates a deep target-owned snapshot before invoking a target pipeline.


validate_program_graph_semantics [source]

def validate_program_graph_semantics(program: PreparedModule) -> None

Validate shared semantics for a direct program-graph target.

Circuit-family planning runs these checks during partial evaluation, analysis, and segmentation. A direct program-graph target preserves the prepared structure, so this helper runs only the non-destructive semantic checks. Inline-policy callables are expanded in the validation view so their formal values retain call-site provenance; the prepared program itself remains hierarchical.

Parameters:

NameTypeDescription
programPreparedModulePrepared entrypoint and callable bodies.

Raises:

Classes

CallableDefinitionConflictError [source]

class CallableDefinitionConflictError(QamomileCompileError)

Report two incompatible definitions claiming one callable symbol.

Parameters:

NameTypeDescription
symbolstrFully qualified callable symbol with conflicting bodies.

Example:

Correct — give independently implemented callables distinct origins
or explicit namespaces::

    configure_composite(left, namespace="example.left")
    configure_composite(right, namespace="example.right")

Incorrect — attaching two different bodies to the same explicit
symbol causes this error during preparation::

    configure_composite(left, namespace="example.shared", name="op")
    configure_composite(right, namespace="example.shared", name="op")

Constructor

def __init__(self, symbol: str) -> None

Initialize a callable-definition collision diagnosis.

Parameters:

NameTypeDescription
symbolstrFully qualified callable symbol with conflicting definitions.

Attributes


ClassicalExecutor [source]

class ClassicalExecutor

Executes classical segments in Python.

Methods

execute
def execute(self, segment: ClassicalSegment, context: ExecutionContext) -> dict[str, Any]

Execute classical operations and return outputs.

Interprets the operations list directly using Python.

Parameters:

NameTypeDescription
segmentClassicalSegmentOrdered classical operations and declared outputs to evaluate.
contextExecutionContextPer-shot quantum and bound input values available to the segment.

Returns:

dict[str, Any] — dict[str, Any]: Computed classical values keyed by result UUID.

Raises:

resolve_value
def resolve_value(self, value: ValueLike, context: ExecutionContext) -> Any

Resolve a typed classical output using the execution interpreter.

Parameters:

NameTypeDescription
valueValueLikeScalar, array, tuple, or dictionary output.
contextExecutionContextRuntime bindings and computed values keyed by their IR identities or public parameter names.

Returns:

Any — Concrete value with tuple and dictionary structure retained.

Raises:


ClassicalSegment [source]

class ClassicalSegment(Segment)

A segment of pure classical operations.

Contains arithmetic, comparisons, and control flow. Will be executed directly in Python.

Constructor

def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
) -> None

Attributes


CompilationDiagnostic [source]

class CompilationDiagnostic

Describe one target-independent or target-specific diagnostic.

Parameters:

NameTypeDescription
severityDiagnosticSeverityDiagnostic severity.
messagestrHuman-readable explanation.
codestr | NoneStable machine-readable diagnostic code.
sourcestr | NoneOptional source location or IR provenance label.

Constructor

def __init__(
    self,
    severity: DiagnosticSeverity,
    message: str,
    code: str | None = None,
    source: str | None = None,
) -> None

Attributes


CompilationMetadata [source]

class CompilationMetadata

Record how a target artifact was produced.

Parameters:

NameTypeDescription
targetstrStable compilation target name.
pipelinestrLowering-family or pipeline name.
propertiesMapping[str, Any]Additional immutable-by-contract target metadata. Defaults to an empty mapping.

Constructor

def __init__(
    self,
    target: str,
    pipeline: str,
    properties: Mapping[str, Any] = dict(),
) -> None

Attributes


CompilationTarget [source]

class CompilationTarget(Protocol[PlanT, ArtifactT])

Define the contract implemented by every compilation target.

Attributes

Methods

compile
def compile(self, program: PreparedModule, plan: PlanT) -> CompiledProgram[ArtifactT]

Lower and materialize a prepared program for this target.

Parameters:

NameTypeDescription
programPreparedModulePrepared semantic program.
planPlanTDecisions returned by :meth:plan.

Returns:

CompiledProgram[ArtifactT] — CompiledProgram[ArtifactT]: Target-native artifact and metadata.

plan
def plan(self, program: PreparedModule) -> PlanT

Choose target-specific lowering decisions for a program.

Parameters:

NameTypeDescription
programPreparedModulePrepared semantic program.

Returns:

PlanT — Immutable target-specific compilation plan.

validate
def validate(self, artifact: ArtifactT) -> None

Validate a materialized artifact with target-native rules.

Parameters:

NameTypeDescription
artifactArtifactTTarget-native artifact to validate.

Raises:


CompiledProgram [source]

class CompiledProgram(Generic[ArtifactT])

Package an artifact with its ABI, diagnostics, and provenance.

Parameters:

NameTypeDescription
artifactArtifactTTarget-native circuit, graph, module, or package.
abiProgramABIRuntime-visible input and output contract.
metadataCompilationMetadataTarget and pipeline provenance.
diagnosticstuple[CompilationDiagnostic, ...]Non-fatal compilation diagnostics. Defaults to an empty tuple.

Constructor

def __init__(
    self,
    artifact: ArtifactT,
    abi: ProgramABI,
    metadata: CompilationMetadata,
    diagnostics: tuple[CompilationDiagnostic, ...] = (),
) -> None

Attributes


CompilerConfig [source]

class CompilerConfig

Configure semantic preparation and target-independent rewrites.

Parameters:

NameTypeDescription
decompositionDecompositionConfigComposite-gate decomposition choices. Defaults to the standard decomposition configuration.
substitutionsSubstitutionConfigCallable substitution rules. Defaults to no substitutions.

Constructor

def __init__(
    self,
    decomposition: DecompositionConfig = DecompositionConfig(),
    substitutions: SubstitutionConfig = SubstitutionConfig(),
) -> None

Attributes

Methods

with_strategies
@classmethod
def with_strategies(
    cls,
    strategy_overrides: dict[str, str] | None = None,
    **kwargs: Any = {},
) -> 'CompilerConfig'

Create configuration with named decomposition strategies.

Parameters:

NameTypeDescription
strategy_overridesdict[str, str] | NoneGate-name to strategy mapping. Defaults to an empty mapping.
**kwargsAnyAdditional :class:CompilerConfig constructor arguments.

Returns:

'CompilerConfig' — Configuration containing matching decomposition and substitution rules.


CompletedExecutionHandle [source]

class CompletedExecutionHandle(ExecutionHandle[ResultT])

Wrap an already available result for synchronous executors.

Parameters:

NameTypeDescription
valueResultTCompleted execution value.

Constructor

def __init__(self, value: ResultT) -> None

Initialize an immediately completed execution.

Parameters:

NameTypeDescription
valueResultTCompleted execution value.

Methods

result
def result(self, timeout: float | None = None) -> ResultT

Return the completed value without waiting.

Parameters:

NameTypeDescription
timeoutfloat | NoneIgnored compatibility timeout.

Returns:

ResultT — Stored execution value.

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture the already available raw result without waiting.

Returns:

ExecutionSnapshot — Owned, type-preserving local value.

Raises:

status
def status(self) -> JobStatus

Return the completed status.

Returns:

JobStatus — Always :attr:JobStatus.COMPLETED.


CompositeExecutionHandle [source]

class CompositeExecutionHandle(ExecutionHandle[tuple[ResultT, ...]])

Aggregate several independently submitted executions.

Parameters:

NameTypeDescription
handlesSequence[ExecutionHandle[ResultT]]Child executions in stable result order.

Constructor

def __init__(self, handles: Sequence[ExecutionHandle[ResultT]]) -> None

Initialize an ordered execution aggregate.

Parameters:

NameTypeDescription
handlesSequence[ExecutionHandle[ResultT]]Child executions.

Attributes

Methods

cancel
def cancel(self) -> None

Attempt cancellation of every child not known to be terminal.

A status lookup failure leaves the child’s state unknown, so cancellation is still attempted. Failures are reported together after all children have been visited, retaining the original exceptions and tracebacks.

Raises:

metadata
def metadata(self) -> Mapping[str, Any]

Return metadata grouped by child index.

Returns:

Mapping[str, Any] — Mapping[str, Any]: Child metadata sequence.

raw_status
def raw_status(self) -> object

Return every child provider status.

Returns:

object — Tuple of child raw statuses.

references
def references(self) -> tuple[ExecutionReference, ...]

Return the legacy one-reference-per-child view.

This flat view cannot preserve child boundaries when a child exposes zero or multiple references. Use :meth:snapshot to retain local results and nested groups in their original positions.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Ordered child references, or an empty tuple when any child does not expose exactly one.

result
def result(self, timeout: float | None = None) -> tuple[ResultT, ...]

Return all child results in submission order.

Parameters:

NameTypeDescription
timeoutfloat | NoneTotal local wait budget in seconds.

Returns:

tuple[ResultT, ...] — tuple[ResultT, ...]: Ordered child results.

Raises:

result_async
def result_async(self, timeout: float | None = None) -> tuple[ResultT, ...]

Return all child results asynchronously.

Parameters:

NameTypeDescription
timeoutfloat | NoneTotal local wait budget in seconds.

Returns:

tuple[ResultT, ...] — tuple[ResultT, ...]: Ordered child results.

Raises:

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture all children with their original tuple boundaries.

Returns:

ExecutionSnapshot — Ordered nested execution structure.

Raises:

status
def status(self) -> JobStatus

Aggregate child statuses without hiding partial completion.

Returns:

JobStatus — Aggregate execution status.


DiagnosticSeverity [source]

class DiagnosticSeverity(enum.Enum)

Classify the severity of a compilation diagnostic.

Attributes


EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return

Constructor

def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Attributes


Exact [source]

class Exact

Request an analytic expectation value without shot noise.

Constructor

def __init__(self) -> None

ExecutionCapabilities [source]

class ExecutionCapabilities

Declare the execution features implemented by one executor.

Parameters:

NameTypeDescription
supports_async_samplingboolWhether sampling submission returns before provider execution completes. Defaults to False.
supports_async_estimationboolWhether expectation submission returns before provider execution completes. Defaults to False.
supports_estimationboolWhether expectation-value execution is implemented. Defaults to False.
supports_cancellationboolWhether provider-backed handles can request cancellation. Defaults to False.
supports_restorationboolWhether execution references can recreate provider-backed handles. Defaults to False.
supports_native_batchboolWhether multiple logical requests can be submitted through one provider-native batch or job. Defaults to False.
supports_native_parameter_inputsboolWhether runtime values remain separate from emitted circuits during provider submission. Defaults to False.
estimation_accuracyfrozenset[EstimationPolicyType]Explicit per-request accuracy policies accepted by the executor. An empty set means only executor-configured estimation behavior is available.

Raises:

Constructor

def __init__(
    self,
    supports_async_sampling: bool = False,
    supports_async_estimation: bool = False,
    supports_estimation: bool = False,
    supports_cancellation: bool = False,
    supports_restoration: bool = False,
    supports_native_batch: bool = False,
    supports_native_parameter_inputs: bool = False,
    estimation_accuracy: frozenset[EstimationPolicyType] = frozenset(),
) -> None

Attributes


ExecutionContext [source]

class ExecutionContext

Holds global state during program execution.

Constructor

def __init__(self, initial_bindings: dict[str, Any] | None = None)

Methods

copy
def copy(self) -> 'ExecutionContext'

Clone the execution context.

get
def get(self, key: str) -> Any
get_many
def get_many(self, keys: list[str]) -> dict[str, Any]
has
def has(self, key: str) -> bool
set
def set(self, key: str, value: Any) -> None
update
def update(self, values: dict[str, Any]) -> None

ExecutionError [source]

class ExecutionError(QamomileCompileError)

Error during program execution.


ExecutionHandle [source]

class ExecutionHandle(ABC, Generic[ResultT])

Expose an engine execution without forcing immediate result retrieval.

Attributes

Methods

cancel
def cancel(self) -> None

Request best-effort cancellation.

Cancellation is intentionally not reported as a boolean because providers may accept a request after execution has already started. Call :meth:status to observe the eventual state.

metadata
def metadata(self) -> Mapping[str, Any]

Return optional provider execution metadata.

Returns:

Mapping[str, Any] — Mapping[str, Any]: Provider metadata such as timestamps or usage.

raw_status
def raw_status(self) -> object

Return provider-specific status information.

Returns:

object — Provider status value, or the normalized status when no richer value exists.

references
def references(self) -> tuple[ExecutionReference, ...]

Return serializable remote execution references.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Secret-free provider references.

result
def result(self, timeout: float | None = None) -> ResultT

Wait for and return the engine-neutral raw result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds. None delegates the wait policy to the provider.

Returns:

ResultT — Raw result normalized by the engine executor.

Raises:

result_async
def result_async(self, timeout: float | None = None) -> ResultT

Wait asynchronously for the engine-neutral raw result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds. Defaults to provider behavior when None.

Returns:

ResultT — Raw result normalized by the engine executor.

Raises:

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture one remote execution without fetching its result.

Adapters exposing several logical references must override this method with an explicit reconstruction structure. A provider reference may itself contain multiple physical job IDs.

Returns:

ExecutionSnapshot — One opaque provider execution.

Raises:

status
def status(self) -> JobStatus

Return the current provider-independent execution status.

Returns:

JobStatus — Current normalized status.


ExecutionReference [source]

class ExecutionReference

Store secret-free identifiers needed to restore remote execution.

Parameters:

NameTypeDescription
providerstrStable provider or adapter name.
job_idstuple[str, ...]One or more provider job identifiers.
targetstr | NoneProvider target or device identifier. Defaults to None.
group_idstr | NoneSession, batch, program, or parent identifier. Defaults to None.
contextMapping[str, str]Additional non-secret identifiers needed to restore the job. Defaults to an empty mapping.

Raises:

Constructor

def __init__(
    self,
    provider: str,
    job_ids: tuple[str, ...],
    target: str | None = None,
    group_id: str | None = None,
    context: Mapping[str, str] = dict(),
) -> None

Attributes

Methods

from_dict
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionReference

Reconstruct a provider reference from JSON-compatible data.

Parameters:

NameTypeDescription
dataMapping[str, Any]Mapping produced by :meth:to_dict.

Returns:

ExecutionReference — Validated provider execution reference.

Raises:

to_dict
def to_dict(self) -> dict[str, Any]

Convert the provider reference to JSON-compatible data.

Returns:

dict[str, Any] — dict[str, Any]: Provider identifiers and decoding context without credentials or SDK objects.


ExecutionSnapshot [source]

class ExecutionSnapshot

Store a remote leaf, a local value, or an ordered execution group.

Provider leaves may identify several physical jobs or produce native batch results. Composite children retain their result boundaries independently of the number of provider identifiers. Local values contain raw engine-neutral results, before the executable applies its public result conversion. Trees and local values support at most 100 levels of nesting.

Parameters:

NameTypeDescription
kindstr | ExecutionSnapshotKindOne of remote, local, or composite, normalized to an enum member.
referenceExecutionReference | NoneRequired only for remote leaves.
valueAnySupported native result for local leaves. Defaults to None.
childrentuple[ExecutionSnapshot, ...]Ordered composite children. Defaults to an empty tuple.

Raises:

Constructor

def __init__(
    self,
    kind: str | ExecutionSnapshotKind,
    reference: ExecutionReference | None = None,
    value: Any = None,
    children: tuple[ExecutionSnapshot, ...] = (),
) -> None

Attributes

Methods

from_dict
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionSnapshot

Reconstruct an execution tree with strict node and value validation.

Parameters:

NameTypeDescription
dataMapping[str, Any]Mapping produced by :meth:to_dict.

Returns:

ExecutionSnapshot — Validated execution structure.

Raises:

references
def references(self) -> tuple[ExecutionReference, ...]

Collect provider leaves in order without discarding tree structure.

This list supports diagnostics; restoration uses the complete tree.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Detached remote references in order.

Raises:

restore
def restore(
    self,
    restore_reference: Callable[[ExecutionReference], ExecutionHandle[Any]],
) -> ExecutionHandle[Any]

Reattach remote leaves and rebuild local values and ordered groups.

The callback must reattach an existing provider execution. This method neither retrieves remote results nor submits any execution.

Parameters:

NameTypeDescription
restore_referenceCallable[[ExecutionReference], ExecutionHandle[Any]]Provider-specific callback for one complete remote leaf.

Returns:

ExecutionHandle[Any] — ExecutionHandle[Any]: Reconstructed raw execution lifecycle.

Raises:

to_dict
def to_dict(self) -> dict[str, Any]

Serialize the execution tree and type-preserving local values.

Returns:

dict[str, Any] — dict[str, Any]: JSON-compatible execution tree.

Raises:


ExecutionSnapshotKind [source]

class ExecutionSnapshotKind(StrEnum)

Identify the reconstruction contract of an execution snapshot node.

Attributes


ExpvalJob [source]

class ExpvalJob(Job[float])

Job for expectation value computation.

Returns a single float representing <psi|H|psi>.

Constructor

def __init__(self, exp_val: float | ExecutionHandle[float]) -> None

Initialize expval job.

Parameters:

NameTypeDescription
exp_valfloat | ExecutionHandle[float]Completed value or deferred expectation execution.

Methods

result
def result(self, timeout: float | None = None) -> float

Wait for and return the expectation value.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

float — Expectation value.

result_async
def result_async(self, timeout: float | None = None) -> float

Wait asynchronously for and return the expectation value.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

float — Expectation value.


Job [source]

class Job(ABC, Generic[T])

Abstract base class for quantum execution jobs.

A Job represents a quantum execution that can be awaited for results.

Constructor

def __init__(
    self,
    handle: ExecutionHandle[Any],
    kind: JobKind,
    shots: int | None = None,
) -> None

Initialize a public job around an execution handle.

Parameters:

NameTypeDescription
handleExecutionHandle[Any]Raw or mapped engine execution.
kindJobKindPublic operation represented by the job.
shotsint | NoneSampling shot count. Defaults to None for run jobs.

Attributes

Methods

cancel
def cancel(self) -> None

Request best-effort cancellation of the underlying execution.

metadata
def metadata(self) -> Mapping[str, Any]

Return provider execution metadata.

Returns:

Mapping[str, Any] — Mapping[str, Any]: Provider-specific metadata.

raw_status
def raw_status(self) -> object

Return provider-specific status information.

Returns:

object — Provider status or aggregate status values.

references
def references(self) -> tuple[ExecutionReference, ...]

Return the execution handle’s legacy provider-reference view.

Use :meth:snapshot for typed restoration of local values or nested groups, which a flat reference list cannot represent completely.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Provider execution references.

result
def result(self, timeout: float | None = None) -> T

Wait for and return the result.

Blocks until the job completes.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds. None uses provider behavior.

Returns:

T — Execution result with the appropriate public type.

Raises:

result_async
def result_async(self, timeout: float | None = None) -> T

Wait asynchronously for and return the public result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds. Defaults to provider behavior when None.

Returns:

T — Execution result with the appropriate public type.

snapshot
def snapshot(self) -> JobSnapshot

Capture secret-free information needed for typed restoration.

Returns:

JobSnapshot — Public metadata, local values, and remote references with ordered execution boundaries. No remote results are read.

Raises:

status
def status(self) -> JobStatus

Return the current job status.

Returns:

JobStatus — Current normalized status.


JobKind [source]

class JobKind(StrEnum)

Identify the public operation needed to reconstruct a typed job.

Attributes


JobSnapshot [source]

class JobSnapshot

Store operation metadata and lossless raw execution reconstruction.

Runtime bindings are intentionally excluded. They can contain arbitrary application data, so callers supply them again to :meth:ExecutableProgram.restore instead of persisting them implicitly.

Parameters:

NameTypeDescription
kindJobKindPublic operation that created the job.
executionstuple[ExecutionReference, ...]Ordered provider reference inventory. Empty for entirely local structured executions. For legacy snapshots, these references also specify the result layout.
shotsint | NoneSampling shot count. Required for sample jobs and absent for run jobs.
executionExecutionSnapshot | NoneOrdered remote/local execution tree. None denotes the legacy flat-reference format. When present, executions must exactly match its remote leaves.

Raises:

Constructor

def __init__(
    self,
    kind: JobKind,
    executions: tuple[ExecutionReference, ...],
    shots: int | None = None,
    execution: ExecutionSnapshot | None = None,
) -> None

Attributes

Methods

from_dict
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> JobSnapshot

Reconstruct a validated snapshot from JSON-compatible data.

Parameters:

NameTypeDescription
dataMapping[str, Any]Mapping produced by :meth:to_dict.

Returns:

JobSnapshot — Validated typed-job restoration snapshot.

Raises:

to_dict
def to_dict(self) -> dict[str, Any]

Convert the snapshot to JSON-compatible data.

Returns:

dict[str, Any] — dict[str, Any]: Version 2 operation metadata and execution tree, or the original legacy format for a flat-reference snapshot.

Raises:


JobStatus [source]

class JobStatus(Enum)

Describe a provider-independent execution state.

The numeric values of the original four states remain stable for serialization compatibility.

Attributes


MappedExecutionHandle [source]

class MappedExecutionHandle(ExecutionHandle[MappedT], Generic[ResultT, MappedT])

Lazily transform another execution handle’s result.

Parameters:

NameTypeDescription
sourceExecutionHandle[ResultT]Underlying execution handle.
transformCallable[[ResultT], MappedT]Result transformation.
snapshot_sourceboolWhether the owning executable reconstructs this transformation when restoring the source. Defaults to False.

Constructor

def __init__(
    self,
    source: ExecutionHandle[ResultT],
    transform: Callable[[ResultT], MappedT],
    *,
    snapshot_source: bool = False,
) -> None

Initialize a lazy mapped execution.

Parameters:

NameTypeDescription
sourceExecutionHandle[ResultT]Underlying execution handle.
transformCallable[[ResultT], MappedT]Result transformation.
snapshot_sourceboolAllow source snapshots only when the owner rebuilds the transformation on restore. Defaults to False.

Attributes

Methods

cancel
def cancel(self) -> None

Forward a cancellation request to the source execution.

metadata
def metadata(self) -> Mapping[str, Any]

Return source execution metadata.

Returns:

Mapping[str, Any] — Mapping[str, Any]: Source metadata.

raw_status
def raw_status(self) -> object

Return the source provider status.

Returns:

object — Provider-specific source status.

references
def references(self) -> tuple[ExecutionReference, ...]

Return source execution references.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Source references.

result
def result(self, timeout: float | None = None) -> MappedT

Retrieve and transform the source result once.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

MappedT — Cached transformed result.

Raises:

result_async
def result_async(self, timeout: float | None = None) -> MappedT

Retrieve and transform the source result asynchronously.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

MappedT — Cached transformed result.

Raises:

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture a source whose mapping is rebuilt by its owning executable.

Python callables are never serialized. Arbitrary mappings must supply an adapter-specific restoration recipe instead of losing conversion.

Returns:

ExecutionSnapshot — Source reconstruction structure.

Raises:

status
def status(self) -> JobStatus

Return the source execution status.

Returns:

JobStatus — Current mapped execution status.


PreparedModule [source]

class PreparedModule

Hold a prepared entrypoint and its reachable callable definitions.

Parameters:

NameTypeDescription
entrypoint_refCallableRefStable symbol assigned to the program entrypoint.
entrypointBlockHierarchical semantic block for the entrypoint.
definitionsMapping[CallableRef, CallableDef]Reachable callable definitions keyed by their stable symbols.
definition_variantsMapping[CallableRef, tuple[CallableDef, ...]]Every distinct body observed for a symbol. Multiple variants of one origin may be valid for circuit-family inlining but must be handled or rejected by targets that emit one function per symbol.
call_graphMapping[CallableRef, frozenset[CallableRef]]Directed caller-to-callee relation, including the entrypoint symbol.
abiProgramABIClassical public input and output contract.
bindingsMapping[str, Any]Compile-time values retained for direct program-graph targets. Circuit-family targets receive the same values through their emit pass.

Constructor

def __init__(
    self,
    entrypoint_ref: CallableRef,
    entrypoint: Block,
    definitions: Mapping[CallableRef, CallableDef],
    definition_variants: Mapping[CallableRef, tuple[CallableDef, ...]],
    call_graph: Mapping[CallableRef, frozenset[CallableRef]],
    abi: ProgramABI,
    bindings: Mapping[str, Any],
) -> None

Attributes

Methods

body
def body(self, ref: CallableRef) -> Block

Return the semantic body associated with a program symbol.

Parameters:

NameTypeDescription
refCallableRefEntrypoint or callable symbol to resolve.

Returns:

Block — Hierarchical semantic body for ref.

Raises:

owned_snapshot
def owned_snapshot(self) -> PreparedModule

Create a deep, target-owned snapshot of prepared semantics.

The semantic IR intentionally remains mutable while compiler passes are being developed. Copying the entrypoint and definition registry as one object graph preserves shared callable bodies while preventing one target from mutating the source module observed by another.

Returns:

PreparedModule — Deep snapshot with read-only definition and call graph registries.


ProgramABI [source]

class ProgramABI

Runtime-visible ABI for a segmented program.

Constructor

def __init__(
    self,
    public_inputs: dict[str, ValueLike] = dict(),
    output_values: list[ValueLike] = list(),
) -> None

Attributes


QKernelLike [source]

class QKernelLike(Protocol)

Describe the frontend surface required by compiler entrypoints.

This protocol is intentionally structural. It lets decorator-created composites reuse the qkernel inspection and build interface without making them inherit from QKernel or exposing the compiler-facing callable descriptor model as a frontend concept.

Attributes

Methods

build
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> Block

Build a traced body block.

Parameters:

NameTypeDescription
parameterslist[str] | NoneRuntime parameter names to preserve. Defaults to None.
**kwargsAnyCompile-time bindings for non-parameter arguments.

Returns:

Block — Traced hierarchical body block.


QamomileCompiler [source]

class QamomileCompiler

Prepare Qamomile semantics and dispatch explicit target compilation.

Parameters:

NameTypeDescription
configCompilerConfig | NoneShared frontend and substitution configuration. Defaults to :class:CompilerConfig.

Constructor

def __init__(self, config: CompilerConfig | None = None) -> None

Initialize the target-neutral compiler.

Parameters:

NameTypeDescription
configCompilerConfig | NoneShared frontend configuration. Defaults to :class:CompilerConfig.

Attributes

Methods

compile
def compile(
    self,
    kernel: QKernelLike,
    target: CompilationTarget[PlanT, ArtifactT],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> CompiledProgram[ArtifactT]

Compile a qkernel with an explicit target implementation.

Parameters:

NameTypeDescription
kernelQKernelLikeTop-level qkernel-like entrypoint.
targetCompilationTarget[PlanT, ArtifactT]Target planner, lowerer, materializer, and validator.
bindingsdict[str, Any] | NoneCompile-time bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.

Returns:

CompiledProgram[ArtifactT] — CompiledProgram[ArtifactT]: Validated target-native artifact.

Raises:

prepare
def prepare(
    self,
    kernel: QKernelLike,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> PreparedModule

Prepare a hierarchical semantic module without destroying calls.

Parameters:

NameTypeDescription
kernelQKernelLikeTop-level qkernel-like entrypoint.
bindingsdict[str, Any] | NoneCompile-time bindings used for tracing and shape resolution. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.

Returns:

PreparedModule — Program-level semantic input for target planning.

Raises:

to_block
def to_block(
    self,
    kernel: QKernelLike,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> Block

Trace a qkernel-like object into a hierarchical semantic block.

Parameters:

NameTypeDescription
kernelQKernelLikeFrontend object to trace.
bindingsdict[str, Any] | NoneCompile-time argument values. Defaults to None.
parameterslist[str] | NoneArgument names retained as runtime parameters. Defaults to None.

Returns:

Block — Hierarchical Qamomile semantic block.

Raises:


RunJob [source]

class RunJob(Job[T], Generic[T])

Job for single execution.

Returns a single result value matching the kernel’s return type.

Constructor

def __init__(
    self,
    raw_counts: dict[str, int] | ExecutionHandle[dict[str, int]] | None,
    result_converter: Callable[[str], T] | None,
    *,
    value_handle: ExecutionHandle[T] | None = None,
) -> None

Initialize run job.

Parameters:

NameTypeDescription
raw_countsdict[str, int] | ExecutionHandle[dict[str, int]] | NoneCounts or deferred counts. May be None with value_handle.
result_converterCallable[[str], T] | NoneFunction converting one bitstring. May be None with value_handle.
value_handleExecutionHandle[T] | NoneHandle already producing the final public value. Defaults to None.

Raises:

Methods

from_handle
@classmethod
def from_handle(cls, handle: ExecutionHandle[T]) -> RunJob[T]

Create a run job whose handle already returns the public value.

Parameters:

NameTypeDescription
handleExecutionHandle[T]Final-value execution handle.

Returns:

RunJob[T] — RunJob[T]: Public run job delegating to handle.

result
def result(self, timeout: float | None = None) -> T

Wait for and return the single public result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

T — Public kernel return value.

result_async
def result_async(self, timeout: float | None = None) -> T

Wait asynchronously for the single public result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

T — Public kernel return value.


SampleResult [source]

class SampleResult(Generic[T])

Result of a sample() execution.

Contains results as a list of (value, count) tuples.

Example:

result.results  # [(0.25, 500), (0.75, 500)]

Constructor

def __init__(self, results: list[tuple[T, int]], shots: int) -> None

Attributes

Methods

most_common
def most_common(self, n: int = 1) -> list[tuple[T, int]]

Return the n most common results.

Parameters:

NameTypeDescription
nintNumber of results to return.

Returns:

list[tuple[T, int]] — List of (result, count) tuples sorted by count descending.

probabilities
def probabilities(self) -> list[tuple[T, float]]

Return probability distribution over results.

Returns:

list[tuple[T, float]] — List of (value, probability) tuples.


ShotBased [source]

class ShotBased

Request a shot-based expectation value.

Parameters:

NameTypeDescription
shotsintPositive number of measurement shots.

Raises:

Constructor

def __init__(self, shots: int) -> None

Attributes


TargetCapabilityError [source]

class TargetCapabilityError(EmitError)

A program requires a capability the selected target does not declare.

Raised by circuit-IR target-legality verification before any engine materialization starts. The message always names the target and the missing capability axis, so the failure reads as a target restriction rather than a Qamomile language error.

Parameters:

NameTypeDescription
messagestrHuman-readable diagnosis naming the target and the missing capability.
targetstr | NoneDeclared target name. Defaults to None.
operationstr | NoneInstruction description that triggered the failure. Defaults to None.

Example:

Correct — bind the runtime parameter before selecting a
concrete-angle-only target::

    transpiler.transpile(kernel, bindings={"theta": 0.5})

Incorrect — keeping ``theta`` symbolic on such a target raises this
error::

    transpiler.transpile(kernel, parameters=["theta"])

Constructor

def __init__(self, message: str, target: str | None = None, operation: str | None = None)

Initialize a target-capability diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable diagnosis naming the target and the missing capability.
targetstr | NoneDeclared target name. Defaults to None.
operationstr | NoneInstruction description that triggered the failure. Defaults to None.

Attributes


TargetPrecision [source]

class TargetPrecision

Request an expectation value at a provider target precision.

Parameters:

NameTypeDescription
precisionfloatPositive absolute target precision.

Raises:

Constructor

def __init__(self, precision: float) -> None

Attributes


qamomile.circuit.transpiler.artifact

Target-neutral containers for compiled artifacts and diagnostics.

Overview

ClassDescription
CompilationDiagnosticDescribe one target-independent or target-specific diagnostic.
CompilationMetadataRecord how a target artifact was produced.
CompiledProgramPackage an artifact with its ABI, diagnostics, and provenance.
DiagnosticSeverityClassify the severity of a compilation diagnostic.
ProgramABIRuntime-visible ABI for a segmented program.

Classes

CompilationDiagnostic [source]

class CompilationDiagnostic

Describe one target-independent or target-specific diagnostic.

Parameters:

NameTypeDescription
severityDiagnosticSeverityDiagnostic severity.
messagestrHuman-readable explanation.
codestr | NoneStable machine-readable diagnostic code.
sourcestr | NoneOptional source location or IR provenance label.
Constructor
def __init__(
    self,
    severity: DiagnosticSeverity,
    message: str,
    code: str | None = None,
    source: str | None = None,
) -> None
Attributes

CompilationMetadata [source]

class CompilationMetadata

Record how a target artifact was produced.

Parameters:

NameTypeDescription
targetstrStable compilation target name.
pipelinestrLowering-family or pipeline name.
propertiesMapping[str, Any]Additional immutable-by-contract target metadata. Defaults to an empty mapping.
Constructor
def __init__(
    self,
    target: str,
    pipeline: str,
    properties: Mapping[str, Any] = dict(),
) -> None
Attributes

CompiledProgram [source]

class CompiledProgram(Generic[ArtifactT])

Package an artifact with its ABI, diagnostics, and provenance.

Parameters:

NameTypeDescription
artifactArtifactTTarget-native circuit, graph, module, or package.
abiProgramABIRuntime-visible input and output contract.
metadataCompilationMetadataTarget and pipeline provenance.
diagnosticstuple[CompilationDiagnostic, ...]Non-fatal compilation diagnostics. Defaults to an empty tuple.
Constructor
def __init__(
    self,
    artifact: ArtifactT,
    abi: ProgramABI,
    metadata: CompilationMetadata,
    diagnostics: tuple[CompilationDiagnostic, ...] = (),
) -> None
Attributes

DiagnosticSeverity [source]

class DiagnosticSeverity(enum.Enum)

Classify the severity of a compilation diagnostic.

Attributes

ProgramABI [source]

class ProgramABI

Runtime-visible ABI for a segmented program.

Constructor
def __init__(
    self,
    public_inputs: dict[str, ValueLike] = dict(),
    output_values: list[ValueLike] = list(),
) -> None
Attributes

qamomile.circuit.transpiler.block_parameter_binding

Shared call-site pairing for operation-owned blocks.

Overview

FunctionDescription
align_formal_operandsAlign split call-site operand pools to formal declaration order.
block_parameter_binding_keysReturn the sanctioned emit-binding keys for an inner formal.
pair_block_operandsPair all block inputs with category-grouped call-site operands.
pair_block_parameter_operandsPair a block’s classical/object inputs with call-site operands.
ClassDescription
BlockUnified block representation for all pipeline stages.
ValueBaseNominal base for every typed IR value.

Functions

align_formal_operands [source]

def align_formal_operands(
    formals: Sequence[ValueBase],
    quantum_operands: Sequence[ValueBase],
    parameter_operands: Sequence[ValueBase],
) -> list[ValueBase]

Align split call-site operand pools to formal declaration order.

Operation-owned call sites store quantum operands separately from classical/object operands, while a block keeps the Python declaration order and may interleave those categories. Reweaving the two pools here gives every consumer one canonical formal-to-actual convention.

Parameters:

NameTypeDescription
formalsSequence[ValueBase]Formal inputs in declaration order.
quantum_operandsSequence[ValueBase]Quantum actual operands in their call-site order.
parameter_operandsSequence[ValueBase]Classical/object actual operands in their call-site order.

Returns:

list[ValueBase] — list[ValueBase]: Actual operands aligned with formals. The list stops at the first category shortfall so a downstream positional pairing cannot silently consume an operand of the wrong category.


block_parameter_binding_keys [source]

def block_parameter_binding_keys(parameter: ValueBase) -> tuple[str, ...]

Return the sanctioned emit-binding keys for an inner formal.

Emit resolution accepts a kernel parameter name before its UUID for public API compatibility, so an operation-owned fresh scope must write both keys. Keeping the key choice here prevents individual emit paths from reviving a parent binding that merely shares the inner formal’s display name.

Parameters:

NameTypeDescription
parameterValueBaseClassical/object formal input being bound.

Returns:

tuple[str, ...] — tuple[str, ...]: UUID followed by the formal parameter provenance name and nonempty display-name compatibility key, without duplicates.


pair_block_operands [source]

def pair_block_operands(
    block: Block,
    operands: Sequence[ValueBase],
) -> list[tuple[ValueBase, ValueBase]]

Pair all block inputs with category-grouped call-site operands.

Parameters:

NameTypeDescription
blockBlockOperation-owned block whose inputs are being bound.
operandsSequence[ValueBase]Call-site operands after any controls that are external to block have been removed.

Returns:

list[tuple[ValueBase, ValueBase]] — list[tuple[ValueBase, ValueBase]]: Formal/actual pairs in the block’s list[tuple[ValueBase, ValueBase]] — declaration order.


pair_block_parameter_operands [source]

def pair_block_parameter_operands(
    block: Block,
    param_operands: Sequence[ValueBase],
) -> list[tuple[ValueBase, ValueBase]]

Pair a block’s classical/object inputs with call-site operands.

Both compile-time lowering and emission bind an operation-owned block’s non-quantum inputs by their declaration order. Keeping the filtering and pairing here ensures those stages cannot adopt different positional conventions.

Parameters:

NameTypeDescription
blockBlockOperation-owned block whose formal inputs define the declaration order.
param_operandsSequence[ValueBase]Classical or object operands at the call site, already ordered according to the operation signature.

Returns:

list[tuple[ValueBase, ValueBase]] — list[tuple[ValueBase, ValueBase]]: (formal, actual) pairs in list[tuple[ValueBase, ValueBase]] — declaration order. Missing actual operands leave trailing formals list[tuple[ValueBase, ValueBase]] — unpaired, so they can remain symbolic and be provided at emit time.

Classes

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.


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.


qamomile.circuit.transpiler.circuit_ir

Engine-neutral circuit code-generation IR.

This module is intentionally lower-level than Qamomile’s semantic IR and higher-level than any SDK object. It contains virtual quantum wires, target-neutral scalar expressions, structured control flow, and reusable circuit calls. Circuit-family targets legalize and materialize this IR; program-graph targets such as HUGR do not pass through it.

The semantic-to-circuit lowering currently reuses the established emit walker to preserve frontend behavior; the immutable CircuitProgram boundary is where that mutable traversal ends.

Two rules govern what survives into this IR and how targets consume it:

Overview

FunctionDescription
has_mid_circuit_measurementReturn whether measured quantum state is consumed again in a region.
legalize_programRewrite one circuit program until it is legal for a target.
lower_circuit_planLower every quantum segment in a plan to immutable circuit IR.
materialize_executableMaterialize every quantum segment while preserving orchestration.
verify_circuitVerify wire linearity, regions, expressions, and slot bounds.
verify_target_legalProve a legalized program against declared target capabilities.
ClassDescription
BarrierInstructionSeparate scheduling regions without changing wire versions.
BinaryExprApply a binary scalar operation.
BinaryOperatorEnumerate scalar operations preserved until target materialization.
CallControlModeEnumerate how a target realizes controls on reusable calls.
CallInstructionInvoke a reusable circuit over versioned wires.
CallPhaseModeEnumerate how a target realizes phase in coherently controlled calls.
CallTransformCapabilitiesDeclare reusable-call forms accepted by a target realization.
CallableIdentityPreserve the semantic identity of a reusable circuit body.
CircuitBuilderBuild immutable circuit IR while assigning fresh wire versions.
CircuitCapabilitiesDeclare the complete circuit-IR language accepted by one target.
CircuitEngineEmitPassLower, legalize, verify, and materialize a circuit-family plan.
CircuitGateEmitterEmit primitive operations into engine-neutral circuit IR.
CircuitLoweringPassLower a segmented circuit program into target-neutral builders.
CircuitMaterializerConvert one target-legal circuit program to an engine artifact.
CircuitProgramStore one immutable engine-neutral circuit program.
ClassicalBitExprReference a measured classical bit.
CompilationPolicySelect preferred realizations among target-supported alternatives.
ForInstructionRepeat a structured circuit region over a concrete range.
GateInstructionApply one primitive gate to versioned virtual wires.
GlobalPhaseCapabilitiesDeclare exact standalone global-phase realization requirements.
IfInstructionSelect between two structured circuit regions.
LiteralExprRepresent a concrete scalar literal.
LoopVariableExprReference the induction value of a structured loop.
MaterializedCircuitPackage a circuit artifact and engine-specific binding metadata.
MeasureInstructionMeasure a wire into a classical bit.
MeasureVectorInstructionMeasure an ordered group of wires into classical bits.
NativeSemanticOpCapabilitiesDeclare a target-native realization of an abstract operation.
ParameterExprReference a runtime circuit parameter.
PauliEvolutionInstructionApply an abstract Hamiltonian evolution to selected wires.
PauliEvolutionRealizationEnumerate legalization states for abstract Pauli evolution.
ResetInstructionReset a wire and produce a fresh zero-state wire.
ReusableCircuitDescribe a reusable circuit body and requested transforms.
ScalarAtomEnumerate leaf values that may occur in a scalar expression.
ScalarCapabilitiesDeclare the scalar language accepted in one instruction context.
ScalarExpressionFormEnumerate permitted runtime-parameter expression shapes.
SemanticArgumentsStore immutable named arguments belonging to an operation’s meaning.
SemanticOpKeyIdentify an abstract operation independently of any engine.
UnaryExprApply a unary scalar operation.
UnaryOperatorEnumerate unary scalar operations preserved for materialization.
WhileInstructionRepeat a structured region while a runtime predicate is true.
WireIdIdentify one version of a virtual quantum wire.

Constants

Functions

has_mid_circuit_measurement [source]

def has_mid_circuit_measurement(operations: tuple[CircuitInstruction, ...]) -> bool

Return whether measured quantum state is consumed again in a region.

Static-sampling engines may defer terminal measurements to the end of a shot, but doing so is incorrect when a later gate, reset, call, or control region consumes the post-measurement wire. The circuit IR uses versioned wires, so this scan can distinguish those two cases without engine SDK knowledge.

Parameters:

NameTypeDescription
operationstuple[CircuitInstruction, ...]Structured instruction region to inspect.

Returns:

bool — True when the region or a nested reusable/control-flow body contains a non-terminal measurement.


legalize_program [source]

def legalize_program(
    program: CircuitProgram,
    capabilities: CircuitCapabilities,
    policy: CompilationPolicy,
) -> CircuitProgram

Rewrite one circuit program until it is legal for a target.

Calls whose semantic key the target implements natively receive a target-owned realization identifier. Every other call retains its semantic identity and recursively legalized fallback body.

Parameters:

NameTypeDescription
programCircuitProgramVerified engine-neutral circuit program.
capabilitiesCircuitCapabilitiesDeclared target capabilities.
policyCompilationPolicyUser realization preferences.

Returns:

CircuitProgram — Rebuilt program with freshly numbered wires.


lower_circuit_plan [source]

def lower_circuit_plan(
    plan: ProgramPlan,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> ExecutableProgram[CircuitProgram]

Lower every quantum segment in a plan to immutable circuit IR.

Classical and expectation-value orchestration metadata remains in the returned executable container. Only engine-native quantum artifacts are replaced with verified :class:CircuitProgram objects.

Parameters:

NameTypeDescription
planProgramPlanCircuit-family C-to-Q-to-C execution plan.
bindingsdict[str, Any] | NoneCompile-time parameter bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.

Returns:

ExecutableProgram[CircuitProgram] — ExecutableProgram[CircuitProgram]: Execution structure containing immutable engine-neutral quantum programs.

Raises:


materialize_executable [source]

def materialize_executable(
    executable: ExecutableProgram[CircuitProgram],
    materializer: CircuitMaterializer[ArtifactT],
) -> ExecutableProgram[ArtifactT]

Materialize every quantum segment while preserving orchestration.

Parameters:

NameTypeDescription
executableExecutableProgram[CircuitProgram]Lowered circuit-family execution structure.
materializerCircuitMaterializer[ArtifactT]Engine materializer.

Returns:

ExecutableProgram[ArtifactT] — ExecutableProgram[ArtifactT]: Execution structure containing native engine circuits and unchanged ABI, classical, expectation-value, mapping, and parameter metadata.


verify_circuit [source]

def verify_circuit(program: CircuitProgram) -> None

Verify wire linearity, regions, expressions, and slot bounds.

Parameters:

NameTypeDescription
programCircuitProgramImmutable circuit program to verify.

Raises:


def verify_target_legal(program: CircuitProgram, capabilities: CircuitCapabilities) -> None

Prove a legalized program against declared target capabilities.

Parameters:

NameTypeDescription
programCircuitProgramLegalized circuit program, including every nested reusable-call body.
capabilitiesCircuitCapabilitiesDeclared target capabilities.

Raises:

Classes

BarrierInstruction [source]

class BarrierInstruction

Separate scheduling regions without changing wire versions.

Parameters:

NameTypeDescription
wirestuple[WireId, ...]Wires participating in the barrier.
Constructor
def __init__(self, wires: tuple[WireId, ...]) -> None
Attributes

BinaryExpr [source]

class BinaryExpr(_ScalarOperators)

Apply a binary scalar operation.

Parameters:

NameTypeDescription
operatorBinaryOperatorOperation kind.
leftScalarExprLeft operand.
rightScalarExprRight operand.
Constructor
def __init__(self, operator: BinaryOperator, left: ScalarExpr, right: ScalarExpr) -> None
Attributes

BinaryOperator [source]

class BinaryOperator(enum.Enum)

Enumerate scalar operations preserved until target materialization.

Attributes

CallControlMode [source]

class CallControlMode(enum.Enum)

Enumerate how a target realizes controls on reusable calls.

Attributes

CallInstruction [source]

class CallInstruction

Invoke a reusable circuit over versioned wires.

Parameters:

NameTypeDescription
calleeReusableCircuitReusable circuit and transforms.
inputstuple[WireId, ...]Consumed wire versions.
outputstuple[WireId, ...]Produced wire versions.
Constructor
def __init__(
    self,
    callee: ReusableCircuit,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
) -> None
Attributes

CallPhaseMode [source]

class CallPhaseMode(enum.Enum)

Enumerate how a target realizes phase in coherently controlled calls.

NATIVE_BODY means the target call itself preserves the reusable body’s phase. EXPLICIT_CORRECTION means the materializer emits a separate phase correction alongside the call. UNSUPPORTED rejects a body phase once coherent controls make it observable.

Attributes

CallTransformCapabilities [source]

class CallTransformCapabilities

Declare reusable-call forms accepted by a target realization.

Parameters:

NameTypeDescription
supports_powerboolWhether powers other than one are accepted.
supports_inverseboolWhether inverse calls are accepted.
max_controlsint | NoneMaximum added controls. None means no declared limit.
supports_nonunitary_bodyboolWhether a reusable body may contain measurement, reset, or dynamic control flow.
supports_barrier_bodyboolWhether barriers may remain inside a reusable body.
control_modeCallControlModeHow added controls are realized.
controlled_gate_kindsfrozenset[GateKind]Body gate kinds accepted when controls are distributed into the body.
controlled_pauli_timeScalarCapabilities | NonePauli-time scalar language accepted under distributed controls, or None when controlled Pauli evolution is unsupported.
phase_modeCallPhaseModeHow a reusable body’s phase is realized after coherent controls are known. For native semantic calls, an EXPLICIT_CORRECTION declaration makes the native materializer responsible for emitting that correction. Defaults to UNSUPPORTED.
controlled_phase_scalarsScalarCapabilities | NoneScalar language accepted for an observable controlled-call phase, or None when no such phase is supported. Defaults to None.
Constructor
def __init__(
    self,
    supports_power: bool,
    supports_inverse: bool,
    max_controls: int | None,
    supports_nonunitary_body: bool = False,
    supports_barrier_body: bool = False,
    control_mode: CallControlMode = CallControlMode.WHOLE_CALL,
    controlled_gate_kinds: frozenset[GateKind] = frozenset(),
    controlled_pauli_time: ScalarCapabilities | None = None,
    phase_mode: CallPhaseMode = CallPhaseMode.UNSUPPORTED,
    controlled_phase_scalars: ScalarCapabilities | None = None,
) -> None
Attributes
Methods
accepts
def accepts(self, callee: ReusableCircuit, inherited_controls: int = 0) -> bool

Return whether this declaration accepts a concrete call shape.

Parameters:

NameTypeDescription
calleeReusableCircuitReusable body and requested transforms.
inherited_controlsintControls physically distributed from an enclosing call. Defaults to zero.

Returns:

bool — Whether power, inverse, and control transforms are accepted.


CallableIdentity [source]

class CallableIdentity

Preserve the semantic identity of a reusable circuit body.

Parameters:

NameTypeDescription
keySemanticOpKeyOpen semantic identity used by target-native realization registries.
symbolstrHuman-readable callable name used for diagnostics.
argumentsSemanticArgumentsImmutable arguments that define this invocation’s meaning. Defaults to no arguments.
Constructor
def __init__(
    self,
    key: SemanticOpKey,
    symbol: str,
    arguments: SemanticArguments = SemanticArguments(),
) -> None
Attributes

CircuitBuilder [source]

class CircuitBuilder

Build immutable circuit IR while assigning fresh wire versions.

Parameters:

NameTypeDescription
num_qubitsintNumber of virtual qubit slots.
num_clbitsintNumber of classical bit slots.
namestrCircuit name. Defaults to "main".
Constructor
def __init__(self, num_qubits: int, num_clbits: int, name: str = 'main') -> None

Initialize a circuit builder.

Parameters:

NameTypeDescription
num_qubitsintNumber of virtual qubit slots.
num_clbitsintNumber of classical bit slots.
namestrCircuit name. Defaults to "main".

Raises:

Attributes
Methods
add_global_phase
def add_global_phase(self, phase: ScalarExpr | bool | int | float) -> None

Accumulate a global phase in the current lexical region.

Parameters:

NameTypeDescription
phaseScalarExpr | bool | int | floatPhase contribution.
append_barrier
def append_barrier(self, qubits: tuple[int, ...]) -> None

Append a scheduling barrier without changing wire versions.

Parameters:

NameTypeDescription
qubitstuple[int, ...]Participating qubit slots.
append_call
def append_call(self, callee: ReusableCircuit, qubits: tuple[int, ...]) -> None

Append a reusable-circuit call and advance its wires.

Parameters:

NameTypeDescription
calleeReusableCircuitReusable circuit and transforms.
qubitstuple[int, ...]Participating qubit slots.
append_gate
def append_gate(
    self,
    kind: GateKind,
    qubits: tuple[int, ...],
    parameters: tuple[ScalarExpr, ...] = (),
) -> None

Append a primitive gate and advance all participating wires.

Parameters:

NameTypeDescription
kindGateKindPrimitive gate kind.
qubitstuple[int, ...]Participating qubit slots.
parameterstuple[ScalarExpr, ...]Gate parameters. Defaults to an empty tuple.
append_measure
def append_measure(self, qubit: int, clbit: int) -> None

Append a measurement.

Parameters:

NameTypeDescription
qubitintMeasured qubit slot.
clbitintDestination classical bit slot.

Raises:

append_measure_vector
def append_measure_vector(self, qubits: tuple[int, ...], clbits: tuple[int, ...]) -> None

Append one ordered vector measurement.

Parameters:

NameTypeDescription
qubitstuple[int, ...]Measured qubit slots in result order.
clbitstuple[int, ...]Destination classical slots.

Raises:

append_pauli_evolution
def append_pauli_evolution(
    self,
    qubits: tuple[int, ...],
    hamiltonian: Any,
    time: ScalarExpr | bool | int | float,
) -> None

Append an abstract Pauli evolution and advance its wires.

Parameters:

NameTypeDescription
qubitstuple[int, ...]Participating qubit slots.
hamiltonianAnyQamomile Hamiltonian value.
timeScalarExpr | bool | int | floatEvolution time.

Raises:

append_reset
def append_reset(self, qubit: int) -> None

Append reset and advance the affected wire.

Parameters:

NameTypeDescription
qubitintQubit slot to reset.
begin_else
def begin_else(self, context: _IfContext) -> None

Close a true region and open its false region.

Parameters:

NameTypeDescription
context_IfContextToken returned by :meth:begin_if.

Raises:

begin_for
def begin_for(self, indexset: range) -> LoopVariableExpr

Open a structured for-loop body.

Parameters:

NameTypeDescription
indexsetrangeConcrete iteration range.

Returns:

LoopVariableExpr — Induction expression available inside the body.

begin_if
def begin_if(self, condition: ScalarExpr) -> _IfContext

Open the true region of a structured conditional.

Parameters:

NameTypeDescription
conditionScalarExprRuntime branch predicate.

Returns:

_IfContext — Opaque builder token used to select the else branch.

begin_while
def begin_while(self, condition: ScalarExpr) -> _WhileContext

Open a structured while-loop body.

Parameters:

NameTypeDescription
conditionScalarExprRuntime loop predicate.

Returns:

_WhileContext — Opaque builder token used to close the loop.

current_wire
def current_wire(self, qubit: int) -> WireId

Return the current wire version for a qubit slot.

Parameters:

NameTypeDescription
qubitintPhysical slot index assigned by circuit lowering.

Returns:

WireId — Current version of the slot.

Raises:

end_for
def end_for(self) -> None

Close the innermost structured for-loop body.

Raises:

end_if
def end_if(self, context: _IfContext) -> None

Close a structured conditional and merge its wire states.

Parameters:

NameTypeDescription
context_IfContextToken returned by :meth:begin_if.

Raises:

end_while
def end_while(self, context: _WhileContext) -> None

Close a structured while-loop body.

Parameters:

NameTypeDescription
context_WhileContextToken returned by :meth:begin_while.

Raises:

freeze
def freeze(self) -> CircuitProgram

Finalize the root region into immutable circuit IR.

Returns:

CircuitProgram — Immutable circuit program.

Raises:

fresh_wire
def fresh_wire(self) -> WireId

Allocate a fresh module-local virtual wire version.

Returns:

WireId — Newly allocated wire identifier.

restore_state
def restore_state(self, snapshot: _CircuitBuilderSnapshot) -> None

Restore a checkpoint after an append-only emission attempt.

Parameters:

NameTypeDescription
snapshot_CircuitBuilderSnapshotCheckpoint returned by :meth:snapshot_state for this builder.

Raises:

snapshot_state
def snapshot_state(self) -> _CircuitBuilderSnapshot

Capture state that can be restored after declined emission.

Returns:

_CircuitBuilderSnapshot — Append-only builder checkpoint for the current structured region.


CircuitCapabilities [source]

class CircuitCapabilities

Declare the complete circuit-IR language accepted by one target.

Parameters:

NameTypeDescription
namestrStable target name used in diagnostics.
primitive_gatesfrozenset[GateKind]Primitive gate kinds accepted by the target materializer.
native_semantic_opstuple[NativeSemanticOpCapabilities, ...]Native realizations keyed by open semantic operation identity.
gate_parametersScalarCapabilitiesScalar language accepted by gate parameters.
predicatesScalarCapabilitiesScalar language accepted by dynamic if and while predicates.
pauli_timeScalarCapabilitiesScalar language accepted by Pauli evolution time values.
global_phaseGlobalPhaseCapabilities | ScalarCapabilities | NoneExact standalone phase realization requirements, or None when unsupported. The former ScalarCapabilities value remains accepted and readable for source compatibility.
generic_callsCallTransformCapabilitiesReusable-call forms accepted after semantic-call legalization.
supports_dynamic_ifboolWhether runtime if regions are accepted.
supports_dynamic_whileboolWhether runtime while regions are accepted.
supports_resetboolWhether reset instructions are accepted.
pauli_realizationsfrozenset[PauliEvolutionRealization]Concrete Pauli-evolution realizations accepted by the materializer.
Constructor
def __init__(
    self,
    name: str,
    primitive_gates: frozenset[GateKind],
    native_semantic_ops: tuple[NativeSemanticOpCapabilities, ...],
    gate_parameters: ScalarCapabilities,
    predicates: ScalarCapabilities,
    pauli_time: ScalarCapabilities,
    global_phase: GlobalPhaseCapabilities | ScalarCapabilities | None,
    generic_calls: CallTransformCapabilities,
    supports_dynamic_if: bool,
    supports_dynamic_while: bool,
    supports_reset: bool,
    pauli_realizations: frozenset[PauliEvolutionRealization],
) -> None
Attributes
Methods
native_semantic_op
def native_semantic_op(self, key: SemanticOpKey) -> NativeSemanticOpCapabilities | None

Return the native declaration for one semantic operation.

Parameters:

NameTypeDescription
keySemanticOpKeySemantic operation key to look up.

Returns:

NativeSemanticOpCapabilities | None — NativeSemanticOpCapabilities | None: Matching declaration, or NativeSemanticOpCapabilities | None — None when the target has no native realization.


CircuitEngineEmitPass [source]

class CircuitEngineEmitPass(EmitPass[ArtifactT])

Lower, legalize, verify, and materialize a circuit-family plan.

The pass runs the three phases in order and never interleaves them: shared lowering produces engine-neutral circuit IR, target legalization rewrites it under the materializer’s declared capabilities and the compilation policy, target verification proves the result, and only then does the materializer convert it mechanically.

Parameters:

NameTypeDescription
materializerCircuitMaterializer[ArtifactT]Engine artifact materializer owning the target capability declaration.
bindingsdict[str, Any] | NoneCompile-time bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.
policyCompilationPolicy | NoneRealization preferences. Defaults to None, meaning :data:DEFAULT_POLICY.
Constructor
def __init__(
    self,
    materializer: CircuitMaterializer[ArtifactT],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
    policy: CompilationPolicy | None = None,
) -> None

Initialize a circuit-family lowering and materialization pass.

Parameters:

NameTypeDescription
materializerCircuitMaterializer[ArtifactT]Engine artifact materializer owning the target capability declaration.
bindingsdict[str, Any] | NoneCompile-time bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.
policyCompilationPolicy | NoneRealization preferences. Defaults to None, meaning :data:DEFAULT_POLICY.
Attributes
Methods
run
def run(self, input: ProgramPlan) -> ExecutableProgram[ArtifactT]

Lower, legalize, verify, and materialize every quantum segment.

Parameters:

NameTypeDescription
inputProgramPlanCircuit-family execution plan.

Returns:

ExecutableProgram[ArtifactT] — ExecutableProgram[ArtifactT]: Engine-native executable structure.

Raises:


CircuitGateEmitter [source]

class CircuitGateEmitter

Emit primitive operations into engine-neutral circuit IR.

Attributes
Methods
append_gate
def append_gate(
    self,
    circuit: CircuitBuilder,
    gate: ReusableCircuit,
    qubits: list[int],
) -> None

Append a reusable circuit call.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
gateReusableCircuitReusable circuit value.
qubitslist[int]Participating slots.
circuit_to_gate
def circuit_to_gate(
    self,
    circuit: CircuitBuilder | CircuitProgram,
    name: str = 'U',
) -> ReusableCircuit

Freeze a circuit as a reusable circuit value.

Parameters:

NameTypeDescription
circuitCircuitBuilder | CircuitProgramCircuit body.
namestrReusable circuit name. Defaults to "U".

Returns:

ReusableCircuit — Reusable body without target-native state.

combine_symbolic
def combine_symbolic(
    self,
    kind: BinOpKind,
    lhs: ScalarExpr | bool | int | float,
    rhs: ScalarExpr | bool | int | float,
) -> BinaryExpr | None

Combine symbolic operands without creating engine expressions.

Parameters:

NameTypeDescription
kindBinOpKindQamomile arithmetic operation.
lhsScalarExpr | bool | int | floatLeft operand.
rhsScalarExpr | bool | int | floatRight operand.

Returns:

BinaryExpr | None — BinaryExpr | None: Target-neutral expression, or None for an unsupported operation kind.

create_circuit
def create_circuit(self, num_qubits: int, num_clbits: int) -> CircuitBuilder

Create an empty circuit IR builder.

Parameters:

NameTypeDescription
num_qubitsintNumber of virtual qubit slots.
num_clbitsintNumber of classical bit slots.

Returns:

CircuitBuilder — Empty engine-neutral builder.

create_parameter
def create_parameter(self, name: str) -> ParameterExpr

Create a target-neutral runtime parameter expression.

Parameters:

NameTypeDescription
namestrExternal parameter name.

Returns:

ParameterExpr — Parameter reference preserved until materialization.

emit_barrier
def emit_barrier(self, circuit: CircuitBuilder, qubits: list[int]) -> None

Emit a scheduling barrier.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitslist[int]Participating slots.
emit_ch
def emit_ch(self, circuit: CircuitBuilder, control: int, target: int) -> None

Emit a controlled-H gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
emit_cp
def emit_cp(
    self,
    circuit: CircuitBuilder,
    control: int,
    target: int,
    angle: ScalarExpr | float,
) -> None

Emit a controlled-phase rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
angleScalarExpr | floatPhase angle in radians.
emit_crx
def emit_crx(
    self,
    circuit: CircuitBuilder,
    control: int,
    target: int,
    angle: ScalarExpr | float,
) -> None

Emit a controlled-RX rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
angleScalarExpr | floatRotation angle in radians.
emit_cry
def emit_cry(
    self,
    circuit: CircuitBuilder,
    control: int,
    target: int,
    angle: ScalarExpr | float,
) -> None

Emit a controlled-RY rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
angleScalarExpr | floatRotation angle in radians.
emit_crz
def emit_crz(
    self,
    circuit: CircuitBuilder,
    control: int,
    target: int,
    angle: ScalarExpr | float,
) -> None

Emit a controlled-RZ rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
angleScalarExpr | floatRotation angle in radians.
emit_cx
def emit_cx(self, circuit: CircuitBuilder, control: int, target: int) -> None

Emit a controlled-X gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
emit_cy
def emit_cy(self, circuit: CircuitBuilder, control: int, target: int) -> None

Emit a controlled-Y gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
emit_cz
def emit_cz(self, circuit: CircuitBuilder, control: int, target: int) -> None

Emit a controlled-Z gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
emit_else_start
def emit_else_start(self, circuit: CircuitBuilder, context: Any) -> None

Switch an open conditional to its false branch.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
contextAnyOpaque conditional context.
emit_for_loop_end
def emit_for_loop_end(self, circuit: CircuitBuilder, context: Any) -> None

Close a structured for-loop body.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
contextAnyInduction expression returned at loop start.
emit_for_loop_start
def emit_for_loop_start(self, circuit: CircuitBuilder, indexset: range) -> ScalarExpr

Open a structured for-loop body.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
indexsetrangeConcrete iteration range.

Returns:

ScalarExpr — Target-neutral induction expression.

emit_global_phase
def emit_global_phase(self, circuit: CircuitBuilder, angle: ScalarExpr | float) -> None

Accumulate a phase in the builder’s current lexical region.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
angleScalarExpr | floatPhase angle in radians.
emit_h
def emit_h(self, circuit: CircuitBuilder, qubit: int) -> None

Emit a Hadamard gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_if_end
def emit_if_end(self, circuit: CircuitBuilder, context: Any) -> None

Close a structured conditional.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
contextAnyOpaque conditional context.
emit_if_start
def emit_if_start(self, circuit: CircuitBuilder, clbit: int, value: int = 1) -> Any

Open a structured conditional true branch.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
clbitintPredicate classical bit slot.
valueintRequired bit value. Defaults to one.

Returns:

Any — Opaque conditional builder context.

emit_measure
def emit_measure(self, circuit: CircuitBuilder, qubit: int, clbit: int) -> None

Emit a measurement into a classical slot.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintMeasured qubit slot.
clbitintDestination classical slot.
emit_measure_vector
def emit_measure_vector(
    self,
    circuit: CircuitBuilder,
    qubits: tuple[int, ...],
    clbits: tuple[int, ...],
) -> None

Preserve an ordered vector measurement as one instruction.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitstuple[int, ...]Measured qubit slots in result order.
clbitstuple[int, ...]Destination classical slots.
emit_p
def emit_p(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> None

Emit a phase rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
angleScalarExpr | floatPhase angle in radians.
emit_reset
def emit_reset(self, circuit: CircuitBuilder, qubit: int) -> None

Emit a reset-to-zero operation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintReset qubit slot.
emit_rx
def emit_rx(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> None

Emit an RX rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
angleScalarExpr | floatRotation angle in radians.
emit_ry
def emit_ry(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> None

Emit an RY rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
angleScalarExpr | floatRotation angle in radians.
emit_rz
def emit_rz(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> None

Emit an RZ rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
angleScalarExpr | floatRotation angle in radians.
emit_rzz
def emit_rzz(
    self,
    circuit: CircuitBuilder,
    qubit1: int,
    qubit2: int,
    angle: ScalarExpr | float,
) -> None

Emit an RZZ rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubit1intFirst slot.
qubit2intSecond slot.
angleScalarExpr | floatRotation angle in radians.
emit_s
def emit_s(self, circuit: CircuitBuilder, qubit: int) -> None

Emit an S gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_sdg
def emit_sdg(self, circuit: CircuitBuilder, qubit: int) -> None

Emit an inverse-S gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_swap
def emit_swap(self, circuit: CircuitBuilder, qubit1: int, qubit2: int) -> None

Emit a SWAP gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubit1intFirst slot.
qubit2intSecond slot.
emit_t
def emit_t(self, circuit: CircuitBuilder, qubit: int) -> None

Emit a T gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_tdg
def emit_tdg(self, circuit: CircuitBuilder, qubit: int) -> None

Emit an inverse-T gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_toffoli
def emit_toffoli(
    self,
    circuit: CircuitBuilder,
    control1: int,
    control2: int,
    target: int,
) -> None

Emit a Toffoli gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
control1intFirst control slot.
control2intSecond control slot.
targetintTarget slot.
emit_while_end
def emit_while_end(self, circuit: CircuitBuilder, context: Any) -> None

Close a structured while-loop body.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
contextAnyOpaque while-loop context.
emit_while_start
def emit_while_start(self, circuit: CircuitBuilder, clbit: int, value: int = 1) -> Any

Open a structured while-loop body.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
clbitintPredicate classical bit slot.
valueintRequired bit value. Defaults to one.

Returns:

Any — Opaque while-loop builder context.

emit_x
def emit_x(self, circuit: CircuitBuilder, qubit: int) -> None

Emit a Pauli-X gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_y
def emit_y(self, circuit: CircuitBuilder, qubit: int) -> None

Emit a Pauli-Y gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_z
def emit_z(self, circuit: CircuitBuilder, qubit: int) -> None

Emit a Pauli-Z gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
gate_controlled
def gate_controlled(self, gate: ReusableCircuit, num_controls: int) -> ReusableCircuit

Add control wires to a reusable circuit.

Parameters:

NameTypeDescription
gateReusableCircuitReusable circuit value.
num_controlsintNumber of controls to add.

Returns:

ReusableCircuit — Controlled reusable circuit.

gate_inverse
def gate_inverse(self, gate: ReusableCircuit) -> ReusableCircuit

Toggle the inverse transform on a reusable circuit.

Parameters:

NameTypeDescription
gateReusableCircuitReusable circuit value.

Returns:

ReusableCircuit — Inverse reusable circuit.

gate_power
def gate_power(self, gate: ReusableCircuit, power: int) -> ReusableCircuit

Apply an integral power transform to a reusable circuit.

Parameters:

NameTypeDescription
gateReusableCircuitReusable circuit value.
powerintIntegral repetition count.

Returns:

ReusableCircuit — Transformed reusable circuit.

supports_for_loop
def supports_for_loop(self) -> bool

Report support for structured for loops.

Returns:

bool — Always True for circuit IR.

supports_gate_inverse
def supports_gate_inverse(self) -> bool

Report support for deferred inverse transforms.

Returns:

bool — Always True for circuit IR.

supports_if_else
def supports_if_else(self) -> bool

Report support for structured conditionals.

Returns:

bool — Always True for circuit IR.

supports_reusable_gates
def supports_reusable_gates(self) -> bool

Report support for deferred reusable circuit calls.

Returns:

bool — Always True because :class:ReusableCircuit carries a target-neutral body and transforms until legalization or materialization.

supports_while_loop
def supports_while_loop(self) -> bool

Report support for structured while loops.

Returns:

bool — Always True for circuit IR.


CircuitLoweringPass [source]

class CircuitLoweringPass(StandardEmitPass[CircuitBuilder])

Lower a segmented circuit program into target-neutral builders.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneCompile-time parameter bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.
Constructor
def __init__(
    self,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> None

Initialize circuit-IR lowering.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneCompile-time parameter bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.
Methods
run
def run(self, input: ProgramPlan) -> ExecutableProgram[CircuitBuilder]

Lower one program plan with a fresh SELECT case cache.

Parameters:

NameTypeDescription
inputProgramPlanSegmented program plan to lower.

Returns:

ExecutableProgram[CircuitBuilder] — ExecutableProgram[CircuitBuilder]: Lowered executable builders.


CircuitMaterializer [source]

class CircuitMaterializer(Protocol[ArtifactT])

Convert one target-legal circuit program to an engine artifact.

A materializer owns two things: a declaration of what it accepts (:attr:capabilities) and a mechanical conversion of programs that verification has already proven against that declaration. Realization decisions (native semantic operation vs fallback body, decomposition choices) belong to legalization, never here.

Attributes
Methods
materialize
def materialize(self, program: CircuitProgram) -> MaterializedCircuit[ArtifactT]

Materialize one circuit program.

Parameters:

NameTypeDescription
programCircuitProgramTarget-legal circuit-family program.

Returns:

MaterializedCircuit[ArtifactT] — Artifact plus engine binding metadata.


CircuitProgram [source]

class CircuitProgram

Store one immutable engine-neutral circuit program.

Parameters:

NameTypeDescription
namestrCircuit entrypoint name.
num_qubitsintNumber of virtual input qubit slots.
num_clbitsintNumber of classical bit slots.
input_wirestuple[WireId, ...]Initial wire version per qubit slot.
output_wirestuple[WireId, ...]Final wire version per qubit slot.
operationstuple[CircuitInstruction, ...]Structured instruction sequence.
global_phaseScalarExprPhase accumulated in the root lexical region, in radians. Dynamic control-flow regions retain their own scoped phases. Defaults to zero and becomes observable when the program is controlled.
Constructor
def __init__(
    self,
    name: str,
    num_qubits: int,
    num_clbits: int,
    input_wires: tuple[WireId, ...],
    output_wires: tuple[WireId, ...],
    operations: tuple[CircuitInstruction, ...],
    global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

ClassicalBitExpr [source]

class ClassicalBitExpr(_ScalarOperators)

Reference a measured classical bit.

Parameters:

NameTypeDescription
indexintCircuit-local classical bit index.
Constructor
def __init__(self, index: int) -> None
Attributes

CompilationPolicy [source]

class CompilationPolicy

Select preferred realizations among target-supported alternatives.

Parameters:

NameTypeDescription
prefer_native_semantic_opsboolWhether legal target-native realizations are preferred over reusable fallback bodies. Defaults to True.
prefer_native_pauli_evolutionboolWhether native Pauli evolution is preferred over a gate gadget. Defaults to True.
Constructor
def __init__(
    self,
    prefer_native_semantic_ops: bool = True,
    prefer_native_pauli_evolution: bool = True,
) -> None
Attributes

ForInstruction [source]

class ForInstruction

Repeat a structured circuit region over a concrete range.

Parameters:

NameTypeDescription
indexsetrangeConcrete iteration range.
loop_variableLoopVariableExprInduction expression used by the body.
inputstuple[WireId, ...]Wire versions entering the loop.
bodytuple[CircuitInstruction, ...]Single-iteration body.
body_outputstuple[WireId, ...]Body wire versions yielded to the next iteration.
outputstuple[WireId, ...]Wire versions after the loop.
Constructor
def __init__(
    self,
    indexset: range,
    loop_variable: LoopVariableExpr,
    inputs: tuple[WireId, ...],
    body: tuple[CircuitInstruction, ...],
    body_outputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
) -> None
Attributes

GateInstruction [source]

class GateInstruction

Apply one primitive gate to versioned virtual wires.

Parameters:

NameTypeDescription
kindGateKindPrimitive gate kind.
inputstuple[WireId, ...]Consumed wire versions.
outputstuple[WireId, ...]Produced wire versions.
parameterstuple[ScalarExpr, ...]Gate parameters.
Constructor
def __init__(
    self,
    kind: GateKind,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    parameters: tuple[ScalarExpr, ...] = (),
) -> None
Attributes

GlobalPhaseCapabilities [source]

class GlobalPhaseCapabilities

Declare exact standalone global-phase realization requirements.

Parameters:

NameTypeDescription
scalarsScalarCapabilitiesScalar language accepted for the phase.
min_qubitsintMinimum program width required to preserve a nonzero standalone phase. Targets with a native zero-qubit phase operation, or permission to allocate an internal clean carrier, use the default zero. Targets that require an existing logical qubit declare one.
Constructor
def __init__(self, scalars: ScalarCapabilities, min_qubits: int = 0) -> None
Attributes

IfInstruction [source]

class IfInstruction

Select between two structured circuit regions.

Parameters:

NameTypeDescription
conditionScalarExprRuntime branch predicate.
inputstuple[WireId, ...]Wires entering both branches.
true_bodytuple[CircuitInstruction, ...]True branch body.
false_bodytuple[CircuitInstruction, ...]False branch body.
true_outputstuple[WireId, ...]Wires yielded by the true branch.
false_outputstuple[WireId, ...]Wires yielded by the false branch.
outputstuple[WireId, ...]Merged post-branch wires.
true_global_phaseScalarExprPhase applied only in the true branch.
false_global_phaseScalarExprPhase applied only in the false branch.
Constructor
def __init__(
    self,
    condition: ScalarExpr,
    inputs: tuple[WireId, ...],
    true_body: tuple[CircuitInstruction, ...],
    false_body: tuple[CircuitInstruction, ...],
    true_outputs: tuple[WireId, ...],
    false_outputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    true_global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
    false_global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

LiteralExpr [source]

class LiteralExpr(_ScalarOperators)

Represent a concrete scalar literal.

Parameters:

NameTypeDescription
valuebool | int | floatConcrete scalar value.
Constructor
def __init__(self, value: bool | int | float) -> None
Attributes

LoopVariableExpr [source]

class LoopVariableExpr(_ScalarOperators)

Reference the induction value of a structured loop.

Parameters:

NameTypeDescription
namestrCircuit-local loop variable name.
Constructor
def __init__(self, name: str) -> None
Attributes

MaterializedCircuit [source]

class MaterializedCircuit(Generic[ArtifactT])

Package a circuit artifact and engine-specific binding metadata.

Parameters:

NameTypeDescription
artifactAnyEngine-native circuit object.
parametersMapping[str, Any]Engine parameters keyed by public parameter name.
measurement_qubit_mapMapping[int, int] | NoneStatic-measurement mapping from classical output slot to physical qubit slot. None preserves the lowering-provided mapping; an empty mapping is an explicit override.
parameter_ordertuple[str, ...] | NoneArtifact ABI order for positional parameters. None denotes name-based binding.
implicit_output_qubit_indicestuple[int, ...] | NonePhysical qubit indices exposed when a qkernel has no explicit return value. None preserves the executor’s full raw bitstring; an empty tuple explicitly exposes no qubits.
Constructor
def __init__(
    self,
    artifact: ArtifactT,
    parameters: Mapping[str, Any] = dict(),
    measurement_qubit_map: Mapping[int, int] | None = None,
    parameter_order: tuple[str, ...] | None = None,
    implicit_output_qubit_indices: tuple[int, ...] | None = None,
) -> None
Attributes

MeasureInstruction [source]

class MeasureInstruction

Measure a wire into a classical bit.

Parameters:

NameTypeDescription
inputWireIdMeasured wire version.
outputWireIdPost-measurement wire version.
clbitintDestination classical bit index.
Constructor
def __init__(self, input: WireId, output: WireId, clbit: int) -> None
Attributes

MeasureVectorInstruction [source]

class MeasureVectorInstruction

Measure an ordered group of wires into classical bits.

This instruction preserves vector measurement as one semantic operation until target materialization. An engine with a vector measurement primitive can consume it directly; scalar-only engines expand it at their own boundary.

Parameters:

NameTypeDescription
inputstuple[WireId, ...]Measured wire versions in result order.
outputstuple[WireId, ...]Post-measurement wire versions.
clbitstuple[int, ...]Destination classical bits in result order.
Constructor
def __init__(
    self,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    clbits: tuple[int, ...],
) -> None
Attributes

NativeSemanticOpCapabilities [source]

class NativeSemanticOpCapabilities

Declare a target-native realization of an abstract operation.

Parameters:

NameTypeDescription
keySemanticOpKeyEngine-independent semantic operation key.
realizationstrTarget-owned realization identifier passed to the materializer after legalization.
call_transformsCallTransformCapabilitiesCall shapes supported by the native realization.
operand_widthstuple[int | None, ...] | NoneRequired semantic operand grouping. None accepts any grouping; an integer requires that exact width and None inside the tuple accepts any positive width at that position. Defaults to None.
min_qubitsintMinimum fallback-body width accepted by the native operation. Defaults to zero.
max_qubitsint | NoneMaximum fallback-body width, or None for no limit. Defaults to None.
required_argumentsfrozenset[str]Semantic argument names required by this realization. Defaults to none.
matching_operand_widthstuple[tuple[int, int], ...]Pairs of operand positions that must have equal widths. Defaults to none.
Constructor
def __init__(
    self,
    key: SemanticOpKey,
    realization: str,
    call_transforms: CallTransformCapabilities,
    operand_widths: tuple[int | None, ...] | None = None,
    min_qubits: int = 0,
    max_qubits: int | None = None,
    required_arguments: frozenset[str] = frozenset(),
    matching_operand_widths: tuple[tuple[int, int], ...] = (),
) -> None
Attributes
Methods
accepts
def accepts(self, callee: ReusableCircuit, inherited_controls: int = 0) -> bool

Return whether this realization accepts one semantic call shape.

Parameters:

NameTypeDescription
calleeReusableCircuitReusable call retaining source operand grouping and deferred transforms.
inherited_controlsintControls physically distributed from an enclosing call. Defaults to zero.

Returns:

bool — Whether transform, total-width, and operand-shape contracts bool — all accept the call.


ParameterExpr [source]

class ParameterExpr(_ScalarOperators)

Reference a runtime circuit parameter.

Parameters:

NameTypeDescription
namestrStable external parameter name.
Constructor
def __init__(self, name: str) -> None
Attributes

PauliEvolutionInstruction [source]

class PauliEvolutionInstruction

Apply an abstract Hamiltonian evolution to selected wires.

Parameters:

NameTypeDescription
hamiltonianAnyImmutable Qamomile Hamiltonian value.
timeScalarExprEvolution time in radians.
inputstuple[WireId, ...]Consumed wire versions.
outputstuple[WireId, ...]Produced wire versions.
realizationPauliEvolutionRealizationTarget realization selected by legalization. Defaults to ABSTRACT during shared lowering.
Constructor
def __init__(
    self,
    hamiltonian: Any,
    time: ScalarExpr,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    realization: PauliEvolutionRealization = PauliEvolutionRealization.ABSTRACT,
) -> None
Attributes

PauliEvolutionRealization [source]

class PauliEvolutionRealization(enum.Enum)

Enumerate legalization states for abstract Pauli evolution.

Attributes

ResetInstruction [source]

class ResetInstruction

Reset a wire and produce a fresh zero-state wire.

Parameters:

NameTypeDescription
inputWireIdWire version before reset.
outputWireIdFresh wire version after reset.
Constructor
def __init__(self, input: WireId, output: WireId) -> None
Attributes

ReusableCircuit [source]

class ReusableCircuit

Describe a reusable circuit body and requested transforms.

Parameters:

NameTypeDescription
bodyCircuitProgramReusable circuit body.
namestrDisplay and linkage name.
powerintIntegral repetition count. Defaults to one.
controlsintAdded control-wire count. Defaults to zero.
inverseboolWhether to apply the inverse body. Defaults to false.
identityCallableIdentity | NoneSemantic identity preserved for target legalization. None marks an anonymous body. Defaults to None.
native_realizationstr | NoneTarget-owned realization identifier selected during legalization. None keeps the reusable body as the fallback implementation. Defaults to None.
operand_widthstuple[int, ...]Flattened width of each semantic quantum operand before engine lowering. A vector contributes its element count and a scalar qubit contributes one. An empty tuple means the source boundary did not expose operand grouping.
Constructor
def __init__(
    self,
    body: CircuitProgram,
    name: str,
    power: int = 1,
    controls: int = 0,
    inverse: bool = False,
    identity: CallableIdentity | None = None,
    native_realization: str | None = None,
    operand_widths: tuple[int, ...] = (),
) -> None
Attributes

ScalarAtom [source]

class ScalarAtom(enum.Enum)

Enumerate leaf values that may occur in a scalar expression.

Attributes

ScalarCapabilities [source]

class ScalarCapabilities

Declare the scalar language accepted in one instruction context.

Parameters:

NameTypeDescription
atomsfrozenset[ScalarAtom]Leaf value kinds accepted in the expression.
unary_operatorsfrozenset[UnaryOperator]Accepted unary operators.
binary_operatorsfrozenset[BinaryOperator]Accepted binary operators.
parameter_formScalarExpressionFormMaximum algebraic form for runtime parameters.
Constructor
def __init__(
    self,
    atoms: frozenset[ScalarAtom],
    unary_operators: frozenset[UnaryOperator],
    binary_operators: frozenset[BinaryOperator],
    parameter_form: ScalarExpressionForm,
) -> None
Attributes

ScalarExpressionForm [source]

class ScalarExpressionForm(enum.Enum)

Enumerate permitted runtime-parameter expression shapes.

Attributes

SemanticArguments [source]

class SemanticArguments

Store immutable named arguments belonging to an operation’s meaning.

Parameters:

NameTypeDescription
entriestuple[tuple[str, SemanticValue], ...]Sorted name-value entries. Defaults to an empty tuple.
Constructor
def __init__(self, entries: tuple[tuple[str, SemanticValue], ...] = ()) -> None
Attributes
Methods
from_mapping
@classmethod
def from_mapping(cls, values: Mapping[str, Any] | None) -> 'SemanticArguments'

Freeze one mapping of semantic operation arguments.

Parameters:

NameTypeDescription
valuesMapping[str, Any] | NoneSerializer-friendly arguments, or None for no arguments.

Returns:

'SemanticArguments' — Immutable, deterministically ordered arguments.

Raises:

get
def get(self, name: str, default: SemanticValue = None) -> SemanticValue

Return one semantic argument by name.

Parameters:

NameTypeDescription
namestrArgument name.
defaultSemanticValueValue returned when absent. Defaults to None.

Returns:

SemanticValue — Stored value or default.

names
def names(self) -> frozenset[str]

Return all semantic argument names.

Returns:

frozenset[str] — frozenset[str]: Immutable set of argument names.


SemanticOpKey [source]

class SemanticOpKey

Identify an abstract operation independently of any engine.

The key is deliberately open rather than an enum. Standard-library, algorithm, provider, and user callables can therefore participate in native realization without modifying the compiler’s closed vocabulary.

Parameters:

NameTypeDescription
namespacestrStable owner namespace such as qamomile.stdlib.
namestrStable operation name within the namespace.
versionstrSemantic contract version. Defaults to "1".
variantstr | NoneOptional exact semantic variant, such as a decomposition strategy. Defaults to None.
Constructor
def __init__(
    self,
    namespace: str,
    name: str,
    version: str = '1',
    variant: str | None = None,
) -> None
Attributes

UnaryExpr [source]

class UnaryExpr(_ScalarOperators)

Apply a unary scalar operation.

Parameters:

NameTypeDescription
operatorUnaryOperatorOperation kind.
operandScalarExprInput expression.
Constructor
def __init__(self, operator: UnaryOperator, operand: ScalarExpr) -> None
Attributes

UnaryOperator [source]

class UnaryOperator(enum.Enum)

Enumerate unary scalar operations preserved for materialization.

Attributes

WhileInstruction [source]

class WhileInstruction

Repeat a structured region while a runtime predicate is true.

Parameters:

NameTypeDescription
conditionScalarExprRuntime loop predicate.
inputstuple[WireId, ...]Wires entering the loop.
bodytuple[CircuitInstruction, ...]Loop body.
body_outputstuple[WireId, ...]Wires yielded to the next iteration.
outputstuple[WireId, ...]Wires available after loop termination.
body_global_phaseScalarExprPhase applied once per loop iteration.
Constructor
def __init__(
    self,
    condition: ScalarExpr,
    inputs: tuple[WireId, ...],
    body: tuple[CircuitInstruction, ...],
    body_outputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    body_global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

WireId [source]

class WireId

Identify one version of a virtual quantum wire.

Parameters:

NameTypeDescription
valueintNon-negative module-local wire number.
Constructor
def __init__(self, value: int) -> None
Attributes

qamomile.circuit.transpiler.circuit_ir.capability

Declare circuit-target capabilities and compilation preferences.

Capabilities describe the complete target-legal input language accepted by a materializer. Policy selects between multiple legal realizations. Neither object performs rewriting; :mod:qamomile.circuit.transpiler.circuit_ir.legalize uses both to produce a target-legal :class:CircuitProgram.

Overview

ClassDescription
BinaryOperatorEnumerate scalar operations preserved until target materialization.
CallControlModeEnumerate how a target realizes controls on reusable calls.
CallPhaseModeEnumerate how a target realizes phase in coherently controlled calls.
CallTransformCapabilitiesDeclare reusable-call forms accepted by a target realization.
CircuitCapabilitiesDeclare the complete circuit-IR language accepted by one target.
CompilationPolicySelect preferred realizations among target-supported alternatives.
GateKindClassification of gates for emission.
GlobalPhaseCapabilitiesDeclare exact standalone global-phase realization requirements.
NativeSemanticOpCapabilitiesDeclare a target-native realization of an abstract operation.
PauliEvolutionRealizationEnumerate legalization states for abstract Pauli evolution.
ReusableCircuitDescribe a reusable circuit body and requested transforms.
ScalarAtomEnumerate leaf values that may occur in a scalar expression.
ScalarCapabilitiesDeclare the scalar language accepted in one instruction context.
ScalarExpressionFormEnumerate permitted runtime-parameter expression shapes.
SemanticOpKeyIdentify an abstract operation independently of any engine.
UnaryOperatorEnumerate unary scalar operations preserved for materialization.

Constants

Classes

BinaryOperator [source]

class BinaryOperator(enum.Enum)

Enumerate scalar operations preserved until target materialization.

Attributes

CallControlMode [source]

class CallControlMode(enum.Enum)

Enumerate how a target realizes controls on reusable calls.

Attributes

CallPhaseMode [source]

class CallPhaseMode(enum.Enum)

Enumerate how a target realizes phase in coherently controlled calls.

NATIVE_BODY means the target call itself preserves the reusable body’s phase. EXPLICIT_CORRECTION means the materializer emits a separate phase correction alongside the call. UNSUPPORTED rejects a body phase once coherent controls make it observable.

Attributes

CallTransformCapabilities [source]

class CallTransformCapabilities

Declare reusable-call forms accepted by a target realization.

Parameters:

NameTypeDescription
supports_powerboolWhether powers other than one are accepted.
supports_inverseboolWhether inverse calls are accepted.
max_controlsint | NoneMaximum added controls. None means no declared limit.
supports_nonunitary_bodyboolWhether a reusable body may contain measurement, reset, or dynamic control flow.
supports_barrier_bodyboolWhether barriers may remain inside a reusable body.
control_modeCallControlModeHow added controls are realized.
controlled_gate_kindsfrozenset[GateKind]Body gate kinds accepted when controls are distributed into the body.
controlled_pauli_timeScalarCapabilities | NonePauli-time scalar language accepted under distributed controls, or None when controlled Pauli evolution is unsupported.
phase_modeCallPhaseModeHow a reusable body’s phase is realized after coherent controls are known. For native semantic calls, an EXPLICIT_CORRECTION declaration makes the native materializer responsible for emitting that correction. Defaults to UNSUPPORTED.
controlled_phase_scalarsScalarCapabilities | NoneScalar language accepted for an observable controlled-call phase, or None when no such phase is supported. Defaults to None.
Constructor
def __init__(
    self,
    supports_power: bool,
    supports_inverse: bool,
    max_controls: int | None,
    supports_nonunitary_body: bool = False,
    supports_barrier_body: bool = False,
    control_mode: CallControlMode = CallControlMode.WHOLE_CALL,
    controlled_gate_kinds: frozenset[GateKind] = frozenset(),
    controlled_pauli_time: ScalarCapabilities | None = None,
    phase_mode: CallPhaseMode = CallPhaseMode.UNSUPPORTED,
    controlled_phase_scalars: ScalarCapabilities | None = None,
) -> None
Attributes
Methods
accepts
def accepts(self, callee: ReusableCircuit, inherited_controls: int = 0) -> bool

Return whether this declaration accepts a concrete call shape.

Parameters:

NameTypeDescription
calleeReusableCircuitReusable body and requested transforms.
inherited_controlsintControls physically distributed from an enclosing call. Defaults to zero.

Returns:

bool — Whether power, inverse, and control transforms are accepted.


CircuitCapabilities [source]

class CircuitCapabilities

Declare the complete circuit-IR language accepted by one target.

Parameters:

NameTypeDescription
namestrStable target name used in diagnostics.
primitive_gatesfrozenset[GateKind]Primitive gate kinds accepted by the target materializer.
native_semantic_opstuple[NativeSemanticOpCapabilities, ...]Native realizations keyed by open semantic operation identity.
gate_parametersScalarCapabilitiesScalar language accepted by gate parameters.
predicatesScalarCapabilitiesScalar language accepted by dynamic if and while predicates.
pauli_timeScalarCapabilitiesScalar language accepted by Pauli evolution time values.
global_phaseGlobalPhaseCapabilities | ScalarCapabilities | NoneExact standalone phase realization requirements, or None when unsupported. The former ScalarCapabilities value remains accepted and readable for source compatibility.
generic_callsCallTransformCapabilitiesReusable-call forms accepted after semantic-call legalization.
supports_dynamic_ifboolWhether runtime if regions are accepted.
supports_dynamic_whileboolWhether runtime while regions are accepted.
supports_resetboolWhether reset instructions are accepted.
pauli_realizationsfrozenset[PauliEvolutionRealization]Concrete Pauli-evolution realizations accepted by the materializer.
Constructor
def __init__(
    self,
    name: str,
    primitive_gates: frozenset[GateKind],
    native_semantic_ops: tuple[NativeSemanticOpCapabilities, ...],
    gate_parameters: ScalarCapabilities,
    predicates: ScalarCapabilities,
    pauli_time: ScalarCapabilities,
    global_phase: GlobalPhaseCapabilities | ScalarCapabilities | None,
    generic_calls: CallTransformCapabilities,
    supports_dynamic_if: bool,
    supports_dynamic_while: bool,
    supports_reset: bool,
    pauli_realizations: frozenset[PauliEvolutionRealization],
) -> None
Attributes
Methods
native_semantic_op
def native_semantic_op(self, key: SemanticOpKey) -> NativeSemanticOpCapabilities | None

Return the native declaration for one semantic operation.

Parameters:

NameTypeDescription
keySemanticOpKeySemantic operation key to look up.

Returns:

NativeSemanticOpCapabilities | None — NativeSemanticOpCapabilities | None: Matching declaration, or NativeSemanticOpCapabilities | None — None when the target has no native realization.


CompilationPolicy [source]

class CompilationPolicy

Select preferred realizations among target-supported alternatives.

Parameters:

NameTypeDescription
prefer_native_semantic_opsboolWhether legal target-native realizations are preferred over reusable fallback bodies. Defaults to True.
prefer_native_pauli_evolutionboolWhether native Pauli evolution is preferred over a gate gadget. Defaults to True.
Constructor
def __init__(
    self,
    prefer_native_semantic_ops: bool = True,
    prefer_native_pauli_evolution: bool = True,
) -> None
Attributes

GateKind [source]

class GateKind(Enum)

Classification of gates for emission.

Attributes

GlobalPhaseCapabilities [source]

class GlobalPhaseCapabilities

Declare exact standalone global-phase realization requirements.

Parameters:

NameTypeDescription
scalarsScalarCapabilitiesScalar language accepted for the phase.
min_qubitsintMinimum program width required to preserve a nonzero standalone phase. Targets with a native zero-qubit phase operation, or permission to allocate an internal clean carrier, use the default zero. Targets that require an existing logical qubit declare one.
Constructor
def __init__(self, scalars: ScalarCapabilities, min_qubits: int = 0) -> None
Attributes

NativeSemanticOpCapabilities [source]

class NativeSemanticOpCapabilities

Declare a target-native realization of an abstract operation.

Parameters:

NameTypeDescription
keySemanticOpKeyEngine-independent semantic operation key.
realizationstrTarget-owned realization identifier passed to the materializer after legalization.
call_transformsCallTransformCapabilitiesCall shapes supported by the native realization.
operand_widthstuple[int | None, ...] | NoneRequired semantic operand grouping. None accepts any grouping; an integer requires that exact width and None inside the tuple accepts any positive width at that position. Defaults to None.
min_qubitsintMinimum fallback-body width accepted by the native operation. Defaults to zero.
max_qubitsint | NoneMaximum fallback-body width, or None for no limit. Defaults to None.
required_argumentsfrozenset[str]Semantic argument names required by this realization. Defaults to none.
matching_operand_widthstuple[tuple[int, int], ...]Pairs of operand positions that must have equal widths. Defaults to none.
Constructor
def __init__(
    self,
    key: SemanticOpKey,
    realization: str,
    call_transforms: CallTransformCapabilities,
    operand_widths: tuple[int | None, ...] | None = None,
    min_qubits: int = 0,
    max_qubits: int | None = None,
    required_arguments: frozenset[str] = frozenset(),
    matching_operand_widths: tuple[tuple[int, int], ...] = (),
) -> None
Attributes
Methods
accepts
def accepts(self, callee: ReusableCircuit, inherited_controls: int = 0) -> bool

Return whether this realization accepts one semantic call shape.

Parameters:

NameTypeDescription
calleeReusableCircuitReusable call retaining source operand grouping and deferred transforms.
inherited_controlsintControls physically distributed from an enclosing call. Defaults to zero.

Returns:

bool — Whether transform, total-width, and operand-shape contracts bool — all accept the call.


PauliEvolutionRealization [source]

class PauliEvolutionRealization(enum.Enum)

Enumerate legalization states for abstract Pauli evolution.

Attributes

ReusableCircuit [source]

class ReusableCircuit

Describe a reusable circuit body and requested transforms.

Parameters:

NameTypeDescription
bodyCircuitProgramReusable circuit body.
namestrDisplay and linkage name.
powerintIntegral repetition count. Defaults to one.
controlsintAdded control-wire count. Defaults to zero.
inverseboolWhether to apply the inverse body. Defaults to false.
identityCallableIdentity | NoneSemantic identity preserved for target legalization. None marks an anonymous body. Defaults to None.
native_realizationstr | NoneTarget-owned realization identifier selected during legalization. None keeps the reusable body as the fallback implementation. Defaults to None.
operand_widthstuple[int, ...]Flattened width of each semantic quantum operand before engine lowering. A vector contributes its element count and a scalar qubit contributes one. An empty tuple means the source boundary did not expose operand grouping.
Constructor
def __init__(
    self,
    body: CircuitProgram,
    name: str,
    power: int = 1,
    controls: int = 0,
    inverse: bool = False,
    identity: CallableIdentity | None = None,
    native_realization: str | None = None,
    operand_widths: tuple[int, ...] = (),
) -> None
Attributes

ScalarAtom [source]

class ScalarAtom(enum.Enum)

Enumerate leaf values that may occur in a scalar expression.

Attributes

ScalarCapabilities [source]

class ScalarCapabilities

Declare the scalar language accepted in one instruction context.

Parameters:

NameTypeDescription
atomsfrozenset[ScalarAtom]Leaf value kinds accepted in the expression.
unary_operatorsfrozenset[UnaryOperator]Accepted unary operators.
binary_operatorsfrozenset[BinaryOperator]Accepted binary operators.
parameter_formScalarExpressionFormMaximum algebraic form for runtime parameters.
Constructor
def __init__(
    self,
    atoms: frozenset[ScalarAtom],
    unary_operators: frozenset[UnaryOperator],
    binary_operators: frozenset[BinaryOperator],
    parameter_form: ScalarExpressionForm,
) -> None
Attributes

ScalarExpressionForm [source]

class ScalarExpressionForm(enum.Enum)

Enumerate permitted runtime-parameter expression shapes.

Attributes

SemanticOpKey [source]

class SemanticOpKey

Identify an abstract operation independently of any engine.

The key is deliberately open rather than an enum. Standard-library, algorithm, provider, and user callables can therefore participate in native realization without modifying the compiler’s closed vocabulary.

Parameters:

NameTypeDescription
namespacestrStable owner namespace such as qamomile.stdlib.
namestrStable operation name within the namespace.
versionstrSemantic contract version. Defaults to "1".
variantstr | NoneOptional exact semantic variant, such as a decomposition strategy. Defaults to None.
Constructor
def __init__(
    self,
    namespace: str,
    name: str,
    version: str = '1',
    variant: str | None = None,
) -> None
Attributes

UnaryOperator [source]

class UnaryOperator(enum.Enum)

Enumerate unary scalar operations preserved for materialization.

Attributes

qamomile.circuit.transpiler.circuit_ir.emitter

Gate-emitter adapter that lowers the existing circuit walk into circuit IR.

Overview

FunctionDescription
as_scalar_exprNormalize a Python scalar or existing expression.
ClassDescription
BinOpKind
BinaryExprApply a binary scalar operation.
BinaryOperatorEnumerate scalar operations preserved until target materialization.
CircuitBuilderBuild immutable circuit IR while assigning fresh wire versions.
CircuitGateEmitterEmit primitive operations into engine-neutral circuit IR.
CircuitProgramStore one immutable engine-neutral circuit program.
ClassicalBitExprReference a measured classical bit.
GateKindClassification of gates for emission.
MeasurementModeHow an engine handles measurement operations.
ParameterExprReference a runtime circuit parameter.
ReusableCircuitDescribe a reusable circuit body and requested transforms.

Constants

Functions

as_scalar_expr [source]

def as_scalar_expr(value: ScalarExpr | bool | int | float) -> ScalarExpr

Normalize a Python scalar or existing expression.

Parameters:

NameTypeDescription
valueScalarExpr | bool | int | floatValue to normalize.

Returns:

ScalarExpr — Existing expression or a new literal expression.

Classes

BinOpKind [source]

class BinOpKind(enum.Enum)
Attributes

BinaryExpr [source]

class BinaryExpr(_ScalarOperators)

Apply a binary scalar operation.

Parameters:

NameTypeDescription
operatorBinaryOperatorOperation kind.
leftScalarExprLeft operand.
rightScalarExprRight operand.
Constructor
def __init__(self, operator: BinaryOperator, left: ScalarExpr, right: ScalarExpr) -> None
Attributes

BinaryOperator [source]

class BinaryOperator(enum.Enum)

Enumerate scalar operations preserved until target materialization.

Attributes

CircuitBuilder [source]

class CircuitBuilder

Build immutable circuit IR while assigning fresh wire versions.

Parameters:

NameTypeDescription
num_qubitsintNumber of virtual qubit slots.
num_clbitsintNumber of classical bit slots.
namestrCircuit name. Defaults to "main".
Constructor
def __init__(self, num_qubits: int, num_clbits: int, name: str = 'main') -> None

Initialize a circuit builder.

Parameters:

NameTypeDescription
num_qubitsintNumber of virtual qubit slots.
num_clbitsintNumber of classical bit slots.
namestrCircuit name. Defaults to "main".

Raises:

Attributes
Methods
add_global_phase
def add_global_phase(self, phase: ScalarExpr | bool | int | float) -> None

Accumulate a global phase in the current lexical region.

Parameters:

NameTypeDescription
phaseScalarExpr | bool | int | floatPhase contribution.
append_barrier
def append_barrier(self, qubits: tuple[int, ...]) -> None

Append a scheduling barrier without changing wire versions.

Parameters:

NameTypeDescription
qubitstuple[int, ...]Participating qubit slots.
append_call
def append_call(self, callee: ReusableCircuit, qubits: tuple[int, ...]) -> None

Append a reusable-circuit call and advance its wires.

Parameters:

NameTypeDescription
calleeReusableCircuitReusable circuit and transforms.
qubitstuple[int, ...]Participating qubit slots.
append_gate
def append_gate(
    self,
    kind: GateKind,
    qubits: tuple[int, ...],
    parameters: tuple[ScalarExpr, ...] = (),
) -> None

Append a primitive gate and advance all participating wires.

Parameters:

NameTypeDescription
kindGateKindPrimitive gate kind.
qubitstuple[int, ...]Participating qubit slots.
parameterstuple[ScalarExpr, ...]Gate parameters. Defaults to an empty tuple.
append_measure
def append_measure(self, qubit: int, clbit: int) -> None

Append a measurement.

Parameters:

NameTypeDescription
qubitintMeasured qubit slot.
clbitintDestination classical bit slot.

Raises:

append_measure_vector
def append_measure_vector(self, qubits: tuple[int, ...], clbits: tuple[int, ...]) -> None

Append one ordered vector measurement.

Parameters:

NameTypeDescription
qubitstuple[int, ...]Measured qubit slots in result order.
clbitstuple[int, ...]Destination classical slots.

Raises:

append_pauli_evolution
def append_pauli_evolution(
    self,
    qubits: tuple[int, ...],
    hamiltonian: Any,
    time: ScalarExpr | bool | int | float,
) -> None

Append an abstract Pauli evolution and advance its wires.

Parameters:

NameTypeDescription
qubitstuple[int, ...]Participating qubit slots.
hamiltonianAnyQamomile Hamiltonian value.
timeScalarExpr | bool | int | floatEvolution time.

Raises:

append_reset
def append_reset(self, qubit: int) -> None

Append reset and advance the affected wire.

Parameters:

NameTypeDescription
qubitintQubit slot to reset.
begin_else
def begin_else(self, context: _IfContext) -> None

Close a true region and open its false region.

Parameters:

NameTypeDescription
context_IfContextToken returned by :meth:begin_if.

Raises:

begin_for
def begin_for(self, indexset: range) -> LoopVariableExpr

Open a structured for-loop body.

Parameters:

NameTypeDescription
indexsetrangeConcrete iteration range.

Returns:

LoopVariableExpr — Induction expression available inside the body.

begin_if
def begin_if(self, condition: ScalarExpr) -> _IfContext

Open the true region of a structured conditional.

Parameters:

NameTypeDescription
conditionScalarExprRuntime branch predicate.

Returns:

_IfContext — Opaque builder token used to select the else branch.

begin_while
def begin_while(self, condition: ScalarExpr) -> _WhileContext

Open a structured while-loop body.

Parameters:

NameTypeDescription
conditionScalarExprRuntime loop predicate.

Returns:

_WhileContext — Opaque builder token used to close the loop.

current_wire
def current_wire(self, qubit: int) -> WireId

Return the current wire version for a qubit slot.

Parameters:

NameTypeDescription
qubitintPhysical slot index assigned by circuit lowering.

Returns:

WireId — Current version of the slot.

Raises:

end_for
def end_for(self) -> None

Close the innermost structured for-loop body.

Raises:

end_if
def end_if(self, context: _IfContext) -> None

Close a structured conditional and merge its wire states.

Parameters:

NameTypeDescription
context_IfContextToken returned by :meth:begin_if.

Raises:

end_while
def end_while(self, context: _WhileContext) -> None

Close a structured while-loop body.

Parameters:

NameTypeDescription
context_WhileContextToken returned by :meth:begin_while.

Raises:

freeze
def freeze(self) -> CircuitProgram

Finalize the root region into immutable circuit IR.

Returns:

CircuitProgram — Immutable circuit program.

Raises:

fresh_wire
def fresh_wire(self) -> WireId

Allocate a fresh module-local virtual wire version.

Returns:

WireId — Newly allocated wire identifier.

restore_state
def restore_state(self, snapshot: _CircuitBuilderSnapshot) -> None

Restore a checkpoint after an append-only emission attempt.

Parameters:

NameTypeDescription
snapshot_CircuitBuilderSnapshotCheckpoint returned by :meth:snapshot_state for this builder.

Raises:

snapshot_state
def snapshot_state(self) -> _CircuitBuilderSnapshot

Capture state that can be restored after declined emission.

Returns:

_CircuitBuilderSnapshot — Append-only builder checkpoint for the current structured region.


CircuitGateEmitter [source]

class CircuitGateEmitter

Emit primitive operations into engine-neutral circuit IR.

Attributes
Methods
append_gate
def append_gate(
    self,
    circuit: CircuitBuilder,
    gate: ReusableCircuit,
    qubits: list[int],
) -> None

Append a reusable circuit call.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
gateReusableCircuitReusable circuit value.
qubitslist[int]Participating slots.
circuit_to_gate
def circuit_to_gate(
    self,
    circuit: CircuitBuilder | CircuitProgram,
    name: str = 'U',
) -> ReusableCircuit

Freeze a circuit as a reusable circuit value.

Parameters:

NameTypeDescription
circuitCircuitBuilder | CircuitProgramCircuit body.
namestrReusable circuit name. Defaults to "U".

Returns:

ReusableCircuit — Reusable body without target-native state.

combine_symbolic
def combine_symbolic(
    self,
    kind: BinOpKind,
    lhs: ScalarExpr | bool | int | float,
    rhs: ScalarExpr | bool | int | float,
) -> BinaryExpr | None

Combine symbolic operands without creating engine expressions.

Parameters:

NameTypeDescription
kindBinOpKindQamomile arithmetic operation.
lhsScalarExpr | bool | int | floatLeft operand.
rhsScalarExpr | bool | int | floatRight operand.

Returns:

BinaryExpr | None — BinaryExpr | None: Target-neutral expression, or None for an unsupported operation kind.

create_circuit
def create_circuit(self, num_qubits: int, num_clbits: int) -> CircuitBuilder

Create an empty circuit IR builder.

Parameters:

NameTypeDescription
num_qubitsintNumber of virtual qubit slots.
num_clbitsintNumber of classical bit slots.

Returns:

CircuitBuilder — Empty engine-neutral builder.

create_parameter
def create_parameter(self, name: str) -> ParameterExpr

Create a target-neutral runtime parameter expression.

Parameters:

NameTypeDescription
namestrExternal parameter name.

Returns:

ParameterExpr — Parameter reference preserved until materialization.

emit_barrier
def emit_barrier(self, circuit: CircuitBuilder, qubits: list[int]) -> None

Emit a scheduling barrier.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitslist[int]Participating slots.
emit_ch
def emit_ch(self, circuit: CircuitBuilder, control: int, target: int) -> None

Emit a controlled-H gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
emit_cp
def emit_cp(
    self,
    circuit: CircuitBuilder,
    control: int,
    target: int,
    angle: ScalarExpr | float,
) -> None

Emit a controlled-phase rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
angleScalarExpr | floatPhase angle in radians.
emit_crx
def emit_crx(
    self,
    circuit: CircuitBuilder,
    control: int,
    target: int,
    angle: ScalarExpr | float,
) -> None

Emit a controlled-RX rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
angleScalarExpr | floatRotation angle in radians.
emit_cry
def emit_cry(
    self,
    circuit: CircuitBuilder,
    control: int,
    target: int,
    angle: ScalarExpr | float,
) -> None

Emit a controlled-RY rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
angleScalarExpr | floatRotation angle in radians.
emit_crz
def emit_crz(
    self,
    circuit: CircuitBuilder,
    control: int,
    target: int,
    angle: ScalarExpr | float,
) -> None

Emit a controlled-RZ rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
angleScalarExpr | floatRotation angle in radians.
emit_cx
def emit_cx(self, circuit: CircuitBuilder, control: int, target: int) -> None

Emit a controlled-X gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
emit_cy
def emit_cy(self, circuit: CircuitBuilder, control: int, target: int) -> None

Emit a controlled-Y gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
emit_cz
def emit_cz(self, circuit: CircuitBuilder, control: int, target: int) -> None

Emit a controlled-Z gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
emit_else_start
def emit_else_start(self, circuit: CircuitBuilder, context: Any) -> None

Switch an open conditional to its false branch.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
contextAnyOpaque conditional context.
emit_for_loop_end
def emit_for_loop_end(self, circuit: CircuitBuilder, context: Any) -> None

Close a structured for-loop body.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
contextAnyInduction expression returned at loop start.
emit_for_loop_start
def emit_for_loop_start(self, circuit: CircuitBuilder, indexset: range) -> ScalarExpr

Open a structured for-loop body.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
indexsetrangeConcrete iteration range.

Returns:

ScalarExpr — Target-neutral induction expression.

emit_global_phase
def emit_global_phase(self, circuit: CircuitBuilder, angle: ScalarExpr | float) -> None

Accumulate a phase in the builder’s current lexical region.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
angleScalarExpr | floatPhase angle in radians.
emit_h
def emit_h(self, circuit: CircuitBuilder, qubit: int) -> None

Emit a Hadamard gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_if_end
def emit_if_end(self, circuit: CircuitBuilder, context: Any) -> None

Close a structured conditional.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
contextAnyOpaque conditional context.
emit_if_start
def emit_if_start(self, circuit: CircuitBuilder, clbit: int, value: int = 1) -> Any

Open a structured conditional true branch.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
clbitintPredicate classical bit slot.
valueintRequired bit value. Defaults to one.

Returns:

Any — Opaque conditional builder context.

emit_measure
def emit_measure(self, circuit: CircuitBuilder, qubit: int, clbit: int) -> None

Emit a measurement into a classical slot.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintMeasured qubit slot.
clbitintDestination classical slot.
emit_measure_vector
def emit_measure_vector(
    self,
    circuit: CircuitBuilder,
    qubits: tuple[int, ...],
    clbits: tuple[int, ...],
) -> None

Preserve an ordered vector measurement as one instruction.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitstuple[int, ...]Measured qubit slots in result order.
clbitstuple[int, ...]Destination classical slots.
emit_p
def emit_p(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> None

Emit a phase rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
angleScalarExpr | floatPhase angle in radians.
emit_reset
def emit_reset(self, circuit: CircuitBuilder, qubit: int) -> None

Emit a reset-to-zero operation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintReset qubit slot.
emit_rx
def emit_rx(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> None

Emit an RX rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
angleScalarExpr | floatRotation angle in radians.
emit_ry
def emit_ry(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> None

Emit an RY rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
angleScalarExpr | floatRotation angle in radians.
emit_rz
def emit_rz(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> None

Emit an RZ rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
angleScalarExpr | floatRotation angle in radians.
emit_rzz
def emit_rzz(
    self,
    circuit: CircuitBuilder,
    qubit1: int,
    qubit2: int,
    angle: ScalarExpr | float,
) -> None

Emit an RZZ rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubit1intFirst slot.
qubit2intSecond slot.
angleScalarExpr | floatRotation angle in radians.
emit_s
def emit_s(self, circuit: CircuitBuilder, qubit: int) -> None

Emit an S gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_sdg
def emit_sdg(self, circuit: CircuitBuilder, qubit: int) -> None

Emit an inverse-S gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_swap
def emit_swap(self, circuit: CircuitBuilder, qubit1: int, qubit2: int) -> None

Emit a SWAP gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubit1intFirst slot.
qubit2intSecond slot.
emit_t
def emit_t(self, circuit: CircuitBuilder, qubit: int) -> None

Emit a T gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_tdg
def emit_tdg(self, circuit: CircuitBuilder, qubit: int) -> None

Emit an inverse-T gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_toffoli
def emit_toffoli(
    self,
    circuit: CircuitBuilder,
    control1: int,
    control2: int,
    target: int,
) -> None

Emit a Toffoli gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
control1intFirst control slot.
control2intSecond control slot.
targetintTarget slot.
emit_while_end
def emit_while_end(self, circuit: CircuitBuilder, context: Any) -> None

Close a structured while-loop body.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
contextAnyOpaque while-loop context.
emit_while_start
def emit_while_start(self, circuit: CircuitBuilder, clbit: int, value: int = 1) -> Any

Open a structured while-loop body.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
clbitintPredicate classical bit slot.
valueintRequired bit value. Defaults to one.

Returns:

Any — Opaque while-loop builder context.

emit_x
def emit_x(self, circuit: CircuitBuilder, qubit: int) -> None

Emit a Pauli-X gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_y
def emit_y(self, circuit: CircuitBuilder, qubit: int) -> None

Emit a Pauli-Y gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_z
def emit_z(self, circuit: CircuitBuilder, qubit: int) -> None

Emit a Pauli-Z gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
gate_controlled
def gate_controlled(self, gate: ReusableCircuit, num_controls: int) -> ReusableCircuit

Add control wires to a reusable circuit.

Parameters:

NameTypeDescription
gateReusableCircuitReusable circuit value.
num_controlsintNumber of controls to add.

Returns:

ReusableCircuit — Controlled reusable circuit.

gate_inverse
def gate_inverse(self, gate: ReusableCircuit) -> ReusableCircuit

Toggle the inverse transform on a reusable circuit.

Parameters:

NameTypeDescription
gateReusableCircuitReusable circuit value.

Returns:

ReusableCircuit — Inverse reusable circuit.

gate_power
def gate_power(self, gate: ReusableCircuit, power: int) -> ReusableCircuit

Apply an integral power transform to a reusable circuit.

Parameters:

NameTypeDescription
gateReusableCircuitReusable circuit value.
powerintIntegral repetition count.

Returns:

ReusableCircuit — Transformed reusable circuit.

supports_for_loop
def supports_for_loop(self) -> bool

Report support for structured for loops.

Returns:

bool — Always True for circuit IR.

supports_gate_inverse
def supports_gate_inverse(self) -> bool

Report support for deferred inverse transforms.

Returns:

bool — Always True for circuit IR.

supports_if_else
def supports_if_else(self) -> bool

Report support for structured conditionals.

Returns:

bool — Always True for circuit IR.

supports_reusable_gates
def supports_reusable_gates(self) -> bool

Report support for deferred reusable circuit calls.

Returns:

bool — Always True because :class:ReusableCircuit carries a target-neutral body and transforms until legalization or materialization.

supports_while_loop
def supports_while_loop(self) -> bool

Report support for structured while loops.

Returns:

bool — Always True for circuit IR.


CircuitProgram [source]

class CircuitProgram

Store one immutable engine-neutral circuit program.

Parameters:

NameTypeDescription
namestrCircuit entrypoint name.
num_qubitsintNumber of virtual input qubit slots.
num_clbitsintNumber of classical bit slots.
input_wirestuple[WireId, ...]Initial wire version per qubit slot.
output_wirestuple[WireId, ...]Final wire version per qubit slot.
operationstuple[CircuitInstruction, ...]Structured instruction sequence.
global_phaseScalarExprPhase accumulated in the root lexical region, in radians. Dynamic control-flow regions retain their own scoped phases. Defaults to zero and becomes observable when the program is controlled.
Constructor
def __init__(
    self,
    name: str,
    num_qubits: int,
    num_clbits: int,
    input_wires: tuple[WireId, ...],
    output_wires: tuple[WireId, ...],
    operations: tuple[CircuitInstruction, ...],
    global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

ClassicalBitExpr [source]

class ClassicalBitExpr(_ScalarOperators)

Reference a measured classical bit.

Parameters:

NameTypeDescription
indexintCircuit-local classical bit index.
Constructor
def __init__(self, index: int) -> None
Attributes

GateKind [source]

class GateKind(Enum)

Classification of gates for emission.

Attributes

MeasurementMode [source]

class MeasurementMode(Enum)

How an engine handles measurement operations.

Attributes

ParameterExpr [source]

class ParameterExpr(_ScalarOperators)

Reference a runtime circuit parameter.

Parameters:

NameTypeDescription
namestrStable external parameter name.
Constructor
def __init__(self, name: str) -> None
Attributes

ReusableCircuit [source]

class ReusableCircuit

Describe a reusable circuit body and requested transforms.

Parameters:

NameTypeDescription
bodyCircuitProgramReusable circuit body.
namestrDisplay and linkage name.
powerintIntegral repetition count. Defaults to one.
controlsintAdded control-wire count. Defaults to zero.
inverseboolWhether to apply the inverse body. Defaults to false.
identityCallableIdentity | NoneSemantic identity preserved for target legalization. None marks an anonymous body. Defaults to None.
native_realizationstr | NoneTarget-owned realization identifier selected during legalization. None keeps the reusable body as the fallback implementation. Defaults to None.
operand_widthstuple[int, ...]Flattened width of each semantic quantum operand before engine lowering. A vector contributes its element count and a scalar qubit contributes one. An empty tuple means the source boundary did not expose operand grouping.
Constructor
def __init__(
    self,
    body: CircuitProgram,
    name: str,
    power: int = 1,
    controls: int = 0,
    inverse: bool = False,
    identity: CallableIdentity | None = None,
    native_realization: str | None = None,
    operand_widths: tuple[int, ...] = (),
) -> None
Attributes

qamomile.circuit.transpiler.circuit_ir.legalize

Target legalization and legality verification for circuit programs.

Legalization is an IR-to-IR pass: it consumes one verified :class:CircuitProgram, selects target-native realizations without erasing callable boundaries, and returns a new immutable program. Verification then proves the result against the target’s declared capabilities before any materializer runs.

The pass rebuilds the program with freshly numbered wires instead of patching instruction tuples in place. Fallback bodies stay attached and are legalized recursively, allowing each materializer to lower them only at its own SDK boundary.

Overview

FunctionDescription
legalize_programRewrite one circuit program until it is legal for a target.
verify_target_legalProve a legalized program against declared target capabilities.
ClassDescription
BarrierInstructionSeparate scheduling regions without changing wire versions.
BinaryExprApply a binary scalar operation.
BinaryOperatorEnumerate scalar operations preserved until target materialization.
CallControlModeEnumerate how a target realizes controls on reusable calls.
CallInstructionInvoke a reusable circuit over versioned wires.
CallPhaseModeEnumerate how a target realizes phase in coherently controlled calls.
CallTransformCapabilitiesDeclare reusable-call forms accepted by a target realization.
CallableIdentityPreserve the semantic identity of a reusable circuit body.
CircuitCapabilitiesDeclare the complete circuit-IR language accepted by one target.
CircuitProgramStore one immutable engine-neutral circuit program.
ClassicalBitExprReference a measured classical bit.
CompilationPolicySelect preferred realizations among target-supported alternatives.
ForInstructionRepeat a structured circuit region over a concrete range.
GateInstructionApply one primitive gate to versioned virtual wires.
IfInstructionSelect between two structured circuit regions.
LiteralExprRepresent a concrete scalar literal.
LoopVariableExprReference the induction value of a structured loop.
MeasureInstructionMeasure a wire into a classical bit.
MeasureVectorInstructionMeasure an ordered group of wires into classical bits.
ParameterExprReference a runtime circuit parameter.
PauliEvolutionInstructionApply an abstract Hamiltonian evolution to selected wires.
PauliEvolutionRealizationEnumerate legalization states for abstract Pauli evolution.
ResetInstructionReset a wire and produce a fresh zero-state wire.
ReusableCircuitDescribe a reusable circuit body and requested transforms.
ScalarAtomEnumerate leaf values that may occur in a scalar expression.
ScalarCapabilitiesDeclare the scalar language accepted in one instruction context.
ScalarExpressionFormEnumerate permitted runtime-parameter expression shapes.
TargetCapabilityErrorA program requires a capability the selected target does not declare.
UnaryExprApply a unary scalar operation.
UnaryOperatorEnumerate unary scalar operations preserved for materialization.
WhileInstructionRepeat a structured region while a runtime predicate is true.
WireIdIdentify one version of a virtual quantum wire.

Constants

Functions

legalize_program [source]

def legalize_program(
    program: CircuitProgram,
    capabilities: CircuitCapabilities,
    policy: CompilationPolicy,
) -> CircuitProgram

Rewrite one circuit program until it is legal for a target.

Calls whose semantic key the target implements natively receive a target-owned realization identifier. Every other call retains its semantic identity and recursively legalized fallback body.

Parameters:

NameTypeDescription
programCircuitProgramVerified engine-neutral circuit program.
capabilitiesCircuitCapabilitiesDeclared target capabilities.
policyCompilationPolicyUser realization preferences.

Returns:

CircuitProgram — Rebuilt program with freshly numbered wires.


def verify_target_legal(program: CircuitProgram, capabilities: CircuitCapabilities) -> None

Prove a legalized program against declared target capabilities.

Parameters:

NameTypeDescription
programCircuitProgramLegalized circuit program, including every nested reusable-call body.
capabilitiesCircuitCapabilitiesDeclared target capabilities.

Raises:

Classes

BarrierInstruction [source]

class BarrierInstruction

Separate scheduling regions without changing wire versions.

Parameters:

NameTypeDescription
wirestuple[WireId, ...]Wires participating in the barrier.
Constructor
def __init__(self, wires: tuple[WireId, ...]) -> None
Attributes

BinaryExpr [source]

class BinaryExpr(_ScalarOperators)

Apply a binary scalar operation.

Parameters:

NameTypeDescription
operatorBinaryOperatorOperation kind.
leftScalarExprLeft operand.
rightScalarExprRight operand.
Constructor
def __init__(self, operator: BinaryOperator, left: ScalarExpr, right: ScalarExpr) -> None
Attributes

BinaryOperator [source]

class BinaryOperator(enum.Enum)

Enumerate scalar operations preserved until target materialization.

Attributes

CallControlMode [source]

class CallControlMode(enum.Enum)

Enumerate how a target realizes controls on reusable calls.

Attributes

CallInstruction [source]

class CallInstruction

Invoke a reusable circuit over versioned wires.

Parameters:

NameTypeDescription
calleeReusableCircuitReusable circuit and transforms.
inputstuple[WireId, ...]Consumed wire versions.
outputstuple[WireId, ...]Produced wire versions.
Constructor
def __init__(
    self,
    callee: ReusableCircuit,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
) -> None
Attributes

CallPhaseMode [source]

class CallPhaseMode(enum.Enum)

Enumerate how a target realizes phase in coherently controlled calls.

NATIVE_BODY means the target call itself preserves the reusable body’s phase. EXPLICIT_CORRECTION means the materializer emits a separate phase correction alongside the call. UNSUPPORTED rejects a body phase once coherent controls make it observable.

Attributes

CallTransformCapabilities [source]

class CallTransformCapabilities

Declare reusable-call forms accepted by a target realization.

Parameters:

NameTypeDescription
supports_powerboolWhether powers other than one are accepted.
supports_inverseboolWhether inverse calls are accepted.
max_controlsint | NoneMaximum added controls. None means no declared limit.
supports_nonunitary_bodyboolWhether a reusable body may contain measurement, reset, or dynamic control flow.
supports_barrier_bodyboolWhether barriers may remain inside a reusable body.
control_modeCallControlModeHow added controls are realized.
controlled_gate_kindsfrozenset[GateKind]Body gate kinds accepted when controls are distributed into the body.
controlled_pauli_timeScalarCapabilities | NonePauli-time scalar language accepted under distributed controls, or None when controlled Pauli evolution is unsupported.
phase_modeCallPhaseModeHow a reusable body’s phase is realized after coherent controls are known. For native semantic calls, an EXPLICIT_CORRECTION declaration makes the native materializer responsible for emitting that correction. Defaults to UNSUPPORTED.
controlled_phase_scalarsScalarCapabilities | NoneScalar language accepted for an observable controlled-call phase, or None when no such phase is supported. Defaults to None.
Constructor
def __init__(
    self,
    supports_power: bool,
    supports_inverse: bool,
    max_controls: int | None,
    supports_nonunitary_body: bool = False,
    supports_barrier_body: bool = False,
    control_mode: CallControlMode = CallControlMode.WHOLE_CALL,
    controlled_gate_kinds: frozenset[GateKind] = frozenset(),
    controlled_pauli_time: ScalarCapabilities | None = None,
    phase_mode: CallPhaseMode = CallPhaseMode.UNSUPPORTED,
    controlled_phase_scalars: ScalarCapabilities | None = None,
) -> None
Attributes
Methods
accepts
def accepts(self, callee: ReusableCircuit, inherited_controls: int = 0) -> bool

Return whether this declaration accepts a concrete call shape.

Parameters:

NameTypeDescription
calleeReusableCircuitReusable body and requested transforms.
inherited_controlsintControls physically distributed from an enclosing call. Defaults to zero.

Returns:

bool — Whether power, inverse, and control transforms are accepted.


CallableIdentity [source]

class CallableIdentity

Preserve the semantic identity of a reusable circuit body.

Parameters:

NameTypeDescription
keySemanticOpKeyOpen semantic identity used by target-native realization registries.
symbolstrHuman-readable callable name used for diagnostics.
argumentsSemanticArgumentsImmutable arguments that define this invocation’s meaning. Defaults to no arguments.
Constructor
def __init__(
    self,
    key: SemanticOpKey,
    symbol: str,
    arguments: SemanticArguments = SemanticArguments(),
) -> None
Attributes

CircuitCapabilities [source]

class CircuitCapabilities

Declare the complete circuit-IR language accepted by one target.

Parameters:

NameTypeDescription
namestrStable target name used in diagnostics.
primitive_gatesfrozenset[GateKind]Primitive gate kinds accepted by the target materializer.
native_semantic_opstuple[NativeSemanticOpCapabilities, ...]Native realizations keyed by open semantic operation identity.
gate_parametersScalarCapabilitiesScalar language accepted by gate parameters.
predicatesScalarCapabilitiesScalar language accepted by dynamic if and while predicates.
pauli_timeScalarCapabilitiesScalar language accepted by Pauli evolution time values.
global_phaseGlobalPhaseCapabilities | ScalarCapabilities | NoneExact standalone phase realization requirements, or None when unsupported. The former ScalarCapabilities value remains accepted and readable for source compatibility.
generic_callsCallTransformCapabilitiesReusable-call forms accepted after semantic-call legalization.
supports_dynamic_ifboolWhether runtime if regions are accepted.
supports_dynamic_whileboolWhether runtime while regions are accepted.
supports_resetboolWhether reset instructions are accepted.
pauli_realizationsfrozenset[PauliEvolutionRealization]Concrete Pauli-evolution realizations accepted by the materializer.
Constructor
def __init__(
    self,
    name: str,
    primitive_gates: frozenset[GateKind],
    native_semantic_ops: tuple[NativeSemanticOpCapabilities, ...],
    gate_parameters: ScalarCapabilities,
    predicates: ScalarCapabilities,
    pauli_time: ScalarCapabilities,
    global_phase: GlobalPhaseCapabilities | ScalarCapabilities | None,
    generic_calls: CallTransformCapabilities,
    supports_dynamic_if: bool,
    supports_dynamic_while: bool,
    supports_reset: bool,
    pauli_realizations: frozenset[PauliEvolutionRealization],
) -> None
Attributes
Methods
native_semantic_op
def native_semantic_op(self, key: SemanticOpKey) -> NativeSemanticOpCapabilities | None

Return the native declaration for one semantic operation.

Parameters:

NameTypeDescription
keySemanticOpKeySemantic operation key to look up.

Returns:

NativeSemanticOpCapabilities | None — NativeSemanticOpCapabilities | None: Matching declaration, or NativeSemanticOpCapabilities | None — None when the target has no native realization.


CircuitProgram [source]

class CircuitProgram

Store one immutable engine-neutral circuit program.

Parameters:

NameTypeDescription
namestrCircuit entrypoint name.
num_qubitsintNumber of virtual input qubit slots.
num_clbitsintNumber of classical bit slots.
input_wirestuple[WireId, ...]Initial wire version per qubit slot.
output_wirestuple[WireId, ...]Final wire version per qubit slot.
operationstuple[CircuitInstruction, ...]Structured instruction sequence.
global_phaseScalarExprPhase accumulated in the root lexical region, in radians. Dynamic control-flow regions retain their own scoped phases. Defaults to zero and becomes observable when the program is controlled.
Constructor
def __init__(
    self,
    name: str,
    num_qubits: int,
    num_clbits: int,
    input_wires: tuple[WireId, ...],
    output_wires: tuple[WireId, ...],
    operations: tuple[CircuitInstruction, ...],
    global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

ClassicalBitExpr [source]

class ClassicalBitExpr(_ScalarOperators)

Reference a measured classical bit.

Parameters:

NameTypeDescription
indexintCircuit-local classical bit index.
Constructor
def __init__(self, index: int) -> None
Attributes

CompilationPolicy [source]

class CompilationPolicy

Select preferred realizations among target-supported alternatives.

Parameters:

NameTypeDescription
prefer_native_semantic_opsboolWhether legal target-native realizations are preferred over reusable fallback bodies. Defaults to True.
prefer_native_pauli_evolutionboolWhether native Pauli evolution is preferred over a gate gadget. Defaults to True.
Constructor
def __init__(
    self,
    prefer_native_semantic_ops: bool = True,
    prefer_native_pauli_evolution: bool = True,
) -> None
Attributes

ForInstruction [source]

class ForInstruction

Repeat a structured circuit region over a concrete range.

Parameters:

NameTypeDescription
indexsetrangeConcrete iteration range.
loop_variableLoopVariableExprInduction expression used by the body.
inputstuple[WireId, ...]Wire versions entering the loop.
bodytuple[CircuitInstruction, ...]Single-iteration body.
body_outputstuple[WireId, ...]Body wire versions yielded to the next iteration.
outputstuple[WireId, ...]Wire versions after the loop.
Constructor
def __init__(
    self,
    indexset: range,
    loop_variable: LoopVariableExpr,
    inputs: tuple[WireId, ...],
    body: tuple[CircuitInstruction, ...],
    body_outputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
) -> None
Attributes

GateInstruction [source]

class GateInstruction

Apply one primitive gate to versioned virtual wires.

Parameters:

NameTypeDescription
kindGateKindPrimitive gate kind.
inputstuple[WireId, ...]Consumed wire versions.
outputstuple[WireId, ...]Produced wire versions.
parameterstuple[ScalarExpr, ...]Gate parameters.
Constructor
def __init__(
    self,
    kind: GateKind,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    parameters: tuple[ScalarExpr, ...] = (),
) -> None
Attributes

IfInstruction [source]

class IfInstruction

Select between two structured circuit regions.

Parameters:

NameTypeDescription
conditionScalarExprRuntime branch predicate.
inputstuple[WireId, ...]Wires entering both branches.
true_bodytuple[CircuitInstruction, ...]True branch body.
false_bodytuple[CircuitInstruction, ...]False branch body.
true_outputstuple[WireId, ...]Wires yielded by the true branch.
false_outputstuple[WireId, ...]Wires yielded by the false branch.
outputstuple[WireId, ...]Merged post-branch wires.
true_global_phaseScalarExprPhase applied only in the true branch.
false_global_phaseScalarExprPhase applied only in the false branch.
Constructor
def __init__(
    self,
    condition: ScalarExpr,
    inputs: tuple[WireId, ...],
    true_body: tuple[CircuitInstruction, ...],
    false_body: tuple[CircuitInstruction, ...],
    true_outputs: tuple[WireId, ...],
    false_outputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    true_global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
    false_global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

LiteralExpr [source]

class LiteralExpr(_ScalarOperators)

Represent a concrete scalar literal.

Parameters:

NameTypeDescription
valuebool | int | floatConcrete scalar value.
Constructor
def __init__(self, value: bool | int | float) -> None
Attributes

LoopVariableExpr [source]

class LoopVariableExpr(_ScalarOperators)

Reference the induction value of a structured loop.

Parameters:

NameTypeDescription
namestrCircuit-local loop variable name.
Constructor
def __init__(self, name: str) -> None
Attributes

MeasureInstruction [source]

class MeasureInstruction

Measure a wire into a classical bit.

Parameters:

NameTypeDescription
inputWireIdMeasured wire version.
outputWireIdPost-measurement wire version.
clbitintDestination classical bit index.
Constructor
def __init__(self, input: WireId, output: WireId, clbit: int) -> None
Attributes

MeasureVectorInstruction [source]

class MeasureVectorInstruction

Measure an ordered group of wires into classical bits.

This instruction preserves vector measurement as one semantic operation until target materialization. An engine with a vector measurement primitive can consume it directly; scalar-only engines expand it at their own boundary.

Parameters:

NameTypeDescription
inputstuple[WireId, ...]Measured wire versions in result order.
outputstuple[WireId, ...]Post-measurement wire versions.
clbitstuple[int, ...]Destination classical bits in result order.
Constructor
def __init__(
    self,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    clbits: tuple[int, ...],
) -> None
Attributes

ParameterExpr [source]

class ParameterExpr(_ScalarOperators)

Reference a runtime circuit parameter.

Parameters:

NameTypeDescription
namestrStable external parameter name.
Constructor
def __init__(self, name: str) -> None
Attributes

PauliEvolutionInstruction [source]

class PauliEvolutionInstruction

Apply an abstract Hamiltonian evolution to selected wires.

Parameters:

NameTypeDescription
hamiltonianAnyImmutable Qamomile Hamiltonian value.
timeScalarExprEvolution time in radians.
inputstuple[WireId, ...]Consumed wire versions.
outputstuple[WireId, ...]Produced wire versions.
realizationPauliEvolutionRealizationTarget realization selected by legalization. Defaults to ABSTRACT during shared lowering.
Constructor
def __init__(
    self,
    hamiltonian: Any,
    time: ScalarExpr,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    realization: PauliEvolutionRealization = PauliEvolutionRealization.ABSTRACT,
) -> None
Attributes

PauliEvolutionRealization [source]

class PauliEvolutionRealization(enum.Enum)

Enumerate legalization states for abstract Pauli evolution.

Attributes

ResetInstruction [source]

class ResetInstruction

Reset a wire and produce a fresh zero-state wire.

Parameters:

NameTypeDescription
inputWireIdWire version before reset.
outputWireIdFresh wire version after reset.
Constructor
def __init__(self, input: WireId, output: WireId) -> None
Attributes

ReusableCircuit [source]

class ReusableCircuit

Describe a reusable circuit body and requested transforms.

Parameters:

NameTypeDescription
bodyCircuitProgramReusable circuit body.
namestrDisplay and linkage name.
powerintIntegral repetition count. Defaults to one.
controlsintAdded control-wire count. Defaults to zero.
inverseboolWhether to apply the inverse body. Defaults to false.
identityCallableIdentity | NoneSemantic identity preserved for target legalization. None marks an anonymous body. Defaults to None.
native_realizationstr | NoneTarget-owned realization identifier selected during legalization. None keeps the reusable body as the fallback implementation. Defaults to None.
operand_widthstuple[int, ...]Flattened width of each semantic quantum operand before engine lowering. A vector contributes its element count and a scalar qubit contributes one. An empty tuple means the source boundary did not expose operand grouping.
Constructor
def __init__(
    self,
    body: CircuitProgram,
    name: str,
    power: int = 1,
    controls: int = 0,
    inverse: bool = False,
    identity: CallableIdentity | None = None,
    native_realization: str | None = None,
    operand_widths: tuple[int, ...] = (),
) -> None
Attributes

ScalarAtom [source]

class ScalarAtom(enum.Enum)

Enumerate leaf values that may occur in a scalar expression.

Attributes

ScalarCapabilities [source]

class ScalarCapabilities

Declare the scalar language accepted in one instruction context.

Parameters:

NameTypeDescription
atomsfrozenset[ScalarAtom]Leaf value kinds accepted in the expression.
unary_operatorsfrozenset[UnaryOperator]Accepted unary operators.
binary_operatorsfrozenset[BinaryOperator]Accepted binary operators.
parameter_formScalarExpressionFormMaximum algebraic form for runtime parameters.
Constructor
def __init__(
    self,
    atoms: frozenset[ScalarAtom],
    unary_operators: frozenset[UnaryOperator],
    binary_operators: frozenset[BinaryOperator],
    parameter_form: ScalarExpressionForm,
) -> None
Attributes

ScalarExpressionForm [source]

class ScalarExpressionForm(enum.Enum)

Enumerate permitted runtime-parameter expression shapes.

Attributes

TargetCapabilityError [source]

class TargetCapabilityError(EmitError)

A program requires a capability the selected target does not declare.

Raised by circuit-IR target-legality verification before any engine materialization starts. The message always names the target and the missing capability axis, so the failure reads as a target restriction rather than a Qamomile language error.

Parameters:

NameTypeDescription
messagestrHuman-readable diagnosis naming the target and the missing capability.
targetstr | NoneDeclared target name. Defaults to None.
operationstr | NoneInstruction description that triggered the failure. Defaults to None.

Example:

Correct — bind the runtime parameter before selecting a
concrete-angle-only target::

    transpiler.transpile(kernel, bindings={"theta": 0.5})

Incorrect — keeping ``theta`` symbolic on such a target raises this
error::

    transpiler.transpile(kernel, parameters=["theta"])
Constructor
def __init__(self, message: str, target: str | None = None, operation: str | None = None)

Initialize a target-capability diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable diagnosis naming the target and the missing capability.
targetstr | NoneDeclared target name. Defaults to None.
operationstr | NoneInstruction description that triggered the failure. Defaults to None.
Attributes

UnaryExpr [source]

class UnaryExpr(_ScalarOperators)

Apply a unary scalar operation.

Parameters:

NameTypeDescription
operatorUnaryOperatorOperation kind.
operandScalarExprInput expression.
Constructor
def __init__(self, operator: UnaryOperator, operand: ScalarExpr) -> None
Attributes

UnaryOperator [source]

class UnaryOperator(enum.Enum)

Enumerate unary scalar operations preserved for materialization.

Attributes

WhileInstruction [source]

class WhileInstruction

Repeat a structured region while a runtime predicate is true.

Parameters:

NameTypeDescription
conditionScalarExprRuntime loop predicate.
inputstuple[WireId, ...]Wires entering the loop.
bodytuple[CircuitInstruction, ...]Loop body.
body_outputstuple[WireId, ...]Wires yielded to the next iteration.
outputstuple[WireId, ...]Wires available after loop termination.
body_global_phaseScalarExprPhase applied once per loop iteration.
Constructor
def __init__(
    self,
    condition: ScalarExpr,
    inputs: tuple[WireId, ...],
    body: tuple[CircuitInstruction, ...],
    body_outputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    body_global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

WireId [source]

class WireId

Identify one version of a virtual quantum wire.

Parameters:

NameTypeDescription
valueintNon-negative module-local wire number.
Constructor
def __init__(self, value: int) -> None
Attributes

qamomile.circuit.transpiler.circuit_ir.lowering

Lower circuit-family execution plans into engine-neutral circuit IR.

Overview

FunctionDescription
bracket_control_valueBracket zero-valued controls with target-neutral Pauli-X gates.
build_controlled_block_qubit_mapBuild a block-local qubit map backed by physical target indices.
collect_reachable_valuesCollect values reachable from an IR block in canonical walk order.
content_fingerprintCompute a deterministic fingerprint for supported lowered IR content.
is_plain_intReturn True if value is a Python int but not a bool.
join_runtime_condition_sourcesJoin mutually exclusive overwrite states after runtime control flow.
lower_circuit_planLower every quantum segment in a plan to immutable circuit IR.
reconcile_parameter_metadataFilter provisional runtime metadata to parameters used by CircuitIR.
register_classical_merge_aliasesBind classical merge outputs to a concrete value when resolvable.
register_merge_outputsRegister merge output UUIDs via the shared map_merge_outputs utility.
reject_duplicate_physical_indicesReject a multi-qubit gate whose qubits resolve to the same physical qubit.
resolve_condition_addressResolve a runtime control-flow condition to its clbit_map key.
restore_runtime_condition_sourcesRestore one runtime-control-flow path’s overwrite state.
snapshot_runtime_condition_sourcesSnapshot path-local measurement sources overwritten by while loops.
validate_region_argsValidate the SSA identities owned by a loop’s region arguments.
verify_circuitVerify wire linearity, regions, expressions, and slot bounds.
ClassDescription
ArrayValueAn array of typed IR values.
BinaryExprApply a binary scalar operation.
BinaryOperatorEnumerate scalar operations preserved until target materialization.
BlockUnified block representation for all pipeline stages.
CallInstructionInvoke a reusable circuit over versioned wires.
CallableIdentityPreserve the semantic identity of a reusable circuit body.
CircuitBuilderBuild immutable circuit IR while assigning fresh wire versions.
CircuitGateEmitterEmit primitive operations into engine-neutral circuit IR.
CircuitLoweringPassLower a segmented circuit program into target-neutral builders.
CircuitProgramStore one immutable engine-neutral circuit program.
ClassicalBitExprReference a measured classical bit.
CompOpComparison operation (EQ, NEQ, LT, LE, GT, GE).
CompOpKind
CompiledQuantumSegmentA quantum segment with emitted engine circuit.
CompositeGateTypeClassify standard boxed quantum callables.
CondOpConditional logical operation (AND, OR).
CondOpKind
EmitErrorReport an engine failure to emit one semantic operation.
ExecutableProgramA fully compiled program ready for execution.
ForInstructionRepeat a structured circuit region over a concrete range.
GateInstructionApply one primitive gate to versioned virtual wires.
IfInstructionSelect between two structured circuit regions.
IfOperationRepresents an if-else conditional operation.
InvokeOperationRepresent a composite, stdlib, or oracle call.
LiteralExprRepresent a concrete scalar literal.
LoopVariableExprReference the induction value of a structured loop.
NotOp
ParameterExprReference a runtime circuit parameter.
PauliEvolutionInstructionApply an abstract Hamiltonian evolution to selected wires.
PauliEvolveOpPauli evolution operation: exp(-i * gamma * H).
ProgramPlanExecution plan for a hybrid quantum/classical program.
QubitAddressTyped key for qubit/clbit physical-index maps.
ReusableCircuitDescribe a reusable circuit body and requested transforms.
RuntimeClassicalExprA classical expression known to require runtime evaluation.
RuntimeOpKindUnified kind for RuntimeClassicalExpr covering all classical
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
SemanticArgumentsStore immutable named arguments belonging to an operation’s meaning.
SemanticOpKeyIdentify an abstract operation independently of any engine.
StandardEmitPassStandard emit pass implementation using GateEmitter protocol.
UnaryExprApply a unary scalar operation.
UnaryOperatorEnumerate unary scalar operations preserved for materialization.
ValueA typed SSA value in the IR.
WhileInstructionRepeat a structured region while a runtime predicate is true.
WhileOperationRepresents a while loop operation.

Constants

Functions

bracket_control_value [source]

def bracket_control_value(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    control_indices: Sequence[int],
    control_value: int | None,
) -> Generator[None, None, None]

Bracket zero-valued controls with target-neutral Pauli-X gates.

The controlled operation inside the context remains an ordinary all-ones control. Controls are interpreted LSB-first in their existing physical order, so bit zero of control_value describes control_indices[0]. One bracket surrounds the complete operation, including integral powers and vector-target broadcast.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass providing the gate emitter.
circuitAnyCircuit receiving the bracket gates.
control_indicesSequence[int]Ordered physical control qubits.
control_valueint | NoneRequired basis value, or None for the ordinary all-ones state.

Yields:

None — Control returns while the zero-valued controls are inverted.

Raises:


build_controlled_block_qubit_map [source]

def build_controlled_block_qubit_map(
    emit_pass: 'StandardEmitPass',
    block_value: Any,
    target_indices: list[int],
    bindings: dict[str, Any],
    parent_qubit_map: QubitMap | None = None,
) -> QubitMap

Build a block-local qubit map backed by physical target indices.

Seeds one entry per formal quantum input of block_value — scalar Qubit inputs map to one physical index, Vector[Qubit] inputs map per-element — positionally matching target_indices in declaration order.

Parameters:

NameTypeDescription
emit_passStandardEmitPassEmit pass used to resolve symbolic vector input shapes against bindings.
block_valueAnyInner block whose input_values define the quantum formal arguments. Objects without input_values yield an empty map.
target_indiceslist[int]Physical qubit indices supplied at the controlled call site, one per flattened quantum input qubit.
bindingsdict[str, Any]Bindings used while resolving vector input shapes.
parent_qubit_mapQubitMap | NoneParent-circuit allocation map containing any nested fresh-workspace addresses. Defaults to None.

Returns:

QubitMap — Mapping from the inner block’s formal quantum input addresses to physical parent-circuit qubit indices.

Raises:


collect_reachable_values [source]

def collect_reachable_values(block: Block) -> tuple[ValueBase, ...]

Collect values reachable from an IR block in canonical walk order.

The traversal includes values referenced by operation-owned nested blocks and returns each value UUID at most once. Its ordering is the same stable ordering used by canonical byte emission.

Parameters:

NameTypeDescription
blockBlockRoot block whose reachable values to collect.

Returns:

tuple[ValueBase, ...] — tuple[ValueBase, ...]: Reachable values in deterministic canonical declaration order.


content_fingerprint [source]

def content_fingerprint(obj: Any) -> str

Compute a deterministic fingerprint for supported lowered IR content.

Unlike the legacy canonical content_hash encoder, this function rejects values that would require a repr fallback. Its accepted values are the stable scalar, collection, enum, array, Hamiltonian, type, and dataclass forms used by lowered circuit programs.

Parameters:

NameTypeDescription
objAnyLowered IR content composed exclusively of supported stable values.

Returns:

str — SHA-256 hexadecimal digest of the structural content token.

Raises:


is_plain_int [source]

def is_plain_int(value: object) -> bool

Return True if value is a Python int but not a bool.

bool is a subclass of int in Python, so isinstance(True, int) is True. This helper distinguishes a genuine integer from a boolean, which matters wherever a boolean must be rejected in an integer slot — for example, validating decoded wire data or a register width.

Parameters:

NameTypeDescription
valueobjectThe value to test.

Returns:

bool — True when value is an int and not a bool.


join_runtime_condition_sources [source]

def join_runtime_condition_sources(emit_pass: 'StandardEmitPass', *paths: frozenset[tuple[str, int]] = ()) -> None

Join mutually exclusive overwrite states after runtime control flow.

Parameters:

NameTypeDescription
emit_passStandardEmitPassEmit pass receiving the joined state.
*pathsfrozenset[tuple[str, int]]Completed branch states.

lower_circuit_plan [source]

def lower_circuit_plan(
    plan: ProgramPlan,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> ExecutableProgram[CircuitProgram]

Lower every quantum segment in a plan to immutable circuit IR.

Classical and expectation-value orchestration metadata remains in the returned executable container. Only engine-native quantum artifacts are replaced with verified :class:CircuitProgram objects.

Parameters:

NameTypeDescription
planProgramPlanCircuit-family C-to-Q-to-C execution plan.
bindingsdict[str, Any] | NoneCompile-time parameter bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.

Returns:

ExecutableProgram[CircuitProgram] — ExecutableProgram[CircuitProgram]: Execution structure containing immutable engine-neutral quantum programs.

Raises:


reconcile_parameter_metadata [source]

def reconcile_parameter_metadata(program: CircuitProgram, metadata: ParameterMetadata) -> ParameterMetadata

Filter provisional runtime metadata to parameters used by CircuitIR.

Lowering may resolve formal runtime arguments before it knows whether the callee body uses them. The immutable circuit program is the authoritative record of actual use, while the provisional metadata retains ABI ordering, source references, container kinds, and engine parameter placeholders.

Parameters:

NameTypeDescription
programCircuitProgramVerified immutable circuit program.
metadataParameterMetadataProvisional segment parameter metadata.

Returns:

ParameterMetadata — Metadata containing exactly the used parameter slots, in their original ABI order.

Raises:


register_classical_merge_aliases [source]

def register_classical_merge_aliases(
    emit_pass: 'StandardEmitPass',
    op: IfOperation,
    bindings: dict[str, Any],
    resolved: bool | None,
) -> None

Bind classical merge outputs to a concrete value when resolvable.

The frontend creates a merge for every variable referenced in an if-branch, including read-only ones (e.g. a for-loop index j that is read but not assigned in the branch). These read-only merges are identity merges — both inputs reference the same IR Value — so the merge output is deterministically equal to that input.

For classical types (UInt / Float / Bit) the merge outputs are not captured by map_merge_outputs / remap_static_merge_outputs (which only handle qubit / clbit phys-resource mapping). Without this binding, downstream uses like data[j_merge_4] cannot resolve the index and emit fails with symbolic_index_not_bound.

The alias is written to bindings by both UUID and (when present) name, mirroring the pattern used by emit_for_unrolled for the original loop variable.

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe active emit pass (for resolver access).
opIfOperationThe if-else whose merged classical outputs should be bound; merges are read through iter_merges.
bindingsdict[str, Any]Current bindings; mutated in place to bind merge outputs.
resolvedbool | NoneTrue / False if the if was compile-time resolved (use the selected branch’s input); None if it was a runtime if (only bind identity merges).

Returns:

None — None.


register_merge_outputs [source]

def register_merge_outputs(
    emit_pass: 'StandardEmitPass',
    op: IfOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any] | None = None,
) -> None

Register merge output UUIDs via the shared map_merge_outputs utility.

Uses the full ValueResolver.resolve_qubit_index_detailed for scalar qubit resolution (handles array element operands). Runs at emit time with reject_runtime_bit_mux=True so an unrepresentable runtime multiplexing of two pre-existing measured bits fails loudly rather than silently binding the merge to the true branch.

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe active emit pass, providing the ValueResolver used for scalar / array-element resolution.
opIfOperationThe runtime if-else whose merged outputs are registered onto their physical clbits / qubits.
qubit_mapQubitMapAddress-to-physical-qubit map, mutated in place.
clbit_mapClbitMapAddress-to-physical-clbit map, mutated in place.
bindingsdict[str, Any] | NoneActive emit-time bindings used to fold a merge source’s symbolic Vector[Bit] element index (e.g. an unrolled loop variable). Defaults to None (empty).

Raises:


reject_duplicate_physical_indices [source]

def reject_duplicate_physical_indices(
    gate_label: str,
    physical_indices: list[int],
    operand_names: list[str] | None = None,
) -> None

Reject a multi-qubit gate whose qubits resolve to the same physical qubit.

A multi-qubit gate (cx / cz / swap / toffoli and any controlled block such as qmc.control(...)) is physically defined only on distinct qubits. The frontend’s _check_qubit_alias already rejects the scalar cx(q, q) case by logical_id at trace time, but symbolic array indices — cx(qs[i], qs[j]) where i == j only at runtime, or two loop-variable indices that coincide after unrolling — resolve to the same physical qubit only at emit time. Without this check the duplicate reaches the engine as a raw, engine-specific failure (Qiskit CircuitError: 'duplicate qubit arguments', a CUDA-Q simulator crash, or — on an engine that does not validate — a silently ill-defined gate). Raising a Qamomile QubitAliasError gives one actionable, engine-independent diagnostic.

This is the shared checker used both for native gates (emit_gate via _reject_aliased_operands) and for controlled / composite blocks (the append_gate sites in controlled_emission), so the same diagnostic covers every multi-qubit emission path on every engine.

Parameters:

NameTypeDescription
gate_labelstrHuman-readable name of the gate for the message (e.g. "CX" or "controlled gate").
physical_indiceslist[int]The resolved physical qubit indices the gate acts on, in operand order.
operand_nameslist[str] | NoneOptional display names aligned with physical_indices (e.g. ["qs[i]", "qs[j]"]). When absent, the message falls back to qubit<index>. Defaults to None.

Returns:

None — None

Raises:


resolve_condition_address [source]

def resolve_condition_address(
    condition: Value,
    bindings: dict[str, Any],
    resolver: ValueResolver | None,
) -> QubitAddress

Resolve a runtime control-flow condition to its clbit_map key.

Scalar measurement results carry their own UUID and the clbit allocator registers them under QubitAddress(bit.uuid). Vector[Bit] element accesses (s[i] where s = qmc.measure(register)) instead live under QubitAddress(root_array.uuid, root_index). The element index and every slice_start / slice_step along the parent’s slice_of chain are resolved the same way — taken directly when constant, otherwise folded through bindings via resolver so that loop-variable indices and runtime-valued slice bounds (s[j:k] where j/k are loop variables) both work. The chain composes into a root-space index via the standard affine map root_index = start + step * view_local_index repeated along the chain — matching ResourceAllocator._resolve_root_qubit_address / ValueResolver.resolve_slice_chain. Falls back to the scalar address when no parent array is set, or when the index or any slice bound cannot be resolved to a concrete int (e.g. an engine runtime parameter, which cannot index a static classical register, or any symbolic value with no resolver), deferring the diagnostic to the caller’s clbit_map lookup. Used by both the default if/while emission path and the Qiskit / CUDA-Q engines when looking up a measurement-derived clbit for a runtime predicate.

Parameters:

NameTypeDescription
conditionValueCondition operand of an IfOperation or WhileOperation, or an operand of a measurement-derived classical predicate (e.g. inside RuntimeClassicalExpr).
bindingsdict[str, Any]Active emit-time bindings used to resolve symbolic indices and slice bounds (loop variables, compile-time-bound parameters).
resolverValueResolver | NoneThe active ValueResolver exposing resolve_int_value. None is accepted for early-emit pre-scans (e.g. CUDA-Q’s loop-carried clbit collector) that run before runtime bindings exist — only the constant path is taken in that case; symbolic indices and symbolic slice bounds fall through to the scalar UUID.

Returns:

QubitAddress — Key suitable for looking up the condition in clbit_map.

See resolve_condition_address_detailed for the resolution contract.


restore_runtime_condition_sources [source]

def restore_runtime_condition_sources(emit_pass: 'StandardEmitPass', sources: frozenset[tuple[str, int]]) -> None

Restore one runtime-control-flow path’s overwrite state.

Parameters:

NameTypeDescription
emit_passStandardEmitPassEmit pass whose state is restored.
sourcesfrozenset[tuple[str, int]]Snapshot to install.

snapshot_runtime_condition_sources [source]

def snapshot_runtime_condition_sources(emit_pass: 'StandardEmitPass') -> frozenset[tuple[str, int]]

Snapshot path-local measurement sources overwritten by while loops.

Parameters:

NameTypeDescription
emit_passStandardEmitPassEmit pass carrying the current path state.

Returns:

frozenset[tuple[str, int]] — frozenset[tuple[str, int]]: Immutable snapshot of the current path.


validate_region_args [source]

def validate_region_args(op: ForOperation | ForItemsOperation | WhileOperation) -> tuple[RegionArg, ...]

Validate the SSA identities owned by a loop’s region arguments.

A loop owns several definition namespaces: its iteration variables, every RegionArg.block_arg, and every RegionArg.result. Those identities must be pairwise disjoint. Otherwise different stages can assign incompatible meanings to one UUID: a UUID-keyed environment has only one slot, so binding either the iteration variable or the carried value overwrites the other and makes both reads observe the same value.

Parameters:

NameTypeDescription
opForOperation | ForItemsOperation | WhileOperationLoop operation whose region arguments should be validated.

Returns:

tuple[RegionArg, ...] — tuple[RegionArg, ...]: The validated op.region_args tuple.

Raises:


verify_circuit [source]

def verify_circuit(program: CircuitProgram) -> None

Verify wire linearity, regions, expressions, and slot bounds.

Parameters:

NameTypeDescription
programCircuitProgramImmutable circuit program to verify.

Raises:

Classes

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:

bool — True iff slice_of is non-None.

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

BinaryExpr [source]

class BinaryExpr(_ScalarOperators)

Apply a binary scalar operation.

Parameters:

NameTypeDescription
operatorBinaryOperatorOperation kind.
leftScalarExprLeft operand.
rightScalarExprRight operand.
Constructor
def __init__(self, operator: BinaryOperator, left: ScalarExpr, right: ScalarExpr) -> None
Attributes

BinaryOperator [source]

class BinaryOperator(enum.Enum)

Enumerate scalar operations preserved until target materialization.

Attributes

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.


CallInstruction [source]

class CallInstruction

Invoke a reusable circuit over versioned wires.

Parameters:

NameTypeDescription
calleeReusableCircuitReusable circuit and transforms.
inputstuple[WireId, ...]Consumed wire versions.
outputstuple[WireId, ...]Produced wire versions.
Constructor
def __init__(
    self,
    callee: ReusableCircuit,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
) -> None
Attributes

CallableIdentity [source]

class CallableIdentity

Preserve the semantic identity of a reusable circuit body.

Parameters:

NameTypeDescription
keySemanticOpKeyOpen semantic identity used by target-native realization registries.
symbolstrHuman-readable callable name used for diagnostics.
argumentsSemanticArgumentsImmutable arguments that define this invocation’s meaning. Defaults to no arguments.
Constructor
def __init__(
    self,
    key: SemanticOpKey,
    symbol: str,
    arguments: SemanticArguments = SemanticArguments(),
) -> None
Attributes

CircuitBuilder [source]

class CircuitBuilder

Build immutable circuit IR while assigning fresh wire versions.

Parameters:

NameTypeDescription
num_qubitsintNumber of virtual qubit slots.
num_clbitsintNumber of classical bit slots.
namestrCircuit name. Defaults to "main".
Constructor
def __init__(self, num_qubits: int, num_clbits: int, name: str = 'main') -> None

Initialize a circuit builder.

Parameters:

NameTypeDescription
num_qubitsintNumber of virtual qubit slots.
num_clbitsintNumber of classical bit slots.
namestrCircuit name. Defaults to "main".

Raises:

Attributes
Methods
add_global_phase
def add_global_phase(self, phase: ScalarExpr | bool | int | float) -> None

Accumulate a global phase in the current lexical region.

Parameters:

NameTypeDescription
phaseScalarExpr | bool | int | floatPhase contribution.
append_barrier
def append_barrier(self, qubits: tuple[int, ...]) -> None

Append a scheduling barrier without changing wire versions.

Parameters:

NameTypeDescription
qubitstuple[int, ...]Participating qubit slots.
append_call
def append_call(self, callee: ReusableCircuit, qubits: tuple[int, ...]) -> None

Append a reusable-circuit call and advance its wires.

Parameters:

NameTypeDescription
calleeReusableCircuitReusable circuit and transforms.
qubitstuple[int, ...]Participating qubit slots.
append_gate
def append_gate(
    self,
    kind: GateKind,
    qubits: tuple[int, ...],
    parameters: tuple[ScalarExpr, ...] = (),
) -> None

Append a primitive gate and advance all participating wires.

Parameters:

NameTypeDescription
kindGateKindPrimitive gate kind.
qubitstuple[int, ...]Participating qubit slots.
parameterstuple[ScalarExpr, ...]Gate parameters. Defaults to an empty tuple.
append_measure
def append_measure(self, qubit: int, clbit: int) -> None

Append a measurement.

Parameters:

NameTypeDescription
qubitintMeasured qubit slot.
clbitintDestination classical bit slot.

Raises:

append_measure_vector
def append_measure_vector(self, qubits: tuple[int, ...], clbits: tuple[int, ...]) -> None

Append one ordered vector measurement.

Parameters:

NameTypeDescription
qubitstuple[int, ...]Measured qubit slots in result order.
clbitstuple[int, ...]Destination classical slots.

Raises:

append_pauli_evolution
def append_pauli_evolution(
    self,
    qubits: tuple[int, ...],
    hamiltonian: Any,
    time: ScalarExpr | bool | int | float,
) -> None

Append an abstract Pauli evolution and advance its wires.

Parameters:

NameTypeDescription
qubitstuple[int, ...]Participating qubit slots.
hamiltonianAnyQamomile Hamiltonian value.
timeScalarExpr | bool | int | floatEvolution time.

Raises:

append_reset
def append_reset(self, qubit: int) -> None

Append reset and advance the affected wire.

Parameters:

NameTypeDescription
qubitintQubit slot to reset.
begin_else
def begin_else(self, context: _IfContext) -> None

Close a true region and open its false region.

Parameters:

NameTypeDescription
context_IfContextToken returned by :meth:begin_if.

Raises:

begin_for
def begin_for(self, indexset: range) -> LoopVariableExpr

Open a structured for-loop body.

Parameters:

NameTypeDescription
indexsetrangeConcrete iteration range.

Returns:

LoopVariableExpr — Induction expression available inside the body.

begin_if
def begin_if(self, condition: ScalarExpr) -> _IfContext

Open the true region of a structured conditional.

Parameters:

NameTypeDescription
conditionScalarExprRuntime branch predicate.

Returns:

_IfContext — Opaque builder token used to select the else branch.

begin_while
def begin_while(self, condition: ScalarExpr) -> _WhileContext

Open a structured while-loop body.

Parameters:

NameTypeDescription
conditionScalarExprRuntime loop predicate.

Returns:

_WhileContext — Opaque builder token used to close the loop.

current_wire
def current_wire(self, qubit: int) -> WireId

Return the current wire version for a qubit slot.

Parameters:

NameTypeDescription
qubitintPhysical slot index assigned by circuit lowering.

Returns:

WireId — Current version of the slot.

Raises:

end_for
def end_for(self) -> None

Close the innermost structured for-loop body.

Raises:

end_if
def end_if(self, context: _IfContext) -> None

Close a structured conditional and merge its wire states.

Parameters:

NameTypeDescription
context_IfContextToken returned by :meth:begin_if.

Raises:

end_while
def end_while(self, context: _WhileContext) -> None

Close a structured while-loop body.

Parameters:

NameTypeDescription
context_WhileContextToken returned by :meth:begin_while.

Raises:

freeze
def freeze(self) -> CircuitProgram

Finalize the root region into immutable circuit IR.

Returns:

CircuitProgram — Immutable circuit program.

Raises:

fresh_wire
def fresh_wire(self) -> WireId

Allocate a fresh module-local virtual wire version.

Returns:

WireId — Newly allocated wire identifier.

restore_state
def restore_state(self, snapshot: _CircuitBuilderSnapshot) -> None

Restore a checkpoint after an append-only emission attempt.

Parameters:

NameTypeDescription
snapshot_CircuitBuilderSnapshotCheckpoint returned by :meth:snapshot_state for this builder.

Raises:

snapshot_state
def snapshot_state(self) -> _CircuitBuilderSnapshot

Capture state that can be restored after declined emission.

Returns:

_CircuitBuilderSnapshot — Append-only builder checkpoint for the current structured region.


CircuitGateEmitter [source]

class CircuitGateEmitter

Emit primitive operations into engine-neutral circuit IR.

Attributes
Methods
append_gate
def append_gate(
    self,
    circuit: CircuitBuilder,
    gate: ReusableCircuit,
    qubits: list[int],
) -> None

Append a reusable circuit call.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
gateReusableCircuitReusable circuit value.
qubitslist[int]Participating slots.
circuit_to_gate
def circuit_to_gate(
    self,
    circuit: CircuitBuilder | CircuitProgram,
    name: str = 'U',
) -> ReusableCircuit

Freeze a circuit as a reusable circuit value.

Parameters:

NameTypeDescription
circuitCircuitBuilder | CircuitProgramCircuit body.
namestrReusable circuit name. Defaults to "U".

Returns:

ReusableCircuit — Reusable body without target-native state.

combine_symbolic
def combine_symbolic(
    self,
    kind: BinOpKind,
    lhs: ScalarExpr | bool | int | float,
    rhs: ScalarExpr | bool | int | float,
) -> BinaryExpr | None

Combine symbolic operands without creating engine expressions.

Parameters:

NameTypeDescription
kindBinOpKindQamomile arithmetic operation.
lhsScalarExpr | bool | int | floatLeft operand.
rhsScalarExpr | bool | int | floatRight operand.

Returns:

BinaryExpr | None — BinaryExpr | None: Target-neutral expression, or None for an unsupported operation kind.

create_circuit
def create_circuit(self, num_qubits: int, num_clbits: int) -> CircuitBuilder

Create an empty circuit IR builder.

Parameters:

NameTypeDescription
num_qubitsintNumber of virtual qubit slots.
num_clbitsintNumber of classical bit slots.

Returns:

CircuitBuilder — Empty engine-neutral builder.

create_parameter
def create_parameter(self, name: str) -> ParameterExpr

Create a target-neutral runtime parameter expression.

Parameters:

NameTypeDescription
namestrExternal parameter name.

Returns:

ParameterExpr — Parameter reference preserved until materialization.

emit_barrier
def emit_barrier(self, circuit: CircuitBuilder, qubits: list[int]) -> None

Emit a scheduling barrier.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitslist[int]Participating slots.
emit_ch
def emit_ch(self, circuit: CircuitBuilder, control: int, target: int) -> None

Emit a controlled-H gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
emit_cp
def emit_cp(
    self,
    circuit: CircuitBuilder,
    control: int,
    target: int,
    angle: ScalarExpr | float,
) -> None

Emit a controlled-phase rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
angleScalarExpr | floatPhase angle in radians.
emit_crx
def emit_crx(
    self,
    circuit: CircuitBuilder,
    control: int,
    target: int,
    angle: ScalarExpr | float,
) -> None

Emit a controlled-RX rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
angleScalarExpr | floatRotation angle in radians.
emit_cry
def emit_cry(
    self,
    circuit: CircuitBuilder,
    control: int,
    target: int,
    angle: ScalarExpr | float,
) -> None

Emit a controlled-RY rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
angleScalarExpr | floatRotation angle in radians.
emit_crz
def emit_crz(
    self,
    circuit: CircuitBuilder,
    control: int,
    target: int,
    angle: ScalarExpr | float,
) -> None

Emit a controlled-RZ rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
angleScalarExpr | floatRotation angle in radians.
emit_cx
def emit_cx(self, circuit: CircuitBuilder, control: int, target: int) -> None

Emit a controlled-X gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
emit_cy
def emit_cy(self, circuit: CircuitBuilder, control: int, target: int) -> None

Emit a controlled-Y gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
emit_cz
def emit_cz(self, circuit: CircuitBuilder, control: int, target: int) -> None

Emit a controlled-Z gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
controlintControl slot.
targetintTarget slot.
emit_else_start
def emit_else_start(self, circuit: CircuitBuilder, context: Any) -> None

Switch an open conditional to its false branch.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
contextAnyOpaque conditional context.
emit_for_loop_end
def emit_for_loop_end(self, circuit: CircuitBuilder, context: Any) -> None

Close a structured for-loop body.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
contextAnyInduction expression returned at loop start.
emit_for_loop_start
def emit_for_loop_start(self, circuit: CircuitBuilder, indexset: range) -> ScalarExpr

Open a structured for-loop body.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
indexsetrangeConcrete iteration range.

Returns:

ScalarExpr — Target-neutral induction expression.

emit_global_phase
def emit_global_phase(self, circuit: CircuitBuilder, angle: ScalarExpr | float) -> None

Accumulate a phase in the builder’s current lexical region.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
angleScalarExpr | floatPhase angle in radians.
emit_h
def emit_h(self, circuit: CircuitBuilder, qubit: int) -> None

Emit a Hadamard gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_if_end
def emit_if_end(self, circuit: CircuitBuilder, context: Any) -> None

Close a structured conditional.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
contextAnyOpaque conditional context.
emit_if_start
def emit_if_start(self, circuit: CircuitBuilder, clbit: int, value: int = 1) -> Any

Open a structured conditional true branch.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
clbitintPredicate classical bit slot.
valueintRequired bit value. Defaults to one.

Returns:

Any — Opaque conditional builder context.

emit_measure
def emit_measure(self, circuit: CircuitBuilder, qubit: int, clbit: int) -> None

Emit a measurement into a classical slot.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintMeasured qubit slot.
clbitintDestination classical slot.
emit_measure_vector
def emit_measure_vector(
    self,
    circuit: CircuitBuilder,
    qubits: tuple[int, ...],
    clbits: tuple[int, ...],
) -> None

Preserve an ordered vector measurement as one instruction.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitstuple[int, ...]Measured qubit slots in result order.
clbitstuple[int, ...]Destination classical slots.
emit_p
def emit_p(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> None

Emit a phase rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
angleScalarExpr | floatPhase angle in radians.
emit_reset
def emit_reset(self, circuit: CircuitBuilder, qubit: int) -> None

Emit a reset-to-zero operation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintReset qubit slot.
emit_rx
def emit_rx(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> None

Emit an RX rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
angleScalarExpr | floatRotation angle in radians.
emit_ry
def emit_ry(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> None

Emit an RY rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
angleScalarExpr | floatRotation angle in radians.
emit_rz
def emit_rz(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> None

Emit an RZ rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
angleScalarExpr | floatRotation angle in radians.
emit_rzz
def emit_rzz(
    self,
    circuit: CircuitBuilder,
    qubit1: int,
    qubit2: int,
    angle: ScalarExpr | float,
) -> None

Emit an RZZ rotation.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubit1intFirst slot.
qubit2intSecond slot.
angleScalarExpr | floatRotation angle in radians.
emit_s
def emit_s(self, circuit: CircuitBuilder, qubit: int) -> None

Emit an S gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_sdg
def emit_sdg(self, circuit: CircuitBuilder, qubit: int) -> None

Emit an inverse-S gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_swap
def emit_swap(self, circuit: CircuitBuilder, qubit1: int, qubit2: int) -> None

Emit a SWAP gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubit1intFirst slot.
qubit2intSecond slot.
emit_t
def emit_t(self, circuit: CircuitBuilder, qubit: int) -> None

Emit a T gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_tdg
def emit_tdg(self, circuit: CircuitBuilder, qubit: int) -> None

Emit an inverse-T gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_toffoli
def emit_toffoli(
    self,
    circuit: CircuitBuilder,
    control1: int,
    control2: int,
    target: int,
) -> None

Emit a Toffoli gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
control1intFirst control slot.
control2intSecond control slot.
targetintTarget slot.
emit_while_end
def emit_while_end(self, circuit: CircuitBuilder, context: Any) -> None

Close a structured while-loop body.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
contextAnyOpaque while-loop context.
emit_while_start
def emit_while_start(self, circuit: CircuitBuilder, clbit: int, value: int = 1) -> Any

Open a structured while-loop body.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
clbitintPredicate classical bit slot.
valueintRequired bit value. Defaults to one.

Returns:

Any — Opaque while-loop builder context.

emit_x
def emit_x(self, circuit: CircuitBuilder, qubit: int) -> None

Emit a Pauli-X gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_y
def emit_y(self, circuit: CircuitBuilder, qubit: int) -> None

Emit a Pauli-Y gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
emit_z
def emit_z(self, circuit: CircuitBuilder, qubit: int) -> None

Emit a Pauli-Z gate.

Parameters:

NameTypeDescription
circuitCircuitBuilderDestination builder.
qubitintTarget slot.
gate_controlled
def gate_controlled(self, gate: ReusableCircuit, num_controls: int) -> ReusableCircuit

Add control wires to a reusable circuit.

Parameters:

NameTypeDescription
gateReusableCircuitReusable circuit value.
num_controlsintNumber of controls to add.

Returns:

ReusableCircuit — Controlled reusable circuit.

gate_inverse
def gate_inverse(self, gate: ReusableCircuit) -> ReusableCircuit

Toggle the inverse transform on a reusable circuit.

Parameters:

NameTypeDescription
gateReusableCircuitReusable circuit value.

Returns:

ReusableCircuit — Inverse reusable circuit.

gate_power
def gate_power(self, gate: ReusableCircuit, power: int) -> ReusableCircuit

Apply an integral power transform to a reusable circuit.

Parameters:

NameTypeDescription
gateReusableCircuitReusable circuit value.
powerintIntegral repetition count.

Returns:

ReusableCircuit — Transformed reusable circuit.

supports_for_loop
def supports_for_loop(self) -> bool

Report support for structured for loops.

Returns:

bool — Always True for circuit IR.

supports_gate_inverse
def supports_gate_inverse(self) -> bool

Report support for deferred inverse transforms.

Returns:

bool — Always True for circuit IR.

supports_if_else
def supports_if_else(self) -> bool

Report support for structured conditionals.

Returns:

bool — Always True for circuit IR.

supports_reusable_gates
def supports_reusable_gates(self) -> bool

Report support for deferred reusable circuit calls.

Returns:

bool — Always True because :class:ReusableCircuit carries a target-neutral body and transforms until legalization or materialization.

supports_while_loop
def supports_while_loop(self) -> bool

Report support for structured while loops.

Returns:

bool — Always True for circuit IR.


CircuitLoweringPass [source]

class CircuitLoweringPass(StandardEmitPass[CircuitBuilder])

Lower a segmented circuit program into target-neutral builders.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneCompile-time parameter bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.
Constructor
def __init__(
    self,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> None

Initialize circuit-IR lowering.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneCompile-time parameter bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.
Methods
run
def run(self, input: ProgramPlan) -> ExecutableProgram[CircuitBuilder]

Lower one program plan with a fresh SELECT case cache.

Parameters:

NameTypeDescription
inputProgramPlanSegmented program plan to lower.

Returns:

ExecutableProgram[CircuitBuilder] — ExecutableProgram[CircuitBuilder]: Lowered executable builders.


CircuitProgram [source]

class CircuitProgram

Store one immutable engine-neutral circuit program.

Parameters:

NameTypeDescription
namestrCircuit entrypoint name.
num_qubitsintNumber of virtual input qubit slots.
num_clbitsintNumber of classical bit slots.
input_wirestuple[WireId, ...]Initial wire version per qubit slot.
output_wirestuple[WireId, ...]Final wire version per qubit slot.
operationstuple[CircuitInstruction, ...]Structured instruction sequence.
global_phaseScalarExprPhase accumulated in the root lexical region, in radians. Dynamic control-flow regions retain their own scoped phases. Defaults to zero and becomes observable when the program is controlled.
Constructor
def __init__(
    self,
    name: str,
    num_qubits: int,
    num_clbits: int,
    input_wires: tuple[WireId, ...],
    output_wires: tuple[WireId, ...],
    operations: tuple[CircuitInstruction, ...],
    global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

ClassicalBitExpr [source]

class ClassicalBitExpr(_ScalarOperators)

Reference a measured classical bit.

Parameters:

NameTypeDescription
indexintCircuit-local classical bit index.
Constructor
def __init__(self, index: int) -> None
Attributes

CompOp [source]

class CompOp(BinaryOperationBase)

Comparison operation (EQ, NEQ, LT, LE, GT, GE).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CompOpKind | None = None,
) -> None
Attributes

CompOpKind [source]

class CompOpKind(enum.Enum)
Attributes

CompiledQuantumSegment [source]

class CompiledQuantumSegment(Generic[T])

A quantum segment with emitted engine circuit.

Constructor
def __init__(
    self,
    segment: QuantumSegment,
    circuit: T,
    qubit_map: QubitMap = dict(),
    clbit_map: ClbitMap = dict(),
    measurement_qubit_map: dict[int, int] = dict(),
    parameter_metadata: ParameterMetadata = ParameterMetadata(),
    implicit_output_qubit_indices: tuple[int, ...] | None = None,
) -> None
Attributes

CompositeGateType [source]

class CompositeGateType(enum.Enum)

Classify standard boxed quantum callables.

Attributes

CondOp [source]

class CondOp(BinaryOperationBase)

Conditional logical operation (AND, OR).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CondOpKind | None = None,
) -> None
Attributes

CondOpKind [source]

class CondOpKind(enum.Enum)
Attributes

EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return
Constructor
def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

ExecutableProgram [source]

class ExecutableProgram(Generic[T])

A fully compiled program ready for execution.

Contains compiled quantum, classical, and expectation-value segments. Use sample() for multi-shot execution or run() for single execution.

Example:

executable = transpiler.compile(kernel)

# Sample: multiple shots, returns counts
job = executable.sample(executor, shots=1000)
result = job.result()  # SampleResult with counts

# Run: single shot, returns typed result
job = executable.run(executor)
result = job.result()  # Returns kernel's return type
Constructor
def __init__(
    self,
    plan: ProgramPlan | None = None,
    compiled_quantum: list[CompiledQuantumSegment[T]] = list(),
    compiled_classical: list[CompiledClassicalSegment] = list(),
    compiled_expval: list[CompiledExpvalSegment] = list(),
    output_values: list[ValueLike] = list(),
) -> None
Attributes
Methods
get_circuits
def get_circuits(self) -> list[T]

Get all quantum circuits in execution order.

get_first_circuit
def get_first_circuit(self) -> T | None

Get the first quantum circuit, or None if no quantum segments.

restore
def restore(
    self,
    executor: QuantumExecutor[T],
    snapshot: JobSnapshot,
    bindings: dict[str, Any] | None = None,
) -> SampleJob[Any] | RunJob[Any] | ExpvalJob

Restore saved executions with this program’s typed result ABI.

Snapshots retain provider identifiers, completed local raw values, and ordered execution groups. Legacy flat provider snapshots remain supported. Reuse the same compiled program and pass the original runtime bindings explicitly to reproduce classical pre- and post-processing. Credentials, arbitrary bindings, and Python callables are not saved. Restoration reconnects to remote jobs without resubmitting or waiting for results; local values need no provider restoration support.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine adapter configured with the provider credentials and target used by the original job.
snapshotJobSnapshotSnapshot returned by the original public job’s snapshot() method.
bindingsdict[str, Any] | NoneOriginal runtime parameter bindings. Defaults to None for parameter-free programs.

Returns:

SampleJob[Any] | RunJob[Any] | ExpvalJob — SampleJob[Any] | RunJob[Any] | ExpvalJob: Restored lazy job with the same typed public result conversion as a new execution.

Raises:

Example:

>>> original = executable.sample(executor, shots=1000)
>>> snapshot = original.snapshot()
>>> restored = executable.restore(executor, snapshot)
>>> restored.result()
run
def run(
    self,
    executor: QuantumExecutor[T],
    bindings: dict[str, Any] | None = None,
    *,
    estimation: EstimationAccuracy | None = None,
) -> RunJob[Any] | ExpvalJob

Submit one execution and return its lazy result job.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine-specific quantum executor.
bindingsdict[str, Any] | NoneParameter bindings. Supports three formats: - Vector: {“gammas”: [0.1, 0.2], “betas”: [0.3, 0.4]} - Dict parameter: {“coeffs”: {0: 0.1, (0, 1): 0.2}}, decomposed per key onto the emitted parameters - Indexed: {“gammas[0]”: 0.1, “coeffs[(0, 1)]”: 0.2}
estimationEstimationAccuracy | NoneOptional per-execution expectation accuracy policy. Defaults to the executor’s configured behavior.

Returns:

RunJob[Any] | ExpvalJob — RunJob[Any] | ExpvalJob: A RunJob that resolves to the kernel’s return type, or an ExpvalJob when the program contains an expectation-value computation.

Raises:

Example:

job = executable.run(executor, bindings={"gamma": [0.5]})
result = job.result()
print(result)  # 0.25 (for QFixed) or (0, 1) (for bits)
sample
def sample(
    self,
    executor: QuantumExecutor[T],
    shots: int = 1024,
    bindings: dict[str, Any] | None = None,
) -> SampleJob[Any]

Submit a multi-shot execution and return its lazy job.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine-specific quantum executor.
shotsintNumber of shots to run.
bindingsdict[str, Any] | NoneParameter bindings. Supports three formats: - Vector: {“gammas”: [0.1, 0.2], “betas”: [0.3, 0.4]} - Dict parameter: {“coeffs”: {0: 0.1, (0, 1): 0.2}}, decomposed per key onto the emitted parameters - Indexed: {“gammas[0]”: 0.1, “coeffs[(0, 1)]”: 0.2}

Returns:

SampleJob[Any] — SampleJob[Any]: A job that resolves to a SampleResult with the per-bitstring counts.

Raises:

Example:

job = executable.sample(executor, shots=1000, bindings={"gamma": [0.5]})
result = job.result()
print(result.results)  # [(0.25, 500), (0.75, 500)]

ForInstruction [source]

class ForInstruction

Repeat a structured circuit region over a concrete range.

Parameters:

NameTypeDescription
indexsetrangeConcrete iteration range.
loop_variableLoopVariableExprInduction expression used by the body.
inputstuple[WireId, ...]Wire versions entering the loop.
bodytuple[CircuitInstruction, ...]Single-iteration body.
body_outputstuple[WireId, ...]Body wire versions yielded to the next iteration.
outputstuple[WireId, ...]Wire versions after the loop.
Constructor
def __init__(
    self,
    indexset: range,
    loop_variable: LoopVariableExpr,
    inputs: tuple[WireId, ...],
    body: tuple[CircuitInstruction, ...],
    body_outputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
) -> None
Attributes

GateInstruction [source]

class GateInstruction

Apply one primitive gate to versioned virtual wires.

Parameters:

NameTypeDescription
kindGateKindPrimitive gate kind.
inputstuple[WireId, ...]Consumed wire versions.
outputstuple[WireId, ...]Produced wire versions.
parameterstuple[ScalarExpr, ...]Gate parameters.
Constructor
def __init__(
    self,
    kind: GateKind,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    parameters: tuple[ScalarExpr, ...] = (),
) -> None
Attributes

IfInstruction [source]

class IfInstruction

Select between two structured circuit regions.

Parameters:

NameTypeDescription
conditionScalarExprRuntime branch predicate.
inputstuple[WireId, ...]Wires entering both branches.
true_bodytuple[CircuitInstruction, ...]True branch body.
false_bodytuple[CircuitInstruction, ...]False branch body.
true_outputstuple[WireId, ...]Wires yielded by the true branch.
false_outputstuple[WireId, ...]Wires yielded by the false branch.
outputstuple[WireId, ...]Merged post-branch wires.
true_global_phaseScalarExprPhase applied only in the true branch.
false_global_phaseScalarExprPhase applied only in the false branch.
Constructor
def __init__(
    self,
    condition: ScalarExpr,
    inputs: tuple[WireId, ...],
    true_body: tuple[CircuitInstruction, ...],
    false_body: tuple[CircuitInstruction, ...],
    true_outputs: tuple[WireId, ...],
    false_outputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    true_global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
    false_global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.
Constructor
def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes
Methods
body_for_transform
def body_for_transform(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> tuple[Block | None, CallTransform]

Select a body and report the transform it already realizes.

A controlled-inverse invocation may reuse an explicitly registered inverse body when no implementation realizes both transforms. Keeping that fallback in the IR operation gives emitters and static analyses one selection rule while still letting each consumer apply the remaining coherent controls in its own representation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — tuple[Block | None, CallTransform]: Selected body and the transform CallTransform — already implemented by that body. The callable’s direct body is tuple[Block | None, CallTransform] — returned with DIRECT when no transform-specific body matches.

Raises:

effective_body
def effective_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — Block | None: Selected implementation body, or the callable’s Block | None — default body when no transform-specific implementation exists. Block | None — A compiler may synthesize inverse or controlled behavior from this Block | None — fallback body.

implementation_for
def implementation_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None, which only selects engine-generic implementations.
strategystr | NoneStrategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation candidate, CallableImplementation | None — or None when the callable definition has no match.

measurement_result_indices_for
def measurement_result_indices_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> frozenset[int]

Return measurement-derived results for one selected implementation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name used for implementation selection. Defaults to None.
strategystr | NoneStrategy name used for implementation selection. Defaults to the invocation’s strategy_name.

Returns:

frozenset[int] — frozenset[int]: Caller-local result positions derived from measurement in the selected body.

Raises:

select_body
def select_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> CallableBodySelection

Select and validate the composable body for this invocation.

The result carries the transform already realized by the body and the exact call-site values that bind to it. Consumers therefore cannot independently disagree about whether an invocation’s control prefix belongs to the selected implementation ABI.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

CallableBodySelection — Validated body, realized transform, and CallableBodySelection — aligned call-site operands and results.

Raises:


LiteralExpr [source]

class LiteralExpr(_ScalarOperators)

Represent a concrete scalar literal.

Parameters:

NameTypeDescription
valuebool | int | floatConcrete scalar value.
Constructor
def __init__(self, value: bool | int | float) -> None
Attributes

LoopVariableExpr [source]

class LoopVariableExpr(_ScalarOperators)

Reference the induction value of a structured loop.

Parameters:

NameTypeDescription
namestrCircuit-local loop variable name.
Constructor
def __init__(self, name: str) -> None
Attributes

NotOp [source]

class NotOp(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ParameterExpr [source]

class ParameterExpr(_ScalarOperators)

Reference a runtime circuit parameter.

Parameters:

NameTypeDescription
namestrStable external parameter name.
Constructor
def __init__(self, name: str) -> None
Attributes

PauliEvolutionInstruction [source]

class PauliEvolutionInstruction

Apply an abstract Hamiltonian evolution to selected wires.

Parameters:

NameTypeDescription
hamiltonianAnyImmutable Qamomile Hamiltonian value.
timeScalarExprEvolution time in radians.
inputstuple[WireId, ...]Consumed wire versions.
outputstuple[WireId, ...]Produced wire versions.
realizationPauliEvolutionRealizationTarget realization selected by legalization. Defaults to ABSTRACT during shared lowering.
Constructor
def __init__(
    self,
    hamiltonian: Any,
    time: ScalarExpr,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    realization: PauliEvolutionRealization = PauliEvolutionRealization.ABSTRACT,
) -> None
Attributes

PauliEvolveOp [source]

class PauliEvolveOp(Operation)

Pauli evolution operation: exp(-i * gamma * H).

This operation applies the time evolution of a Pauli Hamiltonian to a quantum register.

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ProgramPlan [source]

class ProgramPlan

Execution plan for a hybrid quantum/classical program.

Structure:

This plan enforces Qamomile’s current execution model: all quantum operations must be in a single quantum circuit.

Constructor
def __init__(
    self,
    steps: list[ProgramStep] = list(),
    abi: ProgramABI = ProgramABI(),
    boundaries: list[HybridBoundary] = list(),
    parameters: dict[str, Value] = dict(),
) -> None
Attributes

QubitAddress [source]

class QubitAddress

Typed key for qubit/clbit physical-index maps.

For scalar qubits: QubitAddress(uuid="abc123") For array elements: QubitAddress(uuid="abc123", element_index=2)

This replaces the f"{uuid}_{i}" string key pattern throughout the emit pipeline, making the key format explicit and preventing format-string bugs.

Constructor
def __init__(self, uuid: str, element_index: int | None = None) -> None
Attributes
Methods
from_composite_key
@classmethod
def from_composite_key(cls, key: str) -> QubitAddress

Parse a legacy composite key string into a QubitAddress.

The frontend stores qubit references as composite strings in the format "{array_uuid}_{element_index}" (e.g., cast operation qubit mappings, element UUIDs). This helper converts such strings to proper QubitAddress instances.

If the key does not match the composite format (i.e., the suffix after the last _ is not a non-negative integer), it is treated as a plain scalar UUID.

matches_array
def matches_array(self, array_uuid: str) -> bool

True if this address belongs to the given array.

with_element
def with_element(self, index: int) -> QubitAddress

Create an array-element address from this array’s base UUID.


ReusableCircuit [source]

class ReusableCircuit

Describe a reusable circuit body and requested transforms.

Parameters:

NameTypeDescription
bodyCircuitProgramReusable circuit body.
namestrDisplay and linkage name.
powerintIntegral repetition count. Defaults to one.
controlsintAdded control-wire count. Defaults to zero.
inverseboolWhether to apply the inverse body. Defaults to false.
identityCallableIdentity | NoneSemantic identity preserved for target legalization. None marks an anonymous body. Defaults to None.
native_realizationstr | NoneTarget-owned realization identifier selected during legalization. None keeps the reusable body as the fallback implementation. Defaults to None.
operand_widthstuple[int, ...]Flattened width of each semantic quantum operand before engine lowering. A vector contributes its element count and a scalar qubit contributes one. An empty tuple means the source boundary did not expose operand grouping.
Constructor
def __init__(
    self,
    body: CircuitProgram,
    name: str,
    power: int = 1,
    controls: int = 0,
    inverse: bool = False,
    identity: CallableIdentity | None = None,
    native_realization: str | None = None,
    operand_widths: tuple[int, ...] = (),
) -> None
Attributes

RuntimeClassicalExpr [source]

class RuntimeClassicalExpr(Operation)

A classical expression known to require runtime evaluation.

Lowered from CompOp / CondOp / NotOp / BinOp by ClassicalLoweringPass when the op’s operand dataflow traces back to a MeasureOperation (i.e. cannot be folded at compile-time, by emit-time loop unrolling, or by compile_time_if_lowering). Engine emit translates this 1:1 to an engine-native runtime expression (e.g. qiskit.circuit.classical.expr.Expr).

Operand convention:

The single-node + unified-kind shape (vs four parallel subclasses) keeps the engine dispatch a single match op.kind instead of four parallel hooks, and makes the IR self-documenting: a single RuntimeClassicalExpr instance signals “runtime evaluation required” regardless of which classical family it came from.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: RuntimeOpKind | None = None,
) -> None
Attributes

RuntimeOpKind [source]

class RuntimeOpKind(enum.Enum)

Unified kind for RuntimeClassicalExpr covering all classical op families that can appear at runtime.

The split between this enum and the per-family BinOpKind / CompOpKind / CondOpKind is intentional: compile-time-foldable classical ops keep their original IR types so the existing fold pipeline (constant_fold → compile_time_if_lowering → emit-time evaluate_classical_predicate) is undisturbed. Only ops identified as runtime-evaluation-only by ClassicalLoweringPass get rewritten to RuntimeClassicalExpr with a member of this enum.

Attributes

SelectOperation [source]

class SelectOperation(Operation)

Quantum multiplexer: apply case_blocks[i] when the index reads i.

Concrete operand layout: [idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...]. Symbolic-width operand layout: [idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...]. Results mirror the quantum operand grouping.

A concrete index register is normalized to one scalar Qubit operand per physical index qubit. A symbolic-width register instead retains each leading caller argument as one scalar or array operand until its bound shape is known. Whole-Vector[Qubit] / scalar targets follow and keep their shapes, and classical parameters shared across every case come last.

Index bit order is LSB-first: idx_0 is the least-significant bit, matching Qamomile’s qubit-zero convention. Case i is selected when index qubit j reads bit j of i. len(case_blocks) need not be a power of two; index values >= len(case_blocks) apply no operation (identity).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_index_qubits: int | Value = 0,
    case_blocks: list[Block] = list(),
    num_index_args: int = 0,
    case_callable_attrs: list[dict[str, Any]] = list(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Return every value consumed by the SELECT operation.

Returns:

list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width value when present.

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed replacement values.

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


SemanticArguments [source]

class SemanticArguments

Store immutable named arguments belonging to an operation’s meaning.

Parameters:

NameTypeDescription
entriestuple[tuple[str, SemanticValue], ...]Sorted name-value entries. Defaults to an empty tuple.
Constructor
def __init__(self, entries: tuple[tuple[str, SemanticValue], ...] = ()) -> None
Attributes
Methods
from_mapping
@classmethod
def from_mapping(cls, values: Mapping[str, Any] | None) -> 'SemanticArguments'

Freeze one mapping of semantic operation arguments.

Parameters:

NameTypeDescription
valuesMapping[str, Any] | NoneSerializer-friendly arguments, or None for no arguments.

Returns:

'SemanticArguments' — Immutable, deterministically ordered arguments.

Raises:

get
def get(self, name: str, default: SemanticValue = None) -> SemanticValue

Return one semantic argument by name.

Parameters:

NameTypeDescription
namestrArgument name.
defaultSemanticValueValue returned when absent. Defaults to None.

Returns:

SemanticValue — Stored value or default.

names
def names(self) -> frozenset[str]

Return all semantic argument names.

Returns:

frozenset[str] — frozenset[str]: Immutable set of argument names.


SemanticOpKey [source]

class SemanticOpKey

Identify an abstract operation independently of any engine.

The key is deliberately open rather than an enum. Standard-library, algorithm, provider, and user callables can therefore participate in native realization without modifying the compiler’s closed vocabulary.

Parameters:

NameTypeDescription
namespacestrStable owner namespace such as qamomile.stdlib.
namestrStable operation name within the namespace.
versionstrSemantic contract version. Defaults to "1".
variantstr | NoneOptional exact semantic variant, such as a decomposition strategy. Defaults to None.
Constructor
def __init__(
    self,
    namespace: str,
    name: str,
    version: str = '1',
    variant: str | None = None,
) -> None
Attributes

StandardEmitPass [source]

class StandardEmitPass(EmitPass[T], Generic[T])

Standard emit pass implementation using GateEmitter protocol.

This class provides orchestration for semantic IR traversal while delegating circuit instruction construction to a GateEmitter. The concrete compiler use is CircuitLoweringPass; SDK targets materialize its immutable result instead of subclassing this class.

Parameters:

NameTypeDescription
gate_emitterGateEmitter[T]Instruction builder used during the semantic traversal.
bindingsdict[str, Any] | NoneCompile-time parameter bindings.
parameterslist[str] | NoneParameter names preserved at runtime.
composite_emitterslist[CompositeGateEmitter[T]] | NoneOptional callable-preservation or lowering hooks.
engine_namestr | NoneDiagnostic name for the traversal target.
Constructor
def __init__(
    self,
    gate_emitter: GateEmitter[T],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
    composite_emitters: list[CompositeGateEmitter[T]] | None = None,
    engine_name: str | None = None,
)
Attributes

UnaryExpr [source]

class UnaryExpr(_ScalarOperators)

Apply a unary scalar operation.

Parameters:

NameTypeDescription
operatorUnaryOperatorOperation kind.
operandScalarExprInput expression.
Constructor
def __init__(self, operator: UnaryOperator, operand: ScalarExpr) -> None
Attributes

UnaryOperator [source]

class UnaryOperator(enum.Enum)

Enumerate unary scalar operations preserved for materialization.

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 engine resource allocation. This applies to every Value regardless of its type (Qubit, Float, Bit, ...) -- it is not specific to qubits.


WhileInstruction [source]

class WhileInstruction

Repeat a structured region while a runtime predicate is true.

Parameters:

NameTypeDescription
conditionScalarExprRuntime loop predicate.
inputstuple[WireId, ...]Wires entering the loop.
bodytuple[CircuitInstruction, ...]Loop body.
body_outputstuple[WireId, ...]Wires yielded to the next iteration.
outputstuple[WireId, ...]Wires available after loop termination.
body_global_phaseScalarExprPhase applied once per loop iteration.
Constructor
def __init__(
    self,
    condition: ScalarExpr,
    inputs: tuple[WireId, ...],
    body: tuple[CircuitInstruction, ...],
    body_outputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    body_global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

WhileOperation [source]

class WhileOperation(HasNestedOps, Operation)

Represents a while loop operation.

Only measurement-backed conditions are supported: the condition must be a Bit value produced by qmc.measure(). Non-measurement conditions (classical variables, constants, comparisons) are rejected by ValidateWhileContractPass before reaching engine emit.

Example::

bit = qmc.measure(q)
while bit:
    q = qmc.h(q)
    bit = qmc.measure(q)
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    operations: list[Operation] = list(),
    max_iterations: int | None = None,
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include rebind records and region args for cloning/substitution.

Same rationale as ForOperation.all_input_values: rebind records and region arguments reference body/pre-loop values by identity, so inline cloning must remap them in lockstep with body operands.

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus rebind-record and region-argument values.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the while body with explicit boundary values.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region whose block arguments and yields are aligned with region_args. The updated condition, when present, is appended as the final yield.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the while body and its complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt while operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, rebind-record, and region-arg values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


qamomile.circuit.transpiler.circuit_ir.materialize

Shared materialization boundary for circuit-family engine artifacts.

Overview

FunctionDescription
legalize_programRewrite one circuit program until it is legal for a target.
lower_circuit_planLower every quantum segment in a plan to immutable circuit IR.
materialize_executableMaterialize every quantum segment while preserving orchestration.
verify_circuitVerify wire linearity, regions, expressions, and slot bounds.
verify_target_legalProve a legalized program against declared target capabilities.
ClassDescription
CircuitCapabilitiesDeclare the complete circuit-IR language accepted by one target.
CircuitEngineEmitPassLower, legalize, verify, and materialize a circuit-family plan.
CircuitMaterializerConvert one target-legal circuit program to an engine artifact.
CircuitProgramStore one immutable engine-neutral circuit program.
CompilationPolicySelect preferred realizations among target-supported alternatives.
CompiledQuantumSegmentA quantum segment with emitted engine circuit.
EmitPassBase class for engine-specific emission passes.
ExecutableProgramA fully compiled program ready for execution.
MaterializedCircuitPackage a circuit artifact and engine-specific binding metadata.
ProgramPlanExecution plan for a hybrid quantum/classical program.

Constants

Functions

legalize_program [source]

def legalize_program(
    program: CircuitProgram,
    capabilities: CircuitCapabilities,
    policy: CompilationPolicy,
) -> CircuitProgram

Rewrite one circuit program until it is legal for a target.

Calls whose semantic key the target implements natively receive a target-owned realization identifier. Every other call retains its semantic identity and recursively legalized fallback body.

Parameters:

NameTypeDescription
programCircuitProgramVerified engine-neutral circuit program.
capabilitiesCircuitCapabilitiesDeclared target capabilities.
policyCompilationPolicyUser realization preferences.

Returns:

CircuitProgram — Rebuilt program with freshly numbered wires.


lower_circuit_plan [source]

def lower_circuit_plan(
    plan: ProgramPlan,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> ExecutableProgram[CircuitProgram]

Lower every quantum segment in a plan to immutable circuit IR.

Classical and expectation-value orchestration metadata remains in the returned executable container. Only engine-native quantum artifacts are replaced with verified :class:CircuitProgram objects.

Parameters:

NameTypeDescription
planProgramPlanCircuit-family C-to-Q-to-C execution plan.
bindingsdict[str, Any] | NoneCompile-time parameter bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.

Returns:

ExecutableProgram[CircuitProgram] — ExecutableProgram[CircuitProgram]: Execution structure containing immutable engine-neutral quantum programs.

Raises:


materialize_executable [source]

def materialize_executable(
    executable: ExecutableProgram[CircuitProgram],
    materializer: CircuitMaterializer[ArtifactT],
) -> ExecutableProgram[ArtifactT]

Materialize every quantum segment while preserving orchestration.

Parameters:

NameTypeDescription
executableExecutableProgram[CircuitProgram]Lowered circuit-family execution structure.
materializerCircuitMaterializer[ArtifactT]Engine materializer.

Returns:

ExecutableProgram[ArtifactT] — ExecutableProgram[ArtifactT]: Execution structure containing native engine circuits and unchanged ABI, classical, expectation-value, mapping, and parameter metadata.


verify_circuit [source]

def verify_circuit(program: CircuitProgram) -> None

Verify wire linearity, regions, expressions, and slot bounds.

Parameters:

NameTypeDescription
programCircuitProgramImmutable circuit program to verify.

Raises:


def verify_target_legal(program: CircuitProgram, capabilities: CircuitCapabilities) -> None

Prove a legalized program against declared target capabilities.

Parameters:

NameTypeDescription
programCircuitProgramLegalized circuit program, including every nested reusable-call body.
capabilitiesCircuitCapabilitiesDeclared target capabilities.

Raises:

Classes

CircuitCapabilities [source]

class CircuitCapabilities

Declare the complete circuit-IR language accepted by one target.

Parameters:

NameTypeDescription
namestrStable target name used in diagnostics.
primitive_gatesfrozenset[GateKind]Primitive gate kinds accepted by the target materializer.
native_semantic_opstuple[NativeSemanticOpCapabilities, ...]Native realizations keyed by open semantic operation identity.
gate_parametersScalarCapabilitiesScalar language accepted by gate parameters.
predicatesScalarCapabilitiesScalar language accepted by dynamic if and while predicates.
pauli_timeScalarCapabilitiesScalar language accepted by Pauli evolution time values.
global_phaseGlobalPhaseCapabilities | ScalarCapabilities | NoneExact standalone phase realization requirements, or None when unsupported. The former ScalarCapabilities value remains accepted and readable for source compatibility.
generic_callsCallTransformCapabilitiesReusable-call forms accepted after semantic-call legalization.
supports_dynamic_ifboolWhether runtime if regions are accepted.
supports_dynamic_whileboolWhether runtime while regions are accepted.
supports_resetboolWhether reset instructions are accepted.
pauli_realizationsfrozenset[PauliEvolutionRealization]Concrete Pauli-evolution realizations accepted by the materializer.
Constructor
def __init__(
    self,
    name: str,
    primitive_gates: frozenset[GateKind],
    native_semantic_ops: tuple[NativeSemanticOpCapabilities, ...],
    gate_parameters: ScalarCapabilities,
    predicates: ScalarCapabilities,
    pauli_time: ScalarCapabilities,
    global_phase: GlobalPhaseCapabilities | ScalarCapabilities | None,
    generic_calls: CallTransformCapabilities,
    supports_dynamic_if: bool,
    supports_dynamic_while: bool,
    supports_reset: bool,
    pauli_realizations: frozenset[PauliEvolutionRealization],
) -> None
Attributes
Methods
native_semantic_op
def native_semantic_op(self, key: SemanticOpKey) -> NativeSemanticOpCapabilities | None

Return the native declaration for one semantic operation.

Parameters:

NameTypeDescription
keySemanticOpKeySemantic operation key to look up.

Returns:

NativeSemanticOpCapabilities | None — NativeSemanticOpCapabilities | None: Matching declaration, or NativeSemanticOpCapabilities | None — None when the target has no native realization.


CircuitEngineEmitPass [source]

class CircuitEngineEmitPass(EmitPass[ArtifactT])

Lower, legalize, verify, and materialize a circuit-family plan.

The pass runs the three phases in order and never interleaves them: shared lowering produces engine-neutral circuit IR, target legalization rewrites it under the materializer’s declared capabilities and the compilation policy, target verification proves the result, and only then does the materializer convert it mechanically.

Parameters:

NameTypeDescription
materializerCircuitMaterializer[ArtifactT]Engine artifact materializer owning the target capability declaration.
bindingsdict[str, Any] | NoneCompile-time bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.
policyCompilationPolicy | NoneRealization preferences. Defaults to None, meaning :data:DEFAULT_POLICY.
Constructor
def __init__(
    self,
    materializer: CircuitMaterializer[ArtifactT],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
    policy: CompilationPolicy | None = None,
) -> None

Initialize a circuit-family lowering and materialization pass.

Parameters:

NameTypeDescription
materializerCircuitMaterializer[ArtifactT]Engine artifact materializer owning the target capability declaration.
bindingsdict[str, Any] | NoneCompile-time bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.
policyCompilationPolicy | NoneRealization preferences. Defaults to None, meaning :data:DEFAULT_POLICY.
Attributes
Methods
run
def run(self, input: ProgramPlan) -> ExecutableProgram[ArtifactT]

Lower, legalize, verify, and materialize every quantum segment.

Parameters:

NameTypeDescription
inputProgramPlanCircuit-family execution plan.

Returns:

ExecutableProgram[ArtifactT] — ExecutableProgram[ArtifactT]: Engine-native executable structure.

Raises:


CircuitMaterializer [source]

class CircuitMaterializer(Protocol[ArtifactT])

Convert one target-legal circuit program to an engine artifact.

A materializer owns two things: a declaration of what it accepts (:attr:capabilities) and a mechanical conversion of programs that verification has already proven against that declaration. Realization decisions (native semantic operation vs fallback body, decomposition choices) belong to legalization, never here.

Attributes
Methods
materialize
def materialize(self, program: CircuitProgram) -> MaterializedCircuit[ArtifactT]

Materialize one circuit program.

Parameters:

NameTypeDescription
programCircuitProgramTarget-legal circuit-family program.

Returns:

MaterializedCircuit[ArtifactT] — Artifact plus engine binding metadata.


CircuitProgram [source]

class CircuitProgram

Store one immutable engine-neutral circuit program.

Parameters:

NameTypeDescription
namestrCircuit entrypoint name.
num_qubitsintNumber of virtual input qubit slots.
num_clbitsintNumber of classical bit slots.
input_wirestuple[WireId, ...]Initial wire version per qubit slot.
output_wirestuple[WireId, ...]Final wire version per qubit slot.
operationstuple[CircuitInstruction, ...]Structured instruction sequence.
global_phaseScalarExprPhase accumulated in the root lexical region, in radians. Dynamic control-flow regions retain their own scoped phases. Defaults to zero and becomes observable when the program is controlled.
Constructor
def __init__(
    self,
    name: str,
    num_qubits: int,
    num_clbits: int,
    input_wires: tuple[WireId, ...],
    output_wires: tuple[WireId, ...],
    operations: tuple[CircuitInstruction, ...],
    global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

CompilationPolicy [source]

class CompilationPolicy

Select preferred realizations among target-supported alternatives.

Parameters:

NameTypeDescription
prefer_native_semantic_opsboolWhether legal target-native realizations are preferred over reusable fallback bodies. Defaults to True.
prefer_native_pauli_evolutionboolWhether native Pauli evolution is preferred over a gate gadget. Defaults to True.
Constructor
def __init__(
    self,
    prefer_native_semantic_ops: bool = True,
    prefer_native_pauli_evolution: bool = True,
) -> None
Attributes

CompiledQuantumSegment [source]

class CompiledQuantumSegment(Generic[T])

A quantum segment with emitted engine circuit.

Constructor
def __init__(
    self,
    segment: QuantumSegment,
    circuit: T,
    qubit_map: QubitMap = dict(),
    clbit_map: ClbitMap = dict(),
    measurement_qubit_map: dict[int, int] = dict(),
    parameter_metadata: ParameterMetadata = ParameterMetadata(),
    implicit_output_qubit_indices: tuple[int, ...] | None = None,
) -> None
Attributes

EmitPass [source]

class EmitPass(Pass[ProgramPlan, ExecutableProgram[T]], Generic[T])

Base class for engine-specific emission passes.

Subclasses implement _emit_quantum_segment() to generate engine-specific quantum circuits.

Input: ProgramPlan Output: ExecutableProgram with compiled segments

Constructor
def __init__(
    self,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
)

Initialize with optional parameter bindings.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneValues to bind parameters to. If not provided, parameters must be bound at execution time.
parameterslist[str] | NoneList of parameter names to preserve as engine parameters.

Raises:

Attributes
Methods
run
def run(self, input: ProgramPlan) -> ExecutableProgram[T]

Emit engine code from a program plan.

Parameters:

NameTypeDescription
inputProgramPlanSegmented plan whose quantum and classical steps should be compiled.

Returns:

ExecutableProgram[T] — ExecutableProgram[T]: Executable program containing all compiled segments and the public output contract.

Raises:


ExecutableProgram [source]

class ExecutableProgram(Generic[T])

A fully compiled program ready for execution.

Contains compiled quantum, classical, and expectation-value segments. Use sample() for multi-shot execution or run() for single execution.

Example:

executable = transpiler.compile(kernel)

# Sample: multiple shots, returns counts
job = executable.sample(executor, shots=1000)
result = job.result()  # SampleResult with counts

# Run: single shot, returns typed result
job = executable.run(executor)
result = job.result()  # Returns kernel's return type
Constructor
def __init__(
    self,
    plan: ProgramPlan | None = None,
    compiled_quantum: list[CompiledQuantumSegment[T]] = list(),
    compiled_classical: list[CompiledClassicalSegment] = list(),
    compiled_expval: list[CompiledExpvalSegment] = list(),
    output_values: list[ValueLike] = list(),
) -> None
Attributes
Methods
get_circuits
def get_circuits(self) -> list[T]

Get all quantum circuits in execution order.

get_first_circuit
def get_first_circuit(self) -> T | None

Get the first quantum circuit, or None if no quantum segments.

restore
def restore(
    self,
    executor: QuantumExecutor[T],
    snapshot: JobSnapshot,
    bindings: dict[str, Any] | None = None,
) -> SampleJob[Any] | RunJob[Any] | ExpvalJob

Restore saved executions with this program’s typed result ABI.

Snapshots retain provider identifiers, completed local raw values, and ordered execution groups. Legacy flat provider snapshots remain supported. Reuse the same compiled program and pass the original runtime bindings explicitly to reproduce classical pre- and post-processing. Credentials, arbitrary bindings, and Python callables are not saved. Restoration reconnects to remote jobs without resubmitting or waiting for results; local values need no provider restoration support.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine adapter configured with the provider credentials and target used by the original job.
snapshotJobSnapshotSnapshot returned by the original public job’s snapshot() method.
bindingsdict[str, Any] | NoneOriginal runtime parameter bindings. Defaults to None for parameter-free programs.

Returns:

SampleJob[Any] | RunJob[Any] | ExpvalJob — SampleJob[Any] | RunJob[Any] | ExpvalJob: Restored lazy job with the same typed public result conversion as a new execution.

Raises:

Example:

>>> original = executable.sample(executor, shots=1000)
>>> snapshot = original.snapshot()
>>> restored = executable.restore(executor, snapshot)
>>> restored.result()
run
def run(
    self,
    executor: QuantumExecutor[T],
    bindings: dict[str, Any] | None = None,
    *,
    estimation: EstimationAccuracy | None = None,
) -> RunJob[Any] | ExpvalJob

Submit one execution and return its lazy result job.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine-specific quantum executor.
bindingsdict[str, Any] | NoneParameter bindings. Supports three formats: - Vector: {“gammas”: [0.1, 0.2], “betas”: [0.3, 0.4]} - Dict parameter: {“coeffs”: {0: 0.1, (0, 1): 0.2}}, decomposed per key onto the emitted parameters - Indexed: {“gammas[0]”: 0.1, “coeffs[(0, 1)]”: 0.2}
estimationEstimationAccuracy | NoneOptional per-execution expectation accuracy policy. Defaults to the executor’s configured behavior.

Returns:

RunJob[Any] | ExpvalJob — RunJob[Any] | ExpvalJob: A RunJob that resolves to the kernel’s return type, or an ExpvalJob when the program contains an expectation-value computation.

Raises:

Example:

job = executable.run(executor, bindings={"gamma": [0.5]})
result = job.result()
print(result)  # 0.25 (for QFixed) or (0, 1) (for bits)
sample
def sample(
    self,
    executor: QuantumExecutor[T],
    shots: int = 1024,
    bindings: dict[str, Any] | None = None,
) -> SampleJob[Any]

Submit a multi-shot execution and return its lazy job.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine-specific quantum executor.
shotsintNumber of shots to run.
bindingsdict[str, Any] | NoneParameter bindings. Supports three formats: - Vector: {“gammas”: [0.1, 0.2], “betas”: [0.3, 0.4]} - Dict parameter: {“coeffs”: {0: 0.1, (0, 1): 0.2}}, decomposed per key onto the emitted parameters - Indexed: {“gammas[0]”: 0.1, “coeffs[(0, 1)]”: 0.2}

Returns:

SampleJob[Any] — SampleJob[Any]: A job that resolves to a SampleResult with the per-bitstring counts.

Raises:

Example:

job = executable.sample(executor, shots=1000, bindings={"gamma": [0.5]})
result = job.result()
print(result.results)  # [(0.25, 500), (0.75, 500)]

MaterializedCircuit [source]

class MaterializedCircuit(Generic[ArtifactT])

Package a circuit artifact and engine-specific binding metadata.

Parameters:

NameTypeDescription
artifactAnyEngine-native circuit object.
parametersMapping[str, Any]Engine parameters keyed by public parameter name.
measurement_qubit_mapMapping[int, int] | NoneStatic-measurement mapping from classical output slot to physical qubit slot. None preserves the lowering-provided mapping; an empty mapping is an explicit override.
parameter_ordertuple[str, ...] | NoneArtifact ABI order for positional parameters. None denotes name-based binding.
implicit_output_qubit_indicestuple[int, ...] | NonePhysical qubit indices exposed when a qkernel has no explicit return value. None preserves the executor’s full raw bitstring; an empty tuple explicitly exposes no qubits.
Constructor
def __init__(
    self,
    artifact: ArtifactT,
    parameters: Mapping[str, Any] = dict(),
    measurement_qubit_map: Mapping[int, int] | None = None,
    parameter_order: tuple[str, ...] | None = None,
    implicit_output_qubit_indices: tuple[int, ...] | None = None,
) -> None
Attributes

ProgramPlan [source]

class ProgramPlan

Execution plan for a hybrid quantum/classical program.

Structure:

This plan enforces Qamomile’s current execution model: all quantum operations must be in a single quantum circuit.

Constructor
def __init__(
    self,
    steps: list[ProgramStep] = list(),
    abi: ProgramABI = ProgramABI(),
    boundaries: list[HybridBoundary] = list(),
    parameters: dict[str, Value] = dict(),
) -> None
Attributes

qamomile.circuit.transpiler.circuit_ir.model

Immutable circuit IR nodes and the private mutable construction builder.

Overview

FunctionDescription
as_scalar_exprNormalize a Python scalar or existing expression.
has_mid_circuit_measurementReturn whether measured quantum state is consumed again in a region.
ClassDescription
BarrierInstructionSeparate scheduling regions without changing wire versions.
BinaryExprApply a binary scalar operation.
BinaryOperatorEnumerate scalar operations preserved until target materialization.
CallInstructionInvoke a reusable circuit over versioned wires.
CallableIdentityPreserve the semantic identity of a reusable circuit body.
CircuitBuilderBuild immutable circuit IR while assigning fresh wire versions.
CircuitProgramStore one immutable engine-neutral circuit program.
ClassicalBitExprReference a measured classical bit.
ForInstructionRepeat a structured circuit region over a concrete range.
GateInstructionApply one primitive gate to versioned virtual wires.
GateKindClassification of gates for emission.
IfInstructionSelect between two structured circuit regions.
LiteralExprRepresent a concrete scalar literal.
LoopVariableExprReference the induction value of a structured loop.
MeasureInstructionMeasure a wire into a classical bit.
MeasureVectorInstructionMeasure an ordered group of wires into classical bits.
ParameterExprReference a runtime circuit parameter.
PauliEvolutionInstructionApply an abstract Hamiltonian evolution to selected wires.
PauliEvolutionRealizationEnumerate legalization states for abstract Pauli evolution.
ResetInstructionReset a wire and produce a fresh zero-state wire.
ReusableCircuitDescribe a reusable circuit body and requested transforms.
SemanticArgumentsStore immutable named arguments belonging to an operation’s meaning.
SemanticOpKeyIdentify an abstract operation independently of any engine.
UnaryExprApply a unary scalar operation.
UnaryOperatorEnumerate unary scalar operations preserved for materialization.
WhileInstructionRepeat a structured region while a runtime predicate is true.
WireIdIdentify one version of a virtual quantum wire.

Constants

Functions

as_scalar_expr [source]

def as_scalar_expr(value: ScalarExpr | bool | int | float) -> ScalarExpr

Normalize a Python scalar or existing expression.

Parameters:

NameTypeDescription
valueScalarExpr | bool | int | floatValue to normalize.

Returns:

ScalarExpr — Existing expression or a new literal expression.


has_mid_circuit_measurement [source]

def has_mid_circuit_measurement(operations: tuple[CircuitInstruction, ...]) -> bool

Return whether measured quantum state is consumed again in a region.

Static-sampling engines may defer terminal measurements to the end of a shot, but doing so is incorrect when a later gate, reset, call, or control region consumes the post-measurement wire. The circuit IR uses versioned wires, so this scan can distinguish those two cases without engine SDK knowledge.

Parameters:

NameTypeDescription
operationstuple[CircuitInstruction, ...]Structured instruction region to inspect.

Returns:

bool — True when the region or a nested reusable/control-flow body contains a non-terminal measurement.

Classes

BarrierInstruction [source]

class BarrierInstruction

Separate scheduling regions without changing wire versions.

Parameters:

NameTypeDescription
wirestuple[WireId, ...]Wires participating in the barrier.
Constructor
def __init__(self, wires: tuple[WireId, ...]) -> None
Attributes

BinaryExpr [source]

class BinaryExpr(_ScalarOperators)

Apply a binary scalar operation.

Parameters:

NameTypeDescription
operatorBinaryOperatorOperation kind.
leftScalarExprLeft operand.
rightScalarExprRight operand.
Constructor
def __init__(self, operator: BinaryOperator, left: ScalarExpr, right: ScalarExpr) -> None
Attributes

BinaryOperator [source]

class BinaryOperator(enum.Enum)

Enumerate scalar operations preserved until target materialization.

Attributes

CallInstruction [source]

class CallInstruction

Invoke a reusable circuit over versioned wires.

Parameters:

NameTypeDescription
calleeReusableCircuitReusable circuit and transforms.
inputstuple[WireId, ...]Consumed wire versions.
outputstuple[WireId, ...]Produced wire versions.
Constructor
def __init__(
    self,
    callee: ReusableCircuit,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
) -> None
Attributes

CallableIdentity [source]

class CallableIdentity

Preserve the semantic identity of a reusable circuit body.

Parameters:

NameTypeDescription
keySemanticOpKeyOpen semantic identity used by target-native realization registries.
symbolstrHuman-readable callable name used for diagnostics.
argumentsSemanticArgumentsImmutable arguments that define this invocation’s meaning. Defaults to no arguments.
Constructor
def __init__(
    self,
    key: SemanticOpKey,
    symbol: str,
    arguments: SemanticArguments = SemanticArguments(),
) -> None
Attributes

CircuitBuilder [source]

class CircuitBuilder

Build immutable circuit IR while assigning fresh wire versions.

Parameters:

NameTypeDescription
num_qubitsintNumber of virtual qubit slots.
num_clbitsintNumber of classical bit slots.
namestrCircuit name. Defaults to "main".
Constructor
def __init__(self, num_qubits: int, num_clbits: int, name: str = 'main') -> None

Initialize a circuit builder.

Parameters:

NameTypeDescription
num_qubitsintNumber of virtual qubit slots.
num_clbitsintNumber of classical bit slots.
namestrCircuit name. Defaults to "main".

Raises:

Attributes
Methods
add_global_phase
def add_global_phase(self, phase: ScalarExpr | bool | int | float) -> None

Accumulate a global phase in the current lexical region.

Parameters:

NameTypeDescription
phaseScalarExpr | bool | int | floatPhase contribution.
append_barrier
def append_barrier(self, qubits: tuple[int, ...]) -> None

Append a scheduling barrier without changing wire versions.

Parameters:

NameTypeDescription
qubitstuple[int, ...]Participating qubit slots.
append_call
def append_call(self, callee: ReusableCircuit, qubits: tuple[int, ...]) -> None

Append a reusable-circuit call and advance its wires.

Parameters:

NameTypeDescription
calleeReusableCircuitReusable circuit and transforms.
qubitstuple[int, ...]Participating qubit slots.
append_gate
def append_gate(
    self,
    kind: GateKind,
    qubits: tuple[int, ...],
    parameters: tuple[ScalarExpr, ...] = (),
) -> None

Append a primitive gate and advance all participating wires.

Parameters:

NameTypeDescription
kindGateKindPrimitive gate kind.
qubitstuple[int, ...]Participating qubit slots.
parameterstuple[ScalarExpr, ...]Gate parameters. Defaults to an empty tuple.
append_measure
def append_measure(self, qubit: int, clbit: int) -> None

Append a measurement.

Parameters:

NameTypeDescription
qubitintMeasured qubit slot.
clbitintDestination classical bit slot.

Raises:

append_measure_vector
def append_measure_vector(self, qubits: tuple[int, ...], clbits: tuple[int, ...]) -> None

Append one ordered vector measurement.

Parameters:

NameTypeDescription
qubitstuple[int, ...]Measured qubit slots in result order.
clbitstuple[int, ...]Destination classical slots.

Raises:

append_pauli_evolution
def append_pauli_evolution(
    self,
    qubits: tuple[int, ...],
    hamiltonian: Any,
    time: ScalarExpr | bool | int | float,
) -> None

Append an abstract Pauli evolution and advance its wires.

Parameters:

NameTypeDescription
qubitstuple[int, ...]Participating qubit slots.
hamiltonianAnyQamomile Hamiltonian value.
timeScalarExpr | bool | int | floatEvolution time.

Raises:

append_reset
def append_reset(self, qubit: int) -> None

Append reset and advance the affected wire.

Parameters:

NameTypeDescription
qubitintQubit slot to reset.
begin_else
def begin_else(self, context: _IfContext) -> None

Close a true region and open its false region.

Parameters:

NameTypeDescription
context_IfContextToken returned by :meth:begin_if.

Raises:

begin_for
def begin_for(self, indexset: range) -> LoopVariableExpr

Open a structured for-loop body.

Parameters:

NameTypeDescription
indexsetrangeConcrete iteration range.

Returns:

LoopVariableExpr — Induction expression available inside the body.

begin_if
def begin_if(self, condition: ScalarExpr) -> _IfContext

Open the true region of a structured conditional.

Parameters:

NameTypeDescription
conditionScalarExprRuntime branch predicate.

Returns:

_IfContext — Opaque builder token used to select the else branch.

begin_while
def begin_while(self, condition: ScalarExpr) -> _WhileContext

Open a structured while-loop body.

Parameters:

NameTypeDescription
conditionScalarExprRuntime loop predicate.

Returns:

_WhileContext — Opaque builder token used to close the loop.

current_wire
def current_wire(self, qubit: int) -> WireId

Return the current wire version for a qubit slot.

Parameters:

NameTypeDescription
qubitintPhysical slot index assigned by circuit lowering.

Returns:

WireId — Current version of the slot.

Raises:

end_for
def end_for(self) -> None

Close the innermost structured for-loop body.

Raises:

end_if
def end_if(self, context: _IfContext) -> None

Close a structured conditional and merge its wire states.

Parameters:

NameTypeDescription
context_IfContextToken returned by :meth:begin_if.

Raises:

end_while
def end_while(self, context: _WhileContext) -> None

Close a structured while-loop body.

Parameters:

NameTypeDescription
context_WhileContextToken returned by :meth:begin_while.

Raises:

freeze
def freeze(self) -> CircuitProgram

Finalize the root region into immutable circuit IR.

Returns:

CircuitProgram — Immutable circuit program.

Raises:

fresh_wire
def fresh_wire(self) -> WireId

Allocate a fresh module-local virtual wire version.

Returns:

WireId — Newly allocated wire identifier.

restore_state
def restore_state(self, snapshot: _CircuitBuilderSnapshot) -> None

Restore a checkpoint after an append-only emission attempt.

Parameters:

NameTypeDescription
snapshot_CircuitBuilderSnapshotCheckpoint returned by :meth:snapshot_state for this builder.

Raises:

snapshot_state
def snapshot_state(self) -> _CircuitBuilderSnapshot

Capture state that can be restored after declined emission.

Returns:

_CircuitBuilderSnapshot — Append-only builder checkpoint for the current structured region.


CircuitProgram [source]

class CircuitProgram

Store one immutable engine-neutral circuit program.

Parameters:

NameTypeDescription
namestrCircuit entrypoint name.
num_qubitsintNumber of virtual input qubit slots.
num_clbitsintNumber of classical bit slots.
input_wirestuple[WireId, ...]Initial wire version per qubit slot.
output_wirestuple[WireId, ...]Final wire version per qubit slot.
operationstuple[CircuitInstruction, ...]Structured instruction sequence.
global_phaseScalarExprPhase accumulated in the root lexical region, in radians. Dynamic control-flow regions retain their own scoped phases. Defaults to zero and becomes observable when the program is controlled.
Constructor
def __init__(
    self,
    name: str,
    num_qubits: int,
    num_clbits: int,
    input_wires: tuple[WireId, ...],
    output_wires: tuple[WireId, ...],
    operations: tuple[CircuitInstruction, ...],
    global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

ClassicalBitExpr [source]

class ClassicalBitExpr(_ScalarOperators)

Reference a measured classical bit.

Parameters:

NameTypeDescription
indexintCircuit-local classical bit index.
Constructor
def __init__(self, index: int) -> None
Attributes

ForInstruction [source]

class ForInstruction

Repeat a structured circuit region over a concrete range.

Parameters:

NameTypeDescription
indexsetrangeConcrete iteration range.
loop_variableLoopVariableExprInduction expression used by the body.
inputstuple[WireId, ...]Wire versions entering the loop.
bodytuple[CircuitInstruction, ...]Single-iteration body.
body_outputstuple[WireId, ...]Body wire versions yielded to the next iteration.
outputstuple[WireId, ...]Wire versions after the loop.
Constructor
def __init__(
    self,
    indexset: range,
    loop_variable: LoopVariableExpr,
    inputs: tuple[WireId, ...],
    body: tuple[CircuitInstruction, ...],
    body_outputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
) -> None
Attributes

GateInstruction [source]

class GateInstruction

Apply one primitive gate to versioned virtual wires.

Parameters:

NameTypeDescription
kindGateKindPrimitive gate kind.
inputstuple[WireId, ...]Consumed wire versions.
outputstuple[WireId, ...]Produced wire versions.
parameterstuple[ScalarExpr, ...]Gate parameters.
Constructor
def __init__(
    self,
    kind: GateKind,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    parameters: tuple[ScalarExpr, ...] = (),
) -> None
Attributes

GateKind [source]

class GateKind(Enum)

Classification of gates for emission.

Attributes

IfInstruction [source]

class IfInstruction

Select between two structured circuit regions.

Parameters:

NameTypeDescription
conditionScalarExprRuntime branch predicate.
inputstuple[WireId, ...]Wires entering both branches.
true_bodytuple[CircuitInstruction, ...]True branch body.
false_bodytuple[CircuitInstruction, ...]False branch body.
true_outputstuple[WireId, ...]Wires yielded by the true branch.
false_outputstuple[WireId, ...]Wires yielded by the false branch.
outputstuple[WireId, ...]Merged post-branch wires.
true_global_phaseScalarExprPhase applied only in the true branch.
false_global_phaseScalarExprPhase applied only in the false branch.
Constructor
def __init__(
    self,
    condition: ScalarExpr,
    inputs: tuple[WireId, ...],
    true_body: tuple[CircuitInstruction, ...],
    false_body: tuple[CircuitInstruction, ...],
    true_outputs: tuple[WireId, ...],
    false_outputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    true_global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
    false_global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

LiteralExpr [source]

class LiteralExpr(_ScalarOperators)

Represent a concrete scalar literal.

Parameters:

NameTypeDescription
valuebool | int | floatConcrete scalar value.
Constructor
def __init__(self, value: bool | int | float) -> None
Attributes

LoopVariableExpr [source]

class LoopVariableExpr(_ScalarOperators)

Reference the induction value of a structured loop.

Parameters:

NameTypeDescription
namestrCircuit-local loop variable name.
Constructor
def __init__(self, name: str) -> None
Attributes

MeasureInstruction [source]

class MeasureInstruction

Measure a wire into a classical bit.

Parameters:

NameTypeDescription
inputWireIdMeasured wire version.
outputWireIdPost-measurement wire version.
clbitintDestination classical bit index.
Constructor
def __init__(self, input: WireId, output: WireId, clbit: int) -> None
Attributes

MeasureVectorInstruction [source]

class MeasureVectorInstruction

Measure an ordered group of wires into classical bits.

This instruction preserves vector measurement as one semantic operation until target materialization. An engine with a vector measurement primitive can consume it directly; scalar-only engines expand it at their own boundary.

Parameters:

NameTypeDescription
inputstuple[WireId, ...]Measured wire versions in result order.
outputstuple[WireId, ...]Post-measurement wire versions.
clbitstuple[int, ...]Destination classical bits in result order.
Constructor
def __init__(
    self,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    clbits: tuple[int, ...],
) -> None
Attributes

ParameterExpr [source]

class ParameterExpr(_ScalarOperators)

Reference a runtime circuit parameter.

Parameters:

NameTypeDescription
namestrStable external parameter name.
Constructor
def __init__(self, name: str) -> None
Attributes

PauliEvolutionInstruction [source]

class PauliEvolutionInstruction

Apply an abstract Hamiltonian evolution to selected wires.

Parameters:

NameTypeDescription
hamiltonianAnyImmutable Qamomile Hamiltonian value.
timeScalarExprEvolution time in radians.
inputstuple[WireId, ...]Consumed wire versions.
outputstuple[WireId, ...]Produced wire versions.
realizationPauliEvolutionRealizationTarget realization selected by legalization. Defaults to ABSTRACT during shared lowering.
Constructor
def __init__(
    self,
    hamiltonian: Any,
    time: ScalarExpr,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    realization: PauliEvolutionRealization = PauliEvolutionRealization.ABSTRACT,
) -> None
Attributes

PauliEvolutionRealization [source]

class PauliEvolutionRealization(enum.Enum)

Enumerate legalization states for abstract Pauli evolution.

Attributes

ResetInstruction [source]

class ResetInstruction

Reset a wire and produce a fresh zero-state wire.

Parameters:

NameTypeDescription
inputWireIdWire version before reset.
outputWireIdFresh wire version after reset.
Constructor
def __init__(self, input: WireId, output: WireId) -> None
Attributes

ReusableCircuit [source]

class ReusableCircuit

Describe a reusable circuit body and requested transforms.

Parameters:

NameTypeDescription
bodyCircuitProgramReusable circuit body.
namestrDisplay and linkage name.
powerintIntegral repetition count. Defaults to one.
controlsintAdded control-wire count. Defaults to zero.
inverseboolWhether to apply the inverse body. Defaults to false.
identityCallableIdentity | NoneSemantic identity preserved for target legalization. None marks an anonymous body. Defaults to None.
native_realizationstr | NoneTarget-owned realization identifier selected during legalization. None keeps the reusable body as the fallback implementation. Defaults to None.
operand_widthstuple[int, ...]Flattened width of each semantic quantum operand before engine lowering. A vector contributes its element count and a scalar qubit contributes one. An empty tuple means the source boundary did not expose operand grouping.
Constructor
def __init__(
    self,
    body: CircuitProgram,
    name: str,
    power: int = 1,
    controls: int = 0,
    inverse: bool = False,
    identity: CallableIdentity | None = None,
    native_realization: str | None = None,
    operand_widths: tuple[int, ...] = (),
) -> None
Attributes

SemanticArguments [source]

class SemanticArguments

Store immutable named arguments belonging to an operation’s meaning.

Parameters:

NameTypeDescription
entriestuple[tuple[str, SemanticValue], ...]Sorted name-value entries. Defaults to an empty tuple.
Constructor
def __init__(self, entries: tuple[tuple[str, SemanticValue], ...] = ()) -> None
Attributes
Methods
from_mapping
@classmethod
def from_mapping(cls, values: Mapping[str, Any] | None) -> 'SemanticArguments'

Freeze one mapping of semantic operation arguments.

Parameters:

NameTypeDescription
valuesMapping[str, Any] | NoneSerializer-friendly arguments, or None for no arguments.

Returns:

'SemanticArguments' — Immutable, deterministically ordered arguments.

Raises:

get
def get(self, name: str, default: SemanticValue = None) -> SemanticValue

Return one semantic argument by name.

Parameters:

NameTypeDescription
namestrArgument name.
defaultSemanticValueValue returned when absent. Defaults to None.

Returns:

SemanticValue — Stored value or default.

names
def names(self) -> frozenset[str]

Return all semantic argument names.

Returns:

frozenset[str] — frozenset[str]: Immutable set of argument names.


SemanticOpKey [source]

class SemanticOpKey

Identify an abstract operation independently of any engine.

The key is deliberately open rather than an enum. Standard-library, algorithm, provider, and user callables can therefore participate in native realization without modifying the compiler’s closed vocabulary.

Parameters:

NameTypeDescription
namespacestrStable owner namespace such as qamomile.stdlib.
namestrStable operation name within the namespace.
versionstrSemantic contract version. Defaults to "1".
variantstr | NoneOptional exact semantic variant, such as a decomposition strategy. Defaults to None.
Constructor
def __init__(
    self,
    namespace: str,
    name: str,
    version: str = '1',
    variant: str | None = None,
) -> None
Attributes

UnaryExpr [source]

class UnaryExpr(_ScalarOperators)

Apply a unary scalar operation.

Parameters:

NameTypeDescription
operatorUnaryOperatorOperation kind.
operandScalarExprInput expression.
Constructor
def __init__(self, operator: UnaryOperator, operand: ScalarExpr) -> None
Attributes

UnaryOperator [source]

class UnaryOperator(enum.Enum)

Enumerate unary scalar operations preserved for materialization.

Attributes

WhileInstruction [source]

class WhileInstruction

Repeat a structured region while a runtime predicate is true.

Parameters:

NameTypeDescription
conditionScalarExprRuntime loop predicate.
inputstuple[WireId, ...]Wires entering the loop.
bodytuple[CircuitInstruction, ...]Loop body.
body_outputstuple[WireId, ...]Wires yielded to the next iteration.
outputstuple[WireId, ...]Wires available after loop termination.
body_global_phaseScalarExprPhase applied once per loop iteration.
Constructor
def __init__(
    self,
    condition: ScalarExpr,
    inputs: tuple[WireId, ...],
    body: tuple[CircuitInstruction, ...],
    body_outputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    body_global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

WireId [source]

class WireId

Identify one version of a virtual quantum wire.

Parameters:

NameTypeDescription
valueintNon-negative module-local wire number.
Constructor
def __init__(self, value: int) -> None
Attributes

qamomile.circuit.transpiler.circuit_ir.parameter_usage

Reconcile runtime parameter metadata with immutable circuit IR usage.

Overview

FunctionDescription
collect_program_parameter_namesCollect runtime parameter names used by one complete circuit program.
collect_scalar_parameter_namesCollect runtime parameter names from one scalar expression.
reconcile_parameter_metadataFilter provisional runtime metadata to parameters used by CircuitIR.
ClassDescription
BarrierInstructionSeparate scheduling regions without changing wire versions.
BinaryExprApply a binary scalar operation.
CallInstructionInvoke a reusable circuit over versioned wires.
CircuitProgramStore one immutable engine-neutral circuit program.
ClassicalBitExprReference a measured classical bit.
EmitErrorReport an engine failure to emit one semantic operation.
ForInstructionRepeat a structured circuit region over a concrete range.
GateInstructionApply one primitive gate to versioned virtual wires.
IfInstructionSelect between two structured circuit regions.
LiteralExprRepresent a concrete scalar literal.
LoopVariableExprReference the induction value of a structured loop.
MeasureInstructionMeasure a wire into a classical bit.
MeasureVectorInstructionMeasure an ordered group of wires into classical bits.
ParameterExprReference a runtime circuit parameter.
ParameterMetadataDescribe every scalar slot and runtime array in a compiled segment.
PauliEvolutionInstructionApply an abstract Hamiltonian evolution to selected wires.
ResetInstructionReset a wire and produce a fresh zero-state wire.
UnaryExprApply a unary scalar operation.
WhileInstructionRepeat a structured region while a runtime predicate is true.

Constants

Functions

collect_program_parameter_names [source]

def collect_program_parameter_names(program: CircuitProgram) -> set[str]

Collect runtime parameter names used by one complete circuit program.

Shared reusable bodies are scanned once. An active-call guard rejects a malformed cyclic reusable-call graph instead of recursing indefinitely.

Parameters:

NameTypeDescription
programCircuitProgramImmutable circuit program to inspect.

Returns:

set[str] — set[str]: Names referenced anywhere in the program or nested bodies.

Raises:


collect_scalar_parameter_names [source]

def collect_scalar_parameter_names(expression: ScalarExpr) -> set[str]

Collect runtime parameter names from one scalar expression.

Parameters:

NameTypeDescription
expressionScalarExprClosed CircuitIR scalar expression to inspect.

Returns:

set[str] — set[str]: Names referenced by the expression.

Raises:


reconcile_parameter_metadata [source]

def reconcile_parameter_metadata(program: CircuitProgram, metadata: ParameterMetadata) -> ParameterMetadata

Filter provisional runtime metadata to parameters used by CircuitIR.

Lowering may resolve formal runtime arguments before it knows whether the callee body uses them. The immutable circuit program is the authoritative record of actual use, while the provisional metadata retains ABI ordering, source references, container kinds, and engine parameter placeholders.

Parameters:

NameTypeDescription
programCircuitProgramVerified immutable circuit program.
metadataParameterMetadataProvisional segment parameter metadata.

Returns:

ParameterMetadata — Metadata containing exactly the used parameter slots, in their original ABI order.

Raises:

Classes

BarrierInstruction [source]

class BarrierInstruction

Separate scheduling regions without changing wire versions.

Parameters:

NameTypeDescription
wirestuple[WireId, ...]Wires participating in the barrier.
Constructor
def __init__(self, wires: tuple[WireId, ...]) -> None
Attributes

BinaryExpr [source]

class BinaryExpr(_ScalarOperators)

Apply a binary scalar operation.

Parameters:

NameTypeDescription
operatorBinaryOperatorOperation kind.
leftScalarExprLeft operand.
rightScalarExprRight operand.
Constructor
def __init__(self, operator: BinaryOperator, left: ScalarExpr, right: ScalarExpr) -> None
Attributes

CallInstruction [source]

class CallInstruction

Invoke a reusable circuit over versioned wires.

Parameters:

NameTypeDescription
calleeReusableCircuitReusable circuit and transforms.
inputstuple[WireId, ...]Consumed wire versions.
outputstuple[WireId, ...]Produced wire versions.
Constructor
def __init__(
    self,
    callee: ReusableCircuit,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
) -> None
Attributes

CircuitProgram [source]

class CircuitProgram

Store one immutable engine-neutral circuit program.

Parameters:

NameTypeDescription
namestrCircuit entrypoint name.
num_qubitsintNumber of virtual input qubit slots.
num_clbitsintNumber of classical bit slots.
input_wirestuple[WireId, ...]Initial wire version per qubit slot.
output_wirestuple[WireId, ...]Final wire version per qubit slot.
operationstuple[CircuitInstruction, ...]Structured instruction sequence.
global_phaseScalarExprPhase accumulated in the root lexical region, in radians. Dynamic control-flow regions retain their own scoped phases. Defaults to zero and becomes observable when the program is controlled.
Constructor
def __init__(
    self,
    name: str,
    num_qubits: int,
    num_clbits: int,
    input_wires: tuple[WireId, ...],
    output_wires: tuple[WireId, ...],
    operations: tuple[CircuitInstruction, ...],
    global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

ClassicalBitExpr [source]

class ClassicalBitExpr(_ScalarOperators)

Reference a measured classical bit.

Parameters:

NameTypeDescription
indexintCircuit-local classical bit index.
Constructor
def __init__(self, index: int) -> None
Attributes

EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return
Constructor
def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

ForInstruction [source]

class ForInstruction

Repeat a structured circuit region over a concrete range.

Parameters:

NameTypeDescription
indexsetrangeConcrete iteration range.
loop_variableLoopVariableExprInduction expression used by the body.
inputstuple[WireId, ...]Wire versions entering the loop.
bodytuple[CircuitInstruction, ...]Single-iteration body.
body_outputstuple[WireId, ...]Body wire versions yielded to the next iteration.
outputstuple[WireId, ...]Wire versions after the loop.
Constructor
def __init__(
    self,
    indexset: range,
    loop_variable: LoopVariableExpr,
    inputs: tuple[WireId, ...],
    body: tuple[CircuitInstruction, ...],
    body_outputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
) -> None
Attributes

GateInstruction [source]

class GateInstruction

Apply one primitive gate to versioned virtual wires.

Parameters:

NameTypeDescription
kindGateKindPrimitive gate kind.
inputstuple[WireId, ...]Consumed wire versions.
outputstuple[WireId, ...]Produced wire versions.
parameterstuple[ScalarExpr, ...]Gate parameters.
Constructor
def __init__(
    self,
    kind: GateKind,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    parameters: tuple[ScalarExpr, ...] = (),
) -> None
Attributes

IfInstruction [source]

class IfInstruction

Select between two structured circuit regions.

Parameters:

NameTypeDescription
conditionScalarExprRuntime branch predicate.
inputstuple[WireId, ...]Wires entering both branches.
true_bodytuple[CircuitInstruction, ...]True branch body.
false_bodytuple[CircuitInstruction, ...]False branch body.
true_outputstuple[WireId, ...]Wires yielded by the true branch.
false_outputstuple[WireId, ...]Wires yielded by the false branch.
outputstuple[WireId, ...]Merged post-branch wires.
true_global_phaseScalarExprPhase applied only in the true branch.
false_global_phaseScalarExprPhase applied only in the false branch.
Constructor
def __init__(
    self,
    condition: ScalarExpr,
    inputs: tuple[WireId, ...],
    true_body: tuple[CircuitInstruction, ...],
    false_body: tuple[CircuitInstruction, ...],
    true_outputs: tuple[WireId, ...],
    false_outputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    true_global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
    false_global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

LiteralExpr [source]

class LiteralExpr(_ScalarOperators)

Represent a concrete scalar literal.

Parameters:

NameTypeDescription
valuebool | int | floatConcrete scalar value.
Constructor
def __init__(self, value: bool | int | float) -> None
Attributes

LoopVariableExpr [source]

class LoopVariableExpr(_ScalarOperators)

Reference the induction value of a structured loop.

Parameters:

NameTypeDescription
namestrCircuit-local loop variable name.
Constructor
def __init__(self, name: str) -> None
Attributes

MeasureInstruction [source]

class MeasureInstruction

Measure a wire into a classical bit.

Parameters:

NameTypeDescription
inputWireIdMeasured wire version.
outputWireIdPost-measurement wire version.
clbitintDestination classical bit index.
Constructor
def __init__(self, input: WireId, output: WireId, clbit: int) -> None
Attributes

MeasureVectorInstruction [source]

class MeasureVectorInstruction

Measure an ordered group of wires into classical bits.

This instruction preserves vector measurement as one semantic operation until target materialization. An engine with a vector measurement primitive can consume it directly; scalar-only engines expand it at their own boundary.

Parameters:

NameTypeDescription
inputstuple[WireId, ...]Measured wire versions in result order.
outputstuple[WireId, ...]Post-measurement wire versions.
clbitstuple[int, ...]Destination classical bits in result order.
Constructor
def __init__(
    self,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    clbits: tuple[int, ...],
) -> None
Attributes

ParameterExpr [source]

class ParameterExpr(_ScalarOperators)

Reference a runtime circuit parameter.

Parameters:

NameTypeDescription
namestrStable external parameter name.
Constructor
def __init__(self, name: str) -> None
Attributes

ParameterMetadata [source]

class ParameterMetadata

Describe every scalar slot and runtime array in a compiled segment.

Parameters:

NameTypeDescription
parameterslist[ParameterInfo]Ordered scalar engine slots. Defaults to an empty list.
arraysdict[str, ParameterArrayInfo]Explicit runtime-array ABI descriptors keyed by root name. Defaults to descriptors derived from parameters for backward compatibility.
Constructor
def __init__(
    self,
    parameters: list[ParameterInfo] = list(),
    arrays: dict[str, ParameterArrayInfo] = dict(),
) -> None
Attributes
Methods
get_array_names
def get_array_names(self) -> set[str]

Return unique scalar and array root names.

Returns:

set[str] — set[str]: Root name for every emitted parameter.

get_ordered_params
def get_ordered_params(self) -> list[Any]

Return engine parameter objects in ABI definition order.

Returns:

list[Any] — list[Any]: Engine-specific parameter objects.

get_param_by_name
def get_param_by_name(self, name: str) -> ParameterInfo | None

Find one scalar slot by its full emitted key.

Parameters:

NameTypeDescription
namestrFull engine parameter key.

Returns:

ParameterInfo | None — ParameterInfo | None: Matching slot, or None when absent.

merge
@classmethod
def merge(cls, metadata: Sequence[ParameterMetadata]) -> ParameterMetadata

Merge parameter manifests from multiple quantum segments.

Parameters:

NameTypeDescription
metadataSequence[ParameterMetadata]Segment manifests in execution order.

Returns:

ParameterMetadata — Combined manifest with first-seen scalar slot ordering and array descriptors derived across all segments.

to_binding_dict
def to_binding_dict(self, bindings: Mapping[str, Any]) -> dict[Any, Any]

Map indexed user bindings to engine parameter objects.

Parameters:

NameTypeDescription
bindingsMapping[str, Any]Scalar values keyed by full emitted parameter name.

Returns:

dict[Any, Any] — dict[Any, Any]: Engine parameter objects mapped to bound values.

validate_array_shapes
def validate_array_shapes(self, bindings: Mapping[str, Any] | None) -> None

Validate user array rank and every concrete ABI dimension.

Parameters:

NameTypeDescription
bindingsMapping[str, Any] | NoneRaw public bindings before scalar flattening. None means no validation is needed.

Raises:

validate_required_bindings
def validate_required_bindings(self, indexed_bindings: Mapping[str, Any]) -> None

Reject missing scalar slots in an indexed binding map.

Parameters:

NameTypeDescription
indexed_bindingsMapping[str, Any]Flattened user bindings.

Raises:


PauliEvolutionInstruction [source]

class PauliEvolutionInstruction

Apply an abstract Hamiltonian evolution to selected wires.

Parameters:

NameTypeDescription
hamiltonianAnyImmutable Qamomile Hamiltonian value.
timeScalarExprEvolution time in radians.
inputstuple[WireId, ...]Consumed wire versions.
outputstuple[WireId, ...]Produced wire versions.
realizationPauliEvolutionRealizationTarget realization selected by legalization. Defaults to ABSTRACT during shared lowering.
Constructor
def __init__(
    self,
    hamiltonian: Any,
    time: ScalarExpr,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    realization: PauliEvolutionRealization = PauliEvolutionRealization.ABSTRACT,
) -> None
Attributes

ResetInstruction [source]

class ResetInstruction

Reset a wire and produce a fresh zero-state wire.

Parameters:

NameTypeDescription
inputWireIdWire version before reset.
outputWireIdFresh wire version after reset.
Constructor
def __init__(self, input: WireId, output: WireId) -> None
Attributes

UnaryExpr [source]

class UnaryExpr(_ScalarOperators)

Apply a unary scalar operation.

Parameters:

NameTypeDescription
operatorUnaryOperatorOperation kind.
operandScalarExprInput expression.
Constructor
def __init__(self, operator: UnaryOperator, operand: ScalarExpr) -> None
Attributes

WhileInstruction [source]

class WhileInstruction

Repeat a structured region while a runtime predicate is true.

Parameters:

NameTypeDescription
conditionScalarExprRuntime loop predicate.
inputstuple[WireId, ...]Wires entering the loop.
bodytuple[CircuitInstruction, ...]Loop body.
body_outputstuple[WireId, ...]Wires yielded to the next iteration.
outputstuple[WireId, ...]Wires available after loop termination.
body_global_phaseScalarExprPhase applied once per loop iteration.
Constructor
def __init__(
    self,
    condition: ScalarExpr,
    inputs: tuple[WireId, ...],
    body: tuple[CircuitInstruction, ...],
    body_outputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    body_global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

qamomile.circuit.transpiler.circuit_ir.verify

Structural verifier for engine-neutral circuit programs.

Overview

FunctionDescription
verify_circuitVerify wire linearity, regions, expressions, and slot bounds.
ClassDescription
BarrierInstructionSeparate scheduling regions without changing wire versions.
BinaryExprApply a binary scalar operation.
CallInstructionInvoke a reusable circuit over versioned wires.
CircuitProgramStore one immutable engine-neutral circuit program.
ClassicalBitExprReference a measured classical bit.
ForInstructionRepeat a structured circuit region over a concrete range.
GateInstructionApply one primitive gate to versioned virtual wires.
GateKindClassification of gates for emission.
IfInstructionSelect between two structured circuit regions.
LiteralExprRepresent a concrete scalar literal.
LoopVariableExprReference the induction value of a structured loop.
MeasureInstructionMeasure a wire into a classical bit.
MeasureVectorInstructionMeasure an ordered group of wires into classical bits.
PauliEvolutionInstructionApply an abstract Hamiltonian evolution to selected wires.
ResetInstructionReset a wire and produce a fresh zero-state wire.
UnaryExprApply a unary scalar operation.
WhileInstructionRepeat a structured region while a runtime predicate is true.
WireIdIdentify one version of a virtual quantum wire.

Constants

Functions

verify_circuit [source]

def verify_circuit(program: CircuitProgram) -> None

Verify wire linearity, regions, expressions, and slot bounds.

Parameters:

NameTypeDescription
programCircuitProgramImmutable circuit program to verify.

Raises:

Classes

BarrierInstruction [source]

class BarrierInstruction

Separate scheduling regions without changing wire versions.

Parameters:

NameTypeDescription
wirestuple[WireId, ...]Wires participating in the barrier.
Constructor
def __init__(self, wires: tuple[WireId, ...]) -> None
Attributes

BinaryExpr [source]

class BinaryExpr(_ScalarOperators)

Apply a binary scalar operation.

Parameters:

NameTypeDescription
operatorBinaryOperatorOperation kind.
leftScalarExprLeft operand.
rightScalarExprRight operand.
Constructor
def __init__(self, operator: BinaryOperator, left: ScalarExpr, right: ScalarExpr) -> None
Attributes

CallInstruction [source]

class CallInstruction

Invoke a reusable circuit over versioned wires.

Parameters:

NameTypeDescription
calleeReusableCircuitReusable circuit and transforms.
inputstuple[WireId, ...]Consumed wire versions.
outputstuple[WireId, ...]Produced wire versions.
Constructor
def __init__(
    self,
    callee: ReusableCircuit,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
) -> None
Attributes

CircuitProgram [source]

class CircuitProgram

Store one immutable engine-neutral circuit program.

Parameters:

NameTypeDescription
namestrCircuit entrypoint name.
num_qubitsintNumber of virtual input qubit slots.
num_clbitsintNumber of classical bit slots.
input_wirestuple[WireId, ...]Initial wire version per qubit slot.
output_wirestuple[WireId, ...]Final wire version per qubit slot.
operationstuple[CircuitInstruction, ...]Structured instruction sequence.
global_phaseScalarExprPhase accumulated in the root lexical region, in radians. Dynamic control-flow regions retain their own scoped phases. Defaults to zero and becomes observable when the program is controlled.
Constructor
def __init__(
    self,
    name: str,
    num_qubits: int,
    num_clbits: int,
    input_wires: tuple[WireId, ...],
    output_wires: tuple[WireId, ...],
    operations: tuple[CircuitInstruction, ...],
    global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

ClassicalBitExpr [source]

class ClassicalBitExpr(_ScalarOperators)

Reference a measured classical bit.

Parameters:

NameTypeDescription
indexintCircuit-local classical bit index.
Constructor
def __init__(self, index: int) -> None
Attributes

ForInstruction [source]

class ForInstruction

Repeat a structured circuit region over a concrete range.

Parameters:

NameTypeDescription
indexsetrangeConcrete iteration range.
loop_variableLoopVariableExprInduction expression used by the body.
inputstuple[WireId, ...]Wire versions entering the loop.
bodytuple[CircuitInstruction, ...]Single-iteration body.
body_outputstuple[WireId, ...]Body wire versions yielded to the next iteration.
outputstuple[WireId, ...]Wire versions after the loop.
Constructor
def __init__(
    self,
    indexset: range,
    loop_variable: LoopVariableExpr,
    inputs: tuple[WireId, ...],
    body: tuple[CircuitInstruction, ...],
    body_outputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
) -> None
Attributes

GateInstruction [source]

class GateInstruction

Apply one primitive gate to versioned virtual wires.

Parameters:

NameTypeDescription
kindGateKindPrimitive gate kind.
inputstuple[WireId, ...]Consumed wire versions.
outputstuple[WireId, ...]Produced wire versions.
parameterstuple[ScalarExpr, ...]Gate parameters.
Constructor
def __init__(
    self,
    kind: GateKind,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    parameters: tuple[ScalarExpr, ...] = (),
) -> None
Attributes

GateKind [source]

class GateKind(Enum)

Classification of gates for emission.

Attributes

IfInstruction [source]

class IfInstruction

Select between two structured circuit regions.

Parameters:

NameTypeDescription
conditionScalarExprRuntime branch predicate.
inputstuple[WireId, ...]Wires entering both branches.
true_bodytuple[CircuitInstruction, ...]True branch body.
false_bodytuple[CircuitInstruction, ...]False branch body.
true_outputstuple[WireId, ...]Wires yielded by the true branch.
false_outputstuple[WireId, ...]Wires yielded by the false branch.
outputstuple[WireId, ...]Merged post-branch wires.
true_global_phaseScalarExprPhase applied only in the true branch.
false_global_phaseScalarExprPhase applied only in the false branch.
Constructor
def __init__(
    self,
    condition: ScalarExpr,
    inputs: tuple[WireId, ...],
    true_body: tuple[CircuitInstruction, ...],
    false_body: tuple[CircuitInstruction, ...],
    true_outputs: tuple[WireId, ...],
    false_outputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    true_global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
    false_global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

LiteralExpr [source]

class LiteralExpr(_ScalarOperators)

Represent a concrete scalar literal.

Parameters:

NameTypeDescription
valuebool | int | floatConcrete scalar value.
Constructor
def __init__(self, value: bool | int | float) -> None
Attributes

LoopVariableExpr [source]

class LoopVariableExpr(_ScalarOperators)

Reference the induction value of a structured loop.

Parameters:

NameTypeDescription
namestrCircuit-local loop variable name.
Constructor
def __init__(self, name: str) -> None
Attributes

MeasureInstruction [source]

class MeasureInstruction

Measure a wire into a classical bit.

Parameters:

NameTypeDescription
inputWireIdMeasured wire version.
outputWireIdPost-measurement wire version.
clbitintDestination classical bit index.
Constructor
def __init__(self, input: WireId, output: WireId, clbit: int) -> None
Attributes

MeasureVectorInstruction [source]

class MeasureVectorInstruction

Measure an ordered group of wires into classical bits.

This instruction preserves vector measurement as one semantic operation until target materialization. An engine with a vector measurement primitive can consume it directly; scalar-only engines expand it at their own boundary.

Parameters:

NameTypeDescription
inputstuple[WireId, ...]Measured wire versions in result order.
outputstuple[WireId, ...]Post-measurement wire versions.
clbitstuple[int, ...]Destination classical bits in result order.
Constructor
def __init__(
    self,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    clbits: tuple[int, ...],
) -> None
Attributes

PauliEvolutionInstruction [source]

class PauliEvolutionInstruction

Apply an abstract Hamiltonian evolution to selected wires.

Parameters:

NameTypeDescription
hamiltonianAnyImmutable Qamomile Hamiltonian value.
timeScalarExprEvolution time in radians.
inputstuple[WireId, ...]Consumed wire versions.
outputstuple[WireId, ...]Produced wire versions.
realizationPauliEvolutionRealizationTarget realization selected by legalization. Defaults to ABSTRACT during shared lowering.
Constructor
def __init__(
    self,
    hamiltonian: Any,
    time: ScalarExpr,
    inputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    realization: PauliEvolutionRealization = PauliEvolutionRealization.ABSTRACT,
) -> None
Attributes

ResetInstruction [source]

class ResetInstruction

Reset a wire and produce a fresh zero-state wire.

Parameters:

NameTypeDescription
inputWireIdWire version before reset.
outputWireIdFresh wire version after reset.
Constructor
def __init__(self, input: WireId, output: WireId) -> None
Attributes

UnaryExpr [source]

class UnaryExpr(_ScalarOperators)

Apply a unary scalar operation.

Parameters:

NameTypeDescription
operatorUnaryOperatorOperation kind.
operandScalarExprInput expression.
Constructor
def __init__(self, operator: UnaryOperator, operand: ScalarExpr) -> None
Attributes

WhileInstruction [source]

class WhileInstruction

Repeat a structured region while a runtime predicate is true.

Parameters:

NameTypeDescription
conditionScalarExprRuntime loop predicate.
inputstuple[WireId, ...]Wires entering the loop.
bodytuple[CircuitInstruction, ...]Loop body.
body_outputstuple[WireId, ...]Wires yielded to the next iteration.
outputstuple[WireId, ...]Wires available after loop termination.
body_global_phaseScalarExprPhase applied once per loop iteration.
Constructor
def __init__(
    self,
    condition: ScalarExpr,
    inputs: tuple[WireId, ...],
    body: tuple[CircuitInstruction, ...],
    body_outputs: tuple[WireId, ...],
    outputs: tuple[WireId, ...],
    body_global_phase: ScalarExpr = (lambda: LiteralExpr(0.0))(),
) -> None
Attributes

WireId [source]

class WireId

Identify one version of a virtual quantum wire.

Parameters:

NameTypeDescription
valueintNon-negative module-local wire number.
Constructor
def __init__(self, value: int) -> None
Attributes

qamomile.circuit.transpiler.classical_executor

Classical segment executor for Python-based classical operations.

Overview

FunctionDescription
array_static_lengthResolve a one-dimensional array’s compile-time length.
resolve_runtime_array_locationResolve local array indices through runtime-bound slice views.
validate_region_argsValidate the SSA identities owned by a loop’s region arguments.
ClassDescription
ArrayValueAn array of typed IR values.
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
BinOpKind
CInitOperationInitialize the classical values (const, arguments etc)
ClassicalExecutorExecutes classical segments in Python.
ClassicalSegmentA segment of pure classical operations.
CompOpComparison operation (EQ, NEQ, LT, LE, GT, GE).
CompOpKind
CondOpConditional logical operation (AND, OR).
CondOpKind
DecodeQFixedOperationDecode measured bits to float (classical operation).
DecodeQIntOperationDecode least-significant-first measurement bits to an unsigned integer.
DictGetItemOperationLook up one entry of a Dict by a (possibly symbolic) key.
DictValueA dictionary value stored as stable ordered entries.
ExecutionContextHolds global state during program execution.
ExecutionErrorError during program execution.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
HasNestedOpsMixin for operations that contain nested operation lists.
IfOperationRepresents an if-else conditional operation.
NotOp
RegionArgExplicit loop-carried value on a loop operation (MLIR-style iter_arg).
RuntimeClassicalExprA classical expression known to require runtime evaluation.
RuntimeOpKindUnified kind for RuntimeClassicalExpr covering all classical
StoreArrayElementOperationStore a classical scalar into one element of a classical array.
TupleValueA tuple of IR values for structured data.
ValueA typed SSA value in the IR.
WhileOperationRepresents a while loop operation.

Constants

Functions

array_static_length [source]

def array_static_length(array: 'ArrayValue') -> int | None

Resolve a one-dimensional array’s compile-time length.

Parameters:

NameTypeDescription
arrayArrayValueArray whose sole shape dimension is inspected.

Returns:

int | None — int | None: Non-negative static length, or None when the array is not one-dimensional, its length is symbolic/non-integral, or it is malformed with a negative length. Boolean constants are rejected even though bool is an int subclass.


resolve_runtime_array_location [source]

def resolve_runtime_array_location(
    array: ArrayValue,
    indices: tuple[int, ...],
    resolve_int: Callable[[Value], int | None],
) -> tuple[ArrayValue, tuple[int, ...]] | None

Resolve local array indices through runtime-bound slice views.

Parameters:

NameTypeDescription
arrayArrayValueArray whose local indices should be resolved. May be a root array or a slice_of view chain.
indicestuple[int, ...]Concrete indices in array’s local coordinate space.
resolve_intCallable[[Value], int | None]Callback used to evaluate slice_start / slice_step values against the current runtime state.

Returns:

tuple[ArrayValue, tuple[int, ...]] | None — tuple[ArrayValue, tuple[int, ...]] | None: The root array and indices in root coordinates, or None when a slice bound is unresolved or violates the frontend slice contract.


validate_region_args [source]

def validate_region_args(op: ForOperation | ForItemsOperation | WhileOperation) -> tuple[RegionArg, ...]

Validate the SSA identities owned by a loop’s region arguments.

A loop owns several definition namespaces: its iteration variables, every RegionArg.block_arg, and every RegionArg.result. Those identities must be pairwise disjoint. Otherwise different stages can assign incompatible meanings to one UUID: a UUID-keyed environment has only one slot, so binding either the iteration variable or the carried value overwrites the other and makes both reads observe the same value.

Parameters:

NameTypeDescription
opForOperation | ForItemsOperation | WhileOperationLoop operation whose region arguments should be validated.

Returns:

tuple[RegionArg, ...] — tuple[RegionArg, ...]: The validated op.region_args tuple.

Raises:

Classes

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:

bool — True iff slice_of is non-None.

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

BinOp [source]

class BinOp(BinaryOperationBase)

Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: BinOpKind | None = None,
) -> None
Attributes

BinOpKind [source]

class BinOpKind(enum.Enum)
Attributes

CInitOperation [source]

class CInitOperation(Operation)

Initialize the classical values (const, arguments etc)

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ClassicalExecutor [source]

class ClassicalExecutor

Executes classical segments in Python.

Methods
execute
def execute(self, segment: ClassicalSegment, context: ExecutionContext) -> dict[str, Any]

Execute classical operations and return outputs.

Interprets the operations list directly using Python.

Parameters:

NameTypeDescription
segmentClassicalSegmentOrdered classical operations and declared outputs to evaluate.
contextExecutionContextPer-shot quantum and bound input values available to the segment.

Returns:

dict[str, Any] — dict[str, Any]: Computed classical values keyed by result UUID.

Raises:

resolve_value
def resolve_value(self, value: ValueLike, context: ExecutionContext) -> Any

Resolve a typed classical output using the execution interpreter.

Parameters:

NameTypeDescription
valueValueLikeScalar, array, tuple, or dictionary output.
contextExecutionContextRuntime bindings and computed values keyed by their IR identities or public parameter names.

Returns:

Any — Concrete value with tuple and dictionary structure retained.

Raises:


ClassicalSegment [source]

class ClassicalSegment(Segment)

A segment of pure classical operations.

Contains arithmetic, comparisons, and control flow. Will be executed directly in Python.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
) -> None
Attributes

CompOp [source]

class CompOp(BinaryOperationBase)

Comparison operation (EQ, NEQ, LT, LE, GT, GE).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CompOpKind | None = None,
) -> None
Attributes

CompOpKind [source]

class CompOpKind(enum.Enum)
Attributes

CondOp [source]

class CondOp(BinaryOperationBase)

Conditional logical operation (AND, OR).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CondOpKind | None = None,
) -> None
Attributes

CondOpKind [source]

class CondOpKind(enum.Enum)
Attributes

DecodeQFixedOperation [source]

class DecodeQFixedOperation(Operation)

Decode measured bits to float (classical operation).

This operation converts a sequence of classical bits from qubit measurements into a floating-point number using fixed-point encoding.

The decoding formula for least-significant-first storage:

float_value = Σ bit[i] * 2^(int_bits - num_bits + i)

For QPE phase (int_bits=0): bit[0] has weight 2**(-num_bits) and bit[-1] has weight 0.5.

Example:

bits = [1, 0, 1] with int_bits=0
→ 0.101 (MSB-first display) = 0.5 + 0.125 = 0.625

operands: [ArrayValue of bits (vec[bit])] results: [Float value]

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_bits: int = 0,
    int_bits: int = 0,
) -> None
Attributes

DecodeQIntOperation [source]

class DecodeQIntOperation(Operation)

Decode least-significant-first measurement bits to an unsigned integer.

Carrier position i contributes bit[i] * 2**i, which matches the carrier ordering used by DecodeQFixedOperation.

The bit count is not stored on the operation: it is derived from the bit-array operand’s static length through num_bits.

Parameters:

NameTypeDescription
operandslist[Value]Single measured ArrayValue[Bit] operand.
resultslist[Value]Single decoded UIntType result.
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

DictGetItemOperation [source]

class DictGetItemOperation(Operation)

Look up one entry of a Dict by a (possibly symbolic) key.

This is the IR form of d[key] on a Dict handle. The key components may be symbolic (e.g. loop variables of a for-items loop); the lookup is resolved at emit time when the key values and the dict’s bound data are both concrete.

operands: [DictValue, *key_component_values] results: [looked-up scalar value]

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_arity: int = 1,
) -> None
Attributes

DictValue [source]

class DictValue(_MetadataValueMixin, ValueBase)

A dictionary value stored as stable ordered entries.

Constructor
def __init__(
    self,
    name: str,
    entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> DictValue

ExecutionContext [source]

class ExecutionContext

Holds global state during program execution.

Constructor
def __init__(self, initial_bindings: dict[str, Any] | None = None)
Methods
copy
def copy(self) -> 'ExecutionContext'

Clone the execution context.

get
def get(self, key: str) -> Any
get_many
def get_many(self, keys: list[str]) -> dict[str, Any]
has
def has(self, key: str) -> bool
set
def set(self, key: str, value: Any) -> None
update
def update(self, values: dict[str, Any]) -> None

ExecutionError [source]

class ExecutionError(QamomileCompileError)

Error during program execution.


ForItemsOperation [source]

class ForItemsOperation(HasNestedOps, Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    key_var_values: tuple[Value, ...] | None = None,
    value_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include the per-key/value Value fields for cloning/substitution.

Same rationale as ForOperation.all_input_values: keep the IR identity fields in lockstep with body references so UUID-keyed lookups stay valid after inline cloning. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the items-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing key/value formals, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the items-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt items-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


NotOp [source]

class NotOp(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

RegionArg [source]

class RegionArg

Explicit loop-carried value on a loop operation (MLIR-style iter_arg).

A RegionArg makes a loop-carried dependency explicit in the IR, the way MLIR’s scf.for models iter_args / scf.yield:

The loop body’s operations reference block_arg (the frontend substitutes the traced pre-loop reads), and post-loop operations reference result (the frontend rebinds the Python handle when it closes the loop). result is also appended to the loop operation’s results list so dependency analysis sees the loop as its producer.

This subsumes the trace-once staleness that LoopCarriedRebind records exist to reject: a rebind represented as a RegionArg is a supported loop-carried value, not a miscompilation hazard.

Constructor
def __init__(
    self,
    var_name: str,
    init: Value,
    block_arg: Value,
    yielded: Value,
    result: Value,
) -> None
Attributes

RuntimeClassicalExpr [source]

class RuntimeClassicalExpr(Operation)

A classical expression known to require runtime evaluation.

Lowered from CompOp / CondOp / NotOp / BinOp by ClassicalLoweringPass when the op’s operand dataflow traces back to a MeasureOperation (i.e. cannot be folded at compile-time, by emit-time loop unrolling, or by compile_time_if_lowering). Engine emit translates this 1:1 to an engine-native runtime expression (e.g. qiskit.circuit.classical.expr.Expr).

Operand convention:

The single-node + unified-kind shape (vs four parallel subclasses) keeps the engine dispatch a single match op.kind instead of four parallel hooks, and makes the IR self-documenting: a single RuntimeClassicalExpr instance signals “runtime evaluation required” regardless of which classical family it came from.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: RuntimeOpKind | None = None,
) -> None
Attributes

RuntimeOpKind [source]

class RuntimeOpKind(enum.Enum)

Unified kind for RuntimeClassicalExpr covering all classical op families that can appear at runtime.

The split between this enum and the per-family BinOpKind / CompOpKind / CondOpKind is intentional: compile-time-foldable classical ops keep their original IR types so the existing fold pipeline (constant_fold → compile_time_if_lowering → emit-time evaluate_classical_predicate) is undisturbed. Only ops identified as runtime-evaluation-only by ClassicalLoweringPass get rewritten to RuntimeClassicalExpr with a member of this enum.

Attributes

StoreArrayElementOperation [source]

class StoreArrayElementOperation(Operation)

Store a classical scalar into one element of a classical array.

This is the IR form of array[index] = value for classical element types (Bit / UInt / Float). Classical values are freely copyable, so the store is an ordinary SSA rewrite: the operation consumes the current array version and produces a new ArrayValue version (same logical_id, fresh uuid) whose contents equal the input array with the addressed element replaced. Quantum arrays never use this operation — qubit element assignment is the return half of the borrow-return idiom and emits no IR.

The operation is evaluated in one of two places:

Operand convention:

operands: [array (ArrayValue), stored_value (Value), *index_values] results: [new_array (ArrayValue)]

Example:

@qmc.qkernel
def k() -> qmc.Vector[qmc.Bit]:
    qs = qmc.qubit_array(2, "qs")
    qs[0] = qmc.x(qs[0])
    bits = qmc.measure(qs)
    bits[1] = bits[0]   # emits StoreArrayElementOperation
    return bits
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

TupleValue [source]

class TupleValue(_MetadataValueMixin, ValueBase)

A tuple of IR values for structured data.

Constructor
def __init__(
    self,
    name: str,
    elements: tuple[ValueLike, ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> TupleValue

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 engine resource allocation. This applies to every Value regardless of its type (Qubit, Float, Bit, ...) -- it is not specific to qubits.


WhileOperation [source]

class WhileOperation(HasNestedOps, Operation)

Represents a while loop operation.

Only measurement-backed conditions are supported: the condition must be a Bit value produced by qmc.measure(). Non-measurement conditions (classical variables, constants, comparisons) are rejected by ValidateWhileContractPass before reaching engine emit.

Example::

bit = qmc.measure(q)
while bit:
    q = qmc.h(q)
    bit = qmc.measure(q)
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    operations: list[Operation] = list(),
    max_iterations: int | None = None,
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include rebind records and region args for cloning/substitution.

Same rationale as ForOperation.all_input_values: rebind records and region arguments reference body/pre-loop values by identity, so inline cloning must remap them in lockstep with body operands.

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus rebind-record and region-argument values.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the while body with explicit boundary values.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region whose block arguments and yields are aligned with region_args. The updated condition, when present, is appended as the final yield.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the while body and its complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt while operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, rebind-record, and region-arg values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


qamomile.circuit.transpiler.compile_check

Overview

FunctionDescription
is_block_compilableCheck if a Block is compilable.
ClassDescription
BlockUnified block representation for all pipeline stages.

Functions

is_block_compilable [source]

def is_block_compilable(block: Block) -> bool

Check if a Block is compilable.

A Block is considered compilable if all its operations are compilable. This function checks each operation in the block’s operations list.

Parameters:

NameTypeDescription
blockBlockThe Block to check.

Returns: bool: True if the block is compilable, False otherwise.

Classes

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.


qamomile.circuit.transpiler.compiled_segments

Compiled segment structures for transpiled quantum circuits.

Overview

ClassDescription
ClassicalSegmentA segment of pure classical operations.
CompiledClassicalSegmentA classical segment ready for Python execution.
CompiledExpvalSegmentA compiled expectation value segment with concrete Hamiltonian.
CompiledQuantumSegmentA quantum segment with emitted engine circuit.
ExpvalSegmentA segment for expectation value computation.
ParameterMetadataDescribe every scalar slot and runtime array in a compiled segment.
QuantumSegmentA segment of pure quantum operations.

Classes

ClassicalSegment [source]

class ClassicalSegment(Segment)

A segment of pure classical operations.

Contains arithmetic, comparisons, and control flow. Will be executed directly in Python.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
) -> None
Attributes

CompiledClassicalSegment [source]

class CompiledClassicalSegment

A classical segment ready for Python execution.

Constructor
def __init__(self, segment: ClassicalSegment) -> None
Attributes

CompiledExpvalSegment [source]

class CompiledExpvalSegment

A compiled expectation value segment with concrete Hamiltonian.

This segment computes <psi|H|psi> where psi is the quantum state from a quantum circuit and H is a qamomile.observable.Hamiltonian.

Constructor
def __init__(
    self,
    segment: ExpvalSegment,
    hamiltonian: 'qm_o.Hamiltonian',
    quantum_segment_index: int = 0,
    result_ref: str = '',
    qubit_map: dict[int, int] = dict(),
) -> None
Attributes

CompiledQuantumSegment [source]

class CompiledQuantumSegment(Generic[T])

A quantum segment with emitted engine circuit.

Constructor
def __init__(
    self,
    segment: QuantumSegment,
    circuit: T,
    qubit_map: QubitMap = dict(),
    clbit_map: ClbitMap = dict(),
    measurement_qubit_map: dict[int, int] = dict(),
    parameter_metadata: ParameterMetadata = ParameterMetadata(),
    implicit_output_qubit_indices: tuple[int, ...] | None = None,
) -> None
Attributes

ExpvalSegment [source]

class ExpvalSegment(Segment)

A segment for expectation value computation.

Represents computing <psi|H|psi> where psi is the quantum state and H is a Hamiltonian observable.

This segment bridges a quantum circuit (state preparation) to a classical expectation value.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
    hamiltonian_value: Value | None = None,
    qubits_value: Value | None = None,
    result_ref: str = '',
) -> None
Attributes

ParameterMetadata [source]

class ParameterMetadata

Describe every scalar slot and runtime array in a compiled segment.

Parameters:

NameTypeDescription
parameterslist[ParameterInfo]Ordered scalar engine slots. Defaults to an empty list.
arraysdict[str, ParameterArrayInfo]Explicit runtime-array ABI descriptors keyed by root name. Defaults to descriptors derived from parameters for backward compatibility.
Constructor
def __init__(
    self,
    parameters: list[ParameterInfo] = list(),
    arrays: dict[str, ParameterArrayInfo] = dict(),
) -> None
Attributes
Methods
get_array_names
def get_array_names(self) -> set[str]

Return unique scalar and array root names.

Returns:

set[str] — set[str]: Root name for every emitted parameter.

get_ordered_params
def get_ordered_params(self) -> list[Any]

Return engine parameter objects in ABI definition order.

Returns:

list[Any] — list[Any]: Engine-specific parameter objects.

get_param_by_name
def get_param_by_name(self, name: str) -> ParameterInfo | None

Find one scalar slot by its full emitted key.

Parameters:

NameTypeDescription
namestrFull engine parameter key.

Returns:

ParameterInfo | None — ParameterInfo | None: Matching slot, or None when absent.

merge
@classmethod
def merge(cls, metadata: Sequence[ParameterMetadata]) -> ParameterMetadata

Merge parameter manifests from multiple quantum segments.

Parameters:

NameTypeDescription
metadataSequence[ParameterMetadata]Segment manifests in execution order.

Returns:

ParameterMetadata — Combined manifest with first-seen scalar slot ordering and array descriptors derived across all segments.

to_binding_dict
def to_binding_dict(self, bindings: Mapping[str, Any]) -> dict[Any, Any]

Map indexed user bindings to engine parameter objects.

Parameters:

NameTypeDescription
bindingsMapping[str, Any]Scalar values keyed by full emitted parameter name.

Returns:

dict[Any, Any] — dict[Any, Any]: Engine parameter objects mapped to bound values.

validate_array_shapes
def validate_array_shapes(self, bindings: Mapping[str, Any] | None) -> None

Validate user array rank and every concrete ABI dimension.

Parameters:

NameTypeDescription
bindingsMapping[str, Any] | NoneRaw public bindings before scalar flattening. None means no validation is needed.

Raises:

validate_required_bindings
def validate_required_bindings(self, indexed_bindings: Mapping[str, Any]) -> None

Reject missing scalar slots in an indexed binding map.

Parameters:

NameTypeDescription
indexed_bindingsMapping[str, Any]Flattened user bindings.

Raises:


QuantumSegment [source]

class QuantumSegment(Segment)

A segment of pure quantum operations.

Contains quantum gates and qubit allocations. Will be emitted to a quantum circuit.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
    qubit_values: list[Value] = list(),
    num_qubits: int = 0,
) -> None
Attributes

qamomile.circuit.transpiler.compiler

Target-neutral compiler entrypoint for Qamomile programs.

Overview

FunctionDescription
prepare_moduleCollect a hierarchical block into an immutable program-level view.
validate_bindings_parameters_disjointEnforce the project rule that bindings and parameters are disjoint.
without_static_bindingsRemove compile-time object bindings already consumed by qkernel build.
ClassDescription
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
CompilationTargetDefine the contract implemented by every compilation target.
CompiledProgramPackage an artifact with its ABI, diagnostics, and provenance.
CompilerConfigConfigure semantic preparation and target-independent rewrites.
EffectValidationPassReject execution-mode conflicts using cached kernel effects.
EntrypointValidationPassValidate top-level entrypoint constraints.
ParameterShapeResolutionPassSubstitute symbolic parameter array shape dims with concrete constants.
PreparedModuleHold a prepared entrypoint and its reachable callable definitions.
QKernelLikeDescribe the frontend surface required by compiler entrypoints.
QamomileCompilerPrepare Qamomile semantics and dispatch explicit target compilation.
RegionCapturePassPopulate explicit captures for every structured control-flow region.
RegionValidationPassVerify dominance and signatures for every explicit semantic region.
SubstitutionPassPass that substitutes call operations and callable strategies.

Functions

prepare_module [source]

def prepare_module(entrypoint: Block, bindings: Mapping[str, Any] | None = None) -> PreparedModule

Collect a hierarchical block into an immutable program-level view.

The collector follows calls in nested control-flow regions, SELECT case Blocks, and every body carried by a callable definition. Definitions remain Qamomile semantic IR; this function does not inline, clone, or lower operations.

Parameters:

NameTypeDescription
entrypointBlockHierarchical entrypoint after target-independent frontend preparation.
bindingsMapping[str, Any] | NoneCompile-time values that cannot be embedded in scalar value metadata, such as Hamiltonians. Defaults to None.

Returns:

PreparedModule — Entrypoint, reachable definitions, call graph, and public ABI. :class:QamomileCompiler creates a deep target-owned snapshot before invoking a target pipeline.


validate_bindings_parameters_disjoint [source]

def validate_bindings_parameters_disjoint(bindings: dict[str, Any] | None, parameters: list[str] | None) -> None

Enforce the project rule that bindings and parameters are disjoint.

A kernel argument name must be resolved exactly one way: compile-time bound (in bindings, baked into the emitted circuit) or runtime symbolic (in parameters, surviving as an engine parameter). Listing the same name in both is ambiguous and historically caused silent miscompilation — the binding won the resolution race and the runtime parameter was silently dropped from the emitted circuit (see #354). This is the single shared checker so the rule is enforced identically at every entry point (QKernel.build / Transpiler.to_block / Transpiler.emit / Transpiler.transpile), not only in the top-level transpile wrapper.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneCompile-time bindings keyed by argument name, or None. None is treated as empty.
parameterslist[str] | NoneArgument names to keep as runtime parameters, or None. None is treated as empty.

Returns:

None — None

Raises:

Example:

>>> validate_bindings_parameters_disjoint({"theta": 0.5}, ["phi"])
>>> validate_bindings_parameters_disjoint({"theta": 0.5}, ["theta"])
Traceback (most recent call last):
    ...
ValueError: Parameter name(s) ['theta'] appear in both ...

without_static_bindings [source]

def without_static_bindings(
    input_types: Mapping[str, Any],
    bindings: Mapping[str, Any] | None,
) -> dict[str, Any]

Remove compile-time object bindings already consumed by qkernel build.

Parameters:

NameTypeDescription
input_typesMapping[str, Any]QKernel input annotations by name.
bindingsMapping[str, Any] | NoneUser-provided compile-time values.

Returns:

dict[str, Any] — dict[str, Any]: Ordinary scalar, array, and structural bindings only.

Classes

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.


BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

CompilationTarget [source]

class CompilationTarget(Protocol[PlanT, ArtifactT])

Define the contract implemented by every compilation target.

Attributes
Methods
compile
def compile(self, program: PreparedModule, plan: PlanT) -> CompiledProgram[ArtifactT]

Lower and materialize a prepared program for this target.

Parameters:

NameTypeDescription
programPreparedModulePrepared semantic program.
planPlanTDecisions returned by :meth:plan.

Returns:

CompiledProgram[ArtifactT] — CompiledProgram[ArtifactT]: Target-native artifact and metadata.

plan
def plan(self, program: PreparedModule) -> PlanT

Choose target-specific lowering decisions for a program.

Parameters:

NameTypeDescription
programPreparedModulePrepared semantic program.

Returns:

PlanT — Immutable target-specific compilation plan.

validate
def validate(self, artifact: ArtifactT) -> None

Validate a materialized artifact with target-native rules.

Parameters:

NameTypeDescription
artifactArtifactTTarget-native artifact to validate.

Raises:


CompiledProgram [source]

class CompiledProgram(Generic[ArtifactT])

Package an artifact with its ABI, diagnostics, and provenance.

Parameters:

NameTypeDescription
artifactArtifactTTarget-native circuit, graph, module, or package.
abiProgramABIRuntime-visible input and output contract.
metadataCompilationMetadataTarget and pipeline provenance.
diagnosticstuple[CompilationDiagnostic, ...]Non-fatal compilation diagnostics. Defaults to an empty tuple.
Constructor
def __init__(
    self,
    artifact: ArtifactT,
    abi: ProgramABI,
    metadata: CompilationMetadata,
    diagnostics: tuple[CompilationDiagnostic, ...] = (),
) -> None
Attributes

CompilerConfig [source]

class CompilerConfig

Configure semantic preparation and target-independent rewrites.

Parameters:

NameTypeDescription
decompositionDecompositionConfigComposite-gate decomposition choices. Defaults to the standard decomposition configuration.
substitutionsSubstitutionConfigCallable substitution rules. Defaults to no substitutions.
Constructor
def __init__(
    self,
    decomposition: DecompositionConfig = DecompositionConfig(),
    substitutions: SubstitutionConfig = SubstitutionConfig(),
) -> None
Attributes
Methods
with_strategies
@classmethod
def with_strategies(
    cls,
    strategy_overrides: dict[str, str] | None = None,
    **kwargs: Any = {},
) -> 'CompilerConfig'

Create configuration with named decomposition strategies.

Parameters:

NameTypeDescription
strategy_overridesdict[str, str] | NoneGate-name to strategy mapping. Defaults to an empty mapping.
**kwargsAnyAdditional :class:CompilerConfig constructor arguments.

Returns:

'CompilerConfig' — Configuration containing matching decomposition and substitution rules.


EffectValidationPass [source]

class EffectValidationPass(Pass)

Reject execution-mode conflicts using cached kernel effects.

Attributes
Methods
run
def run(self, block: Block) -> Block

Validate expectation-value compatibility for one entrypoint.

Parameters:

NameTypeDescription
blockBlockHierarchical entrypoint block.

Returns:

Block — The unchanged validated block.

Raises:


EntrypointValidationPass [source]

class EntrypointValidationPass(Pass[Block, Block])

Validate top-level entrypoint constraints.

Attributes
Methods
run
def run(self, input: Block) -> Block

ParameterShapeResolutionPass [source]

class ParameterShapeResolutionPass(Pass[Block, Block])

Substitute symbolic parameter array shape dims with concrete constants.

Input: BlockKind.HIERARCHICAL (runs before InlinePass). Output: same block kind, with matching shape dim Values constant-folded.

Constructor
def __init__(self, bindings: dict[str, Any] | None = None) -> None

Initialize parameter-shape resolution.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneCompile-time bindings keyed by entrypoint argument name. Defaults to None.
Attributes
Methods
run
def run(self, input: Block) -> Block

Replace resolvable symbolic array dimensions with constants.

Parameters:

NameTypeDescription
inputBlockHierarchical semantic block to rewrite.

Returns:

Block — Rewritten block preserving all display, ABI, parameter, and stage metadata.

Raises:


PreparedModule [source]

class PreparedModule

Hold a prepared entrypoint and its reachable callable definitions.

Parameters:

NameTypeDescription
entrypoint_refCallableRefStable symbol assigned to the program entrypoint.
entrypointBlockHierarchical semantic block for the entrypoint.
definitionsMapping[CallableRef, CallableDef]Reachable callable definitions keyed by their stable symbols.
definition_variantsMapping[CallableRef, tuple[CallableDef, ...]]Every distinct body observed for a symbol. Multiple variants of one origin may be valid for circuit-family inlining but must be handled or rejected by targets that emit one function per symbol.
call_graphMapping[CallableRef, frozenset[CallableRef]]Directed caller-to-callee relation, including the entrypoint symbol.
abiProgramABIClassical public input and output contract.
bindingsMapping[str, Any]Compile-time values retained for direct program-graph targets. Circuit-family targets receive the same values through their emit pass.
Constructor
def __init__(
    self,
    entrypoint_ref: CallableRef,
    entrypoint: Block,
    definitions: Mapping[CallableRef, CallableDef],
    definition_variants: Mapping[CallableRef, tuple[CallableDef, ...]],
    call_graph: Mapping[CallableRef, frozenset[CallableRef]],
    abi: ProgramABI,
    bindings: Mapping[str, Any],
) -> None
Attributes
Methods
body
def body(self, ref: CallableRef) -> Block

Return the semantic body associated with a program symbol.

Parameters:

NameTypeDescription
refCallableRefEntrypoint or callable symbol to resolve.

Returns:

Block — Hierarchical semantic body for ref.

Raises:

owned_snapshot
def owned_snapshot(self) -> PreparedModule

Create a deep, target-owned snapshot of prepared semantics.

The semantic IR intentionally remains mutable while compiler passes are being developed. Copying the entrypoint and definition registry as one object graph preserves shared callable bodies while preventing one target from mutating the source module observed by another.

Returns:

PreparedModule — Deep snapshot with read-only definition and call graph registries.


QKernelLike [source]

class QKernelLike(Protocol)

Describe the frontend surface required by compiler entrypoints.

This protocol is intentionally structural. It lets decorator-created composites reuse the qkernel inspection and build interface without making them inherit from QKernel or exposing the compiler-facing callable descriptor model as a frontend concept.

Attributes
Methods
build
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> Block

Build a traced body block.

Parameters:

NameTypeDescription
parameterslist[str] | NoneRuntime parameter names to preserve. Defaults to None.
**kwargsAnyCompile-time bindings for non-parameter arguments.

Returns:

Block — Traced hierarchical body block.


QamomileCompiler [source]

class QamomileCompiler

Prepare Qamomile semantics and dispatch explicit target compilation.

Parameters:

NameTypeDescription
configCompilerConfig | NoneShared frontend and substitution configuration. Defaults to :class:CompilerConfig.
Constructor
def __init__(self, config: CompilerConfig | None = None) -> None

Initialize the target-neutral compiler.

Parameters:

NameTypeDescription
configCompilerConfig | NoneShared frontend configuration. Defaults to :class:CompilerConfig.
Attributes
Methods
compile
def compile(
    self,
    kernel: QKernelLike,
    target: CompilationTarget[PlanT, ArtifactT],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> CompiledProgram[ArtifactT]

Compile a qkernel with an explicit target implementation.

Parameters:

NameTypeDescription
kernelQKernelLikeTop-level qkernel-like entrypoint.
targetCompilationTarget[PlanT, ArtifactT]Target planner, lowerer, materializer, and validator.
bindingsdict[str, Any] | NoneCompile-time bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.

Returns:

CompiledProgram[ArtifactT] — CompiledProgram[ArtifactT]: Validated target-native artifact.

Raises:

prepare
def prepare(
    self,
    kernel: QKernelLike,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> PreparedModule

Prepare a hierarchical semantic module without destroying calls.

Parameters:

NameTypeDescription
kernelQKernelLikeTop-level qkernel-like entrypoint.
bindingsdict[str, Any] | NoneCompile-time bindings used for tracing and shape resolution. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.

Returns:

PreparedModule — Program-level semantic input for target planning.

Raises:

to_block
def to_block(
    self,
    kernel: QKernelLike,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> Block

Trace a qkernel-like object into a hierarchical semantic block.

Parameters:

NameTypeDescription
kernelQKernelLikeFrontend object to trace.
bindingsdict[str, Any] | NoneCompile-time argument values. Defaults to None.
parameterslist[str] | NoneArgument names retained as runtime parameters. Defaults to None.

Returns:

Block — Hierarchical Qamomile semantic block.

Raises:


RegionCapturePass [source]

class RegionCapturePass(Pass[Block, Block])

Populate explicit captures for every structured control-flow region.

The pass derives captures from the current semantic IR, so it can normalize hand-built and deserialized blocks as well as frontend output. The pass preserves existing block identity while replacing structured operations with capture-annotated values. Running it repeatedly is idempotent.

Constructor
def __init__(self) -> None

Initialize an empty reachable-block visitation set.

Attributes
Methods
run
def run(self, input: Block) -> Block

Populate explicit captures throughout one block graph.

Parameters:

NameTypeDescription
inputBlockSemantic entrypoint whose reachable regions should be normalized.

Returns:

Block — The input entrypoint with capture lists populated on every reachable structured-control operation.


RegionValidationPass [source]

class RegionValidationPass(Pass[Block, Block])

Verify dominance and signatures for every explicit semantic region.

Constructor
def __init__(self) -> None

Initialize an empty reachable-block visitation set.

Attributes
Methods
run
def run(self, input: Block) -> Block

Validate a block graph and return it unchanged.

Parameters:

NameTypeDescription
inputBlockSemantic entrypoint whose regions should be verified.

Returns:

Block — The validated input block.

Raises:


SubstitutionPass [source]

class SubstitutionPass(Pass[Block, Block])

Pass that substitutes call operations and callable strategies.

This pass traverses the block and applies substitution rules:

The pass preserves the block structure and only modifies matching operations.

Input: Block (any kind) Output: Block with substitutions applied (same kind as input)

Constructor
def __init__(self, config: SubstitutionConfig) -> None

Initialize the pass with configuration.

Parameters:

NameTypeDescription
configSubstitutionConfigSubstitution configuration with rules
Attributes
Methods
run
def run(self, input: Block) -> Block

Apply substitutions to the block.

Parameters:

NameTypeDescription
inputBlockBlock to transform

Returns:

Block — Block with substitutions applied


qamomile.circuit.transpiler.config

Configuration shared by semantic preparation and target compilation.

Overview

ClassDescription
CompilerConfigConfigure semantic preparation and target-independent rewrites.
DecompositionConfigConfigure named implementation strategies for callable lowering.
SubstitutionConfigConfiguration for the substitution pass.
SubstitutionRuleA single substitution rule.

Constants

Classes

CompilerConfig [source]

class CompilerConfig

Configure semantic preparation and target-independent rewrites.

Parameters:

NameTypeDescription
decompositionDecompositionConfigComposite-gate decomposition choices. Defaults to the standard decomposition configuration.
substitutionsSubstitutionConfigCallable substitution rules. Defaults to no substitutions.
Constructor
def __init__(
    self,
    decomposition: DecompositionConfig = DecompositionConfig(),
    substitutions: SubstitutionConfig = SubstitutionConfig(),
) -> None
Attributes
Methods
with_strategies
@classmethod
def with_strategies(
    cls,
    strategy_overrides: dict[str, str] | None = None,
    **kwargs: Any = {},
) -> 'CompilerConfig'

Create configuration with named decomposition strategies.

Parameters:

NameTypeDescription
strategy_overridesdict[str, str] | NoneGate-name to strategy mapping. Defaults to an empty mapping.
**kwargsAnyAdditional :class:CompilerConfig constructor arguments.

Returns:

'CompilerConfig' — Configuration containing matching decomposition and substitution rules.


DecompositionConfig [source]

class DecompositionConfig

Configure named implementation strategies for callable lowering.

Implementations live on each callable definition. This object only records user selection; it is intentionally not a second global strategy registry.

Parameters:

NameTypeDescription
strategy_overridesdict[str, str]Callable-name to strategy-name overrides.
strategy_paramsdict[str, dict[str, Any]]Optional strategy parameters keyed by strategy name.
default_strategystrFallback strategy name. Defaults to "standard".
Constructor
def __init__(
    self,
    strategy_overrides: dict[str, str] = dict(),
    strategy_params: dict[str, dict[str, Any]] = dict(),
    default_strategy: str = 'standard',
) -> None
Attributes
Methods
get_strategy_for_gate
def get_strategy_for_gate(self, gate_name: str) -> str

Return the selected strategy name for a callable.

Parameters:

NameTypeDescription
gate_namestrCallable name.

Returns:

str — Explicit override or the configured default.

get_strategy_params
def get_strategy_params(self, strategy_name: str) -> dict[str, Any]

Return parameters for one strategy.

Parameters:

NameTypeDescription
strategy_namestrStrategy name.

Returns:

dict[str, Any] — dict[str, Any]: Copy of the configured parameter mapping.


SubstitutionConfig [source]

class SubstitutionConfig

Configuration for the substitution pass.

Constructor
def __init__(self, rules: list[SubstitutionRule] = list()) -> None
Attributes
Methods
get_rule_for_name
def get_rule_for_name(self, name: str) -> SubstitutionRule | None

Find a rule matching the given name.

Parameters:

NameTypeDescription
namestrName to look up

Returns:

SubstitutionRule | None — Matching SubstitutionRule or None


SubstitutionRule [source]

class SubstitutionRule

A single substitution rule.

Constructor
def __init__(
    self,
    source_name: str,
    target: 'Block | QKernel | None' = None,
    strategy: str | None = None,
    validate_signature: bool = True,
) -> None
Attributes

qamomile.circuit.transpiler.decompositions

Shared gate decomposition recipes for engine emitters.

This module defines the canonical decomposition of controlled gates (CH, CY, CP, CRY, CRZ) into primitive operations (RY, RZ, CNOT, S, SDG). Each recipe is a frozen sequence of :class:DecompStep instances that encode:

The recipes are the single source of truth for how Qamomile decomposes controlled gates when an engine cannot use a native controlled-U operation.

Why data-only (no shared execution helper)

Each engine has its own emission dialect:

Because no single helper absorbs all three styles cleanly, engines inline their decomposition using their own idiomatic emission, and reference the recipe constants below from the emit_ch / emit_cy / ... docstrings to document equivalence. When changing a recipe, update the constant here and ensure every engine’s inline implementation matches.

Overview

ClassDescription
DecompStepA single step in a decomposition recipe.
PrimitiveGateGate primitives used in decomposition recipes.

Constants

Classes

DecompStep [source]

class DecompStep

A single step in a decomposition recipe.

Constructor
def __init__(self, gate: PrimitiveGate, target: str, angle: str | None = None) -> None
Attributes

PrimitiveGate [source]

class PrimitiveGate(Enum)

Gate primitives used in decomposition recipes.

Attributes

qamomile.circuit.transpiler.emit_context

Typed bindings container for the emit pipeline.

Background — what was wrong with the bare dict[str, Any]:

The pre-EmitContext design used a single bindings: dict[str, Any] threaded through every emit-pipeline function. That dict served at least eight distinct semantic purposes simultaneously:

  1. User-supplied kernel parameters (keyed by parameter name).

  2. Loop iteration variables (keyed by Value UUID; pushed on entry, restored on exit).

  3. Emit-time-computed intermediates — BinOp / CompOp / CondOp / NotOp results (keyed by Value UUID after Fix B; originally also keyed by Value name, which collided across tmps).

  4. Merge-output aliases (keyed by merge-output UUID; written by register_classical_merge_aliases).

  5. Engine runtime expressions (e.g. qiskit.circuit.classical.expr.Expr for compound runtime if-conditions).

  6. Array data (keyed by ArrayValue UUID).

  7. Dict data (keyed by DictValue UUID).

  8. Pauli observables (keyed by Value UUID).

This overloading was the structural cause of every name-collision bug class seen in this codebase: "bit_tmp" chained predicates, j_merge_4 merge aliases, the inline-pass DictValue drop, and the type-blind bool(...) coercion in resolve_operand. Each was patched locally; the structural overloading remained.

What EmitContext does (root-cause fix):

EmitContext is a dict subclass — flat [key] access still works for migration compatibility. On top of dict semantics, every binding kind has a separate, semantically-typed slot with the appropriate identity key:

The key invariant: after the migration, the dict-baseclass writes disappear. All writers go through typed setters (push_loop_var, set_array_data, etc.); all readers go through typed getters. EmitContext retains dict-protocol read-compat for legacy callers during migration, but new code should never touch ctx[key].

Identity policy:

This eliminates the name-collision bug class entirely: empty/duplicate names cannot resolve to anything because lookups never go through the name path.

Overview

ClassDescription
EmitContextBindings container with semantic slots, dict-compatible.

Classes

EmitContext [source]

class EmitContext(dict)

Bindings container with semantic slots, dict-compatible.

All emit-pipeline functions that take bindings: dict[str, Any] accept an EmitContext unchanged because it inherits from dict.

Use the typed methods (bind_param, set_value, etc.) when writing new code so the slot tracking stays accurate; existing ctx[key] = value writes still work but bypass the slots.

Slots:

_params: User-supplied kernel parameters, keyed by parameter name. Stable across the run. Name-keyed because the user supplies parameters by name at the public API boundary. _loop_vars: Currently-bound loop iteration variables, keyed by ForOperation.loop_var_value.uuid / ForItemsOperation.value_var_value.uuid etc. Pushed on loop entry, restored on exit. UUID-keyed so identical user-chosen variable names in nested or sibling loops never collide. _values: Emit-time-computed intermediate values (BinOp results, CompOp/CondOp/NotOp results, merge aliases), keyed by Value UUID. _runtime_exprs: Engine runtime-expression objects (e.g. Qiskit expr.Expr for compound classical conditions), keyed by Value UUID. _array_data: Bound array data (e.g. Vector[Float] parameter values), keyed by ArrayValue.uuid. _dict_data: Bound dict data (e.g. Dict[Tuple[UInt, UInt], Float] ising coefficients), keyed by DictValue.uuid. _observables: Bound Pauli observables (used by PauliEvolveOp and gate counting), keyed by observable Value UUID.

Example:

>>> ctx = EmitContext.from_user_bindings({"theta": 0.5, "n": 3})
>>> ctx["theta"]  # dict-style read still works
0.5
>>> ctx.bind_param("phi", 1.5)
>>> "phi" in ctx and ctx["phi"] == 1.5
True
>>> ctx.set_value(some_uuid, 42)
>>> ctx[some_uuid] == 42 and some_uuid in ctx._values
True
Constructor
def __init__(self, *args: Any = (), **kwargs: Any = {}) -> None
Methods
bind_param
def bind_param(self, name: str, value: Any) -> None

Register a kernel parameter binding (by name).

bind_params
def bind_params(self, params: dict[str, Any]) -> None

Register multiple kernel parameter bindings.

copy
def copy(self) -> 'EmitContext'

Return a shallow copy preserving all semantic slots.

The dict baseclass copy() returns a plain dict, dropping the slot-tracking metadata. Loop unrollers call bindings.copy() to make a per-iteration child scope; without this override the child would lose the params/loop_vars/values/runtime_exprs partitioning and become a flat dict, defeating the whole point of EmitContext. We override to return an EmitContext with slot dicts independently copied so child mutations (e.g. pushing a new loop var) don’t bleed back to the parent.

describe
def describe(self) -> str

Return a multi-line summary suitable for debug printing.

from_user_bindings
@classmethod
def from_user_bindings(cls, user_bindings: dict[str, Any] | None) -> 'EmitContext'

Build an EmitContext seeded with user-supplied parameters.

Parameters:

NameTypeDescription
user_bindingsdict[str, Any] | NoneThe dict passed by the user to transpile(); None is treated as empty.

Returns:

'EmitContext' — A fresh EmitContext with all entries registered as parameters.

get_array_data
def get_array_data(self, uuid: str) -> Any

Get array data by ArrayValue.uuid, or None.

get_dict_data
def get_dict_data(self, uuid: str) -> Any

Get dict data by DictValue.uuid, or None.

get_loop_var
def get_loop_var(self, uuid: str) -> Any

Get a loop variable binding by Value UUID, or None if absent.

get_observable
def get_observable(self, uuid: str) -> Any

Get a Pauli observable by Value UUID, or None.

get_runtime_expr
def get_runtime_expr(self, uuid: str) -> Any

Get an engine runtime expression by Value UUID, or None.

iter_values
def iter_values(self) -> Iterator[tuple[str, Any]]

Iterate over UUID-keyed emit-time intermediates only.

push_loop_var
def push_loop_var(self, uuid: str, value: Any, display_name: str | None = None) -> None

Bind a loop iteration variable, keyed by Value UUID.

Parameters:

NameTypeDescription
uuidstrloop_var_value.uuid (or per-key/value UUID for ForItemsOperation). Different loops with identical user-chosen names (e.g. nested for i) get distinct UUIDs and therefore never collide here.
valueAnyThe bound iteration value (int / Hamiltonian item / etc.).
display_namestr | NoneReserved for future debug-only use. Currently unused — loop variables are looked up exclusively by UUID, so the display name is never written into the bindings dict. Defaults to None.

Note: this adds a binding to the existing context. Loop unrollers typically copy the parent context first so the binding is local to one iteration; this method does not copy.

restore_state
def restore_state(self, snapshot: dict[str, Any]) -> None

Restore the dict body and slots from snapshot in place.

The object’s identity is preserved (the dict body is cleared and repopulated rather than replaced), so references held elsewhere stay valid.

Parameters:

NameTypeDescription
snapshotdict[str, Any]A snapshot from snapshot_state.

Returns:

None — None.

set_array_data
def set_array_data(self, uuid: str, data: Any, display_name: str | None = None) -> None

Bind array data by ArrayValue.uuid.

Parameters:

NameTypeDescription
uuidstrThe array Value’s UUID.
dataAnyThe bound iterable / sequence / Vector handle.
display_namestr | NoneReserved for debug-only display. It is not used as a binding key.
set_dict_data
def set_dict_data(self, uuid: str, data: Any, display_name: str | None = None) -> None

Bind dict data by DictValue.uuid.

Parameters:

NameTypeDescription
uuidstrThe dict Value’s UUID.
dataAnyThe bound dict / iterable.
display_namestr | NoneReserved for debug-only display. It is not used as a binding key.
set_observable
def set_observable(self, uuid: str, observable: Any, display_name: str | None = None) -> None

Bind a Pauli observable by Value UUID.

Parameters:

NameTypeDescription
uuidstrThe observable Value’s UUID.
observableAnyA qm_o.Hamiltonian (or engine-equivalent).
display_namestr | NoneReserved for debug-only display. It is not used as a binding key.
set_runtime_expr
def set_runtime_expr(self, uuid: str, expr: Any) -> None

Bind an engine runtime expression by Value UUID.

Engines (e.g. Qiskit) call this when they construct a runtime-evaluable expression for a classical predicate that wasn’t compile-time-foldable. _emit_if / _emit_while consult the runtime-expr slot first when resolving conditions.

set_value
def set_value(self, uuid: str, value: Any) -> None

Bind an emit-time-computed intermediate by Value UUID.

Use for BinOp / CompOp / CondOp / NotOp results, merge aliases, and other UUID-identified intermediates.

snapshot_state
def snapshot_state(self) -> dict[str, Any]

Capture the dict body and every semantic slot for later restore.

Used to run a throwaway dry-run emission (ancilla demand counting) against the same context object and then roll it back, so the count run’s intermediate fold results and parameters do not leak into the real emission. Unlike copy this records enough to restore this object in place, preserving its identity for callers that hold a reference to it.

Returns:

dict[str, Any] — dict[str, Any]: A snapshot passable to restore_state.


qamomile.circuit.transpiler.errors

Compilation error classes for Qamomile transpiler.

Overview

ClassDescription
AffineTypeErrorBase class for affine type violations.
CallableDefinitionConflictErrorReport two incompatible definitions claiming one callable symbol.
DependencyErrorError when quantum operation depends on non-parameter classical value.
EmitErrorReport an engine failure to emit one semantic operation.
EntrypointValidationErrorError when a top-level transpilation entrypoint has unsupported I/O.
ExecutionErrorError during program execution.
FrontendTransformErrorError during frontend AST-to-builder lowering.
InliningErrorError during inline pass for callable invocations.
OperandResolutionInfoDetailed information about a single operand that failed to resolve.
QamomileCompileErrorBase class for all Qamomile compilation errors.
QubitAliasErrorSame qubit used multiple times in one operation.
QubitBorrowConflictErrorQubit slot inaccessible because another live handle borrows it.
QubitConsumedErrorQubit handle used after being consumed by a previous operation.
QubitIndexResolutionErrorError when qubit indices cannot be resolved during emission.
QubitRebindErrorQuantum variable reassigned from a different quantum source.
ResolutionFailureReasonCategorizes why qubit index resolution failed.
SeparationErrorError during quantum/classical separation.
TargetCapabilityErrorA program requires a capability the selected target does not declare.
UnreturnedBorrowErrorBorrowed array element not returned before array use.
ValidationErrorError during validation (e.g., non-classical I/O).

Classes

AffineTypeError [source]

class AffineTypeError(QamomileCompileError)

Base class for affine type violations.

Affine types enforce that quantum resources (qubits) are used at most once. This prevents common errors such as reusing a consumed qubit or aliasing.

Constructor
def __init__(
    self,
    message: str,
    handle_name: str | None = None,
    operation_name: str | None = None,
    first_use_location: str | None = None,
)

Initialize an affine-resource violation diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable affine-type failure.
handle_namestr | NoneConsumed or borrowed handle. Defaults to None.
operation_namestr | NoneOperation reporting the violation. Defaults to None.
first_use_locationstr | NoneOriginal consuming use location. Defaults to None.
Attributes

CallableDefinitionConflictError [source]

class CallableDefinitionConflictError(QamomileCompileError)

Report two incompatible definitions claiming one callable symbol.

Parameters:

NameTypeDescription
symbolstrFully qualified callable symbol with conflicting bodies.

Example:

Correct — give independently implemented callables distinct origins
or explicit namespaces::

    configure_composite(left, namespace="example.left")
    configure_composite(right, namespace="example.right")

Incorrect — attaching two different bodies to the same explicit
symbol causes this error during preparation::

    configure_composite(left, namespace="example.shared", name="op")
    configure_composite(right, namespace="example.shared", name="op")
Constructor
def __init__(self, symbol: str) -> None

Initialize a callable-definition collision diagnosis.

Parameters:

NameTypeDescription
symbolstrFully qualified callable symbol with conflicting definitions.
Attributes

DependencyError [source]

class DependencyError(QamomileCompileError)

Error when quantum operation depends on non-parameter classical value.

This error indicates that the program requires JIT compilation which is not yet supported.

Constructor
def __init__(
    self,
    message: str,
    quantum_op: str | None = None,
    classical_value: str | None = None,
)

Initialize a classical-to-quantum dependency diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable dependency failure.
quantum_opstr | NoneDependent quantum operation. Defaults to None.
classical_valuestr | NoneUnsupported classical dependency. Defaults to None.
Attributes

EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return
Constructor
def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

EntrypointValidationError [source]

class EntrypointValidationError(ValidationError)

Error when a top-level transpilation entrypoint has unsupported I/O.


ExecutionError [source]

class ExecutionError(QamomileCompileError)

Error during program execution.


FrontendTransformError [source]

class FrontendTransformError(QamomileCompileError)

Error during frontend AST-to-builder lowering.


InliningError [source]

class InliningError(QamomileCompileError)

Error during inline pass for callable invocations.


OperandResolutionInfo [source]

class OperandResolutionInfo

Detailed information about a single operand that failed to resolve.

Constructor
def __init__(
    self,
    operand_name: str,
    operand_uuid: str,
    is_array_element: bool,
    parent_array_name: str | None,
    element_indices_names: list[str],
    failure_reason: ResolutionFailureReason,
    failure_details: str,
) -> None
Attributes

QamomileCompileError [source]

class QamomileCompileError(Exception)

Base class for all Qamomile compilation errors.


QubitAliasError [source]

class QubitAliasError(AffineTypeError)

Same qubit used multiple times in one operation.

Operations like cx() require distinct qubits for control and target. Using the same qubit in both positions is physically impossible and indicates a programming error.

Example of incorrect code:

q1, q2 = qm.cx(q, q) # ERROR: same qubit as control and target

Correct code:

q1, q2 = qm.cx(control, target) # Use distinct qubits


QubitBorrowConflictError [source]

class QubitBorrowConflictError(AffineTypeError)

Qubit slot inaccessible because another live handle borrows it.

Raised when a qubit slot cannot be accessed because another live handle currently borrows it — a slice view that has not been returned, an outstanding element borrow, or any future borrow form Qamomile may add. The same error is used whether the conflict is discovered while tracing concrete indices or after symbolic slice bounds are resolved during transpilation. Unlike :class:QubitConsumedError, the slot is not destroyed: releasing the borrowing handle (slice assignment, element write-back, etc.) restores access.

Example of incorrect code (overlapping slice views)::

a = q[0:3]      # q[0..2] now borrowed by ``a``
b = q[2:5]      # ERROR: q[2] is still borrowed by ``a``

Correct code::

a = q[0:3]
q[0:3] = a      # return ``a`` first
b = q[2:5]      # now safe

Example of incorrect code (element borrow not returned before borrowing a neighbour)::

q0 = qubits[0]
q0 = qmc.h(q0)
q1 = qubits[1]  # ERROR: q0 is still borrowed

Correct code::

q0 = qubits[0]
q0 = qmc.h(q0)
qubits[0] = q0  # return the element first
q1 = qubits[1]  # now safe

QubitConsumedError [source]

class QubitConsumedError(AffineTypeError)

Qubit handle used after being consumed by a previous operation.

Each qubit handle can only be used once. After a gate operation, you must reassign the result to use the new handle.

Example of incorrect code:

q1 = qm.h(q) q2 = qm.x(q) # ERROR: q was already consumed by h()

Correct code:

q = qm.h(q) # Reassign to capture new handle q = qm.x(q) # Use the reassigned handle


QubitIndexResolutionError [source]

class QubitIndexResolutionError(EmitError)

Error when qubit indices cannot be resolved during emission.

This error provides detailed diagnostic information about why qubit index resolution failed and suggests remediation steps.

Constructor
def __init__(
    self,
    gate_type: str,
    operand_infos: list[OperandResolutionInfo],
    available_bindings_keys: list[str],
    available_qubit_map_keys: list[str],
)

Initialize detailed qubit-index resolution diagnostics.

Parameters:

NameTypeDescription
gate_typestrGate whose operands could not be resolved.
operand_infoslist[OperandResolutionInfo]Per-operand failure details.
available_bindings_keyslist[str]Binding names visible during resolution.
available_qubit_map_keyslist[str]Qubit-map keys visible during resolution.
Attributes

QubitRebindError [source]

class QubitRebindError(AffineTypeError)

Quantum variable reassigned from a different quantum source.

When a quantum variable is reassigned, the RHS must consume the same variable (self-update pattern). Reassigning from a different quantum variable would silently discard the original quantum state.

The check runs at qkernel decoration time as a static AST analysis (see qamomile.circuit.frontend.ast_transform.collect_quantum_rebind_violations) and raises immediately — the wrapped QKernel object is never constructed when a violation is present. The check is run unconditionally for every decorated kernel: kernel-level quantum parameters (Qubit / Vector[Qubit]) seed origins from the signature, and the analyzer’s recognition of internal quantum constructors (qubit(...) / qubit_array(...)) seeds further origins from inside the body so kernels that derive all of their quantum state from internal allocations are also covered.

Branch-internal rebinds (assignments inside an if / for / while body) are NOT flagged at decoration time: compile-time conditional branches legitimately rebind quantum names (the compile-time-if lowering pass selects one branch and discards the other), and the single-pass AST analyzer cannot distinguish compile-time from runtime branches. To keep those compile-time patterns working, branch-internal violations are suppressed.

The runtime side of that gap is closed at the IR layer instead: reject_control_flow_quantum_discard (in qamomile.circuit.transpiler.passes.analyze) classifies branch conditions the same way the compile-time-if lowering pass does and raises this same QubitRebindError for a runtime if cond: q = qm.qubit("fresh") that discards the pre-branch state — and for a for / while body rebind that discards the incoming loop state the same way — while leaving compile-time branch rebinds legal; so a caller catching QubitRebindError (or AffineTypeError) sees the decoration-time and IR-time forms of the violation uniformly. That IR check covers if conditions that transitively derive from a measurement (including expression forms like ~bit); a condition that is neither compile-time-resolvable nor measurement-derived cannot drive runtime branching and keeps its emit-time diagnosis. (AffineValidationPass itself still only enforces “consumed at most once”.) Top-level (non-branch-internal) bypasses continue to raise at decoration time.

Example of incorrect code:

a = qm.h(b) # ERROR: ‘a’ was quantum, now overwritten from ‘b’ a = b # ERROR: ‘a’ was quantum, now overwritten from ‘b’

Correct patterns:

a = qm.h(a) # Self-update (OK) new = qm.h(b) # New binding (OK, ‘new’ wasn’t quantum before)


ResolutionFailureReason [source]

class ResolutionFailureReason(Enum)

Categorizes why qubit index resolution failed.

Attributes

SeparationError [source]

class SeparationError(QamomileCompileError)

Error during quantum/classical separation.


TargetCapabilityError [source]

class TargetCapabilityError(EmitError)

A program requires a capability the selected target does not declare.

Raised by circuit-IR target-legality verification before any engine materialization starts. The message always names the target and the missing capability axis, so the failure reads as a target restriction rather than a Qamomile language error.

Parameters:

NameTypeDescription
messagestrHuman-readable diagnosis naming the target and the missing capability.
targetstr | NoneDeclared target name. Defaults to None.
operationstr | NoneInstruction description that triggered the failure. Defaults to None.

Example:

Correct — bind the runtime parameter before selecting a
concrete-angle-only target::

    transpiler.transpile(kernel, bindings={"theta": 0.5})

Incorrect — keeping ``theta`` symbolic on such a target raises this
error::

    transpiler.transpile(kernel, parameters=["theta"])
Constructor
def __init__(self, message: str, target: str | None = None, operation: str | None = None)

Initialize a target-capability diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable diagnosis naming the target and the missing capability.
targetstr | NoneDeclared target name. Defaults to None.
operationstr | NoneInstruction description that triggered the failure. Defaults to None.
Attributes

UnreturnedBorrowError [source]

class UnreturnedBorrowError(AffineTypeError)

Borrowed array element not returned before array use.

When you borrow an element from a qubit array, you must return it (write it back) before using other elements or the array itself.

Example of incorrect code:

q0 = qubits[0] q0 = qmc.h(q0) q1 = qubits[1] # ERROR: q0 not returned yet

Correct code:

q0 = qubits[0] q0 = qmc.h(q0) qubits[0] = q0 # Return the borrowed element q1 = qubits[1] # Now safe to borrow another


ValidationError [source]

class ValidationError(QamomileCompileError)

Error during validation (e.g., non-classical I/O).

Constructor
def __init__(self, message: str, value_name: str | None = None)

Initialize a validation diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable validation failure.
value_namestr | NoneRelated IR value name. Defaults to None.
Attributes

qamomile.circuit.transpiler.executable

Executable program structure for compiled quantum-classical programs.

Overview

ClassDescription
ClassicalExecutorExecutes classical segments in Python.
CompiledClassicalSegmentA classical segment ready for Python execution.
CompiledExpvalSegmentA compiled expectation value segment with concrete Hamiltonian.
CompiledQuantumSegmentA quantum segment with emitted engine circuit.
ExecutableProgramA fully compiled program ready for execution.
ExecutionContextHolds global state during program execution.
ExecutionErrorError during program execution.
ExpvalJobJob for expectation value computation.
JobSnapshotStore operation metadata and lossless raw execution reconstruction.
ParameterArrayInfoDescribe the shape constraints known for one runtime array.
ParameterContainerKindClassify the public container that owns one engine scalar slot.
ParameterInfoDescribe one scalar slot in a compiled engine parameter ABI.
ParameterMetadataDescribe every scalar slot and runtime array in a compiled segment.
ProgramPlanExecution plan for a hybrid quantum/classical program.
QuantumExecutorAbstract base class for quantum backend execution.
RunJobJob for single execution.
SampleJobJob for sampling execution (multiple shots).

Constants

Classes

ClassicalExecutor [source]

class ClassicalExecutor

Executes classical segments in Python.

Methods
execute
def execute(self, segment: ClassicalSegment, context: ExecutionContext) -> dict[str, Any]

Execute classical operations and return outputs.

Interprets the operations list directly using Python.

Parameters:

NameTypeDescription
segmentClassicalSegmentOrdered classical operations and declared outputs to evaluate.
contextExecutionContextPer-shot quantum and bound input values available to the segment.

Returns:

dict[str, Any] — dict[str, Any]: Computed classical values keyed by result UUID.

Raises:

resolve_value
def resolve_value(self, value: ValueLike, context: ExecutionContext) -> Any

Resolve a typed classical output using the execution interpreter.

Parameters:

NameTypeDescription
valueValueLikeScalar, array, tuple, or dictionary output.
contextExecutionContextRuntime bindings and computed values keyed by their IR identities or public parameter names.

Returns:

Any — Concrete value with tuple and dictionary structure retained.

Raises:


CompiledClassicalSegment [source]

class CompiledClassicalSegment

A classical segment ready for Python execution.

Constructor
def __init__(self, segment: ClassicalSegment) -> None
Attributes

CompiledExpvalSegment [source]

class CompiledExpvalSegment

A compiled expectation value segment with concrete Hamiltonian.

This segment computes <psi|H|psi> where psi is the quantum state from a quantum circuit and H is a qamomile.observable.Hamiltonian.

Constructor
def __init__(
    self,
    segment: ExpvalSegment,
    hamiltonian: 'qm_o.Hamiltonian',
    quantum_segment_index: int = 0,
    result_ref: str = '',
    qubit_map: dict[int, int] = dict(),
) -> None
Attributes

CompiledQuantumSegment [source]

class CompiledQuantumSegment(Generic[T])

A quantum segment with emitted engine circuit.

Constructor
def __init__(
    self,
    segment: QuantumSegment,
    circuit: T,
    qubit_map: QubitMap = dict(),
    clbit_map: ClbitMap = dict(),
    measurement_qubit_map: dict[int, int] = dict(),
    parameter_metadata: ParameterMetadata = ParameterMetadata(),
    implicit_output_qubit_indices: tuple[int, ...] | None = None,
) -> None
Attributes

ExecutableProgram [source]

class ExecutableProgram(Generic[T])

A fully compiled program ready for execution.

Contains compiled quantum, classical, and expectation-value segments. Use sample() for multi-shot execution or run() for single execution.

Example:

executable = transpiler.compile(kernel)

# Sample: multiple shots, returns counts
job = executable.sample(executor, shots=1000)
result = job.result()  # SampleResult with counts

# Run: single shot, returns typed result
job = executable.run(executor)
result = job.result()  # Returns kernel's return type
Constructor
def __init__(
    self,
    plan: ProgramPlan | None = None,
    compiled_quantum: list[CompiledQuantumSegment[T]] = list(),
    compiled_classical: list[CompiledClassicalSegment] = list(),
    compiled_expval: list[CompiledExpvalSegment] = list(),
    output_values: list[ValueLike] = list(),
) -> None
Attributes
Methods
get_circuits
def get_circuits(self) -> list[T]

Get all quantum circuits in execution order.

get_first_circuit
def get_first_circuit(self) -> T | None

Get the first quantum circuit, or None if no quantum segments.

restore
def restore(
    self,
    executor: QuantumExecutor[T],
    snapshot: JobSnapshot,
    bindings: dict[str, Any] | None = None,
) -> SampleJob[Any] | RunJob[Any] | ExpvalJob

Restore saved executions with this program’s typed result ABI.

Snapshots retain provider identifiers, completed local raw values, and ordered execution groups. Legacy flat provider snapshots remain supported. Reuse the same compiled program and pass the original runtime bindings explicitly to reproduce classical pre- and post-processing. Credentials, arbitrary bindings, and Python callables are not saved. Restoration reconnects to remote jobs without resubmitting or waiting for results; local values need no provider restoration support.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine adapter configured with the provider credentials and target used by the original job.
snapshotJobSnapshotSnapshot returned by the original public job’s snapshot() method.
bindingsdict[str, Any] | NoneOriginal runtime parameter bindings. Defaults to None for parameter-free programs.

Returns:

SampleJob[Any] | RunJob[Any] | ExpvalJob — SampleJob[Any] | RunJob[Any] | ExpvalJob: Restored lazy job with the same typed public result conversion as a new execution.

Raises:

Example:

>>> original = executable.sample(executor, shots=1000)
>>> snapshot = original.snapshot()
>>> restored = executable.restore(executor, snapshot)
>>> restored.result()
run
def run(
    self,
    executor: QuantumExecutor[T],
    bindings: dict[str, Any] | None = None,
    *,
    estimation: EstimationAccuracy | None = None,
) -> RunJob[Any] | ExpvalJob

Submit one execution and return its lazy result job.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine-specific quantum executor.
bindingsdict[str, Any] | NoneParameter bindings. Supports three formats: - Vector: {“gammas”: [0.1, 0.2], “betas”: [0.3, 0.4]} - Dict parameter: {“coeffs”: {0: 0.1, (0, 1): 0.2}}, decomposed per key onto the emitted parameters - Indexed: {“gammas[0]”: 0.1, “coeffs[(0, 1)]”: 0.2}
estimationEstimationAccuracy | NoneOptional per-execution expectation accuracy policy. Defaults to the executor’s configured behavior.

Returns:

RunJob[Any] | ExpvalJob — RunJob[Any] | ExpvalJob: A RunJob that resolves to the kernel’s return type, or an ExpvalJob when the program contains an expectation-value computation.

Raises:

Example:

job = executable.run(executor, bindings={"gamma": [0.5]})
result = job.result()
print(result)  # 0.25 (for QFixed) or (0, 1) (for bits)
sample
def sample(
    self,
    executor: QuantumExecutor[T],
    shots: int = 1024,
    bindings: dict[str, Any] | None = None,
) -> SampleJob[Any]

Submit a multi-shot execution and return its lazy job.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine-specific quantum executor.
shotsintNumber of shots to run.
bindingsdict[str, Any] | NoneParameter bindings. Supports three formats: - Vector: {“gammas”: [0.1, 0.2], “betas”: [0.3, 0.4]} - Dict parameter: {“coeffs”: {0: 0.1, (0, 1): 0.2}}, decomposed per key onto the emitted parameters - Indexed: {“gammas[0]”: 0.1, “coeffs[(0, 1)]”: 0.2}

Returns:

SampleJob[Any] — SampleJob[Any]: A job that resolves to a SampleResult with the per-bitstring counts.

Raises:

Example:

job = executable.sample(executor, shots=1000, bindings={"gamma": [0.5]})
result = job.result()
print(result.results)  # [(0.25, 500), (0.75, 500)]

ExecutionContext [source]

class ExecutionContext

Holds global state during program execution.

Constructor
def __init__(self, initial_bindings: dict[str, Any] | None = None)
Methods
copy
def copy(self) -> 'ExecutionContext'

Clone the execution context.

get
def get(self, key: str) -> Any
get_many
def get_many(self, keys: list[str]) -> dict[str, Any]
has
def has(self, key: str) -> bool
set
def set(self, key: str, value: Any) -> None
update
def update(self, values: dict[str, Any]) -> None

ExecutionError [source]

class ExecutionError(QamomileCompileError)

Error during program execution.


ExpvalJob [source]

class ExpvalJob(Job[float])

Job for expectation value computation.

Returns a single float representing <psi|H|psi>.

Constructor
def __init__(self, exp_val: float | ExecutionHandle[float]) -> None

Initialize expval job.

Parameters:

NameTypeDescription
exp_valfloat | ExecutionHandle[float]Completed value or deferred expectation execution.
Methods
result
def result(self, timeout: float | None = None) -> float

Wait for and return the expectation value.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

float — Expectation value.

result_async
def result_async(self, timeout: float | None = None) -> float

Wait asynchronously for and return the expectation value.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

float — Expectation value.


JobSnapshot [source]

class JobSnapshot

Store operation metadata and lossless raw execution reconstruction.

Runtime bindings are intentionally excluded. They can contain arbitrary application data, so callers supply them again to :meth:ExecutableProgram.restore instead of persisting them implicitly.

Parameters:

NameTypeDescription
kindJobKindPublic operation that created the job.
executionstuple[ExecutionReference, ...]Ordered provider reference inventory. Empty for entirely local structured executions. For legacy snapshots, these references also specify the result layout.
shotsint | NoneSampling shot count. Required for sample jobs and absent for run jobs.
executionExecutionSnapshot | NoneOrdered remote/local execution tree. None denotes the legacy flat-reference format. When present, executions must exactly match its remote leaves.

Raises:

Constructor
def __init__(
    self,
    kind: JobKind,
    executions: tuple[ExecutionReference, ...],
    shots: int | None = None,
    execution: ExecutionSnapshot | None = None,
) -> None
Attributes
Methods
from_dict
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> JobSnapshot

Reconstruct a validated snapshot from JSON-compatible data.

Parameters:

NameTypeDescription
dataMapping[str, Any]Mapping produced by :meth:to_dict.

Returns:

JobSnapshot — Validated typed-job restoration snapshot.

Raises:

to_dict
def to_dict(self) -> dict[str, Any]

Convert the snapshot to JSON-compatible data.

Returns:

dict[str, Any] — dict[str, Any]: Version 2 operation metadata and execution tree, or the original legacy format for a flat-reference snapshot.

Raises:


ParameterArrayInfo [source]

class ParameterArrayInfo

Describe the shape constraints known for one runtime array.

None dimensions remain open because the frontend annotation records rank but does not always provide a concrete runtime extent. A dimension becomes concrete only when emitted scalar slots establish a contiguous ABI prefix with at least two elements.

Parameters:

NameTypeDescription
namestrRoot runtime parameter name.
rankintNumber of array dimensions.
expected_shapetuple[int | None, ...]Exact known dimensions and None for dimensions whose extent remains open.
Constructor
def __init__(self, name: str, rank: int, expected_shape: tuple[int | None, ...]) -> None
Attributes

ParameterContainerKind [source]

class ParameterContainerKind(enum.StrEnum)

Classify the public container that owns one engine scalar slot.

Attributes

ParameterInfo [source]

class ParameterInfo

Describe one scalar slot in a compiled engine parameter ABI.

Parameters:

NameTypeDescription
namestrFull scalar key, for example gammas[0].
array_namestrRoot parameter name, for example gammas.
indexint | NoneBackward-compatible one-dimensional index, or None for scalars and higher-rank elements.
engine_paramAnyEngine-specific parameter object.
source_refstr | NoneIR value UUID providing the runtime value. Defaults to None.
indicestuple[int, ...] | NoneComplete array index tuple, or None for a scalar. Defaults to None.
container_kindParameterContainerKindPublic parameter container kind. Defaults to SCALAR.
Constructor
def __init__(
    self,
    name: str,
    array_name: str,
    index: int | None,
    engine_param: Any,
    source_ref: str | None = None,
    indices: tuple[int, ...] | None = None,
    container_kind: ParameterContainerKind = ParameterContainerKind.SCALAR,
) -> None
Attributes

ParameterMetadata [source]

class ParameterMetadata

Describe every scalar slot and runtime array in a compiled segment.

Parameters:

NameTypeDescription
parameterslist[ParameterInfo]Ordered scalar engine slots. Defaults to an empty list.
arraysdict[str, ParameterArrayInfo]Explicit runtime-array ABI descriptors keyed by root name. Defaults to descriptors derived from parameters for backward compatibility.
Constructor
def __init__(
    self,
    parameters: list[ParameterInfo] = list(),
    arrays: dict[str, ParameterArrayInfo] = dict(),
) -> None
Attributes
Methods
get_array_names
def get_array_names(self) -> set[str]

Return unique scalar and array root names.

Returns:

set[str] — set[str]: Root name for every emitted parameter.

get_ordered_params
def get_ordered_params(self) -> list[Any]

Return engine parameter objects in ABI definition order.

Returns:

list[Any] — list[Any]: Engine-specific parameter objects.

get_param_by_name
def get_param_by_name(self, name: str) -> ParameterInfo | None

Find one scalar slot by its full emitted key.

Parameters:

NameTypeDescription
namestrFull engine parameter key.

Returns:

ParameterInfo | None — ParameterInfo | None: Matching slot, or None when absent.

merge
@classmethod
def merge(cls, metadata: Sequence[ParameterMetadata]) -> ParameterMetadata

Merge parameter manifests from multiple quantum segments.

Parameters:

NameTypeDescription
metadataSequence[ParameterMetadata]Segment manifests in execution order.

Returns:

ParameterMetadata — Combined manifest with first-seen scalar slot ordering and array descriptors derived across all segments.

to_binding_dict
def to_binding_dict(self, bindings: Mapping[str, Any]) -> dict[Any, Any]

Map indexed user bindings to engine parameter objects.

Parameters:

NameTypeDescription
bindingsMapping[str, Any]Scalar values keyed by full emitted parameter name.

Returns:

dict[Any, Any] — dict[Any, Any]: Engine parameter objects mapped to bound values.

validate_array_shapes
def validate_array_shapes(self, bindings: Mapping[str, Any] | None) -> None

Validate user array rank and every concrete ABI dimension.

Parameters:

NameTypeDescription
bindingsMapping[str, Any] | NoneRaw public bindings before scalar flattening. None means no validation is needed.

Raises:

validate_required_bindings
def validate_required_bindings(self, indexed_bindings: Mapping[str, Any]) -> None

Reject missing scalar slots in an indexed binding map.

Parameters:

NameTypeDescription
indexed_bindingsMapping[str, Any]Flattened user bindings.

Raises:


ProgramPlan [source]

class ProgramPlan

Execution plan for a hybrid quantum/classical program.

Structure:

This plan enforces Qamomile’s current execution model: all quantum operations must be in a single quantum circuit.

Constructor
def __init__(
    self,
    steps: list[ProgramStep] = list(),
    abi: ProgramABI = ProgramABI(),
    boundaries: list[HybridBoundary] = list(),
    parameters: dict[str, Value] = dict(),
) -> None
Attributes

QuantumExecutor [source]

class QuantumExecutor(ABC, Generic[T])

Abstract base class for quantum backend execution.

To implement a custom executor:

  1. execute() [Required] Execute circuit and return bitstring counts as dict[str, int]. Keys are bitstrings in big-endian format (e.g., “011” means q2=0, q1=1, q0=1).

  2. bind_parameters() [Optional] Bind parameter values to parametric circuits. Override if your executor supports parametric circuits (e.g., QAOA variational circuits). Use ParameterMetadata.to_binding_dict() for easy conversion.

  3. estimate() [Optional] Compute expectation values <psi|H|psi>. Override if your executor supports estimation primitives (e.g., Qiskit Estimator, QURI Parts).

Example (Minimal): class MyExecutor(QuantumExecutor[QuantumCircuit]): def init(self): from qiskit_aer import AerSimulator self.backend = AerSimulator()

    def execute(self, circuit, shots):
        from qiskit import transpile
        if circuit.num_clbits == 0:
            circuit = circuit.copy()
            circuit.measure_all()
        transpiled = transpile(circuit, self.backend)
        return self.backend.run(transpiled, shots=shots).result().get_counts()

Example (With Parameter Binding): def bind_parameters(self, circuit, bindings, metadata): # metadata.to_binding_dict() converts indexed names to engine params return circuit.assign_parameters(metadata.to_binding_dict(bindings))

Attributes
Methods
bind_invocation
def bind_invocation(self, invocation: CircuitInvocation[T]) -> T

Bind one invocation for a backend without native input submission.

Parameters:

NameTypeDescription
invocationCircuitInvocation[T]Circuit, flattened bindings, and engine parameter metadata.

Returns:

T — Bound circuit, or the original circuit when it has no runtime parameters.

bind_parameters
def bind_parameters(
    self,
    circuit: T,
    bindings: dict[str, Any],
    parameter_metadata: ParameterMetadata,
) -> T

Bind parameter values to the circuit.

Default implementation returns the circuit unchanged. Override for backends that support parametric circuits.

Parameters:

NameTypeDescription
circuitTThe parameterized circuit
bindingsdict[str, Any]Dict mapping parameter names (indexed format) to values. e.g., {“gammas[0]”: 0.1, “gammas[1]”: 0.2}
parameter_metadataParameterMetadataMetadata about circuit parameters

Returns:

T — New circuit with parameters bound

estimate
def estimate(
    self,
    circuit: T,
    hamiltonian: 'qm_o.Hamiltonian',
    params: Sequence[float] | None = None,
) -> float

Estimate the expectation value of a Hamiltonian.

This method computes <psi|H|psi> where psi is the quantum state prepared by the circuit and H is the Hamiltonian.

Backends can override this method to provide optimized implementations using their native estimator primitives.

Parameters:

NameTypeDescription
circuitTThe quantum circuit (state preparation ansatz)
hamiltonian'qm_o.Hamiltonian'The qamomile.observable.Hamiltonian to measure
paramsSequence[float] | NoneOptional parameter values for parametric circuits

Returns:

float — The estimated expectation value

Raises:

execute
def execute(self, circuit: T, shots: int) -> dict[str, int]

Execute the circuit and return bitstring counts.

Parameters:

NameTypeDescription
circuitTThe quantum circuit to execute
shotsintNumber of measurement shots

Returns:

dict[str, int] — Dictionary mapping bitstrings to counts. dict[str, int] — {“00”: 512, “11”: 512}

restore
def restore(self, reference: ExecutionReference) -> ExecutionHandle[Any]

Restore a remote execution from a secret-free reference.

Parameters:

NameTypeDescription
referenceExecutionReferenceProvider execution reference.

Returns:

ExecutionHandle[Any] — ExecutionHandle[Any]: Restored provider-backed handle.

Raises:

submit_estimate
def submit_estimate(self, request: EstimateRequest[T]) -> ExecutionHandle[float]

Submit an expectation request through the synchronous path.

Parameters:

NameTypeDescription
requestEstimateRequest[T]Circuit, Hamiltonian, and optional accuracy policy.

Returns:

ExecutionHandle[float] — ExecutionHandle[float]: Completed compatibility handle.

Raises:

submit_estimates
def submit_estimates(
    self,
    requests: Sequence[EstimateRequest[T]],
) -> ExecutionHandle[tuple[float, ...]]

Submit an ordered collection of expectation requests.

Parameters:

NameTypeDescription
requestsSequence[EstimateRequest[T]]Expectation requests.

Returns:

ExecutionHandle[tuple[float, ...]] — ExecutionHandle[tuple[float, ...]]: Composite result handle in request order.

submit_sample
def submit_sample(self, request: SampleRequest[T]) -> ExecutionHandle[dict[str, int]]

Submit a sampling request through the synchronous compatibility path.

Remote executors should override this method and return immediately with a provider-backed handle. Existing synchronous executors inherit this implementation unchanged.

Parameters:

NameTypeDescription
requestSampleRequest[T]Circuit invocation and shot count.

Returns:

ExecutionHandle[dict[str, int]] — ExecutionHandle[dict[str, int]]: Completed compatibility handle.

submit_samples
def submit_samples(
    self,
    requests: Sequence[SampleRequest[T]],
) -> ExecutionHandle[tuple[dict[str, int], ...]]

Submit an ordered collection of sampling requests.

Backends with native batch or parameter-sweep support should override this method. The default preserves ordering with individual requests.

Parameters:

NameTypeDescription
requestsSequence[SampleRequest[T]]Sampling requests.

Returns:

ExecutionHandle[tuple[dict[str, int], ...]] — ExecutionHandle[tuple[dict[str, int], ...]]: Composite result handle preserving request order.


RunJob [source]

class RunJob(Job[T], Generic[T])

Job for single execution.

Returns a single result value matching the kernel’s return type.

Constructor
def __init__(
    self,
    raw_counts: dict[str, int] | ExecutionHandle[dict[str, int]] | None,
    result_converter: Callable[[str], T] | None,
    *,
    value_handle: ExecutionHandle[T] | None = None,
) -> None

Initialize run job.

Parameters:

NameTypeDescription
raw_countsdict[str, int] | ExecutionHandle[dict[str, int]] | NoneCounts or deferred counts. May be None with value_handle.
result_converterCallable[[str], T] | NoneFunction converting one bitstring. May be None with value_handle.
value_handleExecutionHandle[T] | NoneHandle already producing the final public value. Defaults to None.

Raises:

Methods
from_handle
@classmethod
def from_handle(cls, handle: ExecutionHandle[T]) -> RunJob[T]

Create a run job whose handle already returns the public value.

Parameters:

NameTypeDescription
handleExecutionHandle[T]Final-value execution handle.

Returns:

RunJob[T] — RunJob[T]: Public run job delegating to handle.

result
def result(self, timeout: float | None = None) -> T

Wait for and return the single public result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

T — Public kernel return value.

result_async
def result_async(self, timeout: float | None = None) -> T

Wait asynchronously for the single public result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

T — Public kernel return value.


SampleJob [source]

class SampleJob(Job[SampleResult[T]], Generic[T])

Job for sampling execution (multiple shots).

Returns a SampleResult containing counts for each unique result.

Constructor
def __init__(
    self,
    raw_counts: dict[str, int] | ExecutionHandle[dict[str, int]],
    result_converter: Callable[[dict[str, int]], list[tuple[T, int]]],
    shots: int,
) -> None

Initialize sample job.

Parameters:

NameTypeDescription
raw_countsdict[str, int] | ExecutionHandle[dict[str, int]]Counts or a deferred counts execution.
result_converterCallable[[dict[str, int]], list[tuple[T, int]]]Function converting raw counts to typed values.
shotsintNumber of requested shots.
Methods
result
def result(self, timeout: float | None = None) -> SampleResult[T]

Wait for and return the typed sample result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

SampleResult[T] — SampleResult[T]: Aggregated typed result.

result_async
def result_async(self, timeout: float | None = None) -> SampleResult[T]

Wait asynchronously for the typed sample result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

SampleResult[T] — SampleResult[T]: Aggregated typed result.


qamomile.circuit.transpiler.execution_capability

Describe engine execution features without exposing provider SDK types.

Overview

ClassDescription
ExactRequest an analytic expectation value without shot noise.
ExecutionCapabilitiesDeclare the execution features implemented by one executor.
ShotBasedRequest a shot-based expectation value.
TargetPrecisionRequest an expectation value at a provider target precision.

Classes

Exact [source]

class Exact

Request an analytic expectation value without shot noise.

Constructor
def __init__(self) -> None

ExecutionCapabilities [source]

class ExecutionCapabilities

Declare the execution features implemented by one executor.

Parameters:

NameTypeDescription
supports_async_samplingboolWhether sampling submission returns before provider execution completes. Defaults to False.
supports_async_estimationboolWhether expectation submission returns before provider execution completes. Defaults to False.
supports_estimationboolWhether expectation-value execution is implemented. Defaults to False.
supports_cancellationboolWhether provider-backed handles can request cancellation. Defaults to False.
supports_restorationboolWhether execution references can recreate provider-backed handles. Defaults to False.
supports_native_batchboolWhether multiple logical requests can be submitted through one provider-native batch or job. Defaults to False.
supports_native_parameter_inputsboolWhether runtime values remain separate from emitted circuits during provider submission. Defaults to False.
estimation_accuracyfrozenset[EstimationPolicyType]Explicit per-request accuracy policies accepted by the executor. An empty set means only executor-configured estimation behavior is available.

Raises:

Constructor
def __init__(
    self,
    supports_async_sampling: bool = False,
    supports_async_estimation: bool = False,
    supports_estimation: bool = False,
    supports_cancellation: bool = False,
    supports_restoration: bool = False,
    supports_native_batch: bool = False,
    supports_native_parameter_inputs: bool = False,
    estimation_accuracy: frozenset[EstimationPolicyType] = frozenset(),
) -> None
Attributes

ShotBased [source]

class ShotBased

Request a shot-based expectation value.

Parameters:

NameTypeDescription
shotsintPositive number of measurement shots.

Raises:

Constructor
def __init__(self, shots: int) -> None
Attributes

TargetPrecision [source]

class TargetPrecision

Request an expectation value at a provider target precision.

Parameters:

NameTypeDescription
precisionfloatPositive absolute target precision.

Raises:

Constructor
def __init__(self, precision: float) -> None
Attributes

qamomile.circuit.transpiler.execution_context

Execution context for quantum-classical program execution.

Overview

ClassDescription
ExecutionContextHolds global state during program execution.

Classes

ExecutionContext [source]

class ExecutionContext

Holds global state during program execution.

Constructor
def __init__(self, initial_bindings: dict[str, Any] | None = None)
Methods
copy
def copy(self) -> 'ExecutionContext'

Clone the execution context.

get
def get(self, key: str) -> Any
get_many
def get_many(self, keys: list[str]) -> dict[str, Any]
has
def has(self, key: str) -> bool
set
def set(self, key: str, value: Any) -> None
update
def update(self, values: dict[str, Any]) -> None

qamomile.circuit.transpiler.execution_handle

Represent local and remote quantum execution lifecycles.

Overview

ClassDescription
CompletedExecutionHandleWrap an already available result for synchronous executors.
CompositeExecutionHandleAggregate several independently submitted executions.
ExecutionHandleExpose an engine execution without forcing immediate result retrieval.
ExecutionReferenceStore secret-free identifiers needed to restore remote execution.
ExecutionSnapshotStore a remote leaf, a local value, or an ordered execution group.
ExecutionSnapshotKindIdentify the reconstruction contract of an execution snapshot node.
JobStatusDescribe a provider-independent execution state.
MappedExecutionHandleLazily transform another execution handle’s result.

Classes

CompletedExecutionHandle [source]

class CompletedExecutionHandle(ExecutionHandle[ResultT])

Wrap an already available result for synchronous executors.

Parameters:

NameTypeDescription
valueResultTCompleted execution value.
Constructor
def __init__(self, value: ResultT) -> None

Initialize an immediately completed execution.

Parameters:

NameTypeDescription
valueResultTCompleted execution value.
Methods
result
def result(self, timeout: float | None = None) -> ResultT

Return the completed value without waiting.

Parameters:

NameTypeDescription
timeoutfloat | NoneIgnored compatibility timeout.

Returns:

ResultT — Stored execution value.

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture the already available raw result without waiting.

Returns:

ExecutionSnapshot — Owned, type-preserving local value.

Raises:

status
def status(self) -> JobStatus

Return the completed status.

Returns:

JobStatus — Always :attr:JobStatus.COMPLETED.


CompositeExecutionHandle [source]

class CompositeExecutionHandle(ExecutionHandle[tuple[ResultT, ...]])

Aggregate several independently submitted executions.

Parameters:

NameTypeDescription
handlesSequence[ExecutionHandle[ResultT]]Child executions in stable result order.
Constructor
def __init__(self, handles: Sequence[ExecutionHandle[ResultT]]) -> None

Initialize an ordered execution aggregate.

Parameters:

NameTypeDescription
handlesSequence[ExecutionHandle[ResultT]]Child executions.
Attributes
Methods
cancel
def cancel(self) -> None

Attempt cancellation of every child not known to be terminal.

A status lookup failure leaves the child’s state unknown, so cancellation is still attempted. Failures are reported together after all children have been visited, retaining the original exceptions and tracebacks.

Raises:

metadata
def metadata(self) -> Mapping[str, Any]

Return metadata grouped by child index.

Returns:

Mapping[str, Any] — Mapping[str, Any]: Child metadata sequence.

raw_status
def raw_status(self) -> object

Return every child provider status.

Returns:

object — Tuple of child raw statuses.

references
def references(self) -> tuple[ExecutionReference, ...]

Return the legacy one-reference-per-child view.

This flat view cannot preserve child boundaries when a child exposes zero or multiple references. Use :meth:snapshot to retain local results and nested groups in their original positions.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Ordered child references, or an empty tuple when any child does not expose exactly one.

result
def result(self, timeout: float | None = None) -> tuple[ResultT, ...]

Return all child results in submission order.

Parameters:

NameTypeDescription
timeoutfloat | NoneTotal local wait budget in seconds.

Returns:

tuple[ResultT, ...] — tuple[ResultT, ...]: Ordered child results.

Raises:

result_async
def result_async(self, timeout: float | None = None) -> tuple[ResultT, ...]

Return all child results asynchronously.

Parameters:

NameTypeDescription
timeoutfloat | NoneTotal local wait budget in seconds.

Returns:

tuple[ResultT, ...] — tuple[ResultT, ...]: Ordered child results.

Raises:

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture all children with their original tuple boundaries.

Returns:

ExecutionSnapshot — Ordered nested execution structure.

Raises:

status
def status(self) -> JobStatus

Aggregate child statuses without hiding partial completion.

Returns:

JobStatus — Aggregate execution status.


ExecutionHandle [source]

class ExecutionHandle(ABC, Generic[ResultT])

Expose an engine execution without forcing immediate result retrieval.

Attributes
Methods
cancel
def cancel(self) -> None

Request best-effort cancellation.

Cancellation is intentionally not reported as a boolean because providers may accept a request after execution has already started. Call :meth:status to observe the eventual state.

metadata
def metadata(self) -> Mapping[str, Any]

Return optional provider execution metadata.

Returns:

Mapping[str, Any] — Mapping[str, Any]: Provider metadata such as timestamps or usage.

raw_status
def raw_status(self) -> object

Return provider-specific status information.

Returns:

object — Provider status value, or the normalized status when no richer value exists.

references
def references(self) -> tuple[ExecutionReference, ...]

Return serializable remote execution references.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Secret-free provider references.

result
def result(self, timeout: float | None = None) -> ResultT

Wait for and return the engine-neutral raw result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds. None delegates the wait policy to the provider.

Returns:

ResultT — Raw result normalized by the engine executor.

Raises:

result_async
def result_async(self, timeout: float | None = None) -> ResultT

Wait asynchronously for the engine-neutral raw result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds. Defaults to provider behavior when None.

Returns:

ResultT — Raw result normalized by the engine executor.

Raises:

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture one remote execution without fetching its result.

Adapters exposing several logical references must override this method with an explicit reconstruction structure. A provider reference may itself contain multiple physical job IDs.

Returns:

ExecutionSnapshot — One opaque provider execution.

Raises:

status
def status(self) -> JobStatus

Return the current provider-independent execution status.

Returns:

JobStatus — Current normalized status.


ExecutionReference [source]

class ExecutionReference

Store secret-free identifiers needed to restore remote execution.

Parameters:

NameTypeDescription
providerstrStable provider or adapter name.
job_idstuple[str, ...]One or more provider job identifiers.
targetstr | NoneProvider target or device identifier. Defaults to None.
group_idstr | NoneSession, batch, program, or parent identifier. Defaults to None.
contextMapping[str, str]Additional non-secret identifiers needed to restore the job. Defaults to an empty mapping.

Raises:

Constructor
def __init__(
    self,
    provider: str,
    job_ids: tuple[str, ...],
    target: str | None = None,
    group_id: str | None = None,
    context: Mapping[str, str] = dict(),
) -> None
Attributes
Methods
from_dict
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionReference

Reconstruct a provider reference from JSON-compatible data.

Parameters:

NameTypeDescription
dataMapping[str, Any]Mapping produced by :meth:to_dict.

Returns:

ExecutionReference — Validated provider execution reference.

Raises:

to_dict
def to_dict(self) -> dict[str, Any]

Convert the provider reference to JSON-compatible data.

Returns:

dict[str, Any] — dict[str, Any]: Provider identifiers and decoding context without credentials or SDK objects.


ExecutionSnapshot [source]

class ExecutionSnapshot

Store a remote leaf, a local value, or an ordered execution group.

Provider leaves may identify several physical jobs or produce native batch results. Composite children retain their result boundaries independently of the number of provider identifiers. Local values contain raw engine-neutral results, before the executable applies its public result conversion. Trees and local values support at most 100 levels of nesting.

Parameters:

NameTypeDescription
kindstr | ExecutionSnapshotKindOne of remote, local, or composite, normalized to an enum member.
referenceExecutionReference | NoneRequired only for remote leaves.
valueAnySupported native result for local leaves. Defaults to None.
childrentuple[ExecutionSnapshot, ...]Ordered composite children. Defaults to an empty tuple.

Raises:

Constructor
def __init__(
    self,
    kind: str | ExecutionSnapshotKind,
    reference: ExecutionReference | None = None,
    value: Any = None,
    children: tuple[ExecutionSnapshot, ...] = (),
) -> None
Attributes
Methods
from_dict
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionSnapshot

Reconstruct an execution tree with strict node and value validation.

Parameters:

NameTypeDescription
dataMapping[str, Any]Mapping produced by :meth:to_dict.

Returns:

ExecutionSnapshot — Validated execution structure.

Raises:

references
def references(self) -> tuple[ExecutionReference, ...]

Collect provider leaves in order without discarding tree structure.

This list supports diagnostics; restoration uses the complete tree.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Detached remote references in order.

Raises:

restore
def restore(
    self,
    restore_reference: Callable[[ExecutionReference], ExecutionHandle[Any]],
) -> ExecutionHandle[Any]

Reattach remote leaves and rebuild local values and ordered groups.

The callback must reattach an existing provider execution. This method neither retrieves remote results nor submits any execution.

Parameters:

NameTypeDescription
restore_referenceCallable[[ExecutionReference], ExecutionHandle[Any]]Provider-specific callback for one complete remote leaf.

Returns:

ExecutionHandle[Any] — ExecutionHandle[Any]: Reconstructed raw execution lifecycle.

Raises:

to_dict
def to_dict(self) -> dict[str, Any]

Serialize the execution tree and type-preserving local values.

Returns:

dict[str, Any] — dict[str, Any]: JSON-compatible execution tree.

Raises:


ExecutionSnapshotKind [source]

class ExecutionSnapshotKind(StrEnum)

Identify the reconstruction contract of an execution snapshot node.

Attributes

JobStatus [source]

class JobStatus(Enum)

Describe a provider-independent execution state.

The numeric values of the original four states remain stable for serialization compatibility.

Attributes

MappedExecutionHandle [source]

class MappedExecutionHandle(ExecutionHandle[MappedT], Generic[ResultT, MappedT])

Lazily transform another execution handle’s result.

Parameters:

NameTypeDescription
sourceExecutionHandle[ResultT]Underlying execution handle.
transformCallable[[ResultT], MappedT]Result transformation.
snapshot_sourceboolWhether the owning executable reconstructs this transformation when restoring the source. Defaults to False.
Constructor
def __init__(
    self,
    source: ExecutionHandle[ResultT],
    transform: Callable[[ResultT], MappedT],
    *,
    snapshot_source: bool = False,
) -> None

Initialize a lazy mapped execution.

Parameters:

NameTypeDescription
sourceExecutionHandle[ResultT]Underlying execution handle.
transformCallable[[ResultT], MappedT]Result transformation.
snapshot_sourceboolAllow source snapshots only when the owner rebuilds the transformation on restore. Defaults to False.
Attributes
Methods
cancel
def cancel(self) -> None

Forward a cancellation request to the source execution.

metadata
def metadata(self) -> Mapping[str, Any]

Return source execution metadata.

Returns:

Mapping[str, Any] — Mapping[str, Any]: Source metadata.

raw_status
def raw_status(self) -> object

Return the source provider status.

Returns:

object — Provider-specific source status.

references
def references(self) -> tuple[ExecutionReference, ...]

Return source execution references.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Source references.

result
def result(self, timeout: float | None = None) -> MappedT

Retrieve and transform the source result once.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

MappedT — Cached transformed result.

Raises:

result_async
def result_async(self, timeout: float | None = None) -> MappedT

Retrieve and transform the source result asynchronously.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

MappedT — Cached transformed result.

Raises:

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture a source whose mapping is rebuilt by its owning executable.

Python callables are never serialized. Arbitrary mappings must supply an adapter-specific restoration recipe instead of losing conversion.

Returns:

ExecutionSnapshot — Source reconstruction structure.

Raises:

status
def status(self) -> JobStatus

Return the source execution status.

Returns:

JobStatus — Current mapped execution status.


qamomile.circuit.transpiler.execution_request

Describe engine-neutral quantum execution requests.

Overview

ClassDescription
CircuitInvocationKeep an emitted circuit and runtime parameter values together.
EstimateRequestDescribe one Hamiltonian expectation execution.
ExactRequest an analytic expectation value without shot noise.
ParameterMetadataDescribe every scalar slot and runtime array in a compiled segment.
SampleRequestDescribe one sampling execution.
ShotBasedRequest a shot-based expectation value.
TargetPrecisionRequest an expectation value at a provider target precision.

Constants

Classes

CircuitInvocation [source]

class CircuitInvocation(Generic[CircuitT])

Keep an emitted circuit and runtime parameter values together.

Engines may bind the values into a new circuit or submit them through a native parameter-input API. Keeping both forms available preserves native parameter sweeps and provider-side compilation caches.

Parameters:

NameTypeDescription
circuitCircuitTEmitted engine circuit or kernel artifact.
bindingsMapping[str, Any]Flattened Qamomile runtime bindings.
parameter_metadataParameterMetadataMapping from public parameter names to engine parameter objects.
Constructor
def __init__(
    self,
    circuit: CircuitT,
    bindings: Mapping[str, Any],
    parameter_metadata: ParameterMetadata,
) -> None
Attributes

EstimateRequest [source]

class EstimateRequest(Generic[CircuitT])

Describe one Hamiltonian expectation execution.

Parameters:

NameTypeDescription
invocationCircuitInvocation[CircuitT]Circuit and runtime inputs.
hamiltonianqm_o.HamiltonianObservable to evaluate.
accuracyEstimationAccuracy | NoneExplicit accuracy policy. None uses the executor’s configured default.
Constructor
def __init__(
    self,
    invocation: CircuitInvocation[CircuitT],
    hamiltonian: qm_o.Hamiltonian,
    accuracy: EstimationAccuracy | None = None,
) -> None
Attributes

Exact [source]

class Exact

Request an analytic expectation value without shot noise.

Constructor
def __init__(self) -> None

ParameterMetadata [source]

class ParameterMetadata

Describe every scalar slot and runtime array in a compiled segment.

Parameters:

NameTypeDescription
parameterslist[ParameterInfo]Ordered scalar engine slots. Defaults to an empty list.
arraysdict[str, ParameterArrayInfo]Explicit runtime-array ABI descriptors keyed by root name. Defaults to descriptors derived from parameters for backward compatibility.
Constructor
def __init__(
    self,
    parameters: list[ParameterInfo] = list(),
    arrays: dict[str, ParameterArrayInfo] = dict(),
) -> None
Attributes
Methods
get_array_names
def get_array_names(self) -> set[str]

Return unique scalar and array root names.

Returns:

set[str] — set[str]: Root name for every emitted parameter.

get_ordered_params
def get_ordered_params(self) -> list[Any]

Return engine parameter objects in ABI definition order.

Returns:

list[Any] — list[Any]: Engine-specific parameter objects.

get_param_by_name
def get_param_by_name(self, name: str) -> ParameterInfo | None

Find one scalar slot by its full emitted key.

Parameters:

NameTypeDescription
namestrFull engine parameter key.

Returns:

ParameterInfo | None — ParameterInfo | None: Matching slot, or None when absent.

merge
@classmethod
def merge(cls, metadata: Sequence[ParameterMetadata]) -> ParameterMetadata

Merge parameter manifests from multiple quantum segments.

Parameters:

NameTypeDescription
metadataSequence[ParameterMetadata]Segment manifests in execution order.

Returns:

ParameterMetadata — Combined manifest with first-seen scalar slot ordering and array descriptors derived across all segments.

to_binding_dict
def to_binding_dict(self, bindings: Mapping[str, Any]) -> dict[Any, Any]

Map indexed user bindings to engine parameter objects.

Parameters:

NameTypeDescription
bindingsMapping[str, Any]Scalar values keyed by full emitted parameter name.

Returns:

dict[Any, Any] — dict[Any, Any]: Engine parameter objects mapped to bound values.

validate_array_shapes
def validate_array_shapes(self, bindings: Mapping[str, Any] | None) -> None

Validate user array rank and every concrete ABI dimension.

Parameters:

NameTypeDescription
bindingsMapping[str, Any] | NoneRaw public bindings before scalar flattening. None means no validation is needed.

Raises:

validate_required_bindings
def validate_required_bindings(self, indexed_bindings: Mapping[str, Any]) -> None

Reject missing scalar slots in an indexed binding map.

Parameters:

NameTypeDescription
indexed_bindingsMapping[str, Any]Flattened user bindings.

Raises:


SampleRequest [source]

class SampleRequest(Generic[CircuitT])

Describe one sampling execution.

Parameters:

NameTypeDescription
invocationCircuitInvocation[CircuitT]Circuit and runtime inputs.
shotsintNumber of requested samples.

Raises:

Constructor
def __init__(self, invocation: CircuitInvocation[CircuitT], shots: int) -> None
Attributes

ShotBased [source]

class ShotBased

Request a shot-based expectation value.

Parameters:

NameTypeDescription
shotsintPositive number of measurement shots.

Raises:

Constructor
def __init__(self, shots: int) -> None
Attributes

TargetPrecision [source]

class TargetPrecision

Request an expectation value at a provider target precision.

Parameters:

NameTypeDescription
precisionfloatPositive absolute target precision.

Raises:

Constructor
def __init__(self, precision: float) -> None
Attributes

qamomile.circuit.transpiler.execution_snapshot

Persist ordered execution structure without SDK objects or callables.

Overview

ClassDescription
ExecutionHandleExpose an engine execution without forcing immediate result retrieval.
ExecutionReferenceStore secret-free identifiers needed to restore remote execution.
ExecutionSnapshotStore a remote leaf, a local value, or an ordered execution group.
ExecutionSnapshotKindIdentify the reconstruction contract of an execution snapshot node.

Classes

ExecutionHandle [source]

class ExecutionHandle(ABC, Generic[ResultT])

Expose an engine execution without forcing immediate result retrieval.

Attributes
Methods
cancel
def cancel(self) -> None

Request best-effort cancellation.

Cancellation is intentionally not reported as a boolean because providers may accept a request after execution has already started. Call :meth:status to observe the eventual state.

metadata
def metadata(self) -> Mapping[str, Any]

Return optional provider execution metadata.

Returns:

Mapping[str, Any] — Mapping[str, Any]: Provider metadata such as timestamps or usage.

raw_status
def raw_status(self) -> object

Return provider-specific status information.

Returns:

object — Provider status value, or the normalized status when no richer value exists.

references
def references(self) -> tuple[ExecutionReference, ...]

Return serializable remote execution references.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Secret-free provider references.

result
def result(self, timeout: float | None = None) -> ResultT

Wait for and return the engine-neutral raw result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds. None delegates the wait policy to the provider.

Returns:

ResultT — Raw result normalized by the engine executor.

Raises:

result_async
def result_async(self, timeout: float | None = None) -> ResultT

Wait asynchronously for the engine-neutral raw result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds. Defaults to provider behavior when None.

Returns:

ResultT — Raw result normalized by the engine executor.

Raises:

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture one remote execution without fetching its result.

Adapters exposing several logical references must override this method with an explicit reconstruction structure. A provider reference may itself contain multiple physical job IDs.

Returns:

ExecutionSnapshot — One opaque provider execution.

Raises:

status
def status(self) -> JobStatus

Return the current provider-independent execution status.

Returns:

JobStatus — Current normalized status.


ExecutionReference [source]

class ExecutionReference

Store secret-free identifiers needed to restore remote execution.

Parameters:

NameTypeDescription
providerstrStable provider or adapter name.
job_idstuple[str, ...]One or more provider job identifiers.
targetstr | NoneProvider target or device identifier. Defaults to None.
group_idstr | NoneSession, batch, program, or parent identifier. Defaults to None.
contextMapping[str, str]Additional non-secret identifiers needed to restore the job. Defaults to an empty mapping.

Raises:

Constructor
def __init__(
    self,
    provider: str,
    job_ids: tuple[str, ...],
    target: str | None = None,
    group_id: str | None = None,
    context: Mapping[str, str] = dict(),
) -> None
Attributes
Methods
from_dict
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionReference

Reconstruct a provider reference from JSON-compatible data.

Parameters:

NameTypeDescription
dataMapping[str, Any]Mapping produced by :meth:to_dict.

Returns:

ExecutionReference — Validated provider execution reference.

Raises:

to_dict
def to_dict(self) -> dict[str, Any]

Convert the provider reference to JSON-compatible data.

Returns:

dict[str, Any] — dict[str, Any]: Provider identifiers and decoding context without credentials or SDK objects.


ExecutionSnapshot [source]

class ExecutionSnapshot

Store a remote leaf, a local value, or an ordered execution group.

Provider leaves may identify several physical jobs or produce native batch results. Composite children retain their result boundaries independently of the number of provider identifiers. Local values contain raw engine-neutral results, before the executable applies its public result conversion. Trees and local values support at most 100 levels of nesting.

Parameters:

NameTypeDescription
kindstr | ExecutionSnapshotKindOne of remote, local, or composite, normalized to an enum member.
referenceExecutionReference | NoneRequired only for remote leaves.
valueAnySupported native result for local leaves. Defaults to None.
childrentuple[ExecutionSnapshot, ...]Ordered composite children. Defaults to an empty tuple.

Raises:

Constructor
def __init__(
    self,
    kind: str | ExecutionSnapshotKind,
    reference: ExecutionReference | None = None,
    value: Any = None,
    children: tuple[ExecutionSnapshot, ...] = (),
) -> None
Attributes
Methods
from_dict
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionSnapshot

Reconstruct an execution tree with strict node and value validation.

Parameters:

NameTypeDescription
dataMapping[str, Any]Mapping produced by :meth:to_dict.

Returns:

ExecutionSnapshot — Validated execution structure.

Raises:

references
def references(self) -> tuple[ExecutionReference, ...]

Collect provider leaves in order without discarding tree structure.

This list supports diagnostics; restoration uses the complete tree.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Detached remote references in order.

Raises:

restore
def restore(
    self,
    restore_reference: Callable[[ExecutionReference], ExecutionHandle[Any]],
) -> ExecutionHandle[Any]

Reattach remote leaves and rebuild local values and ordered groups.

The callback must reattach an existing provider execution. This method neither retrieves remote results nor submits any execution.

Parameters:

NameTypeDescription
restore_referenceCallable[[ExecutionReference], ExecutionHandle[Any]]Provider-specific callback for one complete remote leaf.

Returns:

ExecutionHandle[Any] — ExecutionHandle[Any]: Reconstructed raw execution lifecycle.

Raises:

to_dict
def to_dict(self) -> dict[str, Any]

Serialize the execution tree and type-preserving local values.

Returns:

dict[str, Any] — dict[str, Any]: JSON-compatible execution tree.

Raises:


ExecutionSnapshotKind [source]

class ExecutionSnapshotKind(StrEnum)

Identify the reconstruction contract of an execution snapshot node.

Attributes

qamomile.circuit.transpiler.gate_emitter

GateEmitter protocol for engine-agnostic gate emission.

This module defines the GateEmitter protocol that engines implement to emit individual quantum gates. The StandardEmitPass uses this protocol to orchestrate circuit generation without engine-specific code.

Overview

FunctionDescription
default_combine_symbolicDefault combine_symbolic for engines with arithmetic-capable Parameters.
ClassDescription
BinOpKind
GateEmitterProtocol for engine-specific gate emission.
GateKindClassification of gates for emission.
GateSpecSpecification for a gate type.
MeasurementModeHow an engine handles measurement operations.

Constants

Functions

default_combine_symbolic [source]

def default_combine_symbolic(kind: 'BinOpKind', lhs: Any, rhs: Any) -> Any

Default combine_symbolic for engines with arithmetic-capable Parameters.

Performs Python operator dispatch on the operands. Used by evaluate_binop whenever the active emitter does not define its own combine_symbolic method — the typical case for Qiskit (ParameterExpression overloads __add__ etc.) and CUDA-Q parameters. Engines whose Parameter type lacks Python operators (e.g. QURI Parts) define their own combine_symbolic on the emitter class to return an engine-native symbolic representation instead.

Parameters:

NameTypeDescription
kind'BinOpKind'The BinOpKind to apply.
lhsAnyLeft operand (numeric or engine Parameter / expression).
rhsAnyRight operand (same shape).

Returns:

Any — lhs OP rhs for the matching operator. 0.0 / 0 for Any — division-by-zero in the symbolic path so the caller can finish Any — emission without aborting on a numerically degenerate case. Any — None for unrecognised kind values, which the caller Any — treats as a no-op.

Classes

BinOpKind [source]

class BinOpKind(enum.Enum)
Attributes

GateEmitter [source]

class GateEmitter(Protocol[T])

Protocol for engine-specific gate emission.

Each engine implements this protocol to emit individual gates to their circuit representation.

Type parameter T is the engine’s circuit type (e.g., QuantumCircuit).

Attributes
Methods
append_gate
def append_gate(self, circuit: T, gate: Any, qubits: list[int]) -> None

Append a gate to the circuit.

Parameters:

NameTypeDescription
circuitTThe circuit to append to
gateAnyThe gate to append (from circuit_to_gate)
qubitslist[int]Target qubit indices
circuit_to_gate
def circuit_to_gate(self, circuit: T, name: str = 'U') -> Any

Convert a circuit to a reusable gate.

Parameters:

NameTypeDescription
circuitTThe circuit to convert
namestrLabel for the gate

Returns:

Any — Engine-specific gate object, or None if not supported

create_circuit
def create_circuit(self, num_qubits: int, num_clbits: int) -> T

Create a new empty circuit.

Parameters:

NameTypeDescription
num_qubitsintNumber of qubits in the circuit
num_clbitsintNumber of classical bits in the circuit

Returns:

T — A new engine-specific circuit object

create_parameter
def create_parameter(self, name: str) -> Any

Create a symbolic parameter for the engine.

Parameters:

NameTypeDescription
namestrParameter name (e.g., “gammas[0]”)

Returns:

Any — Engine-specific parameter object

emit_barrier
def emit_barrier(self, circuit: T, qubits: list[int]) -> None

Emit barrier on specified qubits.

emit_ch
def emit_ch(self, circuit: T, control: int, target: int) -> None

Emit controlled-Hadamard gate.

emit_cp
def emit_cp(self, circuit: T, control: int, target: int, angle: float | Any) -> None

Emit controlled-Phase gate.

emit_crx
def emit_crx(self, circuit: T, control: int, target: int, angle: float | Any) -> None

Emit controlled-RX gate.

emit_cry
def emit_cry(self, circuit: T, control: int, target: int, angle: float | Any) -> None

Emit controlled-RY gate.

emit_crz
def emit_crz(self, circuit: T, control: int, target: int, angle: float | Any) -> None

Emit controlled-RZ gate.

emit_cx
def emit_cx(self, circuit: T, control: int, target: int) -> None

Emit CNOT gate.

emit_cy
def emit_cy(self, circuit: T, control: int, target: int) -> None

Emit controlled-Y gate.

emit_cz
def emit_cz(self, circuit: T, control: int, target: int) -> None

Emit CZ gate.

emit_else_start
def emit_else_start(self, circuit: T, context: Any) -> None

Start the else branch.

emit_for_loop_end
def emit_for_loop_end(self, circuit: T, context: Any) -> None

End a native for loop context.

emit_for_loop_start
def emit_for_loop_start(self, circuit: T, indexset: range) -> Any

Start a native for loop context.

Returns a context manager or loop parameter, depending on engine.

emit_h
def emit_h(self, circuit: T, qubit: int) -> None

Emit Hadamard gate.

emit_if_end
def emit_if_end(self, circuit: T, context: Any) -> None

End the if/else block.

emit_if_start
def emit_if_start(self, circuit: T, clbit: int, value: int = 1) -> Any

Start a native if context.

Returns context for the if/else block.

emit_measure
def emit_measure(self, circuit: T, qubit: int, clbit: int) -> None

Emit measurement operation.

emit_p
def emit_p(self, circuit: T, qubit: int, angle: float | Any) -> None

Emit Phase gate (P(θ) = diag(1, e^(iθ))).

emit_reset
def emit_reset(self, circuit: T, qubit: int) -> None

Emit a reset-to-zero operation.

Parameters:

NameTypeDescription
circuitTEngine circuit to emit into.
qubitintPhysical qubit index to reset.

Raises:

emit_rx
def emit_rx(self, circuit: T, qubit: int, angle: float | Any) -> None

Emit RX rotation gate.

Parameters:

NameTypeDescription
circuitTThe circuit to emit to
qubitintTarget qubit index
anglefloat | AnyRotation angle (float or engine parameter)
emit_ry
def emit_ry(self, circuit: T, qubit: int, angle: float | Any) -> None

Emit RY rotation gate.

emit_rz
def emit_rz(self, circuit: T, qubit: int, angle: float | Any) -> None

Emit RZ rotation gate.

emit_rzz
def emit_rzz(self, circuit: T, qubit1: int, qubit2: int, angle: float | Any) -> None

Emit RZZ gate (exp(-i * θ/2 * Z⊗Z)).

emit_s
def emit_s(self, circuit: T, qubit: int) -> None

Emit S gate (√Z).

emit_sdg
def emit_sdg(self, circuit: T, qubit: int) -> None

Emit S-dagger gate (inverse of S).

emit_swap
def emit_swap(self, circuit: T, qubit1: int, qubit2: int) -> None

Emit SWAP gate.

emit_t
def emit_t(self, circuit: T, qubit: int) -> None

Emit T gate (√S).

emit_tdg
def emit_tdg(self, circuit: T, qubit: int) -> None

Emit T-dagger gate (inverse of T).

emit_toffoli
def emit_toffoli(self, circuit: T, control1: int, control2: int, target: int) -> None

Emit Toffoli (CCX) gate.

emit_while_end
def emit_while_end(self, circuit: T, context: Any) -> None

End the while loop context.

emit_while_start
def emit_while_start(self, circuit: T, clbit: int, value: int = 1) -> Any

Start a native while loop context.

emit_x
def emit_x(self, circuit: T, qubit: int) -> None

Emit Pauli-X gate.

emit_y
def emit_y(self, circuit: T, qubit: int) -> None

Emit Pauli-Y gate.

emit_z
def emit_z(self, circuit: T, qubit: int) -> None

Emit Pauli-Z gate.

gate_controlled
def gate_controlled(self, gate: Any, num_controls: int) -> Any

Create controlled version of a gate.

Parameters:

NameTypeDescription
gateAnyThe gate to control
num_controlsintNumber of control qubits

Returns:

Any — New controlled gate

gate_inverse
def gate_inverse(self, gate: Any) -> Any

Create an engine-native inverse gate when supported.

Parameters:

NameTypeDescription
gateAnyEngine-specific gate object returned by circuit_to_gate.

Returns:

Any — Engine-specific inverse gate object, or None when the Any — engine cannot invert reusable gates natively.

gate_power
def gate_power(self, gate: Any, power: int) -> Any

Create gate raised to a power (U^n).

Parameters:

NameTypeDescription
gateAnyThe gate to raise to a power
powerintThe power to raise to

Returns:

Any — New gate representing gate^power

supports_for_loop
def supports_for_loop(self) -> bool

Check if engine supports native for loops.

supports_gate_inverse
def supports_gate_inverse(self) -> bool

Return whether reusable gates can be inverted natively.

Returns:

bool — True when gate_inverse can return an engine-native inverse for gates produced by circuit_to_gate. Defaults to False.

supports_if_else
def supports_if_else(self) -> bool

Check if engine supports native if/else.

supports_reusable_gates
def supports_reusable_gates(self) -> bool

Return whether circuit_to_gate can produce reusable gates.

Returns:

bool — True when the engine can convert emitted sub-circuits to reusable gate objects. Defaults to False so emit paths can avoid building throwaway sub-circuits for engines that only support inline fallback emission.

supports_while_loop
def supports_while_loop(self) -> bool

Check if engine supports native while loops.


GateKind [source]

class GateKind(Enum)

Classification of gates for emission.

Attributes

GateSpec [source]

class GateSpec

Specification for a gate type.

Constructor
def __init__(
    self,
    kind: GateKind,
    num_qubits: int,
    has_angle: bool = False,
    num_controls: int = 0,
) -> None
Attributes

MeasurementMode [source]

class MeasurementMode(Enum)

How an engine handles measurement operations.

Attributes

qamomile.circuit.transpiler.job

Job classes for quantum execution results.

Overview

FunctionDescription
aggregate_typed_resultsCombine counts whose converted public result values are equal.
ClassDescription
CompletedExecutionHandleWrap an already available result for synchronous executors.
ExecutionHandleExpose an engine execution without forcing immediate result retrieval.
ExecutionReferenceStore secret-free identifiers needed to restore remote execution.
ExecutionSnapshotStore a remote leaf, a local value, or an ordered execution group.
ExpvalJobJob for expectation value computation.
JobAbstract base class for quantum execution jobs.
JobKindIdentify the public operation needed to reconstruct a typed job.
JobSnapshotStore operation metadata and lossless raw execution reconstruction.
JobStatusDescribe a provider-independent execution state.
RunJobJob for single execution.
SampleJobJob for sampling execution (multiple shots).
SampleResultResult of a sample() execution.

Functions

aggregate_typed_results [source]

def aggregate_typed_results(results: Iterable[tuple[T, int]]) -> list[tuple[T, int]]

Combine counts whose converted public result values are equal.

Engine raw bitstrings can differ only on qubits that are not part of the program output. After result conversion those rows represent the same public value and must appear as one SampleResult entry.

Parameters:

NameTypeDescription
resultsIterable[tuple[T, int]]Converted result values and counts.

Returns:

list[tuple[T, int]] — list[tuple[T, int]]: Stable first-seen values with duplicate counts summed.

Classes

CompletedExecutionHandle [source]

class CompletedExecutionHandle(ExecutionHandle[ResultT])

Wrap an already available result for synchronous executors.

Parameters:

NameTypeDescription
valueResultTCompleted execution value.
Constructor
def __init__(self, value: ResultT) -> None

Initialize an immediately completed execution.

Parameters:

NameTypeDescription
valueResultTCompleted execution value.
Methods
result
def result(self, timeout: float | None = None) -> ResultT

Return the completed value without waiting.

Parameters:

NameTypeDescription
timeoutfloat | NoneIgnored compatibility timeout.

Returns:

ResultT — Stored execution value.

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture the already available raw result without waiting.

Returns:

ExecutionSnapshot — Owned, type-preserving local value.

Raises:

status
def status(self) -> JobStatus

Return the completed status.

Returns:

JobStatus — Always :attr:JobStatus.COMPLETED.


ExecutionHandle [source]

class ExecutionHandle(ABC, Generic[ResultT])

Expose an engine execution without forcing immediate result retrieval.

Attributes
Methods
cancel
def cancel(self) -> None

Request best-effort cancellation.

Cancellation is intentionally not reported as a boolean because providers may accept a request after execution has already started. Call :meth:status to observe the eventual state.

metadata
def metadata(self) -> Mapping[str, Any]

Return optional provider execution metadata.

Returns:

Mapping[str, Any] — Mapping[str, Any]: Provider metadata such as timestamps or usage.

raw_status
def raw_status(self) -> object

Return provider-specific status information.

Returns:

object — Provider status value, or the normalized status when no richer value exists.

references
def references(self) -> tuple[ExecutionReference, ...]

Return serializable remote execution references.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Secret-free provider references.

result
def result(self, timeout: float | None = None) -> ResultT

Wait for and return the engine-neutral raw result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds. None delegates the wait policy to the provider.

Returns:

ResultT — Raw result normalized by the engine executor.

Raises:

result_async
def result_async(self, timeout: float | None = None) -> ResultT

Wait asynchronously for the engine-neutral raw result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds. Defaults to provider behavior when None.

Returns:

ResultT — Raw result normalized by the engine executor.

Raises:

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture one remote execution without fetching its result.

Adapters exposing several logical references must override this method with an explicit reconstruction structure. A provider reference may itself contain multiple physical job IDs.

Returns:

ExecutionSnapshot — One opaque provider execution.

Raises:

status
def status(self) -> JobStatus

Return the current provider-independent execution status.

Returns:

JobStatus — Current normalized status.


ExecutionReference [source]

class ExecutionReference

Store secret-free identifiers needed to restore remote execution.

Parameters:

NameTypeDescription
providerstrStable provider or adapter name.
job_idstuple[str, ...]One or more provider job identifiers.
targetstr | NoneProvider target or device identifier. Defaults to None.
group_idstr | NoneSession, batch, program, or parent identifier. Defaults to None.
contextMapping[str, str]Additional non-secret identifiers needed to restore the job. Defaults to an empty mapping.

Raises:

Constructor
def __init__(
    self,
    provider: str,
    job_ids: tuple[str, ...],
    target: str | None = None,
    group_id: str | None = None,
    context: Mapping[str, str] = dict(),
) -> None
Attributes
Methods
from_dict
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionReference

Reconstruct a provider reference from JSON-compatible data.

Parameters:

NameTypeDescription
dataMapping[str, Any]Mapping produced by :meth:to_dict.

Returns:

ExecutionReference — Validated provider execution reference.

Raises:

to_dict
def to_dict(self) -> dict[str, Any]

Convert the provider reference to JSON-compatible data.

Returns:

dict[str, Any] — dict[str, Any]: Provider identifiers and decoding context without credentials or SDK objects.


ExecutionSnapshot [source]

class ExecutionSnapshot

Store a remote leaf, a local value, or an ordered execution group.

Provider leaves may identify several physical jobs or produce native batch results. Composite children retain their result boundaries independently of the number of provider identifiers. Local values contain raw engine-neutral results, before the executable applies its public result conversion. Trees and local values support at most 100 levels of nesting.

Parameters:

NameTypeDescription
kindstr | ExecutionSnapshotKindOne of remote, local, or composite, normalized to an enum member.
referenceExecutionReference | NoneRequired only for remote leaves.
valueAnySupported native result for local leaves. Defaults to None.
childrentuple[ExecutionSnapshot, ...]Ordered composite children. Defaults to an empty tuple.

Raises:

Constructor
def __init__(
    self,
    kind: str | ExecutionSnapshotKind,
    reference: ExecutionReference | None = None,
    value: Any = None,
    children: tuple[ExecutionSnapshot, ...] = (),
) -> None
Attributes
Methods
from_dict
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionSnapshot

Reconstruct an execution tree with strict node and value validation.

Parameters:

NameTypeDescription
dataMapping[str, Any]Mapping produced by :meth:to_dict.

Returns:

ExecutionSnapshot — Validated execution structure.

Raises:

references
def references(self) -> tuple[ExecutionReference, ...]

Collect provider leaves in order without discarding tree structure.

This list supports diagnostics; restoration uses the complete tree.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Detached remote references in order.

Raises:

restore
def restore(
    self,
    restore_reference: Callable[[ExecutionReference], ExecutionHandle[Any]],
) -> ExecutionHandle[Any]

Reattach remote leaves and rebuild local values and ordered groups.

The callback must reattach an existing provider execution. This method neither retrieves remote results nor submits any execution.

Parameters:

NameTypeDescription
restore_referenceCallable[[ExecutionReference], ExecutionHandle[Any]]Provider-specific callback for one complete remote leaf.

Returns:

ExecutionHandle[Any] — ExecutionHandle[Any]: Reconstructed raw execution lifecycle.

Raises:

to_dict
def to_dict(self) -> dict[str, Any]

Serialize the execution tree and type-preserving local values.

Returns:

dict[str, Any] — dict[str, Any]: JSON-compatible execution tree.

Raises:


ExpvalJob [source]

class ExpvalJob(Job[float])

Job for expectation value computation.

Returns a single float representing <psi|H|psi>.

Constructor
def __init__(self, exp_val: float | ExecutionHandle[float]) -> None

Initialize expval job.

Parameters:

NameTypeDescription
exp_valfloat | ExecutionHandle[float]Completed value or deferred expectation execution.
Methods
result
def result(self, timeout: float | None = None) -> float

Wait for and return the expectation value.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

float — Expectation value.

result_async
def result_async(self, timeout: float | None = None) -> float

Wait asynchronously for and return the expectation value.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

float — Expectation value.


Job [source]

class Job(ABC, Generic[T])

Abstract base class for quantum execution jobs.

A Job represents a quantum execution that can be awaited for results.

Constructor
def __init__(
    self,
    handle: ExecutionHandle[Any],
    kind: JobKind,
    shots: int | None = None,
) -> None

Initialize a public job around an execution handle.

Parameters:

NameTypeDescription
handleExecutionHandle[Any]Raw or mapped engine execution.
kindJobKindPublic operation represented by the job.
shotsint | NoneSampling shot count. Defaults to None for run jobs.
Attributes
Methods
cancel
def cancel(self) -> None

Request best-effort cancellation of the underlying execution.

metadata
def metadata(self) -> Mapping[str, Any]

Return provider execution metadata.

Returns:

Mapping[str, Any] — Mapping[str, Any]: Provider-specific metadata.

raw_status
def raw_status(self) -> object

Return provider-specific status information.

Returns:

object — Provider status or aggregate status values.

references
def references(self) -> tuple[ExecutionReference, ...]

Return the execution handle’s legacy provider-reference view.

Use :meth:snapshot for typed restoration of local values or nested groups, which a flat reference list cannot represent completely.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Provider execution references.

result
def result(self, timeout: float | None = None) -> T

Wait for and return the result.

Blocks until the job completes.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds. None uses provider behavior.

Returns:

T — Execution result with the appropriate public type.

Raises:

result_async
def result_async(self, timeout: float | None = None) -> T

Wait asynchronously for and return the public result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds. Defaults to provider behavior when None.

Returns:

T — Execution result with the appropriate public type.

snapshot
def snapshot(self) -> JobSnapshot

Capture secret-free information needed for typed restoration.

Returns:

JobSnapshot — Public metadata, local values, and remote references with ordered execution boundaries. No remote results are read.

Raises:

status
def status(self) -> JobStatus

Return the current job status.

Returns:

JobStatus — Current normalized status.


JobKind [source]

class JobKind(StrEnum)

Identify the public operation needed to reconstruct a typed job.

Attributes

JobSnapshot [source]

class JobSnapshot

Store operation metadata and lossless raw execution reconstruction.

Runtime bindings are intentionally excluded. They can contain arbitrary application data, so callers supply them again to :meth:ExecutableProgram.restore instead of persisting them implicitly.

Parameters:

NameTypeDescription
kindJobKindPublic operation that created the job.
executionstuple[ExecutionReference, ...]Ordered provider reference inventory. Empty for entirely local structured executions. For legacy snapshots, these references also specify the result layout.
shotsint | NoneSampling shot count. Required for sample jobs and absent for run jobs.
executionExecutionSnapshot | NoneOrdered remote/local execution tree. None denotes the legacy flat-reference format. When present, executions must exactly match its remote leaves.

Raises:

Constructor
def __init__(
    self,
    kind: JobKind,
    executions: tuple[ExecutionReference, ...],
    shots: int | None = None,
    execution: ExecutionSnapshot | None = None,
) -> None
Attributes
Methods
from_dict
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> JobSnapshot

Reconstruct a validated snapshot from JSON-compatible data.

Parameters:

NameTypeDescription
dataMapping[str, Any]Mapping produced by :meth:to_dict.

Returns:

JobSnapshot — Validated typed-job restoration snapshot.

Raises:

to_dict
def to_dict(self) -> dict[str, Any]

Convert the snapshot to JSON-compatible data.

Returns:

dict[str, Any] — dict[str, Any]: Version 2 operation metadata and execution tree, or the original legacy format for a flat-reference snapshot.

Raises:


JobStatus [source]

class JobStatus(Enum)

Describe a provider-independent execution state.

The numeric values of the original four states remain stable for serialization compatibility.

Attributes

RunJob [source]

class RunJob(Job[T], Generic[T])

Job for single execution.

Returns a single result value matching the kernel’s return type.

Constructor
def __init__(
    self,
    raw_counts: dict[str, int] | ExecutionHandle[dict[str, int]] | None,
    result_converter: Callable[[str], T] | None,
    *,
    value_handle: ExecutionHandle[T] | None = None,
) -> None

Initialize run job.

Parameters:

NameTypeDescription
raw_countsdict[str, int] | ExecutionHandle[dict[str, int]] | NoneCounts or deferred counts. May be None with value_handle.
result_converterCallable[[str], T] | NoneFunction converting one bitstring. May be None with value_handle.
value_handleExecutionHandle[T] | NoneHandle already producing the final public value. Defaults to None.

Raises:

Methods
from_handle
@classmethod
def from_handle(cls, handle: ExecutionHandle[T]) -> RunJob[T]

Create a run job whose handle already returns the public value.

Parameters:

NameTypeDescription
handleExecutionHandle[T]Final-value execution handle.

Returns:

RunJob[T] — RunJob[T]: Public run job delegating to handle.

result
def result(self, timeout: float | None = None) -> T

Wait for and return the single public result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

T — Public kernel return value.

result_async
def result_async(self, timeout: float | None = None) -> T

Wait asynchronously for the single public result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

T — Public kernel return value.


SampleJob [source]

class SampleJob(Job[SampleResult[T]], Generic[T])

Job for sampling execution (multiple shots).

Returns a SampleResult containing counts for each unique result.

Constructor
def __init__(
    self,
    raw_counts: dict[str, int] | ExecutionHandle[dict[str, int]],
    result_converter: Callable[[dict[str, int]], list[tuple[T, int]]],
    shots: int,
) -> None

Initialize sample job.

Parameters:

NameTypeDescription
raw_countsdict[str, int] | ExecutionHandle[dict[str, int]]Counts or a deferred counts execution.
result_converterCallable[[dict[str, int]], list[tuple[T, int]]]Function converting raw counts to typed values.
shotsintNumber of requested shots.
Methods
result
def result(self, timeout: float | None = None) -> SampleResult[T]

Wait for and return the typed sample result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

SampleResult[T] — SampleResult[T]: Aggregated typed result.

result_async
def result_async(self, timeout: float | None = None) -> SampleResult[T]

Wait asynchronously for the typed sample result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

SampleResult[T] — SampleResult[T]: Aggregated typed result.


SampleResult [source]

class SampleResult(Generic[T])

Result of a sample() execution.

Contains results as a list of (value, count) tuples.

Example:

result.results  # [(0.25, 500), (0.75, 500)]
Constructor
def __init__(self, results: list[tuple[T, int]], shots: int) -> None
Attributes
Methods
most_common
def most_common(self, n: int = 1) -> list[tuple[T, int]]

Return the n most common results.

Parameters:

NameTypeDescription
nintNumber of results to return.

Returns:

list[tuple[T, int]] — List of (result, count) tuples sorted by count descending.

probabilities
def probabilities(self) -> list[tuple[T, float]]

Return probability distribution over results.

Returns:

list[tuple[T, float]] — List of (value, probability) tuples.


qamomile.circuit.transpiler.param_keys

Shared naming for per-key engine parameters of runtime-parameter Dicts.

A Dict[K, Float] kernel argument kept as a runtime parameter (transpile(..., parameters=["coeffs"])) is decomposed into one engine parameter per looked-up key. The emit pass creates each engine parameter from the key it resolves (coeffs[3], coeffs[(0, 1)]), and the program orchestrator decomposes the execution-time binding {"coeffs": {...}} into the same names. Both sides MUST agree on the string format, so the formatting lives here and nowhere else.

Overview

FunctionDescription
dict_param_keyFormat the engine-parameter name for one entry of a Dict parameter.
is_decomposable_dict_binding_keyReport whether a normalized key can name an emitted parameter.
normalize_dict_binding_keyNormalize a user-supplied dict key for parameter-name formatting.

Functions

dict_param_key [source]

def dict_param_key(dict_name: str, key: Any) -> str

Format the engine-parameter name for one entry of a Dict parameter.

The key is formatted with repr rather than str so the helper is collision-proof on its own: str("0") and str(0) both yield "coeffs[0]", but repr keeps the string key distinct ("coeffs['0']"). Callers pass keys already normalized to plain int / tuple-of-int (see :func:normalize_dict_binding_key), for which repr and str produce identical text (repr(3) == '3', repr((0, 1)) == '(0, 1)'), so the emitted names are unchanged.

Parameters:

NameTypeDescription
dict_namestrThe kernel argument name of the Dict parameter.
keyAnyThe looked-up key, already normalized (a plain int or a tuple of plain ints — see :func:normalize_dict_binding_key).

Returns:

str — The engine parameter name, e.g. "coeffs[3]" for an int key or "coeffs[(0, 1)]" for a tuple key.


is_decomposable_dict_binding_key [source]

def is_decomposable_dict_binding_key(key: Any) -> bool

Report whether a normalized key can name an emitted parameter.

The emit pass creates per-key parameters only from IR-resolved integer keys (int or tuples of int), so only those keys can ever match an emitted parameter name. Any other key must NOT be string-formatted into a name: the str key "1" would format identically to the int key 1 (both d[1]) and silently bind the wrong parameter, and "(0, 1)" would collide with the tuple key (0, 1).

Parameters:

NameTypeDescription
keyAnyA key already passed through :func:normalize_dict_binding_key.

Returns:

bool — True when the key is an int or a tuple of ints (numpy integers count once normalized; anything else, including nested tuples, is not decomposable).


normalize_dict_binding_key [source]

def normalize_dict_binding_key(key: Any) -> Any

Normalize a user-supplied dict key for parameter-name formatting.

Integer-valued keys are canonicalized to plain int (numpy.int64, float 1.0, ...) so that the execution-time decomposition of {"coeffs": {np.int64(3): 0.5}} produces the same parameter name the emit pass created from the IR-resolved int key. Tuples/lists are normalized component-wise into a tuple. Non-integer-valued keys (str, 1.5, float("inf"), float("nan"), ...) are returned unchanged; callers must then filter them out via :func:is_decomposable_dict_binding_key — string-formatting them into a parameter name would collide with genuine int keys ("1" and 1 both format as d[1]).

Parameters:

NameTypeDescription
keyAnyA key of the user-supplied binding dict.

Returns:

typing.Any — int, tuple of normalized components, or the original key when it has no exact integer representation.


qamomile.circuit.transpiler.parameter_binding

Define and validate the runtime parameter ABI for quantum segments.

Overview

FunctionDescription
dict_param_keyFormat the engine-parameter name for one entry of a Dict parameter.
flatten_user_bindingsFlatten public arrays and dictionaries into scalar ABI keys.
is_decomposable_dict_binding_keyReport whether a normalized key can name an emitted parameter.
normalize_dict_binding_keyNormalize a user-supplied dict key for parameter-name formatting.
split_parameter_keySplit an emitted scalar key into its root name and array indices.
ClassDescription
ParameterArrayInfoDescribe the shape constraints known for one runtime array.
ParameterContainerKindClassify the public container that owns one engine scalar slot.
ParameterInfoDescribe one scalar slot in a compiled engine parameter ABI.
ParameterMetadataDescribe every scalar slot and runtime array in a compiled segment.

Functions

dict_param_key [source]

def dict_param_key(dict_name: str, key: Any) -> str

Format the engine-parameter name for one entry of a Dict parameter.

The key is formatted with repr rather than str so the helper is collision-proof on its own: str("0") and str(0) both yield "coeffs[0]", but repr keeps the string key distinct ("coeffs['0']"). Callers pass keys already normalized to plain int / tuple-of-int (see :func:normalize_dict_binding_key), for which repr and str produce identical text (repr(3) == '3', repr((0, 1)) == '(0, 1)'), so the emitted names are unchanged.

Parameters:

NameTypeDescription
dict_namestrThe kernel argument name of the Dict parameter.
keyAnyThe looked-up key, already normalized (a plain int or a tuple of plain ints — see :func:normalize_dict_binding_key).

Returns:

str — The engine parameter name, e.g. "coeffs[3]" for an int key or "coeffs[(0, 1)]" for a tuple key.


flatten_user_bindings [source]

def flatten_user_bindings(bindings: Mapping[str, Any] | None) -> dict[str, Any]

Flatten public arrays and dictionaries into scalar ABI keys.

Parameters:

NameTypeDescription
bindingsMapping[str, Any] | NoneRaw user bindings keyed by kernel parameter name.

Returns:

dict[str, Any] — dict[str, Any]: Scalar and dictionary entries keyed by emitted ABI names.


is_decomposable_dict_binding_key [source]

def is_decomposable_dict_binding_key(key: Any) -> bool

Report whether a normalized key can name an emitted parameter.

The emit pass creates per-key parameters only from IR-resolved integer keys (int or tuples of int), so only those keys can ever match an emitted parameter name. Any other key must NOT be string-formatted into a name: the str key "1" would format identically to the int key 1 (both d[1]) and silently bind the wrong parameter, and "(0, 1)" would collide with the tuple key (0, 1).

Parameters:

NameTypeDescription
keyAnyA key already passed through :func:normalize_dict_binding_key.

Returns:

bool — True when the key is an int or a tuple of ints (numpy integers count once normalized; anything else, including nested tuples, is not decomposable).


normalize_dict_binding_key [source]

def normalize_dict_binding_key(key: Any) -> Any

Normalize a user-supplied dict key for parameter-name formatting.

Integer-valued keys are canonicalized to plain int (numpy.int64, float 1.0, ...) so that the execution-time decomposition of {"coeffs": {np.int64(3): 0.5}} produces the same parameter name the emit pass created from the IR-resolved int key. Tuples/lists are normalized component-wise into a tuple. Non-integer-valued keys (str, 1.5, float("inf"), float("nan"), ...) are returned unchanged; callers must then filter them out via :func:is_decomposable_dict_binding_key — string-formatting them into a parameter name would collide with genuine int keys ("1" and 1 both format as d[1]).

Parameters:

NameTypeDescription
keyAnyA key of the user-supplied binding dict.

Returns:

typing.Any — int, tuple of normalized components, or the original key when it has no exact integer representation.


split_parameter_key [source]

def split_parameter_key(name: str) -> tuple[str, tuple[int, ...] | None]

Split an emitted scalar key into its root name and array indices.

Parameters:

NameTypeDescription
namestrEngine parameter key such as theta or angles[1][0].

Returns:

tuple[str, tuple[int, ...] | None] — tuple[str, tuple[int, ...] | None]: Root parameter name and its concrete index tuple, or None for a scalar parameter.

Classes

ParameterArrayInfo [source]

class ParameterArrayInfo

Describe the shape constraints known for one runtime array.

None dimensions remain open because the frontend annotation records rank but does not always provide a concrete runtime extent. A dimension becomes concrete only when emitted scalar slots establish a contiguous ABI prefix with at least two elements.

Parameters:

NameTypeDescription
namestrRoot runtime parameter name.
rankintNumber of array dimensions.
expected_shapetuple[int | None, ...]Exact known dimensions and None for dimensions whose extent remains open.
Constructor
def __init__(self, name: str, rank: int, expected_shape: tuple[int | None, ...]) -> None
Attributes

ParameterContainerKind [source]

class ParameterContainerKind(enum.StrEnum)

Classify the public container that owns one engine scalar slot.

Attributes

ParameterInfo [source]

class ParameterInfo

Describe one scalar slot in a compiled engine parameter ABI.

Parameters:

NameTypeDescription
namestrFull scalar key, for example gammas[0].
array_namestrRoot parameter name, for example gammas.
indexint | NoneBackward-compatible one-dimensional index, or None for scalars and higher-rank elements.
engine_paramAnyEngine-specific parameter object.
source_refstr | NoneIR value UUID providing the runtime value. Defaults to None.
indicestuple[int, ...] | NoneComplete array index tuple, or None for a scalar. Defaults to None.
container_kindParameterContainerKindPublic parameter container kind. Defaults to SCALAR.
Constructor
def __init__(
    self,
    name: str,
    array_name: str,
    index: int | None,
    engine_param: Any,
    source_ref: str | None = None,
    indices: tuple[int, ...] | None = None,
    container_kind: ParameterContainerKind = ParameterContainerKind.SCALAR,
) -> None
Attributes

ParameterMetadata [source]

class ParameterMetadata

Describe every scalar slot and runtime array in a compiled segment.

Parameters:

NameTypeDescription
parameterslist[ParameterInfo]Ordered scalar engine slots. Defaults to an empty list.
arraysdict[str, ParameterArrayInfo]Explicit runtime-array ABI descriptors keyed by root name. Defaults to descriptors derived from parameters for backward compatibility.
Constructor
def __init__(
    self,
    parameters: list[ParameterInfo] = list(),
    arrays: dict[str, ParameterArrayInfo] = dict(),
) -> None
Attributes
Methods
get_array_names
def get_array_names(self) -> set[str]

Return unique scalar and array root names.

Returns:

set[str] — set[str]: Root name for every emitted parameter.

get_ordered_params
def get_ordered_params(self) -> list[Any]

Return engine parameter objects in ABI definition order.

Returns:

list[Any] — list[Any]: Engine-specific parameter objects.

get_param_by_name
def get_param_by_name(self, name: str) -> ParameterInfo | None

Find one scalar slot by its full emitted key.

Parameters:

NameTypeDescription
namestrFull engine parameter key.

Returns:

ParameterInfo | None — ParameterInfo | None: Matching slot, or None when absent.

merge
@classmethod
def merge(cls, metadata: Sequence[ParameterMetadata]) -> ParameterMetadata

Merge parameter manifests from multiple quantum segments.

Parameters:

NameTypeDescription
metadataSequence[ParameterMetadata]Segment manifests in execution order.

Returns:

ParameterMetadata — Combined manifest with first-seen scalar slot ordering and array descriptors derived across all segments.

to_binding_dict
def to_binding_dict(self, bindings: Mapping[str, Any]) -> dict[Any, Any]

Map indexed user bindings to engine parameter objects.

Parameters:

NameTypeDescription
bindingsMapping[str, Any]Scalar values keyed by full emitted parameter name.

Returns:

dict[Any, Any] — dict[Any, Any]: Engine parameter objects mapped to bound values.

validate_array_shapes
def validate_array_shapes(self, bindings: Mapping[str, Any] | None) -> None

Validate user array rank and every concrete ABI dimension.

Parameters:

NameTypeDescription
bindingsMapping[str, Any] | NoneRaw public bindings before scalar flattening. None means no validation is needed.

Raises:

validate_required_bindings
def validate_required_bindings(self, indexed_bindings: Mapping[str, Any]) -> None

Reject missing scalar slots in an indexed binding map.

Parameters:

NameTypeDescription
indexed_bindingsMapping[str, Any]Flattened user bindings.

Raises:


qamomile.circuit.transpiler.passes

Base classes for compiler passes.

Overview

ClassDescription
AffineTypeErrorBase class for affine type violations.
AffineValidationPassValidate affine type semantics at IR level.
ArrayBoundsValidationPassReject reachable element accesses and views outside array bounds.
CompileTimeIfLoweringPassLowers compile-time resolvable IfOperations before separation.
ConstantFoldingPassEvaluates constant expressions at compile time.
ControlFlowVisitorBase class for visiting operations with control flow handling.
DependencyErrorError when quantum operation depends on non-parameter classical value.
OperationCollectorCollects operations matching a predicate.
OperationTransformerBase class for transforming operations with control flow handling.
PassBase class for all compiler passes.
QamomileCompileErrorBase class for all Qamomile compilation errors.
RegionCapturePassPopulate explicit captures for every structured control-flow region.
RegionValidationPassVerify dominance and signatures for every explicit semantic region.
SliceBorrowCheckPassPost-fold linearity checker for sliced views and borrow state.
ValidateWhileContractPassValidates that all WhileOperation conditions are measurement-backed.
ValidationErrorError during validation (e.g., non-classical I/O).
ValueCollectorCollects Value UUIDs from operation operands and results.

Classes

AffineTypeError [source]

class AffineTypeError(QamomileCompileError)

Base class for affine type violations.

Affine types enforce that quantum resources (qubits) are used at most once. This prevents common errors such as reusing a consumed qubit or aliasing.

Constructor
def __init__(
    self,
    message: str,
    handle_name: str | None = None,
    operation_name: str | None = None,
    first_use_location: str | None = None,
)

Initialize an affine-resource violation diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable affine-type failure.
handle_namestr | NoneConsumed or borrowed handle. Defaults to None.
operation_namestr | NoneOperation reporting the violation. Defaults to None.
first_use_locationstr | NoneOriginal consuming use location. Defaults to None.
Attributes

AffineValidationPass [source]

class AffineValidationPass(Pass[Block, Block])

Validate affine type semantics at IR level.

This pass serves as a safety net to catch affine type violations that may have bypassed the frontend checks. It verifies that each quantum value is used (consumed) at most once. It does NOT detect “never consumed” / silent-discard patterns; the branch-internal and loop-body discard cases are rejected separately by reject_control_flow_quantum_discard in qamomile.circuit.transpiler.passes.analyze.

Input: Block (any kind) Output: Same Block (unchanged, validation only)

Attributes
Methods
run
def run(self, input: Block) -> Block

Validate affine type semantics in the block.

Raises:


ArrayBoundsValidationPass [source]

class ArrayBoundsValidationPass(Pass[Block, Block])

Reject reachable element accesses and views outside array bounds.

This pass runs after partial evaluation has resolved binding-dependent slice extents and before declarative slice operations are stripped. It deliberately skips statically zero-trip loop bodies so an unreachable access does not become a false-positive compilation error. Exact loop replay is capped by MAX_STATIC_REPLAY_TRIPS; the conservative fallback validates one reachable body instance, including first-iteration constants when available, and never publishes speculative final results.

Attributes
Methods
run
def run(self, input: Block) -> Block

Validate reachable array element operands in one semantic block.

Parameters:

NameTypeDescription
inputBlockPost-partial-evaluation affine or hierarchical block whose concrete array extents should be checked.

Returns:

Block — input unchanged when every reachable access and view is valid or still symbolic.

Raises:


CompileTimeIfLoweringPass [source]

class CompileTimeIfLoweringPass(Pass[Block, Block])

Lowers compile-time resolvable IfOperations before separation.

After constant folding, some IfOperation conditions are statically known but remain as control-flow nodes. SegmentationPass treats them as segment boundaries, causing MultipleQuantumSegmentsError for classical-only compile-time if after quantum init.

This pass:

  1. Evaluates conditions including expression-derived ones (CompOp, CondOp, NotOp, BinOp, and UnaryMathOp chains).

  2. Replaces resolved IfOperations with selected-branch operations.

  3. Substitutes merge output UUIDs with selected-branch values in all subsequent operations and block outputs.

Constructor
def __init__(
    self,
    bindings: dict[str, Any] | None = None,
    *,
    preserved_condition_uuids: AbstractSet[str] | None = None,
    _under_controlled_unitary: bool = False,
    _active_block_ids: frozenset[int] | None = None,
)

Initialize compile-time if lowering state.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneCompile-time bindings visible in the current block. Defaults to no bindings.
preserved_condition_uuidsAbstractSet[str] | NoneConditions that must remain unresolved so a later validation pass can inspect their dataflow. Defaults to an empty set.
_under_controlled_unitaryboolInternal context flag indicating that boxed callables encountered here will be decomposed by the controlled emission walker and therefore need their owned bodies lowered too. Defaults to False.
_active_block_idsfrozenset[int] | NoneInternal recursion-path guard for operation-owned blocks. Defaults to an empty set.
Attributes
Methods
run
def run(self, input: Block) -> Block

Lower every compile-time resolvable IfOperation in the block.

Parameters:

NameTypeDescription
inputBlockBlock to lower. Must be TRACED, AFFINE, or HIERARCHICAL. TRACED is accepted so the circuit drawer can resolve bound/constant if conditions on a freshly traced block before the transpiler pipeline runs; HIERARCHICAL is accepted during the self-recursion unroll loop. Surviving inline callable invocations are passed through untouched in both cases.

Returns:

Block — New block with compile-time ifs replaced by their selected-branch operations and merge outputs substituted. The input’s BlockKind is preserved.

Raises:


ConstantFoldingPass [source]

class ConstantFoldingPass(Pass[Block, Block])

Evaluates constant expressions at compile time.

This pass folds BinOp operations when all operands are constants or bound parameters, eliminating unnecessary classical operations that would otherwise split quantum segments.

Example:

Before (with bindings={"phase": 0.5}):
    BinOp(phase * 2) -> classical segment split

After:
    Constant 1.0 -> no segment split
Constructor
def __init__(self, bindings: dict[str, Any] | None = None, *, strip_slice_ops: bool = True)

Create a constant-folding pass.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneCompile-time parameter bindings used when folding BinOps that reference declared parameters.
strip_slice_opsboolWhen True (default), removes SliceArrayOperation nodes after folding. Set to False when a downstream pass — notably SliceBorrowCheckPass — still needs to observe slice declaration points in program order to decide view liveness. A separate strip pass must then run after the linearity check so segmentation still sees a pure quantum-op stream.
Attributes
Methods
run
def run(self, input: Block) -> Block

Fold resolvable classical values throughout a block.

Parameters:

NameTypeDescription
inputBlockAffine or hierarchical block to rewrite.

Returns:

Block — Copy with folded operations and output values.

Raises:


ControlFlowVisitor [source]

class ControlFlowVisitor(ABC)

Base class for visiting operations with control flow handling.

Subclasses override visit_operation to define per-operation behavior. Control flow recursion is handled automatically by the base class.

Example:

class MeasurementCounter(ControlFlowVisitor):
    def __init__(self):
        self.count = 0

    def visit_operation(self, op: Operation) -> None:
        if isinstance(op, MeasureOperation):
            self.count += 1
Methods
visit_operation
def visit_operation(self, op: Operation) -> None

Process a single operation. Override in subclasses.

visit_operations
def visit_operations(self, operations: list[Operation]) -> None

Visit all operations including nested control flow.


DependencyError [source]

class DependencyError(QamomileCompileError)

Error when quantum operation depends on non-parameter classical value.

This error indicates that the program requires JIT compilation which is not yet supported.

Constructor
def __init__(
    self,
    message: str,
    quantum_op: str | None = None,
    classical_value: str | None = None,
)

Initialize a classical-to-quantum dependency diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable dependency failure.
quantum_opstr | NoneDependent quantum operation. Defaults to None.
classical_valuestr | NoneUnsupported classical dependency. Defaults to None.
Attributes

OperationCollector [source]

class OperationCollector(ControlFlowVisitor)

Collects operations matching a predicate.

Example:

collector = OperationCollector(lambda op: isinstance(op, MeasureOperation))
collector.visit_operations(block.operations)
measurements = collector.collected
Constructor
def __init__(self, predicate: Callable[[Operation], bool])
Attributes
Methods
visit_operation
def visit_operation(self, op: Operation) -> None

OperationTransformer [source]

class OperationTransformer(ABC)

Base class for transforming operations with control flow handling.

Subclasses override transform_operation to define per-operation transformation. Control flow recursion and rebuilding is handled automatically.

Example:

class OperationRenamer(OperationTransformer):
    def transform_operation(self, op: Operation) -> Operation:
        # Return modified operation
        return dataclasses.replace(op, ...)
Methods
transform_operation
def transform_operation(self, op: Operation) -> Operation | None

Transform a single operation. Return None to remove it.

transform_operations
def transform_operations(self, operations: list[Operation]) -> list[Operation]

Transform all operations including nested control flow.


Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


QamomileCompileError [source]

class QamomileCompileError(Exception)

Base class for all Qamomile compilation errors.


RegionCapturePass [source]

class RegionCapturePass(Pass[Block, Block])

Populate explicit captures for every structured control-flow region.

The pass derives captures from the current semantic IR, so it can normalize hand-built and deserialized blocks as well as frontend output. The pass preserves existing block identity while replacing structured operations with capture-annotated values. Running it repeatedly is idempotent.

Constructor
def __init__(self) -> None

Initialize an empty reachable-block visitation set.

Attributes
Methods
run
def run(self, input: Block) -> Block

Populate explicit captures throughout one block graph.

Parameters:

NameTypeDescription
inputBlockSemantic entrypoint whose reachable regions should be normalized.

Returns:

Block — The input entrypoint with capture lists populated on every reachable structured-control operation.


RegionValidationPass [source]

class RegionValidationPass(Pass[Block, Block])

Verify dominance and signatures for every explicit semantic region.

Constructor
def __init__(self) -> None

Initialize an empty reachable-block visitation set.

Attributes
Methods
run
def run(self, input: Block) -> Block

Validate a block graph and return it unchanged.

Parameters:

NameTypeDescription
inputBlockSemantic entrypoint whose regions should be verified.

Returns:

Block — The validated input block.

Raises:


SliceBorrowCheckPass [source]

class SliceBorrowCheckPass(Pass[Block, Block])

Post-fold linearity checker for sliced views and borrow state.

Runs after :class:ConstantFoldingPass (so slice bounds are concrete where possible) and before segmentation / emit. Walks the operations of the root block in order, maintaining a borrow state map modelled on the frontend’s :attr:ArrayBase._borrowed_indices — a single dict whose values are slice-view ArrayValue owners or the _ConsumedSlotMarker sentinel. Creating a direct element borrow (q[i]) emits no IR operation, but later operand uses remain visible to this pass; the frontend validator handles an unreturned borrow with no observable operand use.

The pass does not flag a leftover slice view at block end — slice views are affine at the kernel boundary, mirroring how element borrows behave on a locally-allocated register (the frontend’s qamomile.circuit.frontend.func_to_block._validate_returned_arrays covers the genuine leak: returning the parent with a live borrow). Anything that actually clashes with a live view (direct slot access, destructive parent consume, overlapping views, use-after-destroy) is rejected at the eager check points listed in the module docstring.

Constructor
def __init__(self) -> None

Initialize per-run mutable state to safe defaults.

Attributes
Methods
run
def run(self, input: Block) -> Block

Run the borrow tracker over input.

Parameters:

NameTypeDescription
inputBlockBlock to check. Expected to be in AFFINE or HIERARCHICAL kind — post-fold but pre-segmentation.

Returns:

Block — The same block unchanged after successful validation.

Raises:


ValidateWhileContractPass [source]

class ValidateWhileContractPass(Pass[Block, Block])

Validates that all WhileOperation conditions are measurement-backed.

Builds a producer map (result UUID → producing Operation instance) and checks every WhileOperation operand against it. A valid condition must be:

  1. A Value with BitType

  2. Measurement-backed: produced by MeasureOperation directly, or an IfOperation merge output where every reachable leaf source is itself measurement-backed.

Both operands[0] (initial condition) and operands[1] (loop-carried condition) are validated.

Raises ValidationError for any non-measurement while pattern.

Attributes
Methods
run
def run(self, block: Block) -> Block

Validate all WhileOperations and return block unchanged.


ValidationError [source]

class ValidationError(QamomileCompileError)

Error during validation (e.g., non-classical I/O).

Constructor
def __init__(self, message: str, value_name: str | None = None)

Initialize a validation diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable validation failure.
value_namestr | NoneRelated IR value name. Defaults to None.
Attributes

ValueCollector [source]

class ValueCollector(ControlFlowVisitor)

Collects Value UUIDs from operation operands and results.

Constructor
def __init__(self)
Attributes
Methods
visit_operation
def visit_operation(self, op: Operation) -> None

Record one operation’s input and result Value UUIDs.

Parameters:

NameTypeDescription
opOperationThe visited operation. Inputs are read via all_input_values so subclass-specific Value fields (e.g. IfOperation yields) are covered.

qamomile.circuit.transpiler.passes.affine_validate

Affine type validation pass: Verify quantum resources are used correctly.

Overview

ClassDescription
AffineTypeErrorBase class for affine type violations.
AffineValidationPassValidate affine type semantics at IR level.
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
HasNestedOpsMixin for operations that contain nested operation lists.
IfOperationRepresents an if-else conditional operation.
PassBase class for all compiler passes.
ValidationErrorError during validation (e.g., non-classical I/O).
ValueA typed SSA value in the IR.

Classes

AffineTypeError [source]

class AffineTypeError(QamomileCompileError)

Base class for affine type violations.

Affine types enforce that quantum resources (qubits) are used at most once. This prevents common errors such as reusing a consumed qubit or aliasing.

Constructor
def __init__(
    self,
    message: str,
    handle_name: str | None = None,
    operation_name: str | None = None,
    first_use_location: str | None = None,
)

Initialize an affine-resource violation diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable affine-type failure.
handle_namestr | NoneConsumed or borrowed handle. Defaults to None.
operation_namestr | NoneOperation reporting the violation. Defaults to None.
first_use_locationstr | NoneOriginal consuming use location. Defaults to None.
Attributes

AffineValidationPass [source]

class AffineValidationPass(Pass[Block, Block])

Validate affine type semantics at IR level.

This pass serves as a safety net to catch affine type violations that may have bypassed the frontend checks. It verifies that each quantum value is used (consumed) at most once. It does NOT detect “never consumed” / silent-discard patterns; the branch-internal and loop-body discard cases are rejected separately by reject_control_flow_quantum_discard in qamomile.circuit.transpiler.passes.analyze.

Input: Block (any kind) Output: Same Block (unchanged, validation only)

Attributes
Methods
run
def run(self, input: Block) -> Block

Validate affine type semantics in the block.

Raises:


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.


BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


ValidationError [source]

class ValidationError(QamomileCompileError)

Error during validation (e.g., non-classical I/O).

Constructor
def __init__(self, message: str, value_name: str | None = None)

Initialize a validation diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable validation failure.
value_namestr | NoneRelated IR value name. Defaults to None.
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 engine resource allocation. This applies to every Value regardless of its type (Qubit, Float, Bit, ...) -- it is not specific to qubits.


qamomile.circuit.transpiler.passes.analyze

Analyze pass: Validate and analyze dependencies in an affine block.

Overview

FunctionDescription
array_static_lengthResolve a one-dimensional array’s compile-time length.
arrays_share_physical_regionReturn whether two arrays denote the same ordered physical region.
build_dependency_graphBuild result-to-input dependency edges for semantic operations.
build_producer_mapWalk operations recursively, mapping result UUIDs to producer instances.
coerce_nonnegative_integralNormalize a real scalar with an integer value to a nonnegative integer.
collect_value_like_uuidsCollect UUIDs contained in a value-like IR object.
evaluate_classical_op_concreteTry to evaluate a classical op and record its concrete result.
find_loop_carried_condition_readsFind legacy loop rebinds whose entry value controls a nested branch.
find_measurement_derived_valuesPropagate measurement provenance forward through a dependency graph.
find_measurement_resultsReturn UUIDs directly produced from quantum measurement.
flatten_opsFlatten operations recursively through nested control flow.
genuine_input_valuesReturn an operation’s input values that count as genuine reads.
prune_compile_time_ifsReplace compile-time-decidable IfOperations by their taken branch.
reject_control_flow_quantum_discardReject control-flow-internal quantum rebinds that discard state.
reject_loop_carried_classical_rebindsReject in-loop classical scalar rebinds that cannot compile correctly.
reject_self_referential_loop_storesReject in-loop classical element stores that read the same array.
resolve_compile_time_conditionResolve an IfOperation condition to a compile-time bool.
resolve_root_qubit_addressResolve an array-element value to its root (array_uuid, index).
same_exact_typed_constantReturn whether two scalar Values carry the same exact typed constant.
ClassDescription
AnalyzePassAnalyze and validate an affine block.
ArrayValueAn array of typed IR values.
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
BinOpKind
BitTypeType representing a classical bit.
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
BranchRebindTrace-time record of a quantum variable rebound inside an if branch.
ControlFlowVisitorBase class for visiting operations with control flow handling.
DependencyErrorError when quantum operation depends on non-parameter classical value.
FloatTypeType representing a floating-point number.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
GateOperationQuantum gate operation.
HasNestedOpsMixin for operations that contain nested operation lists.
IfOperationRepresents an if-else conditional operation.
LoopCarriedRebindTrace-time record of a variable rebound inside a loop body.
MeasureOperation
MeasureVectorOperationMeasure a vector of qubits.
OperationKindClassification of operations for classical/quantum separation.
PassBase class for all compiler passes.
PauliEvolveOpPauli evolution operation: exp(-i * gamma * H).
ProjectOperationProject a qubit in one Pauli basis and keep the projected state.
PrunedIfViewPruned view of an operation list plus its dead-branch merge aliases.
QInitOperationInitialize the qubit
QubitRebindErrorQuantum variable reassigned from a different quantum source.
StoreArrayElementOperationStore a classical scalar into one element of a classical array.
UIntTypeType representing an unsigned integer.
ValidationErrorError during validation (e.g., non-classical I/O).
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.
WhileOperationRepresents a while loop operation.

Constants

Functions

array_static_length [source]

def array_static_length(array: 'ArrayValue') -> int | None

Resolve a one-dimensional array’s compile-time length.

Parameters:

NameTypeDescription
arrayArrayValueArray whose sole shape dimension is inspected.

Returns:

int | None — int | None: Non-negative static length, or None when the array is not one-dimensional, its length is symbolic/non-integral, or it is malformed with a negative length. Boolean constants are rejected even though bool is an int subclass.


arrays_share_physical_region [source]

def arrays_share_physical_region(left: 'ArrayValue', right: 'ArrayValue') -> bool

Return whether two arrays denote the same ordered physical region.

Parameters:

NameTypeDescription
leftArrayValueFirst root array or sliced view.
rightArrayValueSecond root array or sliced view.

Returns:

bool — True for the same SSA value/version lineage, when both arrays resolve to the same root logical identity and ordered root indices, or when both resolve to empty regions (whose root is unobservable). Returns False for non-empty divergent regions and unresolved symbolic coverage.


build_dependency_graph [source]

def build_dependency_graph(operations: Sequence[Operation]) -> dict[str, set[str]]

Build result-to-input dependency edges for semantic operations.

The graph includes nested control flow, branch merges, loop-carried region arguments, array-element ancestry, and slice ancestry. These are the shared semantics used by measurement provenance, kernel effects, and the compiler’s classical lowering passes.

Parameters:

NameTypeDescription
operationsSequence[Operation]Top-level semantic operations.

Returns:

dict[str, set[str]] — dict[str, set[str]]: Result UUIDs mapped to the UUIDs they depend on.


build_producer_map [source]

def build_producer_map(operations: list[Operation], producer_map: dict[str, Operation]) -> None

Walk operations recursively, mapping result UUIDs to producer instances.

Exposed at module scope so measurement-backing checks outside this pass (e.g. the loop-carried rebind check in analyze) can build the same map.

Parameters:

NameTypeDescription
operationslist[Operation]Operations to walk, recursing into all HasNestedOps bodies. IfOperation merge outputs are on results, so they map to the IfOperation itself.
producer_mapdict[str, Operation]Mutable map from result UUID to the producing operation; updated in place.

coerce_nonnegative_integral [source]

def coerce_nonnegative_integral(value: object, *, label: str) -> int

Normalize a real scalar with an integer value to a nonnegative integer.

Parameters:

NameTypeDescription
valueobjectCandidate Python, NumPy, or SymPy real scalar.
labelstrUser-facing field label used in diagnostics.

Returns:

int — Equivalent nonnegative Python integer.

Raises:


collect_value_like_uuids [source]

def collect_value_like_uuids(value: 'ValueLike') -> set[str]

Collect UUIDs contained in a value-like IR object.

Parameters:

NameTypeDescription
valueValueLikeValue-like object to inspect.

Returns:

set[str] — set[str]: UUIDs for value itself, recursively contained tuple/dict elements, and array view/element dependencies.


evaluate_classical_op_concrete [source]

def evaluate_classical_op_concrete(
    op: Operation,
    concrete_values: dict[str, Any],
    bindings: dict[str, Any],
) -> None

Try to evaluate a classical op and record its concrete result.

Supported operation types:

Delegates the actual fold to fold_classical_op under the COMPILE_TIME policy, which bypasses the runtime-parameter guard: everything in bindings is treated as a real compile-time value. Other operation types are silently ignored. If evaluation fails, nothing is recorded and downstream IfOperations referencing the result remain unresolved.

Parameters:

NameTypeDescription
opOperationThe operation to evaluate.
concrete_valuesdict[str, Any]UUID-keyed map of concrete results; the op’s result is recorded here on success. Updated in place.
bindingsdict[str, Any]Compile-time parameter bindings used to resolve operands.

find_loop_carried_condition_reads [source]

def find_loop_carried_condition_reads(
    loop_operation: ForOperation | ForItemsOperation | WhileOperation,
    *,
    condition_values: Sequence[ValueBase] | None = None,
    selected_aliases: Mapping[str, str] | None = None,
) -> set[tuple[str, str]]

Find legacy loop rebinds whose entry value controls a nested branch.

A legacy LoopCarriedRebind does not provide runtime storage between iterations. If its entry value transitively feeds an IfOperation condition, pruning that first-iteration branch must therefore not erase the evidence that a later iteration would read the updated value.

Parameters:

NameTypeDescription
loop_operationForOperation | ForItemsOperation | WhileOperationLoop whose legacy rebind records are inspected.
condition_valuesSequence[ValueBase] | NoneOptional branch conditions from a reachability-aware caller. When omitted, every nested IfOperation condition in the loop body is considered.
selected_aliasesMapping[str, str] | NoneOptional merge-result to selected-source aliases established by branch specialization.

Returns:

set[tuple[str, str]] — set[tuple[str, str]]: (before_uuid, after_uuid) pairs for rebinds whose entry value transitively influences a considered condition.


find_measurement_derived_values [source]

def find_measurement_derived_values(dependency_graph: dict[str, set[str]], measurement_uuids: set[str]) -> set[str]

Propagate measurement provenance forward through a dependency graph.

Parameters:

NameTypeDescription
dependency_graphdict[str, set[str]]Result UUIDs mapped to their dependency UUIDs.
measurement_uuidsset[str]Direct measurement-result UUIDs.

Returns:

set[str] — set[str]: Direct and transitively measurement-derived UUIDs.


find_measurement_results [source]

def find_measurement_results(operations: Sequence[Operation]) -> set[str]

Return UUIDs directly produced from quantum measurement.

Parameters:

NameTypeDescription
operationsSequence[Operation]Top-level semantic operations.

Returns:

set[str] — set[str]: Direct scalar, vector, quantum-integer, fixed-point, and projection results.


flatten_ops [source]

def flatten_ops(ops: list[Operation], *, into_if_branches: bool = True) -> list[Operation]

Flatten operations recursively through nested control flow.

Parameters:

NameTypeDescription
opslist[Operation]Operations to flatten.
into_if_branchesboolWhen True (default), recurse into IfOperation bodies too. False skips them — used by the self-referential store check, since stores inside a (runtime) if branch are rejected by AnalyzePass._reject_stores_in_if_branches instead.

Returns:

list[Operation] — list[Operation]: All reachable operations, including the control flow ops themselves.


genuine_input_values [source]

def genuine_input_values(op: Operation) -> list[ValueBase]

Return an operation’s input values that count as genuine reads.

Structured operations derive reads from their explicit region interface: enclosing operands, captures, loop initializers, and region yields. Block arguments and operation results are definitions, while legacy rebind records are diagnostics rather than dataflow. Leaf operations keep their ordinary all_input_values contract.

Parameters:

NameTypeDescription
opOperationOperation to inspect.

Returns:

list[ValueBase] — list[ValueBase]: Semantic reads in interface order.


prune_compile_time_ifs [source]

def prune_compile_time_ifs(
    ops: list[Operation],
    concrete_values: dict[str, Any],
    bindings: dict[str, Any],
    *,
    walk_runtime_branches: bool = False,
) -> PrunedIfView

Replace compile-time-decidable IfOperations by their taken branch.

Mirrors CompileTimeIfLoweringPass: conditions are resolved with the shared resolve_compile_time_condition / evaluate_classical_op_concrete helpers so the taken / dead / runtime classification here cannot disagree with the branch the lowering pass will actually keep. For a resolved condition the taken branch’s operations are inlined (recursively pruned) and each merge output is recorded as a (result, selected_source) alias pair, so merge-mediated dataflow out of the branch stays visible to dependency scans without dead-branch edges. Runtime IfOperations are kept by default with their branches untouched; with walk_runtime_branches=True their branch bodies are pruned in place (each side with its own copy of the accumulated state, exactly like the lowering pass) while the if itself and its merges stay.

Shared by reject_self_referential_loop_stores and reject_loop_carried_classical_rebinds — both checks must classify conditions exactly the way the lowering pass does.

Parameters:

NameTypeDescription
opslist[Operation]Operations to prune, in program order.
concrete_valuesdict[str, Any]UUID-keyed concrete classical-op results accumulated along the walk. Updated in place (nested non-if bodies get a copy, matching the lowering pass’s scoping).
bindingsdict[str, Any]Compile-time parameter bindings used to resolve conditions.
walk_runtime_branchesboolWhen True, descend into kept runtime IfOperation branches so compile-time ifs nested inside them are pruned (and their merge aliases recorded) too — the lowering pass lowers those, so scans that must match its output need this. False (default) preserves the historical view where runtime branches pass through verbatim, which the quantum discard checks rely on for their own position-aware classification. Defaults to False.

Returns:

PrunedIfView — The pruned operations together with the recorded dead-branch merge alias pairs (global and per pruned loop op).


reject_control_flow_quantum_discard [source]

def reject_control_flow_quantum_discard(operations: list[Operation], bindings: dict[str, Any] | None = None) -> None

Reject control-flow-internal quantum rebinds that discard state.

The decoration-time rebind analyzer intentionally suppresses branch-internal violations (its snapshot-restore scope truncates them) so that compile-time-if branch-selection rebinds stay legal. That leaves a runtime hole: rebinding a quantum variable inside a runtime branch — to a fresh allocation (if cond: q = qmc.qubit("fresh")) or to any other quantum value (if cond: q = other, including in both branches at once) — silently drops the variable’s pre-branch state exactly when a rebinding branch is taken. The frontend records every branch-internal quantum binding change on the IfOperation (BranchRebind, preserving the pre-branch value even when it no longer appears in any merge); this check verifies each record against each runtime execution path and raises QubitRebindError — the same AffineTypeError the decoration-time analyzer raises for a top-level rebind from a different quantum source, since this is that exact affine violation surfacing at runtime inside a branch — when the pre-branch value has no owner on a rebinding path: not consumed inside the taken branch, not carried out through any merge of that side, and not referenced by any operation outside the if. Scalar Qubit and whole-register Vector[Qubit] rebinds are covered alike.

Loop bodies are covered more strictly than branches (see :func:_check_loop_quantum_discards): the frontend records quantum rebinds on ForOperation / ForItemsOperation / WhileOperation (LoopCarriedRebind entries whose before is quantum), and each record is rejected unless it carries the incoming value forward on the same wires, is a covered loop-invariant rebind, or is the terminal fresh-allocation pattern where nested QInitOperation reset/prepare-zero emission gives qmc.qubit() fresh-per-iteration semantics. In-body consumption of the incoming value itself is not an exemption: the read re-executes against the traced register every iteration and matches Python semantics only for the first one. A loop-body rebind needs no runtime/compile-time classification, so loops are checked wherever they appear on a live (non-pruned) path, trip-count-agnostically, exactly like the classical loop-carried check.

IfOperations are classified with the same condition resolution CompileTimeIfLoweringPass uses (via bindings), including for ifs nested inside runtime branches. A rebind confined to a compile-time branch stays legal when the surrounding control flow is compile-time too: rebinding to an alternative register under a compile-time flag is the documented branch-selection idiom, and a dead branch is eliminated entirely. A compile-time-TAKEN rebind nested inside a runtime branch inherits that branch’s runtime conditionality and is checked (and rejected when it discards). Only ifs whose condition transitively derives from a measurement result are checked — the same taint analysis the classical-lowering pipeline uses, so expression-derived runtime conditions (~bit, a & b) are covered; a non-measurement, non-compile-time condition cannot drive runtime branching and is rejected at emit by the shared condition resolution (though for this discard shape the emit-side merge physical-resource check can fire first with its generic message).

What stays allowed:

The check is deliberately conservative toward allowing where it cannot be exact. Merge lineage is over-approximated: producers without a positional qubit model (composite gates, controlled blocks, casts) contribute all of their quantum inputs as possible roots, so the carried exemption can only grow — a rejection requires the pre-branch value to be provably absent from every merge lineage. Outside-ownership evidence is path-sensitive with respect to enclosing ifs (a read on the sibling branch of an enclosing runtime if does not exempt), but path-insensitive for non-ancestor runtime ifs elsewhere: a value conditionally consumed downstream counts as owned. Rebinds inside compile-time-TAKEN ifs nested in a runtime branch are promoted to the enclosing if’s check trip-count- and loop-agnostically; because the lowering pass erases those nested ifs (and their records), the promoted rebinds are only caught by the pre-fold PartialEvaluationPass hook, not by the AnalyzePass safety net.

Scope contract: the scan recurses through control-flow nesting only (IfOperation branches and HasNestedOps bodies). Boxed implementation blocks — InvokeOperation bodies and implementations, InverseBlockOperation.implementation_block, ControlledUOperation.block — are NOT descended into: they stay HIERARCHICAL recipe blocks outside the entrypoint pipeline, exactly like every other transpile-time rebind check (reject_loop_carried_classical_rebinds, AffineValidationPass, both built on the same HasNestedOps walk). A discard written inside a composite’s recipe kernel is therefore only covered by the decoration-time top-level analyzer, with the same branch/loop suppression as everywhere else pre-IR.

Exposed at module scope because it runs from two passes: PartialEvaluationPass calls it before folding and if-lowering (with bindings, so compile-time branches are classified exactly as the lowering pass will lower them), and AnalyzePass calls it again as a safety net for pipelines that skip partial_eval.

Parameters:

NameTypeDescription
operationslist[Operation]Operations to scan. Recurses through all control flow; every runtime if and every loop at any nesting depth on a live path is checked.
bindingsdict[str, Any] | NoneCompile-time parameter bindings used to resolve IfOperation conditions, matching what CompileTimeIfLoweringPass will later resolve. Defaults to None (no bindings).

Raises:


reject_loop_carried_classical_rebinds [source]

def reject_loop_carried_classical_rebinds(
    operations: list[Operation],
    bindings: dict[str, Any] | None = None,
    output_values: list[ValueLike] | None = None,
) -> None

Reject in-loop classical scalar rebinds that cannot compile correctly.

A loop body is traced once, so a Python-level reassignment like total = total + i inside a qmc.range / while / qmc.items loop reads a fixed pre-loop value instead of the previous iteration’s value. Every executor (the classical segment interpreter and emit-time unrolling) re-runs the same traced operations per iteration, so the program silently diverges from Python semantics (e.g. total ends as 0 + i_last instead of the sum). The frontend records candidate rebinds on the loop operations (LoopCarriedRebind); this check rejects the classical ones that survive dead-branch pruning. Records whose before is quantum model state discard, not traced-once divergence — they are skipped here and rejected by :func:reject_control_flow_quantum_discard instead.

IfOperations are classified with the same condition resolution CompileTimeIfLoweringPass uses (via bindings): a rebind whose only path is a compile-time-dead branch canonicalizes back to the pre-loop value and is allowed. Unlike the array-store check, loops nested inside runtime if branches are scanned too — a loop-carried scalar rebind there miscompiles all the same — and the pruning walk descends into those branches (walk_runtime_branches=True) so dead-branch canonicalization applies to them exactly as the lowering pass will lower them.

The one exempted rebind — the while loop-carried condition pair — additionally requires that the condition’s pre-loop snapshot is not read after its shared clbit is updated, either later in the body or after the loop (see _reject_stale_while_condition_reads). The allocator aliases the whole condition series onto one classical bit, so such a read would observe the newer in-loop measurement instead of the snapshot Python promises.

Exposed at module scope because it must run from two passes: PartialEvaluationPass calls it before constant folding (folding an all-constant accumulation like total = total + 1 erases the dependency evidence while keeping the wrong result), and AnalyzePass calls it again as a safety net for pipelines that skip partial_eval.

Parameters:

NameTypeDescription
operationslist[Operation]Operations to scan. Recurses through all control flow.
bindingsdict[str, Any] | NoneCompile-time parameter bindings used to resolve IfOperation conditions, matching what CompileTimeIfLoweringPass will later resolve. Defaults to None (no bindings).
output_valueslist[ValueLike] | NoneThe block’s output values; a while condition’s pre-loop value escaping through them is a post-loop read. Structural outputs (TupleValue / DictValue) are searched recursively so a condition returned inside a tuple is still detected. Defaults to None (no outputs known).

Raises:


reject_self_referential_loop_stores [source]

def reject_self_referential_loop_stores(operations: list[Operation], bindings: dict[str, Any] | None = None) -> None

Reject in-loop classical element stores that read the same array.

A loop body is traced once, so a StoreArrayElementOperation inside a loop references a fixed pre-loop version of the array it writes. If the stored value or the store index reads an element of that same logical array — directly or through classical arithmetic — later iterations would observe stale pre-loop contents instead of earlier iterations’ writes, silently diverging from Python semantics (e.g. vals[i] = vals[0] + 1 would write the same folded value every iteration). Such stores are rejected at compile time.

IfOperations are classified with the same condition resolution CompileTimeIfLoweringPass uses (via bindings): a compile-time condition contributes only its taken branch to the scan (a dead branch is eliminated by the lowering pass, so a self-referential store inside it never executes), while a runtime condition’s branches are skipped entirely — every store inside a runtime if branch is rejected by AnalyzePass._reject_stores_in_if_branches regardless of self-reference.

Exposed at module scope because it must run from two passes: PartialEvaluationPass calls it before constant folding (folding a bound element read to a constant erases the parent_array provenance this check relies on — the fold is exactly what bakes the stale pre-loop value into the loop body), and AnalyzePass calls it again as a safety net for pipelines that skip partial_eval.

Parameters:

NameTypeDescription
operationslist[Operation]Operations to scan. Recurses through all control flow; every loop at any nesting depth is checked against the stores inside its body (if branches per the classification above).
bindingsdict[str, Any] | NoneCompile-time parameter bindings used to resolve IfOperation conditions, matching what CompileTimeIfLoweringPass will later resolve. Defaults to None (no bindings): only constant conditions resolve and all others are treated as runtime — correct for the AnalyzePass safety-net call, where compile-time ifs are already lowered away and any store left inside an if branch was already rejected.

Raises:


resolve_compile_time_condition [source]

def resolve_compile_time_condition(
    condition: Any,
    concrete_values: dict[str, Any],
    bindings: dict[str, Any],
) -> bool | None

Resolve an IfOperation condition to a compile-time bool.

Single source of truth for classifying an if-condition as compile-time taken / dead / runtime. Used by :class:CompileTimeIfLoweringPass to decide which branches to lower and by reject_self_referential_loop_stores to prune the same branches from its scan — both callers must agree on the classification, so they share this function.

Tries resolve_if_condition first (plain Python values, constant Values, direct UUID / parameter-provenance bindings), then falls back to the accumulated concrete_values map for expression-derived conditions (CompOp / CondOp / NotOp / BinOp chains evaluated by :func:evaluate_classical_op_concrete).

Parameters:

NameTypeDescription
conditionAnyThe condition operand. May be a plain Python value or a Value.
concrete_valuesdict[str, Any]UUID-keyed map of concrete classical-op results accumulated in program order.
bindingsdict[str, Any]Compile-time parameter bindings.

Returns:

bool | None — bool | None: The condition’s compile-time truth value, or None when it is not compile-time resolvable (a runtime condition).


resolve_root_qubit_address [source]

def resolve_root_qubit_address(value: 'Value') -> tuple[str, int] | None

Resolve an array-element value to its root (array_uuid, index).

Walks the parent_array / slice_of chain and composes the nested affine slice maps, so view[i] resolves to (root_uuid, start + step * i) for the composed (start, step). The returned pair is the build-stable identity of the physical qubit slot: the root array’s QInitOperation always registers it as QubitAddress(root_uuid, index), so this address resolves even when the element’s own (per-version) UUID was never registered.

The transpiler’s resource allocator uses the same walk to resolve gate and measurement operands; this shared helper keeps both call sites consistent.

Parameters:

NameTypeDescription
valueValueThe value to resolve. Expected to be an array element (parent_array set with a single constant element_indices entry).

Returns:

tuple[str, int] | None — tuple[str, int] | None: (root_array_uuid, composed_index) when value is an array element with a constant index whose entire slice_of chain has constant slice_start / slice_step. None when value is not an array element, when its index is non-constant, or when any slice bound in the chain is non-constant (those cases are deferred to the emit-time resolver, which has bindings available). Also None for a negative constant index or a chain frame with negative slice_start / non-positive slice_step — composing those would silently address a wrong root slot, so they are refused rather than guessed (the frontend rejects them at trace time; this guard covers programmatically constructed IR).


same_exact_typed_constant [source]

def same_exact_typed_constant(left: Value, right: Value) -> bool

Return whether two scalar Values carry the same exact typed constant.

Equality requires matching IR and Python types. Floating-point comparison preserves the sign of zero and the payload bits of NaNs.

Parameters:

NameTypeDescription
leftValueFirst scalar value to compare.
rightValueSecond scalar value to compare.

Returns:

bool — True only for constants of the same IR type and Python type with equal value representations.

Classes

AnalyzePass [source]

class AnalyzePass(Pass[Block, Block])

Analyze and validate an affine block.

This pass:

  1. Builds a dependency graph between values (used locally for validation)

  2. Validates that quantum ops don’t depend on non-parameter classical results

  3. Checks that block inputs/outputs are classical

Input: Block with BlockKind.AFFINE Output: Block with BlockKind.ANALYZED

Attributes
Methods
run
def run(self, input: Block) -> Block

Analyze the block and validate dependencies.


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:

bool — True iff slice_of is non-None.

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

BinOp [source]

class BinOp(BinaryOperationBase)

Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: BinOpKind | None = None,
) -> None
Attributes

BinOpKind [source]

class BinOpKind(enum.Enum)
Attributes

BitType [source]

class BitType(ClassicalTypeMixin, ValueType)

Type representing a classical bit.


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.


BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

BranchRebind [source]

class BranchRebind

Trace-time record of a quantum variable rebound inside an if branch.

The frontend’s branch tracing merges only the new branch values through merge operations; when both branches rebind a variable, the value the variable held before the branch no longer appears anywhere in the IfOperation. These records preserve that pre-branch binding so the transpiler’s control-flow discard check (reject_control_flow_quantum_discard in qamomile.circuit.transpiler.passes.analyze) can verify that the pre-branch quantum state is consumed or carried on every runtime execution path instead of being silently dropped.

Constructor
def __init__(
    self,
    var_name: str,
    before: Value,
    rebound_in_true: bool,
    rebound_in_false: bool,
) -> None
Attributes

ControlFlowVisitor [source]

class ControlFlowVisitor(ABC)

Base class for visiting operations with control flow handling.

Subclasses override visit_operation to define per-operation behavior. Control flow recursion is handled automatically by the base class.

Example:

class MeasurementCounter(ControlFlowVisitor):
    def __init__(self):
        self.count = 0

    def visit_operation(self, op: Operation) -> None:
        if isinstance(op, MeasureOperation):
            self.count += 1
Methods
visit_operation
def visit_operation(self, op: Operation) -> None

Process a single operation. Override in subclasses.

visit_operations
def visit_operations(self, operations: list[Operation]) -> None

Visit all operations including nested control flow.


DependencyError [source]

class DependencyError(QamomileCompileError)

Error when quantum operation depends on non-parameter classical value.

This error indicates that the program requires JIT compilation which is not yet supported.

Constructor
def __init__(
    self,
    message: str,
    quantum_op: str | None = None,
    classical_value: str | None = None,
)

Initialize a classical-to-quantum dependency diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable dependency failure.
quantum_opstr | NoneDependent quantum operation. Defaults to None.
classical_valuestr | NoneUnsupported classical dependency. Defaults to None.
Attributes

FloatType [source]

class FloatType(ClassicalTypeMixin, ValueType)

Type representing a floating-point number.


ForItemsOperation [source]

class ForItemsOperation(HasNestedOps, Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    key_var_values: tuple[Value, ...] | None = None,
    value_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include the per-key/value Value fields for cloning/substitution.

Same rationale as ForOperation.all_input_values: keep the IR identity fields in lockstep with body references so UUID-keyed lookups stay valid after inline cloning. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the items-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing key/value formals, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the items-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt items-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

GateOperation [source]

class GateOperation(Operation)

Quantum gate operation.

For rotation gates (RX, RY, RZ, P, CP, RZZ), the angle parameter is stored as the last element of operands. Use the theta property for typed read access and the rotation / fixed factory class-methods for type-safe construction.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    gate_type: GateOperationType | None = None,
) -> None
Attributes
Methods
fixed
@classmethod
def fixed(
    cls,
    gate_type: GateOperationType,
    qubits: list[Value],
    results: list[Value],
) -> 'GateOperation'

Create a fixed gate (H, X, CX, SWAP, …) with no angle parameter.

rotation
@classmethod
def rotation(
    cls,
    gate_type: GateOperationType,
    qubits: list[Value],
    theta: Value,
    results: list[Value],
) -> 'GateOperation'

Create a rotation gate (RX, RY, RZ, P, CP, RZZ) with an angle.


HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


LoopCarriedRebind [source]

class LoopCarriedRebind

Trace-time record of a variable rebound inside a loop body.

Two rebind families share this record type, distinguished by the type of before:

Constructor
def __init__(
    self,
    var_name: str,
    before: ValueBase,
    after: ValueBase,
    before_synthesized: bool = False,
) -> None
Attributes

MeasureOperation [source]

class MeasureOperation(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

MeasureVectorOperation [source]

class MeasureVectorOperation(Operation)

Measure a vector of qubits.

Takes a Vector[Qubit] (ArrayValue) and produces a Vector[Bit] (ArrayValue). This operation measures all qubits in the vector as a single operation.

operands: [ArrayValue of qubits] results: [ArrayValue of bits]

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

OperationKind [source]

class OperationKind(enum.Enum)

Classification of operations for classical/quantum separation.

This enum is used to categorize operations during compilation to determine which parts run on classical hardware vs quantum hardware.

Values:

QUANTUM: Pure quantum operations (gates, qubit allocation) CLASSICAL: Pure classical operations (arithmetic, comparisons) HYBRID: Operations that bridge classical and quantum (measurement, encode/decode) CONTROL: Control flow structures (for, while, if)

Attributes

Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


PauliEvolveOp [source]

class PauliEvolveOp(Operation)

Pauli evolution operation: exp(-i * gamma * H).

This operation applies the time evolution of a Pauli Hamiltonian to a quantum register.

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ProjectOperation [source]

class ProjectOperation(Operation)

Project a qubit in one Pauli basis and keep the projected state.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    axis: str = 'z',
) -> None
Attributes

PrunedIfView [source]

class PrunedIfView

Pruned view of an operation list plus its dead-branch merge aliases.

Produced by :func:prune_compile_time_ifs. A compile-time-resolved IfOperation disappears from operations (only its taken branch survives, inlined); each of its merge outputs is recorded here as a (result, selected_source) alias pair so merge-mediated dataflow out of the pruned branch stays visible to dependency scans without any synthetic operation in the list.

Constructor
def __init__(
    self,
    operations: list[Operation],
    merge_aliases: tuple[tuple[Value, Value], ...],
    _loop_aliases: dict[int, tuple[tuple[Value, Value], ...]],
    _loop_condition_reads: dict[int, frozenset[tuple[str, str]]],
) -> None
Attributes
Methods
aliases_for_loop
def aliases_for_loop(self, loop_op: Operation) -> tuple[tuple[Value, Value], ...]

Return the alias pairs recorded inside one pruned loop’s body.

Parameters:

NameTypeDescription
loop_opOperationA loop operation taken from operations (or a body nested within it). Loop ops that were never walked — e.g. inside a kept runtime-if branch — have no recorded aliases.

Returns:

tuple[tuple[Value, Value], ...] — tuple[tuple[Value, Value], ...]: (result, selected_source) pairs from compile-time ifs pruned anywhere inside the loop’s body, or an empty tuple.

condition_reads_for_loop
def condition_reads_for_loop(self, loop_op: Operation) -> frozenset[tuple[str, str]]

Return condition-dependent legacy rebinds for one pruned loop.

Parameters:

NameTypeDescription
loop_opOperationLoop operation taken from operations.

Returns:

frozenset[tuple[str, str]] — frozenset[tuple[str, str]]: (before_uuid, after_uuid) pairs observed on paths visited by compile-time pruning.


QInitOperation [source]

class QInitOperation(Operation)

Initialize the qubit

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

QubitRebindError [source]

class QubitRebindError(AffineTypeError)

Quantum variable reassigned from a different quantum source.

When a quantum variable is reassigned, the RHS must consume the same variable (self-update pattern). Reassigning from a different quantum variable would silently discard the original quantum state.

The check runs at qkernel decoration time as a static AST analysis (see qamomile.circuit.frontend.ast_transform.collect_quantum_rebind_violations) and raises immediately — the wrapped QKernel object is never constructed when a violation is present. The check is run unconditionally for every decorated kernel: kernel-level quantum parameters (Qubit / Vector[Qubit]) seed origins from the signature, and the analyzer’s recognition of internal quantum constructors (qubit(...) / qubit_array(...)) seeds further origins from inside the body so kernels that derive all of their quantum state from internal allocations are also covered.

Branch-internal rebinds (assignments inside an if / for / while body) are NOT flagged at decoration time: compile-time conditional branches legitimately rebind quantum names (the compile-time-if lowering pass selects one branch and discards the other), and the single-pass AST analyzer cannot distinguish compile-time from runtime branches. To keep those compile-time patterns working, branch-internal violations are suppressed.

The runtime side of that gap is closed at the IR layer instead: reject_control_flow_quantum_discard (in qamomile.circuit.transpiler.passes.analyze) classifies branch conditions the same way the compile-time-if lowering pass does and raises this same QubitRebindError for a runtime if cond: q = qm.qubit("fresh") that discards the pre-branch state — and for a for / while body rebind that discards the incoming loop state the same way — while leaving compile-time branch rebinds legal; so a caller catching QubitRebindError (or AffineTypeError) sees the decoration-time and IR-time forms of the violation uniformly. That IR check covers if conditions that transitively derive from a measurement (including expression forms like ~bit); a condition that is neither compile-time-resolvable nor measurement-derived cannot drive runtime branching and keeps its emit-time diagnosis. (AffineValidationPass itself still only enforces “consumed at most once”.) Top-level (non-branch-internal) bypasses continue to raise at decoration time.

Example of incorrect code:

a = qm.h(b) # ERROR: ‘a’ was quantum, now overwritten from ‘b’ a = b # ERROR: ‘a’ was quantum, now overwritten from ‘b’

Correct patterns:

a = qm.h(a) # Self-update (OK) new = qm.h(b) # New binding (OK, ‘new’ wasn’t quantum before)


StoreArrayElementOperation [source]

class StoreArrayElementOperation(Operation)

Store a classical scalar into one element of a classical array.

This is the IR form of array[index] = value for classical element types (Bit / UInt / Float). Classical values are freely copyable, so the store is an ordinary SSA rewrite: the operation consumes the current array version and produces a new ArrayValue version (same logical_id, fresh uuid) whose contents equal the input array with the addressed element replaced. Quantum arrays never use this operation — qubit element assignment is the return half of the borrow-return idiom and emits no IR.

The operation is evaluated in one of two places:

Operand convention:

operands: [array (ArrayValue), stored_value (Value), *index_values] results: [new_array (ArrayValue)]

Example:

@qmc.qkernel
def k() -> qmc.Vector[qmc.Bit]:
    qs = qmc.qubit_array(2, "qs")
    qs[0] = qmc.x(qs[0])
    bits = qmc.measure(qs)
    bits[1] = bits[0]   # emits StoreArrayElementOperation
    return bits
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

UIntType [source]

class UIntType(ClassicalTypeMixin, ValueType)

Type representing an unsigned integer.


ValidationError [source]

class ValidationError(QamomileCompileError)

Error during validation (e.g., non-classical I/O).

Constructor
def __init__(self, message: str, value_name: str | None = None)

Initialize a validation diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable validation failure.
value_namestr | NoneRelated IR value name. Defaults to None.
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 engine 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.


WhileOperation [source]

class WhileOperation(HasNestedOps, Operation)

Represents a while loop operation.

Only measurement-backed conditions are supported: the condition must be a Bit value produced by qmc.measure(). Non-measurement conditions (classical variables, constants, comparisons) are rejected by ValidateWhileContractPass before reaching engine emit.

Example::

bit = qmc.measure(q)
while bit:
    q = qmc.h(q)
    bit = qmc.measure(q)
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    operations: list[Operation] = list(),
    max_iterations: int | None = None,
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include rebind records and region args for cloning/substitution.

Same rationale as ForOperation.all_input_values: rebind records and region arguments reference body/pre-loop values by identity, so inline cloning must remap them in lockstep with body operands.

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus rebind-record and region-argument values.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the while body with explicit boundary values.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region whose block arguments and yields are aligned with region_args. The updated condition, when present, is appended as the final yield.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the while body and its complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt while operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, rebind-record, and region-arg values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


qamomile.circuit.transpiler.passes.array_bounds_validation

Reject reachable compile-time array accesses outside resolved extents.

Overview

FunctionDescription
constant_integerReturn a non-boolean integer constant carried by an IR value.
genuine_input_valuesReturn an operation’s input values that count as genuine reads.
pair_block_operandsPair all block inputs with category-grouped call-site operands.
reachable_nested_regionsReturn nested regions that may execute for one control-flow operation.
same_exact_typed_constantReturn whether two scalar Values carry the same exact typed constant.
static_for_items_entriesReturn compile-time entries iterated by a for-items operation.
static_for_rangeResolve the exact iteration range of a statically bounded loop.
ClassDescription
ArrayBoundsValidationPassReject reachable element accesses and views outside array bounds.
ArrayValueAn array of typed IR values.
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
CompOpComparison operation (EQ, NEQ, LT, LE, GT, GE).
CondOpConditional logical operation (AND, OR).
ControlledUOperationBase class for controlled-U operations.
DictValueA dictionary value stored as stable ordered entries.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
HasNestedOpsMixin for operations that contain nested operation lists.
IfOperationRepresents an if-else conditional operation.
NotOp
PassBase class for all compiler passes.
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
SliceArrayOperationConstruct a strided view of an ArrayValue.
TupleValueA tuple of IR values for structured data.
UnaryMathOpRepresent one pure unary mathematical expression.
ValidationErrorError during validation (e.g., non-classical I/O).
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.
ValueResolverResolve IR Values to concrete Python values.

Functions

constant_integer [source]

def constant_integer(value: ValueBase | None) -> int | None

Return a non-boolean integer constant carried by an IR value.

Parameters:

NameTypeDescription
valueValueBase | NoneCandidate scalar value.

Returns:

int | None — int | None: Normalized Python integer, or None when value is absent, symbolic, boolean, or non-integral.


genuine_input_values [source]

def genuine_input_values(op: Operation) -> list[ValueBase]

Return an operation’s input values that count as genuine reads.

Structured operations derive reads from their explicit region interface: enclosing operands, captures, loop initializers, and region yields. Block arguments and operation results are definitions, while legacy rebind records are diagnostics rather than dataflow. Leaf operations keep their ordinary all_input_values contract.

Parameters:

NameTypeDescription
opOperationOperation to inspect.

Returns:

list[ValueBase] — list[ValueBase]: Semantic reads in interface order.


pair_block_operands [source]

def pair_block_operands(
    block: Block,
    operands: Sequence[ValueBase],
) -> list[tuple[ValueBase, ValueBase]]

Pair all block inputs with category-grouped call-site operands.

Parameters:

NameTypeDescription
blockBlockOperation-owned block whose inputs are being bound.
operandsSequence[ValueBase]Call-site operands after any controls that are external to block have been removed.

Returns:

list[tuple[ValueBase, ValueBase]] — list[tuple[ValueBase, ValueBase]]: Formal/actual pairs in the block’s list[tuple[ValueBase, ValueBase]] — declaration order.


reachable_nested_regions [source]

def reachable_nested_regions(operation: HasNestedOps) -> tuple[Region, ...]

Return nested regions that may execute for one control-flow operation.

Constant conditionals expose only their selected branch. Statically empty counted and items loops expose no body region. All unresolved control flow remains conservative and exposes every region.

Parameters:

NameTypeDescription
operationHasNestedOpsStructured-control operation to inspect.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Regions that are reachable under compile-time-known control decisions.


same_exact_typed_constant [source]

def same_exact_typed_constant(left: Value, right: Value) -> bool

Return whether two scalar Values carry the same exact typed constant.

Equality requires matching IR and Python types. Floating-point comparison preserves the sign of zero and the payload bits of NaNs.

Parameters:

NameTypeDescription
leftValueFirst scalar value to compare.
rightValueSecond scalar value to compare.

Returns:

bool — True only for constants of the same IR type and Python type with equal value representations.


static_for_items_entries [source]

def static_for_items_entries(operation: ForItemsOperation) -> tuple[tuple[Any, Any], ...] | None

Return compile-time entries iterated by a for-items operation.

Parameters:

NameTypeDescription
operationForItemsOperationItems loop whose iterable should be inspected.

Returns:

tuple[tuple[Any, Any], ...] | None — tuple[tuple[Any, Any], ...] | None: Bound key/value entries in iteration order, including an empty tuple for a known-empty mapping, or None when the iterable remains symbolic.


static_for_range [source]

def static_for_range(operation: ForOperation) -> range | None

Resolve the exact iteration range of a statically bounded loop.

Parameters:

NameTypeDescription
operationForOperationCounted loop whose three bounds should be inspected.

Returns:

range | None — range | None: Exact Python range when all bounds are integral constants and the step is nonzero, otherwise None.

Classes

ArrayBoundsValidationPass [source]

class ArrayBoundsValidationPass(Pass[Block, Block])

Reject reachable element accesses and views outside array bounds.

This pass runs after partial evaluation has resolved binding-dependent slice extents and before declarative slice operations are stripped. It deliberately skips statically zero-trip loop bodies so an unreachable access does not become a false-positive compilation error. Exact loop replay is capped by MAX_STATIC_REPLAY_TRIPS; the conservative fallback validates one reachable body instance, including first-iteration constants when available, and never publishes speculative final results.

Attributes
Methods
run
def run(self, input: Block) -> Block

Validate reachable array element operands in one semantic block.

Parameters:

NameTypeDescription
inputBlockPost-partial-evaluation affine or hierarchical block whose concrete array extents should be checked.

Returns:

Block — input unchanged when every reachable access and view is valid or still symbolic.

Raises:


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:

bool — True iff slice_of is non-None.

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

BinOp [source]

class BinOp(BinaryOperationBase)

Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: BinOpKind | None = None,
) -> None
Attributes

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.


BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

CompOp [source]

class CompOp(BinaryOperationBase)

Comparison operation (EQ, NEQ, LT, LE, GT, GE).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CompOpKind | None = None,
) -> None
Attributes

CondOp [source]

class CondOp(BinaryOperationBase)

Conditional logical operation (AND, OR).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CondOpKind | None = None,
) -> None
Attributes

ControlledUOperation [source]

class ControlledUOperation(Operation)

Base class for controlled-U operations.

Two concrete subclasses handle distinct operand layouts:

All isinstance(op, ControlledUOperation) checks match every subclass.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int | Value = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]
replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

DictValue [source]

class DictValue(_MetadataValueMixin, ValueBase)

A dictionary value stored as stable ordered entries.

Constructor
def __init__(
    self,
    name: str,
    entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> DictValue

ForItemsOperation [source]

class ForItemsOperation(HasNestedOps, Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    key_var_values: tuple[Value, ...] | None = None,
    value_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include the per-key/value Value fields for cloning/substitution.

Same rationale as ForOperation.all_input_values: keep the IR identity fields in lockstep with body references so UUID-keyed lookups stay valid after inline cloning. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the items-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing key/value formals, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the items-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt items-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


NotOp [source]

class NotOp(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


SelectOperation [source]

class SelectOperation(Operation)

Quantum multiplexer: apply case_blocks[i] when the index reads i.

Concrete operand layout: [idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...]. Symbolic-width operand layout: [idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...]. Results mirror the quantum operand grouping.

A concrete index register is normalized to one scalar Qubit operand per physical index qubit. A symbolic-width register instead retains each leading caller argument as one scalar or array operand until its bound shape is known. Whole-Vector[Qubit] / scalar targets follow and keep their shapes, and classical parameters shared across every case come last.

Index bit order is LSB-first: idx_0 is the least-significant bit, matching Qamomile’s qubit-zero convention. Case i is selected when index qubit j reads bit j of i. len(case_blocks) need not be a power of two; index values >= len(case_blocks) apply no operation (identity).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_index_qubits: int | Value = 0,
    case_blocks: list[Block] = list(),
    num_index_args: int = 0,
    case_callable_attrs: list[dict[str, Any]] = list(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Return every value consumed by the SELECT operation.

Returns:

list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width value when present.

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed replacement values.

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


SliceArrayOperation [source]

class SliceArrayOperation(Operation)

Construct a strided view of an ArrayValue.

The op itself performs no quantum action — it records that the result ArrayValue is a strided view of the operand parent with the given start / step. The result’s slice_of / slice_start / slice_step fields carry the affine map used by the emit-time resolver.

SliceArrayOperation is classified as :attr:OperationKind.CLASSICAL because slicing is pure index selection — no new quantum operation is introduced. The pipeline keeps this op through PartialEvaluationPass (which invokes ConstantFoldingPass(..., strip_slice_ops=False)) so the post-fold :class:~qamomile.circuit.transpiler.passes.slice_borrow_check.SliceBorrowCheckPass can use it as a view-declaration marker; once that check has run, StripSliceArrayOpsPass removes every SliceArrayOperation / ReleaseSliceViewOperation so segmentation (:mod:~qamomile.circuit.transpiler.passes.separate) and the downstream emit stage only see a pure quantum-op stream. By the time :mod:~qamomile.circuit.transpiler.passes.separate runs the op has therefore been stripped — reaching emit is a compiler- internal invariant violation.

Example:

``q[1::2]`` on a ``Vector[Qubit]`` emits::

    SliceArrayOperation(
        operands=[q_value, uint_1, uint_2],
        results=[sliced_value],  # slice_of=q_value, slice_start=uint_1, slice_step=uint_2
    )
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

TupleValue [source]

class TupleValue(_MetadataValueMixin, ValueBase)

A tuple of IR values for structured data.

Constructor
def __init__(
    self,
    name: str,
    elements: tuple[ValueLike, ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> TupleValue

UnaryMathOp [source]

class UnaryMathOp(Operation)

Represent one pure unary mathematical expression.

Parameters:

NameTypeDescription
operandslist[Value]Single numeric input value.
resultslist[Value]Single numeric result value.
kindUnaryMathOpKind | NoneMathematical operation to apply.

Raises:

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: UnaryMathOpKind | None = None,
) -> None
Attributes

ValidationError [source]

class ValidationError(QamomileCompileError)

Error during validation (e.g., non-classical I/O).

Constructor
def __init__(self, message: str, value_name: str | None = None)

Initialize a validation diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable validation failure.
value_namestr | NoneRelated IR value name. Defaults to None.
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 engine 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.


ValueResolver [source]

class ValueResolver

Resolve IR Values to concrete Python values.

Parameters:

NameTypeDescription
contextdict[str, Any] | NoneUUID-keyed map of already resolved values. The values may be either raw Python scalars or Value objects; if a Value is found its get_const() is extracted automatically.
bindingsdict[str, Any] | NoneName-keyed parameter bindings supplied by the user at transpile time.
Constructor
def __init__(
    self,
    context: dict[str, Any] | None = None,
    bindings: dict[str, Any] | None = None,
)

Create a resolver with optional context and bindings.

Parameters:

NameTypeDescription
contextdict[str, Any] | NoneUUID-keyed map of already-resolved values. Defaults to None.
bindingsdict[str, Any] | NoneName-keyed parameter bindings supplied by the user. Defaults to None.
Methods
resolve
def resolve(self, value: Any) -> Any | None

Resolve a Value-like object to a concrete Python value.

If value is not a Value-like object (no uuid attribute) it is returned as-is — the caller already has a concrete value.

Parameters:

NameTypeDescription
valueAnyThe Value-like object or already concrete value to resolve.

Returns:

Any | None — Any | None: The resolved concrete value, the original concrete value for non-Value inputs, or None when no resolution rule applies.


qamomile.circuit.transpiler.passes.circuit_shot_validation

Validate shot context in reachable circuit-family bodies.

Overview

FunctionDescription
block_parameter_binding_keysReturn the sanctioned emit-binding keys for an inner formal.
lower_compile_time_ifs_preserving_loop_conditionsSpecialize compile-time branches without erasing loop conditions.
pair_block_parameter_operandsPair a block’s classical/object inputs with call-site operands.
reachable_nested_regionsReturn nested regions that may execute for one control-flow operation.
validate_circuit_shot_contextReject shot context only in reachable circuit-family bodies.
ClassDescription
BlockUnified block representation for all pipeline stages.
ControlledUOperationBase class for controlled-U operations.
GetCurrentShotOperationRead the zero-based index of the current device program repetition.
HasNestedOpsMixin for operations that contain nested operation lists.
InverseBlockOperationRepresent an inverse qkernel/block as a first-class IR operation.
InvokeOperationRepresent a composite, stdlib, or oracle call.
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
TargetCapabilityErrorA program requires a capability the selected target does not declare.
ValueBaseNominal base for every typed IR value.
ValueResolverResolve IR Values to concrete Python values.

Functions

block_parameter_binding_keys [source]

def block_parameter_binding_keys(parameter: ValueBase) -> tuple[str, ...]

Return the sanctioned emit-binding keys for an inner formal.

Emit resolution accepts a kernel parameter name before its UUID for public API compatibility, so an operation-owned fresh scope must write both keys. Keeping the key choice here prevents individual emit paths from reviving a parent binding that merely shares the inner formal’s display name.

Parameters:

NameTypeDescription
parameterValueBaseClassical/object formal input being bound.

Returns:

tuple[str, ...] — tuple[str, ...]: UUID followed by the formal parameter provenance name and nonempty display-name compatibility key, without duplicates.


lower_compile_time_ifs_preserving_loop_conditions [source]

def lower_compile_time_ifs_preserving_loop_conditions(block: Block, bindings: dict[str, Any] | None = None) -> Block

Specialize compile-time branches without erasing loop conditions.

Parameters:

NameTypeDescription
blockBlockBlock whose resolvable compile-time branches should be lowered.
bindingsdict[str, Any] | NoneCompile-time input bindings used for condition resolution. Defaults to None.

Returns:

Block — Specialized block with loop-carried conditions preserved.

Raises:


pair_block_parameter_operands [source]

def pair_block_parameter_operands(
    block: Block,
    param_operands: Sequence[ValueBase],
) -> list[tuple[ValueBase, ValueBase]]

Pair a block’s classical/object inputs with call-site operands.

Both compile-time lowering and emission bind an operation-owned block’s non-quantum inputs by their declaration order. Keeping the filtering and pairing here ensures those stages cannot adopt different positional conventions.

Parameters:

NameTypeDescription
blockBlockOperation-owned block whose formal inputs define the declaration order.
param_operandsSequence[ValueBase]Classical or object operands at the call site, already ordered according to the operation signature.

Returns:

list[tuple[ValueBase, ValueBase]] — list[tuple[ValueBase, ValueBase]]: (formal, actual) pairs in list[tuple[ValueBase, ValueBase]] — declaration order. Missing actual operands leave trailing formals list[tuple[ValueBase, ValueBase]] — unpaired, so they can remain symbolic and be provided at emit time.


reachable_nested_regions [source]

def reachable_nested_regions(operation: HasNestedOps) -> tuple[Region, ...]

Return nested regions that may execute for one control-flow operation.

Constant conditionals expose only their selected branch. Statically empty counted and items loops expose no body region. All unresolved control flow remains conservative and exposes every region.

Parameters:

NameTypeDescription
operationHasNestedOpsStructured-control operation to inspect.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Regions that are reachable under compile-time-known control decisions.


validate_circuit_shot_context [source]

def validate_circuit_shot_context(block: Block, bindings: dict[str, Any] | None, *, target: str) -> None

Reject shot context only in reachable circuit-family bodies.

Circuit lowering selects engine-generic callable decompositions using the circuit_ir selector. Backend-specific alternatives are metadata for other consumers and must not impose their capabilities here. Specialize operation-owned bodies in their own parameter scope before inspecting them, just as the entrypoint is inspected after pruning.

Parameters:

NameTypeDescription
blockBlockPartially evaluated circuit entrypoint.
bindingsdict[str, Any] | NoneCompile-time entrypoint bindings.
targetstrTarget name used in capability errors.

Raises:

Classes

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.


ControlledUOperation [source]

class ControlledUOperation(Operation)

Base class for controlled-U operations.

Two concrete subclasses handle distinct operand layouts:

All isinstance(op, ControlledUOperation) checks match every subclass.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int | Value = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]
replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

GetCurrentShotOperation [source]

class GetCurrentShotOperation(Operation)

Read the zero-based index of the current device program repetition.

The value is stable throughout one repetition and is supplied by the execution target, never by compile-time bindings or a host-side counter.

Parameters:

NameTypeDescription
operandslist[Value]Empty operand list.
resultslist[Value]One nonconstant UInt result.
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


InverseBlockOperation [source]

class InverseBlockOperation(Operation)

Represent an inverse qkernel/block as a first-class IR operation.

The operation stores both the original forward block and a Qamomile-built inverse implementation block. Emitters may use source_block with a engine-native inverse/adjoint primitive, then fall back to implementation_block when native inversion is unavailable.

Operands are ordered as scalar control qubits, target quantum operands, then classical/object parameters. Results mirror the quantum operand layout: control results first, then one target result per target operand. Vector target operands therefore count as one operand/result while contributing their scalar width to num_target_qubits.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_control_qubits: int = 0,
    num_target_qubits: int = 0,
    custom_name: str = '',
    source_block: Block | None = None,
    implementation_block: Block | None = None,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_value: int | None = None,
) -> None
Attributes

InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.
Constructor
def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes
Methods
body_for_transform
def body_for_transform(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> tuple[Block | None, CallTransform]

Select a body and report the transform it already realizes.

A controlled-inverse invocation may reuse an explicitly registered inverse body when no implementation realizes both transforms. Keeping that fallback in the IR operation gives emitters and static analyses one selection rule while still letting each consumer apply the remaining coherent controls in its own representation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — tuple[Block | None, CallTransform]: Selected body and the transform CallTransform — already implemented by that body. The callable’s direct body is tuple[Block | None, CallTransform] — returned with DIRECT when no transform-specific body matches.

Raises:

effective_body
def effective_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — Block | None: Selected implementation body, or the callable’s Block | None — default body when no transform-specific implementation exists. Block | None — A compiler may synthesize inverse or controlled behavior from this Block | None — fallback body.

implementation_for
def implementation_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None, which only selects engine-generic implementations.
strategystr | NoneStrategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation candidate, CallableImplementation | None — or None when the callable definition has no match.

measurement_result_indices_for
def measurement_result_indices_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> frozenset[int]

Return measurement-derived results for one selected implementation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name used for implementation selection. Defaults to None.
strategystr | NoneStrategy name used for implementation selection. Defaults to the invocation’s strategy_name.

Returns:

frozenset[int] — frozenset[int]: Caller-local result positions derived from measurement in the selected body.

Raises:

select_body
def select_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> CallableBodySelection

Select and validate the composable body for this invocation.

The result carries the transform already realized by the body and the exact call-site values that bind to it. Consumers therefore cannot independently disagree about whether an invocation’s control prefix belongs to the selected implementation ABI.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

CallableBodySelection — Validated body, realized transform, and CallableBodySelection — aligned call-site operands and results.

Raises:


SelectOperation [source]

class SelectOperation(Operation)

Quantum multiplexer: apply case_blocks[i] when the index reads i.

Concrete operand layout: [idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...]. Symbolic-width operand layout: [idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...]. Results mirror the quantum operand grouping.

A concrete index register is normalized to one scalar Qubit operand per physical index qubit. A symbolic-width register instead retains each leading caller argument as one scalar or array operand until its bound shape is known. Whole-Vector[Qubit] / scalar targets follow and keep their shapes, and classical parameters shared across every case come last.

Index bit order is LSB-first: idx_0 is the least-significant bit, matching Qamomile’s qubit-zero convention. Case i is selected when index qubit j reads bit j of i. len(case_blocks) need not be a power of two; index values >= len(case_blocks) apply no operation (identity).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_index_qubits: int | Value = 0,
    case_blocks: list[Block] = list(),
    num_index_args: int = 0,
    case_callable_attrs: list[dict[str, Any]] = list(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Return every value consumed by the SELECT operation.

Returns:

list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width value when present.

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed replacement values.

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


TargetCapabilityError [source]

class TargetCapabilityError(EmitError)

A program requires a capability the selected target does not declare.

Raised by circuit-IR target-legality verification before any engine materialization starts. The message always names the target and the missing capability axis, so the failure reads as a target restriction rather than a Qamomile language error.

Parameters:

NameTypeDescription
messagestrHuman-readable diagnosis naming the target and the missing capability.
targetstr | NoneDeclared target name. Defaults to None.
operationstr | NoneInstruction description that triggered the failure. Defaults to None.

Example:

Correct — bind the runtime parameter before selecting a
concrete-angle-only target::

    transpiler.transpile(kernel, bindings={"theta": 0.5})

Incorrect — keeping ``theta`` symbolic on such a target raises this
error::

    transpiler.transpile(kernel, parameters=["theta"])
Constructor
def __init__(self, message: str, target: str | None = None, operation: str | None = None)

Initialize a target-capability diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable diagnosis naming the target and the missing capability.
targetstr | NoneDeclared target name. Defaults to None.
operationstr | NoneInstruction description that triggered the failure. Defaults to None.
Attributes

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.


ValueResolver [source]

class ValueResolver

Resolve IR Values to concrete Python values.

Parameters:

NameTypeDescription
contextdict[str, Any] | NoneUUID-keyed map of already resolved values. The values may be either raw Python scalars or Value objects; if a Value is found its get_const() is extracted automatically.
bindingsdict[str, Any] | NoneName-keyed parameter bindings supplied by the user at transpile time.
Constructor
def __init__(
    self,
    context: dict[str, Any] | None = None,
    bindings: dict[str, Any] | None = None,
)

Create a resolver with optional context and bindings.

Parameters:

NameTypeDescription
contextdict[str, Any] | NoneUUID-keyed map of already-resolved values. Defaults to None.
bindingsdict[str, Any] | NoneName-keyed parameter bindings supplied by the user. Defaults to None.
Methods
resolve
def resolve(self, value: Any) -> Any | None

Resolve a Value-like object to a concrete Python value.

If value is not a Value-like object (no uuid attribute) it is returned as-is — the caller already has a concrete value.

Parameters:

NameTypeDescription
valueAnyThe Value-like object or already concrete value to resolve.

Returns:

Any | None — Any | None: The resolved concrete value, the original concrete value for non-Value inputs, or None when no resolution rule applies.


qamomile.circuit.transpiler.passes.classical_lowering

Classical-op lowering pass: identify runtime-evaluation classical ops.

Walks the block, identifies CompOp / CondOp / NotOp / BinOp instances whose operand dataflow traces back to a MeasureOperation (i.e. cannot be folded at compile-time, by emit-time loop unrolling, or by compile_time_if_lowering), and replaces them with the equivalent RuntimeClassicalExpr.

It also lowers the scalar classical merge slots of measurement-conditioned runtime IfOperations to RuntimeClassicalExpr(SELECT) expressions (result = true if cond else false), so branch merges ride the same runtime-expression machinery as every other measurement-derived classical op: consumer-based segment placement, host-side per-shot evaluation, and engine runtime-expression emission. See :meth:_lower_if_merges.

Why this pass exists:

The pre-RuntimeClassicalExpr design left runtime classical ops in their compile-time IR form (CompOp etc.) all the way to emit, where the emit pass had to fold-or-translate via evaluate_classical_predicate

By identifying runtime classical ops at IR level and giving them their own node type, we:

Overview

FunctionDescription
collect_value_like_uuidsCollect UUIDs contained in a value-like IR object.
runtime_kind_from_binopMap a BinOpKind to its RuntimeOpKind counterpart.
runtime_kind_from_compopMap a CompOpKind to its RuntimeOpKind counterpart.
runtime_kind_from_condopMap a CondOpKind to its RuntimeOpKind counterpart.
ClassDescription
ArrayValueAn array of typed IR values.
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
BinOpKind
BitTypeType representing a classical bit.
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
ClassicalLoweringPassLower measurement-derived classical ops to RuntimeClassicalExpr.
CompOpComparison operation (EQ, NEQ, LT, LE, GT, GE).
CondOpConditional logical operation (AND, OR).
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
HasNestedOpsMixin for operations that contain nested operation lists.
IfMergeOne branch-merge slot of an :class:IfOperation.
IfOperationRepresents an if-else conditional operation.
MeasureOperation
NotOp
OperationKindClassification of operations for classical/quantum separation.
PassBase class for all compiler passes.
RuntimeClassicalExprA classical expression known to require runtime evaluation.
RuntimeOpKindUnified kind for RuntimeClassicalExpr covering all classical
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.
WhileOperationRepresents a while loop operation.

Constants

Functions

collect_value_like_uuids [source]

def collect_value_like_uuids(value: 'ValueLike') -> set[str]

Collect UUIDs contained in a value-like IR object.

Parameters:

NameTypeDescription
valueValueLikeValue-like object to inspect.

Returns:

set[str] — set[str]: UUIDs for value itself, recursively contained tuple/dict elements, and array view/element dependencies.


runtime_kind_from_binop [source]

def runtime_kind_from_binop(kind: BinOpKind) -> RuntimeOpKind

Map a BinOpKind to its RuntimeOpKind counterpart.


runtime_kind_from_compop [source]

def runtime_kind_from_compop(kind: CompOpKind) -> RuntimeOpKind

Map a CompOpKind to its RuntimeOpKind counterpart.


runtime_kind_from_condop [source]

def runtime_kind_from_condop(kind: CondOpKind) -> RuntimeOpKind

Map a CondOpKind to its RuntimeOpKind counterpart.

Classes

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:

bool — True iff slice_of is non-None.

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

BinOp [source]

class BinOp(BinaryOperationBase)

Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: BinOpKind | None = None,
) -> None
Attributes

BinOpKind [source]

class BinOpKind(enum.Enum)
Attributes

BitType [source]

class BitType(ClassicalTypeMixin, ValueType)

Type representing a classical bit.


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.


BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

ClassicalLoweringPass [source]

class ClassicalLoweringPass(Pass[Block, Block])

Lower measurement-derived classical ops to RuntimeClassicalExpr.

Input: Block with BlockKind.ANALYZED. Output: Block with BlockKind.ANALYZED (same kind; only op rewrites).

The pass:

  1. Builds a measurement-taint set using the same dataflow utilities as AnalyzePass (forward propagation from MeasureOperation results through the dependency graph).

  2. Walks operations recursively (through HasNestedOps).

  3. For each engine-expressible CompOp / CondOp / NotOp / BinOp whose result UUID is in the taint set, replaces it with an equivalent RuntimeClassicalExpr (same operands and result Value, only the op type and kind enum change). Internal slice-clamp MIN operations stay as host-side BinOp nodes because Circuit IR has no runtime minimum expression.

  4. Non-tainted classical ops are left unchanged so the existing fold paths (compile-time fold in compile_time_if_lowering, emit-time fold in evaluate_classical_predicate) continue to handle them.

The dependency graph and taint set are computed once, walked once, so the pass is O(N) where N is the number of operations.

Attributes
Methods
run
def run(self, input: Block) -> Block

CompOp [source]

class CompOp(BinaryOperationBase)

Comparison operation (EQ, NEQ, LT, LE, GT, GE).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CompOpKind | None = None,
) -> None
Attributes

CondOp [source]

class CondOp(BinaryOperationBase)

Conditional logical operation (AND, OR).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CondOpKind | None = None,
) -> None
Attributes

ForItemsOperation [source]

class ForItemsOperation(HasNestedOps, Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    key_var_values: tuple[Value, ...] | None = None,
    value_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include the per-key/value Value fields for cloning/substitution.

Same rationale as ForOperation.all_input_values: keep the IR identity fields in lockstep with body references so UUID-keyed lookups stay valid after inline cloning. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the items-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing key/value formals, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the items-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt items-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


IfMerge [source]

class IfMerge(NamedTuple)

One branch-merge slot of an :class:IfOperation.

An IfOperation merges each variable touched by its branches back into a single SSA value. IfMerge is the read-side view of one such merge slot, decoupling every consumer from how the merge is stored in the IR (today the parallel IfOperation.true_yields / false_yields lists; the storage may change without touching consumers).

Attributes
Methods
select
def select(self, taken: bool) -> Value

Return the branch source selected by a resolved condition.

Parameters:

NameTypeDescription
takenboolThe condition’s truth value (True selects the true branch).

Returns:

Value — true_value when taken is true, else false_value.


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


MeasureOperation [source]

class MeasureOperation(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

NotOp [source]

class NotOp(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

OperationKind [source]

class OperationKind(enum.Enum)

Classification of operations for classical/quantum separation.

This enum is used to categorize operations during compilation to determine which parts run on classical hardware vs quantum hardware.

Values:

QUANTUM: Pure quantum operations (gates, qubit allocation) CLASSICAL: Pure classical operations (arithmetic, comparisons) HYBRID: Operations that bridge classical and quantum (measurement, encode/decode) CONTROL: Control flow structures (for, while, if)

Attributes

Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


RuntimeClassicalExpr [source]

class RuntimeClassicalExpr(Operation)

A classical expression known to require runtime evaluation.

Lowered from CompOp / CondOp / NotOp / BinOp by ClassicalLoweringPass when the op’s operand dataflow traces back to a MeasureOperation (i.e. cannot be folded at compile-time, by emit-time loop unrolling, or by compile_time_if_lowering). Engine emit translates this 1:1 to an engine-native runtime expression (e.g. qiskit.circuit.classical.expr.Expr).

Operand convention:

The single-node + unified-kind shape (vs four parallel subclasses) keeps the engine dispatch a single match op.kind instead of four parallel hooks, and makes the IR self-documenting: a single RuntimeClassicalExpr instance signals “runtime evaluation required” regardless of which classical family it came from.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: RuntimeOpKind | None = None,
) -> None
Attributes

RuntimeOpKind [source]

class RuntimeOpKind(enum.Enum)

Unified kind for RuntimeClassicalExpr covering all classical op families that can appear at runtime.

The split between this enum and the per-family BinOpKind / CompOpKind / CondOpKind is intentional: compile-time-foldable classical ops keep their original IR types so the existing fold pipeline (constant_fold → compile_time_if_lowering → emit-time evaluate_classical_predicate) is undisturbed. Only ops identified as runtime-evaluation-only by ClassicalLoweringPass get rewritten to RuntimeClassicalExpr with a member of this enum.

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


WhileOperation [source]

class WhileOperation(HasNestedOps, Operation)

Represents a while loop operation.

Only measurement-backed conditions are supported: the condition must be a Bit value produced by qmc.measure(). Non-measurement conditions (classical variables, constants, comparisons) are rejected by ValidateWhileContractPass before reaching engine emit.

Example::

bit = qmc.measure(q)
while bit:
    q = qmc.h(q)
    bit = qmc.measure(q)
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    operations: list[Operation] = list(),
    max_iterations: int | None = None,
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include rebind records and region args for cloning/substitution.

Same rationale as ForOperation.all_input_values: rebind records and region arguments reference body/pre-loop values by identity, so inline cloning must remap them in lockstep with body operands.

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus rebind-record and region-argument values.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the while body with explicit boundary values.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region whose block arguments and yields are aligned with region_args. The updated condition, when present, is appended as the final yield.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the while body and its complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt while operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, rebind-record, and region-arg values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


qamomile.circuit.transpiler.passes.compile_time_if_lowering

Compile-time IfOperation lowering pass.

Lowers compile-time resolvable IfOperations before the segmentation pass, replacing them with selected-branch operations and substituting merge outputs with selected-branch values throughout the block.

This prevents SegmentationPass from seeing classical-only compile-time IfOperations that would otherwise split quantum segments.

Overview

FunctionDescription
array_static_lengthResolve a one-dimensional array’s compile-time length.
collect_value_like_uuidsCollect UUIDs contained in a value-like IR object.
evaluate_classical_op_concreteTry to evaluate a classical op and record its concrete result.
find_loop_carried_condition_uuidsFind branch conditions that read legacy loop-carried scalar Bits.
genuine_input_valuesReturn an operation’s input values that count as genuine reads.
lower_compile_time_ifs_preserving_loop_conditionsSpecialize compile-time branches without erasing loop conditions.
packed_register_type_widthReturn the type-declared width of a packed quantum register type.
pair_block_parameter_operandsPair a block’s classical/object inputs with call-site operands.
resolve_compile_time_conditionResolve an IfOperation condition to a compile-time bool.
root_carrier_keysBuild root-space carrier keys for the first count array elements.
same_exact_typed_constantReturn whether two scalar Values carry the same exact typed constant.
validate_region_argsValidate the SSA identities owned by a loop’s region arguments.
ClassDescription
ArrayValueAn array of typed IR values.
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
CompOpComparison operation (EQ, NEQ, LT, LE, GT, GE).
CompileTimeIfLoweringPassLowers compile-time resolvable IfOperations before separation.
CondOpConditional logical operation (AND, OR).
ControlledUOperationBase class for controlled-U operations.
DictValueA dictionary value stored as stable ordered entries.
FloatTypeType representing a floating-point number.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
HasNestedOpsMixin for operations that contain nested operation lists.
IfOperationRepresents an if-else conditional operation.
InverseBlockOperationRepresent an inverse qkernel/block as a first-class IR operation.
InvokeOperationRepresent a composite, stdlib, or oracle call.
MeasureQFixedOperationMeasure a quantum fixed-point number.
MeasureVectorOperationMeasure a vector of qubits.
NotOp
OperationKindClassification of operations for classical/quantum separation.
PassBase class for all compiler passes.
QFixedTypeQuantum fixed-point type.
QInitOperationInitialize the qubit
QUIntTypeQuantum unsigned integer type.
RegionArgExplicit loop-carried value on a loop operation (MLIR-style iter_arg).
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
UIntTypeType representing an unsigned integer.
UnaryMathOpRepresent one pure unary mathematical expression.
UnifiedValueResolverResolve IR Values to concrete Python values.
ValidationErrorError during validation (e.g., non-classical I/O).
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.
WhileOperationRepresents a while loop operation.

Constants

Functions

array_static_length [source]

def array_static_length(array: 'ArrayValue') -> int | None

Resolve a one-dimensional array’s compile-time length.

Parameters:

NameTypeDescription
arrayArrayValueArray whose sole shape dimension is inspected.

Returns:

int | None — int | None: Non-negative static length, or None when the array is not one-dimensional, its length is symbolic/non-integral, or it is malformed with a negative length. Boolean constants are rejected even though bool is an int subclass.


collect_value_like_uuids [source]

def collect_value_like_uuids(value: 'ValueLike') -> set[str]

Collect UUIDs contained in a value-like IR object.

Parameters:

NameTypeDescription
valueValueLikeValue-like object to inspect.

Returns:

set[str] — set[str]: UUIDs for value itself, recursively contained tuple/dict elements, and array view/element dependencies.


evaluate_classical_op_concrete [source]

def evaluate_classical_op_concrete(
    op: Operation,
    concrete_values: dict[str, Any],
    bindings: dict[str, Any],
) -> None

Try to evaluate a classical op and record its concrete result.

Supported operation types:

Delegates the actual fold to fold_classical_op under the COMPILE_TIME policy, which bypasses the runtime-parameter guard: everything in bindings is treated as a real compile-time value. Other operation types are silently ignored. If evaluation fails, nothing is recorded and downstream IfOperations referencing the result remain unresolved.

Parameters:

NameTypeDescription
opOperationThe operation to evaluate.
concrete_valuesdict[str, Any]UUID-keyed map of concrete results; the op’s result is recorded here on success. Updated in place.
bindingsdict[str, Any]Compile-time parameter bindings used to resolve operands.

find_loop_carried_condition_uuids [source]

def find_loop_carried_condition_uuids(operations: Sequence[Operation]) -> set[str]

Find branch conditions that read legacy loop-carried scalar Bits.

Compile-time specialization normally removes a branch whose first traced condition is a constant. That is unsafe while recursively unrolling a body when the same condition reads a legacy loop-carried Bit: later iterations observe the refreshed value, so the final loop-state validator still needs the branch as dependency evidence.

Parameters:

NameTypeDescription
operationsSequence[Operation]Semantic operation tree to inspect.

Returns:

set[str] — set[str]: UUIDs of conditions that transitively depend on a legacy scalar Bit entry value.


genuine_input_values [source]

def genuine_input_values(op: Operation) -> list[ValueBase]

Return an operation’s input values that count as genuine reads.

Structured operations derive reads from their explicit region interface: enclosing operands, captures, loop initializers, and region yields. Block arguments and operation results are definitions, while legacy rebind records are diagnostics rather than dataflow. Leaf operations keep their ordinary all_input_values contract.

Parameters:

NameTypeDescription
opOperationOperation to inspect.

Returns:

list[ValueBase] — list[ValueBase]: Semantic reads in interface order.


lower_compile_time_ifs_preserving_loop_conditions [source]

def lower_compile_time_ifs_preserving_loop_conditions(block: Block, bindings: dict[str, Any] | None = None) -> Block

Specialize compile-time branches without erasing loop conditions.

Parameters:

NameTypeDescription
blockBlockBlock whose resolvable compile-time branches should be lowered.
bindingsdict[str, Any] | NoneCompile-time input bindings used for condition resolution. Defaults to None.

Returns:

Block — Specialized block with loop-carried conditions preserved.

Raises:


packed_register_type_width [source]

def packed_register_type_width(value_type: ValueType) -> int | None

Return the type-declared width of a packed quantum register type.

Unlike :func:static_quantum_width, this helper consults only the type and never runtime carrier or fixed-point metadata, so it distinguishes a register whose width is known to be zero (returns 0) from one whose width is symbolic (returns None). static_quantum_width cannot make that distinction for a QFixed whose frontend qfixed metadata records num_bits=0 for a symbolic layout.

Parameters:

NameTypeDescription
value_typeValueTypeType to inspect. Only QUIntType and QFixedType describe packed registers.

Returns:

int | None — int | None: QUIntType.width or QFixedType.integer_bits + fractional_bits when every component is a compile-time non-negative integer; None when any component is symbolic or when value_type is not a packed register type.


pair_block_parameter_operands [source]

def pair_block_parameter_operands(
    block: Block,
    param_operands: Sequence[ValueBase],
) -> list[tuple[ValueBase, ValueBase]]

Pair a block’s classical/object inputs with call-site operands.

Both compile-time lowering and emission bind an operation-owned block’s non-quantum inputs by their declaration order. Keeping the filtering and pairing here ensures those stages cannot adopt different positional conventions.

Parameters:

NameTypeDescription
blockBlockOperation-owned block whose formal inputs define the declaration order.
param_operandsSequence[ValueBase]Classical or object operands at the call site, already ordered according to the operation signature.

Returns:

list[tuple[ValueBase, ValueBase]] — list[tuple[ValueBase, ValueBase]]: (formal, actual) pairs in list[tuple[ValueBase, ValueBase]] — declaration order. Missing actual operands leave trailing formals list[tuple[ValueBase, ValueBase]] — unpaired, so they can remain symbolic and be provided at emit time.


resolve_compile_time_condition [source]

def resolve_compile_time_condition(
    condition: Any,
    concrete_values: dict[str, Any],
    bindings: dict[str, Any],
) -> bool | None

Resolve an IfOperation condition to a compile-time bool.

Single source of truth for classifying an if-condition as compile-time taken / dead / runtime. Used by :class:CompileTimeIfLoweringPass to decide which branches to lower and by reject_self_referential_loop_stores to prune the same branches from its scan — both callers must agree on the classification, so they share this function.

Tries resolve_if_condition first (plain Python values, constant Values, direct UUID / parameter-provenance bindings), then falls back to the accumulated concrete_values map for expression-derived conditions (CompOp / CondOp / NotOp / BinOp chains evaluated by :func:evaluate_classical_op_concrete).

Parameters:

NameTypeDescription
conditionAnyThe condition operand. May be a plain Python value or a Value.
concrete_valuesdict[str, Any]UUID-keyed map of concrete classical-op results accumulated in program order.
bindingsdict[str, Any]Compile-time parameter bindings.

Returns:

bool | None — bool | None: The condition’s compile-time truth value, or None when it is not compile-time resolvable (a runtime condition).


root_carrier_keys [source]

def root_carrier_keys(array: 'ArrayValue', count: int) -> tuple[list[str], list[str]] | None

Build root-space carrier keys for the first count array elements.

Folds each view-local index through :func:resolve_root_array_index and spells the result with :func:composite_carrier_key, so packed register (QInt and QFixed) carriers produced by the frontend cast, rebuilt by compile-time if lowering, and re-derived by serialization validation all share one key producer.

Callers are responsible for bounding count by the array’s static length: this helper performs no bounds check because its None result must keep the single meaning “a slice bound on the chain is symbolic or out of contract, defer resolution”. Serialization validation compares count against array_static_length before calling; compile-time if lowering does the same whenever the selected source has a static length and otherwise trusts the trace-time carrier count.

Parameters:

NameTypeDescription
arrayArrayValueOne-dimensional qubit array, either a root array or an arbitrarily nested strided view.
countintNumber of leading elements to key, in array’s own index space.

Returns:

tuple[list[str], list[str]] | None — tuple[list[str], list[str]] | None: Parallel (uuids, logical_ids) carrier keys, (root.uuid, root_index) and (root.logical_id, root_index) respectively, or None when any index cannot be folded to the root index space.


same_exact_typed_constant [source]

def same_exact_typed_constant(left: Value, right: Value) -> bool

Return whether two scalar Values carry the same exact typed constant.

Equality requires matching IR and Python types. Floating-point comparison preserves the sign of zero and the payload bits of NaNs.

Parameters:

NameTypeDescription
leftValueFirst scalar value to compare.
rightValueSecond scalar value to compare.

Returns:

bool — True only for constants of the same IR type and Python type with equal value representations.


validate_region_args [source]

def validate_region_args(op: ForOperation | ForItemsOperation | WhileOperation) -> tuple[RegionArg, ...]

Validate the SSA identities owned by a loop’s region arguments.

A loop owns several definition namespaces: its iteration variables, every RegionArg.block_arg, and every RegionArg.result. Those identities must be pairwise disjoint. Otherwise different stages can assign incompatible meanings to one UUID: a UUID-keyed environment has only one slot, so binding either the iteration variable or the carried value overwrites the other and makes both reads observe the same value.

Parameters:

NameTypeDescription
opForOperation | ForItemsOperation | WhileOperationLoop operation whose region arguments should be validated.

Returns:

tuple[RegionArg, ...] — tuple[RegionArg, ...]: The validated op.region_args tuple.

Raises:

Classes

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:

bool — True iff slice_of is non-None.

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

BinOp [source]

class BinOp(BinaryOperationBase)

Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: BinOpKind | None = None,
) -> None
Attributes

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.


BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

CompOp [source]

class CompOp(BinaryOperationBase)

Comparison operation (EQ, NEQ, LT, LE, GT, GE).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CompOpKind | None = None,
) -> None
Attributes

CompileTimeIfLoweringPass [source]

class CompileTimeIfLoweringPass(Pass[Block, Block])

Lowers compile-time resolvable IfOperations before separation.

After constant folding, some IfOperation conditions are statically known but remain as control-flow nodes. SegmentationPass treats them as segment boundaries, causing MultipleQuantumSegmentsError for classical-only compile-time if after quantum init.

This pass:

  1. Evaluates conditions including expression-derived ones (CompOp, CondOp, NotOp, BinOp, and UnaryMathOp chains).

  2. Replaces resolved IfOperations with selected-branch operations.

  3. Substitutes merge output UUIDs with selected-branch values in all subsequent operations and block outputs.

Constructor
def __init__(
    self,
    bindings: dict[str, Any] | None = None,
    *,
    preserved_condition_uuids: AbstractSet[str] | None = None,
    _under_controlled_unitary: bool = False,
    _active_block_ids: frozenset[int] | None = None,
)

Initialize compile-time if lowering state.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneCompile-time bindings visible in the current block. Defaults to no bindings.
preserved_condition_uuidsAbstractSet[str] | NoneConditions that must remain unresolved so a later validation pass can inspect their dataflow. Defaults to an empty set.
_under_controlled_unitaryboolInternal context flag indicating that boxed callables encountered here will be decomposed by the controlled emission walker and therefore need their owned bodies lowered too. Defaults to False.
_active_block_idsfrozenset[int] | NoneInternal recursion-path guard for operation-owned blocks. Defaults to an empty set.
Attributes
Methods
run
def run(self, input: Block) -> Block

Lower every compile-time resolvable IfOperation in the block.

Parameters:

NameTypeDescription
inputBlockBlock to lower. Must be TRACED, AFFINE, or HIERARCHICAL. TRACED is accepted so the circuit drawer can resolve bound/constant if conditions on a freshly traced block before the transpiler pipeline runs; HIERARCHICAL is accepted during the self-recursion unroll loop. Surviving inline callable invocations are passed through untouched in both cases.

Returns:

Block — New block with compile-time ifs replaced by their selected-branch operations and merge outputs substituted. The input’s BlockKind is preserved.

Raises:


CondOp [source]

class CondOp(BinaryOperationBase)

Conditional logical operation (AND, OR).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CondOpKind | None = None,
) -> None
Attributes

ControlledUOperation [source]

class ControlledUOperation(Operation)

Base class for controlled-U operations.

Two concrete subclasses handle distinct operand layouts:

All isinstance(op, ControlledUOperation) checks match every subclass.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int | Value = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]
replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

DictValue [source]

class DictValue(_MetadataValueMixin, ValueBase)

A dictionary value stored as stable ordered entries.

Constructor
def __init__(
    self,
    name: str,
    entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> DictValue

FloatType [source]

class FloatType(ClassicalTypeMixin, ValueType)

Type representing a floating-point number.


ForItemsOperation [source]

class ForItemsOperation(HasNestedOps, Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    key_var_values: tuple[Value, ...] | None = None,
    value_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include the per-key/value Value fields for cloning/substitution.

Same rationale as ForOperation.all_input_values: keep the IR identity fields in lockstep with body references so UUID-keyed lookups stay valid after inline cloning. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the items-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing key/value formals, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the items-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt items-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


InverseBlockOperation [source]

class InverseBlockOperation(Operation)

Represent an inverse qkernel/block as a first-class IR operation.

The operation stores both the original forward block and a Qamomile-built inverse implementation block. Emitters may use source_block with a engine-native inverse/adjoint primitive, then fall back to implementation_block when native inversion is unavailable.

Operands are ordered as scalar control qubits, target quantum operands, then classical/object parameters. Results mirror the quantum operand layout: control results first, then one target result per target operand. Vector target operands therefore count as one operand/result while contributing their scalar width to num_target_qubits.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_control_qubits: int = 0,
    num_target_qubits: int = 0,
    custom_name: str = '',
    source_block: Block | None = None,
    implementation_block: Block | None = None,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_value: int | None = None,
) -> None
Attributes

InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.
Constructor
def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes
Methods
body_for_transform
def body_for_transform(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> tuple[Block | None, CallTransform]

Select a body and report the transform it already realizes.

A controlled-inverse invocation may reuse an explicitly registered inverse body when no implementation realizes both transforms. Keeping that fallback in the IR operation gives emitters and static analyses one selection rule while still letting each consumer apply the remaining coherent controls in its own representation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — tuple[Block | None, CallTransform]: Selected body and the transform CallTransform — already implemented by that body. The callable’s direct body is tuple[Block | None, CallTransform] — returned with DIRECT when no transform-specific body matches.

Raises:

effective_body
def effective_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — Block | None: Selected implementation body, or the callable’s Block | None — default body when no transform-specific implementation exists. Block | None — A compiler may synthesize inverse or controlled behavior from this Block | None — fallback body.

implementation_for
def implementation_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None, which only selects engine-generic implementations.
strategystr | NoneStrategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation candidate, CallableImplementation | None — or None when the callable definition has no match.

measurement_result_indices_for
def measurement_result_indices_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> frozenset[int]

Return measurement-derived results for one selected implementation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name used for implementation selection. Defaults to None.
strategystr | NoneStrategy name used for implementation selection. Defaults to the invocation’s strategy_name.

Returns:

frozenset[int] — frozenset[int]: Caller-local result positions derived from measurement in the selected body.

Raises:

select_body
def select_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> CallableBodySelection

Select and validate the composable body for this invocation.

The result carries the transform already realized by the body and the exact call-site values that bind to it. Consumers therefore cannot independently disagree about whether an invocation’s control prefix belongs to the selected implementation ABI.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

CallableBodySelection — Validated body, realized transform, and CallableBodySelection — aligned call-site operands and results.

Raises:


MeasureQFixedOperation [source]

class MeasureQFixedOperation(Operation)

Measure a quantum fixed-point number.

This operation measures all qubits in a QFixed register and produces a Float result. During transpilation, this is lowered to individual MeasureOperations plus a DecodeQFixedOperation.

operands: [QFixed value (contains qubit_values in params)] results: [Float value]

Encoding:

For QPE phase (int_bits=0): Qubits are stored least-significant first. For n qubits, bit i has weight 2**(-n + i).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_bits: int = 0,
    int_bits: int = 0,
) -> None
Attributes

MeasureVectorOperation [source]

class MeasureVectorOperation(Operation)

Measure a vector of qubits.

Takes a Vector[Qubit] (ArrayValue) and produces a Vector[Bit] (ArrayValue). This operation measures all qubits in the vector as a single operation.

operands: [ArrayValue of qubits] results: [ArrayValue of bits]

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

NotOp [source]

class NotOp(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

OperationKind [source]

class OperationKind(enum.Enum)

Classification of operations for classical/quantum separation.

This enum is used to categorize operations during compilation to determine which parts run on classical hardware vs quantum hardware.

Values:

QUANTUM: Pure quantum operations (gates, qubit allocation) CLASSICAL: Pure classical operations (arithmetic, comparisons) HYBRID: Operations that bridge classical and quantum (measurement, encode/decode) CONTROL: Control flow structures (for, while, if)

Attributes

Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


QFixedType [source]

class QFixedType(QuantumTypeMixin, ValueType)

Quantum fixed-point type.

Represents a quantum register encoding a fixed-point number with specified integer and fractional bits.

Constructor
def __init__(
    self,
    integer_bits: int | Value[UIntType] = 0,
    fractional_bits: int | Value[UIntType] = 0,
) -> None
Attributes
Methods
label
def label(self) -> str

QInitOperation [source]

class QInitOperation(Operation)

Initialize the qubit

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

QUIntType [source]

class QUIntType(QuantumTypeMixin, ValueType)

Quantum unsigned integer type.

Represents a quantum register encoding an unsigned integer value using binary encoding (little-endian by default).

Constructor
def __init__(self, width: int | Value[UIntType]) -> None
Attributes
Methods
label
def label(self) -> str

RegionArg [source]

class RegionArg

Explicit loop-carried value on a loop operation (MLIR-style iter_arg).

A RegionArg makes a loop-carried dependency explicit in the IR, the way MLIR’s scf.for models iter_args / scf.yield:

The loop body’s operations reference block_arg (the frontend substitutes the traced pre-loop reads), and post-loop operations reference result (the frontend rebinds the Python handle when it closes the loop). result is also appended to the loop operation’s results list so dependency analysis sees the loop as its producer.

This subsumes the trace-once staleness that LoopCarriedRebind records exist to reject: a rebind represented as a RegionArg is a supported loop-carried value, not a miscompilation hazard.

Constructor
def __init__(
    self,
    var_name: str,
    init: Value,
    block_arg: Value,
    yielded: Value,
    result: Value,
) -> None
Attributes

SelectOperation [source]

class SelectOperation(Operation)

Quantum multiplexer: apply case_blocks[i] when the index reads i.

Concrete operand layout: [idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...]. Symbolic-width operand layout: [idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...]. Results mirror the quantum operand grouping.

A concrete index register is normalized to one scalar Qubit operand per physical index qubit. A symbolic-width register instead retains each leading caller argument as one scalar or array operand until its bound shape is known. Whole-Vector[Qubit] / scalar targets follow and keep their shapes, and classical parameters shared across every case come last.

Index bit order is LSB-first: idx_0 is the least-significant bit, matching Qamomile’s qubit-zero convention. Case i is selected when index qubit j reads bit j of i. len(case_blocks) need not be a power of two; index values >= len(case_blocks) apply no operation (identity).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_index_qubits: int | Value = 0,
    case_blocks: list[Block] = list(),
    num_index_args: int = 0,
    case_callable_attrs: list[dict[str, Any]] = list(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Return every value consumed by the SELECT operation.

Returns:

list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width value when present.

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed replacement values.

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


UIntType [source]

class UIntType(ClassicalTypeMixin, ValueType)

Type representing an unsigned integer.


UnaryMathOp [source]

class UnaryMathOp(Operation)

Represent one pure unary mathematical expression.

Parameters:

NameTypeDescription
operandslist[Value]Single numeric input value.
resultslist[Value]Single numeric result value.
kindUnaryMathOpKind | NoneMathematical operation to apply.

Raises:

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: UnaryMathOpKind | None = None,
) -> None
Attributes

ValueResolver [source]

class ValueResolver

Resolve IR Values to concrete Python values.

Parameters:

NameTypeDescription
contextdict[str, Any] | NoneUUID-keyed map of already resolved values. The values may be either raw Python scalars or Value objects; if a Value is found its get_const() is extracted automatically.
bindingsdict[str, Any] | NoneName-keyed parameter bindings supplied by the user at transpile time.
Constructor
def __init__(
    self,
    context: dict[str, Any] | None = None,
    bindings: dict[str, Any] | None = None,
)

Create a resolver with optional context and bindings.

Parameters:

NameTypeDescription
contextdict[str, Any] | NoneUUID-keyed map of already-resolved values. Defaults to None.
bindingsdict[str, Any] | NoneName-keyed parameter bindings supplied by the user. Defaults to None.
Methods
resolve
def resolve(self, value: Any) -> Any | None

Resolve a Value-like object to a concrete Python value.

If value is not a Value-like object (no uuid attribute) it is returned as-is — the caller already has a concrete value.

Parameters:

NameTypeDescription
valueAnyThe Value-like object or already concrete value to resolve.

Returns:

Any | None — Any | None: The resolved concrete value, the original concrete value for non-Value inputs, or None when no resolution rule applies.


ValidationError [source]

class ValidationError(QamomileCompileError)

Error during validation (e.g., non-classical I/O).

Constructor
def __init__(self, message: str, value_name: str | None = None)

Initialize a validation diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable validation failure.
value_namestr | NoneRelated IR value name. Defaults to None.
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 engine 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.


WhileOperation [source]

class WhileOperation(HasNestedOps, Operation)

Represents a while loop operation.

Only measurement-backed conditions are supported: the condition must be a Bit value produced by qmc.measure(). Non-measurement conditions (classical variables, constants, comparisons) are rejected by ValidateWhileContractPass before reaching engine emit.

Example::

bit = qmc.measure(q)
while bit:
    q = qmc.h(q)
    bit = qmc.measure(q)
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    operations: list[Operation] = list(),
    max_iterations: int | None = None,
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include rebind records and region args for cloning/substitution.

Same rationale as ForOperation.all_input_values: rebind records and region arguments reference body/pre-loop values by identity, so inline cloning must remap them in lockstep with body operands.

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus rebind-record and region-argument values.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the while body with explicit boundary values.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region whose block arguments and yields are aligned with region_args. The updated condition, when present, is appended as the final yield.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the while body and its complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt while operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, rebind-record, and region-arg values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


qamomile.circuit.transpiler.passes.constant_fold

Constant folding pass for compile-time expression evaluation.

Overview

FunctionDescription
coerce_nonnegative_integralNormalize a real scalar with an integer value to a nonnegative integer.
collect_value_like_uuidsCollect UUIDs contained in a value-like IR object.
validate_region_argsValidate the SSA identities owned by a loop’s region arguments.
ClassDescription
ArrayValueAn array of typed IR values.
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
BinOpKind
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
CompOpComparison operation (EQ, NEQ, LT, LE, GT, GE).
ConcreteControlledUControlled-U with concrete (int) number of controls.
CondOpConditional logical operation (AND, OR).
ConstantFoldingPassEvaluates constant expressions at compile time.
ControlledUOperationBase class for controlled-U operations.
DictValueA dictionary value stored as stable ordered entries.
ForOperationRepresents a for loop operation.
IfOperationRepresents an if-else conditional operation.
NotOp
OperationTransformerBase class for transforming operations with control flow handling.
PassBase class for all compiler passes.
StoreArrayElementOperationStore a classical scalar into one element of a classical array.
SymbolicControlledUControlled-U with symbolic (Value) number of controls.
TupleValueA tuple of IR values for structured data.
UnaryMathOpRepresent one pure unary mathematical expression.
UnifiedValueResolverResolve IR Values to concrete Python values.
ValidationErrorError during validation (e.g., non-classical I/O).
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.

Constants

Functions

coerce_nonnegative_integral [source]

def coerce_nonnegative_integral(value: object, *, label: str) -> int

Normalize a real scalar with an integer value to a nonnegative integer.

Parameters:

NameTypeDescription
valueobjectCandidate Python, NumPy, or SymPy real scalar.
labelstrUser-facing field label used in diagnostics.

Returns:

int — Equivalent nonnegative Python integer.

Raises:


collect_value_like_uuids [source]

def collect_value_like_uuids(value: 'ValueLike') -> set[str]

Collect UUIDs contained in a value-like IR object.

Parameters:

NameTypeDescription
valueValueLikeValue-like object to inspect.

Returns:

set[str] — set[str]: UUIDs for value itself, recursively contained tuple/dict elements, and array view/element dependencies.


validate_region_args [source]

def validate_region_args(op: ForOperation | ForItemsOperation | WhileOperation) -> tuple[RegionArg, ...]

Validate the SSA identities owned by a loop’s region arguments.

A loop owns several definition namespaces: its iteration variables, every RegionArg.block_arg, and every RegionArg.result. Those identities must be pairwise disjoint. Otherwise different stages can assign incompatible meanings to one UUID: a UUID-keyed environment has only one slot, so binding either the iteration variable or the carried value overwrites the other and makes both reads observe the same value.

Parameters:

NameTypeDescription
opForOperation | ForItemsOperation | WhileOperationLoop operation whose region arguments should be validated.

Returns:

tuple[RegionArg, ...] — tuple[RegionArg, ...]: The validated op.region_args tuple.

Raises:

Classes

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:

bool — True iff slice_of is non-None.

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

BinOp [source]

class BinOp(BinaryOperationBase)

Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: BinOpKind | None = None,
) -> None
Attributes

BinOpKind [source]

class BinOpKind(enum.Enum)
Attributes

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.


BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

CompOp [source]

class CompOp(BinaryOperationBase)

Comparison operation (EQ, NEQ, LT, LE, GT, GE).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CompOpKind | None = None,
) -> None
Attributes

ConcreteControlledU [source]

class ConcreteControlledU(ControlledUOperation)

Controlled-U with concrete (int) number of controls.

Operand layout: [ctrl_0, ..., ctrl_n, tgt_0, ..., tgt_m, params...] Result layout: [ctrl_0', ..., ctrl_n', tgt_0', ..., tgt_m']

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_value: int | None = None,
) -> None
Attributes

CondOp [source]

class CondOp(BinaryOperationBase)

Conditional logical operation (AND, OR).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CondOpKind | None = None,
) -> None
Attributes

ConstantFoldingPass [source]

class ConstantFoldingPass(Pass[Block, Block])

Evaluates constant expressions at compile time.

This pass folds BinOp operations when all operands are constants or bound parameters, eliminating unnecessary classical operations that would otherwise split quantum segments.

Example:

Before (with bindings={"phase": 0.5}):
    BinOp(phase * 2) -> classical segment split

After:
    Constant 1.0 -> no segment split
Constructor
def __init__(self, bindings: dict[str, Any] | None = None, *, strip_slice_ops: bool = True)

Create a constant-folding pass.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneCompile-time parameter bindings used when folding BinOps that reference declared parameters.
strip_slice_opsboolWhen True (default), removes SliceArrayOperation nodes after folding. Set to False when a downstream pass — notably SliceBorrowCheckPass — still needs to observe slice declaration points in program order to decide view liveness. A separate strip pass must then run after the linearity check so segmentation still sees a pure quantum-op stream.
Attributes
Methods
run
def run(self, input: Block) -> Block

Fold resolvable classical values throughout a block.

Parameters:

NameTypeDescription
inputBlockAffine or hierarchical block to rewrite.

Returns:

Block — Copy with folded operations and output values.

Raises:


ControlledUOperation [source]

class ControlledUOperation(Operation)

Base class for controlled-U operations.

Two concrete subclasses handle distinct operand layouts:

All isinstance(op, ControlledUOperation) checks match every subclass.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int | Value = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]
replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

DictValue [source]

class DictValue(_MetadataValueMixin, ValueBase)

A dictionary value stored as stable ordered entries.

Constructor
def __init__(
    self,
    name: str,
    entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> DictValue

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


NotOp [source]

class NotOp(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

OperationTransformer [source]

class OperationTransformer(ABC)

Base class for transforming operations with control flow handling.

Subclasses override transform_operation to define per-operation transformation. Control flow recursion and rebuilding is handled automatically.

Example:

class OperationRenamer(OperationTransformer):
    def transform_operation(self, op: Operation) -> Operation:
        # Return modified operation
        return dataclasses.replace(op, ...)
Methods
transform_operation
def transform_operation(self, op: Operation) -> Operation | None

Transform a single operation. Return None to remove it.

transform_operations
def transform_operations(self, operations: list[Operation]) -> list[Operation]

Transform all operations including nested control flow.


Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


StoreArrayElementOperation [source]

class StoreArrayElementOperation(Operation)

Store a classical scalar into one element of a classical array.

This is the IR form of array[index] = value for classical element types (Bit / UInt / Float). Classical values are freely copyable, so the store is an ordinary SSA rewrite: the operation consumes the current array version and produces a new ArrayValue version (same logical_id, fresh uuid) whose contents equal the input array with the addressed element replaced. Quantum arrays never use this operation — qubit element assignment is the return half of the borrow-return idiom and emits no IR.

The operation is evaluated in one of two places:

Operand convention:

operands: [array (ArrayValue), stored_value (Value), *index_values] results: [new_array (ArrayValue)]

Example:

@qmc.qkernel
def k() -> qmc.Vector[qmc.Bit]:
    qs = qmc.qubit_array(2, "qs")
    qs[0] = qmc.x(qs[0])
    bits = qmc.measure(qs)
    bits[1] = bits[0]   # emits StoreArrayElementOperation
    return bits
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

SymbolicControlledU [source]

class SymbolicControlledU(ControlledUOperation)

Controlled-U with symbolic (Value) number of controls.

Operand layout: [ctrl_arg_0, ..., ctrl_arg_{k-1}, tgt_0, ..., tgt_m, params...] Result layout: [ctrl_arg_0', ..., ctrl_arg_{k-1}', tgt_0', ..., tgt_m']

The number of control arguments k is recorded in num_control_args; the default k = 1 corresponds to the historical single-pool form (operands[0] is a Vector[Qubit] / VectorView whose length equals num_controls, or whose control_indices-selected subset does). When k > 1 the control prefix is a heterogeneous sequence of scalar Qubit values and ArrayValues whose total qubit count is num_controls; the emit pass walks them in order to recover the per-physical-qubit control set.

When control_indices is None the entire control prefix is used as active controls (one-arg form: len(ctrl_vector) == num_controls; multi-arg form: the qubit-count sum of the prefix args equals num_controls). When non-None, the listed indices select exactly num_controls slots from a single-arg pool to act as controls; combining control_indices with the multi-arg control prefix is rejected at frontend time.

Each control_indices entry is stored as a Value of UIntType regardless of whether the frontend passed an int literal or a UInt handle, so all downstream value-substitution passes see a uniform shape.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: Value = (lambda: Value(type=(UIntType()), name=''))(),
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_indices: tuple[Value, ...] | None = None,
    num_control_args: int = 1,
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]
replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

TupleValue [source]

class TupleValue(_MetadataValueMixin, ValueBase)

A tuple of IR values for structured data.

Constructor
def __init__(
    self,
    name: str,
    elements: tuple[ValueLike, ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> TupleValue

UnaryMathOp [source]

class UnaryMathOp(Operation)

Represent one pure unary mathematical expression.

Parameters:

NameTypeDescription
operandslist[Value]Single numeric input value.
resultslist[Value]Single numeric result value.
kindUnaryMathOpKind | NoneMathematical operation to apply.

Raises:

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: UnaryMathOpKind | None = None,
) -> None
Attributes

ValueResolver [source]

class ValueResolver

Resolve IR Values to concrete Python values.

Parameters:

NameTypeDescription
contextdict[str, Any] | NoneUUID-keyed map of already resolved values. The values may be either raw Python scalars or Value objects; if a Value is found its get_const() is extracted automatically.
bindingsdict[str, Any] | NoneName-keyed parameter bindings supplied by the user at transpile time.
Constructor
def __init__(
    self,
    context: dict[str, Any] | None = None,
    bindings: dict[str, Any] | None = None,
)

Create a resolver with optional context and bindings.

Parameters:

NameTypeDescription
contextdict[str, Any] | NoneUUID-keyed map of already-resolved values. Defaults to None.
bindingsdict[str, Any] | NoneName-keyed parameter bindings supplied by the user. Defaults to None.
Methods
resolve
def resolve(self, value: Any) -> Any | None

Resolve a Value-like object to a concrete Python value.

If value is not a Value-like object (no uuid attribute) it is returned as-is — the caller already has a concrete value.

Parameters:

NameTypeDescription
valueAnyThe Value-like object or already concrete value to resolve.

Returns:

Any | None — Any | None: The resolved concrete value, the original concrete value for non-Value inputs, or None when no resolution rule applies.


ValidationError [source]

class ValidationError(QamomileCompileError)

Error during validation (e.g., non-classical I/O).

Constructor
def __init__(self, message: str, value_name: str | None = None)

Initialize a validation diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable validation failure.
value_namestr | NoneRelated IR value name. Defaults to None.
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 engine 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.


qamomile.circuit.transpiler.passes.control_flow_reachability

Resolve statically reachable structured-control regions.

Overview

FunctionDescription
constant_integerReturn a non-boolean integer constant carried by an IR value.
reachable_nested_regionsReturn nested regions that may execute for one control-flow operation.
same_exact_typed_constantReturn whether two scalar Values carry the same exact typed constant.
static_for_items_entriesReturn compile-time entries iterated by a for-items operation.
static_for_rangeResolve the exact iteration range of a statically bounded loop.
static_loop_trip_countResolve the exact trip count of a compile-time loop.
ClassDescription
ArrayValueAn array of typed IR values.
DictValueA dictionary value stored as stable ordered entries.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
HasNestedOpsMixin for operations that contain nested operation lists.
IfOperationRepresents an if-else conditional operation.
RegionExpose one structured-control region through a uniform interface.
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.

Functions

constant_integer [source]

def constant_integer(value: ValueBase | None) -> int | None

Return a non-boolean integer constant carried by an IR value.

Parameters:

NameTypeDescription
valueValueBase | NoneCandidate scalar value.

Returns:

int | None — int | None: Normalized Python integer, or None when value is absent, symbolic, boolean, or non-integral.


reachable_nested_regions [source]

def reachable_nested_regions(operation: HasNestedOps) -> tuple[Region, ...]

Return nested regions that may execute for one control-flow operation.

Constant conditionals expose only their selected branch. Statically empty counted and items loops expose no body region. All unresolved control flow remains conservative and exposes every region.

Parameters:

NameTypeDescription
operationHasNestedOpsStructured-control operation to inspect.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Regions that are reachable under compile-time-known control decisions.


same_exact_typed_constant [source]

def same_exact_typed_constant(left: Value, right: Value) -> bool

Return whether two scalar Values carry the same exact typed constant.

Equality requires matching IR and Python types. Floating-point comparison preserves the sign of zero and the payload bits of NaNs.

Parameters:

NameTypeDescription
leftValueFirst scalar value to compare.
rightValueSecond scalar value to compare.

Returns:

bool — True only for constants of the same IR type and Python type with equal value representations.


static_for_items_entries [source]

def static_for_items_entries(operation: ForItemsOperation) -> tuple[tuple[Any, Any], ...] | None

Return compile-time entries iterated by a for-items operation.

Parameters:

NameTypeDescription
operationForItemsOperationItems loop whose iterable should be inspected.

Returns:

tuple[tuple[Any, Any], ...] | None — tuple[tuple[Any, Any], ...] | None: Bound key/value entries in iteration order, including an empty tuple for a known-empty mapping, or None when the iterable remains symbolic.


static_for_range [source]

def static_for_range(operation: ForOperation) -> range | None

Resolve the exact iteration range of a statically bounded loop.

Parameters:

NameTypeDescription
operationForOperationCounted loop whose three bounds should be inspected.

Returns:

range | None — range | None: Exact Python range when all bounds are integral constants and the step is nonzero, otherwise None.


static_loop_trip_count [source]

def static_loop_trip_count(operation: ForOperation | ForItemsOperation) -> int | None

Resolve the exact trip count of a compile-time loop.

Parameters:

NameTypeDescription
operationForOperation | ForItemsOperationCounted or items loop whose cardinality should be inspected.

Returns:

int | None — int | None: Exact non-negative trip count, or None when the loop cardinality is unresolved.

Classes

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:

bool — True iff slice_of is non-None.

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

DictValue [source]

class DictValue(_MetadataValueMixin, ValueBase)

A dictionary value stored as stable ordered entries.

Constructor
def __init__(
    self,
    name: str,
    entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> DictValue

ForItemsOperation [source]

class ForItemsOperation(HasNestedOps, Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    key_var_values: tuple[Value, ...] | None = None,
    value_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include the per-key/value Value fields for cloning/substitution.

Same rationale as ForOperation.all_input_values: keep the IR identity fields in lockstep with body references so UUID-keyed lookups stay valid after inline cloning. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the items-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing key/value formals, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the items-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt items-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


Region [source]

class Region

Expose one structured-control region through a uniform interface.

This is a view over the existing semantic IR rather than a parallel value system: every entry is an ordinary Qamomile ValueBase carrying the current UUID identity. Control-flow operations remain the owners of the stored fields and construct Region views through nested_regions.

Parameters:

NameTypeDescription
operationstuple[Operation, ...]Operations evaluated inside the region in program order.
block_argstuple[ValueBase, ...]Values defined at region entry, such as a loop induction variable or carried-value formal.
capturestuple[ValueBase, ...]Explicit outer-scope values read by the region, ordered by first use.
yieldstuple[ValueBase, ...]Values yielded at the region boundary in result-slot order.
Constructor
def __init__(
    self,
    operations: tuple[Operation, ...],
    block_args: tuple[ValueBase, ...] = (),
    captures: tuple[ValueBase, ...] = (),
    yields: tuple[ValueBase, ...] = (),
) -> None
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 engine 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.


qamomile.circuit.transpiler.passes.control_flow_visitor

Control flow visitor for operation traversal.

Overview

ClassDescription
ControlFlowVisitorBase class for visiting operations with control flow handling.
HasNestedOpsMixin for operations that contain nested operation lists.
OperationCollectorCollects operations matching a predicate.
OperationTransformerBase class for transforming operations with control flow handling.
ValueCollectorCollects Value UUIDs from operation operands and results.

Classes

ControlFlowVisitor [source]

class ControlFlowVisitor(ABC)

Base class for visiting operations with control flow handling.

Subclasses override visit_operation to define per-operation behavior. Control flow recursion is handled automatically by the base class.

Example:

class MeasurementCounter(ControlFlowVisitor):
    def __init__(self):
        self.count = 0

    def visit_operation(self, op: Operation) -> None:
        if isinstance(op, MeasureOperation):
            self.count += 1
Methods
visit_operation
def visit_operation(self, op: Operation) -> None

Process a single operation. Override in subclasses.

visit_operations
def visit_operations(self, operations: list[Operation]) -> None

Visit all operations including nested control flow.


HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


OperationCollector [source]

class OperationCollector(ControlFlowVisitor)

Collects operations matching a predicate.

Example:

collector = OperationCollector(lambda op: isinstance(op, MeasureOperation))
collector.visit_operations(block.operations)
measurements = collector.collected
Constructor
def __init__(self, predicate: Callable[[Operation], bool])
Attributes
Methods
visit_operation
def visit_operation(self, op: Operation) -> None

OperationTransformer [source]

class OperationTransformer(ABC)

Base class for transforming operations with control flow handling.

Subclasses override transform_operation to define per-operation transformation. Control flow recursion and rebuilding is handled automatically.

Example:

class OperationRenamer(OperationTransformer):
    def transform_operation(self, op: Operation) -> Operation:
        # Return modified operation
        return dataclasses.replace(op, ...)
Methods
transform_operation
def transform_operation(self, op: Operation) -> Operation | None

Transform a single operation. Return None to remove it.

transform_operations
def transform_operations(self, operations: list[Operation]) -> list[Operation]

Transform all operations including nested control flow.


ValueCollector [source]

class ValueCollector(ControlFlowVisitor)

Collects Value UUIDs from operation operands and results.

Constructor
def __init__(self)
Attributes
Methods
visit_operation
def visit_operation(self, op: Operation) -> None

Record one operation’s input and result Value UUIDs.

Parameters:

NameTypeDescription
opOperationThe visited operation. Inputs are read via all_input_values so subclass-specific Value fields (e.g. IfOperation yields) are covered.

qamomile.circuit.transpiler.passes.effect_validation

Validate execution-mode constraints from cached kernel effects.

Overview

FunctionDescription
callable_bodiesReturn cached semantic bodies relevant to one call transform.
format_kernel_effectsFormat an effect set for deterministic user-facing diagnostics.
ClassDescription
BlockUnified block representation for all pipeline stages.
ControlledUOperationBase class for controlled-U operations.
EffectValidationPassReject execution-mode conflicts using cached kernel effects.
ExpvalOpExpectation value operation.
HasNestedOpsMixin for operations that contain nested operation lists.
InverseBlockOperationRepresent an inverse qkernel/block as a first-class IR operation.
InvokeOperationRepresent a composite, stdlib, or oracle call.
PassBase class for all compiler passes.
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
ValidationErrorError during validation (e.g., non-classical I/O).

Functions

callable_bodies [source]

def callable_bodies(definition: 'CallableDef', transform: CallTransform) -> tuple['Block', ...]

Return cached semantic bodies relevant to one call transform.

An explicit implementation of the complete transform takes precedence. A controlled-inverse call then reuses explicit inverse-body metadata when generic lowering only needs to add controls; all other structural fallbacks conservatively inherit the direct body’s effects.

Parameters:

NameTypeDescription
definitionCallableDefCallable definition referenced by a call.
transformCallTransformRequested direct, inverse, or controlled transform.

Returns:

tuple['Block', ...] — tuple[Block, ...]: Candidate bodies whose cached metadata applies.


format_kernel_effects [source]

def format_kernel_effects(effects: KernelEffect) -> str

Format an effect set for deterministic user-facing diagnostics.

Parameters:

NameTypeDescription
effectsKernelEffectEffect set to format.

Returns:

str — Comma-separated flag names, or NONE for a unitary kernel.

Classes

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.


ControlledUOperation [source]

class ControlledUOperation(Operation)

Base class for controlled-U operations.

Two concrete subclasses handle distinct operand layouts:

All isinstance(op, ControlledUOperation) checks match every subclass.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int | Value = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]
replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

EffectValidationPass [source]

class EffectValidationPass(Pass)

Reject execution-mode conflicts using cached kernel effects.

Attributes
Methods
run
def run(self, block: Block) -> Block

Validate expectation-value compatibility for one entrypoint.

Parameters:

NameTypeDescription
blockBlockHierarchical entrypoint block.

Returns:

Block — The unchanged validated block.

Raises:


ExpvalOp [source]

class ExpvalOp(Operation)

Expectation value operation.

This operation computes the expectation value <psi|H|psi> where psi is the quantum state and H is the Hamiltonian observable.

The operation bridges quantum and classical computation:

Example IR:

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


InverseBlockOperation [source]

class InverseBlockOperation(Operation)

Represent an inverse qkernel/block as a first-class IR operation.

The operation stores both the original forward block and a Qamomile-built inverse implementation block. Emitters may use source_block with a engine-native inverse/adjoint primitive, then fall back to implementation_block when native inversion is unavailable.

Operands are ordered as scalar control qubits, target quantum operands, then classical/object parameters. Results mirror the quantum operand layout: control results first, then one target result per target operand. Vector target operands therefore count as one operand/result while contributing their scalar width to num_target_qubits.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_control_qubits: int = 0,
    num_target_qubits: int = 0,
    custom_name: str = '',
    source_block: Block | None = None,
    implementation_block: Block | None = None,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_value: int | None = None,
) -> None
Attributes

InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.
Constructor
def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes
Methods
body_for_transform
def body_for_transform(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> tuple[Block | None, CallTransform]

Select a body and report the transform it already realizes.

A controlled-inverse invocation may reuse an explicitly registered inverse body when no implementation realizes both transforms. Keeping that fallback in the IR operation gives emitters and static analyses one selection rule while still letting each consumer apply the remaining coherent controls in its own representation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — tuple[Block | None, CallTransform]: Selected body and the transform CallTransform — already implemented by that body. The callable’s direct body is tuple[Block | None, CallTransform] — returned with DIRECT when no transform-specific body matches.

Raises:

effective_body
def effective_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — Block | None: Selected implementation body, or the callable’s Block | None — default body when no transform-specific implementation exists. Block | None — A compiler may synthesize inverse or controlled behavior from this Block | None — fallback body.

implementation_for
def implementation_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None, which only selects engine-generic implementations.
strategystr | NoneStrategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation candidate, CallableImplementation | None — or None when the callable definition has no match.

measurement_result_indices_for
def measurement_result_indices_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> frozenset[int]

Return measurement-derived results for one selected implementation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name used for implementation selection. Defaults to None.
strategystr | NoneStrategy name used for implementation selection. Defaults to the invocation’s strategy_name.

Returns:

frozenset[int] — frozenset[int]: Caller-local result positions derived from measurement in the selected body.

Raises:

select_body
def select_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> CallableBodySelection

Select and validate the composable body for this invocation.

The result carries the transform already realized by the body and the exact call-site values that bind to it. Consumers therefore cannot independently disagree about whether an invocation’s control prefix belongs to the selected implementation ABI.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

CallableBodySelection — Validated body, realized transform, and CallableBodySelection — aligned call-site operands and results.

Raises:


Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


SelectOperation [source]

class SelectOperation(Operation)

Quantum multiplexer: apply case_blocks[i] when the index reads i.

Concrete operand layout: [idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...]. Symbolic-width operand layout: [idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...]. Results mirror the quantum operand grouping.

A concrete index register is normalized to one scalar Qubit operand per physical index qubit. A symbolic-width register instead retains each leading caller argument as one scalar or array operand until its bound shape is known. Whole-Vector[Qubit] / scalar targets follow and keep their shapes, and classical parameters shared across every case come last.

Index bit order is LSB-first: idx_0 is the least-significant bit, matching Qamomile’s qubit-zero convention. Case i is selected when index qubit j reads bit j of i. len(case_blocks) need not be a power of two; index values >= len(case_blocks) apply no operation (identity).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_index_qubits: int | Value = 0,
    case_blocks: list[Block] = list(),
    num_index_args: int = 0,
    case_callable_attrs: list[dict[str, Any]] = list(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Return every value consumed by the SELECT operation.

Returns:

list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width value when present.

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed replacement values.

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


ValidationError [source]

class ValidationError(QamomileCompileError)

Error during validation (e.g., non-classical I/O).

Constructor
def __init__(self, message: str, value_name: str | None = None)

Initialize a validation diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable validation failure.
value_namestr | NoneRelated IR value name. Defaults to None.
Attributes

qamomile.circuit.transpiler.passes.emit

Emit pass: Generate engine-specific code from separated program.

Overview

FunctionDescription
collect_value_like_uuidsCollect UUIDs contained in a value-like IR object.
resolve_condition_address_detailedResolve a condition / source Value to its clbit_map key.
resolve_root_qubit_addressResolve an array-element value to its root (array_uuid, index).
ClassDescription
ArrayValueAn array of typed IR values.
BitTypeType representing a classical bit.
ClassicalSegmentA segment of pure classical operations.
ClassicalStepA classical execution step.
CompositeGateEmitterProtocol for preserving or lowering boxed callable operations.
CompositeGateTypeClassify standard boxed quantum callables.
DictValueA dictionary value stored as stable ordered entries.
EmitErrorReport an engine failure to emit one semantic operation.
EmitPassBase class for engine-specific emission passes.
ExecutableProgramA fully compiled program ready for execution.
ExpvalSegmentA segment for expectation value computation.
ExpvalStepAn expectation-value execution step.
InvokeOperationRepresent a composite, stdlib, or oracle call.
MeasureOperation
MeasureQFixedOperationMeasure a quantum fixed-point number.
MeasureQIntOperationMeasure an unsigned quantum integer as one abstract hybrid operation.
MeasureVectorOperationMeasure a vector of qubits.
OperationCollectorCollects operations matching a predicate.
PassBase class for all compiler passes.
ProgramPlanExecution plan for a hybrid quantum/classical program.
ProjectOperationProject a qubit in one Pauli basis and keep the projected state.
QuantumSegmentA segment of pure quantum operations.
QuantumStepA quantum execution step.
QubitAddressTyped key for qubit/clbit physical-index maps.
ResetOperationReset a qubit to the |0> state and return the fresh handle.
TupleValueA tuple of IR values for structured data.
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.
ValueResolverResolves Value objects to concrete indices or values.

Functions

collect_value_like_uuids [source]

def collect_value_like_uuids(value: 'ValueLike') -> set[str]

Collect UUIDs contained in a value-like IR object.

Parameters:

NameTypeDescription
valueValueLikeValue-like object to inspect.

Returns:

set[str] — set[str]: UUIDs for value itself, recursively contained tuple/dict elements, and array view/element dependencies.


resolve_condition_address_detailed [source]

def resolve_condition_address_detailed(
    condition: Value,
    bindings: dict[str, Any],
    resolver: ValueResolver | None = None,
) -> tuple[QubitAddress, bool]

Resolve a condition / source Value to its clbit_map key.

Single source of truth (shared by control_flow_emission.emit_if / emit_while, the Qiskit / CUDA-Q engines, ResourceAllocator’s loop-carried / merge aliasing, and the merge-output mapping helpers here) for turning a runtime control-flow condition — or a merge source Value — into the address its classical bit is registered under.

Scalar measurement results register under QubitAddress(bit.uuid), while a Vector[Bit] element s[i] (s = qmc.measure(register)) registers under QubitAddress(root_array.uuid, root_index). The element index and every slice_start / slice_step along the parent’s slice_of chain are resolved the same way — taken directly when constant, otherwise folded through bindings via resolver — and composed into the root index via root_index = start + step * view_local_index repeated along the chain.

Parameters:

NameTypeDescription
conditionValueThe condition operand or merge source Value.
bindingsdict[str, Any]Active emit-time bindings used to fold symbolic indices / slice bounds. May be empty for callers that only have constant addresses to resolve (e.g. the allocator’s pre-emit pass).
resolverValueResolver | NoneResolver exposing resolve_int_value; None restricts resolution to constants. Defaults to None.

Returns:

tuple[QubitAddress, bool] — tuple[QubitAddress, bool]: (address, resolved_as_element). resolved_as_element is True only when condition is a Vector[Bit] element whose index (and any slice bounds) resolved to concrete ints, giving the root-space QubitAddress(root.uuid, root_index). It is False for a plain scalar, or when an element’s index / slice bound could not be resolved (the scalar UUID fallback). Callers that mutate clbit_map should trust the address as a vector key only when this flag is True, to avoid aliasing an unresolved element onto an unrelated scalar slot.


resolve_root_qubit_address [source]

def resolve_root_qubit_address(value: 'Value') -> tuple[str, int] | None

Resolve an array-element value to its root (array_uuid, index).

Walks the parent_array / slice_of chain and composes the nested affine slice maps, so view[i] resolves to (root_uuid, start + step * i) for the composed (start, step). The returned pair is the build-stable identity of the physical qubit slot: the root array’s QInitOperation always registers it as QubitAddress(root_uuid, index), so this address resolves even when the element’s own (per-version) UUID was never registered.

The transpiler’s resource allocator uses the same walk to resolve gate and measurement operands; this shared helper keeps both call sites consistent.

Parameters:

NameTypeDescription
valueValueThe value to resolve. Expected to be an array element (parent_array set with a single constant element_indices entry).

Returns:

tuple[str, int] | None — tuple[str, int] | None: (root_array_uuid, composed_index) when value is an array element with a constant index whose entire slice_of chain has constant slice_start / slice_step. None when value is not an array element, when its index is non-constant, or when any slice bound in the chain is non-constant (those cases are deferred to the emit-time resolver, which has bindings available). Also None for a negative constant index or a chain frame with negative slice_start / non-positive slice_step — composing those would silently address a wrong root slot, so they are refused rather than guessed (the frontend rejects them at trace time; this guard covers programmatically constructed IR).

Classes

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:

bool — True iff slice_of is non-None.

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

BitType [source]

class BitType(ClassicalTypeMixin, ValueType)

Type representing a classical bit.


ClassicalSegment [source]

class ClassicalSegment(Segment)

A segment of pure classical operations.

Contains arithmetic, comparisons, and control flow. Will be executed directly in Python.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
) -> None
Attributes

ClassicalStep [source]

class ClassicalStep

A classical execution step.

Constructor
def __init__(self, segment: ClassicalSegment, role: str = 'classical') -> None
Attributes

CompositeGateEmitter [source]

class CompositeGateEmitter(Protocol[C])

Protocol for preserving or lowering boxed callable operations.

The concrete compiler installs a semantic emitter that boxes every executable callable into circuit IR with its identity and fallback body. Native SDK selection happens later, through target capabilities and legalization; this traversal hook must not import or select an engine.

Methods
can_emit
def can_emit(self, gate_type: CompositeGateType) -> bool

Check whether this emitter handles the given callable kind.

Parameters:

NameTypeDescription
gate_typeCompositeGateTypeCallable kind to check.

Returns:

bool — True if this emitter handles the callable kind.

emit
def emit(
    self,
    circuit: C,
    op: InvokeOperation,
    qubit_indices: list[int],
    bindings: dict[str, Any],
) -> bool

Preserve or lower the boxed callable into the output builder.

Parameters:

NameTypeDescription
circuitCOutput builder receiving the callable representation.
opInvokeOperationInvocation to preserve or lower.
qubit_indiceslist[int]Physical qubit indices for the operation.
bindingsdict[str, Any]Parameter bindings for the operation.

Returns:

bool — True if handled, or False to use the generic fallback bool — decomposition.


CompositeGateType [source]

class CompositeGateType(enum.Enum)

Classify standard boxed quantum callables.

Attributes

DictValue [source]

class DictValue(_MetadataValueMixin, ValueBase)

A dictionary value stored as stable ordered entries.

Constructor
def __init__(
    self,
    name: str,
    entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> DictValue

EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return
Constructor
def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

EmitPass [source]

class EmitPass(Pass[ProgramPlan, ExecutableProgram[T]], Generic[T])

Base class for engine-specific emission passes.

Subclasses implement _emit_quantum_segment() to generate engine-specific quantum circuits.

Input: ProgramPlan Output: ExecutableProgram with compiled segments

Constructor
def __init__(
    self,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
)

Initialize with optional parameter bindings.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneValues to bind parameters to. If not provided, parameters must be bound at execution time.
parameterslist[str] | NoneList of parameter names to preserve as engine parameters.

Raises:

Attributes
Methods
run
def run(self, input: ProgramPlan) -> ExecutableProgram[T]

Emit engine code from a program plan.

Parameters:

NameTypeDescription
inputProgramPlanSegmented plan whose quantum and classical steps should be compiled.

Returns:

ExecutableProgram[T] — ExecutableProgram[T]: Executable program containing all compiled segments and the public output contract.

Raises:


ExecutableProgram [source]

class ExecutableProgram(Generic[T])

A fully compiled program ready for execution.

Contains compiled quantum, classical, and expectation-value segments. Use sample() for multi-shot execution or run() for single execution.

Example:

executable = transpiler.compile(kernel)

# Sample: multiple shots, returns counts
job = executable.sample(executor, shots=1000)
result = job.result()  # SampleResult with counts

# Run: single shot, returns typed result
job = executable.run(executor)
result = job.result()  # Returns kernel's return type
Constructor
def __init__(
    self,
    plan: ProgramPlan | None = None,
    compiled_quantum: list[CompiledQuantumSegment[T]] = list(),
    compiled_classical: list[CompiledClassicalSegment] = list(),
    compiled_expval: list[CompiledExpvalSegment] = list(),
    output_values: list[ValueLike] = list(),
) -> None
Attributes
Methods
get_circuits
def get_circuits(self) -> list[T]

Get all quantum circuits in execution order.

get_first_circuit
def get_first_circuit(self) -> T | None

Get the first quantum circuit, or None if no quantum segments.

restore
def restore(
    self,
    executor: QuantumExecutor[T],
    snapshot: JobSnapshot,
    bindings: dict[str, Any] | None = None,
) -> SampleJob[Any] | RunJob[Any] | ExpvalJob

Restore saved executions with this program’s typed result ABI.

Snapshots retain provider identifiers, completed local raw values, and ordered execution groups. Legacy flat provider snapshots remain supported. Reuse the same compiled program and pass the original runtime bindings explicitly to reproduce classical pre- and post-processing. Credentials, arbitrary bindings, and Python callables are not saved. Restoration reconnects to remote jobs without resubmitting or waiting for results; local values need no provider restoration support.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine adapter configured with the provider credentials and target used by the original job.
snapshotJobSnapshotSnapshot returned by the original public job’s snapshot() method.
bindingsdict[str, Any] | NoneOriginal runtime parameter bindings. Defaults to None for parameter-free programs.

Returns:

SampleJob[Any] | RunJob[Any] | ExpvalJob — SampleJob[Any] | RunJob[Any] | ExpvalJob: Restored lazy job with the same typed public result conversion as a new execution.

Raises:

Example:

>>> original = executable.sample(executor, shots=1000)
>>> snapshot = original.snapshot()
>>> restored = executable.restore(executor, snapshot)
>>> restored.result()
run
def run(
    self,
    executor: QuantumExecutor[T],
    bindings: dict[str, Any] | None = None,
    *,
    estimation: EstimationAccuracy | None = None,
) -> RunJob[Any] | ExpvalJob

Submit one execution and return its lazy result job.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine-specific quantum executor.
bindingsdict[str, Any] | NoneParameter bindings. Supports three formats: - Vector: {“gammas”: [0.1, 0.2], “betas”: [0.3, 0.4]} - Dict parameter: {“coeffs”: {0: 0.1, (0, 1): 0.2}}, decomposed per key onto the emitted parameters - Indexed: {“gammas[0]”: 0.1, “coeffs[(0, 1)]”: 0.2}
estimationEstimationAccuracy | NoneOptional per-execution expectation accuracy policy. Defaults to the executor’s configured behavior.

Returns:

RunJob[Any] | ExpvalJob — RunJob[Any] | ExpvalJob: A RunJob that resolves to the kernel’s return type, or an ExpvalJob when the program contains an expectation-value computation.

Raises:

Example:

job = executable.run(executor, bindings={"gamma": [0.5]})
result = job.result()
print(result)  # 0.25 (for QFixed) or (0, 1) (for bits)
sample
def sample(
    self,
    executor: QuantumExecutor[T],
    shots: int = 1024,
    bindings: dict[str, Any] | None = None,
) -> SampleJob[Any]

Submit a multi-shot execution and return its lazy job.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine-specific quantum executor.
shotsintNumber of shots to run.
bindingsdict[str, Any] | NoneParameter bindings. Supports three formats: - Vector: {“gammas”: [0.1, 0.2], “betas”: [0.3, 0.4]} - Dict parameter: {“coeffs”: {0: 0.1, (0, 1): 0.2}}, decomposed per key onto the emitted parameters - Indexed: {“gammas[0]”: 0.1, “coeffs[(0, 1)]”: 0.2}

Returns:

SampleJob[Any] — SampleJob[Any]: A job that resolves to a SampleResult with the per-bitstring counts.

Raises:

Example:

job = executable.sample(executor, shots=1000, bindings={"gamma": [0.5]})
result = job.result()
print(result.results)  # [(0.25, 500), (0.75, 500)]

ExpvalSegment [source]

class ExpvalSegment(Segment)

A segment for expectation value computation.

Represents computing <psi|H|psi> where psi is the quantum state and H is a Hamiltonian observable.

This segment bridges a quantum circuit (state preparation) to a classical expectation value.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
    hamiltonian_value: Value | None = None,
    qubits_value: Value | None = None,
    result_ref: str = '',
) -> None
Attributes

ExpvalStep [source]

class ExpvalStep

An expectation-value execution step.

Constructor
def __init__(self, segment: ExpvalSegment, quantum_step_index: int = 0) -> None
Attributes

InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.
Constructor
def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes
Methods
body_for_transform
def body_for_transform(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> tuple[Block | None, CallTransform]

Select a body and report the transform it already realizes.

A controlled-inverse invocation may reuse an explicitly registered inverse body when no implementation realizes both transforms. Keeping that fallback in the IR operation gives emitters and static analyses one selection rule while still letting each consumer apply the remaining coherent controls in its own representation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — tuple[Block | None, CallTransform]: Selected body and the transform CallTransform — already implemented by that body. The callable’s direct body is tuple[Block | None, CallTransform] — returned with DIRECT when no transform-specific body matches.

Raises:

effective_body
def effective_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — Block | None: Selected implementation body, or the callable’s Block | None — default body when no transform-specific implementation exists. Block | None — A compiler may synthesize inverse or controlled behavior from this Block | None — fallback body.

implementation_for
def implementation_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None, which only selects engine-generic implementations.
strategystr | NoneStrategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation candidate, CallableImplementation | None — or None when the callable definition has no match.

measurement_result_indices_for
def measurement_result_indices_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> frozenset[int]

Return measurement-derived results for one selected implementation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name used for implementation selection. Defaults to None.
strategystr | NoneStrategy name used for implementation selection. Defaults to the invocation’s strategy_name.

Returns:

frozenset[int] — frozenset[int]: Caller-local result positions derived from measurement in the selected body.

Raises:

select_body
def select_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> CallableBodySelection

Select and validate the composable body for this invocation.

The result carries the transform already realized by the body and the exact call-site values that bind to it. Consumers therefore cannot independently disagree about whether an invocation’s control prefix belongs to the selected implementation ABI.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

CallableBodySelection — Validated body, realized transform, and CallableBodySelection — aligned call-site operands and results.

Raises:


MeasureOperation [source]

class MeasureOperation(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

MeasureQFixedOperation [source]

class MeasureQFixedOperation(Operation)

Measure a quantum fixed-point number.

This operation measures all qubits in a QFixed register and produces a Float result. During transpilation, this is lowered to individual MeasureOperations plus a DecodeQFixedOperation.

operands: [QFixed value (contains qubit_values in params)] results: [Float value]

Encoding:

For QPE phase (int_bits=0): Qubits are stored least-significant first. For n qubits, bit i has weight 2**(-n + i).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_bits: int = 0,
    int_bits: int = 0,
) -> None
Attributes

MeasureQIntOperation [source]

class MeasureQIntOperation(Operation)

Measure an unsigned quantum integer as one abstract hybrid operation.

The carrier sequence is least-significant-bit first: carrier i has integer weight 2**i. Planning lowers this operation to one vector measurement followed by a host-side DecodeQIntOperation.

The carrier width is not stored on the operation: it is derived from the register operand’s type and carrier metadata through num_bits.

Parameters:

NameTypeDescription
operandslist[Value]Single QUIntType register operand.
resultslist[Value]Single decoded UIntType result.
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

MeasureVectorOperation [source]

class MeasureVectorOperation(Operation)

Measure a vector of qubits.

Takes a Vector[Qubit] (ArrayValue) and produces a Vector[Bit] (ArrayValue). This operation measures all qubits in the vector as a single operation.

operands: [ArrayValue of qubits] results: [ArrayValue of bits]

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

OperationCollector [source]

class OperationCollector(ControlFlowVisitor)

Collects operations matching a predicate.

Example:

collector = OperationCollector(lambda op: isinstance(op, MeasureOperation))
collector.visit_operations(block.operations)
measurements = collector.collected
Constructor
def __init__(self, predicate: Callable[[Operation], bool])
Attributes
Methods
visit_operation
def visit_operation(self, op: Operation) -> None

Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


ProgramPlan [source]

class ProgramPlan

Execution plan for a hybrid quantum/classical program.

Structure:

This plan enforces Qamomile’s current execution model: all quantum operations must be in a single quantum circuit.

Constructor
def __init__(
    self,
    steps: list[ProgramStep] = list(),
    abi: ProgramABI = ProgramABI(),
    boundaries: list[HybridBoundary] = list(),
    parameters: dict[str, Value] = dict(),
) -> None
Attributes

ProjectOperation [source]

class ProjectOperation(Operation)

Project a qubit in one Pauli basis and keep the projected state.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    axis: str = 'z',
) -> None
Attributes

QuantumSegment [source]

class QuantumSegment(Segment)

A segment of pure quantum operations.

Contains quantum gates and qubit allocations. Will be emitted to a quantum circuit.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
    qubit_values: list[Value] = list(),
    num_qubits: int = 0,
) -> None
Attributes

QuantumStep [source]

class QuantumStep

A quantum execution step.

Constructor
def __init__(self, segment: QuantumSegment) -> None
Attributes

QubitAddress [source]

class QubitAddress

Typed key for qubit/clbit physical-index maps.

For scalar qubits: QubitAddress(uuid="abc123") For array elements: QubitAddress(uuid="abc123", element_index=2)

This replaces the f"{uuid}_{i}" string key pattern throughout the emit pipeline, making the key format explicit and preventing format-string bugs.

Constructor
def __init__(self, uuid: str, element_index: int | None = None) -> None
Attributes
Methods
from_composite_key
@classmethod
def from_composite_key(cls, key: str) -> QubitAddress

Parse a legacy composite key string into a QubitAddress.

The frontend stores qubit references as composite strings in the format "{array_uuid}_{element_index}" (e.g., cast operation qubit mappings, element UUIDs). This helper converts such strings to proper QubitAddress instances.

If the key does not match the composite format (i.e., the suffix after the last _ is not a non-negative integer), it is treated as a plain scalar UUID.

matches_array
def matches_array(self, array_uuid: str) -> bool

True if this address belongs to the given array.

with_element
def with_element(self, index: int) -> QubitAddress

Create an array-element address from this array’s base UUID.


ResetOperation [source]

class ResetOperation(Operation)

Reset a qubit to the |0> state and return the fresh handle.

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

TupleValue [source]

class TupleValue(_MetadataValueMixin, ValueBase)

A tuple of IR values for structured data.

Constructor
def __init__(
    self,
    name: str,
    elements: tuple[ValueLike, ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> TupleValue

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


ValueResolver [source]

class ValueResolver

Resolves Value objects to concrete indices or values.

Constructor
def __init__(self, parameters: set[str] | None = None)

Create an emit-time resolver.

Parameters:

NameTypeDescription
parametersset[str] | NoneNames preserved as engine runtime parameters. Defaults to None.
Attributes
Methods
bind_block_params
def bind_block_params(
    self,
    block_value: Any,
    param_operands: list['Value'],
    bindings: dict[str, Any],
    *,
    parameter_factory: Callable[[str, str], Any] | None = None,
) -> dict[str, Any]

Create local bindings by matching block inputs to call-site operands.

Parameters:

NameTypeDescription
block_valueAnyNested block whose classical/object inputs are bound. Objects without input_values receive no additional local bindings for compatibility with optional engine recipes.
param_operandslist[Value]Classical/object call-site operands in the controlled operation’s signature order.
bindingsdict[str, Any]Parent emit-time bindings used to resolve the call-site operands.
parameter_factoryCallable[[str, str], Any] | NoneOptional engine parameter factory used when an operand is a declared runtime parameter rather than a concrete binding. Defaults to None so standalone resolver use remains engine-neutral.

Returns:

dict[str, Any] — dict[str, Any]: Parent bindings with each inner formal rebound under both its UUID and sanctioned parameter-name key.

get_parameter_key
def get_parameter_key(self, value: 'Value', bindings: dict[str, Any]) -> str | None

Get the engine parameter key for a symbolic scalar.

Parameters:

NameTypeDescription
valueValueScalar value or array element to identify.
bindingsdict[str, Any]Active bindings used to resolve element indices and slice offsets.

Returns:

str | None — str | None: Scalar name or root-array indexed key, or None when an array element’s root location is unresolved.

lookup_in_bindings
def lookup_in_bindings(
    self,
    value: Any,
    bindings: dict[str, Any],
    *,
    index_array: bool = False,
) -> Any

Canonical resolution chain for a Value against bindings.

All other resolver methods (resolve_bound_value, resolve_classical_value, resolve_int_value, resolve_operand_for_binding) wrap this single chain. Centralizing precedence here prevents the historical drift where one resolver checked is_parameter before UUID and another checked it after, which manifested as obscure binding failures when name-keyed writes were dropped from the emit pass.

Resolution order (each step returns immediately on a hit):

  1. value is already a concrete Python scalar (no uuid).

  2. value.uuid is in bindings — return that. This is where emit-time-computed intermediates (evaluate_binop / evaluate_classical_predicate results) and merge aliases live.

  3. A compile-time array or dict payload stored in typed metadata.

  4. value.is_constant() — return value.get_const().

  5. value.is_parameter() and its parameter name is in bindings — return that.

  6. (When index_array=True) value is an array element with a resolvable parent in bindings — index into it.

  7. A non-empty display name is present in bindings. This is a compatibility bridge for programmatically constructed Values and older transforms that do not carry parameter metadata; UUID and explicit parameter provenance always take precedence.

Compiler-created temporaries are anonymous and compiler-internal writers use UUID keys, so the compatibility bridge cannot merge two same-named temporaries. Kernel parameters should normally resolve via explicit parameter metadata, while loop variables and intermediates remain UUID-keyed.

Parameters:

NameTypeDescription
valueAnyThe IR value (or already-concrete Python scalar) to resolve.
bindingsdict[str, Any]The active bindings dictionary.
index_arrayboolWhen True, also resolve array-element accesses via parent_array indexing. Off by default because not all callers want to index into bound containers.

Returns:

Any — The resolved Python value, or None if no step matched.

resolve_bound_value
def resolve_bound_value(self, value: 'Value', bindings: dict[str, Any]) -> Any

Resolve a Value to its raw bound Python object.

Wraps :meth:lookup_in_bindings with index_array=True so that arr[i] accesses against a bound container resolve to the element. Does not coerce the result — callers that need a numeric scalar should go through :meth:resolve_classical_value.

Parameters:

NameTypeDescription
valueValueValue to resolve.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

Any — Raw bound object, or None when unresolved.

resolve_classical_value
def resolve_classical_value(self, value: 'Value', bindings: dict[str, Any]) -> Any

Resolve a classical Value to a concrete Python value.

Numeric bindings are normalized to native Python scalars regardless of whether they come from a direct binding or from array-element indexing, so downstream isinstance(x, (int, float)) checks are stable when callers bind np.pi/4 or the like. bool is preserved (not coerced to int). Non-numeric values (Hamiltonians, strings, dict values, …) pass through unchanged.

Parameters:

NameTypeDescription
valueValueClassical value to resolve.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

Any — Resolved native scalar/object, or None when unresolved.

resolve_int_value
def resolve_int_value(self, val: Any, bindings: dict[str, Any]) -> int | None

Resolve a value to an integer, or None when unresolvable.

Unresolvable symbolic Values must return None. The previous return 0 fallback caused silent loop elision when parameter shape dims (gamma_dim0) reached this resolver without being folded into constants — downstream loop-bound resolution saw 0 and quietly emitted an empty loop. Returning None propagates the failure to emit_for_unrolled, which converts it into a hard compile error.

resolve_operand_for_binding
def resolve_operand_for_binding(self, operand: Any, bindings: dict[str, Any]) -> Any

Resolve an operand to a concrete value for block parameter binding.

Used when calling a sub-block (e.g. a controlled-U body): each param operand at the call site must resolve to a value to seed the callee’s parameter bindings.

Parameters:

NameTypeDescription
operandAnyCall-site value or already-concrete operand.
bindingsdict[str, Any]Parent emit-time bindings.

Returns:

Any — Resolved value, or None when the operand is symbolic.

resolve_qubit_index
def resolve_qubit_index(self, v: 'Value', qubit_map: QubitMap, bindings: dict[str, Any]) -> int | None

Resolve a qubit value to its physical index.

Parameters:

NameTypeDescription
vValueScalar or indexed qubit value.
qubit_mapQubitMapPhysical resource mapping.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

int | None — int | None: Physical index, or None when unresolved.

resolve_qubit_index_detailed
def resolve_qubit_index_detailed(
    self,
    v: 'Value',
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> QubitResolutionResult

Resolve a Value to a physical qubit index with detailed failure info.

Parameters:

NameTypeDescription
vValueThe qubit Value to resolve. May be a scalar qubit or an array element (possibly through a sliced view chain).
qubit_mapQubitMapMapping from QubitAddress to physical qubit indices built by the resource allocator.
bindingsdict[str, Any]Active emit-time bindings used to resolve symbolic element indices and slice bounds.

Returns:

QubitResolutionResult — Success with the physical index, or a failure carrying a ResolutionFailureReason — including NEGATIVE_INDEX when a resolved element index is negative or a resolved slice bound violates the frontend contract (non-negative start, positive step); composing those through the affine map would silently address a wrong root slot.

resolve_slice_chain
def resolve_slice_chain(
    self,
    av: 'ArrayValue',
    bindings: dict[str, Any],
    *,
    operation: str = 'emit',
) -> tuple['ArrayValue', int, int]

Walk an ArrayValue’s slice_of chain and return root + affine map.

Composes the nested affine maps so that a view-local index i corresponds to the root-space index start + step * i. For a root ArrayValue (no slice_of chain), returns (av, 0, 1) so callers can always apply the same formula uniformly.

Parameters:

NameTypeDescription
av'ArrayValue'The possibly-sliced ArrayValue whose root and affine mapping should be resolved.
bindingsdict[str, Any]Compile-time parameter bindings; required when any slice_start / slice_step in the chain is symbolic.
operationstrHuman-readable name of the enclosing emit operation. Used only in the EmitError message when a symbolic slice bound cannot be resolved. Defaults to "emit".

Returns:

'ArrayValue' — Tuple (root_array, start, step) where root_array is int — the underlying non-sliced ArrayValue, and start/step int — are Python int values satisfying tuple['ArrayValue', int, int] — view[i] == root_array[start + step * i].

Raises:

Example:

>>> # For ``view = q[1::2]`` where ``q`` has 4 qubits:
>>> resolver.resolve_slice_chain(view_av, bindings={})
(q_av, 1, 2)

qamomile.circuit.transpiler.passes.emit_support

Shared helpers for engine emission.

Overview

FunctionDescription
map_merge_outputsRegister merge output UUIDs to the same physical resources as their sources.
remap_static_merge_outputsRemap merge outputs for a compile-time constant IfOperation.
resolve_condition_addressResolve a runtime control-flow condition to its clbit_map key.
resolve_if_conditionResolve an if-condition to a compile-time boolean.
resolve_qubit_keyResolve a qubit Value to its allocation key.
ClassDescription
CompositeDecomposerDecomposes composite gates into primitive operations.
LoopAnalyzerAnalyze loop structures to determine an emission strategy.
MultiControlAncillaPoolA reserved block of clean ancilla qubits for multi-control lowering.
QubitAddressTyped key for qubit/clbit physical-index maps.
QubitResolutionResultResult of attempting to resolve a qubit index.
ResourceAllocatorAllocates qubit and classical bit indices from operations.
ValueResolverResolves Value objects to concrete indices or values.

Functions

map_merge_outputs [source]

def map_merge_outputs(
    if_op: IfOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    resolve_scalar_qubit: Any = None,
    bindings: dict[str, Any] | None = None,
    resolver: ValueResolver | None = None,
    reject_runtime_bit_mux: bool = False,
    allowed_mixed_bit_outputs: frozenset[str] | set[str] | None = None,
) -> None

Register merge output UUIDs to the same physical resources as their sources.

Runtime-if counterpart of :func:remap_static_merge_outputs: both branches may execute, so quantum merges are validated to sit on identical physical resources, and classical Bit merges consolidate both branches’ clbits only when the complete source-alias partition is representable without overwriting an independently live value. Outputs already registered are left untouched.

Parameters:

NameTypeDescription
if_opIfOperationThe runtime if-else whose merged outputs need physical-resource registration; merges are read through iter_merges.
qubit_mapQubitMapAddress-to-physical-qubit map, mutated in place.
clbit_mapClbitMapAddress-to-physical-clbit map, mutated in place.
resolve_scalar_qubitAnyOptional callable (source, qubit_map) -> int | None used to resolve scalar qubit sources that are not directly registered (e.g. array elements). Defaults to None, restricting resolution to direct and root-array lookups.
bindingsdict[str, Any] | NoneActive bindings used to fold a classical Bit merge source’s symbolic Vector[Bit] element index / slice bounds (e.g. an unrolled loop variable). Defaults to None (empty), restricting element resolution to constant indices.
resolverValueResolver | NoneResolver used with bindings to fold non-constant element indices; None restricts to constants. Defaults to None.
reject_runtime_bit_muxboolWhen True, raise EmitError for a runtime Bit merge that requires an at-runtime mux, mixes a pre-existing source with a branch-local measurement, or has incompatible source-sharing partitions across multiple outputs. Two all-branch-local source sets remain eligible only when their alias partitions match. Defaults to False.
allowed_mixed_bit_outputsfrozenset[str] | set[str] | NoneMerge result UUIDs whose pre-existing source is proven dead after the merge. This includes safe ordinary-if updates and phi-like loop condition remeasurements. Defaults to None.

Raises:


remap_static_merge_outputs [source]

def remap_static_merge_outputs(
    if_op: IfOperation,
    condition_value: bool,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any] | None = None,
    resolver: ValueResolver | None = None,
) -> None

Remap merge outputs for a compile-time constant IfOperation.

Registers each merged output under the physical resource of the branch selected by the resolved condition, so downstream operations referencing the merge output resolve to the surviving branch’s qubit / clbit. Outputs already registered are left untouched.

Parameters:

NameTypeDescription
if_opIfOperationThe if-else whose condition resolved at compile time; merges are read through iter_merges.
condition_valueboolThe resolved condition, selecting which branch’s source the outputs alias.
qubit_mapQubitMapAddress-to-physical-qubit map, mutated in place.
clbit_mapClbitMapAddress-to-physical-clbit map, mutated in place.
bindingsdict[str, Any] | NoneActive bindings used to fold a merge source’s symbolic Vector[Bit] element index / slice bounds (e.g. an unrolled loop variable). Defaults to None (empty), restricting element resolution to constant indices.
resolverValueResolver | NoneResolver used with bindings to fold non-constant element indices; None restricts to constants. Defaults to None.

resolve_condition_address [source]

def resolve_condition_address(
    condition: Value,
    bindings: dict[str, Any],
    resolver: ValueResolver | None,
) -> QubitAddress

Resolve a runtime control-flow condition to its clbit_map key.

Scalar measurement results carry their own UUID and the clbit allocator registers them under QubitAddress(bit.uuid). Vector[Bit] element accesses (s[i] where s = qmc.measure(register)) instead live under QubitAddress(root_array.uuid, root_index). The element index and every slice_start / slice_step along the parent’s slice_of chain are resolved the same way — taken directly when constant, otherwise folded through bindings via resolver so that loop-variable indices and runtime-valued slice bounds (s[j:k] where j/k are loop variables) both work. The chain composes into a root-space index via the standard affine map root_index = start + step * view_local_index repeated along the chain — matching ResourceAllocator._resolve_root_qubit_address / ValueResolver.resolve_slice_chain. Falls back to the scalar address when no parent array is set, or when the index or any slice bound cannot be resolved to a concrete int (e.g. an engine runtime parameter, which cannot index a static classical register, or any symbolic value with no resolver), deferring the diagnostic to the caller’s clbit_map lookup. Used by both the default if/while emission path and the Qiskit / CUDA-Q engines when looking up a measurement-derived clbit for a runtime predicate.

Parameters:

NameTypeDescription
conditionValueCondition operand of an IfOperation or WhileOperation, or an operand of a measurement-derived classical predicate (e.g. inside RuntimeClassicalExpr).
bindingsdict[str, Any]Active emit-time bindings used to resolve symbolic indices and slice bounds (loop variables, compile-time-bound parameters).
resolverValueResolver | NoneThe active ValueResolver exposing resolve_int_value. None is accepted for early-emit pre-scans (e.g. CUDA-Q’s loop-carried clbit collector) that run before runtime bindings exist — only the constant path is taken in that case; symbolic indices and symbolic slice bounds fall through to the scalar UUID.

Returns:

QubitAddress — Key suitable for looking up the condition in clbit_map.

See resolve_condition_address_detailed for the resolution contract.


resolve_if_condition [source]

def resolve_if_condition(condition: Any, bindings: dict[str, Any]) -> bool | None

Resolve an if-condition to a compile-time boolean.


resolve_qubit_key [source]

def resolve_qubit_key(qubit: 'Value') -> tuple[QubitAddress | None, bool]

Resolve a qubit Value to its allocation key.

Parameters:

NameTypeDescription
qubitValueQubit value to resolve. Array elements with a constant index are resolved through their full slice_of chain to the root array address.

Returns:

tuple[QubitAddress | None, bool] — tuple[QubitAddress | None, bool]: (address, is_array_element). address is the root-space address for a resolvable array element, None for an array element whose index or slice bounds are symbolic at this binding-free stage, and a scalar UUID address for non-array qubits. A negative constant index (or an out-of-contract slice bound) also yields None: resolve_root_qubit_address refuses it rather than letting it silently address a wrong root slot.

Classes

CompositeDecomposer [source]

class CompositeDecomposer

Decomposes composite gates into primitive operations.

Methods
iqft_structure
@staticmethod
def iqft_structure(n: int) -> list[tuple[str, tuple[int, ...], float | None]]
qft_structure
@staticmethod
def qft_structure(n: int) -> list[tuple[str, tuple[int, ...], float | None]]

LoopAnalyzer [source]

class LoopAnalyzer

Analyze loop structures to determine an emission strategy.

Methods
should_unroll
def should_unroll(self, op: ForOperation, bindings: dict[str, object]) -> bool

Determine whether a for-loop requires emit-time unrolling.

Parameters:

NameTypeDescription
opForOperationLoop to analyze.
bindingsdict[str, object]Compile-time bindings available to nested-bound analysis.

Returns:

bool — True when identities, carries, indices, predicates, dictionary lookups, structural body parameters, or nested bounds require concrete per-iteration evaluation.


MultiControlAncillaPool [source]

class MultiControlAncillaPool

A reserved block of clean ancilla qubits for multi-control lowering.

The pool occupies a contiguous range of physical qubit indices appended after a quantum segment’s data qubits. A single moving _offset gives it stack discipline so nested users never collide:

Constructor
def __init__(self, first_index: int, count: int, *, counting: bool = False) -> None

Initialize the pool.

Parameters:

NameTypeDescription
first_indexintPhysical index of the first reserved ancilla qubit.
countintNumber of reserved ancilla qubits. Must be non-negative. Ignored in counting mode.
countingboolWhen True the pool is unbounded and only records the peak concurrent usage (take / try_hold never fail), so a dry-run emission can measure how many ancillas a real emission would need. Defaults to False.

Raises:

Attributes
Methods
take
def take(self, count: int) -> list[int] | None

Return count clean ancilla indices from the current offset.

Parameters:

NameTypeDescription
countintNumber of ancilla qubits requested.

Returns:

list[int] | None — list[int] | None: The next count reserved physical indices starting at the current offset, or None when the unheld remainder of the pool is smaller than the request (an estimation bug surfaced by the caller). In counting mode the request always succeeds and the peak usage is recorded instead.

Raises:

try_hold
def try_hold(self, count: int) -> Iterator[list[int] | None]

Reserve count ancillas for the duration of a with block.

Used by batched controlled-block emission to keep an AND ladder live while the block body is walked under a single control. The offset advances so that take/try_hold calls made inside the body draw from the qubits after the held range, and it is rewound on exit (including on exception) so sibling batches reuse the same range. When the unheld remainder cannot satisfy the request the caller receives None and must fall back to per-gate emission rather than treating it as an error — the demand estimate legitimately reserves fewer ancillas than a naive batch would want (e.g. a statically empty loop body).

Parameters:

NameTypeDescription
countintNumber of contiguous ancilla qubits to hold.

Yields:

list[int] | None — list[int] | None: The held physical indices, or None when the unheld remainder is too small to satisfy the request.


QubitAddress [source]

class QubitAddress

Typed key for qubit/clbit physical-index maps.

For scalar qubits: QubitAddress(uuid="abc123") For array elements: QubitAddress(uuid="abc123", element_index=2)

This replaces the f"{uuid}_{i}" string key pattern throughout the emit pipeline, making the key format explicit and preventing format-string bugs.

Constructor
def __init__(self, uuid: str, element_index: int | None = None) -> None
Attributes
Methods
from_composite_key
@classmethod
def from_composite_key(cls, key: str) -> QubitAddress

Parse a legacy composite key string into a QubitAddress.

The frontend stores qubit references as composite strings in the format "{array_uuid}_{element_index}" (e.g., cast operation qubit mappings, element UUIDs). This helper converts such strings to proper QubitAddress instances.

If the key does not match the composite format (i.e., the suffix after the last _ is not a non-negative integer), it is treated as a plain scalar UUID.

matches_array
def matches_array(self, array_uuid: str) -> bool

True if this address belongs to the given array.

with_element
def with_element(self, index: int) -> QubitAddress

Create an array-element address from this array’s base UUID.


QubitResolutionResult [source]

class QubitResolutionResult

Result of attempting to resolve a qubit index.

Constructor
def __init__(
    self,
    success: bool,
    index: int | None = None,
    failure_reason: ResolutionFailureReason | None = None,
    failure_details: str = '',
) -> None
Attributes

ResourceAllocator [source]

class ResourceAllocator

Allocates qubit and classical bit indices from operations.

This class handles the first pass of circuit emission: determining how many physical qubits and classical bits are needed and mapping Value UUIDs to their physical indices.

New physical indices are assigned via monotonic counters (_next_qubit_index / _next_clbit_index) so that alias entries — which reuse an existing physical index — never inflate the counter. Using len(map) would cause sparse (gapped) physical indices because alias keys increase the map size without adding new physical resources.

Constructor
def __init__(self, resolver: ValueResolver | None = None) -> None

Initialize allocator state.

Parameters:

NameTypeDescription
resolverValueResolver | NoneEmit value resolver that carries runtime parameter names and binding lookup rules. Defaults to None, which creates a resolver without runtime parameters.
Attributes
Methods
allocate
def allocate(
    self,
    operations: list[Operation],
    bindings: dict[str, Any] | None = None,
    initial_qubit_map: QubitMap | None = None,
    initial_clbit_map: ClbitMap | None = None,
    public_output_uuids: frozenset[str] | set[str] | None = None,
) -> tuple[QubitMap, ClbitMap]

Allocate qubit and clbit indices for all operations.

Parameters:

NameTypeDescription
operationslist[Operation]Operations to allocate resources for.
bindingsdict[str, Any] | NoneOptional variable bindings for resolving dynamic sizes. Defaults to None (treated as an empty mapping).
initial_qubit_mapQubitMap | NoneOptional pre-populated qubit address mapping. Used by callers that need to seed the allocator with bindings established outside the operation list — for instance, the inner-block emitter in blockvalue_to_gate pre-allocates Vector[Qubit] input elements (the inner block has no QInitOperation for inputs, so per-element entries must be supplied here or the assertion in _allocate_gate fires). The map is copied; allocation continues from max(values) + 1 so new QInitOperation allocations inside operations do not collide. Defaults to None (treated as empty).
initial_clbit_mapClbitMap | NoneOptional pre-populated clbit address mapping. Same semantics as initial_qubit_map but for classical bits. Defaults to None.
public_output_uuidsfrozenset[str] | set[str] | NoneProgram outputs that must remain live after this operation tree. Defaults to None, which disables dead-source approval for mixed prior/fresh Bit merges.

Returns:

tuple[QubitMap, ClbitMap] — tuple[QubitMap, ClbitMap]: (qubit_map, clbit_map) where each maps QubitAddress to a physical index. If an initial map was supplied, its entries are preserved verbatim in the returned map.

preserving_analysis_state
def preserving_analysis_state(self) -> Iterator[None]

Preserve segment-level analysis state across a nested allocation.

allocate recomputes the measurement-taint set, the safe mixed-merge allowlist, and the monotonic resource counters for the operation list it receives. Nested sub-circuit emission (controlled blocks, native inverses) reuses the SEGMENT allocator on a different operation list mid-emission; without a snapshot that leaves the sub-block’s analysis state behind, and later resolve_iteration_maps replays of the enclosing segment consult the wrong taint/allowlist sets — silently disarming the runtime-mux guards.

Yields:

None — The nested allocation and emission run inside the snapshot; the segment state is restored on exit even when the nested work raises.

resolve_iteration_maps
def resolve_iteration_maps(
    self,
    operations: list[Operation],
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
) -> tuple[QubitMap, ClbitMap]

Resolve resource aliases for one statically replayed iteration.

The initial allocation walks an unrolled loop body only once, before its loop variable has a concrete value. A nested runtime condition such as while measured[index]: therefore cannot select its root clbit during that first walk. Replaying the allocator over copies of the already-complete maps with the iteration binding present resolves those aliases without allocating another physical resource. The caller uses the returned maps for that iteration only; the same body UUIDs may legitimately alias different measured-vector elements in later iterations.

Parameters:

NameTypeDescription
operationslist[Operation]Statically replayed loop body.
qubit_mapQubitMapComplete enclosing qubit map.
clbit_mapClbitMapComplete enclosing clbit map.
bindingsdict[str, Any]Iteration-local UUID bindings, including the concrete range index or items-loop key/value identities.

Returns:

tuple[QubitMap, ClbitMap] — tuple[QubitMap, ClbitMap]: Per-iteration copies with conditional aliases resolved for the supplied bindings.

Raises:


ValueResolver [source]

class ValueResolver

Resolves Value objects to concrete indices or values.

Constructor
def __init__(self, parameters: set[str] | None = None)

Create an emit-time resolver.

Parameters:

NameTypeDescription
parametersset[str] | NoneNames preserved as engine runtime parameters. Defaults to None.
Attributes
Methods
bind_block_params
def bind_block_params(
    self,
    block_value: Any,
    param_operands: list['Value'],
    bindings: dict[str, Any],
    *,
    parameter_factory: Callable[[str, str], Any] | None = None,
) -> dict[str, Any]

Create local bindings by matching block inputs to call-site operands.

Parameters:

NameTypeDescription
block_valueAnyNested block whose classical/object inputs are bound. Objects without input_values receive no additional local bindings for compatibility with optional engine recipes.
param_operandslist[Value]Classical/object call-site operands in the controlled operation’s signature order.
bindingsdict[str, Any]Parent emit-time bindings used to resolve the call-site operands.
parameter_factoryCallable[[str, str], Any] | NoneOptional engine parameter factory used when an operand is a declared runtime parameter rather than a concrete binding. Defaults to None so standalone resolver use remains engine-neutral.

Returns:

dict[str, Any] — dict[str, Any]: Parent bindings with each inner formal rebound under both its UUID and sanctioned parameter-name key.

get_parameter_key
def get_parameter_key(self, value: 'Value', bindings: dict[str, Any]) -> str | None

Get the engine parameter key for a symbolic scalar.

Parameters:

NameTypeDescription
valueValueScalar value or array element to identify.
bindingsdict[str, Any]Active bindings used to resolve element indices and slice offsets.

Returns:

str | None — str | None: Scalar name or root-array indexed key, or None when an array element’s root location is unresolved.

lookup_in_bindings
def lookup_in_bindings(
    self,
    value: Any,
    bindings: dict[str, Any],
    *,
    index_array: bool = False,
) -> Any

Canonical resolution chain for a Value against bindings.

All other resolver methods (resolve_bound_value, resolve_classical_value, resolve_int_value, resolve_operand_for_binding) wrap this single chain. Centralizing precedence here prevents the historical drift where one resolver checked is_parameter before UUID and another checked it after, which manifested as obscure binding failures when name-keyed writes were dropped from the emit pass.

Resolution order (each step returns immediately on a hit):

  1. value is already a concrete Python scalar (no uuid).

  2. value.uuid is in bindings — return that. This is where emit-time-computed intermediates (evaluate_binop / evaluate_classical_predicate results) and merge aliases live.

  3. A compile-time array or dict payload stored in typed metadata.

  4. value.is_constant() — return value.get_const().

  5. value.is_parameter() and its parameter name is in bindings — return that.

  6. (When index_array=True) value is an array element with a resolvable parent in bindings — index into it.

  7. A non-empty display name is present in bindings. This is a compatibility bridge for programmatically constructed Values and older transforms that do not carry parameter metadata; UUID and explicit parameter provenance always take precedence.

Compiler-created temporaries are anonymous and compiler-internal writers use UUID keys, so the compatibility bridge cannot merge two same-named temporaries. Kernel parameters should normally resolve via explicit parameter metadata, while loop variables and intermediates remain UUID-keyed.

Parameters:

NameTypeDescription
valueAnyThe IR value (or already-concrete Python scalar) to resolve.
bindingsdict[str, Any]The active bindings dictionary.
index_arrayboolWhen True, also resolve array-element accesses via parent_array indexing. Off by default because not all callers want to index into bound containers.

Returns:

Any — The resolved Python value, or None if no step matched.

resolve_bound_value
def resolve_bound_value(self, value: 'Value', bindings: dict[str, Any]) -> Any

Resolve a Value to its raw bound Python object.

Wraps :meth:lookup_in_bindings with index_array=True so that arr[i] accesses against a bound container resolve to the element. Does not coerce the result — callers that need a numeric scalar should go through :meth:resolve_classical_value.

Parameters:

NameTypeDescription
valueValueValue to resolve.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

Any — Raw bound object, or None when unresolved.

resolve_classical_value
def resolve_classical_value(self, value: 'Value', bindings: dict[str, Any]) -> Any

Resolve a classical Value to a concrete Python value.

Numeric bindings are normalized to native Python scalars regardless of whether they come from a direct binding or from array-element indexing, so downstream isinstance(x, (int, float)) checks are stable when callers bind np.pi/4 or the like. bool is preserved (not coerced to int). Non-numeric values (Hamiltonians, strings, dict values, …) pass through unchanged.

Parameters:

NameTypeDescription
valueValueClassical value to resolve.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

Any — Resolved native scalar/object, or None when unresolved.

resolve_int_value
def resolve_int_value(self, val: Any, bindings: dict[str, Any]) -> int | None

Resolve a value to an integer, or None when unresolvable.

Unresolvable symbolic Values must return None. The previous return 0 fallback caused silent loop elision when parameter shape dims (gamma_dim0) reached this resolver without being folded into constants — downstream loop-bound resolution saw 0 and quietly emitted an empty loop. Returning None propagates the failure to emit_for_unrolled, which converts it into a hard compile error.

resolve_operand_for_binding
def resolve_operand_for_binding(self, operand: Any, bindings: dict[str, Any]) -> Any

Resolve an operand to a concrete value for block parameter binding.

Used when calling a sub-block (e.g. a controlled-U body): each param operand at the call site must resolve to a value to seed the callee’s parameter bindings.

Parameters:

NameTypeDescription
operandAnyCall-site value or already-concrete operand.
bindingsdict[str, Any]Parent emit-time bindings.

Returns:

Any — Resolved value, or None when the operand is symbolic.

resolve_qubit_index
def resolve_qubit_index(self, v: 'Value', qubit_map: QubitMap, bindings: dict[str, Any]) -> int | None

Resolve a qubit value to its physical index.

Parameters:

NameTypeDescription
vValueScalar or indexed qubit value.
qubit_mapQubitMapPhysical resource mapping.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

int | None — int | None: Physical index, or None when unresolved.

resolve_qubit_index_detailed
def resolve_qubit_index_detailed(
    self,
    v: 'Value',
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> QubitResolutionResult

Resolve a Value to a physical qubit index with detailed failure info.

Parameters:

NameTypeDescription
vValueThe qubit Value to resolve. May be a scalar qubit or an array element (possibly through a sliced view chain).
qubit_mapQubitMapMapping from QubitAddress to physical qubit indices built by the resource allocator.
bindingsdict[str, Any]Active emit-time bindings used to resolve symbolic element indices and slice bounds.

Returns:

QubitResolutionResult — Success with the physical index, or a failure carrying a ResolutionFailureReason — including NEGATIVE_INDEX when a resolved element index is negative or a resolved slice bound violates the frontend contract (non-negative start, positive step); composing those through the affine map would silently address a wrong root slot.

resolve_slice_chain
def resolve_slice_chain(
    self,
    av: 'ArrayValue',
    bindings: dict[str, Any],
    *,
    operation: str = 'emit',
) -> tuple['ArrayValue', int, int]

Walk an ArrayValue’s slice_of chain and return root + affine map.

Composes the nested affine maps so that a view-local index i corresponds to the root-space index start + step * i. For a root ArrayValue (no slice_of chain), returns (av, 0, 1) so callers can always apply the same formula uniformly.

Parameters:

NameTypeDescription
av'ArrayValue'The possibly-sliced ArrayValue whose root and affine mapping should be resolved.
bindingsdict[str, Any]Compile-time parameter bindings; required when any slice_start / slice_step in the chain is symbolic.
operationstrHuman-readable name of the enclosing emit operation. Used only in the EmitError message when a symbolic slice bound cannot be resolved. Defaults to "emit".

Returns:

'ArrayValue' — Tuple (root_array, start, step) where root_array is int — the underlying non-sliced ArrayValue, and start/step int — are Python int values satisfying tuple['ArrayValue', int, int] — view[i] == root_array[start + step * i].

Raises:

Example:

>>> # For ``view = q[1::2]`` where ``q`` has 4 qubits:
>>> resolver.resolve_slice_chain(view_av, bindings={})
(q_av, 1, 2)

qamomile.circuit.transpiler.passes.emit_support.cast_binop_emission

Cast and binary-operation emission helpers for StandardEmitPass.

Extracted from standard_emit.py to keep the main class focused on gate-level dispatch. Each function mirrors the original method but takes an explicit emit_pass parameter instead of self.

Overview

FunctionDescription
default_combine_symbolicDefault combine_symbolic for engines with arithmetic-capable Parameters.
evaluate_binopEvaluate a BinOp and store the result in bindings.
evaluate_classical_predicateEvaluate a CompOp/CondOp/NotOp at emit time and bind its boolean result.
evaluate_unary_mathEvaluate concrete unary math used inside a controlled body.
handle_castHandle CastOperation - update qubit_map without emitting gates.
ClassDescription
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
CastOperationType cast operation for creating aliases over the same quantum resources.
CompOpComparison operation (EQ, NEQ, LT, LE, GT, GE).
CondOpConditional logical operation (AND, OR).
NotOp
QubitAddressTyped key for qubit/clbit physical-index maps.
StandardEmitPassStandard emit pass implementation using GateEmitter protocol.
UnaryMathOpRepresent one pure unary mathematical expression.

Functions

default_combine_symbolic [source]

def default_combine_symbolic(kind: 'BinOpKind', lhs: Any, rhs: Any) -> Any

Default combine_symbolic for engines with arithmetic-capable Parameters.

Performs Python operator dispatch on the operands. Used by evaluate_binop whenever the active emitter does not define its own combine_symbolic method — the typical case for Qiskit (ParameterExpression overloads __add__ etc.) and CUDA-Q parameters. Engines whose Parameter type lacks Python operators (e.g. QURI Parts) define their own combine_symbolic on the emitter class to return an engine-native symbolic representation instead.

Parameters:

NameTypeDescription
kind'BinOpKind'The BinOpKind to apply.
lhsAnyLeft operand (numeric or engine Parameter / expression).
rhsAnyRight operand (same shape).

Returns:

Any — lhs OP rhs for the matching operator. 0.0 / 0 for Any — division-by-zero in the symbolic path so the caller can finish Any — emission without aborting on a numerically degenerate case. Any — None for unrecognised kind values, which the caller Any — treats as a no-op.


evaluate_binop [source]

def evaluate_binop(emit_pass: 'StandardEmitPass', op: BinOp, bindings: dict[str, Any]) -> None

Evaluate a BinOp and store the result in bindings.

Tries the shared fold_classical_op first for a clean concrete fold (which already encapsulates the runtime-parameter guard). Falls back to creating engine Parameter symbols and doing symbolic arithmetic when one or both operands are runtime parameters — that’s the path that lets rx(q, gamma * 2) produce a circuit with a single Parameter("gamma") * 2 expression rather than baking in a placeholder.


evaluate_classical_predicate [source]

def evaluate_classical_predicate(
    emit_pass: 'StandardEmitPass',
    op: 'CompOp | CondOp | NotOp',
    bindings: dict[str, Any],
) -> None

Evaluate a CompOp/CondOp/NotOp at emit time and bind its boolean result.

Mirrors the predicate evaluation already done by compile_time_if_lowering and classical_executor so that an IfOperation whose condition reaches emit unfolded — typically because its operands depend on a loop variable bound only at emit time by emit_for_items / emit_for_unrolled — can still be resolved via resolve_if_condition.

Delegates the actual fold (including runtime-parameter guard and strict scalar typing) to fold_classical_op so that all three callers of the same kind dispatch share one implementation. There is no symbolic-Parameter fallback for predicates: a runtime classical expression cannot be expressed as a folded scalar, so the op is left unbound and downstream emit handles it as a runtime condition.

Parameters:

NameTypeDescription
emit_pass'StandardEmitPass'The active emit pass (for resolver access).
op'CompOp | CondOp | NotOp'The predicate op to evaluate.
bindingsdict[str, Any]Current parameter/loop-variable bindings; mutated in place on successful evaluation. No-op when operands are unresolvable (e.g. measurement bits) or evaluation raises.

Returns:

None — None.


evaluate_unary_math [source]

def evaluate_unary_math(
    emit_pass: 'StandardEmitPass',
    op: UnaryMathOp,
    bindings: dict[str, Any],
) -> None

Evaluate concrete unary math used inside a controlled body.

An unresolved runtime unary expression is left unbound. Pure unused expressions can then disappear like ordinary dead classical work, while a later loop bound, branch, or gate-angle consumer still fails at its normal resolution boundary instead of receiving a fabricated value.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass used for value resolution and runtime-parameter classification.
opUnaryMathOpUnary expression to evaluate.
bindingsdict[str, Any]Current emit-time values, updated when the expression resolves to a valid concrete scalar.

handle_cast [source]

def handle_cast(emit_pass: 'StandardEmitPass', op: CastOperation, qubit_map: QubitMap) -> None

Handle CastOperation - update qubit_map without emitting gates.

Classes

BinOp [source]

class BinOp(BinaryOperationBase)

Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: BinOpKind | None = None,
) -> None
Attributes

CastOperation [source]

class CastOperation(Operation)

Type cast operation for creating aliases over the same quantum resources.

This operation does NOT allocate new qubits. It creates a new Value that references the same underlying quantum resources with a different type.

Use cases:

operands: [source_value] - The value being cast results: [cast_result] - The new value with target type (same physical qubits)

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    source_type: ValueType | None = None,
    target_type: ValueType | None = None,
    qubit_mapping: list[str] = list(),
) -> None
Attributes

CompOp [source]

class CompOp(BinaryOperationBase)

Comparison operation (EQ, NEQ, LT, LE, GT, GE).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CompOpKind | None = None,
) -> None
Attributes

CondOp [source]

class CondOp(BinaryOperationBase)

Conditional logical operation (AND, OR).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CondOpKind | None = None,
) -> None
Attributes

NotOp [source]

class NotOp(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

QubitAddress [source]

class QubitAddress

Typed key for qubit/clbit physical-index maps.

For scalar qubits: QubitAddress(uuid="abc123") For array elements: QubitAddress(uuid="abc123", element_index=2)

This replaces the f"{uuid}_{i}" string key pattern throughout the emit pipeline, making the key format explicit and preventing format-string bugs.

Constructor
def __init__(self, uuid: str, element_index: int | None = None) -> None
Attributes
Methods
from_composite_key
@classmethod
def from_composite_key(cls, key: str) -> QubitAddress

Parse a legacy composite key string into a QubitAddress.

The frontend stores qubit references as composite strings in the format "{array_uuid}_{element_index}" (e.g., cast operation qubit mappings, element UUIDs). This helper converts such strings to proper QubitAddress instances.

If the key does not match the composite format (i.e., the suffix after the last _ is not a non-negative integer), it is treated as a plain scalar UUID.

matches_array
def matches_array(self, array_uuid: str) -> bool

True if this address belongs to the given array.

with_element
def with_element(self, index: int) -> QubitAddress

Create an array-element address from this array’s base UUID.


StandardEmitPass [source]

class StandardEmitPass(EmitPass[T], Generic[T])

Standard emit pass implementation using GateEmitter protocol.

This class provides orchestration for semantic IR traversal while delegating circuit instruction construction to a GateEmitter. The concrete compiler use is CircuitLoweringPass; SDK targets materialize its immutable result instead of subclassing this class.

Parameters:

NameTypeDescription
gate_emitterGateEmitter[T]Instruction builder used during the semantic traversal.
bindingsdict[str, Any] | NoneCompile-time parameter bindings.
parameterslist[str] | NoneParameter names preserved at runtime.
composite_emitterslist[CompositeGateEmitter[T]] | NoneOptional callable-preservation or lowering hooks.
engine_namestr | NoneDiagnostic name for the traversal target.
Constructor
def __init__(
    self,
    gate_emitter: GateEmitter[T],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
    composite_emitters: list[CompositeGateEmitter[T]] | None = None,
    engine_name: str | None = None,
)
Attributes

UnaryMathOp [source]

class UnaryMathOp(Operation)

Represent one pure unary mathematical expression.

Parameters:

NameTypeDescription
operandslist[Value]Single numeric input value.
resultslist[Value]Single numeric result value.
kindUnaryMathOpKind | NoneMathematical operation to apply.

Raises:

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: UnaryMathOpKind | None = None,
) -> None
Attributes

qamomile.circuit.transpiler.passes.emit_support.clean_ancilla_toffoli

Pure arithmetic for the named clean-ancilla Toffoli ladder recipe.

Overview

FunctionDescription
clean_ancilla_toffoli_ladderReturn the arithmetic for the named clean-ancilla recipe.
clean_ancilla_toffoli_ladder_or_emptyReturn the named ladder arithmetic including its empty cases.
ClassDescription
CleanAncillaToffoliLadderDescribe the size of one clean-ancilla Toffoli ladder.

Functions

clean_ancilla_toffoli_ladder [source]

def clean_ancilla_toffoli_ladder(num_controls: int | sp.Expr) -> CleanAncillaToffoliLadder[Any]

Return the arithmetic for the named clean-ancilla recipe.

The caller owns recipe selection and must use the result on a branch where at least two controls are active. Keeping validation outside this helper lets symbolic resource expressions construct inactive Piecewise branches without prematurely rejecting them.

Parameters:

NameTypeDescription
num_controlsint | sp.ExprConcrete or symbolic control count.

Returns:

CleanAncillaToffoliLadder[Any] — CleanAncillaToffoliLadder[Any]: Compute, total-Toffoli, and clean- ancilla requirements in the same numeric domain as the input.


clean_ancilla_toffoli_ladder_or_empty [source]

def clean_ancilla_toffoli_ladder_or_empty(num_controls: int | sp.Expr) -> CleanAncillaToffoliLadder[Any]

Return the named ladder arithmetic including its empty cases.

The caller guarantees that num_controls is a nonnegative integer in its concrete or symbolic domain. Zero and one control need no conjunction ladder; two or more controls use the same named clean-ancilla recipe as :func:clean_ancilla_toffoli_ladder.

Parameters:

NameTypeDescription
num_controlsint | sp.ExprConcrete or symbolic nonnegative control count.

Returns:

CleanAncillaToffoliLadder[Any] — CleanAncillaToffoliLadder[Any]: Nonnegative compute, total-Toffoli, and clean-ancilla requirements.

Classes

CleanAncillaToffoliLadder [source]

class CleanAncillaToffoliLadder(Generic[_CountT])

Describe the size of one clean-ancilla Toffoli ladder.

Parameters:

NameTypeDescription
compute_toffolis_CountTToffoli count in the compute half.
total_toffolis_CountTCombined compute and uncompute count.
clean_ancillas_CountTSimultaneously required clean ancillas.
Constructor
def __init__(
    self,
    compute_toffolis: _CountT,
    total_toffolis: _CountT,
    clean_ancillas: _CountT,
) -> None
Attributes

qamomile.circuit.transpiler.passes.emit_support.composite_decomposer

Composite gate decomposition helpers.

Overview

ClassDescription
CompositeDecomposerDecomposes composite gates into primitive operations.

Classes

CompositeDecomposer [source]

class CompositeDecomposer

Decomposes composite gates into primitive operations.

Methods
iqft_structure
@staticmethod
def iqft_structure(n: int) -> list[tuple[str, tuple[int, ...], float | None]]
qft_structure
@staticmethod
def qft_structure(n: int) -> list[tuple[str, tuple[int, ...], float | None]]

qamomile.circuit.transpiler.passes.emit_support.composite_gate_emission

Boxed callable emission helpers extracted from StandardEmitPass.

This module provides module-level functions for emitting boxed callables (QFT, IQFT, QPE, custom composites, and opaque oracles) and their approximate variants. Each function takes an emit_pass parameter (a StandardEmitPass instance) in place of self.

Overview

FunctionDescription
bracket_control_valueBracket zero-valued controls with target-neutral Pauli-X gates.
emit_approximate_iqftEmit approximate IQFT with truncated rotations matching stdlib convention.
emit_approximate_qftEmit approximate QFT with truncated rotations matching stdlib convention.
emit_callable_implementation_emitterEmit using a selected callable implementation emitter, if present.
emit_composite_fallbackEmit composite gate using decomposition.
emit_composite_gateEmit a boxed composite/oracle invocation.
emit_invoke_operationEmit an invoke operation.
emit_iqft_manualEmit inverse QFT using decomposition matching stdlib convention.
emit_iqft_with_strategyEmit IQFT considering strategy selection.
emit_qft_manualEmit QFT using decomposition matching stdlib convention.
emit_qft_with_strategyEmit QFT considering strategy selection.
emit_qpe_manualEmit QPE using manual decomposition.
extract_phase_from_paramsExtract a concrete phase parameter from a QPE operation.
map_array_result_groupMap an array-valued result to a physical index group.
update_composite_result_mappingUpdate qubit_map for composite gate results.
ClassDescription
CallTransformDescribe the requested transform of a callable implementation.
CompositeGateTypeClassify standard boxed quantum callables.
EmitErrorReport an engine failure to emit one semantic operation.
InvokeOperationRepresent a composite, stdlib, or oracle call.
QubitAddressTyped key for qubit/clbit physical-index maps.
StandardEmitPassStandard emit pass implementation using GateEmitter protocol.

Functions

bracket_control_value [source]

def bracket_control_value(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    control_indices: Sequence[int],
    control_value: int | None,
) -> Generator[None, None, None]

Bracket zero-valued controls with target-neutral Pauli-X gates.

The controlled operation inside the context remains an ordinary all-ones control. Controls are interpreted LSB-first in their existing physical order, so bit zero of control_value describes control_indices[0]. One bracket surrounds the complete operation, including integral powers and vector-target broadcast.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass providing the gate emitter.
circuitAnyCircuit receiving the bracket gates.
control_indicesSequence[int]Ordered physical control qubits.
control_valueint | NoneRequired basis value, or None for the ordinary all-ones state.

Yields:

None — Control returns while the zero-valued controls are inverted.

Raises:


emit_approximate_iqft [source]

def emit_approximate_iqft(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    qubit_indices: list[int],
    truncation_depth: int,
) -> None

Emit approximate IQFT with truncated rotations matching stdlib convention.

IQFT = QFT†. SWAP comes first (undoing QFT’s trailing SWAP), then for each qubit j (low-to-high), applies inverse controlled-phase rotations with lower-indexed qubits first (omitting exponents > truncation_depth), then H.

Parameters:

NameTypeDescription
emit_pass'StandardEmitPass'The StandardEmitPass instance.
circuitAnyTarget circuit
qubit_indiceslist[int]Qubit indices
truncation_depthintMaximum exponent for controlled phase gates

emit_approximate_qft [source]

def emit_approximate_qft(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    qubit_indices: list[int],
    truncation_depth: int,
) -> None

Emit approximate QFT with truncated rotations matching stdlib convention.

Processes qubits from highest index to lowest (same as exact QFT), applying H then controlled-phase rotations with lower-indexed qubits. Rotations with exponent > truncation_depth are omitted. Finishes with bit-reversal SWAPs.

Parameters:

NameTypeDescription
emit_pass'StandardEmitPass'The StandardEmitPass instance.
circuitAnyTarget circuit
qubit_indiceslist[int]Qubit indices
truncation_depthintMaximum exponent for controlled phase gates

emit_callable_implementation_emitter [source]

def emit_callable_implementation_emitter(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: InvokeOperation,
    qubit_indices: list[int],
    bindings: dict[str, Any],
) -> bool

Emit using a selected callable implementation emitter, if present.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted.
opInvokeOperationInvocation to emit.
qubit_indiceslist[int]Physical qubit indices in operand order.
bindingsdict[str, Any]Active emit bindings.

Returns:

bool — True when the implementation emitter handled the operation.

Raises:


emit_composite_fallback [source]

def emit_composite_fallback(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: InvokeOperation,
    qubit_indices: list[int],
    bindings: dict[str, Any],
) -> None

Emit composite gate using decomposition.

If the operation has a strategy name, resolve it from the callable’s own implementation candidates.


emit_composite_gate [source]

def emit_composite_gate(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: InvokeOperation,
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> None

Emit a boxed composite/oracle invocation.

Resolves each qubit operand through resolve_qubit_index_detailed so that view-local operands (qft(q[1::2])) walk the slice_of chain and map to the root parent’s physical qubits. Raises EmitError if any operand cannot be resolved, rather than silently dropping it (previously qft(view) emitted zero gates).

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
opInvokeOperationComposite or Oracle invocation to emit.
qubit_mapQubitMapLogical-to-physical map, mutated with results.
bindingsdict[str, Any]Bindings visible at the call site.

Raises:


emit_invoke_operation [source]

def emit_invoke_operation(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: InvokeOperation,
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> None

Emit an invoke operation.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted.
opInvokeOperationInvocation to emit.
qubit_mapQubitMapCurrent qubit allocation map.
bindingsdict[str, Any]Active emit bindings.

Raises:


emit_iqft_manual [source]

def emit_iqft_manual(emit_pass: 'StandardEmitPass', circuit: Any, qubit_indices: list[int]) -> None

Emit inverse QFT using decomposition matching stdlib convention.

IQFT = QFT†. SWAP comes first (undoing QFT’s trailing SWAP), then for each qubit j (low-to-high), applies inverse controlled-phase rotations with all lower-indexed qubits k (angle = -π/2^(j-k)) first, then H.


emit_iqft_with_strategy [source]

def emit_iqft_with_strategy(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: InvokeOperation,
    qubit_indices: list[int],
) -> None

Emit IQFT considering strategy selection.

If approximate_kN is selected, omits rotations beyond depth N. Otherwise falls back to standard IQFT.

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe active emit pass whose emitter should receive decomposed IQFT gates.
circuitAnyEngine circuit being emitted.
opInvokeOperationInvocation expected to be an IQFT.
qubit_indiceslist[int]Physical qubit indices for the IQFT target register.

Raises:


emit_qft_manual [source]

def emit_qft_manual(emit_pass: 'StandardEmitPass', circuit: Any, qubit_indices: list[int]) -> None

Emit QFT using decomposition matching stdlib convention.

Processes qubits from highest index to lowest: for each qubit j, applies H then controlled-phase rotations with all lower-indexed qubits k (angle = π/2^(j-k)). Finishes with bit-reversal SWAPs.


emit_qft_with_strategy [source]

def emit_qft_with_strategy(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: InvokeOperation,
    qubit_indices: list[int],
) -> None

Emit QFT considering strategy selection.

If approximate_kN is selected, omits rotations beyond depth N. Otherwise falls back to standard QFT.

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe active emit pass whose emitter should receive decomposed QFT gates.
circuitAnyEngine circuit being emitted.
opInvokeOperationInvocation expected to be a QFT.
qubit_indiceslist[int]Physical qubit indices for the QFT target register.

Raises:


emit_qpe_manual [source]

def emit_qpe_manual(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: InvokeOperation,
    qubit_indices: list[int],
    bindings: dict[str, Any],
) -> None

Emit QPE using manual decomposition.

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe active emit pass whose emitter should receive decomposed QPE gates.
circuitAnyEngine circuit being emitted.
opInvokeOperationInvocation expected to be a QPE.
qubit_indiceslist[int]Physical qubit indices for counting and target registers, in operation operand order.
bindingsdict[str, Any]Emit-time concrete bindings used to resolve QPE block parameters or phase operands.

Raises:


extract_phase_from_params [source]

def extract_phase_from_params(
    emit_pass: 'StandardEmitPass',
    op: InvokeOperation,
    bindings: dict[str, Any],
) -> float | None

Extract a concrete phase parameter from a QPE operation.

Scans the operation’s parameter operands. The block-free QPE fallback models a single phase parameter, so more than one concrete numeric parameter is ambiguous and rejected instead of guessed.

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe active emit pass whose resolver should resolve bound scalar and array-element operands.
opInvokeOperationThe QPE invocation.
bindingsdict[str, Any]Emit-time concrete bindings keyed by parameter name, value UUID, or loop-local variable name.

Returns:

float | None — float | None: The resolved phase angle, or None when the phase operand remains symbolic.

Raises:


map_array_result_group [source]

def map_array_result_group(result_uuid: str, index_group: list[int], index_map: PhysicalIndexMap) -> None

Map an array-valued result to a physical index group.

Parameters:

NameTypeDescription
result_uuidstrUUID of the array-valued result whose element addresses should be registered.
index_grouplist[int]Physical indices for the result elements, in result-local element order.
index_mapPhysicalIndexMapMutable physical-index map updated in place with element addresses and, when available, the base result address.

update_composite_result_mapping [source]

def update_composite_result_mapping(
    op: InvokeOperation,
    qubit_groups: list[list[int]],
    qubit_map: QubitMap,
) -> None

Update qubit_map for composite gate results.

Parameters:

NameTypeDescription
opInvokeOperationInvocation whose quantum results should be mapped onto the unchanged physical slots of its operands.
qubit_groupslist[list[int]]Physical indices grouped per quantum operand. A scalar qubit contributes one index; a vector operand contributes one index per element.
qubit_mapQubitMapMutable map updated in place.

Classes

CallTransform [source]

class CallTransform(enum.Enum)

Describe the requested transform of a callable implementation.

Attributes
Methods
inverted
def inverted(self) -> CallTransform

Toggle inverse application while preserving coherent control.

Returns:

CallTransform — Transform with the inverse component toggled.


CompositeGateType [source]

class CompositeGateType(enum.Enum)

Classify standard boxed quantum callables.

Attributes

EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return
Constructor
def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.
Constructor
def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes
Methods
body_for_transform
def body_for_transform(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> tuple[Block | None, CallTransform]

Select a body and report the transform it already realizes.

A controlled-inverse invocation may reuse an explicitly registered inverse body when no implementation realizes both transforms. Keeping that fallback in the IR operation gives emitters and static analyses one selection rule while still letting each consumer apply the remaining coherent controls in its own representation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — tuple[Block | None, CallTransform]: Selected body and the transform CallTransform — already implemented by that body. The callable’s direct body is tuple[Block | None, CallTransform] — returned with DIRECT when no transform-specific body matches.

Raises:

effective_body
def effective_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — Block | None: Selected implementation body, or the callable’s Block | None — default body when no transform-specific implementation exists. Block | None — A compiler may synthesize inverse or controlled behavior from this Block | None — fallback body.

implementation_for
def implementation_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None, which only selects engine-generic implementations.
strategystr | NoneStrategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation candidate, CallableImplementation | None — or None when the callable definition has no match.

measurement_result_indices_for
def measurement_result_indices_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> frozenset[int]

Return measurement-derived results for one selected implementation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name used for implementation selection. Defaults to None.
strategystr | NoneStrategy name used for implementation selection. Defaults to the invocation’s strategy_name.

Returns:

frozenset[int] — frozenset[int]: Caller-local result positions derived from measurement in the selected body.

Raises:

select_body
def select_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> CallableBodySelection

Select and validate the composable body for this invocation.

The result carries the transform already realized by the body and the exact call-site values that bind to it. Consumers therefore cannot independently disagree about whether an invocation’s control prefix belongs to the selected implementation ABI.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

CallableBodySelection — Validated body, realized transform, and CallableBodySelection — aligned call-site operands and results.

Raises:


QubitAddress [source]

class QubitAddress

Typed key for qubit/clbit physical-index maps.

For scalar qubits: QubitAddress(uuid="abc123") For array elements: QubitAddress(uuid="abc123", element_index=2)

This replaces the f"{uuid}_{i}" string key pattern throughout the emit pipeline, making the key format explicit and preventing format-string bugs.

Constructor
def __init__(self, uuid: str, element_index: int | None = None) -> None
Attributes
Methods
from_composite_key
@classmethod
def from_composite_key(cls, key: str) -> QubitAddress

Parse a legacy composite key string into a QubitAddress.

The frontend stores qubit references as composite strings in the format "{array_uuid}_{element_index}" (e.g., cast operation qubit mappings, element UUIDs). This helper converts such strings to proper QubitAddress instances.

If the key does not match the composite format (i.e., the suffix after the last _ is not a non-negative integer), it is treated as a plain scalar UUID.

matches_array
def matches_array(self, array_uuid: str) -> bool

True if this address belongs to the given array.

with_element
def with_element(self, index: int) -> QubitAddress

Create an array-element address from this array’s base UUID.


StandardEmitPass [source]

class StandardEmitPass(EmitPass[T], Generic[T])

Standard emit pass implementation using GateEmitter protocol.

This class provides orchestration for semantic IR traversal while delegating circuit instruction construction to a GateEmitter. The concrete compiler use is CircuitLoweringPass; SDK targets materialize its immutable result instead of subclassing this class.

Parameters:

NameTypeDescription
gate_emitterGateEmitter[T]Instruction builder used during the semantic traversal.
bindingsdict[str, Any] | NoneCompile-time parameter bindings.
parameterslist[str] | NoneParameter names preserved at runtime.
composite_emitterslist[CompositeGateEmitter[T]] | NoneOptional callable-preservation or lowering hooks.
engine_namestr | NoneDiagnostic name for the traversal target.
Constructor
def __init__(
    self,
    gate_emitter: GateEmitter[T],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
    composite_emitters: list[CompositeGateEmitter[T]] | None = None,
    engine_name: str | None = None,
)
Attributes

qamomile.circuit.transpiler.passes.emit_support.condition_resolution

Helpers for compile-time condition resolution and merge remapping.

Overview

FunctionDescription
array_element_mappingCollect physical indices for the elements of an array value.
array_physical_regionResolve a one-dimensional array to its ordered physical region.
map_array_element_aliasesMap explicit array element aliases to a result array.
map_merge_outputsRegister merge output UUIDs to the same physical resources as their sources.
remap_static_merge_outputsRemap merge outputs for a compile-time constant IfOperation.
resolve_condition_address_detailedResolve a condition / source Value to its clbit_map key.
resolve_if_conditionResolve an if-condition to a compile-time boolean.
resolve_qubit_keyResolve a qubit Value to its allocation key.
ClassDescription
ArrayValueAn array of typed IR values.
BitTypeType representing a classical bit.
EmitErrorReport an engine failure to emit one semantic operation.
HasNestedOpsMixin for operations that contain nested operation lists.
IfOperationRepresents an if-else conditional operation.
MeasureOperation
MeasureVectorOperationMeasure a vector of qubits.
ProjectOperationProject a qubit in one Pauli basis and keep the projected state.
QubitAddressTyped key for qubit/clbit physical-index maps.
UIntTypeType representing an unsigned integer.
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.
ValueResolverResolves Value objects to concrete indices or values.

Functions

array_element_mapping [source]

def array_element_mapping(source_uuid: str, index_map: Mapping[QubitAddress, int]) -> dict[int, int]

Collect physical indices for the elements of an array value.

Parameters:

NameTypeDescription
source_uuidstrUUID of the array whose element addresses should be collected.
index_mapMapping[QubitAddress, int]Physical-index map to read.

Returns:

dict[int, int] — dict[int, int]: Mapping from element index to physical index.


array_physical_region [source]

def array_physical_region(array: 'ArrayValue') -> tuple[str, tuple[int, ...]] | None

Resolve a one-dimensional array to its ordered physical region.

The region is expressed independently of SSA version UUIDs: the first element is the root array’s logical_id and the second is the ordered tuple of root-space indices addressed by the array. This makes a root register and its full view compare equal while keeping partial, strided, reordered, and different-root registers distinct.

Parameters:

NameTypeDescription
arrayArrayValueRoot array or nested sliced view to resolve. The array must be one-dimensional and have a compile-time integer length; every slice bound in its ancestry must also be constant.

Returns:

tuple[str, tuple[int, ...]] | None — tuple[str, tuple[int, ...]] | None: (root_logical_id, indices) when the complete ordered coverage is statically known, otherwise None. Symbolic shapes or slice bounds remain unresolved so callers can defer to emit-time physical mappings.


map_array_element_aliases [source]

def map_array_element_aliases(
    result_uuid: str,
    element_mapping: Mapping[int, int],
    index_map: PhysicalIndexMap,
    *,
    map_base_address: bool = True,
) -> None

Map explicit array element aliases to a result array.

Parameters:

NameTypeDescription
result_uuidstrUUID of the result array that should receive the element aliases.
element_mappingMapping[int, int]Physical indices keyed by result element index.
index_mapPhysicalIndexMapMutable physical-index map updated in place with missing result element addresses and, when requested, the result base address.
map_base_addressboolWhether to map the scalar base address for the result array to its lowest-index element. Defaults to True.

map_merge_outputs [source]

def map_merge_outputs(
    if_op: IfOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    resolve_scalar_qubit: Any = None,
    bindings: dict[str, Any] | None = None,
    resolver: ValueResolver | None = None,
    reject_runtime_bit_mux: bool = False,
    allowed_mixed_bit_outputs: frozenset[str] | set[str] | None = None,
) -> None

Register merge output UUIDs to the same physical resources as their sources.

Runtime-if counterpart of :func:remap_static_merge_outputs: both branches may execute, so quantum merges are validated to sit on identical physical resources, and classical Bit merges consolidate both branches’ clbits only when the complete source-alias partition is representable without overwriting an independently live value. Outputs already registered are left untouched.

Parameters:

NameTypeDescription
if_opIfOperationThe runtime if-else whose merged outputs need physical-resource registration; merges are read through iter_merges.
qubit_mapQubitMapAddress-to-physical-qubit map, mutated in place.
clbit_mapClbitMapAddress-to-physical-clbit map, mutated in place.
resolve_scalar_qubitAnyOptional callable (source, qubit_map) -> int | None used to resolve scalar qubit sources that are not directly registered (e.g. array elements). Defaults to None, restricting resolution to direct and root-array lookups.
bindingsdict[str, Any] | NoneActive bindings used to fold a classical Bit merge source’s symbolic Vector[Bit] element index / slice bounds (e.g. an unrolled loop variable). Defaults to None (empty), restricting element resolution to constant indices.
resolverValueResolver | NoneResolver used with bindings to fold non-constant element indices; None restricts to constants. Defaults to None.
reject_runtime_bit_muxboolWhen True, raise EmitError for a runtime Bit merge that requires an at-runtime mux, mixes a pre-existing source with a branch-local measurement, or has incompatible source-sharing partitions across multiple outputs. Two all-branch-local source sets remain eligible only when their alias partitions match. Defaults to False.
allowed_mixed_bit_outputsfrozenset[str] | set[str] | NoneMerge result UUIDs whose pre-existing source is proven dead after the merge. This includes safe ordinary-if updates and phi-like loop condition remeasurements. Defaults to None.

Raises:


remap_static_merge_outputs [source]

def remap_static_merge_outputs(
    if_op: IfOperation,
    condition_value: bool,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any] | None = None,
    resolver: ValueResolver | None = None,
) -> None

Remap merge outputs for a compile-time constant IfOperation.

Registers each merged output under the physical resource of the branch selected by the resolved condition, so downstream operations referencing the merge output resolve to the surviving branch’s qubit / clbit. Outputs already registered are left untouched.

Parameters:

NameTypeDescription
if_opIfOperationThe if-else whose condition resolved at compile time; merges are read through iter_merges.
condition_valueboolThe resolved condition, selecting which branch’s source the outputs alias.
qubit_mapQubitMapAddress-to-physical-qubit map, mutated in place.
clbit_mapClbitMapAddress-to-physical-clbit map, mutated in place.
bindingsdict[str, Any] | NoneActive bindings used to fold a merge source’s symbolic Vector[Bit] element index / slice bounds (e.g. an unrolled loop variable). Defaults to None (empty), restricting element resolution to constant indices.
resolverValueResolver | NoneResolver used with bindings to fold non-constant element indices; None restricts to constants. Defaults to None.

resolve_condition_address_detailed [source]

def resolve_condition_address_detailed(
    condition: Value,
    bindings: dict[str, Any],
    resolver: ValueResolver | None = None,
) -> tuple[QubitAddress, bool]

Resolve a condition / source Value to its clbit_map key.

Single source of truth (shared by control_flow_emission.emit_if / emit_while, the Qiskit / CUDA-Q engines, ResourceAllocator’s loop-carried / merge aliasing, and the merge-output mapping helpers here) for turning a runtime control-flow condition — or a merge source Value — into the address its classical bit is registered under.

Scalar measurement results register under QubitAddress(bit.uuid), while a Vector[Bit] element s[i] (s = qmc.measure(register)) registers under QubitAddress(root_array.uuid, root_index). The element index and every slice_start / slice_step along the parent’s slice_of chain are resolved the same way — taken directly when constant, otherwise folded through bindings via resolver — and composed into the root index via root_index = start + step * view_local_index repeated along the chain.

Parameters:

NameTypeDescription
conditionValueThe condition operand or merge source Value.
bindingsdict[str, Any]Active emit-time bindings used to fold symbolic indices / slice bounds. May be empty for callers that only have constant addresses to resolve (e.g. the allocator’s pre-emit pass).
resolverValueResolver | NoneResolver exposing resolve_int_value; None restricts resolution to constants. Defaults to None.

Returns:

tuple[QubitAddress, bool] — tuple[QubitAddress, bool]: (address, resolved_as_element). resolved_as_element is True only when condition is a Vector[Bit] element whose index (and any slice bounds) resolved to concrete ints, giving the root-space QubitAddress(root.uuid, root_index). It is False for a plain scalar, or when an element’s index / slice bound could not be resolved (the scalar UUID fallback). Callers that mutate clbit_map should trust the address as a vector key only when this flag is True, to avoid aliasing an unresolved element onto an unrelated scalar slot.


resolve_if_condition [source]

def resolve_if_condition(condition: Any, bindings: dict[str, Any]) -> bool | None

Resolve an if-condition to a compile-time boolean.


resolve_qubit_key [source]

def resolve_qubit_key(qubit: 'Value') -> tuple[QubitAddress | None, bool]

Resolve a qubit Value to its allocation key.

Parameters:

NameTypeDescription
qubitValueQubit value to resolve. Array elements with a constant index are resolved through their full slice_of chain to the root array address.

Returns:

tuple[QubitAddress | None, bool] — tuple[QubitAddress | None, bool]: (address, is_array_element). address is the root-space address for a resolvable array element, None for an array element whose index or slice bounds are symbolic at this binding-free stage, and a scalar UUID address for non-array qubits. A negative constant index (or an out-of-contract slice bound) also yields None: resolve_root_qubit_address refuses it rather than letting it silently address a wrong root slot.

Classes

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:

bool — True iff slice_of is non-None.

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

BitType [source]

class BitType(ClassicalTypeMixin, ValueType)

Type representing a classical bit.


EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return
Constructor
def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


MeasureOperation [source]

class MeasureOperation(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

MeasureVectorOperation [source]

class MeasureVectorOperation(Operation)

Measure a vector of qubits.

Takes a Vector[Qubit] (ArrayValue) and produces a Vector[Bit] (ArrayValue). This operation measures all qubits in the vector as a single operation.

operands: [ArrayValue of qubits] results: [ArrayValue of bits]

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ProjectOperation [source]

class ProjectOperation(Operation)

Project a qubit in one Pauli basis and keep the projected state.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    axis: str = 'z',
) -> None
Attributes

QubitAddress [source]

class QubitAddress

Typed key for qubit/clbit physical-index maps.

For scalar qubits: QubitAddress(uuid="abc123") For array elements: QubitAddress(uuid="abc123", element_index=2)

This replaces the f"{uuid}_{i}" string key pattern throughout the emit pipeline, making the key format explicit and preventing format-string bugs.

Constructor
def __init__(self, uuid: str, element_index: int | None = None) -> None
Attributes
Methods
from_composite_key
@classmethod
def from_composite_key(cls, key: str) -> QubitAddress

Parse a legacy composite key string into a QubitAddress.

The frontend stores qubit references as composite strings in the format "{array_uuid}_{element_index}" (e.g., cast operation qubit mappings, element UUIDs). This helper converts such strings to proper QubitAddress instances.

If the key does not match the composite format (i.e., the suffix after the last _ is not a non-negative integer), it is treated as a plain scalar UUID.

matches_array
def matches_array(self, array_uuid: str) -> bool

True if this address belongs to the given array.

with_element
def with_element(self, index: int) -> QubitAddress

Create an array-element address from this array’s base UUID.


UIntType [source]

class UIntType(ClassicalTypeMixin, ValueType)

Type representing an unsigned integer.


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


ValueResolver [source]

class ValueResolver

Resolves Value objects to concrete indices or values.

Constructor
def __init__(self, parameters: set[str] | None = None)

Create an emit-time resolver.

Parameters:

NameTypeDescription
parametersset[str] | NoneNames preserved as engine runtime parameters. Defaults to None.
Attributes
Methods
bind_block_params
def bind_block_params(
    self,
    block_value: Any,
    param_operands: list['Value'],
    bindings: dict[str, Any],
    *,
    parameter_factory: Callable[[str, str], Any] | None = None,
) -> dict[str, Any]

Create local bindings by matching block inputs to call-site operands.

Parameters:

NameTypeDescription
block_valueAnyNested block whose classical/object inputs are bound. Objects without input_values receive no additional local bindings for compatibility with optional engine recipes.
param_operandslist[Value]Classical/object call-site operands in the controlled operation’s signature order.
bindingsdict[str, Any]Parent emit-time bindings used to resolve the call-site operands.
parameter_factoryCallable[[str, str], Any] | NoneOptional engine parameter factory used when an operand is a declared runtime parameter rather than a concrete binding. Defaults to None so standalone resolver use remains engine-neutral.

Returns:

dict[str, Any] — dict[str, Any]: Parent bindings with each inner formal rebound under both its UUID and sanctioned parameter-name key.

get_parameter_key
def get_parameter_key(self, value: 'Value', bindings: dict[str, Any]) -> str | None

Get the engine parameter key for a symbolic scalar.

Parameters:

NameTypeDescription
valueValueScalar value or array element to identify.
bindingsdict[str, Any]Active bindings used to resolve element indices and slice offsets.

Returns:

str | None — str | None: Scalar name or root-array indexed key, or None when an array element’s root location is unresolved.

lookup_in_bindings
def lookup_in_bindings(
    self,
    value: Any,
    bindings: dict[str, Any],
    *,
    index_array: bool = False,
) -> Any

Canonical resolution chain for a Value against bindings.

All other resolver methods (resolve_bound_value, resolve_classical_value, resolve_int_value, resolve_operand_for_binding) wrap this single chain. Centralizing precedence here prevents the historical drift where one resolver checked is_parameter before UUID and another checked it after, which manifested as obscure binding failures when name-keyed writes were dropped from the emit pass.

Resolution order (each step returns immediately on a hit):

  1. value is already a concrete Python scalar (no uuid).

  2. value.uuid is in bindings — return that. This is where emit-time-computed intermediates (evaluate_binop / evaluate_classical_predicate results) and merge aliases live.

  3. A compile-time array or dict payload stored in typed metadata.

  4. value.is_constant() — return value.get_const().

  5. value.is_parameter() and its parameter name is in bindings — return that.

  6. (When index_array=True) value is an array element with a resolvable parent in bindings — index into it.

  7. A non-empty display name is present in bindings. This is a compatibility bridge for programmatically constructed Values and older transforms that do not carry parameter metadata; UUID and explicit parameter provenance always take precedence.

Compiler-created temporaries are anonymous and compiler-internal writers use UUID keys, so the compatibility bridge cannot merge two same-named temporaries. Kernel parameters should normally resolve via explicit parameter metadata, while loop variables and intermediates remain UUID-keyed.

Parameters:

NameTypeDescription
valueAnyThe IR value (or already-concrete Python scalar) to resolve.
bindingsdict[str, Any]The active bindings dictionary.
index_arrayboolWhen True, also resolve array-element accesses via parent_array indexing. Off by default because not all callers want to index into bound containers.

Returns:

Any — The resolved Python value, or None if no step matched.

resolve_bound_value
def resolve_bound_value(self, value: 'Value', bindings: dict[str, Any]) -> Any

Resolve a Value to its raw bound Python object.

Wraps :meth:lookup_in_bindings with index_array=True so that arr[i] accesses against a bound container resolve to the element. Does not coerce the result — callers that need a numeric scalar should go through :meth:resolve_classical_value.

Parameters:

NameTypeDescription
valueValueValue to resolve.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

Any — Raw bound object, or None when unresolved.

resolve_classical_value
def resolve_classical_value(self, value: 'Value', bindings: dict[str, Any]) -> Any

Resolve a classical Value to a concrete Python value.

Numeric bindings are normalized to native Python scalars regardless of whether they come from a direct binding or from array-element indexing, so downstream isinstance(x, (int, float)) checks are stable when callers bind np.pi/4 or the like. bool is preserved (not coerced to int). Non-numeric values (Hamiltonians, strings, dict values, …) pass through unchanged.

Parameters:

NameTypeDescription
valueValueClassical value to resolve.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

Any — Resolved native scalar/object, or None when unresolved.

resolve_int_value
def resolve_int_value(self, val: Any, bindings: dict[str, Any]) -> int | None

Resolve a value to an integer, or None when unresolvable.

Unresolvable symbolic Values must return None. The previous return 0 fallback caused silent loop elision when parameter shape dims (gamma_dim0) reached this resolver without being folded into constants — downstream loop-bound resolution saw 0 and quietly emitted an empty loop. Returning None propagates the failure to emit_for_unrolled, which converts it into a hard compile error.

resolve_operand_for_binding
def resolve_operand_for_binding(self, operand: Any, bindings: dict[str, Any]) -> Any

Resolve an operand to a concrete value for block parameter binding.

Used when calling a sub-block (e.g. a controlled-U body): each param operand at the call site must resolve to a value to seed the callee’s parameter bindings.

Parameters:

NameTypeDescription
operandAnyCall-site value or already-concrete operand.
bindingsdict[str, Any]Parent emit-time bindings.

Returns:

Any — Resolved value, or None when the operand is symbolic.

resolve_qubit_index
def resolve_qubit_index(self, v: 'Value', qubit_map: QubitMap, bindings: dict[str, Any]) -> int | None

Resolve a qubit value to its physical index.

Parameters:

NameTypeDescription
vValueScalar or indexed qubit value.
qubit_mapQubitMapPhysical resource mapping.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

int | None — int | None: Physical index, or None when unresolved.

resolve_qubit_index_detailed
def resolve_qubit_index_detailed(
    self,
    v: 'Value',
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> QubitResolutionResult

Resolve a Value to a physical qubit index with detailed failure info.

Parameters:

NameTypeDescription
vValueThe qubit Value to resolve. May be a scalar qubit or an array element (possibly through a sliced view chain).
qubit_mapQubitMapMapping from QubitAddress to physical qubit indices built by the resource allocator.
bindingsdict[str, Any]Active emit-time bindings used to resolve symbolic element indices and slice bounds.

Returns:

QubitResolutionResult — Success with the physical index, or a failure carrying a ResolutionFailureReason — including NEGATIVE_INDEX when a resolved element index is negative or a resolved slice bound violates the frontend contract (non-negative start, positive step); composing those through the affine map would silently address a wrong root slot.

resolve_slice_chain
def resolve_slice_chain(
    self,
    av: 'ArrayValue',
    bindings: dict[str, Any],
    *,
    operation: str = 'emit',
) -> tuple['ArrayValue', int, int]

Walk an ArrayValue’s slice_of chain and return root + affine map.

Composes the nested affine maps so that a view-local index i corresponds to the root-space index start + step * i. For a root ArrayValue (no slice_of chain), returns (av, 0, 1) so callers can always apply the same formula uniformly.

Parameters:

NameTypeDescription
av'ArrayValue'The possibly-sliced ArrayValue whose root and affine mapping should be resolved.
bindingsdict[str, Any]Compile-time parameter bindings; required when any slice_start / slice_step in the chain is symbolic.
operationstrHuman-readable name of the enclosing emit operation. Used only in the EmitError message when a symbolic slice bound cannot be resolved. Defaults to "emit".

Returns:

'ArrayValue' — Tuple (root_array, start, step) where root_array is int — the underlying non-sliced ArrayValue, and start/step int — are Python int values satisfying tuple['ArrayValue', int, int] — view[i] == root_array[start + step * i].

Raises:

Example:

>>> # For ``view = q[1::2]`` where ``q`` has 4 qubits:
>>> resolver.resolve_slice_chain(view_av, bindings={})
(q_av, 1, 2)

qamomile.circuit.transpiler.passes.emit_support.control_batching

Own controlled-body batching policy for engine fallback emission.

Overview

FunctionDescription
classify_control_workReturn the shared coherent-control category for one IR operation.
combine_control_batch_profilesCombine sequential emission profiles up to the decision threshold.
should_batch_controlled_bodyReturn whether engine fallback should share one AND carrier.
static_controlled_batch_profileReturn context-free emission batching information for one operation.
ClassDescription
ControlBatchProfileDescribe resolved work and the engine’s exact-two-control choice.
ControlWorkKindDescribe how an operation participates in coherent-control analysis.
GateOperationQuantum gate operation.
GateOperationType

Constants

Functions

classify_control_work [source]

def classify_control_work(operation: Operation) -> ControlWorkKind

Return the shared coherent-control category for one IR operation.

BOOKKEEPING means zero controlled quantum work, not that the operation may be discarded. Emitters must still run bookkeeping semantics such as classical evaluation, cast alias propagation, and deferred borrow-return validation.

Parameters:

NameTypeDescription
operationOperationIR operation inside a coherently controlled body.

Returns:

ControlWorkKind — Semantic category consumed by both estimation and emission policy.


combine_control_batch_profiles [source]

def combine_control_batch_profiles(profiles: Iterable[ControlBatchProfile]) -> ControlBatchProfile

Combine sequential emission profiles up to the decision threshold.

Parameters:

NameTypeDescription
profilesIterable[ControlBatchProfile]Resolved operation profiles.

Returns:

ControlBatchProfile — Capped work and the union of exact-two choices.


should_batch_controlled_body [source]

def should_batch_controlled_body(num_controls: int, *, profile: ControlBatchProfile) -> bool

Return whether engine fallback should share one AND carrier.

Parameters:

NameTypeDescription
num_controlsintConcrete number of composed controls.
profileControlBatchProfileContext-resolved emission profile.

Returns:

bool — Whether engine fallback should build one body-wide ladder.


static_controlled_batch_profile [source]

def static_controlled_batch_profile(operation: Operation) -> ControlBatchProfile | None

Return context-free emission batching information for one operation.

None means that emission must resolve classical state or a nested callable before deciding the weight. Unknown operation kinds count as one leaf so eligibility analysis never hides work rejected by the later walker.

Parameters:

NameTypeDescription
operationOperationOperation inside a controlled body.

Returns:

ControlBatchProfile | None — ControlBatchProfile | None: Context-free emission profile, or None when engine-specific value resolution is required.

Classes

ControlBatchProfile [source]

class ControlBatchProfile

Describe resolved work and the engine’s exact-two-control choice.

Parameters:

NameTypeDescription
weightintControlled work clamped to zero, one, or two.
selects_exact_twoboolWhether the engine selects a shared carrier when exactly two outer controls are present.
Constructor
def __init__(self, weight: int = 0, selects_exact_two: bool = False) -> None
Attributes

ControlWorkKind [source]

class ControlWorkKind(enum.Enum)

Describe how an operation participates in coherent-control analysis.

Values:

BOOKKEEPING: The operation contributes no controlled quantum gate, but its validation or value/alias update may still have to execute. QUANTUM_LEAF: One primitive quantum gate whose decomposition policy is selected by the consumer. CONTEXT_DEPENDENT: A structured operation whose work must be resolved from its values, selected body, or nested regions. UNSUPPORTED: An operation outside the supported controlled-unitary language. Consumers keep it visible so their normal error path rejects it rather than silently dropping it.

Attributes

GateOperation [source]

class GateOperation(Operation)

Quantum gate operation.

For rotation gates (RX, RY, RZ, P, CP, RZZ), the angle parameter is stored as the last element of operands. Use the theta property for typed read access and the rotation / fixed factory class-methods for type-safe construction.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    gate_type: GateOperationType | None = None,
) -> None
Attributes
Methods
fixed
@classmethod
def fixed(
    cls,
    gate_type: GateOperationType,
    qubits: list[Value],
    results: list[Value],
) -> 'GateOperation'

Create a fixed gate (H, X, CX, SWAP, …) with no angle parameter.

rotation
@classmethod
def rotation(
    cls,
    gate_type: GateOperationType,
    qubits: list[Value],
    theta: Value,
    results: list[Value],
) -> 'GateOperation'

Create a rotation gate (RX, RY, RZ, P, CP, RZZ) with an angle.


GateOperationType [source]

class GateOperationType(enum.Enum)
Attributes

qamomile.circuit.transpiler.passes.emit_support.control_flow_emission

Control flow emission helpers for StandardEmitPass.

Extracted from standard_emit.py to keep the main class focused on gate-level dispatch. Each function mirrors the original method but takes an explicit emit_pass parameter instead of self.

These are the default implementations. Engine-specific emit passes (e.g., QiskitEmitPass) may override the corresponding methods on StandardEmitPass; calling super()._emit_for(...) etc. will ultimately delegate here.

Overview

FunctionDescription
array_static_lengthResolve a one-dimensional array’s compile-time length.
dict_param_keyFormat the engine-parameter name for one entry of a Dict parameter.
emit_forEmit a for loop.
emit_for_itemsEmit for-items loop (always unrolled).
emit_for_unrolledEmit a range loop by replaying every iteration.
emit_ifEmit if/else operation.
emit_whileEmit while loop operation.
evaluate_dict_getitemEvaluate a DictGetItemOperation and store the result in bindings.
join_runtime_condition_sourcesJoin mutually exclusive overwrite states after runtime control flow.
map_merge_outputsRegister merge output UUIDs to the same physical resources as their sources.
mark_updated_while_conditionRecord that a while update may overwrite its initial snapshot clbit.
register_classical_merge_aliasesBind classical merge outputs to a concrete value when resolvable.
register_merge_outputsRegister merge output UUIDs via the shared map_merge_outputs utility.
reject_stale_runtime_conditionReject rereading a measurement snapshot overwritten by an earlier loop.
remap_static_merge_outputsRemap merge outputs for a compile-time constant IfOperation.
resolve_condition_addressResolve a runtime control-flow condition to its clbit_map key.
resolve_condition_address_detailedResolve a condition / source Value to its clbit_map key.
resolve_dict_entriesResolve DictValue to concrete (key, value) pairs.
resolve_if_conditionResolve an if-condition to a compile-time boolean.
resolve_loop_boundsResolve for-loop bounds (start, stop, step) from operands.
restore_runtime_condition_sourcesRestore one runtime-control-flow path’s overwrite state.
runtime_condition_source_keyIdentify one immutable measurement snapshot and physical clbit.
snapshot_runtime_condition_sourcesSnapshot path-local measurement sources overwritten by while loops.
validate_region_argsValidate the SSA identities owned by a loop’s region arguments.
validated_loop_indexsetBuild an engine-safe Python range for resolved loop bounds.
ClassDescription
ArrayValueAn array of typed IR values.
BitTypeType representing a classical bit.
DictGetItemOperationLook up one entry of a Dict by a (possibly symbolic) key.
EmitErrorReport an engine failure to emit one semantic operation.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
IfOperationRepresents an if-else conditional operation.
MeasureVectorOperationMeasure a vector of qubits.
ParameterContainerKindClassify the public container that owns one engine scalar slot.
QInitOperationInitialize the qubit
QubitAddressTyped key for qubit/clbit physical-index maps.
RegionArgExplicit loop-carried value on a loop operation (MLIR-style iter_arg).
StandardEmitPassStandard emit pass implementation using GateEmitter protocol.
ValueA typed SSA value in the IR.
ValueResolverResolves Value objects to concrete indices or values.
WhileOperationRepresents a while loop operation.

Functions

array_static_length [source]

def array_static_length(array: 'ArrayValue') -> int | None

Resolve a one-dimensional array’s compile-time length.

Parameters:

NameTypeDescription
arrayArrayValueArray whose sole shape dimension is inspected.

Returns:

int | None — int | None: Non-negative static length, or None when the array is not one-dimensional, its length is symbolic/non-integral, or it is malformed with a negative length. Boolean constants are rejected even though bool is an int subclass.


dict_param_key [source]

def dict_param_key(dict_name: str, key: Any) -> str

Format the engine-parameter name for one entry of a Dict parameter.

The key is formatted with repr rather than str so the helper is collision-proof on its own: str("0") and str(0) both yield "coeffs[0]", but repr keeps the string key distinct ("coeffs['0']"). Callers pass keys already normalized to plain int / tuple-of-int (see :func:normalize_dict_binding_key), for which repr and str produce identical text (repr(3) == '3', repr((0, 1)) == '(0, 1)'), so the emitted names are unchanged.

Parameters:

NameTypeDescription
dict_namestrThe kernel argument name of the Dict parameter.
keyAnyThe looked-up key, already normalized (a plain int or a tuple of plain ints — see :func:normalize_dict_binding_key).

Returns:

str — The engine parameter name, e.g. "coeffs[3]" for an int key or "coeffs[(0, 1)]" for a tuple key.


emit_for [source]

def emit_for(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: ForOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
    force_unroll: bool = False,
) -> None

Emit a for loop.


emit_for_items [source]

def emit_for_items(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: ForItemsOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
) -> None

Emit for-items loop (always unrolled).

This handles iteration over Dict items, e.g.: for (i, j), Jij in qmc.items(ising): ...

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe emit pass (for resolver access).
circuitAnyThe engine circuit being built.
opForItemsOperationThe for-items loop being unrolled.
qubit_mapQubitMapCurrent qubit address mapping.
clbit_mapClbitMapCurrent classical bit address mapping.
bindingsdict[str, Any]Current emit-time bindings.

Raises:


emit_for_unrolled [source]

def emit_for_unrolled(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: ForOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
) -> None

Emit a range loop by replaying every iteration.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass and value resolver.
circuitAnyEngine circuit being constructed.
opForOperationRange loop to replay.
qubit_mapQubitMapLogical-to-physical qubit map.
clbit_mapClbitMapLogical-to-physical classical-bit map.
bindingsdict[str, Any]Enclosing emit-time bindings, updated with carry results and the final loop-index identity.

Returns:

None — Operations are appended to circuit in place.

Raises:


emit_if [source]

def emit_if(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: IfOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
) -> None

Emit if/else operation.

Handles two condition types:

  1. Compile-time constant (plain Python int/bool from @qkernel AST transformer closure variables, constant-folded Values, or Values resolvable via bindings): the active branch is emitted unconditionally, the inactive branch is discarded. No engine c_if / if_test is needed.

  2. Runtime condition (measurement Value that cannot be resolved at compile time): delegates to the engine’s emit_if_start / emit_else_start / emit_if_end protocol.


emit_while [source]

def emit_while(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: WhileOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
) -> None

Emit while loop operation.


evaluate_dict_getitem [source]

def evaluate_dict_getitem(
    emit_pass: 'StandardEmitPass',
    op: DictGetItemOperation,
    bindings: dict[str, Any],
) -> None

Evaluate a DictGetItemOperation and store the result in bindings.

Resolves each key component (typically a for-items loop variable bound by UUID in bindings), looks the key up in the dict’s resolved entries, and writes the value into bindings under the result UUID so downstream ops (BinOps feeding gate angles) can consume it.

When the dict is a declared runtime parameter (transpile(..., parameters=["coeffs"])), there are no entries to look up; the resolved key instead names one engine parameter (coeffs[3] / coeffs[(0, 1)]) which is stored under the result UUID. Repeated lookups of the same key share one engine parameter via _get_or_create_parameter.

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe emit pass (for resolver access).
opDictGetItemOperationThe lookup op being evaluated.
bindingsdict[str, Any]Current emit-time bindings.

Raises:


join_runtime_condition_sources [source]

def join_runtime_condition_sources(emit_pass: 'StandardEmitPass', *paths: frozenset[tuple[str, int]] = ()) -> None

Join mutually exclusive overwrite states after runtime control flow.

Parameters:

NameTypeDescription
emit_passStandardEmitPassEmit pass receiving the joined state.
*pathsfrozenset[tuple[str, int]]Completed branch states.

map_merge_outputs [source]

def map_merge_outputs(
    if_op: IfOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    resolve_scalar_qubit: Any = None,
    bindings: dict[str, Any] | None = None,
    resolver: ValueResolver | None = None,
    reject_runtime_bit_mux: bool = False,
    allowed_mixed_bit_outputs: frozenset[str] | set[str] | None = None,
) -> None

Register merge output UUIDs to the same physical resources as their sources.

Runtime-if counterpart of :func:remap_static_merge_outputs: both branches may execute, so quantum merges are validated to sit on identical physical resources, and classical Bit merges consolidate both branches’ clbits only when the complete source-alias partition is representable without overwriting an independently live value. Outputs already registered are left untouched.

Parameters:

NameTypeDescription
if_opIfOperationThe runtime if-else whose merged outputs need physical-resource registration; merges are read through iter_merges.
qubit_mapQubitMapAddress-to-physical-qubit map, mutated in place.
clbit_mapClbitMapAddress-to-physical-clbit map, mutated in place.
resolve_scalar_qubitAnyOptional callable (source, qubit_map) -> int | None used to resolve scalar qubit sources that are not directly registered (e.g. array elements). Defaults to None, restricting resolution to direct and root-array lookups.
bindingsdict[str, Any] | NoneActive bindings used to fold a classical Bit merge source’s symbolic Vector[Bit] element index / slice bounds (e.g. an unrolled loop variable). Defaults to None (empty), restricting element resolution to constant indices.
resolverValueResolver | NoneResolver used with bindings to fold non-constant element indices; None restricts to constants. Defaults to None.
reject_runtime_bit_muxboolWhen True, raise EmitError for a runtime Bit merge that requires an at-runtime mux, mixes a pre-existing source with a branch-local measurement, or has incompatible source-sharing partitions across multiple outputs. Two all-branch-local source sets remain eligible only when their alias partitions match. Defaults to False.
allowed_mixed_bit_outputsfrozenset[str] | set[str] | NoneMerge result UUIDs whose pre-existing source is proven dead after the merge. This includes safe ordinary-if updates and phi-like loop condition remeasurements. Defaults to None.

Raises:


mark_updated_while_condition [source]

def mark_updated_while_condition(
    emit_pass: 'StandardEmitPass',
    operation: WhileOperation,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
) -> None

Record that a while update may overwrite its initial snapshot clbit.

Parameters:

NameTypeDescription
emit_passStandardEmitPassEmit pass carrying path-local overwrite state.
operationWhileOperationEmitted while operation.
clbit_mapClbitMapCurrent per-iteration clbit aliases.
bindingsdict[str, Any]Active emit-time bindings.

register_classical_merge_aliases [source]

def register_classical_merge_aliases(
    emit_pass: 'StandardEmitPass',
    op: IfOperation,
    bindings: dict[str, Any],
    resolved: bool | None,
) -> None

Bind classical merge outputs to a concrete value when resolvable.

The frontend creates a merge for every variable referenced in an if-branch, including read-only ones (e.g. a for-loop index j that is read but not assigned in the branch). These read-only merges are identity merges — both inputs reference the same IR Value — so the merge output is deterministically equal to that input.

For classical types (UInt / Float / Bit) the merge outputs are not captured by map_merge_outputs / remap_static_merge_outputs (which only handle qubit / clbit phys-resource mapping). Without this binding, downstream uses like data[j_merge_4] cannot resolve the index and emit fails with symbolic_index_not_bound.

The alias is written to bindings by both UUID and (when present) name, mirroring the pattern used by emit_for_unrolled for the original loop variable.

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe active emit pass (for resolver access).
opIfOperationThe if-else whose merged classical outputs should be bound; merges are read through iter_merges.
bindingsdict[str, Any]Current bindings; mutated in place to bind merge outputs.
resolvedbool | NoneTrue / False if the if was compile-time resolved (use the selected branch’s input); None if it was a runtime if (only bind identity merges).

Returns:

None — None.


register_merge_outputs [source]

def register_merge_outputs(
    emit_pass: 'StandardEmitPass',
    op: IfOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any] | None = None,
) -> None

Register merge output UUIDs via the shared map_merge_outputs utility.

Uses the full ValueResolver.resolve_qubit_index_detailed for scalar qubit resolution (handles array element operands). Runs at emit time with reject_runtime_bit_mux=True so an unrepresentable runtime multiplexing of two pre-existing measured bits fails loudly rather than silently binding the merge to the true branch.

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe active emit pass, providing the ValueResolver used for scalar / array-element resolution.
opIfOperationThe runtime if-else whose merged outputs are registered onto their physical clbits / qubits.
qubit_mapQubitMapAddress-to-physical-qubit map, mutated in place.
clbit_mapClbitMapAddress-to-physical-clbit map, mutated in place.
bindingsdict[str, Any] | NoneActive emit-time bindings used to fold a merge source’s symbolic Vector[Bit] element index (e.g. an unrolled loop variable). Defaults to None (empty).

Raises:


reject_stale_runtime_condition [source]

def reject_stale_runtime_condition(
    emit_pass: 'StandardEmitPass',
    condition: Value,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
) -> None

Reject rereading a measurement snapshot overwritten by an earlier loop.

Parameters:

NameTypeDescription
emit_passStandardEmitPassEmit pass carrying path-local overwrite state.
conditionValueRuntime if/while condition about to be emitted.
clbit_mapClbitMapCurrent per-iteration clbit aliases.
bindingsdict[str, Any]Active emit-time bindings.

Raises:


remap_static_merge_outputs [source]

def remap_static_merge_outputs(
    if_op: IfOperation,
    condition_value: bool,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any] | None = None,
    resolver: ValueResolver | None = None,
) -> None

Remap merge outputs for a compile-time constant IfOperation.

Registers each merged output under the physical resource of the branch selected by the resolved condition, so downstream operations referencing the merge output resolve to the surviving branch’s qubit / clbit. Outputs already registered are left untouched.

Parameters:

NameTypeDescription
if_opIfOperationThe if-else whose condition resolved at compile time; merges are read through iter_merges.
condition_valueboolThe resolved condition, selecting which branch’s source the outputs alias.
qubit_mapQubitMapAddress-to-physical-qubit map, mutated in place.
clbit_mapClbitMapAddress-to-physical-clbit map, mutated in place.
bindingsdict[str, Any] | NoneActive bindings used to fold a merge source’s symbolic Vector[Bit] element index / slice bounds (e.g. an unrolled loop variable). Defaults to None (empty), restricting element resolution to constant indices.
resolverValueResolver | NoneResolver used with bindings to fold non-constant element indices; None restricts to constants. Defaults to None.

resolve_condition_address [source]

def resolve_condition_address(
    condition: Value,
    bindings: dict[str, Any],
    resolver: ValueResolver | None,
) -> QubitAddress

Resolve a runtime control-flow condition to its clbit_map key.

Scalar measurement results carry their own UUID and the clbit allocator registers them under QubitAddress(bit.uuid). Vector[Bit] element accesses (s[i] where s = qmc.measure(register)) instead live under QubitAddress(root_array.uuid, root_index). The element index and every slice_start / slice_step along the parent’s slice_of chain are resolved the same way — taken directly when constant, otherwise folded through bindings via resolver so that loop-variable indices and runtime-valued slice bounds (s[j:k] where j/k are loop variables) both work. The chain composes into a root-space index via the standard affine map root_index = start + step * view_local_index repeated along the chain — matching ResourceAllocator._resolve_root_qubit_address / ValueResolver.resolve_slice_chain. Falls back to the scalar address when no parent array is set, or when the index or any slice bound cannot be resolved to a concrete int (e.g. an engine runtime parameter, which cannot index a static classical register, or any symbolic value with no resolver), deferring the diagnostic to the caller’s clbit_map lookup. Used by both the default if/while emission path and the Qiskit / CUDA-Q engines when looking up a measurement-derived clbit for a runtime predicate.

Parameters:

NameTypeDescription
conditionValueCondition operand of an IfOperation or WhileOperation, or an operand of a measurement-derived classical predicate (e.g. inside RuntimeClassicalExpr).
bindingsdict[str, Any]Active emit-time bindings used to resolve symbolic indices and slice bounds (loop variables, compile-time-bound parameters).
resolverValueResolver | NoneThe active ValueResolver exposing resolve_int_value. None is accepted for early-emit pre-scans (e.g. CUDA-Q’s loop-carried clbit collector) that run before runtime bindings exist — only the constant path is taken in that case; symbolic indices and symbolic slice bounds fall through to the scalar UUID.

Returns:

QubitAddress — Key suitable for looking up the condition in clbit_map.

See resolve_condition_address_detailed for the resolution contract.


resolve_condition_address_detailed [source]

def resolve_condition_address_detailed(
    condition: Value,
    bindings: dict[str, Any],
    resolver: ValueResolver | None = None,
) -> tuple[QubitAddress, bool]

Resolve a condition / source Value to its clbit_map key.

Single source of truth (shared by control_flow_emission.emit_if / emit_while, the Qiskit / CUDA-Q engines, ResourceAllocator’s loop-carried / merge aliasing, and the merge-output mapping helpers here) for turning a runtime control-flow condition — or a merge source Value — into the address its classical bit is registered under.

Scalar measurement results register under QubitAddress(bit.uuid), while a Vector[Bit] element s[i] (s = qmc.measure(register)) registers under QubitAddress(root_array.uuid, root_index). The element index and every slice_start / slice_step along the parent’s slice_of chain are resolved the same way — taken directly when constant, otherwise folded through bindings via resolver — and composed into the root index via root_index = start + step * view_local_index repeated along the chain.

Parameters:

NameTypeDescription
conditionValueThe condition operand or merge source Value.
bindingsdict[str, Any]Active emit-time bindings used to fold symbolic indices / slice bounds. May be empty for callers that only have constant addresses to resolve (e.g. the allocator’s pre-emit pass).
resolverValueResolver | NoneResolver exposing resolve_int_value; None restricts resolution to constants. Defaults to None.

Returns:

tuple[QubitAddress, bool] — tuple[QubitAddress, bool]: (address, resolved_as_element). resolved_as_element is True only when condition is a Vector[Bit] element whose index (and any slice bounds) resolved to concrete ints, giving the root-space QubitAddress(root.uuid, root_index). It is False for a plain scalar, or when an element’s index / slice bound could not be resolved (the scalar UUID fallback). Callers that mutate clbit_map should trust the address as a vector key only when this flag is True, to avoid aliasing an unresolved element onto an unrelated scalar slot.


resolve_dict_entries [source]

def resolve_dict_entries(
    emit_pass: 'StandardEmitPass',
    dict_value: Any,
    bindings: dict[str, Any],
) -> list[tuple[Any, Any]] | None

Resolve DictValue to concrete (key, value) pairs.

Parameters:

NameTypeDescription
emit_pass'StandardEmitPass'The StandardEmitPass instance (for resolver access)
dict_valueAnyThe DictValue IR node being iterated
bindingsdict[str, Any]Current parameter bindings

Returns:

list[tuple[Any, Any]] | None — List of (key, value) tuples, or None if cannot be resolved


resolve_if_condition [source]

def resolve_if_condition(condition: Any, bindings: dict[str, Any]) -> bool | None

Resolve an if-condition to a compile-time boolean.


resolve_loop_bounds [source]

def resolve_loop_bounds(
    resolver: Any,
    op: ForOperation,
    bindings: dict[str, Any],
) -> tuple[int | None, int | None, int | None]

Resolve for-loop bounds (start, stop, step) from operands.

Missing operands use defaults: start=0, stop=1, step=1. Returns None for bounds that cannot be resolved to concrete ints.


restore_runtime_condition_sources [source]

def restore_runtime_condition_sources(emit_pass: 'StandardEmitPass', sources: frozenset[tuple[str, int]]) -> None

Restore one runtime-control-flow path’s overwrite state.

Parameters:

NameTypeDescription
emit_passStandardEmitPassEmit pass whose state is restored.
sourcesfrozenset[tuple[str, int]]Snapshot to install.

runtime_condition_source_key [source]

def runtime_condition_source_key(
    condition: Value,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
    resolver: ValueResolver,
) -> tuple[str, int] | None

Identify one immutable measurement snapshot and physical clbit.

Parameters:

NameTypeDescription
conditionValueRuntime condition Value to identify.
clbit_mapClbitMapCurrent per-iteration clbit aliases.
bindingsdict[str, Any]Active emit-time bindings.
resolverValueResolverResolver for symbolic element indices.

Returns:

tuple[str, int] | None — tuple[str, int] | None: Structural source identity and physical clbit, or None when the source cannot yet be resolved.


snapshot_runtime_condition_sources [source]

def snapshot_runtime_condition_sources(emit_pass: 'StandardEmitPass') -> frozenset[tuple[str, int]]

Snapshot path-local measurement sources overwritten by while loops.

Parameters:

NameTypeDescription
emit_passStandardEmitPassEmit pass carrying the current path state.

Returns:

frozenset[tuple[str, int]] — frozenset[tuple[str, int]]: Immutable snapshot of the current path.


validate_region_args [source]

def validate_region_args(op: ForOperation | ForItemsOperation | WhileOperation) -> tuple[RegionArg, ...]

Validate the SSA identities owned by a loop’s region arguments.

A loop owns several definition namespaces: its iteration variables, every RegionArg.block_arg, and every RegionArg.result. Those identities must be pairwise disjoint. Otherwise different stages can assign incompatible meanings to one UUID: a UUID-keyed environment has only one slot, so binding either the iteration variable or the carried value overwrites the other and makes both reads observe the same value.

Parameters:

NameTypeDescription
opForOperation | ForItemsOperation | WhileOperationLoop operation whose region arguments should be validated.

Returns:

tuple[RegionArg, ...] — tuple[RegionArg, ...]: The validated op.region_args tuple.

Raises:


validated_loop_indexset [source]

def validated_loop_indexset(start: int, stop: int, step: int) -> range

Build an engine-safe Python range for resolved loop bounds.

Parameters:

NameTypeDescription
startintInclusive loop start.
stopintExclusive loop stop.
stepintNonzero loop step.

Returns:

range — The resolved loop index set when its cardinality fits Python’s platform-sized sequence protocol.

Raises:

Classes

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:

bool — True iff slice_of is non-None.

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

BitType [source]

class BitType(ClassicalTypeMixin, ValueType)

Type representing a classical bit.


DictGetItemOperation [source]

class DictGetItemOperation(Operation)

Look up one entry of a Dict by a (possibly symbolic) key.

This is the IR form of d[key] on a Dict handle. The key components may be symbolic (e.g. loop variables of a for-items loop); the lookup is resolved at emit time when the key values and the dict’s bound data are both concrete.

operands: [DictValue, *key_component_values] results: [looked-up scalar value]

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_arity: int = 1,
) -> None
Attributes

EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return
Constructor
def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

ForItemsOperation [source]

class ForItemsOperation(HasNestedOps, Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    key_var_values: tuple[Value, ...] | None = None,
    value_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include the per-key/value Value fields for cloning/substitution.

Same rationale as ForOperation.all_input_values: keep the IR identity fields in lockstep with body references so UUID-keyed lookups stay valid after inline cloning. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the items-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing key/value formals, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the items-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt items-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


MeasureVectorOperation [source]

class MeasureVectorOperation(Operation)

Measure a vector of qubits.

Takes a Vector[Qubit] (ArrayValue) and produces a Vector[Bit] (ArrayValue). This operation measures all qubits in the vector as a single operation.

operands: [ArrayValue of qubits] results: [ArrayValue of bits]

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ParameterContainerKind [source]

class ParameterContainerKind(enum.StrEnum)

Classify the public container that owns one engine scalar slot.

Attributes

QInitOperation [source]

class QInitOperation(Operation)

Initialize the qubit

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

QubitAddress [source]

class QubitAddress

Typed key for qubit/clbit physical-index maps.

For scalar qubits: QubitAddress(uuid="abc123") For array elements: QubitAddress(uuid="abc123", element_index=2)

This replaces the f"{uuid}_{i}" string key pattern throughout the emit pipeline, making the key format explicit and preventing format-string bugs.

Constructor
def __init__(self, uuid: str, element_index: int | None = None) -> None
Attributes
Methods
from_composite_key
@classmethod
def from_composite_key(cls, key: str) -> QubitAddress

Parse a legacy composite key string into a QubitAddress.

The frontend stores qubit references as composite strings in the format "{array_uuid}_{element_index}" (e.g., cast operation qubit mappings, element UUIDs). This helper converts such strings to proper QubitAddress instances.

If the key does not match the composite format (i.e., the suffix after the last _ is not a non-negative integer), it is treated as a plain scalar UUID.

matches_array
def matches_array(self, array_uuid: str) -> bool

True if this address belongs to the given array.

with_element
def with_element(self, index: int) -> QubitAddress

Create an array-element address from this array’s base UUID.


RegionArg [source]

class RegionArg

Explicit loop-carried value on a loop operation (MLIR-style iter_arg).

A RegionArg makes a loop-carried dependency explicit in the IR, the way MLIR’s scf.for models iter_args / scf.yield:

The loop body’s operations reference block_arg (the frontend substitutes the traced pre-loop reads), and post-loop operations reference result (the frontend rebinds the Python handle when it closes the loop). result is also appended to the loop operation’s results list so dependency analysis sees the loop as its producer.

This subsumes the trace-once staleness that LoopCarriedRebind records exist to reject: a rebind represented as a RegionArg is a supported loop-carried value, not a miscompilation hazard.

Constructor
def __init__(
    self,
    var_name: str,
    init: Value,
    block_arg: Value,
    yielded: Value,
    result: Value,
) -> None
Attributes

StandardEmitPass [source]

class StandardEmitPass(EmitPass[T], Generic[T])

Standard emit pass implementation using GateEmitter protocol.

This class provides orchestration for semantic IR traversal while delegating circuit instruction construction to a GateEmitter. The concrete compiler use is CircuitLoweringPass; SDK targets materialize its immutable result instead of subclassing this class.

Parameters:

NameTypeDescription
gate_emitterGateEmitter[T]Instruction builder used during the semantic traversal.
bindingsdict[str, Any] | NoneCompile-time parameter bindings.
parameterslist[str] | NoneParameter names preserved at runtime.
composite_emitterslist[CompositeGateEmitter[T]] | NoneOptional callable-preservation or lowering hooks.
engine_namestr | NoneDiagnostic name for the traversal target.
Constructor
def __init__(
    self,
    gate_emitter: GateEmitter[T],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
    composite_emitters: list[CompositeGateEmitter[T]] | None = None,
    engine_name: str | None = None,
)
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 engine resource allocation. This applies to every Value regardless of its type (Qubit, Float, Bit, ...) -- it is not specific to qubits.


ValueResolver [source]

class ValueResolver

Resolves Value objects to concrete indices or values.

Constructor
def __init__(self, parameters: set[str] | None = None)

Create an emit-time resolver.

Parameters:

NameTypeDescription
parametersset[str] | NoneNames preserved as engine runtime parameters. Defaults to None.
Attributes
Methods
bind_block_params
def bind_block_params(
    self,
    block_value: Any,
    param_operands: list['Value'],
    bindings: dict[str, Any],
    *,
    parameter_factory: Callable[[str, str], Any] | None = None,
) -> dict[str, Any]

Create local bindings by matching block inputs to call-site operands.

Parameters:

NameTypeDescription
block_valueAnyNested block whose classical/object inputs are bound. Objects without input_values receive no additional local bindings for compatibility with optional engine recipes.
param_operandslist[Value]Classical/object call-site operands in the controlled operation’s signature order.
bindingsdict[str, Any]Parent emit-time bindings used to resolve the call-site operands.
parameter_factoryCallable[[str, str], Any] | NoneOptional engine parameter factory used when an operand is a declared runtime parameter rather than a concrete binding. Defaults to None so standalone resolver use remains engine-neutral.

Returns:

dict[str, Any] — dict[str, Any]: Parent bindings with each inner formal rebound under both its UUID and sanctioned parameter-name key.

get_parameter_key
def get_parameter_key(self, value: 'Value', bindings: dict[str, Any]) -> str | None

Get the engine parameter key for a symbolic scalar.

Parameters:

NameTypeDescription
valueValueScalar value or array element to identify.
bindingsdict[str, Any]Active bindings used to resolve element indices and slice offsets.

Returns:

str | None — str | None: Scalar name or root-array indexed key, or None when an array element’s root location is unresolved.

lookup_in_bindings
def lookup_in_bindings(
    self,
    value: Any,
    bindings: dict[str, Any],
    *,
    index_array: bool = False,
) -> Any

Canonical resolution chain for a Value against bindings.

All other resolver methods (resolve_bound_value, resolve_classical_value, resolve_int_value, resolve_operand_for_binding) wrap this single chain. Centralizing precedence here prevents the historical drift where one resolver checked is_parameter before UUID and another checked it after, which manifested as obscure binding failures when name-keyed writes were dropped from the emit pass.

Resolution order (each step returns immediately on a hit):

  1. value is already a concrete Python scalar (no uuid).

  2. value.uuid is in bindings — return that. This is where emit-time-computed intermediates (evaluate_binop / evaluate_classical_predicate results) and merge aliases live.

  3. A compile-time array or dict payload stored in typed metadata.

  4. value.is_constant() — return value.get_const().

  5. value.is_parameter() and its parameter name is in bindings — return that.

  6. (When index_array=True) value is an array element with a resolvable parent in bindings — index into it.

  7. A non-empty display name is present in bindings. This is a compatibility bridge for programmatically constructed Values and older transforms that do not carry parameter metadata; UUID and explicit parameter provenance always take precedence.

Compiler-created temporaries are anonymous and compiler-internal writers use UUID keys, so the compatibility bridge cannot merge two same-named temporaries. Kernel parameters should normally resolve via explicit parameter metadata, while loop variables and intermediates remain UUID-keyed.

Parameters:

NameTypeDescription
valueAnyThe IR value (or already-concrete Python scalar) to resolve.
bindingsdict[str, Any]The active bindings dictionary.
index_arrayboolWhen True, also resolve array-element accesses via parent_array indexing. Off by default because not all callers want to index into bound containers.

Returns:

Any — The resolved Python value, or None if no step matched.

resolve_bound_value
def resolve_bound_value(self, value: 'Value', bindings: dict[str, Any]) -> Any

Resolve a Value to its raw bound Python object.

Wraps :meth:lookup_in_bindings with index_array=True so that arr[i] accesses against a bound container resolve to the element. Does not coerce the result — callers that need a numeric scalar should go through :meth:resolve_classical_value.

Parameters:

NameTypeDescription
valueValueValue to resolve.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

Any — Raw bound object, or None when unresolved.

resolve_classical_value
def resolve_classical_value(self, value: 'Value', bindings: dict[str, Any]) -> Any

Resolve a classical Value to a concrete Python value.

Numeric bindings are normalized to native Python scalars regardless of whether they come from a direct binding or from array-element indexing, so downstream isinstance(x, (int, float)) checks are stable when callers bind np.pi/4 or the like. bool is preserved (not coerced to int). Non-numeric values (Hamiltonians, strings, dict values, …) pass through unchanged.

Parameters:

NameTypeDescription
valueValueClassical value to resolve.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

Any — Resolved native scalar/object, or None when unresolved.

resolve_int_value
def resolve_int_value(self, val: Any, bindings: dict[str, Any]) -> int | None

Resolve a value to an integer, or None when unresolvable.

Unresolvable symbolic Values must return None. The previous return 0 fallback caused silent loop elision when parameter shape dims (gamma_dim0) reached this resolver without being folded into constants — downstream loop-bound resolution saw 0 and quietly emitted an empty loop. Returning None propagates the failure to emit_for_unrolled, which converts it into a hard compile error.

resolve_operand_for_binding
def resolve_operand_for_binding(self, operand: Any, bindings: dict[str, Any]) -> Any

Resolve an operand to a concrete value for block parameter binding.

Used when calling a sub-block (e.g. a controlled-U body): each param operand at the call site must resolve to a value to seed the callee’s parameter bindings.

Parameters:

NameTypeDescription
operandAnyCall-site value or already-concrete operand.
bindingsdict[str, Any]Parent emit-time bindings.

Returns:

Any — Resolved value, or None when the operand is symbolic.

resolve_qubit_index
def resolve_qubit_index(self, v: 'Value', qubit_map: QubitMap, bindings: dict[str, Any]) -> int | None

Resolve a qubit value to its physical index.

Parameters:

NameTypeDescription
vValueScalar or indexed qubit value.
qubit_mapQubitMapPhysical resource mapping.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

int | None — int | None: Physical index, or None when unresolved.

resolve_qubit_index_detailed
def resolve_qubit_index_detailed(
    self,
    v: 'Value',
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> QubitResolutionResult

Resolve a Value to a physical qubit index with detailed failure info.

Parameters:

NameTypeDescription
vValueThe qubit Value to resolve. May be a scalar qubit or an array element (possibly through a sliced view chain).
qubit_mapQubitMapMapping from QubitAddress to physical qubit indices built by the resource allocator.
bindingsdict[str, Any]Active emit-time bindings used to resolve symbolic element indices and slice bounds.

Returns:

QubitResolutionResult — Success with the physical index, or a failure carrying a ResolutionFailureReason — including NEGATIVE_INDEX when a resolved element index is negative or a resolved slice bound violates the frontend contract (non-negative start, positive step); composing those through the affine map would silently address a wrong root slot.

resolve_slice_chain
def resolve_slice_chain(
    self,
    av: 'ArrayValue',
    bindings: dict[str, Any],
    *,
    operation: str = 'emit',
) -> tuple['ArrayValue', int, int]

Walk an ArrayValue’s slice_of chain and return root + affine map.

Composes the nested affine maps so that a view-local index i corresponds to the root-space index start + step * i. For a root ArrayValue (no slice_of chain), returns (av, 0, 1) so callers can always apply the same formula uniformly.

Parameters:

NameTypeDescription
av'ArrayValue'The possibly-sliced ArrayValue whose root and affine mapping should be resolved.
bindingsdict[str, Any]Compile-time parameter bindings; required when any slice_start / slice_step in the chain is symbolic.
operationstrHuman-readable name of the enclosing emit operation. Used only in the EmitError message when a symbolic slice bound cannot be resolved. Defaults to "emit".

Returns:

'ArrayValue' — Tuple (root_array, start, step) where root_array is int — the underlying non-sliced ArrayValue, and start/step int — are Python int values satisfying tuple['ArrayValue', int, int] — view[i] == root_array[start + step * i].

Raises:

Example:

>>> # For ``view = q[1::2]`` where ``q`` has 4 qubits:
>>> resolver.resolve_slice_chain(view_av, bindings={})
(q_av, 1, 2)

WhileOperation [source]

class WhileOperation(HasNestedOps, Operation)

Represents a while loop operation.

Only measurement-backed conditions are supported: the condition must be a Bit value produced by qmc.measure(). Non-measurement conditions (classical variables, constants, comparisons) are rejected by ValidateWhileContractPass before reaching engine emit.

Example::

bit = qmc.measure(q)
while bit:
    q = qmc.h(q)
    bit = qmc.measure(q)
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    operations: list[Operation] = list(),
    max_iterations: int | None = None,
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include rebind records and region args for cloning/substitution.

Same rationale as ForOperation.all_input_values: rebind records and region arguments reference body/pre-loop values by identity, so inline cloning must remap them in lockstep with body operands.

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus rebind-record and region-argument values.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the while body with explicit boundary values.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region whose block arguments and yields are aligned with region_args. The updated condition, when present, is appended as the final yield.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the while body and its complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt while operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, rebind-record, and region-arg values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


qamomile.circuit.transpiler.passes.emit_support.control_value_emission

Shared emission support for computational-basis control values.

Overview

FunctionDescription
bracket_control_valueBracket zero-valued controls with target-neutral Pauli-X gates.
control_pattern_for_valueReturn the LSB-first activation pattern for a control value.
ClassDescription
StandardEmitPassStandard emit pass implementation using GateEmitter protocol.

Functions

bracket_control_value [source]

def bracket_control_value(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    control_indices: Sequence[int],
    control_value: int | None,
) -> Generator[None, None, None]

Bracket zero-valued controls with target-neutral Pauli-X gates.

The controlled operation inside the context remains an ordinary all-ones control. Controls are interpreted LSB-first in their existing physical order, so bit zero of control_value describes control_indices[0]. One bracket surrounds the complete operation, including integral powers and vector-target broadcast.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass providing the gate emitter.
circuitAnyCircuit receiving the bracket gates.
control_indicesSequence[int]Ordered physical control qubits.
control_valueint | NoneRequired basis value, or None for the ordinary all-ones state.

Yields:

None — Control returns while the zero-valued controls are inverted.

Raises:


control_pattern_for_value [source]

def control_pattern_for_value(control_value: int | None, num_controls: int) -> tuple[int, ...]

Return the LSB-first activation pattern for a control value.

Parameters:

NameTypeDescription
control_valueint | NoneRequired computational-basis value. None means the ordinary all-ones control state.
num_controlsintConcrete positive control-register width.

Returns:

tuple[int, ...] — tuple[int, ...]: One 0/1 activation bit per flattened control, with the first control represented by bit zero.

Raises:

Example:

>>> control_pattern_for_value(2, 2)
(0, 1)
>>> control_pattern_for_value(None, 2)
(1, 1)

Classes

StandardEmitPass [source]

class StandardEmitPass(EmitPass[T], Generic[T])

Standard emit pass implementation using GateEmitter protocol.

This class provides orchestration for semantic IR traversal while delegating circuit instruction construction to a GateEmitter. The concrete compiler use is CircuitLoweringPass; SDK targets materialize its immutable result instead of subclassing this class.

Parameters:

NameTypeDescription
gate_emitterGateEmitter[T]Instruction builder used during the semantic traversal.
bindingsdict[str, Any] | NoneCompile-time parameter bindings.
parameterslist[str] | NoneParameter names preserved at runtime.
composite_emitterslist[CompositeGateEmitter[T]] | NoneOptional callable-preservation or lowering hooks.
engine_namestr | NoneDiagnostic name for the traversal target.
Constructor
def __init__(
    self,
    gate_emitter: GateEmitter[T],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
    composite_emitters: list[CompositeGateEmitter[T]] | None = None,
    engine_name: str | None = None,
)
Attributes

qamomile.circuit.transpiler.passes.emit_support.controlled_block_support

Prepare reusable controlled blocks and map their quantum operands.

Overview

FunctionDescription
block_parameter_binding_keysReturn the sanctioned emit-binding keys for an inner formal.
blockvalue_to_gateConvert a Block to an engine gate.
map_array_result_groupMap an array-valued result to a physical index group.
pair_block_parameter_operandsPair a block’s classical/object inputs with call-site operands.
ClassDescription
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
ConcreteControlledUControlled-U with concrete (int) number of controls.
EmitErrorReport an engine failure to emit one semantic operation.
HasNestedOpsMixin for operations that contain nested operation lists.
QubitAddressTyped key for qubit/clbit physical-index maps.
StandardEmitPassStandard emit pass implementation using GateEmitter protocol.
ValueA typed SSA value in the IR.
ValueResolverResolves Value objects to concrete indices or values.

Functions

block_parameter_binding_keys [source]

def block_parameter_binding_keys(parameter: ValueBase) -> tuple[str, ...]

Return the sanctioned emit-binding keys for an inner formal.

Emit resolution accepts a kernel parameter name before its UUID for public API compatibility, so an operation-owned fresh scope must write both keys. Keeping the key choice here prevents individual emit paths from reviving a parent binding that merely shares the inner formal’s display name.

Parameters:

NameTypeDescription
parameterValueBaseClassical/object formal input being bound.

Returns:

tuple[str, ...] — tuple[str, ...]: UUID followed by the formal parameter provenance name and nonempty display-name compatibility key, without duplicates.


blockvalue_to_gate [source]

def blockvalue_to_gate(
    emit_pass: 'StandardEmitPass',
    block_value: Any,
    num_qubits: int,
    bindings: dict[str, Any],
    input_operands: list[Any] | None = None,
    operation_name: str = 'ControlledUOperation',
) -> Any

Convert a Block to an engine gate.

Pre-populates local_qubit_map with one entry per quantum input in declaration order, then runs the allocator over the block’s body. For Vector[Qubit] inputs (ArrayValue with a quantum element type) the entry expands into per-element QubitAddress(uuid, i) keys — the inner block has no QInitOperation for inputs, so without these the allocator’s element-resolution assertion fires for every qs[i] reference in the body.

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe emit pass driving the conversion. Used for its _allocator, _emitter, _resolver, and _emit_operations.
block_valueAnyThe inner block to convert. Expected to expose operations and input_values; anything else returns None (the caller falls back to gate-by-gate decomposition).
num_qubitsintTotal physical qubits the resulting gate will occupy in the parent circuit. Used as the fallback length for a single Vector[Qubit] input whose shape is symbolic and unresolvable from bindings, and as the sub-circuit width when the block has no qubit-producing operations.
bindingsdict[str, Any]Parameter bindings forwarded to the allocator and _emit_operations. Also consulted when resolving Vector[Qubit] input shapes.
input_operandslist[Any] | NoneOptional call-site operands corresponding to block_value.input_values. Quantum operands propagate actual Vector[Qubit] shapes into the nested block before the vector-aware input qubit map is populated; classical operands are resolved into local bindings before the nested block is emitted. Defaults to None.
operation_namestrOperation name used in diagnostics when input binding fails. Defaults to "ControlledUOperation".

Returns:

Any — An engine gate object produced by emit_pass._emitter.circuit_to_gate, or None when the conversion is unable to proceed (missing operations, allocator / emitter exception, etc.) so the caller can fall back to gate-by-gate emission.


map_array_result_group [source]

def map_array_result_group(result_uuid: str, index_group: list[int], index_map: PhysicalIndexMap) -> None

Map an array-valued result to a physical index group.

Parameters:

NameTypeDescription
result_uuidstrUUID of the array-valued result whose element addresses should be registered.
index_grouplist[int]Physical indices for the result elements, in result-local element order.
index_mapPhysicalIndexMapMutable physical-index map updated in place with element addresses and, when available, the base result address.

pair_block_parameter_operands [source]

def pair_block_parameter_operands(
    block: Block,
    param_operands: Sequence[ValueBase],
) -> list[tuple[ValueBase, ValueBase]]

Pair a block’s classical/object inputs with call-site operands.

Both compile-time lowering and emission bind an operation-owned block’s non-quantum inputs by their declaration order. Keeping the filtering and pairing here ensures those stages cannot adopt different positional conventions.

Parameters:

NameTypeDescription
blockBlockOperation-owned block whose formal inputs define the declaration order.
param_operandsSequence[ValueBase]Classical or object operands at the call site, already ordered according to the operation signature.

Returns:

list[tuple[ValueBase, ValueBase]] — list[tuple[ValueBase, ValueBase]]: (formal, actual) pairs in list[tuple[ValueBase, ValueBase]] — declaration order. Missing actual operands leave trailing formals list[tuple[ValueBase, ValueBase]] — unpaired, so they can remain symbolic and be provided at emit time.

Classes

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.


BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

ConcreteControlledU [source]

class ConcreteControlledU(ControlledUOperation)

Controlled-U with concrete (int) number of controls.

Operand layout: [ctrl_0, ..., ctrl_n, tgt_0, ..., tgt_m, params...] Result layout: [ctrl_0', ..., ctrl_n', tgt_0', ..., tgt_m']

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_value: int | None = None,
) -> None
Attributes

EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return
Constructor
def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


QubitAddress [source]

class QubitAddress

Typed key for qubit/clbit physical-index maps.

For scalar qubits: QubitAddress(uuid="abc123") For array elements: QubitAddress(uuid="abc123", element_index=2)

This replaces the f"{uuid}_{i}" string key pattern throughout the emit pipeline, making the key format explicit and preventing format-string bugs.

Constructor
def __init__(self, uuid: str, element_index: int | None = None) -> None
Attributes
Methods
from_composite_key
@classmethod
def from_composite_key(cls, key: str) -> QubitAddress

Parse a legacy composite key string into a QubitAddress.

The frontend stores qubit references as composite strings in the format "{array_uuid}_{element_index}" (e.g., cast operation qubit mappings, element UUIDs). This helper converts such strings to proper QubitAddress instances.

If the key does not match the composite format (i.e., the suffix after the last _ is not a non-negative integer), it is treated as a plain scalar UUID.

matches_array
def matches_array(self, array_uuid: str) -> bool

True if this address belongs to the given array.

with_element
def with_element(self, index: int) -> QubitAddress

Create an array-element address from this array’s base UUID.


StandardEmitPass [source]

class StandardEmitPass(EmitPass[T], Generic[T])

Standard emit pass implementation using GateEmitter protocol.

This class provides orchestration for semantic IR traversal while delegating circuit instruction construction to a GateEmitter. The concrete compiler use is CircuitLoweringPass; SDK targets materialize its immutable result instead of subclassing this class.

Parameters:

NameTypeDescription
gate_emitterGateEmitter[T]Instruction builder used during the semantic traversal.
bindingsdict[str, Any] | NoneCompile-time parameter bindings.
parameterslist[str] | NoneParameter names preserved at runtime.
composite_emitterslist[CompositeGateEmitter[T]] | NoneOptional callable-preservation or lowering hooks.
engine_namestr | NoneDiagnostic name for the traversal target.
Constructor
def __init__(
    self,
    gate_emitter: GateEmitter[T],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
    composite_emitters: list[CompositeGateEmitter[T]] | None = None,
    engine_name: str | None = None,
)
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 engine resource allocation. This applies to every Value regardless of its type (Qubit, Float, Bit, ...) -- it is not specific to qubits.


ValueResolver [source]

class ValueResolver

Resolves Value objects to concrete indices or values.

Constructor
def __init__(self, parameters: set[str] | None = None)

Create an emit-time resolver.

Parameters:

NameTypeDescription
parametersset[str] | NoneNames preserved as engine runtime parameters. Defaults to None.
Attributes
Methods
bind_block_params
def bind_block_params(
    self,
    block_value: Any,
    param_operands: list['Value'],
    bindings: dict[str, Any],
    *,
    parameter_factory: Callable[[str, str], Any] | None = None,
) -> dict[str, Any]

Create local bindings by matching block inputs to call-site operands.

Parameters:

NameTypeDescription
block_valueAnyNested block whose classical/object inputs are bound. Objects without input_values receive no additional local bindings for compatibility with optional engine recipes.
param_operandslist[Value]Classical/object call-site operands in the controlled operation’s signature order.
bindingsdict[str, Any]Parent emit-time bindings used to resolve the call-site operands.
parameter_factoryCallable[[str, str], Any] | NoneOptional engine parameter factory used when an operand is a declared runtime parameter rather than a concrete binding. Defaults to None so standalone resolver use remains engine-neutral.

Returns:

dict[str, Any] — dict[str, Any]: Parent bindings with each inner formal rebound under both its UUID and sanctioned parameter-name key.

get_parameter_key
def get_parameter_key(self, value: 'Value', bindings: dict[str, Any]) -> str | None

Get the engine parameter key for a symbolic scalar.

Parameters:

NameTypeDescription
valueValueScalar value or array element to identify.
bindingsdict[str, Any]Active bindings used to resolve element indices and slice offsets.

Returns:

str | None — str | None: Scalar name or root-array indexed key, or None when an array element’s root location is unresolved.

lookup_in_bindings
def lookup_in_bindings(
    self,
    value: Any,
    bindings: dict[str, Any],
    *,
    index_array: bool = False,
) -> Any

Canonical resolution chain for a Value against bindings.

All other resolver methods (resolve_bound_value, resolve_classical_value, resolve_int_value, resolve_operand_for_binding) wrap this single chain. Centralizing precedence here prevents the historical drift where one resolver checked is_parameter before UUID and another checked it after, which manifested as obscure binding failures when name-keyed writes were dropped from the emit pass.

Resolution order (each step returns immediately on a hit):

  1. value is already a concrete Python scalar (no uuid).

  2. value.uuid is in bindings — return that. This is where emit-time-computed intermediates (evaluate_binop / evaluate_classical_predicate results) and merge aliases live.

  3. A compile-time array or dict payload stored in typed metadata.

  4. value.is_constant() — return value.get_const().

  5. value.is_parameter() and its parameter name is in bindings — return that.

  6. (When index_array=True) value is an array element with a resolvable parent in bindings — index into it.

  7. A non-empty display name is present in bindings. This is a compatibility bridge for programmatically constructed Values and older transforms that do not carry parameter metadata; UUID and explicit parameter provenance always take precedence.

Compiler-created temporaries are anonymous and compiler-internal writers use UUID keys, so the compatibility bridge cannot merge two same-named temporaries. Kernel parameters should normally resolve via explicit parameter metadata, while loop variables and intermediates remain UUID-keyed.

Parameters:

NameTypeDescription
valueAnyThe IR value (or already-concrete Python scalar) to resolve.
bindingsdict[str, Any]The active bindings dictionary.
index_arrayboolWhen True, also resolve array-element accesses via parent_array indexing. Off by default because not all callers want to index into bound containers.

Returns:

Any — The resolved Python value, or None if no step matched.

resolve_bound_value
def resolve_bound_value(self, value: 'Value', bindings: dict[str, Any]) -> Any

Resolve a Value to its raw bound Python object.

Wraps :meth:lookup_in_bindings with index_array=True so that arr[i] accesses against a bound container resolve to the element. Does not coerce the result — callers that need a numeric scalar should go through :meth:resolve_classical_value.

Parameters:

NameTypeDescription
valueValueValue to resolve.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

Any — Raw bound object, or None when unresolved.

resolve_classical_value
def resolve_classical_value(self, value: 'Value', bindings: dict[str, Any]) -> Any

Resolve a classical Value to a concrete Python value.

Numeric bindings are normalized to native Python scalars regardless of whether they come from a direct binding or from array-element indexing, so downstream isinstance(x, (int, float)) checks are stable when callers bind np.pi/4 or the like. bool is preserved (not coerced to int). Non-numeric values (Hamiltonians, strings, dict values, …) pass through unchanged.

Parameters:

NameTypeDescription
valueValueClassical value to resolve.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

Any — Resolved native scalar/object, or None when unresolved.

resolve_int_value
def resolve_int_value(self, val: Any, bindings: dict[str, Any]) -> int | None

Resolve a value to an integer, or None when unresolvable.

Unresolvable symbolic Values must return None. The previous return 0 fallback caused silent loop elision when parameter shape dims (gamma_dim0) reached this resolver without being folded into constants — downstream loop-bound resolution saw 0 and quietly emitted an empty loop. Returning None propagates the failure to emit_for_unrolled, which converts it into a hard compile error.

resolve_operand_for_binding
def resolve_operand_for_binding(self, operand: Any, bindings: dict[str, Any]) -> Any

Resolve an operand to a concrete value for block parameter binding.

Used when calling a sub-block (e.g. a controlled-U body): each param operand at the call site must resolve to a value to seed the callee’s parameter bindings.

Parameters:

NameTypeDescription
operandAnyCall-site value or already-concrete operand.
bindingsdict[str, Any]Parent emit-time bindings.

Returns:

Any — Resolved value, or None when the operand is symbolic.

resolve_qubit_index
def resolve_qubit_index(self, v: 'Value', qubit_map: QubitMap, bindings: dict[str, Any]) -> int | None

Resolve a qubit value to its physical index.

Parameters:

NameTypeDescription
vValueScalar or indexed qubit value.
qubit_mapQubitMapPhysical resource mapping.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

int | None — int | None: Physical index, or None when unresolved.

resolve_qubit_index_detailed
def resolve_qubit_index_detailed(
    self,
    v: 'Value',
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> QubitResolutionResult

Resolve a Value to a physical qubit index with detailed failure info.

Parameters:

NameTypeDescription
vValueThe qubit Value to resolve. May be a scalar qubit or an array element (possibly through a sliced view chain).
qubit_mapQubitMapMapping from QubitAddress to physical qubit indices built by the resource allocator.
bindingsdict[str, Any]Active emit-time bindings used to resolve symbolic element indices and slice bounds.

Returns:

QubitResolutionResult — Success with the physical index, or a failure carrying a ResolutionFailureReason — including NEGATIVE_INDEX when a resolved element index is negative or a resolved slice bound violates the frontend contract (non-negative start, positive step); composing those through the affine map would silently address a wrong root slot.

resolve_slice_chain
def resolve_slice_chain(
    self,
    av: 'ArrayValue',
    bindings: dict[str, Any],
    *,
    operation: str = 'emit',
) -> tuple['ArrayValue', int, int]

Walk an ArrayValue’s slice_of chain and return root + affine map.

Composes the nested affine maps so that a view-local index i corresponds to the root-space index start + step * i. For a root ArrayValue (no slice_of chain), returns (av, 0, 1) so callers can always apply the same formula uniformly.

Parameters:

NameTypeDescription
av'ArrayValue'The possibly-sliced ArrayValue whose root and affine mapping should be resolved.
bindingsdict[str, Any]Compile-time parameter bindings; required when any slice_start / slice_step in the chain is symbolic.
operationstrHuman-readable name of the enclosing emit operation. Used only in the EmitError message when a symbolic slice bound cannot be resolved. Defaults to "emit".

Returns:

'ArrayValue' — Tuple (root_array, start, step) where root_array is int — the underlying non-sliced ArrayValue, and start/step int — are Python int values satisfying tuple['ArrayValue', int, int] — view[i] == root_array[start + step * i].

Raises:

Example:

>>> # For ``view = q[1::2]`` where ``q`` has 4 qubits:
>>> resolver.resolve_slice_chain(view_av, bindings={})
(q_av, 1, 2)

qamomile.circuit.transpiler.passes.emit_support.controlled_emission

Controlled operation emission helpers extracted from StandardEmitPass.

This module provides module-level functions for emitting controlled-U operations, controlled gates, and related helpers. Each function takes an emit_pass parameter (a StandardEmitPass instance) in place of self.

Primitive multi-control decomposition lives in multi_control_gate_emission. Reusable block preparation and operand mapping live in controlled_block_support; their names are re-exported here for compatibility with existing internal extension points.

Note: emit_controlled_fallback and blockvalue_to_gate are called via emit_pass._emit_controlled_fallback(...) and emit_pass._blockvalue_to_gate(...) respectively, so that subclass overrides (e.g. CudaqEmitPass) are respected.

Overview

FunctionDescription
allocate_controlled_workspacesReserve parent-circuit wires for fresh allocations in controlled bodies.
blockvalue_to_gateConvert a Block to an engine gate.
bracket_control_valueBracket zero-valued controls with target-neutral Pauli-X gates.
build_controlled_block_qubit_mapBuild a block-local qubit map backed by physical target indices.
clean_ancilla_toffoli_ladderReturn the arithmetic for the named clean-ancilla recipe.
coerce_nonnegative_integralNormalize a real scalar with an integer value to a nonnegative integer.
combine_control_batch_profilesCombine sequential emission profiles up to the decision threshold.
control_pattern_for_valueReturn the LSB-first activation pattern for a control value.
emit_controlled_blockEmit a controlled version of a block via the mapped walker.
emit_controlled_composite_at_indicesEmit a composite gate under already-resolved outer controls.
emit_controlled_fallbackFallback emission for controlled-U when gate conversion fails.
emit_controlled_gateEmit a controlled version of a gate.
emit_controlled_global_phase_operationEmit a global phase as a relative phase under accumulated controls.
emit_controlled_operationsEmit controlled versions of operations with operand mapping.
emit_controlled_pauli_evolveEmit exp(-i * gamma * H) under accumulated controls.
emit_controlled_powersEmit controlled-U^(2^k) operations.
emit_controlled_uEmit a controlled operation for every concrete operand layout.
emit_controlled_u_multi_argEmit a SymbolicControlledU whose control prefix is multi-arg.
emit_controlled_u_with_symbolic_indicesEmit a SymbolicControlledU whose control_indices is set.
emit_custom_compositeEmit a custom composite gate with implementation.
emit_multi_controlled_gateEmit one gate under an arbitrary number of accumulated controls.
emit_multi_controlled_on_clean_ancillasLower an irreducible multi-controlled gate via a Toffoli cascade.
emit_single_controlled_primitiveEmit one singly-controlled single-qubit gate from a resolved angle.
emit_static_controlled_ifEmit the selected branch of a static if under accumulated controls.
evaluate_binopEvaluate a BinOp and store the result in bindings.
evaluate_classical_predicateEvaluate a CompOp/CondOp/NotOp at emit time and bind its boolean result.
evaluate_dict_getitemEvaluate a DictGetItemOperation and store the result in bindings.
evaluate_unary_mathEvaluate concrete unary math used inside a controlled body.
handle_castHandle CastOperation - update qubit_map without emitting gates.
is_identity_phase_angleReturn whether a concrete angle is exactly zero modulo two pi.
map_array_result_groupMap an array-valued result to a physical index group.
map_nested_controlled_u_resultsMap a nested controlled-U’s result values to physical qubits.
quantum_operand_widthsDecode exact quantum-operand widths from callable resource metadata.
register_classical_merge_aliasesBind classical merge outputs to a concrete value when resolvable.
reject_duplicate_physical_indicesReject a multi-qubit gate whose qubits resolve to the same physical qubit.
remap_static_merge_outputsRemap merge outputs for a compile-time constant IfOperation.
replay_controlled_forReplay one static range loop under accumulated quantum controls.
resolve_angle_valueResolve a bare angle Value to a concrete float or engine parameter.
resolve_controlled_u_callResolve a (possibly nested) controlled-U call site to physical qubits.
resolve_if_conditionResolve an if-condition to a compile-time boolean.
resolve_loop_boundsResolve for-loop bounds (start, stop, step) from operands.
resolve_powerResolve ControlledUOperation.power to a concrete integer.
should_batch_controlled_bodyReturn whether engine fallback should share one AND carrier.
static_controlled_batch_profileReturn context-free emission batching information for one operation.
try_emit_batched_controlled_operationsEmit a controlled block body behind a single shared AND ladder.
ClassDescription
ArrayValueAn array of typed IR values.
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
BlockUnified block representation for all pipeline stages.
CInitOperationInitialize the classical values (const, arguments etc)
CallTransformDescribe the requested transform of a callable implementation.
CallableBodySelectionDescribe one validated IR body selected for an invocation.
CastOperationType cast operation for creating aliases over the same quantum resources.
CompOpComparison operation (EQ, NEQ, LT, LE, GT, GE).
ConcreteControlledUControlled-U with concrete (int) number of controls.
CondOpConditional logical operation (AND, OR).
ControlBatchProfileDescribe resolved work and the engine’s exact-two-control choice.
ControlledUOperationBase class for controlled-U operations.
CountingEmitterA no-op gate emitter that lets a real emission walk run for counting.
DictGetItemOperationLook up one entry of a Dict by a (possibly symbolic) key.
EmitErrorReport an engine failure to emit one semantic operation.
ForOperationRepresents a for loop operation.
GateOperationQuantum gate operation.
GateOperationType
GlobalPhaseOperationMultiply the complete quantum state by exp(i * phase).
HasNestedOpsMixin for operations that contain nested operation lists.
IfOperationRepresents an if-else conditional operation.
InverseBlockOperationRepresent an inverse qkernel/block as a first-class IR operation.
InvokeOperationRepresent a composite, stdlib, or oracle call.
NotOp
PauliEvolveOpPauli evolution operation: exp(-i * gamma * H).
QInitOperationInitialize the qubit
QubitAddressTyped key for qubit/clbit physical-index maps.
ReleaseSliceViewOperationMark a slice view’s borrow as explicitly returned to its parent.
ResolvedControlledUPhysical resolution of one ControlledUOperation call site.
ReturnOperationExplicit return operation marking the end of a block with return values.
ReturnQuantumArrayElementOperationValidate a branch-selected quantum element’s array return at emit time.
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
SliceArrayOperationConstruct a strided view of an ArrayValue.
StandardEmitPassStandard emit pass implementation using GateEmitter protocol.
StoreArrayElementOperationStore a classical scalar into one element of a classical array.
SymbolicControlledUControlled-U with symbolic (Value) number of controls.
UnaryMathOpRepresent one pure unary mathematical expression.
ValueA typed SSA value in the IR.

Functions

allocate_controlled_workspaces [source]

def allocate_controlled_workspaces(
    emit_pass: 'StandardEmitPass',
    operations: list[Operation],
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
    *,
    _under_control: bool = False,
    _active_invoke_bodies: set[int] | None = None,
) -> None

Reserve parent-circuit wires for fresh allocations in controlled bodies.

A reusable engine gate can only act on wires supplied by its call site. When a controlled qkernel allocates private workspace, its body must therefore be decomposed on the parent circuit and the workspace wires must be included before that circuit’s width is fixed. This pre-emission walk allocates those nested QInitOperation resources and publishes their addresses in qubit_map for the controlled walker.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass and resource allocator.
operationslist[Operation]Segment operations to inspect recursively.
qubit_mapQubitMapParent logical-to-physical map, mutated in place.
clbit_mapClbitMapParent classical map used to seed nested allocation.
bindingsdict[str, Any]Compile-time bindings visible in the segment.
_under_controlboolWhether operations are already reached by a controlled-body walker. Defaults to False.
_active_invoke_bodiesset[int] | NoneDefinition-body identities on the active recursive path. Defaults to a fresh set.

Raises:


blockvalue_to_gate [source]

def blockvalue_to_gate(
    emit_pass: 'StandardEmitPass',
    block_value: Any,
    num_qubits: int,
    bindings: dict[str, Any],
    input_operands: list[Any] | None = None,
    operation_name: str = 'ControlledUOperation',
) -> Any

Convert a Block to an engine gate.

Pre-populates local_qubit_map with one entry per quantum input in declaration order, then runs the allocator over the block’s body. For Vector[Qubit] inputs (ArrayValue with a quantum element type) the entry expands into per-element QubitAddress(uuid, i) keys — the inner block has no QInitOperation for inputs, so without these the allocator’s element-resolution assertion fires for every qs[i] reference in the body.

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe emit pass driving the conversion. Used for its _allocator, _emitter, _resolver, and _emit_operations.
block_valueAnyThe inner block to convert. Expected to expose operations and input_values; anything else returns None (the caller falls back to gate-by-gate decomposition).
num_qubitsintTotal physical qubits the resulting gate will occupy in the parent circuit. Used as the fallback length for a single Vector[Qubit] input whose shape is symbolic and unresolvable from bindings, and as the sub-circuit width when the block has no qubit-producing operations.
bindingsdict[str, Any]Parameter bindings forwarded to the allocator and _emit_operations. Also consulted when resolving Vector[Qubit] input shapes.
input_operandslist[Any] | NoneOptional call-site operands corresponding to block_value.input_values. Quantum operands propagate actual Vector[Qubit] shapes into the nested block before the vector-aware input qubit map is populated; classical operands are resolved into local bindings before the nested block is emitted. Defaults to None.
operation_namestrOperation name used in diagnostics when input binding fails. Defaults to "ControlledUOperation".

Returns:

Any — An engine gate object produced by emit_pass._emitter.circuit_to_gate, or None when the conversion is unable to proceed (missing operations, allocator / emitter exception, etc.) so the caller can fall back to gate-by-gate emission.


bracket_control_value [source]

def bracket_control_value(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    control_indices: Sequence[int],
    control_value: int | None,
) -> Generator[None, None, None]

Bracket zero-valued controls with target-neutral Pauli-X gates.

The controlled operation inside the context remains an ordinary all-ones control. Controls are interpreted LSB-first in their existing physical order, so bit zero of control_value describes control_indices[0]. One bracket surrounds the complete operation, including integral powers and vector-target broadcast.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass providing the gate emitter.
circuitAnyCircuit receiving the bracket gates.
control_indicesSequence[int]Ordered physical control qubits.
control_valueint | NoneRequired basis value, or None for the ordinary all-ones state.

Yields:

None — Control returns while the zero-valued controls are inverted.

Raises:


build_controlled_block_qubit_map [source]

def build_controlled_block_qubit_map(
    emit_pass: 'StandardEmitPass',
    block_value: Any,
    target_indices: list[int],
    bindings: dict[str, Any],
    parent_qubit_map: QubitMap | None = None,
) -> QubitMap

Build a block-local qubit map backed by physical target indices.

Seeds one entry per formal quantum input of block_value — scalar Qubit inputs map to one physical index, Vector[Qubit] inputs map per-element — positionally matching target_indices in declaration order.

Parameters:

NameTypeDescription
emit_passStandardEmitPassEmit pass used to resolve symbolic vector input shapes against bindings.
block_valueAnyInner block whose input_values define the quantum formal arguments. Objects without input_values yield an empty map.
target_indiceslist[int]Physical qubit indices supplied at the controlled call site, one per flattened quantum input qubit.
bindingsdict[str, Any]Bindings used while resolving vector input shapes.
parent_qubit_mapQubitMap | NoneParent-circuit allocation map containing any nested fresh-workspace addresses. Defaults to None.

Returns:

QubitMap — Mapping from the inner block’s formal quantum input addresses to physical parent-circuit qubit indices.

Raises:


clean_ancilla_toffoli_ladder [source]

def clean_ancilla_toffoli_ladder(num_controls: int | sp.Expr) -> CleanAncillaToffoliLadder[Any]

Return the arithmetic for the named clean-ancilla recipe.

The caller owns recipe selection and must use the result on a branch where at least two controls are active. Keeping validation outside this helper lets symbolic resource expressions construct inactive Piecewise branches without prematurely rejecting them.

Parameters:

NameTypeDescription
num_controlsint | sp.ExprConcrete or symbolic control count.

Returns:

CleanAncillaToffoliLadder[Any] — CleanAncillaToffoliLadder[Any]: Compute, total-Toffoli, and clean- ancilla requirements in the same numeric domain as the input.


coerce_nonnegative_integral [source]

def coerce_nonnegative_integral(value: object, *, label: str) -> int

Normalize a real scalar with an integer value to a nonnegative integer.

Parameters:

NameTypeDescription
valueobjectCandidate Python, NumPy, or SymPy real scalar.
labelstrUser-facing field label used in diagnostics.

Returns:

int — Equivalent nonnegative Python integer.

Raises:


combine_control_batch_profiles [source]

def combine_control_batch_profiles(profiles: Iterable[ControlBatchProfile]) -> ControlBatchProfile

Combine sequential emission profiles up to the decision threshold.

Parameters:

NameTypeDescription
profilesIterable[ControlBatchProfile]Resolved operation profiles.

Returns:

ControlBatchProfile — Capped work and the union of exact-two choices.


control_pattern_for_value [source]

def control_pattern_for_value(control_value: int | None, num_controls: int) -> tuple[int, ...]

Return the LSB-first activation pattern for a control value.

Parameters:

NameTypeDescription
control_valueint | NoneRequired computational-basis value. None means the ordinary all-ones control state.
num_controlsintConcrete positive control-register width.

Returns:

tuple[int, ...] — tuple[int, ...]: One 0/1 activation bit per flattened control, with the first control represented by bit zero.

Raises:

Example:

>>> control_pattern_for_value(2, 2)
(0, 1)
>>> control_pattern_for_value(None, 2)
(1, 1)

emit_controlled_block [source]

def emit_controlled_block(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    block_value: Any,
    control_idx: int,
    target_indices: list[int],
    bindings: dict[str, Any],
    parent_qubit_map: QubitMap | None = None,
) -> None

Emit a controlled version of a block via the mapped walker.

Builds a block-local qubit map from the block’s formal quantum inputs to target_indices and walks the block body, so inner gates land on the physical qubit their operand actually refers to rather than on target_indices[0].

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
block_valueAnyInner block whose operations are controlled. Objects without operations are silently skipped.
control_idxintPhysical control qubit index.
target_indiceslist[int]Physical target qubits covering the block’s quantum inputs in declaration order.
bindingsdict[str, Any]Local block bindings.
parent_qubit_mapQubitMap | NoneParent-circuit allocation map. Internal fresh-allocation addresses are copied from it when present. Defaults to None.

Raises:


emit_controlled_composite_at_indices [source]

def emit_controlled_composite_at_indices(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: InvokeOperation,
    control_indices: list[int],
    qubit_indices: list[int],
    bindings: dict[str, Any],
) -> None

Emit a composite gate under already-resolved outer controls.

A non-default activation value applies only to the invocation’s own leading controls. Enclosing controls remain ordinary all-ones controls; bracketing the inner controls around the complete call composes correctly even when the enclosing control is inactive.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
opInvokeOperationComposite or oracle invocation to emit.
control_indiceslist[int]Physical outer control qubits.
qubit_indiceslist[int]Physical qubits occupied by op’s own control and target operands.
bindingsdict[str, Any]Active emit bindings.

Returns:

None — None.

Raises:


emit_controlled_fallback [source]

def emit_controlled_fallback(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    block_value: Any,
    num_controls: int,
    control_indices: list[int],
    target_indices: list[int],
    power: int,
    bindings: dict[str, Any],
    batch_profile: ControlBatchProfile | None = None,
) -> None

Fallback emission for controlled-U when gate conversion fails.

Decomposes the block body gate-by-gate under the full control set. A block-local qubit map ties the block’s formal quantum inputs to target_indices, so every inner gate is emitted on the physical qubit its operand resolves to — multi-target inner blocks are supported. Nested ControlledUOperations compose their controls with the outer ones; irreducible multi-controlled single-qubit gates route through the engine’s _emit_irreducible_multi_controlled_gate hook. Subclasses may still override this method to emit controlled blocks natively (e.g. CUDA-Q’s cudaq.control helper kernels).

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being built.
block_valueAnyBlock whose operations should be controlled.
num_controlsintNumber of control qubits.
control_indiceslist[int]Physical indices of control qubits.
target_indiceslist[int]Physical indices of target qubits.
powerintNumber of controlled body repetitions.
bindingsdict[str, Any]Parameter bindings visible in the body.
batch_profileControlBatchProfile | NonePreviously resolved body profile for this exact block and binding scope. Defaults to None, which lets the controlled walker compute it.

Raises:


emit_controlled_gate [source]

def emit_controlled_gate(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: GateOperation,
    control_idx: int,
    target_indices: list[int],
    bindings: dict[str, Any],
) -> None

Emit a controlled version of a gate.

Resolves the rotation angle for rotation-like gates and dispatches single-target gate kinds through :func:emit_single_controlled_primitive; SWAP is lowered here via its Fredkin conjugation because it needs two targets.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
opGateOperationGate operation to control.
control_idxintPhysical control qubit.
target_indiceslist[int]Physical qubits for the gate’s own operands, in operand order. An empty list is a no-op.
bindingsdict[str, Any]Bindings used to resolve rotation angles.

Raises:


emit_controlled_global_phase_operation [source]

def emit_controlled_global_phase_operation(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: GlobalPhaseOperation,
    control_indices: list[int],
    bindings: dict[str, Any],
) -> None

Emit a global phase as a relative phase under accumulated controls.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyCircuit representation being emitted into.
opGlobalPhaseOperationGlobal-phase operation to control.
control_indiceslist[int]Accumulated physical control qubits.
bindingsdict[str, Any]Active emit bindings.

Raises:


emit_controlled_operations [source]

def emit_controlled_operations(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    operations: list[Operation],
    control_indices: list[int],
    qubit_map: QubitMap,
    bindings: dict[str, Any],
    batch_profile: ControlBatchProfile | None = None,
) -> None

Emit controlled versions of operations with operand mapping.

Walks operations under the accumulated control_indices, resolving every quantum operand through qubit_map so gates land on the physical qubit their operand refers to. Nested ControlledUOperations are not rejected: their own controls are resolved and composed with the outer controls, lowering e.g. an inner qmc.control(qmc.x, num_controls=k) under one outer control to a (k+1)-controlled X.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
operationslist[Operation]Block operations to walk.
control_indiceslist[int]Accumulated physical control qubits.
qubit_mapQubitMapMutable block-local qubit map seeded by :func:build_controlled_block_qubit_map; updated in place with gate / nested-op result addresses.
bindingsdict[str, Any]Bindings visible inside the block, including loop-iteration values during unrolling.
batch_profileControlBatchProfile | NonePreviously resolved body profile for this exact block and binding scope. Defaults to None, which computes the profile only if batching is possible.

Raises:


emit_controlled_pauli_evolve [source]

def emit_controlled_pauli_evolve(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: PauliEvolveOp,
    control_indices: list[int],
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> None

Emit exp(-i * gamma * H) under accumulated controls.

Lowers a controlled Pauli evolution by exploiting that each Pauli term’s evolution exp(-i * theta * P) factors as U_dagger * RZ(2 * theta) * U where U (the basis change onto the Z axis followed by the parity CX ladder) is Clifford and thus control-independent. Controlling a conjugated gate is U_dagger * C[RZ] * U with U / U_dagger applied unconditionally: when every control is 0 the central RZ becomes the identity and U_dagger * I * U = I. Only the central RZ therefore carries the controls, which keeps the multi-controlled cost to a single rotation per Hamiltonian term instead of controlling every basis-change and ladder gate.

The basis-change (H / SDG / S) and CX-ladder gates are emitted uncontrolled through emit_pass._emitter; the central RZ is routed through :func:_emit_mc_rotation, which dispatches to emit_crz for a single control and to the engine’s _emit_irreducible_multi_controlled_gate hook for two or more.

A constant (identity) Hamiltonian term c * I is the standalone phase exp(-i * gamma * c) for an uncontrolled evolution and is retained by :func:emit_pauli_evolve. Under controls it becomes an observable relative phase on the all-controls-on subspace, so it is realized here as a P(-gamma * c) on one control conditioned on the remaining controls (emit_p for a single control, a multi-controlled P for more), matching Qiskit’s native PauliEvolutionGate whose SparsePauliOp carries the constant.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass; provides the value resolver, gate emitter, and the multi-controlled rotation hook.
circuitAnyEngine circuit being emitted into.
opPauliEvolveOpThe Pauli evolution operation inside the controlled block.
control_indiceslist[int]Accumulated physical control qubits. Must be non-empty.
qubit_mapQubitMapBlock-local qubit map the operation’s quantum operands resolve against; updated in place with the evolved-register result addresses.
bindingsdict[str, Any]Bindings visible inside the block, used to resolve the Hamiltonian, gamma, and register shape.

Raises:


emit_controlled_powers [source]

def emit_controlled_powers(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    block_value: Any,
    counting_indices: list[int],
    target_indices: list[int],
    bindings: dict[str, Any],
    parent_qubit_map: QubitMap | None = None,
) -> None

Emit controlled-U^(2^k) operations.


emit_controlled_u [source]

def emit_controlled_u(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: ControlledUOperation,
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> None

Emit a controlled operation for every concrete operand layout.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
opControlledUOperationConcrete or symbolic controlled operation.
qubit_mapQubitMapLogical-to-physical map, mutated with results.
bindingsdict[str, Any]Bindings visible at the call site.

Raises:


emit_controlled_u_multi_arg [source]

def emit_controlled_u_multi_arg(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: SymbolicControlledU,
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> None

Emit a SymbolicControlledU whose control prefix is multi-arg.

The multi-arg form (num_control_args > 1) carries a heterogeneous control prefix: a mix of scalar Value (single-qubit) and ArrayValue (whole Vector / slice VectorView) operands whose qubit-count sum equals num_controls once bindings resolves the lengths. ConstantFoldingPass cannot promote this shape to ConcreteControlledU (the per-control-qubit operand layout would lose the array-grouping the resource allocator needs), so it survives intact and lands here.

The function expands every control operand into physical qubit indices via _expand_quantum_operands_to_phys, asserts the resulting count matches the resolved num_controls, expands the target side the same way, and threads the rest through the standard gate_controlled + append_gate pipeline (with the per-gate fallback for engines whose circuit_to_gate returns None).

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe emit pass driving the conversion.
circuitAnyThe engine circuit being built.
opSymbolicControlledUThe IR op with num_control_args > 1 and control_indices is None.
qubit_mapQubitMapThe active QubitAddress -> physical qubit map; mutated in place with the result-side mappings.
bindingsdict[str, Any]Caller bindings used to resolve num_controls and any symbolic-length control / target operand.

Raises:


emit_controlled_u_with_symbolic_indices [source]

def emit_controlled_u_with_symbolic_indices(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: SymbolicControlledU,
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> None

Emit a SymbolicControlledU whose control_indices is set.

Routed from :func:emit_controlled_u when the constant-folding pass has left the op as SymbolicControlledU because control_indices carries pass-through semantics that the ConcreteControlledU promotion cannot represent in its scalar control-operand layout.

The function resolves the symbolic num_controls and every control_indices entry to concrete ints, walks the control pool’s slice_of chain to look up physical qubits per element, builds control_phys from the selected pool slots, expands the sub-kernel quantum operands via _expand_quantum_operands_to_phys for the target side, and threads the rest through the standard gate_controlled + append_gate pipeline (with the per-gate fallback for engines whose circuit_to_gate returns None).

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe emit pass driving the conversion; provides _resolver, _emitter, _blockvalue_to_gate, and _emit_controlled_fallback.
circuitAnyThe engine circuit being built.
opSymbolicControlledUThe IR op with control_indices not None. Callers must guarantee this; the control_indices is None branch is handled by the constant-folding promotion to ConcreteControlledU.
qubit_mapQubitMapThe active QubitAddress -> physical qubit map; mutated in place with the result-side mappings.
bindingsdict[str, Any]Caller bindings used to resolve num_controls, control_indices Values, c_qs length, and slice bounds.

Raises:


emit_custom_composite [source]

def emit_custom_composite(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: Any,
    impl: Any,
    qubit_indices: list[int],
    bindings: dict[str, Any],
) -> None

Emit a custom composite gate with implementation.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
opAnyComposite gate operation.
implAnyFallback implementation block to emit.
qubit_indiceslist[int]Physical qubits for the operation.
bindingsdict[str, Any]Active emit bindings.

Raises:


emit_multi_controlled_gate [source]

def emit_multi_controlled_gate(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: GateOperation,
    control_indices: list[int],
    target_indices: list[int],
    bindings: dict[str, Any],
) -> None

Emit one gate under an arbitrary number of accumulated controls.

Structurally reduces multi-qubit gate types to single-target forms by absorbing their own control qubits into the control set (CX -> X, CZ -> Z, CP -> P, TOFFOLI -> X; SWAP and RZZ via their standard CX conjugations), then emits:

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass. Subclass overrides of _emit_irreducible_multi_controlled_gate are respected for the irreducible tail.
circuitAnyEngine circuit being emitted into.
opGateOperationGate operation whose operands are already resolved to target_indices.
control_indiceslist[int]Physical control qubits. Must be non-empty.
target_indiceslist[int]Physical qubits for the gate’s own operands, in operand order.
bindingsdict[str, Any]Bindings used to resolve rotation angles.

Raises:


emit_multi_controlled_on_clean_ancillas [source]

def emit_multi_controlled_on_clean_ancillas(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    gate_type: GateOperationType,
    control_indices: list[int],
    target_idx: int,
    angle: Any,
    ancilla_indices: list[int],
) -> None

Lower an irreducible multi-controlled gate via a Toffoli cascade.

Implements the standard clean-ancilla construction (arXiv:2307.07478, Appendix A.3): the logical AND of the n controls is accumulated onto n - 1 clean ancillas with a cascade of Toffoli gates, the gate is applied once under a single control (the last ancilla) through :func:emit_single_controlled_primitive, and the cascade is uncomputed in reverse order. The cost is 2 * (n - 1) Toffoli gates plus one singly-controlled gate, and every ancilla returns to |0>, so the same pool may be reused by subsequent gates.

Unlike a dense 2**(n+1) unitary-matrix lowering, this scales linearly in the control count and keeps rotation angles symbolic, so runtime-parametric multi-controlled rotations are supported.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
gate_typeGateOperationTypeSingle-qubit gate kind to apply under the controls.
control_indiceslist[int]Physical control qubits; at least two.
target_idxintPhysical target qubit.
angleAnyResolved rotation angle (concrete number or engine parameter expression) for rotation-like gates, or None for fixed gates.
ancilla_indiceslist[int]Clean (|0>) ancilla qubits; at least len(control_indices) - 1 entries.

Raises:


emit_single_controlled_primitive [source]

def emit_single_controlled_primitive(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    gate_type: GateOperationType | None,
    control_idx: int,
    target_idx: int,
    angle: Any,
) -> None

Emit one singly-controlled single-qubit gate from a resolved angle.

This is the single-control dispatch shared by :func:emit_controlled_gate (which resolves the angle from the IR operation first) and the Toffoli-cascade lowering of irreducible multi-controlled gates (which arrives with the angle already resolved). Fixed phase-family gates (S / T and daggers) are emitted as controlled phases.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
gate_typeGateOperationType | NoneSingle-qubit gate kind. None (a gate operation without a type) is rejected like any other unsupported kind.
control_idxintPhysical control qubit.
target_idxintPhysical target qubit.
angleAnyResolved rotation angle (concrete number or engine parameter expression) for P / RX / RY / RZ; ignored for fixed gates.

Raises:


emit_static_controlled_if [source]

def emit_static_controlled_if(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: IfOperation,
    control_indices: list[int],
    qubit_map: QubitMap,
    bindings: dict[str, Any],
    walker: Callable[..., None],
) -> None

Emit the selected branch of a static if under accumulated controls.

This is the common safety net for controlled-body walkers. Compile-time lowering normally removes these nodes earlier, but a loop induction value can make the condition concrete only while emit unrolls that iteration.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
opIfOperationStatic branch to resolve and emit.
control_indiceslist[int]Accumulated physical control qubits.
qubit_mapQubitMapMutable block-local qubit map.
bindingsdict[str, Any]Bindings visible in the current iteration.
walkerCallable[..., None]Engine controlled-body walker used to emit the selected branch.

Raises:


evaluate_binop [source]

def evaluate_binop(emit_pass: 'StandardEmitPass', op: BinOp, bindings: dict[str, Any]) -> None

Evaluate a BinOp and store the result in bindings.

Tries the shared fold_classical_op first for a clean concrete fold (which already encapsulates the runtime-parameter guard). Falls back to creating engine Parameter symbols and doing symbolic arithmetic when one or both operands are runtime parameters — that’s the path that lets rx(q, gamma * 2) produce a circuit with a single Parameter("gamma") * 2 expression rather than baking in a placeholder.


evaluate_classical_predicate [source]

def evaluate_classical_predicate(
    emit_pass: 'StandardEmitPass',
    op: 'CompOp | CondOp | NotOp',
    bindings: dict[str, Any],
) -> None

Evaluate a CompOp/CondOp/NotOp at emit time and bind its boolean result.

Mirrors the predicate evaluation already done by compile_time_if_lowering and classical_executor so that an IfOperation whose condition reaches emit unfolded — typically because its operands depend on a loop variable bound only at emit time by emit_for_items / emit_for_unrolled — can still be resolved via resolve_if_condition.

Delegates the actual fold (including runtime-parameter guard and strict scalar typing) to fold_classical_op so that all three callers of the same kind dispatch share one implementation. There is no symbolic-Parameter fallback for predicates: a runtime classical expression cannot be expressed as a folded scalar, so the op is left unbound and downstream emit handles it as a runtime condition.

Parameters:

NameTypeDescription
emit_pass'StandardEmitPass'The active emit pass (for resolver access).
op'CompOp | CondOp | NotOp'The predicate op to evaluate.
bindingsdict[str, Any]Current parameter/loop-variable bindings; mutated in place on successful evaluation. No-op when operands are unresolvable (e.g. measurement bits) or evaluation raises.

Returns:

None — None.


evaluate_dict_getitem [source]

def evaluate_dict_getitem(
    emit_pass: 'StandardEmitPass',
    op: DictGetItemOperation,
    bindings: dict[str, Any],
) -> None

Evaluate a DictGetItemOperation and store the result in bindings.

Resolves each key component (typically a for-items loop variable bound by UUID in bindings), looks the key up in the dict’s resolved entries, and writes the value into bindings under the result UUID so downstream ops (BinOps feeding gate angles) can consume it.

When the dict is a declared runtime parameter (transpile(..., parameters=["coeffs"])), there are no entries to look up; the resolved key instead names one engine parameter (coeffs[3] / coeffs[(0, 1)]) which is stored under the result UUID. Repeated lookups of the same key share one engine parameter via _get_or_create_parameter.

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe emit pass (for resolver access).
opDictGetItemOperationThe lookup op being evaluated.
bindingsdict[str, Any]Current emit-time bindings.

Raises:


evaluate_unary_math [source]

def evaluate_unary_math(
    emit_pass: 'StandardEmitPass',
    op: UnaryMathOp,
    bindings: dict[str, Any],
) -> None

Evaluate concrete unary math used inside a controlled body.

An unresolved runtime unary expression is left unbound. Pure unused expressions can then disappear like ordinary dead classical work, while a later loop bound, branch, or gate-angle consumer still fails at its normal resolution boundary instead of receiving a fabricated value.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass used for value resolution and runtime-parameter classification.
opUnaryMathOpUnary expression to evaluate.
bindingsdict[str, Any]Current emit-time values, updated when the expression resolves to a valid concrete scalar.

handle_cast [source]

def handle_cast(emit_pass: 'StandardEmitPass', op: CastOperation, qubit_map: QubitMap) -> None

Handle CastOperation - update qubit_map without emitting gates.


is_identity_phase_angle [source]

def is_identity_phase_angle(angle: Any) -> bool

Return whether a concrete angle is exactly zero modulo two pi.

The test intentionally uses no tolerance so a tiny but nonzero phase is never discarded. Runtime parameter expressions remain non-identity until an engine resolves them to a concrete number.

Parameters:

NameTypeDescription
angleAnyResolved numeric angle or engine parameter expression.

Returns:

bool — Whether angle is a finite real number exactly congruent to bool — zero modulo 2 * pi.


map_array_result_group [source]

def map_array_result_group(result_uuid: str, index_group: list[int], index_map: PhysicalIndexMap) -> None

Map an array-valued result to a physical index group.

Parameters:

NameTypeDescription
result_uuidstrUUID of the array-valued result whose element addresses should be registered.
index_grouplist[int]Physical indices for the result elements, in result-local element order.
index_mapPhysicalIndexMapMutable physical-index map updated in place with element addresses and, when available, the base result address.

map_nested_controlled_u_results [source]

def map_nested_controlled_u_results(
    op: ControlledUOperation,
    resolved: ResolvedControlledU,
    qubit_map: QubitMap,
) -> None

Map a nested controlled-U’s result values to physical qubits.

The result layout mirrors the operand layout for every controlled-U shape: one result per control operand slot followed by one result per sub-kernel quantum operand. Controlled gates only add a relative phase — no qubit moves — so each result keeps the physical slots of its operand. For the control_indices pool form the whole pool passes through, selected controls included.

Parameters:

NameTypeDescription
opControlledUOperationThe operation whose results need mapping.
resolvedResolvedControlledUPhysical resolution returned by :func:resolve_controlled_u_call for this operation.
qubit_mapQubitMapMutable qubit map updated in place.

quantum_operand_widths [source]

def quantum_operand_widths(attrs: Mapping[str, Any], *, source: str) -> tuple[QuantumOperandWidth, ...]

Decode exact quantum-operand widths from callable resource metadata.

Parameters:

NameTypeDescription
attrsMapping[str, Any]Callable definition or operation attrs.
sourcestrCallable name used in malformed-contract diagnostics.

Returns:

tuple[QuantumOperandWidth, ...] — tuple[QuantumOperandWidth, ...]: Validated exact-width entries, or an empty tuple when the callable declares no such contract.

Raises:


register_classical_merge_aliases [source]

def register_classical_merge_aliases(
    emit_pass: 'StandardEmitPass',
    op: IfOperation,
    bindings: dict[str, Any],
    resolved: bool | None,
) -> None

Bind classical merge outputs to a concrete value when resolvable.

The frontend creates a merge for every variable referenced in an if-branch, including read-only ones (e.g. a for-loop index j that is read but not assigned in the branch). These read-only merges are identity merges — both inputs reference the same IR Value — so the merge output is deterministically equal to that input.

For classical types (UInt / Float / Bit) the merge outputs are not captured by map_merge_outputs / remap_static_merge_outputs (which only handle qubit / clbit phys-resource mapping). Without this binding, downstream uses like data[j_merge_4] cannot resolve the index and emit fails with symbolic_index_not_bound.

The alias is written to bindings by both UUID and (when present) name, mirroring the pattern used by emit_for_unrolled for the original loop variable.

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe active emit pass (for resolver access).
opIfOperationThe if-else whose merged classical outputs should be bound; merges are read through iter_merges.
bindingsdict[str, Any]Current bindings; mutated in place to bind merge outputs.
resolvedbool | NoneTrue / False if the if was compile-time resolved (use the selected branch’s input); None if it was a runtime if (only bind identity merges).

Returns:

None — None.


reject_duplicate_physical_indices [source]

def reject_duplicate_physical_indices(
    gate_label: str,
    physical_indices: list[int],
    operand_names: list[str] | None = None,
) -> None

Reject a multi-qubit gate whose qubits resolve to the same physical qubit.

A multi-qubit gate (cx / cz / swap / toffoli and any controlled block such as qmc.control(...)) is physically defined only on distinct qubits. The frontend’s _check_qubit_alias already rejects the scalar cx(q, q) case by logical_id at trace time, but symbolic array indices — cx(qs[i], qs[j]) where i == j only at runtime, or two loop-variable indices that coincide after unrolling — resolve to the same physical qubit only at emit time. Without this check the duplicate reaches the engine as a raw, engine-specific failure (Qiskit CircuitError: 'duplicate qubit arguments', a CUDA-Q simulator crash, or — on an engine that does not validate — a silently ill-defined gate). Raising a Qamomile QubitAliasError gives one actionable, engine-independent diagnostic.

This is the shared checker used both for native gates (emit_gate via _reject_aliased_operands) and for controlled / composite blocks (the append_gate sites in controlled_emission), so the same diagnostic covers every multi-qubit emission path on every engine.

Parameters:

NameTypeDescription
gate_labelstrHuman-readable name of the gate for the message (e.g. "CX" or "controlled gate").
physical_indiceslist[int]The resolved physical qubit indices the gate acts on, in operand order.
operand_nameslist[str] | NoneOptional display names aligned with physical_indices (e.g. ["qs[i]", "qs[j]"]). When absent, the message falls back to qubit<index>. Defaults to None.

Returns:

None — None

Raises:


remap_static_merge_outputs [source]

def remap_static_merge_outputs(
    if_op: IfOperation,
    condition_value: bool,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any] | None = None,
    resolver: ValueResolver | None = None,
) -> None

Remap merge outputs for a compile-time constant IfOperation.

Registers each merged output under the physical resource of the branch selected by the resolved condition, so downstream operations referencing the merge output resolve to the surviving branch’s qubit / clbit. Outputs already registered are left untouched.

Parameters:

NameTypeDescription
if_opIfOperationThe if-else whose condition resolved at compile time; merges are read through iter_merges.
condition_valueboolThe resolved condition, selecting which branch’s source the outputs alias.
qubit_mapQubitMapAddress-to-physical-qubit map, mutated in place.
clbit_mapClbitMapAddress-to-physical-clbit map, mutated in place.
bindingsdict[str, Any] | NoneActive bindings used to fold a merge source’s symbolic Vector[Bit] element index / slice bounds (e.g. an unrolled loop variable). Defaults to None (empty), restricting element resolution to constant indices.
resolverValueResolver | NoneResolver used with bindings to fold non-constant element indices; None restricts to constants. Defaults to None.

replay_controlled_for [source]

def replay_controlled_for(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: ForOperation,
    control_indices: list[int],
    qubit_map: QubitMap,
    bindings: dict[str, Any],
    *,
    walker: Callable[..., None],
) -> None

Replay one static range loop under accumulated quantum controls.

Controlled blocks use a specialized operation walker because every quantum gate in the body must inherit the outer controls. Reusing only the old loop-variable binding logic here skipped the loop’s explicit RegionArg protocol, so a scalar recurrence such as index += 1 either stayed pinned to its initial value or became unresolved. This helper shares the canonical emit-time carry primitives with ordinary loop emission and accepts the engine-specific controlled walker as a callback. Nested range loops therefore replay recursively with the same init -> block_arg -> yielded -> result semantics on every engine.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass and value resolver.
circuitAnyEngine circuit being constructed.
opForOperationStatic range loop to replay.
control_indiceslist[int]Physical controls accumulated from the enclosing controlled operations.
qubit_mapQubitMapMutable block-local qubit map.
bindingsdict[str, Any]Bindings visible before the loop. Final RegionArg results and the final loop variable are published here.
walkerCallable[..., None]Controlled operation walker with the same leading arguments as :func:emit_controlled_operations.

Returns:

None — The callback appends operations to circuit in place.

Raises:


resolve_angle_value [source]

def resolve_angle_value(
    emit_pass: 'StandardEmitPass',
    theta: Any,
    bindings: dict[str, Any],
) -> float | Any

Resolve a bare angle Value to a concrete float or engine parameter.

Shared core of :func:resolve_angle so operations carrying a standalone angle Value reuse the exact same resolution order as rotation-gate thetas.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass providing the resolver and engine-parameter factory.
thetaAnyAngle Value to resolve.
bindingsdict[str, Any]Active compile-time bindings.

Returns:

float | Any — float | Any: A concrete float when the angle is bound, or a engine parameter expression when it stays symbolic.

Raises:


resolve_controlled_u_call [source]

def resolve_controlled_u_call(
    emit_pass: 'StandardEmitPass',
    op: ControlledUOperation,
    qubit_map: QubitMap,
    bindings: dict[str, Any],
    *,
    bind_body: bool = True,
) -> ResolvedControlledU

Resolve a (possibly nested) controlled-U call site to physical qubits.

Handles all three operand layouts:

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass; provides the value resolver.
opControlledUOperationThe controlled-U operation to resolve.
qubit_mapQubitMapQubit map the operands resolve against (block-local when called from a controlled walker).
bindingsdict[str, Any]Bindings visible at the call site, including loop-iteration values during unrolling.
bind_bodyboolWhether to bind the selected body’s formal parameters and shapes. Set to False for a zero-powered identity. Defaults to True.

Returns:

ResolvedControlledU — Physical controls / targets and the inner-block bindings.

Raises:


resolve_if_condition [source]

def resolve_if_condition(condition: Any, bindings: dict[str, Any]) -> bool | None

Resolve an if-condition to a compile-time boolean.


resolve_loop_bounds [source]

def resolve_loop_bounds(
    resolver: Any,
    op: ForOperation,
    bindings: dict[str, Any],
) -> tuple[int | None, int | None, int | None]

Resolve for-loop bounds (start, stop, step) from operands.

Missing operands use defaults: start=0, stop=1, step=1. Returns None for bounds that cannot be resolved to concrete ints.


resolve_power [source]

def resolve_power(
    emit_pass: 'StandardEmitPass',
    op: ControlledUOperation,
    bindings: dict[str, Any],
) -> int

Resolve ControlledUOperation.power to a concrete integer.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass and value resolver.
opControlledUOperationControlled operation owning the power.
bindingsdict[str, Any]Emit-time bindings visible in the current scope.

Returns:

int — Validated nonnegative power.

Raises:


should_batch_controlled_body [source]

def should_batch_controlled_body(num_controls: int, *, profile: ControlBatchProfile) -> bool

Return whether engine fallback should share one AND carrier.

Parameters:

NameTypeDescription
num_controlsintConcrete number of composed controls.
profileControlBatchProfileContext-resolved emission profile.

Returns:

bool — Whether engine fallback should build one body-wide ladder.


static_controlled_batch_profile [source]

def static_controlled_batch_profile(operation: Operation) -> ControlBatchProfile | None

Return context-free emission batching information for one operation.

None means that emission must resolve classical state or a nested callable before deciding the weight. Unknown operation kinds count as one leaf so eligibility analysis never hides work rejected by the later walker.

Parameters:

NameTypeDescription
operationOperationOperation inside a controlled body.

Returns:

ControlBatchProfile | None — ControlBatchProfile | None: Context-free emission profile, or None when engine-specific value resolution is required.


try_emit_batched_controlled_operations [source]

def try_emit_batched_controlled_operations(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    operations: list[Operation],
    control_indices: list[int],
    qubit_map: QubitMap,
    bindings: dict[str, Any],
    walker: Callable[..., None],
    batch_profile: ControlBatchProfile | None = None,
) -> bool

Emit a controlled block body behind a single shared AND ladder.

When a block body emits several gates under the same composed controls, lowering each gate through its own Toffoli cascade rebuilds the same AND ladder per gate — the uncompute of one gate and the recompute of the next cancel. This helper instead ANDs the controls onto one ancilla once, walks the whole body under that single control, then uncomputes the ladder once. Nested controlled-U operations compose [and_ancilla] with their own controls and re-enter walker, which batches again from the advanced pool offset; loops are batched before iteration expansion, so the ladder is hoisted out.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass (must hold a _mc_ancilla_pool).
circuitAnyEngine circuit being emitted into.
operationslist[Operation]Controlled block body operations.
control_indiceslist[int]Composed physical control qubits.
qubit_mapQubitMapMutable block-local qubit map.
bindingsdict[str, Any]Bindings visible inside the block.
walkerCallable[..., None]The controlled-body walker to run under the single AND control (its own signature).
batch_profileControlBatchProfile | NonePreviously resolved body profile for this exact block and binding scope. Defaults to None, which computes the profile locally.

Returns:

bool — True when the body was batched, False when the caller should fall back to per-gate emission (fewer than two controls, no pool, insufficient weight, the two-control guard, or a pool that cannot spare the ladder).

Raises:

Classes

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:

bool — True iff slice_of is non-None.

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

BinOp [source]

class BinOp(BinaryOperationBase)

Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: BinOpKind | None = None,
) -> None
Attributes

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.


CInitOperation [source]

class CInitOperation(Operation)

Initialize the classical values (const, arguments etc)

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

CallTransform [source]

class CallTransform(enum.Enum)

Describe the requested transform of a callable implementation.

Attributes
Methods
inverted
def inverted(self) -> CallTransform

Toggle inverse application while preserving coherent control.

Returns:

CallTransform — Transform with the inverse component toggled.


CallableBodySelection [source]

class CallableBodySelection

Describe one validated IR body selected for an invocation.

Parameters:

NameTypeDescription
bodyBlock | NoneSelected IR body, or None when no composable body is available.
realized_transformCallTransformTransform already implemented by body.
operandstuple[ValueBase, ...]Call-site operands corresponding to the selected body’s formal inputs.
resultstuple[ValueBase, ...]Call-site results corresponding to the selected body’s formal outputs.
Constructor
def __init__(
    self,
    body: Block | None,
    realized_transform: CallTransform,
    operands: tuple[ValueBase, ...],
    results: tuple[ValueBase, ...],
) -> None
Attributes
Methods
map_result_indices
def map_result_indices(
    self,
    body_indices: Iterable[int],
    invocation_results: Sequence[ValueBase],
) -> frozenset[int]

Map selected-body output positions to invocation result positions.

Generic controlled lowering removes the external control prefix before aligning a direct body. Transform-specific implementations instead use the complete invocation ABI. Mapping through the selected call-site result values handles both layouts, including any quantum/non-quantum reordering performed while aligning a fallback body.

Parameters:

NameTypeDescription
body_indicesIterable[int]Selected-body output positions to map.
invocation_resultsSequence[ValueBase]Complete caller-side invocation results.

Returns:

frozenset[int] — frozenset[int]: Corresponding positions in invocation_results.


CastOperation [source]

class CastOperation(Operation)

Type cast operation for creating aliases over the same quantum resources.

This operation does NOT allocate new qubits. It creates a new Value that references the same underlying quantum resources with a different type.

Use cases:

operands: [source_value] - The value being cast results: [cast_result] - The new value with target type (same physical qubits)

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    source_type: ValueType | None = None,
    target_type: ValueType | None = None,
    qubit_mapping: list[str] = list(),
) -> None
Attributes

CompOp [source]

class CompOp(BinaryOperationBase)

Comparison operation (EQ, NEQ, LT, LE, GT, GE).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CompOpKind | None = None,
) -> None
Attributes

ConcreteControlledU [source]

class ConcreteControlledU(ControlledUOperation)

Controlled-U with concrete (int) number of controls.

Operand layout: [ctrl_0, ..., ctrl_n, tgt_0, ..., tgt_m, params...] Result layout: [ctrl_0', ..., ctrl_n', tgt_0', ..., tgt_m']

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_value: int | None = None,
) -> None
Attributes

CondOp [source]

class CondOp(BinaryOperationBase)

Conditional logical operation (AND, OR).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CondOpKind | None = None,
) -> None
Attributes

ControlBatchProfile [source]

class ControlBatchProfile

Describe resolved work and the engine’s exact-two-control choice.

Parameters:

NameTypeDescription
weightintControlled work clamped to zero, one, or two.
selects_exact_twoboolWhether the engine selects a shared carrier when exactly two outer controls are present.
Constructor
def __init__(self, weight: int = 0, selects_exact_two: bool = False) -> None
Attributes

ControlledUOperation [source]

class ControlledUOperation(Operation)

Base class for controlled-U operations.

Two concrete subclasses handle distinct operand layouts:

All isinstance(op, ControlledUOperation) checks match every subclass.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int | Value = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]
replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

CountingEmitter [source]

class CountingEmitter

A no-op gate emitter that lets a real emission walk run for counting.

Wraps the real engine emitter, delegating capability queries so control-flow lowering matches real emission while turning every gate emission into a no-op and every gate/sub-circuit construction into a None that forces the cascade-prone fallback path. Used by isolated analysis-emission transactions for ancilla sizing and zero-work semantic validation; the object is passed where a GateEmitter[T] is expected via a cast.

Constructor
def __init__(self, real: Any) -> None

Wrap a real emitter for a counting run.

Parameters:

NameTypeDescription
realAnyThe engine emitter whose capability answers should be mirrored so the walk makes the same structural choices.
Attributes
Methods
append_gate
def append_gate(self, circuit: Any, gate: Any, qubits: list[int]) -> None

Count appending a prebuilt gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
gateAnyIgnored gate object (never built in counting mode).
qubitslist[int]Ignored qubit indices the gate acts on.
circuit_to_gate
def circuit_to_gate(self, circuit: Any, name: str = 'U') -> Any

Force the fallback path by declining to build a reusable gate.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
namestrIgnored gate name. Defaults to "U".

Returns:

Any — Always None.

combine_symbolic
def combine_symbolic(self, kind: Any, lhs: Any, rhs: Any) -> _CountingParameter

Return a placeholder for a symbolic angle combination.

Parameters:

NameTypeDescription
kindAnyIgnored binary-op kind.
lhsAnyIgnored left operand.
rhsAnyIgnored right operand.

Returns:

_CountingParameter — A placeholder symbolic angle.

create_circuit
def create_circuit(self, num_qubits: int, num_clbits: int) -> _CountingCircuit

Return a placeholder circuit.

Parameters:

NameTypeDescription
num_qubitsintIgnored.
num_clbitsintIgnored.

Returns:

_CountingCircuit — A stateless placeholder.

create_parameter
def create_parameter(self, name: str) -> _CountingParameter

Return an arithmetic-absorbing placeholder parameter.

Parameters:

NameTypeDescription
namestrIgnored.

Returns:

_CountingParameter — A placeholder runtime parameter.

emit_barrier
def emit_barrier(self, circuit: Any, qubits: list[int]) -> None

Count a barrier as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitslist[int]Ignored qubit indices spanned by the barrier.
emit_ch
def emit_ch(self, circuit: Any, control: int, target: int) -> None

Count a CH gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
emit_cp
def emit_cp(self, circuit: Any, control: int, target: int, angle: Any) -> None

Count a controlled-phase gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
angleAnyIgnored phase angle.
emit_crx
def emit_crx(self, circuit: Any, control: int, target: int, angle: Any) -> None

Count a CRX gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
angleAnyIgnored rotation angle.
emit_cry
def emit_cry(self, circuit: Any, control: int, target: int, angle: Any) -> None

Count a CRY gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
angleAnyIgnored rotation angle.
emit_crz
def emit_crz(self, circuit: Any, control: int, target: int, angle: Any) -> None

Count a CRZ gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
angleAnyIgnored rotation angle.
emit_cx
def emit_cx(self, circuit: Any, control: int, target: int) -> None

Count a CX gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
emit_cy
def emit_cy(self, circuit: Any, control: int, target: int) -> None

Count a CY gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
emit_cz
def emit_cz(self, circuit: Any, control: int, target: int) -> None

Count a CZ gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
emit_else_start
def emit_else_start(self, circuit: Any, context: Any) -> None

Count the start of a native else branch as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
contextAnyIgnored branch context from emit_if_start.
emit_for_loop_end
def emit_for_loop_end(self, circuit: Any, context: Any) -> None

Count the end of a native for loop as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
contextAnyIgnored loop context from emit_for_loop_start.
emit_for_loop_start
def emit_for_loop_start(self, circuit: Any, indexset: range) -> Any

Return a placeholder loop variable for a native-for-loop count.

Unlike the other control-flow hooks, emit_for’s return value is bound as the loop variable (via _bind_loop_var) and the body is then walked once. A real native-loop emitter returns a symbolic loop parameter, so return the arithmetic-absorbing :class:_CountingParameter rather than None — otherwise a body that carries the loop value into an angle or index expression during counting would see None and fail. (No pool-reserving engine supports native for loops today, so this is future-proofing.)

Parameters:

NameTypeDescription
circuitAnyIgnored.
indexsetrangeIgnored.

Returns:

Any — A placeholder loop variable.

emit_global_phase
def emit_global_phase(self, circuit: Any, angle: Any) -> None

Accept a standalone phase during the internal counting walk.

The counting emitter observes only peak clean-ancilla demand. It does not materialize any gate, including a phase that the wrapped real emitter will preserve during the subsequent emission walk.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
angleAnyIgnored phase angle.
emit_h
def emit_h(self, circuit: Any, qubit: int) -> None

Count an H gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_if_end
def emit_if_end(self, circuit: Any, context: Any) -> None

Count the end of a native if/else block as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
contextAnyIgnored branch context from emit_if_start.
emit_if_start
def emit_if_start(self, circuit: Any, clbit: int, value: int = 1) -> Any

Count the start of a native if branch as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
clbitintIgnored predicate classical bit index.
valueintIgnored predicate value to match. Defaults to 1.

Returns:

Any — Always None (a null branch context).

emit_measure
def emit_measure(self, circuit: Any, qubit: int, clbit: int) -> None

Count a measurement as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored measured qubit index.
clbitintIgnored destination classical bit index.
emit_p
def emit_p(self, circuit: Any, qubit: int, angle: Any) -> None

Count a phase gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
angleAnyIgnored phase angle.
emit_reset
def emit_reset(self, circuit: Any, qubit: int) -> None

Count a reset as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored reset qubit index.
emit_rx
def emit_rx(self, circuit: Any, qubit: int, angle: Any) -> None

Count an RX gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
angleAnyIgnored rotation angle.
emit_ry
def emit_ry(self, circuit: Any, qubit: int, angle: Any) -> None

Count an RY gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
angleAnyIgnored rotation angle.
emit_rz
def emit_rz(self, circuit: Any, qubit: int, angle: Any) -> None

Count an RZ gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
angleAnyIgnored rotation angle.
emit_rzz
def emit_rzz(self, circuit: Any, qubit1: int, qubit2: int, angle: Any) -> None

Count an RZZ gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubit1intIgnored first qubit index.
qubit2intIgnored second qubit index.
angleAnyIgnored rotation angle.
emit_s
def emit_s(self, circuit: Any, qubit: int) -> None

Count an S gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_sdg
def emit_sdg(self, circuit: Any, qubit: int) -> None

Count an Sdg gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_swap
def emit_swap(self, circuit: Any, qubit1: int, qubit2: int) -> None

Count a SWAP gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubit1intIgnored first qubit index.
qubit2intIgnored second qubit index.
emit_t
def emit_t(self, circuit: Any, qubit: int) -> None

Count a T gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_tdg
def emit_tdg(self, circuit: Any, qubit: int) -> None

Count a Tdg gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_toffoli
def emit_toffoli(self, circuit: Any, control1: int, control2: int, target: int) -> None

Count a Toffoli gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
control1intIgnored first control qubit index.
control2intIgnored second control qubit index.
targetintIgnored target qubit index.
emit_while_end
def emit_while_end(self, circuit: Any, context: Any) -> None

Count the end of a native while loop as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
contextAnyIgnored loop context from emit_while_start.
emit_while_start
def emit_while_start(self, circuit: Any, clbit: int, value: int = 1) -> Any

Count the start of a native while loop as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
clbitintIgnored predicate classical bit index.
valueintIgnored predicate value to match. Defaults to 1.

Returns:

Any — Always None (a null loop context).

emit_x
def emit_x(self, circuit: Any, qubit: int) -> None

Count an X gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_y
def emit_y(self, circuit: Any, qubit: int) -> None

Count a Y gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_z
def emit_z(self, circuit: Any, qubit: int) -> None

Count a Z gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
gate_controlled
def gate_controlled(self, gate: Any, num_controls: int) -> Any

Decline to build a real controlled gate.

Parameters:

NameTypeDescription
gateAnyIgnored gate object.
num_controlsintIgnored number of control qubits.

Returns:

Any — Always None.

gate_inverse
def gate_inverse(self, gate: Any) -> Any

Decline to build a real inverse gate.

Parameters:

NameTypeDescription
gateAnyIgnored gate object.

Returns:

Any — Always None.

gate_power
def gate_power(self, gate: Any, power: int) -> Any

Decline to build a real powered gate.

Parameters:

NameTypeDescription
gateAnyIgnored gate object.
powerintIgnored exponent.

Returns:

Any — Always None.

supports_for_loop
def supports_for_loop(self) -> bool

Delegate native-for-loop support to the wrapped emitter.

Returns:

bool — The real emitter’s answer, so loops unroll (or not) the same way real emission would.

supports_gate_inverse
def supports_gate_inverse(self) -> bool

Force the inverse-by-emission fallback path.

Returns:

bool — Always False.

supports_if_else
def supports_if_else(self) -> bool

Delegate native if/else support to the wrapped emitter.

Returns:

bool — The real emitter’s answer.

supports_reusable_gates
def supports_reusable_gates(self) -> bool

Force the gate-by-gate fallback path.

Returns:

bool — Always False.

supports_while_loop
def supports_while_loop(self) -> bool

Delegate native while-loop support to the wrapped emitter.

Returns:

bool — The real emitter’s answer.


DictGetItemOperation [source]

class DictGetItemOperation(Operation)

Look up one entry of a Dict by a (possibly symbolic) key.

This is the IR form of d[key] on a Dict handle. The key components may be symbolic (e.g. loop variables of a for-items loop); the lookup is resolved at emit time when the key values and the dict’s bound data are both concrete.

operands: [DictValue, *key_component_values] results: [looked-up scalar value]

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_arity: int = 1,
) -> None
Attributes

EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return
Constructor
def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

GateOperation [source]

class GateOperation(Operation)

Quantum gate operation.

For rotation gates (RX, RY, RZ, P, CP, RZZ), the angle parameter is stored as the last element of operands. Use the theta property for typed read access and the rotation / fixed factory class-methods for type-safe construction.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    gate_type: GateOperationType | None = None,
) -> None
Attributes
Methods
fixed
@classmethod
def fixed(
    cls,
    gate_type: GateOperationType,
    qubits: list[Value],
    results: list[Value],
) -> 'GateOperation'

Create a fixed gate (H, X, CX, SWAP, …) with no angle parameter.

rotation
@classmethod
def rotation(
    cls,
    gate_type: GateOperationType,
    qubits: list[Value],
    theta: Value,
    results: list[Value],
) -> 'GateOperation'

Create a rotation gate (RX, RY, RZ, P, CP, RZZ) with an angle.


GateOperationType [source]

class GateOperationType(enum.Enum)
Attributes

GlobalPhaseOperation [source]

class GlobalPhaseOperation(Operation)

Multiply the complete quantum state by exp(i * phase).

Global phase has no target qubit and does not create a new quantum value. Keeping the phase as the operation’s sole ordinary operand lets generic IR passes substitute, serialize, and analyze it without a special value-field protocol. A surrounding controlled-unitary lowering turns the operation into an observable phase gate on the accumulated controls.

Parameters:

NameTypeDescription
operandslist[Value]Exactly one scalar FloatType phase angle in radians.
resultslist[Value]Must be empty because global phase changes no qubit identity.

Raises:

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


InverseBlockOperation [source]

class InverseBlockOperation(Operation)

Represent an inverse qkernel/block as a first-class IR operation.

The operation stores both the original forward block and a Qamomile-built inverse implementation block. Emitters may use source_block with a engine-native inverse/adjoint primitive, then fall back to implementation_block when native inversion is unavailable.

Operands are ordered as scalar control qubits, target quantum operands, then classical/object parameters. Results mirror the quantum operand layout: control results first, then one target result per target operand. Vector target operands therefore count as one operand/result while contributing their scalar width to num_target_qubits.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_control_qubits: int = 0,
    num_target_qubits: int = 0,
    custom_name: str = '',
    source_block: Block | None = None,
    implementation_block: Block | None = None,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_value: int | None = None,
) -> None
Attributes

InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.
Constructor
def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes
Methods
body_for_transform
def body_for_transform(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> tuple[Block | None, CallTransform]

Select a body and report the transform it already realizes.

A controlled-inverse invocation may reuse an explicitly registered inverse body when no implementation realizes both transforms. Keeping that fallback in the IR operation gives emitters and static analyses one selection rule while still letting each consumer apply the remaining coherent controls in its own representation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — tuple[Block | None, CallTransform]: Selected body and the transform CallTransform — already implemented by that body. The callable’s direct body is tuple[Block | None, CallTransform] — returned with DIRECT when no transform-specific body matches.

Raises:

effective_body
def effective_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — Block | None: Selected implementation body, or the callable’s Block | None — default body when no transform-specific implementation exists. Block | None — A compiler may synthesize inverse or controlled behavior from this Block | None — fallback body.

implementation_for
def implementation_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None, which only selects engine-generic implementations.
strategystr | NoneStrategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation candidate, CallableImplementation | None — or None when the callable definition has no match.

measurement_result_indices_for
def measurement_result_indices_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> frozenset[int]

Return measurement-derived results for one selected implementation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name used for implementation selection. Defaults to None.
strategystr | NoneStrategy name used for implementation selection. Defaults to the invocation’s strategy_name.

Returns:

frozenset[int] — frozenset[int]: Caller-local result positions derived from measurement in the selected body.

Raises:

select_body
def select_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> CallableBodySelection

Select and validate the composable body for this invocation.

The result carries the transform already realized by the body and the exact call-site values that bind to it. Consumers therefore cannot independently disagree about whether an invocation’s control prefix belongs to the selected implementation ABI.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

CallableBodySelection — Validated body, realized transform, and CallableBodySelection — aligned call-site operands and results.

Raises:


NotOp [source]

class NotOp(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

PauliEvolveOp [source]

class PauliEvolveOp(Operation)

Pauli evolution operation: exp(-i * gamma * H).

This operation applies the time evolution of a Pauli Hamiltonian to a quantum register.

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

QInitOperation [source]

class QInitOperation(Operation)

Initialize the qubit

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

QubitAddress [source]

class QubitAddress

Typed key for qubit/clbit physical-index maps.

For scalar qubits: QubitAddress(uuid="abc123") For array elements: QubitAddress(uuid="abc123", element_index=2)

This replaces the f"{uuid}_{i}" string key pattern throughout the emit pipeline, making the key format explicit and preventing format-string bugs.

Constructor
def __init__(self, uuid: str, element_index: int | None = None) -> None
Attributes
Methods
from_composite_key
@classmethod
def from_composite_key(cls, key: str) -> QubitAddress

Parse a legacy composite key string into a QubitAddress.

The frontend stores qubit references as composite strings in the format "{array_uuid}_{element_index}" (e.g., cast operation qubit mappings, element UUIDs). This helper converts such strings to proper QubitAddress instances.

If the key does not match the composite format (i.e., the suffix after the last _ is not a non-negative integer), it is treated as a plain scalar UUID.

matches_array
def matches_array(self, array_uuid: str) -> bool

True if this address belongs to the given array.

with_element
def with_element(self, index: int) -> QubitAddress

Create an array-element address from this array’s base UUID.


ReleaseSliceViewOperation [source]

class ReleaseSliceViewOperation(Operation)

Mark a slice view’s borrow as explicitly returned to its parent.

Emitted by :meth:Vector.__setitem__ when used with a slice index (qs[a:b] = qmc.h(qs[a:b])). This op tells the post-fold linearity checker (:class:~qamomile.circuit.transpiler.passes.slice_borrow_check.SliceBorrowCheckPass) that the view referenced in operands[0] no longer owns its covered parent slots, mirroring the frontend’s VectorView.consume(operation_name="slice assignment") borrow release.

Like :class:SliceArrayOperation, this op is a declarative classical-side marker that does not survive into the emit stream: :class:~qamomile.circuit.transpiler.passes.strip_slice_ops.StripSliceArrayOpsPass removes both :class:SliceArrayOperation and :class:ReleaseSliceViewOperation after :class:SliceBorrowCheckPass has observed them. Reaching emit is a compiler-internal invariant violation and is rejected with a RuntimeError from :mod:standard_emit.

Within a control-flow body (ForOperation / WhileOperation / IfOperation), this op only releases view borrows that were created within the same body. Releasing a borrow that the enclosing block has registered (an “outer-snapshot” borrow) is rejected by SliceBorrowCheckPass with ValidationError — the loop-merge semantics of the pass cannot propagate entry deletions out of the body, so the only way to keep the static check consistent is to forbid that pattern.

Example:

``qs[1:3] = qmc.h(qs[1:3])`` emits, after the broadcast loop::

    ReleaseSliceViewOperation(
        operands=[qmc_h_result_view],  # slice_of=qs_value
        results=[],
    )
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ResolvedControlledU [source]

class ResolvedControlledU

Physical resolution of one ControlledUOperation call site.

Produced by :func:resolve_controlled_u_call for every concrete and symbolic operand layout, so walkers can lower nested controlled-U operations without shape-specific branching.

Constructor
def __init__(
    self,
    control_phys: list[int],
    control_operand_groups: list[list[int]],
    target_qubit_operands: list[Any],
    target_index_groups: list[list[int]],
    target_phys: list[int],
    block: Any,
    local_bindings: dict[str, Any],
) -> None
Attributes

ReturnOperation [source]

class ReturnOperation(Operation)

Explicit return operation marking the end of a block with return values.

This operation represents an explicit return statement in the IR. It takes the values to be returned as operands and produces no results (it is a terminal operation that transfers control flow back to the caller).

operands: [Value, ...] - The values to return (may be empty for void returns) results: [] - Always empty (terminal operation)

Example:

A function that returns two values (a UInt and a Float):

ReturnOperation(
    operands=[uint_value, float_value],
    results=[],
)

The signature would be:
    operands=[ParamHint("return_0", UIntType()), ParamHint("return_1", FloatType())]
    results=[]
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ReturnQuantumArrayElementOperation [source]

class ReturnQuantumArrayElementOperation(Operation)

Validate a branch-selected quantum element’s array return at emit time.

Most quantum element assignments are verified structurally by the frontend and emit no IR. A compile-time conditional can instead select different element indices on its branches; only the unrolled emit context knows which source index survived. This operation carries both the requested target indices and the conditional source indices so emission can prove they resolve to the same physical slot before treating the assignment as a borrow return.

Operand convention:

[array, returned_qubit, *target_indices, *source_indices]. The target and source halves have equal nonzero arity, inferred from the operand count. The operation has no results and emits no engine gate.

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

SelectOperation [source]

class SelectOperation(Operation)

Quantum multiplexer: apply case_blocks[i] when the index reads i.

Concrete operand layout: [idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...]. Symbolic-width operand layout: [idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...]. Results mirror the quantum operand grouping.

A concrete index register is normalized to one scalar Qubit operand per physical index qubit. A symbolic-width register instead retains each leading caller argument as one scalar or array operand until its bound shape is known. Whole-Vector[Qubit] / scalar targets follow and keep their shapes, and classical parameters shared across every case come last.

Index bit order is LSB-first: idx_0 is the least-significant bit, matching Qamomile’s qubit-zero convention. Case i is selected when index qubit j reads bit j of i. len(case_blocks) need not be a power of two; index values >= len(case_blocks) apply no operation (identity).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_index_qubits: int | Value = 0,
    case_blocks: list[Block] = list(),
    num_index_args: int = 0,
    case_callable_attrs: list[dict[str, Any]] = list(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Return every value consumed by the SELECT operation.

Returns:

list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width value when present.

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed replacement values.

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


SliceArrayOperation [source]

class SliceArrayOperation(Operation)

Construct a strided view of an ArrayValue.

The op itself performs no quantum action — it records that the result ArrayValue is a strided view of the operand parent with the given start / step. The result’s slice_of / slice_start / slice_step fields carry the affine map used by the emit-time resolver.

SliceArrayOperation is classified as :attr:OperationKind.CLASSICAL because slicing is pure index selection — no new quantum operation is introduced. The pipeline keeps this op through PartialEvaluationPass (which invokes ConstantFoldingPass(..., strip_slice_ops=False)) so the post-fold :class:~qamomile.circuit.transpiler.passes.slice_borrow_check.SliceBorrowCheckPass can use it as a view-declaration marker; once that check has run, StripSliceArrayOpsPass removes every SliceArrayOperation / ReleaseSliceViewOperation so segmentation (:mod:~qamomile.circuit.transpiler.passes.separate) and the downstream emit stage only see a pure quantum-op stream. By the time :mod:~qamomile.circuit.transpiler.passes.separate runs the op has therefore been stripped — reaching emit is a compiler- internal invariant violation.

Example:

``q[1::2]`` on a ``Vector[Qubit]`` emits::

    SliceArrayOperation(
        operands=[q_value, uint_1, uint_2],
        results=[sliced_value],  # slice_of=q_value, slice_start=uint_1, slice_step=uint_2
    )
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

StandardEmitPass [source]

class StandardEmitPass(EmitPass[T], Generic[T])

Standard emit pass implementation using GateEmitter protocol.

This class provides orchestration for semantic IR traversal while delegating circuit instruction construction to a GateEmitter. The concrete compiler use is CircuitLoweringPass; SDK targets materialize its immutable result instead of subclassing this class.

Parameters:

NameTypeDescription
gate_emitterGateEmitter[T]Instruction builder used during the semantic traversal.
bindingsdict[str, Any] | NoneCompile-time parameter bindings.
parameterslist[str] | NoneParameter names preserved at runtime.
composite_emitterslist[CompositeGateEmitter[T]] | NoneOptional callable-preservation or lowering hooks.
engine_namestr | NoneDiagnostic name for the traversal target.
Constructor
def __init__(
    self,
    gate_emitter: GateEmitter[T],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
    composite_emitters: list[CompositeGateEmitter[T]] | None = None,
    engine_name: str | None = None,
)
Attributes

StoreArrayElementOperation [source]

class StoreArrayElementOperation(Operation)

Store a classical scalar into one element of a classical array.

This is the IR form of array[index] = value for classical element types (Bit / UInt / Float). Classical values are freely copyable, so the store is an ordinary SSA rewrite: the operation consumes the current array version and produces a new ArrayValue version (same logical_id, fresh uuid) whose contents equal the input array with the addressed element replaced. Quantum arrays never use this operation — qubit element assignment is the return half of the borrow-return idiom and emits no IR.

The operation is evaluated in one of two places:

Operand convention:

operands: [array (ArrayValue), stored_value (Value), *index_values] results: [new_array (ArrayValue)]

Example:

@qmc.qkernel
def k() -> qmc.Vector[qmc.Bit]:
    qs = qmc.qubit_array(2, "qs")
    qs[0] = qmc.x(qs[0])
    bits = qmc.measure(qs)
    bits[1] = bits[0]   # emits StoreArrayElementOperation
    return bits
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

SymbolicControlledU [source]

class SymbolicControlledU(ControlledUOperation)

Controlled-U with symbolic (Value) number of controls.

Operand layout: [ctrl_arg_0, ..., ctrl_arg_{k-1}, tgt_0, ..., tgt_m, params...] Result layout: [ctrl_arg_0', ..., ctrl_arg_{k-1}', tgt_0', ..., tgt_m']

The number of control arguments k is recorded in num_control_args; the default k = 1 corresponds to the historical single-pool form (operands[0] is a Vector[Qubit] / VectorView whose length equals num_controls, or whose control_indices-selected subset does). When k > 1 the control prefix is a heterogeneous sequence of scalar Qubit values and ArrayValues whose total qubit count is num_controls; the emit pass walks them in order to recover the per-physical-qubit control set.

When control_indices is None the entire control prefix is used as active controls (one-arg form: len(ctrl_vector) == num_controls; multi-arg form: the qubit-count sum of the prefix args equals num_controls). When non-None, the listed indices select exactly num_controls slots from a single-arg pool to act as controls; combining control_indices with the multi-arg control prefix is rejected at frontend time.

Each control_indices entry is stored as a Value of UIntType regardless of whether the frontend passed an int literal or a UInt handle, so all downstream value-substitution passes see a uniform shape.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: Value = (lambda: Value(type=(UIntType()), name=''))(),
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_indices: tuple[Value, ...] | None = None,
    num_control_args: int = 1,
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]
replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

UnaryMathOp [source]

class UnaryMathOp(Operation)

Represent one pure unary mathematical expression.

Parameters:

NameTypeDescription
operandslist[Value]Single numeric input value.
resultslist[Value]Single numeric result value.
kindUnaryMathOpKind | NoneMathematical operation to apply.

Raises:

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: UnaryMathOpKind | None = None,
) -> None
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 engine resource allocation. This applies to every Value regardless of its type (Qubit, Float, Bit, ...) -- it is not specific to qubits.


qamomile.circuit.transpiler.passes.emit_support.counting_emitter

Count-only emitter for measuring multi-control ancilla demand.

A quantum segment’s engine circuit is created with a fixed qubit count before emission starts, so the multi-control ancilla pool must be sized in advance. Rather than mirror the emit-time control-absorption rules in a separate static walk — which has to stay in lockstep with the real emitter or it will silently under-reserve — the demand is measured by running the real emission machinery once against this no-op emitter and a counting ancilla pool.

Every gate emission is a no-op and every structural query returns a value that keeps the walk on its cascade-prone fallback path (circuit_to_gate / gate_controlled / gate_power / gate_inverse return None and supports_reusable_gates / supports_gate_inverse are False), so the count is an upper bound and never touches a real circuit object. Capability queries (measurement_mode and the control-flow supports_* hooks) delegate to the wrapped emitter so the walk takes the same unroll-versus- native-loop decisions the real emission would.

Overview

ClassDescription
CountingEmitterA no-op gate emitter that lets a real emission walk run for counting.
MeasurementModeHow an engine handles measurement operations.

Classes

CountingEmitter [source]

class CountingEmitter

A no-op gate emitter that lets a real emission walk run for counting.

Wraps the real engine emitter, delegating capability queries so control-flow lowering matches real emission while turning every gate emission into a no-op and every gate/sub-circuit construction into a None that forces the cascade-prone fallback path. Used by isolated analysis-emission transactions for ancilla sizing and zero-work semantic validation; the object is passed where a GateEmitter[T] is expected via a cast.

Constructor
def __init__(self, real: Any) -> None

Wrap a real emitter for a counting run.

Parameters:

NameTypeDescription
realAnyThe engine emitter whose capability answers should be mirrored so the walk makes the same structural choices.
Attributes
Methods
append_gate
def append_gate(self, circuit: Any, gate: Any, qubits: list[int]) -> None

Count appending a prebuilt gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
gateAnyIgnored gate object (never built in counting mode).
qubitslist[int]Ignored qubit indices the gate acts on.
circuit_to_gate
def circuit_to_gate(self, circuit: Any, name: str = 'U') -> Any

Force the fallback path by declining to build a reusable gate.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
namestrIgnored gate name. Defaults to "U".

Returns:

Any — Always None.

combine_symbolic
def combine_symbolic(self, kind: Any, lhs: Any, rhs: Any) -> _CountingParameter

Return a placeholder for a symbolic angle combination.

Parameters:

NameTypeDescription
kindAnyIgnored binary-op kind.
lhsAnyIgnored left operand.
rhsAnyIgnored right operand.

Returns:

_CountingParameter — A placeholder symbolic angle.

create_circuit
def create_circuit(self, num_qubits: int, num_clbits: int) -> _CountingCircuit

Return a placeholder circuit.

Parameters:

NameTypeDescription
num_qubitsintIgnored.
num_clbitsintIgnored.

Returns:

_CountingCircuit — A stateless placeholder.

create_parameter
def create_parameter(self, name: str) -> _CountingParameter

Return an arithmetic-absorbing placeholder parameter.

Parameters:

NameTypeDescription
namestrIgnored.

Returns:

_CountingParameter — A placeholder runtime parameter.

emit_barrier
def emit_barrier(self, circuit: Any, qubits: list[int]) -> None

Count a barrier as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitslist[int]Ignored qubit indices spanned by the barrier.
emit_ch
def emit_ch(self, circuit: Any, control: int, target: int) -> None

Count a CH gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
emit_cp
def emit_cp(self, circuit: Any, control: int, target: int, angle: Any) -> None

Count a controlled-phase gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
angleAnyIgnored phase angle.
emit_crx
def emit_crx(self, circuit: Any, control: int, target: int, angle: Any) -> None

Count a CRX gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
angleAnyIgnored rotation angle.
emit_cry
def emit_cry(self, circuit: Any, control: int, target: int, angle: Any) -> None

Count a CRY gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
angleAnyIgnored rotation angle.
emit_crz
def emit_crz(self, circuit: Any, control: int, target: int, angle: Any) -> None

Count a CRZ gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
angleAnyIgnored rotation angle.
emit_cx
def emit_cx(self, circuit: Any, control: int, target: int) -> None

Count a CX gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
emit_cy
def emit_cy(self, circuit: Any, control: int, target: int) -> None

Count a CY gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
emit_cz
def emit_cz(self, circuit: Any, control: int, target: int) -> None

Count a CZ gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
emit_else_start
def emit_else_start(self, circuit: Any, context: Any) -> None

Count the start of a native else branch as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
contextAnyIgnored branch context from emit_if_start.
emit_for_loop_end
def emit_for_loop_end(self, circuit: Any, context: Any) -> None

Count the end of a native for loop as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
contextAnyIgnored loop context from emit_for_loop_start.
emit_for_loop_start
def emit_for_loop_start(self, circuit: Any, indexset: range) -> Any

Return a placeholder loop variable for a native-for-loop count.

Unlike the other control-flow hooks, emit_for’s return value is bound as the loop variable (via _bind_loop_var) and the body is then walked once. A real native-loop emitter returns a symbolic loop parameter, so return the arithmetic-absorbing :class:_CountingParameter rather than None — otherwise a body that carries the loop value into an angle or index expression during counting would see None and fail. (No pool-reserving engine supports native for loops today, so this is future-proofing.)

Parameters:

NameTypeDescription
circuitAnyIgnored.
indexsetrangeIgnored.

Returns:

Any — A placeholder loop variable.

emit_global_phase
def emit_global_phase(self, circuit: Any, angle: Any) -> None

Accept a standalone phase during the internal counting walk.

The counting emitter observes only peak clean-ancilla demand. It does not materialize any gate, including a phase that the wrapped real emitter will preserve during the subsequent emission walk.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
angleAnyIgnored phase angle.
emit_h
def emit_h(self, circuit: Any, qubit: int) -> None

Count an H gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_if_end
def emit_if_end(self, circuit: Any, context: Any) -> None

Count the end of a native if/else block as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
contextAnyIgnored branch context from emit_if_start.
emit_if_start
def emit_if_start(self, circuit: Any, clbit: int, value: int = 1) -> Any

Count the start of a native if branch as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
clbitintIgnored predicate classical bit index.
valueintIgnored predicate value to match. Defaults to 1.

Returns:

Any — Always None (a null branch context).

emit_measure
def emit_measure(self, circuit: Any, qubit: int, clbit: int) -> None

Count a measurement as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored measured qubit index.
clbitintIgnored destination classical bit index.
emit_p
def emit_p(self, circuit: Any, qubit: int, angle: Any) -> None

Count a phase gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
angleAnyIgnored phase angle.
emit_reset
def emit_reset(self, circuit: Any, qubit: int) -> None

Count a reset as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored reset qubit index.
emit_rx
def emit_rx(self, circuit: Any, qubit: int, angle: Any) -> None

Count an RX gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
angleAnyIgnored rotation angle.
emit_ry
def emit_ry(self, circuit: Any, qubit: int, angle: Any) -> None

Count an RY gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
angleAnyIgnored rotation angle.
emit_rz
def emit_rz(self, circuit: Any, qubit: int, angle: Any) -> None

Count an RZ gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
angleAnyIgnored rotation angle.
emit_rzz
def emit_rzz(self, circuit: Any, qubit1: int, qubit2: int, angle: Any) -> None

Count an RZZ gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubit1intIgnored first qubit index.
qubit2intIgnored second qubit index.
angleAnyIgnored rotation angle.
emit_s
def emit_s(self, circuit: Any, qubit: int) -> None

Count an S gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_sdg
def emit_sdg(self, circuit: Any, qubit: int) -> None

Count an Sdg gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_swap
def emit_swap(self, circuit: Any, qubit1: int, qubit2: int) -> None

Count a SWAP gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubit1intIgnored first qubit index.
qubit2intIgnored second qubit index.
emit_t
def emit_t(self, circuit: Any, qubit: int) -> None

Count a T gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_tdg
def emit_tdg(self, circuit: Any, qubit: int) -> None

Count a Tdg gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_toffoli
def emit_toffoli(self, circuit: Any, control1: int, control2: int, target: int) -> None

Count a Toffoli gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
control1intIgnored first control qubit index.
control2intIgnored second control qubit index.
targetintIgnored target qubit index.
emit_while_end
def emit_while_end(self, circuit: Any, context: Any) -> None

Count the end of a native while loop as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
contextAnyIgnored loop context from emit_while_start.
emit_while_start
def emit_while_start(self, circuit: Any, clbit: int, value: int = 1) -> Any

Count the start of a native while loop as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
clbitintIgnored predicate classical bit index.
valueintIgnored predicate value to match. Defaults to 1.

Returns:

Any — Always None (a null loop context).

emit_x
def emit_x(self, circuit: Any, qubit: int) -> None

Count an X gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_y
def emit_y(self, circuit: Any, qubit: int) -> None

Count a Y gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_z
def emit_z(self, circuit: Any, qubit: int) -> None

Count a Z gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
gate_controlled
def gate_controlled(self, gate: Any, num_controls: int) -> Any

Decline to build a real controlled gate.

Parameters:

NameTypeDescription
gateAnyIgnored gate object.
num_controlsintIgnored number of control qubits.

Returns:

Any — Always None.

gate_inverse
def gate_inverse(self, gate: Any) -> Any

Decline to build a real inverse gate.

Parameters:

NameTypeDescription
gateAnyIgnored gate object.

Returns:

Any — Always None.

gate_power
def gate_power(self, gate: Any, power: int) -> Any

Decline to build a real powered gate.

Parameters:

NameTypeDescription
gateAnyIgnored gate object.
powerintIgnored exponent.

Returns:

Any — Always None.

supports_for_loop
def supports_for_loop(self) -> bool

Delegate native-for-loop support to the wrapped emitter.

Returns:

bool — The real emitter’s answer, so loops unroll (or not) the same way real emission would.

supports_gate_inverse
def supports_gate_inverse(self) -> bool

Force the inverse-by-emission fallback path.

Returns:

bool — Always False.

supports_if_else
def supports_if_else(self) -> bool

Delegate native if/else support to the wrapped emitter.

Returns:

bool — The real emitter’s answer.

supports_reusable_gates
def supports_reusable_gates(self) -> bool

Force the gate-by-gate fallback path.

Returns:

bool — Always False.

supports_while_loop
def supports_while_loop(self) -> bool

Delegate native while-loop support to the wrapped emitter.

Returns:

bool — The real emitter’s answer.


MeasurementMode [source]

class MeasurementMode(Enum)

How an engine handles measurement operations.

Attributes

qamomile.circuit.transpiler.passes.emit_support.gate_emission

Gate emission helper extracted from StandardEmitPass.

Provides emit_gate and resolve_angle as module-level functions so they can be tested and reused independently of the class.

Overview

FunctionDescription
emit_gateEmit a single gate operation.
reject_duplicate_physical_indicesReject a multi-qubit gate whose qubits resolve to the same physical qubit.
resolve_angleResolve angle parameter for rotation gates.
resolve_angle_valueResolve a bare angle Value to a concrete float or engine parameter.
ClassDescription
EmitErrorReport an engine failure to emit one semantic operation.
GateOperationQuantum gate operation.
GateOperationType
OperandResolutionInfoDetailed information about a single operand that failed to resolve.
QubitAddressTyped key for qubit/clbit physical-index maps.
QubitAliasErrorSame qubit used multiple times in one operation.
QubitIndexResolutionErrorError when qubit indices cannot be resolved during emission.
ResolutionFailureReasonCategorizes why qubit index resolution failed.
StandardEmitPassStandard emit pass implementation using GateEmitter protocol.
UnifiedValueResolverResolve IR Values to concrete Python values.

Functions

emit_gate [source]

def emit_gate(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: GateOperation,
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> None

Emit a single gate operation.


reject_duplicate_physical_indices [source]

def reject_duplicate_physical_indices(
    gate_label: str,
    physical_indices: list[int],
    operand_names: list[str] | None = None,
) -> None

Reject a multi-qubit gate whose qubits resolve to the same physical qubit.

A multi-qubit gate (cx / cz / swap / toffoli and any controlled block such as qmc.control(...)) is physically defined only on distinct qubits. The frontend’s _check_qubit_alias already rejects the scalar cx(q, q) case by logical_id at trace time, but symbolic array indices — cx(qs[i], qs[j]) where i == j only at runtime, or two loop-variable indices that coincide after unrolling — resolve to the same physical qubit only at emit time. Without this check the duplicate reaches the engine as a raw, engine-specific failure (Qiskit CircuitError: 'duplicate qubit arguments', a CUDA-Q simulator crash, or — on an engine that does not validate — a silently ill-defined gate). Raising a Qamomile QubitAliasError gives one actionable, engine-independent diagnostic.

This is the shared checker used both for native gates (emit_gate via _reject_aliased_operands) and for controlled / composite blocks (the append_gate sites in controlled_emission), so the same diagnostic covers every multi-qubit emission path on every engine.

Parameters:

NameTypeDescription
gate_labelstrHuman-readable name of the gate for the message (e.g. "CX" or "controlled gate").
physical_indiceslist[int]The resolved physical qubit indices the gate acts on, in operand order.
operand_nameslist[str] | NoneOptional display names aligned with physical_indices (e.g. ["qs[i]", "qs[j]"]). When absent, the message falls back to qubit<index>. Defaults to None.

Returns:

None — None

Raises:


resolve_angle [source]

def resolve_angle(
    emit_pass: 'StandardEmitPass',
    op: GateOperation,
    bindings: dict[str, Any],
) -> float | Any

Resolve angle parameter for rotation gates.

The angle is always a Value stored as the last operand of a rotation gate.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass providing parameter resolution and creation.
opGateOperationRotation gate whose angle is resolved.
bindingsdict[str, Any]Active compile-time bindings.

Returns:

float | Any — float | Any: Concrete angle or engine parameter expression.

Raises:


resolve_angle_value [source]

def resolve_angle_value(
    emit_pass: 'StandardEmitPass',
    theta: Any,
    bindings: dict[str, Any],
) -> float | Any

Resolve a bare angle Value to a concrete float or engine parameter.

Shared core of :func:resolve_angle so operations carrying a standalone angle Value reuse the exact same resolution order as rotation-gate thetas.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass providing the resolver and engine-parameter factory.
thetaAnyAngle Value to resolve.
bindingsdict[str, Any]Active compile-time bindings.

Returns:

float | Any — float | Any: A concrete float when the angle is bound, or a engine parameter expression when it stays symbolic.

Raises:

Classes

EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return
Constructor
def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

GateOperation [source]

class GateOperation(Operation)

Quantum gate operation.

For rotation gates (RX, RY, RZ, P, CP, RZZ), the angle parameter is stored as the last element of operands. Use the theta property for typed read access and the rotation / fixed factory class-methods for type-safe construction.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    gate_type: GateOperationType | None = None,
) -> None
Attributes
Methods
fixed
@classmethod
def fixed(
    cls,
    gate_type: GateOperationType,
    qubits: list[Value],
    results: list[Value],
) -> 'GateOperation'

Create a fixed gate (H, X, CX, SWAP, …) with no angle parameter.

rotation
@classmethod
def rotation(
    cls,
    gate_type: GateOperationType,
    qubits: list[Value],
    theta: Value,
    results: list[Value],
) -> 'GateOperation'

Create a rotation gate (RX, RY, RZ, P, CP, RZZ) with an angle.


GateOperationType [source]

class GateOperationType(enum.Enum)
Attributes

OperandResolutionInfo [source]

class OperandResolutionInfo

Detailed information about a single operand that failed to resolve.

Constructor
def __init__(
    self,
    operand_name: str,
    operand_uuid: str,
    is_array_element: bool,
    parent_array_name: str | None,
    element_indices_names: list[str],
    failure_reason: ResolutionFailureReason,
    failure_details: str,
) -> None
Attributes

QubitAddress [source]

class QubitAddress

Typed key for qubit/clbit physical-index maps.

For scalar qubits: QubitAddress(uuid="abc123") For array elements: QubitAddress(uuid="abc123", element_index=2)

This replaces the f"{uuid}_{i}" string key pattern throughout the emit pipeline, making the key format explicit and preventing format-string bugs.

Constructor
def __init__(self, uuid: str, element_index: int | None = None) -> None
Attributes
Methods
from_composite_key
@classmethod
def from_composite_key(cls, key: str) -> QubitAddress

Parse a legacy composite key string into a QubitAddress.

The frontend stores qubit references as composite strings in the format "{array_uuid}_{element_index}" (e.g., cast operation qubit mappings, element UUIDs). This helper converts such strings to proper QubitAddress instances.

If the key does not match the composite format (i.e., the suffix after the last _ is not a non-negative integer), it is treated as a plain scalar UUID.

matches_array
def matches_array(self, array_uuid: str) -> bool

True if this address belongs to the given array.

with_element
def with_element(self, index: int) -> QubitAddress

Create an array-element address from this array’s base UUID.


QubitAliasError [source]

class QubitAliasError(AffineTypeError)

Same qubit used multiple times in one operation.

Operations like cx() require distinct qubits for control and target. Using the same qubit in both positions is physically impossible and indicates a programming error.

Example of incorrect code:

q1, q2 = qm.cx(q, q) # ERROR: same qubit as control and target

Correct code:

q1, q2 = qm.cx(control, target) # Use distinct qubits


QubitIndexResolutionError [source]

class QubitIndexResolutionError(EmitError)

Error when qubit indices cannot be resolved during emission.

This error provides detailed diagnostic information about why qubit index resolution failed and suggests remediation steps.

Constructor
def __init__(
    self,
    gate_type: str,
    operand_infos: list[OperandResolutionInfo],
    available_bindings_keys: list[str],
    available_qubit_map_keys: list[str],
)

Initialize detailed qubit-index resolution diagnostics.

Parameters:

NameTypeDescription
gate_typestrGate whose operands could not be resolved.
operand_infoslist[OperandResolutionInfo]Per-operand failure details.
available_bindings_keyslist[str]Binding names visible during resolution.
available_qubit_map_keyslist[str]Qubit-map keys visible during resolution.
Attributes

ResolutionFailureReason [source]

class ResolutionFailureReason(Enum)

Categorizes why qubit index resolution failed.

Attributes

StandardEmitPass [source]

class StandardEmitPass(EmitPass[T], Generic[T])

Standard emit pass implementation using GateEmitter protocol.

This class provides orchestration for semantic IR traversal while delegating circuit instruction construction to a GateEmitter. The concrete compiler use is CircuitLoweringPass; SDK targets materialize its immutable result instead of subclassing this class.

Parameters:

NameTypeDescription
gate_emitterGateEmitter[T]Instruction builder used during the semantic traversal.
bindingsdict[str, Any] | NoneCompile-time parameter bindings.
parameterslist[str] | NoneParameter names preserved at runtime.
composite_emitterslist[CompositeGateEmitter[T]] | NoneOptional callable-preservation or lowering hooks.
engine_namestr | NoneDiagnostic name for the traversal target.
Constructor
def __init__(
    self,
    gate_emitter: GateEmitter[T],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
    composite_emitters: list[CompositeGateEmitter[T]] | None = None,
    engine_name: str | None = None,
)
Attributes

ValueResolver [source]

class ValueResolver

Resolve IR Values to concrete Python values.

Parameters:

NameTypeDescription
contextdict[str, Any] | NoneUUID-keyed map of already resolved values. The values may be either raw Python scalars or Value objects; if a Value is found its get_const() is extracted automatically.
bindingsdict[str, Any] | NoneName-keyed parameter bindings supplied by the user at transpile time.
Constructor
def __init__(
    self,
    context: dict[str, Any] | None = None,
    bindings: dict[str, Any] | None = None,
)

Create a resolver with optional context and bindings.

Parameters:

NameTypeDescription
contextdict[str, Any] | NoneUUID-keyed map of already-resolved values. Defaults to None.
bindingsdict[str, Any] | NoneName-keyed parameter bindings supplied by the user. Defaults to None.
Methods
resolve
def resolve(self, value: Any) -> Any | None

Resolve a Value-like object to a concrete Python value.

If value is not a Value-like object (no uuid attribute) it is returned as-is — the caller already has a concrete value.

Parameters:

NameTypeDescription
valueAnyThe Value-like object or already concrete value to resolve.

Returns:

Any | None — Any | None: The resolved concrete value, the original concrete value for non-Value inputs, or None when no resolution rule applies.


qamomile.circuit.transpiler.passes.emit_support.global_phase_emission

Emit zero-qubit global-phase operations.

Overview

FunctionDescription
emit_controlled_global_phaseEmit the relative phase produced by controlling a global phase.
emit_controlled_global_phase_operationEmit a global phase as a relative phase under accumulated controls.
emit_global_phaseEmit a standalone phase when the lowering adapter collects it.
emit_resolved_global_phaseEmit an already resolved standalone phase without discarding it.
is_exact_real_zeroReturn whether a value is a concrete real scalar equal to zero.
is_identity_phase_angleReturn whether a concrete angle is exactly zero modulo two pi.
resolve_angle_valueResolve a bare angle Value to a concrete float or engine parameter.
ClassDescription
EmitErrorReport an engine failure to emit one semantic operation.
GateOperationType
GlobalPhaseOperationMultiply the complete quantum state by exp(i * phase).
StandardEmitPassStandard emit pass implementation using GateEmitter protocol.

Functions

emit_controlled_global_phase [source]

def emit_controlled_global_phase(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    control_indices: list[int],
    angle: Any,
) -> None

Emit the relative phase produced by controlling a global phase.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
control_indiceslist[int]Physical controls gating the phase.
angleAnyResolved phase angle.

Raises:


emit_controlled_global_phase_operation [source]

def emit_controlled_global_phase_operation(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: GlobalPhaseOperation,
    control_indices: list[int],
    bindings: dict[str, Any],
) -> None

Emit a global phase as a relative phase under accumulated controls.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyCircuit representation being emitted into.
opGlobalPhaseOperationGlobal-phase operation to control.
control_indiceslist[int]Accumulated physical control qubits.
bindingsdict[str, Any]Active emit bindings.

Raises:


emit_global_phase [source]

def emit_global_phase(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: GlobalPhaseOperation,
    bindings: dict[str, Any],
) -> None

Emit a standalone phase when the lowering adapter collects it.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyCircuit representation being emitted into.
opGlobalPhaseOperationGlobal-phase operation to emit.
bindingsdict[str, Any]Active emit bindings.

Raises:


emit_resolved_global_phase [source]

def emit_resolved_global_phase(emit_pass: 'StandardEmitPass', circuit: Any, angle: Any) -> None

Emit an already resolved standalone phase without discarding it.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyCircuit representation being emitted into.
angleAnyResolved phase angle.

Raises:


is_exact_real_zero [source]

def is_exact_real_zero(value: Any) -> bool

Return whether a value is a concrete real scalar equal to zero.

The comparison intentionally has no tolerance: a tiny nonzero value must remain observable, while engine parameter expressions remain unresolved.

Parameters:

NameTypeDescription
valueAnyConcrete numeric value or engine parameter expression.

Returns:

bool — True only for a non-boolean real scalar exactly equal to bool — zero.


is_identity_phase_angle [source]

def is_identity_phase_angle(angle: Any) -> bool

Return whether a concrete angle is exactly zero modulo two pi.

The test intentionally uses no tolerance so a tiny but nonzero phase is never discarded. Runtime parameter expressions remain non-identity until an engine resolves them to a concrete number.

Parameters:

NameTypeDescription
angleAnyResolved numeric angle or engine parameter expression.

Returns:

bool — Whether angle is a finite real number exactly congruent to bool — zero modulo 2 * pi.


resolve_angle_value [source]

def resolve_angle_value(
    emit_pass: 'StandardEmitPass',
    theta: Any,
    bindings: dict[str, Any],
) -> float | Any

Resolve a bare angle Value to a concrete float or engine parameter.

Shared core of :func:resolve_angle so operations carrying a standalone angle Value reuse the exact same resolution order as rotation-gate thetas.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass providing the resolver and engine-parameter factory.
thetaAnyAngle Value to resolve.
bindingsdict[str, Any]Active compile-time bindings.

Returns:

float | Any — float | Any: A concrete float when the angle is bound, or a engine parameter expression when it stays symbolic.

Raises:

Classes

EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return
Constructor
def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

GateOperationType [source]

class GateOperationType(enum.Enum)
Attributes

GlobalPhaseOperation [source]

class GlobalPhaseOperation(Operation)

Multiply the complete quantum state by exp(i * phase).

Global phase has no target qubit and does not create a new quantum value. Keeping the phase as the operation’s sole ordinary operand lets generic IR passes substitute, serialize, and analyze it without a special value-field protocol. A surrounding controlled-unitary lowering turns the operation into an observable phase gate on the accumulated controls.

Parameters:

NameTypeDescription
operandslist[Value]Exactly one scalar FloatType phase angle in radians.
resultslist[Value]Must be empty because global phase changes no qubit identity.

Raises:

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

StandardEmitPass [source]

class StandardEmitPass(EmitPass[T], Generic[T])

Standard emit pass implementation using GateEmitter protocol.

This class provides orchestration for semantic IR traversal while delegating circuit instruction construction to a GateEmitter. The concrete compiler use is CircuitLoweringPass; SDK targets materialize its immutable result instead of subclassing this class.

Parameters:

NameTypeDescription
gate_emitterGateEmitter[T]Instruction builder used during the semantic traversal.
bindingsdict[str, Any] | NoneCompile-time parameter bindings.
parameterslist[str] | NoneParameter names preserved at runtime.
composite_emitterslist[CompositeGateEmitter[T]] | NoneOptional callable-preservation or lowering hooks.
engine_namestr | NoneDiagnostic name for the traversal target.
Constructor
def __init__(
    self,
    gate_emitter: GateEmitter[T],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
    composite_emitters: list[CompositeGateEmitter[T]] | None = None,
    engine_name: str | None = None,
)
Attributes

qamomile.circuit.transpiler.passes.emit_support.inverse_emission

Inverse block emission helpers extracted from StandardEmitPass.

Emits :class:InverseBlockOperation with a three-tier strategy: try the engine-native inverse of the forward source_block first (reusable gate + gate_inverse), then a reusable gate built from the implementation_block fallback, and finally inline the fallback gate by gate. Each function takes an emit_pass parameter (a StandardEmitPass instance) in place of self so subclass overrides (e.g. engine emit passes) are respected, mirroring :mod:.controlled_emission.

Overview

FunctionDescription
bracket_control_valueBracket zero-valued controls with target-neutral Pauli-X gates.
emit_inverse_blockEmit a first-class inverse block operation.
emit_inverse_block_at_indicesEmit an inverse block after physical qubits have been resolved.
map_array_result_groupMap an array-valued result to a physical index group.
reject_duplicate_physical_indicesReject a multi-qubit gate whose qubits resolve to the same physical qubit.
ClassDescription
ArrayValueAn array of typed IR values.
EmitErrorReport an engine failure to emit one semantic operation.
InverseBlockOperationRepresent an inverse qkernel/block as a first-class IR operation.
QubitAddressTyped key for qubit/clbit physical-index maps.
StandardEmitPassStandard emit pass implementation using GateEmitter protocol.

Functions

bracket_control_value [source]

def bracket_control_value(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    control_indices: Sequence[int],
    control_value: int | None,
) -> Generator[None, None, None]

Bracket zero-valued controls with target-neutral Pauli-X gates.

The controlled operation inside the context remains an ordinary all-ones control. Controls are interpreted LSB-first in their existing physical order, so bit zero of control_value describes control_indices[0]. One bracket surrounds the complete operation, including integral powers and vector-target broadcast.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass providing the gate emitter.
circuitAnyCircuit receiving the bracket gates.
control_indicesSequence[int]Ordered physical control qubits.
control_valueint | NoneRequired basis value, or None for the ordinary all-ones state.

Yields:

None — Control returns while the zero-valued controls are inverted.

Raises:


emit_inverse_block [source]

def emit_inverse_block(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: InverseBlockOperation,
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> None

Emit a first-class inverse block operation.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
opInverseBlockOperationInverse block operation to emit.
qubit_mapQubitMapCurrent quantum value to physical qubit map.
bindingsdict[str, Any]Active emit bindings.

Raises:


emit_inverse_block_at_indices [source]

def emit_inverse_block_at_indices(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: InverseBlockOperation,
    control_indices: list[int],
    target_indices: list[int],
    bindings: dict[str, Any],
) -> None

Emit an inverse block after physical qubits have been resolved.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
opInverseBlockOperationInverse block operation to emit.
control_indiceslist[int]Physical control qubits in enclosing-first order, followed by this operation’s own controls.
target_indiceslist[int]Physical target qubits.
bindingsdict[str, Any]Active emit bindings.

Raises:


map_array_result_group [source]

def map_array_result_group(result_uuid: str, index_group: list[int], index_map: PhysicalIndexMap) -> None

Map an array-valued result to a physical index group.

Parameters:

NameTypeDescription
result_uuidstrUUID of the array-valued result whose element addresses should be registered.
index_grouplist[int]Physical indices for the result elements, in result-local element order.
index_mapPhysicalIndexMapMutable physical-index map updated in place with element addresses and, when available, the base result address.

reject_duplicate_physical_indices [source]

def reject_duplicate_physical_indices(
    gate_label: str,
    physical_indices: list[int],
    operand_names: list[str] | None = None,
) -> None

Reject a multi-qubit gate whose qubits resolve to the same physical qubit.

A multi-qubit gate (cx / cz / swap / toffoli and any controlled block such as qmc.control(...)) is physically defined only on distinct qubits. The frontend’s _check_qubit_alias already rejects the scalar cx(q, q) case by logical_id at trace time, but symbolic array indices — cx(qs[i], qs[j]) where i == j only at runtime, or two loop-variable indices that coincide after unrolling — resolve to the same physical qubit only at emit time. Without this check the duplicate reaches the engine as a raw, engine-specific failure (Qiskit CircuitError: 'duplicate qubit arguments', a CUDA-Q simulator crash, or — on an engine that does not validate — a silently ill-defined gate). Raising a Qamomile QubitAliasError gives one actionable, engine-independent diagnostic.

This is the shared checker used both for native gates (emit_gate via _reject_aliased_operands) and for controlled / composite blocks (the append_gate sites in controlled_emission), so the same diagnostic covers every multi-qubit emission path on every engine.

Parameters:

NameTypeDescription
gate_labelstrHuman-readable name of the gate for the message (e.g. "CX" or "controlled gate").
physical_indiceslist[int]The resolved physical qubit indices the gate acts on, in operand order.
operand_nameslist[str] | NoneOptional display names aligned with physical_indices (e.g. ["qs[i]", "qs[j]"]). When absent, the message falls back to qubit<index>. Defaults to None.

Returns:

None — None

Raises:

Classes

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:

bool — True iff slice_of is non-None.

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

EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return
Constructor
def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

InverseBlockOperation [source]

class InverseBlockOperation(Operation)

Represent an inverse qkernel/block as a first-class IR operation.

The operation stores both the original forward block and a Qamomile-built inverse implementation block. Emitters may use source_block with a engine-native inverse/adjoint primitive, then fall back to implementation_block when native inversion is unavailable.

Operands are ordered as scalar control qubits, target quantum operands, then classical/object parameters. Results mirror the quantum operand layout: control results first, then one target result per target operand. Vector target operands therefore count as one operand/result while contributing their scalar width to num_target_qubits.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_control_qubits: int = 0,
    num_target_qubits: int = 0,
    custom_name: str = '',
    source_block: Block | None = None,
    implementation_block: Block | None = None,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_value: int | None = None,
) -> None
Attributes

QubitAddress [source]

class QubitAddress

Typed key for qubit/clbit physical-index maps.

For scalar qubits: QubitAddress(uuid="abc123") For array elements: QubitAddress(uuid="abc123", element_index=2)

This replaces the f"{uuid}_{i}" string key pattern throughout the emit pipeline, making the key format explicit and preventing format-string bugs.

Constructor
def __init__(self, uuid: str, element_index: int | None = None) -> None
Attributes
Methods
from_composite_key
@classmethod
def from_composite_key(cls, key: str) -> QubitAddress

Parse a legacy composite key string into a QubitAddress.

The frontend stores qubit references as composite strings in the format "{array_uuid}_{element_index}" (e.g., cast operation qubit mappings, element UUIDs). This helper converts such strings to proper QubitAddress instances.

If the key does not match the composite format (i.e., the suffix after the last _ is not a non-negative integer), it is treated as a plain scalar UUID.

matches_array
def matches_array(self, array_uuid: str) -> bool

True if this address belongs to the given array.

with_element
def with_element(self, index: int) -> QubitAddress

Create an array-element address from this array’s base UUID.


StandardEmitPass [source]

class StandardEmitPass(EmitPass[T], Generic[T])

Standard emit pass implementation using GateEmitter protocol.

This class provides orchestration for semantic IR traversal while delegating circuit instruction construction to a GateEmitter. The concrete compiler use is CircuitLoweringPass; SDK targets materialize its immutable result instead of subclassing this class.

Parameters:

NameTypeDescription
gate_emitterGateEmitter[T]Instruction builder used during the semantic traversal.
bindingsdict[str, Any] | NoneCompile-time parameter bindings.
parameterslist[str] | NoneParameter names preserved at runtime.
composite_emitterslist[CompositeGateEmitter[T]] | NoneOptional callable-preservation or lowering hooks.
engine_namestr | NoneDiagnostic name for the traversal target.
Constructor
def __init__(
    self,
    gate_emitter: GateEmitter[T],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
    composite_emitters: list[CompositeGateEmitter[T]] | None = None,
    engine_name: str | None = None,
)
Attributes

qamomile.circuit.transpiler.passes.emit_support.loop_analyzer

Loop analysis helpers for emission.

Identity policy: loop variables are identified by their IR Value UUID (ForOperation.loop_var_value.uuid), not by their display name. Two nested or sibling loops with identical user-chosen names (e.g. for i in range(N): for i in range(M):) are distinct here because each ForOperation carries its own loop_var_value with a fresh UUID, and UUIDRemapper clones that field consistently with body references via the all_input_values / replace_values protocol.

There is no name fallback: if loop_var_value is None (legacy IR built before the field existed), analysis conservatively requests unrolling and the emit entry point rejects the malformed IR. Comparing by name was the soil for nested-loop name-collision bugs.

Overview

ClassDescription
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
CompOpComparison operation (EQ, NEQ, LT, LE, GT, GE).
CondOpConditional logical operation (AND, OR).
ControlledUOperationBase class for controlled-U operations.
DictGetItemOperationLook up one entry of a Dict by a (possibly symbolic) key.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
GlobalPhaseOperationMultiply the complete quantum state by exp(i * phase).
HasNestedOpsMixin for operations that contain nested operation lists.
IfOperationRepresents an if-else conditional operation.
InverseBlockOperationRepresent an inverse qkernel/block as a first-class IR operation.
InvokeOperationRepresent a composite, stdlib, or oracle call.
LoopAnalyzerAnalyze loop structures to determine an emission strategy.
NotOp
PauliEvolveOpPauli evolution operation: exp(-i * gamma * H).
RuntimeClassicalExprA classical expression known to require runtime evaluation.
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
ValueA typed SSA value in the IR.
WhileOperationRepresents a while loop operation.

Classes

BinOp [source]

class BinOp(BinaryOperationBase)

Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: BinOpKind | None = None,
) -> None
Attributes

CompOp [source]

class CompOp(BinaryOperationBase)

Comparison operation (EQ, NEQ, LT, LE, GT, GE).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CompOpKind | None = None,
) -> None
Attributes

CondOp [source]

class CondOp(BinaryOperationBase)

Conditional logical operation (AND, OR).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CondOpKind | None = None,
) -> None
Attributes

ControlledUOperation [source]

class ControlledUOperation(Operation)

Base class for controlled-U operations.

Two concrete subclasses handle distinct operand layouts:

All isinstance(op, ControlledUOperation) checks match every subclass.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int | Value = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]
replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

DictGetItemOperation [source]

class DictGetItemOperation(Operation)

Look up one entry of a Dict by a (possibly symbolic) key.

This is the IR form of d[key] on a Dict handle. The key components may be symbolic (e.g. loop variables of a for-items loop); the lookup is resolved at emit time when the key values and the dict’s bound data are both concrete.

operands: [DictValue, *key_component_values] results: [looked-up scalar value]

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_arity: int = 1,
) -> None
Attributes

ForItemsOperation [source]

class ForItemsOperation(HasNestedOps, Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    key_var_values: tuple[Value, ...] | None = None,
    value_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include the per-key/value Value fields for cloning/substitution.

Same rationale as ForOperation.all_input_values: keep the IR identity fields in lockstep with body references so UUID-keyed lookups stay valid after inline cloning. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the items-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing key/value formals, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the items-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt items-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

GlobalPhaseOperation [source]

class GlobalPhaseOperation(Operation)

Multiply the complete quantum state by exp(i * phase).

Global phase has no target qubit and does not create a new quantum value. Keeping the phase as the operation’s sole ordinary operand lets generic IR passes substitute, serialize, and analyze it without a special value-field protocol. A surrounding controlled-unitary lowering turns the operation into an observable phase gate on the accumulated controls.

Parameters:

NameTypeDescription
operandslist[Value]Exactly one scalar FloatType phase angle in radians.
resultslist[Value]Must be empty because global phase changes no qubit identity.

Raises:

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


InverseBlockOperation [source]

class InverseBlockOperation(Operation)

Represent an inverse qkernel/block as a first-class IR operation.

The operation stores both the original forward block and a Qamomile-built inverse implementation block. Emitters may use source_block with a engine-native inverse/adjoint primitive, then fall back to implementation_block when native inversion is unavailable.

Operands are ordered as scalar control qubits, target quantum operands, then classical/object parameters. Results mirror the quantum operand layout: control results first, then one target result per target operand. Vector target operands therefore count as one operand/result while contributing their scalar width to num_target_qubits.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_control_qubits: int = 0,
    num_target_qubits: int = 0,
    custom_name: str = '',
    source_block: Block | None = None,
    implementation_block: Block | None = None,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_value: int | None = None,
) -> None
Attributes

InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.
Constructor
def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes
Methods
body_for_transform
def body_for_transform(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> tuple[Block | None, CallTransform]

Select a body and report the transform it already realizes.

A controlled-inverse invocation may reuse an explicitly registered inverse body when no implementation realizes both transforms. Keeping that fallback in the IR operation gives emitters and static analyses one selection rule while still letting each consumer apply the remaining coherent controls in its own representation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — tuple[Block | None, CallTransform]: Selected body and the transform CallTransform — already implemented by that body. The callable’s direct body is tuple[Block | None, CallTransform] — returned with DIRECT when no transform-specific body matches.

Raises:

effective_body
def effective_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — Block | None: Selected implementation body, or the callable’s Block | None — default body when no transform-specific implementation exists. Block | None — A compiler may synthesize inverse or controlled behavior from this Block | None — fallback body.

implementation_for
def implementation_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None, which only selects engine-generic implementations.
strategystr | NoneStrategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation candidate, CallableImplementation | None — or None when the callable definition has no match.

measurement_result_indices_for
def measurement_result_indices_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> frozenset[int]

Return measurement-derived results for one selected implementation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name used for implementation selection. Defaults to None.
strategystr | NoneStrategy name used for implementation selection. Defaults to the invocation’s strategy_name.

Returns:

frozenset[int] — frozenset[int]: Caller-local result positions derived from measurement in the selected body.

Raises:

select_body
def select_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> CallableBodySelection

Select and validate the composable body for this invocation.

The result carries the transform already realized by the body and the exact call-site values that bind to it. Consumers therefore cannot independently disagree about whether an invocation’s control prefix belongs to the selected implementation ABI.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

CallableBodySelection — Validated body, realized transform, and CallableBodySelection — aligned call-site operands and results.

Raises:


LoopAnalyzer [source]

class LoopAnalyzer

Analyze loop structures to determine an emission strategy.

Methods
should_unroll
def should_unroll(self, op: ForOperation, bindings: dict[str, object]) -> bool

Determine whether a for-loop requires emit-time unrolling.

Parameters:

NameTypeDescription
opForOperationLoop to analyze.
bindingsdict[str, object]Compile-time bindings available to nested-bound analysis.

Returns:

bool — True when identities, carries, indices, predicates, dictionary lookups, structural body parameters, or nested bounds require concrete per-iteration evaluation.


NotOp [source]

class NotOp(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

PauliEvolveOp [source]

class PauliEvolveOp(Operation)

Pauli evolution operation: exp(-i * gamma * H).

This operation applies the time evolution of a Pauli Hamiltonian to a quantum register.

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

RuntimeClassicalExpr [source]

class RuntimeClassicalExpr(Operation)

A classical expression known to require runtime evaluation.

Lowered from CompOp / CondOp / NotOp / BinOp by ClassicalLoweringPass when the op’s operand dataflow traces back to a MeasureOperation (i.e. cannot be folded at compile-time, by emit-time loop unrolling, or by compile_time_if_lowering). Engine emit translates this 1:1 to an engine-native runtime expression (e.g. qiskit.circuit.classical.expr.Expr).

Operand convention:

The single-node + unified-kind shape (vs four parallel subclasses) keeps the engine dispatch a single match op.kind instead of four parallel hooks, and makes the IR self-documenting: a single RuntimeClassicalExpr instance signals “runtime evaluation required” regardless of which classical family it came from.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: RuntimeOpKind | None = None,
) -> None
Attributes

SelectOperation [source]

class SelectOperation(Operation)

Quantum multiplexer: apply case_blocks[i] when the index reads i.

Concrete operand layout: [idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...]. Symbolic-width operand layout: [idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...]. Results mirror the quantum operand grouping.

A concrete index register is normalized to one scalar Qubit operand per physical index qubit. A symbolic-width register instead retains each leading caller argument as one scalar or array operand until its bound shape is known. Whole-Vector[Qubit] / scalar targets follow and keep their shapes, and classical parameters shared across every case come last.

Index bit order is LSB-first: idx_0 is the least-significant bit, matching Qamomile’s qubit-zero convention. Case i is selected when index qubit j reads bit j of i. len(case_blocks) need not be a power of two; index values >= len(case_blocks) apply no operation (identity).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_index_qubits: int | Value = 0,
    case_blocks: list[Block] = list(),
    num_index_args: int = 0,
    case_callable_attrs: list[dict[str, Any]] = list(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Return every value consumed by the SELECT operation.

Returns:

list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width value when present.

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed replacement values.

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


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 engine resource allocation. This applies to every Value regardless of its type (Qubit, Float, Bit, ...) -- it is not specific to qubits.


WhileOperation [source]

class WhileOperation(HasNestedOps, Operation)

Represents a while loop operation.

Only measurement-backed conditions are supported: the condition must be a Bit value produced by qmc.measure(). Non-measurement conditions (classical variables, constants, comparisons) are rejected by ValidateWhileContractPass before reaching engine emit.

Example::

bit = qmc.measure(q)
while bit:
    q = qmc.h(q)
    bit = qmc.measure(q)
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    operations: list[Operation] = list(),
    max_iterations: int | None = None,
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include rebind records and region args for cloning/substitution.

Same rationale as ForOperation.all_input_values: rebind records and region arguments reference body/pre-loop values by identity, so inline cloning must remap them in lockstep with body operands.

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus rebind-record and region-argument values.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the while body with explicit boundary values.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region whose block arguments and yields are aligned with region_args. The updated condition, when present, is appended as the final yield.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the while body and its complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt while operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, rebind-record, and region-arg values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


qamomile.circuit.transpiler.passes.emit_support.measurement_emission

Measurement emission helpers extracted from StandardEmitPass.

Provides emit_measure, emit_measure_vector and emit_measure_qfixed as module-level functions.

Overview

FunctionDescription
emit_measureEmit a single measurement.
emit_measure_qfixedEmit QFixed measurement.
emit_measure_vectorEmit vector measurement.
ClassDescription
ArrayValueAn array of typed IR values.
EmitErrorReport an engine failure to emit one semantic operation.
MeasureOperation
MeasureQFixedOperationMeasure a quantum fixed-point number.
MeasureVectorOperationMeasure a vector of qubits.
MeasurementModeHow an engine handles measurement operations.
QubitAddressTyped key for qubit/clbit physical-index maps.
StandardEmitPassStandard emit pass implementation using GateEmitter protocol.

Functions

emit_measure [source]

def emit_measure(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: MeasureOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any] | None = None,
) -> None

Emit a single measurement.

Resolves the qubit operand using the full resolver (handles both scalar qubits and array element qubits with composite keys).

Raises:


emit_measure_qfixed [source]

def emit_measure_qfixed(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: MeasureQFixedOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
) -> None

Emit QFixed measurement.


emit_measure_vector [source]

def emit_measure_vector(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: MeasureVectorOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
) -> None

Emit vector measurement.

Resolves the qubit operand’s slice_of chain so that measuring a view (measure(q[1::2])) correctly targets the root parent’s physical qubits.

Behaviour for unresolvable inputs differs by case:

Raises:

Classes

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:

bool — True iff slice_of is non-None.

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

EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return
Constructor
def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

MeasureOperation [source]

class MeasureOperation(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

MeasureQFixedOperation [source]

class MeasureQFixedOperation(Operation)

Measure a quantum fixed-point number.

This operation measures all qubits in a QFixed register and produces a Float result. During transpilation, this is lowered to individual MeasureOperations plus a DecodeQFixedOperation.

operands: [QFixed value (contains qubit_values in params)] results: [Float value]

Encoding:

For QPE phase (int_bits=0): Qubits are stored least-significant first. For n qubits, bit i has weight 2**(-n + i).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_bits: int = 0,
    int_bits: int = 0,
) -> None
Attributes

MeasureVectorOperation [source]

class MeasureVectorOperation(Operation)

Measure a vector of qubits.

Takes a Vector[Qubit] (ArrayValue) and produces a Vector[Bit] (ArrayValue). This operation measures all qubits in the vector as a single operation.

operands: [ArrayValue of qubits] results: [ArrayValue of bits]

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

MeasurementMode [source]

class MeasurementMode(Enum)

How an engine handles measurement operations.

Attributes

QubitAddress [source]

class QubitAddress

Typed key for qubit/clbit physical-index maps.

For scalar qubits: QubitAddress(uuid="abc123") For array elements: QubitAddress(uuid="abc123", element_index=2)

This replaces the f"{uuid}_{i}" string key pattern throughout the emit pipeline, making the key format explicit and preventing format-string bugs.

Constructor
def __init__(self, uuid: str, element_index: int | None = None) -> None
Attributes
Methods
from_composite_key
@classmethod
def from_composite_key(cls, key: str) -> QubitAddress

Parse a legacy composite key string into a QubitAddress.

The frontend stores qubit references as composite strings in the format "{array_uuid}_{element_index}" (e.g., cast operation qubit mappings, element UUIDs). This helper converts such strings to proper QubitAddress instances.

If the key does not match the composite format (i.e., the suffix after the last _ is not a non-negative integer), it is treated as a plain scalar UUID.

matches_array
def matches_array(self, array_uuid: str) -> bool

True if this address belongs to the given array.

with_element
def with_element(self, index: int) -> QubitAddress

Create an array-element address from this array’s base UUID.


StandardEmitPass [source]

class StandardEmitPass(EmitPass[T], Generic[T])

Standard emit pass implementation using GateEmitter protocol.

This class provides orchestration for semantic IR traversal while delegating circuit instruction construction to a GateEmitter. The concrete compiler use is CircuitLoweringPass; SDK targets materialize its immutable result instead of subclassing this class.

Parameters:

NameTypeDescription
gate_emitterGateEmitter[T]Instruction builder used during the semantic traversal.
bindingsdict[str, Any] | NoneCompile-time parameter bindings.
parameterslist[str] | NoneParameter names preserved at runtime.
composite_emitterslist[CompositeGateEmitter[T]] | NoneOptional callable-preservation or lowering hooks.
engine_namestr | NoneDiagnostic name for the traversal target.
Constructor
def __init__(
    self,
    gate_emitter: GateEmitter[T],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
    composite_emitters: list[CompositeGateEmitter[T]] | None = None,
    engine_name: str | None = None,
)
Attributes

qamomile.circuit.transpiler.passes.emit_support.multi_control_ancilla

Clean-ancilla planning for the shared multi-controlled decomposition.

Engines without a native multi-controlled gate primitive lower an irreducible n-controlled single-qubit gate through the standard Toffoli-cascade construction (arXiv:2307.07478, Appendix A.3): the logical AND of all n controls is accumulated onto n - 1 clean ancilla qubits with a cascade of Toffoli gates, the gate is applied once under a single control (the last ancilla), and the cascade is uncomputed in reverse. Every ancilla therefore returns to |0> and the same pool can be reused by every multi-controlled gate in the segment.

Engine circuits are created with a fixed qubit count before emission starts, so the pool must be sized up front. Its size is measured by a count-only dry-run of the real emission (see StandardEmitPass._count_multi_control_ancilla_demand and counting_emitter.CountingEmitter): the same walk the real emission runs is executed against a no-op emitter and a counting pool that records peak concurrent usage, so the size can never drift from what the emitter actually does. This module provides only :class:MultiControlAncillaPool — the reserved (or counting) block of physical qubit indices appended after the segment’s data qubits.

The pool has stack discipline (a moving offset) so leaf cascades and the AND ladders that batched controlled-block emission holds via :meth:MultiControlAncillaPool.try_hold draw from disjoint ranges. Under counting the pool is unbounded and only records the peak, which is an upper bound of real usage because the dry run biases capability answers toward the cascade path; a shortfall in a real (bounded) pool would mean the count under-measured and is reported as a compiler bug at emit time by StandardEmitPass._emit_irreducible_multi_controlled_gate.

Overview

ClassDescription
MultiControlAncillaPoolA reserved block of clean ancilla qubits for multi-control lowering.

Classes

MultiControlAncillaPool [source]

class MultiControlAncillaPool

A reserved block of clean ancilla qubits for multi-control lowering.

The pool occupies a contiguous range of physical qubit indices appended after a quantum segment’s data qubits. A single moving _offset gives it stack discipline so nested users never collide:

Constructor
def __init__(self, first_index: int, count: int, *, counting: bool = False) -> None

Initialize the pool.

Parameters:

NameTypeDescription
first_indexintPhysical index of the first reserved ancilla qubit.
countintNumber of reserved ancilla qubits. Must be non-negative. Ignored in counting mode.
countingboolWhen True the pool is unbounded and only records the peak concurrent usage (take / try_hold never fail), so a dry-run emission can measure how many ancillas a real emission would need. Defaults to False.

Raises:

Attributes
Methods
take
def take(self, count: int) -> list[int] | None

Return count clean ancilla indices from the current offset.

Parameters:

NameTypeDescription
countintNumber of ancilla qubits requested.

Returns:

list[int] | None — list[int] | None: The next count reserved physical indices starting at the current offset, or None when the unheld remainder of the pool is smaller than the request (an estimation bug surfaced by the caller). In counting mode the request always succeeds and the peak usage is recorded instead.

Raises:

try_hold
def try_hold(self, count: int) -> Iterator[list[int] | None]

Reserve count ancillas for the duration of a with block.

Used by batched controlled-block emission to keep an AND ladder live while the block body is walked under a single control. The offset advances so that take/try_hold calls made inside the body draw from the qubits after the held range, and it is rewound on exit (including on exception) so sibling batches reuse the same range. When the unheld remainder cannot satisfy the request the caller receives None and must fall back to per-gate emission rather than treating it as an error — the demand estimate legitimately reserves fewer ancillas than a naive batch would want (e.g. a statically empty loop body).

Parameters:

NameTypeDescription
countintNumber of contiguous ancilla qubits to hold.

Yields:

list[int] | None — list[int] | None: The held physical indices, or None when the unheld remainder is too small to satisfy the request.


qamomile.circuit.transpiler.passes.emit_support.multi_control_gate_emission

Lower primitive gates with one or more quantum controls.

Overview

FunctionDescription
clean_ancilla_toffoli_ladderReturn the arithmetic for the named clean-ancilla recipe.
emit_controlled_gateEmit a controlled version of a gate.
emit_multi_controlled_gateEmit one gate under an arbitrary number of accumulated controls.
emit_multi_controlled_on_clean_ancillasLower an irreducible multi-controlled gate via a Toffoli cascade.
emit_single_controlled_primitiveEmit one singly-controlled single-qubit gate from a resolved angle.
reject_duplicate_physical_indicesReject a multi-qubit gate whose qubits resolve to the same physical qubit.
ClassDescription
EmitErrorReport an engine failure to emit one semantic operation.
GateOperationQuantum gate operation.
GateOperationType
StandardEmitPassStandard emit pass implementation using GateEmitter protocol.

Functions

clean_ancilla_toffoli_ladder [source]

def clean_ancilla_toffoli_ladder(num_controls: int | sp.Expr) -> CleanAncillaToffoliLadder[Any]

Return the arithmetic for the named clean-ancilla recipe.

The caller owns recipe selection and must use the result on a branch where at least two controls are active. Keeping validation outside this helper lets symbolic resource expressions construct inactive Piecewise branches without prematurely rejecting them.

Parameters:

NameTypeDescription
num_controlsint | sp.ExprConcrete or symbolic control count.

Returns:

CleanAncillaToffoliLadder[Any] — CleanAncillaToffoliLadder[Any]: Compute, total-Toffoli, and clean- ancilla requirements in the same numeric domain as the input.


emit_controlled_gate [source]

def emit_controlled_gate(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: GateOperation,
    control_idx: int,
    target_indices: list[int],
    bindings: dict[str, Any],
) -> None

Emit a controlled version of a gate.

Resolves the rotation angle for rotation-like gates and dispatches single-target gate kinds through :func:emit_single_controlled_primitive; SWAP is lowered here via its Fredkin conjugation because it needs two targets.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
opGateOperationGate operation to control.
control_idxintPhysical control qubit.
target_indiceslist[int]Physical qubits for the gate’s own operands, in operand order. An empty list is a no-op.
bindingsdict[str, Any]Bindings used to resolve rotation angles.

Raises:


emit_multi_controlled_gate [source]

def emit_multi_controlled_gate(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: GateOperation,
    control_indices: list[int],
    target_indices: list[int],
    bindings: dict[str, Any],
) -> None

Emit one gate under an arbitrary number of accumulated controls.

Structurally reduces multi-qubit gate types to single-target forms by absorbing their own control qubits into the control set (CX -> X, CZ -> Z, CP -> P, TOFFOLI -> X; SWAP and RZZ via their standard CX conjugations), then emits:

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass. Subclass overrides of _emit_irreducible_multi_controlled_gate are respected for the irreducible tail.
circuitAnyEngine circuit being emitted into.
opGateOperationGate operation whose operands are already resolved to target_indices.
control_indiceslist[int]Physical control qubits. Must be non-empty.
target_indiceslist[int]Physical qubits for the gate’s own operands, in operand order.
bindingsdict[str, Any]Bindings used to resolve rotation angles.

Raises:


emit_multi_controlled_on_clean_ancillas [source]

def emit_multi_controlled_on_clean_ancillas(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    gate_type: GateOperationType,
    control_indices: list[int],
    target_idx: int,
    angle: Any,
    ancilla_indices: list[int],
) -> None

Lower an irreducible multi-controlled gate via a Toffoli cascade.

Implements the standard clean-ancilla construction (arXiv:2307.07478, Appendix A.3): the logical AND of the n controls is accumulated onto n - 1 clean ancillas with a cascade of Toffoli gates, the gate is applied once under a single control (the last ancilla) through :func:emit_single_controlled_primitive, and the cascade is uncomputed in reverse order. The cost is 2 * (n - 1) Toffoli gates plus one singly-controlled gate, and every ancilla returns to |0>, so the same pool may be reused by subsequent gates.

Unlike a dense 2**(n+1) unitary-matrix lowering, this scales linearly in the control count and keeps rotation angles symbolic, so runtime-parametric multi-controlled rotations are supported.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
gate_typeGateOperationTypeSingle-qubit gate kind to apply under the controls.
control_indiceslist[int]Physical control qubits; at least two.
target_idxintPhysical target qubit.
angleAnyResolved rotation angle (concrete number or engine parameter expression) for rotation-like gates, or None for fixed gates.
ancilla_indiceslist[int]Clean (|0>) ancilla qubits; at least len(control_indices) - 1 entries.

Raises:


emit_single_controlled_primitive [source]

def emit_single_controlled_primitive(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    gate_type: GateOperationType | None,
    control_idx: int,
    target_idx: int,
    angle: Any,
) -> None

Emit one singly-controlled single-qubit gate from a resolved angle.

This is the single-control dispatch shared by :func:emit_controlled_gate (which resolves the angle from the IR operation first) and the Toffoli-cascade lowering of irreducible multi-controlled gates (which arrives with the angle already resolved). Fixed phase-family gates (S / T and daggers) are emitted as controlled phases.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
gate_typeGateOperationType | NoneSingle-qubit gate kind. None (a gate operation without a type) is rejected like any other unsupported kind.
control_idxintPhysical control qubit.
target_idxintPhysical target qubit.
angleAnyResolved rotation angle (concrete number or engine parameter expression) for P / RX / RY / RZ; ignored for fixed gates.

Raises:


reject_duplicate_physical_indices [source]

def reject_duplicate_physical_indices(
    gate_label: str,
    physical_indices: list[int],
    operand_names: list[str] | None = None,
) -> None

Reject a multi-qubit gate whose qubits resolve to the same physical qubit.

A multi-qubit gate (cx / cz / swap / toffoli and any controlled block such as qmc.control(...)) is physically defined only on distinct qubits. The frontend’s _check_qubit_alias already rejects the scalar cx(q, q) case by logical_id at trace time, but symbolic array indices — cx(qs[i], qs[j]) where i == j only at runtime, or two loop-variable indices that coincide after unrolling — resolve to the same physical qubit only at emit time. Without this check the duplicate reaches the engine as a raw, engine-specific failure (Qiskit CircuitError: 'duplicate qubit arguments', a CUDA-Q simulator crash, or — on an engine that does not validate — a silently ill-defined gate). Raising a Qamomile QubitAliasError gives one actionable, engine-independent diagnostic.

This is the shared checker used both for native gates (emit_gate via _reject_aliased_operands) and for controlled / composite blocks (the append_gate sites in controlled_emission), so the same diagnostic covers every multi-qubit emission path on every engine.

Parameters:

NameTypeDescription
gate_labelstrHuman-readable name of the gate for the message (e.g. "CX" or "controlled gate").
physical_indiceslist[int]The resolved physical qubit indices the gate acts on, in operand order.
operand_nameslist[str] | NoneOptional display names aligned with physical_indices (e.g. ["qs[i]", "qs[j]"]). When absent, the message falls back to qubit<index>. Defaults to None.

Returns:

None — None

Raises:

Classes

EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return
Constructor
def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

GateOperation [source]

class GateOperation(Operation)

Quantum gate operation.

For rotation gates (RX, RY, RZ, P, CP, RZZ), the angle parameter is stored as the last element of operands. Use the theta property for typed read access and the rotation / fixed factory class-methods for type-safe construction.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    gate_type: GateOperationType | None = None,
) -> None
Attributes
Methods
fixed
@classmethod
def fixed(
    cls,
    gate_type: GateOperationType,
    qubits: list[Value],
    results: list[Value],
) -> 'GateOperation'

Create a fixed gate (H, X, CX, SWAP, …) with no angle parameter.

rotation
@classmethod
def rotation(
    cls,
    gate_type: GateOperationType,
    qubits: list[Value],
    theta: Value,
    results: list[Value],
) -> 'GateOperation'

Create a rotation gate (RX, RY, RZ, P, CP, RZZ) with an angle.


GateOperationType [source]

class GateOperationType(enum.Enum)
Attributes

StandardEmitPass [source]

class StandardEmitPass(EmitPass[T], Generic[T])

Standard emit pass implementation using GateEmitter protocol.

This class provides orchestration for semantic IR traversal while delegating circuit instruction construction to a GateEmitter. The concrete compiler use is CircuitLoweringPass; SDK targets materialize its immutable result instead of subclassing this class.

Parameters:

NameTypeDescription
gate_emitterGateEmitter[T]Instruction builder used during the semantic traversal.
bindingsdict[str, Any] | NoneCompile-time parameter bindings.
parameterslist[str] | NoneParameter names preserved at runtime.
composite_emitterslist[CompositeGateEmitter[T]] | NoneOptional callable-preservation or lowering hooks.
engine_namestr | NoneDiagnostic name for the traversal target.
Constructor
def __init__(
    self,
    gate_emitter: GateEmitter[T],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
    composite_emitters: list[CompositeGateEmitter[T]] | None = None,
    engine_name: str | None = None,
)
Attributes

qamomile.circuit.transpiler.passes.emit_support.pauli_evolve_emission

Pauli evolution emission helper for StandardEmitPass.

Extracted from standard_emit.py to isolate the Hamiltonian decomposition logic from the main emit dispatch.

The emit_pauli_evolve function is the default implementation. Engine-specific emit passes (e.g., QiskitEmitPass) may override the corresponding _emit_pauli_evolve method; calling super()._emit_pauli_evolve(...) will ultimately delegate here.

Overview

FunctionDescription
emit_pauli_evolveEmit Pauli evolution: exp(-i * gamma * H).
emit_resolved_global_phaseEmit an already resolved standalone phase without discarding it.
is_exact_real_zeroReturn whether a value is a concrete real scalar equal to zero.
is_zero_evolution_timeReturn whether a resolved evolution time is the numeric identity.
resolve_angle_valueResolve a bare angle Value to a concrete float or engine parameter.
validate_hamiltonian_within_registerValidate that a Hamiltonian fits within the target qubit register.
validate_hermitian_hamiltonianValidate every coefficient before Pauli-evolution emission starts.
ClassDescription
ArrayValueAn array of typed IR values.
EmitErrorReport an engine failure to emit one semantic operation.
HamiltonianRepresents a quantum Hamiltonian as a sum of Pauli operator products.
PauliEvolveOpPauli evolution operation: exp(-i * gamma * H).
QubitAddressTyped key for qubit/clbit physical-index maps.
StandardEmitPassStandard emit pass implementation using GateEmitter protocol.

Functions

emit_pauli_evolve [source]

def emit_pauli_evolve(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: PauliEvolveOp,
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> None

Emit Pauli evolution: exp(-i * gamma * H).

Resolves the Hamiltonian from bindings and decomposes each term using the Pauli gadget technique:

  1. Basis change per qubit (X->H, Y->Sdg*H, Z->identity)

  2. CNOT ladder + RZ

  3. Undo basis change

Subclasses can override this for engine-native implementations (e.g., Qiskit PauliEvolutionGate).


emit_resolved_global_phase [source]

def emit_resolved_global_phase(emit_pass: 'StandardEmitPass', circuit: Any, angle: Any) -> None

Emit an already resolved standalone phase without discarding it.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyCircuit representation being emitted into.
angleAnyResolved phase angle.

Raises:


is_exact_real_zero [source]

def is_exact_real_zero(value: Any) -> bool

Return whether a value is a concrete real scalar equal to zero.

The comparison intentionally has no tolerance: a tiny nonzero value must remain observable, while engine parameter expressions remain unresolved.

Parameters:

NameTypeDescription
valueAnyConcrete numeric value or engine parameter expression.

Returns:

bool — True only for a non-boolean real scalar exactly equal to bool — zero.


is_zero_evolution_time [source]

def is_zero_evolution_time(gamma: Any) -> bool

Return whether a resolved evolution time is the numeric identity.

Python and NumPy real scalars share the same rule. Engine parameter objects deliberately remain nonzero here: their runtime value is unknown even if they support comparison with Python numbers.

Parameters:

NameTypeDescription
gammaAnyConcrete float or engine-native parameter expression.

Returns:

bool — True only for a concrete numeric zero.


resolve_angle_value [source]

def resolve_angle_value(
    emit_pass: 'StandardEmitPass',
    theta: Any,
    bindings: dict[str, Any],
) -> float | Any

Resolve a bare angle Value to a concrete float or engine parameter.

Shared core of :func:resolve_angle so operations carrying a standalone angle Value reuse the exact same resolution order as rotation-gate thetas.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass providing the resolver and engine-parameter factory.
thetaAnyAngle Value to resolve.
bindingsdict[str, Any]Active compile-time bindings.

Returns:

float | Any — float | Any: A concrete float when the angle is bound, or a engine parameter expression when it stays symbolic.

Raises:


validate_hamiltonian_within_register [source]

def validate_hamiltonian_within_register(num_h_qubits: int, register_size: int) -> None

Validate that a Hamiltonian fits within the target qubit register.

A Hamiltonian acting on fewer qubits than the register is embedded into the register’s qubit space (identity on the untouched qubits) by acting only on its declared qubits; only a Hamiltonian larger than the register is a genuine error. Every PauliEvolveOp emit path (shared, engine-native, and controlled) must apply this same rule through this helper so the size contract cannot drift between engines.

Parameters:

NameTypeDescription
num_h_qubitsintNumber of qubits the Hamiltonian acts on (Hamiltonian.num_qubits).
register_sizeintResolved element count of the target qubit register.

Raises:


validate_hermitian_hamiltonian [source]

def validate_hermitian_hamiltonian(hamiltonian: Hamiltonian) -> None

Validate every coefficient before Pauli-evolution emission starts.

This validation deliberately completes before the zero-time shortcut and before any circuit mutation. Consequently, malformed Hamiltonians fail consistently for controlled and uncontrolled evolution, and a late invalid term cannot leave a partially emitted circuit behind.

Parameters:

NameTypeDescription
hamiltonianHamiltonianHamiltonian whose constant and Pauli-term coefficients must be real within HERMITIAN_IMAG_ATOL.

Raises:

Classes

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:

bool — True iff slice_of is non-None.

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

EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return
Constructor
def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

Hamiltonian [source]

class Hamiltonian

Represents a quantum Hamiltonian as a sum of Pauli operator products.

The Hamiltonian is stored as a dictionary where keys are tuples of PauliOperators and values are their corresponding coefficients.

Example:

>>> H = Hamiltonian()
>>> H.add_term((PauliOperator(Pauli.X, 0), PauliOperator(Pauli.Y, 1)), 0.5)
>>> H.add_term((PauliOperator(Pauli.Z, 2),), 1.0)
>>> print(H.terms)
{(X0, Y1): 0.5, (Z2,): 1.0}
Constructor
def __init__(self, num_qubits: int | None = None) -> None
Attributes
Methods
add_term
def add_term(self, operators: tuple[PauliOperator, ...], coeff: float | complex)

Adds a term to the Hamiltonian.

This method adds a product of Pauli operators with a given coefficient to the Hamiltonian. If the term already exists, the coefficients are summed.

Parameters:

NameTypeDescription
operatorsTuple[PauliOperator, ...]A tuple of PauliOperators representing the term.
coeffUnion[float, complex]The coefficient of the term.

Example:

>>> H = Hamiltonian()
>>> H.add_term((PauliOperator(Pauli.X, 0), PauliOperator(Pauli.Y, 1)), 0.5)
>>> H.add_term((PauliOperator(Pauli.X, 0), PauliOperator(Pauli.Y, 1)), 0.5j)
>>> print(H.terms)
{(X0, Y1): (0.5+0.5j)}
copy
def copy(self) -> Hamiltonian

Return an independent copy sharing no mutable state with self.

Produces a new Hamiltonian with the same terms, constant, and declared _num_qubits. The underlying _terms dict is fresh, so subsequent add_term / constant mutations on either instance do not affect the other. PauliOperator instances inside the term tuples are reused — they are dataclass(frozen=True) values and safely shared.

Returns:

Hamiltonian — A shallow-cloned Hamiltonian instance.

Example:

>>> H = Hamiltonian()
>>> H.add_term((PauliOperator(Pauli.Z, 0),), 1.0)
>>> H2 = H.copy()
>>> H2.add_term((PauliOperator(Pauli.X, 1),), 0.5)
>>> H.num_qubits  # unchanged by H2's mutation
1
identity
@classmethod
def identity(
    cls,
    coeff: float | complex = 1.0,
    num_qubits: int | None = None,
) -> Hamiltonian

Create a scalar times identity Hamiltonian.

remap_qubits
def remap_qubits(self, qubit_map: dict[int, int]) -> Hamiltonian

Remap qubit indices according to the given mapping.

This is used to translate Pauli indices (logical indices within an expval call) to physical qubit indices in the actual quantum circuit.

Parameters:

NameTypeDescription
qubit_mapdict[int, int]Mapping from logical index to physical index. e.g., {0: 5, 1: 3} maps logical index 0 → physical qubit 5

Returns:

Hamiltonian — New Hamiltonian with remapped qubit indices.

single_pauli
@classmethod
def single_pauli(cls, pauli: Pauli, index: int, coeff: float | complex = 1.0) -> Hamiltonian

Create a single Pauli term Hamiltonian.

to_latex
def to_latex(self) -> str

Converts the Hamiltonian to a LaTeX representation.

This function does not add constant term when we show the Hamiltonian. This function does not add $ symbols.

Returns:

str — A LaTeX representation of the Hamiltonian.

import qamomile.observable as qm_o
import IPython.display as ipd

h = qm_o.Hamiltonian()
h += -qm_o.X(0) * qm_o.Y(1) - 2.0 * qm_o.Z(0) * qm_o.Z(1)

# Show the Hamiltonian in LaTeX at Jupyter Notebook
ipd.display(ipd.Latex("$" + h.to_latex() + "$"))
to_numpy
def to_numpy(self) -> np.ndarray

Convert the Hamiltonian to a dense NumPy matrix.

Qubit 0 is mapped to the least-significant bit of computational-basis indices, matching :meth:qamomile.linalg.HermitianMatrix.to_hamiltonian. The returned array has shape (2**n, 2**n) where n is :attr:num_qubits.

zero
@classmethod
def zero(cls, num_qubits: int | None = None) -> Hamiltonian

Create a zero Hamiltonian.


PauliEvolveOp [source]

class PauliEvolveOp(Operation)

Pauli evolution operation: exp(-i * gamma * H).

This operation applies the time evolution of a Pauli Hamiltonian to a quantum register.

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

QubitAddress [source]

class QubitAddress

Typed key for qubit/clbit physical-index maps.

For scalar qubits: QubitAddress(uuid="abc123") For array elements: QubitAddress(uuid="abc123", element_index=2)

This replaces the f"{uuid}_{i}" string key pattern throughout the emit pipeline, making the key format explicit and preventing format-string bugs.

Constructor
def __init__(self, uuid: str, element_index: int | None = None) -> None
Attributes
Methods
from_composite_key
@classmethod
def from_composite_key(cls, key: str) -> QubitAddress

Parse a legacy composite key string into a QubitAddress.

The frontend stores qubit references as composite strings in the format "{array_uuid}_{element_index}" (e.g., cast operation qubit mappings, element UUIDs). This helper converts such strings to proper QubitAddress instances.

If the key does not match the composite format (i.e., the suffix after the last _ is not a non-negative integer), it is treated as a plain scalar UUID.

matches_array
def matches_array(self, array_uuid: str) -> bool

True if this address belongs to the given array.

with_element
def with_element(self, index: int) -> QubitAddress

Create an array-element address from this array’s base UUID.


StandardEmitPass [source]

class StandardEmitPass(EmitPass[T], Generic[T])

Standard emit pass implementation using GateEmitter protocol.

This class provides orchestration for semantic IR traversal while delegating circuit instruction construction to a GateEmitter. The concrete compiler use is CircuitLoweringPass; SDK targets materialize its immutable result instead of subclassing this class.

Parameters:

NameTypeDescription
gate_emitterGateEmitter[T]Instruction builder used during the semantic traversal.
bindingsdict[str, Any] | NoneCompile-time parameter bindings.
parameterslist[str] | NoneParameter names preserved at runtime.
composite_emitterslist[CompositeGateEmitter[T]] | NoneOptional callable-preservation or lowering hooks.
engine_namestr | NoneDiagnostic name for the traversal target.
Constructor
def __init__(
    self,
    gate_emitter: GateEmitter[T],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
    composite_emitters: list[CompositeGateEmitter[T]] | None = None,
    engine_name: str | None = None,
)
Attributes

qamomile.circuit.transpiler.passes.emit_support.physical_index_map

Helpers for mutating physical-index maps during emission.

Overview

FunctionDescription
array_element_mappingCollect physical indices for the elements of an array value.
array_element_mappingsCollect array element mappings for multiple source arrays.
copy_array_element_aliasesCopy array element aliases from a source array to a result array.
map_array_element_aliasesMap explicit array element aliases to a result array.
map_array_result_groupMap an array-valued result to a physical index group.
ClassDescription
QubitAddressTyped key for qubit/clbit physical-index maps.

Functions

array_element_mapping [source]

def array_element_mapping(source_uuid: str, index_map: Mapping[QubitAddress, int]) -> dict[int, int]

Collect physical indices for the elements of an array value.

Parameters:

NameTypeDescription
source_uuidstrUUID of the array whose element addresses should be collected.
index_mapMapping[QubitAddress, int]Physical-index map to read.

Returns:

dict[int, int] — dict[int, int]: Mapping from element index to physical index.


array_element_mappings [source]

def array_element_mappings(
    source_uuids: set[str],
    index_map: Mapping[QubitAddress, int],
) -> dict[str, dict[int, int]]

Collect array element mappings for multiple source arrays.

Parameters:

NameTypeDescription
source_uuidsset[str]UUIDs of the arrays whose element addresses should be collected.
index_mapMapping[QubitAddress, int]Physical-index map to read.

Returns:

dict[str, dict[int, int]] — dict[str, dict[int, int]]: Mapping from each requested source UUID to its element-index-to-physical-index mapping.


copy_array_element_aliases [source]

def copy_array_element_aliases(source_uuid: str, result_uuid: str, index_map: PhysicalIndexMap) -> None

Copy array element aliases from a source array to a result array.

Parameters:

NameTypeDescription
source_uuidstrUUID of the source array whose element addresses are already present in index_map.
result_uuidstrUUID of the result array that should alias the same physical resources element by element.
index_mapPhysicalIndexMapMutable physical-index map updated in place with any missing result element addresses and the result base address.

map_array_element_aliases [source]

def map_array_element_aliases(
    result_uuid: str,
    element_mapping: Mapping[int, int],
    index_map: PhysicalIndexMap,
    *,
    map_base_address: bool = True,
) -> None

Map explicit array element aliases to a result array.

Parameters:

NameTypeDescription
result_uuidstrUUID of the result array that should receive the element aliases.
element_mappingMapping[int, int]Physical indices keyed by result element index.
index_mapPhysicalIndexMapMutable physical-index map updated in place with missing result element addresses and, when requested, the result base address.
map_base_addressboolWhether to map the scalar base address for the result array to its lowest-index element. Defaults to True.

map_array_result_group [source]

def map_array_result_group(result_uuid: str, index_group: list[int], index_map: PhysicalIndexMap) -> None

Map an array-valued result to a physical index group.

Parameters:

NameTypeDescription
result_uuidstrUUID of the array-valued result whose element addresses should be registered.
index_grouplist[int]Physical indices for the result elements, in result-local element order.
index_mapPhysicalIndexMapMutable physical-index map updated in place with element addresses and, when available, the base result address.

Classes

QubitAddress [source]

class QubitAddress

Typed key for qubit/clbit physical-index maps.

For scalar qubits: QubitAddress(uuid="abc123") For array elements: QubitAddress(uuid="abc123", element_index=2)

This replaces the f"{uuid}_{i}" string key pattern throughout the emit pipeline, making the key format explicit and preventing format-string bugs.

Constructor
def __init__(self, uuid: str, element_index: int | None = None) -> None
Attributes
Methods
from_composite_key
@classmethod
def from_composite_key(cls, key: str) -> QubitAddress

Parse a legacy composite key string into a QubitAddress.

The frontend stores qubit references as composite strings in the format "{array_uuid}_{element_index}" (e.g., cast operation qubit mappings, element UUIDs). This helper converts such strings to proper QubitAddress instances.

If the key does not match the composite format (i.e., the suffix after the last _ is not a non-negative integer), it is treated as a plain scalar UUID.

matches_array
def matches_array(self, array_uuid: str) -> bool

True if this address belongs to the given array.

with_element
def with_element(self, index: int) -> QubitAddress

Create an array-element address from this array’s base UUID.


qamomile.circuit.transpiler.passes.emit_support.qubit_address

Typed key for qubit/clbit physical-index maps.

Replaces the ad-hoc f"{uuid}_{index}" string convention with an explicit, hashable value object that makes the construction/parsing contract type-safe.

Overview

ClassDescription
QubitAddressTyped key for qubit/clbit physical-index maps.

Classes

QubitAddress [source]

class QubitAddress

Typed key for qubit/clbit physical-index maps.

For scalar qubits: QubitAddress(uuid="abc123") For array elements: QubitAddress(uuid="abc123", element_index=2)

This replaces the f"{uuid}_{i}" string key pattern throughout the emit pipeline, making the key format explicit and preventing format-string bugs.

Constructor
def __init__(self, uuid: str, element_index: int | None = None) -> None
Attributes
Methods
from_composite_key
@classmethod
def from_composite_key(cls, key: str) -> QubitAddress

Parse a legacy composite key string into a QubitAddress.

The frontend stores qubit references as composite strings in the format "{array_uuid}_{element_index}" (e.g., cast operation qubit mappings, element UUIDs). This helper converts such strings to proper QubitAddress instances.

If the key does not match the composite format (i.e., the suffix after the last _ is not a non-negative integer), it is treated as a plain scalar UUID.

matches_array
def matches_array(self, array_uuid: str) -> bool

True if this address belongs to the given array.

with_element
def with_element(self, index: int) -> QubitAddress

Create an array-element address from this array’s base UUID.


qamomile.circuit.transpiler.passes.emit_support.resource_allocator

Resource allocation helpers for emission.

Overview

FunctionDescription
array_physical_regionResolve a one-dimensional array to its ordered physical region.
copy_array_element_aliasesCopy array element aliases from a source array to a result array.
genuine_input_valuesReturn an operation’s input values that count as genuine reads.
map_merge_outputsRegister merge output UUIDs to the same physical resources as their sources.
remap_static_merge_outputsRemap merge outputs for a compile-time constant IfOperation.
resolve_condition_address_detailedResolve a condition / source Value to its clbit_map key.
resolve_if_conditionResolve an if-condition to a compile-time boolean.
resolve_loop_boundsResolve for-loop bounds (start, stop, step) from operands.
resolve_qubit_keyResolve a qubit Value to its allocation key.
resolve_root_qubit_addressResolve an array-element value to its root (array_uuid, index).
validated_loop_indexsetBuild an engine-safe Python range for resolved loop bounds.
ClassDescription
ArrayValueAn array of typed IR values.
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
BitTypeType representing a classical bit.
CastOperationType cast operation for creating aliases over the same quantum resources.
CompOpComparison operation (EQ, NEQ, LT, LE, GT, GE).
ConcreteControlledUControlled-U with concrete (int) number of controls.
CondOpConditional logical operation (AND, OR).
ControlledUOperationBase class for controlled-U operations.
EmitErrorReport an engine failure to emit one semantic operation.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
GateOperationQuantum gate operation.
HasNestedOpsMixin for operations that contain nested operation lists.
IfOperationRepresents an if-else conditional operation.
InverseBlockOperationRepresent an inverse qkernel/block as a first-class IR operation.
InvokeOperationRepresent a composite, stdlib, or oracle call.
MeasureOperation
MeasureQFixedOperationMeasure a quantum fixed-point number.
MeasureVectorOperationMeasure a vector of qubits.
NotOp
PauliEvolveOpPauli evolution operation: exp(-i * gamma * H).
ProjectOperationProject a qubit in one Pauli basis and keep the projected state.
QInitOperationInitialize the qubit
QubitAddressTyped key for qubit/clbit physical-index maps.
ResetOperationReset a qubit to the |0> state and return the fresh handle.
ResourceAllocatorAllocates qubit and classical bit indices from operations.
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
SymbolicControlledUControlled-U with symbolic (Value) number of controls.
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.
ValueResolverResolves Value objects to concrete indices or values.
WhileOperationRepresents a while loop operation.

Functions

array_physical_region [source]

def array_physical_region(array: 'ArrayValue') -> tuple[str, tuple[int, ...]] | None

Resolve a one-dimensional array to its ordered physical region.

The region is expressed independently of SSA version UUIDs: the first element is the root array’s logical_id and the second is the ordered tuple of root-space indices addressed by the array. This makes a root register and its full view compare equal while keeping partial, strided, reordered, and different-root registers distinct.

Parameters:

NameTypeDescription
arrayArrayValueRoot array or nested sliced view to resolve. The array must be one-dimensional and have a compile-time integer length; every slice bound in its ancestry must also be constant.

Returns:

tuple[str, tuple[int, ...]] | None — tuple[str, tuple[int, ...]] | None: (root_logical_id, indices) when the complete ordered coverage is statically known, otherwise None. Symbolic shapes or slice bounds remain unresolved so callers can defer to emit-time physical mappings.


copy_array_element_aliases [source]

def copy_array_element_aliases(source_uuid: str, result_uuid: str, index_map: PhysicalIndexMap) -> None

Copy array element aliases from a source array to a result array.

Parameters:

NameTypeDescription
source_uuidstrUUID of the source array whose element addresses are already present in index_map.
result_uuidstrUUID of the result array that should alias the same physical resources element by element.
index_mapPhysicalIndexMapMutable physical-index map updated in place with any missing result element addresses and the result base address.

genuine_input_values [source]

def genuine_input_values(op: Operation) -> list[ValueBase]

Return an operation’s input values that count as genuine reads.

Structured operations derive reads from their explicit region interface: enclosing operands, captures, loop initializers, and region yields. Block arguments and operation results are definitions, while legacy rebind records are diagnostics rather than dataflow. Leaf operations keep their ordinary all_input_values contract.

Parameters:

NameTypeDescription
opOperationOperation to inspect.

Returns:

list[ValueBase] — list[ValueBase]: Semantic reads in interface order.


map_merge_outputs [source]

def map_merge_outputs(
    if_op: IfOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    resolve_scalar_qubit: Any = None,
    bindings: dict[str, Any] | None = None,
    resolver: ValueResolver | None = None,
    reject_runtime_bit_mux: bool = False,
    allowed_mixed_bit_outputs: frozenset[str] | set[str] | None = None,
) -> None

Register merge output UUIDs to the same physical resources as their sources.

Runtime-if counterpart of :func:remap_static_merge_outputs: both branches may execute, so quantum merges are validated to sit on identical physical resources, and classical Bit merges consolidate both branches’ clbits only when the complete source-alias partition is representable without overwriting an independently live value. Outputs already registered are left untouched.

Parameters:

NameTypeDescription
if_opIfOperationThe runtime if-else whose merged outputs need physical-resource registration; merges are read through iter_merges.
qubit_mapQubitMapAddress-to-physical-qubit map, mutated in place.
clbit_mapClbitMapAddress-to-physical-clbit map, mutated in place.
resolve_scalar_qubitAnyOptional callable (source, qubit_map) -> int | None used to resolve scalar qubit sources that are not directly registered (e.g. array elements). Defaults to None, restricting resolution to direct and root-array lookups.
bindingsdict[str, Any] | NoneActive bindings used to fold a classical Bit merge source’s symbolic Vector[Bit] element index / slice bounds (e.g. an unrolled loop variable). Defaults to None (empty), restricting element resolution to constant indices.
resolverValueResolver | NoneResolver used with bindings to fold non-constant element indices; None restricts to constants. Defaults to None.
reject_runtime_bit_muxboolWhen True, raise EmitError for a runtime Bit merge that requires an at-runtime mux, mixes a pre-existing source with a branch-local measurement, or has incompatible source-sharing partitions across multiple outputs. Two all-branch-local source sets remain eligible only when their alias partitions match. Defaults to False.
allowed_mixed_bit_outputsfrozenset[str] | set[str] | NoneMerge result UUIDs whose pre-existing source is proven dead after the merge. This includes safe ordinary-if updates and phi-like loop condition remeasurements. Defaults to None.

Raises:


remap_static_merge_outputs [source]

def remap_static_merge_outputs(
    if_op: IfOperation,
    condition_value: bool,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any] | None = None,
    resolver: ValueResolver | None = None,
) -> None

Remap merge outputs for a compile-time constant IfOperation.

Registers each merged output under the physical resource of the branch selected by the resolved condition, so downstream operations referencing the merge output resolve to the surviving branch’s qubit / clbit. Outputs already registered are left untouched.

Parameters:

NameTypeDescription
if_opIfOperationThe if-else whose condition resolved at compile time; merges are read through iter_merges.
condition_valueboolThe resolved condition, selecting which branch’s source the outputs alias.
qubit_mapQubitMapAddress-to-physical-qubit map, mutated in place.
clbit_mapClbitMapAddress-to-physical-clbit map, mutated in place.
bindingsdict[str, Any] | NoneActive bindings used to fold a merge source’s symbolic Vector[Bit] element index / slice bounds (e.g. an unrolled loop variable). Defaults to None (empty), restricting element resolution to constant indices.
resolverValueResolver | NoneResolver used with bindings to fold non-constant element indices; None restricts to constants. Defaults to None.

resolve_condition_address_detailed [source]

def resolve_condition_address_detailed(
    condition: Value,
    bindings: dict[str, Any],
    resolver: ValueResolver | None = None,
) -> tuple[QubitAddress, bool]

Resolve a condition / source Value to its clbit_map key.

Single source of truth (shared by control_flow_emission.emit_if / emit_while, the Qiskit / CUDA-Q engines, ResourceAllocator’s loop-carried / merge aliasing, and the merge-output mapping helpers here) for turning a runtime control-flow condition — or a merge source Value — into the address its classical bit is registered under.

Scalar measurement results register under QubitAddress(bit.uuid), while a Vector[Bit] element s[i] (s = qmc.measure(register)) registers under QubitAddress(root_array.uuid, root_index). The element index and every slice_start / slice_step along the parent’s slice_of chain are resolved the same way — taken directly when constant, otherwise folded through bindings via resolver — and composed into the root index via root_index = start + step * view_local_index repeated along the chain.

Parameters:

NameTypeDescription
conditionValueThe condition operand or merge source Value.
bindingsdict[str, Any]Active emit-time bindings used to fold symbolic indices / slice bounds. May be empty for callers that only have constant addresses to resolve (e.g. the allocator’s pre-emit pass).
resolverValueResolver | NoneResolver exposing resolve_int_value; None restricts resolution to constants. Defaults to None.

Returns:

tuple[QubitAddress, bool] — tuple[QubitAddress, bool]: (address, resolved_as_element). resolved_as_element is True only when condition is a Vector[Bit] element whose index (and any slice bounds) resolved to concrete ints, giving the root-space QubitAddress(root.uuid, root_index). It is False for a plain scalar, or when an element’s index / slice bound could not be resolved (the scalar UUID fallback). Callers that mutate clbit_map should trust the address as a vector key only when this flag is True, to avoid aliasing an unresolved element onto an unrelated scalar slot.


resolve_if_condition [source]

def resolve_if_condition(condition: Any, bindings: dict[str, Any]) -> bool | None

Resolve an if-condition to a compile-time boolean.


resolve_loop_bounds [source]

def resolve_loop_bounds(
    resolver: Any,
    op: ForOperation,
    bindings: dict[str, Any],
) -> tuple[int | None, int | None, int | None]

Resolve for-loop bounds (start, stop, step) from operands.

Missing operands use defaults: start=0, stop=1, step=1. Returns None for bounds that cannot be resolved to concrete ints.


resolve_qubit_key [source]

def resolve_qubit_key(qubit: 'Value') -> tuple[QubitAddress | None, bool]

Resolve a qubit Value to its allocation key.

Parameters:

NameTypeDescription
qubitValueQubit value to resolve. Array elements with a constant index are resolved through their full slice_of chain to the root array address.

Returns:

tuple[QubitAddress | None, bool] — tuple[QubitAddress | None, bool]: (address, is_array_element). address is the root-space address for a resolvable array element, None for an array element whose index or slice bounds are symbolic at this binding-free stage, and a scalar UUID address for non-array qubits. A negative constant index (or an out-of-contract slice bound) also yields None: resolve_root_qubit_address refuses it rather than letting it silently address a wrong root slot.


resolve_root_qubit_address [source]

def resolve_root_qubit_address(value: 'Value') -> tuple[str, int] | None

Resolve an array-element value to its root (array_uuid, index).

Walks the parent_array / slice_of chain and composes the nested affine slice maps, so view[i] resolves to (root_uuid, start + step * i) for the composed (start, step). The returned pair is the build-stable identity of the physical qubit slot: the root array’s QInitOperation always registers it as QubitAddress(root_uuid, index), so this address resolves even when the element’s own (per-version) UUID was never registered.

The transpiler’s resource allocator uses the same walk to resolve gate and measurement operands; this shared helper keeps both call sites consistent.

Parameters:

NameTypeDescription
valueValueThe value to resolve. Expected to be an array element (parent_array set with a single constant element_indices entry).

Returns:

tuple[str, int] | None — tuple[str, int] | None: (root_array_uuid, composed_index) when value is an array element with a constant index whose entire slice_of chain has constant slice_start / slice_step. None when value is not an array element, when its index is non-constant, or when any slice bound in the chain is non-constant (those cases are deferred to the emit-time resolver, which has bindings available). Also None for a negative constant index or a chain frame with negative slice_start / non-positive slice_step — composing those would silently address a wrong root slot, so they are refused rather than guessed (the frontend rejects them at trace time; this guard covers programmatically constructed IR).


validated_loop_indexset [source]

def validated_loop_indexset(start: int, stop: int, step: int) -> range

Build an engine-safe Python range for resolved loop bounds.

Parameters:

NameTypeDescription
startintInclusive loop start.
stopintExclusive loop stop.
stepintNonzero loop step.

Returns:

range — The resolved loop index set when its cardinality fits Python’s platform-sized sequence protocol.

Raises:

Classes

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:

bool — True iff slice_of is non-None.

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

BinOp [source]

class BinOp(BinaryOperationBase)

Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: BinOpKind | None = None,
) -> None
Attributes

BitType [source]

class BitType(ClassicalTypeMixin, ValueType)

Type representing a classical bit.


CastOperation [source]

class CastOperation(Operation)

Type cast operation for creating aliases over the same quantum resources.

This operation does NOT allocate new qubits. It creates a new Value that references the same underlying quantum resources with a different type.

Use cases:

operands: [source_value] - The value being cast results: [cast_result] - The new value with target type (same physical qubits)

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    source_type: ValueType | None = None,
    target_type: ValueType | None = None,
    qubit_mapping: list[str] = list(),
) -> None
Attributes

CompOp [source]

class CompOp(BinaryOperationBase)

Comparison operation (EQ, NEQ, LT, LE, GT, GE).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CompOpKind | None = None,
) -> None
Attributes

ConcreteControlledU [source]

class ConcreteControlledU(ControlledUOperation)

Controlled-U with concrete (int) number of controls.

Operand layout: [ctrl_0, ..., ctrl_n, tgt_0, ..., tgt_m, params...] Result layout: [ctrl_0', ..., ctrl_n', tgt_0', ..., tgt_m']

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_value: int | None = None,
) -> None
Attributes

CondOp [source]

class CondOp(BinaryOperationBase)

Conditional logical operation (AND, OR).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CondOpKind | None = None,
) -> None
Attributes

ControlledUOperation [source]

class ControlledUOperation(Operation)

Base class for controlled-U operations.

Two concrete subclasses handle distinct operand layouts:

All isinstance(op, ControlledUOperation) checks match every subclass.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int | Value = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]
replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return
Constructor
def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

ForItemsOperation [source]

class ForItemsOperation(HasNestedOps, Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    key_var_values: tuple[Value, ...] | None = None,
    value_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include the per-key/value Value fields for cloning/substitution.

Same rationale as ForOperation.all_input_values: keep the IR identity fields in lockstep with body references so UUID-keyed lookups stay valid after inline cloning. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the items-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing key/value formals, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the items-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt items-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

GateOperation [source]

class GateOperation(Operation)

Quantum gate operation.

For rotation gates (RX, RY, RZ, P, CP, RZZ), the angle parameter is stored as the last element of operands. Use the theta property for typed read access and the rotation / fixed factory class-methods for type-safe construction.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    gate_type: GateOperationType | None = None,
) -> None
Attributes
Methods
fixed
@classmethod
def fixed(
    cls,
    gate_type: GateOperationType,
    qubits: list[Value],
    results: list[Value],
) -> 'GateOperation'

Create a fixed gate (H, X, CX, SWAP, …) with no angle parameter.

rotation
@classmethod
def rotation(
    cls,
    gate_type: GateOperationType,
    qubits: list[Value],
    theta: Value,
    results: list[Value],
) -> 'GateOperation'

Create a rotation gate (RX, RY, RZ, P, CP, RZZ) with an angle.


HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


InverseBlockOperation [source]

class InverseBlockOperation(Operation)

Represent an inverse qkernel/block as a first-class IR operation.

The operation stores both the original forward block and a Qamomile-built inverse implementation block. Emitters may use source_block with a engine-native inverse/adjoint primitive, then fall back to implementation_block when native inversion is unavailable.

Operands are ordered as scalar control qubits, target quantum operands, then classical/object parameters. Results mirror the quantum operand layout: control results first, then one target result per target operand. Vector target operands therefore count as one operand/result while contributing their scalar width to num_target_qubits.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_control_qubits: int = 0,
    num_target_qubits: int = 0,
    custom_name: str = '',
    source_block: Block | None = None,
    implementation_block: Block | None = None,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_value: int | None = None,
) -> None
Attributes

InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.
Constructor
def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes
Methods
body_for_transform
def body_for_transform(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> tuple[Block | None, CallTransform]

Select a body and report the transform it already realizes.

A controlled-inverse invocation may reuse an explicitly registered inverse body when no implementation realizes both transforms. Keeping that fallback in the IR operation gives emitters and static analyses one selection rule while still letting each consumer apply the remaining coherent controls in its own representation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — tuple[Block | None, CallTransform]: Selected body and the transform CallTransform — already implemented by that body. The callable’s direct body is tuple[Block | None, CallTransform] — returned with DIRECT when no transform-specific body matches.

Raises:

effective_body
def effective_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — Block | None: Selected implementation body, or the callable’s Block | None — default body when no transform-specific implementation exists. Block | None — A compiler may synthesize inverse or controlled behavior from this Block | None — fallback body.

implementation_for
def implementation_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None, which only selects engine-generic implementations.
strategystr | NoneStrategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation candidate, CallableImplementation | None — or None when the callable definition has no match.

measurement_result_indices_for
def measurement_result_indices_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> frozenset[int]

Return measurement-derived results for one selected implementation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name used for implementation selection. Defaults to None.
strategystr | NoneStrategy name used for implementation selection. Defaults to the invocation’s strategy_name.

Returns:

frozenset[int] — frozenset[int]: Caller-local result positions derived from measurement in the selected body.

Raises:

select_body
def select_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> CallableBodySelection

Select and validate the composable body for this invocation.

The result carries the transform already realized by the body and the exact call-site values that bind to it. Consumers therefore cannot independently disagree about whether an invocation’s control prefix belongs to the selected implementation ABI.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

CallableBodySelection — Validated body, realized transform, and CallableBodySelection — aligned call-site operands and results.

Raises:


MeasureOperation [source]

class MeasureOperation(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

MeasureQFixedOperation [source]

class MeasureQFixedOperation(Operation)

Measure a quantum fixed-point number.

This operation measures all qubits in a QFixed register and produces a Float result. During transpilation, this is lowered to individual MeasureOperations plus a DecodeQFixedOperation.

operands: [QFixed value (contains qubit_values in params)] results: [Float value]

Encoding:

For QPE phase (int_bits=0): Qubits are stored least-significant first. For n qubits, bit i has weight 2**(-n + i).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_bits: int = 0,
    int_bits: int = 0,
) -> None
Attributes

MeasureVectorOperation [source]

class MeasureVectorOperation(Operation)

Measure a vector of qubits.

Takes a Vector[Qubit] (ArrayValue) and produces a Vector[Bit] (ArrayValue). This operation measures all qubits in the vector as a single operation.

operands: [ArrayValue of qubits] results: [ArrayValue of bits]

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

NotOp [source]

class NotOp(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

PauliEvolveOp [source]

class PauliEvolveOp(Operation)

Pauli evolution operation: exp(-i * gamma * H).

This operation applies the time evolution of a Pauli Hamiltonian to a quantum register.

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ProjectOperation [source]

class ProjectOperation(Operation)

Project a qubit in one Pauli basis and keep the projected state.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    axis: str = 'z',
) -> None
Attributes

QInitOperation [source]

class QInitOperation(Operation)

Initialize the qubit

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

QubitAddress [source]

class QubitAddress

Typed key for qubit/clbit physical-index maps.

For scalar qubits: QubitAddress(uuid="abc123") For array elements: QubitAddress(uuid="abc123", element_index=2)

This replaces the f"{uuid}_{i}" string key pattern throughout the emit pipeline, making the key format explicit and preventing format-string bugs.

Constructor
def __init__(self, uuid: str, element_index: int | None = None) -> None
Attributes
Methods
from_composite_key
@classmethod
def from_composite_key(cls, key: str) -> QubitAddress

Parse a legacy composite key string into a QubitAddress.

The frontend stores qubit references as composite strings in the format "{array_uuid}_{element_index}" (e.g., cast operation qubit mappings, element UUIDs). This helper converts such strings to proper QubitAddress instances.

If the key does not match the composite format (i.e., the suffix after the last _ is not a non-negative integer), it is treated as a plain scalar UUID.

matches_array
def matches_array(self, array_uuid: str) -> bool

True if this address belongs to the given array.

with_element
def with_element(self, index: int) -> QubitAddress

Create an array-element address from this array’s base UUID.


ResetOperation [source]

class ResetOperation(Operation)

Reset a qubit to the |0> state and return the fresh handle.

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ResourceAllocator [source]

class ResourceAllocator

Allocates qubit and classical bit indices from operations.

This class handles the first pass of circuit emission: determining how many physical qubits and classical bits are needed and mapping Value UUIDs to their physical indices.

New physical indices are assigned via monotonic counters (_next_qubit_index / _next_clbit_index) so that alias entries — which reuse an existing physical index — never inflate the counter. Using len(map) would cause sparse (gapped) physical indices because alias keys increase the map size without adding new physical resources.

Constructor
def __init__(self, resolver: ValueResolver | None = None) -> None

Initialize allocator state.

Parameters:

NameTypeDescription
resolverValueResolver | NoneEmit value resolver that carries runtime parameter names and binding lookup rules. Defaults to None, which creates a resolver without runtime parameters.
Attributes
Methods
allocate
def allocate(
    self,
    operations: list[Operation],
    bindings: dict[str, Any] | None = None,
    initial_qubit_map: QubitMap | None = None,
    initial_clbit_map: ClbitMap | None = None,
    public_output_uuids: frozenset[str] | set[str] | None = None,
) -> tuple[QubitMap, ClbitMap]

Allocate qubit and clbit indices for all operations.

Parameters:

NameTypeDescription
operationslist[Operation]Operations to allocate resources for.
bindingsdict[str, Any] | NoneOptional variable bindings for resolving dynamic sizes. Defaults to None (treated as an empty mapping).
initial_qubit_mapQubitMap | NoneOptional pre-populated qubit address mapping. Used by callers that need to seed the allocator with bindings established outside the operation list — for instance, the inner-block emitter in blockvalue_to_gate pre-allocates Vector[Qubit] input elements (the inner block has no QInitOperation for inputs, so per-element entries must be supplied here or the assertion in _allocate_gate fires). The map is copied; allocation continues from max(values) + 1 so new QInitOperation allocations inside operations do not collide. Defaults to None (treated as empty).
initial_clbit_mapClbitMap | NoneOptional pre-populated clbit address mapping. Same semantics as initial_qubit_map but for classical bits. Defaults to None.
public_output_uuidsfrozenset[str] | set[str] | NoneProgram outputs that must remain live after this operation tree. Defaults to None, which disables dead-source approval for mixed prior/fresh Bit merges.

Returns:

tuple[QubitMap, ClbitMap] — tuple[QubitMap, ClbitMap]: (qubit_map, clbit_map) where each maps QubitAddress to a physical index. If an initial map was supplied, its entries are preserved verbatim in the returned map.

preserving_analysis_state
def preserving_analysis_state(self) -> Iterator[None]

Preserve segment-level analysis state across a nested allocation.

allocate recomputes the measurement-taint set, the safe mixed-merge allowlist, and the monotonic resource counters for the operation list it receives. Nested sub-circuit emission (controlled blocks, native inverses) reuses the SEGMENT allocator on a different operation list mid-emission; without a snapshot that leaves the sub-block’s analysis state behind, and later resolve_iteration_maps replays of the enclosing segment consult the wrong taint/allowlist sets — silently disarming the runtime-mux guards.

Yields:

None — The nested allocation and emission run inside the snapshot; the segment state is restored on exit even when the nested work raises.

resolve_iteration_maps
def resolve_iteration_maps(
    self,
    operations: list[Operation],
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
) -> tuple[QubitMap, ClbitMap]

Resolve resource aliases for one statically replayed iteration.

The initial allocation walks an unrolled loop body only once, before its loop variable has a concrete value. A nested runtime condition such as while measured[index]: therefore cannot select its root clbit during that first walk. Replaying the allocator over copies of the already-complete maps with the iteration binding present resolves those aliases without allocating another physical resource. The caller uses the returned maps for that iteration only; the same body UUIDs may legitimately alias different measured-vector elements in later iterations.

Parameters:

NameTypeDescription
operationslist[Operation]Statically replayed loop body.
qubit_mapQubitMapComplete enclosing qubit map.
clbit_mapClbitMapComplete enclosing clbit map.
bindingsdict[str, Any]Iteration-local UUID bindings, including the concrete range index or items-loop key/value identities.

Returns:

tuple[QubitMap, ClbitMap] — tuple[QubitMap, ClbitMap]: Per-iteration copies with conditional aliases resolved for the supplied bindings.

Raises:


SelectOperation [source]

class SelectOperation(Operation)

Quantum multiplexer: apply case_blocks[i] when the index reads i.

Concrete operand layout: [idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...]. Symbolic-width operand layout: [idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...]. Results mirror the quantum operand grouping.

A concrete index register is normalized to one scalar Qubit operand per physical index qubit. A symbolic-width register instead retains each leading caller argument as one scalar or array operand until its bound shape is known. Whole-Vector[Qubit] / scalar targets follow and keep their shapes, and classical parameters shared across every case come last.

Index bit order is LSB-first: idx_0 is the least-significant bit, matching Qamomile’s qubit-zero convention. Case i is selected when index qubit j reads bit j of i. len(case_blocks) need not be a power of two; index values >= len(case_blocks) apply no operation (identity).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_index_qubits: int | Value = 0,
    case_blocks: list[Block] = list(),
    num_index_args: int = 0,
    case_callable_attrs: list[dict[str, Any]] = list(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Return every value consumed by the SELECT operation.

Returns:

list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width value when present.

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed replacement values.

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


SymbolicControlledU [source]

class SymbolicControlledU(ControlledUOperation)

Controlled-U with symbolic (Value) number of controls.

Operand layout: [ctrl_arg_0, ..., ctrl_arg_{k-1}, tgt_0, ..., tgt_m, params...] Result layout: [ctrl_arg_0', ..., ctrl_arg_{k-1}', tgt_0', ..., tgt_m']

The number of control arguments k is recorded in num_control_args; the default k = 1 corresponds to the historical single-pool form (operands[0] is a Vector[Qubit] / VectorView whose length equals num_controls, or whose control_indices-selected subset does). When k > 1 the control prefix is a heterogeneous sequence of scalar Qubit values and ArrayValues whose total qubit count is num_controls; the emit pass walks them in order to recover the per-physical-qubit control set.

When control_indices is None the entire control prefix is used as active controls (one-arg form: len(ctrl_vector) == num_controls; multi-arg form: the qubit-count sum of the prefix args equals num_controls). When non-None, the listed indices select exactly num_controls slots from a single-arg pool to act as controls; combining control_indices with the multi-arg control prefix is rejected at frontend time.

Each control_indices entry is stored as a Value of UIntType regardless of whether the frontend passed an int literal or a UInt handle, so all downstream value-substitution passes see a uniform shape.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: Value = (lambda: Value(type=(UIntType()), name=''))(),
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_indices: tuple[Value, ...] | None = None,
    num_control_args: int = 1,
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]
replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

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


ValueResolver [source]

class ValueResolver

Resolves Value objects to concrete indices or values.

Constructor
def __init__(self, parameters: set[str] | None = None)

Create an emit-time resolver.

Parameters:

NameTypeDescription
parametersset[str] | NoneNames preserved as engine runtime parameters. Defaults to None.
Attributes
Methods
bind_block_params
def bind_block_params(
    self,
    block_value: Any,
    param_operands: list['Value'],
    bindings: dict[str, Any],
    *,
    parameter_factory: Callable[[str, str], Any] | None = None,
) -> dict[str, Any]

Create local bindings by matching block inputs to call-site operands.

Parameters:

NameTypeDescription
block_valueAnyNested block whose classical/object inputs are bound. Objects without input_values receive no additional local bindings for compatibility with optional engine recipes.
param_operandslist[Value]Classical/object call-site operands in the controlled operation’s signature order.
bindingsdict[str, Any]Parent emit-time bindings used to resolve the call-site operands.
parameter_factoryCallable[[str, str], Any] | NoneOptional engine parameter factory used when an operand is a declared runtime parameter rather than a concrete binding. Defaults to None so standalone resolver use remains engine-neutral.

Returns:

dict[str, Any] — dict[str, Any]: Parent bindings with each inner formal rebound under both its UUID and sanctioned parameter-name key.

get_parameter_key
def get_parameter_key(self, value: 'Value', bindings: dict[str, Any]) -> str | None

Get the engine parameter key for a symbolic scalar.

Parameters:

NameTypeDescription
valueValueScalar value or array element to identify.
bindingsdict[str, Any]Active bindings used to resolve element indices and slice offsets.

Returns:

str | None — str | None: Scalar name or root-array indexed key, or None when an array element’s root location is unresolved.

lookup_in_bindings
def lookup_in_bindings(
    self,
    value: Any,
    bindings: dict[str, Any],
    *,
    index_array: bool = False,
) -> Any

Canonical resolution chain for a Value against bindings.

All other resolver methods (resolve_bound_value, resolve_classical_value, resolve_int_value, resolve_operand_for_binding) wrap this single chain. Centralizing precedence here prevents the historical drift where one resolver checked is_parameter before UUID and another checked it after, which manifested as obscure binding failures when name-keyed writes were dropped from the emit pass.

Resolution order (each step returns immediately on a hit):

  1. value is already a concrete Python scalar (no uuid).

  2. value.uuid is in bindings — return that. This is where emit-time-computed intermediates (evaluate_binop / evaluate_classical_predicate results) and merge aliases live.

  3. A compile-time array or dict payload stored in typed metadata.

  4. value.is_constant() — return value.get_const().

  5. value.is_parameter() and its parameter name is in bindings — return that.

  6. (When index_array=True) value is an array element with a resolvable parent in bindings — index into it.

  7. A non-empty display name is present in bindings. This is a compatibility bridge for programmatically constructed Values and older transforms that do not carry parameter metadata; UUID and explicit parameter provenance always take precedence.

Compiler-created temporaries are anonymous and compiler-internal writers use UUID keys, so the compatibility bridge cannot merge two same-named temporaries. Kernel parameters should normally resolve via explicit parameter metadata, while loop variables and intermediates remain UUID-keyed.

Parameters:

NameTypeDescription
valueAnyThe IR value (or already-concrete Python scalar) to resolve.
bindingsdict[str, Any]The active bindings dictionary.
index_arrayboolWhen True, also resolve array-element accesses via parent_array indexing. Off by default because not all callers want to index into bound containers.

Returns:

Any — The resolved Python value, or None if no step matched.

resolve_bound_value
def resolve_bound_value(self, value: 'Value', bindings: dict[str, Any]) -> Any

Resolve a Value to its raw bound Python object.

Wraps :meth:lookup_in_bindings with index_array=True so that arr[i] accesses against a bound container resolve to the element. Does not coerce the result — callers that need a numeric scalar should go through :meth:resolve_classical_value.

Parameters:

NameTypeDescription
valueValueValue to resolve.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

Any — Raw bound object, or None when unresolved.

resolve_classical_value
def resolve_classical_value(self, value: 'Value', bindings: dict[str, Any]) -> Any

Resolve a classical Value to a concrete Python value.

Numeric bindings are normalized to native Python scalars regardless of whether they come from a direct binding or from array-element indexing, so downstream isinstance(x, (int, float)) checks are stable when callers bind np.pi/4 or the like. bool is preserved (not coerced to int). Non-numeric values (Hamiltonians, strings, dict values, …) pass through unchanged.

Parameters:

NameTypeDescription
valueValueClassical value to resolve.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

Any — Resolved native scalar/object, or None when unresolved.

resolve_int_value
def resolve_int_value(self, val: Any, bindings: dict[str, Any]) -> int | None

Resolve a value to an integer, or None when unresolvable.

Unresolvable symbolic Values must return None. The previous return 0 fallback caused silent loop elision when parameter shape dims (gamma_dim0) reached this resolver without being folded into constants — downstream loop-bound resolution saw 0 and quietly emitted an empty loop. Returning None propagates the failure to emit_for_unrolled, which converts it into a hard compile error.

resolve_operand_for_binding
def resolve_operand_for_binding(self, operand: Any, bindings: dict[str, Any]) -> Any

Resolve an operand to a concrete value for block parameter binding.

Used when calling a sub-block (e.g. a controlled-U body): each param operand at the call site must resolve to a value to seed the callee’s parameter bindings.

Parameters:

NameTypeDescription
operandAnyCall-site value or already-concrete operand.
bindingsdict[str, Any]Parent emit-time bindings.

Returns:

Any — Resolved value, or None when the operand is symbolic.

resolve_qubit_index
def resolve_qubit_index(self, v: 'Value', qubit_map: QubitMap, bindings: dict[str, Any]) -> int | None

Resolve a qubit value to its physical index.

Parameters:

NameTypeDescription
vValueScalar or indexed qubit value.
qubit_mapQubitMapPhysical resource mapping.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

int | None — int | None: Physical index, or None when unresolved.

resolve_qubit_index_detailed
def resolve_qubit_index_detailed(
    self,
    v: 'Value',
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> QubitResolutionResult

Resolve a Value to a physical qubit index with detailed failure info.

Parameters:

NameTypeDescription
vValueThe qubit Value to resolve. May be a scalar qubit or an array element (possibly through a sliced view chain).
qubit_mapQubitMapMapping from QubitAddress to physical qubit indices built by the resource allocator.
bindingsdict[str, Any]Active emit-time bindings used to resolve symbolic element indices and slice bounds.

Returns:

QubitResolutionResult — Success with the physical index, or a failure carrying a ResolutionFailureReason — including NEGATIVE_INDEX when a resolved element index is negative or a resolved slice bound violates the frontend contract (non-negative start, positive step); composing those through the affine map would silently address a wrong root slot.

resolve_slice_chain
def resolve_slice_chain(
    self,
    av: 'ArrayValue',
    bindings: dict[str, Any],
    *,
    operation: str = 'emit',
) -> tuple['ArrayValue', int, int]

Walk an ArrayValue’s slice_of chain and return root + affine map.

Composes the nested affine maps so that a view-local index i corresponds to the root-space index start + step * i. For a root ArrayValue (no slice_of chain), returns (av, 0, 1) so callers can always apply the same formula uniformly.

Parameters:

NameTypeDescription
av'ArrayValue'The possibly-sliced ArrayValue whose root and affine mapping should be resolved.
bindingsdict[str, Any]Compile-time parameter bindings; required when any slice_start / slice_step in the chain is symbolic.
operationstrHuman-readable name of the enclosing emit operation. Used only in the EmitError message when a symbolic slice bound cannot be resolved. Defaults to "emit".

Returns:

'ArrayValue' — Tuple (root_array, start, step) where root_array is int — the underlying non-sliced ArrayValue, and start/step int — are Python int values satisfying tuple['ArrayValue', int, int] — view[i] == root_array[start + step * i].

Raises:

Example:

>>> # For ``view = q[1::2]`` where ``q`` has 4 qubits:
>>> resolver.resolve_slice_chain(view_av, bindings={})
(q_av, 1, 2)

WhileOperation [source]

class WhileOperation(HasNestedOps, Operation)

Represents a while loop operation.

Only measurement-backed conditions are supported: the condition must be a Bit value produced by qmc.measure(). Non-measurement conditions (classical variables, constants, comparisons) are rejected by ValidateWhileContractPass before reaching engine emit.

Example::

bit = qmc.measure(q)
while bit:
    q = qmc.h(q)
    bit = qmc.measure(q)
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    operations: list[Operation] = list(),
    max_iterations: int | None = None,
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include rebind records and region args for cloning/substitution.

Same rationale as ForOperation.all_input_values: rebind records and region arguments reference body/pre-loop values by identity, so inline cloning must remap them in lockstep with body operands.

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus rebind-record and region-argument values.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the while body with explicit boundary values.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region whose block arguments and yields are aligned with region_args. The updated condition, when present, is appended as the final yield.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the while body and its complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt while operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, rebind-record, and region-arg values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


qamomile.circuit.transpiler.passes.emit_support.value_resolver

Value resolution helpers for emission.

Overview

FunctionDescription
block_parameter_binding_keysReturn the sanctioned emit-binding keys for an inner formal.
pair_block_parameter_operandsPair a block’s classical/object inputs with call-site operands.
resolve_qubit_keyResolve a qubit Value to its allocation key.
resolve_root_qubit_addressResolve an array-element value to its root (array_uuid, index).
ClassDescription
ArrayValueAn array of typed IR values.
EmitErrorReport an engine failure to emit one semantic operation.
QubitAddressTyped key for qubit/clbit physical-index maps.
QubitResolutionResultResult of attempting to resolve a qubit index.
ResolutionFailureReasonCategorizes why qubit index resolution failed.
ValueA typed SSA value in the IR.
ValueResolverResolves Value objects to concrete indices or values.

Functions

block_parameter_binding_keys [source]

def block_parameter_binding_keys(parameter: ValueBase) -> tuple[str, ...]

Return the sanctioned emit-binding keys for an inner formal.

Emit resolution accepts a kernel parameter name before its UUID for public API compatibility, so an operation-owned fresh scope must write both keys. Keeping the key choice here prevents individual emit paths from reviving a parent binding that merely shares the inner formal’s display name.

Parameters:

NameTypeDescription
parameterValueBaseClassical/object formal input being bound.

Returns:

tuple[str, ...] — tuple[str, ...]: UUID followed by the formal parameter provenance name and nonempty display-name compatibility key, without duplicates.


pair_block_parameter_operands [source]

def pair_block_parameter_operands(
    block: Block,
    param_operands: Sequence[ValueBase],
) -> list[tuple[ValueBase, ValueBase]]

Pair a block’s classical/object inputs with call-site operands.

Both compile-time lowering and emission bind an operation-owned block’s non-quantum inputs by their declaration order. Keeping the filtering and pairing here ensures those stages cannot adopt different positional conventions.

Parameters:

NameTypeDescription
blockBlockOperation-owned block whose formal inputs define the declaration order.
param_operandsSequence[ValueBase]Classical or object operands at the call site, already ordered according to the operation signature.

Returns:

list[tuple[ValueBase, ValueBase]] — list[tuple[ValueBase, ValueBase]]: (formal, actual) pairs in list[tuple[ValueBase, ValueBase]] — declaration order. Missing actual operands leave trailing formals list[tuple[ValueBase, ValueBase]] — unpaired, so they can remain symbolic and be provided at emit time.


resolve_qubit_key [source]

def resolve_qubit_key(qubit: 'Value') -> tuple[QubitAddress | None, bool]

Resolve a qubit Value to its allocation key.

Parameters:

NameTypeDescription
qubitValueQubit value to resolve. Array elements with a constant index are resolved through their full slice_of chain to the root array address.

Returns:

tuple[QubitAddress | None, bool] — tuple[QubitAddress | None, bool]: (address, is_array_element). address is the root-space address for a resolvable array element, None for an array element whose index or slice bounds are symbolic at this binding-free stage, and a scalar UUID address for non-array qubits. A negative constant index (or an out-of-contract slice bound) also yields None: resolve_root_qubit_address refuses it rather than letting it silently address a wrong root slot.


resolve_root_qubit_address [source]

def resolve_root_qubit_address(value: 'Value') -> tuple[str, int] | None

Resolve an array-element value to its root (array_uuid, index).

Walks the parent_array / slice_of chain and composes the nested affine slice maps, so view[i] resolves to (root_uuid, start + step * i) for the composed (start, step). The returned pair is the build-stable identity of the physical qubit slot: the root array’s QInitOperation always registers it as QubitAddress(root_uuid, index), so this address resolves even when the element’s own (per-version) UUID was never registered.

The transpiler’s resource allocator uses the same walk to resolve gate and measurement operands; this shared helper keeps both call sites consistent.

Parameters:

NameTypeDescription
valueValueThe value to resolve. Expected to be an array element (parent_array set with a single constant element_indices entry).

Returns:

tuple[str, int] | None — tuple[str, int] | None: (root_array_uuid, composed_index) when value is an array element with a constant index whose entire slice_of chain has constant slice_start / slice_step. None when value is not an array element, when its index is non-constant, or when any slice bound in the chain is non-constant (those cases are deferred to the emit-time resolver, which has bindings available). Also None for a negative constant index or a chain frame with negative slice_start / non-positive slice_step — composing those would silently address a wrong root slot, so they are refused rather than guessed (the frontend rejects them at trace time; this guard covers programmatically constructed IR).

Classes

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:

bool — True iff slice_of is non-None.

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

EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return
Constructor
def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

QubitAddress [source]

class QubitAddress

Typed key for qubit/clbit physical-index maps.

For scalar qubits: QubitAddress(uuid="abc123") For array elements: QubitAddress(uuid="abc123", element_index=2)

This replaces the f"{uuid}_{i}" string key pattern throughout the emit pipeline, making the key format explicit and preventing format-string bugs.

Constructor
def __init__(self, uuid: str, element_index: int | None = None) -> None
Attributes
Methods
from_composite_key
@classmethod
def from_composite_key(cls, key: str) -> QubitAddress

Parse a legacy composite key string into a QubitAddress.

The frontend stores qubit references as composite strings in the format "{array_uuid}_{element_index}" (e.g., cast operation qubit mappings, element UUIDs). This helper converts such strings to proper QubitAddress instances.

If the key does not match the composite format (i.e., the suffix after the last _ is not a non-negative integer), it is treated as a plain scalar UUID.

matches_array
def matches_array(self, array_uuid: str) -> bool

True if this address belongs to the given array.

with_element
def with_element(self, index: int) -> QubitAddress

Create an array-element address from this array’s base UUID.


QubitResolutionResult [source]

class QubitResolutionResult

Result of attempting to resolve a qubit index.

Constructor
def __init__(
    self,
    success: bool,
    index: int | None = None,
    failure_reason: ResolutionFailureReason | None = None,
    failure_details: str = '',
) -> None
Attributes

ResolutionFailureReason [source]

class ResolutionFailureReason(Enum)

Categorizes why qubit index resolution failed.

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 engine resource allocation. This applies to every Value regardless of its type (Qubit, Float, Bit, ...) -- it is not specific to qubits.


ValueResolver [source]

class ValueResolver

Resolves Value objects to concrete indices or values.

Constructor
def __init__(self, parameters: set[str] | None = None)

Create an emit-time resolver.

Parameters:

NameTypeDescription
parametersset[str] | NoneNames preserved as engine runtime parameters. Defaults to None.
Attributes
Methods
bind_block_params
def bind_block_params(
    self,
    block_value: Any,
    param_operands: list['Value'],
    bindings: dict[str, Any],
    *,
    parameter_factory: Callable[[str, str], Any] | None = None,
) -> dict[str, Any]

Create local bindings by matching block inputs to call-site operands.

Parameters:

NameTypeDescription
block_valueAnyNested block whose classical/object inputs are bound. Objects without input_values receive no additional local bindings for compatibility with optional engine recipes.
param_operandslist[Value]Classical/object call-site operands in the controlled operation’s signature order.
bindingsdict[str, Any]Parent emit-time bindings used to resolve the call-site operands.
parameter_factoryCallable[[str, str], Any] | NoneOptional engine parameter factory used when an operand is a declared runtime parameter rather than a concrete binding. Defaults to None so standalone resolver use remains engine-neutral.

Returns:

dict[str, Any] — dict[str, Any]: Parent bindings with each inner formal rebound under both its UUID and sanctioned parameter-name key.

get_parameter_key
def get_parameter_key(self, value: 'Value', bindings: dict[str, Any]) -> str | None

Get the engine parameter key for a symbolic scalar.

Parameters:

NameTypeDescription
valueValueScalar value or array element to identify.
bindingsdict[str, Any]Active bindings used to resolve element indices and slice offsets.

Returns:

str | None — str | None: Scalar name or root-array indexed key, or None when an array element’s root location is unresolved.

lookup_in_bindings
def lookup_in_bindings(
    self,
    value: Any,
    bindings: dict[str, Any],
    *,
    index_array: bool = False,
) -> Any

Canonical resolution chain for a Value against bindings.

All other resolver methods (resolve_bound_value, resolve_classical_value, resolve_int_value, resolve_operand_for_binding) wrap this single chain. Centralizing precedence here prevents the historical drift where one resolver checked is_parameter before UUID and another checked it after, which manifested as obscure binding failures when name-keyed writes were dropped from the emit pass.

Resolution order (each step returns immediately on a hit):

  1. value is already a concrete Python scalar (no uuid).

  2. value.uuid is in bindings — return that. This is where emit-time-computed intermediates (evaluate_binop / evaluate_classical_predicate results) and merge aliases live.

  3. A compile-time array or dict payload stored in typed metadata.

  4. value.is_constant() — return value.get_const().

  5. value.is_parameter() and its parameter name is in bindings — return that.

  6. (When index_array=True) value is an array element with a resolvable parent in bindings — index into it.

  7. A non-empty display name is present in bindings. This is a compatibility bridge for programmatically constructed Values and older transforms that do not carry parameter metadata; UUID and explicit parameter provenance always take precedence.

Compiler-created temporaries are anonymous and compiler-internal writers use UUID keys, so the compatibility bridge cannot merge two same-named temporaries. Kernel parameters should normally resolve via explicit parameter metadata, while loop variables and intermediates remain UUID-keyed.

Parameters:

NameTypeDescription
valueAnyThe IR value (or already-concrete Python scalar) to resolve.
bindingsdict[str, Any]The active bindings dictionary.
index_arrayboolWhen True, also resolve array-element accesses via parent_array indexing. Off by default because not all callers want to index into bound containers.

Returns:

Any — The resolved Python value, or None if no step matched.

resolve_bound_value
def resolve_bound_value(self, value: 'Value', bindings: dict[str, Any]) -> Any

Resolve a Value to its raw bound Python object.

Wraps :meth:lookup_in_bindings with index_array=True so that arr[i] accesses against a bound container resolve to the element. Does not coerce the result — callers that need a numeric scalar should go through :meth:resolve_classical_value.

Parameters:

NameTypeDescription
valueValueValue to resolve.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

Any — Raw bound object, or None when unresolved.

resolve_classical_value
def resolve_classical_value(self, value: 'Value', bindings: dict[str, Any]) -> Any

Resolve a classical Value to a concrete Python value.

Numeric bindings are normalized to native Python scalars regardless of whether they come from a direct binding or from array-element indexing, so downstream isinstance(x, (int, float)) checks are stable when callers bind np.pi/4 or the like. bool is preserved (not coerced to int). Non-numeric values (Hamiltonians, strings, dict values, …) pass through unchanged.

Parameters:

NameTypeDescription
valueValueClassical value to resolve.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

Any — Resolved native scalar/object, or None when unresolved.

resolve_int_value
def resolve_int_value(self, val: Any, bindings: dict[str, Any]) -> int | None

Resolve a value to an integer, or None when unresolvable.

Unresolvable symbolic Values must return None. The previous return 0 fallback caused silent loop elision when parameter shape dims (gamma_dim0) reached this resolver without being folded into constants — downstream loop-bound resolution saw 0 and quietly emitted an empty loop. Returning None propagates the failure to emit_for_unrolled, which converts it into a hard compile error.

resolve_operand_for_binding
def resolve_operand_for_binding(self, operand: Any, bindings: dict[str, Any]) -> Any

Resolve an operand to a concrete value for block parameter binding.

Used when calling a sub-block (e.g. a controlled-U body): each param operand at the call site must resolve to a value to seed the callee’s parameter bindings.

Parameters:

NameTypeDescription
operandAnyCall-site value or already-concrete operand.
bindingsdict[str, Any]Parent emit-time bindings.

Returns:

Any — Resolved value, or None when the operand is symbolic.

resolve_qubit_index
def resolve_qubit_index(self, v: 'Value', qubit_map: QubitMap, bindings: dict[str, Any]) -> int | None

Resolve a qubit value to its physical index.

Parameters:

NameTypeDescription
vValueScalar or indexed qubit value.
qubit_mapQubitMapPhysical resource mapping.
bindingsdict[str, Any]Active UUID/parameter bindings.

Returns:

int | None — int | None: Physical index, or None when unresolved.

resolve_qubit_index_detailed
def resolve_qubit_index_detailed(
    self,
    v: 'Value',
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> QubitResolutionResult

Resolve a Value to a physical qubit index with detailed failure info.

Parameters:

NameTypeDescription
vValueThe qubit Value to resolve. May be a scalar qubit or an array element (possibly through a sliced view chain).
qubit_mapQubitMapMapping from QubitAddress to physical qubit indices built by the resource allocator.
bindingsdict[str, Any]Active emit-time bindings used to resolve symbolic element indices and slice bounds.

Returns:

QubitResolutionResult — Success with the physical index, or a failure carrying a ResolutionFailureReason — including NEGATIVE_INDEX when a resolved element index is negative or a resolved slice bound violates the frontend contract (non-negative start, positive step); composing those through the affine map would silently address a wrong root slot.

resolve_slice_chain
def resolve_slice_chain(
    self,
    av: 'ArrayValue',
    bindings: dict[str, Any],
    *,
    operation: str = 'emit',
) -> tuple['ArrayValue', int, int]

Walk an ArrayValue’s slice_of chain and return root + affine map.

Composes the nested affine maps so that a view-local index i corresponds to the root-space index start + step * i. For a root ArrayValue (no slice_of chain), returns (av, 0, 1) so callers can always apply the same formula uniformly.

Parameters:

NameTypeDescription
av'ArrayValue'The possibly-sliced ArrayValue whose root and affine mapping should be resolved.
bindingsdict[str, Any]Compile-time parameter bindings; required when any slice_start / slice_step in the chain is symbolic.
operationstrHuman-readable name of the enclosing emit operation. Used only in the EmitError message when a symbolic slice bound cannot be resolved. Defaults to "emit".

Returns:

'ArrayValue' — Tuple (root_array, start, step) where root_array is int — the underlying non-sliced ArrayValue, and start/step int — are Python int values satisfying tuple['ArrayValue', int, int] — view[i] == root_array[start + step * i].

Raises:

Example:

>>> # For ``view = q[1::2]`` where ``q`` has 4 qubits:
>>> resolver.resolve_slice_chain(view_av, bindings={})
(q_av, 1, 2)

qamomile.circuit.transpiler.passes.entrypoint_validation

Entrypoint validation pass for top-level transpilation.

Overview

ClassDescription
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
EntrypointValidationErrorError when a top-level transpilation entrypoint has unsupported I/O.
EntrypointValidationPassValidate top-level entrypoint constraints.
PassBase class for all compiler passes.
ValidationErrorError during validation (e.g., non-classical I/O).

Classes

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.


BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

EntrypointValidationError [source]

class EntrypointValidationError(ValidationError)

Error when a top-level transpilation entrypoint has unsupported I/O.


EntrypointValidationPass [source]

class EntrypointValidationPass(Pass[Block, Block])

Validate top-level entrypoint constraints.

Attributes
Methods
run
def run(self, input: Block) -> Block

Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


ValidationError [source]

class ValidationError(QamomileCompileError)

Error during validation (e.g., non-classical I/O).

Constructor
def __init__(self, message: str, value_name: str | None = None)

Initialize a validation diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable validation failure.
value_namestr | NoneRelated IR value name. Defaults to None.
Attributes

qamomile.circuit.transpiler.passes.eval_utils

Preserve compiler imports for the shared classical IR evaluator.

Evaluation semantics live in ir.classical_eval so frontend tracing and compiler passes use the same pure operations without reversing dependencies.

Overview

FunctionDescription
evaluate_binop_valuesEvaluate a binary arithmetic operation on two concrete values.
evaluate_compop_valuesEvaluate a comparison operation on two concrete values.
evaluate_condop_valuesEvaluate a logical and/or operation on two concrete values.
evaluate_notop_valueEvaluate a logical-not operation on a concrete value.
evaluate_runtime_op_valuesEvaluate a lowered runtime-classical expression on concrete operands.
evaluate_unary_math_valueEvaluate one unary mathematical operation on a concrete value.
fold_classical_opFold a classical op to a concrete value, respecting the given policy.
ClassDescription
FoldPolicyPolicy controlling how fold_classical_op treats parameters.

Functions

evaluate_binop_values [source]

def evaluate_binop_values(
    kind: BinOpKind | None,
    left: float | int,
    right: float | int,
) -> float | int | None

Evaluate a binary arithmetic operation on two concrete values.

Parameters:

NameTypeDescription
kindBinOpKind | NoneArithmetic operation to apply.
leftfloat | intLeft numeric operand.
rightfloat | intRight numeric operand.

Returns:

float | int | None — float | int | None: Result, or None on division by zero, unknown kind, or arithmetic error.


evaluate_compop_values [source]

def evaluate_compop_values(kind: CompOpKind | None, left: Any, right: Any) -> bool | None

Evaluate a comparison operation on two concrete values.

Parameters:

NameTypeDescription
kindCompOpKind | NoneComparison operation to apply.
leftAnyLeft operand.
rightAnyRight operand.

Returns:

bool | None — bool | None: Boolean result, or None on unknown kind or type incompatibility.


evaluate_condop_values [source]

def evaluate_condop_values(kind: CondOpKind | None, left: Any, right: Any) -> bool | None

Evaluate a logical and/or operation on two concrete values.

Parameters:

NameTypeDescription
kindCondOpKind | NoneBoolean operation to apply.
leftAnyLeft operand.
rightAnyRight operand.

Returns:

bool | None — bool | None: Boolean result, or None on unknown kind.


evaluate_notop_value [source]

def evaluate_notop_value(operand: Any) -> bool | None

Evaluate a logical-not operation on a concrete value.

Parameters:

NameTypeDescription
operandAnyOperand to negate.

Returns:

bool | None — bool | None: Boolean negation, or None on type error.


evaluate_runtime_op_values [source]

def evaluate_runtime_op_values(kind: RuntimeOpKind | None, operands: list[Any]) -> Any | None

Evaluate a lowered runtime-classical expression on concrete operands.

Delegates to the same family evaluators used by BinOp, CompOp, CondOp, and NotOp so lowering an operation changes only when it is evaluated, not its scalar semantics.

Parameters:

NameTypeDescription
kindRuntimeOpKind | NoneUnified lowered operation kind.
operandslist[Any]Concrete operands in IR order. NOT requires one operand; every other kind requires two.

Returns:

Any | None — Any | None: Evaluated numeric or boolean result, or None when the kind/arity is invalid or the underlying operation fails.


evaluate_unary_math_value [source]

def evaluate_unary_math_value(kind: UnaryMathOpKind | None, operand: float | int) -> float | int | None

Evaluate one unary mathematical operation on a concrete value.

Parameters:

NameTypeDescription
kindUnaryMathOpKind | NoneMathematical operation to apply.
operandfloat | intConcrete numeric operand.

Returns:

float | int | None — float | int | None: Computed value, or None for an invalid domain or missing operation kind.


fold_classical_op [source]

def fold_classical_op(
    op: 'BinOp | CompOp | CondOp | NotOp | UnaryMathOp',
    operand_resolver: Callable[[Any], Any],
    parameters: set[str],
    policy: FoldPolicy,
) -> Any | None

Fold a classical op to a concrete value, respecting the given policy.

The caller supplies an operand_resolver callable that knows how to look up a Value in the caller’s context (a concrete_values map, an emit bindings dict + ValueResolver, or any other source). This function handles:

  1. The parameter guard (skips folding when an operand is a runtime parameter or parameter-array element under EMIT_RESPECT_PARAMS).

  2. Strict scalar-only typing (rejects engine Expr objects and other non-numeric values that would spuriously fold to True).

  3. Kind dispatch via the underlying evaluate_*_values primitives.

Parameters:

NameTypeDescription
opBinOp | CompOp | CondOp | NotOp | UnaryMathOpClassical op to fold using the supplied operand resolver.
operand_resolverCallable[[Any], Any]Map each operand Value to a resolved Python scalar (or None when unresolvable).
parametersset[str]Runtime parameter names. Used only when policy is EMIT_RESPECT_PARAMS.
policyFoldPolicyFolding policy. See FoldPolicy docstring.

Returns:

Any | None — Any | None: Folded numeric value or boolean predicate, or None when an operand is symbolic, missing, or a runtime parameter under the policy.

Classes

FoldPolicy [source]

class FoldPolicy(enum.Enum)

Policy controlling how fold_classical_op treats parameters.

COMPILE_TIME is for passes that have no notion of runtime parameters (e.g. compile_time_if_lowering); every operand the resolver returns is treated as a real value to fold.

EMIT_RESPECT_PARAMS is for emit-time passes where some Values may correspond to runtime engine parameters whose concrete values are placeholders or absent. Operands whose Value or parent_array.name is in the active parameters set are treated as symbolic and the fold returns None rather than producing an incorrect concrete result.

Attributes

qamomile.circuit.transpiler.passes.inline

Inline pass: resolve inline callable invocations to create an affine block.

Overview

FunctionDescription
count_inline_invokesCount all inlineable calls reachable from an operation list.
count_unrollable_inline_invokesCount inlineable calls the inline/partial-eval loop can still resolve.
find_return_operationFind the ReturnOperation in a list of operations (expected at the end).
walk_operationsYield operations in preorder across every nested control-flow region.
ClassDescription
ArrayValueAn array of typed IR values.
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
CallPolicyDescribe the default lowering policy for a callable call.
CallTransformDescribe the requested transform of a callable implementation.
ControlledUOperationBase class for controlled-U operations.
DictValueA dictionary value stored as stable ordered entries.
HasNestedOpsMixin for operations that contain nested operation lists.
InlinePassInline qkernel callables to create an affine block.
InverseBlockOperationRepresent an inverse qkernel/block as a first-class IR operation.
InvokeOperationRepresent a composite, stdlib, or oracle call.
PassBase class for all compiler passes.
QubitConsumedErrorQubit handle used after being consumed by a previous operation.
ReturnOperationExplicit return operation marking the end of a block with return values.
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
TupleValueA tuple of IR values for structured data.
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.

Constants

Functions

count_inline_invokes [source]

def count_inline_invokes(operations: list[Operation]) -> int

Count all inlineable calls reachable from an operation list.

Recurses into InverseBlockOperation / ControlledUOperation / SelectOperation nested blocks and into HasNestedOps bodies, so calls hidden inside control flow or operation-owned blocks are counted. unroll_recursion uses this as the primary termination signal (count == 0 means the block is fully inlined).

Parameters:

NameTypeDescription
operationslist[Operation]Operations to scan.

Returns:

int — Total number of inlineable calls reachable from operations.


count_unrollable_inline_invokes [source]

def count_unrollable_inline_invokes(operations: list[Operation]) -> int

Count inlineable calls the inline/partial-eval loop can still resolve.

This mirrors :func:count_inline_invokes but does not descend into a ControlledUOperation.block, an InverseBlockOperation’s nested blocks, or a SelectOperation case block. A call still inside one of those operation-owned blocks after a full inline pass is a self-recursive call that inline’s cycle guard could not unroll — it stops after one layer and does not re-enter the operation-owned block — so no later unroll_recursion iteration can resolve it. Folding compile-time ifs there never removes the trapped call itself. Such a call is therefore not unrollable. Calls at the top level or inside For / If / While bodies are unrollable and are counted.

The unroll loop uses this to tell two failure modes apart: a non-zero :func:count_inline_invokes with a zero count_unrollable_inline_invokes means every residual call is trapped inside a controlled / inverted block (i.e. a recursive qkernel was passed to qmc.control / qmc.inverse), as opposed to a genuinely non-terminating top-level recursion.

Parameters:

NameTypeDescription
operationslist[Operation]Operations to scan.

Returns:

int — Number of inlineable calls reachable without entering a ControlledUOperation.block, InverseBlockOperation nested block, or SelectOperation case block.


find_return_operation [source]

def find_return_operation(operations: list[Operation]) -> ReturnOperation | None

Find the ReturnOperation in a list of operations (expected at the end).


walk_operations [source]

def walk_operations(operations: Sequence[Operation]) -> Iterable[Operation]

Yield operations in preorder across every nested control-flow region.

Parameters:

NameTypeDescription
operationsSequence[Operation]Top-level semantic operations.

Returns:

Iterable[Operation] — Iterable[Operation]: Preorder traversal including nested operations.

Classes

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:

bool — True 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.


BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

CallPolicy [source]

class CallPolicy(enum.Enum)

Describe the default lowering policy for a callable call.

Attributes

CallTransform [source]

class CallTransform(enum.Enum)

Describe the requested transform of a callable implementation.

Attributes
Methods
inverted
def inverted(self) -> CallTransform

Toggle inverse application while preserving coherent control.

Returns:

CallTransform — Transform with the inverse component toggled.


ControlledUOperation [source]

class ControlledUOperation(Operation)

Base class for controlled-U operations.

Two concrete subclasses handle distinct operand layouts:

All isinstance(op, ControlledUOperation) checks match every subclass.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int | Value = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]
replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

DictValue [source]

class DictValue(_MetadataValueMixin, ValueBase)

A dictionary value stored as stable ordered entries.

Constructor
def __init__(
    self,
    name: str,
    entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> DictValue

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


InlinePass [source]

class InlinePass(Pass[Block, Block])

Inline qkernel callables to create an affine block.

This pass recursively inlines function calls while preserving control flow structures (For, If, While).

Input: Block with BlockKind.HIERARCHICAL (may contain callable calls) Output: Block with BlockKind.AFFINE (no inline callable calls)

Parameters:

NameTypeDescription
body_selectorCallable[[InvokeOperation], Block | None] | NoneOptional body-selection hook for consumers whose configured strategy differs from InvokeOperation.strategy_name. The standard compiler leaves this unset. Defaults to None.
preserve_bound_quantum_identityboolWhether cloned callee quantum values should retain the logical owner and array-element address of their bound caller operands. Resource liveness analysis enables this so an inline call does not create phantom owners or erase lane identities. Defaults to False.
preserve_bound_array_identityboolWhether cloned callee array values should retain the logical lineage of bound caller arrays. Resource classical-state analysis enables this so loop-carried stores remain connected across an inlined call. Defaults to False.
Constructor
def __init__(
    self,
    body_selector: Callable[[InvokeOperation], Block | None] | None = None,
    *,
    inline_prefix_factory: Callable[[InvokeOperation, tuple[tuple[ArrayValue, tuple[ArrayValue, ...]], ...]], Sequence[Operation]] | None = None,
    preserve_bound_quantum_identity: bool = False,
    preserve_bound_array_identity: bool = False,
) -> None

Initialize the pass with body-selection and identity policies.

Parameters:

NameTypeDescription
body_selectorCallable[[InvokeOperation], Block | None] | NoneConsumer-specific selector used for inline-policy calls. Defaults to the invocation’s ordinary effective body.
preserve_bound_quantum_identityboolWhether cloned quantum SSA values descending from a formal input retain the actual caller operand’s logical owner and array-element address. Defaults to False.
preserve_bound_array_identityboolWhether cloned array SSA values descending from a formal input retain the actual caller array’s logical lineage. Defaults to False.
Attributes
Methods
run
def run(self, input: Block) -> Block

Inline all inline-policy callable invocations.

Self-recursive qkernel invocations are unrolled one level per call: the inner self-call is substituted but left intact so the outer fixed-point loop can fold the base-case if between iterations. The output kind is AFFINE when no inlineable calls remain, otherwise HIERARCHICAL.


InverseBlockOperation [source]

class InverseBlockOperation(Operation)

Represent an inverse qkernel/block as a first-class IR operation.

The operation stores both the original forward block and a Qamomile-built inverse implementation block. Emitters may use source_block with a engine-native inverse/adjoint primitive, then fall back to implementation_block when native inversion is unavailable.

Operands are ordered as scalar control qubits, target quantum operands, then classical/object parameters. Results mirror the quantum operand layout: control results first, then one target result per target operand. Vector target operands therefore count as one operand/result while contributing their scalar width to num_target_qubits.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_control_qubits: int = 0,
    num_target_qubits: int = 0,
    custom_name: str = '',
    source_block: Block | None = None,
    implementation_block: Block | None = None,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_value: int | None = None,
) -> None
Attributes

InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.
Constructor
def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes
Methods
body_for_transform
def body_for_transform(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> tuple[Block | None, CallTransform]

Select a body and report the transform it already realizes.

A controlled-inverse invocation may reuse an explicitly registered inverse body when no implementation realizes both transforms. Keeping that fallback in the IR operation gives emitters and static analyses one selection rule while still letting each consumer apply the remaining coherent controls in its own representation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — tuple[Block | None, CallTransform]: Selected body and the transform CallTransform — already implemented by that body. The callable’s direct body is tuple[Block | None, CallTransform] — returned with DIRECT when no transform-specific body matches.

Raises:

effective_body
def effective_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — Block | None: Selected implementation body, or the callable’s Block | None — default body when no transform-specific implementation exists. Block | None — A compiler may synthesize inverse or controlled behavior from this Block | None — fallback body.

implementation_for
def implementation_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None, which only selects engine-generic implementations.
strategystr | NoneStrategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation candidate, CallableImplementation | None — or None when the callable definition has no match.

measurement_result_indices_for
def measurement_result_indices_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> frozenset[int]

Return measurement-derived results for one selected implementation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name used for implementation selection. Defaults to None.
strategystr | NoneStrategy name used for implementation selection. Defaults to the invocation’s strategy_name.

Returns:

frozenset[int] — frozenset[int]: Caller-local result positions derived from measurement in the selected body.

Raises:

select_body
def select_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> CallableBodySelection

Select and validate the composable body for this invocation.

The result carries the transform already realized by the body and the exact call-site values that bind to it. Consumers therefore cannot independently disagree about whether an invocation’s control prefix belongs to the selected implementation ABI.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

CallableBodySelection — Validated body, realized transform, and CallableBodySelection — aligned call-site operands and results.

Raises:


Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


QubitConsumedError [source]

class QubitConsumedError(AffineTypeError)

Qubit handle used after being consumed by a previous operation.

Each qubit handle can only be used once. After a gate operation, you must reassign the result to use the new handle.

Example of incorrect code:

q1 = qm.h(q) q2 = qm.x(q) # ERROR: q was already consumed by h()

Correct code:

q = qm.h(q) # Reassign to capture new handle q = qm.x(q) # Use the reassigned handle


ReturnOperation [source]

class ReturnOperation(Operation)

Explicit return operation marking the end of a block with return values.

This operation represents an explicit return statement in the IR. It takes the values to be returned as operands and produces no results (it is a terminal operation that transfers control flow back to the caller).

operands: [Value, ...] - The values to return (may be empty for void returns) results: [] - Always empty (terminal operation)

Example:

A function that returns two values (a UInt and a Float):

ReturnOperation(
    operands=[uint_value, float_value],
    results=[],
)

The signature would be:
    operands=[ParamHint("return_0", UIntType()), ParamHint("return_1", FloatType())]
    results=[]
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

SelectOperation [source]

class SelectOperation(Operation)

Quantum multiplexer: apply case_blocks[i] when the index reads i.

Concrete operand layout: [idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...]. Symbolic-width operand layout: [idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...]. Results mirror the quantum operand grouping.

A concrete index register is normalized to one scalar Qubit operand per physical index qubit. A symbolic-width register instead retains each leading caller argument as one scalar or array operand until its bound shape is known. Whole-Vector[Qubit] / scalar targets follow and keep their shapes, and classical parameters shared across every case come last.

Index bit order is LSB-first: idx_0 is the least-significant bit, matching Qamomile’s qubit-zero convention. Case i is selected when index qubit j reads bit j of i. len(case_blocks) need not be a power of two; index values >= len(case_blocks) apply no operation (identity).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_index_qubits: int | Value = 0,
    case_blocks: list[Block] = list(),
    num_index_args: int = 0,
    case_callable_attrs: list[dict[str, Any]] = list(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Return every value consumed by the SELECT operation.

Returns:

list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width value when present.

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed replacement values.

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


TupleValue [source]

class TupleValue(_MetadataValueMixin, ValueBase)

A tuple of IR values for structured data.

Constructor
def __init__(
    self,
    name: str,
    elements: tuple[ValueLike, ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> TupleValue

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


qamomile.circuit.transpiler.passes.parameter_shape_resolution

Compile-time resolution of symbolic Vector parameter shape dimensions.

Qiskit / CUDA-Q / QuriParts circuits are fixed-structure at compile time: loop bounds and array lengths must be concrete to emit a valid circuit. Top-level Vector[Float] / Vector[UInt] parameters are created with symbolic {name}_dim{i} Values (see qamomile.circuit.frontend.func_to_block.create_dummy_input), so when a kernel queries arr.shape[i] the IR references those symbolic Values in loop operands, array allocations, etc.

This pass walks the HIERARCHICAL block before inlining and, for every input array whose name is bound to a concrete array-like value in bindings, replaces its symbolic shape dim Values with constant Values holding the runtime length. After this pass the downstream pipeline can unroll for i in qmc.range(arr.shape[0]) loops normally.

Parameters without a concrete binding (e.g. the library QAOA pattern where only p is bound and gammas.shape is never queried) are left untouched — their symbolic dims simply do not flow into any compile-time structure decision, so they are harmless.

Overview

ClassDescription
ArrayValueAn array of typed IR values.
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
HasNestedOpsMixin for operations that contain nested operation lists.
ParameterShapeResolutionPassSubstitute symbolic parameter array shape dims with concrete constants.
PassBase class for all compiler passes.
UIntTypeType representing an unsigned integer.
ValidationErrorError during validation (e.g., non-classical I/O).
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.

Constants

Classes

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:

bool — True 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.


BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


ParameterShapeResolutionPass [source]

class ParameterShapeResolutionPass(Pass[Block, Block])

Substitute symbolic parameter array shape dims with concrete constants.

Input: BlockKind.HIERARCHICAL (runs before InlinePass). Output: same block kind, with matching shape dim Values constant-folded.

Constructor
def __init__(self, bindings: dict[str, Any] | None = None) -> None

Initialize parameter-shape resolution.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneCompile-time bindings keyed by entrypoint argument name. Defaults to None.
Attributes
Methods
run
def run(self, input: Block) -> Block

Replace resolvable symbolic array dimensions with constants.

Parameters:

NameTypeDescription
inputBlockHierarchical semantic block to rewrite.

Returns:

Block — Rewritten block preserving all display, ABI, parameter, and stage metadata.

Raises:


Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


UIntType [source]

class UIntType(ClassicalTypeMixin, ValueType)

Type representing an unsigned integer.


ValidationError [source]

class ValidationError(QamomileCompileError)

Error during validation (e.g., non-classical I/O).

Constructor
def __init__(self, message: str, value_name: str | None = None)

Initialize a validation diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable validation failure.
value_namestr | NoneRelated IR value name. Defaults to None.
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 engine 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.


qamomile.circuit.transpiler.passes.partial_eval

Partial evaluation pass for compile-time simplification.

Overview

FunctionDescription
block_parameter_binding_keysReturn the sanctioned emit-binding keys for an inner formal.
pair_block_parameter_operandsPair a block’s classical/object inputs with call-site operands.
reject_control_flow_quantum_discardReject control-flow-internal quantum rebinds that discard state.
reject_loop_carried_classical_rebindsReject in-loop classical scalar rebinds that cannot compile correctly.
reject_self_referential_loop_storesReject in-loop classical element stores that read the same array.
ClassDescription
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
CompileTimeIfLoweringPassLowers compile-time resolvable IfOperations before separation.
ConstantFoldingPassEvaluates constant expressions at compile time.
HasNestedOpsMixin for operations that contain nested operation lists.
PartialEvaluationPassFold constants and lower compile-time control flow.
PassBase class for all compiler passes.
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
UnifiedValueResolverResolve IR Values to concrete Python values.
ValidationErrorError during validation (e.g., non-classical I/O).

Functions

block_parameter_binding_keys [source]

def block_parameter_binding_keys(parameter: ValueBase) -> tuple[str, ...]

Return the sanctioned emit-binding keys for an inner formal.

Emit resolution accepts a kernel parameter name before its UUID for public API compatibility, so an operation-owned fresh scope must write both keys. Keeping the key choice here prevents individual emit paths from reviving a parent binding that merely shares the inner formal’s display name.

Parameters:

NameTypeDescription
parameterValueBaseClassical/object formal input being bound.

Returns:

tuple[str, ...] — tuple[str, ...]: UUID followed by the formal parameter provenance name and nonempty display-name compatibility key, without duplicates.


pair_block_parameter_operands [source]

def pair_block_parameter_operands(
    block: Block,
    param_operands: Sequence[ValueBase],
) -> list[tuple[ValueBase, ValueBase]]

Pair a block’s classical/object inputs with call-site operands.

Both compile-time lowering and emission bind an operation-owned block’s non-quantum inputs by their declaration order. Keeping the filtering and pairing here ensures those stages cannot adopt different positional conventions.

Parameters:

NameTypeDescription
blockBlockOperation-owned block whose formal inputs define the declaration order.
param_operandsSequence[ValueBase]Classical or object operands at the call site, already ordered according to the operation signature.

Returns:

list[tuple[ValueBase, ValueBase]] — list[tuple[ValueBase, ValueBase]]: (formal, actual) pairs in list[tuple[ValueBase, ValueBase]] — declaration order. Missing actual operands leave trailing formals list[tuple[ValueBase, ValueBase]] — unpaired, so they can remain symbolic and be provided at emit time.


reject_control_flow_quantum_discard [source]

def reject_control_flow_quantum_discard(operations: list[Operation], bindings: dict[str, Any] | None = None) -> None

Reject control-flow-internal quantum rebinds that discard state.

The decoration-time rebind analyzer intentionally suppresses branch-internal violations (its snapshot-restore scope truncates them) so that compile-time-if branch-selection rebinds stay legal. That leaves a runtime hole: rebinding a quantum variable inside a runtime branch — to a fresh allocation (if cond: q = qmc.qubit("fresh")) or to any other quantum value (if cond: q = other, including in both branches at once) — silently drops the variable’s pre-branch state exactly when a rebinding branch is taken. The frontend records every branch-internal quantum binding change on the IfOperation (BranchRebind, preserving the pre-branch value even when it no longer appears in any merge); this check verifies each record against each runtime execution path and raises QubitRebindError — the same AffineTypeError the decoration-time analyzer raises for a top-level rebind from a different quantum source, since this is that exact affine violation surfacing at runtime inside a branch — when the pre-branch value has no owner on a rebinding path: not consumed inside the taken branch, not carried out through any merge of that side, and not referenced by any operation outside the if. Scalar Qubit and whole-register Vector[Qubit] rebinds are covered alike.

Loop bodies are covered more strictly than branches (see :func:_check_loop_quantum_discards): the frontend records quantum rebinds on ForOperation / ForItemsOperation / WhileOperation (LoopCarriedRebind entries whose before is quantum), and each record is rejected unless it carries the incoming value forward on the same wires, is a covered loop-invariant rebind, or is the terminal fresh-allocation pattern where nested QInitOperation reset/prepare-zero emission gives qmc.qubit() fresh-per-iteration semantics. In-body consumption of the incoming value itself is not an exemption: the read re-executes against the traced register every iteration and matches Python semantics only for the first one. A loop-body rebind needs no runtime/compile-time classification, so loops are checked wherever they appear on a live (non-pruned) path, trip-count-agnostically, exactly like the classical loop-carried check.

IfOperations are classified with the same condition resolution CompileTimeIfLoweringPass uses (via bindings), including for ifs nested inside runtime branches. A rebind confined to a compile-time branch stays legal when the surrounding control flow is compile-time too: rebinding to an alternative register under a compile-time flag is the documented branch-selection idiom, and a dead branch is eliminated entirely. A compile-time-TAKEN rebind nested inside a runtime branch inherits that branch’s runtime conditionality and is checked (and rejected when it discards). Only ifs whose condition transitively derives from a measurement result are checked — the same taint analysis the classical-lowering pipeline uses, so expression-derived runtime conditions (~bit, a & b) are covered; a non-measurement, non-compile-time condition cannot drive runtime branching and is rejected at emit by the shared condition resolution (though for this discard shape the emit-side merge physical-resource check can fire first with its generic message).

What stays allowed:

The check is deliberately conservative toward allowing where it cannot be exact. Merge lineage is over-approximated: producers without a positional qubit model (composite gates, controlled blocks, casts) contribute all of their quantum inputs as possible roots, so the carried exemption can only grow — a rejection requires the pre-branch value to be provably absent from every merge lineage. Outside-ownership evidence is path-sensitive with respect to enclosing ifs (a read on the sibling branch of an enclosing runtime if does not exempt), but path-insensitive for non-ancestor runtime ifs elsewhere: a value conditionally consumed downstream counts as owned. Rebinds inside compile-time-TAKEN ifs nested in a runtime branch are promoted to the enclosing if’s check trip-count- and loop-agnostically; because the lowering pass erases those nested ifs (and their records), the promoted rebinds are only caught by the pre-fold PartialEvaluationPass hook, not by the AnalyzePass safety net.

Scope contract: the scan recurses through control-flow nesting only (IfOperation branches and HasNestedOps bodies). Boxed implementation blocks — InvokeOperation bodies and implementations, InverseBlockOperation.implementation_block, ControlledUOperation.block — are NOT descended into: they stay HIERARCHICAL recipe blocks outside the entrypoint pipeline, exactly like every other transpile-time rebind check (reject_loop_carried_classical_rebinds, AffineValidationPass, both built on the same HasNestedOps walk). A discard written inside a composite’s recipe kernel is therefore only covered by the decoration-time top-level analyzer, with the same branch/loop suppression as everywhere else pre-IR.

Exposed at module scope because it runs from two passes: PartialEvaluationPass calls it before folding and if-lowering (with bindings, so compile-time branches are classified exactly as the lowering pass will lower them), and AnalyzePass calls it again as a safety net for pipelines that skip partial_eval.

Parameters:

NameTypeDescription
operationslist[Operation]Operations to scan. Recurses through all control flow; every runtime if and every loop at any nesting depth on a live path is checked.
bindingsdict[str, Any] | NoneCompile-time parameter bindings used to resolve IfOperation conditions, matching what CompileTimeIfLoweringPass will later resolve. Defaults to None (no bindings).

Raises:


reject_loop_carried_classical_rebinds [source]

def reject_loop_carried_classical_rebinds(
    operations: list[Operation],
    bindings: dict[str, Any] | None = None,
    output_values: list[ValueLike] | None = None,
) -> None

Reject in-loop classical scalar rebinds that cannot compile correctly.

A loop body is traced once, so a Python-level reassignment like total = total + i inside a qmc.range / while / qmc.items loop reads a fixed pre-loop value instead of the previous iteration’s value. Every executor (the classical segment interpreter and emit-time unrolling) re-runs the same traced operations per iteration, so the program silently diverges from Python semantics (e.g. total ends as 0 + i_last instead of the sum). The frontend records candidate rebinds on the loop operations (LoopCarriedRebind); this check rejects the classical ones that survive dead-branch pruning. Records whose before is quantum model state discard, not traced-once divergence — they are skipped here and rejected by :func:reject_control_flow_quantum_discard instead.

IfOperations are classified with the same condition resolution CompileTimeIfLoweringPass uses (via bindings): a rebind whose only path is a compile-time-dead branch canonicalizes back to the pre-loop value and is allowed. Unlike the array-store check, loops nested inside runtime if branches are scanned too — a loop-carried scalar rebind there miscompiles all the same — and the pruning walk descends into those branches (walk_runtime_branches=True) so dead-branch canonicalization applies to them exactly as the lowering pass will lower them.

The one exempted rebind — the while loop-carried condition pair — additionally requires that the condition’s pre-loop snapshot is not read after its shared clbit is updated, either later in the body or after the loop (see _reject_stale_while_condition_reads). The allocator aliases the whole condition series onto one classical bit, so such a read would observe the newer in-loop measurement instead of the snapshot Python promises.

Exposed at module scope because it must run from two passes: PartialEvaluationPass calls it before constant folding (folding an all-constant accumulation like total = total + 1 erases the dependency evidence while keeping the wrong result), and AnalyzePass calls it again as a safety net for pipelines that skip partial_eval.

Parameters:

NameTypeDescription
operationslist[Operation]Operations to scan. Recurses through all control flow.
bindingsdict[str, Any] | NoneCompile-time parameter bindings used to resolve IfOperation conditions, matching what CompileTimeIfLoweringPass will later resolve. Defaults to None (no bindings).
output_valueslist[ValueLike] | NoneThe block’s output values; a while condition’s pre-loop value escaping through them is a post-loop read. Structural outputs (TupleValue / DictValue) are searched recursively so a condition returned inside a tuple is still detected. Defaults to None (no outputs known).

Raises:


reject_self_referential_loop_stores [source]

def reject_self_referential_loop_stores(operations: list[Operation], bindings: dict[str, Any] | None = None) -> None

Reject in-loop classical element stores that read the same array.

A loop body is traced once, so a StoreArrayElementOperation inside a loop references a fixed pre-loop version of the array it writes. If the stored value or the store index reads an element of that same logical array — directly or through classical arithmetic — later iterations would observe stale pre-loop contents instead of earlier iterations’ writes, silently diverging from Python semantics (e.g. vals[i] = vals[0] + 1 would write the same folded value every iteration). Such stores are rejected at compile time.

IfOperations are classified with the same condition resolution CompileTimeIfLoweringPass uses (via bindings): a compile-time condition contributes only its taken branch to the scan (a dead branch is eliminated by the lowering pass, so a self-referential store inside it never executes), while a runtime condition’s branches are skipped entirely — every store inside a runtime if branch is rejected by AnalyzePass._reject_stores_in_if_branches regardless of self-reference.

Exposed at module scope because it must run from two passes: PartialEvaluationPass calls it before constant folding (folding a bound element read to a constant erases the parent_array provenance this check relies on — the fold is exactly what bakes the stale pre-loop value into the loop body), and AnalyzePass calls it again as a safety net for pipelines that skip partial_eval.

Parameters:

NameTypeDescription
operationslist[Operation]Operations to scan. Recurses through all control flow; every loop at any nesting depth is checked against the stores inside its body (if branches per the classification above).
bindingsdict[str, Any] | NoneCompile-time parameter bindings used to resolve IfOperation conditions, matching what CompileTimeIfLoweringPass will later resolve. Defaults to None (no bindings): only constant conditions resolve and all others are treated as runtime — correct for the AnalyzePass safety-net call, where compile-time ifs are already lowered away and any store left inside an if branch was already rejected.

Raises:

Classes

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.


BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

CompileTimeIfLoweringPass [source]

class CompileTimeIfLoweringPass(Pass[Block, Block])

Lowers compile-time resolvable IfOperations before separation.

After constant folding, some IfOperation conditions are statically known but remain as control-flow nodes. SegmentationPass treats them as segment boundaries, causing MultipleQuantumSegmentsError for classical-only compile-time if after quantum init.

This pass:

  1. Evaluates conditions including expression-derived ones (CompOp, CondOp, NotOp, BinOp, and UnaryMathOp chains).

  2. Replaces resolved IfOperations with selected-branch operations.

  3. Substitutes merge output UUIDs with selected-branch values in all subsequent operations and block outputs.

Constructor
def __init__(
    self,
    bindings: dict[str, Any] | None = None,
    *,
    preserved_condition_uuids: AbstractSet[str] | None = None,
    _under_controlled_unitary: bool = False,
    _active_block_ids: frozenset[int] | None = None,
)

Initialize compile-time if lowering state.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneCompile-time bindings visible in the current block. Defaults to no bindings.
preserved_condition_uuidsAbstractSet[str] | NoneConditions that must remain unresolved so a later validation pass can inspect their dataflow. Defaults to an empty set.
_under_controlled_unitaryboolInternal context flag indicating that boxed callables encountered here will be decomposed by the controlled emission walker and therefore need their owned bodies lowered too. Defaults to False.
_active_block_idsfrozenset[int] | NoneInternal recursion-path guard for operation-owned blocks. Defaults to an empty set.
Attributes
Methods
run
def run(self, input: Block) -> Block

Lower every compile-time resolvable IfOperation in the block.

Parameters:

NameTypeDescription
inputBlockBlock to lower. Must be TRACED, AFFINE, or HIERARCHICAL. TRACED is accepted so the circuit drawer can resolve bound/constant if conditions on a freshly traced block before the transpiler pipeline runs; HIERARCHICAL is accepted during the self-recursion unroll loop. Surviving inline callable invocations are passed through untouched in both cases.

Returns:

Block — New block with compile-time ifs replaced by their selected-branch operations and merge outputs substituted. The input’s BlockKind is preserved.

Raises:


ConstantFoldingPass [source]

class ConstantFoldingPass(Pass[Block, Block])

Evaluates constant expressions at compile time.

This pass folds BinOp operations when all operands are constants or bound parameters, eliminating unnecessary classical operations that would otherwise split quantum segments.

Example:

Before (with bindings={"phase": 0.5}):
    BinOp(phase * 2) -> classical segment split

After:
    Constant 1.0 -> no segment split
Constructor
def __init__(self, bindings: dict[str, Any] | None = None, *, strip_slice_ops: bool = True)

Create a constant-folding pass.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneCompile-time parameter bindings used when folding BinOps that reference declared parameters.
strip_slice_opsboolWhen True (default), removes SliceArrayOperation nodes after folding. Set to False when a downstream pass — notably SliceBorrowCheckPass — still needs to observe slice declaration points in program order to decide view liveness. A separate strip pass must then run after the linearity check so segmentation still sees a pure quantum-op stream.
Attributes
Methods
run
def run(self, input: Block) -> Block

Fold resolvable classical values throughout a block.

Parameters:

NameTypeDescription
inputBlockAffine or hierarchical block to rewrite.

Returns:

Block — Copy with folded operations and output values.

Raises:


HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


PartialEvaluationPass [source]

class PartialEvaluationPass(Pass[Block, Block])

Fold constants and lower compile-time control flow.

Constructor
def __init__(self, bindings: dict[str, Any] | None = None)
Attributes
Methods
run
def run(self, input: Block) -> Block

Fold constants and lower compile-time control flow.

Parameters:

NameTypeDescription
inputBlockBlock to evaluate. AFFINE in the normal pipeline; HIERARCHICAL is also accepted for the self-recursion unroll loop (see inline comment).

Returns:

Block — Block with constants folded and compile-time-resolvable IfOperations lowered.

Raises:


Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


SelectOperation [source]

class SelectOperation(Operation)

Quantum multiplexer: apply case_blocks[i] when the index reads i.

Concrete operand layout: [idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...]. Symbolic-width operand layout: [idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...]. Results mirror the quantum operand grouping.

A concrete index register is normalized to one scalar Qubit operand per physical index qubit. A symbolic-width register instead retains each leading caller argument as one scalar or array operand until its bound shape is known. Whole-Vector[Qubit] / scalar targets follow and keep their shapes, and classical parameters shared across every case come last.

Index bit order is LSB-first: idx_0 is the least-significant bit, matching Qamomile’s qubit-zero convention. Case i is selected when index qubit j reads bit j of i. len(case_blocks) need not be a power of two; index values >= len(case_blocks) apply no operation (identity).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_index_qubits: int | Value = 0,
    case_blocks: list[Block] = list(),
    num_index_args: int = 0,
    case_callable_attrs: list[dict[str, Any]] = list(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Return every value consumed by the SELECT operation.

Returns:

list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width value when present.

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed replacement values.

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


ValueResolver [source]

class ValueResolver

Resolve IR Values to concrete Python values.

Parameters:

NameTypeDescription
contextdict[str, Any] | NoneUUID-keyed map of already resolved values. The values may be either raw Python scalars or Value objects; if a Value is found its get_const() is extracted automatically.
bindingsdict[str, Any] | NoneName-keyed parameter bindings supplied by the user at transpile time.
Constructor
def __init__(
    self,
    context: dict[str, Any] | None = None,
    bindings: dict[str, Any] | None = None,
)

Create a resolver with optional context and bindings.

Parameters:

NameTypeDescription
contextdict[str, Any] | NoneUUID-keyed map of already-resolved values. Defaults to None.
bindingsdict[str, Any] | NoneName-keyed parameter bindings supplied by the user. Defaults to None.
Methods
resolve
def resolve(self, value: Any) -> Any | None

Resolve a Value-like object to a concrete Python value.

If value is not a Value-like object (no uuid attribute) it is returned as-is — the caller already has a concrete value.

Parameters:

NameTypeDescription
valueAnyThe Value-like object or already concrete value to resolve.

Returns:

Any | None — Any | None: The resolved concrete value, the original concrete value for non-Value inputs, or None when no resolution rule applies.


ValidationError [source]

class ValidationError(QamomileCompileError)

Error during validation (e.g., non-classical I/O).

Constructor
def __init__(self, message: str, value_name: str | None = None)

Initialize a validation diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable validation failure.
value_namestr | NoneRelated IR value name. Defaults to None.
Attributes

qamomile.circuit.transpiler.passes.region_capture

Materialize explicit capture lists on structured semantic IR regions.

Overview

FunctionDescription
genuine_input_valuesReturn an operation’s input values that count as genuine reads.
ClassDescription
ArrayValueAn array of typed IR values.
BlockUnified block representation for all pipeline stages.
DictValueA dictionary value stored as stable ordered entries.
HasNestedOpsMixin for operations that contain nested operation lists.
InvokeOperationRepresent a composite, stdlib, or oracle call.
PassBase class for all compiler passes.
RegionCapturePassPopulate explicit captures for every structured control-flow region.
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
TupleValueA tuple of IR values for structured data.
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.

Functions

genuine_input_values [source]

def genuine_input_values(op: Operation) -> list[ValueBase]

Return an operation’s input values that count as genuine reads.

Structured operations derive reads from their explicit region interface: enclosing operands, captures, loop initializers, and region yields. Block arguments and operation results are definitions, while legacy rebind records are diagnostics rather than dataflow. Leaf operations keep their ordinary all_input_values contract.

Parameters:

NameTypeDescription
opOperationOperation to inspect.

Returns:

list[ValueBase] — list[ValueBase]: Semantic reads in interface order.

Classes

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:

bool — True 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.


DictValue [source]

class DictValue(_MetadataValueMixin, ValueBase)

A dictionary value stored as stable ordered entries.

Constructor
def __init__(
    self,
    name: str,
    entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> DictValue

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.
Constructor
def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes
Methods
body_for_transform
def body_for_transform(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> tuple[Block | None, CallTransform]

Select a body and report the transform it already realizes.

A controlled-inverse invocation may reuse an explicitly registered inverse body when no implementation realizes both transforms. Keeping that fallback in the IR operation gives emitters and static analyses one selection rule while still letting each consumer apply the remaining coherent controls in its own representation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — tuple[Block | None, CallTransform]: Selected body and the transform CallTransform — already implemented by that body. The callable’s direct body is tuple[Block | None, CallTransform] — returned with DIRECT when no transform-specific body matches.

Raises:

effective_body
def effective_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — Block | None: Selected implementation body, or the callable’s Block | None — default body when no transform-specific implementation exists. Block | None — A compiler may synthesize inverse or controlled behavior from this Block | None — fallback body.

implementation_for
def implementation_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None, which only selects engine-generic implementations.
strategystr | NoneStrategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation candidate, CallableImplementation | None — or None when the callable definition has no match.

measurement_result_indices_for
def measurement_result_indices_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> frozenset[int]

Return measurement-derived results for one selected implementation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name used for implementation selection. Defaults to None.
strategystr | NoneStrategy name used for implementation selection. Defaults to the invocation’s strategy_name.

Returns:

frozenset[int] — frozenset[int]: Caller-local result positions derived from measurement in the selected body.

Raises:

select_body
def select_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> CallableBodySelection

Select and validate the composable body for this invocation.

The result carries the transform already realized by the body and the exact call-site values that bind to it. Consumers therefore cannot independently disagree about whether an invocation’s control prefix belongs to the selected implementation ABI.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

CallableBodySelection — Validated body, realized transform, and CallableBodySelection — aligned call-site operands and results.

Raises:


Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


RegionCapturePass [source]

class RegionCapturePass(Pass[Block, Block])

Populate explicit captures for every structured control-flow region.

The pass derives captures from the current semantic IR, so it can normalize hand-built and deserialized blocks as well as frontend output. The pass preserves existing block identity while replacing structured operations with capture-annotated values. Running it repeatedly is idempotent.

Constructor
def __init__(self) -> None

Initialize an empty reachable-block visitation set.

Attributes
Methods
run
def run(self, input: Block) -> Block

Populate explicit captures throughout one block graph.

Parameters:

NameTypeDescription
inputBlockSemantic entrypoint whose reachable regions should be normalized.

Returns:

Block — The input entrypoint with capture lists populated on every reachable structured-control operation.


SelectOperation [source]

class SelectOperation(Operation)

Quantum multiplexer: apply case_blocks[i] when the index reads i.

Concrete operand layout: [idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...]. Symbolic-width operand layout: [idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...]. Results mirror the quantum operand grouping.

A concrete index register is normalized to one scalar Qubit operand per physical index qubit. A symbolic-width register instead retains each leading caller argument as one scalar or array operand until its bound shape is known. Whole-Vector[Qubit] / scalar targets follow and keep their shapes, and classical parameters shared across every case come last.

Index bit order is LSB-first: idx_0 is the least-significant bit, matching Qamomile’s qubit-zero convention. Case i is selected when index qubit j reads bit j of i. len(case_blocks) need not be a power of two; index values >= len(case_blocks) apply no operation (identity).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_index_qubits: int | Value = 0,
    case_blocks: list[Block] = list(),
    num_index_args: int = 0,
    case_callable_attrs: list[dict[str, Any]] = list(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Return every value consumed by the SELECT operation.

Returns:

list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width value when present.

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed replacement values.

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


TupleValue [source]

class TupleValue(_MetadataValueMixin, ValueBase)

A tuple of IR values for structured data.

Constructor
def __init__(
    self,
    name: str,
    elements: tuple[ValueLike, ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> TupleValue

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


qamomile.circuit.transpiler.passes.region_validation

Validation of explicit structured-region interfaces.

Overview

FunctionDescription
genuine_input_valuesReturn an operation’s input values that count as genuine reads.
validate_region_argsValidate the SSA identities owned by a loop’s region arguments.
ClassDescription
ArrayValueAn array of typed IR values.
BlockUnified block representation for all pipeline stages.
DictValueA dictionary value stored as stable ordered entries.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
HasNestedOpsMixin for operations that contain nested operation lists.
IfOperationRepresents an if-else conditional operation.
InvokeOperationRepresent a composite, stdlib, or oracle call.
PassBase class for all compiler passes.
RegionValidationPassVerify dominance and signatures for every explicit semantic region.
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
TupleValueA tuple of IR values for structured data.
ValidationErrorError during validation (e.g., non-classical I/O).
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.
WhileOperationRepresents a while loop operation.

Functions

genuine_input_values [source]

def genuine_input_values(op: Operation) -> list[ValueBase]

Return an operation’s input values that count as genuine reads.

Structured operations derive reads from their explicit region interface: enclosing operands, captures, loop initializers, and region yields. Block arguments and operation results are definitions, while legacy rebind records are diagnostics rather than dataflow. Leaf operations keep their ordinary all_input_values contract.

Parameters:

NameTypeDescription
opOperationOperation to inspect.

Returns:

list[ValueBase] — list[ValueBase]: Semantic reads in interface order.


validate_region_args [source]

def validate_region_args(op: ForOperation | ForItemsOperation | WhileOperation) -> tuple[RegionArg, ...]

Validate the SSA identities owned by a loop’s region arguments.

A loop owns several definition namespaces: its iteration variables, every RegionArg.block_arg, and every RegionArg.result. Those identities must be pairwise disjoint. Otherwise different stages can assign incompatible meanings to one UUID: a UUID-keyed environment has only one slot, so binding either the iteration variable or the carried value overwrites the other and makes both reads observe the same value.

Parameters:

NameTypeDescription
opForOperation | ForItemsOperation | WhileOperationLoop operation whose region arguments should be validated.

Returns:

tuple[RegionArg, ...] — tuple[RegionArg, ...]: The validated op.region_args tuple.

Raises:

Classes

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:

bool — True 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.


DictValue [source]

class DictValue(_MetadataValueMixin, ValueBase)

A dictionary value stored as stable ordered entries.

Constructor
def __init__(
    self,
    name: str,
    entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> DictValue

ForItemsOperation [source]

class ForItemsOperation(HasNestedOps, Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    key_var_values: tuple[Value, ...] | None = None,
    value_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include the per-key/value Value fields for cloning/substitution.

Same rationale as ForOperation.all_input_values: keep the IR identity fields in lockstep with body references so UUID-keyed lookups stay valid after inline cloning. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the items-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing key/value formals, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the items-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt items-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.
Constructor
def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes
Methods
body_for_transform
def body_for_transform(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> tuple[Block | None, CallTransform]

Select a body and report the transform it already realizes.

A controlled-inverse invocation may reuse an explicitly registered inverse body when no implementation realizes both transforms. Keeping that fallback in the IR operation gives emitters and static analyses one selection rule while still letting each consumer apply the remaining coherent controls in its own representation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — tuple[Block | None, CallTransform]: Selected body and the transform CallTransform — already implemented by that body. The callable’s direct body is tuple[Block | None, CallTransform] — returned with DIRECT when no transform-specific body matches.

Raises:

effective_body
def effective_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — Block | None: Selected implementation body, or the callable’s Block | None — default body when no transform-specific implementation exists. Block | None — A compiler may synthesize inverse or controlled behavior from this Block | None — fallback body.

implementation_for
def implementation_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None, which only selects engine-generic implementations.
strategystr | NoneStrategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation candidate, CallableImplementation | None — or None when the callable definition has no match.

measurement_result_indices_for
def measurement_result_indices_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> frozenset[int]

Return measurement-derived results for one selected implementation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name used for implementation selection. Defaults to None.
strategystr | NoneStrategy name used for implementation selection. Defaults to the invocation’s strategy_name.

Returns:

frozenset[int] — frozenset[int]: Caller-local result positions derived from measurement in the selected body.

Raises:

select_body
def select_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> CallableBodySelection

Select and validate the composable body for this invocation.

The result carries the transform already realized by the body and the exact call-site values that bind to it. Consumers therefore cannot independently disagree about whether an invocation’s control prefix belongs to the selected implementation ABI.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

CallableBodySelection — Validated body, realized transform, and CallableBodySelection — aligned call-site operands and results.

Raises:


Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


RegionValidationPass [source]

class RegionValidationPass(Pass[Block, Block])

Verify dominance and signatures for every explicit semantic region.

Constructor
def __init__(self) -> None

Initialize an empty reachable-block visitation set.

Attributes
Methods
run
def run(self, input: Block) -> Block

Validate a block graph and return it unchanged.

Parameters:

NameTypeDescription
inputBlockSemantic entrypoint whose regions should be verified.

Returns:

Block — The validated input block.

Raises:


SelectOperation [source]

class SelectOperation(Operation)

Quantum multiplexer: apply case_blocks[i] when the index reads i.

Concrete operand layout: [idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...]. Symbolic-width operand layout: [idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...]. Results mirror the quantum operand grouping.

A concrete index register is normalized to one scalar Qubit operand per physical index qubit. A symbolic-width register instead retains each leading caller argument as one scalar or array operand until its bound shape is known. Whole-Vector[Qubit] / scalar targets follow and keep their shapes, and classical parameters shared across every case come last.

Index bit order is LSB-first: idx_0 is the least-significant bit, matching Qamomile’s qubit-zero convention. Case i is selected when index qubit j reads bit j of i. len(case_blocks) need not be a power of two; index values >= len(case_blocks) apply no operation (identity).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_index_qubits: int | Value = 0,
    case_blocks: list[Block] = list(),
    num_index_args: int = 0,
    case_callable_attrs: list[dict[str, Any]] = list(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Return every value consumed by the SELECT operation.

Returns:

list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width value when present.

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed replacement values.

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


TupleValue [source]

class TupleValue(_MetadataValueMixin, ValueBase)

A tuple of IR values for structured data.

Constructor
def __init__(
    self,
    name: str,
    elements: tuple[ValueLike, ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> TupleValue

ValidationError [source]

class ValidationError(QamomileCompileError)

Error during validation (e.g., non-classical I/O).

Constructor
def __init__(self, message: str, value_name: str | None = None)

Initialize a validation diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable validation failure.
value_namestr | NoneRelated IR value name. Defaults to None.
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 engine 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.


WhileOperation [source]

class WhileOperation(HasNestedOps, Operation)

Represents a while loop operation.

Only measurement-backed conditions are supported: the condition must be a Bit value produced by qmc.measure(). Non-measurement conditions (classical variables, constants, comparisons) are rejected by ValidateWhileContractPass before reaching engine emit.

Example::

bit = qmc.measure(q)
while bit:
    q = qmc.h(q)
    bit = qmc.measure(q)
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    operations: list[Operation] = list(),
    max_iterations: int | None = None,
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include rebind records and region args for cloning/substitution.

Same rationale as ForOperation.all_input_values: rebind records and region arguments reference body/pre-loop values by identity, so inline cloning must remap them in lockstep with body operands.

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus rebind-record and region-argument values.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the while body with explicit boundary values.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region whose block arguments and yields are aligned with region_args. The updated condition, when present, is appended as the final yield.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the while body and its complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt while operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, rebind-record, and region-arg values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


qamomile.circuit.transpiler.passes.separate

Segmentation pass: Split a block into executable program steps.

Overview

FunctionDescription
array_physical_regionResolve a one-dimensional array to its ordered physical region.
array_static_lengthResolve a one-dimensional array’s compile-time length.
arrays_share_physical_regionReturn whether two arrays denote the same ordered physical region.
collect_value_like_uuidsCollect UUIDs contained in a value-like IR object.
genuine_input_valuesReturn an operation’s input values that count as genuine reads.
lower_measure_qfixedLower MeasureQFixedOperation to MeasureVectorOperation plus decode.
lower_measure_qintLower MeasureQIntOperation to vector measurement plus integer decode.
lower_operationsLower packed-register measurements before segmentation.
materialize_returnSynchronize output_values from ReturnOperation.
packed_register_type_widthReturn the type-declared width of a packed quantum register type.
walk_operationsYield operations in preorder across every nested control-flow region.
ClassDescription
ArrayValueAn array of typed IR values.
BitTypeType representing a classical bit.
BlockUnified block representation for all pipeline stages.
CastOperationType cast operation for creating aliases over the same quantum resources.
ClassicalSegmentA segment of pure classical operations.
ClassicalStepA classical execution step.
ControlFlowVisitorBase class for visiting operations with control flow handling.
DecodeQFixedOperationDecode measured bits to float (classical operation).
DecodeQIntOperationDecode least-significant-first measurement bits to an unsigned integer.
DictValueA dictionary value stored as stable ordered entries.
ExpvalOpExpectation value operation.
ExpvalSegmentA segment for expectation value computation.
ExpvalStepAn expectation-value execution step.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
HasNestedOpsMixin for operations that contain nested operation lists.
HybridBoundaryRepresents a measurement or encode operation at quantum/classical boundary.
IfOperationRepresents an if-else conditional operation.
MeasureQFixedOperationMeasure a quantum fixed-point number.
MeasureQIntOperationMeasure an unsigned quantum integer as one abstract hybrid operation.
MeasureVectorOperationMeasure a vector of qubits.
MultipleQuantumSegmentsErrorRaised when a program cannot fit the single-quantum-segment model.
NisqSegmentationStrategySingle-quantum-segment planning strategy for current Qamomile runtimes.
OperationKindClassification of operations for classical/quantum separation.
PassBase class for all compiler passes.
ProgramABIRuntime-visible ABI for a segmented program.
ProgramPlanExecution plan for a hybrid quantum/classical program.
QuantumSegmentA segment of pure quantum operations.
QuantumStepA quantum execution step.
QubitTypeType representing a quantum bit (qubit).
ReturnOperationExplicit return operation marking the end of a block with return values.
RuntimeClassicalExprA classical expression known to require runtime evaluation.
SegmentBase class for separated computation segments.
SegmentationPassSegment a block into a strategy-specific executable program plan.
SegmentationStrategyExecution-model-specific strategy for building a ProgramPlan.
SeparationErrorError during quantum/classical separation.
TupleValueA tuple of IR values for structured data.
UIntTypeType representing an unsigned integer.
ValidateWhileContractPassValidates that all WhileOperation conditions are measurement-backed.
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.
ValueResolverResolve IR Values to concrete Python values.
WhileOperationRepresents a while loop operation.

Constants

Functions

array_physical_region [source]

def array_physical_region(array: 'ArrayValue') -> tuple[str, tuple[int, ...]] | None

Resolve a one-dimensional array to its ordered physical region.

The region is expressed independently of SSA version UUIDs: the first element is the root array’s logical_id and the second is the ordered tuple of root-space indices addressed by the array. This makes a root register and its full view compare equal while keeping partial, strided, reordered, and different-root registers distinct.

Parameters:

NameTypeDescription
arrayArrayValueRoot array or nested sliced view to resolve. The array must be one-dimensional and have a compile-time integer length; every slice bound in its ancestry must also be constant.

Returns:

tuple[str, tuple[int, ...]] | None — tuple[str, tuple[int, ...]] | None: (root_logical_id, indices) when the complete ordered coverage is statically known, otherwise None. Symbolic shapes or slice bounds remain unresolved so callers can defer to emit-time physical mappings.


array_static_length [source]

def array_static_length(array: 'ArrayValue') -> int | None

Resolve a one-dimensional array’s compile-time length.

Parameters:

NameTypeDescription
arrayArrayValueArray whose sole shape dimension is inspected.

Returns:

int | None — int | None: Non-negative static length, or None when the array is not one-dimensional, its length is symbolic/non-integral, or it is malformed with a negative length. Boolean constants are rejected even though bool is an int subclass.


arrays_share_physical_region [source]

def arrays_share_physical_region(left: 'ArrayValue', right: 'ArrayValue') -> bool

Return whether two arrays denote the same ordered physical region.

Parameters:

NameTypeDescription
leftArrayValueFirst root array or sliced view.
rightArrayValueSecond root array or sliced view.

Returns:

bool — True for the same SSA value/version lineage, when both arrays resolve to the same root logical identity and ordered root indices, or when both resolve to empty regions (whose root is unobservable). Returns False for non-empty divergent regions and unresolved symbolic coverage.


collect_value_like_uuids [source]

def collect_value_like_uuids(value: 'ValueLike') -> set[str]

Collect UUIDs contained in a value-like IR object.

Parameters:

NameTypeDescription
valueValueLikeValue-like object to inspect.

Returns:

set[str] — set[str]: UUIDs for value itself, recursively contained tuple/dict elements, and array view/element dependencies.


genuine_input_values [source]

def genuine_input_values(op: Operation) -> list[ValueBase]

Return an operation’s input values that count as genuine reads.

Structured operations derive reads from their explicit region interface: enclosing operands, captures, loop initializers, and region yields. Block arguments and operation results are definitions, while legacy rebind records are diagnostics rather than dataflow. Leaf operations keep their ordinary all_input_values contract.

Parameters:

NameTypeDescription
opOperationOperation to inspect.

Returns:

list[ValueBase] — list[ValueBase]: Semantic reads in interface order.


lower_measure_qfixed [source]

def lower_measure_qfixed(
    op: MeasureQFixedOperation,
    cast_source: ArrayValue | None = None,
) -> list[Operation]

Lower MeasureQFixedOperation to MeasureVectorOperation plus decode.

Carrier keys are read exclusively from the operand’s required cast metadata.

Parameters:

NameTypeDescription
opMeasureQFixedOperationQFixed measurement to lower.
cast_sourceArrayValue | NoneSource vector for a deferred-width cast. Defaults to None for concrete carrier lists.

Returns:

list[Operation] — list[Operation]: Ordered vector measurement and fixed-point decode.

Raises:


lower_measure_qint [source]

def lower_measure_qint(
    op: MeasureQIntOperation,
    cast_source: ArrayValue | None = None,
) -> list[Operation]

Lower MeasureQIntOperation to vector measurement plus integer decode.

Parameters:

NameTypeDescription
opMeasureQIntOperationUnsigned quantum-integer measurement to lower.
cast_sourceArrayValue | NoneSource vector for a deferred-width cast. Defaults to None for concrete carrier lists.

Returns:

list[Operation] — list[Operation]: Ordered vector measurement and unsigned-integer decode.

Raises:


lower_operations [source]

def lower_operations(block: Block) -> Block

Lower packed-register measurements before segmentation.

QFixed and QInt measurements become one ordered vector measurement plus a type-specific host-side decode operation.

Parameters:

NameTypeDescription
blockBlockBlock whose top-level high-level operations should be lowered.

Returns:

Block — Block with top-level packed-register measurements split into quantum measurement and classical decode operations.

Raises:


materialize_return [source]

def materialize_return(block: Block) -> Block

Synchronize output_values from ReturnOperation.

Uses ReturnOperation.operands as the source of truth for return values, ensuring consistency between the operation stream and block metadata.


packed_register_type_width [source]

def packed_register_type_width(value_type: ValueType) -> int | None

Return the type-declared width of a packed quantum register type.

Unlike :func:static_quantum_width, this helper consults only the type and never runtime carrier or fixed-point metadata, so it distinguishes a register whose width is known to be zero (returns 0) from one whose width is symbolic (returns None). static_quantum_width cannot make that distinction for a QFixed whose frontend qfixed metadata records num_bits=0 for a symbolic layout.

Parameters:

NameTypeDescription
value_typeValueTypeType to inspect. Only QUIntType and QFixedType describe packed registers.

Returns:

int | None — int | None: QUIntType.width or QFixedType.integer_bits + fractional_bits when every component is a compile-time non-negative integer; None when any component is symbolic or when value_type is not a packed register type.


walk_operations [source]

def walk_operations(operations: Sequence[Operation]) -> Iterable[Operation]

Yield operations in preorder across every nested control-flow region.

Parameters:

NameTypeDescription
operationsSequence[Operation]Top-level semantic operations.

Returns:

Iterable[Operation] — Iterable[Operation]: Preorder traversal including nested operations.

Classes

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:

bool — True iff slice_of is non-None.

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

BitType [source]

class BitType(ClassicalTypeMixin, ValueType)

Type representing a classical bit.


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.


CastOperation [source]

class CastOperation(Operation)

Type cast operation for creating aliases over the same quantum resources.

This operation does NOT allocate new qubits. It creates a new Value that references the same underlying quantum resources with a different type.

Use cases:

operands: [source_value] - The value being cast results: [cast_result] - The new value with target type (same physical qubits)

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    source_type: ValueType | None = None,
    target_type: ValueType | None = None,
    qubit_mapping: list[str] = list(),
) -> None
Attributes

ClassicalSegment [source]

class ClassicalSegment(Segment)

A segment of pure classical operations.

Contains arithmetic, comparisons, and control flow. Will be executed directly in Python.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
) -> None
Attributes

ClassicalStep [source]

class ClassicalStep

A classical execution step.

Constructor
def __init__(self, segment: ClassicalSegment, role: str = 'classical') -> None
Attributes

ControlFlowVisitor [source]

class ControlFlowVisitor(ABC)

Base class for visiting operations with control flow handling.

Subclasses override visit_operation to define per-operation behavior. Control flow recursion is handled automatically by the base class.

Example:

class MeasurementCounter(ControlFlowVisitor):
    def __init__(self):
        self.count = 0

    def visit_operation(self, op: Operation) -> None:
        if isinstance(op, MeasureOperation):
            self.count += 1
Methods
visit_operation
def visit_operation(self, op: Operation) -> None

Process a single operation. Override in subclasses.

visit_operations
def visit_operations(self, operations: list[Operation]) -> None

Visit all operations including nested control flow.


DecodeQFixedOperation [source]

class DecodeQFixedOperation(Operation)

Decode measured bits to float (classical operation).

This operation converts a sequence of classical bits from qubit measurements into a floating-point number using fixed-point encoding.

The decoding formula for least-significant-first storage:

float_value = Σ bit[i] * 2^(int_bits - num_bits + i)

For QPE phase (int_bits=0): bit[0] has weight 2**(-num_bits) and bit[-1] has weight 0.5.

Example:

bits = [1, 0, 1] with int_bits=0
→ 0.101 (MSB-first display) = 0.5 + 0.125 = 0.625

operands: [ArrayValue of bits (vec[bit])] results: [Float value]

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_bits: int = 0,
    int_bits: int = 0,
) -> None
Attributes

DecodeQIntOperation [source]

class DecodeQIntOperation(Operation)

Decode least-significant-first measurement bits to an unsigned integer.

Carrier position i contributes bit[i] * 2**i, which matches the carrier ordering used by DecodeQFixedOperation.

The bit count is not stored on the operation: it is derived from the bit-array operand’s static length through num_bits.

Parameters:

NameTypeDescription
operandslist[Value]Single measured ArrayValue[Bit] operand.
resultslist[Value]Single decoded UIntType result.
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

DictValue [source]

class DictValue(_MetadataValueMixin, ValueBase)

A dictionary value stored as stable ordered entries.

Constructor
def __init__(
    self,
    name: str,
    entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> DictValue

ExpvalOp [source]

class ExpvalOp(Operation)

Expectation value operation.

This operation computes the expectation value <psi|H|psi> where psi is the quantum state and H is the Hamiltonian observable.

The operation bridges quantum and classical computation:

Example IR:

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ExpvalSegment [source]

class ExpvalSegment(Segment)

A segment for expectation value computation.

Represents computing <psi|H|psi> where psi is the quantum state and H is a Hamiltonian observable.

This segment bridges a quantum circuit (state preparation) to a classical expectation value.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
    hamiltonian_value: Value | None = None,
    qubits_value: Value | None = None,
    result_ref: str = '',
) -> None
Attributes

ExpvalStep [source]

class ExpvalStep

An expectation-value execution step.

Constructor
def __init__(self, segment: ExpvalSegment, quantum_step_index: int = 0) -> None
Attributes

ForItemsOperation [source]

class ForItemsOperation(HasNestedOps, Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    key_var_values: tuple[Value, ...] | None = None,
    value_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include the per-key/value Value fields for cloning/substitution.

Same rationale as ForOperation.all_input_values: keep the IR identity fields in lockstep with body references so UUID-keyed lookups stay valid after inline cloning. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the items-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing key/value formals, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the items-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt items-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


HybridBoundary [source]

class HybridBoundary

Represents a measurement or encode operation at quantum/classical boundary.

These operations bridge quantum and classical segments.

Constructor
def __init__(
    self,
    operation: Operation,
    source_segment_index: int,
    target_segment_index: int,
    value_ref: str,
) -> None
Attributes

IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


MeasureQFixedOperation [source]

class MeasureQFixedOperation(Operation)

Measure a quantum fixed-point number.

This operation measures all qubits in a QFixed register and produces a Float result. During transpilation, this is lowered to individual MeasureOperations plus a DecodeQFixedOperation.

operands: [QFixed value (contains qubit_values in params)] results: [Float value]

Encoding:

For QPE phase (int_bits=0): Qubits are stored least-significant first. For n qubits, bit i has weight 2**(-n + i).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_bits: int = 0,
    int_bits: int = 0,
) -> None
Attributes

MeasureQIntOperation [source]

class MeasureQIntOperation(Operation)

Measure an unsigned quantum integer as one abstract hybrid operation.

The carrier sequence is least-significant-bit first: carrier i has integer weight 2**i. Planning lowers this operation to one vector measurement followed by a host-side DecodeQIntOperation.

The carrier width is not stored on the operation: it is derived from the register operand’s type and carrier metadata through num_bits.

Parameters:

NameTypeDescription
operandslist[Value]Single QUIntType register operand.
resultslist[Value]Single decoded UIntType result.
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

MeasureVectorOperation [source]

class MeasureVectorOperation(Operation)

Measure a vector of qubits.

Takes a Vector[Qubit] (ArrayValue) and produces a Vector[Bit] (ArrayValue). This operation measures all qubits in the vector as a single operation.

operands: [ArrayValue of qubits] results: [ArrayValue of bits]

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

MultipleQuantumSegmentsError [source]

class MultipleQuantumSegmentsError(SeparationError)

Raised when a program cannot fit the single-quantum-segment model.

Qamomile enforces a single quantum circuit execution pattern:

[Classical Prep] → Quantum Circuit → [Classical Post/Expval]

The error fires when segmentation finds more than one quantum segment (classical work that must execute between two quantum regions, e.g. quantum operations resuming after a qmc.expval), or when a classical value feeding a quantum gate is also consumed by classical work and therefore cannot be absorbed into the quantum segment.

Note that a loop bound left as a runtime parameter is diagnosed earlier, by SymbolicShapeValidationPass, with a dedicated “Cannot unroll loop” message — it does not reach segmentation.

Example:

Incorrect — quantum operations resume after an expectation value,
which closes the quantum segment::

    @qmc.qkernel
    def kernel(obs: qmc.Observable) -> tuple[qmc.Float, qmc.Bit]:
        q = qmc.qubit("q")
        q = qmc.h(q)
        e = qmc.expval(q, obs)   # quantum segment ends here
        q2 = qmc.qubit("q2")
        q2 = qmc.x(q2)           # second quantum segment -> error
        return e, qmc.measure(q2)

Correct — keep all quantum operations in one contiguous region and
take the expectation value at the end::

    @qmc.qkernel
    def kernel(obs: qmc.Observable) -> qmc.Float:
        q = qmc.qubit("q")
        q = qmc.h(q)
        return qmc.expval(q, obs)

NisqSegmentationStrategy [source]

class NisqSegmentationStrategy(SegmentationStrategy)

Single-quantum-segment planning strategy for current Qamomile runtimes.

Methods
create_plan
def create_plan(
    self,
    segments: list[Segment],
    block: Block,
    boundaries: list[HybridBoundary],
) -> ProgramPlan

Build the current single-quantum-segment NISQ plan.

Parameters:

NameTypeDescription
segmentslist[Segment]Ordered classical, quantum, and expval segments.
blockBlockLowered block providing parameters and outputs.
boundarieslist[HybridBoundary]Recorded hybrid transitions.

Returns:

ProgramPlan — Plan with one quantum step and surrounding classical or expectation-value steps.

Raises:


OperationKind [source]

class OperationKind(enum.Enum)

Classification of operations for classical/quantum separation.

This enum is used to categorize operations during compilation to determine which parts run on classical hardware vs quantum hardware.

Values:

QUANTUM: Pure quantum operations (gates, qubit allocation) CLASSICAL: Pure classical operations (arithmetic, comparisons) HYBRID: Operations that bridge classical and quantum (measurement, encode/decode) CONTROL: Control flow structures (for, while, if)

Attributes

Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


ProgramABI [source]

class ProgramABI

Runtime-visible ABI for a segmented program.

Constructor
def __init__(
    self,
    public_inputs: dict[str, ValueLike] = dict(),
    output_values: list[ValueLike] = list(),
) -> None
Attributes

ProgramPlan [source]

class ProgramPlan

Execution plan for a hybrid quantum/classical program.

Structure:

This plan enforces Qamomile’s current execution model: all quantum operations must be in a single quantum circuit.

Constructor
def __init__(
    self,
    steps: list[ProgramStep] = list(),
    abi: ProgramABI = ProgramABI(),
    boundaries: list[HybridBoundary] = list(),
    parameters: dict[str, Value] = dict(),
) -> None
Attributes

QuantumSegment [source]

class QuantumSegment(Segment)

A segment of pure quantum operations.

Contains quantum gates and qubit allocations. Will be emitted to a quantum circuit.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
    qubit_values: list[Value] = list(),
    num_qubits: int = 0,
) -> None
Attributes

QuantumStep [source]

class QuantumStep

A quantum execution step.

Constructor
def __init__(self, segment: QuantumSegment) -> None
Attributes

QubitType [source]

class QubitType(QuantumTypeMixin, ValueType)

Type representing a quantum bit (qubit).


ReturnOperation [source]

class ReturnOperation(Operation)

Explicit return operation marking the end of a block with return values.

This operation represents an explicit return statement in the IR. It takes the values to be returned as operands and produces no results (it is a terminal operation that transfers control flow back to the caller).

operands: [Value, ...] - The values to return (may be empty for void returns) results: [] - Always empty (terminal operation)

Example:

A function that returns two values (a UInt and a Float):

ReturnOperation(
    operands=[uint_value, float_value],
    results=[],
)

The signature would be:
    operands=[ParamHint("return_0", UIntType()), ParamHint("return_1", FloatType())]
    results=[]
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

RuntimeClassicalExpr [source]

class RuntimeClassicalExpr(Operation)

A classical expression known to require runtime evaluation.

Lowered from CompOp / CondOp / NotOp / BinOp by ClassicalLoweringPass when the op’s operand dataflow traces back to a MeasureOperation (i.e. cannot be folded at compile-time, by emit-time loop unrolling, or by compile_time_if_lowering). Engine emit translates this 1:1 to an engine-native runtime expression (e.g. qiskit.circuit.classical.expr.Expr).

Operand convention:

The single-node + unified-kind shape (vs four parallel subclasses) keeps the engine dispatch a single match op.kind instead of four parallel hooks, and makes the IR self-documenting: a single RuntimeClassicalExpr instance signals “runtime evaluation required” regardless of which classical family it came from.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: RuntimeOpKind | None = None,
) -> None
Attributes

Segment [source]

class Segment(ABC)

Base class for separated computation segments.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
) -> None
Attributes

SegmentationPass [source]

class SegmentationPass(Pass[Block, ProgramPlan])

Segment a block into a strategy-specific executable program plan.

This pass:

  1. Materializes return operations (syncs output_values from ReturnOperation)

  2. Splits the operation list into quantum and classical segments

  3. Builds a ProgramPlan via the configured segmentation strategy

Input: Block (typically ANALYZED or AFFINE) Output: ProgramPlan

Constructor
def __init__(self, strategy: SegmentationStrategy | None = None) -> None
Attributes
Methods
run
def run(self, input: Block) -> ProgramPlan

Lower and segment a block into a program plan.

Parameters:

NameTypeDescription
inputBlockBlock whose while contract and hybrid operations should be lowered before segmentation.

Returns:

ProgramPlan — Strategy-produced execution plan.

Raises:


SegmentationStrategy [source]

class SegmentationStrategy(ABC)

Execution-model-specific strategy for building a ProgramPlan.

Methods
create_plan
def create_plan(
    self,
    segments: list[Segment],
    block: Block,
    boundaries: list[HybridBoundary],
) -> ProgramPlan

Build a program plan from segmented operations.

Parameters:

NameTypeDescription
segmentslist[Segment]Ordered execution segments.
blockBlockLowered source block carrying the public ABI.
boundarieslist[HybridBoundary]Quantum/classical boundaries.

Returns:

ProgramPlan — Strategy-specific executable plan.

Raises:


SeparationError [source]

class SeparationError(QamomileCompileError)

Error during quantum/classical separation.


TupleValue [source]

class TupleValue(_MetadataValueMixin, ValueBase)

A tuple of IR values for structured data.

Constructor
def __init__(
    self,
    name: str,
    elements: tuple[ValueLike, ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> TupleValue

UIntType [source]

class UIntType(ClassicalTypeMixin, ValueType)

Type representing an unsigned integer.


ValidateWhileContractPass [source]

class ValidateWhileContractPass(Pass[Block, Block])

Validates that all WhileOperation conditions are measurement-backed.

Builds a producer map (result UUID → producing Operation instance) and checks every WhileOperation operand against it. A valid condition must be:

  1. A Value with BitType

  2. Measurement-backed: produced by MeasureOperation directly, or an IfOperation merge output where every reachable leaf source is itself measurement-backed.

Both operands[0] (initial condition) and operands[1] (loop-carried condition) are validated.

Raises ValidationError for any non-measurement while pattern.

Attributes
Methods
run
def run(self, block: Block) -> Block

Validate all WhileOperations and return block unchanged.


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


ValueResolver [source]

class ValueResolver

Resolve IR Values to concrete Python values.

Parameters:

NameTypeDescription
contextdict[str, Any] | NoneUUID-keyed map of already resolved values. The values may be either raw Python scalars or Value objects; if a Value is found its get_const() is extracted automatically.
bindingsdict[str, Any] | NoneName-keyed parameter bindings supplied by the user at transpile time.
Constructor
def __init__(
    self,
    context: dict[str, Any] | None = None,
    bindings: dict[str, Any] | None = None,
)

Create a resolver with optional context and bindings.

Parameters:

NameTypeDescription
contextdict[str, Any] | NoneUUID-keyed map of already-resolved values. Defaults to None.
bindingsdict[str, Any] | NoneName-keyed parameter bindings supplied by the user. Defaults to None.
Methods
resolve
def resolve(self, value: Any) -> Any | None

Resolve a Value-like object to a concrete Python value.

If value is not a Value-like object (no uuid attribute) it is returned as-is — the caller already has a concrete value.

Parameters:

NameTypeDescription
valueAnyThe Value-like object or already concrete value to resolve.

Returns:

Any | None — Any | None: The resolved concrete value, the original concrete value for non-Value inputs, or None when no resolution rule applies.


WhileOperation [source]

class WhileOperation(HasNestedOps, Operation)

Represents a while loop operation.

Only measurement-backed conditions are supported: the condition must be a Bit value produced by qmc.measure(). Non-measurement conditions (classical variables, constants, comparisons) are rejected by ValidateWhileContractPass before reaching engine emit.

Example::

bit = qmc.measure(q)
while bit:
    q = qmc.h(q)
    bit = qmc.measure(q)
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    operations: list[Operation] = list(),
    max_iterations: int | None = None,
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include rebind records and region args for cloning/substitution.

Same rationale as ForOperation.all_input_values: rebind records and region arguments reference body/pre-loop values by identity, so inline cloning must remap them in lockstep with body operands.

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus rebind-record and region-argument values.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the while body with explicit boundary values.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region whose block arguments and yields are aligned with region_args. The updated condition, when present, is appended as the final yield.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the while body and its complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt while operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, rebind-record, and region-arg values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


qamomile.circuit.transpiler.passes.slice_borrow_check

Post-fold block-wide slice-view borrow check.

Mirrors the slice-view subset of the frontend’s ArrayBase._borrowed_indices borrow-tracker semantics on the IR after :class:ConstantFoldingPass has resolved slice bounds to concrete values. The pass exists to catch bugs the trace-time checker cannot see on its own — slices whose bounds were UInt at trace time so their covered slot set was not enumerable until bindings were applied:

  1. Aliasing between a (now-concrete) slice view and another live view of the same root parent (raised as :class:QubitBorrowConflictError from :meth:_register_slice_bulk_borrow_if_new).

  2. A view whose newly-concrete coverage hits a slot that was consumed by a destructive operation earlier in the block (raised as :class:QubitConsumedError while registering the view in :meth:_register_slice_bulk_borrow_if_new or inspecting its operands in :meth:_process_operand_borrows).

  3. A slice ownership release, drain, or refresh that crosses a control-flow boundary the current state merge cannot represent safely (raised as :class:ValidationError from the corresponding snapshot guard).

Slice views are otherwise treated as affine at the kernel boundary: a view that goes out of scope without being slice- assigned back to the parent is no longer flagged here. This mirrors how element borrows on locally-allocated registers behave — natural ancilla / scratch-register patterns such as Deutsch-Jozsa’s ancilla = qs[n] and Simon’s qs2 = qs[n:2*n] (used by the oracle, then discarded unmeasured) compile cleanly. The genuine hazards stay covered:

The creation of a direct element borrow (q[i]) is intentionally not observed here because element access emits no IR operation. Later uses of that element do appear as operation operands, however, so :meth:_process_operand_borrows can reject a use that collides with a live slice view. The frontend trace-time validator (qamomile.circuit.frontend.func_to_block._validate_returned_arrays and ArrayBase.validate_all_returned) remains the source of truth for unreturned direct-element borrows that have no observable operand use.

State shape: a single dict keyed by a 2-tuple (root_logical_id, slot_descriptor) where root_logical_id is the logical_id of the root parent ArrayValue (after walking the slice_of chain) and slot_descriptor is f"const:<idx>" for slots covered by compile-time-constant slices. Symbolic-bound slices (those whose bounds remain non-constant post-fold) are not enumerated into per-qubit slots; the pass records only an exact "sym:<descriptor>" entry so a later SSA-version refresh of the same symbolic slice descriptor can update the owner without claiming any new concrete range.

Namespacing by root logical_id is required so that borrow / consumed state on one register (a) does not block access to the identically-named slot on another register (b); without it, measure(a[1::2]) would incorrectly mark b[1] and b[3] as destroyed.

Values are either an :class:ArrayValue (the slice view that owns the slot) or a _ConsumedSlotMarker (a slot already destroyed by a prior destructive view consume). isinstance on the value dispatches the two violation messages.

Overview

ClassDescription
ArrayValueAn array of typed IR values.
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
BinOpKind
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
CastOperationType cast operation for creating aliases over the same quantum resources.
CompOpComparison operation (EQ, NEQ, LT, LE, GT, GE).
ExpvalOpExpectation value operation.
ForOperationRepresents a for loop operation.
HasNestedOpsMixin for operations that contain nested operation lists.
IfMergeOne branch-merge slot of an :class:IfOperation.
IfOperationRepresents an if-else conditional operation.
MeasureOperation
MeasureVectorOperationMeasure a vector of qubits.
PassBase class for all compiler passes.
QubitBorrowConflictErrorQubit slot inaccessible because another live handle borrows it.
QubitConsumedErrorQubit handle used after being consumed by a previous operation.
SliceBorrowCheckPassPost-fold linearity checker for sliced views and borrow state.
UIntTypeType representing an unsigned integer.
ValidationErrorError during validation (e.g., non-classical I/O).
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.

Constants

Classes

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:

bool — True iff slice_of is non-None.

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

BinOp [source]

class BinOp(BinaryOperationBase)

Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: BinOpKind | None = None,
) -> None
Attributes

BinOpKind [source]

class BinOpKind(enum.Enum)
Attributes

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.


BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

CastOperation [source]

class CastOperation(Operation)

Type cast operation for creating aliases over the same quantum resources.

This operation does NOT allocate new qubits. It creates a new Value that references the same underlying quantum resources with a different type.

Use cases:

operands: [source_value] - The value being cast results: [cast_result] - The new value with target type (same physical qubits)

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    source_type: ValueType | None = None,
    target_type: ValueType | None = None,
    qubit_mapping: list[str] = list(),
) -> None
Attributes

CompOp [source]

class CompOp(BinaryOperationBase)

Comparison operation (EQ, NEQ, LT, LE, GT, GE).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CompOpKind | None = None,
) -> None
Attributes

ExpvalOp [source]

class ExpvalOp(Operation)

Expectation value operation.

This operation computes the expectation value <psi|H|psi> where psi is the quantum state and H is the Hamiltonian observable.

The operation bridges quantum and classical computation:

Example IR:

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


IfMerge [source]

class IfMerge(NamedTuple)

One branch-merge slot of an :class:IfOperation.

An IfOperation merges each variable touched by its branches back into a single SSA value. IfMerge is the read-side view of one such merge slot, decoupling every consumer from how the merge is stored in the IR (today the parallel IfOperation.true_yields / false_yields lists; the storage may change without touching consumers).

Attributes
Methods
select
def select(self, taken: bool) -> Value

Return the branch source selected by a resolved condition.

Parameters:

NameTypeDescription
takenboolThe condition’s truth value (True selects the true branch).

Returns:

Value — true_value when taken is true, else false_value.


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


MeasureOperation [source]

class MeasureOperation(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

MeasureVectorOperation [source]

class MeasureVectorOperation(Operation)

Measure a vector of qubits.

Takes a Vector[Qubit] (ArrayValue) and produces a Vector[Bit] (ArrayValue). This operation measures all qubits in the vector as a single operation.

operands: [ArrayValue of qubits] results: [ArrayValue of bits]

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


QubitBorrowConflictError [source]

class QubitBorrowConflictError(AffineTypeError)

Qubit slot inaccessible because another live handle borrows it.

Raised when a qubit slot cannot be accessed because another live handle currently borrows it — a slice view that has not been returned, an outstanding element borrow, or any future borrow form Qamomile may add. The same error is used whether the conflict is discovered while tracing concrete indices or after symbolic slice bounds are resolved during transpilation. Unlike :class:QubitConsumedError, the slot is not destroyed: releasing the borrowing handle (slice assignment, element write-back, etc.) restores access.

Example of incorrect code (overlapping slice views)::

a = q[0:3]      # q[0..2] now borrowed by ``a``
b = q[2:5]      # ERROR: q[2] is still borrowed by ``a``

Correct code::

a = q[0:3]
q[0:3] = a      # return ``a`` first
b = q[2:5]      # now safe

Example of incorrect code (element borrow not returned before borrowing a neighbour)::

q0 = qubits[0]
q0 = qmc.h(q0)
q1 = qubits[1]  # ERROR: q0 is still borrowed

Correct code::

q0 = qubits[0]
q0 = qmc.h(q0)
qubits[0] = q0  # return the element first
q1 = qubits[1]  # now safe

QubitConsumedError [source]

class QubitConsumedError(AffineTypeError)

Qubit handle used after being consumed by a previous operation.

Each qubit handle can only be used once. After a gate operation, you must reassign the result to use the new handle.

Example of incorrect code:

q1 = qm.h(q) q2 = qm.x(q) # ERROR: q was already consumed by h()

Correct code:

q = qm.h(q) # Reassign to capture new handle q = qm.x(q) # Use the reassigned handle


SliceBorrowCheckPass [source]

class SliceBorrowCheckPass(Pass[Block, Block])

Post-fold linearity checker for sliced views and borrow state.

Runs after :class:ConstantFoldingPass (so slice bounds are concrete where possible) and before segmentation / emit. Walks the operations of the root block in order, maintaining a borrow state map modelled on the frontend’s :attr:ArrayBase._borrowed_indices — a single dict whose values are slice-view ArrayValue owners or the _ConsumedSlotMarker sentinel. Creating a direct element borrow (q[i]) emits no IR operation, but later operand uses remain visible to this pass; the frontend validator handles an unreturned borrow with no observable operand use.

The pass does not flag a leftover slice view at block end — slice views are affine at the kernel boundary, mirroring how element borrows behave on a locally-allocated register (the frontend’s qamomile.circuit.frontend.func_to_block._validate_returned_arrays covers the genuine leak: returning the parent with a live borrow). Anything that actually clashes with a live view (direct slot access, destructive parent consume, overlapping views, use-after-destroy) is rejected at the eager check points listed in the module docstring.

Constructor
def __init__(self) -> None

Initialize per-run mutable state to safe defaults.

Attributes
Methods
run
def run(self, input: Block) -> Block

Run the borrow tracker over input.

Parameters:

NameTypeDescription
inputBlockBlock to check. Expected to be in AFFINE or HIERARCHICAL kind — post-fold but pre-segmentation.

Returns:

Block — The same block unchanged after successful validation.

Raises:


UIntType [source]

class UIntType(ClassicalTypeMixin, ValueType)

Type representing an unsigned integer.


ValidationError [source]

class ValidationError(QamomileCompileError)

Error during validation (e.g., non-classical I/O).

Constructor
def __init__(self, message: str, value_name: str | None = None)

Initialize a validation diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable validation failure.
value_namestr | NoneRelated IR value name. Defaults to None.
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 engine 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.


qamomile.circuit.transpiler.passes.standard_emit

Shared semantic-to-circuit lowering engine.

This module provides the legacy-named StandardEmitPass used internally by CircuitLoweringPass to walk Qamomile semantic IR and construct the engine-neutral circuit-family IR.

The actual emission logic is decomposed into focused modules under emit_support/. This class serves as the orchestrator with thin wrappers that delegate to those module functions. SDK engines do not subclass this engine; they consume the resulting immutable circuit program.

Overview

FunctionDescription
blockvalue_to_gateConvert a Block to an engine gate.
clean_ancilla_toffoli_ladderReturn the arithmetic for the named clean-ancilla recipe.
emit_controlled_fallbackFallback emission for controlled-U when gate conversion fails.
emit_controlled_uEmit a controlled operation for every concrete operand layout.
emit_forEmit a for loop.
emit_for_itemsEmit for-items loop (always unrolled).
emit_gateEmit a single gate operation.
emit_global_phaseEmit a standalone phase when the lowering adapter collects it.
emit_ifEmit if/else operation.
emit_inverse_blockEmit a first-class inverse block operation.
emit_invoke_operationEmit an invoke operation.
emit_measureEmit a single measurement.
emit_measure_qfixedEmit QFixed measurement.
emit_measure_vectorEmit vector measurement.
emit_multi_controlled_on_clean_ancillasLower an irreducible multi-controlled gate via a Toffoli cascade.
emit_pauli_evolveEmit Pauli evolution: exp(-i * gamma * H).
emit_whileEmit while loop operation.
evaluate_binopEvaluate a BinOp and store the result in bindings.
evaluate_classical_predicateEvaluate a CompOp/CondOp/NotOp at emit time and bind its boolean result.
evaluate_dict_getitemEvaluate a DictGetItemOperation and store the result in bindings.
handle_castHandle CastOperation - update qubit_map without emitting gates.
mark_updated_while_conditionRecord that a while update may overwrite its initial snapshot clbit.
reject_stale_runtime_conditionReject rereading a measurement snapshot overwritten by an earlier loop.
split_parameter_keySplit an emitted scalar key into its root name and array indices.
ClassDescription
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
CastOperationType cast operation for creating aliases over the same quantum resources.
CompOpComparison operation (EQ, NEQ, LT, LE, GT, GE).
CompositeGateEmitterProtocol for preserving or lowering boxed callable operations.
CondOpConditional logical operation (AND, OR).
ControlBatchProfileDescribe resolved work and the engine’s exact-two-control choice.
ControlledUOperationBase class for controlled-U operations.
CountingEmitterA no-op gate emitter that lets a real emission walk run for counting.
DictGetItemOperationLook up one entry of a Dict by a (possibly symbolic) key.
EmitContextBindings container with semantic slots, dict-compatible.
EmitErrorReport an engine failure to emit one semantic operation.
EmitPassBase class for engine-specific emission passes.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
GateEmitterProtocol for engine-specific gate emission.
GateOperationQuantum gate operation.
GateOperationType
GlobalPhaseOperationMultiply the complete quantum state by exp(i * phase).
HasNestedOpsMixin for operations that contain nested operation lists.
IfOperationRepresents an if-else conditional operation.
InverseBlockOperationRepresent an inverse qkernel/block as a first-class IR operation.
InvokeOperationRepresent a composite, stdlib, or oracle call.
MeasureOperation
MeasureQFixedOperationMeasure a quantum fixed-point number.
MeasureQIntOperationMeasure an unsigned quantum integer as one abstract hybrid operation.
MeasureVectorOperationMeasure a vector of qubits.
NotOp
OperationKindClassification of operations for classical/quantum separation.
ParameterContainerKindClassify the public container that owns one engine scalar slot.
PauliEvolveOpPauli evolution operation: exp(-i * gamma * H).
ProjectOperationProject a qubit in one Pauli basis and keep the projected state.
QInitOperationInitialize the qubit
ResetOperationReset a qubit to the |0> state and return the fresh handle.
ReturnQuantumArrayElementOperationValidate a branch-selected quantum element’s array return at emit time.
RuntimeClassicalExprA classical expression known to require runtime evaluation.
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
StandardEmitPassStandard emit pass implementation using GateEmitter protocol.
StoreArrayElementOperationStore a classical scalar into one element of a classical array.
ValueA typed SSA value in the IR.
WhileOperationRepresents a while loop operation.

Functions

blockvalue_to_gate [source]

def blockvalue_to_gate(
    emit_pass: 'StandardEmitPass',
    block_value: Any,
    num_qubits: int,
    bindings: dict[str, Any],
    input_operands: list[Any] | None = None,
    operation_name: str = 'ControlledUOperation',
) -> Any

Convert a Block to an engine gate.

Pre-populates local_qubit_map with one entry per quantum input in declaration order, then runs the allocator over the block’s body. For Vector[Qubit] inputs (ArrayValue with a quantum element type) the entry expands into per-element QubitAddress(uuid, i) keys — the inner block has no QInitOperation for inputs, so without these the allocator’s element-resolution assertion fires for every qs[i] reference in the body.

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe emit pass driving the conversion. Used for its _allocator, _emitter, _resolver, and _emit_operations.
block_valueAnyThe inner block to convert. Expected to expose operations and input_values; anything else returns None (the caller falls back to gate-by-gate decomposition).
num_qubitsintTotal physical qubits the resulting gate will occupy in the parent circuit. Used as the fallback length for a single Vector[Qubit] input whose shape is symbolic and unresolvable from bindings, and as the sub-circuit width when the block has no qubit-producing operations.
bindingsdict[str, Any]Parameter bindings forwarded to the allocator and _emit_operations. Also consulted when resolving Vector[Qubit] input shapes.
input_operandslist[Any] | NoneOptional call-site operands corresponding to block_value.input_values. Quantum operands propagate actual Vector[Qubit] shapes into the nested block before the vector-aware input qubit map is populated; classical operands are resolved into local bindings before the nested block is emitted. Defaults to None.
operation_namestrOperation name used in diagnostics when input binding fails. Defaults to "ControlledUOperation".

Returns:

Any — An engine gate object produced by emit_pass._emitter.circuit_to_gate, or None when the conversion is unable to proceed (missing operations, allocator / emitter exception, etc.) so the caller can fall back to gate-by-gate emission.


clean_ancilla_toffoli_ladder [source]

def clean_ancilla_toffoli_ladder(num_controls: int | sp.Expr) -> CleanAncillaToffoliLadder[Any]

Return the arithmetic for the named clean-ancilla recipe.

The caller owns recipe selection and must use the result on a branch where at least two controls are active. Keeping validation outside this helper lets symbolic resource expressions construct inactive Piecewise branches without prematurely rejecting them.

Parameters:

NameTypeDescription
num_controlsint | sp.ExprConcrete or symbolic control count.

Returns:

CleanAncillaToffoliLadder[Any] — CleanAncillaToffoliLadder[Any]: Compute, total-Toffoli, and clean- ancilla requirements in the same numeric domain as the input.


emit_controlled_fallback [source]

def emit_controlled_fallback(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    block_value: Any,
    num_controls: int,
    control_indices: list[int],
    target_indices: list[int],
    power: int,
    bindings: dict[str, Any],
    batch_profile: ControlBatchProfile | None = None,
) -> None

Fallback emission for controlled-U when gate conversion fails.

Decomposes the block body gate-by-gate under the full control set. A block-local qubit map ties the block’s formal quantum inputs to target_indices, so every inner gate is emitted on the physical qubit its operand resolves to — multi-target inner blocks are supported. Nested ControlledUOperations compose their controls with the outer ones; irreducible multi-controlled single-qubit gates route through the engine’s _emit_irreducible_multi_controlled_gate hook. Subclasses may still override this method to emit controlled blocks natively (e.g. CUDA-Q’s cudaq.control helper kernels).

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being built.
block_valueAnyBlock whose operations should be controlled.
num_controlsintNumber of control qubits.
control_indiceslist[int]Physical indices of control qubits.
target_indiceslist[int]Physical indices of target qubits.
powerintNumber of controlled body repetitions.
bindingsdict[str, Any]Parameter bindings visible in the body.
batch_profileControlBatchProfile | NonePreviously resolved body profile for this exact block and binding scope. Defaults to None, which lets the controlled walker compute it.

Raises:


emit_controlled_u [source]

def emit_controlled_u(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: ControlledUOperation,
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> None

Emit a controlled operation for every concrete operand layout.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
opControlledUOperationConcrete or symbolic controlled operation.
qubit_mapQubitMapLogical-to-physical map, mutated with results.
bindingsdict[str, Any]Bindings visible at the call site.

Raises:


emit_for [source]

def emit_for(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: ForOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
    force_unroll: bool = False,
) -> None

Emit a for loop.


emit_for_items [source]

def emit_for_items(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: ForItemsOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
) -> None

Emit for-items loop (always unrolled).

This handles iteration over Dict items, e.g.: for (i, j), Jij in qmc.items(ising): ...

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe emit pass (for resolver access).
circuitAnyThe engine circuit being built.
opForItemsOperationThe for-items loop being unrolled.
qubit_mapQubitMapCurrent qubit address mapping.
clbit_mapClbitMapCurrent classical bit address mapping.
bindingsdict[str, Any]Current emit-time bindings.

Raises:


emit_gate [source]

def emit_gate(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: GateOperation,
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> None

Emit a single gate operation.


emit_global_phase [source]

def emit_global_phase(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: GlobalPhaseOperation,
    bindings: dict[str, Any],
) -> None

Emit a standalone phase when the lowering adapter collects it.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyCircuit representation being emitted into.
opGlobalPhaseOperationGlobal-phase operation to emit.
bindingsdict[str, Any]Active emit bindings.

Raises:


emit_if [source]

def emit_if(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: IfOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
) -> None

Emit if/else operation.

Handles two condition types:

  1. Compile-time constant (plain Python int/bool from @qkernel AST transformer closure variables, constant-folded Values, or Values resolvable via bindings): the active branch is emitted unconditionally, the inactive branch is discarded. No engine c_if / if_test is needed.

  2. Runtime condition (measurement Value that cannot be resolved at compile time): delegates to the engine’s emit_if_start / emit_else_start / emit_if_end protocol.


emit_inverse_block [source]

def emit_inverse_block(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: InverseBlockOperation,
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> None

Emit a first-class inverse block operation.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
opInverseBlockOperationInverse block operation to emit.
qubit_mapQubitMapCurrent quantum value to physical qubit map.
bindingsdict[str, Any]Active emit bindings.

Raises:


emit_invoke_operation [source]

def emit_invoke_operation(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: InvokeOperation,
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> None

Emit an invoke operation.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted.
opInvokeOperationInvocation to emit.
qubit_mapQubitMapCurrent qubit allocation map.
bindingsdict[str, Any]Active emit bindings.

Raises:


emit_measure [source]

def emit_measure(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: MeasureOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any] | None = None,
) -> None

Emit a single measurement.

Resolves the qubit operand using the full resolver (handles both scalar qubits and array element qubits with composite keys).

Raises:


emit_measure_qfixed [source]

def emit_measure_qfixed(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: MeasureQFixedOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
) -> None

Emit QFixed measurement.


emit_measure_vector [source]

def emit_measure_vector(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: MeasureVectorOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
) -> None

Emit vector measurement.

Resolves the qubit operand’s slice_of chain so that measuring a view (measure(q[1::2])) correctly targets the root parent’s physical qubits.

Behaviour for unresolvable inputs differs by case:

Raises:


emit_multi_controlled_on_clean_ancillas [source]

def emit_multi_controlled_on_clean_ancillas(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    gate_type: GateOperationType,
    control_indices: list[int],
    target_idx: int,
    angle: Any,
    ancilla_indices: list[int],
) -> None

Lower an irreducible multi-controlled gate via a Toffoli cascade.

Implements the standard clean-ancilla construction (arXiv:2307.07478, Appendix A.3): the logical AND of the n controls is accumulated onto n - 1 clean ancillas with a cascade of Toffoli gates, the gate is applied once under a single control (the last ancilla) through :func:emit_single_controlled_primitive, and the cascade is uncomputed in reverse order. The cost is 2 * (n - 1) Toffoli gates plus one singly-controlled gate, and every ancilla returns to |0>, so the same pool may be reused by subsequent gates.

Unlike a dense 2**(n+1) unitary-matrix lowering, this scales linearly in the control count and keeps rotation angles symbolic, so runtime-parametric multi-controlled rotations are supported.

Parameters:

NameTypeDescription
emit_passStandardEmitPassActive emit pass.
circuitAnyEngine circuit being emitted into.
gate_typeGateOperationTypeSingle-qubit gate kind to apply under the controls.
control_indiceslist[int]Physical control qubits; at least two.
target_idxintPhysical target qubit.
angleAnyResolved rotation angle (concrete number or engine parameter expression) for rotation-like gates, or None for fixed gates.
ancilla_indiceslist[int]Clean (|0>) ancilla qubits; at least len(control_indices) - 1 entries.

Raises:


emit_pauli_evolve [source]

def emit_pauli_evolve(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: PauliEvolveOp,
    qubit_map: QubitMap,
    bindings: dict[str, Any],
) -> None

Emit Pauli evolution: exp(-i * gamma * H).

Resolves the Hamiltonian from bindings and decomposes each term using the Pauli gadget technique:

  1. Basis change per qubit (X->H, Y->Sdg*H, Z->identity)

  2. CNOT ladder + RZ

  3. Undo basis change

Subclasses can override this for engine-native implementations (e.g., Qiskit PauliEvolutionGate).


emit_while [source]

def emit_while(
    emit_pass: 'StandardEmitPass',
    circuit: Any,
    op: WhileOperation,
    qubit_map: QubitMap,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
) -> None

Emit while loop operation.


evaluate_binop [source]

def evaluate_binop(emit_pass: 'StandardEmitPass', op: BinOp, bindings: dict[str, Any]) -> None

Evaluate a BinOp and store the result in bindings.

Tries the shared fold_classical_op first for a clean concrete fold (which already encapsulates the runtime-parameter guard). Falls back to creating engine Parameter symbols and doing symbolic arithmetic when one or both operands are runtime parameters — that’s the path that lets rx(q, gamma * 2) produce a circuit with a single Parameter("gamma") * 2 expression rather than baking in a placeholder.


evaluate_classical_predicate [source]

def evaluate_classical_predicate(
    emit_pass: 'StandardEmitPass',
    op: 'CompOp | CondOp | NotOp',
    bindings: dict[str, Any],
) -> None

Evaluate a CompOp/CondOp/NotOp at emit time and bind its boolean result.

Mirrors the predicate evaluation already done by compile_time_if_lowering and classical_executor so that an IfOperation whose condition reaches emit unfolded — typically because its operands depend on a loop variable bound only at emit time by emit_for_items / emit_for_unrolled — can still be resolved via resolve_if_condition.

Delegates the actual fold (including runtime-parameter guard and strict scalar typing) to fold_classical_op so that all three callers of the same kind dispatch share one implementation. There is no symbolic-Parameter fallback for predicates: a runtime classical expression cannot be expressed as a folded scalar, so the op is left unbound and downstream emit handles it as a runtime condition.

Parameters:

NameTypeDescription
emit_pass'StandardEmitPass'The active emit pass (for resolver access).
op'CompOp | CondOp | NotOp'The predicate op to evaluate.
bindingsdict[str, Any]Current parameter/loop-variable bindings; mutated in place on successful evaluation. No-op when operands are unresolvable (e.g. measurement bits) or evaluation raises.

Returns:

None — None.


evaluate_dict_getitem [source]

def evaluate_dict_getitem(
    emit_pass: 'StandardEmitPass',
    op: DictGetItemOperation,
    bindings: dict[str, Any],
) -> None

Evaluate a DictGetItemOperation and store the result in bindings.

Resolves each key component (typically a for-items loop variable bound by UUID in bindings), looks the key up in the dict’s resolved entries, and writes the value into bindings under the result UUID so downstream ops (BinOps feeding gate angles) can consume it.

When the dict is a declared runtime parameter (transpile(..., parameters=["coeffs"])), there are no entries to look up; the resolved key instead names one engine parameter (coeffs[3] / coeffs[(0, 1)]) which is stored under the result UUID. Repeated lookups of the same key share one engine parameter via _get_or_create_parameter.

Parameters:

NameTypeDescription
emit_passStandardEmitPassThe emit pass (for resolver access).
opDictGetItemOperationThe lookup op being evaluated.
bindingsdict[str, Any]Current emit-time bindings.

Raises:


handle_cast [source]

def handle_cast(emit_pass: 'StandardEmitPass', op: CastOperation, qubit_map: QubitMap) -> None

Handle CastOperation - update qubit_map without emitting gates.


mark_updated_while_condition [source]

def mark_updated_while_condition(
    emit_pass: 'StandardEmitPass',
    operation: WhileOperation,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
) -> None

Record that a while update may overwrite its initial snapshot clbit.

Parameters:

NameTypeDescription
emit_passStandardEmitPassEmit pass carrying path-local overwrite state.
operationWhileOperationEmitted while operation.
clbit_mapClbitMapCurrent per-iteration clbit aliases.
bindingsdict[str, Any]Active emit-time bindings.

reject_stale_runtime_condition [source]

def reject_stale_runtime_condition(
    emit_pass: 'StandardEmitPass',
    condition: Value,
    clbit_map: ClbitMap,
    bindings: dict[str, Any],
) -> None

Reject rereading a measurement snapshot overwritten by an earlier loop.

Parameters:

NameTypeDescription
emit_passStandardEmitPassEmit pass carrying path-local overwrite state.
conditionValueRuntime if/while condition about to be emitted.
clbit_mapClbitMapCurrent per-iteration clbit aliases.
bindingsdict[str, Any]Active emit-time bindings.

Raises:


split_parameter_key [source]

def split_parameter_key(name: str) -> tuple[str, tuple[int, ...] | None]

Split an emitted scalar key into its root name and array indices.

Parameters:

NameTypeDescription
namestrEngine parameter key such as theta or angles[1][0].

Returns:

tuple[str, tuple[int, ...] | None] — tuple[str, tuple[int, ...] | None]: Root parameter name and its concrete index tuple, or None for a scalar parameter.

Classes

BinOp [source]

class BinOp(BinaryOperationBase)

Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: BinOpKind | None = None,
) -> None
Attributes

CastOperation [source]

class CastOperation(Operation)

Type cast operation for creating aliases over the same quantum resources.

This operation does NOT allocate new qubits. It creates a new Value that references the same underlying quantum resources with a different type.

Use cases:

operands: [source_value] - The value being cast results: [cast_result] - The new value with target type (same physical qubits)

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    source_type: ValueType | None = None,
    target_type: ValueType | None = None,
    qubit_mapping: list[str] = list(),
) -> None
Attributes

CompOp [source]

class CompOp(BinaryOperationBase)

Comparison operation (EQ, NEQ, LT, LE, GT, GE).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CompOpKind | None = None,
) -> None
Attributes

CompositeGateEmitter [source]

class CompositeGateEmitter(Protocol[C])

Protocol for preserving or lowering boxed callable operations.

The concrete compiler installs a semantic emitter that boxes every executable callable into circuit IR with its identity and fallback body. Native SDK selection happens later, through target capabilities and legalization; this traversal hook must not import or select an engine.

Methods
can_emit
def can_emit(self, gate_type: CompositeGateType) -> bool

Check whether this emitter handles the given callable kind.

Parameters:

NameTypeDescription
gate_typeCompositeGateTypeCallable kind to check.

Returns:

bool — True if this emitter handles the callable kind.

emit
def emit(
    self,
    circuit: C,
    op: InvokeOperation,
    qubit_indices: list[int],
    bindings: dict[str, Any],
) -> bool

Preserve or lower the boxed callable into the output builder.

Parameters:

NameTypeDescription
circuitCOutput builder receiving the callable representation.
opInvokeOperationInvocation to preserve or lower.
qubit_indiceslist[int]Physical qubit indices for the operation.
bindingsdict[str, Any]Parameter bindings for the operation.

Returns:

bool — True if handled, or False to use the generic fallback bool — decomposition.


CondOp [source]

class CondOp(BinaryOperationBase)

Conditional logical operation (AND, OR).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: CondOpKind | None = None,
) -> None
Attributes

ControlBatchProfile [source]

class ControlBatchProfile

Describe resolved work and the engine’s exact-two-control choice.

Parameters:

NameTypeDescription
weightintControlled work clamped to zero, one, or two.
selects_exact_twoboolWhether the engine selects a shared carrier when exactly two outer controls are present.
Constructor
def __init__(self, weight: int = 0, selects_exact_two: bool = False) -> None
Attributes

ControlledUOperation [source]

class ControlledUOperation(Operation)

Base class for controlled-U operations.

Two concrete subclasses handle distinct operand layouts:

All isinstance(op, ControlledUOperation) checks match every subclass.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int | Value = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]
replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

CountingEmitter [source]

class CountingEmitter

A no-op gate emitter that lets a real emission walk run for counting.

Wraps the real engine emitter, delegating capability queries so control-flow lowering matches real emission while turning every gate emission into a no-op and every gate/sub-circuit construction into a None that forces the cascade-prone fallback path. Used by isolated analysis-emission transactions for ancilla sizing and zero-work semantic validation; the object is passed where a GateEmitter[T] is expected via a cast.

Constructor
def __init__(self, real: Any) -> None

Wrap a real emitter for a counting run.

Parameters:

NameTypeDescription
realAnyThe engine emitter whose capability answers should be mirrored so the walk makes the same structural choices.
Attributes
Methods
append_gate
def append_gate(self, circuit: Any, gate: Any, qubits: list[int]) -> None

Count appending a prebuilt gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
gateAnyIgnored gate object (never built in counting mode).
qubitslist[int]Ignored qubit indices the gate acts on.
circuit_to_gate
def circuit_to_gate(self, circuit: Any, name: str = 'U') -> Any

Force the fallback path by declining to build a reusable gate.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
namestrIgnored gate name. Defaults to "U".

Returns:

Any — Always None.

combine_symbolic
def combine_symbolic(self, kind: Any, lhs: Any, rhs: Any) -> _CountingParameter

Return a placeholder for a symbolic angle combination.

Parameters:

NameTypeDescription
kindAnyIgnored binary-op kind.
lhsAnyIgnored left operand.
rhsAnyIgnored right operand.

Returns:

_CountingParameter — A placeholder symbolic angle.

create_circuit
def create_circuit(self, num_qubits: int, num_clbits: int) -> _CountingCircuit

Return a placeholder circuit.

Parameters:

NameTypeDescription
num_qubitsintIgnored.
num_clbitsintIgnored.

Returns:

_CountingCircuit — A stateless placeholder.

create_parameter
def create_parameter(self, name: str) -> _CountingParameter

Return an arithmetic-absorbing placeholder parameter.

Parameters:

NameTypeDescription
namestrIgnored.

Returns:

_CountingParameter — A placeholder runtime parameter.

emit_barrier
def emit_barrier(self, circuit: Any, qubits: list[int]) -> None

Count a barrier as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitslist[int]Ignored qubit indices spanned by the barrier.
emit_ch
def emit_ch(self, circuit: Any, control: int, target: int) -> None

Count a CH gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
emit_cp
def emit_cp(self, circuit: Any, control: int, target: int, angle: Any) -> None

Count a controlled-phase gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
angleAnyIgnored phase angle.
emit_crx
def emit_crx(self, circuit: Any, control: int, target: int, angle: Any) -> None

Count a CRX gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
angleAnyIgnored rotation angle.
emit_cry
def emit_cry(self, circuit: Any, control: int, target: int, angle: Any) -> None

Count a CRY gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
angleAnyIgnored rotation angle.
emit_crz
def emit_crz(self, circuit: Any, control: int, target: int, angle: Any) -> None

Count a CRZ gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
angleAnyIgnored rotation angle.
emit_cx
def emit_cx(self, circuit: Any, control: int, target: int) -> None

Count a CX gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
emit_cy
def emit_cy(self, circuit: Any, control: int, target: int) -> None

Count a CY gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
emit_cz
def emit_cz(self, circuit: Any, control: int, target: int) -> None

Count a CZ gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
controlintIgnored control qubit index.
targetintIgnored target qubit index.
emit_else_start
def emit_else_start(self, circuit: Any, context: Any) -> None

Count the start of a native else branch as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
contextAnyIgnored branch context from emit_if_start.
emit_for_loop_end
def emit_for_loop_end(self, circuit: Any, context: Any) -> None

Count the end of a native for loop as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
contextAnyIgnored loop context from emit_for_loop_start.
emit_for_loop_start
def emit_for_loop_start(self, circuit: Any, indexset: range) -> Any

Return a placeholder loop variable for a native-for-loop count.

Unlike the other control-flow hooks, emit_for’s return value is bound as the loop variable (via _bind_loop_var) and the body is then walked once. A real native-loop emitter returns a symbolic loop parameter, so return the arithmetic-absorbing :class:_CountingParameter rather than None — otherwise a body that carries the loop value into an angle or index expression during counting would see None and fail. (No pool-reserving engine supports native for loops today, so this is future-proofing.)

Parameters:

NameTypeDescription
circuitAnyIgnored.
indexsetrangeIgnored.

Returns:

Any — A placeholder loop variable.

emit_global_phase
def emit_global_phase(self, circuit: Any, angle: Any) -> None

Accept a standalone phase during the internal counting walk.

The counting emitter observes only peak clean-ancilla demand. It does not materialize any gate, including a phase that the wrapped real emitter will preserve during the subsequent emission walk.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
angleAnyIgnored phase angle.
emit_h
def emit_h(self, circuit: Any, qubit: int) -> None

Count an H gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_if_end
def emit_if_end(self, circuit: Any, context: Any) -> None

Count the end of a native if/else block as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
contextAnyIgnored branch context from emit_if_start.
emit_if_start
def emit_if_start(self, circuit: Any, clbit: int, value: int = 1) -> Any

Count the start of a native if branch as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
clbitintIgnored predicate classical bit index.
valueintIgnored predicate value to match. Defaults to 1.

Returns:

Any — Always None (a null branch context).

emit_measure
def emit_measure(self, circuit: Any, qubit: int, clbit: int) -> None

Count a measurement as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored measured qubit index.
clbitintIgnored destination classical bit index.
emit_p
def emit_p(self, circuit: Any, qubit: int, angle: Any) -> None

Count a phase gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
angleAnyIgnored phase angle.
emit_reset
def emit_reset(self, circuit: Any, qubit: int) -> None

Count a reset as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored reset qubit index.
emit_rx
def emit_rx(self, circuit: Any, qubit: int, angle: Any) -> None

Count an RX gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
angleAnyIgnored rotation angle.
emit_ry
def emit_ry(self, circuit: Any, qubit: int, angle: Any) -> None

Count an RY gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
angleAnyIgnored rotation angle.
emit_rz
def emit_rz(self, circuit: Any, qubit: int, angle: Any) -> None

Count an RZ gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
angleAnyIgnored rotation angle.
emit_rzz
def emit_rzz(self, circuit: Any, qubit1: int, qubit2: int, angle: Any) -> None

Count an RZZ gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubit1intIgnored first qubit index.
qubit2intIgnored second qubit index.
angleAnyIgnored rotation angle.
emit_s
def emit_s(self, circuit: Any, qubit: int) -> None

Count an S gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_sdg
def emit_sdg(self, circuit: Any, qubit: int) -> None

Count an Sdg gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_swap
def emit_swap(self, circuit: Any, qubit1: int, qubit2: int) -> None

Count a SWAP gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubit1intIgnored first qubit index.
qubit2intIgnored second qubit index.
emit_t
def emit_t(self, circuit: Any, qubit: int) -> None

Count a T gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_tdg
def emit_tdg(self, circuit: Any, qubit: int) -> None

Count a Tdg gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_toffoli
def emit_toffoli(self, circuit: Any, control1: int, control2: int, target: int) -> None

Count a Toffoli gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
control1intIgnored first control qubit index.
control2intIgnored second control qubit index.
targetintIgnored target qubit index.
emit_while_end
def emit_while_end(self, circuit: Any, context: Any) -> None

Count the end of a native while loop as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
contextAnyIgnored loop context from emit_while_start.
emit_while_start
def emit_while_start(self, circuit: Any, clbit: int, value: int = 1) -> Any

Count the start of a native while loop as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
clbitintIgnored predicate classical bit index.
valueintIgnored predicate value to match. Defaults to 1.

Returns:

Any — Always None (a null loop context).

emit_x
def emit_x(self, circuit: Any, qubit: int) -> None

Count an X gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_y
def emit_y(self, circuit: Any, qubit: int) -> None

Count a Y gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
emit_z
def emit_z(self, circuit: Any, qubit: int) -> None

Count a Z gate as a no-op.

Parameters:

NameTypeDescription
circuitAnyIgnored placeholder circuit.
qubitintIgnored target qubit index.
gate_controlled
def gate_controlled(self, gate: Any, num_controls: int) -> Any

Decline to build a real controlled gate.

Parameters:

NameTypeDescription
gateAnyIgnored gate object.
num_controlsintIgnored number of control qubits.

Returns:

Any — Always None.

gate_inverse
def gate_inverse(self, gate: Any) -> Any

Decline to build a real inverse gate.

Parameters:

NameTypeDescription
gateAnyIgnored gate object.

Returns:

Any — Always None.

gate_power
def gate_power(self, gate: Any, power: int) -> Any

Decline to build a real powered gate.

Parameters:

NameTypeDescription
gateAnyIgnored gate object.
powerintIgnored exponent.

Returns:

Any — Always None.

supports_for_loop
def supports_for_loop(self) -> bool

Delegate native-for-loop support to the wrapped emitter.

Returns:

bool — The real emitter’s answer, so loops unroll (or not) the same way real emission would.

supports_gate_inverse
def supports_gate_inverse(self) -> bool

Force the inverse-by-emission fallback path.

Returns:

bool — Always False.

supports_if_else
def supports_if_else(self) -> bool

Delegate native if/else support to the wrapped emitter.

Returns:

bool — The real emitter’s answer.

supports_reusable_gates
def supports_reusable_gates(self) -> bool

Force the gate-by-gate fallback path.

Returns:

bool — Always False.

supports_while_loop
def supports_while_loop(self) -> bool

Delegate native while-loop support to the wrapped emitter.

Returns:

bool — The real emitter’s answer.


DictGetItemOperation [source]

class DictGetItemOperation(Operation)

Look up one entry of a Dict by a (possibly symbolic) key.

This is the IR form of d[key] on a Dict handle. The key components may be symbolic (e.g. loop variables of a for-items loop); the lookup is resolved at emit time when the key values and the dict’s bound data are both concrete.

operands: [DictValue, *key_component_values] results: [looked-up scalar value]

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_arity: int = 1,
) -> None
Attributes

EmitContext [source]

class EmitContext(dict)

Bindings container with semantic slots, dict-compatible.

All emit-pipeline functions that take bindings: dict[str, Any] accept an EmitContext unchanged because it inherits from dict.

Use the typed methods (bind_param, set_value, etc.) when writing new code so the slot tracking stays accurate; existing ctx[key] = value writes still work but bypass the slots.

Slots:

_params: User-supplied kernel parameters, keyed by parameter name. Stable across the run. Name-keyed because the user supplies parameters by name at the public API boundary. _loop_vars: Currently-bound loop iteration variables, keyed by ForOperation.loop_var_value.uuid / ForItemsOperation.value_var_value.uuid etc. Pushed on loop entry, restored on exit. UUID-keyed so identical user-chosen variable names in nested or sibling loops never collide. _values: Emit-time-computed intermediate values (BinOp results, CompOp/CondOp/NotOp results, merge aliases), keyed by Value UUID. _runtime_exprs: Engine runtime-expression objects (e.g. Qiskit expr.Expr for compound classical conditions), keyed by Value UUID. _array_data: Bound array data (e.g. Vector[Float] parameter values), keyed by ArrayValue.uuid. _dict_data: Bound dict data (e.g. Dict[Tuple[UInt, UInt], Float] ising coefficients), keyed by DictValue.uuid. _observables: Bound Pauli observables (used by PauliEvolveOp and gate counting), keyed by observable Value UUID.

Example:

>>> ctx = EmitContext.from_user_bindings({"theta": 0.5, "n": 3})
>>> ctx["theta"]  # dict-style read still works
0.5
>>> ctx.bind_param("phi", 1.5)
>>> "phi" in ctx and ctx["phi"] == 1.5
True
>>> ctx.set_value(some_uuid, 42)
>>> ctx[some_uuid] == 42 and some_uuid in ctx._values
True
Constructor
def __init__(self, *args: Any = (), **kwargs: Any = {}) -> None
Methods
bind_param
def bind_param(self, name: str, value: Any) -> None

Register a kernel parameter binding (by name).

bind_params
def bind_params(self, params: dict[str, Any]) -> None

Register multiple kernel parameter bindings.

copy
def copy(self) -> 'EmitContext'

Return a shallow copy preserving all semantic slots.

The dict baseclass copy() returns a plain dict, dropping the slot-tracking metadata. Loop unrollers call bindings.copy() to make a per-iteration child scope; without this override the child would lose the params/loop_vars/values/runtime_exprs partitioning and become a flat dict, defeating the whole point of EmitContext. We override to return an EmitContext with slot dicts independently copied so child mutations (e.g. pushing a new loop var) don’t bleed back to the parent.

describe
def describe(self) -> str

Return a multi-line summary suitable for debug printing.

from_user_bindings
@classmethod
def from_user_bindings(cls, user_bindings: dict[str, Any] | None) -> 'EmitContext'

Build an EmitContext seeded with user-supplied parameters.

Parameters:

NameTypeDescription
user_bindingsdict[str, Any] | NoneThe dict passed by the user to transpile(); None is treated as empty.

Returns:

'EmitContext' — A fresh EmitContext with all entries registered as parameters.

get_array_data
def get_array_data(self, uuid: str) -> Any

Get array data by ArrayValue.uuid, or None.

get_dict_data
def get_dict_data(self, uuid: str) -> Any

Get dict data by DictValue.uuid, or None.

get_loop_var
def get_loop_var(self, uuid: str) -> Any

Get a loop variable binding by Value UUID, or None if absent.

get_observable
def get_observable(self, uuid: str) -> Any

Get a Pauli observable by Value UUID, or None.

get_runtime_expr
def get_runtime_expr(self, uuid: str) -> Any

Get an engine runtime expression by Value UUID, or None.

iter_values
def iter_values(self) -> Iterator[tuple[str, Any]]

Iterate over UUID-keyed emit-time intermediates only.

push_loop_var
def push_loop_var(self, uuid: str, value: Any, display_name: str | None = None) -> None

Bind a loop iteration variable, keyed by Value UUID.

Parameters:

NameTypeDescription
uuidstrloop_var_value.uuid (or per-key/value UUID for ForItemsOperation). Different loops with identical user-chosen names (e.g. nested for i) get distinct UUIDs and therefore never collide here.
valueAnyThe bound iteration value (int / Hamiltonian item / etc.).
display_namestr | NoneReserved for future debug-only use. Currently unused — loop variables are looked up exclusively by UUID, so the display name is never written into the bindings dict. Defaults to None.

Note: this adds a binding to the existing context. Loop unrollers typically copy the parent context first so the binding is local to one iteration; this method does not copy.

restore_state
def restore_state(self, snapshot: dict[str, Any]) -> None

Restore the dict body and slots from snapshot in place.

The object’s identity is preserved (the dict body is cleared and repopulated rather than replaced), so references held elsewhere stay valid.

Parameters:

NameTypeDescription
snapshotdict[str, Any]A snapshot from snapshot_state.

Returns:

None — None.

set_array_data
def set_array_data(self, uuid: str, data: Any, display_name: str | None = None) -> None

Bind array data by ArrayValue.uuid.

Parameters:

NameTypeDescription
uuidstrThe array Value’s UUID.
dataAnyThe bound iterable / sequence / Vector handle.
display_namestr | NoneReserved for debug-only display. It is not used as a binding key.
set_dict_data
def set_dict_data(self, uuid: str, data: Any, display_name: str | None = None) -> None

Bind dict data by DictValue.uuid.

Parameters:

NameTypeDescription
uuidstrThe dict Value’s UUID.
dataAnyThe bound dict / iterable.
display_namestr | NoneReserved for debug-only display. It is not used as a binding key.
set_observable
def set_observable(self, uuid: str, observable: Any, display_name: str | None = None) -> None

Bind a Pauli observable by Value UUID.

Parameters:

NameTypeDescription
uuidstrThe observable Value’s UUID.
observableAnyA qm_o.Hamiltonian (or engine-equivalent).
display_namestr | NoneReserved for debug-only display. It is not used as a binding key.
set_runtime_expr
def set_runtime_expr(self, uuid: str, expr: Any) -> None

Bind an engine runtime expression by Value UUID.

Engines (e.g. Qiskit) call this when they construct a runtime-evaluable expression for a classical predicate that wasn’t compile-time-foldable. _emit_if / _emit_while consult the runtime-expr slot first when resolving conditions.

set_value
def set_value(self, uuid: str, value: Any) -> None

Bind an emit-time-computed intermediate by Value UUID.

Use for BinOp / CompOp / CondOp / NotOp results, merge aliases, and other UUID-identified intermediates.

snapshot_state
def snapshot_state(self) -> dict[str, Any]

Capture the dict body and every semantic slot for later restore.

Used to run a throwaway dry-run emission (ancilla demand counting) against the same context object and then roll it back, so the count run’s intermediate fold results and parameters do not leak into the real emission. Unlike copy this records enough to restore this object in place, preserving its identity for callers that hold a reference to it.

Returns:

dict[str, Any] — dict[str, Any]: A snapshot passable to restore_state.


EmitError [source]

class EmitError(QamomileCompileError)

Report an engine failure to emit one semantic operation.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.

Example:

Correct — identify the unsupported operation at its target boundary::

    raise EmitError(
        "HUGR cannot emit a symbolic gate power",
        operation="ControlledUOperation",
    )

Incorrect — silently dropping an unsupported operation can change the
compiled program's meaning::

    if not target_supports(operation):
        return
Constructor
def __init__(self, message: str, operation: str | None = None)

Initialize an engine emission diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

EmitPass [source]

class EmitPass(Pass[ProgramPlan, ExecutableProgram[T]], Generic[T])

Base class for engine-specific emission passes.

Subclasses implement _emit_quantum_segment() to generate engine-specific quantum circuits.

Input: ProgramPlan Output: ExecutableProgram with compiled segments

Constructor
def __init__(
    self,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
)

Initialize with optional parameter bindings.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneValues to bind parameters to. If not provided, parameters must be bound at execution time.
parameterslist[str] | NoneList of parameter names to preserve as engine parameters.

Raises:

Attributes
Methods
run
def run(self, input: ProgramPlan) -> ExecutableProgram[T]

Emit engine code from a program plan.

Parameters:

NameTypeDescription
inputProgramPlanSegmented plan whose quantum and classical steps should be compiled.

Returns:

ExecutableProgram[T] — ExecutableProgram[T]: Executable program containing all compiled segments and the public output contract.

Raises:


ForItemsOperation [source]

class ForItemsOperation(HasNestedOps, Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    key_var_values: tuple[Value, ...] | None = None,
    value_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include the per-key/value Value fields for cloning/substitution.

Same rationale as ForOperation.all_input_values: keep the IR identity fields in lockstep with body references so UUID-keyed lookups stay valid after inline cloning. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the items-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing key/value formals, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the items-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt items-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

GateEmitter [source]

class GateEmitter(Protocol[T])

Protocol for engine-specific gate emission.

Each engine implements this protocol to emit individual gates to their circuit representation.

Type parameter T is the engine’s circuit type (e.g., QuantumCircuit).

Attributes
Methods
append_gate
def append_gate(self, circuit: T, gate: Any, qubits: list[int]) -> None

Append a gate to the circuit.

Parameters:

NameTypeDescription
circuitTThe circuit to append to
gateAnyThe gate to append (from circuit_to_gate)
qubitslist[int]Target qubit indices
circuit_to_gate
def circuit_to_gate(self, circuit: T, name: str = 'U') -> Any

Convert a circuit to a reusable gate.

Parameters:

NameTypeDescription
circuitTThe circuit to convert
namestrLabel for the gate

Returns:

Any — Engine-specific gate object, or None if not supported

create_circuit
def create_circuit(self, num_qubits: int, num_clbits: int) -> T

Create a new empty circuit.

Parameters:

NameTypeDescription
num_qubitsintNumber of qubits in the circuit
num_clbitsintNumber of classical bits in the circuit

Returns:

T — A new engine-specific circuit object

create_parameter
def create_parameter(self, name: str) -> Any

Create a symbolic parameter for the engine.

Parameters:

NameTypeDescription
namestrParameter name (e.g., “gammas[0]”)

Returns:

Any — Engine-specific parameter object

emit_barrier
def emit_barrier(self, circuit: T, qubits: list[int]) -> None

Emit barrier on specified qubits.

emit_ch
def emit_ch(self, circuit: T, control: int, target: int) -> None

Emit controlled-Hadamard gate.

emit_cp
def emit_cp(self, circuit: T, control: int, target: int, angle: float | Any) -> None

Emit controlled-Phase gate.

emit_crx
def emit_crx(self, circuit: T, control: int, target: int, angle: float | Any) -> None

Emit controlled-RX gate.

emit_cry
def emit_cry(self, circuit: T, control: int, target: int, angle: float | Any) -> None

Emit controlled-RY gate.

emit_crz
def emit_crz(self, circuit: T, control: int, target: int, angle: float | Any) -> None

Emit controlled-RZ gate.

emit_cx
def emit_cx(self, circuit: T, control: int, target: int) -> None

Emit CNOT gate.

emit_cy
def emit_cy(self, circuit: T, control: int, target: int) -> None

Emit controlled-Y gate.

emit_cz
def emit_cz(self, circuit: T, control: int, target: int) -> None

Emit CZ gate.

emit_else_start
def emit_else_start(self, circuit: T, context: Any) -> None

Start the else branch.

emit_for_loop_end
def emit_for_loop_end(self, circuit: T, context: Any) -> None

End a native for loop context.

emit_for_loop_start
def emit_for_loop_start(self, circuit: T, indexset: range) -> Any

Start a native for loop context.

Returns a context manager or loop parameter, depending on engine.

emit_h
def emit_h(self, circuit: T, qubit: int) -> None

Emit Hadamard gate.

emit_if_end
def emit_if_end(self, circuit: T, context: Any) -> None

End the if/else block.

emit_if_start
def emit_if_start(self, circuit: T, clbit: int, value: int = 1) -> Any

Start a native if context.

Returns context for the if/else block.

emit_measure
def emit_measure(self, circuit: T, qubit: int, clbit: int) -> None

Emit measurement operation.

emit_p
def emit_p(self, circuit: T, qubit: int, angle: float | Any) -> None

Emit Phase gate (P(θ) = diag(1, e^(iθ))).

emit_reset
def emit_reset(self, circuit: T, qubit: int) -> None

Emit a reset-to-zero operation.

Parameters:

NameTypeDescription
circuitTEngine circuit to emit into.
qubitintPhysical qubit index to reset.

Raises:

emit_rx
def emit_rx(self, circuit: T, qubit: int, angle: float | Any) -> None

Emit RX rotation gate.

Parameters:

NameTypeDescription
circuitTThe circuit to emit to
qubitintTarget qubit index
anglefloat | AnyRotation angle (float or engine parameter)
emit_ry
def emit_ry(self, circuit: T, qubit: int, angle: float | Any) -> None

Emit RY rotation gate.

emit_rz
def emit_rz(self, circuit: T, qubit: int, angle: float | Any) -> None

Emit RZ rotation gate.

emit_rzz
def emit_rzz(self, circuit: T, qubit1: int, qubit2: int, angle: float | Any) -> None

Emit RZZ gate (exp(-i * θ/2 * Z⊗Z)).

emit_s
def emit_s(self, circuit: T, qubit: int) -> None

Emit S gate (√Z).

emit_sdg
def emit_sdg(self, circuit: T, qubit: int) -> None

Emit S-dagger gate (inverse of S).

emit_swap
def emit_swap(self, circuit: T, qubit1: int, qubit2: int) -> None

Emit SWAP gate.

emit_t
def emit_t(self, circuit: T, qubit: int) -> None

Emit T gate (√S).

emit_tdg
def emit_tdg(self, circuit: T, qubit: int) -> None

Emit T-dagger gate (inverse of T).

emit_toffoli
def emit_toffoli(self, circuit: T, control1: int, control2: int, target: int) -> None

Emit Toffoli (CCX) gate.

emit_while_end
def emit_while_end(self, circuit: T, context: Any) -> None

End the while loop context.

emit_while_start
def emit_while_start(self, circuit: T, clbit: int, value: int = 1) -> Any

Start a native while loop context.

emit_x
def emit_x(self, circuit: T, qubit: int) -> None

Emit Pauli-X gate.

emit_y
def emit_y(self, circuit: T, qubit: int) -> None

Emit Pauli-Y gate.

emit_z
def emit_z(self, circuit: T, qubit: int) -> None

Emit Pauli-Z gate.

gate_controlled
def gate_controlled(self, gate: Any, num_controls: int) -> Any

Create controlled version of a gate.

Parameters:

NameTypeDescription
gateAnyThe gate to control
num_controlsintNumber of control qubits

Returns:

Any — New controlled gate

gate_inverse
def gate_inverse(self, gate: Any) -> Any

Create an engine-native inverse gate when supported.

Parameters:

NameTypeDescription
gateAnyEngine-specific gate object returned by circuit_to_gate.

Returns:

Any — Engine-specific inverse gate object, or None when the Any — engine cannot invert reusable gates natively.

gate_power
def gate_power(self, gate: Any, power: int) -> Any

Create gate raised to a power (U^n).

Parameters:

NameTypeDescription
gateAnyThe gate to raise to a power
powerintThe power to raise to

Returns:

Any — New gate representing gate^power

supports_for_loop
def supports_for_loop(self) -> bool

Check if engine supports native for loops.

supports_gate_inverse
def supports_gate_inverse(self) -> bool

Return whether reusable gates can be inverted natively.

Returns:

bool — True when gate_inverse can return an engine-native inverse for gates produced by circuit_to_gate. Defaults to False.

supports_if_else
def supports_if_else(self) -> bool

Check if engine supports native if/else.

supports_reusable_gates
def supports_reusable_gates(self) -> bool

Return whether circuit_to_gate can produce reusable gates.

Returns:

bool — True when the engine can convert emitted sub-circuits to reusable gate objects. Defaults to False so emit paths can avoid building throwaway sub-circuits for engines that only support inline fallback emission.

supports_while_loop
def supports_while_loop(self) -> bool

Check if engine supports native while loops.


GateOperation [source]

class GateOperation(Operation)

Quantum gate operation.

For rotation gates (RX, RY, RZ, P, CP, RZZ), the angle parameter is stored as the last element of operands. Use the theta property for typed read access and the rotation / fixed factory class-methods for type-safe construction.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    gate_type: GateOperationType | None = None,
) -> None
Attributes
Methods
fixed
@classmethod
def fixed(
    cls,
    gate_type: GateOperationType,
    qubits: list[Value],
    results: list[Value],
) -> 'GateOperation'

Create a fixed gate (H, X, CX, SWAP, …) with no angle parameter.

rotation
@classmethod
def rotation(
    cls,
    gate_type: GateOperationType,
    qubits: list[Value],
    theta: Value,
    results: list[Value],
) -> 'GateOperation'

Create a rotation gate (RX, RY, RZ, P, CP, RZZ) with an angle.


GateOperationType [source]

class GateOperationType(enum.Enum)
Attributes

GlobalPhaseOperation [source]

class GlobalPhaseOperation(Operation)

Multiply the complete quantum state by exp(i * phase).

Global phase has no target qubit and does not create a new quantum value. Keeping the phase as the operation’s sole ordinary operand lets generic IR passes substitute, serialize, and analyze it without a special value-field protocol. A surrounding controlled-unitary lowering turns the operation into an observable phase gate on the accumulated controls.

Parameters:

NameTypeDescription
operandslist[Value]Exactly one scalar FloatType phase angle in radians.
resultslist[Value]Must be empty because global phase changes no qubit identity.

Raises:

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


InverseBlockOperation [source]

class InverseBlockOperation(Operation)

Represent an inverse qkernel/block as a first-class IR operation.

The operation stores both the original forward block and a Qamomile-built inverse implementation block. Emitters may use source_block with a engine-native inverse/adjoint primitive, then fall back to implementation_block when native inversion is unavailable.

Operands are ordered as scalar control qubits, target quantum operands, then classical/object parameters. Results mirror the quantum operand layout: control results first, then one target result per target operand. Vector target operands therefore count as one operand/result while contributing their scalar width to num_target_qubits.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_control_qubits: int = 0,
    num_target_qubits: int = 0,
    custom_name: str = '',
    source_block: Block | None = None,
    implementation_block: Block | None = None,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_value: int | None = None,
) -> None
Attributes

InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.
Constructor
def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes
Methods
body_for_transform
def body_for_transform(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> tuple[Block | None, CallTransform]

Select a body and report the transform it already realizes.

A controlled-inverse invocation may reuse an explicitly registered inverse body when no implementation realizes both transforms. Keeping that fallback in the IR operation gives emitters and static analyses one selection rule while still letting each consumer apply the remaining coherent controls in its own representation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — tuple[Block | None, CallTransform]: Selected body and the transform CallTransform — already implemented by that body. The callable’s direct body is tuple[Block | None, CallTransform] — returned with DIRECT when no transform-specific body matches.

Raises:

effective_body
def effective_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — Block | None: Selected implementation body, or the callable’s Block | None — default body when no transform-specific implementation exists. Block | None — A compiler may synthesize inverse or controlled behavior from this Block | None — fallback body.

implementation_for
def implementation_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None, which only selects engine-generic implementations.
strategystr | NoneStrategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation candidate, CallableImplementation | None — or None when the callable definition has no match.

measurement_result_indices_for
def measurement_result_indices_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> frozenset[int]

Return measurement-derived results for one selected implementation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name used for implementation selection. Defaults to None.
strategystr | NoneStrategy name used for implementation selection. Defaults to the invocation’s strategy_name.

Returns:

frozenset[int] — frozenset[int]: Caller-local result positions derived from measurement in the selected body.

Raises:

select_body
def select_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> CallableBodySelection

Select and validate the composable body for this invocation.

The result carries the transform already realized by the body and the exact call-site values that bind to it. Consumers therefore cannot independently disagree about whether an invocation’s control prefix belongs to the selected implementation ABI.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

CallableBodySelection — Validated body, realized transform, and CallableBodySelection — aligned call-site operands and results.

Raises:


MeasureOperation [source]

class MeasureOperation(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

MeasureQFixedOperation [source]

class MeasureQFixedOperation(Operation)

Measure a quantum fixed-point number.

This operation measures all qubits in a QFixed register and produces a Float result. During transpilation, this is lowered to individual MeasureOperations plus a DecodeQFixedOperation.

operands: [QFixed value (contains qubit_values in params)] results: [Float value]

Encoding:

For QPE phase (int_bits=0): Qubits are stored least-significant first. For n qubits, bit i has weight 2**(-n + i).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_bits: int = 0,
    int_bits: int = 0,
) -> None
Attributes

MeasureQIntOperation [source]

class MeasureQIntOperation(Operation)

Measure an unsigned quantum integer as one abstract hybrid operation.

The carrier sequence is least-significant-bit first: carrier i has integer weight 2**i. Planning lowers this operation to one vector measurement followed by a host-side DecodeQIntOperation.

The carrier width is not stored on the operation: it is derived from the register operand’s type and carrier metadata through num_bits.

Parameters:

NameTypeDescription
operandslist[Value]Single QUIntType register operand.
resultslist[Value]Single decoded UIntType result.
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

MeasureVectorOperation [source]

class MeasureVectorOperation(Operation)

Measure a vector of qubits.

Takes a Vector[Qubit] (ArrayValue) and produces a Vector[Bit] (ArrayValue). This operation measures all qubits in the vector as a single operation.

operands: [ArrayValue of qubits] results: [ArrayValue of bits]

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

NotOp [source]

class NotOp(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

OperationKind [source]

class OperationKind(enum.Enum)

Classification of operations for classical/quantum separation.

This enum is used to categorize operations during compilation to determine which parts run on classical hardware vs quantum hardware.

Values:

QUANTUM: Pure quantum operations (gates, qubit allocation) CLASSICAL: Pure classical operations (arithmetic, comparisons) HYBRID: Operations that bridge classical and quantum (measurement, encode/decode) CONTROL: Control flow structures (for, while, if)

Attributes

ParameterContainerKind [source]

class ParameterContainerKind(enum.StrEnum)

Classify the public container that owns one engine scalar slot.

Attributes

PauliEvolveOp [source]

class PauliEvolveOp(Operation)

Pauli evolution operation: exp(-i * gamma * H).

This operation applies the time evolution of a Pauli Hamiltonian to a quantum register.

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ProjectOperation [source]

class ProjectOperation(Operation)

Project a qubit in one Pauli basis and keep the projected state.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    axis: str = 'z',
) -> None
Attributes

QInitOperation [source]

class QInitOperation(Operation)

Initialize the qubit

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ResetOperation [source]

class ResetOperation(Operation)

Reset a qubit to the |0> state and return the fresh handle.

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ReturnQuantumArrayElementOperation [source]

class ReturnQuantumArrayElementOperation(Operation)

Validate a branch-selected quantum element’s array return at emit time.

Most quantum element assignments are verified structurally by the frontend and emit no IR. A compile-time conditional can instead select different element indices on its branches; only the unrolled emit context knows which source index survived. This operation carries both the requested target indices and the conditional source indices so emission can prove they resolve to the same physical slot before treating the assignment as a borrow return.

Operand convention:

[array, returned_qubit, *target_indices, *source_indices]. The target and source halves have equal nonzero arity, inferred from the operand count. The operation has no results and emits no engine gate.

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

RuntimeClassicalExpr [source]

class RuntimeClassicalExpr(Operation)

A classical expression known to require runtime evaluation.

Lowered from CompOp / CondOp / NotOp / BinOp by ClassicalLoweringPass when the op’s operand dataflow traces back to a MeasureOperation (i.e. cannot be folded at compile-time, by emit-time loop unrolling, or by compile_time_if_lowering). Engine emit translates this 1:1 to an engine-native runtime expression (e.g. qiskit.circuit.classical.expr.Expr).

Operand convention:

The single-node + unified-kind shape (vs four parallel subclasses) keeps the engine dispatch a single match op.kind instead of four parallel hooks, and makes the IR self-documenting: a single RuntimeClassicalExpr instance signals “runtime evaluation required” regardless of which classical family it came from.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: RuntimeOpKind | None = None,
) -> None
Attributes

SelectOperation [source]

class SelectOperation(Operation)

Quantum multiplexer: apply case_blocks[i] when the index reads i.

Concrete operand layout: [idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...]. Symbolic-width operand layout: [idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...]. Results mirror the quantum operand grouping.

A concrete index register is normalized to one scalar Qubit operand per physical index qubit. A symbolic-width register instead retains each leading caller argument as one scalar or array operand until its bound shape is known. Whole-Vector[Qubit] / scalar targets follow and keep their shapes, and classical parameters shared across every case come last.

Index bit order is LSB-first: idx_0 is the least-significant bit, matching Qamomile’s qubit-zero convention. Case i is selected when index qubit j reads bit j of i. len(case_blocks) need not be a power of two; index values >= len(case_blocks) apply no operation (identity).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_index_qubits: int | Value = 0,
    case_blocks: list[Block] = list(),
    num_index_args: int = 0,
    case_callable_attrs: list[dict[str, Any]] = list(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Return every value consumed by the SELECT operation.

Returns:

list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width value when present.

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed replacement values.

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


StandardEmitPass [source]

class StandardEmitPass(EmitPass[T], Generic[T])

Standard emit pass implementation using GateEmitter protocol.

This class provides orchestration for semantic IR traversal while delegating circuit instruction construction to a GateEmitter. The concrete compiler use is CircuitLoweringPass; SDK targets materialize its immutable result instead of subclassing this class.

Parameters:

NameTypeDescription
gate_emitterGateEmitter[T]Instruction builder used during the semantic traversal.
bindingsdict[str, Any] | NoneCompile-time parameter bindings.
parameterslist[str] | NoneParameter names preserved at runtime.
composite_emitterslist[CompositeGateEmitter[T]] | NoneOptional callable-preservation or lowering hooks.
engine_namestr | NoneDiagnostic name for the traversal target.
Constructor
def __init__(
    self,
    gate_emitter: GateEmitter[T],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
    composite_emitters: list[CompositeGateEmitter[T]] | None = None,
    engine_name: str | None = None,
)
Attributes

StoreArrayElementOperation [source]

class StoreArrayElementOperation(Operation)

Store a classical scalar into one element of a classical array.

This is the IR form of array[index] = value for classical element types (Bit / UInt / Float). Classical values are freely copyable, so the store is an ordinary SSA rewrite: the operation consumes the current array version and produces a new ArrayValue version (same logical_id, fresh uuid) whose contents equal the input array with the addressed element replaced. Quantum arrays never use this operation — qubit element assignment is the return half of the borrow-return idiom and emits no IR.

The operation is evaluated in one of two places:

Operand convention:

operands: [array (ArrayValue), stored_value (Value), *index_values] results: [new_array (ArrayValue)]

Example:

@qmc.qkernel
def k() -> qmc.Vector[qmc.Bit]:
    qs = qmc.qubit_array(2, "qs")
    qs[0] = qmc.x(qs[0])
    bits = qmc.measure(qs)
    bits[1] = bits[0]   # emits StoreArrayElementOperation
    return bits
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
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 engine resource allocation. This applies to every Value regardless of its type (Qubit, Float, Bit, ...) -- it is not specific to qubits.


WhileOperation [source]

class WhileOperation(HasNestedOps, Operation)

Represents a while loop operation.

Only measurement-backed conditions are supported: the condition must be a Bit value produced by qmc.measure(). Non-measurement conditions (classical variables, constants, comparisons) are rejected by ValidateWhileContractPass before reaching engine emit.

Example::

bit = qmc.measure(q)
while bit:
    q = qmc.h(q)
    bit = qmc.measure(q)
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    operations: list[Operation] = list(),
    max_iterations: int | None = None,
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include rebind records and region args for cloning/substitution.

Same rationale as ForOperation.all_input_values: rebind records and region arguments reference body/pre-loop values by identity, so inline cloning must remap them in lockstep with body operands.

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus rebind-record and region-argument values.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the while body with explicit boundary values.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region whose block arguments and yields are aligned with region_args. The updated condition, when present, is appended as the final yield.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the while body and its complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt while operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, rebind-record, and region-arg values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


qamomile.circuit.transpiler.passes.strip_slice_ops

Strip SliceArrayOperation / ReleaseSliceViewOperation after the linearity check.

Both ops are purely declarative — the resulting sliced ArrayValue carries all the emit-time metadata on its own (slice_of / slice_start / slice_step), and the release marker only exists so SliceBorrowCheckPass can observe explicit slice-assignment borrow-returns in program order. ConstantFoldingPass keeps these ops around when strip_slice_ops=False so the downstream linearity check can see them. Once the linearity check has run, both ops are unneeded; segmentation and emission expect a pure quantum-op stream without classical slice declarations in the middle. This pass removes them and leaves the block otherwise unchanged.

Overview

ClassDescription
BlockUnified block representation for all pipeline stages.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
OperationTransformerBase class for transforming operations with control flow handling.
PassBase class for all compiler passes.
StripSliceArrayOpsPassRemove SliceArrayOperation / ReleaseSliceViewOperation nodes.

Classes

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.


ForItemsOperation [source]

class ForItemsOperation(HasNestedOps, Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    key_var_values: tuple[Value, ...] | None = None,
    value_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include the per-key/value Value fields for cloning/substitution.

Same rationale as ForOperation.all_input_values: keep the IR identity fields in lockstep with body references so UUID-keyed lookups stay valid after inline cloning. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the items-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing key/value formals, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the items-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt items-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

OperationTransformer [source]

class OperationTransformer(ABC)

Base class for transforming operations with control flow handling.

Subclasses override transform_operation to define per-operation transformation. Control flow recursion and rebuilding is handled automatically.

Example:

class OperationRenamer(OperationTransformer):
    def transform_operation(self, op: Operation) -> Operation:
        # Return modified operation
        return dataclasses.replace(op, ...)
Methods
transform_operation
def transform_operation(self, op: Operation) -> Operation | None

Transform a single operation. Return None to remove it.

transform_operations
def transform_operations(self, operations: list[Operation]) -> list[Operation]

Transform all operations including nested control flow.


Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


StripSliceArrayOpsPass [source]

class StripSliceArrayOpsPass(Pass[Block, Block])

Remove SliceArrayOperation / ReleaseSliceViewOperation nodes.

Both ops are only meaningful to SliceBorrowCheckPass as view-declaration / release markers; downstream passes (analyze, plan, emit) neither need nor expect them. Dropping them here keeps the segmentation quantum-op-only.

Attributes
Methods
run
def run(self, input: Block) -> Block

Drop slice marker ops from input.

Walks the operation tree (including nested control flow) and returns a structurally identical block with every SliceArrayOperation and ReleaseSliceViewOperation node removed. The sliced ArrayValue results remain reachable through later operands’ parent_array chains, so emit-time resolution is unaffected.

Parameters:

NameTypeDescription
inputBlockBlock that has completed SliceBorrowCheckPass.

Returns:

Block — A new block with all slice marker ops removed.


qamomile.circuit.transpiler.passes.substitution

Substitution pass for replacing callable bodies and strategies.

This pass allows replacing:

  1. Inline callable bodies (QKernel subroutines) with alternative implementations

  2. InvokeOperation strategies with specified decomposition strategies

Example:

# Replace a custom oracle with an optimized version
config = SubstitutionConfig(
    rules=[
        SubstitutionRule(source_name="my_oracle", target=optimized_oracle),
        SubstitutionRule(source_name="qft", strategy="approximate_k2"),
    ]
)
pass = SubstitutionPass(config)
new_block = pass.run(block)

Overview

FunctionDescription
check_signature_compatibilityCheck signature compatibility between two Blocks.
create_substitution_passConvenience factory for creating a SubstitutionPass.
ClassDescription
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
CallableDefDescribe a compiler-facing callable definition.
CallableRefIdentify a callable independently of its Python object.
HasNestedOpsMixin for operations that contain nested operation lists.
InvokeOperationRepresent a composite, stdlib, or oracle call.
PassBase class for all compiler passes.
QKernelDecorator class for Qamomile quantum kernels.
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
SignatureCompatibilityErrorError raised when signatures are incompatible during substitution.
SubstitutionConfigConfiguration for the substitution pass.
SubstitutionPassPass that substitutes call operations and callable strategies.
SubstitutionRuleA single substitution rule.
ValidationErrorError during validation (e.g., non-classical I/O).

Functions

check_signature_compatibility [source]

def check_signature_compatibility(source: Block, target: Block, strict: bool = True) -> tuple[bool, str | None]

Check signature compatibility between two Blocks.

Parameters:

NameTypeDescription
sourceBlockThe source Block being replaced
targetBlockThe target Block to replace with
strictboolIf True, require exact type matches

Returns:

bool — Tuple of (is_compatible, error_message). str | None — If compatible, error_message is None.


create_substitution_pass [source]

def create_substitution_pass(
    block_replacements: dict[str, 'Block | QKernel'] | None = None,
    *,
    strategy_overrides: dict[str, str] | None = None,
    validate_signatures: bool = True,
) -> SubstitutionPass

Convenience factory for creating a SubstitutionPass.

Parameters:

NameTypeDescription
block_replacementsdict[str, 'Block | QKernel'] | NoneMap of block name to replacement
strategy_overridesdict[str, str] | NoneMap of gate name to strategy name
validate_signaturesboolIf True, validate signature compatibility when replacing blocks. Default is True.

Returns:

SubstitutionPass — Configured SubstitutionPass

Example:

pass = create_substitution_pass(
    block_replacements={"my_oracle": optimized_oracle},
    strategy_overrides={"qft": "approximate_k2", "iqft": "approximate_k2"},
)

Classes

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.


BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

CallableDef [source]

class CallableDef

Describe a compiler-facing callable definition.

Parameters:

NameTypeDescription
refCallableRefStable callable identity.
signatureSignature | NoneOptional callable signature.
bodyBlock | NoneStandard IR body, or None for opaque calls.
body_refCallableBodyRef | NoneReference to a standard body that is intentionally deferred. Defaults to None.
implementationslist[CallableImplementation]Alternative native or strategy-specific implementations.
opaque_costAny | NoneExplicit cost contract for a bodyless callable. Body-backed callables must leave this as None.
default_policyCallPolicyDefault call lowering policy.
attrsdict[str, Any]Serializer-friendly definition metadata.
Constructor
def __init__(
    self,
    ref: CallableRef,
    signature: Signature | None = None,
    body: Block | None = None,
    body_ref: CallableBodyRef | None = None,
    implementations: list[CallableImplementation] = list(),
    opaque_cost: Any | None = None,
    default_policy: CallPolicy = CallPolicy.INLINE,
    attrs: dict[str, Any] = dict(),
) -> None
Attributes
Methods
effects_for
def effects_for(self, transform: CallTransform = CallTransform.DIRECT) -> 'KernelEffect'

Return cached semantic effects for one call transform.

Parameters:

NameTypeDescription
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.

Returns:

'KernelEffect' — Union of relevant implementation-body effects.

implementation_for
def implementation_for(
    self,
    *,
    transform: CallTransform = CallTransform.DIRECT,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the best matching implementation candidate.

Parameters:

NameTypeDescription
transformCallTransformRequested call transform.
enginestr | NoneRequested engine name.
strategystr | NoneRequested strategy name.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation, if any.

measurement_result_indices_for
def measurement_result_indices_for(self, transform: CallTransform = CallTransform.DIRECT) -> frozenset[int]

Return measured result positions for one call transform.

Parameters:

NameTypeDescription
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.

Returns:

frozenset[int] — frozenset[int]: Result indices carrying measurement provenance.


CallableRef [source]

class CallableRef

Identify a callable independently of its Python object.

Parameters:

NameTypeDescription
namespacestrStable namespace such as "qamomile.stdlib" or "user".
namestrStable callable name within the namespace.
versionstrSchema or behavior version for the callable.
Constructor
def __init__(self, namespace: str, name: str, version: str = '1') -> None
Attributes

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.
Constructor
def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes
Methods
body_for_transform
def body_for_transform(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> tuple[Block | None, CallTransform]

Select a body and report the transform it already realizes.

A controlled-inverse invocation may reuse an explicitly registered inverse body when no implementation realizes both transforms. Keeping that fallback in the IR operation gives emitters and static analyses one selection rule while still letting each consumer apply the remaining coherent controls in its own representation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — tuple[Block | None, CallTransform]: Selected body and the transform CallTransform — already implemented by that body. The callable’s direct body is tuple[Block | None, CallTransform] — returned with DIRECT when no transform-specific body matches.

Raises:

effective_body
def effective_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — Block | None: Selected implementation body, or the callable’s Block | None — default body when no transform-specific implementation exists. Block | None — A compiler may synthesize inverse or controlled behavior from this Block | None — fallback body.

implementation_for
def implementation_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None, which only selects engine-generic implementations.
strategystr | NoneStrategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation candidate, CallableImplementation | None — or None when the callable definition has no match.

measurement_result_indices_for
def measurement_result_indices_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> frozenset[int]

Return measurement-derived results for one selected implementation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name used for implementation selection. Defaults to None.
strategystr | NoneStrategy name used for implementation selection. Defaults to the invocation’s strategy_name.

Returns:

frozenset[int] — frozenset[int]: Caller-local result positions derived from measurement in the selected body.

Raises:

select_body
def select_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> CallableBodySelection

Select and validate the composable body for this invocation.

The result carries the transform already realized by the body and the exact call-site values that bind to it. Consumers therefore cannot independently disagree about whether an invocation’s control prefix belongs to the selected implementation ABI.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

CallableBodySelection — Validated body, realized transform, and CallableBodySelection — aligned call-site operands and results.

Raises:


Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


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

SelectOperation [source]

class SelectOperation(Operation)

Quantum multiplexer: apply case_blocks[i] when the index reads i.

Concrete operand layout: [idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...]. Symbolic-width operand layout: [idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...]. Results mirror the quantum operand grouping.

A concrete index register is normalized to one scalar Qubit operand per physical index qubit. A symbolic-width register instead retains each leading caller argument as one scalar or array operand until its bound shape is known. Whole-Vector[Qubit] / scalar targets follow and keep their shapes, and classical parameters shared across every case come last.

Index bit order is LSB-first: idx_0 is the least-significant bit, matching Qamomile’s qubit-zero convention. Case i is selected when index qubit j reads bit j of i. len(case_blocks) need not be a power of two; index values >= len(case_blocks) apply no operation (identity).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_index_qubits: int | Value = 0,
    case_blocks: list[Block] = list(),
    num_index_args: int = 0,
    case_callable_attrs: list[dict[str, Any]] = list(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Return every value consumed by the SELECT operation.

Returns:

list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width value when present.

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed replacement values.

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


SignatureCompatibilityError [source]

class SignatureCompatibilityError(Exception)

Error raised when signatures are incompatible during substitution.


SubstitutionConfig [source]

class SubstitutionConfig

Configuration for the substitution pass.

Constructor
def __init__(self, rules: list[SubstitutionRule] = list()) -> None
Attributes
Methods
get_rule_for_name
def get_rule_for_name(self, name: str) -> SubstitutionRule | None

Find a rule matching the given name.

Parameters:

NameTypeDescription
namestrName to look up

Returns:

SubstitutionRule | None — Matching SubstitutionRule or None


SubstitutionPass [source]

class SubstitutionPass(Pass[Block, Block])

Pass that substitutes call operations and callable strategies.

This pass traverses the block and applies substitution rules:

The pass preserves the block structure and only modifies matching operations.

Input: Block (any kind) Output: Block with substitutions applied (same kind as input)

Constructor
def __init__(self, config: SubstitutionConfig) -> None

Initialize the pass with configuration.

Parameters:

NameTypeDescription
configSubstitutionConfigSubstitution configuration with rules
Attributes
Methods
run
def run(self, input: Block) -> Block

Apply substitutions to the block.

Parameters:

NameTypeDescription
inputBlockBlock to transform

Returns:

Block — Block with substitutions applied


SubstitutionRule [source]

class SubstitutionRule

A single substitution rule.

Constructor
def __init__(
    self,
    source_name: str,
    target: 'Block | QKernel | None' = None,
    strategy: str | None = None,
    validate_signature: bool = True,
) -> None
Attributes

ValidationError [source]

class ValidationError(QamomileCompileError)

Error during validation (e.g., non-classical I/O).

Constructor
def __init__(self, message: str, value_name: str | None = None)

Initialize a validation diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable validation failure.
value_namestr | NoneRelated IR value name. Defaults to None.
Attributes

qamomile.circuit.transpiler.passes.symbolic_shape_validation

Reject unresolved values that determine compile-time circuit structure.

Qamomile circuits are fixed-structure at compile time: loop bounds determine how many gates are emitted, and SELECT index widths determine reusable-call arity, while controlled-unitary widths, powers, and selected control indices determine coherent-control structure. These values must be resolvable before emit. This pass catches two failure families early — right before segmentation — with an actionable diagnostic, instead of letting them surface downstream as inconsistent errors:

  1. Unresolved parameter shape dims (e.g. gamma_dim0): a loop bound reads a parameter array’s length, but no concrete binding was provided so ParameterShapeResolutionPass could not fold it.

  2. Runtime-parameter-dependent bounds (e.g. qmc.range(n) with parameters=["n"]): the bound depends — directly or through a chain of classical arithmetic — on a kernel argument left as a runtime parameter. Runtime parameters are bound per execution, after the circuit structure is frozen, so such a loop can never be unrolled. Without this check the failure surfaces inconsistently downstream: as an emit-time ValueError (“Cannot unroll loop”) when the bound is the parameter itself, or as a misleading MultipleQuantumSegmentsError blaming measurement-dependent control flow when a bound expression strands its classical op between quantum ops at segmentation.

The same early diagnostic applies to symbolic controlled-unitary structure (num_controls, power, and control_indices) and to loops stored in operation-owned SELECT/control blocks.

Bounds that depend only on enclosing loop variables (e.g. a nested qmc.range(i + 1) inside qmc.range(p)) are resolvable during emit-time unrolling and are left alone, as are measurement-derived values (handled by the runtime control-flow machinery).

The library QAOA pattern (p bound to an int, for layer in qmc.range(p), gammas kept as runtime parameters for gate angles) is unaffected — compile-time-bound counters are folded to constants by partial_eval before this pass runs.

Overview

FunctionDescription
pair_block_operandsPair all block inputs with category-grouped call-site operands.
reachable_nested_regionsReturn nested regions that may execute for one control-flow operation.
same_exact_typed_constantReturn whether two scalar Values carry the same exact typed constant.
static_loop_trip_countResolve the exact trip count of a compile-time loop.
ClassDescription
ArrayValueAn array of typed IR values.
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
ControlFlowVisitorBase class for visiting operations with control flow handling.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
HasNestedOpsMixin for operations that contain nested operation lists.
IfOperationRepresents an if-else conditional operation.
OperationKindClassification of operations for classical/quantum separation.
PassBase class for all compiler passes.
QamomileCompileErrorBase class for all Qamomile compilation errors.
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
SymbolicShapeValidationPassReject unresolvable values that determine emitted circuit structure.
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.
WhileOperationRepresents a while loop operation.

Functions

pair_block_operands [source]

def pair_block_operands(
    block: Block,
    operands: Sequence[ValueBase],
) -> list[tuple[ValueBase, ValueBase]]

Pair all block inputs with category-grouped call-site operands.

Parameters:

NameTypeDescription
blockBlockOperation-owned block whose inputs are being bound.
operandsSequence[ValueBase]Call-site operands after any controls that are external to block have been removed.

Returns:

list[tuple[ValueBase, ValueBase]] — list[tuple[ValueBase, ValueBase]]: Formal/actual pairs in the block’s list[tuple[ValueBase, ValueBase]] — declaration order.


reachable_nested_regions [source]

def reachable_nested_regions(operation: HasNestedOps) -> tuple[Region, ...]

Return nested regions that may execute for one control-flow operation.

Constant conditionals expose only their selected branch. Statically empty counted and items loops expose no body region. All unresolved control flow remains conservative and exposes every region.

Parameters:

NameTypeDescription
operationHasNestedOpsStructured-control operation to inspect.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Regions that are reachable under compile-time-known control decisions.


same_exact_typed_constant [source]

def same_exact_typed_constant(left: Value, right: Value) -> bool

Return whether two scalar Values carry the same exact typed constant.

Equality requires matching IR and Python types. Floating-point comparison preserves the sign of zero and the payload bits of NaNs.

Parameters:

NameTypeDescription
leftValueFirst scalar value to compare.
rightValueSecond scalar value to compare.

Returns:

bool — True only for constants of the same IR type and Python type with equal value representations.


static_loop_trip_count [source]

def static_loop_trip_count(operation: ForOperation | ForItemsOperation) -> int | None

Resolve the exact trip count of a compile-time loop.

Parameters:

NameTypeDescription
operationForOperation | ForItemsOperationCounted or items loop whose cardinality should be inspected.

Returns:

int | None — int | None: Exact non-negative trip count, or None when the loop cardinality is unresolved.

Classes

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:

bool — True 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.


BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

ControlFlowVisitor [source]

class ControlFlowVisitor(ABC)

Base class for visiting operations with control flow handling.

Subclasses override visit_operation to define per-operation behavior. Control flow recursion is handled automatically by the base class.

Example:

class MeasurementCounter(ControlFlowVisitor):
    def __init__(self):
        self.count = 0

    def visit_operation(self, op: Operation) -> None:
        if isinstance(op, MeasureOperation):
            self.count += 1
Methods
visit_operation
def visit_operation(self, op: Operation) -> None

Process a single operation. Override in subclasses.

visit_operations
def visit_operations(self, operations: list[Operation]) -> None

Visit all operations including nested control flow.


ForItemsOperation [source]

class ForItemsOperation(HasNestedOps, Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    key_var_values: tuple[Value, ...] | None = None,
    value_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include the per-key/value Value fields for cloning/substitution.

Same rationale as ForOperation.all_input_values: keep the IR identity fields in lockstep with body references so UUID-keyed lookups stay valid after inline cloning. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the items-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing key/value formals, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the items-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt items-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


OperationKind [source]

class OperationKind(enum.Enum)

Classification of operations for classical/quantum separation.

This enum is used to categorize operations during compilation to determine which parts run on classical hardware vs quantum hardware.

Values:

QUANTUM: Pure quantum operations (gates, qubit allocation) CLASSICAL: Pure classical operations (arithmetic, comparisons) HYBRID: Operations that bridge classical and quantum (measurement, encode/decode) CONTROL: Control flow structures (for, while, if)

Attributes

Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


QamomileCompileError [source]

class QamomileCompileError(Exception)

Base class for all Qamomile compilation errors.


SelectOperation [source]

class SelectOperation(Operation)

Quantum multiplexer: apply case_blocks[i] when the index reads i.

Concrete operand layout: [idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...]. Symbolic-width operand layout: [idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...]. Results mirror the quantum operand grouping.

A concrete index register is normalized to one scalar Qubit operand per physical index qubit. A symbolic-width register instead retains each leading caller argument as one scalar or array operand until its bound shape is known. Whole-Vector[Qubit] / scalar targets follow and keep their shapes, and classical parameters shared across every case come last.

Index bit order is LSB-first: idx_0 is the least-significant bit, matching Qamomile’s qubit-zero convention. Case i is selected when index qubit j reads bit j of i. len(case_blocks) need not be a power of two; index values >= len(case_blocks) apply no operation (identity).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_index_qubits: int | Value = 0,
    case_blocks: list[Block] = list(),
    num_index_args: int = 0,
    case_callable_attrs: list[dict[str, Any]] = list(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Return every value consumed by the SELECT operation.

Returns:

list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width value when present.

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed replacement values.

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


SymbolicShapeValidationPass [source]

class SymbolicShapeValidationPass(Pass[Block, Block])

Reject unresolvable values that determine emitted circuit structure.

Runs two checks on every ForOperation bound, symbolic SELECT index width, and symbolic controlled-unitary structural field, walking nested control flow and operation-owned SELECT/control blocks recursively:

  1. Unresolved parameter array shape dims, recognized by the {array}_dim{i} naming convention.

  2. Bounds whose dataflow traces back to a runtime parameter (an entry of Block.parameters), directly or through classical arithmetic. Dependencies on enclosing loop variables are exempt — those resolve during emit-time unrolling.

Input: BlockKind.ANALYZED (runs after AnalyzePass). Output: same block unchanged, or raises QamomileCompileError.

Attributes
Methods
run
def run(self, input: Block) -> Block

Validate compile-time structure throughout the analyzed block.

Checks loop bounds, SELECT widths, and controlled-unitary structural fields at top level, in ordinary control-flow bodies, and in operation-owned SELECT/control blocks.

Parameters:

NameTypeDescription
inputBlockThe block to validate. Must be BlockKind.ANALYZED; other kinds pass through unchanged (the pass is defensive and avoids false positives on partially-built IR).

Returns:

Block — input, unchanged, when validation succeeds.

Raises:


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


WhileOperation [source]

class WhileOperation(HasNestedOps, Operation)

Represents a while loop operation.

Only measurement-backed conditions are supported: the condition must be a Bit value produced by qmc.measure(). Non-measurement conditions (classical variables, constants, comparisons) are rejected by ValidateWhileContractPass before reaching engine emit.

Example::

bit = qmc.measure(q)
while bit:
    q = qmc.h(q)
    bit = qmc.measure(q)
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    operations: list[Operation] = list(),
    max_iterations: int | None = None,
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include rebind records and region args for cloning/substitution.

Same rationale as ForOperation.all_input_values: rebind records and region arguments reference body/pre-loop values by identity, so inline cloning must remap them in lockstep with body operands.

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus rebind-record and region-argument values.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the while body with explicit boundary values.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region whose block arguments and yields are aligned with region_args. The updated condition, when present, is appended as the final yield.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the while body and its complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt while operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, rebind-record, and region-arg values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


qamomile.circuit.transpiler.passes.validate_while

WhileOperation contract validation pass.

Validates that all WhileOperation conditions are measurement-backed Bit values. A condition is measurement-backed if it originates from qmc.measure() either directly or through merged branches where every leaf is itself measurement-backed (e.g. if sel: bit = measure(q1) else: bit = measure(q2)).

All other while patterns (classical variables, constants, comparison results, non-measurement branch leaves) are rejected with a clear ValidationError before reaching engine-specific emit passes.

This pass runs after lower_compile_time_ifs and before analyze.

Overview

FunctionDescription
build_producer_mapWalk operations recursively, mapping result UUIDs to producer instances.
is_measurement_backedRecursively check whether a value traces back to measurement operations.
resolve_root_array_indexFold a view-local element index into the root array’s index space.
ClassDescription
ArrayValueAn array of typed IR values.
BitTypeType representing a classical bit.
BlockUnified block representation for all pipeline stages.
HasNestedOpsMixin for operations that contain nested operation lists.
IfOperationRepresents an if-else conditional operation.
MeasureOperation
MeasureVectorOperationMeasure a vector of qubits.
PassBase class for all compiler passes.
ProjectOperationProject a qubit in one Pauli basis and keep the projected state.
RuntimeClassicalExprA classical expression known to require runtime evaluation.
RuntimeOpKindUnified kind for RuntimeClassicalExpr covering all classical
StoreArrayElementOperationStore a classical scalar into one element of a classical array.
ValidateWhileContractPassValidates that all WhileOperation conditions are measurement-backed.
ValidationErrorError during validation (e.g., non-classical I/O).
ValueA typed SSA value in the IR.
WhileOperationRepresents a while loop operation.

Functions

build_producer_map [source]

def build_producer_map(operations: list[Operation], producer_map: dict[str, Operation]) -> None

Walk operations recursively, mapping result UUIDs to producer instances.

Exposed at module scope so measurement-backing checks outside this pass (e.g. the loop-carried rebind check in analyze) can build the same map.

Parameters:

NameTypeDescription
operationslist[Operation]Operations to walk, recursing into all HasNestedOps bodies. IfOperation merge outputs are on results, so they map to the IfOperation itself.
producer_mapdict[str, Operation]Mutable map from result UUID to the producing operation; updated in place.

is_measurement_backed [source]

def is_measurement_backed(
    value: Value,
    producer_map: dict[str, Operation],
    visiting: set[str] | None = None,
) -> bool

Recursively check whether a value traces back to measurement operations.

Returns True if the value is produced by MeasureOperation / MeasureVectorOperation directly, if it is an element access of a measured Vector[Bit] (its parent_array — possibly through a slice_of view chain — is measurement-backed), or if it is an IfOperation merge output where every reachable leaf source is itself measurement-backed.

Uses backtracking on visiting so that the same value can be reached from multiple independent merge branches without false negatives.

Parameters:

NameTypeDescription
valueValueThe IR value to trace.
producer_mapdict[str, Operation]Map from result UUID to the operation that produced it.
visitingset[str] | NoneUUIDs on the current DFS path, used to break cycles. Defaults to None (fresh traversal).

Returns:

bool — True if the value is measurement-backed.


resolve_root_array_index [source]

def resolve_root_array_index(array: 'ArrayValue', index: int) -> tuple['ArrayValue', int] | None

Fold a view-local element index into the root array’s index space.

Walks the slice_of chain root-ward, composing each strided view’s affine map parent_index = start + step * local_index. This is the array-level counterpart of :func:resolve_root_qubit_address (which starts from an array-element Value); both must stay consistent with the composite carrier keys "<root_uuid>_<root_index>" registered by QInitOperation at emit time.

Parameters:

NameTypeDescription
arrayArrayValueArray the index is local to. May be a root array (slice_of unset) or an arbitrarily nested strided view.
indexintElement index in array’s own index space.

Returns:

tuple['ArrayValue', int] | None — tuple[ArrayValue, int] | None: (root_array, composed_index) when every slice bound on the chain is compile-time constant and satisfies the frontend contract (non-negative slice_start, positive slice_step). None when any slice_start / slice_step on the chain is missing, symbolic, or violates that contract; callers must then defer resolution rather than guess. Out-of-contract bounds would compose index onto a wrong root slot, so they are refused here too (the frontend rejects them at trace time; this guard covers programmatically constructed IR).

Classes

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:

bool — True iff slice_of is non-None.

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

BitType [source]

class BitType(ClassicalTypeMixin, ValueType)

Type representing a classical bit.


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.


HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


MeasureOperation [source]

class MeasureOperation(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

MeasureVectorOperation [source]

class MeasureVectorOperation(Operation)

Measure a vector of qubits.

Takes a Vector[Qubit] (ArrayValue) and produces a Vector[Bit] (ArrayValue). This operation measures all qubits in the vector as a single operation.

operands: [ArrayValue of qubits] results: [ArrayValue of bits]

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

Pass [source]

class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


ProjectOperation [source]

class ProjectOperation(Operation)

Project a qubit in one Pauli basis and keep the projected state.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    axis: str = 'z',
) -> None
Attributes

RuntimeClassicalExpr [source]

class RuntimeClassicalExpr(Operation)

A classical expression known to require runtime evaluation.

Lowered from CompOp / CondOp / NotOp / BinOp by ClassicalLoweringPass when the op’s operand dataflow traces back to a MeasureOperation (i.e. cannot be folded at compile-time, by emit-time loop unrolling, or by compile_time_if_lowering). Engine emit translates this 1:1 to an engine-native runtime expression (e.g. qiskit.circuit.classical.expr.Expr).

Operand convention:

The single-node + unified-kind shape (vs four parallel subclasses) keeps the engine dispatch a single match op.kind instead of four parallel hooks, and makes the IR self-documenting: a single RuntimeClassicalExpr instance signals “runtime evaluation required” regardless of which classical family it came from.

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    kind: RuntimeOpKind | None = None,
) -> None
Attributes

RuntimeOpKind [source]

class RuntimeOpKind(enum.Enum)

Unified kind for RuntimeClassicalExpr covering all classical op families that can appear at runtime.

The split between this enum and the per-family BinOpKind / CompOpKind / CondOpKind is intentional: compile-time-foldable classical ops keep their original IR types so the existing fold pipeline (constant_fold → compile_time_if_lowering → emit-time evaluate_classical_predicate) is undisturbed. Only ops identified as runtime-evaluation-only by ClassicalLoweringPass get rewritten to RuntimeClassicalExpr with a member of this enum.

Attributes

StoreArrayElementOperation [source]

class StoreArrayElementOperation(Operation)

Store a classical scalar into one element of a classical array.

This is the IR form of array[index] = value for classical element types (Bit / UInt / Float). Classical values are freely copyable, so the store is an ordinary SSA rewrite: the operation consumes the current array version and produces a new ArrayValue version (same logical_id, fresh uuid) whose contents equal the input array with the addressed element replaced. Quantum arrays never use this operation — qubit element assignment is the return half of the borrow-return idiom and emits no IR.

The operation is evaluated in one of two places:

Operand convention:

operands: [array (ArrayValue), stored_value (Value), *index_values] results: [new_array (ArrayValue)]

Example:

@qmc.qkernel
def k() -> qmc.Vector[qmc.Bit]:
    qs = qmc.qubit_array(2, "qs")
    qs[0] = qmc.x(qs[0])
    bits = qmc.measure(qs)
    bits[1] = bits[0]   # emits StoreArrayElementOperation
    return bits
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ValidateWhileContractPass [source]

class ValidateWhileContractPass(Pass[Block, Block])

Validates that all WhileOperation conditions are measurement-backed.

Builds a producer map (result UUID → producing Operation instance) and checks every WhileOperation operand against it. A valid condition must be:

  1. A Value with BitType

  2. Measurement-backed: produced by MeasureOperation directly, or an IfOperation merge output where every reachable leaf source is itself measurement-backed.

Both operands[0] (initial condition) and operands[1] (loop-carried condition) are validated.

Raises ValidationError for any non-measurement while pattern.

Attributes
Methods
run
def run(self, block: Block) -> Block

Validate all WhileOperations and return block unchanged.


ValidationError [source]

class ValidationError(QamomileCompileError)

Error during validation (e.g., non-classical I/O).

Constructor
def __init__(self, message: str, value_name: str | None = None)

Initialize a validation diagnosis.

Parameters:

NameTypeDescription
messagestrHuman-readable validation failure.
value_namestr | NoneRelated IR value name. Defaults to None.
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 engine resource allocation. This applies to every Value regardless of its type (Qubit, Float, Bit, ...) -- it is not specific to qubits.


WhileOperation [source]

class WhileOperation(HasNestedOps, Operation)

Represents a while loop operation.

Only measurement-backed conditions are supported: the condition must be a Bit value produced by qmc.measure(). Non-measurement conditions (classical variables, constants, comparisons) are rejected by ValidateWhileContractPass before reaching engine emit.

Example::

bit = qmc.measure(q)
while bit:
    q = qmc.h(q)
    bit = qmc.measure(q)
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    operations: list[Operation] = list(),
    max_iterations: int | None = None,
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include rebind records and region args for cloning/substitution.

Same rationale as ForOperation.all_input_values: rebind records and region arguments reference body/pre-loop values by identity, so inline cloning must remap them in lockstep with body operands.

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus rebind-record and region-argument values.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the while body with explicit boundary values.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region whose block arguments and yields are aligned with region_args. The updated condition, when present, is appended as the final yield.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the while body and its complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt while operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, rebind-record, and region-arg values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


qamomile.circuit.transpiler.passes.value_mapping

Compatibility exports for shared IR value-mapping utilities.

Overview

ClassDescription
UUIDRemapperClones values and operations with fresh UUIDs and logical_ids.
ValueSubstitutorSubstitute IR values in operations using a UUID-keyed mapping.

Classes

UUIDRemapper [source]

class UUIDRemapper

Clones values and operations with fresh UUIDs and logical_ids.

Used during inlining to create unique identities for values when a block is called multiple times.

Constructor
def __init__(self)

Initialize empty identity, value, and block remapping caches.

Attributes
Methods
clone_block
def clone_block(self, block: Block) -> Block

Clone an executable block namespace with fresh value identities.

Callable definitions and inverse source blocks are semantic provenance shared with the original graph. Transform implementations, controlled bodies, and SELECT cases are executable children and are cloned recursively.

Parameters:

NameTypeDescription
blockBlockBlock whose interface, operations, and executable owned blocks should be cloned.

Returns:

Block — Structurally equivalent block whose values have fresh UUIDs and logical IDs.

Raises:

clone_operation
def clone_operation(self, op: Operation) -> Operation

Clone an operation with fresh UUIDs for all values.

Cloning goes through the Operation.all_input_values() / Operation.replace_values() protocol so every Value-typed field — including subclass extras (ControlledUOperation.power, ForOperation.loop_var_value, ForItemsOperation.key_var_values etc.) — is cloned consistently with the body references that point to it. Without this, a subclass field could keep an old UUID while body operands referencing the same logical Value got fresh UUIDs, breaking identity-by-UUID lookups at emit time.

Parameters:

NameTypeDescription
opOperationOperation to clone.

Returns:

Operation — A clone of op with every owned Value (operands, results, subclass-extra fields) and every nested-body Value reassigned a fresh UUID / logical_id, and with CastOperation.qubit_mapping carrier keys remapped.

clone_operations
def clone_operations(self, operations: list[Operation]) -> list[Operation]

Clone a list of operations with fresh UUIDs.

Parameters:

NameTypeDescription
operationslist[Operation]Operations to clone in order.

Returns:

list[Operation] — list[Operation]: Cloned operations, each with fresh UUIDs, in the same order as operations.

clone_value
def clone_value(self, value: ValueBase) -> ValueBase

Clone any value type with a fresh UUID and logical_id.

Handles Value, ArrayValue, TupleValue, and DictValue through the unified ValueBase protocol. Nested values (tuple elements, dict entries, parent_array / element_indices / shape / slice fields) and embedded metadata references are cloned consistently. Results are cached by source UUID so a repeated clone returns the same instance.

Parameters:

NameTypeDescription
valueValueBaseThe value to clone.

Returns:

ValueBase — The cloned value of the same concrete type, with a fresh UUID / logical_id and its nested values and metadata references remapped through this remapper.


ValueSubstitutor [source]

class ValueSubstitutor

Substitute IR values in operations using a UUID-keyed mapping.

Parameters:

NameTypeDescription
value_mapMapping[str, ValueBase]Mapping from original value UUIDs to replacement values.
transitiveboolWhether substitutions should chase chains such as A -> B -> C to the terminal value. Defaults to False.
Constructor
def __init__(self, value_map: Mapping[str, ValueBase], transitive: bool = False)

Initialize the substitutor.

Parameters:

NameTypeDescription
value_mapMapping[str, ValueBase]Mapping from original value UUIDs to replacement values.
transitiveboolWhether substitutions should chase chains to their terminal value. Defaults to False.
Methods
substitute_operation
def substitute_operation(self, op: Operation) -> Operation

Substitute values in an operation.

Parameters:

NameTypeDescription
opOperationOperation whose operands, results, and subclass-specific value fields should be substituted.

Returns:

Operation — Operation with all mapped value references replaced.

substitute_value
def substitute_value(self, value: ValueBase) -> ValueBase

Substitute a single value.

Parameters:

NameTypeDescription
valueValueBaseValue to replace or rebuild.

Returns:

ValueBase — Replacement value, rebuilt value with substituted ValueBase — metadata, or the original value when nothing maps.


qamomile.circuit.transpiler.prepared

Program-level semantic input for target-specific compilation pipelines.

Overview

FunctionDescription
prepare_moduleCollect a hierarchical block into an immutable program-level view.
ClassDescription
BlockUnified block representation for all pipeline stages.
CallableDefDescribe a compiler-facing callable definition.
CallableRefIdentify a callable independently of its Python object.
HasNestedOpsMixin for operations that contain nested operation lists.
InvokeOperationRepresent a composite, stdlib, or oracle call.
PreparedModuleHold a prepared entrypoint and its reachable callable definitions.
ProgramABIRuntime-visible ABI for a segmented program.
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.

Functions

prepare_module [source]

def prepare_module(entrypoint: Block, bindings: Mapping[str, Any] | None = None) -> PreparedModule

Collect a hierarchical block into an immutable program-level view.

The collector follows calls in nested control-flow regions, SELECT case Blocks, and every body carried by a callable definition. Definitions remain Qamomile semantic IR; this function does not inline, clone, or lower operations.

Parameters:

NameTypeDescription
entrypointBlockHierarchical entrypoint after target-independent frontend preparation.
bindingsMapping[str, Any] | NoneCompile-time values that cannot be embedded in scalar value metadata, such as Hamiltonians. Defaults to None.

Returns:

PreparedModule — Entrypoint, reachable definitions, call graph, and public ABI. :class:QamomileCompiler creates a deep target-owned snapshot before invoking a target pipeline.

Classes

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.


CallableDef [source]

class CallableDef

Describe a compiler-facing callable definition.

Parameters:

NameTypeDescription
refCallableRefStable callable identity.
signatureSignature | NoneOptional callable signature.
bodyBlock | NoneStandard IR body, or None for opaque calls.
body_refCallableBodyRef | NoneReference to a standard body that is intentionally deferred. Defaults to None.
implementationslist[CallableImplementation]Alternative native or strategy-specific implementations.
opaque_costAny | NoneExplicit cost contract for a bodyless callable. Body-backed callables must leave this as None.
default_policyCallPolicyDefault call lowering policy.
attrsdict[str, Any]Serializer-friendly definition metadata.
Constructor
def __init__(
    self,
    ref: CallableRef,
    signature: Signature | None = None,
    body: Block | None = None,
    body_ref: CallableBodyRef | None = None,
    implementations: list[CallableImplementation] = list(),
    opaque_cost: Any | None = None,
    default_policy: CallPolicy = CallPolicy.INLINE,
    attrs: dict[str, Any] = dict(),
) -> None
Attributes
Methods
effects_for
def effects_for(self, transform: CallTransform = CallTransform.DIRECT) -> 'KernelEffect'

Return cached semantic effects for one call transform.

Parameters:

NameTypeDescription
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.

Returns:

'KernelEffect' — Union of relevant implementation-body effects.

implementation_for
def implementation_for(
    self,
    *,
    transform: CallTransform = CallTransform.DIRECT,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the best matching implementation candidate.

Parameters:

NameTypeDescription
transformCallTransformRequested call transform.
enginestr | NoneRequested engine name.
strategystr | NoneRequested strategy name.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation, if any.

measurement_result_indices_for
def measurement_result_indices_for(self, transform: CallTransform = CallTransform.DIRECT) -> frozenset[int]

Return measured result positions for one call transform.

Parameters:

NameTypeDescription
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.

Returns:

frozenset[int] — frozenset[int]: Result indices carrying measurement provenance.


CallableRef [source]

class CallableRef

Identify a callable independently of its Python object.

Parameters:

NameTypeDescription
namespacestrStable namespace such as "qamomile.stdlib" or "user".
namestrStable callable name within the namespace.
versionstrSchema or behavior version for the callable.
Constructor
def __init__(self, namespace: str, name: str, version: str = '1') -> None
Attributes

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods
nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.
Constructor
def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes
Methods
body_for_transform
def body_for_transform(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> tuple[Block | None, CallTransform]

Select a body and report the transform it already realizes.

A controlled-inverse invocation may reuse an explicitly registered inverse body when no implementation realizes both transforms. Keeping that fallback in the IR operation gives emitters and static analyses one selection rule while still letting each consumer apply the remaining coherent controls in its own representation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — tuple[Block | None, CallTransform]: Selected body and the transform CallTransform — already implemented by that body. The callable’s direct body is tuple[Block | None, CallTransform] — returned with DIRECT when no transform-specific body matches.

Raises:

effective_body
def effective_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — Block | None: Selected implementation body, or the callable’s Block | None — default body when no transform-specific implementation exists. Block | None — A compiler may synthesize inverse or controlled behavior from this Block | None — fallback body.

implementation_for
def implementation_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None, which only selects engine-generic implementations.
strategystr | NoneStrategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation candidate, CallableImplementation | None — or None when the callable definition has no match.

measurement_result_indices_for
def measurement_result_indices_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> frozenset[int]

Return measurement-derived results for one selected implementation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name used for implementation selection. Defaults to None.
strategystr | NoneStrategy name used for implementation selection. Defaults to the invocation’s strategy_name.

Returns:

frozenset[int] — frozenset[int]: Caller-local result positions derived from measurement in the selected body.

Raises:

select_body
def select_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> CallableBodySelection

Select and validate the composable body for this invocation.

The result carries the transform already realized by the body and the exact call-site values that bind to it. Consumers therefore cannot independently disagree about whether an invocation’s control prefix belongs to the selected implementation ABI.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

CallableBodySelection — Validated body, realized transform, and CallableBodySelection — aligned call-site operands and results.

Raises:


PreparedModule [source]

class PreparedModule

Hold a prepared entrypoint and its reachable callable definitions.

Parameters:

NameTypeDescription
entrypoint_refCallableRefStable symbol assigned to the program entrypoint.
entrypointBlockHierarchical semantic block for the entrypoint.
definitionsMapping[CallableRef, CallableDef]Reachable callable definitions keyed by their stable symbols.
definition_variantsMapping[CallableRef, tuple[CallableDef, ...]]Every distinct body observed for a symbol. Multiple variants of one origin may be valid for circuit-family inlining but must be handled or rejected by targets that emit one function per symbol.
call_graphMapping[CallableRef, frozenset[CallableRef]]Directed caller-to-callee relation, including the entrypoint symbol.
abiProgramABIClassical public input and output contract.
bindingsMapping[str, Any]Compile-time values retained for direct program-graph targets. Circuit-family targets receive the same values through their emit pass.
Constructor
def __init__(
    self,
    entrypoint_ref: CallableRef,
    entrypoint: Block,
    definitions: Mapping[CallableRef, CallableDef],
    definition_variants: Mapping[CallableRef, tuple[CallableDef, ...]],
    call_graph: Mapping[CallableRef, frozenset[CallableRef]],
    abi: ProgramABI,
    bindings: Mapping[str, Any],
) -> None
Attributes
Methods
body
def body(self, ref: CallableRef) -> Block

Return the semantic body associated with a program symbol.

Parameters:

NameTypeDescription
refCallableRefEntrypoint or callable symbol to resolve.

Returns:

Block — Hierarchical semantic body for ref.

Raises:

owned_snapshot
def owned_snapshot(self) -> PreparedModule

Create a deep, target-owned snapshot of prepared semantics.

The semantic IR intentionally remains mutable while compiler passes are being developed. Copying the entrypoint and definition registry as one object graph preserves shared callable bodies while preventing one target from mutating the source module observed by another.

Returns:

PreparedModule — Deep snapshot with read-only definition and call graph registries.


ProgramABI [source]

class ProgramABI

Runtime-visible ABI for a segmented program.

Constructor
def __init__(
    self,
    public_inputs: dict[str, ValueLike] = dict(),
    output_values: list[ValueLike] = list(),
) -> None
Attributes

SelectOperation [source]

class SelectOperation(Operation)

Quantum multiplexer: apply case_blocks[i] when the index reads i.

Concrete operand layout: [idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...]. Symbolic-width operand layout: [idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...]. Results mirror the quantum operand grouping.

A concrete index register is normalized to one scalar Qubit operand per physical index qubit. A symbolic-width register instead retains each leading caller argument as one scalar or array operand until its bound shape is known. Whole-Vector[Qubit] / scalar targets follow and keep their shapes, and classical parameters shared across every case come last.

Index bit order is LSB-first: idx_0 is the least-significant bit, matching Qamomile’s qubit-zero convention. Case i is selected when index qubit j reads bit j of i. len(case_blocks) need not be a power of two; index values >= len(case_blocks) apply no operation (identity).

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_index_qubits: int | Value = 0,
    case_blocks: list[Block] = list(),
    num_index_args: int = 0,
    case_callable_attrs: list[dict[str, Any]] = list(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Return every value consumed by the SELECT operation.

Returns:

list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width value when present.

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed replacement values.

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


qamomile.circuit.transpiler.program_graph

Public compiler support for direct program-graph targets.

Overview

FunctionDescription
inline_callablesExpand inline-policy callables once with the compiler’s default policy.
reject_control_flow_quantum_discardReject control-flow-internal quantum rebinds that discard state.
validate_program_graph_semanticsValidate shared semantics for a direct program-graph target.
ClassDescription
BlockUnified block representation for all pipeline stages.
CallPolicyDescribe the default lowering policy for a callable call.
InlinePassInline qkernel callables to create an affine block.
InvokeOperationRepresent a composite, stdlib, or oracle call.
PreparedModuleHold a prepared entrypoint and its reachable callable definitions.
ValidateWhileContractPassValidates that all WhileOperation conditions are measurement-backed.

Functions

inline_callables [source]

def inline_callables(
    block: Block,
    *,
    body_selector: Callable[[InvokeOperation], Block | None] | None = None,
) -> Block

Expand inline-policy callables once with the compiler’s default policy.

Boxed calls, transformed calls, and recursive calls that remain after one pass are preserved. Direct program-graph targets use this narrow helper at target legalization boundaries without depending on the configurable compiler pass implementation.

Parameters:

NameTypeDescription
blockBlockHierarchical or traced semantic block to rewrite.
body_selectorCallable[[InvokeOperation], Block | None] | NoneOptional selector returning the body to inline, or None to retain a call boundary. Defaults to the ordinary effective body.

Returns:

Block — Block after one default callable-inlining pass.

Raises:


reject_control_flow_quantum_discard [source]

def reject_control_flow_quantum_discard(operations: list[Operation], bindings: dict[str, Any] | None = None) -> None

Reject control-flow-internal quantum rebinds that discard state.

The decoration-time rebind analyzer intentionally suppresses branch-internal violations (its snapshot-restore scope truncates them) so that compile-time-if branch-selection rebinds stay legal. That leaves a runtime hole: rebinding a quantum variable inside a runtime branch — to a fresh allocation (if cond: q = qmc.qubit("fresh")) or to any other quantum value (if cond: q = other, including in both branches at once) — silently drops the variable’s pre-branch state exactly when a rebinding branch is taken. The frontend records every branch-internal quantum binding change on the IfOperation (BranchRebind, preserving the pre-branch value even when it no longer appears in any merge); this check verifies each record against each runtime execution path and raises QubitRebindError — the same AffineTypeError the decoration-time analyzer raises for a top-level rebind from a different quantum source, since this is that exact affine violation surfacing at runtime inside a branch — when the pre-branch value has no owner on a rebinding path: not consumed inside the taken branch, not carried out through any merge of that side, and not referenced by any operation outside the if. Scalar Qubit and whole-register Vector[Qubit] rebinds are covered alike.

Loop bodies are covered more strictly than branches (see :func:_check_loop_quantum_discards): the frontend records quantum rebinds on ForOperation / ForItemsOperation / WhileOperation (LoopCarriedRebind entries whose before is quantum), and each record is rejected unless it carries the incoming value forward on the same wires, is a covered loop-invariant rebind, or is the terminal fresh-allocation pattern where nested QInitOperation reset/prepare-zero emission gives qmc.qubit() fresh-per-iteration semantics. In-body consumption of the incoming value itself is not an exemption: the read re-executes against the traced register every iteration and matches Python semantics only for the first one. A loop-body rebind needs no runtime/compile-time classification, so loops are checked wherever they appear on a live (non-pruned) path, trip-count-agnostically, exactly like the classical loop-carried check.

IfOperations are classified with the same condition resolution CompileTimeIfLoweringPass uses (via bindings), including for ifs nested inside runtime branches. A rebind confined to a compile-time branch stays legal when the surrounding control flow is compile-time too: rebinding to an alternative register under a compile-time flag is the documented branch-selection idiom, and a dead branch is eliminated entirely. A compile-time-TAKEN rebind nested inside a runtime branch inherits that branch’s runtime conditionality and is checked (and rejected when it discards). Only ifs whose condition transitively derives from a measurement result are checked — the same taint analysis the classical-lowering pipeline uses, so expression-derived runtime conditions (~bit, a & b) are covered; a non-measurement, non-compile-time condition cannot drive runtime branching and is rejected at emit by the shared condition resolution (though for this discard shape the emit-side merge physical-resource check can fire first with its generic message).

What stays allowed:

The check is deliberately conservative toward allowing where it cannot be exact. Merge lineage is over-approximated: producers without a positional qubit model (composite gates, controlled blocks, casts) contribute all of their quantum inputs as possible roots, so the carried exemption can only grow — a rejection requires the pre-branch value to be provably absent from every merge lineage. Outside-ownership evidence is path-sensitive with respect to enclosing ifs (a read on the sibling branch of an enclosing runtime if does not exempt), but path-insensitive for non-ancestor runtime ifs elsewhere: a value conditionally consumed downstream counts as owned. Rebinds inside compile-time-TAKEN ifs nested in a runtime branch are promoted to the enclosing if’s check trip-count- and loop-agnostically; because the lowering pass erases those nested ifs (and their records), the promoted rebinds are only caught by the pre-fold PartialEvaluationPass hook, not by the AnalyzePass safety net.

Scope contract: the scan recurses through control-flow nesting only (IfOperation branches and HasNestedOps bodies). Boxed implementation blocks — InvokeOperation bodies and implementations, InverseBlockOperation.implementation_block, ControlledUOperation.block — are NOT descended into: they stay HIERARCHICAL recipe blocks outside the entrypoint pipeline, exactly like every other transpile-time rebind check (reject_loop_carried_classical_rebinds, AffineValidationPass, both built on the same HasNestedOps walk). A discard written inside a composite’s recipe kernel is therefore only covered by the decoration-time top-level analyzer, with the same branch/loop suppression as everywhere else pre-IR.

Exposed at module scope because it runs from two passes: PartialEvaluationPass calls it before folding and if-lowering (with bindings, so compile-time branches are classified exactly as the lowering pass will lower them), and AnalyzePass calls it again as a safety net for pipelines that skip partial_eval.

Parameters:

NameTypeDescription
operationslist[Operation]Operations to scan. Recurses through all control flow; every runtime if and every loop at any nesting depth on a live path is checked.
bindingsdict[str, Any] | NoneCompile-time parameter bindings used to resolve IfOperation conditions, matching what CompileTimeIfLoweringPass will later resolve. Defaults to None (no bindings).

Raises:


validate_program_graph_semantics [source]

def validate_program_graph_semantics(program: PreparedModule) -> None

Validate shared semantics for a direct program-graph target.

Circuit-family planning runs these checks during partial evaluation, analysis, and segmentation. A direct program-graph target preserves the prepared structure, so this helper runs only the non-destructive semantic checks. Inline-policy callables are expanded in the validation view so their formal values retain call-site provenance; the prepared program itself remains hierarchical.

Parameters:

NameTypeDescription
programPreparedModulePrepared entrypoint and callable bodies.

Raises:

Classes

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.


CallPolicy [source]

class CallPolicy(enum.Enum)

Describe the default lowering policy for a callable call.

Attributes

InlinePass [source]

class InlinePass(Pass[Block, Block])

Inline qkernel callables to create an affine block.

This pass recursively inlines function calls while preserving control flow structures (For, If, While).

Input: Block with BlockKind.HIERARCHICAL (may contain callable calls) Output: Block with BlockKind.AFFINE (no inline callable calls)

Parameters:

NameTypeDescription
body_selectorCallable[[InvokeOperation], Block | None] | NoneOptional body-selection hook for consumers whose configured strategy differs from InvokeOperation.strategy_name. The standard compiler leaves this unset. Defaults to None.
preserve_bound_quantum_identityboolWhether cloned callee quantum values should retain the logical owner and array-element address of their bound caller operands. Resource liveness analysis enables this so an inline call does not create phantom owners or erase lane identities. Defaults to False.
preserve_bound_array_identityboolWhether cloned callee array values should retain the logical lineage of bound caller arrays. Resource classical-state analysis enables this so loop-carried stores remain connected across an inlined call. Defaults to False.
Constructor
def __init__(
    self,
    body_selector: Callable[[InvokeOperation], Block | None] | None = None,
    *,
    inline_prefix_factory: Callable[[InvokeOperation, tuple[tuple[ArrayValue, tuple[ArrayValue, ...]], ...]], Sequence[Operation]] | None = None,
    preserve_bound_quantum_identity: bool = False,
    preserve_bound_array_identity: bool = False,
) -> None

Initialize the pass with body-selection and identity policies.

Parameters:

NameTypeDescription
body_selectorCallable[[InvokeOperation], Block | None] | NoneConsumer-specific selector used for inline-policy calls. Defaults to the invocation’s ordinary effective body.
preserve_bound_quantum_identityboolWhether cloned quantum SSA values descending from a formal input retain the actual caller operand’s logical owner and array-element address. Defaults to False.
preserve_bound_array_identityboolWhether cloned array SSA values descending from a formal input retain the actual caller array’s logical lineage. Defaults to False.
Attributes
Methods
run
def run(self, input: Block) -> Block

Inline all inline-policy callable invocations.

Self-recursive qkernel invocations are unrolled one level per call: the inner self-call is substituted but left intact so the outer fixed-point loop can fold the base-case if between iterations. The output kind is AFFINE when no inlineable calls remain, otherwise HIERARCHICAL.


InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.
Constructor
def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes
Methods
body_for_transform
def body_for_transform(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> tuple[Block | None, CallTransform]

Select a body and report the transform it already realizes.

A controlled-inverse invocation may reuse an explicitly registered inverse body when no implementation realizes both transforms. Keeping that fallback in the IR operation gives emitters and static analyses one selection rule while still letting each consumer apply the remaining coherent controls in its own representation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — tuple[Block | None, CallTransform]: Selected body and the transform CallTransform — already implemented by that body. The callable’s direct body is tuple[Block | None, CallTransform] — returned with DIRECT when no transform-specific body matches.

Raises:

effective_body
def effective_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — Block | None: Selected implementation body, or the callable’s Block | None — default body when no transform-specific implementation exists. Block | None — A compiler may synthesize inverse or controlled behavior from this Block | None — fallback body.

implementation_for
def implementation_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None, which only selects engine-generic implementations.
strategystr | NoneStrategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation candidate, CallableImplementation | None — or None when the callable definition has no match.

measurement_result_indices_for
def measurement_result_indices_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> frozenset[int]

Return measurement-derived results for one selected implementation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name used for implementation selection. Defaults to None.
strategystr | NoneStrategy name used for implementation selection. Defaults to the invocation’s strategy_name.

Returns:

frozenset[int] — frozenset[int]: Caller-local result positions derived from measurement in the selected body.

Raises:

select_body
def select_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> CallableBodySelection

Select and validate the composable body for this invocation.

The result carries the transform already realized by the body and the exact call-site values that bind to it. Consumers therefore cannot independently disagree about whether an invocation’s control prefix belongs to the selected implementation ABI.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

CallableBodySelection — Validated body, realized transform, and CallableBodySelection — aligned call-site operands and results.

Raises:


PreparedModule [source]

class PreparedModule

Hold a prepared entrypoint and its reachable callable definitions.

Parameters:

NameTypeDescription
entrypoint_refCallableRefStable symbol assigned to the program entrypoint.
entrypointBlockHierarchical semantic block for the entrypoint.
definitionsMapping[CallableRef, CallableDef]Reachable callable definitions keyed by their stable symbols.
definition_variantsMapping[CallableRef, tuple[CallableDef, ...]]Every distinct body observed for a symbol. Multiple variants of one origin may be valid for circuit-family inlining but must be handled or rejected by targets that emit one function per symbol.
call_graphMapping[CallableRef, frozenset[CallableRef]]Directed caller-to-callee relation, including the entrypoint symbol.
abiProgramABIClassical public input and output contract.
bindingsMapping[str, Any]Compile-time values retained for direct program-graph targets. Circuit-family targets receive the same values through their emit pass.
Constructor
def __init__(
    self,
    entrypoint_ref: CallableRef,
    entrypoint: Block,
    definitions: Mapping[CallableRef, CallableDef],
    definition_variants: Mapping[CallableRef, tuple[CallableDef, ...]],
    call_graph: Mapping[CallableRef, frozenset[CallableRef]],
    abi: ProgramABI,
    bindings: Mapping[str, Any],
) -> None
Attributes
Methods
body
def body(self, ref: CallableRef) -> Block

Return the semantic body associated with a program symbol.

Parameters:

NameTypeDescription
refCallableRefEntrypoint or callable symbol to resolve.

Returns:

Block — Hierarchical semantic body for ref.

Raises:

owned_snapshot
def owned_snapshot(self) -> PreparedModule

Create a deep, target-owned snapshot of prepared semantics.

The semantic IR intentionally remains mutable while compiler passes are being developed. Copying the entrypoint and definition registry as one object graph preserves shared callable bodies while preventing one target from mutating the source module observed by another.

Returns:

PreparedModule — Deep snapshot with read-only definition and call graph registries.


ValidateWhileContractPass [source]

class ValidateWhileContractPass(Pass[Block, Block])

Validates that all WhileOperation conditions are measurement-backed.

Builds a producer map (result UUID → producing Operation instance) and checks every WhileOperation operand against it. A valid condition must be:

  1. A Value with BitType

  2. Measurement-backed: produced by MeasureOperation directly, or an IfOperation merge output where every reachable leaf source is itself measurement-backed.

Both operands[0] (initial condition) and operands[1] (loop-carried condition) are validated.

Raises ValidationError for any non-measurement while pattern.

Attributes
Methods
run
def run(self, block: Block) -> Block

Validate all WhileOperations and return block unchanged.


qamomile.circuit.transpiler.program_orchestrator

Orchestration logic for compiled quantum-classical programs.

This module is internal. Users interact with ExecutableProgram.sample()/run().

Overview

FunctionDescription
flatten_user_bindingsFlatten public arrays and dictionaries into scalar ABI keys.
resolve_runtime_array_locationResolve local array indices through runtime-bound slice views.
ClassDescription
ArrayValueAn array of typed IR values.
CircuitInvocationKeep an emitted circuit and runtime parameter values together.
ClassicalExecutorExecutes classical segments in Python.
ClassicalStepA classical execution step.
CompiledClassicalSegmentA classical segment ready for Python execution.
CompiledExpvalSegmentA compiled expectation value segment with concrete Hamiltonian.
CompiledQuantumSegmentA quantum segment with emitted engine circuit.
CompositeExecutionHandleAggregate several independently submitted executions.
DictValueA dictionary value stored as stable ordered entries.
EstimateRequestDescribe one Hamiltonian expectation execution.
ExecutableProgramA fully compiled program ready for execution.
ExecutionContextHolds global state during program execution.
ExecutionErrorError during program execution.
ExecutionHandleExpose an engine execution without forcing immediate result retrieval.
ExecutionSnapshotKindIdentify the reconstruction contract of an execution snapshot node.
ExpvalJobJob for expectation value computation.
ExpvalStepAn expectation-value execution step.
JobKindIdentify the public operation needed to reconstruct a typed job.
JobSnapshotStore operation metadata and lossless raw execution reconstruction.
MappedExecutionHandleLazily transform another execution handle’s result.
ParameterMetadataDescribe every scalar slot and runtime array in a compiled segment.
ProgramOrchestratorOrchestrates execution of compiled quantum-classical programs.
QuantumExecutorAbstract base class for quantum backend execution.
QuantumStepA quantum execution step.
RunJobJob for single execution.
SampleJobJob for sampling execution (multiple shots).
SampleRequestDescribe one sampling execution.
TupleValueA tuple of IR values for structured data.
ValueA typed SSA value in the IR.

Constants

Functions

flatten_user_bindings [source]

def flatten_user_bindings(bindings: Mapping[str, Any] | None) -> dict[str, Any]

Flatten public arrays and dictionaries into scalar ABI keys.

Parameters:

NameTypeDescription
bindingsMapping[str, Any] | NoneRaw user bindings keyed by kernel parameter name.

Returns:

dict[str, Any] — dict[str, Any]: Scalar and dictionary entries keyed by emitted ABI names.


resolve_runtime_array_location [source]

def resolve_runtime_array_location(
    array: ArrayValue,
    indices: tuple[int, ...],
    resolve_int: Callable[[Value], int | None],
) -> tuple[ArrayValue, tuple[int, ...]] | None

Resolve local array indices through runtime-bound slice views.

Parameters:

NameTypeDescription
arrayArrayValueArray whose local indices should be resolved. May be a root array or a slice_of view chain.
indicestuple[int, ...]Concrete indices in array’s local coordinate space.
resolve_intCallable[[Value], int | None]Callback used to evaluate slice_start / slice_step values against the current runtime state.

Returns:

tuple[ArrayValue, tuple[int, ...]] | None — tuple[ArrayValue, tuple[int, ...]] | None: The root array and indices in root coordinates, or None when a slice bound is unresolved or violates the frontend slice contract.

Classes

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:

bool — True iff slice_of is non-None.

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

CircuitInvocation [source]

class CircuitInvocation(Generic[CircuitT])

Keep an emitted circuit and runtime parameter values together.

Engines may bind the values into a new circuit or submit them through a native parameter-input API. Keeping both forms available preserves native parameter sweeps and provider-side compilation caches.

Parameters:

NameTypeDescription
circuitCircuitTEmitted engine circuit or kernel artifact.
bindingsMapping[str, Any]Flattened Qamomile runtime bindings.
parameter_metadataParameterMetadataMapping from public parameter names to engine parameter objects.
Constructor
def __init__(
    self,
    circuit: CircuitT,
    bindings: Mapping[str, Any],
    parameter_metadata: ParameterMetadata,
) -> None
Attributes

ClassicalExecutor [source]

class ClassicalExecutor

Executes classical segments in Python.

Methods
execute
def execute(self, segment: ClassicalSegment, context: ExecutionContext) -> dict[str, Any]

Execute classical operations and return outputs.

Interprets the operations list directly using Python.

Parameters:

NameTypeDescription
segmentClassicalSegmentOrdered classical operations and declared outputs to evaluate.
contextExecutionContextPer-shot quantum and bound input values available to the segment.

Returns:

dict[str, Any] — dict[str, Any]: Computed classical values keyed by result UUID.

Raises:

resolve_value
def resolve_value(self, value: ValueLike, context: ExecutionContext) -> Any

Resolve a typed classical output using the execution interpreter.

Parameters:

NameTypeDescription
valueValueLikeScalar, array, tuple, or dictionary output.
contextExecutionContextRuntime bindings and computed values keyed by their IR identities or public parameter names.

Returns:

Any — Concrete value with tuple and dictionary structure retained.

Raises:


ClassicalStep [source]

class ClassicalStep

A classical execution step.

Constructor
def __init__(self, segment: ClassicalSegment, role: str = 'classical') -> None
Attributes

CompiledClassicalSegment [source]

class CompiledClassicalSegment

A classical segment ready for Python execution.

Constructor
def __init__(self, segment: ClassicalSegment) -> None
Attributes

CompiledExpvalSegment [source]

class CompiledExpvalSegment

A compiled expectation value segment with concrete Hamiltonian.

This segment computes <psi|H|psi> where psi is the quantum state from a quantum circuit and H is a qamomile.observable.Hamiltonian.

Constructor
def __init__(
    self,
    segment: ExpvalSegment,
    hamiltonian: 'qm_o.Hamiltonian',
    quantum_segment_index: int = 0,
    result_ref: str = '',
    qubit_map: dict[int, int] = dict(),
) -> None
Attributes

CompiledQuantumSegment [source]

class CompiledQuantumSegment(Generic[T])

A quantum segment with emitted engine circuit.

Constructor
def __init__(
    self,
    segment: QuantumSegment,
    circuit: T,
    qubit_map: QubitMap = dict(),
    clbit_map: ClbitMap = dict(),
    measurement_qubit_map: dict[int, int] = dict(),
    parameter_metadata: ParameterMetadata = ParameterMetadata(),
    implicit_output_qubit_indices: tuple[int, ...] | None = None,
) -> None
Attributes

CompositeExecutionHandle [source]

class CompositeExecutionHandle(ExecutionHandle[tuple[ResultT, ...]])

Aggregate several independently submitted executions.

Parameters:

NameTypeDescription
handlesSequence[ExecutionHandle[ResultT]]Child executions in stable result order.
Constructor
def __init__(self, handles: Sequence[ExecutionHandle[ResultT]]) -> None

Initialize an ordered execution aggregate.

Parameters:

NameTypeDescription
handlesSequence[ExecutionHandle[ResultT]]Child executions.
Attributes
Methods
cancel
def cancel(self) -> None

Attempt cancellation of every child not known to be terminal.

A status lookup failure leaves the child’s state unknown, so cancellation is still attempted. Failures are reported together after all children have been visited, retaining the original exceptions and tracebacks.

Raises:

metadata
def metadata(self) -> Mapping[str, Any]

Return metadata grouped by child index.

Returns:

Mapping[str, Any] — Mapping[str, Any]: Child metadata sequence.

raw_status
def raw_status(self) -> object

Return every child provider status.

Returns:

object — Tuple of child raw statuses.

references
def references(self) -> tuple[ExecutionReference, ...]

Return the legacy one-reference-per-child view.

This flat view cannot preserve child boundaries when a child exposes zero or multiple references. Use :meth:snapshot to retain local results and nested groups in their original positions.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Ordered child references, or an empty tuple when any child does not expose exactly one.

result
def result(self, timeout: float | None = None) -> tuple[ResultT, ...]

Return all child results in submission order.

Parameters:

NameTypeDescription
timeoutfloat | NoneTotal local wait budget in seconds.

Returns:

tuple[ResultT, ...] — tuple[ResultT, ...]: Ordered child results.

Raises:

result_async
def result_async(self, timeout: float | None = None) -> tuple[ResultT, ...]

Return all child results asynchronously.

Parameters:

NameTypeDescription
timeoutfloat | NoneTotal local wait budget in seconds.

Returns:

tuple[ResultT, ...] — tuple[ResultT, ...]: Ordered child results.

Raises:

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture all children with their original tuple boundaries.

Returns:

ExecutionSnapshot — Ordered nested execution structure.

Raises:

status
def status(self) -> JobStatus

Aggregate child statuses without hiding partial completion.

Returns:

JobStatus — Aggregate execution status.


DictValue [source]

class DictValue(_MetadataValueMixin, ValueBase)

A dictionary value stored as stable ordered entries.

Constructor
def __init__(
    self,
    name: str,
    entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> DictValue

EstimateRequest [source]

class EstimateRequest(Generic[CircuitT])

Describe one Hamiltonian expectation execution.

Parameters:

NameTypeDescription
invocationCircuitInvocation[CircuitT]Circuit and runtime inputs.
hamiltonianqm_o.HamiltonianObservable to evaluate.
accuracyEstimationAccuracy | NoneExplicit accuracy policy. None uses the executor’s configured default.
Constructor
def __init__(
    self,
    invocation: CircuitInvocation[CircuitT],
    hamiltonian: qm_o.Hamiltonian,
    accuracy: EstimationAccuracy | None = None,
) -> None
Attributes

ExecutableProgram [source]

class ExecutableProgram(Generic[T])

A fully compiled program ready for execution.

Contains compiled quantum, classical, and expectation-value segments. Use sample() for multi-shot execution or run() for single execution.

Example:

executable = transpiler.compile(kernel)

# Sample: multiple shots, returns counts
job = executable.sample(executor, shots=1000)
result = job.result()  # SampleResult with counts

# Run: single shot, returns typed result
job = executable.run(executor)
result = job.result()  # Returns kernel's return type
Constructor
def __init__(
    self,
    plan: ProgramPlan | None = None,
    compiled_quantum: list[CompiledQuantumSegment[T]] = list(),
    compiled_classical: list[CompiledClassicalSegment] = list(),
    compiled_expval: list[CompiledExpvalSegment] = list(),
    output_values: list[ValueLike] = list(),
) -> None
Attributes
Methods
get_circuits
def get_circuits(self) -> list[T]

Get all quantum circuits in execution order.

get_first_circuit
def get_first_circuit(self) -> T | None

Get the first quantum circuit, or None if no quantum segments.

restore
def restore(
    self,
    executor: QuantumExecutor[T],
    snapshot: JobSnapshot,
    bindings: dict[str, Any] | None = None,
) -> SampleJob[Any] | RunJob[Any] | ExpvalJob

Restore saved executions with this program’s typed result ABI.

Snapshots retain provider identifiers, completed local raw values, and ordered execution groups. Legacy flat provider snapshots remain supported. Reuse the same compiled program and pass the original runtime bindings explicitly to reproduce classical pre- and post-processing. Credentials, arbitrary bindings, and Python callables are not saved. Restoration reconnects to remote jobs without resubmitting or waiting for results; local values need no provider restoration support.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine adapter configured with the provider credentials and target used by the original job.
snapshotJobSnapshotSnapshot returned by the original public job’s snapshot() method.
bindingsdict[str, Any] | NoneOriginal runtime parameter bindings. Defaults to None for parameter-free programs.

Returns:

SampleJob[Any] | RunJob[Any] | ExpvalJob — SampleJob[Any] | RunJob[Any] | ExpvalJob: Restored lazy job with the same typed public result conversion as a new execution.

Raises:

Example:

>>> original = executable.sample(executor, shots=1000)
>>> snapshot = original.snapshot()
>>> restored = executable.restore(executor, snapshot)
>>> restored.result()
run
def run(
    self,
    executor: QuantumExecutor[T],
    bindings: dict[str, Any] | None = None,
    *,
    estimation: EstimationAccuracy | None = None,
) -> RunJob[Any] | ExpvalJob

Submit one execution and return its lazy result job.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine-specific quantum executor.
bindingsdict[str, Any] | NoneParameter bindings. Supports three formats: - Vector: {“gammas”: [0.1, 0.2], “betas”: [0.3, 0.4]} - Dict parameter: {“coeffs”: {0: 0.1, (0, 1): 0.2}}, decomposed per key onto the emitted parameters - Indexed: {“gammas[0]”: 0.1, “coeffs[(0, 1)]”: 0.2}
estimationEstimationAccuracy | NoneOptional per-execution expectation accuracy policy. Defaults to the executor’s configured behavior.

Returns:

RunJob[Any] | ExpvalJob — RunJob[Any] | ExpvalJob: A RunJob that resolves to the kernel’s return type, or an ExpvalJob when the program contains an expectation-value computation.

Raises:

Example:

job = executable.run(executor, bindings={"gamma": [0.5]})
result = job.result()
print(result)  # 0.25 (for QFixed) or (0, 1) (for bits)
sample
def sample(
    self,
    executor: QuantumExecutor[T],
    shots: int = 1024,
    bindings: dict[str, Any] | None = None,
) -> SampleJob[Any]

Submit a multi-shot execution and return its lazy job.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine-specific quantum executor.
shotsintNumber of shots to run.
bindingsdict[str, Any] | NoneParameter bindings. Supports three formats: - Vector: {“gammas”: [0.1, 0.2], “betas”: [0.3, 0.4]} - Dict parameter: {“coeffs”: {0: 0.1, (0, 1): 0.2}}, decomposed per key onto the emitted parameters - Indexed: {“gammas[0]”: 0.1, “coeffs[(0, 1)]”: 0.2}

Returns:

SampleJob[Any] — SampleJob[Any]: A job that resolves to a SampleResult with the per-bitstring counts.

Raises:

Example:

job = executable.sample(executor, shots=1000, bindings={"gamma": [0.5]})
result = job.result()
print(result.results)  # [(0.25, 500), (0.75, 500)]

ExecutionContext [source]

class ExecutionContext

Holds global state during program execution.

Constructor
def __init__(self, initial_bindings: dict[str, Any] | None = None)
Methods
copy
def copy(self) -> 'ExecutionContext'

Clone the execution context.

get
def get(self, key: str) -> Any
get_many
def get_many(self, keys: list[str]) -> dict[str, Any]
has
def has(self, key: str) -> bool
set
def set(self, key: str, value: Any) -> None
update
def update(self, values: dict[str, Any]) -> None

ExecutionError [source]

class ExecutionError(QamomileCompileError)

Error during program execution.


ExecutionHandle [source]

class ExecutionHandle(ABC, Generic[ResultT])

Expose an engine execution without forcing immediate result retrieval.

Attributes
Methods
cancel
def cancel(self) -> None

Request best-effort cancellation.

Cancellation is intentionally not reported as a boolean because providers may accept a request after execution has already started. Call :meth:status to observe the eventual state.

metadata
def metadata(self) -> Mapping[str, Any]

Return optional provider execution metadata.

Returns:

Mapping[str, Any] — Mapping[str, Any]: Provider metadata such as timestamps or usage.

raw_status
def raw_status(self) -> object

Return provider-specific status information.

Returns:

object — Provider status value, or the normalized status when no richer value exists.

references
def references(self) -> tuple[ExecutionReference, ...]

Return serializable remote execution references.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Secret-free provider references.

result
def result(self, timeout: float | None = None) -> ResultT

Wait for and return the engine-neutral raw result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds. None delegates the wait policy to the provider.

Returns:

ResultT — Raw result normalized by the engine executor.

Raises:

result_async
def result_async(self, timeout: float | None = None) -> ResultT

Wait asynchronously for the engine-neutral raw result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds. Defaults to provider behavior when None.

Returns:

ResultT — Raw result normalized by the engine executor.

Raises:

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture one remote execution without fetching its result.

Adapters exposing several logical references must override this method with an explicit reconstruction structure. A provider reference may itself contain multiple physical job IDs.

Returns:

ExecutionSnapshot — One opaque provider execution.

Raises:

status
def status(self) -> JobStatus

Return the current provider-independent execution status.

Returns:

JobStatus — Current normalized status.


ExecutionSnapshotKind [source]

class ExecutionSnapshotKind(StrEnum)

Identify the reconstruction contract of an execution snapshot node.

Attributes

ExpvalJob [source]

class ExpvalJob(Job[float])

Job for expectation value computation.

Returns a single float representing <psi|H|psi>.

Constructor
def __init__(self, exp_val: float | ExecutionHandle[float]) -> None

Initialize expval job.

Parameters:

NameTypeDescription
exp_valfloat | ExecutionHandle[float]Completed value or deferred expectation execution.
Methods
result
def result(self, timeout: float | None = None) -> float

Wait for and return the expectation value.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

float — Expectation value.

result_async
def result_async(self, timeout: float | None = None) -> float

Wait asynchronously for and return the expectation value.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

float — Expectation value.


ExpvalStep [source]

class ExpvalStep

An expectation-value execution step.

Constructor
def __init__(self, segment: ExpvalSegment, quantum_step_index: int = 0) -> None
Attributes

JobKind [source]

class JobKind(StrEnum)

Identify the public operation needed to reconstruct a typed job.

Attributes

JobSnapshot [source]

class JobSnapshot

Store operation metadata and lossless raw execution reconstruction.

Runtime bindings are intentionally excluded. They can contain arbitrary application data, so callers supply them again to :meth:ExecutableProgram.restore instead of persisting them implicitly.

Parameters:

NameTypeDescription
kindJobKindPublic operation that created the job.
executionstuple[ExecutionReference, ...]Ordered provider reference inventory. Empty for entirely local structured executions. For legacy snapshots, these references also specify the result layout.
shotsint | NoneSampling shot count. Required for sample jobs and absent for run jobs.
executionExecutionSnapshot | NoneOrdered remote/local execution tree. None denotes the legacy flat-reference format. When present, executions must exactly match its remote leaves.

Raises:

Constructor
def __init__(
    self,
    kind: JobKind,
    executions: tuple[ExecutionReference, ...],
    shots: int | None = None,
    execution: ExecutionSnapshot | None = None,
) -> None
Attributes
Methods
from_dict
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> JobSnapshot

Reconstruct a validated snapshot from JSON-compatible data.

Parameters:

NameTypeDescription
dataMapping[str, Any]Mapping produced by :meth:to_dict.

Returns:

JobSnapshot — Validated typed-job restoration snapshot.

Raises:

to_dict
def to_dict(self) -> dict[str, Any]

Convert the snapshot to JSON-compatible data.

Returns:

dict[str, Any] — dict[str, Any]: Version 2 operation metadata and execution tree, or the original legacy format for a flat-reference snapshot.

Raises:


MappedExecutionHandle [source]

class MappedExecutionHandle(ExecutionHandle[MappedT], Generic[ResultT, MappedT])

Lazily transform another execution handle’s result.

Parameters:

NameTypeDescription
sourceExecutionHandle[ResultT]Underlying execution handle.
transformCallable[[ResultT], MappedT]Result transformation.
snapshot_sourceboolWhether the owning executable reconstructs this transformation when restoring the source. Defaults to False.
Constructor
def __init__(
    self,
    source: ExecutionHandle[ResultT],
    transform: Callable[[ResultT], MappedT],
    *,
    snapshot_source: bool = False,
) -> None

Initialize a lazy mapped execution.

Parameters:

NameTypeDescription
sourceExecutionHandle[ResultT]Underlying execution handle.
transformCallable[[ResultT], MappedT]Result transformation.
snapshot_sourceboolAllow source snapshots only when the owner rebuilds the transformation on restore. Defaults to False.
Attributes
Methods
cancel
def cancel(self) -> None

Forward a cancellation request to the source execution.

metadata
def metadata(self) -> Mapping[str, Any]

Return source execution metadata.

Returns:

Mapping[str, Any] — Mapping[str, Any]: Source metadata.

raw_status
def raw_status(self) -> object

Return the source provider status.

Returns:

object — Provider-specific source status.

references
def references(self) -> tuple[ExecutionReference, ...]

Return source execution references.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Source references.

result
def result(self, timeout: float | None = None) -> MappedT

Retrieve and transform the source result once.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

MappedT — Cached transformed result.

Raises:

result_async
def result_async(self, timeout: float | None = None) -> MappedT

Retrieve and transform the source result asynchronously.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

MappedT — Cached transformed result.

Raises:

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture a source whose mapping is rebuilt by its owning executable.

Python callables are never serialized. Arbitrary mappings must supply an adapter-specific restoration recipe instead of losing conversion.

Returns:

ExecutionSnapshot — Source reconstruction structure.

Raises:

status
def status(self) -> JobStatus

Return the source execution status.

Returns:

JobStatus — Current mapped execution status.


ParameterMetadata [source]

class ParameterMetadata

Describe every scalar slot and runtime array in a compiled segment.

Parameters:

NameTypeDescription
parameterslist[ParameterInfo]Ordered scalar engine slots. Defaults to an empty list.
arraysdict[str, ParameterArrayInfo]Explicit runtime-array ABI descriptors keyed by root name. Defaults to descriptors derived from parameters for backward compatibility.
Constructor
def __init__(
    self,
    parameters: list[ParameterInfo] = list(),
    arrays: dict[str, ParameterArrayInfo] = dict(),
) -> None
Attributes
Methods
get_array_names
def get_array_names(self) -> set[str]

Return unique scalar and array root names.

Returns:

set[str] — set[str]: Root name for every emitted parameter.

get_ordered_params
def get_ordered_params(self) -> list[Any]

Return engine parameter objects in ABI definition order.

Returns:

list[Any] — list[Any]: Engine-specific parameter objects.

get_param_by_name
def get_param_by_name(self, name: str) -> ParameterInfo | None

Find one scalar slot by its full emitted key.

Parameters:

NameTypeDescription
namestrFull engine parameter key.

Returns:

ParameterInfo | None — ParameterInfo | None: Matching slot, or None when absent.

merge
@classmethod
def merge(cls, metadata: Sequence[ParameterMetadata]) -> ParameterMetadata

Merge parameter manifests from multiple quantum segments.

Parameters:

NameTypeDescription
metadataSequence[ParameterMetadata]Segment manifests in execution order.

Returns:

ParameterMetadata — Combined manifest with first-seen scalar slot ordering and array descriptors derived across all segments.

to_binding_dict
def to_binding_dict(self, bindings: Mapping[str, Any]) -> dict[Any, Any]

Map indexed user bindings to engine parameter objects.

Parameters:

NameTypeDescription
bindingsMapping[str, Any]Scalar values keyed by full emitted parameter name.

Returns:

dict[Any, Any] — dict[Any, Any]: Engine parameter objects mapped to bound values.

validate_array_shapes
def validate_array_shapes(self, bindings: Mapping[str, Any] | None) -> None

Validate user array rank and every concrete ABI dimension.

Parameters:

NameTypeDescription
bindingsMapping[str, Any] | NoneRaw public bindings before scalar flattening. None means no validation is needed.

Raises:

validate_required_bindings
def validate_required_bindings(self, indexed_bindings: Mapping[str, Any]) -> None

Reject missing scalar slots in an indexed binding map.

Parameters:

NameTypeDescription
indexed_bindingsMapping[str, Any]Flattened user bindings.

Raises:


ProgramOrchestrator [source]

class ProgramOrchestrator(Generic[T])

Orchestrates execution of compiled quantum-classical programs.

This is an internal class that handles the runtime execution logic. Users should use ExecutableProgram.sample() and ExecutableProgram.run() instead.

Constructor
def __init__(self, program: ExecutableProgram[T]) -> None
Methods
restore
def restore(
    self,
    executor: QuantumExecutor[T],
    snapshot: JobSnapshot,
    bindings: dict[str, Any] | None,
) -> SampleJob[Any] | RunJob[Any] | ExpvalJob

Restore provider executions and rebuild the typed public job.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine adapter configured with the credentials and target needed to restore provider jobs.
snapshotJobSnapshotOperation metadata and provider references captured from the original public job.
bindingsdict[str, Any] | NoneOriginal runtime bindings used to rebuild classical pre- and post-processing context.

Returns:

SampleJob[Any] | RunJob[Any] | ExpvalJob — SampleJob[Any] | RunJob[Any] | ExpvalJob: Lazy typed job with the same public result conversion as the original execution.

Raises:

run
def run(
    self,
    executor: QuantumExecutor[T],
    bindings: dict[str, Any] | None,
    estimation: EstimationAccuracy | None = None,
) -> RunJob[Any] | ExpvalJob

Submit one execution and return its lazy public job.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine execution adapter.
bindingsdict[str, Any] | NoneRuntime public bindings.
estimationEstimationAccuracy | NoneOptional expectation accuracy policy. Defaults to the executor configuration.

Returns:

RunJob[Any] | ExpvalJob — RunJob[Any] | ExpvalJob: Deferred public result job.

run_expval
def run_expval(
    self,
    executor: QuantumExecutor[T],
    bindings: dict[str, Any] | None,
    estimation: EstimationAccuracy | None = None,
) -> ExpvalJob

Submit a pure expectation execution through the public run path.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine execution adapter.
bindingsdict[str, Any] | NoneRuntime public bindings.
estimationEstimationAccuracy | NoneOptional expectation accuracy policy.

Returns:

ExpvalJob — Deferred expectation result.

Raises:

sample
def sample(
    self,
    executor: QuantumExecutor[T],
    shots: int,
    bindings: dict[str, Any] | None,
) -> SampleJob[Any]

Submit sampling and return a lazy typed-result job.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine execution adapter.
shotsintPositive number of requested samples.
bindingsdict[str, Any] | NoneRuntime public bindings.

Returns:

SampleJob[Any] — SampleJob[Any]: Deferred typed sample job.

Raises:


QuantumExecutor [source]

class QuantumExecutor(ABC, Generic[T])

Abstract base class for quantum backend execution.

To implement a custom executor:

  1. execute() [Required] Execute circuit and return bitstring counts as dict[str, int]. Keys are bitstrings in big-endian format (e.g., “011” means q2=0, q1=1, q0=1).

  2. bind_parameters() [Optional] Bind parameter values to parametric circuits. Override if your executor supports parametric circuits (e.g., QAOA variational circuits). Use ParameterMetadata.to_binding_dict() for easy conversion.

  3. estimate() [Optional] Compute expectation values <psi|H|psi>. Override if your executor supports estimation primitives (e.g., Qiskit Estimator, QURI Parts).

Example (Minimal): class MyExecutor(QuantumExecutor[QuantumCircuit]): def init(self): from qiskit_aer import AerSimulator self.backend = AerSimulator()

    def execute(self, circuit, shots):
        from qiskit import transpile
        if circuit.num_clbits == 0:
            circuit = circuit.copy()
            circuit.measure_all()
        transpiled = transpile(circuit, self.backend)
        return self.backend.run(transpiled, shots=shots).result().get_counts()

Example (With Parameter Binding): def bind_parameters(self, circuit, bindings, metadata): # metadata.to_binding_dict() converts indexed names to engine params return circuit.assign_parameters(metadata.to_binding_dict(bindings))

Attributes
Methods
bind_invocation
def bind_invocation(self, invocation: CircuitInvocation[T]) -> T

Bind one invocation for a backend without native input submission.

Parameters:

NameTypeDescription
invocationCircuitInvocation[T]Circuit, flattened bindings, and engine parameter metadata.

Returns:

T — Bound circuit, or the original circuit when it has no runtime parameters.

bind_parameters
def bind_parameters(
    self,
    circuit: T,
    bindings: dict[str, Any],
    parameter_metadata: ParameterMetadata,
) -> T

Bind parameter values to the circuit.

Default implementation returns the circuit unchanged. Override for backends that support parametric circuits.

Parameters:

NameTypeDescription
circuitTThe parameterized circuit
bindingsdict[str, Any]Dict mapping parameter names (indexed format) to values. e.g., {“gammas[0]”: 0.1, “gammas[1]”: 0.2}
parameter_metadataParameterMetadataMetadata about circuit parameters

Returns:

T — New circuit with parameters bound

estimate
def estimate(
    self,
    circuit: T,
    hamiltonian: 'qm_o.Hamiltonian',
    params: Sequence[float] | None = None,
) -> float

Estimate the expectation value of a Hamiltonian.

This method computes <psi|H|psi> where psi is the quantum state prepared by the circuit and H is the Hamiltonian.

Backends can override this method to provide optimized implementations using their native estimator primitives.

Parameters:

NameTypeDescription
circuitTThe quantum circuit (state preparation ansatz)
hamiltonian'qm_o.Hamiltonian'The qamomile.observable.Hamiltonian to measure
paramsSequence[float] | NoneOptional parameter values for parametric circuits

Returns:

float — The estimated expectation value

Raises:

execute
def execute(self, circuit: T, shots: int) -> dict[str, int]

Execute the circuit and return bitstring counts.

Parameters:

NameTypeDescription
circuitTThe quantum circuit to execute
shotsintNumber of measurement shots

Returns:

dict[str, int] — Dictionary mapping bitstrings to counts. dict[str, int] — {“00”: 512, “11”: 512}

restore
def restore(self, reference: ExecutionReference) -> ExecutionHandle[Any]

Restore a remote execution from a secret-free reference.

Parameters:

NameTypeDescription
referenceExecutionReferenceProvider execution reference.

Returns:

ExecutionHandle[Any] — ExecutionHandle[Any]: Restored provider-backed handle.

Raises:

submit_estimate
def submit_estimate(self, request: EstimateRequest[T]) -> ExecutionHandle[float]

Submit an expectation request through the synchronous path.

Parameters:

NameTypeDescription
requestEstimateRequest[T]Circuit, Hamiltonian, and optional accuracy policy.

Returns:

ExecutionHandle[float] — ExecutionHandle[float]: Completed compatibility handle.

Raises:

submit_estimates
def submit_estimates(
    self,
    requests: Sequence[EstimateRequest[T]],
) -> ExecutionHandle[tuple[float, ...]]

Submit an ordered collection of expectation requests.

Parameters:

NameTypeDescription
requestsSequence[EstimateRequest[T]]Expectation requests.

Returns:

ExecutionHandle[tuple[float, ...]] — ExecutionHandle[tuple[float, ...]]: Composite result handle in request order.

submit_sample
def submit_sample(self, request: SampleRequest[T]) -> ExecutionHandle[dict[str, int]]

Submit a sampling request through the synchronous compatibility path.

Remote executors should override this method and return immediately with a provider-backed handle. Existing synchronous executors inherit this implementation unchanged.

Parameters:

NameTypeDescription
requestSampleRequest[T]Circuit invocation and shot count.

Returns:

ExecutionHandle[dict[str, int]] — ExecutionHandle[dict[str, int]]: Completed compatibility handle.

submit_samples
def submit_samples(
    self,
    requests: Sequence[SampleRequest[T]],
) -> ExecutionHandle[tuple[dict[str, int], ...]]

Submit an ordered collection of sampling requests.

Backends with native batch or parameter-sweep support should override this method. The default preserves ordering with individual requests.

Parameters:

NameTypeDescription
requestsSequence[SampleRequest[T]]Sampling requests.

Returns:

ExecutionHandle[tuple[dict[str, int], ...]] — ExecutionHandle[tuple[dict[str, int], ...]]: Composite result handle preserving request order.


QuantumStep [source]

class QuantumStep

A quantum execution step.

Constructor
def __init__(self, segment: QuantumSegment) -> None
Attributes

RunJob [source]

class RunJob(Job[T], Generic[T])

Job for single execution.

Returns a single result value matching the kernel’s return type.

Constructor
def __init__(
    self,
    raw_counts: dict[str, int] | ExecutionHandle[dict[str, int]] | None,
    result_converter: Callable[[str], T] | None,
    *,
    value_handle: ExecutionHandle[T] | None = None,
) -> None

Initialize run job.

Parameters:

NameTypeDescription
raw_countsdict[str, int] | ExecutionHandle[dict[str, int]] | NoneCounts or deferred counts. May be None with value_handle.
result_converterCallable[[str], T] | NoneFunction converting one bitstring. May be None with value_handle.
value_handleExecutionHandle[T] | NoneHandle already producing the final public value. Defaults to None.

Raises:

Methods
from_handle
@classmethod
def from_handle(cls, handle: ExecutionHandle[T]) -> RunJob[T]

Create a run job whose handle already returns the public value.

Parameters:

NameTypeDescription
handleExecutionHandle[T]Final-value execution handle.

Returns:

RunJob[T] — RunJob[T]: Public run job delegating to handle.

result
def result(self, timeout: float | None = None) -> T

Wait for and return the single public result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

T — Public kernel return value.

result_async
def result_async(self, timeout: float | None = None) -> T

Wait asynchronously for the single public result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

T — Public kernel return value.


SampleJob [source]

class SampleJob(Job[SampleResult[T]], Generic[T])

Job for sampling execution (multiple shots).

Returns a SampleResult containing counts for each unique result.

Constructor
def __init__(
    self,
    raw_counts: dict[str, int] | ExecutionHandle[dict[str, int]],
    result_converter: Callable[[dict[str, int]], list[tuple[T, int]]],
    shots: int,
) -> None

Initialize sample job.

Parameters:

NameTypeDescription
raw_countsdict[str, int] | ExecutionHandle[dict[str, int]]Counts or a deferred counts execution.
result_converterCallable[[dict[str, int]], list[tuple[T, int]]]Function converting raw counts to typed values.
shotsintNumber of requested shots.
Methods
result
def result(self, timeout: float | None = None) -> SampleResult[T]

Wait for and return the typed sample result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

SampleResult[T] — SampleResult[T]: Aggregated typed result.

result_async
def result_async(self, timeout: float | None = None) -> SampleResult[T]

Wait asynchronously for the typed sample result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds.

Returns:

SampleResult[T] — SampleResult[T]: Aggregated typed result.


SampleRequest [source]

class SampleRequest(Generic[CircuitT])

Describe one sampling execution.

Parameters:

NameTypeDescription
invocationCircuitInvocation[CircuitT]Circuit and runtime inputs.
shotsintNumber of requested samples.

Raises:

Constructor
def __init__(self, invocation: CircuitInvocation[CircuitT], shots: int) -> None
Attributes

TupleValue [source]

class TupleValue(_MetadataValueMixin, ValueBase)

A tuple of IR values for structured data.

Constructor
def __init__(
    self,
    name: str,
    elements: tuple[ValueLike, ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> TupleValue

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 engine resource allocation. This applies to every Value regardless of its type (Qubit, Float, Bit, ...) -- it is not specific to qubits.


qamomile.circuit.transpiler.quantum_executor

Abstract base class for quantum backend execution.

This module provides a simple interface for implementing custom quantum executors. Executors bridge Qamomile’s compiled circuits to various quantum backends including local simulators and cloud quantum devices.

Basic Example (Local Simulator): from qiskit_aer import AerSimulator

class MyExecutor(QuantumExecutor[QuantumCircuit]):
    def __init__(self):
        self.backend = AerSimulator()

    def execute(self, circuit: QuantumCircuit, shots: int) -> dict[str, int]:
        from qiskit import transpile
        if circuit.num_clbits == 0:
            circuit = circuit.copy()
            circuit.measure_all()
        transpiled = transpile(circuit, self.backend)
        job = self.backend.run(transpiled, shots=shots)
        return job.result().get_counts()

Cloud Backend Example (IBM Quantum): from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2

class IBMQuantumExecutor(QuantumExecutor[QuantumCircuit]):
    def __init__(self, backend_name: str = "ibm_brisbane"):
        self.service = QiskitRuntimeService()
        self.backend_name = backend_name

    def execute(self, circuit: QuantumCircuit, shots: int) -> dict[str, int]:
        from qiskit.transpiler.preset_passmanagers import (
            generate_preset_pass_manager,
        )
        backend = self.service.backend(self.backend_name)
        pm = generate_preset_pass_manager(backend=backend, optimization_level=1)
        transpiled = pm.run(circuit)
        sampler = SamplerV2(backend)
        job = sampler.run([transpiled], shots=shots)
        return job.result()[0].data.meas.get_counts()

    def bind_parameters(self, circuit, bindings, metadata):
        # Use helper method for easy conversion
        return circuit.assign_parameters(metadata.to_binding_dict(bindings))

Bitstring Format:

The execute() method returns dict[str, int] where keys are bitstrings in big-endian format (leftmost bit = highest qubit index). Example: {“011”: 512, “100”: 488} for 3 qubits

Overview

ClassDescription
CircuitInvocationKeep an emitted circuit and runtime parameter values together.
CompletedExecutionHandleWrap an already available result for synchronous executors.
CompositeExecutionHandleAggregate several independently submitted executions.
EstimateRequestDescribe one Hamiltonian expectation execution.
ExecutionCapabilitiesDeclare the execution features implemented by one executor.
ExecutionHandleExpose an engine execution without forcing immediate result retrieval.
ExecutionReferenceStore secret-free identifiers needed to restore remote execution.
ParameterMetadataDescribe every scalar slot and runtime array in a compiled segment.
QuantumExecutorAbstract base class for quantum backend execution.
SampleRequestDescribe one sampling execution.

Classes

CircuitInvocation [source]

class CircuitInvocation(Generic[CircuitT])

Keep an emitted circuit and runtime parameter values together.

Engines may bind the values into a new circuit or submit them through a native parameter-input API. Keeping both forms available preserves native parameter sweeps and provider-side compilation caches.

Parameters:

NameTypeDescription
circuitCircuitTEmitted engine circuit or kernel artifact.
bindingsMapping[str, Any]Flattened Qamomile runtime bindings.
parameter_metadataParameterMetadataMapping from public parameter names to engine parameter objects.
Constructor
def __init__(
    self,
    circuit: CircuitT,
    bindings: Mapping[str, Any],
    parameter_metadata: ParameterMetadata,
) -> None
Attributes

CompletedExecutionHandle [source]

class CompletedExecutionHandle(ExecutionHandle[ResultT])

Wrap an already available result for synchronous executors.

Parameters:

NameTypeDescription
valueResultTCompleted execution value.
Constructor
def __init__(self, value: ResultT) -> None

Initialize an immediately completed execution.

Parameters:

NameTypeDescription
valueResultTCompleted execution value.
Methods
result
def result(self, timeout: float | None = None) -> ResultT

Return the completed value without waiting.

Parameters:

NameTypeDescription
timeoutfloat | NoneIgnored compatibility timeout.

Returns:

ResultT — Stored execution value.

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture the already available raw result without waiting.

Returns:

ExecutionSnapshot — Owned, type-preserving local value.

Raises:

status
def status(self) -> JobStatus

Return the completed status.

Returns:

JobStatus — Always :attr:JobStatus.COMPLETED.


CompositeExecutionHandle [source]

class CompositeExecutionHandle(ExecutionHandle[tuple[ResultT, ...]])

Aggregate several independently submitted executions.

Parameters:

NameTypeDescription
handlesSequence[ExecutionHandle[ResultT]]Child executions in stable result order.
Constructor
def __init__(self, handles: Sequence[ExecutionHandle[ResultT]]) -> None

Initialize an ordered execution aggregate.

Parameters:

NameTypeDescription
handlesSequence[ExecutionHandle[ResultT]]Child executions.
Attributes
Methods
cancel
def cancel(self) -> None

Attempt cancellation of every child not known to be terminal.

A status lookup failure leaves the child’s state unknown, so cancellation is still attempted. Failures are reported together after all children have been visited, retaining the original exceptions and tracebacks.

Raises:

metadata
def metadata(self) -> Mapping[str, Any]

Return metadata grouped by child index.

Returns:

Mapping[str, Any] — Mapping[str, Any]: Child metadata sequence.

raw_status
def raw_status(self) -> object

Return every child provider status.

Returns:

object — Tuple of child raw statuses.

references
def references(self) -> tuple[ExecutionReference, ...]

Return the legacy one-reference-per-child view.

This flat view cannot preserve child boundaries when a child exposes zero or multiple references. Use :meth:snapshot to retain local results and nested groups in their original positions.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Ordered child references, or an empty tuple when any child does not expose exactly one.

result
def result(self, timeout: float | None = None) -> tuple[ResultT, ...]

Return all child results in submission order.

Parameters:

NameTypeDescription
timeoutfloat | NoneTotal local wait budget in seconds.

Returns:

tuple[ResultT, ...] — tuple[ResultT, ...]: Ordered child results.

Raises:

result_async
def result_async(self, timeout: float | None = None) -> tuple[ResultT, ...]

Return all child results asynchronously.

Parameters:

NameTypeDescription
timeoutfloat | NoneTotal local wait budget in seconds.

Returns:

tuple[ResultT, ...] — tuple[ResultT, ...]: Ordered child results.

Raises:

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture all children with their original tuple boundaries.

Returns:

ExecutionSnapshot — Ordered nested execution structure.

Raises:

status
def status(self) -> JobStatus

Aggregate child statuses without hiding partial completion.

Returns:

JobStatus — Aggregate execution status.


EstimateRequest [source]

class EstimateRequest(Generic[CircuitT])

Describe one Hamiltonian expectation execution.

Parameters:

NameTypeDescription
invocationCircuitInvocation[CircuitT]Circuit and runtime inputs.
hamiltonianqm_o.HamiltonianObservable to evaluate.
accuracyEstimationAccuracy | NoneExplicit accuracy policy. None uses the executor’s configured default.
Constructor
def __init__(
    self,
    invocation: CircuitInvocation[CircuitT],
    hamiltonian: qm_o.Hamiltonian,
    accuracy: EstimationAccuracy | None = None,
) -> None
Attributes

ExecutionCapabilities [source]

class ExecutionCapabilities

Declare the execution features implemented by one executor.

Parameters:

NameTypeDescription
supports_async_samplingboolWhether sampling submission returns before provider execution completes. Defaults to False.
supports_async_estimationboolWhether expectation submission returns before provider execution completes. Defaults to False.
supports_estimationboolWhether expectation-value execution is implemented. Defaults to False.
supports_cancellationboolWhether provider-backed handles can request cancellation. Defaults to False.
supports_restorationboolWhether execution references can recreate provider-backed handles. Defaults to False.
supports_native_batchboolWhether multiple logical requests can be submitted through one provider-native batch or job. Defaults to False.
supports_native_parameter_inputsboolWhether runtime values remain separate from emitted circuits during provider submission. Defaults to False.
estimation_accuracyfrozenset[EstimationPolicyType]Explicit per-request accuracy policies accepted by the executor. An empty set means only executor-configured estimation behavior is available.

Raises:

Constructor
def __init__(
    self,
    supports_async_sampling: bool = False,
    supports_async_estimation: bool = False,
    supports_estimation: bool = False,
    supports_cancellation: bool = False,
    supports_restoration: bool = False,
    supports_native_batch: bool = False,
    supports_native_parameter_inputs: bool = False,
    estimation_accuracy: frozenset[EstimationPolicyType] = frozenset(),
) -> None
Attributes

ExecutionHandle [source]

class ExecutionHandle(ABC, Generic[ResultT])

Expose an engine execution without forcing immediate result retrieval.

Attributes
Methods
cancel
def cancel(self) -> None

Request best-effort cancellation.

Cancellation is intentionally not reported as a boolean because providers may accept a request after execution has already started. Call :meth:status to observe the eventual state.

metadata
def metadata(self) -> Mapping[str, Any]

Return optional provider execution metadata.

Returns:

Mapping[str, Any] — Mapping[str, Any]: Provider metadata such as timestamps or usage.

raw_status
def raw_status(self) -> object

Return provider-specific status information.

Returns:

object — Provider status value, or the normalized status when no richer value exists.

references
def references(self) -> tuple[ExecutionReference, ...]

Return serializable remote execution references.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Secret-free provider references.

result
def result(self, timeout: float | None = None) -> ResultT

Wait for and return the engine-neutral raw result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds. None delegates the wait policy to the provider.

Returns:

ResultT — Raw result normalized by the engine executor.

Raises:

result_async
def result_async(self, timeout: float | None = None) -> ResultT

Wait asynchronously for the engine-neutral raw result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds. Defaults to provider behavior when None.

Returns:

ResultT — Raw result normalized by the engine executor.

Raises:

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture one remote execution without fetching its result.

Adapters exposing several logical references must override this method with an explicit reconstruction structure. A provider reference may itself contain multiple physical job IDs.

Returns:

ExecutionSnapshot — One opaque provider execution.

Raises:

status
def status(self) -> JobStatus

Return the current provider-independent execution status.

Returns:

JobStatus — Current normalized status.


ExecutionReference [source]

class ExecutionReference

Store secret-free identifiers needed to restore remote execution.

Parameters:

NameTypeDescription
providerstrStable provider or adapter name.
job_idstuple[str, ...]One or more provider job identifiers.
targetstr | NoneProvider target or device identifier. Defaults to None.
group_idstr | NoneSession, batch, program, or parent identifier. Defaults to None.
contextMapping[str, str]Additional non-secret identifiers needed to restore the job. Defaults to an empty mapping.

Raises:

Constructor
def __init__(
    self,
    provider: str,
    job_ids: tuple[str, ...],
    target: str | None = None,
    group_id: str | None = None,
    context: Mapping[str, str] = dict(),
) -> None
Attributes
Methods
from_dict
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionReference

Reconstruct a provider reference from JSON-compatible data.

Parameters:

NameTypeDescription
dataMapping[str, Any]Mapping produced by :meth:to_dict.

Returns:

ExecutionReference — Validated provider execution reference.

Raises:

to_dict
def to_dict(self) -> dict[str, Any]

Convert the provider reference to JSON-compatible data.

Returns:

dict[str, Any] — dict[str, Any]: Provider identifiers and decoding context without credentials or SDK objects.


ParameterMetadata [source]

class ParameterMetadata

Describe every scalar slot and runtime array in a compiled segment.

Parameters:

NameTypeDescription
parameterslist[ParameterInfo]Ordered scalar engine slots. Defaults to an empty list.
arraysdict[str, ParameterArrayInfo]Explicit runtime-array ABI descriptors keyed by root name. Defaults to descriptors derived from parameters for backward compatibility.
Constructor
def __init__(
    self,
    parameters: list[ParameterInfo] = list(),
    arrays: dict[str, ParameterArrayInfo] = dict(),
) -> None
Attributes
Methods
get_array_names
def get_array_names(self) -> set[str]

Return unique scalar and array root names.

Returns:

set[str] — set[str]: Root name for every emitted parameter.

get_ordered_params
def get_ordered_params(self) -> list[Any]

Return engine parameter objects in ABI definition order.

Returns:

list[Any] — list[Any]: Engine-specific parameter objects.

get_param_by_name
def get_param_by_name(self, name: str) -> ParameterInfo | None

Find one scalar slot by its full emitted key.

Parameters:

NameTypeDescription
namestrFull engine parameter key.

Returns:

ParameterInfo | None — ParameterInfo | None: Matching slot, or None when absent.

merge
@classmethod
def merge(cls, metadata: Sequence[ParameterMetadata]) -> ParameterMetadata

Merge parameter manifests from multiple quantum segments.

Parameters:

NameTypeDescription
metadataSequence[ParameterMetadata]Segment manifests in execution order.

Returns:

ParameterMetadata — Combined manifest with first-seen scalar slot ordering and array descriptors derived across all segments.

to_binding_dict
def to_binding_dict(self, bindings: Mapping[str, Any]) -> dict[Any, Any]

Map indexed user bindings to engine parameter objects.

Parameters:

NameTypeDescription
bindingsMapping[str, Any]Scalar values keyed by full emitted parameter name.

Returns:

dict[Any, Any] — dict[Any, Any]: Engine parameter objects mapped to bound values.

validate_array_shapes
def validate_array_shapes(self, bindings: Mapping[str, Any] | None) -> None

Validate user array rank and every concrete ABI dimension.

Parameters:

NameTypeDescription
bindingsMapping[str, Any] | NoneRaw public bindings before scalar flattening. None means no validation is needed.

Raises:

validate_required_bindings
def validate_required_bindings(self, indexed_bindings: Mapping[str, Any]) -> None

Reject missing scalar slots in an indexed binding map.

Parameters:

NameTypeDescription
indexed_bindingsMapping[str, Any]Flattened user bindings.

Raises:


QuantumExecutor [source]

class QuantumExecutor(ABC, Generic[T])

Abstract base class for quantum backend execution.

To implement a custom executor:

  1. execute() [Required] Execute circuit and return bitstring counts as dict[str, int]. Keys are bitstrings in big-endian format (e.g., “011” means q2=0, q1=1, q0=1).

  2. bind_parameters() [Optional] Bind parameter values to parametric circuits. Override if your executor supports parametric circuits (e.g., QAOA variational circuits). Use ParameterMetadata.to_binding_dict() for easy conversion.

  3. estimate() [Optional] Compute expectation values <psi|H|psi>. Override if your executor supports estimation primitives (e.g., Qiskit Estimator, QURI Parts).

Example (Minimal): class MyExecutor(QuantumExecutor[QuantumCircuit]): def init(self): from qiskit_aer import AerSimulator self.backend = AerSimulator()

    def execute(self, circuit, shots):
        from qiskit import transpile
        if circuit.num_clbits == 0:
            circuit = circuit.copy()
            circuit.measure_all()
        transpiled = transpile(circuit, self.backend)
        return self.backend.run(transpiled, shots=shots).result().get_counts()

Example (With Parameter Binding): def bind_parameters(self, circuit, bindings, metadata): # metadata.to_binding_dict() converts indexed names to engine params return circuit.assign_parameters(metadata.to_binding_dict(bindings))

Attributes
Methods
bind_invocation
def bind_invocation(self, invocation: CircuitInvocation[T]) -> T

Bind one invocation for a backend without native input submission.

Parameters:

NameTypeDescription
invocationCircuitInvocation[T]Circuit, flattened bindings, and engine parameter metadata.

Returns:

T — Bound circuit, or the original circuit when it has no runtime parameters.

bind_parameters
def bind_parameters(
    self,
    circuit: T,
    bindings: dict[str, Any],
    parameter_metadata: ParameterMetadata,
) -> T

Bind parameter values to the circuit.

Default implementation returns the circuit unchanged. Override for backends that support parametric circuits.

Parameters:

NameTypeDescription
circuitTThe parameterized circuit
bindingsdict[str, Any]Dict mapping parameter names (indexed format) to values. e.g., {“gammas[0]”: 0.1, “gammas[1]”: 0.2}
parameter_metadataParameterMetadataMetadata about circuit parameters

Returns:

T — New circuit with parameters bound

estimate
def estimate(
    self,
    circuit: T,
    hamiltonian: 'qm_o.Hamiltonian',
    params: Sequence[float] | None = None,
) -> float

Estimate the expectation value of a Hamiltonian.

This method computes <psi|H|psi> where psi is the quantum state prepared by the circuit and H is the Hamiltonian.

Backends can override this method to provide optimized implementations using their native estimator primitives.

Parameters:

NameTypeDescription
circuitTThe quantum circuit (state preparation ansatz)
hamiltonian'qm_o.Hamiltonian'The qamomile.observable.Hamiltonian to measure
paramsSequence[float] | NoneOptional parameter values for parametric circuits

Returns:

float — The estimated expectation value

Raises:

execute
def execute(self, circuit: T, shots: int) -> dict[str, int]

Execute the circuit and return bitstring counts.

Parameters:

NameTypeDescription
circuitTThe quantum circuit to execute
shotsintNumber of measurement shots

Returns:

dict[str, int] — Dictionary mapping bitstrings to counts. dict[str, int] — {“00”: 512, “11”: 512}

restore
def restore(self, reference: ExecutionReference) -> ExecutionHandle[Any]

Restore a remote execution from a secret-free reference.

Parameters:

NameTypeDescription
referenceExecutionReferenceProvider execution reference.

Returns:

ExecutionHandle[Any] — ExecutionHandle[Any]: Restored provider-backed handle.

Raises:

submit_estimate
def submit_estimate(self, request: EstimateRequest[T]) -> ExecutionHandle[float]

Submit an expectation request through the synchronous path.

Parameters:

NameTypeDescription
requestEstimateRequest[T]Circuit, Hamiltonian, and optional accuracy policy.

Returns:

ExecutionHandle[float] — ExecutionHandle[float]: Completed compatibility handle.

Raises:

submit_estimates
def submit_estimates(
    self,
    requests: Sequence[EstimateRequest[T]],
) -> ExecutionHandle[tuple[float, ...]]

Submit an ordered collection of expectation requests.

Parameters:

NameTypeDescription
requestsSequence[EstimateRequest[T]]Expectation requests.

Returns:

ExecutionHandle[tuple[float, ...]] — ExecutionHandle[tuple[float, ...]]: Composite result handle in request order.

submit_sample
def submit_sample(self, request: SampleRequest[T]) -> ExecutionHandle[dict[str, int]]

Submit a sampling request through the synchronous compatibility path.

Remote executors should override this method and return immediately with a provider-backed handle. Existing synchronous executors inherit this implementation unchanged.

Parameters:

NameTypeDescription
requestSampleRequest[T]Circuit invocation and shot count.

Returns:

ExecutionHandle[dict[str, int]] — ExecutionHandle[dict[str, int]]: Completed compatibility handle.

submit_samples
def submit_samples(
    self,
    requests: Sequence[SampleRequest[T]],
) -> ExecutionHandle[tuple[dict[str, int], ...]]

Submit an ordered collection of sampling requests.

Backends with native batch or parameter-sweep support should override this method. The default preserves ordering with individual requests.

Parameters:

NameTypeDescription
requestsSequence[SampleRequest[T]]Sampling requests.

Returns:

ExecutionHandle[tuple[dict[str, int], ...]] — ExecutionHandle[tuple[dict[str, int], ...]]: Composite result handle preserving request order.


SampleRequest [source]

class SampleRequest(Generic[CircuitT])

Describe one sampling execution.

Parameters:

NameTypeDescription
invocationCircuitInvocation[CircuitT]Circuit and runtime inputs.
shotsintNumber of requested samples.

Raises:

Constructor
def __init__(self, invocation: CircuitInvocation[CircuitT], shots: int) -> None
Attributes

qamomile.circuit.transpiler.result

EmitResult data structures for transpiler output.

Overview

ClassDescription
ClassicalMappingMaps a logical Value to a classical value or measurement result slot.
EmitResultStructured result from Transpiler.emit().
OutputMappingMaps Block output position to a physical resource.
QubitMappingMaps a logical Value to a physical qubit index.

Classes

ClassicalMapping [source]

class ClassicalMapping

Maps a logical Value to a classical value or measurement result slot.

Constructor
def __init__(
    self,
    value_uuid: str,
    value_name: str,
    value: Union[int, float, bool, None],
    clbit_index: Union[int, None] = None,
) -> None
Attributes

EmitResult [source]

class EmitResult(Generic[T])

Structured result from Transpiler.emit().

Contains the engine-specific circuit along with mapping information that tracks the correspondence between logical Values and physical qubit/clbit indices.

Constructor
def __init__(
    self,
    circuit: T,
    qubit_mappings: list[QubitMapping],
    classical_mappings: list[ClassicalMapping],
    output_mappings: list[OutputMapping],
    num_qubits: int,
    num_clbits: int = 0,
) -> None
Attributes
Methods
get_measurement_clbit_indices
def get_measurement_clbit_indices(self) -> list[int]

Get clbit indices for all measurement outputs in order.

get_output_mapping_by_index
def get_output_mapping_by_index(self, index: int) -> Union[OutputMapping, None]

Get output mapping by tuple index.

get_output_qubit_indices
def get_output_qubit_indices(self) -> list[int]

Get qubit indices for all quantum outputs in order.

get_qubit_index_by_name
def get_qubit_index_by_name(self, name: str) -> Union[int, None]

Look up qubit index by Value name.


OutputMapping [source]

class OutputMapping

Maps Block output position to a physical resource.

Constructor
def __init__(
    self,
    output_index: int,
    value_uuid: str,
    value_name: str,
    kind: str,
    physical_index: Union[int, None],
    classical_value: Union[int, float, bool, None] = None,
) -> None
Attributes

QubitMapping [source]

class QubitMapping

Maps a logical Value to a physical qubit index.

Constructor
def __init__(self, value_uuid: str, value_name: str, qubit_index: int) -> None
Attributes

qamomile.circuit.transpiler.segments

Data structures for segmented quantum/classical execution plans.

Overview

ClassDescription
ClassicalSegmentA segment of pure classical operations.
ClassicalStepA classical execution step.
ExpvalSegmentA segment for expectation value computation.
ExpvalStepAn expectation-value execution step.
HybridBoundaryRepresents a measurement or encode operation at quantum/classical boundary.
MultipleQuantumSegmentsErrorRaised when a program cannot fit the single-quantum-segment model.
ProgramABIRuntime-visible ABI for a segmented program.
ProgramPlanExecution plan for a hybrid quantum/classical program.
QuantumSegmentA segment of pure quantum operations.
QuantumStepA quantum execution step.
SegmentBase class for separated computation segments.
SegmentKindType of computation segment.
SeparationErrorError during quantum/classical separation.
ValueA typed SSA value in the IR.

Constants

Classes

ClassicalSegment [source]

class ClassicalSegment(Segment)

A segment of pure classical operations.

Contains arithmetic, comparisons, and control flow. Will be executed directly in Python.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
) -> None
Attributes

ClassicalStep [source]

class ClassicalStep

A classical execution step.

Constructor
def __init__(self, segment: ClassicalSegment, role: str = 'classical') -> None
Attributes

ExpvalSegment [source]

class ExpvalSegment(Segment)

A segment for expectation value computation.

Represents computing <psi|H|psi> where psi is the quantum state and H is a Hamiltonian observable.

This segment bridges a quantum circuit (state preparation) to a classical expectation value.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
    hamiltonian_value: Value | None = None,
    qubits_value: Value | None = None,
    result_ref: str = '',
) -> None
Attributes

ExpvalStep [source]

class ExpvalStep

An expectation-value execution step.

Constructor
def __init__(self, segment: ExpvalSegment, quantum_step_index: int = 0) -> None
Attributes

HybridBoundary [source]

class HybridBoundary

Represents a measurement or encode operation at quantum/classical boundary.

These operations bridge quantum and classical segments.

Constructor
def __init__(
    self,
    operation: Operation,
    source_segment_index: int,
    target_segment_index: int,
    value_ref: str,
) -> None
Attributes

MultipleQuantumSegmentsError [source]

class MultipleQuantumSegmentsError(SeparationError)

Raised when a program cannot fit the single-quantum-segment model.

Qamomile enforces a single quantum circuit execution pattern:

[Classical Prep] → Quantum Circuit → [Classical Post/Expval]

The error fires when segmentation finds more than one quantum segment (classical work that must execute between two quantum regions, e.g. quantum operations resuming after a qmc.expval), or when a classical value feeding a quantum gate is also consumed by classical work and therefore cannot be absorbed into the quantum segment.

Note that a loop bound left as a runtime parameter is diagnosed earlier, by SymbolicShapeValidationPass, with a dedicated “Cannot unroll loop” message — it does not reach segmentation.

Example:

Incorrect — quantum operations resume after an expectation value,
which closes the quantum segment::

    @qmc.qkernel
    def kernel(obs: qmc.Observable) -> tuple[qmc.Float, qmc.Bit]:
        q = qmc.qubit("q")
        q = qmc.h(q)
        e = qmc.expval(q, obs)   # quantum segment ends here
        q2 = qmc.qubit("q2")
        q2 = qmc.x(q2)           # second quantum segment -> error
        return e, qmc.measure(q2)

Correct — keep all quantum operations in one contiguous region and
take the expectation value at the end::

    @qmc.qkernel
    def kernel(obs: qmc.Observable) -> qmc.Float:
        q = qmc.qubit("q")
        q = qmc.h(q)
        return qmc.expval(q, obs)

ProgramABI [source]

class ProgramABI

Runtime-visible ABI for a segmented program.

Constructor
def __init__(
    self,
    public_inputs: dict[str, ValueLike] = dict(),
    output_values: list[ValueLike] = list(),
) -> None
Attributes

ProgramPlan [source]

class ProgramPlan

Execution plan for a hybrid quantum/classical program.

Structure:

This plan enforces Qamomile’s current execution model: all quantum operations must be in a single quantum circuit.

Constructor
def __init__(
    self,
    steps: list[ProgramStep] = list(),
    abi: ProgramABI = ProgramABI(),
    boundaries: list[HybridBoundary] = list(),
    parameters: dict[str, Value] = dict(),
) -> None
Attributes

QuantumSegment [source]

class QuantumSegment(Segment)

A segment of pure quantum operations.

Contains quantum gates and qubit allocations. Will be emitted to a quantum circuit.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
    qubit_values: list[Value] = list(),
    num_qubits: int = 0,
) -> None
Attributes

QuantumStep [source]

class QuantumStep

A quantum execution step.

Constructor
def __init__(self, segment: QuantumSegment) -> None
Attributes

Segment [source]

class Segment(ABC)

Base class for separated computation segments.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
) -> None
Attributes

SegmentKind [source]

class SegmentKind(Enum)

Type of computation segment.

Attributes

SeparationError [source]

class SeparationError(QamomileCompileError)

Error during quantum/classical separation.


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 engine resource allocation. This applies to every Value regardless of its type (Qubit, Float, Bit, ...) -- it is not specific to qubits.


qamomile.circuit.transpiler.target

Protocols for explicit target planning and lowering pipelines.

Overview

ClassDescription
CompilationTargetDefine the contract implemented by every compilation target.
CompiledProgramPackage an artifact with its ABI, diagnostics, and provenance.
PreparedModuleHold a prepared entrypoint and its reachable callable definitions.

Classes

CompilationTarget [source]

class CompilationTarget(Protocol[PlanT, ArtifactT])

Define the contract implemented by every compilation target.

Attributes
Methods
compile
def compile(self, program: PreparedModule, plan: PlanT) -> CompiledProgram[ArtifactT]

Lower and materialize a prepared program for this target.

Parameters:

NameTypeDescription
programPreparedModulePrepared semantic program.
planPlanTDecisions returned by :meth:plan.

Returns:

CompiledProgram[ArtifactT] — CompiledProgram[ArtifactT]: Target-native artifact and metadata.

plan
def plan(self, program: PreparedModule) -> PlanT

Choose target-specific lowering decisions for a program.

Parameters:

NameTypeDescription
programPreparedModulePrepared semantic program.

Returns:

PlanT — Immutable target-specific compilation plan.

validate
def validate(self, artifact: ArtifactT) -> None

Validate a materialized artifact with target-native rules.

Parameters:

NameTypeDescription
artifactArtifactTTarget-native artifact to validate.

Raises:


CompiledProgram [source]

class CompiledProgram(Generic[ArtifactT])

Package an artifact with its ABI, diagnostics, and provenance.

Parameters:

NameTypeDescription
artifactArtifactTTarget-native circuit, graph, module, or package.
abiProgramABIRuntime-visible input and output contract.
metadataCompilationMetadataTarget and pipeline provenance.
diagnosticstuple[CompilationDiagnostic, ...]Non-fatal compilation diagnostics. Defaults to an empty tuple.
Constructor
def __init__(
    self,
    artifact: ArtifactT,
    abi: ProgramABI,
    metadata: CompilationMetadata,
    diagnostics: tuple[CompilationDiagnostic, ...] = (),
) -> None
Attributes

PreparedModule [source]

class PreparedModule

Hold a prepared entrypoint and its reachable callable definitions.

Parameters:

NameTypeDescription
entrypoint_refCallableRefStable symbol assigned to the program entrypoint.
entrypointBlockHierarchical semantic block for the entrypoint.
definitionsMapping[CallableRef, CallableDef]Reachable callable definitions keyed by their stable symbols.
definition_variantsMapping[CallableRef, tuple[CallableDef, ...]]Every distinct body observed for a symbol. Multiple variants of one origin may be valid for circuit-family inlining but must be handled or rejected by targets that emit one function per symbol.
call_graphMapping[CallableRef, frozenset[CallableRef]]Directed caller-to-callee relation, including the entrypoint symbol.
abiProgramABIClassical public input and output contract.
bindingsMapping[str, Any]Compile-time values retained for direct program-graph targets. Circuit-family targets receive the same values through their emit pass.
Constructor
def __init__(
    self,
    entrypoint_ref: CallableRef,
    entrypoint: Block,
    definitions: Mapping[CallableRef, CallableDef],
    definition_variants: Mapping[CallableRef, tuple[CallableDef, ...]],
    call_graph: Mapping[CallableRef, frozenset[CallableRef]],
    abi: ProgramABI,
    bindings: Mapping[str, Any],
) -> None
Attributes
Methods
body
def body(self, ref: CallableRef) -> Block

Return the semantic body associated with a program symbol.

Parameters:

NameTypeDescription
refCallableRefEntrypoint or callable symbol to resolve.

Returns:

Block — Hierarchical semantic body for ref.

Raises:

owned_snapshot
def owned_snapshot(self) -> PreparedModule

Create a deep, target-owned snapshot of prepared semantics.

The semantic IR intentionally remains mutable while compiler passes are being developed. Copying the entrypoint and definition registry as one object graph preserves shared callable bodies while preventing one target from mutating the source module observed by another.

Returns:

PreparedModule — Deep snapshot with read-only definition and call graph registries.


qamomile.circuit.transpiler.transpiler

Base transpiler class for engine-specific compilation.

Overview

FunctionDescription
count_inline_invokesCount all inlineable calls reachable from an operation list.
count_unrollable_inline_invokesCount inlineable calls the inline/partial-eval loop can still resolve.
lower_compile_time_ifs_preserving_loop_conditionsSpecialize compile-time branches without erasing loop conditions.
validate_bindings_parameters_disjointEnforce the project rule that bindings and parameters are disjoint.
validate_circuit_shot_contextReject shot context only in reachable circuit-family bodies.
without_static_bindingsRemove compile-time object bindings already consumed by qkernel build.
ClassDescription
AffineValidationPassValidate affine type semantics at IR level.
AnalyzePassAnalyze and validate an affine block.
ArrayBoundsValidationPassReject reachable element accesses and views outside array bounds.
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
CompileTimeIfLoweringPassLowers compile-time resolvable IfOperations before separation.
ConstantFoldingPassEvaluates constant expressions at compile time.
EmitPassBase class for engine-specific emission passes.
ExecutableProgramA fully compiled program ready for execution.
FrontendTransformErrorError during frontend AST-to-builder lowering.
InlinePassInline qkernel callables to create an affine block.
ParameterShapeResolutionPassSubstitute symbolic parameter array shape dims with concrete constants.
PartialEvaluationPassFold constants and lower compile-time control flow.
PreparedModuleHold a prepared entrypoint and its reachable callable definitions.
ProgramPlanExecution plan for a hybrid quantum/classical program.
QKernelLikeDescribe the frontend surface required by compiler entrypoints.
QamomileCompileErrorBase class for all Qamomile compilation errors.
QamomileCompilerPrepare Qamomile semantics and dispatch explicit target compilation.
SegmentationPassSegment a block into a strategy-specific executable program plan.
SliceBorrowCheckPassPost-fold linearity checker for sliced views and borrow state.
SubstitutionPassPass that substitutes call operations and callable strategies.
SymbolicShapeValidationPassReject unresolvable values that determine emitted circuit structure.
TranspilerBase class for engine-specific transpilers.

Constants

Functions

count_inline_invokes [source]

def count_inline_invokes(operations: list[Operation]) -> int

Count all inlineable calls reachable from an operation list.

Recurses into InverseBlockOperation / ControlledUOperation / SelectOperation nested blocks and into HasNestedOps bodies, so calls hidden inside control flow or operation-owned blocks are counted. unroll_recursion uses this as the primary termination signal (count == 0 means the block is fully inlined).

Parameters:

NameTypeDescription
operationslist[Operation]Operations to scan.

Returns:

int — Total number of inlineable calls reachable from operations.


count_unrollable_inline_invokes [source]

def count_unrollable_inline_invokes(operations: list[Operation]) -> int

Count inlineable calls the inline/partial-eval loop can still resolve.

This mirrors :func:count_inline_invokes but does not descend into a ControlledUOperation.block, an InverseBlockOperation’s nested blocks, or a SelectOperation case block. A call still inside one of those operation-owned blocks after a full inline pass is a self-recursive call that inline’s cycle guard could not unroll — it stops after one layer and does not re-enter the operation-owned block — so no later unroll_recursion iteration can resolve it. Folding compile-time ifs there never removes the trapped call itself. Such a call is therefore not unrollable. Calls at the top level or inside For / If / While bodies are unrollable and are counted.

The unroll loop uses this to tell two failure modes apart: a non-zero :func:count_inline_invokes with a zero count_unrollable_inline_invokes means every residual call is trapped inside a controlled / inverted block (i.e. a recursive qkernel was passed to qmc.control / qmc.inverse), as opposed to a genuinely non-terminating top-level recursion.

Parameters:

NameTypeDescription
operationslist[Operation]Operations to scan.

Returns:

int — Number of inlineable calls reachable without entering a ControlledUOperation.block, InverseBlockOperation nested block, or SelectOperation case block.


lower_compile_time_ifs_preserving_loop_conditions [source]

def lower_compile_time_ifs_preserving_loop_conditions(block: Block, bindings: dict[str, Any] | None = None) -> Block

Specialize compile-time branches without erasing loop conditions.

Parameters:

NameTypeDescription
blockBlockBlock whose resolvable compile-time branches should be lowered.
bindingsdict[str, Any] | NoneCompile-time input bindings used for condition resolution. Defaults to None.

Returns:

Block — Specialized block with loop-carried conditions preserved.

Raises:


validate_bindings_parameters_disjoint [source]

def validate_bindings_parameters_disjoint(bindings: dict[str, Any] | None, parameters: list[str] | None) -> None

Enforce the project rule that bindings and parameters are disjoint.

A kernel argument name must be resolved exactly one way: compile-time bound (in bindings, baked into the emitted circuit) or runtime symbolic (in parameters, surviving as an engine parameter). Listing the same name in both is ambiguous and historically caused silent miscompilation — the binding won the resolution race and the runtime parameter was silently dropped from the emitted circuit (see #354). This is the single shared checker so the rule is enforced identically at every entry point (QKernel.build / Transpiler.to_block / Transpiler.emit / Transpiler.transpile), not only in the top-level transpile wrapper.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneCompile-time bindings keyed by argument name, or None. None is treated as empty.
parameterslist[str] | NoneArgument names to keep as runtime parameters, or None. None is treated as empty.

Returns:

None — None

Raises:

Example:

>>> validate_bindings_parameters_disjoint({"theta": 0.5}, ["phi"])
>>> validate_bindings_parameters_disjoint({"theta": 0.5}, ["theta"])
Traceback (most recent call last):
    ...
ValueError: Parameter name(s) ['theta'] appear in both ...

validate_circuit_shot_context [source]

def validate_circuit_shot_context(block: Block, bindings: dict[str, Any] | None, *, target: str) -> None

Reject shot context only in reachable circuit-family bodies.

Circuit lowering selects engine-generic callable decompositions using the circuit_ir selector. Backend-specific alternatives are metadata for other consumers and must not impose their capabilities here. Specialize operation-owned bodies in their own parameter scope before inspecting them, just as the entrypoint is inspected after pruning.

Parameters:

NameTypeDescription
blockBlockPartially evaluated circuit entrypoint.
bindingsdict[str, Any] | NoneCompile-time entrypoint bindings.
targetstrTarget name used in capability errors.

Raises:


without_static_bindings [source]

def without_static_bindings(
    input_types: Mapping[str, Any],
    bindings: Mapping[str, Any] | None,
) -> dict[str, Any]

Remove compile-time object bindings already consumed by qkernel build.

Parameters:

NameTypeDescription
input_typesMapping[str, Any]QKernel input annotations by name.
bindingsMapping[str, Any] | NoneUser-provided compile-time values.

Returns:

dict[str, Any] — dict[str, Any]: Ordinary scalar, array, and structural bindings only.

Classes

AffineValidationPass [source]

class AffineValidationPass(Pass[Block, Block])

Validate affine type semantics at IR level.

This pass serves as a safety net to catch affine type violations that may have bypassed the frontend checks. It verifies that each quantum value is used (consumed) at most once. It does NOT detect “never consumed” / silent-discard patterns; the branch-internal and loop-body discard cases are rejected separately by reject_control_flow_quantum_discard in qamomile.circuit.transpiler.passes.analyze.

Input: Block (any kind) Output: Same Block (unchanged, validation only)

Attributes
Methods
run
def run(self, input: Block) -> Block

Validate affine type semantics in the block.

Raises:


AnalyzePass [source]

class AnalyzePass(Pass[Block, Block])

Analyze and validate an affine block.

This pass:

  1. Builds a dependency graph between values (used locally for validation)

  2. Validates that quantum ops don’t depend on non-parameter classical results

  3. Checks that block inputs/outputs are classical

Input: Block with BlockKind.AFFINE Output: Block with BlockKind.ANALYZED

Attributes
Methods
run
def run(self, input: Block) -> Block

Analyze the block and validate dependencies.


ArrayBoundsValidationPass [source]

class ArrayBoundsValidationPass(Pass[Block, Block])

Reject reachable element accesses and views outside array bounds.

This pass runs after partial evaluation has resolved binding-dependent slice extents and before declarative slice operations are stripped. It deliberately skips statically zero-trip loop bodies so an unreachable access does not become a false-positive compilation error. Exact loop replay is capped by MAX_STATIC_REPLAY_TRIPS; the conservative fallback validates one reachable body instance, including first-iteration constants when available, and never publishes speculative final results.

Attributes
Methods
run
def run(self, input: Block) -> Block

Validate reachable array element operands in one semantic block.

Parameters:

NameTypeDescription
inputBlockPost-partial-evaluation affine or hierarchical block whose concrete array extents should be checked.

Returns:

Block — input unchanged when every reachable access and view is valid or still symbolic.

Raises:


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.


BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

CompileTimeIfLoweringPass [source]

class CompileTimeIfLoweringPass(Pass[Block, Block])

Lowers compile-time resolvable IfOperations before separation.

After constant folding, some IfOperation conditions are statically known but remain as control-flow nodes. SegmentationPass treats them as segment boundaries, causing MultipleQuantumSegmentsError for classical-only compile-time if after quantum init.

This pass:

  1. Evaluates conditions including expression-derived ones (CompOp, CondOp, NotOp, BinOp, and UnaryMathOp chains).

  2. Replaces resolved IfOperations with selected-branch operations.

  3. Substitutes merge output UUIDs with selected-branch values in all subsequent operations and block outputs.

Constructor
def __init__(
    self,
    bindings: dict[str, Any] | None = None,
    *,
    preserved_condition_uuids: AbstractSet[str] | None = None,
    _under_controlled_unitary: bool = False,
    _active_block_ids: frozenset[int] | None = None,
)

Initialize compile-time if lowering state.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneCompile-time bindings visible in the current block. Defaults to no bindings.
preserved_condition_uuidsAbstractSet[str] | NoneConditions that must remain unresolved so a later validation pass can inspect their dataflow. Defaults to an empty set.
_under_controlled_unitaryboolInternal context flag indicating that boxed callables encountered here will be decomposed by the controlled emission walker and therefore need their owned bodies lowered too. Defaults to False.
_active_block_idsfrozenset[int] | NoneInternal recursion-path guard for operation-owned blocks. Defaults to an empty set.
Attributes
Methods
run
def run(self, input: Block) -> Block

Lower every compile-time resolvable IfOperation in the block.

Parameters:

NameTypeDescription
inputBlockBlock to lower. Must be TRACED, AFFINE, or HIERARCHICAL. TRACED is accepted so the circuit drawer can resolve bound/constant if conditions on a freshly traced block before the transpiler pipeline runs; HIERARCHICAL is accepted during the self-recursion unroll loop. Surviving inline callable invocations are passed through untouched in both cases.

Returns:

Block — New block with compile-time ifs replaced by their selected-branch operations and merge outputs substituted. The input’s BlockKind is preserved.

Raises:


ConstantFoldingPass [source]

class ConstantFoldingPass(Pass[Block, Block])

Evaluates constant expressions at compile time.

This pass folds BinOp operations when all operands are constants or bound parameters, eliminating unnecessary classical operations that would otherwise split quantum segments.

Example:

Before (with bindings={"phase": 0.5}):
    BinOp(phase * 2) -> classical segment split

After:
    Constant 1.0 -> no segment split
Constructor
def __init__(self, bindings: dict[str, Any] | None = None, *, strip_slice_ops: bool = True)

Create a constant-folding pass.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneCompile-time parameter bindings used when folding BinOps that reference declared parameters.
strip_slice_opsboolWhen True (default), removes SliceArrayOperation nodes after folding. Set to False when a downstream pass — notably SliceBorrowCheckPass — still needs to observe slice declaration points in program order to decide view liveness. A separate strip pass must then run after the linearity check so segmentation still sees a pure quantum-op stream.
Attributes
Methods
run
def run(self, input: Block) -> Block

Fold resolvable classical values throughout a block.

Parameters:

NameTypeDescription
inputBlockAffine or hierarchical block to rewrite.

Returns:

Block — Copy with folded operations and output values.

Raises:


EmitPass [source]

class EmitPass(Pass[ProgramPlan, ExecutableProgram[T]], Generic[T])

Base class for engine-specific emission passes.

Subclasses implement _emit_quantum_segment() to generate engine-specific quantum circuits.

Input: ProgramPlan Output: ExecutableProgram with compiled segments

Constructor
def __init__(
    self,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
)

Initialize with optional parameter bindings.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneValues to bind parameters to. If not provided, parameters must be bound at execution time.
parameterslist[str] | NoneList of parameter names to preserve as engine parameters.

Raises:

Attributes
Methods
run
def run(self, input: ProgramPlan) -> ExecutableProgram[T]

Emit engine code from a program plan.

Parameters:

NameTypeDescription
inputProgramPlanSegmented plan whose quantum and classical steps should be compiled.

Returns:

ExecutableProgram[T] — ExecutableProgram[T]: Executable program containing all compiled segments and the public output contract.

Raises:


ExecutableProgram [source]

class ExecutableProgram(Generic[T])

A fully compiled program ready for execution.

Contains compiled quantum, classical, and expectation-value segments. Use sample() for multi-shot execution or run() for single execution.

Example:

executable = transpiler.compile(kernel)

# Sample: multiple shots, returns counts
job = executable.sample(executor, shots=1000)
result = job.result()  # SampleResult with counts

# Run: single shot, returns typed result
job = executable.run(executor)
result = job.result()  # Returns kernel's return type
Constructor
def __init__(
    self,
    plan: ProgramPlan | None = None,
    compiled_quantum: list[CompiledQuantumSegment[T]] = list(),
    compiled_classical: list[CompiledClassicalSegment] = list(),
    compiled_expval: list[CompiledExpvalSegment] = list(),
    output_values: list[ValueLike] = list(),
) -> None
Attributes
Methods
get_circuits
def get_circuits(self) -> list[T]

Get all quantum circuits in execution order.

get_first_circuit
def get_first_circuit(self) -> T | None

Get the first quantum circuit, or None if no quantum segments.

restore
def restore(
    self,
    executor: QuantumExecutor[T],
    snapshot: JobSnapshot,
    bindings: dict[str, Any] | None = None,
) -> SampleJob[Any] | RunJob[Any] | ExpvalJob

Restore saved executions with this program’s typed result ABI.

Snapshots retain provider identifiers, completed local raw values, and ordered execution groups. Legacy flat provider snapshots remain supported. Reuse the same compiled program and pass the original runtime bindings explicitly to reproduce classical pre- and post-processing. Credentials, arbitrary bindings, and Python callables are not saved. Restoration reconnects to remote jobs without resubmitting or waiting for results; local values need no provider restoration support.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine adapter configured with the provider credentials and target used by the original job.
snapshotJobSnapshotSnapshot returned by the original public job’s snapshot() method.
bindingsdict[str, Any] | NoneOriginal runtime parameter bindings. Defaults to None for parameter-free programs.

Returns:

SampleJob[Any] | RunJob[Any] | ExpvalJob — SampleJob[Any] | RunJob[Any] | ExpvalJob: Restored lazy job with the same typed public result conversion as a new execution.

Raises:

Example:

>>> original = executable.sample(executor, shots=1000)
>>> snapshot = original.snapshot()
>>> restored = executable.restore(executor, snapshot)
>>> restored.result()
run
def run(
    self,
    executor: QuantumExecutor[T],
    bindings: dict[str, Any] | None = None,
    *,
    estimation: EstimationAccuracy | None = None,
) -> RunJob[Any] | ExpvalJob

Submit one execution and return its lazy result job.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine-specific quantum executor.
bindingsdict[str, Any] | NoneParameter bindings. Supports three formats: - Vector: {“gammas”: [0.1, 0.2], “betas”: [0.3, 0.4]} - Dict parameter: {“coeffs”: {0: 0.1, (0, 1): 0.2}}, decomposed per key onto the emitted parameters - Indexed: {“gammas[0]”: 0.1, “coeffs[(0, 1)]”: 0.2}
estimationEstimationAccuracy | NoneOptional per-execution expectation accuracy policy. Defaults to the executor’s configured behavior.

Returns:

RunJob[Any] | ExpvalJob — RunJob[Any] | ExpvalJob: A RunJob that resolves to the kernel’s return type, or an ExpvalJob when the program contains an expectation-value computation.

Raises:

Example:

job = executable.run(executor, bindings={"gamma": [0.5]})
result = job.result()
print(result)  # 0.25 (for QFixed) or (0, 1) (for bits)
sample
def sample(
    self,
    executor: QuantumExecutor[T],
    shots: int = 1024,
    bindings: dict[str, Any] | None = None,
) -> SampleJob[Any]

Submit a multi-shot execution and return its lazy job.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Engine-specific quantum executor.
shotsintNumber of shots to run.
bindingsdict[str, Any] | NoneParameter bindings. Supports three formats: - Vector: {“gammas”: [0.1, 0.2], “betas”: [0.3, 0.4]} - Dict parameter: {“coeffs”: {0: 0.1, (0, 1): 0.2}}, decomposed per key onto the emitted parameters - Indexed: {“gammas[0]”: 0.1, “coeffs[(0, 1)]”: 0.2}

Returns:

SampleJob[Any] — SampleJob[Any]: A job that resolves to a SampleResult with the per-bitstring counts.

Raises:

Example:

job = executable.sample(executor, shots=1000, bindings={"gamma": [0.5]})
result = job.result()
print(result.results)  # [(0.25, 500), (0.75, 500)]

FrontendTransformError [source]

class FrontendTransformError(QamomileCompileError)

Error during frontend AST-to-builder lowering.


InlinePass [source]

class InlinePass(Pass[Block, Block])

Inline qkernel callables to create an affine block.

This pass recursively inlines function calls while preserving control flow structures (For, If, While).

Input: Block with BlockKind.HIERARCHICAL (may contain callable calls) Output: Block with BlockKind.AFFINE (no inline callable calls)

Parameters:

NameTypeDescription
body_selectorCallable[[InvokeOperation], Block | None] | NoneOptional body-selection hook for consumers whose configured strategy differs from InvokeOperation.strategy_name. The standard compiler leaves this unset. Defaults to None.
preserve_bound_quantum_identityboolWhether cloned callee quantum values should retain the logical owner and array-element address of their bound caller operands. Resource liveness analysis enables this so an inline call does not create phantom owners or erase lane identities. Defaults to False.
preserve_bound_array_identityboolWhether cloned callee array values should retain the logical lineage of bound caller arrays. Resource classical-state analysis enables this so loop-carried stores remain connected across an inlined call. Defaults to False.
Constructor
def __init__(
    self,
    body_selector: Callable[[InvokeOperation], Block | None] | None = None,
    *,
    inline_prefix_factory: Callable[[InvokeOperation, tuple[tuple[ArrayValue, tuple[ArrayValue, ...]], ...]], Sequence[Operation]] | None = None,
    preserve_bound_quantum_identity: bool = False,
    preserve_bound_array_identity: bool = False,
) -> None

Initialize the pass with body-selection and identity policies.

Parameters:

NameTypeDescription
body_selectorCallable[[InvokeOperation], Block | None] | NoneConsumer-specific selector used for inline-policy calls. Defaults to the invocation’s ordinary effective body.
preserve_bound_quantum_identityboolWhether cloned quantum SSA values descending from a formal input retain the actual caller operand’s logical owner and array-element address. Defaults to False.
preserve_bound_array_identityboolWhether cloned array SSA values descending from a formal input retain the actual caller array’s logical lineage. Defaults to False.
Attributes
Methods
run
def run(self, input: Block) -> Block

Inline all inline-policy callable invocations.

Self-recursive qkernel invocations are unrolled one level per call: the inner self-call is substituted but left intact so the outer fixed-point loop can fold the base-case if between iterations. The output kind is AFFINE when no inlineable calls remain, otherwise HIERARCHICAL.


ParameterShapeResolutionPass [source]

class ParameterShapeResolutionPass(Pass[Block, Block])

Substitute symbolic parameter array shape dims with concrete constants.

Input: BlockKind.HIERARCHICAL (runs before InlinePass). Output: same block kind, with matching shape dim Values constant-folded.

Constructor
def __init__(self, bindings: dict[str, Any] | None = None) -> None

Initialize parameter-shape resolution.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneCompile-time bindings keyed by entrypoint argument name. Defaults to None.
Attributes
Methods
run
def run(self, input: Block) -> Block

Replace resolvable symbolic array dimensions with constants.

Parameters:

NameTypeDescription
inputBlockHierarchical semantic block to rewrite.

Returns:

Block — Rewritten block preserving all display, ABI, parameter, and stage metadata.

Raises:


PartialEvaluationPass [source]

class PartialEvaluationPass(Pass[Block, Block])

Fold constants and lower compile-time control flow.

Constructor
def __init__(self, bindings: dict[str, Any] | None = None)
Attributes
Methods
run
def run(self, input: Block) -> Block

Fold constants and lower compile-time control flow.

Parameters:

NameTypeDescription
inputBlockBlock to evaluate. AFFINE in the normal pipeline; HIERARCHICAL is also accepted for the self-recursion unroll loop (see inline comment).

Returns:

Block — Block with constants folded and compile-time-resolvable IfOperations lowered.

Raises:


PreparedModule [source]

class PreparedModule

Hold a prepared entrypoint and its reachable callable definitions.

Parameters:

NameTypeDescription
entrypoint_refCallableRefStable symbol assigned to the program entrypoint.
entrypointBlockHierarchical semantic block for the entrypoint.
definitionsMapping[CallableRef, CallableDef]Reachable callable definitions keyed by their stable symbols.
definition_variantsMapping[CallableRef, tuple[CallableDef, ...]]Every distinct body observed for a symbol. Multiple variants of one origin may be valid for circuit-family inlining but must be handled or rejected by targets that emit one function per symbol.
call_graphMapping[CallableRef, frozenset[CallableRef]]Directed caller-to-callee relation, including the entrypoint symbol.
abiProgramABIClassical public input and output contract.
bindingsMapping[str, Any]Compile-time values retained for direct program-graph targets. Circuit-family targets receive the same values through their emit pass.
Constructor
def __init__(
    self,
    entrypoint_ref: CallableRef,
    entrypoint: Block,
    definitions: Mapping[CallableRef, CallableDef],
    definition_variants: Mapping[CallableRef, tuple[CallableDef, ...]],
    call_graph: Mapping[CallableRef, frozenset[CallableRef]],
    abi: ProgramABI,
    bindings: Mapping[str, Any],
) -> None
Attributes
Methods
body
def body(self, ref: CallableRef) -> Block

Return the semantic body associated with a program symbol.

Parameters:

NameTypeDescription
refCallableRefEntrypoint or callable symbol to resolve.

Returns:

Block — Hierarchical semantic body for ref.

Raises:

owned_snapshot
def owned_snapshot(self) -> PreparedModule

Create a deep, target-owned snapshot of prepared semantics.

The semantic IR intentionally remains mutable while compiler passes are being developed. Copying the entrypoint and definition registry as one object graph preserves shared callable bodies while preventing one target from mutating the source module observed by another.

Returns:

PreparedModule — Deep snapshot with read-only definition and call graph registries.


ProgramPlan [source]

class ProgramPlan

Execution plan for a hybrid quantum/classical program.

Structure:

This plan enforces Qamomile’s current execution model: all quantum operations must be in a single quantum circuit.

Constructor
def __init__(
    self,
    steps: list[ProgramStep] = list(),
    abi: ProgramABI = ProgramABI(),
    boundaries: list[HybridBoundary] = list(),
    parameters: dict[str, Value] = dict(),
) -> None
Attributes

QKernelLike [source]

class QKernelLike(Protocol)

Describe the frontend surface required by compiler entrypoints.

This protocol is intentionally structural. It lets decorator-created composites reuse the qkernel inspection and build interface without making them inherit from QKernel or exposing the compiler-facing callable descriptor model as a frontend concept.

Attributes
Methods
build
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> Block

Build a traced body block.

Parameters:

NameTypeDescription
parameterslist[str] | NoneRuntime parameter names to preserve. Defaults to None.
**kwargsAnyCompile-time bindings for non-parameter arguments.

Returns:

Block — Traced hierarchical body block.


QamomileCompileError [source]

class QamomileCompileError(Exception)

Base class for all Qamomile compilation errors.


QamomileCompiler [source]

class QamomileCompiler

Prepare Qamomile semantics and dispatch explicit target compilation.

Parameters:

NameTypeDescription
configCompilerConfig | NoneShared frontend and substitution configuration. Defaults to :class:CompilerConfig.
Constructor
def __init__(self, config: CompilerConfig | None = None) -> None

Initialize the target-neutral compiler.

Parameters:

NameTypeDescription
configCompilerConfig | NoneShared frontend configuration. Defaults to :class:CompilerConfig.
Attributes
Methods
compile
def compile(
    self,
    kernel: QKernelLike,
    target: CompilationTarget[PlanT, ArtifactT],
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> CompiledProgram[ArtifactT]

Compile a qkernel with an explicit target implementation.

Parameters:

NameTypeDescription
kernelQKernelLikeTop-level qkernel-like entrypoint.
targetCompilationTarget[PlanT, ArtifactT]Target planner, lowerer, materializer, and validator.
bindingsdict[str, Any] | NoneCompile-time bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.

Returns:

CompiledProgram[ArtifactT] — CompiledProgram[ArtifactT]: Validated target-native artifact.

Raises:

prepare
def prepare(
    self,
    kernel: QKernelLike,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> PreparedModule

Prepare a hierarchical semantic module without destroying calls.

Parameters:

NameTypeDescription
kernelQKernelLikeTop-level qkernel-like entrypoint.
bindingsdict[str, Any] | NoneCompile-time bindings used for tracing and shape resolution. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.

Returns:

PreparedModule — Program-level semantic input for target planning.

Raises:

to_block
def to_block(
    self,
    kernel: QKernelLike,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> Block

Trace a qkernel-like object into a hierarchical semantic block.

Parameters:

NameTypeDescription
kernelQKernelLikeFrontend object to trace.
bindingsdict[str, Any] | NoneCompile-time argument values. Defaults to None.
parameterslist[str] | NoneArgument names retained as runtime parameters. Defaults to None.

Returns:

Block — Hierarchical Qamomile semantic block.

Raises:


SegmentationPass [source]

class SegmentationPass(Pass[Block, ProgramPlan])

Segment a block into a strategy-specific executable program plan.

This pass:

  1. Materializes return operations (syncs output_values from ReturnOperation)

  2. Splits the operation list into quantum and classical segments

  3. Builds a ProgramPlan via the configured segmentation strategy

Input: Block (typically ANALYZED or AFFINE) Output: ProgramPlan

Constructor
def __init__(self, strategy: SegmentationStrategy | None = None) -> None
Attributes
Methods
run
def run(self, input: Block) -> ProgramPlan

Lower and segment a block into a program plan.

Parameters:

NameTypeDescription
inputBlockBlock whose while contract and hybrid operations should be lowered before segmentation.

Returns:

ProgramPlan — Strategy-produced execution plan.

Raises:


SliceBorrowCheckPass [source]

class SliceBorrowCheckPass(Pass[Block, Block])

Post-fold linearity checker for sliced views and borrow state.

Runs after :class:ConstantFoldingPass (so slice bounds are concrete where possible) and before segmentation / emit. Walks the operations of the root block in order, maintaining a borrow state map modelled on the frontend’s :attr:ArrayBase._borrowed_indices — a single dict whose values are slice-view ArrayValue owners or the _ConsumedSlotMarker sentinel. Creating a direct element borrow (q[i]) emits no IR operation, but later operand uses remain visible to this pass; the frontend validator handles an unreturned borrow with no observable operand use.

The pass does not flag a leftover slice view at block end — slice views are affine at the kernel boundary, mirroring how element borrows behave on a locally-allocated register (the frontend’s qamomile.circuit.frontend.func_to_block._validate_returned_arrays covers the genuine leak: returning the parent with a live borrow). Anything that actually clashes with a live view (direct slot access, destructive parent consume, overlapping views, use-after-destroy) is rejected at the eager check points listed in the module docstring.

Constructor
def __init__(self) -> None

Initialize per-run mutable state to safe defaults.

Attributes
Methods
run
def run(self, input: Block) -> Block

Run the borrow tracker over input.

Parameters:

NameTypeDescription
inputBlockBlock to check. Expected to be in AFFINE or HIERARCHICAL kind — post-fold but pre-segmentation.

Returns:

Block — The same block unchanged after successful validation.

Raises:


SubstitutionPass [source]

class SubstitutionPass(Pass[Block, Block])

Pass that substitutes call operations and callable strategies.

This pass traverses the block and applies substitution rules:

The pass preserves the block structure and only modifies matching operations.

Input: Block (any kind) Output: Block with substitutions applied (same kind as input)

Constructor
def __init__(self, config: SubstitutionConfig) -> None

Initialize the pass with configuration.

Parameters:

NameTypeDescription
configSubstitutionConfigSubstitution configuration with rules
Attributes
Methods
run
def run(self, input: Block) -> Block

Apply substitutions to the block.

Parameters:

NameTypeDescription
inputBlockBlock to transform

Returns:

Block — Block with substitutions applied


SymbolicShapeValidationPass [source]

class SymbolicShapeValidationPass(Pass[Block, Block])

Reject unresolvable values that determine emitted circuit structure.

Runs two checks on every ForOperation bound, symbolic SELECT index width, and symbolic controlled-unitary structural field, walking nested control flow and operation-owned SELECT/control blocks recursively:

  1. Unresolved parameter array shape dims, recognized by the {array}_dim{i} naming convention.

  2. Bounds whose dataflow traces back to a runtime parameter (an entry of Block.parameters), directly or through classical arithmetic. Dependencies on enclosing loop variables are exempt — those resolve during emit-time unrolling.

Input: BlockKind.ANALYZED (runs after AnalyzePass). Output: same block unchanged, or raises QamomileCompileError.

Attributes
Methods
run
def run(self, input: Block) -> Block

Validate compile-time structure throughout the analyzed block.

Checks loop bounds, SELECT widths, and controlled-unitary structural fields at top level, in ordinary control-flow bodies, and in operation-owned SELECT/control blocks.

Parameters:

NameTypeDescription
inputBlockThe block to validate. Must be BlockKind.ANALYZED; other kinds pass through unchanged (the pass is defensive and avoids false positives on partially-built IR).

Returns:

Block — input, unchanged, when validation succeeds.

Raises:


Transpiler [source]

class Transpiler(ABC, Generic[T])

Base class for engine-specific transpilers.

Provides the full compilation pipeline from qkernel-like frontend objects to executable programs.

Example:

>>> from qamomile.circuit.transpiler import TranspilerConfig
>>> from qamomile.qiskit import QiskitTranspiler
>>> transpiler = QiskitTranspiler()
>>> executable = transpiler.transpile(kernel, bindings={"theta": 0.5})
>>> circuit = executable.get_first_circuit()
>>> config = TranspilerConfig.with_strategies({"qft": "approximate_k2"})
>>> transpiler.set_config(config)
Attributes
Methods
affine_validate
def affine_validate(self, block: Block) -> Block

Pass 1.5: Validate affine type semantics.

This is a safety net to catch affine type violations that may have bypassed frontend checks. Validates that quantum values are used at most once.

analyze
def analyze(self, block: Block) -> Block

Pass 2: Validate and analyze dependencies.

array_bounds_check
def array_bounds_check(self, block: Block) -> Block

Pass 1.85: Reject reachable accesses outside resolved array bounds.

Runs after :meth:partial_eval so binding-dependent view extents and indices are concrete where possible, and before declarative slice operations are stripped. Statically zero-trip loop bodies are skipped because their element accesses are unreachable.

Parameters:

NameTypeDescription
blockBlockPost-fold affine or hierarchical block to validate.

Returns:

Block — The input block unchanged after successful validation.

Raises:

classical_lowering
def classical_lowering(self, block: Block) -> Block

Pass 2.25: Lower measurement-derived classical ops.

Identifies CompOp / CondOp / NotOp / BinOp instances whose operand dataflow traces back to a measurement and rewrites them to RuntimeClassicalExpr. Compile-time-foldable and emit-time-foldable (loop-bound, parameter-bound) classical ops are left unchanged.

Runs after analyze so the measurement-taint analysis has the full dependency graph available, and before validate_symbolic_shapes / plan / emit so downstream passes can rely on the cleaner IR (in particular: future segmentation work can dispatch on RuntimeClassicalExpr type instead of the BitType-only heuristic).

constant_fold
def constant_fold(self, block: Block, bindings: dict[str, Any] | None = None) -> Block

Pass 1.5: Fold constant expressions.

Evaluates BinOp operations when all operands are constants or bound parameters. This prevents quantum segment splitting from parametric expressions like phase * 2.

emit
def emit(
    self,
    separated: ProgramPlan,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> ExecutableProgram[T]

Pass 4: Generate engine-specific code.

Parameters:

NameTypeDescription
separatedProgramPlanThe separated program to emit
bindingsdict[str, Any] | NoneParameter values to bind at compile time
parameterslist[str] | NoneParameter names to preserve as engine parameters

Raises:

executor
def executor(self, **kwargs: Any = {}) -> QuantumExecutor[T]

Create a quantum executor for this engine.

inline
def inline(self, block: Block) -> Block

Pass 1: Inline all inline-policy callable invocations.

lower_compile_time_ifs
def lower_compile_time_ifs(self, block: Block, bindings: dict[str, Any] | None = None) -> Block

Pass 1.75: Lower compile-time resolvable IfOperations.

Evaluates IfOperation conditions (including expression-derived conditions via CompOp/CondOp/NotOp) and replaces resolved ones with selected-branch operations. Merge outputs are substituted with selected-branch values throughout the block.

This prevents SegmentationPass from seeing classical-only compile-time IfOperations that would otherwise split quantum segments.

partial_eval
def partial_eval(self, block: Block, bindings: dict[str, Any] | None = None) -> Block

Pass 1.75: Fold constants and lower compile-time control flow.

plan
def plan(self, block: Block) -> ProgramPlan

Pass 3: Lower and split into a program plan.

Validates C→Q→C pattern with single quantum segment.

plan_circuit
def plan_circuit(
    self,
    prepared: PreparedModule,
    bindings: dict[str, Any] | None = None,
) -> ProgramPlan

Lower a prepared semantic module into the circuit execution model.

This is the destructive circuit-family path: inline-policy calls are flattened, compile-time structure is evaluated, affine and borrow invariants are checked, measurement-dependent classical expressions are classified, and the result is segmented into C-to-Q-to-C steps. Program-graph targets must compile :class:PreparedModule directly instead of invoking this method.

Parameters:

NameTypeDescription
preparedPreparedModuleHierarchical semantic program returned by :meth:prepare.
bindingsdict[str, Any] | NoneCompile-time bindings used for recursion unrolling and partial evaluation. Defaults to None.

Returns:

ProgramPlan — Circuit-family host-orchestrated execution plan.

Raises:

prepare
def prepare(
    self,
    kernel: QKernelLike,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> PreparedModule

Prepare a qkernel for target-specific planning and lowering.

This phase preserves callable boundaries. It performs tracing, entrypoint validation, configured substitutions, and parameter-shape resolution, then collects the reachable callable graph into a program-level semantic view.

Parameters:

NameTypeDescription
kernelQKernelLikeQKernel or qkernel-like frontend object to prepare as a top-level entrypoint.
bindingsdict[str, Any] | NoneCompile-time values used while tracing and resolving parameter shapes. Defaults to None.
parameterslist[str] | NoneArgument names preserved as runtime parameters. Defaults to None.

Returns:

PreparedModule — Hierarchical entrypoint, reachable callables, call graph, and public ABI.

Raises:

resolve_parameter_shapes
def resolve_parameter_shapes(self, block: Block, bindings: dict[str, Any] | None = None) -> Block

Pass 0.75: Resolve symbolic Vector parameter shape dims.

Qamomile circuits are compile-time fixed-structure. Parameter Vector[Float] / Vector[UInt] inputs carry symbolic {name}_dim{i} shape Values so frontend code like arr.shape[0] returns a usable handle. This pass looks at bindings and, for every parameter array that has a concrete binding, substitutes those symbolic dims with constants so that downstream loop-bound resolution sees fixed lengths.

Parameters without a concrete binding are left as-is; their symbolic dims are harmless as long as no compile-time structure decision depends on them (the library QAOA pattern).

set_config
def set_config(self, config: TranspilerConfig) -> None

Set the transpiler configuration.

Parameters:

NameTypeDescription
configTranspilerConfigTranspiler configuration to use
slice_borrow_check
def slice_borrow_check(self, block: Block) -> Block

Pass 1.9: Post-fold slice-view linearity checker.

Runs after :meth:partial_eval has resolved slice bounds to concrete values. Catches the slice-view linearity violations that the trace-time frontend check cannot detect on its own — specifically, slices whose bounds were symbolic at trace time (so the frontend bulk-borrow tracker had to skip them) and aliasing scenarios that only become visible once those bounds are folded to constants:

  1. A view whose newly-concrete coverage overlaps another live view of the same root parent.

  2. A view whose newly-concrete coverage hits a slot that was consumed by a destructive operation earlier in the block.

  3. Slice ownership changes that cannot be represented safely across control-flow boundaries.

Creating a direct element borrow (q[i]) emits no IR operation, so this pass cannot observe the borrow site itself. Later uses of that element do appear as operation operands and are checked for conflicts with live slice views. Trace-time validation in :func:qamomile.circuit.frontend.func_to_block._validate_returned_arrays covers unreturned direct-element borrows that have no observable operand use.

The pass is a pass-through for the IR — it only raises on violations and leaves the block unchanged on success.

Parameters:

NameTypeDescription
blockBlockPost-fold affine or hierarchical block to validate.

Returns:

Block — The input block unchanged after successful validation.

Raises:

strip_slice_ops
def strip_slice_ops(self, block: Block) -> Block

Pass 1.95: Remove SliceArrayOperation nodes from the block.

PartialEvaluationPass keeps these declarative ops through constant folding so :meth:slice_borrow_check can use them as view-declaration markers. Once the linearity check has run, segmentation and downstream passes expect a classical-op-free quantum stream — this pass performs that cleanup.

substitute
def substitute(self, block: Block) -> Block

Pass 0.5: Apply substitutions (optional).

This pass rewrites inline callable targets and sets strategy names on boxed InvokeOperations based on config.

Parameters:

NameTypeDescription
blockBlockBlock to transform

Returns:

Block — Block with substitutions applied

to_block
def to_block(
    self,
    kernel: QKernelLike,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> Block

Convert a qkernel-like frontend object to a Block.

Parameters:

NameTypeDescription
kernelQKernelLikeQKernel or qkernel-like frontend object to convert.
bindingsdict[str, Any] | NoneConcrete values to bind at trace time, including values used to resolve array shapes.
parameterslist[str] | NoneNames to keep as unbound runtime parameters.

Returns:

Block — Hierarchical block for the frontend object.

Raises:

Always uses kernel.build() so Python defaults, required arguments, runtime parameters, and array shapes follow one validated entry path.

to_circuit
def to_circuit(self, kernel: QKernelLike, bindings: dict[str, Any] | None = None) -> T

Compile and extract just the quantum circuit.

This is a convenience method for when you just want the engine circuit without the full executable.

Parameters:

NameTypeDescription
kernelQKernelLikeQKernel or qkernel-like frontend object to compile.
bindingsdict[str, Any] | NoneParameter values to bind.

Returns:

T — Engine-specific quantum circuit.

transpile
def transpile(
    self,
    kernel: QKernelLike,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> ExecutableProgram[T]

Full compilation pipeline from a qkernel-like object to executable.

Parameters:

NameTypeDescription
kernelQKernelLikeQKernel or qkernel-like frontend object to compile.
bindingsdict[str, Any] | NoneParameter values to bind (also resolves array shapes). Names in bindings and parameters must be disjoint — a name is either compile-time bound or runtime symbolic, never both.
parameterslist[str] | NoneParameter names to preserve as engine parameters. Scalars/arrays of float/int/UInt are supported, plus Dict[K, Float]: each constant-key subscript lookup (d[key]) becomes one engine parameter named "d[<key>]", and the execution-time binding bindings={"d": {...}} is decomposed per key onto those parameters. A Dict runtime parameter is recorded in Block.param_slots as a slot whose type is a DictType (compile-time-bound Dicts and Tuple arguments stay out of the slot manifest); its emitted per-key parameters are visible via ExecutableProgram.parameter_names.

Returns:

ExecutableProgram[T] — ExecutableProgram[T]: Executable wrapping the engine circuit and the parameter metadata needed to re-bind runtime parameters, ready for execution.

Raises:

Pipeline:

  1. prepare: Trace and validate the entrypoint, apply configured substitutions, resolve parameter shapes, and preserve the reachable callable graph.

  2. plan_circuit: Inline inline-policy calls, unroll recursion, validate affine and borrow rules, partially evaluate compile-time structure, analyze dependencies, and segment the program into the host-orchestrated C-to-Q-to-C model.

  3. lower: Convert each quantum segment to immutable, engine-neutral CircuitProgram IR.

  4. legalize: Select native intrinsics and Pauli-evolution realizations from target capabilities and compilation policy.

  5. verify: Prove circuit structure and target legality before constructing engine objects.

  6. materialize: Convert the legalized circuit IR to engine-native artifacts and preserve the executable ABI.

unroll_recursion
def unroll_recursion(self, block: Block, bindings: dict[str, Any] | None = None) -> Block

Fixed-point loop of inline and branch lowering for recursion.

Each iteration unrolls one layer of self-referential inline callable invocation and then lowers its compile-time base-case IfOperation. Loop-carried Bit conditions remain visible until the final validation pass so first-iteration constants cannot erase a real backedge read. Terminates when no inline callable invocation remains (success), when every residual call is trapped inside an operation-owned block whose recursive callable contract is unsupported (control / inverse / select over a recursive kernel — raises a targeted error, see below), or when MAX_UNROLL_DEPTH is reached (genuinely non-terminating top-level recursion — raises).

Parameters:

NameTypeDescription
blockBlockThe block to unroll. May be HIERARCHICAL (still containing self-referential callable invocations) or already AFFINE (returned unchanged).
bindingsdict[str, Any] | NoneCompile-time bindings used by condition lowering to select the base case. Defaults to None, meaning no bindings are applied.

Returns:

Block — The fully unrolled, AFFINE block once no inline callable invocation remains. Returned unchanged when the input already has no calls.

Raises:

validate_symbolic_shapes
def validate_symbolic_shapes(self, block: Block) -> Block

Pass 2.5: Reject unresolvable ForOperation loop bounds.

Runs after analyze so dependency info is complete. Raises QamomileCompileError with an actionable message when a gamma_dim0-style symbolic Value reaches a ForOperation bound without being folded to a constant by ParameterShapeResolutionPass, or when a loop bound depends (directly or through classical arithmetic) on a runtime parameter — loop bounds are compile-time structure and must be provided via bindings, not parameters.

Parameters:

NameTypeDescription
blockBlockThe analyzed block to validate.

Returns:

Block — block, unchanged, when validation succeeds.

Raises:


qamomile.circuit.transpiler.value_resolver

Unified value resolution for transpiler passes.

Several transpiler passes need to resolve an IR Value to a concrete Python value (int, float, bool). Each pass previously carried its own copy of the resolution logic with slightly different lookup orders and naming conventions.

ValueResolver consolidates those into a single class with a deterministic resolution order:

  1. Context map — caller-supplied UUID → concrete value dict (e.g. folded_values, concrete_values).

  2. Container metadata — whole compile-time arrays and dictionaries.

  3. Constant — value.is_constant() → value.get_const().

  4. Compile-time array element — arr[i] or arr[a:b][i] resolves from the root array’s const_array metadata or binding.

  5. Bindings by parameter name — value.is_parameter() → bindings[param_name]. This is the only name-keyed rule: resolution never falls back to the display Value.name, which is excluded from canonical hashing and carries no binding provenance.

  6. Returns None if none of the above match.

Overview

ClassDescription
ArrayValueAn array of typed IR values.
ValueA typed SSA value in the IR.
ValueResolverResolve IR Values to concrete Python values.

Classes

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:

bool — True iff slice_of is non-None.

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

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 engine resource allocation. This applies to every Value regardless of its type (Qubit, Float, Bit, ...) -- it is not specific to qubits.


ValueResolver [source]

class ValueResolver

Resolve IR Values to concrete Python values.

Parameters:

NameTypeDescription
contextdict[str, Any] | NoneUUID-keyed map of already resolved values. The values may be either raw Python scalars or Value objects; if a Value is found its get_const() is extracted automatically.
bindingsdict[str, Any] | NoneName-keyed parameter bindings supplied by the user at transpile time.
Constructor
def __init__(
    self,
    context: dict[str, Any] | None = None,
    bindings: dict[str, Any] | None = None,
)

Create a resolver with optional context and bindings.

Parameters:

NameTypeDescription
contextdict[str, Any] | NoneUUID-keyed map of already-resolved values. Defaults to None.
bindingsdict[str, Any] | NoneName-keyed parameter bindings supplied by the user. Defaults to None.
Methods
resolve
def resolve(self, value: Any) -> Any | None

Resolve a Value-like object to a concrete Python value.

If value is not a Value-like object (no uuid attribute) it is returned as-is — the caller already has a concrete value.

Parameters:

NameTypeDescription
valueAnyThe Value-like object or already concrete value to resolve.

Returns:

Any | None — Any | None: The resolved concrete value, the original concrete value for non-Value inputs, or None when no resolution rule applies.