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:

boolTrue 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 | NoneNone 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 | NoneNone 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 | NoneNone 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:

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

boolTrue 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_foldcompile_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 | NoneNone 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:

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

boolTrue 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_foldcompile_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:

Anylhs 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. AnyNone 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.Anyint, 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.Anyint, 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:

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

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

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

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

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

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

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

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

Valuetrue_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_foldcompile_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 o