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 ABIPreparedModule 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¶
Keep semantic IR abstract and lower late. Per-qubit encoding, native gate selection, transformed-call expansion, and runtime control-flow syntax are target concerns. Segmentation lowers semantics only when separating host and quantum execution requires it.
Use an immutable circuit boundary. Circuit engines consume verified
CircuitProgramvalues rather than walking mutable semantic IR or sharing engine objects through emit-context side channels. The current semantic-to-circuit implementation reuses the established walk internally, but that walker is not an engine extension API.Make target pipelines explicit. A
CompilationTargetowns planning, lowering/materialization, and native validation. Circuit targets declare the complete input language accepted by their materializer; shared legalization fixes realization choices and target verification enforces that declaration before native object construction begins.Preserve dependency direction. This package and
qamomile.circuitdo not import SDK engines. Engine packages depend on the public compiler, circuit-IR, executable, and artifact contracts.Keep
bindingsandparametersdisjoint. Bindings determine compile-time values and structure; parameters survive as runtime artifact inputs. Overlap is rejected before compilation, and structural decisions such as classical-value branches and range bounds must use bindings.Keep the common user surface small. Engine users normally interact with an engine
Transpilerand executor. Materializers, source writers, and engine artifact wrappers are implementation details unless a target exposes a distinct native compilation product intentionally.
Overview¶
| Function | Description |
|---|---|
aggregate_typed_results | Combine counts whose converted public result values are equal. |
dict_param_key | Format the engine-parameter name for one entry of a Dict parameter. |
flatten_user_bindings | Flatten public arrays and dictionaries into scalar ABI keys. |
inline_callables | Expand inline-policy callables once with the compiler’s default policy. |
lower_compile_time_ifs_preserving_loop_conditions | Specialize compile-time branches without erasing loop conditions. |
pair_block_operands | Pair all block inputs with category-grouped call-site operands. |
prepare_module | Collect a hierarchical block into an immutable program-level view. |
validate_program_graph_semantics | Validate shared semantics for a direct program-graph target. |
| Class | Description |
|---|---|
CallableDefinitionConflictError | Report two incompatible definitions claiming one callable symbol. |
ClassicalExecutor | Executes classical segments in Python. |
ClassicalSegment | A segment of pure classical operations. |
CompilationDiagnostic | Describe one target-independent or target-specific diagnostic. |
CompilationMetadata | Record how a target artifact was produced. |
CompilationTarget | Define the contract implemented by every compilation target. |
CompiledProgram | Package an artifact with its ABI, diagnostics, and provenance. |
CompilerConfig | Configure semantic preparation and target-independent rewrites. |
CompletedExecutionHandle | Wrap an already available result for synchronous executors. |
CompositeExecutionHandle | Aggregate several independently submitted executions. |
DiagnosticSeverity | Classify the severity of a compilation diagnostic. |
EmitError | Report an engine failure to emit one semantic operation. |
Exact | Request an analytic expectation value without shot noise. |
ExecutionCapabilities | Declare the execution features implemented by one executor. |
ExecutionContext | Holds global state during program execution. |
ExecutionError | Error during program execution. |
ExecutionHandle | Expose an engine execution without forcing immediate result retrieval. |
ExecutionReference | Store secret-free identifiers needed to restore remote execution. |
ExecutionSnapshot | Store a remote leaf, a local value, or an ordered execution group. |
ExecutionSnapshotKind | Identify the reconstruction contract of an execution snapshot node. |
ExpvalJob | Job for expectation value computation. |
Job | Abstract base class for quantum execution jobs. |
JobKind | Identify the public operation needed to reconstruct a typed job. |
JobSnapshot | Store operation metadata and lossless raw execution reconstruction. |
JobStatus | Describe a provider-independent execution state. |
MappedExecutionHandle | Lazily transform another execution handle’s result. |
PreparedModule | Hold a prepared entrypoint and its reachable callable definitions. |
ProgramABI | Runtime-visible ABI for a segmented program. |
QKernelLike | Describe the frontend surface required by compiler entrypoints. |
QamomileCompiler | Prepare Qamomile semantics and dispatch explicit target compilation. |
RunJob | Job for single execution. |
SampleResult | Result of a sample() execution. |
ShotBased | Request a shot-based expectation value. |
TargetCapabilityError | A program requires a capability the selected target does not declare. |
TargetPrecision | Request an expectation value at a provider target precision. |
Constants¶
EstimationAccuracy:TypeAlias=Exact | ShotBased | TargetPrecisionTranspilerConfig=CompilerConfigBackward name for :class:CompilerConfigduring engine migration.
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:
| Name | Type | Description |
|---|---|---|
results | Iterable[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) -> strFormat 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:
| Name | Type | Description |
|---|---|---|
dict_name | str | The kernel argument name of the Dict parameter. |
key | Any | The 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:
| Name | Type | Description |
|---|---|---|
bindings | Mapping[str, Any] | None | Raw 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,
) -> BlockExpand 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:
| Name | Type | Description |
|---|---|---|
block | Block | Hierarchical or traced semantic block to rewrite. |
body_selector | Callable[[InvokeOperation], Block | None] | None | Optional 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:
QubitConsumedError— If an invocation binds the same quantum resource to multiple formal operands.
lower_compile_time_ifs_preserving_loop_conditions [source]¶
def lower_compile_time_ifs_preserving_loop_conditions(block: Block, bindings: dict[str, Any] | None = None) -> BlockSpecialize compile-time branches without erasing loop conditions.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Block whose resolvable compile-time branches should be lowered. |
bindings | dict[str, Any] | None | Compile-time input bindings used for condition resolution. Defaults to None. |
Returns:
Block — Specialized block with loop-carried conditions preserved.
Raises:
ValidationError— If specialization encounters invalid IR.
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:
| Name | Type | Description |
|---|---|---|
block | Block | Operation-owned block whose inputs are being bound. |
operands | Sequence[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) -> PreparedModuleCollect 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:
| Name | Type | Description |
|---|---|---|
entrypoint | Block | Hierarchical entrypoint after target-independent frontend preparation. |
bindings | Mapping[str, Any] | None | Compile-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) -> NoneValidate 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:
| Name | Type | Description |
|---|---|---|
program | PreparedModule | Prepared entrypoint and callable bodies. |
Raises:
ValidationError— If a while condition is not measurement-backed.AffineTypeError— If structured control flow discards a quantum value.QubitConsumedError— If callable inlining binds one quantum resource to multiple formal operands.
Classes¶
CallableDefinitionConflictError [source]¶
class CallableDefinitionConflictError(QamomileCompileError)Report two incompatible definitions claiming one callable symbol.
Parameters:
| Name | Type | Description |
|---|---|---|
symbol | str | Fully 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) -> NoneInitialize a callable-definition collision diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
symbol | str | Fully qualified callable symbol with conflicting definitions. |
Attributes¶
symbol: str
ClassicalExecutor [source]¶
class ClassicalExecutorExecutes 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:
| Name | Type | Description |
|---|---|---|
segment | ClassicalSegment | Ordered classical operations and declared outputs to evaluate. |
context | ExecutionContext | Per-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:
ExecutionError— If an operation is unsupported or a required runtime value is unavailable.
resolve_value¶
def resolve_value(self, value: ValueLike, context: ExecutionContext) -> AnyResolve a typed classical output using the execution interpreter.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ValueLike | Scalar, array, tuple, or dictionary output. |
context | ExecutionContext | Runtime bindings and computed values keyed by their IR identities or public parameter names. |
Returns:
Any — Concrete value with tuple and dictionary structure retained.
Raises:
ExecutionError— If a required value is absent from the context and its compile-time metadata.
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(),
) -> NoneAttributes¶
kind: SegmentKind
CompilationDiagnostic [source]¶
class CompilationDiagnosticDescribe one target-independent or target-specific diagnostic.
Parameters:
| Name | Type | Description |
|---|---|---|
severity | DiagnosticSeverity | Diagnostic severity. |
message | str | Human-readable explanation. |
code | str | None | Stable machine-readable diagnostic code. |
source | str | None | Optional source location or IR provenance label. |
Constructor¶
def __init__(
self,
severity: DiagnosticSeverity,
message: str,
code: str | None = None,
source: str | None = None,
) -> NoneAttributes¶
code: str | Nonemessage: strseverity: DiagnosticSeveritysource: str | None
CompilationMetadata [source]¶
class CompilationMetadataRecord how a target artifact was produced.
Parameters:
| Name | Type | Description |
|---|---|---|
target | str | Stable compilation target name. |
pipeline | str | Lowering-family or pipeline name. |
properties | Mapping[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(),
) -> NoneAttributes¶
pipeline: strproperties: Mapping[str, Any]target: str
CompilationTarget [source]¶
class CompilationTarget(Protocol[PlanT, ArtifactT])Define the contract implemented by every compilation target.
Attributes¶
name: str Return the stable target name.
Methods¶
compile¶
def compile(self, program: PreparedModule, plan: PlanT) -> CompiledProgram[ArtifactT]Lower and materialize a prepared program for this target.
Parameters:
| Name | Type | Description |
|---|---|---|
program | PreparedModule | Prepared semantic program. |
plan | PlanT | Decisions returned by :meth:plan. |
Returns:
CompiledProgram[ArtifactT] — CompiledProgram[ArtifactT]: Target-native artifact and metadata.
plan¶
def plan(self, program: PreparedModule) -> PlanTChoose target-specific lowering decisions for a program.
Parameters:
| Name | Type | Description |
|---|---|---|
program | PreparedModule | Prepared semantic program. |
Returns:
PlanT — Immutable target-specific compilation plan.
validate¶
def validate(self, artifact: ArtifactT) -> NoneValidate a materialized artifact with target-native rules.
Parameters:
| Name | Type | Description |
|---|---|---|
artifact | ArtifactT | Target-native artifact to validate. |
Raises:
Exception— If target-native validation rejects the artifact.
CompiledProgram [source]¶
class CompiledProgram(Generic[ArtifactT])Package an artifact with its ABI, diagnostics, and provenance.
Parameters:
| Name | Type | Description |
|---|---|---|
artifact | ArtifactT | Target-native circuit, graph, module, or package. |
abi | ProgramABI | Runtime-visible input and output contract. |
metadata | CompilationMetadata | Target and pipeline provenance. |
diagnostics | tuple[CompilationDiagnostic, ...] | Non-fatal compilation diagnostics. Defaults to an empty tuple. |
Constructor¶
def __init__(
self,
artifact: ArtifactT,
abi: ProgramABI,
metadata: CompilationMetadata,
diagnostics: tuple[CompilationDiagnostic, ...] = (),
) -> NoneAttributes¶
abi: ProgramABIartifact: ArtifactTdiagnostics: tuple[CompilationDiagnostic, ...]metadata: CompilationMetadata
CompilerConfig [source]¶
class CompilerConfigConfigure semantic preparation and target-independent rewrites.
Parameters:
| Name | Type | Description |
|---|---|---|
decomposition | DecompositionConfig | Composite-gate decomposition choices. Defaults to the standard decomposition configuration. |
substitutions | SubstitutionConfig | Callable substitution rules. Defaults to no substitutions. |
Constructor¶
def __init__(
self,
decomposition: DecompositionConfig = DecompositionConfig(),
substitutions: SubstitutionConfig = SubstitutionConfig(),
) -> NoneAttributes¶
decomposition: DecompositionConfigsubstitutions: SubstitutionConfig
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:
| Name | Type | Description |
|---|---|---|
strategy_overrides | dict[str, str] | None | Gate-name to strategy mapping. Defaults to an empty mapping. |
**kwargs | Any | Additional :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:
| Name | Type | Description |
|---|---|---|
value | ResultT | Completed execution value. |
Constructor¶
def __init__(self, value: ResultT) -> NoneInitialize an immediately completed execution.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ResultT | Completed execution value. |
Methods¶
result¶
def result(self, timeout: float | None = None) -> ResultTReturn the completed value without waiting.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Ignored compatibility timeout. |
Returns:
ResultT — Stored execution value.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture the already available raw result without waiting.
Returns:
ExecutionSnapshot — Owned, type-preserving local value.
Raises:
TypeError— If the value contains unsupported result objects.ValueError— If the value is nonfinite or cyclic.
status¶
def status(self) -> JobStatusReturn the completed status.
Returns:
JobStatus — Always :attr:JobStatus.COMPLETED.
CompositeExecutionHandle [source]¶
class CompositeExecutionHandle(ExecutionHandle[tuple[ResultT, ...]])Aggregate several independently submitted executions.
Parameters:
| Name | Type | Description |
|---|---|---|
handles | Sequence[ExecutionHandle[ResultT]] | Child executions in stable result order. |
Constructor¶
def __init__(self, handles: Sequence[ExecutionHandle[ResultT]]) -> NoneInitialize an ordered execution aggregate.
Parameters:
| Name | Type | Description |
|---|---|---|
handles | Sequence[ExecutionHandle[ResultT]] | Child executions. |
Attributes¶
native: object | None Return every child provider-native task.
Methods¶
cancel¶
def cancel(self) -> NoneAttempt 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:
ExceptionGroup— If any child status lookup or cancellation fails.
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) -> objectReturn 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:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Total local wait budget in seconds. |
Returns:
tuple[ResultT, ...] — tuple[ResultT, ...]: Ordered child results.
Raises:
TimeoutError— If the total wait budget expires.Exception— Any child execution failure.
result_async¶
def result_async(self, timeout: float | None = None) -> tuple[ResultT, ...]Return all child results asynchronously.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Total local wait budget in seconds. |
Returns:
tuple[ResultT, ...] — tuple[ResultT, ...]: Ordered child results.
Raises:
TimeoutError— If the total wait budget expires.Exception— Any child execution failure.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture all children with their original tuple boundaries.
Returns:
ExecutionSnapshot — Ordered nested execution structure.
Raises:
ValueError— If a child has no supported reconstruction contract.TypeError— If a local child contains unsupported result objects.
status¶
def status(self) -> JobStatusAggregate 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¶
ERRORINFOWARNING
EmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
operation
Exact [source]¶
class ExactRequest an analytic expectation value without shot noise.
Constructor¶
def __init__(self) -> NoneExecutionCapabilities [source]¶
class ExecutionCapabilitiesDeclare the execution features implemented by one executor.
Parameters:
| Name | Type | Description |
|---|---|---|
supports_async_sampling | bool | Whether sampling submission returns before provider execution completes. Defaults to False. |
supports_async_estimation | bool | Whether expectation submission returns before provider execution completes. Defaults to False. |
supports_estimation | bool | Whether expectation-value execution is implemented. Defaults to False. |
supports_cancellation | bool | Whether provider-backed handles can request cancellation. Defaults to False. |
supports_restoration | bool | Whether execution references can recreate provider-backed handles. Defaults to False. |
supports_native_batch | bool | Whether multiple logical requests can be submitted through one provider-native batch or job. Defaults to False. |
supports_native_parameter_inputs | bool | Whether runtime values remain separate from emitted circuits during provider submission. Defaults to False. |
estimation_accuracy | frozenset[EstimationPolicyType] | Explicit per-request accuracy policies accepted by the executor. An empty set means only executor-configured estimation behavior is available. |
Raises:
ValueError— If an unknown estimation policy type is declared or estimation features are declared without estimation support.
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(),
) -> NoneAttributes¶
estimation_accuracy: frozenset[EstimationPolicyType]supports_async_estimation: boolsupports_async_sampling: boolsupports_cancellation: boolsupports_estimation: boolsupports_native_batch: boolsupports_native_parameter_inputs: boolsupports_restoration: bool
ExecutionContext [source]¶
class ExecutionContextHolds 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) -> Anyget_many¶
def get_many(self, keys: list[str]) -> dict[str, Any]has¶
def has(self, key: str) -> boolset¶
def set(self, key: str, value: Any) -> Noneupdate¶
def update(self, values: dict[str, Any]) -> NoneExecutionError [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¶
native: object | None Return the wrapped provider-native task when available.
Methods¶
cancel¶
def cancel(self) -> NoneRequest 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) -> objectReturn 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) -> ResultTWait for and return the engine-neutral raw result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. None delegates the wait policy to the provider. |
Returns:
ResultT — Raw result normalized by the engine executor.
Raises:
TimeoutError— If the local wait expires before completion.
result_async¶
def result_async(self, timeout: float | None = None) -> ResultTWait asynchronously for the engine-neutral raw result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. Defaults to provider behavior when None. |
Returns:
ResultT — Raw result normalized by the engine executor.
Raises:
TimeoutError— If the local wait expires before completion.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture 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:
ValueError— If references are absent or their grouping is unknown.
status¶
def status(self) -> JobStatusReturn the current provider-independent execution status.
Returns:
JobStatus — Current normalized status.
ExecutionReference [source]¶
class ExecutionReferenceStore secret-free identifiers needed to restore remote execution.
Parameters:
| Name | Type | Description |
|---|---|---|
provider | str | Stable provider or adapter name. |
job_ids | tuple[str, ...] | One or more provider job identifiers. |
target | str | None | Provider target or device identifier. Defaults to None. |
group_id | str | None | Session, batch, program, or parent identifier. Defaults to None. |
context | Mapping[str, str] | Additional non-secret identifiers needed to restore the job. Defaults to an empty mapping. |
Raises:
ValueError— If the provider name or any job identifier is empty.TypeError— If identifiers or context have incompatible types.
Constructor¶
def __init__(
self,
provider: str,
job_ids: tuple[str, ...],
target: str | None = None,
group_id: str | None = None,
context: Mapping[str, str] = dict(),
) -> NoneAttributes¶
context: Mapping[str, str]group_id: str | Nonejob_ids: tuple[str, ...]provider: strtarget: str | None
Methods¶
from_dict¶
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionReferenceReconstruct a provider reference from JSON-compatible data.
Parameters:
| Name | Type | Description |
|---|---|---|
data | Mapping[str, Any] | Mapping produced by :meth:to_dict. |
Returns:
ExecutionReference — Validated provider execution reference.
Raises:
KeyError— If a required provider or job identifier field is absent.TypeError— If a field has an incompatible type.ValueError— If provider or job identifiers are empty.
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 ExecutionSnapshotStore 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:
| Name | Type | Description |
|---|---|---|
kind | str | ExecutionSnapshotKind | One of remote, local, or composite, normalized to an enum member. |
reference | ExecutionReference | None | Required only for remote leaves. |
value | Any | Supported native result for local leaves. Defaults to None. |
children | tuple[ExecutionSnapshot, ...] | Ordered composite children. Defaults to an empty tuple. |
Raises:
TypeError— If fields or local result types are unsupported.ValueError— If fields conflict with the node kind or values are invalid.
Constructor¶
def __init__(
self,
kind: str | ExecutionSnapshotKind,
reference: ExecutionReference | None = None,
value: Any = None,
children: tuple[ExecutionSnapshot, ...] = (),
) -> NoneAttributes¶
children: tuple[ExecutionSnapshot, ...]kind: str | ExecutionSnapshotKindreference: ExecutionReference | Nonevalue: Any
Methods¶
from_dict¶
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionSnapshotReconstruct an execution tree with strict node and value validation.
Parameters:
| Name | Type | Description |
|---|---|---|
data | Mapping[str, Any] | Mapping produced by :meth:to_dict. |
Returns:
ExecutionSnapshot — Validated execution structure.
Raises:
TypeError— If node fields have incompatible types.ValueError— If kinds, fields, references, or local values are invalid.
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:
TypeError— If mutable reference fields became incompatible.ValueError— If mutable reference fields became invalid.
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:
| Name | Type | Description |
|---|---|---|
restore_reference | Callable[[ExecutionReference], ExecutionHandle[Any]] | Provider-specific callback for one complete remote leaf. |
Returns:
ExecutionHandle[Any] — ExecutionHandle[Any]: Reconstructed raw execution lifecycle.
Raises:
TypeError— If local data is unsupported or the callback returns an incompatible handle.ValueError— If local values or references became invalid.Exception— If the provider restoration callback fails.
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:
TypeError— If mutable local data was changed to unsupported types.ValueError— If mutable local data or references became invalid.
ExecutionSnapshotKind [source]¶
class ExecutionSnapshotKind(StrEnum)Identify the reconstruction contract of an execution snapshot node.
Attributes¶
COMPOSITELOCALREMOTE
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]) -> NoneInitialize expval job.
Parameters:
| Name | Type | Description |
|---|---|---|
exp_val | float | ExecutionHandle[float] | Completed value or deferred expectation execution. |
Methods¶
result¶
def result(self, timeout: float | None = None) -> floatWait for and return the expectation value.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
float — Expectation value.
result_async¶
def result_async(self, timeout: float | None = None) -> floatWait asynchronously for and return the expectation value.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum 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,
) -> NoneInitialize a public job around an execution handle.
Parameters:
| Name | Type | Description |
|---|---|---|
handle | ExecutionHandle[Any] | Raw or mapped engine execution. |
kind | JobKind | Public operation represented by the job. |
shots | int | None | Sampling shot count. Defaults to None for run jobs. |
Attributes¶
native: object | None Return the wrapped provider-native task when available.
Methods¶
cancel¶
def cancel(self) -> NoneRequest 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) -> objectReturn 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) -> TWait for and return the result.
Blocks until the job completes.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. None uses provider behavior. |
Returns:
T — Execution result with the appropriate public type.
Raises:
ExecutionError— If the job failed.
result_async¶
def result_async(self, timeout: float | None = None) -> TWait asynchronously for and return the public result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. Defaults to provider behavior when None. |
Returns:
T — Execution result with the appropriate public type.
snapshot¶
def snapshot(self) -> JobSnapshotCapture 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:
ValueError— If execution grouping or mapping cannot be restored, or a local value is nonfinite or cyclic.TypeError— If a local result contains unsupported objects.
status¶
def status(self) -> JobStatusReturn 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¶
RUNSAMPLE
JobSnapshot [source]¶
class JobSnapshotStore 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:
| Name | Type | Description |
|---|---|---|
kind | JobKind | Public operation that created the job. |
executions | tuple[ExecutionReference, ...] | Ordered provider reference inventory. Empty for entirely local structured executions. For legacy snapshots, these references also specify the result layout. |
shots | int | None | Sampling shot count. Required for sample jobs and absent for run jobs. |
execution | ExecutionSnapshot | None | Ordered remote/local execution tree. None denotes the legacy flat-reference format. When present, executions must exactly match its remote leaves. |
Raises:
ValueError— If legacy references are empty, the reference inventory disagrees with the tree, or shots disagree with the operation kind.TypeError— If operation kind, references, tree, or shots have incompatible types.
Constructor¶
def __init__(
self,
kind: JobKind,
executions: tuple[ExecutionReference, ...],
shots: int | None = None,
execution: ExecutionSnapshot | None = None,
) -> NoneAttributes¶
execution: ExecutionSnapshot | Noneexecutions: tuple[ExecutionReference, ...]kind: JobKindshots: int | None
Methods¶
from_dict¶
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> JobSnapshotReconstruct a validated snapshot from JSON-compatible data.
Parameters:
| Name | Type | Description |
|---|---|---|
data | Mapping[str, Any] | Mapping produced by :meth:to_dict. |
Returns:
JobSnapshot — Validated typed-job restoration snapshot.
Raises:
KeyError— If operation kind, references, or a version 2 tree is absent.TypeError— If metadata, references, or local values have wrong types.ValueError— If a version, field, tree, or reference is invalid.
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:
TypeError— If local values were mutated to unsupported types.ValueError— If local values or references were mutated to invalid data.
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¶
CANCELLEDCANCELLINGCOMPLETEDFAILEDPARTIALPENDINGQUEUEDRUNNINGUNKNOWN
MappedExecutionHandle [source]¶
class MappedExecutionHandle(ExecutionHandle[MappedT], Generic[ResultT, MappedT])Lazily transform another execution handle’s result.
Parameters:
| Name | Type | Description |
|---|---|---|
source | ExecutionHandle[ResultT] | Underlying execution handle. |
transform | Callable[[ResultT], MappedT] | Result transformation. |
snapshot_source | bool | Whether 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,
) -> NoneInitialize a lazy mapped execution.
Parameters:
| Name | Type | Description |
|---|---|---|
source | ExecutionHandle[ResultT] | Underlying execution handle. |
transform | Callable[[ResultT], MappedT] | Result transformation. |
snapshot_source | bool | Allow source snapshots only when the owner rebuilds the transformation on restore. Defaults to False. |
Attributes¶
native: object | None Return the source provider-native task.
Methods¶
cancel¶
def cancel(self) -> NoneForward 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) -> objectReturn 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) -> MappedTRetrieve and transform the source result once.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
MappedT — Cached transformed result.
Raises:
Exception— Any source or transformation failure.
result_async¶
def result_async(self, timeout: float | None = None) -> MappedTRetrieve and transform the source result asynchronously.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
MappedT — Cached transformed result.
Raises:
Exception— Any source or transformation failure.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture 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:
ValueError— If the mapping has no declared restoration contract.TypeError— If a local source value cannot be saved.
status¶
def status(self) -> JobStatusReturn the source execution status.
Returns:
JobStatus — Current mapped execution status.
PreparedModule [source]¶
class PreparedModuleHold a prepared entrypoint and its reachable callable definitions.
Parameters:
| Name | Type | Description |
|---|---|---|
entrypoint_ref | CallableRef | Stable symbol assigned to the program entrypoint. |
entrypoint | Block | Hierarchical semantic block for the entrypoint. |
definitions | Mapping[CallableRef, CallableDef] | Reachable callable definitions keyed by their stable symbols. |
definition_variants | Mapping[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_graph | Mapping[CallableRef, frozenset[CallableRef]] | Directed caller-to-callee relation, including the entrypoint symbol. |
abi | ProgramABI | Classical public input and output contract. |
bindings | Mapping[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],
) -> NoneAttributes¶
abi: ProgramABIbindings: Mapping[str, Any]call_graph: Mapping[CallableRef, frozenset[CallableRef]]definition_variants: Mapping[CallableRef, tuple[CallableDef, ...]]definitions: Mapping[CallableRef, CallableDef]entrypoint: Blockentrypoint_ref: CallableRef
Methods¶
body¶
def body(self, ref: CallableRef) -> BlockReturn the semantic body associated with a program symbol.
Parameters:
| Name | Type | Description |
|---|---|---|
ref | CallableRef | Entrypoint or callable symbol to resolve. |
Returns:
Block — Hierarchical semantic body for ref.
Raises:
KeyError— Ifrefis neither the entrypoint nor a reachable body-backed callable definition.
owned_snapshot¶
def owned_snapshot(self) -> PreparedModuleCreate 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 ProgramABIRuntime-visible ABI for a segmented program.
Constructor¶
def __init__(
self,
public_inputs: dict[str, ValueLike] = dict(),
output_values: list[ValueLike] = list(),
) -> NoneAttributes¶
output_values: list[ValueLike]public_inputs: dict[str, ValueLike]
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¶
block: Block Return the cached hierarchical body block.effects: KernelEffect Return cached semantic effects of the qkernel body.input_types: dict[str, Any] Return frontend input annotations by parameter name.name: str Return the user-facing callable name.output_types: list[Any] Return frontend output annotations.signature: inspect.Signature Return the Python call signature.
Methods¶
build¶
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> BlockBuild a traced body block.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | list[str] | None | Runtime parameter names to preserve. Defaults to None. |
**kwargs | Any | Compile-time bindings for non-parameter arguments. |
Returns:
Block — Traced hierarchical body block.
QamomileCompiler [source]¶
class QamomileCompilerPrepare Qamomile semantics and dispatch explicit target compilation.
Parameters:
| Name | Type | Description |
|---|---|---|
config | CompilerConfig | None | Shared frontend and substitution configuration. Defaults to :class:CompilerConfig. |
Constructor¶
def __init__(self, config: CompilerConfig | None = None) -> NoneInitialize the target-neutral compiler.
Parameters:
| Name | Type | Description |
|---|---|---|
config | CompilerConfig | None | Shared frontend configuration. Defaults to :class:CompilerConfig. |
Attributes¶
config
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:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | Top-level qkernel-like entrypoint. |
target | CompilationTarget[PlanT, ArtifactT] | Target planner, lowerer, materializer, and validator. |
bindings | dict[str, Any] | None | Compile-time bindings. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
Returns:
CompiledProgram[ArtifactT] — CompiledProgram[ArtifactT]: Validated target-native artifact.
Raises:
Exception— If semantic preparation, target compilation, or target-native validation fails.
prepare¶
def prepare(
self,
kernel: QKernelLike,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> PreparedModulePrepare a hierarchical semantic module without destroying calls.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | Top-level qkernel-like entrypoint. |
bindings | dict[str, Any] | None | Compile-time bindings used for tracing and shape resolution. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
Returns:
PreparedModule — Program-level semantic input for target planning.
Raises:
ValueError— If bindings overlap runtime parameters.EntrypointValidationError— If the top-level kernel has quantum inputs or outputs.
to_block¶
def to_block(
self,
kernel: QKernelLike,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> BlockTrace a qkernel-like object into a hierarchical semantic block.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | Frontend object to trace. |
bindings | dict[str, Any] | None | Compile-time argument values. Defaults to None. |
parameters | list[str] | None | Argument names retained as runtime parameters. Defaults to None. |
Returns:
Block — Hierarchical Qamomile semantic block.
Raises:
ValueError— Ifbindingsandparametersoverlap or frontend argument construction fails.TypeError— If specialization is requested for a block-only qkernel-like object that has nobuildmethod.
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,
) -> NoneInitialize run job.
Parameters:
| Name | Type | Description |
|---|---|---|
raw_counts | dict[str, int] | ExecutionHandle[dict[str, int]] | None | Counts or deferred counts. May be None with value_handle. |
result_converter | Callable[[str], T] | None | Function converting one bitstring. May be None with value_handle. |
value_handle | ExecutionHandle[T] | None | Handle already producing the final public value. Defaults to None. |
Raises:
ValueError— If neither a valid counts source norvalue_handleis supplied.
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:
| Name | Type | Description |
|---|---|---|
handle | ExecutionHandle[T] | Final-value execution handle. |
Returns:
RunJob[T] — RunJob[T]: Public run job delegating to handle.
result¶
def result(self, timeout: float | None = None) -> TWait for and return the single public result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
T — Public kernel return value.
result_async¶
def result_async(self, timeout: float | None = None) -> TWait asynchronously for the single public result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum 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) -> NoneAttributes¶
results: list[tuple[T, int]] List of (value, count) tuples.shots: int Total number of shots executed.
Methods¶
most_common¶
def most_common(self, n: int = 1) -> list[tuple[T, int]]Return the n most common results.
Parameters:
| Name | Type | Description |
|---|---|---|
n | int | Number 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 ShotBasedRequest a shot-based expectation value.
Parameters:
| Name | Type | Description |
|---|---|---|
shots | int | Positive number of measurement shots. |
Raises:
ValueError— Ifshotsis not positive.
Constructor¶
def __init__(self, shots: int) -> NoneAttributes¶
shots: int
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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable diagnosis naming the target and the missing capability. |
target | str | None | Declared target name. Defaults to None. |
operation | str | None | Instruction 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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable diagnosis naming the target and the missing capability. |
target | str | None | Declared target name. Defaults to None. |
operation | str | None | Instruction description that triggered the failure. Defaults to None. |
Attributes¶
target: str | None
TargetPrecision [source]¶
class TargetPrecisionRequest an expectation value at a provider target precision.
Parameters:
| Name | Type | Description |
|---|---|---|
precision | float | Positive absolute target precision. |
Raises:
ValueError— Ifprecisionis not positive.
Constructor¶
def __init__(self, precision: float) -> NoneAttributes¶
precision: float
qamomile.circuit.transpiler.artifact¶
Target-neutral containers for compiled artifacts and diagnostics.
Overview¶
| Class | Description |
|---|---|
CompilationDiagnostic | Describe one target-independent or target-specific diagnostic. |
CompilationMetadata | Record how a target artifact was produced. |
CompiledProgram | Package an artifact with its ABI, diagnostics, and provenance. |
DiagnosticSeverity | Classify the severity of a compilation diagnostic. |
ProgramABI | Runtime-visible ABI for a segmented program. |
Classes¶
CompilationDiagnostic [source]¶
class CompilationDiagnosticDescribe one target-independent or target-specific diagnostic.
Parameters:
| Name | Type | Description |
|---|---|---|
severity | DiagnosticSeverity | Diagnostic severity. |
message | str | Human-readable explanation. |
code | str | None | Stable machine-readable diagnostic code. |
source | str | None | Optional source location or IR provenance label. |
Constructor¶
def __init__(
self,
severity: DiagnosticSeverity,
message: str,
code: str | None = None,
source: str | None = None,
) -> NoneAttributes¶
code: str | Nonemessage: strseverity: DiagnosticSeveritysource: str | None
CompilationMetadata [source]¶
class CompilationMetadataRecord how a target artifact was produced.
Parameters:
| Name | Type | Description |
|---|---|---|
target | str | Stable compilation target name. |
pipeline | str | Lowering-family or pipeline name. |
properties | Mapping[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(),
) -> NoneAttributes¶
pipeline: strproperties: Mapping[str, Any]target: str
CompiledProgram [source]¶
class CompiledProgram(Generic[ArtifactT])Package an artifact with its ABI, diagnostics, and provenance.
Parameters:
| Name | Type | Description |
|---|---|---|
artifact | ArtifactT | Target-native circuit, graph, module, or package. |
abi | ProgramABI | Runtime-visible input and output contract. |
metadata | CompilationMetadata | Target and pipeline provenance. |
diagnostics | tuple[CompilationDiagnostic, ...] | Non-fatal compilation diagnostics. Defaults to an empty tuple. |
Constructor¶
def __init__(
self,
artifact: ArtifactT,
abi: ProgramABI,
metadata: CompilationMetadata,
diagnostics: tuple[CompilationDiagnostic, ...] = (),
) -> NoneAttributes¶
abi: ProgramABIartifact: ArtifactTdiagnostics: tuple[CompilationDiagnostic, ...]metadata: CompilationMetadata
DiagnosticSeverity [source]¶
class DiagnosticSeverity(enum.Enum)Classify the severity of a compilation diagnostic.
Attributes¶
ERRORINFOWARNING
ProgramABI [source]¶
class ProgramABIRuntime-visible ABI for a segmented program.
Constructor¶
def __init__(
self,
public_inputs: dict[str, ValueLike] = dict(),
output_values: list[ValueLike] = list(),
) -> NoneAttributes¶
output_values: list[ValueLike]public_inputs: dict[str, ValueLike]
qamomile.circuit.transpiler.block_parameter_binding¶
Shared call-site pairing for operation-owned blocks.
Overview¶
| Function | Description |
|---|---|
align_formal_operands | Align split call-site operand pools to formal declaration order. |
block_parameter_binding_keys | Return the sanctioned emit-binding keys for an inner formal. |
pair_block_operands | Pair all block inputs with category-grouped call-site operands. |
pair_block_parameter_operands | Pair a block’s classical/object inputs with call-site operands. |
| Class | Description |
|---|---|
Block | Unified block representation for all pipeline stages. |
ValueBase | Nominal 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:
| Name | Type | Description |
|---|---|---|
formals | Sequence[ValueBase] | Formal inputs in declaration order. |
quantum_operands | Sequence[ValueBase] | Quantum actual operands in their call-site order. |
parameter_operands | Sequence[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:
| Name | Type | Description |
|---|---|---|
parameter | ValueBase | Classical/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:
| Name | Type | Description |
|---|---|---|
block | Block | Operation-owned block whose inputs are being bound. |
operands | Sequence[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:
| Name | Type | Description |
|---|---|---|
block | Block | Operation-owned block whose formal inputs define the declaration order. |
param_operands | Sequence[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 BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
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:
Lowering may erase how a program was written, never what it means. Semantic values, slices, bindings, and call machinery are erased; intent a target could exploit — semantic identity and immutable semantic arguments (:class:
CallableIdentity), deferred call transforms, structured control flow, Pauli-evolution semantics — is preserved until a target explicitly decides otherwise. Erasure is irreversible while preservation costs one tag, so the default is to preserve.Capabilities declare, legalization decides, materializers execute. Each target owns an immutable :class:
CircuitCapabilitiesdeclaration; :func:legalize_programrewrites a program under that declaration and the user’s :class:CompilationPolicy; :func:verify_target_legalproves the result before materialization, so a materializer only ever converts a program it has already declared it accepts.
Overview¶
| Function | Description |
|---|---|
has_mid_circuit_measurement | Return whether measured quantum state is consumed again in a region. |
legalize_program | Rewrite one circuit program until it is legal for a target. |
lower_circuit_plan | Lower every quantum segment in a plan to immutable circuit IR. |
materialize_executable | Materialize every quantum segment while preserving orchestration. |
verify_circuit | Verify wire linearity, regions, expressions, and slot bounds. |
verify_target_legal | Prove a legalized program against declared target capabilities. |
| Class | Description |
|---|---|
BarrierInstruction | Separate scheduling regions without changing wire versions. |
BinaryExpr | Apply a binary scalar operation. |
BinaryOperator | Enumerate scalar operations preserved until target materialization. |
CallControlMode | Enumerate how a target realizes controls on reusable calls. |
CallInstruction | Invoke a reusable circuit over versioned wires. |
CallPhaseMode | Enumerate how a target realizes phase in coherently controlled calls. |
CallTransformCapabilities | Declare reusable-call forms accepted by a target realization. |
CallableIdentity | Preserve the semantic identity of a reusable circuit body. |
CircuitBuilder | Build immutable circuit IR while assigning fresh wire versions. |
CircuitCapabilities | Declare the complete circuit-IR language accepted by one target. |
CircuitEngineEmitPass | Lower, legalize, verify, and materialize a circuit-family plan. |
CircuitGateEmitter | Emit primitive operations into engine-neutral circuit IR. |
CircuitLoweringPass | Lower a segmented circuit program into target-neutral builders. |
CircuitMaterializer | Convert one target-legal circuit program to an engine artifact. |
CircuitProgram | Store one immutable engine-neutral circuit program. |
ClassicalBitExpr | Reference a measured classical bit. |
CompilationPolicy | Select preferred realizations among target-supported alternatives. |
ForInstruction | Repeat a structured circuit region over a concrete range. |
GateInstruction | Apply one primitive gate to versioned virtual wires. |
GlobalPhaseCapabilities | Declare exact standalone global-phase realization requirements. |
IfInstruction | Select between two structured circuit regions. |
LiteralExpr | Represent a concrete scalar literal. |
LoopVariableExpr | Reference the induction value of a structured loop. |
MaterializedCircuit | Package a circuit artifact and engine-specific binding metadata. |
MeasureInstruction | Measure a wire into a classical bit. |
MeasureVectorInstruction | Measure an ordered group of wires into classical bits. |
NativeSemanticOpCapabilities | Declare a target-native realization of an abstract operation. |
ParameterExpr | Reference a runtime circuit parameter. |
PauliEvolutionInstruction | Apply an abstract Hamiltonian evolution to selected wires. |
PauliEvolutionRealization | Enumerate legalization states for abstract Pauli evolution. |
ResetInstruction | Reset a wire and produce a fresh zero-state wire. |
ReusableCircuit | Describe a reusable circuit body and requested transforms. |
ScalarAtom | Enumerate leaf values that may occur in a scalar expression. |
ScalarCapabilities | Declare the scalar language accepted in one instruction context. |
ScalarExpressionForm | Enumerate permitted runtime-parameter expression shapes. |
SemanticArguments | Store immutable named arguments belonging to an operation’s meaning. |
SemanticOpKey | Identify an abstract operation independently of any engine. |
UnaryExpr | Apply a unary scalar operation. |
UnaryOperator | Enumerate unary scalar operations preserved for materialization. |
WhileInstruction | Repeat a structured region while a runtime predicate is true. |
WireId | Identify one version of a virtual quantum wire. |
Constants¶
ALL_BINARY_OPERATORS:frozenset[BinaryOperator]=frozenset(BinaryOperator)Every binary operator in the circuit scalar vocabulary.ALL_PRIMITIVE_GATES:frozenset[GateKind]=frozenset(GateKind) - {GateKind.MEASURE}Every gate kind valid inGateInstruction.ALL_UNARY_OPERATORS:frozenset[UnaryOperator]=frozenset(UnaryOperator)Every unary operator in the circuit scalar vocabulary.ARITHMETIC_BINARY_OPERATORS:frozenset[BinaryOperator]Binary operators that produce arithmetic scalar values.CircuitInstruction:TypeAliasDEFAULT_POLICY=CompilationPolicy()Policy used when an engine transpiler does not supply one.IQFT_SEMANTIC_KEY=SemanticOpKey('qamomile.stdlib', 'iqft')Semantic key for the exact inverse quantum Fourier transform.MULTI_CONTROLLED_X_SEMANTIC_KEY=SemanticOpKey('qamomile.stdlib', 'multi_controlled_x')Semantic key for an arbitrary-width multi-controlled X operation.QFT_SEMANTIC_KEY=SemanticOpKey('qamomile.stdlib', 'qft')Semantic key for the exact standard quantum Fourier transform.RIPPLE_CARRY_ADD_SEMANTIC_KEY=SemanticOpKey('qamomile.stdlib', 'ripple_carry_add')Semantic key for the full reversible ripple-carry adder.SELECT_SEMANTIC_KEY=SemanticOpKey('qamomile.circuit', 'select')Semantic key for a fallback-defined, index-addressed quantum multiplexer.STATE_PREPARATION_SEMANTIC_KEY=SemanticOpKey('qamomile.stdlib', 'state_preparation')Semantic key for preparing one concrete normalized state vector.ScalarExpr:TypeAlias
Functions¶
has_mid_circuit_measurement [source]¶
def has_mid_circuit_measurement(operations: tuple[CircuitInstruction, ...]) -> boolReturn 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:
| Name | Type | Description |
|---|---|---|
operations | tuple[CircuitInstruction, ...] | Structured instruction region to inspect. |
Returns:
bool — True when the region or a nested reusable/control-flow body
contains a non-terminal measurement.
legalize_program [source]¶
def legalize_program(
program: CircuitProgram,
capabilities: CircuitCapabilities,
policy: CompilationPolicy,
) -> CircuitProgramRewrite 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:
| Name | Type | Description |
|---|---|---|
program | CircuitProgram | Verified engine-neutral circuit program. |
capabilities | CircuitCapabilities | Declared target capabilities. |
policy | CompilationPolicy | User 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:
| Name | Type | Description |
|---|---|---|
plan | ProgramPlan | Circuit-family C-to-Q-to-C execution plan. |
bindings | dict[str, Any] | None | Compile-time parameter bindings. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
Returns:
ExecutableProgram[CircuitProgram] — ExecutableProgram[CircuitProgram]: Execution structure containing
immutable engine-neutral quantum programs.
Raises:
EmitError— If the semantic operations cannot be lowered to the circuit-family instruction set.ValueError— If structural verification rejects a lowered circuit.
materialize_executable [source]¶
def materialize_executable(
executable: ExecutableProgram[CircuitProgram],
materializer: CircuitMaterializer[ArtifactT],
) -> ExecutableProgram[ArtifactT]Materialize every quantum segment while preserving orchestration.
Parameters:
| Name | Type | Description |
|---|---|---|
executable | ExecutableProgram[CircuitProgram] | Lowered circuit-family execution structure. |
materializer | CircuitMaterializer[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) -> NoneVerify wire linearity, regions, expressions, and slot bounds.
Parameters:
| Name | Type | Description |
|---|---|---|
program | CircuitProgram | Immutable circuit program to verify. |
Raises:
ValueError— If the program contains duplicate wire definitions, consumes a non-live wire, has malformed structured-region yields, references an invalid classical bit or loop variable, or reports incorrect outputs.
verify_target_legal [source]¶
def verify_target_legal(program: CircuitProgram, capabilities: CircuitCapabilities) -> NoneProve a legalized program against declared target capabilities.
Parameters:
| Name | Type | Description |
|---|---|---|
program | CircuitProgram | Legalized circuit program, including every nested reusable-call body. |
capabilities | CircuitCapabilities | Declared target capabilities. |
Raises:
TargetCapabilityError— If any instruction requires a gate kind, semantic realization, control-flow construct, reset, Pauli evolution, or scalar-expression shape the target does not declare.
Classes¶
BarrierInstruction [source]¶
class BarrierInstructionSeparate scheduling regions without changing wire versions.
Parameters:
| Name | Type | Description |
|---|---|---|
wires | tuple[WireId, ...] | Wires participating in the barrier. |
Constructor¶
def __init__(self, wires: tuple[WireId, ...]) -> NoneAttributes¶
wires: tuple[WireId, ...]
BinaryExpr [source]¶
class BinaryExpr(_ScalarOperators)Apply a binary scalar operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operator | BinaryOperator | Operation kind. |
left | ScalarExpr | Left operand. |
right | ScalarExpr | Right operand. |
Constructor¶
def __init__(self, operator: BinaryOperator, left: ScalarExpr, right: ScalarExpr) -> NoneAttributes¶
left: ScalarExproperator: BinaryOperatorright: ScalarExpr
BinaryOperator [source]¶
class BinaryOperator(enum.Enum)Enumerate scalar operations preserved until target materialization.
Attributes¶
ADDANDDIVEQFLOORDIVGEGTLELTMODMULNEQORPOWSUB
CallControlMode [source]¶
class CallControlMode(enum.Enum)Enumerate how a target realizes controls on reusable calls.
Attributes¶
DISTRIBUTEUNSUPPORTEDWHOLE_CALL
CallInstruction [source]¶
class CallInstructionInvoke a reusable circuit over versioned wires.
Parameters:
| Name | Type | Description |
|---|---|---|
callee | ReusableCircuit | Reusable circuit and transforms. |
inputs | tuple[WireId, ...] | Consumed wire versions. |
outputs | tuple[WireId, ...] | Produced wire versions. |
Constructor¶
def __init__(
self,
callee: ReusableCircuit,
inputs: tuple[WireId, ...],
outputs: tuple[WireId, ...],
) -> NoneAttributes¶
callee: ReusableCircuitinputs: tuple[WireId, ...]outputs: tuple[WireId, ...]
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¶
EXPLICIT_CORRECTIONNATIVE_BODYUNSUPPORTED
CallTransformCapabilities [source]¶
class CallTransformCapabilitiesDeclare reusable-call forms accepted by a target realization.
Parameters:
| Name | Type | Description |
|---|---|---|
supports_power | bool | Whether powers other than one are accepted. |
supports_inverse | bool | Whether inverse calls are accepted. |
max_controls | int | None | Maximum added controls. None means no declared limit. |
supports_nonunitary_body | bool | Whether a reusable body may contain measurement, reset, or dynamic control flow. |
supports_barrier_body | bool | Whether barriers may remain inside a reusable body. |
control_mode | CallControlMode | How added controls are realized. |
controlled_gate_kinds | frozenset[GateKind] | Body gate kinds accepted when controls are distributed into the body. |
controlled_pauli_time | ScalarCapabilities | None | Pauli-time scalar language accepted under distributed controls, or None when controlled Pauli evolution is unsupported. |
phase_mode | CallPhaseMode | How 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_scalars | ScalarCapabilities | None | Scalar 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,
) -> NoneAttributes¶
control_mode: CallControlModecontrolled_gate_kinds: frozenset[GateKind]controlled_pauli_time: ScalarCapabilities | Nonecontrolled_phase_scalars: ScalarCapabilities | Nonemax_controls: int | Nonephase_mode: CallPhaseModesupports_barrier_body: boolsupports_inverse: boolsupports_nonunitary_body: boolsupports_power: bool
Methods¶
accepts¶
def accepts(self, callee: ReusableCircuit, inherited_controls: int = 0) -> boolReturn whether this declaration accepts a concrete call shape.
Parameters:
| Name | Type | Description |
|---|---|---|
callee | ReusableCircuit | Reusable body and requested transforms. |
inherited_controls | int | Controls physically distributed from an enclosing call. Defaults to zero. |
Returns:
bool — Whether power, inverse, and control transforms are accepted.
CallableIdentity [source]¶
class CallableIdentityPreserve the semantic identity of a reusable circuit body.
Parameters:
| Name | Type | Description |
|---|---|---|
key | SemanticOpKey | Open semantic identity used by target-native realization registries. |
symbol | str | Human-readable callable name used for diagnostics. |
arguments | SemanticArguments | Immutable arguments that define this invocation’s meaning. Defaults to no arguments. |
Constructor¶
def __init__(
self,
key: SemanticOpKey,
symbol: str,
arguments: SemanticArguments = SemanticArguments(),
) -> NoneAttributes¶
arguments: SemanticArgumentskey: SemanticOpKeysymbol: str
CircuitBuilder [source]¶
class CircuitBuilderBuild immutable circuit IR while assigning fresh wire versions.
Parameters:
| Name | Type | Description |
|---|---|---|
num_qubits | int | Number of virtual qubit slots. |
num_clbits | int | Number of classical bit slots. |
name | str | Circuit name. Defaults to "main". |
Constructor¶
def __init__(self, num_qubits: int, num_clbits: int, name: str = 'main') -> NoneInitialize a circuit builder.
Parameters:
| Name | Type | Description |
|---|---|---|
num_qubits | int | Number of virtual qubit slots. |
num_clbits | int | Number of classical bit slots. |
name | str | Circuit name. Defaults to "main". |
Raises:
ValueError— If either slot count is negative.
Attributes¶
namenum_clbitsnum_qubitsoperations: list[CircuitInstruction] Return the current region instruction list.
Methods¶
add_global_phase¶
def add_global_phase(self, phase: ScalarExpr | bool | int | float) -> NoneAccumulate a global phase in the current lexical region.
Parameters:
| Name | Type | Description |
|---|---|---|
phase | ScalarExpr | bool | int | float | Phase contribution. |
append_barrier¶
def append_barrier(self, qubits: tuple[int, ...]) -> NoneAppend a scheduling barrier without changing wire versions.
Parameters:
| Name | Type | Description |
|---|---|---|
qubits | tuple[int, ...] | Participating qubit slots. |
append_call¶
def append_call(self, callee: ReusableCircuit, qubits: tuple[int, ...]) -> NoneAppend a reusable-circuit call and advance its wires.
Parameters:
| Name | Type | Description |
|---|---|---|
callee | ReusableCircuit | Reusable circuit and transforms. |
qubits | tuple[int, ...] | Participating qubit slots. |
append_gate¶
def append_gate(
self,
kind: GateKind,
qubits: tuple[int, ...],
parameters: tuple[ScalarExpr, ...] = (),
) -> NoneAppend a primitive gate and advance all participating wires.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | GateKind | Primitive gate kind. |
qubits | tuple[int, ...] | Participating qubit slots. |
parameters | tuple[ScalarExpr, ...] | Gate parameters. Defaults to an empty tuple. |
append_measure¶
def append_measure(self, qubit: int, clbit: int) -> NoneAppend a measurement.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | int | Measured qubit slot. |
clbit | int | Destination classical bit slot. |
Raises:
IndexError— Ifclbitis outside the allocated classical slots.
append_measure_vector¶
def append_measure_vector(self, qubits: tuple[int, ...], clbits: tuple[int, ...]) -> NoneAppend one ordered vector measurement.
Parameters:
| Name | Type | Description |
|---|---|---|
qubits | tuple[int, ...] | Measured qubit slots in result order. |
clbits | tuple[int, ...] | Destination classical slots. |
Raises:
ValueError— If qubit and classical-bit arities differ or either sequence contains duplicate slots.IndexError— If a classical-bit slot is outside the circuit.
append_pauli_evolution¶
def append_pauli_evolution(
self,
qubits: tuple[int, ...],
hamiltonian: Any,
time: ScalarExpr | bool | int | float,
) -> NoneAppend an abstract Pauli evolution and advance its wires.
Parameters:
| Name | Type | Description |
|---|---|---|
qubits | tuple[int, ...] | Participating qubit slots. |
hamiltonian | Any | Qamomile Hamiltonian value. |
time | ScalarExpr | bool | int | float | Evolution time. |
Raises:
ValueError— If a Qamomile Hamiltonian has a non-Hermitian identity coefficient.
append_reset¶
def append_reset(self, qubit: int) -> NoneAppend reset and advance the affected wire.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | int | Qubit slot to reset. |
begin_else¶
def begin_else(self, context: _IfContext) -> NoneClose a true region and open its false region.
Parameters:
| Name | Type | Description |
|---|---|---|
context | _IfContext | Token returned by :meth:begin_if. |
Raises:
RuntimeError— Ifcontextis not the innermost open conditional or an else branch has already started.
begin_for¶
def begin_for(self, indexset: range) -> LoopVariableExprOpen a structured for-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
indexset | range | Concrete iteration range. |
Returns:
LoopVariableExpr — Induction expression available inside the body.
begin_if¶
def begin_if(self, condition: ScalarExpr) -> _IfContextOpen the true region of a structured conditional.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime branch predicate. |
Returns:
_IfContext — Opaque builder token used to select the else branch.
begin_while¶
def begin_while(self, condition: ScalarExpr) -> _WhileContextOpen a structured while-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime loop predicate. |
Returns:
_WhileContext — Opaque builder token used to close the loop.
current_wire¶
def current_wire(self, qubit: int) -> WireIdReturn the current wire version for a qubit slot.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | int | Physical slot index assigned by circuit lowering. |
Returns:
WireId — Current version of the slot.
Raises:
KeyError— Ifqubitis outside the allocated slot range.
end_for¶
def end_for(self) -> NoneClose the innermost structured for-loop body.
Raises:
RuntimeError— If the innermost open region is not a for loop.
end_if¶
def end_if(self, context: _IfContext) -> NoneClose a structured conditional and merge its wire states.
Parameters:
| Name | Type | Description |
|---|---|---|
context | _IfContext | Token returned by :meth:begin_if. |
Raises:
RuntimeError— Ifcontextis not the innermost open conditional.
end_while¶
def end_while(self, context: _WhileContext) -> NoneClose a structured while-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
context | _WhileContext | Token returned by :meth:begin_while. |
Raises:
RuntimeError— Ifcontextis not the innermost open while loop.
freeze¶
def freeze(self) -> CircuitProgramFinalize the root region into immutable circuit IR.
Returns:
CircuitProgram — Immutable circuit program.
Raises:
RuntimeError— If a structured region is still open.
fresh_wire¶
def fresh_wire(self) -> WireIdAllocate a fresh module-local virtual wire version.
Returns:
WireId — Newly allocated wire identifier.
restore_state¶
def restore_state(self, snapshot: _CircuitBuilderSnapshot) -> NoneRestore a checkpoint after an append-only emission attempt.
Parameters:
| Name | Type | Description |
|---|---|---|
snapshot | _CircuitBuilderSnapshot | Checkpoint returned by :meth:snapshot_state for this builder. |
Raises:
RuntimeError— If emission removed or replaced state that existed before the checkpoint instead of only appending new state.
snapshot_state¶
def snapshot_state(self) -> _CircuitBuilderSnapshotCapture state that can be restored after declined emission.
Returns:
_CircuitBuilderSnapshot — Append-only builder checkpoint for the
current structured region.
CircuitCapabilities [source]¶
class CircuitCapabilitiesDeclare the complete circuit-IR language accepted by one target.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Stable target name used in diagnostics. |
primitive_gates | frozenset[GateKind] | Primitive gate kinds accepted by the target materializer. |
native_semantic_ops | tuple[NativeSemanticOpCapabilities, ...] | Native realizations keyed by open semantic operation identity. |
gate_parameters | ScalarCapabilities | Scalar language accepted by gate parameters. |
predicates | ScalarCapabilities | Scalar language accepted by dynamic if and while predicates. |
pauli_time | ScalarCapabilities | Scalar language accepted by Pauli evolution time values. |
global_phase | GlobalPhaseCapabilities | ScalarCapabilities | None | Exact standalone phase realization requirements, or None when unsupported. The former ScalarCapabilities value remains accepted and readable for source compatibility. |
generic_calls | CallTransformCapabilities | Reusable-call forms accepted after semantic-call legalization. |
supports_dynamic_if | bool | Whether runtime if regions are accepted. |
supports_dynamic_while | bool | Whether runtime while regions are accepted. |
supports_reset | bool | Whether reset instructions are accepted. |
pauli_realizations | frozenset[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],
) -> NoneAttributes¶
gate_parameters: ScalarCapabilitiesgeneric_calls: CallTransformCapabilitiesglobal_phase: GlobalPhaseCapabilities | ScalarCapabilities | Nonename: strnative_semantic_ops: tuple[NativeSemanticOpCapabilities, ...]normalized_global_phase: GlobalPhaseCapabilities | None Return standalone phase requirements in the extended form.pauli_realizations: frozenset[PauliEvolutionRealization]pauli_time: ScalarCapabilitiespredicates: ScalarCapabilitiesprimitive_gates: frozenset[GateKind]supports_dynamic_if: boolsupports_dynamic_while: boolsupports_reset: bool
Methods¶
native_semantic_op¶
def native_semantic_op(self, key: SemanticOpKey) -> NativeSemanticOpCapabilities | NoneReturn the native declaration for one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
key | SemanticOpKey | Semantic operation key to look up. |
Returns:
NativeSemanticOpCapabilities | None — NativeSemanticOpCapabilities | None: Matching declaration, or
NativeSemanticOpCapabilities | None — None when the target has no native realization.
CircuitEngineEmitPass [source]¶
class CircuitEngineEmitPass(EmitPass[ArtifactT])Lower, legalize, verify, and materialize a circuit-family plan.
The pass runs the three phases in order and never interleaves them: shared lowering produces engine-neutral circuit IR, target legalization rewrites it under the materializer’s declared capabilities and the compilation policy, target verification proves the result, and only then does the materializer convert it mechanically.
Parameters:
| Name | Type | Description |
|---|---|---|
materializer | CircuitMaterializer[ArtifactT] | Engine artifact materializer owning the target capability declaration. |
bindings | dict[str, Any] | None | Compile-time bindings. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
policy | CompilationPolicy | None | Realization 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,
) -> NoneInitialize a circuit-family lowering and materialization pass.
Parameters:
| Name | Type | Description |
|---|---|---|
materializer | CircuitMaterializer[ArtifactT] | Engine artifact materializer owning the target capability declaration. |
bindings | dict[str, Any] | None | Compile-time bindings. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
policy | CompilationPolicy | None | Realization preferences. Defaults to None, meaning :data:DEFAULT_POLICY. |
Attributes¶
materializerparameter_namespolicy
Methods¶
run¶
def run(self, input: ProgramPlan) -> ExecutableProgram[ArtifactT]Lower, legalize, verify, and materialize every quantum segment.
Parameters:
| Name | Type | Description |
|---|---|---|
input | ProgramPlan | Circuit-family execution plan. |
Returns:
ExecutableProgram[ArtifactT] — ExecutableProgram[ArtifactT]: Engine-native executable structure.
Raises:
TargetCapabilityError— If a legalized segment still requires a capability the target does not declare.ValueError— If a legalized segment fails structural verification.
CircuitGateEmitter [source]¶
class CircuitGateEmitterEmit primitive operations into engine-neutral circuit IR.
Attributes¶
measurement_mode: MeasurementMode Return native measurement mode for explicit circuit IR.
Methods¶
append_gate¶
def append_gate(
self,
circuit: CircuitBuilder,
gate: ReusableCircuit,
qubits: list[int],
) -> NoneAppend a reusable circuit call.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
gate | ReusableCircuit | Reusable circuit value. |
qubits | list[int] | Participating slots. |
circuit_to_gate¶
def circuit_to_gate(
self,
circuit: CircuitBuilder | CircuitProgram,
name: str = 'U',
) -> ReusableCircuitFreeze a circuit as a reusable circuit value.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | CircuitProgram | Circuit body. |
name | str | Reusable 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 | NoneCombine symbolic operands without creating engine expressions.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | BinOpKind | Qamomile arithmetic operation. |
lhs | ScalarExpr | bool | int | float | Left operand. |
rhs | ScalarExpr | bool | int | float | Right 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) -> CircuitBuilderCreate an empty circuit IR builder.
Parameters:
| Name | Type | Description |
|---|---|---|
num_qubits | int | Number of virtual qubit slots. |
num_clbits | int | Number of classical bit slots. |
Returns:
CircuitBuilder — Empty engine-neutral builder.
create_parameter¶
def create_parameter(self, name: str) -> ParameterExprCreate a target-neutral runtime parameter expression.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | External parameter name. |
Returns:
ParameterExpr — Parameter reference preserved until materialization.
emit_barrier¶
def emit_barrier(self, circuit: CircuitBuilder, qubits: list[int]) -> NoneEmit a scheduling barrier.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubits | list[int] | Participating slots. |
emit_ch¶
def emit_ch(self, circuit: CircuitBuilder, control: int, target: int) -> NoneEmit a controlled-H gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
emit_cp¶
def emit_cp(
self,
circuit: CircuitBuilder,
control: int,
target: int,
angle: ScalarExpr | float,
) -> NoneEmit a controlled-phase rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
angle | ScalarExpr | float | Phase angle in radians. |
emit_crx¶
def emit_crx(
self,
circuit: CircuitBuilder,
control: int,
target: int,
angle: ScalarExpr | float,
) -> NoneEmit a controlled-RX rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_cry¶
def emit_cry(
self,
circuit: CircuitBuilder,
control: int,
target: int,
angle: ScalarExpr | float,
) -> NoneEmit a controlled-RY rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_crz¶
def emit_crz(
self,
circuit: CircuitBuilder,
control: int,
target: int,
angle: ScalarExpr | float,
) -> NoneEmit a controlled-RZ rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_cx¶
def emit_cx(self, circuit: CircuitBuilder, control: int, target: int) -> NoneEmit a controlled-X gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
emit_cy¶
def emit_cy(self, circuit: CircuitBuilder, control: int, target: int) -> NoneEmit a controlled-Y gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
emit_cz¶
def emit_cz(self, circuit: CircuitBuilder, control: int, target: int) -> NoneEmit a controlled-Z gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
emit_else_start¶
def emit_else_start(self, circuit: CircuitBuilder, context: Any) -> NoneSwitch an open conditional to its false branch.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
context | Any | Opaque conditional context. |
emit_for_loop_end¶
def emit_for_loop_end(self, circuit: CircuitBuilder, context: Any) -> NoneClose a structured for-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
context | Any | Induction expression returned at loop start. |
emit_for_loop_start¶
def emit_for_loop_start(self, circuit: CircuitBuilder, indexset: range) -> ScalarExprOpen a structured for-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
indexset | range | Concrete iteration range. |
Returns:
ScalarExpr — Target-neutral induction expression.
emit_global_phase¶
def emit_global_phase(self, circuit: CircuitBuilder, angle: ScalarExpr | float) -> NoneAccumulate a phase in the builder’s current lexical region.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
angle | ScalarExpr | float | Phase angle in radians. |
emit_h¶
def emit_h(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit a Hadamard gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_if_end¶
def emit_if_end(self, circuit: CircuitBuilder, context: Any) -> NoneClose a structured conditional.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
context | Any | Opaque conditional context. |
emit_if_start¶
def emit_if_start(self, circuit: CircuitBuilder, clbit: int, value: int = 1) -> AnyOpen a structured conditional true branch.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
clbit | int | Predicate classical bit slot. |
value | int | Required bit value. Defaults to one. |
Returns:
Any — Opaque conditional builder context.
emit_measure¶
def emit_measure(self, circuit: CircuitBuilder, qubit: int, clbit: int) -> NoneEmit a measurement into a classical slot.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Measured qubit slot. |
clbit | int | Destination classical slot. |
emit_measure_vector¶
def emit_measure_vector(
self,
circuit: CircuitBuilder,
qubits: tuple[int, ...],
clbits: tuple[int, ...],
) -> NonePreserve an ordered vector measurement as one instruction.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubits | tuple[int, ...] | Measured qubit slots in result order. |
clbits | tuple[int, ...] | Destination classical slots. |
emit_p¶
def emit_p(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> NoneEmit a phase rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
angle | ScalarExpr | float | Phase angle in radians. |
emit_reset¶
def emit_reset(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit a reset-to-zero operation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Reset qubit slot. |
emit_rx¶
def emit_rx(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> NoneEmit an RX rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_ry¶
def emit_ry(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> NoneEmit an RY rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_rz¶
def emit_rz(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> NoneEmit an RZ rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_rzz¶
def emit_rzz(
self,
circuit: CircuitBuilder,
qubit1: int,
qubit2: int,
angle: ScalarExpr | float,
) -> NoneEmit an RZZ rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit1 | int | First slot. |
qubit2 | int | Second slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_s¶
def emit_s(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit an S gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_sdg¶
def emit_sdg(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit an inverse-S gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_swap¶
def emit_swap(self, circuit: CircuitBuilder, qubit1: int, qubit2: int) -> NoneEmit a SWAP gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit1 | int | First slot. |
qubit2 | int | Second slot. |
emit_t¶
def emit_t(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit a T gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_tdg¶
def emit_tdg(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit an inverse-T gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_toffoli¶
def emit_toffoli(
self,
circuit: CircuitBuilder,
control1: int,
control2: int,
target: int,
) -> NoneEmit a Toffoli gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control1 | int | First control slot. |
control2 | int | Second control slot. |
target | int | Target slot. |
emit_while_end¶
def emit_while_end(self, circuit: CircuitBuilder, context: Any) -> NoneClose a structured while-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
context | Any | Opaque while-loop context. |
emit_while_start¶
def emit_while_start(self, circuit: CircuitBuilder, clbit: int, value: int = 1) -> AnyOpen a structured while-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
clbit | int | Predicate classical bit slot. |
value | int | Required bit value. Defaults to one. |
Returns:
Any — Opaque while-loop builder context.
emit_x¶
def emit_x(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit a Pauli-X gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_y¶
def emit_y(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit a Pauli-Y gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_z¶
def emit_z(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit a Pauli-Z gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
gate_controlled¶
def gate_controlled(self, gate: ReusableCircuit, num_controls: int) -> ReusableCircuitAdd control wires to a reusable circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | ReusableCircuit | Reusable circuit value. |
num_controls | int | Number of controls to add. |
Returns:
ReusableCircuit — Controlled reusable circuit.
gate_inverse¶
def gate_inverse(self, gate: ReusableCircuit) -> ReusableCircuitToggle the inverse transform on a reusable circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | ReusableCircuit | Reusable circuit value. |
Returns:
ReusableCircuit — Inverse reusable circuit.
gate_power¶
def gate_power(self, gate: ReusableCircuit, power: int) -> ReusableCircuitApply an integral power transform to a reusable circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | ReusableCircuit | Reusable circuit value. |
power | int | Integral repetition count. |
Returns:
ReusableCircuit — Transformed reusable circuit.
supports_for_loop¶
def supports_for_loop(self) -> boolReport support for structured for loops.
Returns:
bool — Always True for circuit IR.
supports_gate_inverse¶
def supports_gate_inverse(self) -> boolReport support for deferred inverse transforms.
Returns:
bool — Always True for circuit IR.
supports_if_else¶
def supports_if_else(self) -> boolReport support for structured conditionals.
Returns:
bool — Always True for circuit IR.
supports_reusable_gates¶
def supports_reusable_gates(self) -> boolReport 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) -> boolReport 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:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Compile-time parameter bindings. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
Constructor¶
def __init__(
self,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> NoneInitialize circuit-IR lowering.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Compile-time parameter bindings. Defaults to None. |
parameters | list[str] | None | Runtime 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:
| Name | Type | Description |
|---|---|---|
input | ProgramPlan | Segmented 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¶
capabilities: CircuitCapabilities Declare what this target accepts in circuit IR.
Methods¶
materialize¶
def materialize(self, program: CircuitProgram) -> MaterializedCircuit[ArtifactT]Materialize one circuit program.
Parameters:
| Name | Type | Description |
|---|---|---|
program | CircuitProgram | Target-legal circuit-family program. |
Returns:
MaterializedCircuit[ArtifactT] — Artifact plus engine binding metadata.
CircuitProgram [source]¶
class CircuitProgramStore one immutable engine-neutral circuit program.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Circuit entrypoint name. |
num_qubits | int | Number of virtual input qubit slots. |
num_clbits | int | Number of classical bit slots. |
input_wires | tuple[WireId, ...] | Initial wire version per qubit slot. |
output_wires | tuple[WireId, ...] | Final wire version per qubit slot. |
operations | tuple[CircuitInstruction, ...] | Structured instruction sequence. |
global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
global_phase: ScalarExprinput_wires: tuple[WireId, ...]name: strnum_clbits: intnum_qubits: intoperations: tuple[CircuitInstruction, ...]output_wires: tuple[WireId, ...]
ClassicalBitExpr [source]¶
class ClassicalBitExpr(_ScalarOperators)Reference a measured classical bit.
Parameters:
| Name | Type | Description |
|---|---|---|
index | int | Circuit-local classical bit index. |
Constructor¶
def __init__(self, index: int) -> NoneAttributes¶
index: int
CompilationPolicy [source]¶
class CompilationPolicySelect preferred realizations among target-supported alternatives.
Parameters:
| Name | Type | Description |
|---|---|---|
prefer_native_semantic_ops | bool | Whether legal target-native realizations are preferred over reusable fallback bodies. Defaults to True. |
prefer_native_pauli_evolution | bool | Whether 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,
) -> NoneAttributes¶
prefer_native_pauli_evolution: boolprefer_native_semantic_ops: bool
ForInstruction [source]¶
class ForInstructionRepeat a structured circuit region over a concrete range.
Parameters:
| Name | Type | Description |
|---|---|---|
indexset | range | Concrete iteration range. |
loop_variable | LoopVariableExpr | Induction expression used by the body. |
inputs | tuple[WireId, ...] | Wire versions entering the loop. |
body | tuple[CircuitInstruction, ...] | Single-iteration body. |
body_outputs | tuple[WireId, ...] | Body wire versions yielded to the next iteration. |
outputs | tuple[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, ...],
) -> NoneAttributes¶
body: tuple[CircuitInstruction, ...]body_outputs: tuple[WireId, ...]indexset: rangeinputs: tuple[WireId, ...]loop_variable: LoopVariableExproutputs: tuple[WireId, ...]
GateInstruction [source]¶
class GateInstructionApply one primitive gate to versioned virtual wires.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | GateKind | Primitive gate kind. |
inputs | tuple[WireId, ...] | Consumed wire versions. |
outputs | tuple[WireId, ...] | Produced wire versions. |
parameters | tuple[ScalarExpr, ...] | Gate parameters. |
Constructor¶
def __init__(
self,
kind: GateKind,
inputs: tuple[WireId, ...],
outputs: tuple[WireId, ...],
parameters: tuple[ScalarExpr, ...] = (),
) -> NoneAttributes¶
inputs: tuple[WireId, ...]kind: GateKindoutputs: tuple[WireId, ...]parameters: tuple[ScalarExpr, ...]
GlobalPhaseCapabilities [source]¶
class GlobalPhaseCapabilitiesDeclare exact standalone global-phase realization requirements.
Parameters:
| Name | Type | Description |
|---|---|---|
scalars | ScalarCapabilities | Scalar language accepted for the phase. |
min_qubits | int | Minimum 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) -> NoneAttributes¶
atoms: frozenset[ScalarAtom] Return the legacy scalar-atom declaration.binary_operators: frozenset[BinaryOperator] Return the legacy binary-operator declaration.min_qubits: intparameter_form: ScalarExpressionForm Return the legacy runtime-parameter expression form.scalars: ScalarCapabilitiesunary_operators: frozenset[UnaryOperator] Return the legacy unary-operator declaration.
IfInstruction [source]¶
class IfInstructionSelect between two structured circuit regions.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime branch predicate. |
inputs | tuple[WireId, ...] | Wires entering both branches. |
true_body | tuple[CircuitInstruction, ...] | True branch body. |
false_body | tuple[CircuitInstruction, ...] | False branch body. |
true_outputs | tuple[WireId, ...] | Wires yielded by the true branch. |
false_outputs | tuple[WireId, ...] | Wires yielded by the false branch. |
outputs | tuple[WireId, ...] | Merged post-branch wires. |
true_global_phase | ScalarExpr | Phase applied only in the true branch. |
false_global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
condition: ScalarExprfalse_body: tuple[CircuitInstruction, ...]false_global_phase: ScalarExprfalse_outputs: tuple[WireId, ...]inputs: tuple[WireId, ...]outputs: tuple[WireId, ...]true_body: tuple[CircuitInstruction, ...]true_global_phase: ScalarExprtrue_outputs: tuple[WireId, ...]
LiteralExpr [source]¶
class LiteralExpr(_ScalarOperators)Represent a concrete scalar literal.
Parameters:
| Name | Type | Description |
|---|---|---|
value | bool | int | float | Concrete scalar value. |
Constructor¶
def __init__(self, value: bool | int | float) -> NoneAttributes¶
value: bool | int | float
LoopVariableExpr [source]¶
class LoopVariableExpr(_ScalarOperators)Reference the induction value of a structured loop.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Circuit-local loop variable name. |
Constructor¶
def __init__(self, name: str) -> NoneAttributes¶
name: str
MaterializedCircuit [source]¶
class MaterializedCircuit(Generic[ArtifactT])Package a circuit artifact and engine-specific binding metadata.
Parameters:
| Name | Type | Description |
|---|---|---|
artifact | Any | Engine-native circuit object. |
parameters | Mapping[str, Any] | Engine parameters keyed by public parameter name. |
measurement_qubit_map | Mapping[int, int] | None | Static-measurement mapping from classical output slot to physical qubit slot. None preserves the lowering-provided mapping; an empty mapping is an explicit override. |
parameter_order | tuple[str, ...] | None | Artifact ABI order for positional parameters. None denotes name-based binding. |
implicit_output_qubit_indices | tuple[int, ...] | None | Physical 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,
) -> NoneAttributes¶
artifact: ArtifactTimplicit_output_qubit_indices: tuple[int, ...] | Nonemeasurement_qubit_map: Mapping[int, int] | Noneparameter_order: tuple[str, ...] | Noneparameters: Mapping[str, Any]
MeasureInstruction [source]¶
class MeasureInstructionMeasure a wire into a classical bit.
Parameters:
| Name | Type | Description |
|---|---|---|
input | WireId | Measured wire version. |
output | WireId | Post-measurement wire version. |
clbit | int | Destination classical bit index. |
Constructor¶
def __init__(self, input: WireId, output: WireId, clbit: int) -> NoneAttributes¶
clbit: intinput: WireIdoutput: WireId
MeasureVectorInstruction [source]¶
class MeasureVectorInstructionMeasure 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:
| Name | Type | Description |
|---|---|---|
inputs | tuple[WireId, ...] | Measured wire versions in result order. |
outputs | tuple[WireId, ...] | Post-measurement wire versions. |
clbits | tuple[int, ...] | Destination classical bits in result order. |
Constructor¶
def __init__(
self,
inputs: tuple[WireId, ...],
outputs: tuple[WireId, ...],
clbits: tuple[int, ...],
) -> NoneAttributes¶
clbits: tuple[int, ...]inputs: tuple[WireId, ...]outputs: tuple[WireId, ...]
NativeSemanticOpCapabilities [source]¶
class NativeSemanticOpCapabilitiesDeclare a target-native realization of an abstract operation.
Parameters:
| Name | Type | Description |
|---|---|---|
key | SemanticOpKey | Engine-independent semantic operation key. |
realization | str | Target-owned realization identifier passed to the materializer after legalization. |
call_transforms | CallTransformCapabilities | Call shapes supported by the native realization. |
operand_widths | tuple[int | None, ...] | None | Required 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_qubits | int | Minimum fallback-body width accepted by the native operation. Defaults to zero. |
max_qubits | int | None | Maximum fallback-body width, or None for no limit. Defaults to None. |
required_arguments | frozenset[str] | Semantic argument names required by this realization. Defaults to none. |
matching_operand_widths | tuple[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], ...] = (),
) -> NoneAttributes¶
call_transforms: CallTransformCapabilitieskey: SemanticOpKeymatching_operand_widths: tuple[tuple[int, int], ...]max_qubits: int | Nonemin_qubits: intoperand_widths: tuple[int | None, ...] | Nonerealization: strrequired_arguments: frozenset[str]
Methods¶
accepts¶
def accepts(self, callee: ReusableCircuit, inherited_controls: int = 0) -> boolReturn whether this realization accepts one semantic call shape.
Parameters:
| Name | Type | Description |
|---|---|---|
callee | ReusableCircuit | Reusable call retaining source operand grouping and deferred transforms. |
inherited_controls | int | Controls 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:
| Name | Type | Description |
|---|---|---|
name | str | Stable external parameter name. |
Constructor¶
def __init__(self, name: str) -> NoneAttributes¶
name: str
PauliEvolutionInstruction [source]¶
class PauliEvolutionInstructionApply an abstract Hamiltonian evolution to selected wires.
Parameters:
| Name | Type | Description |
|---|---|---|
hamiltonian | Any | Immutable Qamomile Hamiltonian value. |
time | ScalarExpr | Evolution time in radians. |
inputs | tuple[WireId, ...] | Consumed wire versions. |
outputs | tuple[WireId, ...] | Produced wire versions. |
realization | PauliEvolutionRealization | Target 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,
) -> NoneAttributes¶
hamiltonian: Anyinputs: tuple[WireId, ...]outputs: tuple[WireId, ...]realization: PauliEvolutionRealizationtime: ScalarExpr
PauliEvolutionRealization [source]¶
class PauliEvolutionRealization(enum.Enum)Enumerate legalization states for abstract Pauli evolution.
Attributes¶
ABSTRACTGADGETNATIVE
ResetInstruction [source]¶
class ResetInstructionReset a wire and produce a fresh zero-state wire.
Parameters:
| Name | Type | Description |
|---|---|---|
input | WireId | Wire version before reset. |
output | WireId | Fresh wire version after reset. |
Constructor¶
def __init__(self, input: WireId, output: WireId) -> NoneAttributes¶
input: WireIdoutput: WireId
ReusableCircuit [source]¶
class ReusableCircuitDescribe a reusable circuit body and requested transforms.
Parameters:
| Name | Type | Description |
|---|---|---|
body | CircuitProgram | Reusable circuit body. |
name | str | Display and linkage name. |
power | int | Integral repetition count. Defaults to one. |
controls | int | Added control-wire count. Defaults to zero. |
inverse | bool | Whether to apply the inverse body. Defaults to false. |
identity | CallableIdentity | None | Semantic identity preserved for target legalization. None marks an anonymous body. Defaults to None. |
native_realization | str | None | Target-owned realization identifier selected during legalization. None keeps the reusable body as the fallback implementation. Defaults to None. |
operand_widths | tuple[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, ...] = (),
) -> NoneAttributes¶
body: CircuitProgramcontrols: intidentity: CallableIdentity | Noneinverse: boolname: strnative_realization: str | Nonenum_qubits: int Return the transformed call arity.operand_widths: tuple[int, ...]power: int
ScalarAtom [source]¶
class ScalarAtom(enum.Enum)Enumerate leaf values that may occur in a scalar expression.
Attributes¶
CLASSICAL_BITLITERALLOOP_VARIABLEPARAMETER
ScalarCapabilities [source]¶
class ScalarCapabilitiesDeclare the scalar language accepted in one instruction context.
Parameters:
| Name | Type | Description |
|---|---|---|
atoms | frozenset[ScalarAtom] | Leaf value kinds accepted in the expression. |
unary_operators | frozenset[UnaryOperator] | Accepted unary operators. |
binary_operators | frozenset[BinaryOperator] | Accepted binary operators. |
parameter_form | ScalarExpressionForm | Maximum algebraic form for runtime parameters. |
Constructor¶
def __init__(
self,
atoms: frozenset[ScalarAtom],
unary_operators: frozenset[UnaryOperator],
binary_operators: frozenset[BinaryOperator],
parameter_form: ScalarExpressionForm,
) -> NoneAttributes¶
atoms: frozenset[ScalarAtom]binary_operators: frozenset[BinaryOperator]parameter_form: ScalarExpressionFormunary_operators: frozenset[UnaryOperator]
ScalarExpressionForm [source]¶
class ScalarExpressionForm(enum.Enum)Enumerate permitted runtime-parameter expression shapes.
Attributes¶
ARBITRARYCONCRETE_ONLYLINEAR
SemanticArguments [source]¶
class SemanticArgumentsStore immutable named arguments belonging to an operation’s meaning.
Parameters:
| Name | Type | Description |
|---|---|---|
entries | tuple[tuple[str, SemanticValue], ...] | Sorted name-value entries. Defaults to an empty tuple. |
Constructor¶
def __init__(self, entries: tuple[tuple[str, SemanticValue], ...] = ()) -> NoneAttributes¶
entries: tuple[tuple[str, SemanticValue], ...]
Methods¶
from_mapping¶
@classmethod
def from_mapping(cls, values: Mapping[str, Any] | None) -> 'SemanticArguments'Freeze one mapping of semantic operation arguments.
Parameters:
| Name | Type | Description |
|---|---|---|
values | Mapping[str, Any] | None | Serializer-friendly arguments, or None for no arguments. |
Returns:
'SemanticArguments' — Immutable, deterministically ordered arguments.
Raises:
TypeError— If a nested value is not serializer-friendly.
get¶
def get(self, name: str, default: SemanticValue = None) -> SemanticValueReturn one semantic argument by name.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Argument name. |
default | SemanticValue | Value 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 SemanticOpKeyIdentify 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:
| Name | Type | Description |
|---|---|---|
namespace | str | Stable owner namespace such as qamomile.stdlib. |
name | str | Stable operation name within the namespace. |
version | str | Semantic contract version. Defaults to "1". |
variant | str | None | Optional 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,
) -> NoneAttributes¶
name: strnamespace: strvariant: str | Noneversion: str
UnaryExpr [source]¶
class UnaryExpr(_ScalarOperators)Apply a unary scalar operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operator | UnaryOperator | Operation kind. |
operand | ScalarExpr | Input expression. |
Constructor¶
def __init__(self, operator: UnaryOperator, operand: ScalarExpr) -> NoneAttributes¶
operand: ScalarExproperator: UnaryOperator
UnaryOperator [source]¶
class UnaryOperator(enum.Enum)Enumerate unary scalar operations preserved for materialization.
Attributes¶
NEGNOT
WhileInstruction [source]¶
class WhileInstructionRepeat a structured region while a runtime predicate is true.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime loop predicate. |
inputs | tuple[WireId, ...] | Wires entering the loop. |
body | tuple[CircuitInstruction, ...] | Loop body. |
body_outputs | tuple[WireId, ...] | Wires yielded to the next iteration. |
outputs | tuple[WireId, ...] | Wires available after loop termination. |
body_global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
body: tuple[CircuitInstruction, ...]body_global_phase: ScalarExprbody_outputs: tuple[WireId, ...]condition: ScalarExprinputs: tuple[WireId, ...]outputs: tuple[WireId, ...]
WireId [source]¶
class WireIdIdentify one version of a virtual quantum wire.
Parameters:
| Name | Type | Description |
|---|---|---|
value | int | Non-negative module-local wire number. |
Constructor¶
def __init__(self, value: int) -> NoneAttributes¶
value: int
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¶
| Class | Description |
|---|---|
BinaryOperator | Enumerate scalar operations preserved until target materialization. |
CallControlMode | Enumerate how a target realizes controls on reusable calls. |
CallPhaseMode | Enumerate how a target realizes phase in coherently controlled calls. |
CallTransformCapabilities | Declare reusable-call forms accepted by a target realization. |
CircuitCapabilities | Declare the complete circuit-IR language accepted by one target. |
CompilationPolicy | Select preferred realizations among target-supported alternatives. |
GateKind | Classification of gates for emission. |
GlobalPhaseCapabilities | Declare exact standalone global-phase realization requirements. |
NativeSemanticOpCapabilities | Declare a target-native realization of an abstract operation. |
PauliEvolutionRealization | Enumerate legalization states for abstract Pauli evolution. |
ReusableCircuit | Describe a reusable circuit body and requested transforms. |
ScalarAtom | Enumerate leaf values that may occur in a scalar expression. |
ScalarCapabilities | Declare the scalar language accepted in one instruction context. |
ScalarExpressionForm | Enumerate permitted runtime-parameter expression shapes. |
SemanticOpKey | Identify an abstract operation independently of any engine. |
UnaryOperator | Enumerate unary scalar operations preserved for materialization. |
Constants¶
ALL_BINARY_OPERATORS:frozenset[BinaryOperator]=frozenset(BinaryOperator)Every binary operator in the circuit scalar vocabulary.ALL_PRIMITIVE_GATES:frozenset[GateKind]=frozenset(GateKind) - {GateKind.MEASURE}Every gate kind valid inGateInstruction.ALL_UNARY_OPERATORS:frozenset[UnaryOperator]=frozenset(UnaryOperator)Every unary operator in the circuit scalar vocabulary.ARITHMETIC_BINARY_OPERATORS:frozenset[BinaryOperator]Binary operators that produce arithmetic scalar values.DEFAULT_POLICY=CompilationPolicy()Policy used when an engine transpiler does not supply one.
Classes¶
BinaryOperator [source]¶
class BinaryOperator(enum.Enum)Enumerate scalar operations preserved until target materialization.
Attributes¶
ADDANDDIVEQFLOORDIVGEGTLELTMODMULNEQORPOWSUB
CallControlMode [source]¶
class CallControlMode(enum.Enum)Enumerate how a target realizes controls on reusable calls.
Attributes¶
DISTRIBUTEUNSUPPORTEDWHOLE_CALL
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¶
EXPLICIT_CORRECTIONNATIVE_BODYUNSUPPORTED
CallTransformCapabilities [source]¶
class CallTransformCapabilitiesDeclare reusable-call forms accepted by a target realization.
Parameters:
| Name | Type | Description |
|---|---|---|
supports_power | bool | Whether powers other than one are accepted. |
supports_inverse | bool | Whether inverse calls are accepted. |
max_controls | int | None | Maximum added controls. None means no declared limit. |
supports_nonunitary_body | bool | Whether a reusable body may contain measurement, reset, or dynamic control flow. |
supports_barrier_body | bool | Whether barriers may remain inside a reusable body. |
control_mode | CallControlMode | How added controls are realized. |
controlled_gate_kinds | frozenset[GateKind] | Body gate kinds accepted when controls are distributed into the body. |
controlled_pauli_time | ScalarCapabilities | None | Pauli-time scalar language accepted under distributed controls, or None when controlled Pauli evolution is unsupported. |
phase_mode | CallPhaseMode | How 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_scalars | ScalarCapabilities | None | Scalar 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,
) -> NoneAttributes¶
control_mode: CallControlModecontrolled_gate_kinds: frozenset[GateKind]controlled_pauli_time: ScalarCapabilities | Nonecontrolled_phase_scalars: ScalarCapabilities | Nonemax_controls: int | Nonephase_mode: CallPhaseModesupports_barrier_body: boolsupports_inverse: boolsupports_nonunitary_body: boolsupports_power: bool
Methods¶
accepts¶
def accepts(self, callee: ReusableCircuit, inherited_controls: int = 0) -> boolReturn whether this declaration accepts a concrete call shape.
Parameters:
| Name | Type | Description |
|---|---|---|
callee | ReusableCircuit | Reusable body and requested transforms. |
inherited_controls | int | Controls physically distributed from an enclosing call. Defaults to zero. |
Returns:
bool — Whether power, inverse, and control transforms are accepted.
CircuitCapabilities [source]¶
class CircuitCapabilitiesDeclare the complete circuit-IR language accepted by one target.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Stable target name used in diagnostics. |
primitive_gates | frozenset[GateKind] | Primitive gate kinds accepted by the target materializer. |
native_semantic_ops | tuple[NativeSemanticOpCapabilities, ...] | Native realizations keyed by open semantic operation identity. |
gate_parameters | ScalarCapabilities | Scalar language accepted by gate parameters. |
predicates | ScalarCapabilities | Scalar language accepted by dynamic if and while predicates. |
pauli_time | ScalarCapabilities | Scalar language accepted by Pauli evolution time values. |
global_phase | GlobalPhaseCapabilities | ScalarCapabilities | None | Exact standalone phase realization requirements, or None when unsupported. The former ScalarCapabilities value remains accepted and readable for source compatibility. |
generic_calls | CallTransformCapabilities | Reusable-call forms accepted after semantic-call legalization. |
supports_dynamic_if | bool | Whether runtime if regions are accepted. |
supports_dynamic_while | bool | Whether runtime while regions are accepted. |
supports_reset | bool | Whether reset instructions are accepted. |
pauli_realizations | frozenset[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],
) -> NoneAttributes¶
gate_parameters: ScalarCapabilitiesgeneric_calls: CallTransformCapabilitiesglobal_phase: GlobalPhaseCapabilities | ScalarCapabilities | Nonename: strnative_semantic_ops: tuple[NativeSemanticOpCapabilities, ...]normalized_global_phase: GlobalPhaseCapabilities | None Return standalone phase requirements in the extended form.pauli_realizations: frozenset[PauliEvolutionRealization]pauli_time: ScalarCapabilitiespredicates: ScalarCapabilitiesprimitive_gates: frozenset[GateKind]supports_dynamic_if: boolsupports_dynamic_while: boolsupports_reset: bool
Methods¶
native_semantic_op¶
def native_semantic_op(self, key: SemanticOpKey) -> NativeSemanticOpCapabilities | NoneReturn the native declaration for one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
key | SemanticOpKey | Semantic operation key to look up. |
Returns:
NativeSemanticOpCapabilities | None — NativeSemanticOpCapabilities | None: Matching declaration, or
NativeSemanticOpCapabilities | None — None when the target has no native realization.
CompilationPolicy [source]¶
class CompilationPolicySelect preferred realizations among target-supported alternatives.
Parameters:
| Name | Type | Description |
|---|---|---|
prefer_native_semantic_ops | bool | Whether legal target-native realizations are preferred over reusable fallback bodies. Defaults to True. |
prefer_native_pauli_evolution | bool | Whether 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,
) -> NoneAttributes¶
prefer_native_pauli_evolution: boolprefer_native_semantic_ops: bool
GateKind [source]¶
class GateKind(Enum)Classification of gates for emission.
Attributes¶
CHCPCRXCRYCRZCXCYCZHMEASUREPRXRYRZRZZSSDGSWAPTTDGTOFFOLIXYZ
GlobalPhaseCapabilities [source]¶
class GlobalPhaseCapabilitiesDeclare exact standalone global-phase realization requirements.
Parameters:
| Name | Type | Description |
|---|---|---|
scalars | ScalarCapabilities | Scalar language accepted for the phase. |
min_qubits | int | Minimum 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) -> NoneAttributes¶
atoms: frozenset[ScalarAtom] Return the legacy scalar-atom declaration.binary_operators: frozenset[BinaryOperator] Return the legacy binary-operator declaration.min_qubits: intparameter_form: ScalarExpressionForm Return the legacy runtime-parameter expression form.scalars: ScalarCapabilitiesunary_operators: frozenset[UnaryOperator] Return the legacy unary-operator declaration.
NativeSemanticOpCapabilities [source]¶
class NativeSemanticOpCapabilitiesDeclare a target-native realization of an abstract operation.
Parameters:
| Name | Type | Description |
|---|---|---|
key | SemanticOpKey | Engine-independent semantic operation key. |
realization | str | Target-owned realization identifier passed to the materializer after legalization. |
call_transforms | CallTransformCapabilities | Call shapes supported by the native realization. |
operand_widths | tuple[int | None, ...] | None | Required 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_qubits | int | Minimum fallback-body width accepted by the native operation. Defaults to zero. |
max_qubits | int | None | Maximum fallback-body width, or None for no limit. Defaults to None. |
required_arguments | frozenset[str] | Semantic argument names required by this realization. Defaults to none. |
matching_operand_widths | tuple[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], ...] = (),
) -> NoneAttributes¶
call_transforms: CallTransformCapabilitieskey: SemanticOpKeymatching_operand_widths: tuple[tuple[int, int], ...]max_qubits: int | Nonemin_qubits: intoperand_widths: tuple[int | None, ...] | Nonerealization: strrequired_arguments: frozenset[str]
Methods¶
accepts¶
def accepts(self, callee: ReusableCircuit, inherited_controls: int = 0) -> boolReturn whether this realization accepts one semantic call shape.
Parameters:
| Name | Type | Description |
|---|---|---|
callee | ReusableCircuit | Reusable call retaining source operand grouping and deferred transforms. |
inherited_controls | int | Controls 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¶
ABSTRACTGADGETNATIVE
ReusableCircuit [source]¶
class ReusableCircuitDescribe a reusable circuit body and requested transforms.
Parameters:
| Name | Type | Description |
|---|---|---|
body | CircuitProgram | Reusable circuit body. |
name | str | Display and linkage name. |
power | int | Integral repetition count. Defaults to one. |
controls | int | Added control-wire count. Defaults to zero. |
inverse | bool | Whether to apply the inverse body. Defaults to false. |
identity | CallableIdentity | None | Semantic identity preserved for target legalization. None marks an anonymous body. Defaults to None. |
native_realization | str | None | Target-owned realization identifier selected during legalization. None keeps the reusable body as the fallback implementation. Defaults to None. |
operand_widths | tuple[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, ...] = (),
) -> NoneAttributes¶
body: CircuitProgramcontrols: intidentity: CallableIdentity | Noneinverse: boolname: strnative_realization: str | Nonenum_qubits: int Return the transformed call arity.operand_widths: tuple[int, ...]power: int
ScalarAtom [source]¶
class ScalarAtom(enum.Enum)Enumerate leaf values that may occur in a scalar expression.
Attributes¶
CLASSICAL_BITLITERALLOOP_VARIABLEPARAMETER
ScalarCapabilities [source]¶
class ScalarCapabilitiesDeclare the scalar language accepted in one instruction context.
Parameters:
| Name | Type | Description |
|---|---|---|
atoms | frozenset[ScalarAtom] | Leaf value kinds accepted in the expression. |
unary_operators | frozenset[UnaryOperator] | Accepted unary operators. |
binary_operators | frozenset[BinaryOperator] | Accepted binary operators. |
parameter_form | ScalarExpressionForm | Maximum algebraic form for runtime parameters. |
Constructor¶
def __init__(
self,
atoms: frozenset[ScalarAtom],
unary_operators: frozenset[UnaryOperator],
binary_operators: frozenset[BinaryOperator],
parameter_form: ScalarExpressionForm,
) -> NoneAttributes¶
atoms: frozenset[ScalarAtom]binary_operators: frozenset[BinaryOperator]parameter_form: ScalarExpressionFormunary_operators: frozenset[UnaryOperator]
ScalarExpressionForm [source]¶
class ScalarExpressionForm(enum.Enum)Enumerate permitted runtime-parameter expression shapes.
Attributes¶
ARBITRARYCONCRETE_ONLYLINEAR
SemanticOpKey [source]¶
class SemanticOpKeyIdentify 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:
| Name | Type | Description |
|---|---|---|
namespace | str | Stable owner namespace such as qamomile.stdlib. |
name | str | Stable operation name within the namespace. |
version | str | Semantic contract version. Defaults to "1". |
variant | str | None | Optional 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,
) -> NoneAttributes¶
name: strnamespace: strvariant: str | Noneversion: str
UnaryOperator [source]¶
class UnaryOperator(enum.Enum)Enumerate unary scalar operations preserved for materialization.
Attributes¶
NEGNOT
qamomile.circuit.transpiler.circuit_ir.emitter¶
Gate-emitter adapter that lowers the existing circuit walk into circuit IR.
Overview¶
| Function | Description |
|---|---|
as_scalar_expr | Normalize a Python scalar or existing expression. |
| Class | Description |
|---|---|
BinOpKind | |
BinaryExpr | Apply a binary scalar operation. |
BinaryOperator | Enumerate scalar operations preserved until target materialization. |
CircuitBuilder | Build immutable circuit IR while assigning fresh wire versions. |
CircuitGateEmitter | Emit primitive operations into engine-neutral circuit IR. |
CircuitProgram | Store one immutable engine-neutral circuit program. |
ClassicalBitExpr | Reference a measured classical bit. |
GateKind | Classification of gates for emission. |
MeasurementMode | How an engine handles measurement operations. |
ParameterExpr | Reference a runtime circuit parameter. |
ReusableCircuit | Describe a reusable circuit body and requested transforms. |
Constants¶
ScalarExpr:TypeAlias
Functions¶
as_scalar_expr [source]¶
def as_scalar_expr(value: ScalarExpr | bool | int | float) -> ScalarExprNormalize a Python scalar or existing expression.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ScalarExpr | bool | int | float | Value to normalize. |
Returns:
ScalarExpr — Existing expression or a new literal expression.
Classes¶
BinOpKind [source]¶
class BinOpKind(enum.Enum)Attributes¶
ADDDIVFLOORDIVMINMODMULPOWSUB
BinaryExpr [source]¶
class BinaryExpr(_ScalarOperators)Apply a binary scalar operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operator | BinaryOperator | Operation kind. |
left | ScalarExpr | Left operand. |
right | ScalarExpr | Right operand. |
Constructor¶
def __init__(self, operator: BinaryOperator, left: ScalarExpr, right: ScalarExpr) -> NoneAttributes¶
left: ScalarExproperator: BinaryOperatorright: ScalarExpr
BinaryOperator [source]¶
class BinaryOperator(enum.Enum)Enumerate scalar operations preserved until target materialization.
Attributes¶
ADDANDDIVEQFLOORDIVGEGTLELTMODMULNEQORPOWSUB
CircuitBuilder [source]¶
class CircuitBuilderBuild immutable circuit IR while assigning fresh wire versions.
Parameters:
| Name | Type | Description |
|---|---|---|
num_qubits | int | Number of virtual qubit slots. |
num_clbits | int | Number of classical bit slots. |
name | str | Circuit name. Defaults to "main". |
Constructor¶
def __init__(self, num_qubits: int, num_clbits: int, name: str = 'main') -> NoneInitialize a circuit builder.
Parameters:
| Name | Type | Description |
|---|---|---|
num_qubits | int | Number of virtual qubit slots. |
num_clbits | int | Number of classical bit slots. |
name | str | Circuit name. Defaults to "main". |
Raises:
ValueError— If either slot count is negative.
Attributes¶
namenum_clbitsnum_qubitsoperations: list[CircuitInstruction] Return the current region instruction list.
Methods¶
add_global_phase¶
def add_global_phase(self, phase: ScalarExpr | bool | int | float) -> NoneAccumulate a global phase in the current lexical region.
Parameters:
| Name | Type | Description |
|---|---|---|
phase | ScalarExpr | bool | int | float | Phase contribution. |
append_barrier¶
def append_barrier(self, qubits: tuple[int, ...]) -> NoneAppend a scheduling barrier without changing wire versions.
Parameters:
| Name | Type | Description |
|---|---|---|
qubits | tuple[int, ...] | Participating qubit slots. |
append_call¶
def append_call(self, callee: ReusableCircuit, qubits: tuple[int, ...]) -> NoneAppend a reusable-circuit call and advance its wires.
Parameters:
| Name | Type | Description |
|---|---|---|
callee | ReusableCircuit | Reusable circuit and transforms. |
qubits | tuple[int, ...] | Participating qubit slots. |
append_gate¶
def append_gate(
self,
kind: GateKind,
qubits: tuple[int, ...],
parameters: tuple[ScalarExpr, ...] = (),
) -> NoneAppend a primitive gate and advance all participating wires.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | GateKind | Primitive gate kind. |
qubits | tuple[int, ...] | Participating qubit slots. |
parameters | tuple[ScalarExpr, ...] | Gate parameters. Defaults to an empty tuple. |
append_measure¶
def append_measure(self, qubit: int, clbit: int) -> NoneAppend a measurement.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | int | Measured qubit slot. |
clbit | int | Destination classical bit slot. |
Raises:
IndexError— Ifclbitis outside the allocated classical slots.
append_measure_vector¶
def append_measure_vector(self, qubits: tuple[int, ...], clbits: tuple[int, ...]) -> NoneAppend one ordered vector measurement.
Parameters:
| Name | Type | Description |
|---|---|---|
qubits | tuple[int, ...] | Measured qubit slots in result order. |
clbits | tuple[int, ...] | Destination classical slots. |
Raises:
ValueError— If qubit and classical-bit arities differ or either sequence contains duplicate slots.IndexError— If a classical-bit slot is outside the circuit.
append_pauli_evolution¶
def append_pauli_evolution(
self,
qubits: tuple[int, ...],
hamiltonian: Any,
time: ScalarExpr | bool | int | float,
) -> NoneAppend an abstract Pauli evolution and advance its wires.
Parameters:
| Name | Type | Description |
|---|---|---|
qubits | tuple[int, ...] | Participating qubit slots. |
hamiltonian | Any | Qamomile Hamiltonian value. |
time | ScalarExpr | bool | int | float | Evolution time. |
Raises:
ValueError— If a Qamomile Hamiltonian has a non-Hermitian identity coefficient.
append_reset¶
def append_reset(self, qubit: int) -> NoneAppend reset and advance the affected wire.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | int | Qubit slot to reset. |
begin_else¶
def begin_else(self, context: _IfContext) -> NoneClose a true region and open its false region.
Parameters:
| Name | Type | Description |
|---|---|---|
context | _IfContext | Token returned by :meth:begin_if. |
Raises:
RuntimeError— Ifcontextis not the innermost open conditional or an else branch has already started.
begin_for¶
def begin_for(self, indexset: range) -> LoopVariableExprOpen a structured for-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
indexset | range | Concrete iteration range. |
Returns:
LoopVariableExpr — Induction expression available inside the body.
begin_if¶
def begin_if(self, condition: ScalarExpr) -> _IfContextOpen the true region of a structured conditional.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime branch predicate. |
Returns:
_IfContext — Opaque builder token used to select the else branch.
begin_while¶
def begin_while(self, condition: ScalarExpr) -> _WhileContextOpen a structured while-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime loop predicate. |
Returns:
_WhileContext — Opaque builder token used to close the loop.
current_wire¶
def current_wire(self, qubit: int) -> WireIdReturn the current wire version for a qubit slot.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | int | Physical slot index assigned by circuit lowering. |
Returns:
WireId — Current version of the slot.
Raises:
KeyError— Ifqubitis outside the allocated slot range.
end_for¶
def end_for(self) -> NoneClose the innermost structured for-loop body.
Raises:
RuntimeError— If the innermost open region is not a for loop.
end_if¶
def end_if(self, context: _IfContext) -> NoneClose a structured conditional and merge its wire states.
Parameters:
| Name | Type | Description |
|---|---|---|
context | _IfContext | Token returned by :meth:begin_if. |
Raises:
RuntimeError— Ifcontextis not the innermost open conditional.
end_while¶
def end_while(self, context: _WhileContext) -> NoneClose a structured while-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
context | _WhileContext | Token returned by :meth:begin_while. |
Raises:
RuntimeError— Ifcontextis not the innermost open while loop.
freeze¶
def freeze(self) -> CircuitProgramFinalize the root region into immutable circuit IR.
Returns:
CircuitProgram — Immutable circuit program.
Raises:
RuntimeError— If a structured region is still open.
fresh_wire¶
def fresh_wire(self) -> WireIdAllocate a fresh module-local virtual wire version.
Returns:
WireId — Newly allocated wire identifier.
restore_state¶
def restore_state(self, snapshot: _CircuitBuilderSnapshot) -> NoneRestore a checkpoint after an append-only emission attempt.
Parameters:
| Name | Type | Description |
|---|---|---|
snapshot | _CircuitBuilderSnapshot | Checkpoint returned by :meth:snapshot_state for this builder. |
Raises:
RuntimeError— If emission removed or replaced state that existed before the checkpoint instead of only appending new state.
snapshot_state¶
def snapshot_state(self) -> _CircuitBuilderSnapshotCapture state that can be restored after declined emission.
Returns:
_CircuitBuilderSnapshot — Append-only builder checkpoint for the
current structured region.
CircuitGateEmitter [source]¶
class CircuitGateEmitterEmit primitive operations into engine-neutral circuit IR.
Attributes¶
measurement_mode: MeasurementMode Return native measurement mode for explicit circuit IR.
Methods¶
append_gate¶
def append_gate(
self,
circuit: CircuitBuilder,
gate: ReusableCircuit,
qubits: list[int],
) -> NoneAppend a reusable circuit call.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
gate | ReusableCircuit | Reusable circuit value. |
qubits | list[int] | Participating slots. |
circuit_to_gate¶
def circuit_to_gate(
self,
circuit: CircuitBuilder | CircuitProgram,
name: str = 'U',
) -> ReusableCircuitFreeze a circuit as a reusable circuit value.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | CircuitProgram | Circuit body. |
name | str | Reusable 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 | NoneCombine symbolic operands without creating engine expressions.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | BinOpKind | Qamomile arithmetic operation. |
lhs | ScalarExpr | bool | int | float | Left operand. |
rhs | ScalarExpr | bool | int | float | Right 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) -> CircuitBuilderCreate an empty circuit IR builder.
Parameters:
| Name | Type | Description |
|---|---|---|
num_qubits | int | Number of virtual qubit slots. |
num_clbits | int | Number of classical bit slots. |
Returns:
CircuitBuilder — Empty engine-neutral builder.
create_parameter¶
def create_parameter(self, name: str) -> ParameterExprCreate a target-neutral runtime parameter expression.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | External parameter name. |
Returns:
ParameterExpr — Parameter reference preserved until materialization.
emit_barrier¶
def emit_barrier(self, circuit: CircuitBuilder, qubits: list[int]) -> NoneEmit a scheduling barrier.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubits | list[int] | Participating slots. |
emit_ch¶
def emit_ch(self, circuit: CircuitBuilder, control: int, target: int) -> NoneEmit a controlled-H gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
emit_cp¶
def emit_cp(
self,
circuit: CircuitBuilder,
control: int,
target: int,
angle: ScalarExpr | float,
) -> NoneEmit a controlled-phase rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
angle | ScalarExpr | float | Phase angle in radians. |
emit_crx¶
def emit_crx(
self,
circuit: CircuitBuilder,
control: int,
target: int,
angle: ScalarExpr | float,
) -> NoneEmit a controlled-RX rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_cry¶
def emit_cry(
self,
circuit: CircuitBuilder,
control: int,
target: int,
angle: ScalarExpr | float,
) -> NoneEmit a controlled-RY rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_crz¶
def emit_crz(
self,
circuit: CircuitBuilder,
control: int,
target: int,
angle: ScalarExpr | float,
) -> NoneEmit a controlled-RZ rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_cx¶
def emit_cx(self, circuit: CircuitBuilder, control: int, target: int) -> NoneEmit a controlled-X gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
emit_cy¶
def emit_cy(self, circuit: CircuitBuilder, control: int, target: int) -> NoneEmit a controlled-Y gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
emit_cz¶
def emit_cz(self, circuit: CircuitBuilder, control: int, target: int) -> NoneEmit a controlled-Z gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
emit_else_start¶
def emit_else_start(self, circuit: CircuitBuilder, context: Any) -> NoneSwitch an open conditional to its false branch.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
context | Any | Opaque conditional context. |
emit_for_loop_end¶
def emit_for_loop_end(self, circuit: CircuitBuilder, context: Any) -> NoneClose a structured for-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
context | Any | Induction expression returned at loop start. |
emit_for_loop_start¶
def emit_for_loop_start(self, circuit: CircuitBuilder, indexset: range) -> ScalarExprOpen a structured for-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
indexset | range | Concrete iteration range. |
Returns:
ScalarExpr — Target-neutral induction expression.
emit_global_phase¶
def emit_global_phase(self, circuit: CircuitBuilder, angle: ScalarExpr | float) -> NoneAccumulate a phase in the builder’s current lexical region.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
angle | ScalarExpr | float | Phase angle in radians. |
emit_h¶
def emit_h(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit a Hadamard gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_if_end¶
def emit_if_end(self, circuit: CircuitBuilder, context: Any) -> NoneClose a structured conditional.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
context | Any | Opaque conditional context. |
emit_if_start¶
def emit_if_start(self, circuit: CircuitBuilder, clbit: int, value: int = 1) -> AnyOpen a structured conditional true branch.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
clbit | int | Predicate classical bit slot. |
value | int | Required bit value. Defaults to one. |
Returns:
Any — Opaque conditional builder context.
emit_measure¶
def emit_measure(self, circuit: CircuitBuilder, qubit: int, clbit: int) -> NoneEmit a measurement into a classical slot.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Measured qubit slot. |
clbit | int | Destination classical slot. |
emit_measure_vector¶
def emit_measure_vector(
self,
circuit: CircuitBuilder,
qubits: tuple[int, ...],
clbits: tuple[int, ...],
) -> NonePreserve an ordered vector measurement as one instruction.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubits | tuple[int, ...] | Measured qubit slots in result order. |
clbits | tuple[int, ...] | Destination classical slots. |
emit_p¶
def emit_p(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> NoneEmit a phase rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
angle | ScalarExpr | float | Phase angle in radians. |
emit_reset¶
def emit_reset(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit a reset-to-zero operation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Reset qubit slot. |
emit_rx¶
def emit_rx(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> NoneEmit an RX rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_ry¶
def emit_ry(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> NoneEmit an RY rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_rz¶
def emit_rz(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> NoneEmit an RZ rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_rzz¶
def emit_rzz(
self,
circuit: CircuitBuilder,
qubit1: int,
qubit2: int,
angle: ScalarExpr | float,
) -> NoneEmit an RZZ rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit1 | int | First slot. |
qubit2 | int | Second slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_s¶
def emit_s(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit an S gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_sdg¶
def emit_sdg(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit an inverse-S gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_swap¶
def emit_swap(self, circuit: CircuitBuilder, qubit1: int, qubit2: int) -> NoneEmit a SWAP gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit1 | int | First slot. |
qubit2 | int | Second slot. |
emit_t¶
def emit_t(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit a T gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_tdg¶
def emit_tdg(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit an inverse-T gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_toffoli¶
def emit_toffoli(
self,
circuit: CircuitBuilder,
control1: int,
control2: int,
target: int,
) -> NoneEmit a Toffoli gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control1 | int | First control slot. |
control2 | int | Second control slot. |
target | int | Target slot. |
emit_while_end¶
def emit_while_end(self, circuit: CircuitBuilder, context: Any) -> NoneClose a structured while-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
context | Any | Opaque while-loop context. |
emit_while_start¶
def emit_while_start(self, circuit: CircuitBuilder, clbit: int, value: int = 1) -> AnyOpen a structured while-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
clbit | int | Predicate classical bit slot. |
value | int | Required bit value. Defaults to one. |
Returns:
Any — Opaque while-loop builder context.
emit_x¶
def emit_x(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit a Pauli-X gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_y¶
def emit_y(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit a Pauli-Y gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_z¶
def emit_z(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit a Pauli-Z gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
gate_controlled¶
def gate_controlled(self, gate: ReusableCircuit, num_controls: int) -> ReusableCircuitAdd control wires to a reusable circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | ReusableCircuit | Reusable circuit value. |
num_controls | int | Number of controls to add. |
Returns:
ReusableCircuit — Controlled reusable circuit.
gate_inverse¶
def gate_inverse(self, gate: ReusableCircuit) -> ReusableCircuitToggle the inverse transform on a reusable circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | ReusableCircuit | Reusable circuit value. |
Returns:
ReusableCircuit — Inverse reusable circuit.
gate_power¶
def gate_power(self, gate: ReusableCircuit, power: int) -> ReusableCircuitApply an integral power transform to a reusable circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | ReusableCircuit | Reusable circuit value. |
power | int | Integral repetition count. |
Returns:
ReusableCircuit — Transformed reusable circuit.
supports_for_loop¶
def supports_for_loop(self) -> boolReport support for structured for loops.
Returns:
bool — Always True for circuit IR.
supports_gate_inverse¶
def supports_gate_inverse(self) -> boolReport support for deferred inverse transforms.
Returns:
bool — Always True for circuit IR.
supports_if_else¶
def supports_if_else(self) -> boolReport support for structured conditionals.
Returns:
bool — Always True for circuit IR.
supports_reusable_gates¶
def supports_reusable_gates(self) -> boolReport 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) -> boolReport support for structured while loops.
Returns:
bool — Always True for circuit IR.
CircuitProgram [source]¶
class CircuitProgramStore one immutable engine-neutral circuit program.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Circuit entrypoint name. |
num_qubits | int | Number of virtual input qubit slots. |
num_clbits | int | Number of classical bit slots. |
input_wires | tuple[WireId, ...] | Initial wire version per qubit slot. |
output_wires | tuple[WireId, ...] | Final wire version per qubit slot. |
operations | tuple[CircuitInstruction, ...] | Structured instruction sequence. |
global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
global_phase: ScalarExprinput_wires: tuple[WireId, ...]name: strnum_clbits: intnum_qubits: intoperations: tuple[CircuitInstruction, ...]output_wires: tuple[WireId, ...]
ClassicalBitExpr [source]¶
class ClassicalBitExpr(_ScalarOperators)Reference a measured classical bit.
Parameters:
| Name | Type | Description |
|---|---|---|
index | int | Circuit-local classical bit index. |
Constructor¶
def __init__(self, index: int) -> NoneAttributes¶
index: int
GateKind [source]¶
class GateKind(Enum)Classification of gates for emission.
Attributes¶
CHCPCRXCRYCRZCXCYCZHMEASUREPRXRYRZRZZSSDGSWAPTTDGTOFFOLIXYZ
MeasurementMode [source]¶
class MeasurementMode(Enum)How an engine handles measurement operations.
Attributes¶
NATIVERUNNABLESTATIC
ParameterExpr [source]¶
class ParameterExpr(_ScalarOperators)Reference a runtime circuit parameter.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Stable external parameter name. |
Constructor¶
def __init__(self, name: str) -> NoneAttributes¶
name: str
ReusableCircuit [source]¶
class ReusableCircuitDescribe a reusable circuit body and requested transforms.
Parameters:
| Name | Type | Description |
|---|---|---|
body | CircuitProgram | Reusable circuit body. |
name | str | Display and linkage name. |
power | int | Integral repetition count. Defaults to one. |
controls | int | Added control-wire count. Defaults to zero. |
inverse | bool | Whether to apply the inverse body. Defaults to false. |
identity | CallableIdentity | None | Semantic identity preserved for target legalization. None marks an anonymous body. Defaults to None. |
native_realization | str | None | Target-owned realization identifier selected during legalization. None keeps the reusable body as the fallback implementation. Defaults to None. |
operand_widths | tuple[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, ...] = (),
) -> NoneAttributes¶
body: CircuitProgramcontrols: intidentity: CallableIdentity | Noneinverse: boolname: strnative_realization: str | Nonenum_qubits: int Return the transformed call arity.operand_widths: tuple[int, ...]power: int
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¶
| Function | Description |
|---|---|
legalize_program | Rewrite one circuit program until it is legal for a target. |
verify_target_legal | Prove a legalized program against declared target capabilities. |
| Class | Description |
|---|---|
BarrierInstruction | Separate scheduling regions without changing wire versions. |
BinaryExpr | Apply a binary scalar operation. |
BinaryOperator | Enumerate scalar operations preserved until target materialization. |
CallControlMode | Enumerate how a target realizes controls on reusable calls. |
CallInstruction | Invoke a reusable circuit over versioned wires. |
CallPhaseMode | Enumerate how a target realizes phase in coherently controlled calls. |
CallTransformCapabilities | Declare reusable-call forms accepted by a target realization. |
CallableIdentity | Preserve the semantic identity of a reusable circuit body. |
CircuitCapabilities | Declare the complete circuit-IR language accepted by one target. |
CircuitProgram | Store one immutable engine-neutral circuit program. |
ClassicalBitExpr | Reference a measured classical bit. |
CompilationPolicy | Select preferred realizations among target-supported alternatives. |
ForInstruction | Repeat a structured circuit region over a concrete range. |
GateInstruction | Apply one primitive gate to versioned virtual wires. |
IfInstruction | Select between two structured circuit regions. |
LiteralExpr | Represent a concrete scalar literal. |
LoopVariableExpr | Reference the induction value of a structured loop. |
MeasureInstruction | Measure a wire into a classical bit. |
MeasureVectorInstruction | Measure an ordered group of wires into classical bits. |
ParameterExpr | Reference a runtime circuit parameter. |
PauliEvolutionInstruction | Apply an abstract Hamiltonian evolution to selected wires. |
PauliEvolutionRealization | Enumerate legalization states for abstract Pauli evolution. |
ResetInstruction | Reset a wire and produce a fresh zero-state wire. |
ReusableCircuit | Describe a reusable circuit body and requested transforms. |
ScalarAtom | Enumerate leaf values that may occur in a scalar expression. |
ScalarCapabilities | Declare the scalar language accepted in one instruction context. |
ScalarExpressionForm | Enumerate permitted runtime-parameter expression shapes. |
TargetCapabilityError | A program requires a capability the selected target does not declare. |
UnaryExpr | Apply a unary scalar operation. |
UnaryOperator | Enumerate unary scalar operations preserved for materialization. |
WhileInstruction | Repeat a structured region while a runtime predicate is true. |
WireId | Identify one version of a virtual quantum wire. |
Constants¶
CircuitInstruction:TypeAliasScalarExpr:TypeAlias
Functions¶
legalize_program [source]¶
def legalize_program(
program: CircuitProgram,
capabilities: CircuitCapabilities,
policy: CompilationPolicy,
) -> CircuitProgramRewrite 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:
| Name | Type | Description |
|---|---|---|
program | CircuitProgram | Verified engine-neutral circuit program. |
capabilities | CircuitCapabilities | Declared target capabilities. |
policy | CompilationPolicy | User realization preferences. |
Returns:
CircuitProgram — Rebuilt program with freshly numbered wires.
verify_target_legal [source]¶
def verify_target_legal(program: CircuitProgram, capabilities: CircuitCapabilities) -> NoneProve a legalized program against declared target capabilities.
Parameters:
| Name | Type | Description |
|---|---|---|
program | CircuitProgram | Legalized circuit program, including every nested reusable-call body. |
capabilities | CircuitCapabilities | Declared target capabilities. |
Raises:
TargetCapabilityError— If any instruction requires a gate kind, semantic realization, control-flow construct, reset, Pauli evolution, or scalar-expression shape the target does not declare.
Classes¶
BarrierInstruction [source]¶
class BarrierInstructionSeparate scheduling regions without changing wire versions.
Parameters:
| Name | Type | Description |
|---|---|---|
wires | tuple[WireId, ...] | Wires participating in the barrier. |
Constructor¶
def __init__(self, wires: tuple[WireId, ...]) -> NoneAttributes¶
wires: tuple[WireId, ...]
BinaryExpr [source]¶
class BinaryExpr(_ScalarOperators)Apply a binary scalar operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operator | BinaryOperator | Operation kind. |
left | ScalarExpr | Left operand. |
right | ScalarExpr | Right operand. |
Constructor¶
def __init__(self, operator: BinaryOperator, left: ScalarExpr, right: ScalarExpr) -> NoneAttributes¶
left: ScalarExproperator: BinaryOperatorright: ScalarExpr
BinaryOperator [source]¶
class BinaryOperator(enum.Enum)Enumerate scalar operations preserved until target materialization.
Attributes¶
ADDANDDIVEQFLOORDIVGEGTLELTMODMULNEQORPOWSUB
CallControlMode [source]¶
class CallControlMode(enum.Enum)Enumerate how a target realizes controls on reusable calls.
Attributes¶
DISTRIBUTEUNSUPPORTEDWHOLE_CALL
CallInstruction [source]¶
class CallInstructionInvoke a reusable circuit over versioned wires.
Parameters:
| Name | Type | Description |
|---|---|---|
callee | ReusableCircuit | Reusable circuit and transforms. |
inputs | tuple[WireId, ...] | Consumed wire versions. |
outputs | tuple[WireId, ...] | Produced wire versions. |
Constructor¶
def __init__(
self,
callee: ReusableCircuit,
inputs: tuple[WireId, ...],
outputs: tuple[WireId, ...],
) -> NoneAttributes¶
callee: ReusableCircuitinputs: tuple[WireId, ...]outputs: tuple[WireId, ...]
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¶
EXPLICIT_CORRECTIONNATIVE_BODYUNSUPPORTED
CallTransformCapabilities [source]¶
class CallTransformCapabilitiesDeclare reusable-call forms accepted by a target realization.
Parameters:
| Name | Type | Description |
|---|---|---|
supports_power | bool | Whether powers other than one are accepted. |
supports_inverse | bool | Whether inverse calls are accepted. |
max_controls | int | None | Maximum added controls. None means no declared limit. |
supports_nonunitary_body | bool | Whether a reusable body may contain measurement, reset, or dynamic control flow. |
supports_barrier_body | bool | Whether barriers may remain inside a reusable body. |
control_mode | CallControlMode | How added controls are realized. |
controlled_gate_kinds | frozenset[GateKind] | Body gate kinds accepted when controls are distributed into the body. |
controlled_pauli_time | ScalarCapabilities | None | Pauli-time scalar language accepted under distributed controls, or None when controlled Pauli evolution is unsupported. |
phase_mode | CallPhaseMode | How 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_scalars | ScalarCapabilities | None | Scalar 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,
) -> NoneAttributes¶
control_mode: CallControlModecontrolled_gate_kinds: frozenset[GateKind]controlled_pauli_time: ScalarCapabilities | Nonecontrolled_phase_scalars: ScalarCapabilities | Nonemax_controls: int | Nonephase_mode: CallPhaseModesupports_barrier_body: boolsupports_inverse: boolsupports_nonunitary_body: boolsupports_power: bool
Methods¶
accepts¶
def accepts(self, callee: ReusableCircuit, inherited_controls: int = 0) -> boolReturn whether this declaration accepts a concrete call shape.
Parameters:
| Name | Type | Description |
|---|---|---|
callee | ReusableCircuit | Reusable body and requested transforms. |
inherited_controls | int | Controls physically distributed from an enclosing call. Defaults to zero. |
Returns:
bool — Whether power, inverse, and control transforms are accepted.
CallableIdentity [source]¶
class CallableIdentityPreserve the semantic identity of a reusable circuit body.
Parameters:
| Name | Type | Description |
|---|---|---|
key | SemanticOpKey | Open semantic identity used by target-native realization registries. |
symbol | str | Human-readable callable name used for diagnostics. |
arguments | SemanticArguments | Immutable arguments that define this invocation’s meaning. Defaults to no arguments. |
Constructor¶
def __init__(
self,
key: SemanticOpKey,
symbol: str,
arguments: SemanticArguments = SemanticArguments(),
) -> NoneAttributes¶
arguments: SemanticArgumentskey: SemanticOpKeysymbol: str
CircuitCapabilities [source]¶
class CircuitCapabilitiesDeclare the complete circuit-IR language accepted by one target.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Stable target name used in diagnostics. |
primitive_gates | frozenset[GateKind] | Primitive gate kinds accepted by the target materializer. |
native_semantic_ops | tuple[NativeSemanticOpCapabilities, ...] | Native realizations keyed by open semantic operation identity. |
gate_parameters | ScalarCapabilities | Scalar language accepted by gate parameters. |
predicates | ScalarCapabilities | Scalar language accepted by dynamic if and while predicates. |
pauli_time | ScalarCapabilities | Scalar language accepted by Pauli evolution time values. |
global_phase | GlobalPhaseCapabilities | ScalarCapabilities | None | Exact standalone phase realization requirements, or None when unsupported. The former ScalarCapabilities value remains accepted and readable for source compatibility. |
generic_calls | CallTransformCapabilities | Reusable-call forms accepted after semantic-call legalization. |
supports_dynamic_if | bool | Whether runtime if regions are accepted. |
supports_dynamic_while | bool | Whether runtime while regions are accepted. |
supports_reset | bool | Whether reset instructions are accepted. |
pauli_realizations | frozenset[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],
) -> NoneAttributes¶
gate_parameters: ScalarCapabilitiesgeneric_calls: CallTransformCapabilitiesglobal_phase: GlobalPhaseCapabilities | ScalarCapabilities | Nonename: strnative_semantic_ops: tuple[NativeSemanticOpCapabilities, ...]normalized_global_phase: GlobalPhaseCapabilities | None Return standalone phase requirements in the extended form.pauli_realizations: frozenset[PauliEvolutionRealization]pauli_time: ScalarCapabilitiespredicates: ScalarCapabilitiesprimitive_gates: frozenset[GateKind]supports_dynamic_if: boolsupports_dynamic_while: boolsupports_reset: bool
Methods¶
native_semantic_op¶
def native_semantic_op(self, key: SemanticOpKey) -> NativeSemanticOpCapabilities | NoneReturn the native declaration for one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
key | SemanticOpKey | Semantic operation key to look up. |
Returns:
NativeSemanticOpCapabilities | None — NativeSemanticOpCapabilities | None: Matching declaration, or
NativeSemanticOpCapabilities | None — None when the target has no native realization.
CircuitProgram [source]¶
class CircuitProgramStore one immutable engine-neutral circuit program.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Circuit entrypoint name. |
num_qubits | int | Number of virtual input qubit slots. |
num_clbits | int | Number of classical bit slots. |
input_wires | tuple[WireId, ...] | Initial wire version per qubit slot. |
output_wires | tuple[WireId, ...] | Final wire version per qubit slot. |
operations | tuple[CircuitInstruction, ...] | Structured instruction sequence. |
global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
global_phase: ScalarExprinput_wires: tuple[WireId, ...]name: strnum_clbits: intnum_qubits: intoperations: tuple[CircuitInstruction, ...]output_wires: tuple[WireId, ...]
ClassicalBitExpr [source]¶
class ClassicalBitExpr(_ScalarOperators)Reference a measured classical bit.
Parameters:
| Name | Type | Description |
|---|---|---|
index | int | Circuit-local classical bit index. |
Constructor¶
def __init__(self, index: int) -> NoneAttributes¶
index: int
CompilationPolicy [source]¶
class CompilationPolicySelect preferred realizations among target-supported alternatives.
Parameters:
| Name | Type | Description |
|---|---|---|
prefer_native_semantic_ops | bool | Whether legal target-native realizations are preferred over reusable fallback bodies. Defaults to True. |
prefer_native_pauli_evolution | bool | Whether 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,
) -> NoneAttributes¶
prefer_native_pauli_evolution: boolprefer_native_semantic_ops: bool
ForInstruction [source]¶
class ForInstructionRepeat a structured circuit region over a concrete range.
Parameters:
| Name | Type | Description |
|---|---|---|
indexset | range | Concrete iteration range. |
loop_variable | LoopVariableExpr | Induction expression used by the body. |
inputs | tuple[WireId, ...] | Wire versions entering the loop. |
body | tuple[CircuitInstruction, ...] | Single-iteration body. |
body_outputs | tuple[WireId, ...] | Body wire versions yielded to the next iteration. |
outputs | tuple[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, ...],
) -> NoneAttributes¶
body: tuple[CircuitInstruction, ...]body_outputs: tuple[WireId, ...]indexset: rangeinputs: tuple[WireId, ...]loop_variable: LoopVariableExproutputs: tuple[WireId, ...]
GateInstruction [source]¶
class GateInstructionApply one primitive gate to versioned virtual wires.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | GateKind | Primitive gate kind. |
inputs | tuple[WireId, ...] | Consumed wire versions. |
outputs | tuple[WireId, ...] | Produced wire versions. |
parameters | tuple[ScalarExpr, ...] | Gate parameters. |
Constructor¶
def __init__(
self,
kind: GateKind,
inputs: tuple[WireId, ...],
outputs: tuple[WireId, ...],
parameters: tuple[ScalarExpr, ...] = (),
) -> NoneAttributes¶
inputs: tuple[WireId, ...]kind: GateKindoutputs: tuple[WireId, ...]parameters: tuple[ScalarExpr, ...]
IfInstruction [source]¶
class IfInstructionSelect between two structured circuit regions.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime branch predicate. |
inputs | tuple[WireId, ...] | Wires entering both branches. |
true_body | tuple[CircuitInstruction, ...] | True branch body. |
false_body | tuple[CircuitInstruction, ...] | False branch body. |
true_outputs | tuple[WireId, ...] | Wires yielded by the true branch. |
false_outputs | tuple[WireId, ...] | Wires yielded by the false branch. |
outputs | tuple[WireId, ...] | Merged post-branch wires. |
true_global_phase | ScalarExpr | Phase applied only in the true branch. |
false_global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
condition: ScalarExprfalse_body: tuple[CircuitInstruction, ...]false_global_phase: ScalarExprfalse_outputs: tuple[WireId, ...]inputs: tuple[WireId, ...]outputs: tuple[WireId, ...]true_body: tuple[CircuitInstruction, ...]true_global_phase: ScalarExprtrue_outputs: tuple[WireId, ...]
LiteralExpr [source]¶
class LiteralExpr(_ScalarOperators)Represent a concrete scalar literal.
Parameters:
| Name | Type | Description |
|---|---|---|
value | bool | int | float | Concrete scalar value. |
Constructor¶
def __init__(self, value: bool | int | float) -> NoneAttributes¶
value: bool | int | float
LoopVariableExpr [source]¶
class LoopVariableExpr(_ScalarOperators)Reference the induction value of a structured loop.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Circuit-local loop variable name. |
Constructor¶
def __init__(self, name: str) -> NoneAttributes¶
name: str
MeasureInstruction [source]¶
class MeasureInstructionMeasure a wire into a classical bit.
Parameters:
| Name | Type | Description |
|---|---|---|
input | WireId | Measured wire version. |
output | WireId | Post-measurement wire version. |
clbit | int | Destination classical bit index. |
Constructor¶
def __init__(self, input: WireId, output: WireId, clbit: int) -> NoneAttributes¶
clbit: intinput: WireIdoutput: WireId
MeasureVectorInstruction [source]¶
class MeasureVectorInstructionMeasure 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:
| Name | Type | Description |
|---|---|---|
inputs | tuple[WireId, ...] | Measured wire versions in result order. |
outputs | tuple[WireId, ...] | Post-measurement wire versions. |
clbits | tuple[int, ...] | Destination classical bits in result order. |
Constructor¶
def __init__(
self,
inputs: tuple[WireId, ...],
outputs: tuple[WireId, ...],
clbits: tuple[int, ...],
) -> NoneAttributes¶
clbits: tuple[int, ...]inputs: tuple[WireId, ...]outputs: tuple[WireId, ...]
ParameterExpr [source]¶
class ParameterExpr(_ScalarOperators)Reference a runtime circuit parameter.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Stable external parameter name. |
Constructor¶
def __init__(self, name: str) -> NoneAttributes¶
name: str
PauliEvolutionInstruction [source]¶
class PauliEvolutionInstructionApply an abstract Hamiltonian evolution to selected wires.
Parameters:
| Name | Type | Description |
|---|---|---|
hamiltonian | Any | Immutable Qamomile Hamiltonian value. |
time | ScalarExpr | Evolution time in radians. |
inputs | tuple[WireId, ...] | Consumed wire versions. |
outputs | tuple[WireId, ...] | Produced wire versions. |
realization | PauliEvolutionRealization | Target 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,
) -> NoneAttributes¶
hamiltonian: Anyinputs: tuple[WireId, ...]outputs: tuple[WireId, ...]realization: PauliEvolutionRealizationtime: ScalarExpr
PauliEvolutionRealization [source]¶
class PauliEvolutionRealization(enum.Enum)Enumerate legalization states for abstract Pauli evolution.
Attributes¶
ABSTRACTGADGETNATIVE
ResetInstruction [source]¶
class ResetInstructionReset a wire and produce a fresh zero-state wire.
Parameters:
| Name | Type | Description |
|---|---|---|
input | WireId | Wire version before reset. |
output | WireId | Fresh wire version after reset. |
Constructor¶
def __init__(self, input: WireId, output: WireId) -> NoneAttributes¶
input: WireIdoutput: WireId
ReusableCircuit [source]¶
class ReusableCircuitDescribe a reusable circuit body and requested transforms.
Parameters:
| Name | Type | Description |
|---|---|---|
body | CircuitProgram | Reusable circuit body. |
name | str | Display and linkage name. |
power | int | Integral repetition count. Defaults to one. |
controls | int | Added control-wire count. Defaults to zero. |
inverse | bool | Whether to apply the inverse body. Defaults to false. |
identity | CallableIdentity | None | Semantic identity preserved for target legalization. None marks an anonymous body. Defaults to None. |
native_realization | str | None | Target-owned realization identifier selected during legalization. None keeps the reusable body as the fallback implementation. Defaults to None. |
operand_widths | tuple[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, ...] = (),
) -> NoneAttributes¶
body: CircuitProgramcontrols: intidentity: CallableIdentity | Noneinverse: boolname: strnative_realization: str | Nonenum_qubits: int Return the transformed call arity.operand_widths: tuple[int, ...]power: int
ScalarAtom [source]¶
class ScalarAtom(enum.Enum)Enumerate leaf values that may occur in a scalar expression.
Attributes¶
CLASSICAL_BITLITERALLOOP_VARIABLEPARAMETER
ScalarCapabilities [source]¶
class ScalarCapabilitiesDeclare the scalar language accepted in one instruction context.
Parameters:
| Name | Type | Description |
|---|---|---|
atoms | frozenset[ScalarAtom] | Leaf value kinds accepted in the expression. |
unary_operators | frozenset[UnaryOperator] | Accepted unary operators. |
binary_operators | frozenset[BinaryOperator] | Accepted binary operators. |
parameter_form | ScalarExpressionForm | Maximum algebraic form for runtime parameters. |
Constructor¶
def __init__(
self,
atoms: frozenset[ScalarAtom],
unary_operators: frozenset[UnaryOperator],
binary_operators: frozenset[BinaryOperator],
parameter_form: ScalarExpressionForm,
) -> NoneAttributes¶
atoms: frozenset[ScalarAtom]binary_operators: frozenset[BinaryOperator]parameter_form: ScalarExpressionFormunary_operators: frozenset[UnaryOperator]
ScalarExpressionForm [source]¶
class ScalarExpressionForm(enum.Enum)Enumerate permitted runtime-parameter expression shapes.
Attributes¶
ARBITRARYCONCRETE_ONLYLINEAR
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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable diagnosis naming the target and the missing capability. |
target | str | None | Declared target name. Defaults to None. |
operation | str | None | Instruction 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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable diagnosis naming the target and the missing capability. |
target | str | None | Declared target name. Defaults to None. |
operation | str | None | Instruction description that triggered the failure. Defaults to None. |
Attributes¶
target: str | None
UnaryExpr [source]¶
class UnaryExpr(_ScalarOperators)Apply a unary scalar operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operator | UnaryOperator | Operation kind. |
operand | ScalarExpr | Input expression. |
Constructor¶
def __init__(self, operator: UnaryOperator, operand: ScalarExpr) -> NoneAttributes¶
operand: ScalarExproperator: UnaryOperator
UnaryOperator [source]¶
class UnaryOperator(enum.Enum)Enumerate unary scalar operations preserved for materialization.
Attributes¶
NEGNOT
WhileInstruction [source]¶
class WhileInstructionRepeat a structured region while a runtime predicate is true.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime loop predicate. |
inputs | tuple[WireId, ...] | Wires entering the loop. |
body | tuple[CircuitInstruction, ...] | Loop body. |
body_outputs | tuple[WireId, ...] | Wires yielded to the next iteration. |
outputs | tuple[WireId, ...] | Wires available after loop termination. |
body_global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
body: tuple[CircuitInstruction, ...]body_global_phase: ScalarExprbody_outputs: tuple[WireId, ...]condition: ScalarExprinputs: tuple[WireId, ...]outputs: tuple[WireId, ...]
WireId [source]¶
class WireIdIdentify one version of a virtual quantum wire.
Parameters:
| Name | Type | Description |
|---|---|---|
value | int | Non-negative module-local wire number. |
Constructor¶
def __init__(self, value: int) -> NoneAttributes¶
value: int
qamomile.circuit.transpiler.circuit_ir.lowering¶
Lower circuit-family execution plans into engine-neutral circuit IR.
Overview¶
| Function | Description |
|---|---|
bracket_control_value | Bracket zero-valued controls with target-neutral Pauli-X gates. |
build_controlled_block_qubit_map | Build a block-local qubit map backed by physical target indices. |
collect_reachable_values | Collect values reachable from an IR block in canonical walk order. |
content_fingerprint | Compute a deterministic fingerprint for supported lowered IR content. |
is_plain_int | Return True if value is a Python int but not a bool. |
join_runtime_condition_sources | Join mutually exclusive overwrite states after runtime control flow. |
lower_circuit_plan | Lower every quantum segment in a plan to immutable circuit IR. |
reconcile_parameter_metadata | Filter provisional runtime metadata to parameters used by CircuitIR. |
register_classical_merge_aliases | Bind classical merge outputs to a concrete value when resolvable. |
register_merge_outputs | Register merge output UUIDs via the shared map_merge_outputs utility. |
reject_duplicate_physical_indices | Reject a multi-qubit gate whose qubits resolve to the same physical qubit. |
resolve_condition_address | Resolve a runtime control-flow condition to its clbit_map key. |
restore_runtime_condition_sources | Restore one runtime-control-flow path’s overwrite state. |
snapshot_runtime_condition_sources | Snapshot path-local measurement sources overwritten by while loops. |
validate_region_args | Validate the SSA identities owned by a loop’s region arguments. |
verify_circuit | Verify wire linearity, regions, expressions, and slot bounds. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
BinaryExpr | Apply a binary scalar operation. |
BinaryOperator | Enumerate scalar operations preserved until target materialization. |
Block | Unified block representation for all pipeline stages. |
CallInstruction | Invoke a reusable circuit over versioned wires. |
CallableIdentity | Preserve the semantic identity of a reusable circuit body. |
CircuitBuilder | Build immutable circuit IR while assigning fresh wire versions. |
CircuitGateEmitter | Emit primitive operations into engine-neutral circuit IR. |
CircuitLoweringPass | Lower a segmented circuit program into target-neutral builders. |
CircuitProgram | Store one immutable engine-neutral circuit program. |
ClassicalBitExpr | Reference a measured classical bit. |
CompOp | Comparison operation (EQ, NEQ, LT, LE, GT, GE). |
CompOpKind | |
CompiledQuantumSegment | A quantum segment with emitted engine circuit. |
CompositeGateType | Classify standard boxed quantum callables. |
CondOp | Conditional logical operation (AND, OR). |
CondOpKind | |
EmitError | Report an engine failure to emit one semantic operation. |
ExecutableProgram | A fully compiled program ready for execution. |
ForInstruction | Repeat a structured circuit region over a concrete range. |
GateInstruction | Apply one primitive gate to versioned virtual wires. |
IfInstruction | Select between two structured circuit regions. |
IfOperation | Represents an if-else conditional operation. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
LiteralExpr | Represent a concrete scalar literal. |
LoopVariableExpr | Reference the induction value of a structured loop. |
NotOp | |
ParameterExpr | Reference a runtime circuit parameter. |
PauliEvolutionInstruction | Apply an abstract Hamiltonian evolution to selected wires. |
PauliEvolveOp | Pauli evolution operation: exp(-i * gamma * H). |
ProgramPlan | Execution plan for a hybrid quantum/classical program. |
QubitAddress | Typed key for qubit/clbit physical-index maps. |
ReusableCircuit | Describe a reusable circuit body and requested transforms. |
RuntimeClassicalExpr | A classical expression known to require runtime evaluation. |
RuntimeOpKind | Unified kind for RuntimeClassicalExpr covering all classical |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
SemanticArguments | Store immutable named arguments belonging to an operation’s meaning. |
SemanticOpKey | Identify an abstract operation independently of any engine. |
StandardEmitPass | Standard emit pass implementation using GateEmitter protocol. |
UnaryExpr | Apply a unary scalar operation. |
UnaryOperator | Enumerate unary scalar operations preserved for materialization. |
Value | A typed SSA value in the IR. |
WhileInstruction | Repeat a structured region while a runtime predicate is true. |
WhileOperation | Represents a while loop operation. |
Constants¶
CircuitInstruction:TypeAliasSELECT_SEMANTIC_KEY=SemanticOpKey('qamomile.circuit', 'select')Semantic key for a fallback-defined, index-addressed quantum multiplexer.ScalarExpr:TypeAlias
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:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass providing the gate emitter. |
circuit | Any | Circuit receiving the bracket gates. |
control_indices | Sequence[int] | Ordered physical control qubits. |
control_value | int | None | Required basis value, or None for the ordinary all-ones state. |
Yields:
None — Control returns while the zero-valued controls are inverted.
Raises:
TypeError— Ifcontrol_valueis not a PythonintorNone.ValueError— If the activation value does not fit the control width.
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,
) -> QubitMapBuild 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:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Emit pass used to resolve symbolic vector input shapes against bindings. |
block_value | Any | Inner block whose input_values define the quantum formal arguments. Objects without input_values yield an empty map. |
target_indices | list[int] | Physical qubit indices supplied at the controlled call site, one per flattened quantum input qubit. |
bindings | dict[str, Any] | Bindings used while resolving vector input shapes. |
parent_qubit_map | QubitMap | None | Parent-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:
EmitError— If a vector input length cannot be resolved, is negative, or the block’s quantum input footprint exceedslen(target_indices).
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:
| Name | Type | Description |
|---|---|---|
block | Block | Root 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) -> strCompute 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:
| Name | Type | Description |
|---|---|---|
obj | Any | Lowered IR content composed exclusively of supported stable values. |
Returns:
str — SHA-256 hexadecimal digest of the structural content token.
Raises:
TypeError— Ifobjcontains a value without a stable structural encoding.
is_plain_int [source]¶
def is_plain_int(value: object) -> boolReturn 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:
| Name | Type | Description |
|---|---|---|
value | object | The value to test. |
Returns:
bool — True when value is an int and not a bool.
join_runtime_condition_sources [source]¶
def join_runtime_condition_sources(emit_pass: 'StandardEmitPass', *paths: frozenset[tuple[str, int]] = ()) -> NoneJoin mutually exclusive overwrite states after runtime control flow.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Emit pass receiving the joined state. |
*paths | frozenset[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:
| Name | Type | Description |
|---|---|---|
plan | ProgramPlan | Circuit-family C-to-Q-to-C execution plan. |
bindings | dict[str, Any] | None | Compile-time parameter bindings. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
Returns:
ExecutableProgram[CircuitProgram] — ExecutableProgram[CircuitProgram]: Execution structure containing
immutable engine-neutral quantum programs.
Raises:
EmitError— If the semantic operations cannot be lowered to the circuit-family instruction set.ValueError— If structural verification rejects a lowered circuit.
reconcile_parameter_metadata [source]¶
def reconcile_parameter_metadata(program: CircuitProgram, metadata: ParameterMetadata) -> ParameterMetadataFilter 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:
| Name | Type | Description |
|---|---|---|
program | CircuitProgram | Verified immutable circuit program. |
metadata | ParameterMetadata | Provisional segment parameter metadata. |
Returns:
ParameterMetadata — Metadata containing exactly the used parameter
slots, in their original ABI order.
Raises:
EmitError— If CircuitIR references a runtime parameter absent from the provisional metadata, or the CircuitIR graph is malformed.ValueError— If retained array slots have inconsistent ranks.
register_classical_merge_aliases [source]¶
def register_classical_merge_aliases(
emit_pass: 'StandardEmitPass',
op: IfOperation,
bindings: dict[str, Any],
resolved: bool | None,
) -> NoneBind 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:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The active emit pass (for resolver access). |
op | IfOperation | The if-else whose merged classical outputs should be bound; merges are read through iter_merges. |
bindings | dict[str, Any] | Current bindings; mutated in place to bind merge outputs. |
resolved | bool | None | True / 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,
) -> NoneRegister 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:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The active emit pass, providing the ValueResolver used for scalar / array-element resolution. |
op | IfOperation | The runtime if-else whose merged outputs are registered onto their physical clbits / qubits. |
qubit_map | QubitMap | Address-to-physical-qubit map, mutated in place. |
clbit_map | ClbitMap | Address-to-physical-clbit map, mutated in place. |
bindings | dict[str, Any] | None | Active 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:
EmitError— If a quantum merge’s branches resolve to different physical resources, or a runtime scalarBitmerge multiplexes two distinct pre-existing measured clbits (seemap_merge_outputs).
reject_duplicate_physical_indices [source]¶
def reject_duplicate_physical_indices(
gate_label: str,
physical_indices: list[int],
operand_names: list[str] | None = None,
) -> NoneReject 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:
| Name | Type | Description |
|---|---|---|
gate_label | str | Human-readable name of the gate for the message (e.g. "CX" or "controlled gate"). |
physical_indices | list[int] | The resolved physical qubit indices the gate acts on, in operand order. |
operand_names | list[str] | None | Optional 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:
QubitAliasError— If any physical qubit index repeats.
resolve_condition_address [source]¶
def resolve_condition_address(
condition: Value,
bindings: dict[str, Any],
resolver: ValueResolver | None,
) -> QubitAddressResolve 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:
| Name | Type | Description |
|---|---|---|
condition | Value | Condition operand of an IfOperation or WhileOperation, or an operand of a measurement-derived classical predicate (e.g. inside RuntimeClassicalExpr). |
bindings | dict[str, Any] | Active emit-time bindings used to resolve symbolic indices and slice bounds (loop variables, compile-time-bound parameters). |
resolver | ValueResolver | None | The 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]]) -> NoneRestore one runtime-control-flow path’s overwrite state.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Emit pass whose state is restored. |
sources | frozenset[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:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Emit 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:
| Name | Type | Description |
|---|---|---|
op | ForOperation | ForItemsOperation | WhileOperation | Loop operation whose region arguments should be validated. |
Returns:
tuple[RegionArg, ...] — tuple[RegionArg, ...]: The validated op.region_args tuple.
Raises:
ValueError— If result counts or positions disagree, slot types differ, or any loop-owned definition identity collides with another definition or with a region initializer/body yield.
verify_circuit [source]¶
def verify_circuit(program: CircuitProgram) -> NoneVerify wire linearity, regions, expressions, and slot bounds.
Parameters:
| Name | Type | Description |
|---|---|---|
program | CircuitProgram | Immutable circuit program to verify. |
Raises:
ValueError— If the program contains duplicate wire definitions, consumes a non-live wire, has malformed structured-region yields, references an invalid classical bit or loop variable, or reports incorrect outputs.
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,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]BinaryExpr [source]¶
class BinaryExpr(_ScalarOperators)Apply a binary scalar operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operator | BinaryOperator | Operation kind. |
left | ScalarExpr | Left operand. |
right | ScalarExpr | Right operand. |
Constructor¶
def __init__(self, operator: BinaryOperator, left: ScalarExpr, right: ScalarExpr) -> NoneAttributes¶
left: ScalarExproperator: BinaryOperatorright: ScalarExpr
BinaryOperator [source]¶
class BinaryOperator(enum.Enum)Enumerate scalar operations preserved until target materialization.
Attributes¶
ADDANDDIVEQFLOORDIVGEGTLELTMODMULNEQORPOWSUB
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
CallInstruction [source]¶
class CallInstructionInvoke a reusable circuit over versioned wires.
Parameters:
| Name | Type | Description |
|---|---|---|
callee | ReusableCircuit | Reusable circuit and transforms. |
inputs | tuple[WireId, ...] | Consumed wire versions. |
outputs | tuple[WireId, ...] | Produced wire versions. |
Constructor¶
def __init__(
self,
callee: ReusableCircuit,
inputs: tuple[WireId, ...],
outputs: tuple[WireId, ...],
) -> NoneAttributes¶
callee: ReusableCircuitinputs: tuple[WireId, ...]outputs: tuple[WireId, ...]
CallableIdentity [source]¶
class CallableIdentityPreserve the semantic identity of a reusable circuit body.
Parameters:
| Name | Type | Description |
|---|---|---|
key | SemanticOpKey | Open semantic identity used by target-native realization registries. |
symbol | str | Human-readable callable name used for diagnostics. |
arguments | SemanticArguments | Immutable arguments that define this invocation’s meaning. Defaults to no arguments. |
Constructor¶
def __init__(
self,
key: SemanticOpKey,
symbol: str,
arguments: SemanticArguments = SemanticArguments(),
) -> NoneAttributes¶
arguments: SemanticArgumentskey: SemanticOpKeysymbol: str
CircuitBuilder [source]¶
class CircuitBuilderBuild immutable circuit IR while assigning fresh wire versions.
Parameters:
| Name | Type | Description |
|---|---|---|
num_qubits | int | Number of virtual qubit slots. |
num_clbits | int | Number of classical bit slots. |
name | str | Circuit name. Defaults to "main". |
Constructor¶
def __init__(self, num_qubits: int, num_clbits: int, name: str = 'main') -> NoneInitialize a circuit builder.
Parameters:
| Name | Type | Description |
|---|---|---|
num_qubits | int | Number of virtual qubit slots. |
num_clbits | int | Number of classical bit slots. |
name | str | Circuit name. Defaults to "main". |
Raises:
ValueError— If either slot count is negative.
Attributes¶
namenum_clbitsnum_qubitsoperations: list[CircuitInstruction] Return the current region instruction list.
Methods¶
add_global_phase¶
def add_global_phase(self, phase: ScalarExpr | bool | int | float) -> NoneAccumulate a global phase in the current lexical region.
Parameters:
| Name | Type | Description |
|---|---|---|
phase | ScalarExpr | bool | int | float | Phase contribution. |
append_barrier¶
def append_barrier(self, qubits: tuple[int, ...]) -> NoneAppend a scheduling barrier without changing wire versions.
Parameters:
| Name | Type | Description |
|---|---|---|
qubits | tuple[int, ...] | Participating qubit slots. |
append_call¶
def append_call(self, callee: ReusableCircuit, qubits: tuple[int, ...]) -> NoneAppend a reusable-circuit call and advance its wires.
Parameters:
| Name | Type | Description |
|---|---|---|
callee | ReusableCircuit | Reusable circuit and transforms. |
qubits | tuple[int, ...] | Participating qubit slots. |
append_gate¶
def append_gate(
self,
kind: GateKind,
qubits: tuple[int, ...],
parameters: tuple[ScalarExpr, ...] = (),
) -> NoneAppend a primitive gate and advance all participating wires.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | GateKind | Primitive gate kind. |
qubits | tuple[int, ...] | Participating qubit slots. |
parameters | tuple[ScalarExpr, ...] | Gate parameters. Defaults to an empty tuple. |
append_measure¶
def append_measure(self, qubit: int, clbit: int) -> NoneAppend a measurement.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | int | Measured qubit slot. |
clbit | int | Destination classical bit slot. |
Raises:
IndexError— Ifclbitis outside the allocated classical slots.
append_measure_vector¶
def append_measure_vector(self, qubits: tuple[int, ...], clbits: tuple[int, ...]) -> NoneAppend one ordered vector measurement.
Parameters:
| Name | Type | Description |
|---|---|---|
qubits | tuple[int, ...] | Measured qubit slots in result order. |
clbits | tuple[int, ...] | Destination classical slots. |
Raises:
ValueError— If qubit and classical-bit arities differ or either sequence contains duplicate slots.IndexError— If a classical-bit slot is outside the circuit.
append_pauli_evolution¶
def append_pauli_evolution(
self,
qubits: tuple[int, ...],
hamiltonian: Any,
time: ScalarExpr | bool | int | float,
) -> NoneAppend an abstract Pauli evolution and advance its wires.
Parameters:
| Name | Type | Description |
|---|---|---|
qubits | tuple[int, ...] | Participating qubit slots. |
hamiltonian | Any | Qamomile Hamiltonian value. |
time | ScalarExpr | bool | int | float | Evolution time. |
Raises:
ValueError— If a Qamomile Hamiltonian has a non-Hermitian identity coefficient.
append_reset¶
def append_reset(self, qubit: int) -> NoneAppend reset and advance the affected wire.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | int | Qubit slot to reset. |
begin_else¶
def begin_else(self, context: _IfContext) -> NoneClose a true region and open its false region.
Parameters:
| Name | Type | Description |
|---|---|---|
context | _IfContext | Token returned by :meth:begin_if. |
Raises:
RuntimeError— Ifcontextis not the innermost open conditional or an else branch has already started.
begin_for¶
def begin_for(self, indexset: range) -> LoopVariableExprOpen a structured for-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
indexset | range | Concrete iteration range. |
Returns:
LoopVariableExpr — Induction expression available inside the body.
begin_if¶
def begin_if(self, condition: ScalarExpr) -> _IfContextOpen the true region of a structured conditional.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime branch predicate. |
Returns:
_IfContext — Opaque builder token used to select the else branch.
begin_while¶
def begin_while(self, condition: ScalarExpr) -> _WhileContextOpen a structured while-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime loop predicate. |
Returns:
_WhileContext — Opaque builder token used to close the loop.
current_wire¶
def current_wire(self, qubit: int) -> WireIdReturn the current wire version for a qubit slot.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | int | Physical slot index assigned by circuit lowering. |
Returns:
WireId — Current version of the slot.
Raises:
KeyError— Ifqubitis outside the allocated slot range.
end_for¶
def end_for(self) -> NoneClose the innermost structured for-loop body.
Raises:
RuntimeError— If the innermost open region is not a for loop.
end_if¶
def end_if(self, context: _IfContext) -> NoneClose a structured conditional and merge its wire states.
Parameters:
| Name | Type | Description |
|---|---|---|
context | _IfContext | Token returned by :meth:begin_if. |
Raises:
RuntimeError— Ifcontextis not the innermost open conditional.
end_while¶
def end_while(self, context: _WhileContext) -> NoneClose a structured while-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
context | _WhileContext | Token returned by :meth:begin_while. |
Raises:
RuntimeError— Ifcontextis not the innermost open while loop.
freeze¶
def freeze(self) -> CircuitProgramFinalize the root region into immutable circuit IR.
Returns:
CircuitProgram — Immutable circuit program.
Raises:
RuntimeError— If a structured region is still open.
fresh_wire¶
def fresh_wire(self) -> WireIdAllocate a fresh module-local virtual wire version.
Returns:
WireId — Newly allocated wire identifier.
restore_state¶
def restore_state(self, snapshot: _CircuitBuilderSnapshot) -> NoneRestore a checkpoint after an append-only emission attempt.
Parameters:
| Name | Type | Description |
|---|---|---|
snapshot | _CircuitBuilderSnapshot | Checkpoint returned by :meth:snapshot_state for this builder. |
Raises:
RuntimeError— If emission removed or replaced state that existed before the checkpoint instead of only appending new state.
snapshot_state¶
def snapshot_state(self) -> _CircuitBuilderSnapshotCapture state that can be restored after declined emission.
Returns:
_CircuitBuilderSnapshot — Append-only builder checkpoint for the
current structured region.
CircuitGateEmitter [source]¶
class CircuitGateEmitterEmit primitive operations into engine-neutral circuit IR.
Attributes¶
measurement_mode: MeasurementMode Return native measurement mode for explicit circuit IR.
Methods¶
append_gate¶
def append_gate(
self,
circuit: CircuitBuilder,
gate: ReusableCircuit,
qubits: list[int],
) -> NoneAppend a reusable circuit call.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
gate | ReusableCircuit | Reusable circuit value. |
qubits | list[int] | Participating slots. |
circuit_to_gate¶
def circuit_to_gate(
self,
circuit: CircuitBuilder | CircuitProgram,
name: str = 'U',
) -> ReusableCircuitFreeze a circuit as a reusable circuit value.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | CircuitProgram | Circuit body. |
name | str | Reusable 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 | NoneCombine symbolic operands without creating engine expressions.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | BinOpKind | Qamomile arithmetic operation. |
lhs | ScalarExpr | bool | int | float | Left operand. |
rhs | ScalarExpr | bool | int | float | Right 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) -> CircuitBuilderCreate an empty circuit IR builder.
Parameters:
| Name | Type | Description |
|---|---|---|
num_qubits | int | Number of virtual qubit slots. |
num_clbits | int | Number of classical bit slots. |
Returns:
CircuitBuilder — Empty engine-neutral builder.
create_parameter¶
def create_parameter(self, name: str) -> ParameterExprCreate a target-neutral runtime parameter expression.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | External parameter name. |
Returns:
ParameterExpr — Parameter reference preserved until materialization.
emit_barrier¶
def emit_barrier(self, circuit: CircuitBuilder, qubits: list[int]) -> NoneEmit a scheduling barrier.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubits | list[int] | Participating slots. |
emit_ch¶
def emit_ch(self, circuit: CircuitBuilder, control: int, target: int) -> NoneEmit a controlled-H gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
emit_cp¶
def emit_cp(
self,
circuit: CircuitBuilder,
control: int,
target: int,
angle: ScalarExpr | float,
) -> NoneEmit a controlled-phase rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
angle | ScalarExpr | float | Phase angle in radians. |
emit_crx¶
def emit_crx(
self,
circuit: CircuitBuilder,
control: int,
target: int,
angle: ScalarExpr | float,
) -> NoneEmit a controlled-RX rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_cry¶
def emit_cry(
self,
circuit: CircuitBuilder,
control: int,
target: int,
angle: ScalarExpr | float,
) -> NoneEmit a controlled-RY rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_crz¶
def emit_crz(
self,
circuit: CircuitBuilder,
control: int,
target: int,
angle: ScalarExpr | float,
) -> NoneEmit a controlled-RZ rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_cx¶
def emit_cx(self, circuit: CircuitBuilder, control: int, target: int) -> NoneEmit a controlled-X gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
emit_cy¶
def emit_cy(self, circuit: CircuitBuilder, control: int, target: int) -> NoneEmit a controlled-Y gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
emit_cz¶
def emit_cz(self, circuit: CircuitBuilder, control: int, target: int) -> NoneEmit a controlled-Z gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control | int | Control slot. |
target | int | Target slot. |
emit_else_start¶
def emit_else_start(self, circuit: CircuitBuilder, context: Any) -> NoneSwitch an open conditional to its false branch.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
context | Any | Opaque conditional context. |
emit_for_loop_end¶
def emit_for_loop_end(self, circuit: CircuitBuilder, context: Any) -> NoneClose a structured for-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
context | Any | Induction expression returned at loop start. |
emit_for_loop_start¶
def emit_for_loop_start(self, circuit: CircuitBuilder, indexset: range) -> ScalarExprOpen a structured for-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
indexset | range | Concrete iteration range. |
Returns:
ScalarExpr — Target-neutral induction expression.
emit_global_phase¶
def emit_global_phase(self, circuit: CircuitBuilder, angle: ScalarExpr | float) -> NoneAccumulate a phase in the builder’s current lexical region.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
angle | ScalarExpr | float | Phase angle in radians. |
emit_h¶
def emit_h(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit a Hadamard gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_if_end¶
def emit_if_end(self, circuit: CircuitBuilder, context: Any) -> NoneClose a structured conditional.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
context | Any | Opaque conditional context. |
emit_if_start¶
def emit_if_start(self, circuit: CircuitBuilder, clbit: int, value: int = 1) -> AnyOpen a structured conditional true branch.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
clbit | int | Predicate classical bit slot. |
value | int | Required bit value. Defaults to one. |
Returns:
Any — Opaque conditional builder context.
emit_measure¶
def emit_measure(self, circuit: CircuitBuilder, qubit: int, clbit: int) -> NoneEmit a measurement into a classical slot.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Measured qubit slot. |
clbit | int | Destination classical slot. |
emit_measure_vector¶
def emit_measure_vector(
self,
circuit: CircuitBuilder,
qubits: tuple[int, ...],
clbits: tuple[int, ...],
) -> NonePreserve an ordered vector measurement as one instruction.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubits | tuple[int, ...] | Measured qubit slots in result order. |
clbits | tuple[int, ...] | Destination classical slots. |
emit_p¶
def emit_p(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> NoneEmit a phase rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
angle | ScalarExpr | float | Phase angle in radians. |
emit_reset¶
def emit_reset(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit a reset-to-zero operation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Reset qubit slot. |
emit_rx¶
def emit_rx(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> NoneEmit an RX rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_ry¶
def emit_ry(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> NoneEmit an RY rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_rz¶
def emit_rz(self, circuit: CircuitBuilder, qubit: int, angle: ScalarExpr | float) -> NoneEmit an RZ rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_rzz¶
def emit_rzz(
self,
circuit: CircuitBuilder,
qubit1: int,
qubit2: int,
angle: ScalarExpr | float,
) -> NoneEmit an RZZ rotation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit1 | int | First slot. |
qubit2 | int | Second slot. |
angle | ScalarExpr | float | Rotation angle in radians. |
emit_s¶
def emit_s(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit an S gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_sdg¶
def emit_sdg(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit an inverse-S gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_swap¶
def emit_swap(self, circuit: CircuitBuilder, qubit1: int, qubit2: int) -> NoneEmit a SWAP gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit1 | int | First slot. |
qubit2 | int | Second slot. |
emit_t¶
def emit_t(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit a T gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_tdg¶
def emit_tdg(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit an inverse-T gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_toffoli¶
def emit_toffoli(
self,
circuit: CircuitBuilder,
control1: int,
control2: int,
target: int,
) -> NoneEmit a Toffoli gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
control1 | int | First control slot. |
control2 | int | Second control slot. |
target | int | Target slot. |
emit_while_end¶
def emit_while_end(self, circuit: CircuitBuilder, context: Any) -> NoneClose a structured while-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
context | Any | Opaque while-loop context. |
emit_while_start¶
def emit_while_start(self, circuit: CircuitBuilder, clbit: int, value: int = 1) -> AnyOpen a structured while-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
clbit | int | Predicate classical bit slot. |
value | int | Required bit value. Defaults to one. |
Returns:
Any — Opaque while-loop builder context.
emit_x¶
def emit_x(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit a Pauli-X gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_y¶
def emit_y(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit a Pauli-Y gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
emit_z¶
def emit_z(self, circuit: CircuitBuilder, qubit: int) -> NoneEmit a Pauli-Z gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitBuilder | Destination builder. |
qubit | int | Target slot. |
gate_controlled¶
def gate_controlled(self, gate: ReusableCircuit, num_controls: int) -> ReusableCircuitAdd control wires to a reusable circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | ReusableCircuit | Reusable circuit value. |
num_controls | int | Number of controls to add. |
Returns:
ReusableCircuit — Controlled reusable circuit.
gate_inverse¶
def gate_inverse(self, gate: ReusableCircuit) -> ReusableCircuitToggle the inverse transform on a reusable circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | ReusableCircuit | Reusable circuit value. |
Returns:
ReusableCircuit — Inverse reusable circuit.
gate_power¶
def gate_power(self, gate: ReusableCircuit, power: int) -> ReusableCircuitApply an integral power transform to a reusable circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | ReusableCircuit | Reusable circuit value. |
power | int | Integral repetition count. |
Returns:
ReusableCircuit — Transformed reusable circuit.
supports_for_loop¶
def supports_for_loop(self) -> boolReport support for structured for loops.
Returns:
bool — Always True for circuit IR.
supports_gate_inverse¶
def supports_gate_inverse(self) -> boolReport support for deferred inverse transforms.
Returns:
bool — Always True for circuit IR.
supports_if_else¶
def supports_if_else(self) -> boolReport support for structured conditionals.
Returns:
bool — Always True for circuit IR.
supports_reusable_gates¶
def supports_reusable_gates(self) -> boolReport 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) -> boolReport 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:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Compile-time parameter bindings. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
Constructor¶
def __init__(
self,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> NoneInitialize circuit-IR lowering.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Compile-time parameter bindings. Defaults to None. |
parameters | list[str] | None | Runtime 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:
| Name | Type | Description |
|---|---|---|
input | ProgramPlan | Segmented program plan to lower. |
Returns:
ExecutableProgram[CircuitBuilder] — ExecutableProgram[CircuitBuilder]: Lowered executable builders.
CircuitProgram [source]¶
class CircuitProgramStore one immutable engine-neutral circuit program.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Circuit entrypoint name. |
num_qubits | int | Number of virtual input qubit slots. |
num_clbits | int | Number of classical bit slots. |
input_wires | tuple[WireId, ...] | Initial wire version per qubit slot. |
output_wires | tuple[WireId, ...] | Final wire version per qubit slot. |
operations | tuple[CircuitInstruction, ...] | Structured instruction sequence. |
global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
global_phase: ScalarExprinput_wires: tuple[WireId, ...]name: strnum_clbits: intnum_qubits: intoperations: tuple[CircuitInstruction, ...]output_wires: tuple[WireId, ...]
ClassicalBitExpr [source]¶
class ClassicalBitExpr(_ScalarOperators)Reference a measured classical bit.
Parameters:
| Name | Type | Description |
|---|---|---|
index | int | Circuit-local classical bit index. |
Constructor¶
def __init__(self, index: int) -> NoneAttributes¶
index: int
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,
) -> NoneAttributes¶
kind: CompOpKind | Noneoperation_kind: OperationKindsignature: Signature
CompOpKind [source]¶
class CompOpKind(enum.Enum)Attributes¶
EQGEGTLELTNEQ
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,
) -> NoneAttributes¶
circuit: Tclbit_map: ClbitMapimplicit_output_qubit_indices: tuple[int, ...] | Nonemeasurement_qubit_map: dict[int, int]parameter_metadata: ParameterMetadataqubit_map: QubitMapsegment: QuantumSegment
CompositeGateType [source]¶
class CompositeGateType(enum.Enum)Classify standard boxed quantum callables.
Attributes¶
CUSTOMIQFTQFTQPE
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,
) -> NoneAttributes¶
kind: CondOpKind | Noneoperation_kind: OperationKindsignature: Signature
CondOpKind [source]¶
class CondOpKind(enum.Enum)Attributes¶
ANDOR
EmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
operation
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 typeConstructor¶
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(),
) -> NoneAttributes¶
compiled_classical: list[CompiledClassicalSegment]compiled_expval: list[CompiledExpvalSegment]compiled_quantum: list[CompiledQuantumSegment[T]]has_parameters: bool Check if this program has unbound parameters.output_values: list[ValueLike]parameter_names: list[str] Get list of parameter names that need binding.plan: ProgramPlan | Nonequantum_circuit: T Get the single quantum circuit.
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 | NoneGet 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] | ExpvalJobRestore 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:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine adapter configured with the provider credentials and target used by the original job. |
snapshot | JobSnapshot | Snapshot returned by the original public job’s snapshot() method. |
bindings | dict[str, Any] | None | Original 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:
ExecutionError— If the snapshot operation or execution shape does not match this executable program.NotImplementedError— If the executor cannot restore the referenced provider execution.ValueError— If required bindings are missing or invalid.
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] | ExpvalJobSubmit one execution and return its lazy result job.
Parameters:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine-specific quantum executor. |
bindings | dict[str, Any] | None | Parameter 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} |
estimation | EstimationAccuracy | None | Optional 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:
ExecutionError— If no quantum circuit to executeValueError— If required parameters are missing
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:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine-specific quantum executor. |
shots | int | Number of shots to run. |
bindings | dict[str, Any] | None | Parameter 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:
ExecutionError— If no quantum circuit to executeValueError— If required parameters are missing
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 ForInstructionRepeat a structured circuit region over a concrete range.
Parameters:
| Name | Type | Description |
|---|---|---|
indexset | range | Concrete iteration range. |
loop_variable | LoopVariableExpr | Induction expression used by the body. |
inputs | tuple[WireId, ...] | Wire versions entering the loop. |
body | tuple[CircuitInstruction, ...] | Single-iteration body. |
body_outputs | tuple[WireId, ...] | Body wire versions yielded to the next iteration. |
outputs | tuple[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, ...],
) -> NoneAttributes¶
body: tuple[CircuitInstruction, ...]body_outputs: tuple[WireId, ...]indexset: rangeinputs: tuple[WireId, ...]loop_variable: LoopVariableExproutputs: tuple[WireId, ...]
GateInstruction [source]¶
class GateInstructionApply one primitive gate to versioned virtual wires.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | GateKind | Primitive gate kind. |
inputs | tuple[WireId, ...] | Consumed wire versions. |
outputs | tuple[WireId, ...] | Produced wire versions. |
parameters | tuple[ScalarExpr, ...] | Gate parameters. |
Constructor¶
def __init__(
self,
kind: GateKind,
inputs: tuple[WireId, ...],
outputs: tuple[WireId, ...],
parameters: tuple[ScalarExpr, ...] = (),
) -> NoneAttributes¶
inputs: tuple[WireId, ...]kind: GateKindoutputs: tuple[WireId, ...]parameters: tuple[ScalarExpr, ...]
IfInstruction [source]¶
class IfInstructionSelect between two structured circuit regions.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime branch predicate. |
inputs | tuple[WireId, ...] | Wires entering both branches. |
true_body | tuple[CircuitInstruction, ...] | True branch body. |
false_body | tuple[CircuitInstruction, ...] | False branch body. |
true_outputs | tuple[WireId, ...] | Wires yielded by the true branch. |
false_outputs | tuple[WireId, ...] | Wires yielded by the false branch. |
outputs | tuple[WireId, ...] | Merged post-branch wires. |
true_global_phase | ScalarExpr | Phase applied only in the true branch. |
false_global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
condition: ScalarExprfalse_body: tuple[CircuitInstruction, ...]false_global_phase: ScalarExprfalse_outputs: tuple[WireId, ...]inputs: tuple[WireId, ...]outputs: tuple[WireId, ...]true_body: tuple[CircuitInstruction, ...]true_global_phase: ScalarExprtrue_outputs: tuple[WireId, ...]
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[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. |
definition | CallableDef | None | Optional 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,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueor an Oracle control-partition field has an invalid Python type.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width, or if Oracle invocation and definition control metadata disagree.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of relevant callable implementations.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return a conservative union of measurement-derived results.name: str Return the display name for this invocation.num_added_control_qubits: int Return controls introduced by a frontend control transform.num_body_external_control_qubits: int Return control operands generic lowering adds outside a base body.num_control_qubits: int Return the number of leading control-qubit operands.num_declared_control_qubits: int Return controls included in an opaque Oracle’s base definition.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
effective_body¶
def effective_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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 | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None, which only selects engine-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
require_body | bool | Whether 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name used for implementation selection. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
select_body¶
def select_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> CallableBodySelectionSelect 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
LiteralExpr [source]¶
class LiteralExpr(_ScalarOperators)Represent a concrete scalar literal.
Parameters:
| Name | Type | Description |
|---|---|---|
value | bool | int | float | Concrete scalar value. |
Constructor¶
def __init__(self, value: bool | int | float) -> NoneAttributes¶
value: bool | int | float
LoopVariableExpr [source]¶
class LoopVariableExpr(_ScalarOperators)Reference the induction value of a structured loop.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Circuit-local loop variable name. |
Constructor¶
def __init__(self, name: str) -> NoneAttributes¶
name: str
NotOp [source]¶
class NotOp(Operation)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
input: Valueoperation_kind: OperationKindoutput: Valuesignature: Signature
ParameterExpr [source]¶
class ParameterExpr(_ScalarOperators)Reference a runtime circuit parameter.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Stable external parameter name. |
Constructor¶
def __init__(self, name: str) -> NoneAttributes¶
name: str
PauliEvolutionInstruction [source]¶
class PauliEvolutionInstructionApply an abstract Hamiltonian evolution to selected wires.
Parameters:
| Name | Type | Description |
|---|---|---|
hamiltonian | Any | Immutable Qamomile Hamiltonian value. |
time | ScalarExpr | Evolution time in radians. |
inputs | tuple[WireId, ...] | Consumed wire versions. |
outputs | tuple[WireId, ...] | Produced wire versions. |
realization | PauliEvolutionRealization | Target 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,
) -> NoneAttributes¶
hamiltonian: Anyinputs: tuple[WireId, ...]outputs: tuple[WireId, ...]realization: PauliEvolutionRealizationtime: ScalarExpr
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()) -> NoneAttributes¶
evolved_qubits: Value The evolved quantum register result.gamma: Value The evolution time parameter.observable: Value The Observable parameter operand.operation_kind: OperationKind PauliEvolveOp is QUANTUM - transforms quantum state.qubits: Value The quantum register operand.signature: Signature
ProgramPlan [source]¶
class ProgramPlanExecution plan for a hybrid quantum/classical program.
Structure:
[Optional] Classical preprocessing (parameter computation, etc.)
Single quantum segment (REQUIRED)
[Optional] Expval segment OR classical postprocessing
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(),
) -> NoneAttributes¶
abi: ProgramABIboundaries: list[HybridBoundary]parameters: dict[str, Value]steps: list[ProgramStep]
QubitAddress [source]¶
class QubitAddressTyped 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) -> NoneAttributes¶
element_index: int | Noneis_array_element: bool True if this address refers to an array element.uuid: str
Methods¶
from_composite_key¶
@classmethod
def from_composite_key(cls, key: str) -> QubitAddressParse 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) -> boolTrue if this address belongs to the given array.
with_element¶
def with_element(self, index: int) -> QubitAddressCreate an array-element address from this array’s base UUID.
ReusableCircuit [source]¶
class ReusableCircuitDescribe a reusable circuit body and requested transforms.
Parameters:
| Name | Type | Description |
|---|---|---|
body | CircuitProgram | Reusable circuit body. |
name | str | Display and linkage name. |
power | int | Integral repetition count. Defaults to one. |
controls | int | Added control-wire count. Defaults to zero. |
inverse | bool | Whether to apply the inverse body. Defaults to false. |
identity | CallableIdentity | None | Semantic identity preserved for target legalization. None marks an anonymous body. Defaults to None. |
native_realization | str | None | Target-owned realization identifier selected during legalization. None keeps the reusable body as the fallback implementation. Defaults to None. |
operand_widths | tuple[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, ...] = (),
) -> NoneAttributes¶
body: CircuitProgramcontrols: intidentity: CallableIdentity | Noneinverse: boolname: strnative_realization: str | Nonenum_qubits: int Return the transformed call arity.operand_widths: tuple[int, ...]power: int
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:
Binary kinds (EQ/NEQ/LT/LE/GT/GE/AND/OR/ADD/SUB/MUL/DIV/FLOORDIV/MOD/POW):
operands = [lhs, rhs].Unary kind (NOT):
operands = [val].Ternary kind (SELECT):
operands = [condition, true_value, false_value]— the runtime form of a branch merge (result = true_value if condition else false_value).Result:
results = [output_value].
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,
) -> NoneAttributes¶
kind: RuntimeOpKind | Noneoperation_kind: OperationKindsignature: Signature
RuntimeOpKind [source]¶
class RuntimeOpKind(enum.Enum)Unified kind for RuntimeClassicalExpr covering all classical
op families that can appear at runtime.
The split between this enum and the per-family BinOpKind /
CompOpKind / CondOpKind is intentional: compile-time-foldable
classical ops keep their original IR types so the existing fold
pipeline (constant_fold → compile_time_if_lowering → emit-time
evaluate_classical_predicate) is undisturbed. Only ops identified
as runtime-evaluation-only by ClassicalLoweringPass get rewritten
to RuntimeClassicalExpr with a member of this enum.
Attributes¶
ADDANDDIVEQFLOORDIVGEGTLELTMODMULNEQNOTORPOWSELECTSUB
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(),
) -> NoneAttributes¶
case_blocks: list[Block]case_callable_attrs: list[dict[str, Any]]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
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]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed replacement values. |
Returns:
Operation — Rebuilt SELECT operation with matching values replaced.
SemanticArguments [source]¶
class SemanticArgumentsStore immutable named arguments belonging to an operation’s meaning.
Parameters:
| Name | Type | Description |
|---|---|---|
entries | tuple[tuple[str, SemanticValue], ...] | Sorted name-value entries. Defaults to an empty tuple. |
Constructor¶
def __init__(self, entries: tuple[tuple[str, SemanticValue], ...] = ()) -> NoneAttributes¶
entries: tuple[tuple[str, SemanticValue], ...]
Methods¶
from_mapping¶
@classmethod
def from_mapping(cls, values: Mapping[str, Any] | None) -> 'SemanticArguments'Freeze one mapping of semantic operation arguments.
Parameters:
| Name | Type | Description |
|---|---|---|
values | Mapping[str, Any] | None | Serializer-friendly arguments, or None for no arguments. |
Returns:
'SemanticArguments' — Immutable, deterministically ordered arguments.
Raises:
TypeError— If a nested value is not serializer-friendly.
get¶
def get(self, name: str, default: SemanticValue = None) -> SemanticValueReturn one semantic argument by name.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Argument name. |
default | SemanticValue | Value 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 SemanticOpKeyIdentify 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:
| Name | Type | Description |
|---|---|---|
namespace | str | Stable owner namespace such as qamomile.stdlib. |
name | str | Stable operation name within the namespace. |
version | str | Semantic contract version. Defaults to "1". |
variant | str | None | Optional 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,
) -> NoneAttributes¶
name: strnamespace: strvariant: str | Noneversion: str
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:
| Name | Type | Description |
|---|---|---|
gate_emitter | GateEmitter[T] | Instruction builder used during the semantic traversal. |
bindings | dict[str, Any] | None | Compile-time parameter bindings. |
parameters | list[str] | None | Parameter names preserved at runtime. |
composite_emitters | list[CompositeGateEmitter[T]] | None | Optional callable-preservation or lowering hooks. |
engine_name | str | None | Diagnostic 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¶
engine_name
UnaryExpr [source]¶
class UnaryExpr(_ScalarOperators)Apply a unary scalar operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operator | UnaryOperator | Operation kind. |
operand | ScalarExpr | Input expression. |
Constructor¶
def __init__(self, operator: UnaryOperator, operand: ScalarExpr) -> NoneAttributes¶
operand: ScalarExproperator: UnaryOperator
UnaryOperator [source]¶
class UnaryOperator(enum.Enum)Enumerate unary scalar operations preserved for materialization.
Attributes¶
NEGNOT
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
WhileInstruction [source]¶
class WhileInstructionRepeat a structured region while a runtime predicate is true.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime loop predicate. |
inputs | tuple[WireId, ...] | Wires entering the loop. |
body | tuple[CircuitInstruction, ...] | Loop body. |
body_outputs | tuple[WireId, ...] | Wires yielded to the next iteration. |
outputs | tuple[WireId, ...] | Wires available after loop termination. |
body_global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
body: tuple[CircuitInstruction, ...]body_global_phase: ScalarExprbody_outputs: tuple[WireId, ...]condition: ScalarExprinputs: tuple[WireId, ...]outputs: tuple[WireId, ...]
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]max_iterations: int | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the while body and its complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt while operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, rebind-record, and region-arg values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[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¶
| Function | Description |
|---|---|
legalize_program | Rewrite one circuit program until it is legal for a target. |
lower_circuit_plan | Lower every quantum segment in a plan to immutable circuit IR. |
materialize_executable | Materialize every quantum segment while preserving orchestration. |
verify_circuit | Verify wire linearity, regions, expressions, and slot bounds. |
verify_target_legal | Prove a legalized program against declared target capabilities. |
| Class | Description |
|---|---|
CircuitCapabilities | Declare the complete circuit-IR language accepted by one target. |
CircuitEngineEmitPass | Lower, legalize, verify, and materialize a circuit-family plan. |
CircuitMaterializer | Convert one target-legal circuit program to an engine artifact. |
CircuitProgram | Store one immutable engine-neutral circuit program. |
CompilationPolicy | Select preferred realizations among target-supported alternatives. |
CompiledQuantumSegment | A quantum segment with emitted engine circuit. |
EmitPass | Base class for engine-specific emission passes. |
ExecutableProgram | A fully compiled program ready for execution. |
MaterializedCircuit | Package a circuit artifact and engine-specific binding metadata. |
ProgramPlan | Execution plan for a hybrid quantum/classical program. |
Constants¶
DEFAULT_POLICY=CompilationPolicy()Policy used when an engine transpiler does not supply one.
Functions¶
legalize_program [source]¶
def legalize_program(
program: CircuitProgram,
capabilities: CircuitCapabilities,
policy: CompilationPolicy,
) -> CircuitProgramRewrite 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:
| Name | Type | Description |
|---|---|---|
program | CircuitProgram | Verified engine-neutral circuit program. |
capabilities | CircuitCapabilities | Declared target capabilities. |
policy | CompilationPolicy | User 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:
| Name | Type | Description |
|---|---|---|
plan | ProgramPlan | Circuit-family C-to-Q-to-C execution plan. |
bindings | dict[str, Any] | None | Compile-time parameter bindings. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
Returns:
ExecutableProgram[CircuitProgram] — ExecutableProgram[CircuitProgram]: Execution structure containing
immutable engine-neutral quantum programs.
Raises:
EmitError— If the semantic operations cannot be lowered to the circuit-family instruction set.ValueError— If structural verification rejects a lowered circuit.
materialize_executable [source]¶
def materialize_executable(
executable: ExecutableProgram[CircuitProgram],
materializer: CircuitMaterializer[ArtifactT],
) -> ExecutableProgram[ArtifactT]Materialize every quantum segment while preserving orchestration.
Parameters:
| Name | Type | Description |
|---|---|---|
executable | ExecutableProgram[CircuitProgram] | Lowered circuit-family execution structure. |
materializer | CircuitMaterializer[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) -> NoneVerify wire linearity, regions, expressions, and slot bounds.
Parameters:
| Name | Type | Description |
|---|---|---|
program | CircuitProgram | Immutable circuit program to verify. |
Raises:
ValueError— If the program contains duplicate wire definitions, consumes a non-live wire, has malformed structured-region yields, references an invalid classical bit or loop variable, or reports incorrect outputs.
verify_target_legal [source]¶
def verify_target_legal(program: CircuitProgram, capabilities: CircuitCapabilities) -> NoneProve a legalized program against declared target capabilities.
Parameters:
| Name | Type | Description |
|---|---|---|
program | CircuitProgram | Legalized circuit program, including every nested reusable-call body. |
capabilities | CircuitCapabilities | Declared target capabilities. |
Raises:
TargetCapabilityError— If any instruction requires a gate kind, semantic realization, control-flow construct, reset, Pauli evolution, or scalar-expression shape the target does not declare.
Classes¶
CircuitCapabilities [source]¶
class CircuitCapabilitiesDeclare the complete circuit-IR language accepted by one target.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Stable target name used in diagnostics. |
primitive_gates | frozenset[GateKind] | Primitive gate kinds accepted by the target materializer. |
native_semantic_ops | tuple[NativeSemanticOpCapabilities, ...] | Native realizations keyed by open semantic operation identity. |
gate_parameters | ScalarCapabilities | Scalar language accepted by gate parameters. |
predicates | ScalarCapabilities | Scalar language accepted by dynamic if and while predicates. |
pauli_time | ScalarCapabilities | Scalar language accepted by Pauli evolution time values. |
global_phase | GlobalPhaseCapabilities | ScalarCapabilities | None | Exact standalone phase realization requirements, or None when unsupported. The former ScalarCapabilities value remains accepted and readable for source compatibility. |
generic_calls | CallTransformCapabilities | Reusable-call forms accepted after semantic-call legalization. |
supports_dynamic_if | bool | Whether runtime if regions are accepted. |
supports_dynamic_while | bool | Whether runtime while regions are accepted. |
supports_reset | bool | Whether reset instructions are accepted. |
pauli_realizations | frozenset[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],
) -> NoneAttributes¶
gate_parameters: ScalarCapabilitiesgeneric_calls: CallTransformCapabilitiesglobal_phase: GlobalPhaseCapabilities | ScalarCapabilities | Nonename: strnative_semantic_ops: tuple[NativeSemanticOpCapabilities, ...]normalized_global_phase: GlobalPhaseCapabilities | None Return standalone phase requirements in the extended form.pauli_realizations: frozenset[PauliEvolutionRealization]pauli_time: ScalarCapabilitiespredicates: ScalarCapabilitiesprimitive_gates: frozenset[GateKind]supports_dynamic_if: boolsupports_dynamic_while: boolsupports_reset: bool
Methods¶
native_semantic_op¶
def native_semantic_op(self, key: SemanticOpKey) -> NativeSemanticOpCapabilities | NoneReturn the native declaration for one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
key | SemanticOpKey | Semantic operation key to look up. |
Returns:
NativeSemanticOpCapabilities | None — NativeSemanticOpCapabilities | None: Matching declaration, or
NativeSemanticOpCapabilities | None — None when the target has no native realization.
CircuitEngineEmitPass [source]¶
class CircuitEngineEmitPass(EmitPass[ArtifactT])Lower, legalize, verify, and materialize a circuit-family plan.
The pass runs the three phases in order and never interleaves them: shared lowering produces engine-neutral circuit IR, target legalization rewrites it under the materializer’s declared capabilities and the compilation policy, target verification proves the result, and only then does the materializer convert it mechanically.
Parameters:
| Name | Type | Description |
|---|---|---|
materializer | CircuitMaterializer[ArtifactT] | Engine artifact materializer owning the target capability declaration. |
bindings | dict[str, Any] | None | Compile-time bindings. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
policy | CompilationPolicy | None | Realization 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,
) -> NoneInitialize a circuit-family lowering and materialization pass.
Parameters:
| Name | Type | Description |
|---|---|---|
materializer | CircuitMaterializer[ArtifactT] | Engine artifact materializer owning the target capability declaration. |
bindings | dict[str, Any] | None | Compile-time bindings. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
policy | CompilationPolicy | None | Realization preferences. Defaults to None, meaning :data:DEFAULT_POLICY. |
Attributes¶
materializerparameter_namespolicy
Methods¶
run¶
def run(self, input: ProgramPlan) -> ExecutableProgram[ArtifactT]Lower, legalize, verify, and materialize every quantum segment.
Parameters:
| Name | Type | Description |
|---|---|---|
input | ProgramPlan | Circuit-family execution plan. |
Returns:
ExecutableProgram[ArtifactT] — ExecutableProgram[ArtifactT]: Engine-native executable structure.
Raises:
TargetCapabilityError— If a legalized segment still requires a capability the target does not declare.ValueError— If a legalized segment fails structural verification.
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¶
capabilities: CircuitCapabilities Declare what this target accepts in circuit IR.
Methods¶
materialize¶
def materialize(self, program: CircuitProgram) -> MaterializedCircuit[ArtifactT]Materialize one circuit program.
Parameters:
| Name | Type | Description |
|---|---|---|
program | CircuitProgram | Target-legal circuit-family program. |
Returns:
MaterializedCircuit[ArtifactT] — Artifact plus engine binding metadata.
CircuitProgram [source]¶
class CircuitProgramStore one immutable engine-neutral circuit program.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Circuit entrypoint name. |
num_qubits | int | Number of virtual input qubit slots. |
num_clbits | int | Number of classical bit slots. |
input_wires | tuple[WireId, ...] | Initial wire version per qubit slot. |
output_wires | tuple[WireId, ...] | Final wire version per qubit slot. |
operations | tuple[CircuitInstruction, ...] | Structured instruction sequence. |
global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
global_phase: ScalarExprinput_wires: tuple[WireId, ...]name: strnum_clbits: intnum_qubits: intoperations: tuple[CircuitInstruction, ...]output_wires: tuple[WireId, ...]
CompilationPolicy [source]¶
class CompilationPolicySelect preferred realizations among target-supported alternatives.
Parameters:
| Name | Type | Description |
|---|---|---|
prefer_native_semantic_ops | bool | Whether legal target-native realizations are preferred over reusable fallback bodies. Defaults to True. |
prefer_native_pauli_evolution | bool | Whether 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,
) -> NoneAttributes¶
prefer_native_pauli_evolution: boolprefer_native_semantic_ops: bool
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,
) -> NoneAttributes¶
circuit: Tclbit_map: ClbitMapimplicit_output_qubit_indices: tuple[int, ...] | Nonemeasurement_qubit_map: dict[int, int]parameter_metadata: ParameterMetadataqubit_map: QubitMapsegment: QuantumSegment
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:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Values to bind parameters to. If not provided, parameters must be bound at execution time. |
parameters | list[str] | None | List of parameter names to preserve as engine parameters. |
Raises:
ValueError— If a name appears in bothbindingsandparameters. This is the innermost emit-side choke point: it catches the overlap even when anEmitPassis constructed directly (e.g. viaTranspiler._create_emit_pass), bypassing thetranspile/emitwrappers. A name in both is ambiguous and would otherwise silently bake the binding while dropping the runtime parameter (see #354).
Attributes¶
bindingsname: strparameters
Methods¶
run¶
def run(self, input: ProgramPlan) -> ExecutableProgram[T]Emit engine code from a program plan.
Parameters:
| Name | Type | Description |
|---|---|---|
input | ProgramPlan | Segmented 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:
EmitError— If expectation-value evaluation is combined with a measurement, projection, or reset operation, or if a planned segment cannot be emitted.
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 typeConstructor¶
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(),
) -> NoneAttributes¶
compiled_classical: list[CompiledClassicalSegment]compiled_expval: list[CompiledExpvalSegment]compiled_quantum: list[CompiledQuantumSegment[T]]has_parameters: bool Check if this program has unbound parameters.output_values: list[ValueLike]parameter_names: list[str] Get list of parameter names that need binding.plan: ProgramPlan | Nonequantum_circuit: T Get the single quantum circuit.
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 | NoneGet 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] | ExpvalJobRestore 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:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine adapter configured with the provider credentials and target used by the original job. |
snapshot | JobSnapshot | Snapshot returned by the original public job’s snapshot() method. |
bindings | dict[str, Any] | None | Original 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:
ExecutionError— If the snapshot operation or execution shape does not match this executable program.NotImplementedError— If the executor cannot restore the referenced provider execution.ValueError— If required bindings are missing or invalid.
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] | ExpvalJobSubmit one execution and return its lazy result job.
Parameters:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine-specific quantum executor. |
bindings | dict[str, Any] | None | Parameter 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} |
estimation | EstimationAccuracy | None | Optional 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:
ExecutionError— If no quantum circuit to executeValueError— If required parameters are missing
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:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine-specific quantum executor. |
shots | int | Number of shots to run. |
bindings | dict[str, Any] | None | Parameter 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:
ExecutionError— If no quantum circuit to executeValueError— If required parameters are missing
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:
| Name | Type | Description |
|---|---|---|
artifact | Any | Engine-native circuit object. |
parameters | Mapping[str, Any] | Engine parameters keyed by public parameter name. |
measurement_qubit_map | Mapping[int, int] | None | Static-measurement mapping from classical output slot to physical qubit slot. None preserves the lowering-provided mapping; an empty mapping is an explicit override. |
parameter_order | tuple[str, ...] | None | Artifact ABI order for positional parameters. None denotes name-based binding. |
implicit_output_qubit_indices | tuple[int, ...] | None | Physical 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,
) -> NoneAttributes¶
artifact: ArtifactTimplicit_output_qubit_indices: tuple[int, ...] | Nonemeasurement_qubit_map: Mapping[int, int] | Noneparameter_order: tuple[str, ...] | Noneparameters: Mapping[str, Any]
ProgramPlan [source]¶
class ProgramPlanExecution plan for a hybrid quantum/classical program.
Structure:
[Optional] Classical preprocessing (parameter computation, etc.)
Single quantum segment (REQUIRED)
[Optional] Expval segment OR classical postprocessing
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(),
) -> NoneAttributes¶
abi: ProgramABIboundaries: list[HybridBoundary]parameters: dict[str, Value]steps: list[ProgramStep]
qamomile.circuit.transpiler.circuit_ir.model¶
Immutable circuit IR nodes and the private mutable construction builder.
Overview¶
| Function | Description |
|---|---|
as_scalar_expr | Normalize a Python scalar or existing expression. |
has_mid_circuit_measurement | Return whether measured quantum state is consumed again in a region. |
| Class | Description |
|---|---|
BarrierInstruction | Separate scheduling regions without changing wire versions. |
BinaryExpr | Apply a binary scalar operation. |
BinaryOperator | Enumerate scalar operations preserved until target materialization. |
CallInstruction | Invoke a reusable circuit over versioned wires. |
CallableIdentity | Preserve the semantic identity of a reusable circuit body. |
CircuitBuilder | Build immutable circuit IR while assigning fresh wire versions. |
CircuitProgram | Store one immutable engine-neutral circuit program. |
ClassicalBitExpr | Reference a measured classical bit. |
ForInstruction | Repeat a structured circuit region over a concrete range. |
GateInstruction | Apply one primitive gate to versioned virtual wires. |
GateKind | Classification of gates for emission. |
IfInstruction | Select between two structured circuit regions. |
LiteralExpr | Represent a concrete scalar literal. |
LoopVariableExpr | Reference the induction value of a structured loop. |
MeasureInstruction | Measure a wire into a classical bit. |
MeasureVectorInstruction | Measure an ordered group of wires into classical bits. |
ParameterExpr | Reference a runtime circuit parameter. |
PauliEvolutionInstruction | Apply an abstract Hamiltonian evolution to selected wires. |
PauliEvolutionRealization | Enumerate legalization states for abstract Pauli evolution. |
ResetInstruction | Reset a wire and produce a fresh zero-state wire. |
ReusableCircuit | Describe a reusable circuit body and requested transforms. |
SemanticArguments | Store immutable named arguments belonging to an operation’s meaning. |
SemanticOpKey | Identify an abstract operation independently of any engine. |
UnaryExpr | Apply a unary scalar operation. |
UnaryOperator | Enumerate unary scalar operations preserved for materialization. |
WhileInstruction | Repeat a structured region while a runtime predicate is true. |
WireId | Identify one version of a virtual quantum wire. |
Constants¶
CircuitInstruction:TypeAliasIQFT_SEMANTIC_KEY=SemanticOpKey('qamomile.stdlib', 'iqft')Semantic key for the exact inverse quantum Fourier transform.MULTI_CONTROLLED_X_SEMANTIC_KEY=SemanticOpKey('qamomile.stdlib', 'multi_controlled_x')Semantic key for an arbitrary-width multi-controlled X operation.QFT_SEMANTIC_KEY=SemanticOpKey('qamomile.stdlib', 'qft')Semantic key for the exact standard quantum Fourier transform.RIPPLE_CARRY_ADD_SEMANTIC_KEY=SemanticOpKey('qamomile.stdlib', 'ripple_carry_add')Semantic key for the full reversible ripple-carry adder.SELECT_SEMANTIC_KEY=SemanticOpKey('qamomile.circuit', 'select')Semantic key for a fallback-defined, index-addressed quantum multiplexer.STATE_PREPARATION_SEMANTIC_KEY=SemanticOpKey('qamomile.stdlib', 'state_preparation')Semantic key for preparing one concrete normalized state vector.ScalarExpr:TypeAliasSemanticValue:TypeAlias
Functions¶
as_scalar_expr [source]¶
def as_scalar_expr(value: ScalarExpr | bool | int | float) -> ScalarExprNormalize a Python scalar or existing expression.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ScalarExpr | bool | int | float | Value to normalize. |
Returns:
ScalarExpr — Existing expression or a new literal expression.
has_mid_circuit_measurement [source]¶
def has_mid_circuit_measurement(operations: tuple[CircuitInstruction, ...]) -> boolReturn 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:
| Name | Type | Description |
|---|---|---|
operations | tuple[CircuitInstruction, ...] | Structured instruction region to inspect. |
Returns:
bool — True when the region or a nested reusable/control-flow body
contains a non-terminal measurement.
Classes¶
BarrierInstruction [source]¶
class BarrierInstructionSeparate scheduling regions without changing wire versions.
Parameters:
| Name | Type | Description |
|---|---|---|
wires | tuple[WireId, ...] | Wires participating in the barrier. |
Constructor¶
def __init__(self, wires: tuple[WireId, ...]) -> NoneAttributes¶
wires: tuple[WireId, ...]
BinaryExpr [source]¶
class BinaryExpr(_ScalarOperators)Apply a binary scalar operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operator | BinaryOperator | Operation kind. |
left | ScalarExpr | Left operand. |
right | ScalarExpr | Right operand. |
Constructor¶
def __init__(self, operator: BinaryOperator, left: ScalarExpr, right: ScalarExpr) -> NoneAttributes¶
left: ScalarExproperator: BinaryOperatorright: ScalarExpr
BinaryOperator [source]¶
class BinaryOperator(enum.Enum)Enumerate scalar operations preserved until target materialization.
Attributes¶
ADDANDDIVEQFLOORDIVGEGTLELTMODMULNEQORPOWSUB
CallInstruction [source]¶
class CallInstructionInvoke a reusable circuit over versioned wires.
Parameters:
| Name | Type | Description |
|---|---|---|
callee | ReusableCircuit | Reusable circuit and transforms. |
inputs | tuple[WireId, ...] | Consumed wire versions. |
outputs | tuple[WireId, ...] | Produced wire versions. |
Constructor¶
def __init__(
self,
callee: ReusableCircuit,
inputs: tuple[WireId, ...],
outputs: tuple[WireId, ...],
) -> NoneAttributes¶
callee: ReusableCircuitinputs: tuple[WireId, ...]outputs: tuple[WireId, ...]
CallableIdentity [source]¶
class CallableIdentityPreserve the semantic identity of a reusable circuit body.
Parameters:
| Name | Type | Description |
|---|---|---|
key | SemanticOpKey | Open semantic identity used by target-native realization registries. |
symbol | str | Human-readable callable name used for diagnostics. |
arguments | SemanticArguments | Immutable arguments that define this invocation’s meaning. Defaults to no arguments. |
Constructor¶
def __init__(
self,
key: SemanticOpKey,
symbol: str,
arguments: SemanticArguments = SemanticArguments(),
) -> NoneAttributes¶
arguments: SemanticArgumentskey: SemanticOpKeysymbol: str
CircuitBuilder [source]¶
class CircuitBuilderBuild immutable circuit IR while assigning fresh wire versions.
Parameters:
| Name | Type | Description |
|---|---|---|
num_qubits | int | Number of virtual qubit slots. |
num_clbits | int | Number of classical bit slots. |
name | str | Circuit name. Defaults to "main". |
Constructor¶
def __init__(self, num_qubits: int, num_clbits: int, name: str = 'main') -> NoneInitialize a circuit builder.
Parameters:
| Name | Type | Description |
|---|---|---|
num_qubits | int | Number of virtual qubit slots. |
num_clbits | int | Number of classical bit slots. |
name | str | Circuit name. Defaults to "main". |
Raises:
ValueError— If either slot count is negative.
Attributes¶
namenum_clbitsnum_qubitsoperations: list[CircuitInstruction] Return the current region instruction list.
Methods¶
add_global_phase¶
def add_global_phase(self, phase: ScalarExpr | bool | int | float) -> NoneAccumulate a global phase in the current lexical region.
Parameters:
| Name | Type | Description |
|---|---|---|
phase | ScalarExpr | bool | int | float | Phase contribution. |
append_barrier¶
def append_barrier(self, qubits: tuple[int, ...]) -> NoneAppend a scheduling barrier without changing wire versions.
Parameters:
| Name | Type | Description |
|---|---|---|
qubits | tuple[int, ...] | Participating qubit slots. |
append_call¶
def append_call(self, callee: ReusableCircuit, qubits: tuple[int, ...]) -> NoneAppend a reusable-circuit call and advance its wires.
Parameters:
| Name | Type | Description |
|---|---|---|
callee | ReusableCircuit | Reusable circuit and transforms. |
qubits | tuple[int, ...] | Participating qubit slots. |
append_gate¶
def append_gate(
self,
kind: GateKind,
qubits: tuple[int, ...],
parameters: tuple[ScalarExpr, ...] = (),
) -> NoneAppend a primitive gate and advance all participating wires.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | GateKind | Primitive gate kind. |
qubits | tuple[int, ...] | Participating qubit slots. |
parameters | tuple[ScalarExpr, ...] | Gate parameters. Defaults to an empty tuple. |
append_measure¶
def append_measure(self, qubit: int, clbit: int) -> NoneAppend a measurement.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | int | Measured qubit slot. |
clbit | int | Destination classical bit slot. |
Raises:
IndexError— Ifclbitis outside the allocated classical slots.
append_measure_vector¶
def append_measure_vector(self, qubits: tuple[int, ...], clbits: tuple[int, ...]) -> NoneAppend one ordered vector measurement.
Parameters:
| Name | Type | Description |
|---|---|---|
qubits | tuple[int, ...] | Measured qubit slots in result order. |
clbits | tuple[int, ...] | Destination classical slots. |
Raises:
ValueError— If qubit and classical-bit arities differ or either sequence contains duplicate slots.IndexError— If a classical-bit slot is outside the circuit.
append_pauli_evolution¶
def append_pauli_evolution(
self,
qubits: tuple[int, ...],
hamiltonian: Any,
time: ScalarExpr | bool | int | float,
) -> NoneAppend an abstract Pauli evolution and advance its wires.
Parameters:
| Name | Type | Description |
|---|---|---|
qubits | tuple[int, ...] | Participating qubit slots. |
hamiltonian | Any | Qamomile Hamiltonian value. |
time | ScalarExpr | bool | int | float | Evolution time. |
Raises:
ValueError— If a Qamomile Hamiltonian has a non-Hermitian identity coefficient.
append_reset¶
def append_reset(self, qubit: int) -> NoneAppend reset and advance the affected wire.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | int | Qubit slot to reset. |
begin_else¶
def begin_else(self, context: _IfContext) -> NoneClose a true region and open its false region.
Parameters:
| Name | Type | Description |
|---|---|---|
context | _IfContext | Token returned by :meth:begin_if. |
Raises:
RuntimeError— Ifcontextis not the innermost open conditional or an else branch has already started.
begin_for¶
def begin_for(self, indexset: range) -> LoopVariableExprOpen a structured for-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
indexset | range | Concrete iteration range. |
Returns:
LoopVariableExpr — Induction expression available inside the body.
begin_if¶
def begin_if(self, condition: ScalarExpr) -> _IfContextOpen the true region of a structured conditional.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime branch predicate. |
Returns:
_IfContext — Opaque builder token used to select the else branch.
begin_while¶
def begin_while(self, condition: ScalarExpr) -> _WhileContextOpen a structured while-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime loop predicate. |
Returns:
_WhileContext — Opaque builder token used to close the loop.
current_wire¶
def current_wire(self, qubit: int) -> WireIdReturn the current wire version for a qubit slot.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | int | Physical slot index assigned by circuit lowering. |
Returns:
WireId — Current version of the slot.
Raises:
KeyError— Ifqubitis outside the allocated slot range.
end_for¶
def end_for(self) -> NoneClose the innermost structured for-loop body.
Raises:
RuntimeError— If the innermost open region is not a for loop.
end_if¶
def end_if(self, context: _IfContext) -> NoneClose a structured conditional and merge its wire states.
Parameters:
| Name | Type | Description |
|---|---|---|
context | _IfContext | Token returned by :meth:begin_if. |
Raises:
RuntimeError— Ifcontextis not the innermost open conditional.
end_while¶
def end_while(self, context: _WhileContext) -> NoneClose a structured while-loop body.
Parameters:
| Name | Type | Description |
|---|---|---|
context | _WhileContext | Token returned by :meth:begin_while. |
Raises:
RuntimeError— Ifcontextis not the innermost open while loop.
freeze¶
def freeze(self) -> CircuitProgramFinalize the root region into immutable circuit IR.
Returns:
CircuitProgram — Immutable circuit program.
Raises:
RuntimeError— If a structured region is still open.
fresh_wire¶
def fresh_wire(self) -> WireIdAllocate a fresh module-local virtual wire version.
Returns:
WireId — Newly allocated wire identifier.
restore_state¶
def restore_state(self, snapshot: _CircuitBuilderSnapshot) -> NoneRestore a checkpoint after an append-only emission attempt.
Parameters:
| Name | Type | Description |
|---|---|---|
snapshot | _CircuitBuilderSnapshot | Checkpoint returned by :meth:snapshot_state for this builder. |
Raises:
RuntimeError— If emission removed or replaced state that existed before the checkpoint instead of only appending new state.
snapshot_state¶
def snapshot_state(self) -> _CircuitBuilderSnapshotCapture state that can be restored after declined emission.
Returns:
_CircuitBuilderSnapshot — Append-only builder checkpoint for the
current structured region.
CircuitProgram [source]¶
class CircuitProgramStore one immutable engine-neutral circuit program.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Circuit entrypoint name. |
num_qubits | int | Number of virtual input qubit slots. |
num_clbits | int | Number of classical bit slots. |
input_wires | tuple[WireId, ...] | Initial wire version per qubit slot. |
output_wires | tuple[WireId, ...] | Final wire version per qubit slot. |
operations | tuple[CircuitInstruction, ...] | Structured instruction sequence. |
global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
global_phase: ScalarExprinput_wires: tuple[WireId, ...]name: strnum_clbits: intnum_qubits: intoperations: tuple[CircuitInstruction, ...]output_wires: tuple[WireId, ...]
ClassicalBitExpr [source]¶
class ClassicalBitExpr(_ScalarOperators)Reference a measured classical bit.
Parameters:
| Name | Type | Description |
|---|---|---|
index | int | Circuit-local classical bit index. |
Constructor¶
def __init__(self, index: int) -> NoneAttributes¶
index: int
ForInstruction [source]¶
class ForInstructionRepeat a structured circuit region over a concrete range.
Parameters:
| Name | Type | Description |
|---|---|---|
indexset | range | Concrete iteration range. |
loop_variable | LoopVariableExpr | Induction expression used by the body. |
inputs | tuple[WireId, ...] | Wire versions entering the loop. |
body | tuple[CircuitInstruction, ...] | Single-iteration body. |
body_outputs | tuple[WireId, ...] | Body wire versions yielded to the next iteration. |
outputs | tuple[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, ...],
) -> NoneAttributes¶
body: tuple[CircuitInstruction, ...]body_outputs: tuple[WireId, ...]indexset: rangeinputs: tuple[WireId, ...]loop_variable: LoopVariableExproutputs: tuple[WireId, ...]
GateInstruction [source]¶
class GateInstructionApply one primitive gate to versioned virtual wires.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | GateKind | Primitive gate kind. |
inputs | tuple[WireId, ...] | Consumed wire versions. |
outputs | tuple[WireId, ...] | Produced wire versions. |
parameters | tuple[ScalarExpr, ...] | Gate parameters. |
Constructor¶
def __init__(
self,
kind: GateKind,
inputs: tuple[WireId, ...],
outputs: tuple[WireId, ...],
parameters: tuple[ScalarExpr, ...] = (),
) -> NoneAttributes¶
inputs: tuple[WireId, ...]kind: GateKindoutputs: tuple[WireId, ...]parameters: tuple[ScalarExpr, ...]
GateKind [source]¶
class GateKind(Enum)Classification of gates for emission.
Attributes¶
CHCPCRXCRYCRZCXCYCZHMEASUREPRXRYRZRZZSSDGSWAPTTDGTOFFOLIXYZ
IfInstruction [source]¶
class IfInstructionSelect between two structured circuit regions.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime branch predicate. |
inputs | tuple[WireId, ...] | Wires entering both branches. |
true_body | tuple[CircuitInstruction, ...] | True branch body. |
false_body | tuple[CircuitInstruction, ...] | False branch body. |
true_outputs | tuple[WireId, ...] | Wires yielded by the true branch. |
false_outputs | tuple[WireId, ...] | Wires yielded by the false branch. |
outputs | tuple[WireId, ...] | Merged post-branch wires. |
true_global_phase | ScalarExpr | Phase applied only in the true branch. |
false_global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
condition: ScalarExprfalse_body: tuple[CircuitInstruction, ...]false_global_phase: ScalarExprfalse_outputs: tuple[WireId, ...]inputs: tuple[WireId, ...]outputs: tuple[WireId, ...]true_body: tuple[CircuitInstruction, ...]true_global_phase: ScalarExprtrue_outputs: tuple[WireId, ...]
LiteralExpr [source]¶
class LiteralExpr(_ScalarOperators)Represent a concrete scalar literal.
Parameters:
| Name | Type | Description |
|---|---|---|
value | bool | int | float | Concrete scalar value. |
Constructor¶
def __init__(self, value: bool | int | float) -> NoneAttributes¶
value: bool | int | float
LoopVariableExpr [source]¶
class LoopVariableExpr(_ScalarOperators)Reference the induction value of a structured loop.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Circuit-local loop variable name. |
Constructor¶
def __init__(self, name: str) -> NoneAttributes¶
name: str
MeasureInstruction [source]¶
class MeasureInstructionMeasure a wire into a classical bit.
Parameters:
| Name | Type | Description |
|---|---|---|
input | WireId | Measured wire version. |
output | WireId | Post-measurement wire version. |
clbit | int | Destination classical bit index. |
Constructor¶
def __init__(self, input: WireId, output: WireId, clbit: int) -> NoneAttributes¶
clbit: intinput: WireIdoutput: WireId
MeasureVectorInstruction [source]¶
class MeasureVectorInstructionMeasure 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:
| Name | Type | Description |
|---|---|---|
inputs | tuple[WireId, ...] | Measured wire versions in result order. |
outputs | tuple[WireId, ...] | Post-measurement wire versions. |
clbits | tuple[int, ...] | Destination classical bits in result order. |
Constructor¶
def __init__(
self,
inputs: tuple[WireId, ...],
outputs: tuple[WireId, ...],
clbits: tuple[int, ...],
) -> NoneAttributes¶
clbits: tuple[int, ...]inputs: tuple[WireId, ...]outputs: tuple[WireId, ...]
ParameterExpr [source]¶
class ParameterExpr(_ScalarOperators)Reference a runtime circuit parameter.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Stable external parameter name. |
Constructor¶
def __init__(self, name: str) -> NoneAttributes¶
name: str
PauliEvolutionInstruction [source]¶
class PauliEvolutionInstructionApply an abstract Hamiltonian evolution to selected wires.
Parameters:
| Name | Type | Description |
|---|---|---|
hamiltonian | Any | Immutable Qamomile Hamiltonian value. |
time | ScalarExpr | Evolution time in radians. |
inputs | tuple[WireId, ...] | Consumed wire versions. |
outputs | tuple[WireId, ...] | Produced wire versions. |
realization | PauliEvolutionRealization | Target 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,
) -> NoneAttributes¶
hamiltonian: Anyinputs: tuple[WireId, ...]outputs: tuple[WireId, ...]realization: PauliEvolutionRealizationtime: ScalarExpr
PauliEvolutionRealization [source]¶
class PauliEvolutionRealization(enum.Enum)Enumerate legalization states for abstract Pauli evolution.
Attributes¶
ABSTRACTGADGETNATIVE
ResetInstruction [source]¶
class ResetInstructionReset a wire and produce a fresh zero-state wire.
Parameters:
| Name | Type | Description |
|---|---|---|
input | WireId | Wire version before reset. |
output | WireId | Fresh wire version after reset. |
Constructor¶
def __init__(self, input: WireId, output: WireId) -> NoneAttributes¶
input: WireIdoutput: WireId
ReusableCircuit [source]¶
class ReusableCircuitDescribe a reusable circuit body and requested transforms.
Parameters:
| Name | Type | Description |
|---|---|---|
body | CircuitProgram | Reusable circuit body. |
name | str | Display and linkage name. |
power | int | Integral repetition count. Defaults to one. |
controls | int | Added control-wire count. Defaults to zero. |
inverse | bool | Whether to apply the inverse body. Defaults to false. |
identity | CallableIdentity | None | Semantic identity preserved for target legalization. None marks an anonymous body. Defaults to None. |
native_realization | str | None | Target-owned realization identifier selected during legalization. None keeps the reusable body as the fallback implementation. Defaults to None. |
operand_widths | tuple[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, ...] = (),
) -> NoneAttributes¶
body: CircuitProgramcontrols: intidentity: CallableIdentity | Noneinverse: boolname: strnative_realization: str | Nonenum_qubits: int Return the transformed call arity.operand_widths: tuple[int, ...]power: int
SemanticArguments [source]¶
class SemanticArgumentsStore immutable named arguments belonging to an operation’s meaning.
Parameters:
| Name | Type | Description |
|---|---|---|
entries | tuple[tuple[str, SemanticValue], ...] | Sorted name-value entries. Defaults to an empty tuple. |
Constructor¶
def __init__(self, entries: tuple[tuple[str, SemanticValue], ...] = ()) -> NoneAttributes¶
entries: tuple[tuple[str, SemanticValue], ...]
Methods¶
from_mapping¶
@classmethod
def from_mapping(cls, values: Mapping[str, Any] | None) -> 'SemanticArguments'Freeze one mapping of semantic operation arguments.
Parameters:
| Name | Type | Description |
|---|---|---|
values | Mapping[str, Any] | None | Serializer-friendly arguments, or None for no arguments. |
Returns:
'SemanticArguments' — Immutable, deterministically ordered arguments.
Raises:
TypeError— If a nested value is not serializer-friendly.
get¶
def get(self, name: str, default: SemanticValue = None) -> SemanticValueReturn one semantic argument by name.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Argument name. |
default | SemanticValue | Value 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 SemanticOpKeyIdentify 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:
| Name | Type | Description |
|---|---|---|
namespace | str | Stable owner namespace such as qamomile.stdlib. |
name | str | Stable operation name within the namespace. |
version | str | Semantic contract version. Defaults to "1". |
variant | str | None | Optional 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,
) -> NoneAttributes¶
name: strnamespace: strvariant: str | Noneversion: str
UnaryExpr [source]¶
class UnaryExpr(_ScalarOperators)Apply a unary scalar operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operator | UnaryOperator | Operation kind. |
operand | ScalarExpr | Input expression. |
Constructor¶
def __init__(self, operator: UnaryOperator, operand: ScalarExpr) -> NoneAttributes¶
operand: ScalarExproperator: UnaryOperator
UnaryOperator [source]¶
class UnaryOperator(enum.Enum)Enumerate unary scalar operations preserved for materialization.
Attributes¶
NEGNOT
WhileInstruction [source]¶
class WhileInstructionRepeat a structured region while a runtime predicate is true.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime loop predicate. |
inputs | tuple[WireId, ...] | Wires entering the loop. |
body | tuple[CircuitInstruction, ...] | Loop body. |
body_outputs | tuple[WireId, ...] | Wires yielded to the next iteration. |
outputs | tuple[WireId, ...] | Wires available after loop termination. |
body_global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
body: tuple[CircuitInstruction, ...]body_global_phase: ScalarExprbody_outputs: tuple[WireId, ...]condition: ScalarExprinputs: tuple[WireId, ...]outputs: tuple[WireId, ...]
WireId [source]¶
class WireIdIdentify one version of a virtual quantum wire.
Parameters:
| Name | Type | Description |
|---|---|---|
value | int | Non-negative module-local wire number. |
Constructor¶
def __init__(self, value: int) -> NoneAttributes¶
value: int
qamomile.circuit.transpiler.circuit_ir.parameter_usage¶
Reconcile runtime parameter metadata with immutable circuit IR usage.
Overview¶
| Function | Description |
|---|---|
collect_program_parameter_names | Collect runtime parameter names used by one complete circuit program. |
collect_scalar_parameter_names | Collect runtime parameter names from one scalar expression. |
reconcile_parameter_metadata | Filter provisional runtime metadata to parameters used by CircuitIR. |
| Class | Description |
|---|---|
BarrierInstruction | Separate scheduling regions without changing wire versions. |
BinaryExpr | Apply a binary scalar operation. |
CallInstruction | Invoke a reusable circuit over versioned wires. |
CircuitProgram | Store one immutable engine-neutral circuit program. |
ClassicalBitExpr | Reference a measured classical bit. |
EmitError | Report an engine failure to emit one semantic operation. |
ForInstruction | Repeat a structured circuit region over a concrete range. |
GateInstruction | Apply one primitive gate to versioned virtual wires. |
IfInstruction | Select between two structured circuit regions. |
LiteralExpr | Represent a concrete scalar literal. |
LoopVariableExpr | Reference the induction value of a structured loop. |
MeasureInstruction | Measure a wire into a classical bit. |
MeasureVectorInstruction | Measure an ordered group of wires into classical bits. |
ParameterExpr | Reference a runtime circuit parameter. |
ParameterMetadata | Describe every scalar slot and runtime array in a compiled segment. |
PauliEvolutionInstruction | Apply an abstract Hamiltonian evolution to selected wires. |
ResetInstruction | Reset a wire and produce a fresh zero-state wire. |
UnaryExpr | Apply a unary scalar operation. |
WhileInstruction | Repeat a structured region while a runtime predicate is true. |
Constants¶
CircuitInstruction:TypeAliasScalarExpr:TypeAlias
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:
| Name | Type | Description |
|---|---|---|
program | CircuitProgram | Immutable circuit program to inspect. |
Returns:
set[str] — set[str]: Names referenced anywhere in the program or nested bodies.
Raises:
EmitError— If the program contains an unknown node or a cyclic reusable-call graph.
collect_scalar_parameter_names [source]¶
def collect_scalar_parameter_names(expression: ScalarExpr) -> set[str]Collect runtime parameter names from one scalar expression.
Parameters:
| Name | Type | Description |
|---|---|---|
expression | ScalarExpr | Closed CircuitIR scalar expression to inspect. |
Returns:
set[str] — set[str]: Names referenced by the expression.
Raises:
EmitError— If an unknown scalar-expression node reaches CircuitIR.
reconcile_parameter_metadata [source]¶
def reconcile_parameter_metadata(program: CircuitProgram, metadata: ParameterMetadata) -> ParameterMetadataFilter 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:
| Name | Type | Description |
|---|---|---|
program | CircuitProgram | Verified immutable circuit program. |
metadata | ParameterMetadata | Provisional segment parameter metadata. |
Returns:
ParameterMetadata — Metadata containing exactly the used parameter
slots, in their original ABI order.
Raises:
EmitError— If CircuitIR references a runtime parameter absent from the provisional metadata, or the CircuitIR graph is malformed.ValueError— If retained array slots have inconsistent ranks.
Classes¶
BarrierInstruction [source]¶
class BarrierInstructionSeparate scheduling regions without changing wire versions.
Parameters:
| Name | Type | Description |
|---|---|---|
wires | tuple[WireId, ...] | Wires participating in the barrier. |
Constructor¶
def __init__(self, wires: tuple[WireId, ...]) -> NoneAttributes¶
wires: tuple[WireId, ...]
BinaryExpr [source]¶
class BinaryExpr(_ScalarOperators)Apply a binary scalar operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operator | BinaryOperator | Operation kind. |
left | ScalarExpr | Left operand. |
right | ScalarExpr | Right operand. |
Constructor¶
def __init__(self, operator: BinaryOperator, left: ScalarExpr, right: ScalarExpr) -> NoneAttributes¶
left: ScalarExproperator: BinaryOperatorright: ScalarExpr
CallInstruction [source]¶
class CallInstructionInvoke a reusable circuit over versioned wires.
Parameters:
| Name | Type | Description |
|---|---|---|
callee | ReusableCircuit | Reusable circuit and transforms. |
inputs | tuple[WireId, ...] | Consumed wire versions. |
outputs | tuple[WireId, ...] | Produced wire versions. |
Constructor¶
def __init__(
self,
callee: ReusableCircuit,
inputs: tuple[WireId, ...],
outputs: tuple[WireId, ...],
) -> NoneAttributes¶
callee: ReusableCircuitinputs: tuple[WireId, ...]outputs: tuple[WireId, ...]
CircuitProgram [source]¶
class CircuitProgramStore one immutable engine-neutral circuit program.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Circuit entrypoint name. |
num_qubits | int | Number of virtual input qubit slots. |
num_clbits | int | Number of classical bit slots. |
input_wires | tuple[WireId, ...] | Initial wire version per qubit slot. |
output_wires | tuple[WireId, ...] | Final wire version per qubit slot. |
operations | tuple[CircuitInstruction, ...] | Structured instruction sequence. |
global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
global_phase: ScalarExprinput_wires: tuple[WireId, ...]name: strnum_clbits: intnum_qubits: intoperations: tuple[CircuitInstruction, ...]output_wires: tuple[WireId, ...]
ClassicalBitExpr [source]¶
class ClassicalBitExpr(_ScalarOperators)Reference a measured classical bit.
Parameters:
| Name | Type | Description |
|---|---|---|
index | int | Circuit-local classical bit index. |
Constructor¶
def __init__(self, index: int) -> NoneAttributes¶
index: int
EmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
operation
ForInstruction [source]¶
class ForInstructionRepeat a structured circuit region over a concrete range.
Parameters:
| Name | Type | Description |
|---|---|---|
indexset | range | Concrete iteration range. |
loop_variable | LoopVariableExpr | Induction expression used by the body. |
inputs | tuple[WireId, ...] | Wire versions entering the loop. |
body | tuple[CircuitInstruction, ...] | Single-iteration body. |
body_outputs | tuple[WireId, ...] | Body wire versions yielded to the next iteration. |
outputs | tuple[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, ...],
) -> NoneAttributes¶
body: tuple[CircuitInstruction, ...]body_outputs: tuple[WireId, ...]indexset: rangeinputs: tuple[WireId, ...]loop_variable: LoopVariableExproutputs: tuple[WireId, ...]
GateInstruction [source]¶
class GateInstructionApply one primitive gate to versioned virtual wires.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | GateKind | Primitive gate kind. |
inputs | tuple[WireId, ...] | Consumed wire versions. |
outputs | tuple[WireId, ...] | Produced wire versions. |
parameters | tuple[ScalarExpr, ...] | Gate parameters. |
Constructor¶
def __init__(
self,
kind: GateKind,
inputs: tuple[WireId, ...],
outputs: tuple[WireId, ...],
parameters: tuple[ScalarExpr, ...] = (),
) -> NoneAttributes¶
inputs: tuple[WireId, ...]kind: GateKindoutputs: tuple[WireId, ...]parameters: tuple[ScalarExpr, ...]
IfInstruction [source]¶
class IfInstructionSelect between two structured circuit regions.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime branch predicate. |
inputs | tuple[WireId, ...] | Wires entering both branches. |
true_body | tuple[CircuitInstruction, ...] | True branch body. |
false_body | tuple[CircuitInstruction, ...] | False branch body. |
true_outputs | tuple[WireId, ...] | Wires yielded by the true branch. |
false_outputs | tuple[WireId, ...] | Wires yielded by the false branch. |
outputs | tuple[WireId, ...] | Merged post-branch wires. |
true_global_phase | ScalarExpr | Phase applied only in the true branch. |
false_global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
condition: ScalarExprfalse_body: tuple[CircuitInstruction, ...]false_global_phase: ScalarExprfalse_outputs: tuple[WireId, ...]inputs: tuple[WireId, ...]outputs: tuple[WireId, ...]true_body: tuple[CircuitInstruction, ...]true_global_phase: ScalarExprtrue_outputs: tuple[WireId, ...]
LiteralExpr [source]¶
class LiteralExpr(_ScalarOperators)Represent a concrete scalar literal.
Parameters:
| Name | Type | Description |
|---|---|---|
value | bool | int | float | Concrete scalar value. |
Constructor¶
def __init__(self, value: bool | int | float) -> NoneAttributes¶
value: bool | int | float
LoopVariableExpr [source]¶
class LoopVariableExpr(_ScalarOperators)Reference the induction value of a structured loop.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Circuit-local loop variable name. |
Constructor¶
def __init__(self, name: str) -> NoneAttributes¶
name: str
MeasureInstruction [source]¶
class MeasureInstructionMeasure a wire into a classical bit.
Parameters:
| Name | Type | Description |
|---|---|---|
input | WireId | Measured wire version. |
output | WireId | Post-measurement wire version. |
clbit | int | Destination classical bit index. |
Constructor¶
def __init__(self, input: WireId, output: WireId, clbit: int) -> NoneAttributes¶
clbit: intinput: WireIdoutput: WireId
MeasureVectorInstruction [source]¶
class MeasureVectorInstructionMeasure 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:
| Name | Type | Description |
|---|---|---|
inputs | tuple[WireId, ...] | Measured wire versions in result order. |
outputs | tuple[WireId, ...] | Post-measurement wire versions. |
clbits | tuple[int, ...] | Destination classical bits in result order. |
Constructor¶
def __init__(
self,
inputs: tuple[WireId, ...],
outputs: tuple[WireId, ...],
clbits: tuple[int, ...],
) -> NoneAttributes¶
clbits: tuple[int, ...]inputs: tuple[WireId, ...]outputs: tuple[WireId, ...]
ParameterExpr [source]¶
class ParameterExpr(_ScalarOperators)Reference a runtime circuit parameter.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Stable external parameter name. |
Constructor¶
def __init__(self, name: str) -> NoneAttributes¶
name: str
ParameterMetadata [source]¶
class ParameterMetadataDescribe every scalar slot and runtime array in a compiled segment.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | list[ParameterInfo] | Ordered scalar engine slots. Defaults to an empty list. |
arrays | dict[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(),
) -> NoneAttributes¶
arrays: dict[str, ParameterArrayInfo]parameters: list[ParameterInfo]
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 | NoneFind one scalar slot by its full emitted key.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Full engine parameter key. |
Returns:
ParameterInfo | None — ParameterInfo | None: Matching slot, or None when absent.
merge¶
@classmethod
def merge(cls, metadata: Sequence[ParameterMetadata]) -> ParameterMetadataMerge parameter manifests from multiple quantum segments.
Parameters:
| Name | Type | Description |
|---|---|---|
metadata | Sequence[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:
| Name | Type | Description |
|---|---|---|
bindings | Mapping[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) -> NoneValidate user array rank and every concrete ABI dimension.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | Mapping[str, Any] | None | Raw public bindings before scalar flattening. None means no validation is needed. |
Raises:
ValueError— If a supplied array has the wrong rank or exceeds a dimension whose ABI extent is known exactly.
validate_required_bindings¶
def validate_required_bindings(self, indexed_bindings: Mapping[str, Any]) -> NoneReject missing scalar slots in an indexed binding map.
Parameters:
| Name | Type | Description |
|---|---|---|
indexed_bindings | Mapping[str, Any] | Flattened user bindings. |
Raises:
ValueError— If one or more emitted scalar slots are missing.
PauliEvolutionInstruction [source]¶
class PauliEvolutionInstructionApply an abstract Hamiltonian evolution to selected wires.
Parameters:
| Name | Type | Description |
|---|---|---|
hamiltonian | Any | Immutable Qamomile Hamiltonian value. |
time | ScalarExpr | Evolution time in radians. |
inputs | tuple[WireId, ...] | Consumed wire versions. |
outputs | tuple[WireId, ...] | Produced wire versions. |
realization | PauliEvolutionRealization | Target 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,
) -> NoneAttributes¶
hamiltonian: Anyinputs: tuple[WireId, ...]outputs: tuple[WireId, ...]realization: PauliEvolutionRealizationtime: ScalarExpr
ResetInstruction [source]¶
class ResetInstructionReset a wire and produce a fresh zero-state wire.
Parameters:
| Name | Type | Description |
|---|---|---|
input | WireId | Wire version before reset. |
output | WireId | Fresh wire version after reset. |
Constructor¶
def __init__(self, input: WireId, output: WireId) -> NoneAttributes¶
input: WireIdoutput: WireId
UnaryExpr [source]¶
class UnaryExpr(_ScalarOperators)Apply a unary scalar operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operator | UnaryOperator | Operation kind. |
operand | ScalarExpr | Input expression. |
Constructor¶
def __init__(self, operator: UnaryOperator, operand: ScalarExpr) -> NoneAttributes¶
operand: ScalarExproperator: UnaryOperator
WhileInstruction [source]¶
class WhileInstructionRepeat a structured region while a runtime predicate is true.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime loop predicate. |
inputs | tuple[WireId, ...] | Wires entering the loop. |
body | tuple[CircuitInstruction, ...] | Loop body. |
body_outputs | tuple[WireId, ...] | Wires yielded to the next iteration. |
outputs | tuple[WireId, ...] | Wires available after loop termination. |
body_global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
body: tuple[CircuitInstruction, ...]body_global_phase: ScalarExprbody_outputs: tuple[WireId, ...]condition: ScalarExprinputs: tuple[WireId, ...]outputs: tuple[WireId, ...]
qamomile.circuit.transpiler.circuit_ir.verify¶
Structural verifier for engine-neutral circuit programs.
Overview¶
| Function | Description |
|---|---|
verify_circuit | Verify wire linearity, regions, expressions, and slot bounds. |
| Class | Description |
|---|---|
BarrierInstruction | Separate scheduling regions without changing wire versions. |
BinaryExpr | Apply a binary scalar operation. |
CallInstruction | Invoke a reusable circuit over versioned wires. |
CircuitProgram | Store one immutable engine-neutral circuit program. |
ClassicalBitExpr | Reference a measured classical bit. |
ForInstruction | Repeat a structured circuit region over a concrete range. |
GateInstruction | Apply one primitive gate to versioned virtual wires. |
GateKind | Classification of gates for emission. |
IfInstruction | Select between two structured circuit regions. |
LiteralExpr | Represent a concrete scalar literal. |
LoopVariableExpr | Reference the induction value of a structured loop. |
MeasureInstruction | Measure a wire into a classical bit. |
MeasureVectorInstruction | Measure an ordered group of wires into classical bits. |
PauliEvolutionInstruction | Apply an abstract Hamiltonian evolution to selected wires. |
ResetInstruction | Reset a wire and produce a fresh zero-state wire. |
UnaryExpr | Apply a unary scalar operation. |
WhileInstruction | Repeat a structured region while a runtime predicate is true. |
WireId | Identify one version of a virtual quantum wire. |
Constants¶
CircuitInstruction:TypeAliasGATE_SPECS:dict[GateKind, GateSpec]ScalarExpr:TypeAlias
Functions¶
verify_circuit [source]¶
def verify_circuit(program: CircuitProgram) -> NoneVerify wire linearity, regions, expressions, and slot bounds.
Parameters:
| Name | Type | Description |
|---|---|---|
program | CircuitProgram | Immutable circuit program to verify. |
Raises:
ValueError— If the program contains duplicate wire definitions, consumes a non-live wire, has malformed structured-region yields, references an invalid classical bit or loop variable, or reports incorrect outputs.
Classes¶
BarrierInstruction [source]¶
class BarrierInstructionSeparate scheduling regions without changing wire versions.
Parameters:
| Name | Type | Description |
|---|---|---|
wires | tuple[WireId, ...] | Wires participating in the barrier. |
Constructor¶
def __init__(self, wires: tuple[WireId, ...]) -> NoneAttributes¶
wires: tuple[WireId, ...]
BinaryExpr [source]¶
class BinaryExpr(_ScalarOperators)Apply a binary scalar operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operator | BinaryOperator | Operation kind. |
left | ScalarExpr | Left operand. |
right | ScalarExpr | Right operand. |
Constructor¶
def __init__(self, operator: BinaryOperator, left: ScalarExpr, right: ScalarExpr) -> NoneAttributes¶
left: ScalarExproperator: BinaryOperatorright: ScalarExpr
CallInstruction [source]¶
class CallInstructionInvoke a reusable circuit over versioned wires.
Parameters:
| Name | Type | Description |
|---|---|---|
callee | ReusableCircuit | Reusable circuit and transforms. |
inputs | tuple[WireId, ...] | Consumed wire versions. |
outputs | tuple[WireId, ...] | Produced wire versions. |
Constructor¶
def __init__(
self,
callee: ReusableCircuit,
inputs: tuple[WireId, ...],
outputs: tuple[WireId, ...],
) -> NoneAttributes¶
callee: ReusableCircuitinputs: tuple[WireId, ...]outputs: tuple[WireId, ...]
CircuitProgram [source]¶
class CircuitProgramStore one immutable engine-neutral circuit program.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Circuit entrypoint name. |
num_qubits | int | Number of virtual input qubit slots. |
num_clbits | int | Number of classical bit slots. |
input_wires | tuple[WireId, ...] | Initial wire version per qubit slot. |
output_wires | tuple[WireId, ...] | Final wire version per qubit slot. |
operations | tuple[CircuitInstruction, ...] | Structured instruction sequence. |
global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
global_phase: ScalarExprinput_wires: tuple[WireId, ...]name: strnum_clbits: intnum_qubits: intoperations: tuple[CircuitInstruction, ...]output_wires: tuple[WireId, ...]
ClassicalBitExpr [source]¶
class ClassicalBitExpr(_ScalarOperators)Reference a measured classical bit.
Parameters:
| Name | Type | Description |
|---|---|---|
index | int | Circuit-local classical bit index. |
Constructor¶
def __init__(self, index: int) -> NoneAttributes¶
index: int
ForInstruction [source]¶
class ForInstructionRepeat a structured circuit region over a concrete range.
Parameters:
| Name | Type | Description |
|---|---|---|
indexset | range | Concrete iteration range. |
loop_variable | LoopVariableExpr | Induction expression used by the body. |
inputs | tuple[WireId, ...] | Wire versions entering the loop. |
body | tuple[CircuitInstruction, ...] | Single-iteration body. |
body_outputs | tuple[WireId, ...] | Body wire versions yielded to the next iteration. |
outputs | tuple[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, ...],
) -> NoneAttributes¶
body: tuple[CircuitInstruction, ...]body_outputs: tuple[WireId, ...]indexset: rangeinputs: tuple[WireId, ...]loop_variable: LoopVariableExproutputs: tuple[WireId, ...]
GateInstruction [source]¶
class GateInstructionApply one primitive gate to versioned virtual wires.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | GateKind | Primitive gate kind. |
inputs | tuple[WireId, ...] | Consumed wire versions. |
outputs | tuple[WireId, ...] | Produced wire versions. |
parameters | tuple[ScalarExpr, ...] | Gate parameters. |
Constructor¶
def __init__(
self,
kind: GateKind,
inputs: tuple[WireId, ...],
outputs: tuple[WireId, ...],
parameters: tuple[ScalarExpr, ...] = (),
) -> NoneAttributes¶
inputs: tuple[WireId, ...]kind: GateKindoutputs: tuple[WireId, ...]parameters: tuple[ScalarExpr, ...]
GateKind [source]¶
class GateKind(Enum)Classification of gates for emission.
Attributes¶
CHCPCRXCRYCRZCXCYCZHMEASUREPRXRYRZRZZSSDGSWAPTTDGTOFFOLIXYZ
IfInstruction [source]¶
class IfInstructionSelect between two structured circuit regions.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime branch predicate. |
inputs | tuple[WireId, ...] | Wires entering both branches. |
true_body | tuple[CircuitInstruction, ...] | True branch body. |
false_body | tuple[CircuitInstruction, ...] | False branch body. |
true_outputs | tuple[WireId, ...] | Wires yielded by the true branch. |
false_outputs | tuple[WireId, ...] | Wires yielded by the false branch. |
outputs | tuple[WireId, ...] | Merged post-branch wires. |
true_global_phase | ScalarExpr | Phase applied only in the true branch. |
false_global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
condition: ScalarExprfalse_body: tuple[CircuitInstruction, ...]false_global_phase: ScalarExprfalse_outputs: tuple[WireId, ...]inputs: tuple[WireId, ...]outputs: tuple[WireId, ...]true_body: tuple[CircuitInstruction, ...]true_global_phase: ScalarExprtrue_outputs: tuple[WireId, ...]
LiteralExpr [source]¶
class LiteralExpr(_ScalarOperators)Represent a concrete scalar literal.
Parameters:
| Name | Type | Description |
|---|---|---|
value | bool | int | float | Concrete scalar value. |
Constructor¶
def __init__(self, value: bool | int | float) -> NoneAttributes¶
value: bool | int | float
LoopVariableExpr [source]¶
class LoopVariableExpr(_ScalarOperators)Reference the induction value of a structured loop.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Circuit-local loop variable name. |
Constructor¶
def __init__(self, name: str) -> NoneAttributes¶
name: str
MeasureInstruction [source]¶
class MeasureInstructionMeasure a wire into a classical bit.
Parameters:
| Name | Type | Description |
|---|---|---|
input | WireId | Measured wire version. |
output | WireId | Post-measurement wire version. |
clbit | int | Destination classical bit index. |
Constructor¶
def __init__(self, input: WireId, output: WireId, clbit: int) -> NoneAttributes¶
clbit: intinput: WireIdoutput: WireId
MeasureVectorInstruction [source]¶
class MeasureVectorInstructionMeasure 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:
| Name | Type | Description |
|---|---|---|
inputs | tuple[WireId, ...] | Measured wire versions in result order. |
outputs | tuple[WireId, ...] | Post-measurement wire versions. |
clbits | tuple[int, ...] | Destination classical bits in result order. |
Constructor¶
def __init__(
self,
inputs: tuple[WireId, ...],
outputs: tuple[WireId, ...],
clbits: tuple[int, ...],
) -> NoneAttributes¶
clbits: tuple[int, ...]inputs: tuple[WireId, ...]outputs: tuple[WireId, ...]
PauliEvolutionInstruction [source]¶
class PauliEvolutionInstructionApply an abstract Hamiltonian evolution to selected wires.
Parameters:
| Name | Type | Description |
|---|---|---|
hamiltonian | Any | Immutable Qamomile Hamiltonian value. |
time | ScalarExpr | Evolution time in radians. |
inputs | tuple[WireId, ...] | Consumed wire versions. |
outputs | tuple[WireId, ...] | Produced wire versions. |
realization | PauliEvolutionRealization | Target 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,
) -> NoneAttributes¶
hamiltonian: Anyinputs: tuple[WireId, ...]outputs: tuple[WireId, ...]realization: PauliEvolutionRealizationtime: ScalarExpr
ResetInstruction [source]¶
class ResetInstructionReset a wire and produce a fresh zero-state wire.
Parameters:
| Name | Type | Description |
|---|---|---|
input | WireId | Wire version before reset. |
output | WireId | Fresh wire version after reset. |
Constructor¶
def __init__(self, input: WireId, output: WireId) -> NoneAttributes¶
input: WireIdoutput: WireId
UnaryExpr [source]¶
class UnaryExpr(_ScalarOperators)Apply a unary scalar operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operator | UnaryOperator | Operation kind. |
operand | ScalarExpr | Input expression. |
Constructor¶
def __init__(self, operator: UnaryOperator, operand: ScalarExpr) -> NoneAttributes¶
operand: ScalarExproperator: UnaryOperator
WhileInstruction [source]¶
class WhileInstructionRepeat a structured region while a runtime predicate is true.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | ScalarExpr | Runtime loop predicate. |
inputs | tuple[WireId, ...] | Wires entering the loop. |
body | tuple[CircuitInstruction, ...] | Loop body. |
body_outputs | tuple[WireId, ...] | Wires yielded to the next iteration. |
outputs | tuple[WireId, ...] | Wires available after loop termination. |
body_global_phase | ScalarExpr | Phase 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))(),
) -> NoneAttributes¶
body: tuple[CircuitInstruction, ...]body_global_phase: ScalarExprbody_outputs: tuple[WireId, ...]condition: ScalarExprinputs: tuple[WireId, ...]outputs: tuple[WireId, ...]
WireId [source]¶
class WireIdIdentify one version of a virtual quantum wire.
Parameters:
| Name | Type | Description |
|---|---|---|
value | int | Non-negative module-local wire number. |
Constructor¶
def __init__(self, value: int) -> NoneAttributes¶
value: int
qamomile.circuit.transpiler.classical_executor¶
Classical segment executor for Python-based classical operations.
Overview¶
| Function | Description |
|---|---|
array_static_length | Resolve a one-dimensional array’s compile-time length. |
resolve_runtime_array_location | Resolve local array indices through runtime-bound slice views. |
validate_region_args | Validate the SSA identities owned by a loop’s region arguments. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
BinOp | Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN). |
BinOpKind | |
CInitOperation | Initialize the classical values (const, arguments etc) |
ClassicalExecutor | Executes classical segments in Python. |
ClassicalSegment | A segment of pure classical operations. |
CompOp | Comparison operation (EQ, NEQ, LT, LE, GT, GE). |
CompOpKind | |
CondOp | Conditional logical operation (AND, OR). |
CondOpKind | |
DecodeQFixedOperation | Decode measured bits to float (classical operation). |
DecodeQIntOperation | Decode least-significant-first measurement bits to an unsigned integer. |
DictGetItemOperation | Look up one entry of a Dict by a (possibly symbolic) key. |
DictValue | A dictionary value stored as stable ordered entries. |
ExecutionContext | Holds global state during program execution. |
ExecutionError | Error during program execution. |
ForItemsOperation | Represents iteration over dict/iterable items. |
ForOperation | Represents a for loop operation. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
IfOperation | Represents an if-else conditional operation. |
NotOp | |
RegionArg | Explicit loop-carried value on a loop operation (MLIR-style iter_arg). |
RuntimeClassicalExpr | A classical expression known to require runtime evaluation. |
RuntimeOpKind | Unified kind for RuntimeClassicalExpr covering all classical |
StoreArrayElementOperation | Store a classical scalar into one element of a classical array. |
TupleValue | A tuple of IR values for structured data. |
Value | A typed SSA value in the IR. |
WhileOperation | Represents a while loop operation. |
Constants¶
ValueLike:TypeAlias='Value | ArrayValue | TupleValue | DictValue'
Functions¶
array_static_length [source]¶
def array_static_length(array: 'ArrayValue') -> int | NoneResolve a one-dimensional array’s compile-time length.
Parameters:
| Name | Type | Description |
|---|---|---|
array | ArrayValue | Array 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, ...]] | NoneResolve local array indices through runtime-bound slice views.
Parameters:
| Name | Type | Description |
|---|---|---|
array | ArrayValue | Array whose local indices should be resolved. May be a root array or a slice_of view chain. |
indices | tuple[int, ...] | Concrete indices in array’s local coordinate space. |
resolve_int | Callable[[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:
| Name | Type | Description |
|---|---|---|
op | ForOperation | ForItemsOperation | WhileOperation | Loop operation whose region arguments should be validated. |
Returns:
tuple[RegionArg, ...] — tuple[RegionArg, ...]: The validated op.region_args tuple.
Raises:
ValueError— If result counts or positions disagree, slot types differ, or any loop-owned definition identity collides with another definition or with a region initializer/body yield.
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,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]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,
) -> NoneAttributes¶
kind: BinOpKind | Noneoperation_kind: OperationKindsignature: Signature
BinOpKind [source]¶
class BinOpKind(enum.Enum)Attributes¶
ADDDIVFLOORDIVMINMODMULPOWSUB
CInitOperation [source]¶
class CInitOperation(Operation)Initialize the classical values (const, arguments etc)
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
ClassicalExecutor [source]¶
class ClassicalExecutorExecutes 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:
| Name | Type | Description |
|---|---|---|
segment | ClassicalSegment | Ordered classical operations and declared outputs to evaluate. |
context | ExecutionContext | Per-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:
ExecutionError— If an operation is unsupported or a required runtime value is unavailable.
resolve_value¶
def resolve_value(self, value: ValueLike, context: ExecutionContext) -> AnyResolve a typed classical output using the execution interpreter.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ValueLike | Scalar, array, tuple, or dictionary output. |
context | ExecutionContext | Runtime bindings and computed values keyed by their IR identities or public parameter names. |
Returns:
Any — Concrete value with tuple and dictionary structure retained.
Raises:
ExecutionError— If a required value is absent from the context and its compile-time metadata.
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(),
) -> NoneAttributes¶
kind: SegmentKind
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,
) -> NoneAttributes¶
kind: CompOpKind | Noneoperation_kind: OperationKindsignature: Signature
CompOpKind [source]¶
class CompOpKind(enum.Enum)Attributes¶
EQGEGTLELTNEQ
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,
) -> NoneAttributes¶
kind: CondOpKind | Noneoperation_kind: OperationKindsignature: Signature
CondOpKind [source]¶
class CondOpKind(enum.Enum)Attributes¶
ANDOR
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.625operands: [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,
) -> NoneAttributes¶
int_bits: intnum_bits: intoperation_kind: OperationKindsignature: Signature
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:
| Name | Type | Description |
|---|---|---|
operands | list[Value] | Single measured ArrayValue[Bit] operand. |
results | list[Value] | Single decoded UIntType result. |
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
num_bits: int | None Return the bit count derived from the bit-array operand.operation_kind: OperationKind Classify integer decoding as host-side classical work.signature: Signature Return the integer-decoder signature.
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,
) -> NoneAttributes¶
dict_value: Value Value: The DictValue being indexed (operands[0]).key_arity: intkey_values: tuple[Value, ...] tuple[Value, ...]: The key component values.operation_kind: OperationKindsignature: Signature
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()))(),
) -> NoneAttributes¶
entries: tuple[tuple[TupleValue | Value, Value], ...]logical_id: strmetadata: ValueMetadataname: strtype: DictTypeuuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> DictValueExecutionContext [source]¶
class ExecutionContextHolds 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) -> Anyget_many¶
def get_many(self, keys: list[str]) -> dict[str, Any]has¶
def has(self, key: str) -> boolset¶
def set(self, key: str, value: Any) -> Noneupdate¶
def update(self, values: dict[str, Any]) -> NoneExecutionError [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):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]key_is_vector: boolkey_var_values: tuple[Value, ...] | Nonekey_vars: list[str]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]operation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signaturevalue_var: strvalue_var_value: Value | None
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the items-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt items-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationHasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[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()) -> NoneAttributes¶
input: Valueoperation_kind: OperationKindoutput: Valuesignature: Signature
RegionArg [source]¶
class RegionArgExplicit 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:
On iteration 0 the body reads
block_argbound toinit.After each iteration,
block_argis rebound to that iteration’syieldedvalue.After the loop,
resultholds the final carried value (initwhen the loop ran zero iterations).
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,
) -> NoneAttributes¶
block_arg: Valueinit: Valueresult: Valuevar_name: stryielded: Value
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:
Binary kinds (EQ/NEQ/LT/LE/GT/GE/AND/OR/ADD/SUB/MUL/DIV/FLOORDIV/MOD/POW):
operands = [lhs, rhs].Unary kind (NOT):
operands = [val].Ternary kind (SELECT):
operands = [condition, true_value, false_value]— the runtime form of a branch merge (result = true_value if condition else false_value).Result:
results = [output_value].
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,
) -> NoneAttributes¶
kind: RuntimeOpKind | Noneoperation_kind: OperationKindsignature: Signature
RuntimeOpKind [source]¶
class RuntimeOpKind(enum.Enum)Unified kind for RuntimeClassicalExpr covering all classical
op families that can appear at runtime.
The split between this enum and the per-family BinOpKind /
CompOpKind / CondOpKind is intentional: compile-time-foldable
classical ops keep their original IR types so the existing fold
pipeline (constant_fold → compile_time_if_lowering → emit-time
evaluate_classical_predicate) is undisturbed. Only ops identified
as runtime-evaluation-only by ClassicalLoweringPass get rewritten
to RuntimeClassicalExpr with a member of this enum.
Attributes¶
ADDANDDIVEQFLOORDIVGEGTLELTMODMULNEQNOTORPOWSELECTSUB
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:
Compile time:
ConstantFoldingPassfolds the store when the source array contents, the index, and the stored value are all compile-time resolvable, attaching the updatedconst_arraymetadata to the result value.Runtime: otherwise the store executes host-side in a classical segment via
ClassicalExecutor(e.g. for measurement-derivedVector[Bit]contents). It must never reach a quantum segment; engine emit rejects it explicitly.
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 bitsConstructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
array: ArrayValue ArrayValue: The array version the store reads from.index_values: tuple[Value, ...] tuple[Value, ...]: The element indices being written.operation_kind: OperationKindsignature: Signature Return the operation’s dynamic array/qubit/index signature.stored_value: Value Value: The scalar being written into the array.
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()))(),
) -> NoneAttributes¶
elements: tuple[ValueLike, ...]logical_id: strmetadata: ValueMetadataname: strtype: ‘TupleType’uuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> TupleValueValue [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of 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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]max_iterations: int | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the while body and its complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt while operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, rebind-record, and region-arg values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
qamomile.circuit.transpiler.compile_check¶
Overview¶
| Function | Description |
|---|---|
is_block_compilable | Check if a Block is compilable. |
| Class | Description |
|---|---|
Block | Unified block representation for all pipeline stages. |
Functions¶
is_block_compilable [source]¶
def is_block_compilable(block: Block) -> boolCheck 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:
| Name | Type | Description |
|---|---|---|
block | Block | The Block to check. |
Returns: bool: True if the block is compilable, False otherwise.
Classes¶
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
qamomile.circuit.transpiler.compiled_segments¶
Compiled segment structures for transpiled quantum circuits.
Overview¶
| Class | Description |
|---|---|
ClassicalSegment | A segment of pure classical operations. |
CompiledClassicalSegment | A classical segment ready for Python execution. |
CompiledExpvalSegment | A compiled expectation value segment with concrete Hamiltonian. |
CompiledQuantumSegment | A quantum segment with emitted engine circuit. |
ExpvalSegment | A segment for expectation value computation. |
ParameterMetadata | Describe every scalar slot and runtime array in a compiled segment. |
QuantumSegment | A 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(),
) -> NoneAttributes¶
kind: SegmentKind
CompiledClassicalSegment [source]¶
class CompiledClassicalSegmentA classical segment ready for Python execution.
Constructor¶
def __init__(self, segment: ClassicalSegment) -> NoneAttributes¶
segment: ClassicalSegment
CompiledExpvalSegment [source]¶
class CompiledExpvalSegmentA 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(),
) -> NoneAttributes¶
hamiltonian: ‘qm_o.Hamiltonian’quantum_segment_index: intqubit_map: dict[int, int]result_ref: strsegment: ExpvalSegment
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,
) -> NoneAttributes¶
circuit: Tclbit_map: ClbitMapimplicit_output_qubit_indices: tuple[int, ...] | Nonemeasurement_qubit_map: dict[int, int]parameter_metadata: ParameterMetadataqubit_map: QubitMapsegment: QuantumSegment
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 = '',
) -> NoneAttributes¶
hamiltonian_value: Value | Nonekind: SegmentKindqubits_value: Value | Noneresult_ref: str
ParameterMetadata [source]¶
class ParameterMetadataDescribe every scalar slot and runtime array in a compiled segment.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | list[ParameterInfo] | Ordered scalar engine slots. Defaults to an empty list. |
arrays | dict[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(),
) -> NoneAttributes¶
arrays: dict[str, ParameterArrayInfo]parameters: list[ParameterInfo]
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 | NoneFind one scalar slot by its full emitted key.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Full engine parameter key. |
Returns:
ParameterInfo | None — ParameterInfo | None: Matching slot, or None when absent.
merge¶
@classmethod
def merge(cls, metadata: Sequence[ParameterMetadata]) -> ParameterMetadataMerge parameter manifests from multiple quantum segments.
Parameters:
| Name | Type | Description |
|---|---|---|
metadata | Sequence[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:
| Name | Type | Description |
|---|---|---|
bindings | Mapping[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) -> NoneValidate user array rank and every concrete ABI dimension.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | Mapping[str, Any] | None | Raw public bindings before scalar flattening. None means no validation is needed. |
Raises:
ValueError— If a supplied array has the wrong rank or exceeds a dimension whose ABI extent is known exactly.
validate_required_bindings¶
def validate_required_bindings(self, indexed_bindings: Mapping[str, Any]) -> NoneReject missing scalar slots in an indexed binding map.
Parameters:
| Name | Type | Description |
|---|---|---|
indexed_bindings | Mapping[str, Any] | Flattened user bindings. |
Raises:
ValueError— If one or more emitted scalar slots are missing.
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,
) -> NoneAttributes¶
kind: SegmentKindnum_qubits: intqubit_values: list[Value]
qamomile.circuit.transpiler.compiler¶
Target-neutral compiler entrypoint for Qamomile programs.
Overview¶
| Function | Description |
|---|---|
prepare_module | Collect a hierarchical block into an immutable program-level view. |
validate_bindings_parameters_disjoint | Enforce the project rule that bindings and parameters are disjoint. |
without_static_bindings | Remove compile-time object bindings already consumed by qkernel build. |
| Class | Description |
|---|---|
Block | Unified block representation for all pipeline stages. |
BlockKind | Classification of block structure for pipeline stages. |
CompilationTarget | Define the contract implemented by every compilation target. |
CompiledProgram | Package an artifact with its ABI, diagnostics, and provenance. |
CompilerConfig | Configure semantic preparation and target-independent rewrites. |
EffectValidationPass | Reject execution-mode conflicts using cached kernel effects. |
EntrypointValidationPass | Validate top-level entrypoint constraints. |
ParameterShapeResolutionPass | Substitute symbolic parameter array shape dims with concrete constants. |
PreparedModule | Hold a prepared entrypoint and its reachable callable definitions. |
QKernelLike | Describe the frontend surface required by compiler entrypoints. |
QamomileCompiler | Prepare Qamomile semantics and dispatch explicit target compilation. |
RegionCapturePass | Populate explicit captures for every structured control-flow region. |
RegionValidationPass | Verify dominance and signatures for every explicit semantic region. |
SubstitutionPass | Pass that substitutes call operations and callable strategies. |
Functions¶
prepare_module [source]¶
def prepare_module(entrypoint: Block, bindings: Mapping[str, Any] | None = None) -> PreparedModuleCollect 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:
| Name | Type | Description |
|---|---|---|
entrypoint | Block | Hierarchical entrypoint after target-independent frontend preparation. |
bindings | Mapping[str, Any] | None | Compile-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) -> NoneEnforce 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:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Compile-time bindings keyed by argument name, or None. None is treated as empty. |
parameters | list[str] | None | Argument names to keep as runtime parameters, or None. None is treated as empty. |
Returns:
None — None
Raises:
ValueError— If any name appears in bothbindingsandparameters.
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:
| Name | Type | Description |
|---|---|---|
input_types | Mapping[str, Any] | QKernel input annotations by name. |
bindings | Mapping[str, Any] | None | User-provided compile-time values. |
Returns:
dict[str, Any] — dict[str, Any]: Ordinary scalar, array, and structural bindings only.
Classes¶
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
CompilationTarget [source]¶
class CompilationTarget(Protocol[PlanT, ArtifactT])Define the contract implemented by every compilation target.
Attributes¶
name: str Return the stable target name.
Methods¶
compile¶
def compile(self, program: PreparedModule, plan: PlanT) -> CompiledProgram[ArtifactT]Lower and materialize a prepared program for this target.
Parameters:
| Name | Type | Description |
|---|---|---|
program | PreparedModule | Prepared semantic program. |
plan | PlanT | Decisions returned by :meth:plan. |
Returns:
CompiledProgram[ArtifactT] — CompiledProgram[ArtifactT]: Target-native artifact and metadata.
plan¶
def plan(self, program: PreparedModule) -> PlanTChoose target-specific lowering decisions for a program.
Parameters:
| Name | Type | Description |
|---|---|---|
program | PreparedModule | Prepared semantic program. |
Returns:
PlanT — Immutable target-specific compilation plan.
validate¶
def validate(self, artifact: ArtifactT) -> NoneValidate a materialized artifact with target-native rules.
Parameters:
| Name | Type | Description |
|---|---|---|
artifact | ArtifactT | Target-native artifact to validate. |
Raises:
Exception— If target-native validation rejects the artifact.
CompiledProgram [source]¶
class CompiledProgram(Generic[ArtifactT])Package an artifact with its ABI, diagnostics, and provenance.
Parameters:
| Name | Type | Description |
|---|---|---|
artifact | ArtifactT | Target-native circuit, graph, module, or package. |
abi | ProgramABI | Runtime-visible input and output contract. |
metadata | CompilationMetadata | Target and pipeline provenance. |
diagnostics | tuple[CompilationDiagnostic, ...] | Non-fatal compilation diagnostics. Defaults to an empty tuple. |
Constructor¶
def __init__(
self,
artifact: ArtifactT,
abi: ProgramABI,
metadata: CompilationMetadata,
diagnostics: tuple[CompilationDiagnostic, ...] = (),
) -> NoneAttributes¶
abi: ProgramABIartifact: ArtifactTdiagnostics: tuple[CompilationDiagnostic, ...]metadata: CompilationMetadata
CompilerConfig [source]¶
class CompilerConfigConfigure semantic preparation and target-independent rewrites.
Parameters:
| Name | Type | Description |
|---|---|---|
decomposition | DecompositionConfig | Composite-gate decomposition choices. Defaults to the standard decomposition configuration. |
substitutions | SubstitutionConfig | Callable substitution rules. Defaults to no substitutions. |
Constructor¶
def __init__(
self,
decomposition: DecompositionConfig = DecompositionConfig(),
substitutions: SubstitutionConfig = SubstitutionConfig(),
) -> NoneAttributes¶
decomposition: DecompositionConfigsubstitutions: SubstitutionConfig
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:
| Name | Type | Description |
|---|---|---|
strategy_overrides | dict[str, str] | None | Gate-name to strategy mapping. Defaults to an empty mapping. |
**kwargs | Any | Additional :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¶
name: str Return the stable compiler-pass name.
Methods¶
run¶
def run(self, block: Block) -> BlockValidate expectation-value compatibility for one entrypoint.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Hierarchical entrypoint block. |
Returns:
Block — The unchanged validated block.
Raises:
ValidationError— If expectation-value execution is combined with measurement, reset, or feed-forward effects.
EntrypointValidationPass [source]¶
class EntrypointValidationPass(Pass[Block, Block])Validate top-level entrypoint constraints.
Attributes¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockParameterShapeResolutionPass [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) -> NoneInitialize parameter-shape resolution.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Compile-time bindings keyed by entrypoint argument name. Defaults to None. |
Attributes¶
name: str Return the pass name.
Methods¶
run¶
def run(self, input: Block) -> BlockReplace resolvable symbolic array dimensions with constants.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Hierarchical semantic block to rewrite. |
Returns:
Block — Rewritten block preserving all display, ABI, parameter, and
stage metadata.
Raises:
ValidationError— Ifinputis not hierarchical.
PreparedModule [source]¶
class PreparedModuleHold a prepared entrypoint and its reachable callable definitions.
Parameters:
| Name | Type | Description |
|---|---|---|
entrypoint_ref | CallableRef | Stable symbol assigned to the program entrypoint. |
entrypoint | Block | Hierarchical semantic block for the entrypoint. |
definitions | Mapping[CallableRef, CallableDef] | Reachable callable definitions keyed by their stable symbols. |
definition_variants | Mapping[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_graph | Mapping[CallableRef, frozenset[CallableRef]] | Directed caller-to-callee relation, including the entrypoint symbol. |
abi | ProgramABI | Classical public input and output contract. |
bindings | Mapping[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],
) -> NoneAttributes¶
abi: ProgramABIbindings: Mapping[str, Any]call_graph: Mapping[CallableRef, frozenset[CallableRef]]definition_variants: Mapping[CallableRef, tuple[CallableDef, ...]]definitions: Mapping[CallableRef, CallableDef]entrypoint: Blockentrypoint_ref: CallableRef
Methods¶
body¶
def body(self, ref: CallableRef) -> BlockReturn the semantic body associated with a program symbol.
Parameters:
| Name | Type | Description |
|---|---|---|
ref | CallableRef | Entrypoint or callable symbol to resolve. |
Returns:
Block — Hierarchical semantic body for ref.
Raises:
KeyError— Ifrefis neither the entrypoint nor a reachable body-backed callable definition.
owned_snapshot¶
def owned_snapshot(self) -> PreparedModuleCreate 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¶
block: Block Return the cached hierarchical body block.effects: KernelEffect Return cached semantic effects of the qkernel body.input_types: dict[str, Any] Return frontend input annotations by parameter name.name: str Return the user-facing callable name.output_types: list[Any] Return frontend output annotations.signature: inspect.Signature Return the Python call signature.
Methods¶
build¶
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> BlockBuild a traced body block.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | list[str] | None | Runtime parameter names to preserve. Defaults to None. |
**kwargs | Any | Compile-time bindings for non-parameter arguments. |
Returns:
Block — Traced hierarchical body block.
QamomileCompiler [source]¶
class QamomileCompilerPrepare Qamomile semantics and dispatch explicit target compilation.
Parameters:
| Name | Type | Description |
|---|---|---|
config | CompilerConfig | None | Shared frontend and substitution configuration. Defaults to :class:CompilerConfig. |
Constructor¶
def __init__(self, config: CompilerConfig | None = None) -> NoneInitialize the target-neutral compiler.
Parameters:
| Name | Type | Description |
|---|---|---|
config | CompilerConfig | None | Shared frontend configuration. Defaults to :class:CompilerConfig. |
Attributes¶
config
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:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | Top-level qkernel-like entrypoint. |
target | CompilationTarget[PlanT, ArtifactT] | Target planner, lowerer, materializer, and validator. |
bindings | dict[str, Any] | None | Compile-time bindings. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
Returns:
CompiledProgram[ArtifactT] — CompiledProgram[ArtifactT]: Validated target-native artifact.
Raises:
Exception— If semantic preparation, target compilation, or target-native validation fails.
prepare¶
def prepare(
self,
kernel: QKernelLike,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> PreparedModulePrepare a hierarchical semantic module without destroying calls.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | Top-level qkernel-like entrypoint. |
bindings | dict[str, Any] | None | Compile-time bindings used for tracing and shape resolution. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
Returns:
PreparedModule — Program-level semantic input for target planning.
Raises:
ValueError— If bindings overlap runtime parameters.EntrypointValidationError— If the top-level kernel has quantum inputs or outputs.
to_block¶
def to_block(
self,
kernel: QKernelLike,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> BlockTrace a qkernel-like object into a hierarchical semantic block.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | Frontend object to trace. |
bindings | dict[str, Any] | None | Compile-time argument values. Defaults to None. |
parameters | list[str] | None | Argument names retained as runtime parameters. Defaults to None. |
Returns:
Block — Hierarchical Qamomile semantic block.
Raises:
ValueError— Ifbindingsandparametersoverlap or frontend argument construction fails.TypeError— If specialization is requested for a block-only qkernel-like object that has nobuildmethod.
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) -> NoneInitialize an empty reachable-block visitation set.
Attributes¶
name: str Return the compiler-visible pass name.
Methods¶
run¶
def run(self, input: Block) -> BlockPopulate explicit captures throughout one block graph.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Semantic 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) -> NoneInitialize an empty reachable-block visitation set.
Attributes¶
name: str Return the compiler-visible pass name.
Methods¶
run¶
def run(self, input: Block) -> BlockValidate a block graph and return it unchanged.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Semantic entrypoint whose regions should be verified. |
Returns:
Block — The validated input block.
Raises:
ValidationError— If a region has an undeclared capture, violates dominance, or has an inconsistent block/yield signature.
SubstitutionPass [source]¶
class SubstitutionPass(Pass[Block, Block])Pass that substitutes call operations and callable strategies.
This pass traverses the block and applies substitution rules:
For inline InvokeOperation: replaces the callable body with the target
For boxed InvokeOperation: sets the strategy field
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) -> NoneInitialize the pass with configuration.
Parameters:
| Name | Type | Description |
|---|---|---|
config | SubstitutionConfig | Substitution configuration with rules |
Attributes¶
name: str Return pass name.
Methods¶
run¶
def run(self, input: Block) -> BlockApply substitutions to the block.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Block to transform |
Returns:
Block — Block with substitutions applied
qamomile.circuit.transpiler.config¶
Configuration shared by semantic preparation and target compilation.
Overview¶
| Class | Description |
|---|---|
CompilerConfig | Configure semantic preparation and target-independent rewrites. |
DecompositionConfig | Configure named implementation strategies for callable lowering. |
SubstitutionConfig | Configuration for the substitution pass. |
SubstitutionRule | A single substitution rule. |
Constants¶
TranspilerConfig=CompilerConfigBackward name for :class:CompilerConfigduring engine migration.
Classes¶
CompilerConfig [source]¶
class CompilerConfigConfigure semantic preparation and target-independent rewrites.
Parameters:
| Name | Type | Description |
|---|---|---|
decomposition | DecompositionConfig | Composite-gate decomposition choices. Defaults to the standard decomposition configuration. |
substitutions | SubstitutionConfig | Callable substitution rules. Defaults to no substitutions. |
Constructor¶
def __init__(
self,
decomposition: DecompositionConfig = DecompositionConfig(),
substitutions: SubstitutionConfig = SubstitutionConfig(),
) -> NoneAttributes¶
decomposition: DecompositionConfigsubstitutions: SubstitutionConfig
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:
| Name | Type | Description |
|---|---|---|
strategy_overrides | dict[str, str] | None | Gate-name to strategy mapping. Defaults to an empty mapping. |
**kwargs | Any | Additional :class:CompilerConfig constructor arguments. |
Returns:
'CompilerConfig' — Configuration containing matching decomposition
and substitution rules.
DecompositionConfig [source]¶
class DecompositionConfigConfigure 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:
| Name | Type | Description |
|---|---|---|
strategy_overrides | dict[str, str] | Callable-name to strategy-name overrides. |
strategy_params | dict[str, dict[str, Any]] | Optional strategy parameters keyed by strategy name. |
default_strategy | str | Fallback 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',
) -> NoneAttributes¶
default_strategy: strstrategy_overrides: dict[str, str]strategy_params: dict[str, dict[str, Any]]
Methods¶
get_strategy_for_gate¶
def get_strategy_for_gate(self, gate_name: str) -> strReturn the selected strategy name for a callable.
Parameters:
| Name | Type | Description |
|---|---|---|
gate_name | str | Callable 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:
| Name | Type | Description |
|---|---|---|
strategy_name | str | Strategy name. |
Returns:
dict[str, Any] — dict[str, Any]: Copy of the configured parameter mapping.
SubstitutionConfig [source]¶
class SubstitutionConfigConfiguration for the substitution pass.
Constructor¶
def __init__(self, rules: list[SubstitutionRule] = list()) -> NoneAttributes¶
rules: list[SubstitutionRule]
Methods¶
get_rule_for_name¶
def get_rule_for_name(self, name: str) -> SubstitutionRule | NoneFind a rule matching the given name.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Name to look up |
Returns:
SubstitutionRule | None — Matching SubstitutionRule or None
SubstitutionRule [source]¶
class SubstitutionRuleA single substitution rule.
Constructor¶
def __init__(
self,
source_name: str,
target: 'Block | QKernel | None' = None,
strategy: str | None = None,
validate_signature: bool = True,
) -> NoneAttributes¶
source_name: strstrategy: str | Nonetarget: ‘Block | QKernel | None’validate_signature: bool
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:
Which primitive gate to apply,
Which qubit role receives the gate (
"control"or"target"),An optional angle expression (e.g.
"theta/2","-pi/4").
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:
Qiskit uses native
circuit.ch()/circuit.cy()and never needs this decomposition.QURI Parts represents angles as parametric dicts (name -> coefficient); primitive
emit_*methods take those dicts, not plain floats, so a generic “loop over the recipe and callemitter.emit_ry(angle)” helper does not compose.CUDA-Q emits Python source as strings. A generic helper that calls
self.emit_ryinteracts poorly with the tracing test emitter, which wraps everyemit_*method and would double-record each call.
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¶
| Class | Description |
|---|---|
DecompStep | A single step in a decomposition recipe. |
PrimitiveGate | Gate primitives used in decomposition recipes. |
Constants¶
CH_DECOMPOSITION:list[DecompStep]CP_DECOMPOSITION:list[DecompStep]CRY_DECOMPOSITION:list[DecompStep]CRZ_DECOMPOSITION:list[DecompStep]CY_DECOMPOSITION:list[DecompStep]
Classes¶
DecompStep [source]¶
class DecompStepA single step in a decomposition recipe.
Constructor¶
def __init__(self, gate: PrimitiveGate, target: str, angle: str | None = None) -> NoneAttributes¶
angle: str | Nonegate: PrimitiveGatetarget: str
PrimitiveGate [source]¶
class PrimitiveGate(Enum)Gate primitives used in decomposition recipes.
Attributes¶
CNOTRYRZSSDG
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:
User-supplied kernel parameters (keyed by parameter name).
Loop iteration variables (keyed by Value UUID; pushed on entry, restored on exit).
Emit-time-computed intermediates —
BinOp/CompOp/CondOp/NotOpresults (keyed by Value UUID after Fix B; originally also keyed by Value name, which collided across tmps).Merge-output aliases (keyed by merge-output UUID; written by
register_classical_merge_aliases).Engine runtime expressions (e.g.
qiskit.circuit.classical.expr.Exprfor compound runtime if-conditions).Array data (keyed by ArrayValue UUID).
Dict data (keyed by DictValue UUID).
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:
_params— user parameters, keyed by name (user-facing)._loop_vars— loop iteration variables, keyed by Value UUID._values— emit-time intermediates, keyed by UUID._runtime_exprs— engine Expr objects, keyed by UUID._array_data— array bindings, keyed byArrayValue.uuid._dict_data— dict bindings, keyed byDictValue.uuid._observables— Pauli observables, keyed byValue.uuid.
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:
UUID: everything compiler-internal (loop vars, intermediates, runtime exprs, array/dict/observable bindings).
Name: only at the user-API boundary (parameter names supplied by
transpile(bindings={...})).
This eliminates the name-collision bug class entirely: empty/duplicate names cannot resolve to anything because lookups never go through the name path.
Overview¶
| Class | Description |
|---|---|
EmitContext | Bindings 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
TrueConstructor¶
def __init__(self, *args: Any = (), **kwargs: Any = {}) -> NoneMethods¶
bind_param¶
def bind_param(self, name: str, value: Any) -> NoneRegister a kernel parameter binding (by name).
bind_params¶
def bind_params(self, params: dict[str, Any]) -> NoneRegister 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) -> strReturn 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:
| Name | Type | Description |
|---|---|---|
user_bindings | dict[str, Any] | None | The 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) -> AnyGet array data by ArrayValue.uuid, or None.
get_dict_data¶
def get_dict_data(self, uuid: str) -> AnyGet dict data by DictValue.uuid, or None.
get_loop_var¶
def get_loop_var(self, uuid: str) -> AnyGet a loop variable binding by Value UUID, or None if absent.
get_observable¶
def get_observable(self, uuid: str) -> AnyGet a Pauli observable by Value UUID, or None.
get_runtime_expr¶
def get_runtime_expr(self, uuid: str) -> AnyGet 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) -> NoneBind a loop iteration variable, keyed by Value UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
uuid | str | loop_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. |
value | Any | The bound iteration value (int / Hamiltonian item / etc.). |
display_name | str | None | Reserved 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]) -> NoneRestore 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:
| Name | Type | Description |
|---|---|---|
snapshot | dict[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) -> NoneBind array data by ArrayValue.uuid.
Parameters:
| Name | Type | Description |
|---|---|---|
uuid | str | The array Value’s UUID. |
data | Any | The bound iterable / sequence / Vector handle. |
display_name | str | None | Reserved 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) -> NoneBind dict data by DictValue.uuid.
Parameters:
| Name | Type | Description |
|---|---|---|
uuid | str | The dict Value’s UUID. |
data | Any | The bound dict / iterable. |
display_name | str | None | Reserved 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) -> NoneBind a Pauli observable by Value UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
uuid | str | The observable Value’s UUID. |
observable | Any | A qm_o.Hamiltonian (or engine-equivalent). |
display_name | str | None | Reserved for debug-only display. It is not used as a binding key. |
set_runtime_expr¶
def set_runtime_expr(self, uuid: str, expr: Any) -> NoneBind 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) -> NoneBind 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¶
| Class | Description |
|---|---|
AffineTypeError | Base class for affine type violations. |
CallableDefinitionConflictError | Report two incompatible definitions claiming one callable symbol. |
DependencyError | Error when quantum operation depends on non-parameter classical value. |
EmitError | Report an engine failure to emit one semantic operation. |
EntrypointValidationError | Error when a top-level transpilation entrypoint has unsupported I/O. |
ExecutionError | Error during program execution. |
FrontendTransformError | Error during frontend AST-to-builder lowering. |
InliningError | Error during inline pass for callable invocations. |
OperandResolutionInfo | Detailed information about a single operand that failed to resolve. |
QamomileCompileError | Base class for all Qamomile compilation errors. |
QubitAliasError | Same qubit used multiple times in one operation. |
QubitBorrowConflictError | Qubit slot inaccessible because another live handle borrows it. |
QubitConsumedError | Qubit handle used after being consumed by a previous operation. |
QubitIndexResolutionError | Error when qubit indices cannot be resolved during emission. |
QubitRebindError | Quantum variable reassigned from a different quantum source. |
ResolutionFailureReason | Categorizes why qubit index resolution failed. |
SeparationError | Error during quantum/classical separation. |
TargetCapabilityError | A program requires a capability the selected target does not declare. |
UnreturnedBorrowError | Borrowed array element not returned before array use. |
ValidationError | Error 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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable affine-type failure. |
handle_name | str | None | Consumed or borrowed handle. Defaults to None. |
operation_name | str | None | Operation reporting the violation. Defaults to None. |
first_use_location | str | None | Original consuming use location. Defaults to None. |
Attributes¶
first_use_locationhandle_nameoperation_name
CallableDefinitionConflictError [source]¶
class CallableDefinitionConflictError(QamomileCompileError)Report two incompatible definitions claiming one callable symbol.
Parameters:
| Name | Type | Description |
|---|---|---|
symbol | str | Fully 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) -> NoneInitialize a callable-definition collision diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
symbol | str | Fully qualified callable symbol with conflicting definitions. |
Attributes¶
symbol: str
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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable dependency failure. |
quantum_op | str | None | Dependent quantum operation. Defaults to None. |
classical_value | str | None | Unsupported classical dependency. Defaults to None. |
Attributes¶
classical_valuequantum_op
EmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
operation
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 OperandResolutionInfoDetailed 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,
) -> NoneAttributes¶
element_indices_names: list[str]failure_details: strfailure_reason: ResolutionFailureReasonis_array_element: booloperand_name: stroperand_uuid: strparent_array_name: str | None
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 safeExample 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 borrowedCorrect code::
q0 = qubits[0]
q0 = qmc.h(q0)
qubits[0] = q0 # return the element first
q1 = qubits[1] # now safeQubitConsumedError [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:
| Name | Type | Description |
|---|---|---|
gate_type | str | Gate whose operands could not be resolved. |
operand_infos | list[OperandResolutionInfo] | Per-operand failure details. |
available_bindings_keys | list[str] | Binding names visible during resolution. |
available_qubit_map_keys | list[str] | Qubit-map keys visible during resolution. |
Attributes¶
available_bindings_keysavailable_qubit_map_keysgate_typeoperand_infos
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¶
ARRAY_ELEMENT_NOT_IN_QUBIT_MAPDIRECT_UUID_NOT_FOUNDINDEX_NOT_NUMERICNEGATIVE_INDEXNESTED_ARRAY_RESOLUTION_FAILEDSYMBOLIC_INDEX_NOT_BOUNDUNKNOWN
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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable diagnosis naming the target and the missing capability. |
target | str | None | Declared target name. Defaults to None. |
operation | str | None | Instruction 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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable diagnosis naming the target and the missing capability. |
target | str | None | Declared target name. Defaults to None. |
operation | str | None | Instruction description that triggered the failure. Defaults to None. |
Attributes¶
target: str | None
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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable validation failure. |
value_name | str | None | Related IR value name. Defaults to None. |
Attributes¶
value_name
qamomile.circuit.transpiler.executable¶
Executable program structure for compiled quantum-classical programs.
Overview¶
| Class | Description |
|---|---|
ClassicalExecutor | Executes classical segments in Python. |
CompiledClassicalSegment | A classical segment ready for Python execution. |
CompiledExpvalSegment | A compiled expectation value segment with concrete Hamiltonian. |
CompiledQuantumSegment | A quantum segment with emitted engine circuit. |
ExecutableProgram | A fully compiled program ready for execution. |
ExecutionContext | Holds global state during program execution. |
ExecutionError | Error during program execution. |
ExpvalJob | Job for expectation value computation. |
JobSnapshot | Store operation metadata and lossless raw execution reconstruction. |
ParameterArrayInfo | Describe the shape constraints known for one runtime array. |
ParameterContainerKind | Classify the public container that owns one engine scalar slot. |
ParameterInfo | Describe one scalar slot in a compiled engine parameter ABI. |
ParameterMetadata | Describe every scalar slot and runtime array in a compiled segment. |
ProgramPlan | Execution plan for a hybrid quantum/classical program. |
QuantumExecutor | Abstract base class for quantum backend execution. |
RunJob | Job for single execution. |
SampleJob | Job for sampling execution (multiple shots). |
Constants¶
EstimationAccuracy:TypeAlias=Exact | ShotBased | TargetPrecisionValueLike:TypeAlias='Value | ArrayValue | TupleValue | DictValue'
Classes¶
ClassicalExecutor [source]¶
class ClassicalExecutorExecutes 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:
| Name | Type | Description |
|---|---|---|
segment | ClassicalSegment | Ordered classical operations and declared outputs to evaluate. |
context | ExecutionContext | Per-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:
ExecutionError— If an operation is unsupported or a required runtime value is unavailable.
resolve_value¶
def resolve_value(self, value: ValueLike, context: ExecutionContext) -> AnyResolve a typed classical output using the execution interpreter.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ValueLike | Scalar, array, tuple, or dictionary output. |
context | ExecutionContext | Runtime bindings and computed values keyed by their IR identities or public parameter names. |
Returns:
Any — Concrete value with tuple and dictionary structure retained.
Raises:
ExecutionError— If a required value is absent from the context and its compile-time metadata.
CompiledClassicalSegment [source]¶
class CompiledClassicalSegmentA classical segment ready for Python execution.
Constructor¶
def __init__(self, segment: ClassicalSegment) -> NoneAttributes¶
segment: ClassicalSegment
CompiledExpvalSegment [source]¶
class CompiledExpvalSegmentA 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(),
) -> NoneAttributes¶
hamiltonian: ‘qm_o.Hamiltonian’quantum_segment_index: intqubit_map: dict[int, int]result_ref: strsegment: ExpvalSegment
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,
) -> NoneAttributes¶
circuit: Tclbit_map: ClbitMapimplicit_output_qubit_indices: tuple[int, ...] | Nonemeasurement_qubit_map: dict[int, int]parameter_metadata: ParameterMetadataqubit_map: QubitMapsegment: QuantumSegment
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 typeConstructor¶
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(),
) -> NoneAttributes¶
compiled_classical: list[CompiledClassicalSegment]compiled_expval: list[CompiledExpvalSegment]compiled_quantum: list[CompiledQuantumSegment[T]]has_parameters: bool Check if this program has unbound parameters.output_values: list[ValueLike]parameter_names: list[str] Get list of parameter names that need binding.plan: ProgramPlan | Nonequantum_circuit: T Get the single quantum circuit.
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 | NoneGet 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] | ExpvalJobRestore 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:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine adapter configured with the provider credentials and target used by the original job. |
snapshot | JobSnapshot | Snapshot returned by the original public job’s snapshot() method. |
bindings | dict[str, Any] | None | Original 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:
ExecutionError— If the snapshot operation or execution shape does not match this executable program.NotImplementedError— If the executor cannot restore the referenced provider execution.ValueError— If required bindings are missing or invalid.
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] | ExpvalJobSubmit one execution and return its lazy result job.
Parameters:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine-specific quantum executor. |
bindings | dict[str, Any] | None | Parameter 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} |
estimation | EstimationAccuracy | None | Optional 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:
ExecutionError— If no quantum circuit to executeValueError— If required parameters are missing
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:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine-specific quantum executor. |
shots | int | Number of shots to run. |
bindings | dict[str, Any] | None | Parameter 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:
ExecutionError— If no quantum circuit to executeValueError— If required parameters are missing
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 ExecutionContextHolds 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) -> Anyget_many¶
def get_many(self, keys: list[str]) -> dict[str, Any]has¶
def has(self, key: str) -> boolset¶
def set(self, key: str, value: Any) -> Noneupdate¶
def update(self, values: dict[str, Any]) -> NoneExecutionError [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]) -> NoneInitialize expval job.
Parameters:
| Name | Type | Description |
|---|---|---|
exp_val | float | ExecutionHandle[float] | Completed value or deferred expectation execution. |
Methods¶
result¶
def result(self, timeout: float | None = None) -> floatWait for and return the expectation value.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
float — Expectation value.
result_async¶
def result_async(self, timeout: float | None = None) -> floatWait asynchronously for and return the expectation value.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
float — Expectation value.
JobSnapshot [source]¶
class JobSnapshotStore 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:
| Name | Type | Description |
|---|---|---|
kind | JobKind | Public operation that created the job. |
executions | tuple[ExecutionReference, ...] | Ordered provider reference inventory. Empty for entirely local structured executions. For legacy snapshots, these references also specify the result layout. |
shots | int | None | Sampling shot count. Required for sample jobs and absent for run jobs. |
execution | ExecutionSnapshot | None | Ordered remote/local execution tree. None denotes the legacy flat-reference format. When present, executions must exactly match its remote leaves. |
Raises:
ValueError— If legacy references are empty, the reference inventory disagrees with the tree, or shots disagree with the operation kind.TypeError— If operation kind, references, tree, or shots have incompatible types.
Constructor¶
def __init__(
self,
kind: JobKind,
executions: tuple[ExecutionReference, ...],
shots: int | None = None,
execution: ExecutionSnapshot | None = None,
) -> NoneAttributes¶
execution: ExecutionSnapshot | Noneexecutions: tuple[ExecutionReference, ...]kind: JobKindshots: int | None
Methods¶
from_dict¶
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> JobSnapshotReconstruct a validated snapshot from JSON-compatible data.
Parameters:
| Name | Type | Description |
|---|---|---|
data | Mapping[str, Any] | Mapping produced by :meth:to_dict. |
Returns:
JobSnapshot — Validated typed-job restoration snapshot.
Raises:
KeyError— If operation kind, references, or a version 2 tree is absent.TypeError— If metadata, references, or local values have wrong types.ValueError— If a version, field, tree, or reference is invalid.
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:
TypeError— If local values were mutated to unsupported types.ValueError— If local values or references were mutated to invalid data.
ParameterArrayInfo [source]¶
class ParameterArrayInfoDescribe 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:
| Name | Type | Description |
|---|---|---|
name | str | Root runtime parameter name. |
rank | int | Number of array dimensions. |
expected_shape | tuple[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, ...]) -> NoneAttributes¶
expected_shape: tuple[int | None, ...]name: strrank: int
ParameterContainerKind [source]¶
class ParameterContainerKind(enum.StrEnum)Classify the public container that owns one engine scalar slot.
Attributes¶
ARRAYDICTSCALAR
ParameterInfo [source]¶
class ParameterInfoDescribe one scalar slot in a compiled engine parameter ABI.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Full scalar key, for example gammas[0]. |
array_name | str | Root parameter name, for example gammas. |
index | int | None | Backward-compatible one-dimensional index, or None for scalars and higher-rank elements. |
engine_param | Any | Engine-specific parameter object. |
source_ref | str | None | IR value UUID providing the runtime value. Defaults to None. |
indices | tuple[int, ...] | None | Complete array index tuple, or None for a scalar. Defaults to None. |
container_kind | ParameterContainerKind | Public 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,
) -> NoneAttributes¶
array_name: strcontainer_kind: ParameterContainerKindengine_param: Anyindex: int | Noneindices: tuple[int, ...] | Nonename: strsource_ref: str | None
ParameterMetadata [source]¶
class ParameterMetadataDescribe every scalar slot and runtime array in a compiled segment.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | list[ParameterInfo] | Ordered scalar engine slots. Defaults to an empty list. |
arrays | dict[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(),
) -> NoneAttributes¶
arrays: dict[str, ParameterArrayInfo]parameters: list[ParameterInfo]
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 | NoneFind one scalar slot by its full emitted key.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Full engine parameter key. |
Returns:
ParameterInfo | None — ParameterInfo | None: Matching slot, or None when absent.
merge¶
@classmethod
def merge(cls, metadata: Sequence[ParameterMetadata]) -> ParameterMetadataMerge parameter manifests from multiple quantum segments.
Parameters:
| Name | Type | Description |
|---|---|---|
metadata | Sequence[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:
| Name | Type | Description |
|---|---|---|
bindings | Mapping[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) -> NoneValidate user array rank and every concrete ABI dimension.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | Mapping[str, Any] | None | Raw public bindings before scalar flattening. None means no validation is needed. |
Raises:
ValueError— If a supplied array has the wrong rank or exceeds a dimension whose ABI extent is known exactly.
validate_required_bindings¶
def validate_required_bindings(self, indexed_bindings: Mapping[str, Any]) -> NoneReject missing scalar slots in an indexed binding map.
Parameters:
| Name | Type | Description |
|---|---|---|
indexed_bindings | Mapping[str, Any] | Flattened user bindings. |
Raises:
ValueError— If one or more emitted scalar slots are missing.
ProgramPlan [source]¶
class ProgramPlanExecution plan for a hybrid quantum/classical program.
Structure:
[Optional] Classical preprocessing (parameter computation, etc.)
Single quantum segment (REQUIRED)
[Optional] Expval segment OR classical postprocessing
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(),
) -> NoneAttributes¶
abi: ProgramABIboundaries: list[HybridBoundary]parameters: dict[str, Value]steps: list[ProgramStep]
QuantumExecutor [source]¶
class QuantumExecutor(ABC, Generic[T])Abstract base class for quantum backend execution.
To implement a custom executor:
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).
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.
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¶
capabilities: ExecutionCapabilities Describe backend execution features available through this adapter.
Methods¶
bind_invocation¶
def bind_invocation(self, invocation: CircuitInvocation[T]) -> TBind one invocation for a backend without native input submission.
Parameters:
| Name | Type | Description |
|---|---|---|
invocation | CircuitInvocation[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,
) -> TBind parameter values to the circuit.
Default implementation returns the circuit unchanged. Override for backends that support parametric circuits.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | T | The parameterized circuit |
bindings | dict[str, Any] | Dict mapping parameter names (indexed format) to values. e.g., {“gammas[0]”: 0.1, “gammas[1]”: 0.2} |
parameter_metadata | ParameterMetadata | Metadata 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,
) -> floatEstimate 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:
| Name | Type | Description |
|---|---|---|
circuit | T | The quantum circuit (state preparation ansatz) |
hamiltonian | 'qm_o.Hamiltonian' | The qamomile.observable.Hamiltonian to measure |
params | Sequence[float] | None | Optional parameter values for parametric circuits |
Returns:
float — The estimated expectation value
Raises:
NotImplementedError— If the executor does not support estimation
execute¶
def execute(self, circuit: T, shots: int) -> dict[str, int]Execute the circuit and return bitstring counts.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | T | The quantum circuit to execute |
shots | int | Number 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:
| Name | Type | Description |
|---|---|---|
reference | ExecutionReference | Provider execution reference. |
Returns:
ExecutionHandle[Any] — ExecutionHandle[Any]: Restored provider-backed handle.
Raises:
NotImplementedError— If this executor cannot restore jobs.
submit_estimate¶
def submit_estimate(self, request: EstimateRequest[T]) -> ExecutionHandle[float]Submit an expectation request through the synchronous path.
Parameters:
| Name | Type | Description |
|---|---|---|
request | EstimateRequest[T] | Circuit, Hamiltonian, and optional accuracy policy. |
Returns:
ExecutionHandle[float] — ExecutionHandle[float]: Completed compatibility handle.
Raises:
NotImplementedError— If an explicit accuracy policy is requested from an executor that has not implemented request submission.
submit_estimates¶
def submit_estimates(
self,
requests: Sequence[EstimateRequest[T]],
) -> ExecutionHandle[tuple[float, ...]]Submit an ordered collection of expectation requests.
Parameters:
| Name | Type | Description |
|---|---|---|
requests | Sequence[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:
| Name | Type | Description |
|---|---|---|
request | SampleRequest[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:
| Name | Type | Description |
|---|---|---|
requests | Sequence[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,
) -> NoneInitialize run job.
Parameters:
| Name | Type | Description |
|---|---|---|
raw_counts | dict[str, int] | ExecutionHandle[dict[str, int]] | None | Counts or deferred counts. May be None with value_handle. |
result_converter | Callable[[str], T] | None | Function converting one bitstring. May be None with value_handle. |
value_handle | ExecutionHandle[T] | None | Handle already producing the final public value. Defaults to None. |
Raises:
ValueError— If neither a valid counts source norvalue_handleis supplied.
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:
| Name | Type | Description |
|---|---|---|
handle | ExecutionHandle[T] | Final-value execution handle. |
Returns:
RunJob[T] — RunJob[T]: Public run job delegating to handle.
result¶
def result(self, timeout: float | None = None) -> TWait for and return the single public result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
T — Public kernel return value.
result_async¶
def result_async(self, timeout: float | None = None) -> TWait asynchronously for the single public result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum 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,
) -> NoneInitialize sample job.
Parameters:
| Name | Type | Description |
|---|---|---|
raw_counts | dict[str, int] | ExecutionHandle[dict[str, int]] | Counts or a deferred counts execution. |
result_converter | Callable[[dict[str, int]], list[tuple[T, int]]] | Function converting raw counts to typed values. |
shots | int | Number of requested shots. |
Methods¶
result¶
def result(self, timeout: float | None = None) -> SampleResult[T]Wait for and return the typed sample result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum 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:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum 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¶
| Class | Description |
|---|---|
Exact | Request an analytic expectation value without shot noise. |
ExecutionCapabilities | Declare the execution features implemented by one executor. |
ShotBased | Request a shot-based expectation value. |
TargetPrecision | Request an expectation value at a provider target precision. |
Classes¶
Exact [source]¶
class ExactRequest an analytic expectation value without shot noise.
Constructor¶
def __init__(self) -> NoneExecutionCapabilities [source]¶
class ExecutionCapabilitiesDeclare the execution features implemented by one executor.
Parameters:
| Name | Type | Description |
|---|---|---|
supports_async_sampling | bool | Whether sampling submission returns before provider execution completes. Defaults to False. |
supports_async_estimation | bool | Whether expectation submission returns before provider execution completes. Defaults to False. |
supports_estimation | bool | Whether expectation-value execution is implemented. Defaults to False. |
supports_cancellation | bool | Whether provider-backed handles can request cancellation. Defaults to False. |
supports_restoration | bool | Whether execution references can recreate provider-backed handles. Defaults to False. |
supports_native_batch | bool | Whether multiple logical requests can be submitted through one provider-native batch or job. Defaults to False. |
supports_native_parameter_inputs | bool | Whether runtime values remain separate from emitted circuits during provider submission. Defaults to False. |
estimation_accuracy | frozenset[EstimationPolicyType] | Explicit per-request accuracy policies accepted by the executor. An empty set means only executor-configured estimation behavior is available. |
Raises:
ValueError— If an unknown estimation policy type is declared or estimation features are declared without estimation support.
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(),
) -> NoneAttributes¶
estimation_accuracy: frozenset[EstimationPolicyType]supports_async_estimation: boolsupports_async_sampling: boolsupports_cancellation: boolsupports_estimation: boolsupports_native_batch: boolsupports_native_parameter_inputs: boolsupports_restoration: bool
ShotBased [source]¶
class ShotBasedRequest a shot-based expectation value.
Parameters:
| Name | Type | Description |
|---|---|---|
shots | int | Positive number of measurement shots. |
Raises:
ValueError— Ifshotsis not positive.
Constructor¶
def __init__(self, shots: int) -> NoneAttributes¶
shots: int
TargetPrecision [source]¶
class TargetPrecisionRequest an expectation value at a provider target precision.
Parameters:
| Name | Type | Description |
|---|---|---|
precision | float | Positive absolute target precision. |
Raises:
ValueError— Ifprecisionis not positive.
Constructor¶
def __init__(self, precision: float) -> NoneAttributes¶
precision: float
qamomile.circuit.transpiler.execution_context¶
Execution context for quantum-classical program execution.
Overview¶
| Class | Description |
|---|---|
ExecutionContext | Holds global state during program execution. |
Classes¶
ExecutionContext [source]¶
class ExecutionContextHolds 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) -> Anyget_many¶
def get_many(self, keys: list[str]) -> dict[str, Any]has¶
def has(self, key: str) -> boolset¶
def set(self, key: str, value: Any) -> Noneupdate¶
def update(self, values: dict[str, Any]) -> Noneqamomile.circuit.transpiler.execution_handle¶
Represent local and remote quantum execution lifecycles.
Overview¶
| Class | Description |
|---|---|
CompletedExecutionHandle | Wrap an already available result for synchronous executors. |
CompositeExecutionHandle | Aggregate several independently submitted executions. |
ExecutionHandle | Expose an engine execution without forcing immediate result retrieval. |
ExecutionReference | Store secret-free identifiers needed to restore remote execution. |
ExecutionSnapshot | Store a remote leaf, a local value, or an ordered execution group. |
ExecutionSnapshotKind | Identify the reconstruction contract of an execution snapshot node. |
JobStatus | Describe a provider-independent execution state. |
MappedExecutionHandle | Lazily transform another execution handle’s result. |
Classes¶
CompletedExecutionHandle [source]¶
class CompletedExecutionHandle(ExecutionHandle[ResultT])Wrap an already available result for synchronous executors.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ResultT | Completed execution value. |
Constructor¶
def __init__(self, value: ResultT) -> NoneInitialize an immediately completed execution.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ResultT | Completed execution value. |
Methods¶
result¶
def result(self, timeout: float | None = None) -> ResultTReturn the completed value without waiting.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Ignored compatibility timeout. |
Returns:
ResultT — Stored execution value.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture the already available raw result without waiting.
Returns:
ExecutionSnapshot — Owned, type-preserving local value.
Raises:
TypeError— If the value contains unsupported result objects.ValueError— If the value is nonfinite or cyclic.
status¶
def status(self) -> JobStatusReturn the completed status.
Returns:
JobStatus — Always :attr:JobStatus.COMPLETED.
CompositeExecutionHandle [source]¶
class CompositeExecutionHandle(ExecutionHandle[tuple[ResultT, ...]])Aggregate several independently submitted executions.
Parameters:
| Name | Type | Description |
|---|---|---|
handles | Sequence[ExecutionHandle[ResultT]] | Child executions in stable result order. |
Constructor¶
def __init__(self, handles: Sequence[ExecutionHandle[ResultT]]) -> NoneInitialize an ordered execution aggregate.
Parameters:
| Name | Type | Description |
|---|---|---|
handles | Sequence[ExecutionHandle[ResultT]] | Child executions. |
Attributes¶
native: object | None Return every child provider-native task.
Methods¶
cancel¶
def cancel(self) -> NoneAttempt 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:
ExceptionGroup— If any child status lookup or cancellation fails.
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) -> objectReturn 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:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Total local wait budget in seconds. |
Returns:
tuple[ResultT, ...] — tuple[ResultT, ...]: Ordered child results.
Raises:
TimeoutError— If the total wait budget expires.Exception— Any child execution failure.
result_async¶
def result_async(self, timeout: float | None = None) -> tuple[ResultT, ...]Return all child results asynchronously.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Total local wait budget in seconds. |
Returns:
tuple[ResultT, ...] — tuple[ResultT, ...]: Ordered child results.
Raises:
TimeoutError— If the total wait budget expires.Exception— Any child execution failure.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture all children with their original tuple boundaries.
Returns:
ExecutionSnapshot — Ordered nested execution structure.
Raises:
ValueError— If a child has no supported reconstruction contract.TypeError— If a local child contains unsupported result objects.
status¶
def status(self) -> JobStatusAggregate 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¶
native: object | None Return the wrapped provider-native task when available.
Methods¶
cancel¶
def cancel(self) -> NoneRequest 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) -> objectReturn 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) -> ResultTWait for and return the engine-neutral raw result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. None delegates the wait policy to the provider. |
Returns:
ResultT — Raw result normalized by the engine executor.
Raises:
TimeoutError— If the local wait expires before completion.
result_async¶
def result_async(self, timeout: float | None = None) -> ResultTWait asynchronously for the engine-neutral raw result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. Defaults to provider behavior when None. |
Returns:
ResultT — Raw result normalized by the engine executor.
Raises:
TimeoutError— If the local wait expires before completion.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture 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:
ValueError— If references are absent or their grouping is unknown.
status¶
def status(self) -> JobStatusReturn the current provider-independent execution status.
Returns:
JobStatus — Current normalized status.
ExecutionReference [source]¶
class ExecutionReferenceStore secret-free identifiers needed to restore remote execution.
Parameters:
| Name | Type | Description |
|---|---|---|
provider | str | Stable provider or adapter name. |
job_ids | tuple[str, ...] | One or more provider job identifiers. |
target | str | None | Provider target or device identifier. Defaults to None. |
group_id | str | None | Session, batch, program, or parent identifier. Defaults to None. |
context | Mapping[str, str] | Additional non-secret identifiers needed to restore the job. Defaults to an empty mapping. |
Raises:
ValueError— If the provider name or any job identifier is empty.TypeError— If identifiers or context have incompatible types.
Constructor¶
def __init__(
self,
provider: str,
job_ids: tuple[str, ...],
target: str | None = None,
group_id: str | None = None,
context: Mapping[str, str] = dict(),
) -> NoneAttributes¶
context: Mapping[str, str]group_id: str | Nonejob_ids: tuple[str, ...]provider: strtarget: str | None
Methods¶
from_dict¶
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionReferenceReconstruct a provider reference from JSON-compatible data.
Parameters:
| Name | Type | Description |
|---|---|---|
data | Mapping[str, Any] | Mapping produced by :meth:to_dict. |
Returns:
ExecutionReference — Validated provider execution reference.
Raises:
KeyError— If a required provider or job identifier field is absent.TypeError— If a field has an incompatible type.ValueError— If provider or job identifiers are empty.
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 ExecutionSnapshotStore 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:
| Name | Type | Description |
|---|---|---|
kind | str | ExecutionSnapshotKind | One of remote, local, or composite, normalized to an enum member. |
reference | ExecutionReference | None | Required only for remote leaves. |
value | Any | Supported native result for local leaves. Defaults to None. |
children | tuple[ExecutionSnapshot, ...] | Ordered composite children. Defaults to an empty tuple. |
Raises:
TypeError— If fields or local result types are unsupported.ValueError— If fields conflict with the node kind or values are invalid.
Constructor¶
def __init__(
self,
kind: str | ExecutionSnapshotKind,
reference: ExecutionReference | None = None,
value: Any = None,
children: tuple[ExecutionSnapshot, ...] = (),
) -> NoneAttributes¶
children: tuple[ExecutionSnapshot, ...]kind: str | ExecutionSnapshotKindreference: ExecutionReference | Nonevalue: Any
Methods¶
from_dict¶
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionSnapshotReconstruct an execution tree with strict node and value validation.
Parameters:
| Name | Type | Description |
|---|---|---|
data | Mapping[str, Any] | Mapping produced by :meth:to_dict. |
Returns:
ExecutionSnapshot — Validated execution structure.
Raises:
TypeError— If node fields have incompatible types.ValueError— If kinds, fields, references, or local values are invalid.
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:
TypeError— If mutable reference fields became incompatible.ValueError— If mutable reference fields became invalid.
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:
| Name | Type | Description |
|---|---|---|
restore_reference | Callable[[ExecutionReference], ExecutionHandle[Any]] | Provider-specific callback for one complete remote leaf. |
Returns:
ExecutionHandle[Any] — ExecutionHandle[Any]: Reconstructed raw execution lifecycle.
Raises:
TypeError— If local data is unsupported or the callback returns an incompatible handle.ValueError— If local values or references became invalid.Exception— If the provider restoration callback fails.
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:
TypeError— If mutable local data was changed to unsupported types.ValueError— If mutable local data or references became invalid.
ExecutionSnapshotKind [source]¶
class ExecutionSnapshotKind(StrEnum)Identify the reconstruction contract of an execution snapshot node.
Attributes¶
COMPOSITELOCALREMOTE
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¶
CANCELLEDCANCELLINGCOMPLETEDFAILEDPARTIALPENDINGQUEUEDRUNNINGUNKNOWN
MappedExecutionHandle [source]¶
class MappedExecutionHandle(ExecutionHandle[MappedT], Generic[ResultT, MappedT])Lazily transform another execution handle’s result.
Parameters:
| Name | Type | Description |
|---|---|---|
source | ExecutionHandle[ResultT] | Underlying execution handle. |
transform | Callable[[ResultT], MappedT] | Result transformation. |
snapshot_source | bool | Whether 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,
) -> NoneInitialize a lazy mapped execution.
Parameters:
| Name | Type | Description |
|---|---|---|
source | ExecutionHandle[ResultT] | Underlying execution handle. |
transform | Callable[[ResultT], MappedT] | Result transformation. |
snapshot_source | bool | Allow source snapshots only when the owner rebuilds the transformation on restore. Defaults to False. |
Attributes¶
native: object | None Return the source provider-native task.
Methods¶
cancel¶
def cancel(self) -> NoneForward 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) -> objectReturn 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) -> MappedTRetrieve and transform the source result once.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
MappedT — Cached transformed result.
Raises:
Exception— Any source or transformation failure.
result_async¶
def result_async(self, timeout: float | None = None) -> MappedTRetrieve and transform the source result asynchronously.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
MappedT — Cached transformed result.
Raises:
Exception— Any source or transformation failure.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture 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:
ValueError— If the mapping has no declared restoration contract.TypeError— If a local source value cannot be saved.
status¶
def status(self) -> JobStatusReturn the source execution status.
Returns:
JobStatus — Current mapped execution status.
qamomile.circuit.transpiler.execution_request¶
Describe engine-neutral quantum execution requests.
Overview¶
| Class | Description |
|---|---|
CircuitInvocation | Keep an emitted circuit and runtime parameter values together. |
EstimateRequest | Describe one Hamiltonian expectation execution. |
Exact | Request an analytic expectation value without shot noise. |
ParameterMetadata | Describe every scalar slot and runtime array in a compiled segment. |
SampleRequest | Describe one sampling execution. |
ShotBased | Request a shot-based expectation value. |
TargetPrecision | Request an expectation value at a provider target precision. |
Constants¶
EstimationAccuracy:TypeAlias=Exact | ShotBased | TargetPrecision
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:
| Name | Type | Description |
|---|---|---|
circuit | CircuitT | Emitted engine circuit or kernel artifact. |
bindings | Mapping[str, Any] | Flattened Qamomile runtime bindings. |
parameter_metadata | ParameterMetadata | Mapping from public parameter names to engine parameter objects. |
Constructor¶
def __init__(
self,
circuit: CircuitT,
bindings: Mapping[str, Any],
parameter_metadata: ParameterMetadata,
) -> NoneAttributes¶
bindings: Mapping[str, Any]circuit: CircuitTparameter_metadata: ParameterMetadata
EstimateRequest [source]¶
class EstimateRequest(Generic[CircuitT])Describe one Hamiltonian expectation execution.
Parameters:
| Name | Type | Description |
|---|---|---|
invocation | CircuitInvocation[CircuitT] | Circuit and runtime inputs. |
hamiltonian | qm_o.Hamiltonian | Observable to evaluate. |
accuracy | EstimationAccuracy | None | Explicit accuracy policy. None uses the executor’s configured default. |
Constructor¶
def __init__(
self,
invocation: CircuitInvocation[CircuitT],
hamiltonian: qm_o.Hamiltonian,
accuracy: EstimationAccuracy | None = None,
) -> NoneAttributes¶
accuracy: EstimationAccuracy | Nonehamiltonian: qm_o.Hamiltonianinvocation: CircuitInvocation[CircuitT]
Exact [source]¶
class ExactRequest an analytic expectation value without shot noise.
Constructor¶
def __init__(self) -> NoneParameterMetadata [source]¶
class ParameterMetadataDescribe every scalar slot and runtime array in a compiled segment.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | list[ParameterInfo] | Ordered scalar engine slots. Defaults to an empty list. |
arrays | dict[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(),
) -> NoneAttributes¶
arrays: dict[str, ParameterArrayInfo]parameters: list[ParameterInfo]
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 | NoneFind one scalar slot by its full emitted key.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Full engine parameter key. |
Returns:
ParameterInfo | None — ParameterInfo | None: Matching slot, or None when absent.
merge¶
@classmethod
def merge(cls, metadata: Sequence[ParameterMetadata]) -> ParameterMetadataMerge parameter manifests from multiple quantum segments.
Parameters:
| Name | Type | Description |
|---|---|---|
metadata | Sequence[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:
| Name | Type | Description |
|---|---|---|
bindings | Mapping[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) -> NoneValidate user array rank and every concrete ABI dimension.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | Mapping[str, Any] | None | Raw public bindings before scalar flattening. None means no validation is needed. |
Raises:
ValueError— If a supplied array has the wrong rank or exceeds a dimension whose ABI extent is known exactly.
validate_required_bindings¶
def validate_required_bindings(self, indexed_bindings: Mapping[str, Any]) -> NoneReject missing scalar slots in an indexed binding map.
Parameters:
| Name | Type | Description |
|---|---|---|
indexed_bindings | Mapping[str, Any] | Flattened user bindings. |
Raises:
ValueError— If one or more emitted scalar slots are missing.
SampleRequest [source]¶
class SampleRequest(Generic[CircuitT])Describe one sampling execution.
Parameters:
| Name | Type | Description |
|---|---|---|
invocation | CircuitInvocation[CircuitT] | Circuit and runtime inputs. |
shots | int | Number of requested samples. |
Raises:
ValueError— Ifshotsis not positive.
Constructor¶
def __init__(self, invocation: CircuitInvocation[CircuitT], shots: int) -> NoneAttributes¶
invocation: CircuitInvocation[CircuitT]shots: int
ShotBased [source]¶
class ShotBasedRequest a shot-based expectation value.
Parameters:
| Name | Type | Description |
|---|---|---|
shots | int | Positive number of measurement shots. |
Raises:
ValueError— Ifshotsis not positive.
Constructor¶
def __init__(self, shots: int) -> NoneAttributes¶
shots: int
TargetPrecision [source]¶
class TargetPrecisionRequest an expectation value at a provider target precision.
Parameters:
| Name | Type | Description |
|---|---|---|
precision | float | Positive absolute target precision. |
Raises:
ValueError— Ifprecisionis not positive.
Constructor¶
def __init__(self, precision: float) -> NoneAttributes¶
precision: float
qamomile.circuit.transpiler.execution_snapshot¶
Persist ordered execution structure without SDK objects or callables.
Overview¶
| Class | Description |
|---|---|
ExecutionHandle | Expose an engine execution without forcing immediate result retrieval. |
ExecutionReference | Store secret-free identifiers needed to restore remote execution. |
ExecutionSnapshot | Store a remote leaf, a local value, or an ordered execution group. |
ExecutionSnapshotKind | Identify 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¶
native: object | None Return the wrapped provider-native task when available.
Methods¶
cancel¶
def cancel(self) -> NoneRequest 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) -> objectReturn 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) -> ResultTWait for and return the engine-neutral raw result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. None delegates the wait policy to the provider. |
Returns:
ResultT — Raw result normalized by the engine executor.
Raises:
TimeoutError— If the local wait expires before completion.
result_async¶
def result_async(self, timeout: float | None = None) -> ResultTWait asynchronously for the engine-neutral raw result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. Defaults to provider behavior when None. |
Returns:
ResultT — Raw result normalized by the engine executor.
Raises:
TimeoutError— If the local wait expires before completion.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture 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:
ValueError— If references are absent or their grouping is unknown.
status¶
def status(self) -> JobStatusReturn the current provider-independent execution status.
Returns:
JobStatus — Current normalized status.
ExecutionReference [source]¶
class ExecutionReferenceStore secret-free identifiers needed to restore remote execution.
Parameters:
| Name | Type | Description |
|---|---|---|
provider | str | Stable provider or adapter name. |
job_ids | tuple[str, ...] | One or more provider job identifiers. |
target | str | None | Provider target or device identifier. Defaults to None. |
group_id | str | None | Session, batch, program, or parent identifier. Defaults to None. |
context | Mapping[str, str] | Additional non-secret identifiers needed to restore the job. Defaults to an empty mapping. |
Raises:
ValueError— If the provider name or any job identifier is empty.TypeError— If identifiers or context have incompatible types.
Constructor¶
def __init__(
self,
provider: str,
job_ids: tuple[str, ...],
target: str | None = None,
group_id: str | None = None,
context: Mapping[str, str] = dict(),
) -> NoneAttributes¶
context: Mapping[str, str]group_id: str | Nonejob_ids: tuple[str, ...]provider: strtarget: str | None
Methods¶
from_dict¶
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionReferenceReconstruct a provider reference from JSON-compatible data.
Parameters:
| Name | Type | Description |
|---|---|---|
data | Mapping[str, Any] | Mapping produced by :meth:to_dict. |
Returns:
ExecutionReference — Validated provider execution reference.
Raises:
KeyError— If a required provider or job identifier field is absent.TypeError— If a field has an incompatible type.ValueError— If provider or job identifiers are empty.
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 ExecutionSnapshotStore 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:
| Name | Type | Description |
|---|---|---|
kind | str | ExecutionSnapshotKind | One of remote, local, or composite, normalized to an enum member. |
reference | ExecutionReference | None | Required only for remote leaves. |
value | Any | Supported native result for local leaves. Defaults to None. |
children | tuple[ExecutionSnapshot, ...] | Ordered composite children. Defaults to an empty tuple. |
Raises:
TypeError— If fields or local result types are unsupported.ValueError— If fields conflict with the node kind or values are invalid.
Constructor¶
def __init__(
self,
kind: str | ExecutionSnapshotKind,
reference: ExecutionReference | None = None,
value: Any = None,
children: tuple[ExecutionSnapshot, ...] = (),
) -> NoneAttributes¶
children: tuple[ExecutionSnapshot, ...]kind: str | ExecutionSnapshotKindreference: ExecutionReference | Nonevalue: Any
Methods¶
from_dict¶
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionSnapshotReconstruct an execution tree with strict node and value validation.
Parameters:
| Name | Type | Description |
|---|---|---|
data | Mapping[str, Any] | Mapping produced by :meth:to_dict. |
Returns:
ExecutionSnapshot — Validated execution structure.
Raises:
TypeError— If node fields have incompatible types.ValueError— If kinds, fields, references, or local values are invalid.
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:
TypeError— If mutable reference fields became incompatible.ValueError— If mutable reference fields became invalid.
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:
| Name | Type | Description |
|---|---|---|
restore_reference | Callable[[ExecutionReference], ExecutionHandle[Any]] | Provider-specific callback for one complete remote leaf. |
Returns:
ExecutionHandle[Any] — ExecutionHandle[Any]: Reconstructed raw execution lifecycle.
Raises:
TypeError— If local data is unsupported or the callback returns an incompatible handle.ValueError— If local values or references became invalid.Exception— If the provider restoration callback fails.
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:
TypeError— If mutable local data was changed to unsupported types.ValueError— If mutable local data or references became invalid.
ExecutionSnapshotKind [source]¶
class ExecutionSnapshotKind(StrEnum)Identify the reconstruction contract of an execution snapshot node.
Attributes¶
COMPOSITELOCALREMOTE
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¶
| Function | Description |
|---|---|
default_combine_symbolic | Default combine_symbolic for engines with arithmetic-capable Parameters. |
| Class | Description |
|---|---|
BinOpKind | |
GateEmitter | Protocol for engine-specific gate emission. |
GateKind | Classification of gates for emission. |
GateSpec | Specification for a gate type. |
MeasurementMode | How an engine handles measurement operations. |
Constants¶
GATE_SPECS:dict[GateKind, GateSpec]
Functions¶
default_combine_symbolic [source]¶
def default_combine_symbolic(kind: 'BinOpKind', lhs: Any, rhs: Any) -> AnyDefault 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:
| Name | Type | Description |
|---|---|---|
kind | 'BinOpKind' | The BinOpKind to apply. |
lhs | Any | Left operand (numeric or engine Parameter / expression). |
rhs | Any | Right operand (same shape). |
Returns:
Any — lhs OP rhs for the matching operator. 0.0 / 0 for
Any — division-by-zero in the symbolic path so the caller can finish
Any — emission without aborting on a numerically degenerate case.
Any — None for unrecognised kind values, which the caller
Any — treats as a no-op.
Classes¶
BinOpKind [source]¶
class BinOpKind(enum.Enum)Attributes¶
ADDDIVFLOORDIVMINMODMULPOWSUB
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¶
measurement_mode: MeasurementMode Return the measurement mode for this engine.
Methods¶
append_gate¶
def append_gate(self, circuit: T, gate: Any, qubits: list[int]) -> NoneAppend a gate to the circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | T | The circuit to append to |
gate | Any | The gate to append (from circuit_to_gate) |
qubits | list[int] | Target qubit indices |
circuit_to_gate¶
def circuit_to_gate(self, circuit: T, name: str = 'U') -> AnyConvert a circuit to a reusable gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | T | The circuit to convert |
name | str | Label 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) -> TCreate a new empty circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
num_qubits | int | Number of qubits in the circuit |
num_clbits | int | Number of classical bits in the circuit |
Returns:
T — A new engine-specific circuit object
create_parameter¶
def create_parameter(self, name: str) -> AnyCreate a symbolic parameter for the engine.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Parameter name (e.g., “gammas[0]”) |
Returns:
Any — Engine-specific parameter object
emit_barrier¶
def emit_barrier(self, circuit: T, qubits: list[int]) -> NoneEmit barrier on specified qubits.
emit_ch¶
def emit_ch(self, circuit: T, control: int, target: int) -> NoneEmit controlled-Hadamard gate.
emit_cp¶
def emit_cp(self, circuit: T, control: int, target: int, angle: float | Any) -> NoneEmit controlled-Phase gate.
emit_crx¶
def emit_crx(self, circuit: T, control: int, target: int, angle: float | Any) -> NoneEmit controlled-RX gate.
emit_cry¶
def emit_cry(self, circuit: T, control: int, target: int, angle: float | Any) -> NoneEmit controlled-RY gate.
emit_crz¶
def emit_crz(self, circuit: T, control: int, target: int, angle: float | Any) -> NoneEmit controlled-RZ gate.
emit_cx¶
def emit_cx(self, circuit: T, control: int, target: int) -> NoneEmit CNOT gate.
emit_cy¶
def emit_cy(self, circuit: T, control: int, target: int) -> NoneEmit controlled-Y gate.
emit_cz¶
def emit_cz(self, circuit: T, control: int, target: int) -> NoneEmit CZ gate.
emit_else_start¶
def emit_else_start(self, circuit: T, context: Any) -> NoneStart the else branch.
emit_for_loop_end¶
def emit_for_loop_end(self, circuit: T, context: Any) -> NoneEnd a native for loop context.
emit_for_loop_start¶
def emit_for_loop_start(self, circuit: T, indexset: range) -> AnyStart 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) -> NoneEmit Hadamard gate.
emit_if_end¶
def emit_if_end(self, circuit: T, context: Any) -> NoneEnd the if/else block.
emit_if_start¶
def emit_if_start(self, circuit: T, clbit: int, value: int = 1) -> AnyStart a native if context.
Returns context for the if/else block.
emit_measure¶
def emit_measure(self, circuit: T, qubit: int, clbit: int) -> NoneEmit measurement operation.
emit_p¶
def emit_p(self, circuit: T, qubit: int, angle: float | Any) -> NoneEmit Phase gate (P(θ) = diag(1, e^(iθ))).
emit_reset¶
def emit_reset(self, circuit: T, qubit: int) -> NoneEmit a reset-to-zero operation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | T | Engine circuit to emit into. |
qubit | int | Physical qubit index to reset. |
Raises:
NotImplementedError— If the engine cannot represent reset.
emit_rx¶
def emit_rx(self, circuit: T, qubit: int, angle: float | Any) -> NoneEmit RX rotation gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | T | The circuit to emit to |
qubit | int | Target qubit index |
angle | float | Any | Rotation angle (float or engine parameter) |
emit_ry¶
def emit_ry(self, circuit: T, qubit: int, angle: float | Any) -> NoneEmit RY rotation gate.
emit_rz¶
def emit_rz(self, circuit: T, qubit: int, angle: float | Any) -> NoneEmit RZ rotation gate.
emit_rzz¶
def emit_rzz(self, circuit: T, qubit1: int, qubit2: int, angle: float | Any) -> NoneEmit RZZ gate (exp(-i * θ/2 * Z⊗Z)).
emit_s¶
def emit_s(self, circuit: T, qubit: int) -> NoneEmit S gate (√Z).
emit_sdg¶
def emit_sdg(self, circuit: T, qubit: int) -> NoneEmit S-dagger gate (inverse of S).
emit_swap¶
def emit_swap(self, circuit: T, qubit1: int, qubit2: int) -> NoneEmit SWAP gate.
emit_t¶
def emit_t(self, circuit: T, qubit: int) -> NoneEmit T gate (√S).
emit_tdg¶
def emit_tdg(self, circuit: T, qubit: int) -> NoneEmit T-dagger gate (inverse of T).
emit_toffoli¶
def emit_toffoli(self, circuit: T, control1: int, control2: int, target: int) -> NoneEmit Toffoli (CCX) gate.
emit_while_end¶
def emit_while_end(self, circuit: T, context: Any) -> NoneEnd the while loop context.
emit_while_start¶
def emit_while_start(self, circuit: T, clbit: int, value: int = 1) -> AnyStart a native while loop context.
emit_x¶
def emit_x(self, circuit: T, qubit: int) -> NoneEmit Pauli-X gate.
emit_y¶
def emit_y(self, circuit: T, qubit: int) -> NoneEmit Pauli-Y gate.
emit_z¶
def emit_z(self, circuit: T, qubit: int) -> NoneEmit Pauli-Z gate.
gate_controlled¶
def gate_controlled(self, gate: Any, num_controls: int) -> AnyCreate controlled version of a gate.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | Any | The gate to control |
num_controls | int | Number of control qubits |
Returns:
Any — New controlled gate
gate_inverse¶
def gate_inverse(self, gate: Any) -> AnyCreate an engine-native inverse gate when supported.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | Any | Engine-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) -> AnyCreate gate raised to a power (U^n).
Parameters:
| Name | Type | Description |
|---|---|---|
gate | Any | The gate to raise to a power |
power | int | The power to raise to |
Returns:
Any — New gate representing gate^power
supports_for_loop¶
def supports_for_loop(self) -> boolCheck if engine supports native for loops.
supports_gate_inverse¶
def supports_gate_inverse(self) -> boolReturn 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) -> boolCheck if engine supports native if/else.
supports_reusable_gates¶
def supports_reusable_gates(self) -> boolReturn 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) -> boolCheck if engine supports native while loops.
GateKind [source]¶
class GateKind(Enum)Classification of gates for emission.
Attributes¶
CHCPCRXCRYCRZCXCYCZHMEASUREPRXRYRZRZZSSDGSWAPTTDGTOFFOLIXYZ
GateSpec [source]¶
class GateSpecSpecification for a gate type.
Constructor¶
def __init__(
self,
kind: GateKind,
num_qubits: int,
has_angle: bool = False,
num_controls: int = 0,
) -> NoneAttributes¶
has_angle: boolkind: GateKindnum_controls: intnum_qubits: int
MeasurementMode [source]¶
class MeasurementMode(Enum)How an engine handles measurement operations.
Attributes¶
NATIVERUNNABLESTATIC
qamomile.circuit.transpiler.job¶
Job classes for quantum execution results.
Overview¶
| Function | Description |
|---|---|
aggregate_typed_results | Combine counts whose converted public result values are equal. |
| Class | Description |
|---|---|
CompletedExecutionHandle | Wrap an already available result for synchronous executors. |
ExecutionHandle | Expose an engine execution without forcing immediate result retrieval. |
ExecutionReference | Store secret-free identifiers needed to restore remote execution. |
ExecutionSnapshot | Store a remote leaf, a local value, or an ordered execution group. |
ExpvalJob | Job for expectation value computation. |
Job | Abstract base class for quantum execution jobs. |
JobKind | Identify the public operation needed to reconstruct a typed job. |
JobSnapshot | Store operation metadata and lossless raw execution reconstruction. |
JobStatus | Describe a provider-independent execution state. |
RunJob | Job for single execution. |
SampleJob | Job for sampling execution (multiple shots). |
SampleResult | Result 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:
| Name | Type | Description |
|---|---|---|
results | Iterable[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:
| Name | Type | Description |
|---|---|---|
value | ResultT | Completed execution value. |
Constructor¶
def __init__(self, value: ResultT) -> NoneInitialize an immediately completed execution.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ResultT | Completed execution value. |
Methods¶
result¶
def result(self, timeout: float | None = None) -> ResultTReturn the completed value without waiting.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Ignored compatibility timeout. |
Returns:
ResultT — Stored execution value.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture the already available raw result without waiting.
Returns:
ExecutionSnapshot — Owned, type-preserving local value.
Raises:
TypeError— If the value contains unsupported result objects.ValueError— If the value is nonfinite or cyclic.
status¶
def status(self) -> JobStatusReturn 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¶
native: object | None Return the wrapped provider-native task when available.
Methods¶
cancel¶
def cancel(self) -> NoneRequest 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) -> objectReturn 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) -> ResultTWait for and return the engine-neutral raw result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. None delegates the wait policy to the provider. |
Returns:
ResultT — Raw result normalized by the engine executor.
Raises:
TimeoutError— If the local wait expires before completion.
result_async¶
def result_async(self, timeout: float | None = None) -> ResultTWait asynchronously for the engine-neutral raw result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. Defaults to provider behavior when None. |
Returns:
ResultT — Raw result normalized by the engine executor.
Raises:
TimeoutError— If the local wait expires before completion.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture 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:
ValueError— If references are absent or their grouping is unknown.
status¶
def status(self) -> JobStatusReturn the current provider-independent execution status.
Returns:
JobStatus — Current normalized status.
ExecutionReference [source]¶
class ExecutionReferenceStore secret-free identifiers needed to restore remote execution.
Parameters:
| Name | Type | Description |
|---|---|---|
provider | str | Stable provider or adapter name. |
job_ids | tuple[str, ...] | One or more provider job identifiers. |
target | str | None | Provider target or device identifier. Defaults to None. |
group_id | str | None | Session, batch, program, or parent identifier. Defaults to None. |
context | Mapping[str, str] | Additional non-secret identifiers needed to restore the job. Defaults to an empty mapping. |
Raises:
ValueError— If the provider name or any job identifier is empty.TypeError— If identifiers or context have incompatible types.
Constructor¶
def __init__(
self,
provider: str,
job_ids: tuple[str, ...],
target: str | None = None,
group_id: str | None = None,
context: Mapping[str, str] = dict(),
) -> NoneAttributes¶
context: Mapping[str, str]group_id: str | Nonejob_ids: tuple[str, ...]provider: strtarget: str | None
Methods¶
from_dict¶
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionReferenceReconstruct a provider reference from JSON-compatible data.
Parameters:
| Name | Type | Description |
|---|---|---|
data | Mapping[str, Any] | Mapping produced by :meth:to_dict. |
Returns:
ExecutionReference — Validated provider execution reference.
Raises:
KeyError— If a required provider or job identifier field is absent.TypeError— If a field has an incompatible type.ValueError— If provider or job identifiers are empty.
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 ExecutionSnapshotStore 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:
| Name | Type | Description |
|---|---|---|
kind | str | ExecutionSnapshotKind | One of remote, local, or composite, normalized to an enum member. |
reference | ExecutionReference | None | Required only for remote leaves. |
value | Any | Supported native result for local leaves. Defaults to None. |
children | tuple[ExecutionSnapshot, ...] | Ordered composite children. Defaults to an empty tuple. |
Raises:
TypeError— If fields or local result types are unsupported.ValueError— If fields conflict with the node kind or values are invalid.
Constructor¶
def __init__(
self,
kind: str | ExecutionSnapshotKind,
reference: ExecutionReference | None = None,
value: Any = None,
children: tuple[ExecutionSnapshot, ...] = (),
) -> NoneAttributes¶
children: tuple[ExecutionSnapshot, ...]kind: str | ExecutionSnapshotKindreference: ExecutionReference | Nonevalue: Any
Methods¶
from_dict¶
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionSnapshotReconstruct an execution tree with strict node and value validation.
Parameters:
| Name | Type | Description |
|---|---|---|
data | Mapping[str, Any] | Mapping produced by :meth:to_dict. |
Returns:
ExecutionSnapshot — Validated execution structure.
Raises:
TypeError— If node fields have incompatible types.ValueError— If kinds, fields, references, or local values are invalid.
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:
TypeError— If mutable reference fields became incompatible.ValueError— If mutable reference fields became invalid.
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:
| Name | Type | Description |
|---|---|---|
restore_reference | Callable[[ExecutionReference], ExecutionHandle[Any]] | Provider-specific callback for one complete remote leaf. |
Returns:
ExecutionHandle[Any] — ExecutionHandle[Any]: Reconstructed raw execution lifecycle.
Raises:
TypeError— If local data is unsupported or the callback returns an incompatible handle.ValueError— If local values or references became invalid.Exception— If the provider restoration callback fails.
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:
TypeError— If mutable local data was changed to unsupported types.ValueError— If mutable local data or references became invalid.
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]) -> NoneInitialize expval job.
Parameters:
| Name | Type | Description |
|---|---|---|
exp_val | float | ExecutionHandle[float] | Completed value or deferred expectation execution. |
Methods¶
result¶
def result(self, timeout: float | None = None) -> floatWait for and return the expectation value.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
float — Expectation value.
result_async¶
def result_async(self, timeout: float | None = None) -> floatWait asynchronously for and return the expectation value.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum 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,
) -> NoneInitialize a public job around an execution handle.
Parameters:
| Name | Type | Description |
|---|---|---|
handle | ExecutionHandle[Any] | Raw or mapped engine execution. |
kind | JobKind | Public operation represented by the job. |
shots | int | None | Sampling shot count. Defaults to None for run jobs. |
Attributes¶
native: object | None Return the wrapped provider-native task when available.
Methods¶
cancel¶
def cancel(self) -> NoneRequest 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) -> objectReturn 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) -> TWait for and return the result.
Blocks until the job completes.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. None uses provider behavior. |
Returns:
T — Execution result with the appropriate public type.
Raises:
ExecutionError— If the job failed.
result_async¶
def result_async(self, timeout: float | None = None) -> TWait asynchronously for and return the public result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. Defaults to provider behavior when None. |
Returns:
T — Execution result with the appropriate public type.
snapshot¶
def snapshot(self) -> JobSnapshotCapture 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:
ValueError— If execution grouping or mapping cannot be restored, or a local value is nonfinite or cyclic.TypeError— If a local result contains unsupported objects.
status¶
def status(self) -> JobStatusReturn 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¶
RUNSAMPLE
JobSnapshot [source]¶
class JobSnapshotStore 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:
| Name | Type | Description |
|---|---|---|
kind | JobKind | Public operation that created the job. |
executions | tuple[ExecutionReference, ...] | Ordered provider reference inventory. Empty for entirely local structured executions. For legacy snapshots, these references also specify the result layout. |
shots | int | None | Sampling shot count. Required for sample jobs and absent for run jobs. |
execution | ExecutionSnapshot | None | Ordered remote/local execution tree. None denotes the legacy flat-reference format. When present, executions must exactly match its remote leaves. |
Raises:
ValueError— If legacy references are empty, the reference inventory disagrees with the tree, or shots disagree with the operation kind.TypeError— If operation kind, references, tree, or shots have incompatible types.
Constructor¶
def __init__(
self,
kind: JobKind,
executions: tuple[ExecutionReference, ...],
shots: int | None = None,
execution: ExecutionSnapshot | None = None,
) -> NoneAttributes¶
execution: ExecutionSnapshot | Noneexecutions: tuple[ExecutionReference, ...]kind: JobKindshots: int | None
Methods¶
from_dict¶
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> JobSnapshotReconstruct a validated snapshot from JSON-compatible data.
Parameters:
| Name | Type | Description |
|---|---|---|
data | Mapping[str, Any] | Mapping produced by :meth:to_dict. |
Returns:
JobSnapshot — Validated typed-job restoration snapshot.
Raises:
KeyError— If operation kind, references, or a version 2 tree is absent.TypeError— If metadata, references, or local values have wrong types.ValueError— If a version, field, tree, or reference is invalid.
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:
TypeError— If local values were mutated to unsupported types.ValueError— If local values or references were mutated to invalid data.
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¶
CANCELLEDCANCELLINGCOMPLETEDFAILEDPARTIALPENDINGQUEUEDRUNNINGUNKNOWN
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,
) -> NoneInitialize run job.
Parameters:
| Name | Type | Description |
|---|---|---|
raw_counts | dict[str, int] | ExecutionHandle[dict[str, int]] | None | Counts or deferred counts. May be None with value_handle. |
result_converter | Callable[[str], T] | None | Function converting one bitstring. May be None with value_handle. |
value_handle | ExecutionHandle[T] | None | Handle already producing the final public value. Defaults to None. |
Raises:
ValueError— If neither a valid counts source norvalue_handleis supplied.
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:
| Name | Type | Description |
|---|---|---|
handle | ExecutionHandle[T] | Final-value execution handle. |
Returns:
RunJob[T] — RunJob[T]: Public run job delegating to handle.
result¶
def result(self, timeout: float | None = None) -> TWait for and return the single public result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
T — Public kernel return value.
result_async¶
def result_async(self, timeout: float | None = None) -> TWait asynchronously for the single public result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum 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,
) -> NoneInitialize sample job.
Parameters:
| Name | Type | Description |
|---|---|---|
raw_counts | dict[str, int] | ExecutionHandle[dict[str, int]] | Counts or a deferred counts execution. |
result_converter | Callable[[dict[str, int]], list[tuple[T, int]]] | Function converting raw counts to typed values. |
shots | int | Number of requested shots. |
Methods¶
result¶
def result(self, timeout: float | None = None) -> SampleResult[T]Wait for and return the typed sample result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum 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:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum 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) -> NoneAttributes¶
results: list[tuple[T, int]] List of (value, count) tuples.shots: int Total number of shots executed.
Methods¶
most_common¶
def most_common(self, n: int = 1) -> list[tuple[T, int]]Return the n most common results.
Parameters:
| Name | Type | Description |
|---|---|---|
n | int | Number 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¶
| Function | Description |
|---|---|
dict_param_key | Format the engine-parameter name for one entry of a Dict parameter. |
is_decomposable_dict_binding_key | Report whether a normalized key can name an emitted parameter. |
normalize_dict_binding_key | Normalize a user-supplied dict key for parameter-name formatting. |
Functions¶
dict_param_key [source]¶
def dict_param_key(dict_name: str, key: Any) -> strFormat 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:
| Name | Type | Description |
|---|---|---|
dict_name | str | The kernel argument name of the Dict parameter. |
key | Any | The 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) -> boolReport 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:
| Name | Type | Description |
|---|---|---|
key | Any | A 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) -> AnyNormalize 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:
| Name | Type | Description |
|---|---|---|
key | Any | A key of the user-supplied binding dict. |
Returns:
typing.Any — int, tuple of normalized components, or the original
key when it has no exact integer representation.
qamomile.circuit.transpiler.parameter_binding¶
Define and validate the runtime parameter ABI for quantum segments.
Overview¶
| Function | Description |
|---|---|
dict_param_key | Format the engine-parameter name for one entry of a Dict parameter. |
flatten_user_bindings | Flatten public arrays and dictionaries into scalar ABI keys. |
is_decomposable_dict_binding_key | Report whether a normalized key can name an emitted parameter. |
normalize_dict_binding_key | Normalize a user-supplied dict key for parameter-name formatting. |
split_parameter_key | Split an emitted scalar key into its root name and array indices. |
| Class | Description |
|---|---|
ParameterArrayInfo | Describe the shape constraints known for one runtime array. |
ParameterContainerKind | Classify the public container that owns one engine scalar slot. |
ParameterInfo | Describe one scalar slot in a compiled engine parameter ABI. |
ParameterMetadata | Describe every scalar slot and runtime array in a compiled segment. |
Functions¶
dict_param_key [source]¶
def dict_param_key(dict_name: str, key: Any) -> strFormat 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:
| Name | Type | Description |
|---|---|---|
dict_name | str | The kernel argument name of the Dict parameter. |
key | Any | The 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:
| Name | Type | Description |
|---|---|---|
bindings | Mapping[str, Any] | None | Raw 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) -> boolReport 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:
| Name | Type | Description |
|---|---|---|
key | Any | A 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) -> AnyNormalize 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:
| Name | Type | Description |
|---|---|---|
key | Any | A key of the user-supplied binding dict. |
Returns:
typing.Any — int, tuple of normalized components, or the original
key when it has no exact integer representation.
split_parameter_key [source]¶
def split_parameter_key(name: str) -> tuple[str, tuple[int, ...] | None]Split an emitted scalar key into its root name and array indices.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Engine 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 ParameterArrayInfoDescribe 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:
| Name | Type | Description |
|---|---|---|
name | str | Root runtime parameter name. |
rank | int | Number of array dimensions. |
expected_shape | tuple[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, ...]) -> NoneAttributes¶
expected_shape: tuple[int | None, ...]name: strrank: int
ParameterContainerKind [source]¶
class ParameterContainerKind(enum.StrEnum)Classify the public container that owns one engine scalar slot.
Attributes¶
ARRAYDICTSCALAR
ParameterInfo [source]¶
class ParameterInfoDescribe one scalar slot in a compiled engine parameter ABI.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Full scalar key, for example gammas[0]. |
array_name | str | Root parameter name, for example gammas. |
index | int | None | Backward-compatible one-dimensional index, or None for scalars and higher-rank elements. |
engine_param | Any | Engine-specific parameter object. |
source_ref | str | None | IR value UUID providing the runtime value. Defaults to None. |
indices | tuple[int, ...] | None | Complete array index tuple, or None for a scalar. Defaults to None. |
container_kind | ParameterContainerKind | Public 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,
) -> NoneAttributes¶
array_name: strcontainer_kind: ParameterContainerKindengine_param: Anyindex: int | Noneindices: tuple[int, ...] | Nonename: strsource_ref: str | None
ParameterMetadata [source]¶
class ParameterMetadataDescribe every scalar slot and runtime array in a compiled segment.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | list[ParameterInfo] | Ordered scalar engine slots. Defaults to an empty list. |
arrays | dict[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(),
) -> NoneAttributes¶
arrays: dict[str, ParameterArrayInfo]parameters: list[ParameterInfo]
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 | NoneFind one scalar slot by its full emitted key.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Full engine parameter key. |
Returns:
ParameterInfo | None — ParameterInfo | None: Matching slot, or None when absent.
merge¶
@classmethod
def merge(cls, metadata: Sequence[ParameterMetadata]) -> ParameterMetadataMerge parameter manifests from multiple quantum segments.
Parameters:
| Name | Type | Description |
|---|---|---|
metadata | Sequence[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:
| Name | Type | Description |
|---|---|---|
bindings | Mapping[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) -> NoneValidate user array rank and every concrete ABI dimension.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | Mapping[str, Any] | None | Raw public bindings before scalar flattening. None means no validation is needed. |
Raises:
ValueError— If a supplied array has the wrong rank or exceeds a dimension whose ABI extent is known exactly.
validate_required_bindings¶
def validate_required_bindings(self, indexed_bindings: Mapping[str, Any]) -> NoneReject missing scalar slots in an indexed binding map.
Parameters:
| Name | Type | Description |
|---|---|---|
indexed_bindings | Mapping[str, Any] | Flattened user bindings. |
Raises:
ValueError— If one or more emitted scalar slots are missing.
qamomile.circuit.transpiler.passes¶
Base classes for compiler passes.
Overview¶
| Class | Description |
|---|---|
AffineTypeError | Base class for affine type violations. |
AffineValidationPass | Validate affine type semantics at IR level. |
ArrayBoundsValidationPass | Reject reachable element accesses and views outside array bounds. |
CompileTimeIfLoweringPass | Lowers compile-time resolvable IfOperations before separation. |
ConstantFoldingPass | Evaluates constant expressions at compile time. |
ControlFlowVisitor | Base class for visiting operations with control flow handling. |
DependencyError | Error when quantum operation depends on non-parameter classical value. |
OperationCollector | Collects operations matching a predicate. |
OperationTransformer | Base class for transforming operations with control flow handling. |
Pass | Base class for all compiler passes. |
QamomileCompileError | Base class for all Qamomile compilation errors. |
RegionCapturePass | Populate explicit captures for every structured control-flow region. |
RegionValidationPass | Verify dominance and signatures for every explicit semantic region. |
SliceBorrowCheckPass | Post-fold linearity checker for sliced views and borrow state. |
ValidateWhileContractPass | Validates that all WhileOperation conditions are measurement-backed. |
ValidationError | Error during validation (e.g., non-classical I/O). |
ValueCollector | Collects 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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable affine-type failure. |
handle_name | str | None | Consumed or borrowed handle. Defaults to None. |
operation_name | str | None | Operation reporting the violation. Defaults to None. |
first_use_location | str | None | Original consuming use location. Defaults to None. |
Attributes¶
first_use_locationhandle_nameoperation_name
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¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockValidate affine type semantics in the block.
Raises:
ValidationError— If the block kind is not AFFINE.AffineTypeError— If a quantum value is consumed multiple times.
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¶
name: str Return the stable pass identifier.
Methods¶
run¶
def run(self, input: Block) -> BlockValidate reachable array element operands in one semantic block.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Post-partial-evaluation affine or hierarchical block whose concrete array extents should be checked. |
Returns:
Block — input unchanged when every reachable access and view is
valid or still symbolic.
Raises:
ValidationError— Ifinputhas an unsupported block kind, a reachable constant index is outside a resolved array extent, or a concrete view descriptor exceeds its physical root.
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:
Evaluates conditions including expression-derived ones (
CompOp,CondOp,NotOp,BinOp, andUnaryMathOpchains).Replaces resolved
IfOperations with selected-branch operations.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:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Compile-time bindings visible in the current block. Defaults to no bindings. |
preserved_condition_uuids | AbstractSet[str] | None | Conditions that must remain unresolved so a later validation pass can inspect their dataflow. Defaults to an empty set. |
_under_controlled_unitary | bool | Internal 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_ids | frozenset[int] | None | Internal recursion-path guard for operation-owned blocks. Defaults to an empty set. |
Attributes¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockLower every compile-time resolvable IfOperation in the block.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Block 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:
ValidationError— Ifinput.kindisANALYZED(the pass must run before dependency analysis commits to a representation), or if a compile-time branch selects a symbolic-bound slice-view cast source whose root index space is not resolvable.
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 splitConstructor¶
def __init__(self, bindings: dict[str, Any] | None = None, *, strip_slice_ops: bool = True)Create a constant-folding pass.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Compile-time parameter bindings used when folding BinOps that reference declared parameters. |
strip_slice_ops | bool | When 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¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockFold resolvable classical values throughout a block.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Affine or hierarchical block to rewrite. |
Returns:
Block — Copy with folded operations and output values.
Raises:
ValidationError— If the block is neither affine nor hierarchical.
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 += 1Methods¶
visit_operation¶
def visit_operation(self, op: Operation) -> NoneProcess a single operation. Override in subclasses.
visit_operations¶
def visit_operations(self, operations: list[Operation]) -> NoneVisit 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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable dependency failure. |
quantum_op | str | None | Dependent quantum operation. Defaults to None. |
classical_value | str | None | Unsupported classical dependency. Defaults to None. |
Attributes¶
classical_valuequantum_op
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.collectedConstructor¶
def __init__(self, predicate: Callable[[Operation], bool])Attributes¶
collected: list[Operation]
Methods¶
visit_operation¶
def visit_operation(self, op: Operation) -> NoneOperationTransformer [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 | NoneTransform 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¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute 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) -> NoneInitialize an empty reachable-block visitation set.
Attributes¶
name: str Return the compiler-visible pass name.
Methods¶
run¶
def run(self, input: Block) -> BlockPopulate explicit captures throughout one block graph.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Semantic 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) -> NoneInitialize an empty reachable-block visitation set.
Attributes¶
name: str Return the compiler-visible pass name.
Methods¶
run¶
def run(self, input: Block) -> BlockValidate a block graph and return it unchanged.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Semantic entrypoint whose regions should be verified. |
Returns:
Block — The validated input block.
Raises:
ValidationError— If a region has an undeclared capture, violates dominance, or has an inconsistent block/yield signature.
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) -> NoneInitialize per-run mutable state to safe defaults.
Attributes¶
name: str Return the pass identifier for tracing/logging.
Methods¶
run¶
def run(self, input: Block) -> BlockRun the borrow tracker over input.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Block 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:
ValidationError— If called on an unexpected block kind or slice ownership cannot be propagated safely across a control-flow boundary.QubitBorrowConflictError— If a slice view and a direct access collide or two live views may overlap.QubitConsumedError— If an operand accesses a destroyed slot or a stale slice version attempts to replace its live successor.
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:
A
ValuewithBitTypeMeasurement-backed: produced by
MeasureOperationdirectly, or anIfOperationmerge 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¶
name: str
Methods¶
run¶
def run(self, block: Block) -> BlockValidate 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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable validation failure. |
value_name | str | None | Related IR value name. Defaults to None. |
Attributes¶
value_name
ValueCollector [source]¶
class ValueCollector(ControlFlowVisitor)Collects Value UUIDs from operation operands and results.
Constructor¶
def __init__(self)Attributes¶
operand_uuids: set[str]result_uuids: set[str]
Methods¶
visit_operation¶
def visit_operation(self, op: Operation) -> NoneRecord one operation’s input and result Value UUIDs.
Parameters:
| Name | Type | Description |
|---|---|---|
op | Operation | The 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¶
| Class | Description |
|---|---|
AffineTypeError | Base class for affine type violations. |
AffineValidationPass | Validate affine type semantics at IR level. |
Block | Unified block representation for all pipeline stages. |
BlockKind | Classification of block structure for pipeline stages. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
IfOperation | Represents an if-else conditional operation. |
Pass | Base class for all compiler passes. |
ValidationError | Error during validation (e.g., non-classical I/O). |
Value | A 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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable affine-type failure. |
handle_name | str | None | Consumed or borrowed handle. Defaults to None. |
operation_name | str | None | Operation reporting the violation. Defaults to None. |
first_use_location | str | None | Original consuming use location. Defaults to None. |
Attributes¶
first_use_locationhandle_nameoperation_name
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¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockValidate affine type semantics in the block.
Raises:
ValidationError— If the block kind is not AFFINE.AffineTypeError— If a quantum value is consumed multiple times.
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
HasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[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¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute 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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable validation failure. |
value_name | str | None | Related IR value name. Defaults to None. |
Attributes¶
value_name
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of 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¶
| Function | Description |
|---|---|
array_static_length | Resolve a one-dimensional array’s compile-time length. |
arrays_share_physical_region | Return whether two arrays denote the same ordered physical region. |
build_dependency_graph | Build result-to-input dependency edges for semantic operations. |
build_producer_map | Walk operations recursively, mapping result UUIDs to producer instances. |
coerce_nonnegative_integral | Normalize a real scalar with an integer value to a nonnegative integer. |
collect_value_like_uuids | Collect UUIDs contained in a value-like IR object. |
evaluate_classical_op_concrete | Try to evaluate a classical op and record its concrete result. |
find_loop_carried_condition_reads | Find legacy loop rebinds whose entry value controls a nested branch. |
find_measurement_derived_values | Propagate measurement provenance forward through a dependency graph. |
find_measurement_results | Return UUIDs directly produced from quantum measurement. |
flatten_ops | Flatten operations recursively through nested control flow. |
genuine_input_values | Return an operation’s input values that count as genuine reads. |
prune_compile_time_ifs | Replace compile-time-decidable IfOperations by their taken branch. |
reject_control_flow_quantum_discard | Reject control-flow-internal quantum rebinds that discard state. |
reject_loop_carried_classical_rebinds | Reject in-loop classical scalar rebinds that cannot compile correctly. |
reject_self_referential_loop_stores | Reject in-loop classical element stores that read the same array. |
resolve_compile_time_condition | Resolve an IfOperation condition to a compile-time bool. |
resolve_root_qubit_address | Resolve an array-element value to its root (array_uuid, index). |
same_exact_typed_constant | Return whether two scalar Values carry the same exact typed constant. |
| Class | Description |
|---|---|
AnalyzePass | Analyze and validate an affine block. |
ArrayValue | An array of typed IR values. |
BinOp | Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN). |
BinOpKind | |
BitType | Type representing a classical bit. |
Block | Unified block representation for all pipeline stages. |
BlockKind | Classification of block structure for pipeline stages. |
BranchRebind | Trace-time record of a quantum variable rebound inside an if branch. |
ControlFlowVisitor | Base class for visiting operations with control flow handling. |
DependencyError | Error when quantum operation depends on non-parameter classical value. |
FloatType | Type representing a floating-point number. |
ForItemsOperation | Represents iteration over dict/iterable items. |
ForOperation | Represents a for loop operation. |
GateOperation | Quantum gate operation. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
IfOperation | Represents an if-else conditional operation. |
LoopCarriedRebind | Trace-time record of a variable rebound inside a loop body. |
MeasureOperation | |
MeasureVectorOperation | Measure a vector of qubits. |
OperationKind | Classification of operations for classical/quantum separation. |
Pass | Base class for all compiler passes. |
PauliEvolveOp | Pauli evolution operation: exp(-i * gamma * H). |
ProjectOperation | Project a qubit in one Pauli basis and keep the projected state. |
PrunedIfView | Pruned view of an operation list plus its dead-branch merge aliases. |
QInitOperation | Initialize the qubit |
QubitRebindError | Quantum variable reassigned from a different quantum source. |
StoreArrayElementOperation | Store a classical scalar into one element of a classical array. |
UIntType | Type representing an unsigned integer. |
ValidationError | Error during validation (e.g., non-classical I/O). |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
WhileOperation | Represents a while loop operation. |
Constants¶
ValueLike:TypeAlias='Value | ArrayValue | TupleValue | DictValue'
Functions¶
array_static_length [source]¶
def array_static_length(array: 'ArrayValue') -> int | NoneResolve a one-dimensional array’s compile-time length.
Parameters:
| Name | Type | Description |
|---|---|---|
array | ArrayValue | Array 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') -> boolReturn whether two arrays denote the same ordered physical region.
Parameters:
| Name | Type | Description |
|---|---|---|
left | ArrayValue | First root array or sliced view. |
right | ArrayValue | Second root array or sliced view. |
Returns:
bool — True for the same SSA value/version lineage, when both arrays
resolve to the same root logical identity and ordered root indices,
or when both resolve to empty regions (whose root is unobservable).
Returns False for non-empty divergent regions and unresolved
symbolic coverage.
build_dependency_graph [source]¶
def build_dependency_graph(operations: Sequence[Operation]) -> dict[str, set[str]]Build result-to-input dependency edges for semantic operations.
The graph includes nested control flow, branch merges, loop-carried region arguments, array-element ancestry, and slice ancestry. These are the shared semantics used by measurement provenance, kernel effects, and the compiler’s classical lowering passes.
Parameters:
| Name | Type | Description |
|---|---|---|
operations | Sequence[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]) -> NoneWalk 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:
| Name | Type | Description |
|---|---|---|
operations | list[Operation] | Operations to walk, recursing into all HasNestedOps bodies. IfOperation merge outputs are on results, so they map to the IfOperation itself. |
producer_map | dict[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) -> intNormalize a real scalar with an integer value to a nonnegative integer.
Parameters:
| Name | Type | Description |
|---|---|---|
value | object | Candidate Python, NumPy, or SymPy real scalar. |
label | str | User-facing field label used in diagnostics. |
Returns:
int — Equivalent nonnegative Python integer.
Raises:
TypeError— Ifvalueis Boolean, is not a real scalar, is not finite, or does not have an integer value.ValueError— If the normalized integer is negative.
collect_value_like_uuids [source]¶
def collect_value_like_uuids(value: 'ValueLike') -> set[str]Collect UUIDs contained in a value-like IR object.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ValueLike | Value-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],
) -> NoneTry to evaluate a classical op and record its concrete result.
Supported operation types:
CompOp— comparison (==, !=, <, <=, >, >=)CondOp— logical connective (and, or)NotOp— logical negationBinOp— arithmetic (+, -, *, /, //, %)UnaryMathOp— unary mathematical functions such asceilandlog2
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:
| Name | Type | Description |
|---|---|---|
op | Operation | The operation to evaluate. |
concrete_values | dict[str, Any] | UUID-keyed map of concrete results; the op’s result is recorded here on success. Updated in place. |
bindings | dict[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:
| Name | Type | Description |
|---|---|---|
loop_operation | ForOperation | ForItemsOperation | WhileOperation | Loop whose legacy rebind records are inspected. |
condition_values | Sequence[ValueBase] | None | Optional branch conditions from a reachability-aware caller. When omitted, every nested IfOperation condition in the loop body is considered. |
selected_aliases | Mapping[str, str] | None | Optional 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:
| Name | Type | Description |
|---|---|---|
dependency_graph | dict[str, set[str]] | Result UUIDs mapped to their dependency UUIDs. |
measurement_uuids | set[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:
| Name | Type | Description |
|---|---|---|
operations | Sequence[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:
| Name | Type | Description |
|---|---|---|
ops | list[Operation] | Operations to flatten. |
into_if_branches | bool | When 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:
| Name | Type | Description |
|---|---|---|
op | Operation | Operation 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,
) -> PrunedIfViewReplace 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:
| Name | Type | Description |
|---|---|---|
ops | list[Operation] | Operations to prune, in program order. |
concrete_values | dict[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). |
bindings | dict[str, Any] | Compile-time parameter bindings used to resolve conditions. |
walk_runtime_branches | bool | When 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) -> NoneReject 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:
consuming the original inside the branch before rebinding (
if cond: qmc.measure(q); q = qmc.qubit(...)). Scalar consumption is judged at the wire’s final in-branch version (:func:_wire_terminally_consumed), so gating the original and then dropping the gated state (if cond: q = qmc.x(q); q = qmc.qubit("fresh")) is a discard, not a consumption; whole-register rebinds keep the coarser any-touch granularity, where element or view reads count;ordinary quantum rebinds through gates (
q = qmc.h(q)) — the pre-branch value is carried out through the merge;rebinds whose pre-branch value is still owned outside the if (a value consumed before the if, or an alias referenced after it);
handle exchanges where every pre-branch value is carried by some merge of the same side (
q1, q2 = q2, q1).
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:
| Name | Type | Description |
|---|---|---|
operations | list[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. |
bindings | dict[str, Any] | None | Compile-time parameter bindings used to resolve IfOperation conditions, matching what CompileTimeIfLoweringPass will later resolve. Defaults to None (no bindings). |
Raises:
QubitRebindError— If a runtime if branch rebinds a quantum variable whose pre-branch value has no consumer in that branch, no merge carrying it out of that side, and no reference outside the if — or a loop body rebinds a quantum variable whose incoming value it never consumes and whose pre-loop value has no owner outside the loop.
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,
) -> NoneReject 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:
| Name | Type | Description |
|---|---|---|
operations | list[Operation] | Operations to scan. Recurses through all control flow. |
bindings | dict[str, Any] | None | Compile-time parameter bindings used to resolve IfOperation conditions, matching what CompileTimeIfLoweringPass will later resolve. Defaults to None (no bindings). |
output_values | list[ValueLike] | None | The 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:
ValidationError— If a loop body rebinds a classical scalar whose pre-loop value the body still reads (directly, through classical arithmetic, through a surviving merge, or as an embedded constant from a plain-Python initialization), or if a while condition’s pre-loop value is read after the loop.
reject_self_referential_loop_stores [source]¶
def reject_self_referential_loop_stores(operations: list[Operation], bindings: dict[str, Any] | None = None) -> NoneReject 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:
| Name | Type | Description |
|---|---|---|
operations | list[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). |
bindings | dict[str, Any] | None | Compile-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:
ValidationError— If a store inside a loop transitively reads an element of the same logical array it writes.
resolve_compile_time_condition [source]¶
def resolve_compile_time_condition(
condition: Any,
concrete_values: dict[str, Any],
bindings: dict[str, Any],
) -> bool | NoneResolve 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:
| Name | Type | Description |
|---|---|---|
condition | Any | The condition operand. May be a plain Python value or a Value. |
concrete_values | dict[str, Any] | UUID-keyed map of concrete classical-op results accumulated in program order. |
bindings | dict[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] | NoneResolve 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:
| Name | Type | Description |
|---|---|---|
value | Value | The 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) -> boolReturn 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:
| Name | Type | Description |
|---|---|---|
left | Value | First scalar value to compare. |
right | Value | Second scalar value to compare. |
Returns:
bool — True only for constants of the same IR type and Python type
with equal value representations.
Classes¶
AnalyzePass [source]¶
class AnalyzePass(Pass[Block, Block])Analyze and validate an affine block.
This pass:
Builds a dependency graph between values (used locally for validation)
Validates that quantum ops don’t depend on non-parameter classical results
Checks that block inputs/outputs are classical
Input: Block with BlockKind.AFFINE Output: Block with BlockKind.ANALYZED
Attributes¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockAnalyze 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,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]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,
) -> NoneAttributes¶
kind: BinOpKind | Noneoperation_kind: OperationKindsignature: Signature
BinOpKind [source]¶
class BinOpKind(enum.Enum)Attributes¶
ADDDIVFLOORDIVMINMODMULPOWSUB
BitType [source]¶
class BitType(ClassicalTypeMixin, ValueType)Type representing a classical bit.
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
BranchRebind [source]¶
class BranchRebindTrace-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,
) -> NoneAttributes¶
before: Valuerebound_in_false: boolrebound_in_true: boolvar_name: str
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 += 1Methods¶
visit_operation¶
def visit_operation(self, op: Operation) -> NoneProcess a single operation. Override in subclasses.
visit_operations¶
def visit_operations(self, operations: list[Operation]) -> NoneVisit 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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable dependency failure. |
quantum_op | str | None | Dependent quantum operation. Defaults to None. |
classical_value | str | None | Unsupported classical dependency. Defaults to None. |
Attributes¶
classical_valuequantum_op
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):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]key_is_vector: boolkey_var_values: tuple[Value, ...] | Nonekey_vars: list[str]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]operation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signaturevalue_var: strvalue_var_value: Value | None
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the items-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt items-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationGateOperation [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,
) -> NoneAttributes¶
gate_type: GateOperationType | Noneoperation_kind: OperationKindqubit_operands: list[Value] Qubit operands (excluding the theta parameter if present).signature: Signaturetheta: Value | None Angle parameter for rotation gates, orNonefor fixed gates.
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 HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
LoopCarriedRebind [source]¶
class LoopCarriedRebindTrace-time record of a variable rebound inside a loop body.
Two rebind families share this record type, distinguished by the
type of before:
Classical scalar (
beforeclassical): the frontend traces a loop body exactly once, so a Python-level reassignment liketotal = total + iproduces IR whose right-hand side reads the fixed pre-loop value instead of the previous iteration’s value. Most such carries are now represented as explicitRegionArgs (see above) and are fully supported; a classical record is only created for the shapes region binding declines —while-body carries (a runtime while loop cannot be unrolled) and measurement-backedBitcarries — and the transpiler’s classical loop-carried check rejects those with a targeted error instead of silently miscompiling.Quantum (
beforequantum): the loop body left the variable bound to a different quantum resource (logical_idchange — a fresh allocation or another register, not a gate self-update). The transpiler’s control-flow discard check (reject_control_flow_quantum_discard) rejects the ones whose incoming state the body never consumes.
Constructor¶
def __init__(
self,
var_name: str,
before: ValueBase,
after: ValueBase,
before_synthesized: bool = False,
) -> NoneAttributes¶
after: ValueBasebefore: ValueBasebefore_synthesized: boolvar_name: str
MeasureOperation [source]¶
class MeasureOperation(Operation)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
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()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
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¶
CLASSICALCONTROLHYBRIDQUANTUM
Pass [source]¶
class Pass(ABC, Generic[InputT, OutputT])Base class for all compiler passes.
Attributes¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute 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()) -> NoneAttributes¶
evolved_qubits: Value The evolved quantum register result.gamma: Value The evolution time parameter.observable: Value The Observable parameter operand.operation_kind: OperationKind PauliEvolveOp is QUANTUM - transforms quantum state.qubits: Value The quantum register operand.signature: Signature
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',
) -> NoneAttributes¶
axis: stroperation_kind: OperationKindsignature: Signature
PrunedIfView [source]¶
class PrunedIfViewPruned 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]]],
) -> NoneAttributes¶
merge_aliases: tuple[tuple[Value, Value], ...]operations: list[Operation]
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:
| Name | Type | Description |
|---|---|---|
loop_op | Operation | A 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:
| Name | Type | Description |
|---|---|---|
loop_op | Operation | Loop 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()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
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:
Compile time:
ConstantFoldingPassfolds the store when the source array contents, the index, and the stored value are all compile-time resolvable, attaching the updatedconst_arraymetadata to the result value.Runtime: otherwise the store executes host-side in a classical segment via
ClassicalExecutor(e.g. for measurement-derivedVector[Bit]contents). It must never reach a quantum segment; engine emit rejects it explicitly.
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 bitsConstructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
array: ArrayValue ArrayValue: The array version the store reads from.index_values: tuple[Value, ...] tuple[Value, ...]: The element indices being written.operation_kind: OperationKindsignature: Signature Return the operation’s dynamic array/qubit/index signature.stored_value: Value Value: The scalar being written into the array.
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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable validation failure. |
value_name | str | None | Related IR value name. Defaults to None. |
Attributes¶
value_name
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]max_iterations: int | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the while body and its complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt while operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, rebind-record, and region-arg values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[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¶
| Function | Description |
|---|---|
constant_integer | Return a non-boolean integer constant carried by an IR value. |
genuine_input_values | Return an operation’s input values that count as genuine reads. |
pair_block_operands | Pair all block inputs with category-grouped call-site operands. |
reachable_nested_regions | Return nested regions that may execute for one control-flow operation. |
same_exact_typed_constant | Return whether two scalar Values carry the same exact typed constant. |
static_for_items_entries | Return compile-time entries iterated by a for-items operation. |
static_for_range | Resolve the exact iteration range of a statically bounded loop. |
| Class | Description |
|---|---|
ArrayBoundsValidationPass | Reject reachable element accesses and views outside array bounds. |
ArrayValue | An array of typed IR values. |
BinOp | Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN). |
Block | Unified block representation for all pipeline stages. |
BlockKind | Classification of block structure for pipeline stages. |
CompOp | Comparison operation (EQ, NEQ, LT, LE, GT, GE). |
CondOp | Conditional logical operation (AND, OR). |
ControlledUOperation | Base class for controlled-U operations. |
DictValue | A dictionary value stored as stable ordered entries. |
ForItemsOperation | Represents iteration over dict/iterable items. |
ForOperation | Represents a for loop operation. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
IfOperation | Represents an if-else conditional operation. |
NotOp | |
Pass | Base class for all compiler passes. |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
SliceArrayOperation | Construct a strided view of an ArrayValue. |
TupleValue | A tuple of IR values for structured data. |
UnaryMathOp | Represent one pure unary mathematical expression. |
ValidationError | Error during validation (e.g., non-classical I/O). |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
ValueResolver | Resolve IR Values to concrete Python values. |
Functions¶
constant_integer [source]¶
def constant_integer(value: ValueBase | None) -> int | NoneReturn a non-boolean integer constant carried by an IR value.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ValueBase | None | Candidate 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:
| Name | Type | Description |
|---|---|---|
op | Operation | Operation 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:
| Name | Type | Description |
|---|---|---|
block | Block | Operation-owned block whose inputs are being bound. |
operands | Sequence[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:
| Name | Type | Description |
|---|---|---|
operation | HasNestedOps | Structured-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) -> boolReturn 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:
| Name | Type | Description |
|---|---|---|
left | Value | First scalar value to compare. |
right | Value | Second scalar value to compare. |
Returns:
bool — True only for constants of the same IR type and Python type
with equal value representations.
static_for_items_entries [source]¶
def static_for_items_entries(operation: ForItemsOperation) -> tuple[tuple[Any, Any], ...] | NoneReturn compile-time entries iterated by a for-items operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operation | ForItemsOperation | Items 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 | NoneResolve the exact iteration range of a statically bounded loop.
Parameters:
| Name | Type | Description |
|---|---|---|
operation | ForOperation | Counted 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¶
name: str Return the stable pass identifier.
Methods¶
run¶
def run(self, input: Block) -> BlockValidate reachable array element operands in one semantic block.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Post-partial-evaluation affine or hierarchical block whose concrete array extents should be checked. |
Returns:
Block — input unchanged when every reachable access and view is
valid or still symbolic.
Raises:
ValidationError— Ifinputhas an unsupported block kind, a reachable constant index is outside a resolved array extent, or a concrete view descriptor exceeds its physical root.
ArrayValue [source]¶
class ArrayValue(Value[T])An array of typed IR values.
When slice_of is set, this array is a strided view over another
array. Element accesses on a sliced ArrayValue resolve to
physical slots on the root parent via the affine map
parent_index = slice_start + slice_step * view_local_index,
applied recursively along slice_of chains. The emit-time
resolver walks this chain to produce the final qubit index; passes
that substitute or clone values must treat slice_of /
slice_start / slice_step as Value references that need to
track through the same mapping as parent_array.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
shape: tuple[Value, ...] = tuple(),
slice_of: 'ArrayValue | None' = None,
slice_start: 'Value | None' = None,
slice_step: 'Value | None' = None,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]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,
) -> NoneAttributes¶
kind: BinOpKind | Noneoperation_kind: OperationKindsignature: Signature
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
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,
) -> NoneAttributes¶
kind: CompOpKind | Noneoperation_kind: OperationKindsignature: Signature
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,
) -> NoneAttributes¶
kind: CondOpKind | Noneoperation_kind: OperationKindsignature: Signature
ControlledUOperation [source]¶
class ControlledUOperation(Operation)Base class for controlled-U operations.
Two concrete subclasses handle distinct operand layouts:
ConcreteControlledU: Fixednum_controls: int, individual qubit operands.SymbolicControlledU: Symbolicnum_controls: Value, vector-based control operands; optionalcontrol_indicesselects a subset of the control vector to act as controls (the rest pass through).
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(),
) -> NoneAttributes¶
block: Block | Nonebody_operands: list[Value] Get the wrapped callable’s complete argument list.callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_operands: list[Value] Get the control qubit values.is_symbolic_num_controls: bool Whether num_controls is symbolic (Value) rather than concrete.num_controls: int | Valueoperation_kind: OperationKindparam_operands: list[Value] Get the controlled operation’s classical/object arguments.power: int | Valuesignature: Signaturetarget_operands: list[Value] Get the target qubit values (arguments to U).
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationDictValue [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()))(),
) -> NoneAttributes¶
entries: tuple[tuple[TupleValue | Value, Value], ...]logical_id: strmetadata: ValueMetadataname: strtype: DictTypeuuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> DictValueForItemsOperation [source]¶
class ForItemsOperation(HasNestedOps, Operation)Represents iteration over dict/iterable items.
Example:
for (i, j), Jij in qmc.items(ising):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]key_is_vector: boolkey_var_values: tuple[Value, ...] | Nonekey_vars: list[str]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]operation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signaturevalue_var: strvalue_var_value: Value | None
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the items-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt items-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationHasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[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()) -> NoneAttributes¶
input: Valueoperation_kind: OperationKindoutput: Valuesignature: Signature
Pass [source]¶
class Pass(ABC, Generic[InputT, OutputT])Base class for all compiler passes.
Attributes¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute 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(),
) -> NoneAttributes¶
case_blocks: list[Block]case_callable_attrs: list[dict[str, Any]]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
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]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[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()) -> NoneAttributes¶
operation_kind: OperationKind Slice is classical — it selects indices without quantum action.signature: Signature Return the type signature of this slice operation.
TupleValue [source]¶
class TupleValue(_MetadataValueMixin, ValueBase)A tuple of IR values for structured data.
Constructor¶
def __init__(
self,
name: str,
elements: tuple[ValueLike, ...] = tuple(),
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> NoneAttributes¶
elements: tuple[ValueLike, ...]logical_id: strmetadata: ValueMetadataname: strtype: ‘TupleType’uuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> TupleValueUnaryMathOp [source]¶
class UnaryMathOp(Operation)Represent one pure unary mathematical expression.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[Value] | Single numeric input value. |
results | list[Value] | Single numeric result value. |
kind | UnaryMathOpKind | None | Mathematical operation to apply. |
Raises:
ValueError— Ifkindis missing or the operation does not have exactly one operand and one result.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: UnaryMathOpKind | None = None,
) -> NoneAttributes¶
input: Value Return the input value.kind: UnaryMathOpKind | Noneoperation_kind: OperationKind Classify the operation as classical.output: Value Return the output value.signature: Signature Return the typed unary signature.
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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable validation failure. |
value_name | str | None | Related IR value name. Defaults to None. |
Attributes¶
value_name
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
ValueResolver [source]¶
class ValueResolverResolve IR Values to concrete Python values.
Parameters:
| Name | Type | Description |
|---|---|---|
context | dict[str, Any] | None | UUID-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. |
bindings | dict[str, Any] | None | Name-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:
| Name | Type | Description |
|---|---|---|
context | dict[str, Any] | None | UUID-keyed map of already-resolved values. Defaults to None. |
bindings | dict[str, Any] | None | Name-keyed parameter bindings supplied by the user. Defaults to None. |
Methods¶
resolve¶
def resolve(self, value: Any) -> Any | NoneResolve 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:
| Name | Type | Description |
|---|---|---|
value | Any | The Value-like object or already concrete value to resolve. |
Returns:
Any | None — Any | None: The resolved concrete value, the original
concrete value for non-Value inputs, or None when no
resolution rule applies.
qamomile.circuit.transpiler.passes.circuit_shot_validation¶
Validate shot context in reachable circuit-family bodies.
Overview¶
| Function | Description |
|---|---|
block_parameter_binding_keys | Return the sanctioned emit-binding keys for an inner formal. |
lower_compile_time_ifs_preserving_loop_conditions | Specialize compile-time branches without erasing loop conditions. |
pair_block_parameter_operands | Pair a block’s classical/object inputs with call-site operands. |
reachable_nested_regions | Return nested regions that may execute for one control-flow operation. |
validate_circuit_shot_context | Reject shot context only in reachable circuit-family bodies. |
| Class | Description |
|---|---|
Block | Unified block representation for all pipeline stages. |
ControlledUOperation | Base class for controlled-U operations. |
GetCurrentShotOperation | Read the zero-based index of the current device program repetition. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
InverseBlockOperation | Represent an inverse qkernel/block as a first-class IR operation. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
TargetCapabilityError | A program requires a capability the selected target does not declare. |
ValueBase | Nominal base for every typed IR value. |
ValueResolver | Resolve IR Values to concrete Python values. |
Functions¶
block_parameter_binding_keys [source]¶
def block_parameter_binding_keys(parameter: ValueBase) -> tuple[str, ...]Return the sanctioned emit-binding keys for an inner formal.
Emit resolution accepts a kernel parameter name before its UUID for public API compatibility, so an operation-owned fresh scope must write both keys. Keeping the key choice here prevents individual emit paths from reviving a parent binding that merely shares the inner formal’s display name.
Parameters:
| Name | Type | Description |
|---|---|---|
parameter | ValueBase | Classical/object formal input being bound. |
Returns:
tuple[str, ...] — tuple[str, ...]: UUID followed by the formal parameter provenance name
and nonempty display-name compatibility key, without duplicates.
lower_compile_time_ifs_preserving_loop_conditions [source]¶
def lower_compile_time_ifs_preserving_loop_conditions(block: Block, bindings: dict[str, Any] | None = None) -> BlockSpecialize compile-time branches without erasing loop conditions.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Block whose resolvable compile-time branches should be lowered. |
bindings | dict[str, Any] | None | Compile-time input bindings used for condition resolution. Defaults to None. |
Returns:
Block — Specialized block with loop-carried conditions preserved.
Raises:
ValidationError— If specialization encounters invalid IR.
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:
| Name | Type | Description |
|---|---|---|
block | Block | Operation-owned block whose formal inputs define the declaration order. |
param_operands | Sequence[ValueBase] | Classical or object operands at the call site, already ordered according to the operation signature. |
Returns:
list[tuple[ValueBase, ValueBase]] — list[tuple[ValueBase, ValueBase]]: (formal, actual) pairs in
list[tuple[ValueBase, ValueBase]] — declaration order. Missing actual operands leave trailing formals
list[tuple[ValueBase, ValueBase]] — unpaired, so they can remain symbolic and be provided at emit time.
reachable_nested_regions [source]¶
def reachable_nested_regions(operation: HasNestedOps) -> tuple[Region, ...]Return nested regions that may execute for one control-flow operation.
Constant conditionals expose only their selected branch. Statically empty counted and items loops expose no body region. All unresolved control flow remains conservative and exposes every region.
Parameters:
| Name | Type | Description |
|---|---|---|
operation | HasNestedOps | Structured-control operation to inspect. |
Returns:
tuple[Region, ...] — tuple[Region, ...]: Regions that are reachable under compile-time-known
control decisions.
validate_circuit_shot_context [source]¶
def validate_circuit_shot_context(block: Block, bindings: dict[str, Any] | None, *, target: str) -> NoneReject shot context only in reachable circuit-family bodies.
Circuit lowering selects engine-generic callable decompositions using
the circuit_ir selector. Backend-specific alternatives are metadata
for other consumers and must not impose their capabilities here.
Specialize operation-owned bodies in their own parameter scope before
inspecting them, just as the entrypoint is inspected after pruning.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Partially evaluated circuit entrypoint. |
bindings | dict[str, Any] | None | Compile-time entrypoint bindings. |
target | str | Target name used in capability errors. |
Raises:
TargetCapabilityError— If a reachable selected body reads the shot.ValidationError— If nested compile-time specialization is invalid.ValueError— If a selected callable body violates its call contract.
Classes¶
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
ControlledUOperation [source]¶
class ControlledUOperation(Operation)Base class for controlled-U operations.
Two concrete subclasses handle distinct operand layouts:
ConcreteControlledU: Fixednum_controls: int, individual qubit operands.SymbolicControlledU: Symbolicnum_controls: Value, vector-based control operands; optionalcontrol_indicesselects a subset of the control vector to act as controls (the rest pass through).
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(),
) -> NoneAttributes¶
block: Block | Nonebody_operands: list[Value] Get the wrapped callable’s complete argument list.callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_operands: list[Value] Get the control qubit values.is_symbolic_num_controls: bool Whether num_controls is symbolic (Value) rather than concrete.num_controls: int | Valueoperation_kind: OperationKindparam_operands: list[Value] Get the controlled operation’s classical/object arguments.power: int | Valuesignature: Signaturetarget_operands: list[Value] Get the target qubit values (arguments to U).
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationGetCurrentShotOperation [source]¶
class GetCurrentShotOperation(Operation)Read the zero-based index of the current device program repetition.
The value is stable throughout one repetition and is supplied by the execution target, never by compile-time bindings or a host-side counter.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[Value] | Empty operand list. |
results | list[Value] | One nonconstant UInt result. |
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKind Keep this context read inside the device execution.signature: Signature Return the execution-context reader’s signature.
HasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
InverseBlockOperation [source]¶
class InverseBlockOperation(Operation)Represent an inverse qkernel/block as a first-class IR operation.
The operation stores both the original forward block and a Qamomile-built
inverse implementation block. Emitters may use source_block with a
engine-native inverse/adjoint primitive, then fall back to
implementation_block when native inversion is unavailable.
Operands are ordered as scalar control qubits, target quantum operands,
then classical/object parameters. Results mirror the quantum operand
layout: control results first, then one target result per target operand.
Vector target operands therefore count as one operand/result while
contributing their scalar width to num_target_qubits.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_control_qubits: int = 0,
num_target_qubits: int = 0,
custom_name: str = '',
source_block: Block | None = None,
implementation_block: Block | None = None,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_qubits: list[‘Value’] Return control quantum operands.control_value: int | Nonecustom_name: strimplementation_block: Block | Nonename: str Return a human-readable inverse operation name.num_control_qubits: intnum_target_qubits: intoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return classical/object parameter operands.signature: Signature Return the operation signature.source_block: Block | Nonetarget_qubits: list[‘Value’] Return target quantum operands.
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[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. |
definition | CallableDef | None | Optional 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,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueor an Oracle control-partition field has an invalid Python type.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width, or if Oracle invocation and definition control metadata disagree.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of relevant callable implementations.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return a conservative union of measurement-derived results.name: str Return the display name for this invocation.num_added_control_qubits: int Return controls introduced by a frontend control transform.num_body_external_control_qubits: int Return control operands generic lowering adds outside a base body.num_control_qubits: int Return the number of leading control-qubit operands.num_declared_control_qubits: int Return controls included in an opaque Oracle’s base definition.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
effective_body¶
def effective_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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 | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None, which only selects engine-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
require_body | bool | Whether 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name used for implementation selection. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
select_body¶
def select_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> CallableBodySelectionSelect 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
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(),
) -> NoneAttributes¶
case_blocks: list[Block]case_callable_attrs: list[dict[str, Any]]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
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]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed replacement values. |
Returns:
Operation — Rebuilt SELECT operation with matching values replaced.
TargetCapabilityError [source]¶
class TargetCapabilityError(EmitError)A program requires a capability the selected target does not declare.
Raised by circuit-IR target-legality verification before any engine materialization starts. The message always names the target and the missing capability axis, so the failure reads as a target restriction rather than a Qamomile language error.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable diagnosis naming the target and the missing capability. |
target | str | None | Declared target name. Defaults to None. |
operation | str | None | Instruction 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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable diagnosis naming the target and the missing capability. |
target | str | None | Declared target name. Defaults to None. |
operation | str | None | Instruction description that triggered the failure. Defaults to None. |
Attributes¶
target: str | None
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
ValueResolver [source]¶
class ValueResolverResolve IR Values to concrete Python values.
Parameters:
| Name | Type | Description |
|---|---|---|
context | dict[str, Any] | None | UUID-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. |
bindings | dict[str, Any] | None | Name-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:
| Name | Type | Description |
|---|---|---|
context | dict[str, Any] | None | UUID-keyed map of already-resolved values. Defaults to None. |
bindings | dict[str, Any] | None | Name-keyed parameter bindings supplied by the user. Defaults to None. |
Methods¶
resolve¶
def resolve(self, value: Any) -> Any | NoneResolve 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:
| Name | Type | Description |
|---|---|---|
value | Any | The 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
_build_runtime_predicate_expr. This put engine-specific lowering logic inside the emit pass and used thebindingsdict as a polymorphic slot holding either Python scalars (fold result) or engineExprobjects.
By identifying runtime classical ops at IR level and giving them their own node type, we:
Make “runtime evaluation required” structurally explicit in the IR.
Move engine lowering to a dedicated emit hook (
_emit_runtime_classical_expr).Preserve the existing fold path for ops that can fold at compile or emit time (loop-bound or parameter-bound) — those are not measurement- derived and stay as
CompOp/CondOp/NotOp/BinOp.
Overview¶
| Function | Description |
|---|---|
collect_value_like_uuids | Collect UUIDs contained in a value-like IR object. |
runtime_kind_from_binop | Map a BinOpKind to its RuntimeOpKind counterpart. |
runtime_kind_from_compop | Map a CompOpKind to its RuntimeOpKind counterpart. |
runtime_kind_from_condop | Map a CondOpKind to its RuntimeOpKind counterpart. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
BinOp | Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN). |
BinOpKind | |
BitType | Type representing a classical bit. |
Block | Unified block representation for all pipeline stages. |
BlockKind | Classification of block structure for pipeline stages. |
ClassicalLoweringPass | Lower measurement-derived classical ops to RuntimeClassicalExpr. |
CompOp | Comparison operation (EQ, NEQ, LT, LE, GT, GE). |
CondOp | Conditional logical operation (AND, OR). |
ForItemsOperation | Represents iteration over dict/iterable items. |
ForOperation | Represents a for loop operation. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
IfMerge | One branch-merge slot of an :class:IfOperation. |
IfOperation | Represents an if-else conditional operation. |
MeasureOperation | |
NotOp | |
OperationKind | Classification of operations for classical/quantum separation. |
Pass | Base class for all compiler passes. |
RuntimeClassicalExpr | A classical expression known to require runtime evaluation. |
RuntimeOpKind | Unified kind for RuntimeClassicalExpr covering all classical |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
WhileOperation | Represents a while loop operation. |
Constants¶
ValueLike:TypeAlias='Value | ArrayValue | TupleValue | DictValue'
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:
| Name | Type | Description |
|---|---|---|
value | ValueLike | Value-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) -> RuntimeOpKindMap a BinOpKind to its RuntimeOpKind counterpart.
runtime_kind_from_compop [source]¶
def runtime_kind_from_compop(kind: CompOpKind) -> RuntimeOpKindMap a CompOpKind to its RuntimeOpKind counterpart.
runtime_kind_from_condop [source]¶
def runtime_kind_from_condop(kind: CondOpKind) -> RuntimeOpKindMap 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,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]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,
) -> NoneAttributes¶
kind: BinOpKind | Noneoperation_kind: OperationKindsignature: Signature
BinOpKind [source]¶
class BinOpKind(enum.Enum)Attributes¶
ADDDIVFLOORDIVMINMODMULPOWSUB
BitType [source]¶
class BitType(ClassicalTypeMixin, ValueType)Type representing a classical bit.
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
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:
Builds a measurement-taint set using the same dataflow utilities as
AnalyzePass(forward propagation fromMeasureOperationresults through the dependency graph).Walks operations recursively (through
HasNestedOps).For each engine-expressible
CompOp/CondOp/NotOp/BinOpwhose result UUID is in the taint set, replaces it with an equivalentRuntimeClassicalExpr(same operands and result Value, only the op type and kind enum change). Internal slice-clampMINoperations stay as host-sideBinOpnodes because Circuit IR has no runtime minimum expression.Non-tainted classical ops are left unchanged so the existing fold paths (compile-time fold in
compile_time_if_lowering, emit-time fold inevaluate_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¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockCompOp [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,
) -> NoneAttributes¶
kind: CompOpKind | Noneoperation_kind: OperationKindsignature: Signature
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,
) -> NoneAttributes¶
kind: CondOpKind | Noneoperation_kind: OperationKindsignature: Signature
ForItemsOperation [source]¶
class ForItemsOperation(HasNestedOps, Operation)Represents iteration over dict/iterable items.
Example:
for (i, j), Jij in qmc.items(ising):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]key_is_vector: boolkey_var_values: tuple[Value, ...] | Nonekey_vars: list[str]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]operation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signaturevalue_var: strvalue_var_value: Value | None
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the items-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt items-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationHasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
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¶
false_value: Valueindex: intis_identity: bool Whether both branches merge the same underlying value.result: Valuetrue_value: Value
Methods¶
select¶
def select(self, taken: bool) -> ValueReturn the branch source selected by a resolved condition.
Parameters:
| Name | Type | Description |
|---|---|---|
taken | bool | The condition’s truth value (True selects the true branch). |
Returns:
Value — true_value when taken is true, else
false_value.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[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()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
NotOp [source]¶
class NotOp(Operation)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
input: Valueoperation_kind: OperationKindoutput: Valuesignature: Signature
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¶
CLASSICALCONTROLHYBRIDQUANTUM
Pass [source]¶
class Pass(ABC, Generic[InputT, OutputT])Base class for all compiler passes.
Attributes¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute 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:
Binary kinds (EQ/NEQ/LT/LE/GT/GE/AND/OR/ADD/SUB/MUL/DIV/FLOORDIV/MOD/POW):
operands = [lhs, rhs].Unary kind (NOT):
operands = [val].Ternary kind (SELECT):
operands = [condition, true_value, false_value]— the runtime form of a branch merge (result = true_value if condition else false_value).Result:
results = [output_value].
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,
) -> NoneAttributes¶
kind: RuntimeOpKind | Noneoperation_kind: OperationKindsignature: Signature
RuntimeOpKind [source]¶
class RuntimeOpKind(enum.Enum)Unified kind for RuntimeClassicalExpr covering all classical
op families that can appear at runtime.
The split between this enum and the per-family BinOpKind /
CompOpKind / CondOpKind is intentional: compile-time-foldable
classical ops keep their original IR types so the existing fold
pipeline (constant_fold → compile_time_if_lowering → emit-time
evaluate_classical_predicate) is undisturbed. Only ops identified
as runtime-evaluation-only by ClassicalLoweringPass get rewritten
to RuntimeClassicalExpr with a member of this enum.
Attributes¶
ADDANDDIVEQFLOORDIVGEGTLELTMODMULNEQNOTORPOWSELECTSUB
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]max_iterations: int | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the while body and its complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt while operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, rebind-record, and region-arg values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
qamomile.circuit.transpiler.passes.compile_time_if_lowering¶
Compile-time IfOperation lowering pass.
Lowers compile-time resolvable IfOperations before the segmentation pass,
replacing them with selected-branch operations and substituting merge outputs
with selected-branch values throughout the block.
This prevents SegmentationPass from seeing classical-only compile-time
IfOperations that would otherwise split quantum segments.
Overview¶
| Function | Description |
|---|---|
array_static_length | Resolve a one-dimensional array’s compile-time length. |
collect_value_like_uuids | Collect UUIDs contained in a value-like IR object. |
evaluate_classical_op_concrete | Try to evaluate a classical op and record its concrete result. |
find_loop_carried_condition_uuids | Find branch conditions that read legacy loop-carried scalar Bits. |
genuine_input_values | Return an operation’s input values that count as genuine reads. |
lower_compile_time_ifs_preserving_loop_conditions | Specialize compile-time branches without erasing loop conditions. |
packed_register_type_width | Return the type-declared width of a packed quantum register type. |
pair_block_parameter_operands | Pair a block’s classical/object inputs with call-site operands. |
resolve_compile_time_condition | Resolve an IfOperation condition to a compile-time bool. |
root_carrier_keys | Build root-space carrier keys for the first count array elements. |
same_exact_typed_constant | Return whether two scalar Values carry the same exact typed constant. |
validate_region_args | Validate the SSA identities owned by a loop’s region arguments. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
BinOp | Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN). |
Block | Unified block representation for all pipeline stages. |
BlockKind | Classification of block structure for pipeline stages. |
CompOp | Comparison operation (EQ, NEQ, LT, LE, GT, GE). |
CompileTimeIfLoweringPass | Lowers compile-time resolvable IfOperations before separation. |
CondOp | Conditional logical operation (AND, OR). |
ControlledUOperation | Base class for controlled-U operations. |
DictValue | A dictionary value stored as stable ordered entries. |
FloatType | Type representing a floating-point number. |
ForItemsOperation | Represents iteration over dict/iterable items. |
ForOperation | Represents a for loop operation. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
IfOperation | Represents an if-else conditional operation. |
InverseBlockOperation | Represent an inverse qkernel/block as a first-class IR operation. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
MeasureQFixedOperation | Measure a quantum fixed-point number. |
MeasureVectorOperation | Measure a vector of qubits. |
NotOp | |
OperationKind | Classification of operations for classical/quantum separation. |
Pass | Base class for all compiler passes. |
QFixedType | Quantum fixed-point type. |
QInitOperation | Initialize the qubit |
QUIntType | Quantum unsigned integer type. |
RegionArg | Explicit loop-carried value on a loop operation (MLIR-style iter_arg). |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
UIntType | Type representing an unsigned integer. |
UnaryMathOp | Represent one pure unary mathematical expression. |
UnifiedValueResolver | Resolve IR Values to concrete Python values. |
ValidationError | Error during validation (e.g., non-classical I/O). |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
WhileOperation | Represents a while loop operation. |
Constants¶
ValueLike:TypeAlias='Value | ArrayValue | TupleValue | DictValue'
Functions¶
array_static_length [source]¶
def array_static_length(array: 'ArrayValue') -> int | NoneResolve a one-dimensional array’s compile-time length.
Parameters:
| Name | Type | Description |
|---|---|---|
array | ArrayValue | Array whose sole shape dimension is inspected. |
Returns:
int | None — int | None: Non-negative static length, or None when the array is not
one-dimensional, its length is symbolic/non-integral, or it is
malformed with a negative length. Boolean constants are rejected
even though bool is an int subclass.
collect_value_like_uuids [source]¶
def collect_value_like_uuids(value: 'ValueLike') -> set[str]Collect UUIDs contained in a value-like IR object.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ValueLike | Value-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],
) -> NoneTry to evaluate a classical op and record its concrete result.
Supported operation types:
CompOp— comparison (==, !=, <, <=, >, >=)CondOp— logical connective (and, or)NotOp— logical negationBinOp— arithmetic (+, -, *, /, //, %)UnaryMathOp— unary mathematical functions such asceilandlog2
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:
| Name | Type | Description |
|---|---|---|
op | Operation | The operation to evaluate. |
concrete_values | dict[str, Any] | UUID-keyed map of concrete results; the op’s result is recorded here on success. Updated in place. |
bindings | dict[str, Any] | Compile-time parameter bindings used to resolve operands. |
find_loop_carried_condition_uuids [source]¶
def find_loop_carried_condition_uuids(operations: Sequence[Operation]) -> set[str]Find branch conditions that read legacy loop-carried scalar Bits.
Compile-time specialization normally removes a branch whose first traced condition is a constant. That is unsafe while recursively unrolling a body when the same condition reads a legacy loop-carried Bit: later iterations observe the refreshed value, so the final loop-state validator still needs the branch as dependency evidence.
Parameters:
| Name | Type | Description |
|---|---|---|
operations | Sequence[Operation] | Semantic operation tree to inspect. |
Returns:
set[str] — set[str]: UUIDs of conditions that transitively depend on a legacy
scalar Bit entry value.
genuine_input_values [source]¶
def genuine_input_values(op: Operation) -> list[ValueBase]Return an operation’s input values that count as genuine reads.
Structured operations derive reads from their explicit region interface:
enclosing operands, captures, loop initializers, and region yields.
Block arguments and operation results are definitions, while legacy
rebind records are diagnostics rather than dataflow. Leaf operations keep
their ordinary all_input_values contract.
Parameters:
| Name | Type | Description |
|---|---|---|
op | Operation | Operation to inspect. |
Returns:
list[ValueBase] — list[ValueBase]: Semantic reads in interface order.
lower_compile_time_ifs_preserving_loop_conditions [source]¶
def lower_compile_time_ifs_preserving_loop_conditions(block: Block, bindings: dict[str, Any] | None = None) -> BlockSpecialize compile-time branches without erasing loop conditions.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Block whose resolvable compile-time branches should be lowered. |
bindings | dict[str, Any] | None | Compile-time input bindings used for condition resolution. Defaults to None. |
Returns:
Block — Specialized block with loop-carried conditions preserved.
Raises:
ValidationError— If specialization encounters invalid IR.
packed_register_type_width [source]¶
def packed_register_type_width(value_type: ValueType) -> int | NoneReturn the type-declared width of a packed quantum register type.
Unlike :func:static_quantum_width, this helper consults only the type
and never runtime carrier or fixed-point metadata, so it distinguishes a
register whose width is known to be zero (returns 0) from one whose
width is symbolic (returns None). static_quantum_width cannot make
that distinction for a QFixed whose frontend qfixed metadata records
num_bits=0 for a symbolic layout.
Parameters:
| Name | Type | Description |
|---|---|---|
value_type | ValueType | Type to inspect. Only QUIntType and QFixedType describe packed registers. |
Returns:
int | None — int | None: QUIntType.width or QFixedType.integer_bits + fractional_bits when every component is a compile-time
non-negative integer; None when any component is symbolic or
when value_type is not a packed register type.
pair_block_parameter_operands [source]¶
def pair_block_parameter_operands(
block: Block,
param_operands: Sequence[ValueBase],
) -> list[tuple[ValueBase, ValueBase]]Pair a block’s classical/object inputs with call-site operands.
Both compile-time lowering and emission bind an operation-owned block’s non-quantum inputs by their declaration order. Keeping the filtering and pairing here ensures those stages cannot adopt different positional conventions.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Operation-owned block whose formal inputs define the declaration order. |
param_operands | Sequence[ValueBase] | Classical or object operands at the call site, already ordered according to the operation signature. |
Returns:
list[tuple[ValueBase, ValueBase]] — list[tuple[ValueBase, ValueBase]]: (formal, actual) pairs in
list[tuple[ValueBase, ValueBase]] — declaration order. Missing actual operands leave trailing formals
list[tuple[ValueBase, ValueBase]] — unpaired, so they can remain symbolic and be provided at emit time.
resolve_compile_time_condition [source]¶
def resolve_compile_time_condition(
condition: Any,
concrete_values: dict[str, Any],
bindings: dict[str, Any],
) -> bool | NoneResolve 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:
| Name | Type | Description |
|---|---|---|
condition | Any | The condition operand. May be a plain Python value or a Value. |
concrete_values | dict[str, Any] | UUID-keyed map of concrete classical-op results accumulated in program order. |
bindings | dict[str, Any] | Compile-time parameter bindings. |
Returns:
bool | None — bool | None: The condition’s compile-time truth value, or
None when it is not compile-time resolvable (a runtime
condition).
root_carrier_keys [source]¶
def root_carrier_keys(array: 'ArrayValue', count: int) -> tuple[list[str], list[str]] | NoneBuild root-space carrier keys for the first count array elements.
Folds each view-local index through :func:resolve_root_array_index and
spells the result with :func:composite_carrier_key, so packed register
(QInt and QFixed) carriers produced by the frontend cast, rebuilt by
compile-time if lowering, and re-derived by serialization validation
all share one key producer.
Callers are responsible for bounding count by the array’s static
length: this helper performs no bounds check because its None result
must keep the single meaning “a slice bound on the chain is symbolic or
out of contract, defer resolution”. Serialization validation compares
count against array_static_length before calling; compile-time
if lowering does the same whenever the selected source has a static
length and otherwise trusts the trace-time carrier count.
Parameters:
| Name | Type | Description |
|---|---|---|
array | ArrayValue | One-dimensional qubit array, either a root array or an arbitrarily nested strided view. |
count | int | Number of leading elements to key, in array’s own index space. |
Returns:
tuple[list[str], list[str]] | None — tuple[list[str], list[str]] | None: Parallel (uuids, logical_ids)
carrier keys, (root.uuid, root_index) and
(root.logical_id, root_index) respectively, or None when
any index cannot be folded to the root index space.
same_exact_typed_constant [source]¶
def same_exact_typed_constant(left: Value, right: Value) -> boolReturn 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:
| Name | Type | Description |
|---|---|---|
left | Value | First scalar value to compare. |
right | Value | Second scalar value to compare. |
Returns:
bool — True only for constants of the same IR type and Python type
with equal value representations.
validate_region_args [source]¶
def validate_region_args(op: ForOperation | ForItemsOperation | WhileOperation) -> tuple[RegionArg, ...]Validate the SSA identities owned by a loop’s region arguments.
A loop owns several definition namespaces: its iteration variables,
every RegionArg.block_arg, and every RegionArg.result. Those
identities must be pairwise disjoint. Otherwise different stages can
assign incompatible meanings to one UUID: a UUID-keyed environment has
only one slot, so binding either the iteration variable or the carried
value overwrites the other and makes both reads observe the same value.
Parameters:
| Name | Type | Description |
|---|---|---|
op | ForOperation | ForItemsOperation | WhileOperation | Loop operation whose region arguments should be validated. |
Returns:
tuple[RegionArg, ...] — tuple[RegionArg, ...]: The validated op.region_args tuple.
Raises:
ValueError— If result counts or positions disagree, slot types differ, or any loop-owned definition identity collides with another definition or with a region initializer/body yield.
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,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]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,
) -> NoneAttributes¶
kind: BinOpKind | Noneoperation_kind: OperationKindsignature: Signature
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
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,
) -> NoneAttributes¶
kind: CompOpKind | Noneoperation_kind: OperationKindsignature: Signature
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:
Evaluates conditions including expression-derived ones (
CompOp,CondOp,NotOp,BinOp, andUnaryMathOpchains).Replaces resolved
IfOperations with selected-branch operations.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:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Compile-time bindings visible in the current block. Defaults to no bindings. |
preserved_condition_uuids | AbstractSet[str] | None | Conditions that must remain unresolved so a later validation pass can inspect their dataflow. Defaults to an empty set. |
_under_controlled_unitary | bool | Internal 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_ids | frozenset[int] | None | Internal recursion-path guard for operation-owned blocks. Defaults to an empty set. |
Attributes¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockLower every compile-time resolvable IfOperation in the block.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Block 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:
ValidationError— Ifinput.kindisANALYZED(the pass must run before dependency analysis commits to a representation), or if a compile-time branch selects a symbolic-bound slice-view cast source whose root index space is not resolvable.
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,
) -> NoneAttributes¶
kind: CondOpKind | Noneoperation_kind: OperationKindsignature: Signature
ControlledUOperation [source]¶
class ControlledUOperation(Operation)Base class for controlled-U operations.
Two concrete subclasses handle distinct operand layouts:
ConcreteControlledU: Fixednum_controls: int, individual qubit operands.SymbolicControlledU: Symbolicnum_controls: Value, vector-based control operands; optionalcontrol_indicesselects a subset of the control vector to act as controls (the rest pass through).
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(),
) -> NoneAttributes¶
block: Block | Nonebody_operands: list[Value] Get the wrapped callable’s complete argument list.callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_operands: list[Value] Get the control qubit values.is_symbolic_num_controls: bool Whether num_controls is symbolic (Value) rather than concrete.num_controls: int | Valueoperation_kind: OperationKindparam_operands: list[Value] Get the controlled operation’s classical/object arguments.power: int | Valuesignature: Signaturetarget_operands: list[Value] Get the target qubit values (arguments to U).
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationDictValue [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()))(),
) -> NoneAttributes¶
entries: tuple[tuple[TupleValue | Value, Value], ...]logical_id: strmetadata: ValueMetadataname: strtype: DictTypeuuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> DictValueFloatType [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):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]key_is_vector: boolkey_var_values: tuple[Value, ...] | Nonekey_vars: list[str]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]operation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signaturevalue_var: strvalue_var_value: Value | None
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the items-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt items-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationHasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
InverseBlockOperation [source]¶
class InverseBlockOperation(Operation)Represent an inverse qkernel/block as a first-class IR operation.
The operation stores both the original forward block and a Qamomile-built
inverse implementation block. Emitters may use source_block with a
engine-native inverse/adjoint primitive, then fall back to
implementation_block when native inversion is unavailable.
Operands are ordered as scalar control qubits, target quantum operands,
then classical/object parameters. Results mirror the quantum operand
layout: control results first, then one target result per target operand.
Vector target operands therefore count as one operand/result while
contributing their scalar width to num_target_qubits.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_control_qubits: int = 0,
num_target_qubits: int = 0,
custom_name: str = '',
source_block: Block | None = None,
implementation_block: Block | None = None,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_qubits: list[‘Value’] Return control quantum operands.control_value: int | Nonecustom_name: strimplementation_block: Block | Nonename: str Return a human-readable inverse operation name.num_control_qubits: intnum_target_qubits: intoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return classical/object parameter operands.signature: Signature Return the operation signature.source_block: Block | Nonetarget_qubits: list[‘Value’] Return target quantum operands.
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[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. |
definition | CallableDef | None | Optional 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,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueor an Oracle control-partition field has an invalid Python type.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width, or if Oracle invocation and definition control metadata disagree.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of relevant callable implementations.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return a conservative union of measurement-derived results.name: str Return the display name for this invocation.num_added_control_qubits: int Return controls introduced by a frontend control transform.num_body_external_control_qubits: int Return control operands generic lowering adds outside a base body.num_control_qubits: int Return the number of leading control-qubit operands.num_declared_control_qubits: int Return controls included in an opaque Oracle’s base definition.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
effective_body¶
def effective_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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 | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None, which only selects engine-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
require_body | bool | Whether 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name used for implementation selection. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
select_body¶
def select_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> CallableBodySelectionSelect 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
MeasureQFixedOperation [source]¶
class MeasureQFixedOperation(Operation)Measure a quantum fixed-point number.
This operation measures all qubits in a QFixed register and produces a Float result. During transpilation, this is lowered to individual MeasureOperations plus a DecodeQFixedOperation.
operands: [QFixed value (contains qubit_values in params)] results: [Float value]
Encoding:
For QPE phase (int_bits=0):
Qubits are stored least-significant first. For n qubits,
bit i has weight 2**(-n + i).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_bits: int = 0,
int_bits: int = 0,
) -> NoneAttributes¶
int_bits: intnum_bits: intoperation_kind: OperationKindsignature: Signature
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()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
NotOp [source]¶
class NotOp(Operation)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
input: Valueoperation_kind: OperationKindoutput: Valuesignature: Signature
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¶
CLASSICALCONTROLHYBRIDQUANTUM
Pass [source]¶
class Pass(ABC, Generic[InputT, OutputT])Base class for all compiler passes.
Attributes¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute the pass transformation.
QFixedType [source]¶
class QFixedType(QuantumTypeMixin, ValueType)Quantum fixed-point type.
Represents a quantum register encoding a fixed-point number with specified integer and fractional bits.
Constructor¶
def __init__(
self,
integer_bits: int | Value[UIntType] = 0,
fractional_bits: int | Value[UIntType] = 0,
) -> NoneAttributes¶
fractional_bits: int | Value[UIntType]integer_bits: int | Value[UIntType]
Methods¶
label¶
def label(self) -> strQInitOperation [source]¶
class QInitOperation(Operation)Initialize the qubit
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
QUIntType [source]¶
class QUIntType(QuantumTypeMixin, ValueType)Quantum unsigned integer type.
Represents a quantum register encoding an unsigned integer value using binary encoding (little-endian by default).
Constructor¶
def __init__(self, width: int | Value[UIntType]) -> NoneAttributes¶
width: int | Value[UIntType]
Methods¶
label¶
def label(self) -> strRegionArg [source]¶
class RegionArgExplicit 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:
On iteration 0 the body reads
block_argbound toinit.After each iteration,
block_argis rebound to that iteration’syieldedvalue.After the loop,
resultholds the final carried value (initwhen the loop ran zero iterations).
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,
) -> NoneAttributes¶
block_arg: Valueinit: Valueresult: Valuevar_name: stryielded: Value
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(),
) -> NoneAttributes¶
case_blocks: list[Block]case_callable_attrs: list[dict[str, Any]]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
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]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed replacement values. |
Returns:
Operation — Rebuilt SELECT operation with matching values replaced.
UIntType [source]¶
class UIntType(ClassicalTypeMixin, ValueType)Type representing an unsigned integer.
UnaryMathOp [source]¶
class UnaryMathOp(Operation)Represent one pure unary mathematical expression.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[Value] | Single numeric input value. |
results | list[Value] | Single numeric result value. |
kind | UnaryMathOpKind | None | Mathematical operation to apply. |
Raises:
ValueError— Ifkindis missing or the operation does not have exactly one operand and one result.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: UnaryMathOpKind | None = None,
) -> NoneAttributes¶
input: Value Return the input value.kind: UnaryMathOpKind | Noneoperation_kind: OperationKind Classify the operation as classical.output: Value Return the output value.signature: Signature Return the typed unary signature.
ValueResolver [source]¶
class ValueResolverResolve IR Values to concrete Python values.
Parameters:
| Name | Type | Description |
|---|---|---|
context | dict[str, Any] | None | UUID-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. |
bindings | dict[str, Any] | None | Name-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:
| Name | Type | Description |
|---|---|---|
context | dict[str, Any] | None | UUID-keyed map of already-resolved values. Defaults to None. |
bindings | dict[str, Any] | None | Name-keyed parameter bindings supplied by the user. Defaults to None. |
Methods¶
resolve¶
def resolve(self, value: Any) -> Any | NoneResolve 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:
| Name | Type | Description |
|---|---|---|
value | Any | The Value-like object or already concrete value to resolve. |
Returns:
Any | None — Any | None: The resolved concrete value, the original
concrete value for non-Value inputs, or None when no
resolution rule applies.
ValidationError [source]¶
class ValidationError(QamomileCompileError)Error during validation (e.g., non-classical I/O).
Constructor¶
def __init__(self, message: str, value_name: str | None = None)Initialize a validation diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable validation failure. |
value_name | str | None | Related IR value name. Defaults to None. |
Attributes¶
value_name
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]max_iterations: int | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the while body and its complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt while operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, rebind-record, and region-arg values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
qamomile.circuit.transpiler.passes.constant_fold¶
Constant folding pass for compile-time expression evaluation.
Overview¶
| Function | Description |
|---|---|
coerce_nonnegative_integral | Normalize a real scalar with an integer value to a nonnegative integer. |
collect_value_like_uuids | Collect UUIDs contained in a value-like IR object. |
validate_region_args | Validate the SSA identities owned by a loop’s region arguments. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
BinOp | Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN). |
BinOpKind | |
Block | Unified block representation for all pipeline stages. |
BlockKind | Classification of block structure for pipeline stages. |
CompOp | Comparison operation (EQ, NEQ, LT, LE, GT, GE). |
ConcreteControlledU | Controlled-U with concrete (int) number of controls. |
CondOp | Conditional logical operation (AND, OR). |
ConstantFoldingPass | Evaluates constant expressions at compile time. |
ControlledUOperation | Base class for controlled-U operations. |
DictValue | A dictionary value stored as stable ordered entries. |
ForOperation | Represents a for loop operation. |
IfOperation | Represents an if-else conditional operation. |
NotOp | |
OperationTransformer | Base class for transforming operations with control flow handling. |
Pass | Base class for all compiler passes. |
StoreArrayElementOperation | Store a classical scalar into one element of a classical array. |
SymbolicControlledU | Controlled-U with symbolic (Value) number of controls. |
TupleValue | A tuple of IR values for structured data. |
UnaryMathOp | Represent one pure unary mathematical expression. |
UnifiedValueResolver | Resolve IR Values to concrete Python values. |
ValidationError | Error during validation (e.g., non-classical I/O). |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
Constants¶
ValueLike:TypeAlias='Value | ArrayValue | TupleValue | DictValue'
Functions¶
coerce_nonnegative_integral [source]¶
def coerce_nonnegative_integral(value: object, *, label: str) -> intNormalize a real scalar with an integer value to a nonnegative integer.
Parameters:
| Name | Type | Description |
|---|---|---|
value | object | Candidate Python, NumPy, or SymPy real scalar. |
label | str | User-facing field label used in diagnostics. |
Returns:
int — Equivalent nonnegative Python integer.
Raises:
TypeError— Ifvalueis Boolean, is not a real scalar, is not finite, or does not have an integer value.ValueError— If the normalized integer is negative.
collect_value_like_uuids [source]¶
def collect_value_like_uuids(value: 'ValueLike') -> set[str]Collect UUIDs contained in a value-like IR object.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ValueLike | Value-like object to inspect. |
Returns:
set[str] — set[str]: UUIDs for value itself, recursively contained tuple/dict
elements, and array view/element dependencies.
validate_region_args [source]¶
def validate_region_args(op: ForOperation | ForItemsOperation | WhileOperation) -> tuple[RegionArg, ...]Validate the SSA identities owned by a loop’s region arguments.
A loop owns several definition namespaces: its iteration variables,
every RegionArg.block_arg, and every RegionArg.result. Those
identities must be pairwise disjoint. Otherwise different stages can
assign incompatible meanings to one UUID: a UUID-keyed environment has
only one slot, so binding either the iteration variable or the carried
value overwrites the other and makes both reads observe the same value.
Parameters:
| Name | Type | Description |
|---|---|---|
op | ForOperation | ForItemsOperation | WhileOperation | Loop operation whose region arguments should be validated. |
Returns:
tuple[RegionArg, ...] — tuple[RegionArg, ...]: The validated op.region_args tuple.
Raises:
ValueError— If result counts or positions disagree, slot types differ, or any loop-owned definition identity collides with another definition or with a region initializer/body yield.
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,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]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,
) -> NoneAttributes¶
kind: BinOpKind | Noneoperation_kind: OperationKindsignature: Signature
BinOpKind [source]¶
class BinOpKind(enum.Enum)Attributes¶
ADDDIVFLOORDIVMINMODMULPOWSUB
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
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,
) -> NoneAttributes¶
kind: CompOpKind | Noneoperation_kind: OperationKindsignature: Signature
ConcreteControlledU [source]¶
class ConcreteControlledU(ControlledUOperation)Controlled-U with concrete (int) number of controls.
Operand layout: [ctrl_0, ..., ctrl_n, tgt_0, ..., tgt_m, params...]
Result layout: [ctrl_0', ..., ctrl_n', tgt_0', ..., tgt_m']
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
power: int | Value = 1,
block: Block | None = None,
num_controls: int = 1,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
control_operands: list[Value]control_value: int | Nonenum_controls: intparam_operands: list[Value] Get classical/object operands after the concrete control prefix.signature: Signature Build the concrete controlled call signature.target_operands: list[Value] Return the wrapped callable’s target and parameter operands.
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,
) -> NoneAttributes¶
kind: CondOpKind | Noneoperation_kind: OperationKindsignature: Signature
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 splitConstructor¶
def __init__(self, bindings: dict[str, Any] | None = None, *, strip_slice_ops: bool = True)Create a constant-folding pass.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Compile-time parameter bindings used when folding BinOps that reference declared parameters. |
strip_slice_ops | bool | When 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¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockFold resolvable classical values throughout a block.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Affine or hierarchical block to rewrite. |
Returns:
Block — Copy with folded operations and output values.
Raises:
ValidationError— If the block is neither affine nor hierarchical.
ControlledUOperation [source]¶
class ControlledUOperation(Operation)Base class for controlled-U operations.
Two concrete subclasses handle distinct operand layouts:
ConcreteControlledU: Fixednum_controls: int, individual qubit operands.SymbolicControlledU: Symbolicnum_controls: Value, vector-based control operands; optionalcontrol_indicesselects a subset of the control vector to act as controls (the rest pass through).
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(),
) -> NoneAttributes¶
block: Block | Nonebody_operands: list[Value] Get the wrapped callable’s complete argument list.callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_operands: list[Value] Get the control qubit values.is_symbolic_num_controls: bool Whether num_controls is symbolic (Value) rather than concrete.num_controls: int | Valueoperation_kind: OperationKindparam_operands: list[Value] Get the controlled operation’s classical/object arguments.power: int | Valuesignature: Signaturetarget_operands: list[Value] Get the target qubit values (arguments to U).
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationDictValue [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()))(),
) -> NoneAttributes¶
entries: tuple[tuple[TupleValue | Value, Value], ...]logical_id: strmetadata: ValueMetadataname: strtype: DictTypeuuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> DictValueForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationIfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[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()) -> NoneAttributes¶
input: Valueoperation_kind: OperationKindoutput: Valuesignature: Signature
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 | NoneTransform 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¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute the pass transformation.
StoreArrayElementOperation [source]¶
class StoreArrayElementOperation(Operation)Store a classical scalar into one element of a classical array.
This is the IR form of array[index] = value for classical element
types (Bit / UInt / Float). Classical values are freely
copyable, so the store is an ordinary SSA rewrite: the operation
consumes the current array version and produces a new ArrayValue
version (same logical_id, fresh uuid) whose contents equal the
input array with the addressed element replaced. Quantum arrays never
use this operation — qubit element assignment is the return half of
the borrow-return idiom and emits no IR.
The operation is evaluated in one of two places:
Compile time:
ConstantFoldingPassfolds the store when the source array contents, the index, and the stored value are all compile-time resolvable, attaching the updatedconst_arraymetadata to the result value.Runtime: otherwise the store executes host-side in a classical segment via
ClassicalExecutor(e.g. for measurement-derivedVector[Bit]contents). It must never reach a quantum segment; engine emit rejects it explicitly.
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 bitsConstructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
array: ArrayValue ArrayValue: The array version the store reads from.index_values: tuple[Value, ...] tuple[Value, ...]: The element indices being written.operation_kind: OperationKindsignature: Signature Return the operation’s dynamic array/qubit/index signature.stored_value: Value Value: The scalar being written into the array.
SymbolicControlledU [source]¶
class SymbolicControlledU(ControlledUOperation)Controlled-U with symbolic (Value) number of controls.
Operand layout: [ctrl_arg_0, ..., ctrl_arg_{k-1}, tgt_0, ..., tgt_m, params...]
Result layout: [ctrl_arg_0', ..., ctrl_arg_{k-1}', tgt_0', ..., tgt_m']
The number of control arguments k is recorded in
num_control_args; the default k = 1 corresponds to the
historical single-pool form (operands[0] is a
Vector[Qubit] / VectorView whose length equals
num_controls, or whose control_indices-selected subset
does). When k > 1 the control prefix is a heterogeneous
sequence of scalar Qubit values and ArrayValues whose
total qubit count is num_controls; the emit pass walks them
in order to recover the per-physical-qubit control set.
When control_indices is None the entire control prefix
is used as active controls (one-arg form: len(ctrl_vector) == num_controls; multi-arg form: the qubit-count sum of the
prefix args equals num_controls). When non-None, the
listed indices select exactly num_controls slots from a
single-arg pool to act as controls; combining
control_indices with the multi-arg control prefix is
rejected at frontend time.
Each control_indices entry is stored as a Value of
UIntType regardless of whether the frontend passed an
int literal or a UInt handle, so all downstream
value-substitution passes see a uniform shape.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
power: int | Value = 1,
block: Block | None = None,
num_controls: Value = (lambda: Value(type=(UIntType()), name=''))(),
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_indices: tuple[Value, ...] | None = None,
num_control_args: int = 1,
) -> NoneAttributes¶
control_indices: tuple[Value, ...] | Nonecontrol_operands: list[Value]is_symbolic_num_controls: boolnum_control_args: intnum_controls: Valueparam_operands: list[Value] Get classical/object operands after the symbolic control prefix.signature: Signaturetarget_operands: list[Value] Return the wrapped callable’s target and parameter operands.
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationTupleValue [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()))(),
) -> NoneAttributes¶
elements: tuple[ValueLike, ...]logical_id: strmetadata: ValueMetadataname: strtype: ‘TupleType’uuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> TupleValueUnaryMathOp [source]¶
class UnaryMathOp(Operation)Represent one pure unary mathematical expression.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[Value] | Single numeric input value. |
results | list[Value] | Single numeric result value. |
kind | UnaryMathOpKind | None | Mathematical operation to apply. |
Raises:
ValueError— Ifkindis missing or the operation does not have exactly one operand and one result.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: UnaryMathOpKind | None = None,
) -> NoneAttributes¶
input: Value Return the input value.kind: UnaryMathOpKind | Noneoperation_kind: OperationKind Classify the operation as classical.output: Value Return the output value.signature: Signature Return the typed unary signature.
ValueResolver [source]¶
class ValueResolverResolve IR Values to concrete Python values.
Parameters:
| Name | Type | Description |
|---|---|---|
context | dict[str, Any] | None | UUID-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. |
bindings | dict[str, Any] | None | Name-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:
| Name | Type | Description |
|---|---|---|
context | dict[str, Any] | None | UUID-keyed map of already-resolved values. Defaults to None. |
bindings | dict[str, Any] | None | Name-keyed parameter bindings supplied by the user. Defaults to None. |
Methods¶
resolve¶
def resolve(self, value: Any) -> Any | NoneResolve 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:
| Name | Type | Description |
|---|---|---|
value | Any | The Value-like object or already concrete value to resolve. |
Returns:
Any | None — Any | None: The resolved concrete value, the original
concrete value for non-Value inputs, or None when no
resolution rule applies.
ValidationError [source]¶
class ValidationError(QamomileCompileError)Error during validation (e.g., non-classical I/O).
Constructor¶
def __init__(self, message: str, value_name: str | None = None)Initialize a validation diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable validation failure. |
value_name | str | None | Related IR value name. Defaults to None. |
Attributes¶
value_name
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
qamomile.circuit.transpiler.passes.control_flow_reachability¶
Resolve statically reachable structured-control regions.
Overview¶
| Function | Description |
|---|---|
constant_integer | Return a non-boolean integer constant carried by an IR value. |
reachable_nested_regions | Return nested regions that may execute for one control-flow operation. |
same_exact_typed_constant | Return whether two scalar Values carry the same exact typed constant. |
static_for_items_entries | Return compile-time entries iterated by a for-items operation. |
static_for_range | Resolve the exact iteration range of a statically bounded loop. |
static_loop_trip_count | Resolve the exact trip count of a compile-time loop. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
DictValue | A dictionary value stored as stable ordered entries. |
ForItemsOperation | Represents iteration over dict/iterable items. |
ForOperation | Represents a for loop operation. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
IfOperation | Represents an if-else conditional operation. |
Region | Expose one structured-control region through a uniform interface. |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
Functions¶
constant_integer [source]¶
def constant_integer(value: ValueBase | None) -> int | NoneReturn a non-boolean integer constant carried by an IR value.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ValueBase | None | Candidate scalar value. |
Returns:
int | None — int | None: Normalized Python integer, or None when value is
absent, symbolic, boolean, or non-integral.
reachable_nested_regions [source]¶
def reachable_nested_regions(operation: HasNestedOps) -> tuple[Region, ...]Return nested regions that may execute for one control-flow operation.
Constant conditionals expose only their selected branch. Statically empty counted and items loops expose no body region. All unresolved control flow remains conservative and exposes every region.
Parameters:
| Name | Type | Description |
|---|---|---|
operation | HasNestedOps | Structured-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) -> boolReturn 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:
| Name | Type | Description |
|---|---|---|
left | Value | First scalar value to compare. |
right | Value | Second scalar value to compare. |
Returns:
bool — True only for constants of the same IR type and Python type
with equal value representations.
static_for_items_entries [source]¶
def static_for_items_entries(operation: ForItemsOperation) -> tuple[tuple[Any, Any], ...] | NoneReturn compile-time entries iterated by a for-items operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operation | ForItemsOperation | Items 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 | NoneResolve the exact iteration range of a statically bounded loop.
Parameters:
| Name | Type | Description |
|---|---|---|
operation | ForOperation | Counted loop whose three bounds should be inspected. |
Returns:
range | None — range | None: Exact Python range when all bounds are integral
constants and the step is nonzero, otherwise None.
static_loop_trip_count [source]¶
def static_loop_trip_count(operation: ForOperation | ForItemsOperation) -> int | NoneResolve the exact trip count of a compile-time loop.
Parameters:
| Name | Type | Description |
|---|---|---|
operation | ForOperation | ForItemsOperation | Counted or items loop whose cardinality should be inspected. |
Returns:
int | None — int | None: Exact non-negative trip count, or None when the loop
cardinality is unresolved.
Classes¶
ArrayValue [source]¶
class ArrayValue(Value[T])An array of typed IR values.
When slice_of is set, this array is a strided view over another
array. Element accesses on a sliced ArrayValue resolve to
physical slots on the root parent via the affine map
parent_index = slice_start + slice_step * view_local_index,
applied recursively along slice_of chains. The emit-time
resolver walks this chain to produce the final qubit index; passes
that substitute or clone values must treat slice_of /
slice_start / slice_step as Value references that need to
track through the same mapping as parent_array.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
shape: tuple[Value, ...] = tuple(),
slice_of: 'ArrayValue | None' = None,
slice_start: 'Value | None' = None,
slice_step: 'Value | None' = None,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]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()))(),
) -> NoneAttributes¶
entries: tuple[tuple[TupleValue | Value, Value], ...]logical_id: strmetadata: ValueMetadataname: strtype: DictTypeuuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> DictValueForItemsOperation [source]¶
class ForItemsOperation(HasNestedOps, Operation)Represents iteration over dict/iterable items.
Example:
for (i, j), Jij in qmc.items(ising):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]key_is_vector: boolkey_var_values: tuple[Value, ...] | Nonekey_vars: list[str]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]operation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signaturevalue_var: strvalue_var_value: Value | None
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the items-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt items-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationHasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
Region [source]¶
class RegionExpose one structured-control region through a uniform interface.
This is a view over the existing semantic IR rather than a parallel value
system: every entry is an ordinary Qamomile ValueBase carrying the
current UUID identity. Control-flow operations remain the owners of the
stored fields and construct Region views through nested_regions.
Parameters:
| Name | Type | Description |
|---|---|---|
operations | tuple[Operation, ...] | Operations evaluated inside the region in program order. |
block_args | tuple[ValueBase, ...] | Values defined at region entry, such as a loop induction variable or carried-value formal. |
captures | tuple[ValueBase, ...] | Explicit outer-scope values read by the region, ordered by first use. |
yields | tuple[ValueBase, ...] | Values yielded at the region boundary in result-slot order. |
Constructor¶
def __init__(
self,
operations: tuple[Operation, ...],
block_args: tuple[ValueBase, ...] = (),
captures: tuple[ValueBase, ...] = (),
yields: tuple[ValueBase, ...] = (),
) -> NoneAttributes¶
block_args: tuple[ValueBase, ...]captures: tuple[ValueBase, ...]operations: tuple[Operation, ...]yields: tuple[ValueBase, ...]
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
qamomile.circuit.transpiler.passes.control_flow_visitor¶
Control flow visitor for operation traversal.
Overview¶
| Class | Description |
|---|---|
ControlFlowVisitor | Base class for visiting operations with control flow handling. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
OperationCollector | Collects operations matching a predicate. |
OperationTransformer | Base class for transforming operations with control flow handling. |
ValueCollector | Collects Value UUIDs from operation operands and results. |
Classes¶
ControlFlowVisitor [source]¶
class ControlFlowVisitor(ABC)Base class for visiting operations with control flow handling.
Subclasses override visit_operation to define per-operation behavior.
Control flow recursion is handled automatically by the base class.
Example:
class MeasurementCounter(ControlFlowVisitor):
def __init__(self):
self.count = 0
def visit_operation(self, op: Operation) -> None:
if isinstance(op, MeasureOperation):
self.count += 1Methods¶
visit_operation¶
def visit_operation(self, op: Operation) -> NoneProcess a single operation. Override in subclasses.
visit_operations¶
def visit_operations(self, operations: list[Operation]) -> NoneVisit all operations including nested control flow.
HasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
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.collectedConstructor¶
def __init__(self, predicate: Callable[[Operation], bool])Attributes¶
collected: list[Operation]
Methods¶
visit_operation¶
def visit_operation(self, op: Operation) -> NoneOperationTransformer [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 | NoneTransform a single operation. Return None to remove it.
transform_operations¶
def transform_operations(self, operations: list[Operation]) -> list[Operation]Transform all operations including nested control flow.
ValueCollector [source]¶
class ValueCollector(ControlFlowVisitor)Collects Value UUIDs from operation operands and results.
Constructor¶
def __init__(self)Attributes¶
operand_uuids: set[str]result_uuids: set[str]
Methods¶
visit_operation¶
def visit_operation(self, op: Operation) -> NoneRecord one operation’s input and result Value UUIDs.
Parameters:
| Name | Type | Description |
|---|---|---|
op | Operation | The visited operation. Inputs are read via all_input_values so subclass-specific Value fields (e.g. IfOperation yields) are covered. |
qamomile.circuit.transpiler.passes.effect_validation¶
Validate execution-mode constraints from cached kernel effects.
Overview¶
| Function | Description |
|---|---|
callable_bodies | Return cached semantic bodies relevant to one call transform. |
format_kernel_effects | Format an effect set for deterministic user-facing diagnostics. |
| Class | Description |
|---|---|
Block | Unified block representation for all pipeline stages. |
ControlledUOperation | Base class for controlled-U operations. |
EffectValidationPass | Reject execution-mode conflicts using cached kernel effects. |
ExpvalOp | Expectation value operation. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
InverseBlockOperation | Represent an inverse qkernel/block as a first-class IR operation. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
Pass | Base class for all compiler passes. |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
ValidationError | Error during validation (e.g., non-classical I/O). |
Functions¶
callable_bodies [source]¶
def callable_bodies(definition: 'CallableDef', transform: CallTransform) -> tuple['Block', ...]Return cached semantic bodies relevant to one call transform.
An explicit implementation of the complete transform takes precedence. A controlled-inverse call then reuses explicit inverse-body metadata when generic lowering only needs to add controls; all other structural fallbacks conservatively inherit the direct body’s effects.
Parameters:
| Name | Type | Description |
|---|---|---|
definition | CallableDef | Callable definition referenced by a call. |
transform | CallTransform | Requested direct, inverse, or controlled transform. |
Returns:
tuple['Block', ...] — tuple[Block, ...]: Candidate bodies whose cached metadata applies.
format_kernel_effects [source]¶
def format_kernel_effects(effects: KernelEffect) -> strFormat an effect set for deterministic user-facing diagnostics.
Parameters:
| Name | Type | Description |
|---|---|---|
effects | KernelEffect | Effect set to format. |
Returns:
str — Comma-separated flag names, or NONE for a unitary kernel.
Classes¶
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
ControlledUOperation [source]¶
class ControlledUOperation(Operation)Base class for controlled-U operations.
Two concrete subclasses handle distinct operand layouts:
ConcreteControlledU: Fixednum_controls: int, individual qubit operands.SymbolicControlledU: Symbolicnum_controls: Value, vector-based control operands; optionalcontrol_indicesselects a subset of the control vector to act as controls (the rest pass through).
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(),
) -> NoneAttributes¶
block: Block | Nonebody_operands: list[Value] Get the wrapped callable’s complete argument list.callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_operands: list[Value] Get the control qubit values.is_symbolic_num_controls: bool Whether num_controls is symbolic (Value) rather than concrete.num_controls: int | Valueoperation_kind: OperationKindparam_operands: list[Value] Get the controlled operation’s classical/object arguments.power: int | Valuesignature: Signaturetarget_operands: list[Value] Get the target qubit values (arguments to U).
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationEffectValidationPass [source]¶
class EffectValidationPass(Pass)Reject execution-mode conflicts using cached kernel effects.
Attributes¶
name: str Return the stable compiler-pass name.
Methods¶
run¶
def run(self, block: Block) -> BlockValidate expectation-value compatibility for one entrypoint.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Hierarchical entrypoint block. |
Returns:
Block — The unchanged validated block.
Raises:
ValidationError— If expectation-value execution is combined with measurement, reset, or feed-forward effects.
ExpvalOp [source]¶
class ExpvalOp(Operation)Expectation value operation.
This operation computes the expectation value <psi|H|psi> where psi is the quantum state and H is the Hamiltonian observable.
The operation bridges quantum and classical computation:
Input: quantum state (qubits) + Observable reference
Output: classical Float (expectation value)
Example IR:
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
hamiltonian: Value Alias for observable (deprecated, use observable instead).observable: Value The Observable parameter operand.operation_kind: OperationKind ExpvalOp is HYBRID - bridges quantum state to classical value.output: Value The expectation value result.qubits: Value The quantum register operand.signature: Signature
HasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
InverseBlockOperation [source]¶
class InverseBlockOperation(Operation)Represent an inverse qkernel/block as a first-class IR operation.
The operation stores both the original forward block and a Qamomile-built
inverse implementation block. Emitters may use source_block with a
engine-native inverse/adjoint primitive, then fall back to
implementation_block when native inversion is unavailable.
Operands are ordered as scalar control qubits, target quantum operands,
then classical/object parameters. Results mirror the quantum operand
layout: control results first, then one target result per target operand.
Vector target operands therefore count as one operand/result while
contributing their scalar width to num_target_qubits.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_control_qubits: int = 0,
num_target_qubits: int = 0,
custom_name: str = '',
source_block: Block | None = None,
implementation_block: Block | None = None,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_qubits: list[‘Value’] Return control quantum operands.control_value: int | Nonecustom_name: strimplementation_block: Block | Nonename: str Return a human-readable inverse operation name.num_control_qubits: intnum_target_qubits: intoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return classical/object parameter operands.signature: Signature Return the operation signature.source_block: Block | Nonetarget_qubits: list[‘Value’] Return target quantum operands.
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[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. |
definition | CallableDef | None | Optional 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,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueor an Oracle control-partition field has an invalid Python type.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width, or if Oracle invocation and definition control metadata disagree.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of relevant callable implementations.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return a conservative union of measurement-derived results.name: str Return the display name for this invocation.num_added_control_qubits: int Return controls introduced by a frontend control transform.num_body_external_control_qubits: int Return control operands generic lowering adds outside a base body.num_control_qubits: int Return the number of leading control-qubit operands.num_declared_control_qubits: int Return controls included in an opaque Oracle’s base definition.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
effective_body¶
def effective_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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 | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None, which only selects engine-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
require_body | bool | Whether 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name used for implementation selection. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
select_body¶
def select_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> CallableBodySelectionSelect 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
Pass [source]¶
class Pass(ABC, Generic[InputT, OutputT])Base class for all compiler passes.
Attributes¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute 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(),
) -> NoneAttributes¶
case_blocks: list[Block]case_callable_attrs: list[dict[str, Any]]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
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]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed replacement values. |
Returns:
Operation — Rebuilt SELECT operation with matching values replaced.
ValidationError [source]¶
class ValidationError(QamomileCompileError)Error during validation (e.g., non-classical I/O).
Constructor¶
def __init__(self, message: str, value_name: str | None = None)Initialize a validation diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable validation failure. |
value_name | str | None | Related IR value name. Defaults to None. |
Attributes¶
value_name
qamomile.circuit.transpiler.passes.emit¶
Emit pass: Generate engine-specific code from separated program.
Overview¶
| Function | Description |
|---|---|
collect_value_like_uuids | Collect UUIDs contained in a value-like IR object. |
resolve_condition_address_detailed | Resolve a condition / source Value to its clbit_map key. |
resolve_root_qubit_address | Resolve an array-element value to its root (array_uuid, index). |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
BitType | Type representing a classical bit. |
ClassicalSegment | A segment of pure classical operations. |
ClassicalStep | A classical execution step. |
CompositeGateEmitter | Protocol for preserving or lowering boxed callable operations. |
CompositeGateType | Classify standard boxed quantum callables. |
DictValue | A dictionary value stored as stable ordered entries. |
EmitError | Report an engine failure to emit one semantic operation. |
EmitPass | Base class for engine-specific emission passes. |
ExecutableProgram | A fully compiled program ready for execution. |
ExpvalSegment | A segment for expectation value computation. |
ExpvalStep | An expectation-value execution step. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
MeasureOperation | |
MeasureQFixedOperation | Measure a quantum fixed-point number. |
MeasureQIntOperation | Measure an unsigned quantum integer as one abstract hybrid operation. |
MeasureVectorOperation | Measure a vector of qubits. |
OperationCollector | Collects operations matching a predicate. |
Pass | Base class for all compiler passes. |
ProgramPlan | Execution plan for a hybrid quantum/classical program. |
ProjectOperation | Project a qubit in one Pauli basis and keep the projected state. |
QuantumSegment | A segment of pure quantum operations. |
QuantumStep | A quantum execution step. |
QubitAddress | Typed key for qubit/clbit physical-index maps. |
ResetOperation | Reset a qubit to the |0> state and return the fresh handle. |
TupleValue | A tuple of IR values for structured data. |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
ValueResolver | Resolves Value objects to concrete indices or values. |
Functions¶
collect_value_like_uuids [source]¶
def collect_value_like_uuids(value: 'ValueLike') -> set[str]Collect UUIDs contained in a value-like IR object.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ValueLike | Value-like object to inspect. |
Returns:
set[str] — set[str]: UUIDs for value itself, recursively contained tuple/dict
elements, and array view/element dependencies.
resolve_condition_address_detailed [source]¶
def resolve_condition_address_detailed(
condition: Value,
bindings: dict[str, Any],
resolver: ValueResolver | None = None,
) -> tuple[QubitAddress, bool]Resolve a condition / source Value to its clbit_map key.
Single source of truth (shared by control_flow_emission.emit_if /
emit_while, the Qiskit / CUDA-Q engines, ResourceAllocator’s
loop-carried / merge aliasing, and the merge-output mapping helpers here)
for turning a runtime control-flow condition — or a merge source Value —
into the address its classical bit is registered under.
Scalar measurement results register under QubitAddress(bit.uuid),
while a Vector[Bit] element s[i] (s = qmc.measure(register))
registers under QubitAddress(root_array.uuid, root_index). The
element index and every slice_start / slice_step along the
parent’s slice_of chain are resolved the same way — taken directly
when constant, otherwise folded through bindings via resolver —
and composed into the root index via root_index = start + step * view_local_index repeated along the chain.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | Value | The condition operand or merge source Value. |
bindings | dict[str, Any] | Active emit-time bindings used to fold symbolic indices / slice bounds. May be empty for callers that only have constant addresses to resolve (e.g. the allocator’s pre-emit pass). |
resolver | ValueResolver | None | Resolver exposing resolve_int_value; None restricts resolution to constants. Defaults to None. |
Returns:
tuple[QubitAddress, bool] — tuple[QubitAddress, bool]: (address, resolved_as_element).
resolved_as_element is True only when condition is a
Vector[Bit] element whose index (and any slice bounds)
resolved to concrete ints, giving the root-space
QubitAddress(root.uuid, root_index). It is False for a
plain scalar, or when an element’s index / slice bound could
not be resolved (the scalar UUID fallback). Callers that mutate
clbit_map should trust the address as a vector key only when
this flag is True, to avoid aliasing an unresolved element
onto an unrelated scalar slot.
resolve_root_qubit_address [source]¶
def resolve_root_qubit_address(value: 'Value') -> tuple[str, int] | NoneResolve 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:
| Name | Type | Description |
|---|---|---|
value | Value | The value to resolve. Expected to be an array element (parent_array set with a single constant element_indices entry). |
Returns:
tuple[str, int] | None — tuple[str, int] | None: (root_array_uuid, composed_index) when
value is an array element with a constant index whose entire
slice_of chain has constant slice_start / slice_step.
None when value is not an array element, when its index is
non-constant, or when any slice bound in the chain is non-constant
(those cases are deferred to the emit-time resolver, which has
bindings available). Also None for a negative constant index
or a chain frame with negative slice_start / non-positive
slice_step — composing those would silently address a wrong
root slot, so they are refused rather than guessed (the frontend
rejects them at trace time; this guard covers programmatically
constructed IR).
Classes¶
ArrayValue [source]¶
class ArrayValue(Value[T])An array of typed IR values.
When slice_of is set, this array is a strided view over another
array. Element accesses on a sliced ArrayValue resolve to
physical slots on the root parent via the affine map
parent_index = slice_start + slice_step * view_local_index,
applied recursively along slice_of chains. The emit-time
resolver walks this chain to produce the final qubit index; passes
that substitute or clone values must treat slice_of /
slice_start / slice_step as Value references that need to
track through the same mapping as parent_array.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
shape: tuple[Value, ...] = tuple(),
slice_of: 'ArrayValue | None' = None,
slice_start: 'Value | None' = None,
slice_step: 'Value | None' = None,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]BitType [source]¶
class BitType(ClassicalTypeMixin, ValueType)Type representing a classical bit.
ClassicalSegment [source]¶
class ClassicalSegment(Segment)A segment of pure classical operations.
Contains arithmetic, comparisons, and control flow. Will be executed directly in Python.
Constructor¶
def __init__(
self,
operations: list[Operation] = list(),
input_refs: list[str] = list(),
output_refs: list[str] = list(),
) -> NoneAttributes¶
kind: SegmentKind
ClassicalStep [source]¶
class ClassicalStepA classical execution step.
Constructor¶
def __init__(self, segment: ClassicalSegment, role: str = 'classical') -> NoneAttributes¶
role: strsegment: ClassicalSegment
CompositeGateEmitter [source]¶
class CompositeGateEmitter(Protocol[C])Protocol for preserving or lowering boxed callable operations.
The concrete compiler installs a semantic emitter that boxes every executable callable into circuit IR with its identity and fallback body. Native SDK selection happens later, through target capabilities and legalization; this traversal hook must not import or select an engine.
Methods¶
can_emit¶
def can_emit(self, gate_type: CompositeGateType) -> boolCheck whether this emitter handles the given callable kind.
Parameters:
| Name | Type | Description |
|---|---|---|
gate_type | CompositeGateType | Callable kind to check. |
Returns:
bool — True if this emitter handles the callable kind.
emit¶
def emit(
self,
circuit: C,
op: InvokeOperation,
qubit_indices: list[int],
bindings: dict[str, Any],
) -> boolPreserve or lower the boxed callable into the output builder.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | C | Output builder receiving the callable representation. |
op | InvokeOperation | Invocation to preserve or lower. |
qubit_indices | list[int] | Physical qubit indices for the operation. |
bindings | dict[str, Any] | Parameter bindings for the operation. |
Returns:
bool — True if handled, or False to use the generic fallback
bool — decomposition.
CompositeGateType [source]¶
class CompositeGateType(enum.Enum)Classify standard boxed quantum callables.
Attributes¶
CUSTOMIQFTQFTQPE
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()))(),
) -> NoneAttributes¶
entries: tuple[tuple[TupleValue | Value, Value], ...]logical_id: strmetadata: ValueMetadataname: strtype: DictTypeuuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> DictValueEmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
operation
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:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Values to bind parameters to. If not provided, parameters must be bound at execution time. |
parameters | list[str] | None | List of parameter names to preserve as engine parameters. |
Raises:
ValueError— If a name appears in bothbindingsandparameters. This is the innermost emit-side choke point: it catches the overlap even when anEmitPassis constructed directly (e.g. viaTranspiler._create_emit_pass), bypassing thetranspile/emitwrappers. A name in both is ambiguous and would otherwise silently bake the binding while dropping the runtime parameter (see #354).
Attributes¶
bindingsname: strparameters
Methods¶
run¶
def run(self, input: ProgramPlan) -> ExecutableProgram[T]Emit engine code from a program plan.
Parameters:
| Name | Type | Description |
|---|---|---|
input | ProgramPlan | Segmented 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:
EmitError— If expectation-value evaluation is combined with a measurement, projection, or reset operation, or if a planned segment cannot be emitted.
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 typeConstructor¶
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(),
) -> NoneAttributes¶
compiled_classical: list[CompiledClassicalSegment]compiled_expval: list[CompiledExpvalSegment]compiled_quantum: list[CompiledQuantumSegment[T]]has_parameters: bool Check if this program has unbound parameters.output_values: list[ValueLike]parameter_names: list[str] Get list of parameter names that need binding.plan: ProgramPlan | Nonequantum_circuit: T Get the single quantum circuit.
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 | NoneGet 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] | ExpvalJobRestore 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:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine adapter configured with the provider credentials and target used by the original job. |
snapshot | JobSnapshot | Snapshot returned by the original public job’s snapshot() method. |
bindings | dict[str, Any] | None | Original 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:
ExecutionError— If the snapshot operation or execution shape does not match this executable program.NotImplementedError— If the executor cannot restore the referenced provider execution.ValueError— If required bindings are missing or invalid.
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] | ExpvalJobSubmit one execution and return its lazy result job.
Parameters:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine-specific quantum executor. |
bindings | dict[str, Any] | None | Parameter 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} |
estimation | EstimationAccuracy | None | Optional 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:
ExecutionError— If no quantum circuit to executeValueError— If required parameters are missing
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:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine-specific quantum executor. |
shots | int | Number of shots to run. |
bindings | dict[str, Any] | None | Parameter 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:
ExecutionError— If no quantum circuit to executeValueError— If required parameters are missing
Example:
job = executable.sample(executor, shots=1000, bindings={"gamma": [0.5]})
result = job.result()
print(result.results) # [(0.25, 500), (0.75, 500)]ExpvalSegment [source]¶
class ExpvalSegment(Segment)A segment for expectation value computation.
Represents computing <psi|H|psi> where psi is the quantum state and H is a Hamiltonian observable.
This segment bridges a quantum circuit (state preparation) to a classical expectation value.
Constructor¶
def __init__(
self,
operations: list[Operation] = list(),
input_refs: list[str] = list(),
output_refs: list[str] = list(),
hamiltonian_value: Value | None = None,
qubits_value: Value | None = None,
result_ref: str = '',
) -> NoneAttributes¶
hamiltonian_value: Value | Nonekind: SegmentKindqubits_value: Value | Noneresult_ref: str
ExpvalStep [source]¶
class ExpvalStepAn expectation-value execution step.
Constructor¶
def __init__(self, segment: ExpvalSegment, quantum_step_index: int = 0) -> NoneAttributes¶
quantum_step_index: intsegment: ExpvalSegment
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[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. |
definition | CallableDef | None | Optional 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,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueor an Oracle control-partition field has an invalid Python type.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width, or if Oracle invocation and definition control metadata disagree.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of relevant callable implementations.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return a conservative union of measurement-derived results.name: str Return the display name for this invocation.num_added_control_qubits: int Return controls introduced by a frontend control transform.num_body_external_control_qubits: int Return control operands generic lowering adds outside a base body.num_control_qubits: int Return the number of leading control-qubit operands.num_declared_control_qubits: int Return controls included in an opaque Oracle’s base definition.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
effective_body¶
def effective_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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 | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None, which only selects engine-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
require_body | bool | Whether 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name used for implementation selection. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
select_body¶
def select_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> CallableBodySelectionSelect 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
MeasureOperation [source]¶
class MeasureOperation(Operation)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
MeasureQFixedOperation [source]¶
class MeasureQFixedOperation(Operation)Measure a quantum fixed-point number.
This operation measures all qubits in a QFixed register and produces a Float result. During transpilation, this is lowered to individual MeasureOperations plus a DecodeQFixedOperation.
operands: [QFixed value (contains qubit_values in params)] results: [Float value]
Encoding:
For QPE phase (int_bits=0):
Qubits are stored least-significant first. For n qubits,
bit i has weight 2**(-n + i).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_bits: int = 0,
int_bits: int = 0,
) -> NoneAttributes¶
int_bits: intnum_bits: intoperation_kind: OperationKindsignature: Signature
MeasureQIntOperation [source]¶
class MeasureQIntOperation(Operation)Measure an unsigned quantum integer as one abstract hybrid operation.
The carrier sequence is least-significant-bit first: carrier i has
integer weight 2**i. Planning lowers this operation to one vector
measurement followed by a host-side DecodeQIntOperation.
The carrier width is not stored on the operation: it is derived from the
register operand’s type and carrier metadata through num_bits.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[Value] | Single QUIntType register operand. |
results | list[Value] | Single decoded UIntType result. |
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
num_bits: int | None Return the carrier count derived from the register operand.operation_kind: OperationKind Classify QInt measurement as a quantum-to-classical bridge.signature: Signature Return the packed-register measurement signature.
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()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
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.collectedConstructor¶
def __init__(self, predicate: Callable[[Operation], bool])Attributes¶
collected: list[Operation]
Methods¶
visit_operation¶
def visit_operation(self, op: Operation) -> NonePass [source]¶
class Pass(ABC, Generic[InputT, OutputT])Base class for all compiler passes.
Attributes¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute the pass transformation.
ProgramPlan [source]¶
class ProgramPlanExecution plan for a hybrid quantum/classical program.
Structure:
[Optional] Classical preprocessing (parameter computation, etc.)
Single quantum segment (REQUIRED)
[Optional] Expval segment OR classical postprocessing
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(),
) -> NoneAttributes¶
abi: ProgramABIboundaries: list[HybridBoundary]parameters: dict[str, Value]steps: list[ProgramStep]
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',
) -> NoneAttributes¶
axis: stroperation_kind: OperationKindsignature: Signature
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,
) -> NoneAttributes¶
kind: SegmentKindnum_qubits: intqubit_values: list[Value]
QuantumStep [source]¶
class QuantumStepA quantum execution step.
Constructor¶
def __init__(self, segment: QuantumSegment) -> NoneAttributes¶
segment: QuantumSegment
QubitAddress [source]¶
class QubitAddressTyped 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) -> NoneAttributes¶
element_index: int | Noneis_array_element: bool True if this address refers to an array element.uuid: str
Methods¶
from_composite_key¶
@classmethod
def from_composite_key(cls, key: str) -> QubitAddressParse 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) -> boolTrue if this address belongs to the given array.
with_element¶
def with_element(self, index: int) -> QubitAddressCreate an array-element address from this array’s base UUID.
ResetOperation [source]¶
class ResetOperation(Operation)Reset a qubit to the |0> state and return the fresh handle.
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
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()))(),
) -> NoneAttributes¶
elements: tuple[ValueLike, ...]logical_id: strmetadata: ValueMetadataname: strtype: ‘TupleType’uuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> TupleValueValue [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
ValueResolver [source]¶
class ValueResolverResolves Value objects to concrete indices or values.
Constructor¶
def __init__(self, parameters: set[str] | None = None)Create an emit-time resolver.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | set[str] | None | Names preserved as engine runtime parameters. Defaults to None. |
Attributes¶
parameters
Methods¶
bind_block_params¶
def bind_block_params(
self,
block_value: Any,
param_operands: list['Value'],
bindings: dict[str, Any],
*,
parameter_factory: Callable[[str, str], Any] | None = None,
) -> dict[str, Any]Create local bindings by matching block inputs to call-site operands.
Parameters:
| Name | Type | Description |
|---|---|---|
block_value | Any | Nested block whose classical/object inputs are bound. Objects without input_values receive no additional local bindings for compatibility with optional engine recipes. |
param_operands | list[Value] | Classical/object call-site operands in the controlled operation’s signature order. |
bindings | dict[str, Any] | Parent emit-time bindings used to resolve the call-site operands. |
parameter_factory | Callable[[str, str], Any] | None | Optional engine parameter factory used when an operand is a declared runtime parameter rather than a concrete binding. Defaults to None so standalone resolver use remains engine-neutral. |
Returns:
dict[str, Any] — dict[str, Any]: Parent bindings with each inner formal rebound under
both its UUID and sanctioned parameter-name key.
get_parameter_key¶
def get_parameter_key(self, value: 'Value', bindings: dict[str, Any]) -> str | NoneGet the engine parameter key for a symbolic scalar.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Scalar value or array element to identify. |
bindings | dict[str, Any] | Active bindings used to resolve element indices and slice offsets. |
Returns:
str | None — str | None: Scalar name or root-array indexed key, or None
when an array element’s root location is unresolved.
lookup_in_bindings¶
def lookup_in_bindings(
self,
value: Any,
bindings: dict[str, Any],
*,
index_array: bool = False,
) -> AnyCanonical resolution chain for a Value against bindings.
All other resolver methods (resolve_bound_value,
resolve_classical_value, resolve_int_value,
resolve_operand_for_binding) wrap this single chain. Centralizing
precedence here prevents the historical drift where one resolver
checked is_parameter before UUID and another checked it after,
which manifested as obscure binding failures when name-keyed writes
were dropped from the emit pass.
Resolution order (each step returns immediately on a hit):
valueis already a concrete Python scalar (nouuid).value.uuidis inbindings— return that. This is where emit-time-computed intermediates (evaluate_binop/evaluate_classical_predicateresults) and merge aliases live.A compile-time array or dict payload stored in typed metadata.
value.is_constant()— returnvalue.get_const().value.is_parameter()and its parameter name is inbindings— return that.(When
index_array=True)valueis an array element with a resolvable parent inbindings— index into it.A non-empty display name is present in
bindings. This is a compatibility bridge for programmatically constructed Values and older transforms that do not carry parameter metadata; UUID and explicit parameter provenance always take precedence.
Compiler-created temporaries are anonymous and compiler-internal writers use UUID keys, so the compatibility bridge cannot merge two same-named temporaries. Kernel parameters should normally resolve via explicit parameter metadata, while loop variables and intermediates remain UUID-keyed.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Any | The IR value (or already-concrete Python scalar) to resolve. |
bindings | dict[str, Any] | The active bindings dictionary. |
index_array | bool | When True, also resolve array-element accesses via parent_array indexing. Off by default because not all callers want to index into bound containers. |
Returns:
Any — The resolved Python value, or None if no step matched.
resolve_bound_value¶
def resolve_bound_value(self, value: 'Value', bindings: dict[str, Any]) -> AnyResolve a Value to its raw bound Python object.
Wraps :meth:lookup_in_bindings with index_array=True so that
arr[i] accesses against a bound container resolve to the
element. Does not coerce the result — callers that need a
numeric scalar should go through :meth:resolve_classical_value.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Value to resolve. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
Any — Raw bound object, or None when unresolved.
resolve_classical_value¶
def resolve_classical_value(self, value: 'Value', bindings: dict[str, Any]) -> AnyResolve a classical Value to a concrete Python value.
Numeric bindings are normalized to native Python scalars
regardless of whether they come from a direct binding or from
array-element indexing, so downstream isinstance(x, (int, float)) checks are stable when callers bind np.pi/4 or
the like. bool is preserved (not coerced to int).
Non-numeric values (Hamiltonians, strings, dict values, …)
pass through unchanged.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Classical value to resolve. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
Any — Resolved native scalar/object, or None when unresolved.
resolve_int_value¶
def resolve_int_value(self, val: Any, bindings: dict[str, Any]) -> int | NoneResolve a value to an integer, or None when unresolvable.
Unresolvable symbolic Values must return None. The previous
return 0 fallback caused silent loop elision when parameter
shape dims (gamma_dim0) reached this resolver without being
folded into constants — downstream loop-bound resolution saw 0 and
quietly emitted an empty loop. Returning None propagates the
failure to emit_for_unrolled, which converts it into a hard
compile error.
resolve_operand_for_binding¶
def resolve_operand_for_binding(self, operand: Any, bindings: dict[str, Any]) -> AnyResolve an operand to a concrete value for block parameter binding.
Used when calling a sub-block (e.g. a controlled-U body): each param operand at the call site must resolve to a value to seed the callee’s parameter bindings.
Parameters:
| Name | Type | Description |
|---|---|---|
operand | Any | Call-site value or already-concrete operand. |
bindings | dict[str, Any] | Parent emit-time bindings. |
Returns:
Any — Resolved value, or None when the operand is symbolic.
resolve_qubit_index¶
def resolve_qubit_index(self, v: 'Value', qubit_map: QubitMap, bindings: dict[str, Any]) -> int | NoneResolve a qubit value to its physical index.
Parameters:
| Name | Type | Description |
|---|---|---|
v | Value | Scalar or indexed qubit value. |
qubit_map | QubitMap | Physical resource mapping. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
int | None — int | None: Physical index, or None when unresolved.
resolve_qubit_index_detailed¶
def resolve_qubit_index_detailed(
self,
v: 'Value',
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> QubitResolutionResultResolve a Value to a physical qubit index with detailed failure info.
Parameters:
| Name | Type | Description |
|---|---|---|
v | Value | The qubit Value to resolve. May be a scalar qubit or an array element (possibly through a sliced view chain). |
qubit_map | QubitMap | Mapping from QubitAddress to physical qubit indices built by the resource allocator. |
bindings | dict[str, Any] | Active emit-time bindings used to resolve symbolic element indices and slice bounds. |
Returns:
QubitResolutionResult — Success with the physical index, or a
failure carrying a ResolutionFailureReason — including
NEGATIVE_INDEX when a resolved element index is negative
or a resolved slice bound violates the frontend contract
(non-negative start, positive step); composing those through
the affine map would silently address a wrong root slot.
resolve_slice_chain¶
def resolve_slice_chain(
self,
av: 'ArrayValue',
bindings: dict[str, Any],
*,
operation: str = 'emit',
) -> tuple['ArrayValue', int, int]Walk an ArrayValue’s slice_of chain and return root + affine map.
Composes the nested affine maps so that a view-local index i
corresponds to the root-space index start + step * i. For a
root ArrayValue (no slice_of chain), returns (av, 0, 1)
so callers can always apply the same formula uniformly.
Parameters:
| Name | Type | Description |
|---|---|---|
av | 'ArrayValue' | The possibly-sliced ArrayValue whose root and affine mapping should be resolved. |
bindings | dict[str, Any] | Compile-time parameter bindings; required when any slice_start / slice_step in the chain is symbolic. |
operation | str | Human-readable name of the enclosing emit operation. Used only in the EmitError message when a symbolic slice bound cannot be resolved. Defaults to "emit". |
Returns:
'ArrayValue' — Tuple (root_array, start, step) where root_array is
int — the underlying non-sliced ArrayValue, and start/step
int — are Python int values satisfying
tuple['ArrayValue', int, int] — view[i] == root_array[start + step * i].
Raises:
EmitError— If anyslice_startorslice_stepin the chain resolves to a non-numeric or unbound value, or to bounds violating the frontend contract (negative start or non-positive step).
Example:
>>> # For ``view = q[1::2]`` where ``q`` has 4 qubits:
>>> resolver.resolve_slice_chain(view_av, bindings={})
(q_av, 1, 2)qamomile.circuit.transpiler.passes.emit_support¶
Shared helpers for engine emission.
Overview¶
| Function | Description |
|---|---|
map_merge_outputs | Register merge output UUIDs to the same physical resources as their sources. |
remap_static_merge_outputs | Remap merge outputs for a compile-time constant IfOperation. |
resolve_condition_address | Resolve a runtime control-flow condition to its clbit_map key. |
resolve_if_condition | Resolve an if-condition to a compile-time boolean. |
resolve_qubit_key | Resolve a qubit Value to its allocation key. |
| Class | Description |
|---|---|
CompositeDecomposer | Decomposes composite gates into primitive operations. |
LoopAnalyzer | Analyze loop structures to determine an emission strategy. |
MultiControlAncillaPool | A reserved block of clean ancilla qubits for multi-control lowering. |
QubitAddress | Typed key for qubit/clbit physical-index maps. |
QubitResolutionResult | Result of attempting to resolve a qubit index. |
ResourceAllocator | Allocates qubit and classical bit indices from operations. |
ValueResolver | Resolves Value objects to concrete indices or values. |
Functions¶
map_merge_outputs [source]¶
def map_merge_outputs(
if_op: IfOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
resolve_scalar_qubit: Any = None,
bindings: dict[str, Any] | None = None,
resolver: ValueResolver | None = None,
reject_runtime_bit_mux: bool = False,
allowed_mixed_bit_outputs: frozenset[str] | set[str] | None = None,
) -> NoneRegister merge output UUIDs to the same physical resources as their sources.
Runtime-if counterpart of :func:remap_static_merge_outputs: both
branches may execute, so quantum merges are validated to sit on
identical physical resources, and classical Bit merges consolidate
both branches’ clbits only when the complete source-alias partition is
representable without overwriting an independently live value. Outputs
already registered are left untouched.
Parameters:
| Name | Type | Description |
|---|---|---|
if_op | IfOperation | The runtime if-else whose merged outputs need physical-resource registration; merges are read through iter_merges. |
qubit_map | QubitMap | Address-to-physical-qubit map, mutated in place. |
clbit_map | ClbitMap | Address-to-physical-clbit map, mutated in place. |
resolve_scalar_qubit | Any | Optional callable (source, qubit_map) -> int | None used to resolve scalar qubit sources that are not directly registered (e.g. array elements). Defaults to None, restricting resolution to direct and root-array lookups. |
bindings | dict[str, Any] | None | Active bindings used to fold a classical Bit merge source’s symbolic Vector[Bit] element index / slice bounds (e.g. an unrolled loop variable). Defaults to None (empty), restricting element resolution to constant indices. |
resolver | ValueResolver | None | Resolver used with bindings to fold non-constant element indices; None restricts to constants. Defaults to None. |
reject_runtime_bit_mux | bool | When True, raise EmitError for a runtime Bit merge that requires an at-runtime mux, mixes a pre-existing source with a branch-local measurement, or has incompatible source-sharing partitions across multiple outputs. Two all-branch-local source sets remain eligible only when their alias partitions match. Defaults to False. |
allowed_mixed_bit_outputs | frozenset[str] | set[str] | None | Merge result UUIDs whose pre-existing source is proven dead after the merge. This includes safe ordinary-if updates and phi-like loop condition remeasurements. Defaults to None. |
Raises:
EmitError— If a quantum merge’s branches resolve to different physical resources (or only one branch resolves), which a single-execution branch cannot realize; or, whenreject_runtime_bit_muxis True, if a runtimeBitmerge multiplexes two distinct pre-existing measured clbits/regions or has a non-identity branch source with no physical clbit (unrepresentable in the clbit-aliasing model), mixes external and branch-local provenance, or would collapse distinct merge slots.
remap_static_merge_outputs [source]¶
def remap_static_merge_outputs(
if_op: IfOperation,
condition_value: bool,
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any] | None = None,
resolver: ValueResolver | None = None,
) -> NoneRemap merge outputs for a compile-time constant IfOperation.
Registers each merged output under the physical resource of the branch selected by the resolved condition, so downstream operations referencing the merge output resolve to the surviving branch’s qubit / clbit. Outputs already registered are left untouched.
Parameters:
| Name | Type | Description |
|---|---|---|
if_op | IfOperation | The if-else whose condition resolved at compile time; merges are read through iter_merges. |
condition_value | bool | The resolved condition, selecting which branch’s source the outputs alias. |
qubit_map | QubitMap | Address-to-physical-qubit map, mutated in place. |
clbit_map | ClbitMap | Address-to-physical-clbit map, mutated in place. |
bindings | dict[str, Any] | None | Active bindings used to fold a merge source’s symbolic Vector[Bit] element index / slice bounds (e.g. an unrolled loop variable). Defaults to None (empty), restricting element resolution to constant indices. |
resolver | ValueResolver | None | Resolver used with bindings to fold non-constant element indices; None restricts to constants. Defaults to None. |
resolve_condition_address [source]¶
def resolve_condition_address(
condition: Value,
bindings: dict[str, Any],
resolver: ValueResolver | None,
) -> QubitAddressResolve 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:
| Name | Type | Description |
|---|---|---|
condition | Value | Condition operand of an IfOperation or WhileOperation, or an operand of a measurement-derived classical predicate (e.g. inside RuntimeClassicalExpr). |
bindings | dict[str, Any] | Active emit-time bindings used to resolve symbolic indices and slice bounds (loop variables, compile-time-bound parameters). |
resolver | ValueResolver | None | The active ValueResolver exposing resolve_int_value. None is accepted for early-emit pre-scans (e.g. CUDA-Q’s loop-carried clbit collector) that run before runtime bindings exist — only the constant path is taken in that case; symbolic indices and symbolic slice bounds fall through to the scalar UUID. |
Returns:
QubitAddress — Key suitable for looking up the condition in
clbit_map.
See resolve_condition_address_detailed for the resolution contract.
resolve_if_condition [source]¶
def resolve_if_condition(condition: Any, bindings: dict[str, Any]) -> bool | NoneResolve an if-condition to a compile-time boolean.
resolve_qubit_key [source]¶
def resolve_qubit_key(qubit: 'Value') -> tuple[QubitAddress | None, bool]Resolve a qubit Value to its allocation key.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | Value | Qubit value to resolve. Array elements with a constant index are resolved through their full slice_of chain to the root array address. |
Returns:
tuple[QubitAddress | None, bool] — tuple[QubitAddress | None, bool]: (address, is_array_element).
address is the root-space address for a resolvable array
element, None for an array element whose index or slice
bounds are symbolic at this binding-free stage, and a scalar
UUID address for non-array qubits. A negative constant index
(or an out-of-contract slice bound) also yields None:
resolve_root_qubit_address refuses it rather than letting it
silently address a wrong root slot.
Classes¶
CompositeDecomposer [source]¶
class CompositeDecomposerDecomposes composite gates into primitive operations.
Methods¶
iqft_structure¶
@staticmethod
def iqft_structure(n: int) -> list[tuple[str, tuple[int, ...], float | None]]qft_structure¶
@staticmethod
def qft_structure(n: int) -> list[tuple[str, tuple[int, ...], float | None]]LoopAnalyzer [source]¶
class LoopAnalyzerAnalyze loop structures to determine an emission strategy.
Methods¶
should_unroll¶
def should_unroll(self, op: ForOperation, bindings: dict[str, object]) -> boolDetermine whether a for-loop requires emit-time unrolling.
Parameters:
| Name | Type | Description |
|---|---|---|
op | ForOperation | Loop to analyze. |
bindings | dict[str, object] | Compile-time bindings available to nested-bound analysis. |
Returns:
bool — True when identities, carries, indices, predicates,
dictionary lookups, structural body parameters, or nested
bounds require concrete per-iteration evaluation.
MultiControlAncillaPool [source]¶
class MultiControlAncillaPoolA reserved block of clean ancilla qubits for multi-control lowering.
The pool occupies a contiguous range of physical qubit indices
appended after a quantum segment’s data qubits. A single moving
_offset gives it stack discipline so nested users never collide:
A leaf Toffoli cascade uncomputes every ancilla back to
|0>before it returns and holds nothing across gates, so it simplytakes from the current offset (atomic acquire-and-release).Batched controlled-block emission
try_holds the block’s AND ladder for the duration of the body walk, advancing the offset so the leaf cascades emitted inside the body draw from the qubits after the held ladder. The offset is rewound when thewithblock exits, so sibling batches reuse the same range.
Constructor¶
def __init__(self, first_index: int, count: int, *, counting: bool = False) -> NoneInitialize the pool.
Parameters:
| Name | Type | Description |
|---|---|---|
first_index | int | Physical index of the first reserved ancilla qubit. |
count | int | Number of reserved ancilla qubits. Must be non-negative. Ignored in counting mode. |
counting | bool | When True the pool is unbounded and only records the peak concurrent usage (take / try_hold never fail), so a dry-run emission can measure how many ancillas a real emission would need. Defaults to False. |
Raises:
ValueError— Ifcountis negative.
Attributes¶
count: int Return the number of reserved ancilla qubits.peak: int Return the peak concurrent usage recorded in counting mode.
Methods¶
take¶
def take(self, count: int) -> list[int] | NoneReturn count clean ancilla indices from the current offset.
Parameters:
| Name | Type | Description |
|---|---|---|
count | int | Number of ancilla qubits requested. |
Returns:
list[int] | None — list[int] | None: The next count reserved physical
indices starting at the current offset, or None when the
unheld remainder of the pool is smaller than the request
(an estimation bug surfaced by the caller). In counting
mode the request always succeeds and the peak usage is
recorded instead.
Raises:
ValueError— Ifcountis negative — a caller bug rather than a shortfall, which a plain> countcheck would silently turn into an empty list (and, viatry_hold, a negative offset).
try_hold¶
def try_hold(self, count: int) -> Iterator[list[int] | None]Reserve count ancillas for the duration of a with block.
Used by batched controlled-block emission to keep an AND ladder
live while the block body is walked under a single control. The
offset advances so that take/try_hold calls made inside
the body draw from the qubits after the held range, and it is
rewound on exit (including on exception) so sibling batches reuse
the same range. When the unheld remainder cannot satisfy the
request the caller receives None and must fall back to
per-gate emission rather than treating it as an error — the
demand estimate legitimately reserves fewer ancillas than a
naive batch would want (e.g. a statically empty loop body).
Parameters:
| Name | Type | Description |
|---|---|---|
count | int | Number of contiguous ancilla qubits to hold. |
Yields:
list[int] | None — list[int] | None: The held physical indices, or None when the
unheld remainder is too small to satisfy the request.
QubitAddress [source]¶
class QubitAddressTyped 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) -> NoneAttributes¶
element_index: int | Noneis_array_element: bool True if this address refers to an array element.uuid: str
Methods¶
from_composite_key¶
@classmethod
def from_composite_key(cls, key: str) -> QubitAddressParse 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) -> boolTrue if this address belongs to the given array.
with_element¶
def with_element(self, index: int) -> QubitAddressCreate an array-element address from this array’s base UUID.
QubitResolutionResult [source]¶
class QubitResolutionResultResult of attempting to resolve a qubit index.
Constructor¶
def __init__(
self,
success: bool,
index: int | None = None,
failure_reason: ResolutionFailureReason | None = None,
failure_details: str = '',
) -> NoneAttributes¶
failure_details: strfailure_reason: ResolutionFailureReason | Noneindex: int | Nonesuccess: bool
ResourceAllocator [source]¶
class ResourceAllocatorAllocates qubit and classical bit indices from operations.
This class handles the first pass of circuit emission: determining how many physical qubits and classical bits are needed and mapping Value UUIDs to their physical indices.
New physical indices are assigned via monotonic counters
(_next_qubit_index / _next_clbit_index) so that alias
entries — which reuse an existing physical index — never inflate
the counter. Using len(map) would cause sparse (gapped)
physical indices because alias keys increase the map size without
adding new physical resources.
Constructor¶
def __init__(self, resolver: ValueResolver | None = None) -> NoneInitialize allocator state.
Parameters:
| Name | Type | Description |
|---|---|---|
resolver | ValueResolver | None | Emit value resolver that carries runtime parameter names and binding lookup rules. Defaults to None, which creates a resolver without runtime parameters. |
Attributes¶
safe_mixed_bit_merge_outputs: frozenset[str] Return mixed-provenance Bit merges proven safe to alias.
Methods¶
allocate¶
def allocate(
self,
operations: list[Operation],
bindings: dict[str, Any] | None = None,
initial_qubit_map: QubitMap | None = None,
initial_clbit_map: ClbitMap | None = None,
public_output_uuids: frozenset[str] | set[str] | None = None,
) -> tuple[QubitMap, ClbitMap]Allocate qubit and clbit indices for all operations.
Parameters:
| Name | Type | Description |
|---|---|---|
operations | list[Operation] | Operations to allocate resources for. |
bindings | dict[str, Any] | None | Optional variable bindings for resolving dynamic sizes. Defaults to None (treated as an empty mapping). |
initial_qubit_map | QubitMap | None | Optional pre-populated qubit address mapping. Used by callers that need to seed the allocator with bindings established outside the operation list — for instance, the inner-block emitter in blockvalue_to_gate pre-allocates Vector[Qubit] input elements (the inner block has no QInitOperation for inputs, so per-element entries must be supplied here or the assertion in _allocate_gate fires). The map is copied; allocation continues from max(values) + 1 so new QInitOperation allocations inside operations do not collide. Defaults to None (treated as empty). |
initial_clbit_map | ClbitMap | None | Optional pre-populated clbit address mapping. Same semantics as initial_qubit_map but for classical bits. Defaults to None. |
public_output_uuids | frozenset[str] | set[str] | None | Program outputs that must remain live after this operation tree. Defaults to None, which disables dead-source approval for mixed prior/fresh Bit merges. |
Returns:
tuple[QubitMap, ClbitMap] — tuple[QubitMap, ClbitMap]: (qubit_map, clbit_map) where
each maps QubitAddress to a physical index. If an
initial map was supplied, its entries are preserved
verbatim in the returned map.
preserving_analysis_state¶
def preserving_analysis_state(self) -> Iterator[None]Preserve segment-level analysis state across a nested allocation.
allocate recomputes the measurement-taint set, the safe
mixed-merge allowlist, and the monotonic resource counters for
the operation list it receives. Nested sub-circuit emission
(controlled blocks, native inverses) reuses the SEGMENT
allocator on a different operation list mid-emission; without a
snapshot that leaves the sub-block’s analysis state behind, and
later resolve_iteration_maps replays of the enclosing
segment consult the wrong taint/allowlist sets — silently
disarming the runtime-mux guards.
Yields:
None — The nested allocation and emission run inside the
snapshot; the segment state is restored on exit even
when the nested work raises.
resolve_iteration_maps¶
def resolve_iteration_maps(
self,
operations: list[Operation],
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any],
) -> tuple[QubitMap, ClbitMap]Resolve resource aliases for one statically replayed iteration.
The initial allocation walks an unrolled loop body only once, before
its loop variable has a concrete value. A nested runtime condition
such as while measured[index]: therefore cannot select its root
clbit during that first walk. Replaying the allocator over copies of
the already-complete maps with the iteration binding present resolves
those aliases without allocating another physical resource. The
caller uses the returned maps for that iteration only; the same body
UUIDs may legitimately alias different measured-vector elements in
later iterations.
Parameters:
| Name | Type | Description |
|---|---|---|
operations | list[Operation] | Statically replayed loop body. |
qubit_map | QubitMap | Complete enclosing qubit map. |
clbit_map | ClbitMap | Complete enclosing clbit map. |
bindings | dict[str, Any] | Iteration-local UUID bindings, including the concrete range index or items-loop key/value identities. |
Returns:
tuple[QubitMap, ClbitMap] — tuple[QubitMap, ClbitMap]: Per-iteration copies with conditional
aliases resolved for the supplied bindings.
Raises:
EmitError— If resolving the bound body exposes an invalid quantum merge, classical-bit merge, array size, or while-condition lineage — or if replay unexpectedly allocates a new physical qubit or clbit instead of only adding or changing aliases.
ValueResolver [source]¶
class ValueResolverResolves Value objects to concrete indices or values.
Constructor¶
def __init__(self, parameters: set[str] | None = None)Create an emit-time resolver.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | set[str] | None | Names preserved as engine runtime parameters. Defaults to None. |
Attributes¶
parameters
Methods¶
bind_block_params¶
def bind_block_params(
self,
block_value: Any,
param_operands: list['Value'],
bindings: dict[str, Any],
*,
parameter_factory: Callable[[str, str], Any] | None = None,
) -> dict[str, Any]Create local bindings by matching block inputs to call-site operands.
Parameters:
| Name | Type | Description |
|---|---|---|
block_value | Any | Nested block whose classical/object inputs are bound. Objects without input_values receive no additional local bindings for compatibility with optional engine recipes. |
param_operands | list[Value] | Classical/object call-site operands in the controlled operation’s signature order. |
bindings | dict[str, Any] | Parent emit-time bindings used to resolve the call-site operands. |
parameter_factory | Callable[[str, str], Any] | None | Optional engine parameter factory used when an operand is a declared runtime parameter rather than a concrete binding. Defaults to None so standalone resolver use remains engine-neutral. |
Returns:
dict[str, Any] — dict[str, Any]: Parent bindings with each inner formal rebound under
both its UUID and sanctioned parameter-name key.
get_parameter_key¶
def get_parameter_key(self, value: 'Value', bindings: dict[str, Any]) -> str | NoneGet the engine parameter key for a symbolic scalar.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Scalar value or array element to identify. |
bindings | dict[str, Any] | Active bindings used to resolve element indices and slice offsets. |
Returns:
str | None — str | None: Scalar name or root-array indexed key, or None
when an array element’s root location is unresolved.
lookup_in_bindings¶
def lookup_in_bindings(
self,
value: Any,
bindings: dict[str, Any],
*,
index_array: bool = False,
) -> AnyCanonical resolution chain for a Value against bindings.
All other resolver methods (resolve_bound_value,
resolve_classical_value, resolve_int_value,
resolve_operand_for_binding) wrap this single chain. Centralizing
precedence here prevents the historical drift where one resolver
checked is_parameter before UUID and another checked it after,
which manifested as obscure binding failures when name-keyed writes
were dropped from the emit pass.
Resolution order (each step returns immediately on a hit):
valueis already a concrete Python scalar (nouuid).value.uuidis inbindings— return that. This is where emit-time-computed intermediates (evaluate_binop/evaluate_classical_predicateresults) and merge aliases live.A compile-time array or dict payload stored in typed metadata.
value.is_constant()— returnvalue.get_const().value.is_parameter()and its parameter name is inbindings— return that.(When
index_array=True)valueis an array element with a resolvable parent inbindings— index into it.A non-empty display name is present in
bindings. This is a compatibility bridge for programmatically constructed Values and older transforms that do not carry parameter metadata; UUID and explicit parameter provenance always take precedence.
Compiler-created temporaries are anonymous and compiler-internal writers use UUID keys, so the compatibility bridge cannot merge two same-named temporaries. Kernel parameters should normally resolve via explicit parameter metadata, while loop variables and intermediates remain UUID-keyed.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Any | The IR value (or already-concrete Python scalar) to resolve. |
bindings | dict[str, Any] | The active bindings dictionary. |
index_array | bool | When True, also resolve array-element accesses via parent_array indexing. Off by default because not all callers want to index into bound containers. |
Returns:
Any — The resolved Python value, or None if no step matched.
resolve_bound_value¶
def resolve_bound_value(self, value: 'Value', bindings: dict[str, Any]) -> AnyResolve a Value to its raw bound Python object.
Wraps :meth:lookup_in_bindings with index_array=True so that
arr[i] accesses against a bound container resolve to the
element. Does not coerce the result — callers that need a
numeric scalar should go through :meth:resolve_classical_value.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Value to resolve. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
Any — Raw bound object, or None when unresolved.
resolve_classical_value¶
def resolve_classical_value(self, value: 'Value', bindings: dict[str, Any]) -> AnyResolve a classical Value to a concrete Python value.
Numeric bindings are normalized to native Python scalars
regardless of whether they come from a direct binding or from
array-element indexing, so downstream isinstance(x, (int, float)) checks are stable when callers bind np.pi/4 or
the like. bool is preserved (not coerced to int).
Non-numeric values (Hamiltonians, strings, dict values, …)
pass through unchanged.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Classical value to resolve. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
Any — Resolved native scalar/object, or None when unresolved.
resolve_int_value¶
def resolve_int_value(self, val: Any, bindings: dict[str, Any]) -> int | NoneResolve a value to an integer, or None when unresolvable.
Unresolvable symbolic Values must return None. The previous
return 0 fallback caused silent loop elision when parameter
shape dims (gamma_dim0) reached this resolver without being
folded into constants — downstream loop-bound resolution saw 0 and
quietly emitted an empty loop. Returning None propagates the
failure to emit_for_unrolled, which converts it into a hard
compile error.
resolve_operand_for_binding¶
def resolve_operand_for_binding(self, operand: Any, bindings: dict[str, Any]) -> AnyResolve an operand to a concrete value for block parameter binding.
Used when calling a sub-block (e.g. a controlled-U body): each param operand at the call site must resolve to a value to seed the callee’s parameter bindings.
Parameters:
| Name | Type | Description |
|---|---|---|
operand | Any | Call-site value or already-concrete operand. |
bindings | dict[str, Any] | Parent emit-time bindings. |
Returns:
Any — Resolved value, or None when the operand is symbolic.
resolve_qubit_index¶
def resolve_qubit_index(self, v: 'Value', qubit_map: QubitMap, bindings: dict[str, Any]) -> int | NoneResolve a qubit value to its physical index.
Parameters:
| Name | Type | Description |
|---|---|---|
v | Value | Scalar or indexed qubit value. |
qubit_map | QubitMap | Physical resource mapping. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
int | None — int | None: Physical index, or None when unresolved.
resolve_qubit_index_detailed¶
def resolve_qubit_index_detailed(
self,
v: 'Value',
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> QubitResolutionResultResolve a Value to a physical qubit index with detailed failure info.
Parameters:
| Name | Type | Description |
|---|---|---|
v | Value | The qubit Value to resolve. May be a scalar qubit or an array element (possibly through a sliced view chain). |
qubit_map | QubitMap | Mapping from QubitAddress to physical qubit indices built by the resource allocator. |
bindings | dict[str, Any] | Active emit-time bindings used to resolve symbolic element indices and slice bounds. |
Returns:
QubitResolutionResult — Success with the physical index, or a
failure carrying a ResolutionFailureReason — including
NEGATIVE_INDEX when a resolved element index is negative
or a resolved slice bound violates the frontend contract
(non-negative start, positive step); composing those through
the affine map would silently address a wrong root slot.
resolve_slice_chain¶
def resolve_slice_chain(
self,
av: 'ArrayValue',
bindings: dict[str, Any],
*,
operation: str = 'emit',
) -> tuple['ArrayValue', int, int]Walk an ArrayValue’s slice_of chain and return root + affine map.
Composes the nested affine maps so that a view-local index i
corresponds to the root-space index start + step * i. For a
root ArrayValue (no slice_of chain), returns (av, 0, 1)
so callers can always apply the same formula uniformly.
Parameters:
| Name | Type | Description |
|---|---|---|
av | 'ArrayValue' | The possibly-sliced ArrayValue whose root and affine mapping should be resolved. |
bindings | dict[str, Any] | Compile-time parameter bindings; required when any slice_start / slice_step in the chain is symbolic. |
operation | str | Human-readable name of the enclosing emit operation. Used only in the EmitError message when a symbolic slice bound cannot be resolved. Defaults to "emit". |
Returns:
'ArrayValue' — Tuple (root_array, start, step) where root_array is
int — the underlying non-sliced ArrayValue, and start/step
int — are Python int values satisfying
tuple['ArrayValue', int, int] — view[i] == root_array[start + step * i].
Raises:
EmitError— If anyslice_startorslice_stepin the chain resolves to a non-numeric or unbound value, or to bounds violating the frontend contract (negative start or non-positive step).
Example:
>>> # For ``view = q[1::2]`` where ``q`` has 4 qubits:
>>> resolver.resolve_slice_chain(view_av, bindings={})
(q_av, 1, 2)qamomile.circuit.transpiler.passes.emit_support.cast_binop_emission¶
Cast and binary-operation emission helpers for StandardEmitPass.
Extracted from standard_emit.py to keep the main class focused on
gate-level dispatch. Each function mirrors the original method but takes
an explicit emit_pass parameter instead of self.
Overview¶
| Function | Description |
|---|---|
default_combine_symbolic | Default combine_symbolic for engines with arithmetic-capable Parameters. |
evaluate_binop | Evaluate a BinOp and store the result in bindings. |
evaluate_classical_predicate | Evaluate a CompOp/CondOp/NotOp at emit time and bind its boolean result. |
evaluate_unary_math | Evaluate concrete unary math used inside a controlled body. |
handle_cast | Handle CastOperation - update qubit_map without emitting gates. |
| Class | Description |
|---|---|
BinOp | Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN). |
CastOperation | Type cast operation for creating aliases over the same quantum resources. |
CompOp | Comparison operation (EQ, NEQ, LT, LE, GT, GE). |
CondOp | Conditional logical operation (AND, OR). |
NotOp | |
QubitAddress | Typed key for qubit/clbit physical-index maps. |
StandardEmitPass | Standard emit pass implementation using GateEmitter protocol. |
UnaryMathOp | Represent one pure unary mathematical expression. |
Functions¶
default_combine_symbolic [source]¶
def default_combine_symbolic(kind: 'BinOpKind', lhs: Any, rhs: Any) -> AnyDefault 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:
| Name | Type | Description |
|---|---|---|
kind | 'BinOpKind' | The BinOpKind to apply. |
lhs | Any | Left operand (numeric or engine Parameter / expression). |
rhs | Any | Right operand (same shape). |
Returns:
Any — lhs OP rhs for the matching operator. 0.0 / 0 for
Any — division-by-zero in the symbolic path so the caller can finish
Any — emission without aborting on a numerically degenerate case.
Any — None for unrecognised kind values, which the caller
Any — treats as a no-op.
evaluate_binop [source]¶
def evaluate_binop(emit_pass: 'StandardEmitPass', op: BinOp, bindings: dict[str, Any]) -> NoneEvaluate a BinOp and store the result in bindings.
Tries the shared fold_classical_op first for a clean concrete
fold (which already encapsulates the runtime-parameter guard).
Falls back to creating engine Parameter symbols and doing
symbolic arithmetic when one or both operands are runtime
parameters — that’s the path that lets rx(q, gamma * 2) produce
a circuit with a single Parameter("gamma") * 2 expression rather
than baking in a placeholder.
evaluate_classical_predicate [source]¶
def evaluate_classical_predicate(
emit_pass: 'StandardEmitPass',
op: 'CompOp | CondOp | NotOp',
bindings: dict[str, Any],
) -> NoneEvaluate a CompOp/CondOp/NotOp at emit time and bind its boolean result.
Mirrors the predicate evaluation already done by
compile_time_if_lowering and classical_executor so that an
IfOperation whose condition reaches emit unfolded — typically
because its operands depend on a loop variable bound only at emit time
by emit_for_items / emit_for_unrolled — can still be resolved
via resolve_if_condition.
Delegates the actual fold (including runtime-parameter guard and
strict scalar typing) to fold_classical_op so that all three
callers of the same kind dispatch share one implementation. There
is no symbolic-Parameter fallback for predicates: a runtime classical
expression cannot be expressed as a folded scalar, so the op is left
unbound and downstream emit handles it as a runtime condition.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | 'StandardEmitPass' | The active emit pass (for resolver access). |
op | 'CompOp | CondOp | NotOp' | The predicate op to evaluate. |
bindings | dict[str, Any] | Current parameter/loop-variable bindings; mutated in place on successful evaluation. No-op when operands are unresolvable (e.g. measurement bits) or evaluation raises. |
Returns:
None — None.
evaluate_unary_math [source]¶
def evaluate_unary_math(
emit_pass: 'StandardEmitPass',
op: UnaryMathOp,
bindings: dict[str, Any],
) -> NoneEvaluate concrete unary math used inside a controlled body.
An unresolved runtime unary expression is left unbound. Pure unused expressions can then disappear like ordinary dead classical work, while a later loop bound, branch, or gate-angle consumer still fails at its normal resolution boundary instead of receiving a fabricated value.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass used for value resolution and runtime-parameter classification. |
op | UnaryMathOp | Unary expression to evaluate. |
bindings | dict[str, Any] | Current emit-time values, updated when the expression resolves to a valid concrete scalar. |
handle_cast [source]¶
def handle_cast(emit_pass: 'StandardEmitPass', op: CastOperation, qubit_map: QubitMap) -> NoneHandle CastOperation - update qubit_map without emitting gates.
Classes¶
BinOp [source]¶
class BinOp(BinaryOperationBase)Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: BinOpKind | None = None,
) -> NoneAttributes¶
kind: BinOpKind | Noneoperation_kind: OperationKindsignature: Signature
CastOperation [source]¶
class CastOperation(Operation)Type cast operation for creating aliases over the same quantum resources.
This operation does NOT allocate new qubits. It creates a new Value that references the same underlying quantum resources with a different type.
Use cases:
Vector[Qubit] -> QFixed (after QPE, for phase measurement)
Vector[Qubit] -> QUInt (for quantum arithmetic)
QUInt -> QFixed (reinterpret bits with different encoding)
QFixed -> QUInt (reinterpret bits with different encoding)
operands: [source_value] - The value being cast results: [cast_result] - The new value with target type (same physical qubits)
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
source_type: ValueType | None = None,
target_type: ValueType | None = None,
qubit_mapping: list[str] = list(),
) -> NoneAttributes¶
num_qubits: int Number of qubits involved in the cast.operation_kind: OperationKind Cast stays in the same segment as its source (QUANTUM for quantum types).qubit_mapping: list[str]signature: Signature Return the type signature of this cast operation.source_type: ValueType | Nonetarget_type: ValueType | None
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,
) -> NoneAttributes¶
kind: CompOpKind | Noneoperation_kind: OperationKindsignature: Signature
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,
) -> NoneAttributes¶
kind: CondOpKind | Noneoperation_kind: OperationKindsignature: Signature
NotOp [source]¶
class NotOp(Operation)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
input: Valueoperation_kind: OperationKindoutput: Valuesignature: Signature
QubitAddress [source]¶
class QubitAddressTyped 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) -> NoneAttributes¶
element_index: int | Noneis_array_element: bool True if this address refers to an array element.uuid: str
Methods¶
from_composite_key¶
@classmethod
def from_composite_key(cls, key: str) -> QubitAddressParse 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) -> boolTrue if this address belongs to the given array.
with_element¶
def with_element(self, index: int) -> QubitAddressCreate an array-element address from this array’s base UUID.
StandardEmitPass [source]¶
class StandardEmitPass(EmitPass[T], Generic[T])Standard emit pass implementation using GateEmitter protocol.
This class provides orchestration for semantic IR traversal while
delegating circuit instruction construction to a GateEmitter. The
concrete compiler use is CircuitLoweringPass; SDK targets materialize
its immutable result instead of subclassing this class.
Parameters:
| Name | Type | Description |
|---|---|---|
gate_emitter | GateEmitter[T] | Instruction builder used during the semantic traversal. |
bindings | dict[str, Any] | None | Compile-time parameter bindings. |
parameters | list[str] | None | Parameter names preserved at runtime. |
composite_emitters | list[CompositeGateEmitter[T]] | None | Optional callable-preservation or lowering hooks. |
engine_name | str | None | Diagnostic 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¶
engine_name
UnaryMathOp [source]¶
class UnaryMathOp(Operation)Represent one pure unary mathematical expression.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[Value] | Single numeric input value. |
results | list[Value] | Single numeric result value. |
kind | UnaryMathOpKind | None | Mathematical operation to apply. |
Raises:
ValueError— Ifkindis missing or the operation does not have exactly one operand and one result.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: UnaryMathOpKind | None = None,
) -> NoneAttributes¶
input: Value Return the input value.kind: UnaryMathOpKind | Noneoperation_kind: OperationKind Classify the operation as classical.output: Value Return the output value.signature: Signature Return the typed unary signature.
qamomile.circuit.transpiler.passes.emit_support.clean_ancilla_toffoli¶
Pure arithmetic for the named clean-ancilla Toffoli ladder recipe.
Overview¶
| Function | Description |
|---|---|
clean_ancilla_toffoli_ladder | Return the arithmetic for the named clean-ancilla recipe. |
clean_ancilla_toffoli_ladder_or_empty | Return the named ladder arithmetic including its empty cases. |
| Class | Description |
|---|---|
CleanAncillaToffoliLadder | Describe the size of one clean-ancilla Toffoli ladder. |
Functions¶
clean_ancilla_toffoli_ladder [source]¶
def clean_ancilla_toffoli_ladder(num_controls: int | sp.Expr) -> CleanAncillaToffoliLadder[Any]Return the arithmetic for the named clean-ancilla recipe.
The caller owns recipe selection and must use the result on a branch where at least two controls are active. Keeping validation outside this helper lets symbolic resource expressions construct inactive Piecewise branches without prematurely rejecting them.
Parameters:
| Name | Type | Description |
|---|---|---|
num_controls | int | sp.Expr | Concrete or symbolic control count. |
Returns:
CleanAncillaToffoliLadder[Any] — CleanAncillaToffoliLadder[Any]: Compute, total-Toffoli, and clean-
ancilla requirements in the same numeric domain as the input.
clean_ancilla_toffoli_ladder_or_empty [source]¶
def clean_ancilla_toffoli_ladder_or_empty(num_controls: int | sp.Expr) -> CleanAncillaToffoliLadder[Any]Return the named ladder arithmetic including its empty cases.
The caller guarantees that num_controls is a nonnegative integer in
its concrete or symbolic domain. Zero and one control need no conjunction
ladder; two or more controls use the same named clean-ancilla recipe as
:func:clean_ancilla_toffoli_ladder.
Parameters:
| Name | Type | Description |
|---|---|---|
num_controls | int | sp.Expr | Concrete or symbolic nonnegative control count. |
Returns:
CleanAncillaToffoliLadder[Any] — CleanAncillaToffoliLadder[Any]: Nonnegative compute, total-Toffoli,
and clean-ancilla requirements.
Classes¶
CleanAncillaToffoliLadder [source]¶
class CleanAncillaToffoliLadder(Generic[_CountT])Describe the size of one clean-ancilla Toffoli ladder.
Parameters:
| Name | Type | Description |
|---|---|---|
compute_toffolis | _CountT | Toffoli count in the compute half. |
total_toffolis | _CountT | Combined compute and uncompute count. |
clean_ancillas | _CountT | Simultaneously required clean ancillas. |
Constructor¶
def __init__(
self,
compute_toffolis: _CountT,
total_toffolis: _CountT,
clean_ancillas: _CountT,
) -> NoneAttributes¶
clean_ancillas: _CountTcompute_toffolis: _CountTtotal_toffolis: _CountT
qamomile.circuit.transpiler.passes.emit_support.composite_decomposer¶
Composite gate decomposition helpers.
Overview¶
| Class | Description |
|---|---|
CompositeDecomposer | Decomposes composite gates into primitive operations. |
Classes¶
CompositeDecomposer [source]¶
class CompositeDecomposerDecomposes composite gates into primitive operations.
Methods¶
iqft_structure¶
@staticmethod
def iqft_structure(n: int) -> list[tuple[str, tuple[int, ...], float | None]]qft_structure¶
@staticmethod
def qft_structure(n: int) -> list[tuple[str, tuple[int, ...], float | None]]qamomile.circuit.transpiler.passes.emit_support.composite_gate_emission¶
Boxed callable emission helpers extracted from StandardEmitPass.
This module provides module-level functions for emitting boxed callables
(QFT, IQFT, QPE, custom composites, and opaque oracles) and their approximate
variants. Each function takes an
emit_pass parameter (a StandardEmitPass instance) in place of
self.
Overview¶
| Function | Description |
|---|---|
bracket_control_value | Bracket zero-valued controls with target-neutral Pauli-X gates. |
emit_approximate_iqft | Emit approximate IQFT with truncated rotations matching stdlib convention. |
emit_approximate_qft | Emit approximate QFT with truncated rotations matching stdlib convention. |
emit_callable_implementation_emitter | Emit using a selected callable implementation emitter, if present. |
emit_composite_fallback | Emit composite gate using decomposition. |
emit_composite_gate | Emit a boxed composite/oracle invocation. |
emit_invoke_operation | Emit an invoke operation. |
emit_iqft_manual | Emit inverse QFT using decomposition matching stdlib convention. |
emit_iqft_with_strategy | Emit IQFT considering strategy selection. |
emit_qft_manual | Emit QFT using decomposition matching stdlib convention. |
emit_qft_with_strategy | Emit QFT considering strategy selection. |
emit_qpe_manual | Emit QPE using manual decomposition. |
extract_phase_from_params | Extract a concrete phase parameter from a QPE operation. |
map_array_result_group | Map an array-valued result to a physical index group. |
update_composite_result_mapping | Update qubit_map for composite gate results. |
| Class | Description |
|---|---|
CallTransform | Describe the requested transform of a callable implementation. |
CompositeGateType | Classify standard boxed quantum callables. |
EmitError | Report an engine failure to emit one semantic operation. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
QubitAddress | Typed key for qubit/clbit physical-index maps. |
StandardEmitPass | Standard emit pass implementation using GateEmitter protocol. |
Functions¶
bracket_control_value [source]¶
def bracket_control_value(
emit_pass: 'StandardEmitPass',
circuit: Any,
control_indices: Sequence[int],
control_value: int | None,
) -> Generator[None, None, None]Bracket zero-valued controls with target-neutral Pauli-X gates.
The controlled operation inside the context remains an ordinary all-ones
control. Controls are interpreted LSB-first in their existing physical
order, so bit zero of control_value describes control_indices[0].
One bracket surrounds the complete operation, including integral powers
and vector-target broadcast.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass providing the gate emitter. |
circuit | Any | Circuit receiving the bracket gates. |
control_indices | Sequence[int] | Ordered physical control qubits. |
control_value | int | None | Required basis value, or None for the ordinary all-ones state. |
Yields:
None — Control returns while the zero-valued controls are inverted.
Raises:
TypeError— Ifcontrol_valueis not a PythonintorNone.ValueError— If the activation value does not fit the control width.
emit_approximate_iqft [source]¶
def emit_approximate_iqft(
emit_pass: 'StandardEmitPass',
circuit: Any,
qubit_indices: list[int],
truncation_depth: int,
) -> NoneEmit approximate IQFT with truncated rotations matching stdlib convention.
IQFT = QFT†. SWAP comes first (undoing QFT’s trailing SWAP), then for each qubit j (low-to-high), applies inverse controlled-phase rotations with lower-indexed qubits first (omitting exponents > truncation_depth), then H.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | 'StandardEmitPass' | The StandardEmitPass instance. |
circuit | Any | Target circuit |
qubit_indices | list[int] | Qubit indices |
truncation_depth | int | Maximum exponent for controlled phase gates |
emit_approximate_qft [source]¶
def emit_approximate_qft(
emit_pass: 'StandardEmitPass',
circuit: Any,
qubit_indices: list[int],
truncation_depth: int,
) -> NoneEmit approximate QFT with truncated rotations matching stdlib convention.
Processes qubits from highest index to lowest (same as exact QFT), applying H then controlled-phase rotations with lower-indexed qubits. Rotations with exponent > truncation_depth are omitted. Finishes with bit-reversal SWAPs.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | 'StandardEmitPass' | The StandardEmitPass instance. |
circuit | Any | Target circuit |
qubit_indices | list[int] | Qubit indices |
truncation_depth | int | Maximum exponent for controlled phase gates |
emit_callable_implementation_emitter [source]¶
def emit_callable_implementation_emitter(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: InvokeOperation,
qubit_indices: list[int],
bindings: dict[str, Any],
) -> boolEmit using a selected callable implementation emitter, if present.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted. |
op | InvokeOperation | Invocation to emit. |
qubit_indices | list[int] | Physical qubit indices in operand order. |
bindings | dict[str, Any] | Active emit bindings. |
Returns:
bool — True when the implementation emitter handled the operation.
Raises:
EmitError— If the selected emitter object does not provide a callableemitmethod.RuntimeError— If a declining emitter removed or replaced circuit state that existed before its append-only emission attempt.
emit_composite_fallback [source]¶
def emit_composite_fallback(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: InvokeOperation,
qubit_indices: list[int],
bindings: dict[str, Any],
) -> NoneEmit composite gate using decomposition.
If the operation has a strategy name, resolve it from the callable’s own implementation candidates.
emit_composite_gate [source]¶
def emit_composite_gate(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: InvokeOperation,
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> NoneEmit a boxed composite/oracle invocation.
Resolves each qubit operand through resolve_qubit_index_detailed
so that view-local operands (qft(q[1::2])) walk the slice_of
chain and map to the root parent’s physical qubits. Raises
EmitError if any operand cannot be resolved, rather than
silently dropping it (previously qft(view) emitted zero gates).
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
op | InvokeOperation | Composite or Oracle invocation to emit. |
qubit_map | QubitMap | Logical-to-physical map, mutated with results. |
bindings | dict[str, Any] | Bindings visible at the call site. |
Raises:
EmitError— If any control or target qubit operand fails to resolve to a physical qubit index, or an inverse body is absent.ValueError— If the selected implementation body disagrees with the invocation contract.
emit_invoke_operation [source]¶
def emit_invoke_operation(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: InvokeOperation,
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> NoneEmit an invoke operation.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted. |
op | InvokeOperation | Invocation to emit. |
qubit_map | QubitMap | Current qubit allocation map. |
bindings | dict[str, Any] | Active emit bindings. |
Raises:
EmitError— If the invocation is opaque and has neither an executable body nor a selected native emitter.
emit_iqft_manual [source]¶
def emit_iqft_manual(emit_pass: 'StandardEmitPass', circuit: Any, qubit_indices: list[int]) -> NoneEmit inverse QFT using decomposition matching stdlib convention.
IQFT = QFT†. SWAP comes first (undoing QFT’s trailing SWAP), then for each qubit j (low-to-high), applies inverse controlled-phase rotations with all lower-indexed qubits k (angle = -π/2^(j-k)) first, then H.
emit_iqft_with_strategy [source]¶
def emit_iqft_with_strategy(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: InvokeOperation,
qubit_indices: list[int],
) -> NoneEmit IQFT considering strategy selection.
If approximate_kN is selected, omits rotations beyond depth N.
Otherwise falls back to standard IQFT.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The active emit pass whose emitter should receive decomposed IQFT gates. |
circuit | Any | Engine circuit being emitted. |
op | InvokeOperation | Invocation expected to be an IQFT. |
qubit_indices | list[int] | Physical qubit indices for the IQFT target register. |
Raises:
EmitError— Ifopis not an IQFT composite operation.
emit_qft_manual [source]¶
def emit_qft_manual(emit_pass: 'StandardEmitPass', circuit: Any, qubit_indices: list[int]) -> NoneEmit QFT using decomposition matching stdlib convention.
Processes qubits from highest index to lowest: for each qubit j, applies H then controlled-phase rotations with all lower-indexed qubits k (angle = π/2^(j-k)). Finishes with bit-reversal SWAPs.
emit_qft_with_strategy [source]¶
def emit_qft_with_strategy(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: InvokeOperation,
qubit_indices: list[int],
) -> NoneEmit QFT considering strategy selection.
If approximate_kN is selected, omits rotations beyond depth N.
Otherwise falls back to standard QFT.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The active emit pass whose emitter should receive decomposed QFT gates. |
circuit | Any | Engine circuit being emitted. |
op | InvokeOperation | Invocation expected to be a QFT. |
qubit_indices | list[int] | Physical qubit indices for the QFT target register. |
Raises:
EmitError— Ifopis not a QFT composite operation.
emit_qpe_manual [source]¶
def emit_qpe_manual(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: InvokeOperation,
qubit_indices: list[int],
bindings: dict[str, Any],
) -> NoneEmit QPE using manual decomposition.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The active emit pass whose emitter should receive decomposed QPE gates. |
circuit | Any | Engine circuit being emitted. |
op | InvokeOperation | Invocation expected to be a QPE. |
qubit_indices | list[int] | Physical qubit indices for counting and target registers, in operation operand order. |
bindings | dict[str, Any] | Emit-time concrete bindings used to resolve QPE block parameters or phase operands. |
Raises:
EmitError— Ifopis not a QPE composite operation.
extract_phase_from_params [source]¶
def extract_phase_from_params(
emit_pass: 'StandardEmitPass',
op: InvokeOperation,
bindings: dict[str, Any],
) -> float | NoneExtract a concrete phase parameter from a QPE operation.
Scans the operation’s parameter operands. The block-free QPE fallback models a single phase parameter, so more than one concrete numeric parameter is ambiguous and rejected instead of guessed.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The active emit pass whose resolver should resolve bound scalar and array-element operands. |
op | InvokeOperation | The QPE invocation. |
bindings | dict[str, Any] | Emit-time concrete bindings keyed by parameter name, value UUID, or loop-local variable name. |
Returns:
float | None — float | None: The resolved phase angle, or None when the phase
operand remains symbolic.
Raises:
EmitError— Ifopis not a QPE composite operation, or if multiple concrete numeric phase parameters are present.
map_array_result_group [source]¶
def map_array_result_group(result_uuid: str, index_group: list[int], index_map: PhysicalIndexMap) -> NoneMap an array-valued result to a physical index group.
Parameters:
| Name | Type | Description |
|---|---|---|
result_uuid | str | UUID of the array-valued result whose element addresses should be registered. |
index_group | list[int] | Physical indices for the result elements, in result-local element order. |
index_map | PhysicalIndexMap | Mutable physical-index map updated in place with element addresses and, when available, the base result address. |
update_composite_result_mapping [source]¶
def update_composite_result_mapping(
op: InvokeOperation,
qubit_groups: list[list[int]],
qubit_map: QubitMap,
) -> NoneUpdate qubit_map for composite gate results.
Parameters:
| Name | Type | Description |
|---|---|---|
op | InvokeOperation | Invocation whose quantum results should be mapped onto the unchanged physical slots of its operands. |
qubit_groups | list[list[int]] | Physical indices grouped per quantum operand. A scalar qubit contributes one index; a vector operand contributes one index per element. |
qubit_map | QubitMap | Mutable map updated in place. |
Classes¶
CallTransform [source]¶
class CallTransform(enum.Enum)Describe the requested transform of a callable implementation.
Attributes¶
CONTROLLEDCONTROLLED_INVERSEDIRECTINVERSEis_controlled: bool Return whether the transform adds coherent controls.is_inverse: bool Return whether the transform requests inverse application.
Methods¶
inverted¶
def inverted(self) -> CallTransformToggle inverse application while preserving coherent control.
Returns:
CallTransform — Transform with the inverse component toggled.
CompositeGateType [source]¶
class CompositeGateType(enum.Enum)Classify standard boxed quantum callables.
Attributes¶
CUSTOMIQFTQFTQPE
EmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
operation
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[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. |
definition | CallableDef | None | Optional 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,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueor an Oracle control-partition field has an invalid Python type.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width, or if Oracle invocation and definition control metadata disagree.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of relevant callable implementations.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return a conservative union of measurement-derived results.name: str Return the display name for this invocation.num_added_control_qubits: int Return controls introduced by a frontend control transform.num_body_external_control_qubits: int Return control operands generic lowering adds outside a base body.num_control_qubits: int Return the number of leading control-qubit operands.num_declared_control_qubits: int Return controls included in an opaque Oracle’s base definition.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
effective_body¶
def effective_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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 | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None, which only selects engine-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
require_body | bool | Whether 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name used for implementation selection. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
select_body¶
def select_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> CallableBodySelectionSelect 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
QubitAddress [source]¶
class QubitAddressTyped 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) -> NoneAttributes¶
element_index: int | Noneis_array_element: bool True if this address refers to an array element.uuid: str
Methods¶
from_composite_key¶
@classmethod
def from_composite_key(cls, key: str) -> QubitAddressParse 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) -> boolTrue if this address belongs to the given array.
with_element¶
def with_element(self, index: int) -> QubitAddressCreate an array-element address from this array’s base UUID.
StandardEmitPass [source]¶
class StandardEmitPass(EmitPass[T], Generic[T])Standard emit pass implementation using GateEmitter protocol.
This class provides orchestration for semantic IR traversal while
delegating circuit instruction construction to a GateEmitter. The
concrete compiler use is CircuitLoweringPass; SDK targets materialize
its immutable result instead of subclassing this class.
Parameters:
| Name | Type | Description |
|---|---|---|
gate_emitter | GateEmitter[T] | Instruction builder used during the semantic traversal. |
bindings | dict[str, Any] | None | Compile-time parameter bindings. |
parameters | list[str] | None | Parameter names preserved at runtime. |
composite_emitters | list[CompositeGateEmitter[T]] | None | Optional callable-preservation or lowering hooks. |
engine_name | str | None | Diagnostic 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¶
engine_name
qamomile.circuit.transpiler.passes.emit_support.condition_resolution¶
Helpers for compile-time condition resolution and merge remapping.
Overview¶
| Function | Description |
|---|---|
array_element_mapping | Collect physical indices for the elements of an array value. |
array_physical_region | Resolve a one-dimensional array to its ordered physical region. |
map_array_element_aliases | Map explicit array element aliases to a result array. |
map_merge_outputs | Register merge output UUIDs to the same physical resources as their sources. |
remap_static_merge_outputs | Remap merge outputs for a compile-time constant IfOperation. |
resolve_condition_address_detailed | Resolve a condition / source Value to its clbit_map key. |
resolve_if_condition | Resolve an if-condition to a compile-time boolean. |
resolve_qubit_key | Resolve a qubit Value to its allocation key. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
BitType | Type representing a classical bit. |
EmitError | Report an engine failure to emit one semantic operation. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
IfOperation | Represents an if-else conditional operation. |
MeasureOperation | |
MeasureVectorOperation | Measure a vector of qubits. |
ProjectOperation | Project a qubit in one Pauli basis and keep the projected state. |
QubitAddress | Typed key for qubit/clbit physical-index maps. |
UIntType | Type representing an unsigned integer. |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
ValueResolver | Resolves Value objects to concrete indices or values. |
Functions¶
array_element_mapping [source]¶
def array_element_mapping(source_uuid: str, index_map: Mapping[QubitAddress, int]) -> dict[int, int]Collect physical indices for the elements of an array value.
Parameters:
| Name | Type | Description |
|---|---|---|
source_uuid | str | UUID of the array whose element addresses should be collected. |
index_map | Mapping[QubitAddress, int] | Physical-index map to read. |
Returns:
dict[int, int] — dict[int, int]: Mapping from element index to physical index.
array_physical_region [source]¶
def array_physical_region(array: 'ArrayValue') -> tuple[str, tuple[int, ...]] | NoneResolve a one-dimensional array to its ordered physical region.
The region is expressed independently of SSA version UUIDs: the first
element is the root array’s logical_id and the second is the ordered
tuple of root-space indices addressed by the array. This makes a root
register and its full view compare equal while keeping partial, strided,
reordered, and different-root registers distinct.
Parameters:
| Name | Type | Description |
|---|---|---|
array | ArrayValue | Root array or nested sliced view to resolve. The array must be one-dimensional and have a compile-time integer length; every slice bound in its ancestry must also be constant. |
Returns:
tuple[str, tuple[int, ...]] | None — tuple[str, tuple[int, ...]] | None: (root_logical_id, indices)
when the complete ordered coverage is statically known, otherwise
None. Symbolic shapes or slice bounds remain unresolved so
callers can defer to emit-time physical mappings.
map_array_element_aliases [source]¶
def map_array_element_aliases(
result_uuid: str,
element_mapping: Mapping[int, int],
index_map: PhysicalIndexMap,
*,
map_base_address: bool = True,
) -> NoneMap explicit array element aliases to a result array.
Parameters:
| Name | Type | Description |
|---|---|---|
result_uuid | str | UUID of the result array that should receive the element aliases. |
element_mapping | Mapping[int, int] | Physical indices keyed by result element index. |
index_map | PhysicalIndexMap | Mutable physical-index map updated in place with missing result element addresses and, when requested, the result base address. |
map_base_address | bool | Whether to map the scalar base address for the result array to its lowest-index element. Defaults to True. |
map_merge_outputs [source]¶
def map_merge_outputs(
if_op: IfOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
resolve_scalar_qubit: Any = None,
bindings: dict[str, Any] | None = None,
resolver: ValueResolver | None = None,
reject_runtime_bit_mux: bool = False,
allowed_mixed_bit_outputs: frozenset[str] | set[str] | None = None,
) -> NoneRegister merge output UUIDs to the same physical resources as their sources.
Runtime-if counterpart of :func:remap_static_merge_outputs: both
branches may execute, so quantum merges are validated to sit on
identical physical resources, and classical Bit merges consolidate
both branches’ clbits only when the complete source-alias partition is
representable without overwriting an independently live value. Outputs
already registered are left untouched.
Parameters:
| Name | Type | Description |
|---|---|---|
if_op | IfOperation | The runtime if-else whose merged outputs need physical-resource registration; merges are read through iter_merges. |
qubit_map | QubitMap | Address-to-physical-qubit map, mutated in place. |
clbit_map | ClbitMap | Address-to-physical-clbit map, mutated in place. |
resolve_scalar_qubit | Any | Optional callable (source, qubit_map) -> int | None used to resolve scalar qubit sources that are not directly registered (e.g. array elements). Defaults to None, restricting resolution to direct and root-array lookups. |
bindings | dict[str, Any] | None | Active bindings used to fold a classical Bit merge source’s symbolic Vector[Bit] element index / slice bounds (e.g. an unrolled loop variable). Defaults to None (empty), restricting element resolution to constant indices. |
resolver | ValueResolver | None | Resolver used with bindings to fold non-constant element indices; None restricts to constants. Defaults to None. |
reject_runtime_bit_mux | bool | When True, raise EmitError for a runtime Bit merge that requires an at-runtime mux, mixes a pre-existing source with a branch-local measurement, or has incompatible source-sharing partitions across multiple outputs. Two all-branch-local source sets remain eligible only when their alias partitions match. Defaults to False. |
allowed_mixed_bit_outputs | frozenset[str] | set[str] | None | Merge result UUIDs whose pre-existing source is proven dead after the merge. This includes safe ordinary-if updates and phi-like loop condition remeasurements. Defaults to None. |
Raises:
EmitError— If a quantum merge’s branches resolve to different physical resources (or only one branch resolves), which a single-execution branch cannot realize; or, whenreject_runtime_bit_muxis True, if a runtimeBitmerge multiplexes two distinct pre-existing measured clbits/regions or has a non-identity branch source with no physical clbit (unrepresentable in the clbit-aliasing model), mixes external and branch-local provenance, or would collapse distinct merge slots.
remap_static_merge_outputs [source]¶
def remap_static_merge_outputs(
if_op: IfOperation,
condition_value: bool,
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any] | None = None,
resolver: ValueResolver | None = None,
) -> NoneRemap merge outputs for a compile-time constant IfOperation.
Registers each merged output under the physical resource of the branch selected by the resolved condition, so downstream operations referencing the merge output resolve to the surviving branch’s qubit / clbit. Outputs already registered are left untouched.
Parameters:
| Name | Type | Description |
|---|---|---|
if_op | IfOperation | The if-else whose condition resolved at compile time; merges are read through iter_merges. |
condition_value | bool | The resolved condition, selecting which branch’s source the outputs alias. |
qubit_map | QubitMap | Address-to-physical-qubit map, mutated in place. |
clbit_map | ClbitMap | Address-to-physical-clbit map, mutated in place. |
bindings | dict[str, Any] | None | Active bindings used to fold a merge source’s symbolic Vector[Bit] element index / slice bounds (e.g. an unrolled loop variable). Defaults to None (empty), restricting element resolution to constant indices. |
resolver | ValueResolver | None | Resolver used with bindings to fold non-constant element indices; None restricts to constants. Defaults to None. |
resolve_condition_address_detailed [source]¶
def resolve_condition_address_detailed(
condition: Value,
bindings: dict[str, Any],
resolver: ValueResolver | None = None,
) -> tuple[QubitAddress, bool]Resolve a condition / source Value to its clbit_map key.
Single source of truth (shared by control_flow_emission.emit_if /
emit_while, the Qiskit / CUDA-Q engines, ResourceAllocator’s
loop-carried / merge aliasing, and the merge-output mapping helpers here)
for turning a runtime control-flow condition — or a merge source Value —
into the address its classical bit is registered under.
Scalar measurement results register under QubitAddress(bit.uuid),
while a Vector[Bit] element s[i] (s = qmc.measure(register))
registers under QubitAddress(root_array.uuid, root_index). The
element index and every slice_start / slice_step along the
parent’s slice_of chain are resolved the same way — taken directly
when constant, otherwise folded through bindings via resolver —
and composed into the root index via root_index = start + step * view_local_index repeated along the chain.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | Value | The condition operand or merge source Value. |
bindings | dict[str, Any] | Active emit-time bindings used to fold symbolic indices / slice bounds. May be empty for callers that only have constant addresses to resolve (e.g. the allocator’s pre-emit pass). |
resolver | ValueResolver | None | Resolver exposing resolve_int_value; None restricts resolution to constants. Defaults to None. |
Returns:
tuple[QubitAddress, bool] — tuple[QubitAddress, bool]: (address, resolved_as_element).
resolved_as_element is True only when condition is a
Vector[Bit] element whose index (and any slice bounds)
resolved to concrete ints, giving the root-space
QubitAddress(root.uuid, root_index). It is False for a
plain scalar, or when an element’s index / slice bound could
not be resolved (the scalar UUID fallback). Callers that mutate
clbit_map should trust the address as a vector key only when
this flag is True, to avoid aliasing an unresolved element
onto an unrelated scalar slot.
resolve_if_condition [source]¶
def resolve_if_condition(condition: Any, bindings: dict[str, Any]) -> bool | NoneResolve an if-condition to a compile-time boolean.
resolve_qubit_key [source]¶
def resolve_qubit_key(qubit: 'Value') -> tuple[QubitAddress | None, bool]Resolve a qubit Value to its allocation key.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | Value | Qubit value to resolve. Array elements with a constant index are resolved through their full slice_of chain to the root array address. |
Returns:
tuple[QubitAddress | None, bool] — tuple[QubitAddress | None, bool]: (address, is_array_element).
address is the root-space address for a resolvable array
element, None for an array element whose index or slice
bounds are symbolic at this binding-free stage, and a scalar
UUID address for non-array qubits. A negative constant index
(or an out-of-contract slice bound) also yields None:
resolve_root_qubit_address refuses it rather than letting it
silently address a wrong root slot.
Classes¶
ArrayValue [source]¶
class ArrayValue(Value[T])An array of typed IR values.
When slice_of is set, this array is a strided view over another
array. Element accesses on a sliced ArrayValue resolve to
physical slots on the root parent via the affine map
parent_index = slice_start + slice_step * view_local_index,
applied recursively along slice_of chains. The emit-time
resolver walks this chain to produce the final qubit index; passes
that substitute or clone values must treat slice_of /
slice_start / slice_step as Value references that need to
track through the same mapping as parent_array.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
shape: tuple[Value, ...] = tuple(),
slice_of: 'ArrayValue | None' = None,
slice_start: 'Value | None' = None,
slice_step: 'Value | None' = None,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]BitType [source]¶
class BitType(ClassicalTypeMixin, ValueType)Type representing a classical bit.
EmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
operation
HasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[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()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
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()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
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',
) -> NoneAttributes¶
axis: stroperation_kind: OperationKindsignature: Signature
QubitAddress [source]¶
class QubitAddressTyped 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) -> NoneAttributes¶
element_index: int | Noneis_array_element: bool True if this address refers to an array element.uuid: str
Methods¶
from_composite_key¶
@classmethod
def from_composite_key(cls, key: str) -> QubitAddressParse 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) -> boolTrue if this address belongs to the given array.
with_element¶
def with_element(self, index: int) -> QubitAddressCreate an array-element address from this array’s base UUID.
UIntType [source]¶
class UIntType(ClassicalTypeMixin, ValueType)Type representing an unsigned integer.
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
ValueResolver [source]¶
class ValueResolverResolves Value objects to concrete indices or values.
Constructor¶
def __init__(self, parameters: set[str] | None = None)Create an emit-time resolver.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | set[str] | None | Names preserved as engine runtime parameters. Defaults to None. |
Attributes¶
parameters
Methods¶
bind_block_params¶
def bind_block_params(
self,
block_value: Any,
param_operands: list['Value'],
bindings: dict[str, Any],
*,
parameter_factory: Callable[[str, str], Any] | None = None,
) -> dict[str, Any]Create local bindings by matching block inputs to call-site operands.
Parameters:
| Name | Type | Description |
|---|---|---|
block_value | Any | Nested block whose classical/object inputs are bound. Objects without input_values receive no additional local bindings for compatibility with optional engine recipes. |
param_operands | list[Value] | Classical/object call-site operands in the controlled operation’s signature order. |
bindings | dict[str, Any] | Parent emit-time bindings used to resolve the call-site operands. |
parameter_factory | Callable[[str, str], Any] | None | Optional engine parameter factory used when an operand is a declared runtime parameter rather than a concrete binding. Defaults to None so standalone resolver use remains engine-neutral. |
Returns:
dict[str, Any] — dict[str, Any]: Parent bindings with each inner formal rebound under
both its UUID and sanctioned parameter-name key.
get_parameter_key¶
def get_parameter_key(self, value: 'Value', bindings: dict[str, Any]) -> str | NoneGet the engine parameter key for a symbolic scalar.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Scalar value or array element to identify. |
bindings | dict[str, Any] | Active bindings used to resolve element indices and slice offsets. |
Returns:
str | None — str | None: Scalar name or root-array indexed key, or None
when an array element’s root location is unresolved.
lookup_in_bindings¶
def lookup_in_bindings(
self,
value: Any,
bindings: dict[str, Any],
*,
index_array: bool = False,
) -> AnyCanonical resolution chain for a Value against bindings.
All other resolver methods (resolve_bound_value,
resolve_classical_value, resolve_int_value,
resolve_operand_for_binding) wrap this single chain. Centralizing
precedence here prevents the historical drift where one resolver
checked is_parameter before UUID and another checked it after,
which manifested as obscure binding failures when name-keyed writes
were dropped from the emit pass.
Resolution order (each step returns immediately on a hit):
valueis already a concrete Python scalar (nouuid).value.uuidis inbindings— return that. This is where emit-time-computed intermediates (evaluate_binop/evaluate_classical_predicateresults) and merge aliases live.A compile-time array or dict payload stored in typed metadata.
value.is_constant()— returnvalue.get_const().value.is_parameter()and its parameter name is inbindings— return that.(When
index_array=True)valueis an array element with a resolvable parent inbindings— index into it.A non-empty display name is present in
bindings. This is a compatibility bridge for programmatically constructed Values and older transforms that do not carry parameter metadata; UUID and explicit parameter provenance always take precedence.
Compiler-created temporaries are anonymous and compiler-internal writers use UUID keys, so the compatibility bridge cannot merge two same-named temporaries. Kernel parameters should normally resolve via explicit parameter metadata, while loop variables and intermediates remain UUID-keyed.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Any | The IR value (or already-concrete Python scalar) to resolve. |
bindings | dict[str, Any] | The active bindings dictionary. |
index_array | bool | When True, also resolve array-element accesses via parent_array indexing. Off by default because not all callers want to index into bound containers. |
Returns:
Any — The resolved Python value, or None if no step matched.
resolve_bound_value¶
def resolve_bound_value(self, value: 'Value', bindings: dict[str, Any]) -> AnyResolve a Value to its raw bound Python object.
Wraps :meth:lookup_in_bindings with index_array=True so that
arr[i] accesses against a bound container resolve to the
element. Does not coerce the result — callers that need a
numeric scalar should go through :meth:resolve_classical_value.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Value to resolve. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
Any — Raw bound object, or None when unresolved.
resolve_classical_value¶
def resolve_classical_value(self, value: 'Value', bindings: dict[str, Any]) -> AnyResolve a classical Value to a concrete Python value.
Numeric bindings are normalized to native Python scalars
regardless of whether they come from a direct binding or from
array-element indexing, so downstream isinstance(x, (int, float)) checks are stable when callers bind np.pi/4 or
the like. bool is preserved (not coerced to int).
Non-numeric values (Hamiltonians, strings, dict values, …)
pass through unchanged.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Classical value to resolve. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
Any — Resolved native scalar/object, or None when unresolved.
resolve_int_value¶
def resolve_int_value(self, val: Any, bindings: dict[str, Any]) -> int | NoneResolve a value to an integer, or None when unresolvable.
Unresolvable symbolic Values must return None. The previous
return 0 fallback caused silent loop elision when parameter
shape dims (gamma_dim0) reached this resolver without being
folded into constants — downstream loop-bound resolution saw 0 and
quietly emitted an empty loop. Returning None propagates the
failure to emit_for_unrolled, which converts it into a hard
compile error.
resolve_operand_for_binding¶
def resolve_operand_for_binding(self, operand: Any, bindings: dict[str, Any]) -> AnyResolve an operand to a concrete value for block parameter binding.
Used when calling a sub-block (e.g. a controlled-U body): each param operand at the call site must resolve to a value to seed the callee’s parameter bindings.
Parameters:
| Name | Type | Description |
|---|---|---|
operand | Any | Call-site value or already-concrete operand. |
bindings | dict[str, Any] | Parent emit-time bindings. |
Returns:
Any — Resolved value, or None when the operand is symbolic.
resolve_qubit_index¶
def resolve_qubit_index(self, v: 'Value', qubit_map: QubitMap, bindings: dict[str, Any]) -> int | NoneResolve a qubit value to its physical index.
Parameters:
| Name | Type | Description |
|---|---|---|
v | Value | Scalar or indexed qubit value. |
qubit_map | QubitMap | Physical resource mapping. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
int | None — int | None: Physical index, or None when unresolved.
resolve_qubit_index_detailed¶
def resolve_qubit_index_detailed(
self,
v: 'Value',
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> QubitResolutionResultResolve a Value to a physical qubit index with detailed failure info.
Parameters:
| Name | Type | Description |
|---|---|---|
v | Value | The qubit Value to resolve. May be a scalar qubit or an array element (possibly through a sliced view chain). |
qubit_map | QubitMap | Mapping from QubitAddress to physical qubit indices built by the resource allocator. |
bindings | dict[str, Any] | Active emit-time bindings used to resolve symbolic element indices and slice bounds. |
Returns:
QubitResolutionResult — Success with the physical index, or a
failure carrying a ResolutionFailureReason — including
NEGATIVE_INDEX when a resolved element index is negative
or a resolved slice bound violates the frontend contract
(non-negative start, positive step); composing those through
the affine map would silently address a wrong root slot.
resolve_slice_chain¶
def resolve_slice_chain(
self,
av: 'ArrayValue',
bindings: dict[str, Any],
*,
operation: str = 'emit',
) -> tuple['ArrayValue', int, int]Walk an ArrayValue’s slice_of chain and return root + affine map.
Composes the nested affine maps so that a view-local index i
corresponds to the root-space index start + step * i. For a
root ArrayValue (no slice_of chain), returns (av, 0, 1)
so callers can always apply the same formula uniformly.
Parameters:
| Name | Type | Description |
|---|---|---|
av | 'ArrayValue' | The possibly-sliced ArrayValue whose root and affine mapping should be resolved. |
bindings | dict[str, Any] | Compile-time parameter bindings; required when any slice_start / slice_step in the chain is symbolic. |
operation | str | Human-readable name of the enclosing emit operation. Used only in the EmitError message when a symbolic slice bound cannot be resolved. Defaults to "emit". |
Returns:
'ArrayValue' — Tuple (root_array, start, step) where root_array is
int — the underlying non-sliced ArrayValue, and start/step
int — are Python int values satisfying
tuple['ArrayValue', int, int] — view[i] == root_array[start + step * i].
Raises:
EmitError— If anyslice_startorslice_stepin the chain resolves to a non-numeric or unbound value, or to bounds violating the frontend contract (negative start or non-positive step).
Example:
>>> # For ``view = q[1::2]`` where ``q`` has 4 qubits:
>>> resolver.resolve_slice_chain(view_av, bindings={})
(q_av, 1, 2)qamomile.circuit.transpiler.passes.emit_support.control_batching¶
Own controlled-body batching policy for engine fallback emission.
Overview¶
| Function | Description |
|---|---|
classify_control_work | Return the shared coherent-control category for one IR operation. |
combine_control_batch_profiles | Combine sequential emission profiles up to the decision threshold. |
should_batch_controlled_body | Return whether engine fallback should share one AND carrier. |
static_controlled_batch_profile | Return context-free emission batching information for one operation. |
| Class | Description |
|---|---|
ControlBatchProfile | Describe resolved work and the engine’s exact-two-control choice. |
ControlWorkKind | Describe how an operation participates in coherent-control analysis. |
GateOperation | Quantum gate operation. |
GateOperationType |
Constants¶
CONTROL_BATCH_DIRECT_AT_TWO_CONTROLS:frozenset[GateOperationType]=frozenset({GateOperationType.X, GateOperationType.Z})CONTROL_BATCH_HEAVY_GATES:frozenset[GateOperationType]
Functions¶
classify_control_work [source]¶
def classify_control_work(operation: Operation) -> ControlWorkKindReturn the shared coherent-control category for one IR operation.
BOOKKEEPING means zero controlled quantum work, not that the operation
may be discarded. Emitters must still run bookkeeping semantics such as
classical evaluation, cast alias propagation, and deferred borrow-return
validation.
Parameters:
| Name | Type | Description |
|---|---|---|
operation | Operation | IR operation inside a coherently controlled body. |
Returns:
ControlWorkKind — Semantic category consumed by both estimation and
emission policy.
combine_control_batch_profiles [source]¶
def combine_control_batch_profiles(profiles: Iterable[ControlBatchProfile]) -> ControlBatchProfileCombine sequential emission profiles up to the decision threshold.
Parameters:
| Name | Type | Description |
|---|---|---|
profiles | Iterable[ControlBatchProfile] | Resolved operation profiles. |
Returns:
ControlBatchProfile — Capped work and the union of exact-two choices.
should_batch_controlled_body [source]¶
def should_batch_controlled_body(num_controls: int, *, profile: ControlBatchProfile) -> boolReturn whether engine fallback should share one AND carrier.
Parameters:
| Name | Type | Description |
|---|---|---|
num_controls | int | Concrete number of composed controls. |
profile | ControlBatchProfile | Context-resolved emission profile. |
Returns:
bool — Whether engine fallback should build one body-wide ladder.
static_controlled_batch_profile [source]¶
def static_controlled_batch_profile(operation: Operation) -> ControlBatchProfile | NoneReturn context-free emission batching information for one operation.
None means that emission must resolve classical state or a nested
callable before deciding the weight. Unknown operation kinds count as one
leaf so eligibility analysis never hides work rejected by the later walker.
Parameters:
| Name | Type | Description |
|---|---|---|
operation | Operation | Operation inside a controlled body. |
Returns:
ControlBatchProfile | None — ControlBatchProfile | None: Context-free emission profile, or None
when engine-specific value resolution is required.
Classes¶
ControlBatchProfile [source]¶
class ControlBatchProfileDescribe resolved work and the engine’s exact-two-control choice.
Parameters:
| Name | Type | Description |
|---|---|---|
weight | int | Controlled work clamped to zero, one, or two. |
selects_exact_two | bool | Whether the engine selects a shared carrier when exactly two outer controls are present. |
Constructor¶
def __init__(self, weight: int = 0, selects_exact_two: bool = False) -> NoneAttributes¶
decision_complete: bool Return whether later work cannot change the batching decision.selects_exact_two: boolweight: int
ControlWorkKind [source]¶
class ControlWorkKind(enum.Enum)Describe how an operation participates in coherent-control analysis.
Values:
BOOKKEEPING: The operation contributes no controlled quantum gate, but its validation or value/alias update may still have to execute. QUANTUM_LEAF: One primitive quantum gate whose decomposition policy is selected by the consumer. CONTEXT_DEPENDENT: A structured operation whose work must be resolved from its values, selected body, or nested regions. UNSUPPORTED: An operation outside the supported controlled-unitary language. Consumers keep it visible so their normal error path rejects it rather than silently dropping it.
Attributes¶
BOOKKEEPINGCONTEXT_DEPENDENTQUANTUM_LEAFUNSUPPORTED
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,
) -> NoneAttributes¶
gate_type: GateOperationType | Noneoperation_kind: OperationKindqubit_operands: list[Value] Qubit operands (excluding the theta parameter if present).signature: Signaturetheta: Value | None Angle parameter for rotation gates, orNonefor fixed gates.
Methods¶
fixed¶
@classmethod
def fixed(
cls,
gate_type: GateOperationType,
qubits: list[Value],
results: list[Value],
) -> 'GateOperation'Create a fixed gate (H, X, CX, SWAP, …) with no angle parameter.
rotation¶
@classmethod
def rotation(
cls,
gate_type: GateOperationType,
qubits: list[Value],
theta: Value,
results: list[Value],
) -> 'GateOperation'Create a rotation gate (RX, RY, RZ, P, CP, RZZ) with an angle.
GateOperationType [source]¶
class GateOperationType(enum.Enum)Attributes¶
CPCXCZHPRXRYRZRZZSSDGSWAPTTDGTOFFOLIXYZ
qamomile.circuit.transpiler.passes.emit_support.control_flow_emission¶
Control flow emission helpers for StandardEmitPass.
Extracted from standard_emit.py to keep the main class focused on
gate-level dispatch. Each function mirrors the original method but takes
an explicit emit_pass parameter instead of self.
These are the default implementations. Engine-specific emit passes
(e.g., QiskitEmitPass) may override the corresponding methods on
StandardEmitPass; calling super()._emit_for(...) etc. will
ultimately delegate here.
Overview¶
| Function | Description |
|---|---|
array_static_length | Resolve a one-dimensional array’s compile-time length. |
dict_param_key | Format the engine-parameter name for one entry of a Dict parameter. |
emit_for | Emit a for loop. |
emit_for_items | Emit for-items loop (always unrolled). |
emit_for_unrolled | Emit a range loop by replaying every iteration. |
emit_if | Emit if/else operation. |
emit_while | Emit while loop operation. |
evaluate_dict_getitem | Evaluate a DictGetItemOperation and store the result in bindings. |
join_runtime_condition_sources | Join mutually exclusive overwrite states after runtime control flow. |
map_merge_outputs | Register merge output UUIDs to the same physical resources as their sources. |
mark_updated_while_condition | Record that a while update may overwrite its initial snapshot clbit. |
register_classical_merge_aliases | Bind classical merge outputs to a concrete value when resolvable. |
register_merge_outputs | Register merge output UUIDs via the shared map_merge_outputs utility. |
reject_stale_runtime_condition | Reject rereading a measurement snapshot overwritten by an earlier loop. |
remap_static_merge_outputs | Remap merge outputs for a compile-time constant IfOperation. |
resolve_condition_address | Resolve a runtime control-flow condition to its clbit_map key. |
resolve_condition_address_detailed | Resolve a condition / source Value to its clbit_map key. |
resolve_dict_entries | Resolve DictValue to concrete (key, value) pairs. |
resolve_if_condition | Resolve an if-condition to a compile-time boolean. |
resolve_loop_bounds | Resolve for-loop bounds (start, stop, step) from operands. |
restore_runtime_condition_sources | Restore one runtime-control-flow path’s overwrite state. |
runtime_condition_source_key | Identify one immutable measurement snapshot and physical clbit. |
snapshot_runtime_condition_sources | Snapshot path-local measurement sources overwritten by while loops. |
validate_region_args | Validate the SSA identities owned by a loop’s region arguments. |
validated_loop_indexset | Build an engine-safe Python range for resolved loop bounds. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
BitType | Type representing a classical bit. |
DictGetItemOperation | Look up one entry of a Dict by a (possibly symbolic) key. |
EmitError | Report an engine failure to emit one semantic operation. |
ForItemsOperation | Represents iteration over dict/iterable items. |
ForOperation | Represents a for loop operation. |
IfOperation | Represents an if-else conditional operation. |
MeasureVectorOperation | Measure a vector of qubits. |
ParameterContainerKind | Classify the public container that owns one engine scalar slot. |
QInitOperation | Initialize the qubit |
QubitAddress | Typed key for qubit/clbit physical-index maps. |
RegionArg | Explicit loop-carried value on a loop operation (MLIR-style iter_arg). |
StandardEmitPass | Standard emit pass implementation using GateEmitter protocol. |
Value | A typed SSA value in the IR. |
ValueResolver | Resolves Value objects to concrete indices or values. |
WhileOperation | Represents a while loop operation. |
Functions¶
array_static_length [source]¶
def array_static_length(array: 'ArrayValue') -> int | NoneResolve a one-dimensional array’s compile-time length.
Parameters:
| Name | Type | Description |
|---|---|---|
array | ArrayValue | Array whose sole shape dimension is inspected. |
Returns:
int | None — int | None: Non-negative static length, or None when the array is not
one-dimensional, its length is symbolic/non-integral, or it is
malformed with a negative length. Boolean constants are rejected
even though bool is an int subclass.
dict_param_key [source]¶
def dict_param_key(dict_name: str, key: Any) -> strFormat 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:
| Name | Type | Description |
|---|---|---|
dict_name | str | The kernel argument name of the Dict parameter. |
key | Any | The looked-up key, already normalized (a plain int or a tuple of plain ints — see :func:normalize_dict_binding_key). |
Returns:
str — The engine parameter name, e.g. "coeffs[3]" for an int
key or "coeffs[(0, 1)]" for a tuple key.
emit_for [source]¶
def emit_for(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: ForOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any],
force_unroll: bool = False,
) -> NoneEmit a for loop.
emit_for_items [source]¶
def emit_for_items(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: ForItemsOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any],
) -> NoneEmit for-items loop (always unrolled).
This handles iteration over Dict items, e.g.: for (i, j), Jij in qmc.items(ising): ...
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The emit pass (for resolver access). |
circuit | Any | The engine circuit being built. |
op | ForItemsOperation | The for-items loop being unrolled. |
qubit_map | QubitMap | Current qubit address mapping. |
clbit_map | ClbitMap | Current classical bit address mapping. |
bindings | dict[str, Any] | Current emit-time bindings. |
Raises:
EmitError— If the iterated dict is a runtime parameter — its key structure is unknown at compile time, so the loop cannot be unrolled.ValueError— If the dict entries cannot be resolved for any other reason.
emit_for_unrolled [source]¶
def emit_for_unrolled(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: ForOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any],
) -> NoneEmit a range loop by replaying every iteration.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass and value resolver. |
circuit | Any | Engine circuit being constructed. |
op | ForOperation | Range loop to replay. |
qubit_map | QubitMap | Logical-to-physical qubit map. |
clbit_map | ClbitMap | Logical-to-physical classical-bit map. |
bindings | dict[str, Any] | Enclosing emit-time bindings, updated with carry results and the final loop-index identity. |
Returns:
None — Operations are appended to circuit in place.
Raises:
EmitError— If loop identities/carries are inconsistent or a carry cannot be resolved.ValueError— If the range bounds cannot be resolved for unrolling.
emit_if [source]¶
def emit_if(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: IfOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any],
) -> NoneEmit if/else operation.
Handles two condition types:
Compile-time constant (plain Python
int/boolfrom@qkernelAST transformer closure variables, constant-folded Values, or Values resolvable viabindings): the active branch is emitted unconditionally, the inactive branch is discarded. No enginec_if/if_testis needed.Runtime condition (measurement
Valuethat cannot be resolved at compile time): delegates to the engine’semit_if_start/emit_else_start/emit_if_endprotocol.
emit_while [source]¶
def emit_while(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: WhileOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any],
) -> NoneEmit while loop operation.
evaluate_dict_getitem [source]¶
def evaluate_dict_getitem(
emit_pass: 'StandardEmitPass',
op: DictGetItemOperation,
bindings: dict[str, Any],
) -> NoneEvaluate a DictGetItemOperation and store the result in bindings.
Resolves each key component (typically a for-items loop variable
bound by UUID in bindings), looks the key up in the dict’s
resolved entries, and writes the value into bindings under the
result UUID so downstream ops (BinOps feeding gate angles) can
consume it.
When the dict is a declared runtime parameter
(transpile(..., parameters=["coeffs"])), there are no entries to
look up; the resolved key instead names one engine parameter
(coeffs[3] / coeffs[(0, 1)]) which is stored under the
result UUID. Repeated lookups of the same key share one engine
parameter via _get_or_create_parameter.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The emit pass (for resolver access). |
op | DictGetItemOperation | The lookup op being evaluated. |
bindings | dict[str, Any] | Current emit-time bindings. |
Raises:
EmitError— If a key component or the dict entries cannot be resolved, or the key is not present in the dict.
join_runtime_condition_sources [source]¶
def join_runtime_condition_sources(emit_pass: 'StandardEmitPass', *paths: frozenset[tuple[str, int]] = ()) -> NoneJoin mutually exclusive overwrite states after runtime control flow.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Emit pass receiving the joined state. |
*paths | frozenset[tuple[str, int]] | Completed branch states. |
map_merge_outputs [source]¶
def map_merge_outputs(
if_op: IfOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
resolve_scalar_qubit: Any = None,
bindings: dict[str, Any] | None = None,
resolver: ValueResolver | None = None,
reject_runtime_bit_mux: bool = False,
allowed_mixed_bit_outputs: frozenset[str] | set[str] | None = None,
) -> NoneRegister merge output UUIDs to the same physical resources as their sources.
Runtime-if counterpart of :func:remap_static_merge_outputs: both
branches may execute, so quantum merges are validated to sit on
identical physical resources, and classical Bit merges consolidate
both branches’ clbits only when the complete source-alias partition is
representable without overwriting an independently live value. Outputs
already registered are left untouched.
Parameters:
| Name | Type | Description |
|---|---|---|
if_op | IfOperation | The runtime if-else whose merged outputs need physical-resource registration; merges are read through iter_merges. |
qubit_map | QubitMap | Address-to-physical-qubit map, mutated in place. |
clbit_map | ClbitMap | Address-to-physical-clbit map, mutated in place. |
resolve_scalar_qubit | Any | Optional callable (source, qubit_map) -> int | None used to resolve scalar qubit sources that are not directly registered (e.g. array elements). Defaults to None, restricting resolution to direct and root-array lookups. |
bindings | dict[str, Any] | None | Active bindings used to fold a classical Bit merge source’s symbolic Vector[Bit] element index / slice bounds (e.g. an unrolled loop variable). Defaults to None (empty), restricting element resolution to constant indices. |
resolver | ValueResolver | None | Resolver used with bindings to fold non-constant element indices; None restricts to constants. Defaults to None. |
reject_runtime_bit_mux | bool | When True, raise EmitError for a runtime Bit merge that requires an at-runtime mux, mixes a pre-existing source with a branch-local measurement, or has incompatible source-sharing partitions across multiple outputs. Two all-branch-local source sets remain eligible only when their alias partitions match. Defaults to False. |
allowed_mixed_bit_outputs | frozenset[str] | set[str] | None | Merge result UUIDs whose pre-existing source is proven dead after the merge. This includes safe ordinary-if updates and phi-like loop condition remeasurements. Defaults to None. |
Raises:
EmitError— If a quantum merge’s branches resolve to different physical resources (or only one branch resolves), which a single-execution branch cannot realize; or, whenreject_runtime_bit_muxis True, if a runtimeBitmerge multiplexes two distinct pre-existing measured clbits/regions or has a non-identity branch source with no physical clbit (unrepresentable in the clbit-aliasing model), mixes external and branch-local provenance, or would collapse distinct merge slots.
mark_updated_while_condition [source]¶
def mark_updated_while_condition(
emit_pass: 'StandardEmitPass',
operation: WhileOperation,
clbit_map: ClbitMap,
bindings: dict[str, Any],
) -> NoneRecord that a while update may overwrite its initial snapshot clbit.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Emit pass carrying path-local overwrite state. |
operation | WhileOperation | Emitted while operation. |
clbit_map | ClbitMap | Current per-iteration clbit aliases. |
bindings | dict[str, Any] | Active emit-time bindings. |
register_classical_merge_aliases [source]¶
def register_classical_merge_aliases(
emit_pass: 'StandardEmitPass',
op: IfOperation,
bindings: dict[str, Any],
resolved: bool | None,
) -> NoneBind 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:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The active emit pass (for resolver access). |
op | IfOperation | The if-else whose merged classical outputs should be bound; merges are read through iter_merges. |
bindings | dict[str, Any] | Current bindings; mutated in place to bind merge outputs. |
resolved | bool | None | True / 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,
) -> NoneRegister 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:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The active emit pass, providing the ValueResolver used for scalar / array-element resolution. |
op | IfOperation | The runtime if-else whose merged outputs are registered onto their physical clbits / qubits. |
qubit_map | QubitMap | Address-to-physical-qubit map, mutated in place. |
clbit_map | ClbitMap | Address-to-physical-clbit map, mutated in place. |
bindings | dict[str, Any] | None | Active 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:
EmitError— If a quantum merge’s branches resolve to different physical resources, or a runtime scalarBitmerge multiplexes two distinct pre-existing measured clbits (seemap_merge_outputs).
reject_stale_runtime_condition [source]¶
def reject_stale_runtime_condition(
emit_pass: 'StandardEmitPass',
condition: Value,
clbit_map: ClbitMap,
bindings: dict[str, Any],
) -> NoneReject rereading a measurement snapshot overwritten by an earlier loop.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Emit pass carrying path-local overwrite state. |
condition | Value | Runtime if/while condition about to be emitted. |
clbit_map | ClbitMap | Current per-iteration clbit aliases. |
bindings | dict[str, Any] | Active emit-time bindings. |
Raises:
EmitError— If an earlier runtime while update on the same control-flow path reused this immutable measurement snapshot’s clbit.
remap_static_merge_outputs [source]¶
def remap_static_merge_outputs(
if_op: IfOperation,
condition_value: bool,
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any] | None = None,
resolver: ValueResolver | None = None,
) -> NoneRemap merge outputs for a compile-time constant IfOperation.
Registers each merged output under the physical resource of the branch selected by the resolved condition, so downstream operations referencing the merge output resolve to the surviving branch’s qubit / clbit. Outputs already registered are left untouched.
Parameters:
| Name | Type | Description |
|---|---|---|
if_op | IfOperation | The if-else whose condition resolved at compile time; merges are read through iter_merges. |
condition_value | bool | The resolved condition, selecting which branch’s source the outputs alias. |
qubit_map | QubitMap | Address-to-physical-qubit map, mutated in place. |
clbit_map | ClbitMap | Address-to-physical-clbit map, mutated in place. |
bindings | dict[str, Any] | None | Active bindings used to fold a merge source’s symbolic Vector[Bit] element index / slice bounds (e.g. an unrolled loop variable). Defaults to None (empty), restricting element resolution to constant indices. |
resolver | ValueResolver | None | Resolver used with bindings to fold non-constant element indices; None restricts to constants. Defaults to None. |
resolve_condition_address [source]¶
def resolve_condition_address(
condition: Value,
bindings: dict[str, Any],
resolver: ValueResolver | None,
) -> QubitAddressResolve 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:
| Name | Type | Description |
|---|---|---|
condition | Value | Condition operand of an IfOperation or WhileOperation, or an operand of a measurement-derived classical predicate (e.g. inside RuntimeClassicalExpr). |
bindings | dict[str, Any] | Active emit-time bindings used to resolve symbolic indices and slice bounds (loop variables, compile-time-bound parameters). |
resolver | ValueResolver | None | The active ValueResolver exposing resolve_int_value. None is accepted for early-emit pre-scans (e.g. CUDA-Q’s loop-carried clbit collector) that run before runtime bindings exist — only the constant path is taken in that case; symbolic indices and symbolic slice bounds fall through to the scalar UUID. |
Returns:
QubitAddress — Key suitable for looking up the condition in
clbit_map.
See resolve_condition_address_detailed for the resolution contract.
resolve_condition_address_detailed [source]¶
def resolve_condition_address_detailed(
condition: Value,
bindings: dict[str, Any],
resolver: ValueResolver | None = None,
) -> tuple[QubitAddress, bool]Resolve a condition / source Value to its clbit_map key.
Single source of truth (shared by control_flow_emission.emit_if /
emit_while, the Qiskit / CUDA-Q engines, ResourceAllocator’s
loop-carried / merge aliasing, and the merge-output mapping helpers here)
for turning a runtime control-flow condition — or a merge source Value —
into the address its classical bit is registered under.
Scalar measurement results register under QubitAddress(bit.uuid),
while a Vector[Bit] element s[i] (s = qmc.measure(register))
registers under QubitAddress(root_array.uuid, root_index). The
element index and every slice_start / slice_step along the
parent’s slice_of chain are resolved the same way — taken directly
when constant, otherwise folded through bindings via resolver —
and composed into the root index via root_index = start + step * view_local_index repeated along the chain.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | Value | The condition operand or merge source Value. |
bindings | dict[str, Any] | Active emit-time bindings used to fold symbolic indices / slice bounds. May be empty for callers that only have constant addresses to resolve (e.g. the allocator’s pre-emit pass). |
resolver | ValueResolver | None | Resolver exposing resolve_int_value; None restricts resolution to constants. Defaults to None. |
Returns:
tuple[QubitAddress, bool] — tuple[QubitAddress, bool]: (address, resolved_as_element).
resolved_as_element is True only when condition is a
Vector[Bit] element whose index (and any slice bounds)
resolved to concrete ints, giving the root-space
QubitAddress(root.uuid, root_index). It is False for a
plain scalar, or when an element’s index / slice bound could
not be resolved (the scalar UUID fallback). Callers that mutate
clbit_map should trust the address as a vector key only when
this flag is True, to avoid aliasing an unresolved element
onto an unrelated scalar slot.
resolve_dict_entries [source]¶
def resolve_dict_entries(
emit_pass: 'StandardEmitPass',
dict_value: Any,
bindings: dict[str, Any],
) -> list[tuple[Any, Any]] | NoneResolve DictValue to concrete (key, value) pairs.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | 'StandardEmitPass' | The StandardEmitPass instance (for resolver access) |
dict_value | Any | The DictValue IR node being iterated |
bindings | dict[str, Any] | Current parameter bindings |
Returns:
list[tuple[Any, Any]] | None — List of (key, value) tuples, or None if cannot be resolved
resolve_if_condition [source]¶
def resolve_if_condition(condition: Any, bindings: dict[str, Any]) -> bool | NoneResolve an if-condition to a compile-time boolean.
resolve_loop_bounds [source]¶
def resolve_loop_bounds(
resolver: Any,
op: ForOperation,
bindings: dict[str, Any],
) -> tuple[int | None, int | None, int | None]Resolve for-loop bounds (start, stop, step) from operands.
Missing operands use defaults: start=0, stop=1, step=1. Returns None for bounds that cannot be resolved to concrete ints.
restore_runtime_condition_sources [source]¶
def restore_runtime_condition_sources(emit_pass: 'StandardEmitPass', sources: frozenset[tuple[str, int]]) -> NoneRestore one runtime-control-flow path’s overwrite state.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Emit pass whose state is restored. |
sources | frozenset[tuple[str, int]] | Snapshot to install. |
runtime_condition_source_key [source]¶
def runtime_condition_source_key(
condition: Value,
clbit_map: ClbitMap,
bindings: dict[str, Any],
resolver: ValueResolver,
) -> tuple[str, int] | NoneIdentify one immutable measurement snapshot and physical clbit.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | Value | Runtime condition Value to identify. |
clbit_map | ClbitMap | Current per-iteration clbit aliases. |
bindings | dict[str, Any] | Active emit-time bindings. |
resolver | ValueResolver | Resolver for symbolic element indices. |
Returns:
tuple[str, int] | None — tuple[str, int] | None: Structural source identity and physical clbit,
or None when the source cannot yet be resolved.
snapshot_runtime_condition_sources [source]¶
def snapshot_runtime_condition_sources(emit_pass: 'StandardEmitPass') -> frozenset[tuple[str, int]]Snapshot path-local measurement sources overwritten by while loops.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Emit 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:
| Name | Type | Description |
|---|---|---|
op | ForOperation | ForItemsOperation | WhileOperation | Loop operation whose region arguments should be validated. |
Returns:
tuple[RegionArg, ...] — tuple[RegionArg, ...]: The validated op.region_args tuple.
Raises:
ValueError— If result counts or positions disagree, slot types differ, or any loop-owned definition identity collides with another definition or with a region initializer/body yield.
validated_loop_indexset [source]¶
def validated_loop_indexset(start: int, stop: int, step: int) -> rangeBuild an engine-safe Python range for resolved loop bounds.
Parameters:
| Name | Type | Description |
|---|---|---|
start | int | Inclusive loop start. |
stop | int | Exclusive loop stop. |
step | int | Nonzero loop step. |
Returns:
range — The resolved loop index set when its cardinality fits Python’s
platform-sized sequence protocol.
Raises:
EmitError— Ifstepis zero or the range cardinality exceeds what Python/engine loop APIs can represent without overflow.
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,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]BitType [source]¶
class BitType(ClassicalTypeMixin, ValueType)Type representing a classical bit.
DictGetItemOperation [source]¶
class DictGetItemOperation(Operation)Look up one entry of a Dict by a (possibly symbolic) key.
This is the IR form of d[key] on a Dict handle. The key
components may be symbolic (e.g. loop variables of a for-items
loop); the lookup is resolved at emit time when the key values and
the dict’s bound data are both concrete.
operands: [DictValue, *key_component_values] results: [looked-up scalar value]
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
key_arity: int = 1,
) -> NoneAttributes¶
dict_value: Value Value: The DictValue being indexed (operands[0]).key_arity: intkey_values: tuple[Value, ...] tuple[Value, ...]: The key component values.operation_kind: OperationKindsignature: Signature
EmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
operation
ForItemsOperation [source]¶
class ForItemsOperation(HasNestedOps, Operation)Represents iteration over dict/iterable items.
Example:
for (i, j), Jij in qmc.items(ising):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]key_is_vector: boolkey_var_values: tuple[Value, ...] | Nonekey_vars: list[str]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]operation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signaturevalue_var: strvalue_var_value: Value | None
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the items-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt items-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationIfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
MeasureVectorOperation [source]¶
class MeasureVectorOperation(Operation)Measure a vector of qubits.
Takes a Vector[Qubit] (ArrayValue) and produces a Vector[Bit] (ArrayValue). This operation measures all qubits in the vector as a single operation.
operands: [ArrayValue of qubits] results: [ArrayValue of bits]
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
ParameterContainerKind [source]¶
class ParameterContainerKind(enum.StrEnum)Classify the public container that owns one engine scalar slot.
Attributes¶
ARRAYDICTSCALAR
QInitOperation [source]¶
class QInitOperation(Operation)Initialize the qubit
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
QubitAddress [source]¶
class QubitAddressTyped 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) -> NoneAttributes¶
element_index: int | Noneis_array_element: bool True if this address refers to an array element.uuid: str
Methods¶
from_composite_key¶
@classmethod
def from_composite_key(cls, key: str) -> QubitAddressParse 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) -> boolTrue if this address belongs to the given array.
with_element¶
def with_element(self, index: int) -> QubitAddressCreate an array-element address from this array’s base UUID.
RegionArg [source]¶
class RegionArgExplicit 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:
On iteration 0 the body reads
block_argbound toinit.After each iteration,
block_argis rebound to that iteration’syieldedvalue.After the loop,
resultholds the final carried value (initwhen the loop ran zero iterations).
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,
) -> NoneAttributes¶
block_arg: Valueinit: Valueresult: Valuevar_name: stryielded: Value
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:
| Name | Type | Description |
|---|---|---|
gate_emitter | GateEmitter[T] | Instruction builder used during the semantic traversal. |
bindings | dict[str, Any] | None | Compile-time parameter bindings. |
parameters | list[str] | None | Parameter names preserved at runtime. |
composite_emitters | list[CompositeGateEmitter[T]] | None | Optional callable-preservation or lowering hooks. |
engine_name | str | None | Diagnostic 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¶
engine_name
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueResolver [source]¶
class ValueResolverResolves Value objects to concrete indices or values.
Constructor¶
def __init__(self, parameters: set[str] | None = None)Create an emit-time resolver.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | set[str] | None | Names preserved as engine runtime parameters. Defaults to None. |
Attributes¶
parameters
Methods¶
bind_block_params¶
def bind_block_params(
self,
block_value: Any,
param_operands: list['Value'],
bindings: dict[str, Any],
*,
parameter_factory: Callable[[str, str], Any] | None = None,
) -> dict[str, Any]Create local bindings by matching block inputs to call-site operands.
Parameters:
| Name | Type | Description |
|---|---|---|
block_value | Any | Nested block whose classical/object inputs are bound. Objects without input_values receive no additional local bindings for compatibility with optional engine recipes. |
param_operands | list[Value] | Classical/object call-site operands in the controlled operation’s signature order. |
bindings | dict[str, Any] | Parent emit-time bindings used to resolve the call-site operands. |
parameter_factory | Callable[[str, str], Any] | None | Optional engine parameter factory used when an operand is a declared runtime parameter rather than a concrete binding. Defaults to None so standalone resolver use remains engine-neutral. |
Returns:
dict[str, Any] — dict[str, Any]: Parent bindings with each inner formal rebound under
both its UUID and sanctioned parameter-name key.
get_parameter_key¶
def get_parameter_key(self, value: 'Value', bindings: dict[str, Any]) -> str | NoneGet the engine parameter key for a symbolic scalar.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Scalar value or array element to identify. |
bindings | dict[str, Any] | Active bindings used to resolve element indices and slice offsets. |
Returns:
str | None — str | None: Scalar name or root-array indexed key, or None
when an array element’s root location is unresolved.
lookup_in_bindings¶
def lookup_in_bindings(
self,
value: Any,
bindings: dict[str, Any],
*,
index_array: bool = False,
) -> AnyCanonical resolution chain for a Value against bindings.
All other resolver methods (resolve_bound_value,
resolve_classical_value, resolve_int_value,
resolve_operand_for_binding) wrap this single chain. Centralizing
precedence here prevents the historical drift where one resolver
checked is_parameter before UUID and another checked it after,
which manifested as obscure binding failures when name-keyed writes
were dropped from the emit pass.
Resolution order (each step returns immediately on a hit):
valueis already a concrete Python scalar (nouuid).value.uuidis inbindings— return that. This is where emit-time-computed intermediates (evaluate_binop/evaluate_classical_predicateresults) and merge aliases live.A compile-time array or dict payload stored in typed metadata.
value.is_constant()— returnvalue.get_const().value.is_parameter()and its parameter name is inbindings— return that.(When
index_array=True)valueis an array element with a resolvable parent inbindings— index into it.A non-empty display name is present in
bindings. This is a compatibility bridge for programmatically constructed Values and older transforms that do not carry parameter metadata; UUID and explicit parameter provenance always take precedence.
Compiler-created temporaries are anonymous and compiler-internal writers use UUID keys, so the compatibility bridge cannot merge two same-named temporaries. Kernel parameters should normally resolve via explicit parameter metadata, while loop variables and intermediates remain UUID-keyed.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Any | The IR value (or already-concrete Python scalar) to resolve. |
bindings | dict[str, Any] | The active bindings dictionary. |
index_array | bool | When True, also resolve array-element accesses via parent_array indexing. Off by default because not all callers want to index into bound containers. |
Returns:
Any — The resolved Python value, or None if no step matched.
resolve_bound_value¶
def resolve_bound_value(self, value: 'Value', bindings: dict[str, Any]) -> AnyResolve a Value to its raw bound Python object.
Wraps :meth:lookup_in_bindings with index_array=True so that
arr[i] accesses against a bound container resolve to the
element. Does not coerce the result — callers that need a
numeric scalar should go through :meth:resolve_classical_value.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Value to resolve. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
Any — Raw bound object, or None when unresolved.
resolve_classical_value¶
def resolve_classical_value(self, value: 'Value', bindings: dict[str, Any]) -> AnyResolve a classical Value to a concrete Python value.
Numeric bindings are normalized to native Python scalars
regardless of whether they come from a direct binding or from
array-element indexing, so downstream isinstance(x, (int, float)) checks are stable when callers bind np.pi/4 or
the like. bool is preserved (not coerced to int).
Non-numeric values (Hamiltonians, strings, dict values, …)
pass through unchanged.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Classical value to resolve. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
Any — Resolved native scalar/object, or None when unresolved.
resolve_int_value¶
def resolve_int_value(self, val: Any, bindings: dict[str, Any]) -> int | NoneResolve a value to an integer, or None when unresolvable.
Unresolvable symbolic Values must return None. The previous
return 0 fallback caused silent loop elision when parameter
shape dims (gamma_dim0) reached this resolver without being
folded into constants — downstream loop-bound resolution saw 0 and
quietly emitted an empty loop. Returning None propagates the
failure to emit_for_unrolled, which converts it into a hard
compile error.
resolve_operand_for_binding¶
def resolve_operand_for_binding(self, operand: Any, bindings: dict[str, Any]) -> AnyResolve an operand to a concrete value for block parameter binding.
Used when calling a sub-block (e.g. a controlled-U body): each param operand at the call site must resolve to a value to seed the callee’s parameter bindings.
Parameters:
| Name | Type | Description |
|---|---|---|
operand | Any | Call-site value or already-concrete operand. |
bindings | dict[str, Any] | Parent emit-time bindings. |
Returns:
Any — Resolved value, or None when the operand is symbolic.
resolve_qubit_index¶
def resolve_qubit_index(self, v: 'Value', qubit_map: QubitMap, bindings: dict[str, Any]) -> int | NoneResolve a qubit value to its physical index.
Parameters:
| Name | Type | Description |
|---|---|---|
v | Value | Scalar or indexed qubit value. |
qubit_map | QubitMap | Physical resource mapping. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
int | None — int | None: Physical index, or None when unresolved.
resolve_qubit_index_detailed¶
def resolve_qubit_index_detailed(
self,
v: 'Value',
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> QubitResolutionResultResolve a Value to a physical qubit index with detailed failure info.
Parameters:
| Name | Type | Description |
|---|---|---|
v | Value | The qubit Value to resolve. May be a scalar qubit or an array element (possibly through a sliced view chain). |
qubit_map | QubitMap | Mapping from QubitAddress to physical qubit indices built by the resource allocator. |
bindings | dict[str, Any] | Active emit-time bindings used to resolve symbolic element indices and slice bounds. |
Returns:
QubitResolutionResult — Success with the physical index, or a
failure carrying a ResolutionFailureReason — including
NEGATIVE_INDEX when a resolved element index is negative
or a resolved slice bound violates the frontend contract
(non-negative start, positive step); composing those through
the affine map would silently address a wrong root slot.
resolve_slice_chain¶
def resolve_slice_chain(
self,
av: 'ArrayValue',
bindings: dict[str, Any],
*,
operation: str = 'emit',
) -> tuple['ArrayValue', int, int]Walk an ArrayValue’s slice_of chain and return root + affine map.
Composes the nested affine maps so that a view-local index i
corresponds to the root-space index start + step * i. For a
root ArrayValue (no slice_of chain), returns (av, 0, 1)
so callers can always apply the same formula uniformly.
Parameters:
| Name | Type | Description |
|---|---|---|
av | 'ArrayValue' | The possibly-sliced ArrayValue whose root and affine mapping should be resolved. |
bindings | dict[str, Any] | Compile-time parameter bindings; required when any slice_start / slice_step in the chain is symbolic. |
operation | str | Human-readable name of the enclosing emit operation. Used only in the EmitError message when a symbolic slice bound cannot be resolved. Defaults to "emit". |
Returns:
'ArrayValue' — Tuple (root_array, start, step) where root_array is
int — the underlying non-sliced ArrayValue, and start/step
int — are Python int values satisfying
tuple['ArrayValue', int, int] — view[i] == root_array[start + step * i].
Raises:
EmitError— If anyslice_startorslice_stepin the chain resolves to a non-numeric or unbound value, or to bounds violating the frontend contract (negative start or non-positive step).
Example:
>>> # For ``view = q[1::2]`` where ``q`` has 4 qubits:
>>> resolver.resolve_slice_chain(view_av, bindings={})
(q_av, 1, 2)WhileOperation [source]¶
class WhileOperation(HasNestedOps, Operation)Represents a while loop operation.
Only measurement-backed conditions are supported: the condition must
be a Bit value produced by qmc.measure(). Non-measurement
conditions (classical variables, constants, comparisons) are rejected
by ValidateWhileContractPass before reaching engine emit.
Example::
bit = qmc.measure(q)
while bit:
q = qmc.h(q)
bit = qmc.measure(q)Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
operations: list[Operation] = list(),
max_iterations: int | None = None,
loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
region_args: tuple[RegionArg, ...] = (),
captures: tuple[ValueBase, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]max_iterations: int | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the while body and its complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt while operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, rebind-record, and region-arg values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
qamomile.circuit.transpiler.passes.emit_support.control_value_emission¶
Shared emission support for computational-basis control values.
Overview¶
| Function | Description |
|---|---|
bracket_control_value | Bracket zero-valued controls with target-neutral Pauli-X gates. |
control_pattern_for_value | Return the LSB-first activation pattern for a control value. |
| Class | Description |
|---|---|
StandardEmitPass | Standard emit pass implementation using GateEmitter protocol. |
Functions¶
bracket_control_value [source]¶
def bracket_control_value(
emit_pass: 'StandardEmitPass',
circuit: Any,
control_indices: Sequence[int],
control_value: int | None,
) -> Generator[None, None, None]Bracket zero-valued controls with target-neutral Pauli-X gates.
The controlled operation inside the context remains an ordinary all-ones
control. Controls are interpreted LSB-first in their existing physical
order, so bit zero of control_value describes control_indices[0].
One bracket surrounds the complete operation, including integral powers
and vector-target broadcast.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass providing the gate emitter. |
circuit | Any | Circuit receiving the bracket gates. |
control_indices | Sequence[int] | Ordered physical control qubits. |
control_value | int | None | Required basis value, or None for the ordinary all-ones state. |
Yields:
None — Control returns while the zero-valued controls are inverted.
Raises:
TypeError— Ifcontrol_valueis not a PythonintorNone.ValueError— If the activation value does not fit the control width.
control_pattern_for_value [source]¶
def control_pattern_for_value(control_value: int | None, num_controls: int) -> tuple[int, ...]Return the LSB-first activation pattern for a control value.
Parameters:
| Name | Type | Description |
|---|---|---|
control_value | int | None | Required computational-basis value. None means the ordinary all-ones control state. |
num_controls | int | Concrete positive control-register width. |
Returns:
tuple[int, ...] — tuple[int, ...]: One 0/1 activation bit per flattened control,
with the first control represented by bit zero.
Raises:
TypeError— Ifcontrol_valueis not a PythonintorNone.ValueError— If the width or activation value is invalid.
Example:
>>> control_pattern_for_value(2, 2)
(0, 1)
>>> control_pattern_for_value(None, 2)
(1, 1)Classes¶
StandardEmitPass [source]¶
class StandardEmitPass(EmitPass[T], Generic[T])Standard emit pass implementation using GateEmitter protocol.
This class provides orchestration for semantic IR traversal while
delegating circuit instruction construction to a GateEmitter. The
concrete compiler use is CircuitLoweringPass; SDK targets materialize
its immutable result instead of subclassing this class.
Parameters:
| Name | Type | Description |
|---|---|---|
gate_emitter | GateEmitter[T] | Instruction builder used during the semantic traversal. |
bindings | dict[str, Any] | None | Compile-time parameter bindings. |
parameters | list[str] | None | Parameter names preserved at runtime. |
composite_emitters | list[CompositeGateEmitter[T]] | None | Optional callable-preservation or lowering hooks. |
engine_name | str | None | Diagnostic 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¶
engine_name
qamomile.circuit.transpiler.passes.emit_support.controlled_block_support¶
Prepare reusable controlled blocks and map their quantum operands.
Overview¶
| Function | Description |
|---|---|
block_parameter_binding_keys | Return the sanctioned emit-binding keys for an inner formal. |
blockvalue_to_gate | Convert a Block to an engine gate. |
map_array_result_group | Map an array-valued result to a physical index group. |
pair_block_parameter_operands | Pair a block’s classical/object inputs with call-site operands. |
| Class | Description |
|---|---|
Block | Unified block representation for all pipeline stages. |
BlockKind | Classification of block structure for pipeline stages. |
ConcreteControlledU | Controlled-U with concrete (int) number of controls. |
EmitError | Report an engine failure to emit one semantic operation. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
QubitAddress | Typed key for qubit/clbit physical-index maps. |
StandardEmitPass | Standard emit pass implementation using GateEmitter protocol. |
Value | A typed SSA value in the IR. |
ValueResolver | Resolves Value objects to concrete indices or values. |
Functions¶
block_parameter_binding_keys [source]¶
def block_parameter_binding_keys(parameter: ValueBase) -> tuple[str, ...]Return the sanctioned emit-binding keys for an inner formal.
Emit resolution accepts a kernel parameter name before its UUID for public API compatibility, so an operation-owned fresh scope must write both keys. Keeping the key choice here prevents individual emit paths from reviving a parent binding that merely shares the inner formal’s display name.
Parameters:
| Name | Type | Description |
|---|---|---|
parameter | ValueBase | Classical/object formal input being bound. |
Returns:
tuple[str, ...] — tuple[str, ...]: UUID followed by the formal parameter provenance name
and nonempty display-name compatibility key, without duplicates.
blockvalue_to_gate [source]¶
def blockvalue_to_gate(
emit_pass: 'StandardEmitPass',
block_value: Any,
num_qubits: int,
bindings: dict[str, Any],
input_operands: list[Any] | None = None,
operation_name: str = 'ControlledUOperation',
) -> AnyConvert a Block to an engine gate.
Pre-populates local_qubit_map with one entry per quantum input in
declaration order, then runs the allocator over the block’s body.
For Vector[Qubit] inputs (ArrayValue with a quantum element
type) the entry expands into per-element QubitAddress(uuid, i)
keys — the inner block has no QInitOperation for inputs, so
without these the allocator’s element-resolution assertion fires for
every qs[i] reference in the body.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The emit pass driving the conversion. Used for its _allocator, _emitter, _resolver, and _emit_operations. |
block_value | Any | The inner block to convert. Expected to expose operations and input_values; anything else returns None (the caller falls back to gate-by-gate decomposition). |
num_qubits | int | Total physical qubits the resulting gate will occupy in the parent circuit. Used as the fallback length for a single Vector[Qubit] input whose shape is symbolic and unresolvable from bindings, and as the sub-circuit width when the block has no qubit-producing operations. |
bindings | dict[str, Any] | Parameter bindings forwarded to the allocator and _emit_operations. Also consulted when resolving Vector[Qubit] input shapes. |
input_operands | list[Any] | None | Optional call-site operands corresponding to block_value.input_values. Quantum operands propagate actual Vector[Qubit] shapes into the nested block before the vector-aware input qubit map is populated; classical operands are resolved into local bindings before the nested block is emitted. Defaults to None. |
operation_name | str | Operation name used in diagnostics when input binding fails. Defaults to "ControlledUOperation". |
Returns:
Any — An engine gate object produced by
emit_pass._emitter.circuit_to_gate, or None when the
conversion is unable to proceed (missing operations,
allocator / emitter exception, etc.) so the caller can fall
back to gate-by-gate emission.
map_array_result_group [source]¶
def map_array_result_group(result_uuid: str, index_group: list[int], index_map: PhysicalIndexMap) -> NoneMap an array-valued result to a physical index group.
Parameters:
| Name | Type | Description |
|---|---|---|
result_uuid | str | UUID of the array-valued result whose element addresses should be registered. |
index_group | list[int] | Physical indices for the result elements, in result-local element order. |
index_map | PhysicalIndexMap | Mutable physical-index map updated in place with element addresses and, when available, the base result address. |
pair_block_parameter_operands [source]¶
def pair_block_parameter_operands(
block: Block,
param_operands: Sequence[ValueBase],
) -> list[tuple[ValueBase, ValueBase]]Pair a block’s classical/object inputs with call-site operands.
Both compile-time lowering and emission bind an operation-owned block’s non-quantum inputs by their declaration order. Keeping the filtering and pairing here ensures those stages cannot adopt different positional conventions.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Operation-owned block whose formal inputs define the declaration order. |
param_operands | Sequence[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 BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
ConcreteControlledU [source]¶
class ConcreteControlledU(ControlledUOperation)Controlled-U with concrete (int) number of controls.
Operand layout: [ctrl_0, ..., ctrl_n, tgt_0, ..., tgt_m, params...]
Result layout: [ctrl_0', ..., ctrl_n', tgt_0', ..., tgt_m']
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
power: int | Value = 1,
block: Block | None = None,
num_controls: int = 1,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
control_operands: list[Value]control_value: int | Nonenum_controls: intparam_operands: list[Value] Get classical/object operands after the concrete control prefix.signature: Signature Build the concrete controlled call signature.target_operands: list[Value] Return the wrapped callable’s target and parameter operands.
EmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
operation
HasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
QubitAddress [source]¶
class QubitAddressTyped 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) -> NoneAttributes¶
element_index: int | Noneis_array_element: bool True if this address refers to an array element.uuid: str
Methods¶
from_composite_key¶
@classmethod
def from_composite_key(cls, key: str) -> QubitAddressParse 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) -> boolTrue if this address belongs to the given array.
with_element¶
def with_element(self, index: int) -> QubitAddressCreate an array-element address from this array’s base UUID.
StandardEmitPass [source]¶
class StandardEmitPass(EmitPass[T], Generic[T])Standard emit pass implementation using GateEmitter protocol.
This class provides orchestration for semantic IR traversal while
delegating circuit instruction construction to a GateEmitter. The
concrete compiler use is CircuitLoweringPass; SDK targets materialize
its immutable result instead of subclassing this class.
Parameters:
| Name | Type | Description |
|---|---|---|
gate_emitter | GateEmitter[T] | Instruction builder used during the semantic traversal. |
bindings | dict[str, Any] | None | Compile-time parameter bindings. |
parameters | list[str] | None | Parameter names preserved at runtime. |
composite_emitters | list[CompositeGateEmitter[T]] | None | Optional callable-preservation or lowering hooks. |
engine_name | str | None | Diagnostic 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¶
engine_name
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueResolver [source]¶
class ValueResolverResolves Value objects to concrete indices or values.
Constructor¶
def __init__(self, parameters: set[str] | None = None)Create an emit-time resolver.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | set[str] | None | Names preserved as engine runtime parameters. Defaults to None. |
Attributes¶
parameters
Methods¶
bind_block_params¶
def bind_block_params(
self,
block_value: Any,
param_operands: list['Value'],
bindings: dict[str, Any],
*,
parameter_factory: Callable[[str, str], Any] | None = None,
) -> dict[str, Any]Create local bindings by matching block inputs to call-site operands.
Parameters:
| Name | Type | Description |
|---|---|---|
block_value | Any | Nested block whose classical/object inputs are bound. Objects without input_values receive no additional local bindings for compatibility with optional engine recipes. |
param_operands | list[Value] | Classical/object call-site operands in the controlled operation’s signature order. |
bindings | dict[str, Any] | Parent emit-time bindings used to resolve the call-site operands. |
parameter_factory | Callable[[str, str], Any] | None | Optional engine parameter factory used when an operand is a declared runtime parameter rather than a concrete binding. Defaults to None so standalone resolver use remains engine-neutral. |
Returns:
dict[str, Any] — dict[str, Any]: Parent bindings with each inner formal rebound under
both its UUID and sanctioned parameter-name key.
get_parameter_key¶
def get_parameter_key(self, value: 'Value', bindings: dict[str, Any]) -> str | NoneGet the engine parameter key for a symbolic scalar.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Scalar value or array element to identify. |
bindings | dict[str, Any] | Active bindings used to resolve element indices and slice offsets. |
Returns:
str | None — str | None: Scalar name or root-array indexed key, or None
when an array element’s root location is unresolved.
lookup_in_bindings¶
def lookup_in_bindings(
self,
value: Any,
bindings: dict[str, Any],
*,
index_array: bool = False,
) -> AnyCanonical resolution chain for a Value against bindings.
All other resolver methods (resolve_bound_value,
resolve_classical_value, resolve_int_value,
resolve_operand_for_binding) wrap this single chain. Centralizing
precedence here prevents the historical drift where one resolver
checked is_parameter before UUID and another checked it after,
which manifested as obscure binding failures when name-keyed writes
were dropped from the emit pass.
Resolution order (each step returns immediately on a hit):
valueis already a concrete Python scalar (nouuid).value.uuidis inbindings— return that. This is where emit-time-computed intermediates (evaluate_binop/evaluate_classical_predicateresults) and merge aliases live.A compile-time array or dict payload stored in typed metadata.
value.is_constant()— returnvalue.get_const().value.is_parameter()and its parameter name is inbindings— return that.(When
index_array=True)valueis an array element with a resolvable parent inbindings— index into it.A non-empty display name is present in
bindings. This is a compatibility bridge for programmatically constructed Values and older transforms that do not carry parameter metadata; UUID and explicit parameter provenance always take precedence.
Compiler-created temporaries are anonymous and compiler-internal writers use UUID keys, so the compatibility bridge cannot merge two same-named temporaries. Kernel parameters should normally resolve via explicit parameter metadata, while loop variables and intermediates remain UUID-keyed.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Any | The IR value (or already-concrete Python scalar) to resolve. |
bindings | dict[str, Any] | The active bindings dictionary. |
index_array | bool | When True, also resolve array-element accesses via parent_array indexing. Off by default because not all callers want to index into bound containers. |
Returns:
Any — The resolved Python value, or None if no step matched.
resolve_bound_value¶
def resolve_bound_value(self, value: 'Value', bindings: dict[str, Any]) -> AnyResolve a Value to its raw bound Python object.
Wraps :meth:lookup_in_bindings with index_array=True so that
arr[i] accesses against a bound container resolve to the
element. Does not coerce the result — callers that need a
numeric scalar should go through :meth:resolve_classical_value.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Value to resolve. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
Any — Raw bound object, or None when unresolved.
resolve_classical_value¶
def resolve_classical_value(self, value: 'Value', bindings: dict[str, Any]) -> AnyResolve a classical Value to a concrete Python value.
Numeric bindings are normalized to native Python scalars
regardless of whether they come from a direct binding or from
array-element indexing, so downstream isinstance(x, (int, float)) checks are stable when callers bind np.pi/4 or
the like. bool is preserved (not coerced to int).
Non-numeric values (Hamiltonians, strings, dict values, …)
pass through unchanged.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Classical value to resolve. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
Any — Resolved native scalar/object, or None when unresolved.
resolve_int_value¶
def resolve_int_value(self, val: Any, bindings: dict[str, Any]) -> int | NoneResolve a value to an integer, or None when unresolvable.
Unresolvable symbolic Values must return None. The previous
return 0 fallback caused silent loop elision when parameter
shape dims (gamma_dim0) reached this resolver without being
folded into constants — downstream loop-bound resolution saw 0 and
quietly emitted an empty loop. Returning None propagates the
failure to emit_for_unrolled, which converts it into a hard
compile error.
resolve_operand_for_binding¶
def resolve_operand_for_binding(self, operand: Any, bindings: dict[str, Any]) -> AnyResolve an operand to a concrete value for block parameter binding.
Used when calling a sub-block (e.g. a controlled-U body): each param operand at the call site must resolve to a value to seed the callee’s parameter bindings.
Parameters:
| Name | Type | Description |
|---|---|---|
operand | Any | Call-site value or already-concrete operand. |
bindings | dict[str, Any] | Parent emit-time bindings. |
Returns:
Any — Resolved value, or None when the operand is symbolic.
resolve_qubit_index¶
def resolve_qubit_index(self, v: 'Value', qubit_map: QubitMap, bindings: dict[str, Any]) -> int | NoneResolve a qubit value to its physical index.
Parameters:
| Name | Type | Description |
|---|---|---|
v | Value | Scalar or indexed qubit value. |
qubit_map | QubitMap | Physical resource mapping. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
int | None — int | None: Physical index, or None when unresolved.
resolve_qubit_index_detailed¶
def resolve_qubit_index_detailed(
self,
v: 'Value',
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> QubitResolutionResultResolve a Value to a physical qubit index with detailed failure info.
Parameters:
| Name | Type | Description |
|---|---|---|
v | Value | The qubit Value to resolve. May be a scalar qubit or an array element (possibly through a sliced view chain). |
qubit_map | QubitMap | Mapping from QubitAddress to physical qubit indices built by the resource allocator. |
bindings | dict[str, Any] | Active emit-time bindings used to resolve symbolic element indices and slice bounds. |
Returns:
QubitResolutionResult — Success with the physical index, or a
failure carrying a ResolutionFailureReason — including
NEGATIVE_INDEX when a resolved element index is negative
or a resolved slice bound violates the frontend contract
(non-negative start, positive step); composing those through
the affine map would silently address a wrong root slot.
resolve_slice_chain¶
def resolve_slice_chain(
self,
av: 'ArrayValue',
bindings: dict[str, Any],
*,
operation: str = 'emit',
) -> tuple['ArrayValue', int, int]Walk an ArrayValue’s slice_of chain and return root + affine map.
Composes the nested affine maps so that a view-local index i
corresponds to the root-space index start + step * i. For a
root ArrayValue (no slice_of chain), returns (av, 0, 1)
so callers can always apply the same formula uniformly.
Parameters:
| Name | Type | Description |
|---|---|---|
av | 'ArrayValue' | The possibly-sliced ArrayValue whose root and affine mapping should be resolved. |
bindings | dict[str, Any] | Compile-time parameter bindings; required when any slice_start / slice_step in the chain is symbolic. |
operation | str | Human-readable name of the enclosing emit operation. Used only in the EmitError message when a symbolic slice bound cannot be resolved. Defaults to "emit". |
Returns:
'ArrayValue' — Tuple (root_array, start, step) where root_array is
int — the underlying non-sliced ArrayValue, and start/step
int — are Python int values satisfying
tuple['ArrayValue', int, int] — view[i] == root_array[start + step * i].
Raises:
EmitError— If anyslice_startorslice_stepin the chain resolves to a non-numeric or unbound value, or to bounds violating the frontend contract (negative start or non-positive step).
Example:
>>> # For ``view = q[1::2]`` where ``q`` has 4 qubits:
>>> resolver.resolve_slice_chain(view_av, bindings={})
(q_av, 1, 2)qamomile.circuit.transpiler.passes.emit_support.controlled_emission¶
Controlled operation emission helpers extracted from StandardEmitPass.
This module provides module-level functions for emitting controlled-U
operations, controlled gates, and related helpers. Each function takes an
emit_pass parameter (a StandardEmitPass instance) in place of
self.
Primitive multi-control decomposition lives in
multi_control_gate_emission. Reusable block preparation and operand
mapping live in controlled_block_support; their names are re-exported
here for compatibility with existing internal extension points.
Note: emit_controlled_fallback and blockvalue_to_gate are called
via emit_pass._emit_controlled_fallback(...) and
emit_pass._blockvalue_to_gate(...) respectively, so that subclass
overrides (e.g. CudaqEmitPass) are respected.
Overview¶
| Function | Description |
|---|---|
allocate_controlled_workspaces | Reserve parent-circuit wires for fresh allocations in controlled bodies. |
blockvalue_to_gate | Convert a Block to an engine gate. |
bracket_control_value | Bracket zero-valued controls with target-neutral Pauli-X gates. |
build_controlled_block_qubit_map | Build a block-local qubit map backed by physical target indices. |
clean_ancilla_toffoli_ladder | Return the arithmetic for the named clean-ancilla recipe. |
coerce_nonnegative_integral | Normalize a real scalar with an integer value to a nonnegative integer. |
combine_control_batch_profiles | Combine sequential emission profiles up to the decision threshold. |
control_pattern_for_value | Return the LSB-first activation pattern for a control value. |
emit_controlled_block | Emit a controlled version of a block via the mapped walker. |
emit_controlled_composite_at_indices | Emit a composite gate under already-resolved outer controls. |
emit_controlled_fallback | Fallback emission for controlled-U when gate conversion fails. |
emit_controlled_gate | Emit a controlled version of a gate. |
emit_controlled_global_phase_operation | Emit a global phase as a relative phase under accumulated controls. |
emit_controlled_operations | Emit controlled versions of operations with operand mapping. |
emit_controlled_pauli_evolve | Emit exp(-i * gamma * H) under accumulated controls. |
emit_controlled_powers | Emit controlled-U^(2^k) operations. |
emit_controlled_u | Emit a controlled operation for every concrete operand layout. |
emit_controlled_u_multi_arg | Emit a SymbolicControlledU whose control prefix is multi-arg. |
emit_controlled_u_with_symbolic_indices | Emit a SymbolicControlledU whose control_indices is set. |
emit_custom_composite | Emit a custom composite gate with implementation. |
emit_multi_controlled_gate | Emit one gate under an arbitrary number of accumulated controls. |
emit_multi_controlled_on_clean_ancillas | Lower an irreducible multi-controlled gate via a Toffoli cascade. |
emit_single_controlled_primitive | Emit one singly-controlled single-qubit gate from a resolved angle. |
emit_static_controlled_if | Emit the selected branch of a static if under accumulated controls. |
evaluate_binop | Evaluate a BinOp and store the result in bindings. |
evaluate_classical_predicate | Evaluate a CompOp/CondOp/NotOp at emit time and bind its boolean result. |
evaluate_dict_getitem | Evaluate a DictGetItemOperation and store the result in bindings. |
evaluate_unary_math | Evaluate concrete unary math used inside a controlled body. |
handle_cast | Handle CastOperation - update qubit_map without emitting gates. |
is_identity_phase_angle | Return whether a concrete angle is exactly zero modulo two pi. |
map_array_result_group | Map an array-valued result to a physical index group. |
map_nested_controlled_u_results | Map a nested controlled-U’s result values to physical qubits. |
quantum_operand_widths | Decode exact quantum-operand widths from callable resource metadata. |
register_classical_merge_aliases | Bind classical merge outputs to a concrete value when resolvable. |
reject_duplicate_physical_indices | Reject a multi-qubit gate whose qubits resolve to the same physical qubit. |
remap_static_merge_outputs | Remap merge outputs for a compile-time constant IfOperation. |
replay_controlled_for | Replay one static range loop under accumulated quantum controls. |
resolve_angle_value | Resolve a bare angle Value to a concrete float or engine parameter. |
resolve_controlled_u_call | Resolve a (possibly nested) controlled-U call site to physical qubits. |
resolve_if_condition | Resolve an if-condition to a compile-time boolean. |
resolve_loop_bounds | Resolve for-loop bounds (start, stop, step) from operands. |
resolve_power | Resolve ControlledUOperation.power to a concrete integer. |
should_batch_controlled_body | Return whether engine fallback should share one AND carrier. |
static_controlled_batch_profile | Return context-free emission batching information for one operation. |
try_emit_batched_controlled_operations | Emit a controlled block body behind a single shared AND ladder. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
BinOp | Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN). |
Block | Unified block representation for all pipeline stages. |
CInitOperation | Initialize the classical values (const, arguments etc) |
CallTransform | Describe the requested transform of a callable implementation. |
CallableBodySelection | Describe one validated IR body selected for an invocation. |
CastOperation | Type cast operation for creating aliases over the same quantum resources. |
CompOp | Comparison operation (EQ, NEQ, LT, LE, GT, GE). |
ConcreteControlledU | Controlled-U with concrete (int) number of controls. |
CondOp | Conditional logical operation (AND, OR). |
ControlBatchProfile | Describe resolved work and the engine’s exact-two-control choice. |
ControlledUOperation | Base class for controlled-U operations. |
CountingEmitter | A no-op gate emitter that lets a real emission walk run for counting. |
DictGetItemOperation | Look up one entry of a Dict by a (possibly symbolic) key. |
EmitError | Report an engine failure to emit one semantic operation. |
ForOperation | Represents a for loop operation. |
GateOperation | Quantum gate operation. |
GateOperationType | |
GlobalPhaseOperation | Multiply the complete quantum state by exp(i * phase). |
HasNestedOps | Mixin for operations that contain nested operation lists. |
IfOperation | Represents an if-else conditional operation. |
InverseBlockOperation | Represent an inverse qkernel/block as a first-class IR operation. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
NotOp | |
PauliEvolveOp | Pauli evolution operation: exp(-i * gamma * H). |
QInitOperation | Initialize the qubit |
QubitAddress | Typed key for qubit/clbit physical-index maps. |
ReleaseSliceViewOperation | Mark a slice view’s borrow as explicitly returned to its parent. |
ResolvedControlledU | Physical resolution of one ControlledUOperation call site. |
ReturnOperation | Explicit return operation marking the end of a block with return values. |
ReturnQuantumArrayElementOperation | Validate a branch-selected quantum element’s array return at emit time. |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
SliceArrayOperation | Construct a strided view of an ArrayValue. |
StandardEmitPass | Standard emit pass implementation using GateEmitter protocol. |
StoreArrayElementOperation | Store a classical scalar into one element of a classical array. |
SymbolicControlledU | Controlled-U with symbolic (Value) number of controls. |
UnaryMathOp | Represent one pure unary mathematical expression. |
Value | A typed SSA value in the IR. |
Functions¶
allocate_controlled_workspaces [source]¶
def allocate_controlled_workspaces(
emit_pass: 'StandardEmitPass',
operations: list[Operation],
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any],
*,
_under_control: bool = False,
_active_invoke_bodies: set[int] | None = None,
) -> NoneReserve parent-circuit wires for fresh allocations in controlled bodies.
A reusable engine gate can only act on wires supplied by its call site.
When a controlled qkernel allocates private workspace, its body must
therefore be decomposed on the parent circuit and the workspace wires
must be included before that circuit’s width is fixed. This pre-emission
walk allocates those nested QInitOperation resources and publishes
their addresses in qubit_map for the controlled walker.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass and resource allocator. |
operations | list[Operation] | Segment operations to inspect recursively. |
qubit_map | QubitMap | Parent logical-to-physical map, mutated in place. |
clbit_map | ClbitMap | Parent classical map used to seed nested allocation. |
bindings | dict[str, Any] | Compile-time bindings visible in the segment. |
_under_control | bool | Whether operations are already reached by a controlled-body walker. Defaults to False. |
_active_invoke_bodies | set[int] | None | Definition-body identities on the active recursive path. Defaults to a fresh set. |
Raises:
EmitError— If a controlled body’s target footprint or workspace size cannot be resolved at transpile time.ValueError— If a selected callable implementation body disagrees with its invocation contract.
blockvalue_to_gate [source]¶
def blockvalue_to_gate(
emit_pass: 'StandardEmitPass',
block_value: Any,
num_qubits: int,
bindings: dict[str, Any],
input_operands: list[Any] | None = None,
operation_name: str = 'ControlledUOperation',
) -> AnyConvert a Block to an engine gate.
Pre-populates local_qubit_map with one entry per quantum input in
declaration order, then runs the allocator over the block’s body.
For Vector[Qubit] inputs (ArrayValue with a quantum element
type) the entry expands into per-element QubitAddress(uuid, i)
keys — the inner block has no QInitOperation for inputs, so
without these the allocator’s element-resolution assertion fires for
every qs[i] reference in the body.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The emit pass driving the conversion. Used for its _allocator, _emitter, _resolver, and _emit_operations. |
block_value | Any | The inner block to convert. Expected to expose operations and input_values; anything else returns None (the caller falls back to gate-by-gate decomposition). |
num_qubits | int | Total physical qubits the resulting gate will occupy in the parent circuit. Used as the fallback length for a single Vector[Qubit] input whose shape is symbolic and unresolvable from bindings, and as the sub-circuit width when the block has no qubit-producing operations. |
bindings | dict[str, Any] | Parameter bindings forwarded to the allocator and _emit_operations. Also consulted when resolving Vector[Qubit] input shapes. |
input_operands | list[Any] | None | Optional call-site operands corresponding to block_value.input_values. Quantum operands propagate actual Vector[Qubit] shapes into the nested block before the vector-aware input qubit map is populated; classical operands are resolved into local bindings before the nested block is emitted. Defaults to None. |
operation_name | str | Operation name used in diagnostics when input binding fails. Defaults to "ControlledUOperation". |
Returns:
Any — An engine gate object produced by
emit_pass._emitter.circuit_to_gate, or None when the
conversion is unable to proceed (missing operations,
allocator / emitter exception, etc.) so the caller can fall
back to gate-by-gate emission.
bracket_control_value [source]¶
def bracket_control_value(
emit_pass: 'StandardEmitPass',
circuit: Any,
control_indices: Sequence[int],
control_value: int | None,
) -> Generator[None, None, None]Bracket zero-valued controls with target-neutral Pauli-X gates.
The controlled operation inside the context remains an ordinary all-ones
control. Controls are interpreted LSB-first in their existing physical
order, so bit zero of control_value describes control_indices[0].
One bracket surrounds the complete operation, including integral powers
and vector-target broadcast.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass providing the gate emitter. |
circuit | Any | Circuit receiving the bracket gates. |
control_indices | Sequence[int] | Ordered physical control qubits. |
control_value | int | None | Required basis value, or None for the ordinary all-ones state. |
Yields:
None — Control returns while the zero-valued controls are inverted.
Raises:
TypeError— Ifcontrol_valueis not a PythonintorNone.ValueError— If the activation value does not fit the control width.
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,
) -> QubitMapBuild 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:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Emit pass used to resolve symbolic vector input shapes against bindings. |
block_value | Any | Inner block whose input_values define the quantum formal arguments. Objects without input_values yield an empty map. |
target_indices | list[int] | Physical qubit indices supplied at the controlled call site, one per flattened quantum input qubit. |
bindings | dict[str, Any] | Bindings used while resolving vector input shapes. |
parent_qubit_map | QubitMap | None | Parent-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:
EmitError— If a vector input length cannot be resolved, is negative, or the block’s quantum input footprint exceedslen(target_indices).
clean_ancilla_toffoli_ladder [source]¶
def clean_ancilla_toffoli_ladder(num_controls: int | sp.Expr) -> CleanAncillaToffoliLadder[Any]Return the arithmetic for the named clean-ancilla recipe.
The caller owns recipe selection and must use the result on a branch where at least two controls are active. Keeping validation outside this helper lets symbolic resource expressions construct inactive Piecewise branches without prematurely rejecting them.
Parameters:
| Name | Type | Description |
|---|---|---|
num_controls | int | sp.Expr | Concrete or symbolic control count. |
Returns:
CleanAncillaToffoliLadder[Any] — CleanAncillaToffoliLadder[Any]: Compute, total-Toffoli, and clean-
ancilla requirements in the same numeric domain as the input.
coerce_nonnegative_integral [source]¶
def coerce_nonnegative_integral(value: object, *, label: str) -> intNormalize a real scalar with an integer value to a nonnegative integer.
Parameters:
| Name | Type | Description |
|---|---|---|
value | object | Candidate Python, NumPy, or SymPy real scalar. |
label | str | User-facing field label used in diagnostics. |
Returns:
int — Equivalent nonnegative Python integer.
Raises:
TypeError— Ifvalueis Boolean, is not a real scalar, is not finite, or does not have an integer value.ValueError— If the normalized integer is negative.
combine_control_batch_profiles [source]¶
def combine_control_batch_profiles(profiles: Iterable[ControlBatchProfile]) -> ControlBatchProfileCombine sequential emission profiles up to the decision threshold.
Parameters:
| Name | Type | Description |
|---|---|---|
profiles | Iterable[ControlBatchProfile] | Resolved operation profiles. |
Returns:
ControlBatchProfile — Capped work and the union of exact-two choices.
control_pattern_for_value [source]¶
def control_pattern_for_value(control_value: int | None, num_controls: int) -> tuple[int, ...]Return the LSB-first activation pattern for a control value.
Parameters:
| Name | Type | Description |
|---|---|---|
control_value | int | None | Required computational-basis value. None means the ordinary all-ones control state. |
num_controls | int | Concrete positive control-register width. |
Returns:
tuple[int, ...] — tuple[int, ...]: One 0/1 activation bit per flattened control,
with the first control represented by bit zero.
Raises:
TypeError— Ifcontrol_valueis not a PythonintorNone.ValueError— If the width or activation value is invalid.
Example:
>>> control_pattern_for_value(2, 2)
(0, 1)
>>> control_pattern_for_value(None, 2)
(1, 1)emit_controlled_block [source]¶
def emit_controlled_block(
emit_pass: 'StandardEmitPass',
circuit: Any,
block_value: Any,
control_idx: int,
target_indices: list[int],
bindings: dict[str, Any],
parent_qubit_map: QubitMap | None = None,
) -> NoneEmit a controlled version of a block via the mapped walker.
Builds a block-local qubit map from the block’s formal quantum
inputs to target_indices and walks the block body, so inner
gates land on the physical qubit their operand actually refers to
rather than on target_indices[0].
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
block_value | Any | Inner block whose operations are controlled. Objects without operations are silently skipped. |
control_idx | int | Physical control qubit index. |
target_indices | list[int] | Physical target qubits covering the block’s quantum inputs in declaration order. |
bindings | dict[str, Any] | Local block bindings. |
parent_qubit_map | QubitMap | None | Parent-circuit allocation map. Internal fresh-allocation addresses are copied from it when present. Defaults to None. |
Raises:
EmitError— If the block’s quantum inputs cannot be mapped ontotarget_indicesor an inner operation cannot be emitted.
emit_controlled_composite_at_indices [source]¶
def emit_controlled_composite_at_indices(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: InvokeOperation,
control_indices: list[int],
qubit_indices: list[int],
bindings: dict[str, Any],
) -> NoneEmit a composite gate under already-resolved outer controls.
A non-default activation value applies only to the invocation’s own leading controls. Enclosing controls remain ordinary all-ones controls; bracketing the inner controls around the complete call composes correctly even when the enclosing control is inactive.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
op | InvokeOperation | Composite or oracle invocation to emit. |
control_indices | list[int] | Physical outer control qubits. |
qubit_indices | list[int] | Physical qubits occupied by op’s own control and target operands. |
bindings | dict[str, Any] | Active emit bindings. |
Returns:
None — None.
Raises:
EmitError— If the composite has no implementation block or the fallback cannot represent the controlled composite.ValueError— If the selected implementation body disagrees with the invocation contract.
emit_controlled_fallback [source]¶
def emit_controlled_fallback(
emit_pass: 'StandardEmitPass',
circuit: Any,
block_value: Any,
num_controls: int,
control_indices: list[int],
target_indices: list[int],
power: int,
bindings: dict[str, Any],
batch_profile: ControlBatchProfile | None = None,
) -> NoneFallback emission for controlled-U when gate conversion fails.
Decomposes the block body gate-by-gate under the full control set.
A block-local qubit map ties the block’s formal quantum inputs to
target_indices, so every inner gate is emitted on the physical
qubit its operand resolves to — multi-target inner blocks are
supported. Nested ControlledUOperations compose their controls
with the outer ones; irreducible multi-controlled single-qubit
gates route through the engine’s
_emit_irreducible_multi_controlled_gate hook. Subclasses may
still override this method to emit controlled blocks natively
(e.g. CUDA-Q’s cudaq.control helper kernels).
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being built. |
block_value | Any | Block whose operations should be controlled. |
num_controls | int | Number of control qubits. |
control_indices | list[int] | Physical indices of control qubits. |
target_indices | list[int] | Physical indices of target qubits. |
power | int | Number of controlled body repetitions. |
bindings | dict[str, Any] | Parameter bindings visible in the body. |
batch_profile | ControlBatchProfile | None | Previously resolved body profile for this exact block and binding scope. Defaults to None, which lets the controlled walker compute it. |
Raises:
EmitError— Ifnum_controlsdisagrees withcontrol_indices, the block’s quantum inputs cannot be mapped ontotarget_indices, or an inner operation cannot be lowered under the accumulated controls (e.g. an irreducible multi-controlled gate on an engine without the multi-control hook).
emit_controlled_gate [source]¶
def emit_controlled_gate(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: GateOperation,
control_idx: int,
target_indices: list[int],
bindings: dict[str, Any],
) -> NoneEmit a controlled version of a gate.
Resolves the rotation angle for rotation-like gates and dispatches
single-target gate kinds through
:func:emit_single_controlled_primitive; SWAP is lowered here
via its Fredkin conjugation because it needs two targets.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
op | GateOperation | Gate operation to control. |
control_idx | int | Physical control qubit. |
target_indices | list[int] | Physical qubits for the gate’s own operands, in operand order. An empty list is a no-op. |
bindings | dict[str, Any] | Bindings used to resolve rotation angles. |
Raises:
EmitError— If the gate type is unsupported in controlled decomposition, or a controlled SWAP has fewer than two targets.
emit_controlled_global_phase_operation [source]¶
def emit_controlled_global_phase_operation(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: GlobalPhaseOperation,
control_indices: list[int],
bindings: dict[str, Any],
) -> NoneEmit a global phase as a relative phase under accumulated controls.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Circuit representation being emitted into. |
op | GlobalPhaseOperation | Global-phase operation to control. |
control_indices | list[int] | Accumulated physical control qubits. |
bindings | dict[str, Any] | Active emit bindings. |
Raises:
EmitError— If the phase cannot be resolved or the adapter cannot emit the accumulated control arity.
emit_controlled_operations [source]¶
def emit_controlled_operations(
emit_pass: 'StandardEmitPass',
circuit: Any,
operations: list[Operation],
control_indices: list[int],
qubit_map: QubitMap,
bindings: dict[str, Any],
batch_profile: ControlBatchProfile | None = None,
) -> NoneEmit controlled versions of operations with operand mapping.
Walks operations under the accumulated control_indices,
resolving every quantum operand through qubit_map so gates land
on the physical qubit their operand refers to. Nested
ControlledUOperations are not rejected: their own controls are
resolved and composed with the outer controls, lowering e.g. an
inner qmc.control(qmc.x, num_controls=k) under one outer
control to a (k+1)-controlled X.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
operations | list[Operation] | Block operations to walk. |
control_indices | list[int] | Accumulated physical control qubits. |
qubit_map | QubitMap | Mutable block-local qubit map seeded by :func:build_controlled_block_qubit_map; updated in place with gate / nested-op result addresses. |
bindings | dict[str, Any] | Bindings visible inside the block, including loop-iteration values during unrolling. |
batch_profile | ControlBatchProfile | None | Previously resolved body profile for this exact block and binding scope. Defaults to None, which computes the profile only if batching is possible. |
Raises:
EmitError— If an operand cannot be resolved to a physical qubit, aForOperationbound cannot be resolved at transpile time, or an operation kind is unsupported in controlled decomposition.
emit_controlled_pauli_evolve [source]¶
def emit_controlled_pauli_evolve(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: PauliEvolveOp,
control_indices: list[int],
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> NoneEmit exp(-i * gamma * H) under accumulated controls.
Lowers a controlled Pauli evolution by exploiting that each Pauli
term’s evolution exp(-i * theta * P) factors as
U_dagger * RZ(2 * theta) * U where U (the basis change onto
the Z axis followed by the parity CX ladder) is Clifford and thus
control-independent. Controlling a conjugated gate is
U_dagger * C[RZ] * U with U / U_dagger applied
unconditionally: when every control is 0 the central RZ
becomes the identity and U_dagger * I * U = I. Only the central
RZ therefore carries the controls, which keeps the
multi-controlled cost to a single rotation per Hamiltonian term
instead of controlling every basis-change and ladder gate.
The basis-change (H / SDG / S) and CX-ladder gates are
emitted uncontrolled through emit_pass._emitter; the central
RZ is routed through :func:_emit_mc_rotation, which dispatches
to emit_crz for a single control and to the engine’s
_emit_irreducible_multi_controlled_gate hook for two or more.
A constant (identity) Hamiltonian term c * I is the standalone phase
exp(-i * gamma * c) for an uncontrolled evolution and is retained by
:func:emit_pauli_evolve. Under controls it becomes an observable
relative phase on the all-controls-on subspace, so it is realized here as
a P(-gamma * c) on one control conditioned on the remaining controls
(emit_p for a single control, a multi-controlled P for more),
matching Qiskit’s native PauliEvolutionGate whose SparsePauliOp
carries the constant.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass; provides the value resolver, gate emitter, and the multi-controlled rotation hook. |
circuit | Any | Engine circuit being emitted into. |
op | PauliEvolveOp | The Pauli evolution operation inside the controlled block. |
control_indices | list[int] | Accumulated physical control qubits. Must be non-empty. |
qubit_map | QubitMap | Block-local qubit map the operation’s quantum operands resolve against; updated in place with the evolved-register result addresses. |
bindings | dict[str, Any] | Bindings visible inside the block, used to resolve the Hamiltonian, gamma, and register shape. |
Raises:
EmitError— Ifcontrol_indicesis empty, the observable does not resolve to a Hamiltonian, gamma cannot be resolved, the Hamiltonian is non-Hermitian (a term or the constant has a non-real coefficient), the Hamiltonian is larger than the register, a term qubit cannot be resolved, or gamma is runtime-parametric and the engine’s runtime parameter type does not support the required angle scaling (e.g. QURI Parts’Parameter).
emit_controlled_powers [source]¶
def emit_controlled_powers(
emit_pass: 'StandardEmitPass',
circuit: Any,
block_value: Any,
counting_indices: list[int],
target_indices: list[int],
bindings: dict[str, Any],
parent_qubit_map: QubitMap | None = None,
) -> NoneEmit controlled-U^(2^k) operations.
emit_controlled_u [source]¶
def emit_controlled_u(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: ControlledUOperation,
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> NoneEmit a controlled operation for every concrete operand layout.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
op | ControlledUOperation | Concrete or symbolic controlled operation. |
qubit_map | QubitMap | Logical-to-physical map, mutated with results. |
bindings | dict[str, Any] | Bindings visible at the call site. |
Raises:
EmitError— If controls, targets, power, or body parameters cannot be resolved, or the engine cannot lower the controlled operation.
emit_controlled_u_multi_arg [source]¶
def emit_controlled_u_multi_arg(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: SymbolicControlledU,
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> NoneEmit a SymbolicControlledU whose control prefix is multi-arg.
The multi-arg form (num_control_args > 1) carries a
heterogeneous control prefix: a mix of scalar Value
(single-qubit) and ArrayValue (whole Vector / slice
VectorView) operands whose qubit-count sum equals
num_controls once bindings resolves the lengths.
ConstantFoldingPass cannot promote this shape to
ConcreteControlledU (the per-control-qubit operand layout
would lose the array-grouping the resource allocator needs), so
it survives intact and lands here.
The function expands every control operand into physical qubit
indices via _expand_quantum_operands_to_phys, asserts the resulting count
matches the resolved num_controls, expands the target side
the same way, and threads the rest through the standard
gate_controlled + append_gate pipeline (with the
per-gate fallback for engines whose circuit_to_gate returns
None).
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The emit pass driving the conversion. |
circuit | Any | The engine circuit being built. |
op | SymbolicControlledU | The IR op with num_control_args > 1 and control_indices is None. |
qubit_map | QubitMap | The active QubitAddress -> physical qubit map; mutated in place with the result-side mappings. |
bindings | dict[str, Any] | Caller bindings used to resolve num_controls and any symbolic-length control / target operand. |
Raises:
EmitError—num_controlscannot be resolved, is non- positive, or does not match the sum of expanded control operand sizes.
emit_controlled_u_with_symbolic_indices [source]¶
def emit_controlled_u_with_symbolic_indices(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: SymbolicControlledU,
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> NoneEmit a SymbolicControlledU whose control_indices is set.
Routed from :func:emit_controlled_u when the constant-folding
pass has left the op as SymbolicControlledU because
control_indices carries pass-through semantics that the
ConcreteControlledU promotion cannot represent in its scalar
control-operand layout.
The function resolves the symbolic num_controls and every
control_indices entry to concrete ints, walks the control
pool’s slice_of chain to look up physical qubits per element,
builds control_phys from the selected pool slots, expands the
sub-kernel quantum operands via
_expand_quantum_operands_to_phys for the target side, and
threads the rest through the standard gate_controlled +
append_gate pipeline (with the per-gate fallback for engines
whose circuit_to_gate returns None).
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The emit pass driving the conversion; provides _resolver, _emitter, _blockvalue_to_gate, and _emit_controlled_fallback. |
circuit | Any | The engine circuit being built. |
op | SymbolicControlledU | The IR op with control_indices not None. Callers must guarantee this; the control_indices is None branch is handled by the constant-folding promotion to ConcreteControlledU. |
qubit_map | QubitMap | The active QubitAddress -> physical qubit map; mutated in place with the result-side mappings. |
bindings | dict[str, Any] | Caller bindings used to resolve num_controls, control_indices Values, c_qs length, and slice bounds. |
Raises:
EmitError— Surfaces under any of the following conditions:
num_controlscannot be resolved or is<= 0;the control-vector length cannot be resolved, is shorter than
num_controls, or is shorter than the largest listed index;a
control_indicesentry cannot be resolved, is negative, or repeats;len(control_indices) != num_controls;a sub-quantum operand cannot be expanded to physical qubits (delegated to :func:
_expand_quantum_operands_to_phys).
emit_custom_composite [source]¶
def emit_custom_composite(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: Any,
impl: Any,
qubit_indices: list[int],
bindings: dict[str, Any],
) -> NoneEmit a custom composite gate with implementation.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
op | Any | Composite gate operation. |
impl | Any | Fallback implementation block to emit. |
qubit_indices | list[int] | Physical qubits for the operation. |
bindings | dict[str, Any] | Active emit bindings. |
Raises:
EmitError— If body inputs, workspace addresses, or engine gate operands cannot be resolved safely.
emit_multi_controlled_gate [source]¶
def emit_multi_controlled_gate(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: GateOperation,
control_indices: list[int],
target_indices: list[int],
bindings: dict[str, Any],
) -> NoneEmit one gate under an arbitrary number of accumulated controls.
Structurally reduces multi-qubit gate types to single-target forms
by absorbing their own control qubits into the control set
(CX -> X, CZ -> Z, CP -> P, TOFFOLI -> X; SWAP
and RZZ via their standard CX conjugations), then emits:
one control: via :func:
emit_controlled_gate(the existing single-control dispatch),two controls on X / Z: via
emit_toffoli(Z conjugated by H),anything else: via the engine’s
_emit_irreducible_multi_controlled_gatehook, whose base implementation raises a descriptiveEmitError.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. Subclass overrides of _emit_irreducible_multi_controlled_gate are respected for the irreducible tail. |
circuit | Any | Engine circuit being emitted into. |
op | GateOperation | Gate operation whose operands are already resolved to target_indices. |
control_indices | list[int] | Physical control qubits. Must be non-empty. |
target_indices | list[int] | Physical qubits for the gate’s own operands, in operand order. |
bindings | dict[str, Any] | Bindings used to resolve rotation angles. |
Raises:
EmitError— Ifcontrol_indicesis empty, the gate has fewer resolved targets than its type requires, or the reduction bottoms out on an engine without multi-control support.
emit_multi_controlled_on_clean_ancillas [source]¶
def emit_multi_controlled_on_clean_ancillas(
emit_pass: 'StandardEmitPass',
circuit: Any,
gate_type: GateOperationType,
control_indices: list[int],
target_idx: int,
angle: Any,
ancilla_indices: list[int],
) -> NoneLower an irreducible multi-controlled gate via a Toffoli cascade.
Implements the standard clean-ancilla construction (arXiv:2307.07478,
Appendix A.3): the logical AND of the n controls is accumulated
onto n - 1 clean ancillas with a cascade of Toffoli gates, the
gate is applied once under a single control (the last ancilla)
through :func:emit_single_controlled_primitive, and the cascade is
uncomputed in reverse order. The cost is 2 * (n - 1) Toffoli
gates plus one singly-controlled gate, and every ancilla returns to
|0>, so the same pool may be reused by subsequent gates.
Unlike a dense 2**(n+1) unitary-matrix lowering, this scales
linearly in the control count and keeps rotation angles symbolic,
so runtime-parametric multi-controlled rotations are supported.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
gate_type | GateOperationType | Single-qubit gate kind to apply under the controls. |
control_indices | list[int] | Physical control qubits; at least two. |
target_idx | int | Physical target qubit. |
angle | Any | Resolved rotation angle (concrete number or engine parameter expression) for rotation-like gates, or None for fixed gates. |
ancilla_indices | list[int] | Clean (|0>) ancilla qubits; at least len(control_indices) - 1 entries. |
Raises:
EmitError— If fewer than two controls or too few ancillas are supplied (both indicate a caller bug), or the gate type is unsupported by the single-control dispatch.
emit_single_controlled_primitive [source]¶
def emit_single_controlled_primitive(
emit_pass: 'StandardEmitPass',
circuit: Any,
gate_type: GateOperationType | None,
control_idx: int,
target_idx: int,
angle: Any,
) -> NoneEmit one singly-controlled single-qubit gate from a resolved angle.
This is the single-control dispatch shared by
:func:emit_controlled_gate (which resolves the angle from the IR
operation first) and the Toffoli-cascade lowering of irreducible
multi-controlled gates (which arrives with the angle already
resolved). Fixed phase-family gates (S / T and daggers) are
emitted as controlled phases.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
gate_type | GateOperationType | None | Single-qubit gate kind. None (a gate operation without a type) is rejected like any other unsupported kind. |
control_idx | int | Physical control qubit. |
target_idx | int | Physical target qubit. |
angle | Any | Resolved rotation angle (concrete number or engine parameter expression) for P / RX / RY / RZ; ignored for fixed gates. |
Raises:
EmitError— Ifgate_typeis not a single-qubit gate kind supported in controlled decomposition.
emit_static_controlled_if [source]¶
def emit_static_controlled_if(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: IfOperation,
control_indices: list[int],
qubit_map: QubitMap,
bindings: dict[str, Any],
walker: Callable[..., None],
) -> NoneEmit the selected branch of a static if under accumulated controls.
This is the common safety net for controlled-body walkers. Compile-time lowering normally removes these nodes earlier, but a loop induction value can make the condition concrete only while emit unrolls that iteration.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
op | IfOperation | Static branch to resolve and emit. |
control_indices | list[int] | Accumulated physical control qubits. |
qubit_map | QubitMap | Mutable block-local qubit map. |
bindings | dict[str, Any] | Bindings visible in the current iteration. |
walker | Callable[..., None] | Engine controlled-body walker used to emit the selected branch. |
Raises:
EmitError— If the condition remains runtime-dependent.
evaluate_binop [source]¶
def evaluate_binop(emit_pass: 'StandardEmitPass', op: BinOp, bindings: dict[str, Any]) -> NoneEvaluate a BinOp and store the result in bindings.
Tries the shared fold_classical_op first for a clean concrete
fold (which already encapsulates the runtime-parameter guard).
Falls back to creating engine Parameter symbols and doing
symbolic arithmetic when one or both operands are runtime
parameters — that’s the path that lets rx(q, gamma * 2) produce
a circuit with a single Parameter("gamma") * 2 expression rather
than baking in a placeholder.
evaluate_classical_predicate [source]¶
def evaluate_classical_predicate(
emit_pass: 'StandardEmitPass',
op: 'CompOp | CondOp | NotOp',
bindings: dict[str, Any],
) -> NoneEvaluate a CompOp/CondOp/NotOp at emit time and bind its boolean result.
Mirrors the predicate evaluation already done by
compile_time_if_lowering and classical_executor so that an
IfOperation whose condition reaches emit unfolded — typically
because its operands depend on a loop variable bound only at emit time
by emit_for_items / emit_for_unrolled — can still be resolved
via resolve_if_condition.
Delegates the actual fold (including runtime-parameter guard and
strict scalar typing) to fold_classical_op so that all three
callers of the same kind dispatch share one implementation. There
is no symbolic-Parameter fallback for predicates: a runtime classical
expression cannot be expressed as a folded scalar, so the op is left
unbound and downstream emit handles it as a runtime condition.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | 'StandardEmitPass' | The active emit pass (for resolver access). |
op | 'CompOp | CondOp | NotOp' | The predicate op to evaluate. |
bindings | dict[str, Any] | Current parameter/loop-variable bindings; mutated in place on successful evaluation. No-op when operands are unresolvable (e.g. measurement bits) or evaluation raises. |
Returns:
None — None.
evaluate_dict_getitem [source]¶
def evaluate_dict_getitem(
emit_pass: 'StandardEmitPass',
op: DictGetItemOperation,
bindings: dict[str, Any],
) -> NoneEvaluate a DictGetItemOperation and store the result in bindings.
Resolves each key component (typically a for-items loop variable
bound by UUID in bindings), looks the key up in the dict’s
resolved entries, and writes the value into bindings under the
result UUID so downstream ops (BinOps feeding gate angles) can
consume it.
When the dict is a declared runtime parameter
(transpile(..., parameters=["coeffs"])), there are no entries to
look up; the resolved key instead names one engine parameter
(coeffs[3] / coeffs[(0, 1)]) which is stored under the
result UUID. Repeated lookups of the same key share one engine
parameter via _get_or_create_parameter.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The emit pass (for resolver access). |
op | DictGetItemOperation | The lookup op being evaluated. |
bindings | dict[str, Any] | Current emit-time bindings. |
Raises:
EmitError— If a key component or the dict entries cannot be resolved, or the key is not present in the dict.
evaluate_unary_math [source]¶
def evaluate_unary_math(
emit_pass: 'StandardEmitPass',
op: UnaryMathOp,
bindings: dict[str, Any],
) -> NoneEvaluate concrete unary math used inside a controlled body.
An unresolved runtime unary expression is left unbound. Pure unused expressions can then disappear like ordinary dead classical work, while a later loop bound, branch, or gate-angle consumer still fails at its normal resolution boundary instead of receiving a fabricated value.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass used for value resolution and runtime-parameter classification. |
op | UnaryMathOp | Unary expression to evaluate. |
bindings | dict[str, Any] | Current emit-time values, updated when the expression resolves to a valid concrete scalar. |
handle_cast [source]¶
def handle_cast(emit_pass: 'StandardEmitPass', op: CastOperation, qubit_map: QubitMap) -> NoneHandle CastOperation - update qubit_map without emitting gates.
is_identity_phase_angle [source]¶
def is_identity_phase_angle(angle: Any) -> boolReturn whether a concrete angle is exactly zero modulo two pi.
The test intentionally uses no tolerance so a tiny but nonzero phase is never discarded. Runtime parameter expressions remain non-identity until an engine resolves them to a concrete number.
Parameters:
| Name | Type | Description |
|---|---|---|
angle | Any | Resolved numeric angle or engine parameter expression. |
Returns:
bool — Whether angle is a finite real number exactly congruent to
bool — zero modulo 2 * pi.
map_array_result_group [source]¶
def map_array_result_group(result_uuid: str, index_group: list[int], index_map: PhysicalIndexMap) -> NoneMap an array-valued result to a physical index group.
Parameters:
| Name | Type | Description |
|---|---|---|
result_uuid | str | UUID of the array-valued result whose element addresses should be registered. |
index_group | list[int] | Physical indices for the result elements, in result-local element order. |
index_map | PhysicalIndexMap | Mutable physical-index map updated in place with element addresses and, when available, the base result address. |
map_nested_controlled_u_results [source]¶
def map_nested_controlled_u_results(
op: ControlledUOperation,
resolved: ResolvedControlledU,
qubit_map: QubitMap,
) -> NoneMap a nested controlled-U’s result values to physical qubits.
The result layout mirrors the operand layout for every controlled-U
shape: one result per control operand slot followed by one result
per sub-kernel quantum operand. Controlled gates only add a
relative phase — no qubit moves — so each result keeps the physical
slots of its operand. For the control_indices pool form the
whole pool passes through, selected controls included.
Parameters:
| Name | Type | Description |
|---|---|---|
op | ControlledUOperation | The operation whose results need mapping. |
resolved | ResolvedControlledU | Physical resolution returned by :func:resolve_controlled_u_call for this operation. |
qubit_map | QubitMap | Mutable qubit map updated in place. |
quantum_operand_widths [source]¶
def quantum_operand_widths(attrs: Mapping[str, Any], *, source: str) -> tuple[QuantumOperandWidth, ...]Decode exact quantum-operand widths from callable resource metadata.
Parameters:
| Name | Type | Description |
|---|---|---|
attrs | Mapping[str, Any] | Callable definition or operation attrs. |
source | str | Callable name used in malformed-contract diagnostics. |
Returns:
tuple[QuantumOperandWidth, ...] — tuple[QuantumOperandWidth, ...]: Validated exact-width entries, or an
empty tuple when the callable declares no such contract.
Raises:
ValueError— If present resource metadata is malformed or repeats an operand index.
register_classical_merge_aliases [source]¶
def register_classical_merge_aliases(
emit_pass: 'StandardEmitPass',
op: IfOperation,
bindings: dict[str, Any],
resolved: bool | None,
) -> NoneBind 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:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The active emit pass (for resolver access). |
op | IfOperation | The if-else whose merged classical outputs should be bound; merges are read through iter_merges. |
bindings | dict[str, Any] | Current bindings; mutated in place to bind merge outputs. |
resolved | bool | None | True / False if the if was compile-time resolved (use the selected branch’s input); None if it was a runtime if (only bind identity merges). |
Returns:
None — None.
reject_duplicate_physical_indices [source]¶
def reject_duplicate_physical_indices(
gate_label: str,
physical_indices: list[int],
operand_names: list[str] | None = None,
) -> NoneReject 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:
| Name | Type | Description |
|---|---|---|
gate_label | str | Human-readable name of the gate for the message (e.g. "CX" or "controlled gate"). |
physical_indices | list[int] | The resolved physical qubit indices the gate acts on, in operand order. |
operand_names | list[str] | None | Optional 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:
QubitAliasError— If any physical qubit index repeats.
remap_static_merge_outputs [source]¶
def remap_static_merge_outputs(
if_op: IfOperation,
condition_value: bool,
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any] | None = None,
resolver: ValueResolver | None = None,
) -> NoneRemap merge outputs for a compile-time constant IfOperation.
Registers each merged output under the physical resource of the branch selected by the resolved condition, so downstream operations referencing the merge output resolve to the surviving branch’s qubit / clbit. Outputs already registered are left untouched.
Parameters:
| Name | Type | Description |
|---|---|---|
if_op | IfOperation | The if-else whose condition resolved at compile time; merges are read through iter_merges. |
condition_value | bool | The resolved condition, selecting which branch’s source the outputs alias. |
qubit_map | QubitMap | Address-to-physical-qubit map, mutated in place. |
clbit_map | ClbitMap | Address-to-physical-clbit map, mutated in place. |
bindings | dict[str, Any] | None | Active bindings used to fold a merge source’s symbolic Vector[Bit] element index / slice bounds (e.g. an unrolled loop variable). Defaults to None (empty), restricting element resolution to constant indices. |
resolver | ValueResolver | None | Resolver used with bindings to fold non-constant element indices; None restricts to constants. Defaults to None. |
replay_controlled_for [source]¶
def replay_controlled_for(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: ForOperation,
control_indices: list[int],
qubit_map: QubitMap,
bindings: dict[str, Any],
*,
walker: Callable[..., None],
) -> NoneReplay one static range loop under accumulated quantum controls.
Controlled blocks use a specialized operation walker because every
quantum gate in the body must inherit the outer controls. Reusing only
the old loop-variable binding logic here skipped the loop’s explicit
RegionArg protocol, so a scalar recurrence such as index += 1
either stayed pinned to its initial value or became unresolved. This
helper shares the canonical emit-time carry primitives with ordinary
loop emission and accepts the engine-specific controlled walker as a
callback. Nested range loops therefore replay recursively with the same
init -> block_arg -> yielded -> result semantics on every engine.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass and value resolver. |
circuit | Any | Engine circuit being constructed. |
op | ForOperation | Static range loop to replay. |
control_indices | list[int] | Physical controls accumulated from the enclosing controlled operations. |
qubit_map | QubitMap | Mutable block-local qubit map. |
bindings | dict[str, Any] | Bindings visible before the loop. Final RegionArg results and the final loop variable are published here. |
walker | Callable[..., None] | Controlled operation walker with the same leading arguments as :func:emit_controlled_operations. |
Returns:
None — The callback appends operations to circuit in place.
Raises:
EmitError— If the bounds are unresolved or invalid, loop identities are malformed, or a RegionArg value cannot be resolved.
resolve_angle_value [source]¶
def resolve_angle_value(
emit_pass: 'StandardEmitPass',
theta: Any,
bindings: dict[str, Any],
) -> float | AnyResolve a bare angle Value to a concrete float or engine parameter.
Shared core of :func:resolve_angle so operations carrying a standalone
angle Value reuse the exact same resolution order as rotation-gate thetas.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass providing the resolver and engine-parameter factory. |
theta | Any | Angle Value to resolve. |
bindings | dict[str, Any] | Active compile-time bindings. |
Returns:
float | Any — float | Any: A concrete float when the angle is bound, or a
engine parameter expression when it stays symbolic.
Raises:
EmitError— If the angle is missing or cannot be resolved to a concrete value or engine parameter. Emitting0.0in this case would silently change the requested unitary.
resolve_controlled_u_call [source]¶
def resolve_controlled_u_call(
emit_pass: 'StandardEmitPass',
op: ControlledUOperation,
qubit_map: QubitMap,
bindings: dict[str, Any],
*,
bind_body: bool = True,
) -> ResolvedControlledUResolve a (possibly nested) controlled-U call site to physical qubits.
Handles all three operand layouts:
ConcreteControlledU: one scalar operand per control qubit.SymbolicControlledUwithcontrol_indices is None: a control prefix ofnum_control_argsscalar / vector operands whose flattened qubit count equals the resolvednum_controls.SymbolicControlledUwithcontrol_indicesset: a single control pool whose listed elements act as controls while the rest pass through.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass; provides the value resolver. |
op | ControlledUOperation | The controlled-U operation to resolve. |
qubit_map | QubitMap | Qubit map the operands resolve against (block-local when called from a controlled walker). |
bindings | dict[str, Any] | Bindings visible at the call site, including loop-iteration values during unrolling. |
bind_body | bool | Whether to bind the selected body’s formal parameters and shapes. Set to False for a zero-powered identity. Defaults to True. |
Returns:
ResolvedControlledU — Physical controls / targets and the
inner-block bindings.
Raises:
EmitError— If the operation has no inner block,num_controlsor acontrol_indicesentry cannot be resolved, indices repeat or fall outside the pool, the flattened control count does not matchnum_controls, or an operand cannot be expanded to physical qubits.
resolve_if_condition [source]¶
def resolve_if_condition(condition: Any, bindings: dict[str, Any]) -> bool | NoneResolve an if-condition to a compile-time boolean.
resolve_loop_bounds [source]¶
def resolve_loop_bounds(
resolver: Any,
op: ForOperation,
bindings: dict[str, Any],
) -> tuple[int | None, int | None, int | None]Resolve for-loop bounds (start, stop, step) from operands.
Missing operands use defaults: start=0, stop=1, step=1. Returns None for bounds that cannot be resolved to concrete ints.
resolve_power [source]¶
def resolve_power(
emit_pass: 'StandardEmitPass',
op: ControlledUOperation,
bindings: dict[str, Any],
) -> intResolve ControlledUOperation.power to a concrete integer.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass and value resolver. |
op | ControlledUOperation | Controlled operation owning the power. |
bindings | dict[str, Any] | Emit-time bindings visible in the current scope. |
Returns:
int — Validated nonnegative power.
Raises:
EmitError— If the power is unresolved, has an unexpected type, is negative, or its value resolver reports a deterministic error.
should_batch_controlled_body [source]¶
def should_batch_controlled_body(num_controls: int, *, profile: ControlBatchProfile) -> boolReturn whether engine fallback should share one AND carrier.
Parameters:
| Name | Type | Description |
|---|---|---|
num_controls | int | Concrete number of composed controls. |
profile | ControlBatchProfile | Context-resolved emission profile. |
Returns:
bool — Whether engine fallback should build one body-wide ladder.
static_controlled_batch_profile [source]¶
def static_controlled_batch_profile(operation: Operation) -> ControlBatchProfile | NoneReturn context-free emission batching information for one operation.
None means that emission must resolve classical state or a nested
callable before deciding the weight. Unknown operation kinds count as one
leaf so eligibility analysis never hides work rejected by the later walker.
Parameters:
| Name | Type | Description |
|---|---|---|
operation | Operation | Operation inside a controlled body. |
Returns:
ControlBatchProfile | None — ControlBatchProfile | None: Context-free emission profile, or None
when engine-specific value resolution is required.
try_emit_batched_controlled_operations [source]¶
def try_emit_batched_controlled_operations(
emit_pass: 'StandardEmitPass',
circuit: Any,
operations: list[Operation],
control_indices: list[int],
qubit_map: QubitMap,
bindings: dict[str, Any],
walker: Callable[..., None],
batch_profile: ControlBatchProfile | None = None,
) -> boolEmit a controlled block body behind a single shared AND ladder.
When a block body emits several gates under the same composed
controls, lowering each gate through its own Toffoli cascade rebuilds
the same AND ladder per gate — the uncompute of one gate and the
recompute of the next cancel. This helper instead ANDs the controls
onto one ancilla once, walks the whole body under that single control,
then uncomputes the ladder once. Nested controlled-U operations
compose [and_ancilla] with their own controls and re-enter
walker, which batches again from the advanced pool offset; loops
are batched before iteration expansion, so the ladder is hoisted out.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass (must hold a _mc_ancilla_pool). |
circuit | Any | Engine circuit being emitted into. |
operations | list[Operation] | Controlled block body operations. |
control_indices | list[int] | Composed physical control qubits. |
qubit_map | QubitMap | Mutable block-local qubit map. |
bindings | dict[str, Any] | Bindings visible inside the block. |
walker | Callable[..., None] | The controlled-body walker to run under the single AND control (its own signature). |
batch_profile | ControlBatchProfile | None | Previously resolved body profile for this exact block and binding scope. Defaults to None, which computes the profile locally. |
Returns:
bool — True when the body was batched, False when the caller should
fall back to per-gate emission (fewer than two controls, no
pool, insufficient weight, the two-control guard, or a pool
that cannot spare the ladder).
Raises:
EmitError— If resolving nested batching metadata or walking the controlled body fails.
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,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]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,
) -> NoneAttributes¶
kind: BinOpKind | Noneoperation_kind: OperationKindsignature: Signature
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
CInitOperation [source]¶
class CInitOperation(Operation)Initialize the classical values (const, arguments etc)
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
CallTransform [source]¶
class CallTransform(enum.Enum)Describe the requested transform of a callable implementation.
Attributes¶
CONTROLLEDCONTROLLED_INVERSEDIRECTINVERSEis_controlled: bool Return whether the transform adds coherent controls.is_inverse: bool Return whether the transform requests inverse application.
Methods¶
inverted¶
def inverted(self) -> CallTransformToggle inverse application while preserving coherent control.
Returns:
CallTransform — Transform with the inverse component toggled.
CallableBodySelection [source]¶
class CallableBodySelectionDescribe one validated IR body selected for an invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
body | Block | None | Selected IR body, or None when no composable body is available. |
realized_transform | CallTransform | Transform already implemented by body. |
operands | tuple[ValueBase, ...] | Call-site operands corresponding to the selected body’s formal inputs. |
results | tuple[ValueBase, ...] | Call-site results corresponding to the selected body’s formal outputs. |
Constructor¶
def __init__(
self,
body: Block | None,
realized_transform: CallTransform,
operands: tuple[ValueBase, ...],
results: tuple[ValueBase, ...],
) -> NoneAttributes¶
body: Block | Noneimplements_controls: bool Return whether the selected body includes invocation controls.operands: tuple[ValueBase, ...]realized_transform: CallTransformresults: tuple[ValueBase, ...]
Methods¶
map_result_indices¶
def map_result_indices(
self,
body_indices: Iterable[int],
invocation_results: Sequence[ValueBase],
) -> frozenset[int]Map selected-body output positions to invocation result positions.
Generic controlled lowering removes the external control prefix before aligning a direct body. Transform-specific implementations instead use the complete invocation ABI. Mapping through the selected call-site result values handles both layouts, including any quantum/non-quantum reordering performed while aligning a fallback body.
Parameters:
| Name | Type | Description |
|---|---|---|
body_indices | Iterable[int] | Selected-body output positions to map. |
invocation_results | Sequence[ValueBase] | Complete caller-side invocation results. |
Returns:
frozenset[int] — frozenset[int]: Corresponding positions in invocation_results.
CastOperation [source]¶
class CastOperation(Operation)Type cast operation for creating aliases over the same quantum resources.
This operation does NOT allocate new qubits. It creates a new Value that references the same underlying quantum resources with a different type.
Use cases:
Vector[Qubit] -> QFixed (after QPE, for phase measurement)
Vector[Qubit] -> QUInt (for quantum arithmetic)
QUInt -> QFixed (reinterpret bits with different encoding)
QFixed -> QUInt (reinterpret bits with different encoding)
operands: [source_value] - The value being cast results: [cast_result] - The new value with target type (same physical qubits)
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
source_type: ValueType | None = None,
target_type: ValueType | None = None,
qubit_mapping: list[str] = list(),
) -> NoneAttributes¶
num_qubits: int Number of qubits involved in the cast.operation_kind: OperationKind Cast stays in the same segment as its source (QUANTUM for quantum types).qubit_mapping: list[str]signature: Signature Return the type signature of this cast operation.source_type: ValueType | Nonetarget_type: ValueType | None
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,
) -> NoneAttributes¶
kind: CompOpKind | Noneoperation_kind: OperationKindsignature: Signature
ConcreteControlledU [source]¶
class ConcreteControlledU(ControlledUOperation)Controlled-U with concrete (int) number of controls.
Operand layout: [ctrl_0, ..., ctrl_n, tgt_0, ..., tgt_m, params...]
Result layout: [ctrl_0', ..., ctrl_n', tgt_0', ..., tgt_m']
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
power: int | Value = 1,
block: Block | None = None,
num_controls: int = 1,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
control_operands: list[Value]control_value: int | Nonenum_controls: intparam_operands: list[Value] Get classical/object operands after the concrete control prefix.signature: Signature Build the concrete controlled call signature.target_operands: list[Value] Return the wrapped callable’s target and parameter operands.
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,
) -> NoneAttributes¶
kind: CondOpKind | Noneoperation_kind: OperationKindsignature: Signature
ControlBatchProfile [source]¶
class ControlBatchProfileDescribe resolved work and the engine’s exact-two-control choice.
Parameters:
| Name | Type | Description |
|---|---|---|
weight | int | Controlled work clamped to zero, one, or two. |
selects_exact_two | bool | Whether the engine selects a shared carrier when exactly two outer controls are present. |
Constructor¶
def __init__(self, weight: int = 0, selects_exact_two: bool = False) -> NoneAttributes¶
decision_complete: bool Return whether later work cannot change the batching decision.selects_exact_two: boolweight: int
ControlledUOperation [source]¶
class ControlledUOperation(Operation)Base class for controlled-U operations.
Two concrete subclasses handle distinct operand layouts:
ConcreteControlledU: Fixednum_controls: int, individual qubit operands.SymbolicControlledU: Symbolicnum_controls: Value, vector-based control operands; optionalcontrol_indicesselects a subset of the control vector to act as controls (the rest pass through).
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(),
) -> NoneAttributes¶
block: Block | Nonebody_operands: list[Value] Get the wrapped callable’s complete argument list.callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_operands: list[Value] Get the control qubit values.is_symbolic_num_controls: bool Whether num_controls is symbolic (Value) rather than concrete.num_controls: int | Valueoperation_kind: OperationKindparam_operands: list[Value] Get the controlled operation’s classical/object arguments.power: int | Valuesignature: Signaturetarget_operands: list[Value] Get the target qubit values (arguments to U).
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationCountingEmitter [source]¶
class CountingEmitterA no-op gate emitter that lets a real emission walk run for counting.
Wraps the real engine emitter, delegating capability queries so
control-flow lowering matches real emission while turning every gate
emission into a no-op and every gate/sub-circuit construction into a
None that forces the cascade-prone fallback path. Used by isolated
analysis-emission transactions for ancilla sizing and zero-work semantic
validation; the object is passed where a GateEmitter[T] is expected
via a cast.
Constructor¶
def __init__(self, real: Any) -> NoneWrap a real emitter for a counting run.
Parameters:
| Name | Type | Description |
|---|---|---|
real | Any | The engine emitter whose capability answers should be mirrored so the walk makes the same structural choices. |
Attributes¶
measurement_mode: MeasurementMode Delegate the measurement mode to the wrapped emitter.
Methods¶
append_gate¶
def append_gate(self, circuit: Any, gate: Any, qubits: list[int]) -> NoneCount appending a prebuilt gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
gate | Any | Ignored gate object (never built in counting mode). |
qubits | list[int] | Ignored qubit indices the gate acts on. |
circuit_to_gate¶
def circuit_to_gate(self, circuit: Any, name: str = 'U') -> AnyForce the fallback path by declining to build a reusable gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
name | str | Ignored gate name. Defaults to "U". |
Returns:
Any — Always None.
combine_symbolic¶
def combine_symbolic(self, kind: Any, lhs: Any, rhs: Any) -> _CountingParameterReturn a placeholder for a symbolic angle combination.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | Any | Ignored binary-op kind. |
lhs | Any | Ignored left operand. |
rhs | Any | Ignored right operand. |
Returns:
_CountingParameter — A placeholder symbolic angle.
create_circuit¶
def create_circuit(self, num_qubits: int, num_clbits: int) -> _CountingCircuitReturn a placeholder circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
num_qubits | int | Ignored. |
num_clbits | int | Ignored. |
Returns:
_CountingCircuit — A stateless placeholder.
create_parameter¶
def create_parameter(self, name: str) -> _CountingParameterReturn an arithmetic-absorbing placeholder parameter.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Ignored. |
Returns:
_CountingParameter — A placeholder runtime parameter.
emit_barrier¶
def emit_barrier(self, circuit: Any, qubits: list[int]) -> NoneCount a barrier as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubits | list[int] | Ignored qubit indices spanned by the barrier. |
emit_ch¶
def emit_ch(self, circuit: Any, control: int, target: int) -> NoneCount a CH gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
emit_cp¶
def emit_cp(self, circuit: Any, control: int, target: int, angle: Any) -> NoneCount a controlled-phase gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
angle | Any | Ignored phase angle. |
emit_crx¶
def emit_crx(self, circuit: Any, control: int, target: int, angle: Any) -> NoneCount a CRX gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
angle | Any | Ignored rotation angle. |
emit_cry¶
def emit_cry(self, circuit: Any, control: int, target: int, angle: Any) -> NoneCount a CRY gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
angle | Any | Ignored rotation angle. |
emit_crz¶
def emit_crz(self, circuit: Any, control: int, target: int, angle: Any) -> NoneCount a CRZ gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
angle | Any | Ignored rotation angle. |
emit_cx¶
def emit_cx(self, circuit: Any, control: int, target: int) -> NoneCount a CX gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
emit_cy¶
def emit_cy(self, circuit: Any, control: int, target: int) -> NoneCount a CY gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
emit_cz¶
def emit_cz(self, circuit: Any, control: int, target: int) -> NoneCount a CZ gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
emit_else_start¶
def emit_else_start(self, circuit: Any, context: Any) -> NoneCount the start of a native else branch as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
context | Any | Ignored branch context from emit_if_start. |
emit_for_loop_end¶
def emit_for_loop_end(self, circuit: Any, context: Any) -> NoneCount the end of a native for loop as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
context | Any | Ignored loop context from emit_for_loop_start. |
emit_for_loop_start¶
def emit_for_loop_start(self, circuit: Any, indexset: range) -> AnyReturn a placeholder loop variable for a native-for-loop count.
Unlike the other control-flow hooks, emit_for’s return value is
bound as the loop variable (via _bind_loop_var) and the body is
then walked once. A real native-loop emitter returns a symbolic
loop parameter, so return the arithmetic-absorbing
:class:_CountingParameter rather than None — otherwise a
body that carries the loop value into an angle or index expression
during counting would see None and fail. (No pool-reserving
engine supports native for loops today, so this is future-proofing.)
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored. |
indexset | range | Ignored. |
Returns:
Any — A placeholder loop variable.
emit_global_phase¶
def emit_global_phase(self, circuit: Any, angle: Any) -> NoneAccept a standalone phase during the internal counting walk.
The counting emitter observes only peak clean-ancilla demand. It does not materialize any gate, including a phase that the wrapped real emitter will preserve during the subsequent emission walk.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
angle | Any | Ignored phase angle. |
emit_h¶
def emit_h(self, circuit: Any, qubit: int) -> NoneCount an H gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_if_end¶
def emit_if_end(self, circuit: Any, context: Any) -> NoneCount the end of a native if/else block as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
context | Any | Ignored branch context from emit_if_start. |
emit_if_start¶
def emit_if_start(self, circuit: Any, clbit: int, value: int = 1) -> AnyCount the start of a native if branch as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
clbit | int | Ignored predicate classical bit index. |
value | int | Ignored predicate value to match. Defaults to 1. |
Returns:
Any — Always None (a null branch context).
emit_measure¶
def emit_measure(self, circuit: Any, qubit: int, clbit: int) -> NoneCount a measurement as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored measured qubit index. |
clbit | int | Ignored destination classical bit index. |
emit_p¶
def emit_p(self, circuit: Any, qubit: int, angle: Any) -> NoneCount a phase gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
angle | Any | Ignored phase angle. |
emit_reset¶
def emit_reset(self, circuit: Any, qubit: int) -> NoneCount a reset as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored reset qubit index. |
emit_rx¶
def emit_rx(self, circuit: Any, qubit: int, angle: Any) -> NoneCount an RX gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
angle | Any | Ignored rotation angle. |
emit_ry¶
def emit_ry(self, circuit: Any, qubit: int, angle: Any) -> NoneCount an RY gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
angle | Any | Ignored rotation angle. |
emit_rz¶
def emit_rz(self, circuit: Any, qubit: int, angle: Any) -> NoneCount an RZ gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
angle | Any | Ignored rotation angle. |
emit_rzz¶
def emit_rzz(self, circuit: Any, qubit1: int, qubit2: int, angle: Any) -> NoneCount an RZZ gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit1 | int | Ignored first qubit index. |
qubit2 | int | Ignored second qubit index. |
angle | Any | Ignored rotation angle. |
emit_s¶
def emit_s(self, circuit: Any, qubit: int) -> NoneCount an S gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_sdg¶
def emit_sdg(self, circuit: Any, qubit: int) -> NoneCount an Sdg gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_swap¶
def emit_swap(self, circuit: Any, qubit1: int, qubit2: int) -> NoneCount a SWAP gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit1 | int | Ignored first qubit index. |
qubit2 | int | Ignored second qubit index. |
emit_t¶
def emit_t(self, circuit: Any, qubit: int) -> NoneCount a T gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_tdg¶
def emit_tdg(self, circuit: Any, qubit: int) -> NoneCount a Tdg gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_toffoli¶
def emit_toffoli(self, circuit: Any, control1: int, control2: int, target: int) -> NoneCount a Toffoli gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control1 | int | Ignored first control qubit index. |
control2 | int | Ignored second control qubit index. |
target | int | Ignored target qubit index. |
emit_while_end¶
def emit_while_end(self, circuit: Any, context: Any) -> NoneCount the end of a native while loop as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
context | Any | Ignored loop context from emit_while_start. |
emit_while_start¶
def emit_while_start(self, circuit: Any, clbit: int, value: int = 1) -> AnyCount the start of a native while loop as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
clbit | int | Ignored predicate classical bit index. |
value | int | Ignored predicate value to match. Defaults to 1. |
Returns:
Any — Always None (a null loop context).
emit_x¶
def emit_x(self, circuit: Any, qubit: int) -> NoneCount an X gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_y¶
def emit_y(self, circuit: Any, qubit: int) -> NoneCount a Y gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_z¶
def emit_z(self, circuit: Any, qubit: int) -> NoneCount a Z gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
gate_controlled¶
def gate_controlled(self, gate: Any, num_controls: int) -> AnyDecline to build a real controlled gate.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | Any | Ignored gate object. |
num_controls | int | Ignored number of control qubits. |
Returns:
Any — Always None.
gate_inverse¶
def gate_inverse(self, gate: Any) -> AnyDecline to build a real inverse gate.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | Any | Ignored gate object. |
Returns:
Any — Always None.
gate_power¶
def gate_power(self, gate: Any, power: int) -> AnyDecline to build a real powered gate.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | Any | Ignored gate object. |
power | int | Ignored exponent. |
Returns:
Any — Always None.
supports_for_loop¶
def supports_for_loop(self) -> boolDelegate native-for-loop support to the wrapped emitter.
Returns:
bool — The real emitter’s answer, so loops unroll (or not) the
same way real emission would.
supports_gate_inverse¶
def supports_gate_inverse(self) -> boolForce the inverse-by-emission fallback path.
Returns:
bool — Always False.
supports_if_else¶
def supports_if_else(self) -> boolDelegate native if/else support to the wrapped emitter.
Returns:
bool — The real emitter’s answer.
supports_reusable_gates¶
def supports_reusable_gates(self) -> boolForce the gate-by-gate fallback path.
Returns:
bool — Always False.
supports_while_loop¶
def supports_while_loop(self) -> boolDelegate native while-loop support to the wrapped emitter.
Returns:
bool — The real emitter’s answer.
DictGetItemOperation [source]¶
class DictGetItemOperation(Operation)Look up one entry of a Dict by a (possibly symbolic) key.
This is the IR form of d[key] on a Dict handle. The key
components may be symbolic (e.g. loop variables of a for-items
loop); the lookup is resolved at emit time when the key values and
the dict’s bound data are both concrete.
operands: [DictValue, *key_component_values] results: [looked-up scalar value]
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
key_arity: int = 1,
) -> NoneAttributes¶
dict_value: Value Value: The DictValue being indexed (operands[0]).key_arity: intkey_values: tuple[Value, ...] tuple[Value, ...]: The key component values.operation_kind: OperationKindsignature: Signature
EmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
operation
ForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationGateOperation [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,
) -> NoneAttributes¶
gate_type: GateOperationType | Noneoperation_kind: OperationKindqubit_operands: list[Value] Qubit operands (excluding the theta parameter if present).signature: Signaturetheta: Value | None Angle parameter for rotation gates, orNonefor fixed gates.
Methods¶
fixed¶
@classmethod
def fixed(
cls,
gate_type: GateOperationType,
qubits: list[Value],
results: list[Value],
) -> 'GateOperation'Create a fixed gate (H, X, CX, SWAP, …) with no angle parameter.
rotation¶
@classmethod
def rotation(
cls,
gate_type: GateOperationType,
qubits: list[Value],
theta: Value,
results: list[Value],
) -> 'GateOperation'Create a rotation gate (RX, RY, RZ, P, CP, RZZ) with an angle.
GateOperationType [source]¶
class GateOperationType(enum.Enum)Attributes¶
CPCXCZHPRXRYRZRZZSSDGSWAPTTDGTOFFOLIXYZ
GlobalPhaseOperation [source]¶
class GlobalPhaseOperation(Operation)Multiply the complete quantum state by exp(i * phase).
Global phase has no target qubit and does not create a new quantum value. Keeping the phase as the operation’s sole ordinary operand lets generic IR passes substitute, serialize, and analyze it without a special value-field protocol. A surrounding controlled-unitary lowering turns the operation into an observable phase gate on the accumulated controls.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[Value] | Exactly one scalar FloatType phase angle in radians. |
results | list[Value] | Must be empty because global phase changes no qubit identity. |
Raises:
ValueError— If the operand/result layout is invalid or the phase is not a scalarFloatTypevalue.
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKind Classify global phase as a quantum operation.phase: Value Return the scalar phase-angle operand.signature: Signature Return the zero-qubit operation signature.
HasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
InverseBlockOperation [source]¶
class InverseBlockOperation(Operation)Represent an inverse qkernel/block as a first-class IR operation.
The operation stores both the original forward block and a Qamomile-built
inverse implementation block. Emitters may use source_block with a
engine-native inverse/adjoint primitive, then fall back to
implementation_block when native inversion is unavailable.
Operands are ordered as scalar control qubits, target quantum operands,
then classical/object parameters. Results mirror the quantum operand
layout: control results first, then one target result per target operand.
Vector target operands therefore count as one operand/result while
contributing their scalar width to num_target_qubits.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_control_qubits: int = 0,
num_target_qubits: int = 0,
custom_name: str = '',
source_block: Block | None = None,
implementation_block: Block | None = None,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_qubits: list[‘Value’] Return control quantum operands.control_value: int | Nonecustom_name: strimplementation_block: Block | Nonename: str Return a human-readable inverse operation name.num_control_qubits: intnum_target_qubits: intoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return classical/object parameter operands.signature: Signature Return the operation signature.source_block: Block | Nonetarget_qubits: list[‘Value’] Return target quantum operands.
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[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. |
definition | CallableDef | None | Optional 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,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueor an Oracle control-partition field has an invalid Python type.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width, or if Oracle invocation and definition control metadata disagree.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of relevant callable implementations.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return a conservative union of measurement-derived results.name: str Return the display name for this invocation.num_added_control_qubits: int Return controls introduced by a frontend control transform.num_body_external_control_qubits: int Return control operands generic lowering adds outside a base body.num_control_qubits: int Return the number of leading control-qubit operands.num_declared_control_qubits: int Return controls included in an opaque Oracle’s base definition.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
effective_body¶
def effective_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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 | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None, which only selects engine-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
require_body | bool | Whether 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name used for implementation selection. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
select_body¶
def select_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> CallableBodySelectionSelect 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
NotOp [source]¶
class NotOp(Operation)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
input: Valueoperation_kind: OperationKindoutput: Valuesignature: Signature
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()) -> NoneAttributes¶
evolved_qubits: Value The evolved quantum register result.gamma: Value The evolution time parameter.observable: Value The Observable parameter operand.operation_kind: OperationKind PauliEvolveOp is QUANTUM - transforms quantum state.qubits: Value The quantum register operand.signature: Signature
QInitOperation [source]¶
class QInitOperation(Operation)Initialize the qubit
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
QubitAddress [source]¶
class QubitAddressTyped 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) -> NoneAttributes¶
element_index: int | Noneis_array_element: bool True if this address refers to an array element.uuid: str
Methods¶
from_composite_key¶
@classmethod
def from_composite_key(cls, key: str) -> QubitAddressParse 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) -> boolTrue if this address belongs to the given array.
with_element¶
def with_element(self, index: int) -> QubitAddressCreate an array-element address from this array’s base UUID.
ReleaseSliceViewOperation [source]¶
class ReleaseSliceViewOperation(Operation)Mark a slice view’s borrow as explicitly returned to its parent.
Emitted by :meth:Vector.__setitem__ when used with a slice index
(qs[a:b] = qmc.h(qs[a:b])). This op tells the post-fold
linearity checker
(:class:~qamomile.circuit.transpiler.passes.slice_borrow_check.SliceBorrowCheckPass)
that the view referenced in operands[0] no longer owns its
covered parent slots, mirroring the frontend’s
VectorView.consume(operation_name="slice assignment") borrow
release.
Like :class:SliceArrayOperation, this op is a declarative
classical-side marker that does not survive into the emit stream:
:class:~qamomile.circuit.transpiler.passes.strip_slice_ops.StripSliceArrayOpsPass
removes both :class:SliceArrayOperation and
:class:ReleaseSliceViewOperation after
:class:SliceBorrowCheckPass has observed them. Reaching emit
is a compiler-internal invariant violation and is rejected with a
RuntimeError from :mod:standard_emit.
Within a control-flow body (ForOperation / WhileOperation
/ IfOperation), this op only releases view borrows that were
created within the same body. Releasing a borrow that the
enclosing block has registered (an “outer-snapshot” borrow) is
rejected by SliceBorrowCheckPass with ValidationError — the
loop-merge semantics of the
pass cannot propagate entry deletions out of the body, so the only
way to keep the static check consistent is to forbid that pattern.
Example:
``qs[1:3] = qmc.h(qs[1:3])`` emits, after the broadcast loop::
ReleaseSliceViewOperation(
operands=[qmc_h_result_view], # slice_of=qs_value
results=[],
)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKind Release is classical — it updates borrow tracking metadata only.signature: Signature Return the type signature of this release operation.
ResolvedControlledU [source]¶
class ResolvedControlledUPhysical resolution of one ControlledUOperation call site.
Produced by :func:resolve_controlled_u_call for every concrete and
symbolic operand layout, so walkers can lower nested controlled-U
operations without shape-specific branching.
Constructor¶
def __init__(
self,
control_phys: list[int],
control_operand_groups: list[list[int]],
target_qubit_operands: list[Any],
target_index_groups: list[list[int]],
target_phys: list[int],
block: Any,
local_bindings: dict[str, Any],
) -> NoneAttributes¶
block: Anycontrol_operand_groups: list[list[int]]control_phys: list[int]local_bindings: dict[str, Any]target_index_groups: list[list[int]]target_phys: list[int]target_qubit_operands: list[Any]
ReturnOperation [source]¶
class ReturnOperation(Operation)Explicit return operation marking the end of a block with return values.
This operation represents an explicit return statement in the IR. It takes the values to be returned as operands and produces no results (it is a terminal operation that transfers control flow back to the caller).
operands: [Value, ...] - The values to return (may be empty for void returns) results: [] - Always empty (terminal operation)
Example:
A function that returns two values (a UInt and a Float):
ReturnOperation(
operands=[uint_value, float_value],
results=[],
)
The signature would be:
operands=[ParamHint("return_0", UIntType()), ParamHint("return_1", FloatType())]
results=[]Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKind Return CLASSICAL as this is a control flow operation without quantum effects.signature: Signature Return the signature with operands for each return value and no results.
ReturnQuantumArrayElementOperation [source]¶
class ReturnQuantumArrayElementOperation(Operation)Validate a branch-selected quantum element’s array return at emit time.
Most quantum element assignments are verified structurally by the frontend and emit no IR. A compile-time conditional can instead select different element indices on its branches; only the unrolled emit context knows which source index survived. This operation carries both the requested target indices and the conditional source indices so emission can prove they resolve to the same physical slot before treating the assignment as a borrow return.
Operand convention:
[array, returned_qubit, *target_indices, *source_indices]. The
target and source halves have equal nonzero arity, inferred from the
operand count. The operation has no results and emits no engine gate.
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
array: ArrayValue Return the quantum array receiving the borrowed element.index_arity: int Return the number of target (and source) index operands.operation_kind: OperationKind Classify the return validator as a quantum operation.returned_value: Value Return the quantum value being returned.signature: Signature Return the deferred validator’s operand-only signature.source_indices: tuple[Value, ...] Return the branch-merged borrow-source indices.target_indices: tuple[Value, ...] Return the user-written assignment indices.
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(),
) -> NoneAttributes¶
case_blocks: list[Block]case_callable_attrs: list[dict[str, Any]]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
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]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[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()) -> NoneAttributes¶
operation_kind: OperationKind Slice is classical — it selects indices without quantum action.signature: Signature Return the type signature of this slice operation.
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:
| Name | Type | Description |
|---|---|---|
gate_emitter | GateEmitter[T] | Instruction builder used during the semantic traversal. |
bindings | dict[str, Any] | None | Compile-time parameter bindings. |
parameters | list[str] | None | Parameter names preserved at runtime. |
composite_emitters | list[CompositeGateEmitter[T]] | None | Optional callable-preservation or lowering hooks. |
engine_name | str | None | Diagnostic 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¶
engine_name
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:
Compile time:
ConstantFoldingPassfolds the store when the source array contents, the index, and the stored value are all compile-time resolvable, attaching the updatedconst_arraymetadata to the result value.Runtime: otherwise the store executes host-side in a classical segment via
ClassicalExecutor(e.g. for measurement-derivedVector[Bit]contents). It must never reach a quantum segment; engine emit rejects it explicitly.
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 bitsConstructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
array: ArrayValue ArrayValue: The array version the store reads from.index_values: tuple[Value, ...] tuple[Value, ...]: The element indices being written.operation_kind: OperationKindsignature: Signature Return the operation’s dynamic array/qubit/index signature.stored_value: Value Value: The scalar being written into the array.
SymbolicControlledU [source]¶
class SymbolicControlledU(ControlledUOperation)Controlled-U with symbolic (Value) number of controls.
Operand layout: [ctrl_arg_0, ..., ctrl_arg_{k-1}, tgt_0, ..., tgt_m, params...]
Result layout: [ctrl_arg_0', ..., ctrl_arg_{k-1}', tgt_0', ..., tgt_m']
The number of control arguments k is recorded in
num_control_args; the default k = 1 corresponds to the
historical single-pool form (operands[0] is a
Vector[Qubit] / VectorView whose length equals
num_controls, or whose control_indices-selected subset
does). When k > 1 the control prefix is a heterogeneous
sequence of scalar Qubit values and ArrayValues whose
total qubit count is num_controls; the emit pass walks them
in order to recover the per-physical-qubit control set.
When control_indices is None the entire control prefix
is used as active controls (one-arg form: len(ctrl_vector) == num_controls; multi-arg form: the qubit-count sum of the
prefix args equals num_controls). When non-None, the
listed indices select exactly num_controls slots from a
single-arg pool to act as controls; combining
control_indices with the multi-arg control prefix is
rejected at frontend time.
Each control_indices entry is stored as a Value of
UIntType regardless of whether the frontend passed an
int literal or a UInt handle, so all downstream
value-substitution passes see a uniform shape.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
power: int | Value = 1,
block: Block | None = None,
num_controls: Value = (lambda: Value(type=(UIntType()), name=''))(),
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_indices: tuple[Value, ...] | None = None,
num_control_args: int = 1,
) -> NoneAttributes¶
control_indices: tuple[Value, ...] | Nonecontrol_operands: list[Value]is_symbolic_num_controls: boolnum_control_args: intnum_controls: Valueparam_operands: list[Value] Get classical/object operands after the symbolic control prefix.signature: Signaturetarget_operands: list[Value] Return the wrapped callable’s target and parameter operands.
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationUnaryMathOp [source]¶
class UnaryMathOp(Operation)Represent one pure unary mathematical expression.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[Value] | Single numeric input value. |
results | list[Value] | Single numeric result value. |
kind | UnaryMathOpKind | None | Mathematical operation to apply. |
Raises:
ValueError— Ifkindis missing or the operation does not have exactly one operand and one result.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: UnaryMathOpKind | None = None,
) -> NoneAttributes¶
input: Value Return the input value.kind: UnaryMathOpKind | Noneoperation_kind: OperationKind Classify the operation as classical.output: Value Return the output value.signature: Signature Return the typed unary signature.
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
qamomile.circuit.transpiler.passes.emit_support.counting_emitter¶
Count-only emitter for measuring multi-control ancilla demand.
A quantum segment’s engine circuit is created with a fixed qubit count before emission starts, so the multi-control ancilla pool must be sized in advance. Rather than mirror the emit-time control-absorption rules in a separate static walk — which has to stay in lockstep with the real emitter or it will silently under-reserve — the demand is measured by running the real emission machinery once against this no-op emitter and a counting ancilla pool.
Every gate emission is a no-op and every structural query returns a value
that keeps the walk on its cascade-prone fallback path (circuit_to_gate
/ gate_controlled / gate_power / gate_inverse return None and
supports_reusable_gates / supports_gate_inverse are False), so the
count is an upper bound and never touches a real circuit object. Capability
queries (measurement_mode and the control-flow supports_* hooks)
delegate to the wrapped emitter so the walk takes the same unroll-versus-
native-loop decisions the real emission would.
Overview¶
| Class | Description |
|---|---|
CountingEmitter | A no-op gate emitter that lets a real emission walk run for counting. |
MeasurementMode | How an engine handles measurement operations. |
Classes¶
CountingEmitter [source]¶
class CountingEmitterA no-op gate emitter that lets a real emission walk run for counting.
Wraps the real engine emitter, delegating capability queries so
control-flow lowering matches real emission while turning every gate
emission into a no-op and every gate/sub-circuit construction into a
None that forces the cascade-prone fallback path. Used by isolated
analysis-emission transactions for ancilla sizing and zero-work semantic
validation; the object is passed where a GateEmitter[T] is expected
via a cast.
Constructor¶
def __init__(self, real: Any) -> NoneWrap a real emitter for a counting run.
Parameters:
| Name | Type | Description |
|---|---|---|
real | Any | The engine emitter whose capability answers should be mirrored so the walk makes the same structural choices. |
Attributes¶
measurement_mode: MeasurementMode Delegate the measurement mode to the wrapped emitter.
Methods¶
append_gate¶
def append_gate(self, circuit: Any, gate: Any, qubits: list[int]) -> NoneCount appending a prebuilt gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
gate | Any | Ignored gate object (never built in counting mode). |
qubits | list[int] | Ignored qubit indices the gate acts on. |
circuit_to_gate¶
def circuit_to_gate(self, circuit: Any, name: str = 'U') -> AnyForce the fallback path by declining to build a reusable gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
name | str | Ignored gate name. Defaults to "U". |
Returns:
Any — Always None.
combine_symbolic¶
def combine_symbolic(self, kind: Any, lhs: Any, rhs: Any) -> _CountingParameterReturn a placeholder for a symbolic angle combination.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | Any | Ignored binary-op kind. |
lhs | Any | Ignored left operand. |
rhs | Any | Ignored right operand. |
Returns:
_CountingParameter — A placeholder symbolic angle.
create_circuit¶
def create_circuit(self, num_qubits: int, num_clbits: int) -> _CountingCircuitReturn a placeholder circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
num_qubits | int | Ignored. |
num_clbits | int | Ignored. |
Returns:
_CountingCircuit — A stateless placeholder.
create_parameter¶
def create_parameter(self, name: str) -> _CountingParameterReturn an arithmetic-absorbing placeholder parameter.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Ignored. |
Returns:
_CountingParameter — A placeholder runtime parameter.
emit_barrier¶
def emit_barrier(self, circuit: Any, qubits: list[int]) -> NoneCount a barrier as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubits | list[int] | Ignored qubit indices spanned by the barrier. |
emit_ch¶
def emit_ch(self, circuit: Any, control: int, target: int) -> NoneCount a CH gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
emit_cp¶
def emit_cp(self, circuit: Any, control: int, target: int, angle: Any) -> NoneCount a controlled-phase gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
angle | Any | Ignored phase angle. |
emit_crx¶
def emit_crx(self, circuit: Any, control: int, target: int, angle: Any) -> NoneCount a CRX gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
angle | Any | Ignored rotation angle. |
emit_cry¶
def emit_cry(self, circuit: Any, control: int, target: int, angle: Any) -> NoneCount a CRY gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
angle | Any | Ignored rotation angle. |
emit_crz¶
def emit_crz(self, circuit: Any, control: int, target: int, angle: Any) -> NoneCount a CRZ gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
angle | Any | Ignored rotation angle. |
emit_cx¶
def emit_cx(self, circuit: Any, control: int, target: int) -> NoneCount a CX gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
emit_cy¶
def emit_cy(self, circuit: Any, control: int, target: int) -> NoneCount a CY gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
emit_cz¶
def emit_cz(self, circuit: Any, control: int, target: int) -> NoneCount a CZ gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
emit_else_start¶
def emit_else_start(self, circuit: Any, context: Any) -> NoneCount the start of a native else branch as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
context | Any | Ignored branch context from emit_if_start. |
emit_for_loop_end¶
def emit_for_loop_end(self, circuit: Any, context: Any) -> NoneCount the end of a native for loop as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
context | Any | Ignored loop context from emit_for_loop_start. |
emit_for_loop_start¶
def emit_for_loop_start(self, circuit: Any, indexset: range) -> AnyReturn a placeholder loop variable for a native-for-loop count.
Unlike the other control-flow hooks, emit_for’s return value is
bound as the loop variable (via _bind_loop_var) and the body is
then walked once. A real native-loop emitter returns a symbolic
loop parameter, so return the arithmetic-absorbing
:class:_CountingParameter rather than None — otherwise a
body that carries the loop value into an angle or index expression
during counting would see None and fail. (No pool-reserving
engine supports native for loops today, so this is future-proofing.)
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored. |
indexset | range | Ignored. |
Returns:
Any — A placeholder loop variable.
emit_global_phase¶
def emit_global_phase(self, circuit: Any, angle: Any) -> NoneAccept a standalone phase during the internal counting walk.
The counting emitter observes only peak clean-ancilla demand. It does not materialize any gate, including a phase that the wrapped real emitter will preserve during the subsequent emission walk.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
angle | Any | Ignored phase angle. |
emit_h¶
def emit_h(self, circuit: Any, qubit: int) -> NoneCount an H gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_if_end¶
def emit_if_end(self, circuit: Any, context: Any) -> NoneCount the end of a native if/else block as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
context | Any | Ignored branch context from emit_if_start. |
emit_if_start¶
def emit_if_start(self, circuit: Any, clbit: int, value: int = 1) -> AnyCount the start of a native if branch as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
clbit | int | Ignored predicate classical bit index. |
value | int | Ignored predicate value to match. Defaults to 1. |
Returns:
Any — Always None (a null branch context).
emit_measure¶
def emit_measure(self, circuit: Any, qubit: int, clbit: int) -> NoneCount a measurement as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored measured qubit index. |
clbit | int | Ignored destination classical bit index. |
emit_p¶
def emit_p(self, circuit: Any, qubit: int, angle: Any) -> NoneCount a phase gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
angle | Any | Ignored phase angle. |
emit_reset¶
def emit_reset(self, circuit: Any, qubit: int) -> NoneCount a reset as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored reset qubit index. |
emit_rx¶
def emit_rx(self, circuit: Any, qubit: int, angle: Any) -> NoneCount an RX gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
angle | Any | Ignored rotation angle. |
emit_ry¶
def emit_ry(self, circuit: Any, qubit: int, angle: Any) -> NoneCount an RY gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
angle | Any | Ignored rotation angle. |
emit_rz¶
def emit_rz(self, circuit: Any, qubit: int, angle: Any) -> NoneCount an RZ gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
angle | Any | Ignored rotation angle. |
emit_rzz¶
def emit_rzz(self, circuit: Any, qubit1: int, qubit2: int, angle: Any) -> NoneCount an RZZ gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit1 | int | Ignored first qubit index. |
qubit2 | int | Ignored second qubit index. |
angle | Any | Ignored rotation angle. |
emit_s¶
def emit_s(self, circuit: Any, qubit: int) -> NoneCount an S gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_sdg¶
def emit_sdg(self, circuit: Any, qubit: int) -> NoneCount an Sdg gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_swap¶
def emit_swap(self, circuit: Any, qubit1: int, qubit2: int) -> NoneCount a SWAP gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit1 | int | Ignored first qubit index. |
qubit2 | int | Ignored second qubit index. |
emit_t¶
def emit_t(self, circuit: Any, qubit: int) -> NoneCount a T gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_tdg¶
def emit_tdg(self, circuit: Any, qubit: int) -> NoneCount a Tdg gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_toffoli¶
def emit_toffoli(self, circuit: Any, control1: int, control2: int, target: int) -> NoneCount a Toffoli gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control1 | int | Ignored first control qubit index. |
control2 | int | Ignored second control qubit index. |
target | int | Ignored target qubit index. |
emit_while_end¶
def emit_while_end(self, circuit: Any, context: Any) -> NoneCount the end of a native while loop as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
context | Any | Ignored loop context from emit_while_start. |
emit_while_start¶
def emit_while_start(self, circuit: Any, clbit: int, value: int = 1) -> AnyCount the start of a native while loop as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
clbit | int | Ignored predicate classical bit index. |
value | int | Ignored predicate value to match. Defaults to 1. |
Returns:
Any — Always None (a null loop context).
emit_x¶
def emit_x(self, circuit: Any, qubit: int) -> NoneCount an X gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_y¶
def emit_y(self, circuit: Any, qubit: int) -> NoneCount a Y gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_z¶
def emit_z(self, circuit: Any, qubit: int) -> NoneCount a Z gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
gate_controlled¶
def gate_controlled(self, gate: Any, num_controls: int) -> AnyDecline to build a real controlled gate.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | Any | Ignored gate object. |
num_controls | int | Ignored number of control qubits. |
Returns:
Any — Always None.
gate_inverse¶
def gate_inverse(self, gate: Any) -> AnyDecline to build a real inverse gate.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | Any | Ignored gate object. |
Returns:
Any — Always None.
gate_power¶
def gate_power(self, gate: Any, power: int) -> AnyDecline to build a real powered gate.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | Any | Ignored gate object. |
power | int | Ignored exponent. |
Returns:
Any — Always None.
supports_for_loop¶
def supports_for_loop(self) -> boolDelegate native-for-loop support to the wrapped emitter.
Returns:
bool — The real emitter’s answer, so loops unroll (or not) the
same way real emission would.
supports_gate_inverse¶
def supports_gate_inverse(self) -> boolForce the inverse-by-emission fallback path.
Returns:
bool — Always False.
supports_if_else¶
def supports_if_else(self) -> boolDelegate native if/else support to the wrapped emitter.
Returns:
bool — The real emitter’s answer.
supports_reusable_gates¶
def supports_reusable_gates(self) -> boolForce the gate-by-gate fallback path.
Returns:
bool — Always False.
supports_while_loop¶
def supports_while_loop(self) -> boolDelegate native while-loop support to the wrapped emitter.
Returns:
bool — The real emitter’s answer.
MeasurementMode [source]¶
class MeasurementMode(Enum)How an engine handles measurement operations.
Attributes¶
NATIVERUNNABLESTATIC
qamomile.circuit.transpiler.passes.emit_support.gate_emission¶
Gate emission helper extracted from StandardEmitPass.
Provides emit_gate and resolve_angle as module-level functions so
they can be tested and reused independently of the class.
Overview¶
| Function | Description |
|---|---|
emit_gate | Emit a single gate operation. |
reject_duplicate_physical_indices | Reject a multi-qubit gate whose qubits resolve to the same physical qubit. |
resolve_angle | Resolve angle parameter for rotation gates. |
resolve_angle_value | Resolve a bare angle Value to a concrete float or engine parameter. |
| Class | Description |
|---|---|
EmitError | Report an engine failure to emit one semantic operation. |
GateOperation | Quantum gate operation. |
GateOperationType | |
OperandResolutionInfo | Detailed information about a single operand that failed to resolve. |
QubitAddress | Typed key for qubit/clbit physical-index maps. |
QubitAliasError | Same qubit used multiple times in one operation. |
QubitIndexResolutionError | Error when qubit indices cannot be resolved during emission. |
ResolutionFailureReason | Categorizes why qubit index resolution failed. |
StandardEmitPass | Standard emit pass implementation using GateEmitter protocol. |
UnifiedValueResolver | Resolve IR Values to concrete Python values. |
Functions¶
emit_gate [source]¶
def emit_gate(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: GateOperation,
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> NoneEmit a single gate operation.
reject_duplicate_physical_indices [source]¶
def reject_duplicate_physical_indices(
gate_label: str,
physical_indices: list[int],
operand_names: list[str] | None = None,
) -> NoneReject 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:
| Name | Type | Description |
|---|---|---|
gate_label | str | Human-readable name of the gate for the message (e.g. "CX" or "controlled gate"). |
physical_indices | list[int] | The resolved physical qubit indices the gate acts on, in operand order. |
operand_names | list[str] | None | Optional 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:
QubitAliasError— If any physical qubit index repeats.
resolve_angle [source]¶
def resolve_angle(
emit_pass: 'StandardEmitPass',
op: GateOperation,
bindings: dict[str, Any],
) -> float | AnyResolve angle parameter for rotation gates.
The angle is always a Value stored as the last operand of a rotation
gate.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass providing parameter resolution and creation. |
op | GateOperation | Rotation gate whose angle is resolved. |
bindings | dict[str, Any] | Active compile-time bindings. |
Returns:
float | Any — float | Any: Concrete angle or engine parameter expression.
Raises:
EmitError— If the rotation angle is missing or cannot be resolved.
resolve_angle_value [source]¶
def resolve_angle_value(
emit_pass: 'StandardEmitPass',
theta: Any,
bindings: dict[str, Any],
) -> float | AnyResolve a bare angle Value to a concrete float or engine parameter.
Shared core of :func:resolve_angle so operations carrying a standalone
angle Value reuse the exact same resolution order as rotation-gate thetas.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass providing the resolver and engine-parameter factory. |
theta | Any | Angle Value to resolve. |
bindings | dict[str, Any] | Active compile-time bindings. |
Returns:
float | Any — float | Any: A concrete float when the angle is bound, or a
engine parameter expression when it stays symbolic.
Raises:
EmitError— If the angle is missing or cannot be resolved to a concrete value or engine parameter. Emitting0.0in this case would silently change the requested unitary.
Classes¶
EmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
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,
) -> NoneAttributes¶
gate_type: GateOperationType | Noneoperation_kind: OperationKindqubit_operands: list[Value] Qubit operands (excluding the theta parameter if present).signature: Signaturetheta: Value | None Angle parameter for rotation gates, orNonefor fixed gates.
Methods¶
fixed¶
@classmethod
def fixed(
cls,
gate_type: GateOperationType,
qubits: list[Value],
results: list[Value],
) -> 'GateOperation'Create a fixed gate (H, X, CX, SWAP, …) with no angle parameter.
rotation¶
@classmethod
def rotation(
cls,
gate_type: GateOperationType,
qubits: list[Value],
theta: Value,
results: list[Value],
) -> 'GateOperation'Create a rotation gate (RX, RY, RZ, P, CP, RZZ) with an angle.
GateOperationType [source]¶
class GateOperationType(enum.Enum)Attributes¶
CPCXCZHPRXRYRZRZZSSDGSWAPTTDGTOFFOLIXYZ
OperandResolutionInfo [source]¶
class OperandResolutionInfoDetailed 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,
) -> NoneAttributes¶
element_indices_names: list[str]failure_details: strfailure_reason: ResolutionFailureReasonis_array_element: booloperand_name: stroperand_uuid: strparent_array_name: str | None
QubitAddress [source]¶
class QubitAddressTyped 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) -> NoneAttributes¶
element_index: int | Noneis_array_element: bool True if this address refers to an array element.uuid: str
Methods¶
from_composite_key¶
@classmethod
def from_composite_key(cls, key: str) -> QubitAddressParse 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) -> boolTrue if this address belongs to the given array.
with_element¶
def with_element(self, index: int) -> QubitAddressCreate an array-element address from this array’s base UUID.
QubitAliasError [source]¶
class QubitAliasError(AffineTypeError)Same qubit used multiple times in one operation.
Operations like cx() require distinct qubits for control and target. Using the same qubit in both positions is physically impossible and indicates a programming error.
Example of incorrect code:
q1, q2 = qm.cx(q, q) # ERROR: same qubit as control and target
Correct code:
q1, q2 = qm.cx(control, target) # Use distinct qubits
QubitIndexResolutionError [source]¶
class QubitIndexResolutionError(EmitError)Error when qubit indices cannot be resolved during emission.
This error provides detailed diagnostic information about why qubit index resolution failed and suggests remediation steps.
Constructor¶
def __init__(
self,
gate_type: str,
operand_infos: list[OperandResolutionInfo],
available_bindings_keys: list[str],
available_qubit_map_keys: list[str],
)Initialize detailed qubit-index resolution diagnostics.
Parameters:
| Name | Type | Description |
|---|---|---|
gate_type | str | Gate whose operands could not be resolved. |
operand_infos | list[OperandResolutionInfo] | Per-operand failure details. |
available_bindings_keys | list[str] | Binding names visible during resolution. |
available_qubit_map_keys | list[str] | Qubit-map keys visible during resolution. |
Attributes¶
available_bindings_keysavailable_qubit_map_keysgate_typeoperand_infos
ResolutionFailureReason [source]¶
class ResolutionFailureReason(Enum)Categorizes why qubit index resolution failed.
Attributes¶
ARRAY_ELEMENT_NOT_IN_QUBIT_MAPDIRECT_UUID_NOT_FOUNDINDEX_NOT_NUMERICNEGATIVE_INDEXNESTED_ARRAY_RESOLUTION_FAILEDSYMBOLIC_INDEX_NOT_BOUNDUNKNOWN
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:
| Name | Type | Description |
|---|---|---|
gate_emitter | GateEmitter[T] | Instruction builder used during the semantic traversal. |
bindings | dict[str, Any] | None | Compile-time parameter bindings. |
parameters | list[str] | None | Parameter names preserved at runtime. |
composite_emitters | list[CompositeGateEmitter[T]] | None | Optional callable-preservation or lowering hooks. |
engine_name | str | None | Diagnostic 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¶
engine_name
ValueResolver [source]¶
class ValueResolverResolve IR Values to concrete Python values.
Parameters:
| Name | Type | Description |
|---|---|---|
context | dict[str, Any] | None | UUID-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. |
bindings | dict[str, Any] | None | Name-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:
| Name | Type | Description |
|---|---|---|
context | dict[str, Any] | None | UUID-keyed map of already-resolved values. Defaults to None. |
bindings | dict[str, Any] | None | Name-keyed parameter bindings supplied by the user. Defaults to None. |
Methods¶
resolve¶
def resolve(self, value: Any) -> Any | NoneResolve 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:
| Name | Type | Description |
|---|---|---|
value | Any | The Value-like object or already concrete value to resolve. |
Returns:
Any | None — Any | None: The resolved concrete value, the original
concrete value for non-Value inputs, or None when no
resolution rule applies.
qamomile.circuit.transpiler.passes.emit_support.global_phase_emission¶
Emit zero-qubit global-phase operations.
Overview¶
| Function | Description |
|---|---|
emit_controlled_global_phase | Emit the relative phase produced by controlling a global phase. |
emit_controlled_global_phase_operation | Emit a global phase as a relative phase under accumulated controls. |
emit_global_phase | Emit a standalone phase when the lowering adapter collects it. |
emit_resolved_global_phase | Emit an already resolved standalone phase without discarding it. |
is_exact_real_zero | Return whether a value is a concrete real scalar equal to zero. |
is_identity_phase_angle | Return whether a concrete angle is exactly zero modulo two pi. |
resolve_angle_value | Resolve a bare angle Value to a concrete float or engine parameter. |
| Class | Description |
|---|---|
EmitError | Report an engine failure to emit one semantic operation. |
GateOperationType | |
GlobalPhaseOperation | Multiply the complete quantum state by exp(i * phase). |
StandardEmitPass | Standard emit pass implementation using GateEmitter protocol. |
Functions¶
emit_controlled_global_phase [source]¶
def emit_controlled_global_phase(
emit_pass: 'StandardEmitPass',
circuit: Any,
control_indices: list[int],
angle: Any,
) -> NoneEmit the relative phase produced by controlling a global phase.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
control_indices | list[int] | Physical controls gating the phase. |
angle | Any | Resolved phase angle. |
Raises:
EmitError— If three or more controls are requested but the engine provides neither a native primitive nor the shared clean-ancilla decomposition.
emit_controlled_global_phase_operation [source]¶
def emit_controlled_global_phase_operation(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: GlobalPhaseOperation,
control_indices: list[int],
bindings: dict[str, Any],
) -> NoneEmit a global phase as a relative phase under accumulated controls.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Circuit representation being emitted into. |
op | GlobalPhaseOperation | Global-phase operation to control. |
control_indices | list[int] | Accumulated physical control qubits. |
bindings | dict[str, Any] | Active emit bindings. |
Raises:
EmitError— If the phase cannot be resolved or the adapter cannot emit the accumulated control arity.
emit_global_phase [source]¶
def emit_global_phase(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: GlobalPhaseOperation,
bindings: dict[str, Any],
) -> NoneEmit a standalone phase when the lowering adapter collects it.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Circuit representation being emitted into. |
op | GlobalPhaseOperation | Global-phase operation to emit. |
bindings | dict[str, Any] | Active emit bindings. |
Raises:
EmitError— If the adapter cannot preserve or resolve the phase.
emit_resolved_global_phase [source]¶
def emit_resolved_global_phase(emit_pass: 'StandardEmitPass', circuit: Any, angle: Any) -> NoneEmit an already resolved standalone phase without discarding it.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Circuit representation being emitted into. |
angle | Any | Resolved phase angle. |
Raises:
EmitError— If the selected emitter cannot preserve the phase.
is_exact_real_zero [source]¶
def is_exact_real_zero(value: Any) -> boolReturn whether a value is a concrete real scalar equal to zero.
The comparison intentionally has no tolerance: a tiny nonzero value must remain observable, while engine parameter expressions remain unresolved.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Any | Concrete numeric value or engine parameter expression. |
Returns:
bool — True only for a non-boolean real scalar exactly equal to
bool — zero.
is_identity_phase_angle [source]¶
def is_identity_phase_angle(angle: Any) -> boolReturn whether a concrete angle is exactly zero modulo two pi.
The test intentionally uses no tolerance so a tiny but nonzero phase is never discarded. Runtime parameter expressions remain non-identity until an engine resolves them to a concrete number.
Parameters:
| Name | Type | Description |
|---|---|---|
angle | Any | Resolved numeric angle or engine parameter expression. |
Returns:
bool — Whether angle is a finite real number exactly congruent to
bool — zero modulo 2 * pi.
resolve_angle_value [source]¶
def resolve_angle_value(
emit_pass: 'StandardEmitPass',
theta: Any,
bindings: dict[str, Any],
) -> float | AnyResolve a bare angle Value to a concrete float or engine parameter.
Shared core of :func:resolve_angle so operations carrying a standalone
angle Value reuse the exact same resolution order as rotation-gate thetas.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass providing the resolver and engine-parameter factory. |
theta | Any | Angle Value to resolve. |
bindings | dict[str, Any] | Active compile-time bindings. |
Returns:
float | Any — float | Any: A concrete float when the angle is bound, or a
engine parameter expression when it stays symbolic.
Raises:
EmitError— If the angle is missing or cannot be resolved to a concrete value or engine parameter. Emitting0.0in this case would silently change the requested unitary.
Classes¶
EmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
operation
GateOperationType [source]¶
class GateOperationType(enum.Enum)Attributes¶
CPCXCZHPRXRYRZRZZSSDGSWAPTTDGTOFFOLIXYZ
GlobalPhaseOperation [source]¶
class GlobalPhaseOperation(Operation)Multiply the complete quantum state by exp(i * phase).
Global phase has no target qubit and does not create a new quantum value. Keeping the phase as the operation’s sole ordinary operand lets generic IR passes substitute, serialize, and analyze it without a special value-field protocol. A surrounding controlled-unitary lowering turns the operation into an observable phase gate on the accumulated controls.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[Value] | Exactly one scalar FloatType phase angle in radians. |
results | list[Value] | Must be empty because global phase changes no qubit identity. |
Raises:
ValueError— If the operand/result layout is invalid or the phase is not a scalarFloatTypevalue.
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKind Classify global phase as a quantum operation.phase: Value Return the scalar phase-angle operand.signature: Signature Return the zero-qubit operation signature.
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:
| Name | Type | Description |
|---|---|---|
gate_emitter | GateEmitter[T] | Instruction builder used during the semantic traversal. |
bindings | dict[str, Any] | None | Compile-time parameter bindings. |
parameters | list[str] | None | Parameter names preserved at runtime. |
composite_emitters | list[CompositeGateEmitter[T]] | None | Optional callable-preservation or lowering hooks. |
engine_name | str | None | Diagnostic 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¶
engine_name
qamomile.circuit.transpiler.passes.emit_support.inverse_emission¶
Inverse block emission helpers extracted from StandardEmitPass.
Emits :class:InverseBlockOperation with a three-tier strategy: try the
engine-native inverse of the forward source_block first (reusable
gate + gate_inverse), then a reusable gate built from the
implementation_block fallback, and finally inline the fallback
gate by gate. Each function takes an emit_pass parameter (a
StandardEmitPass instance) in place of self so subclass
overrides (e.g. engine emit passes) are respected, mirroring
:mod:.controlled_emission.
Overview¶
| Function | Description |
|---|---|
bracket_control_value | Bracket zero-valued controls with target-neutral Pauli-X gates. |
emit_inverse_block | Emit a first-class inverse block operation. |
emit_inverse_block_at_indices | Emit an inverse block after physical qubits have been resolved. |
map_array_result_group | Map an array-valued result to a physical index group. |
reject_duplicate_physical_indices | Reject a multi-qubit gate whose qubits resolve to the same physical qubit. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
EmitError | Report an engine failure to emit one semantic operation. |
InverseBlockOperation | Represent an inverse qkernel/block as a first-class IR operation. |
QubitAddress | Typed key for qubit/clbit physical-index maps. |
StandardEmitPass | Standard emit pass implementation using GateEmitter protocol. |
Functions¶
bracket_control_value [source]¶
def bracket_control_value(
emit_pass: 'StandardEmitPass',
circuit: Any,
control_indices: Sequence[int],
control_value: int | None,
) -> Generator[None, None, None]Bracket zero-valued controls with target-neutral Pauli-X gates.
The controlled operation inside the context remains an ordinary all-ones
control. Controls are interpreted LSB-first in their existing physical
order, so bit zero of control_value describes control_indices[0].
One bracket surrounds the complete operation, including integral powers
and vector-target broadcast.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass providing the gate emitter. |
circuit | Any | Circuit receiving the bracket gates. |
control_indices | Sequence[int] | Ordered physical control qubits. |
control_value | int | None | Required basis value, or None for the ordinary all-ones state. |
Yields:
None — Control returns while the zero-valued controls are inverted.
Raises:
TypeError— Ifcontrol_valueis not a PythonintorNone.ValueError— If the activation value does not fit the control width.
emit_inverse_block [source]¶
def emit_inverse_block(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: InverseBlockOperation,
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> NoneEmit a first-class inverse block operation.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
op | InverseBlockOperation | Inverse block operation to emit. |
qubit_map | QubitMap | Current quantum value to physical qubit map. |
bindings | dict[str, Any] | Active emit bindings. |
Raises:
EmitError— If an inverse block has missing blocks, unresolved qubit operands, or no available native/fallback emission path.
emit_inverse_block_at_indices [source]¶
def emit_inverse_block_at_indices(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: InverseBlockOperation,
control_indices: list[int],
target_indices: list[int],
bindings: dict[str, Any],
) -> NoneEmit an inverse block after physical qubits have been resolved.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
op | InverseBlockOperation | Inverse block operation to emit. |
control_indices | list[int] | Physical control qubits in enclosing-first order, followed by this operation’s own controls. |
target_indices | list[int] | Physical target qubits. |
bindings | dict[str, Any] | Active emit bindings. |
Raises:
EmitError— If required source/fallback blocks are missing or no emission path can represent the operation.QubitBorrowConflictError— If nested slice views have overlapping live ownership.QubitConsumedError— If a nested block accesses a qubit slot after a destructive operation consumed it.ValidationError— If nested slice ownership cannot be represented safely across a control-flow boundary.
map_array_result_group [source]¶
def map_array_result_group(result_uuid: str, index_group: list[int], index_map: PhysicalIndexMap) -> NoneMap an array-valued result to a physical index group.
Parameters:
| Name | Type | Description |
|---|---|---|
result_uuid | str | UUID of the array-valued result whose element addresses should be registered. |
index_group | list[int] | Physical indices for the result elements, in result-local element order. |
index_map | PhysicalIndexMap | Mutable physical-index map updated in place with element addresses and, when available, the base result address. |
reject_duplicate_physical_indices [source]¶
def reject_duplicate_physical_indices(
gate_label: str,
physical_indices: list[int],
operand_names: list[str] | None = None,
) -> NoneReject 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:
| Name | Type | Description |
|---|---|---|
gate_label | str | Human-readable name of the gate for the message (e.g. "CX" or "controlled gate"). |
physical_indices | list[int] | The resolved physical qubit indices the gate acts on, in operand order. |
operand_names | list[str] | None | Optional 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:
QubitAliasError— If any physical qubit index repeats.
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,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]EmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
operation
InverseBlockOperation [source]¶
class InverseBlockOperation(Operation)Represent an inverse qkernel/block as a first-class IR operation.
The operation stores both the original forward block and a Qamomile-built
inverse implementation block. Emitters may use source_block with a
engine-native inverse/adjoint primitive, then fall back to
implementation_block when native inversion is unavailable.
Operands are ordered as scalar control qubits, target quantum operands,
then classical/object parameters. Results mirror the quantum operand
layout: control results first, then one target result per target operand.
Vector target operands therefore count as one operand/result while
contributing their scalar width to num_target_qubits.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_control_qubits: int = 0,
num_target_qubits: int = 0,
custom_name: str = '',
source_block: Block | None = None,
implementation_block: Block | None = None,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_qubits: list[‘Value’] Return control quantum operands.control_value: int | Nonecustom_name: strimplementation_block: Block | Nonename: str Return a human-readable inverse operation name.num_control_qubits: intnum_target_qubits: intoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return classical/object parameter operands.signature: Signature Return the operation signature.source_block: Block | Nonetarget_qubits: list[‘Value’] Return target quantum operands.
QubitAddress [source]¶
class QubitAddressTyped 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) -> NoneAttributes¶
element_index: int | Noneis_array_element: bool True if this address refers to an array element.uuid: str
Methods¶
from_composite_key¶
@classmethod
def from_composite_key(cls, key: str) -> QubitAddressParse 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) -> boolTrue if this address belongs to the given array.
with_element¶
def with_element(self, index: int) -> QubitAddressCreate an array-element address from this array’s base UUID.
StandardEmitPass [source]¶
class StandardEmitPass(EmitPass[T], Generic[T])Standard emit pass implementation using GateEmitter protocol.
This class provides orchestration for semantic IR traversal while
delegating circuit instruction construction to a GateEmitter. The
concrete compiler use is CircuitLoweringPass; SDK targets materialize
its immutable result instead of subclassing this class.
Parameters:
| Name | Type | Description |
|---|---|---|
gate_emitter | GateEmitter[T] | Instruction builder used during the semantic traversal. |
bindings | dict[str, Any] | None | Compile-time parameter bindings. |
parameters | list[str] | None | Parameter names preserved at runtime. |
composite_emitters | list[CompositeGateEmitter[T]] | None | Optional callable-preservation or lowering hooks. |
engine_name | str | None | Diagnostic 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¶
engine_name
qamomile.circuit.transpiler.passes.emit_support.loop_analyzer¶
Loop analysis helpers for emission.
Identity policy: loop variables are identified by their IR Value
UUID (ForOperation.loop_var_value.uuid), not by their display
name. Two nested or sibling loops with identical user-chosen names
(e.g. for i in range(N): for i in range(M):) are distinct here
because each ForOperation carries its own loop_var_value with
a fresh UUID, and UUIDRemapper clones that field consistently with
body references via the all_input_values / replace_values
protocol.
There is no name fallback: if loop_var_value is None (legacy
IR built before the field existed), analysis conservatively requests
unrolling and the emit entry point rejects the malformed IR. Comparing by
name was the soil for nested-loop name-collision bugs.
Overview¶
| Class | Description |
|---|---|
BinOp | Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN). |
CompOp | Comparison operation (EQ, NEQ, LT, LE, GT, GE). |
CondOp | Conditional logical operation (AND, OR). |
ControlledUOperation | Base class for controlled-U operations. |
DictGetItemOperation | Look up one entry of a Dict by a (possibly symbolic) key. |
ForItemsOperation | Represents iteration over dict/iterable items. |
ForOperation | Represents a for loop operation. |
GlobalPhaseOperation | Multiply the complete quantum state by exp(i * phase). |
HasNestedOps | Mixin for operations that contain nested operation lists. |
IfOperation | Represents an if-else conditional operation. |
InverseBlockOperation | Represent an inverse qkernel/block as a first-class IR operation. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
LoopAnalyzer | Analyze loop structures to determine an emission strategy. |
NotOp | |
PauliEvolveOp | Pauli evolution operation: exp(-i * gamma * H). |
RuntimeClassicalExpr | A classical expression known to require runtime evaluation. |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
Value | A typed SSA value in the IR. |
WhileOperation | Represents a while loop operation. |
Classes¶
BinOp [source]¶
class BinOp(BinaryOperationBase)Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: BinOpKind | None = None,
) -> NoneAttributes¶
kind: BinOpKind | Noneoperation_kind: OperationKindsignature: Signature
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,
) -> NoneAttributes¶
kind: CompOpKind | Noneoperation_kind: OperationKindsignature: Signature
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,
) -> NoneAttributes¶
kind: CondOpKind | Noneoperation_kind: OperationKindsignature: Signature
ControlledUOperation [source]¶
class ControlledUOperation(Operation)Base class for controlled-U operations.
Two concrete subclasses handle distinct operand layouts:
ConcreteControlledU: Fixednum_controls: int, individual qubit operands.SymbolicControlledU: Symbolicnum_controls: Value, vector-based control operands; optionalcontrol_indicesselects a subset of the control vector to act as controls (the rest pass through).
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(),
) -> NoneAttributes¶
block: Block | Nonebody_operands: list[Value] Get the wrapped callable’s complete argument list.callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_operands: list[Value] Get the control qubit values.is_symbolic_num_controls: bool Whether num_controls is symbolic (Value) rather than concrete.num_controls: int | Valueoperation_kind: OperationKindparam_operands: list[Value] Get the controlled operation’s classical/object arguments.power: int | Valuesignature: Signaturetarget_operands: list[Value] Get the target qubit values (arguments to U).
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationDictGetItemOperation [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,
) -> NoneAttributes¶
dict_value: Value Value: The DictValue being indexed (operands[0]).key_arity: intkey_values: tuple[Value, ...] tuple[Value, ...]: The key component values.operation_kind: OperationKindsignature: Signature
ForItemsOperation [source]¶
class ForItemsOperation(HasNestedOps, Operation)Represents iteration over dict/iterable items.
Example:
for (i, j), Jij in qmc.items(ising):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]key_is_vector: boolkey_var_values: tuple[Value, ...] | Nonekey_vars: list[str]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]operation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signaturevalue_var: strvalue_var_value: Value | None
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the items-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt items-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationGlobalPhaseOperation [source]¶
class GlobalPhaseOperation(Operation)Multiply the complete quantum state by exp(i * phase).
Global phase has no target qubit and does not create a new quantum value. Keeping the phase as the operation’s sole ordinary operand lets generic IR passes substitute, serialize, and analyze it without a special value-field protocol. A surrounding controlled-unitary lowering turns the operation into an observable phase gate on the accumulated controls.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[Value] | Exactly one scalar FloatType phase angle in radians. |
results | list[Value] | Must be empty because global phase changes no qubit identity. |
Raises:
ValueError— If the operand/result layout is invalid or the phase is not a scalarFloatTypevalue.
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKind Classify global phase as a quantum operation.phase: Value Return the scalar phase-angle operand.signature: Signature Return the zero-qubit operation signature.
HasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
InverseBlockOperation [source]¶
class InverseBlockOperation(Operation)Represent an inverse qkernel/block as a first-class IR operation.
The operation stores both the original forward block and a Qamomile-built
inverse implementation block. Emitters may use source_block with a
engine-native inverse/adjoint primitive, then fall back to
implementation_block when native inversion is unavailable.
Operands are ordered as scalar control qubits, target quantum operands,
then classical/object parameters. Results mirror the quantum operand
layout: control results first, then one target result per target operand.
Vector target operands therefore count as one operand/result while
contributing their scalar width to num_target_qubits.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_control_qubits: int = 0,
num_target_qubits: int = 0,
custom_name: str = '',
source_block: Block | None = None,
implementation_block: Block | None = None,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_qubits: list[‘Value’] Return control quantum operands.control_value: int | Nonecustom_name: strimplementation_block: Block | Nonename: str Return a human-readable inverse operation name.num_control_qubits: intnum_target_qubits: intoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return classical/object parameter operands.signature: Signature Return the operation signature.source_block: Block | Nonetarget_qubits: list[‘Value’] Return target quantum operands.
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[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. |
definition | CallableDef | None | Optional 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,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueor an Oracle control-partition field has an invalid Python type.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width, or if Oracle invocation and definition control metadata disagree.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of relevant callable implementations.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return a conservative union of measurement-derived results.name: str Return the display name for this invocation.num_added_control_qubits: int Return controls introduced by a frontend control transform.num_body_external_control_qubits: int Return control operands generic lowering adds outside a base body.num_control_qubits: int Return the number of leading control-qubit operands.num_declared_control_qubits: int Return controls included in an opaque Oracle’s base definition.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
effective_body¶
def effective_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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 | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None, which only selects engine-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
require_body | bool | Whether 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name used for implementation selection. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
select_body¶
def select_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> CallableBodySelectionSelect 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
LoopAnalyzer [source]¶
class LoopAnalyzerAnalyze loop structures to determine an emission strategy.
Methods¶
should_unroll¶
def should_unroll(self, op: ForOperation, bindings: dict[str, object]) -> boolDetermine whether a for-loop requires emit-time unrolling.
Parameters:
| Name | Type | Description |
|---|---|---|
op | ForOperation | Loop to analyze. |
bindings | dict[str, object] | Compile-time bindings available to nested-bound analysis. |
Returns:
bool — True when identities, carries, indices, predicates,
dictionary lookups, structural body parameters, or nested
bounds require concrete per-iteration evaluation.
NotOp [source]¶
class NotOp(Operation)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
input: Valueoperation_kind: OperationKindoutput: Valuesignature: Signature
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()) -> NoneAttributes¶
evolved_qubits: Value The evolved quantum register result.gamma: Value The evolution time parameter.observable: Value The Observable parameter operand.operation_kind: OperationKind PauliEvolveOp is QUANTUM - transforms quantum state.qubits: Value The quantum register operand.signature: Signature
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:
Binary kinds (EQ/NEQ/LT/LE/GT/GE/AND/OR/ADD/SUB/MUL/DIV/FLOORDIV/MOD/POW):
operands = [lhs, rhs].Unary kind (NOT):
operands = [val].Ternary kind (SELECT):
operands = [condition, true_value, false_value]— the runtime form of a branch merge (result = true_value if condition else false_value).Result:
results = [output_value].
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,
) -> NoneAttributes¶
kind: RuntimeOpKind | Noneoperation_kind: OperationKindsignature: Signature
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(),
) -> NoneAttributes¶
case_blocks: list[Block]case_callable_attrs: list[dict[str, Any]]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
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]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed replacement values. |
Returns:
Operation — Rebuilt SELECT operation with matching values replaced.
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of 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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]max_iterations: int | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the while body and its complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt while operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, rebind-record, and region-arg values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
qamomile.circuit.transpiler.passes.emit_support.measurement_emission¶
Measurement emission helpers extracted from StandardEmitPass.
Provides emit_measure, emit_measure_vector and
emit_measure_qfixed as module-level functions.
Overview¶
| Function | Description |
|---|---|
emit_measure | Emit a single measurement. |
emit_measure_qfixed | Emit QFixed measurement. |
emit_measure_vector | Emit vector measurement. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
EmitError | Report an engine failure to emit one semantic operation. |
MeasureOperation | |
MeasureQFixedOperation | Measure a quantum fixed-point number. |
MeasureVectorOperation | Measure a vector of qubits. |
MeasurementMode | How an engine handles measurement operations. |
QubitAddress | Typed key for qubit/clbit physical-index maps. |
StandardEmitPass | Standard emit pass implementation using GateEmitter protocol. |
Functions¶
emit_measure [source]¶
def emit_measure(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: MeasureOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any] | None = None,
) -> NoneEmit a single measurement.
Resolves the qubit operand using the full resolver (handles both scalar qubits and array element qubits with composite keys).
Raises:
EmitError— If the qubit or clbit cannot be resolved to a physical address. A dropped measurement is never recoverable inside a quantum segment — the emitted circuit would silently return results with a measured bit missing — so this is a hard error rather than a warning. The most common trigger is ameasure(q[i])whose indexiis an unresolved native-loop parameter;LoopAnalyzer.should_unrollis expected to have forced such loops to unroll before emit, so reaching this path indicates a real resolution failure.
emit_measure_qfixed [source]¶
def emit_measure_qfixed(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: MeasureQFixedOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
) -> NoneEmit QFixed measurement.
emit_measure_vector [source]¶
def emit_measure_vector(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: MeasureVectorOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any],
) -> NoneEmit vector measurement.
Resolves the qubit operand’s slice_of chain so that measuring a
view (measure(q[1::2])) correctly targets the root parent’s
physical qubits.
Behaviour for unresolvable inputs differs by case:
Unknown vector length (
_resolve_sizereturnsNone) — the function defers silently. This handles transpile-only paths (e.g. unbound parameter-size arrays) where downstream late- binding callers still handle the emit correctly.Resolvable length but a sliced view that resolves to zero physical qubits — raises
EmitError. Previously this produced executions returning[(None, N)], a data-integrity hazard, so the silent path is intentionally narrowed to view-on-empty cases only.Resolvable length but slice bounds are themselves symbolic — raises
EmitErrorfromresolve_slice_chain.
Raises:
EmitError— When a sliced view resolves to zero physical qubits, or when slice bounds remain symbolic at emit time.
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,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]EmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
operation
MeasureOperation [source]¶
class MeasureOperation(Operation)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
MeasureQFixedOperation [source]¶
class MeasureQFixedOperation(Operation)Measure a quantum fixed-point number.
This operation measures all qubits in a QFixed register and produces a Float result. During transpilation, this is lowered to individual MeasureOperations plus a DecodeQFixedOperation.
operands: [QFixed value (contains qubit_values in params)] results: [Float value]
Encoding:
For QPE phase (int_bits=0):
Qubits are stored least-significant first. For n qubits,
bit i has weight 2**(-n + i).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_bits: int = 0,
int_bits: int = 0,
) -> NoneAttributes¶
int_bits: intnum_bits: intoperation_kind: OperationKindsignature: Signature
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()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
MeasurementMode [source]¶
class MeasurementMode(Enum)How an engine handles measurement operations.
Attributes¶
NATIVERUNNABLESTATIC
QubitAddress [source]¶
class QubitAddressTyped 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) -> NoneAttributes¶
element_index: int | Noneis_array_element: bool True if this address refers to an array element.uuid: str
Methods¶
from_composite_key¶
@classmethod
def from_composite_key(cls, key: str) -> QubitAddressParse 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) -> boolTrue if this address belongs to the given array.
with_element¶
def with_element(self, index: int) -> QubitAddressCreate an array-element address from this array’s base UUID.
StandardEmitPass [source]¶
class StandardEmitPass(EmitPass[T], Generic[T])Standard emit pass implementation using GateEmitter protocol.
This class provides orchestration for semantic IR traversal while
delegating circuit instruction construction to a GateEmitter. The
concrete compiler use is CircuitLoweringPass; SDK targets materialize
its immutable result instead of subclassing this class.
Parameters:
| Name | Type | Description |
|---|---|---|
gate_emitter | GateEmitter[T] | Instruction builder used during the semantic traversal. |
bindings | dict[str, Any] | None | Compile-time parameter bindings. |
parameters | list[str] | None | Parameter names preserved at runtime. |
composite_emitters | list[CompositeGateEmitter[T]] | None | Optional callable-preservation or lowering hooks. |
engine_name | str | None | Diagnostic 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¶
engine_name
qamomile.circuit.transpiler.passes.emit_support.multi_control_ancilla¶
Clean-ancilla planning for the shared multi-controlled decomposition.
Engines without a native multi-controlled gate primitive lower an
irreducible n-controlled single-qubit gate through the standard
Toffoli-cascade construction (arXiv:2307.07478, Appendix A.3): the
logical AND of all n controls is accumulated onto n - 1 clean
ancilla qubits with a cascade of Toffoli gates, the gate is applied
once under a single control (the last ancilla), and the cascade is
uncomputed in reverse. Every ancilla therefore returns to |0> and
the same pool can be reused by every multi-controlled gate in the
segment.
Engine circuits are created with a fixed qubit count before emission
starts, so the pool must be sized up front. Its size is measured by a
count-only dry-run of the real emission (see
StandardEmitPass._count_multi_control_ancilla_demand and
counting_emitter.CountingEmitter): the same walk the real emission
runs is executed against a no-op emitter and a counting pool that records
peak concurrent usage, so the size can never drift from what the emitter
actually does. This module provides only :class:MultiControlAncillaPool
— the reserved (or counting) block of physical qubit indices appended
after the segment’s data qubits.
The pool has stack discipline (a moving offset) so leaf cascades and the
AND ladders that batched controlled-block emission holds via
:meth:MultiControlAncillaPool.try_hold draw from disjoint ranges. Under
counting the pool is unbounded and only records the peak, which is an
upper bound of real usage because the dry run biases capability answers
toward the cascade path; a shortfall in a real (bounded) pool would mean
the count under-measured and is reported as a compiler bug at emit time by
StandardEmitPass._emit_irreducible_multi_controlled_gate.
Overview¶
| Class | Description |
|---|---|
MultiControlAncillaPool | A reserved block of clean ancilla qubits for multi-control lowering. |
Classes¶
MultiControlAncillaPool [source]¶
class MultiControlAncillaPoolA reserved block of clean ancilla qubits for multi-control lowering.
The pool occupies a contiguous range of physical qubit indices
appended after a quantum segment’s data qubits. A single moving
_offset gives it stack discipline so nested users never collide:
A leaf Toffoli cascade uncomputes every ancilla back to
|0>before it returns and holds nothing across gates, so it simplytakes from the current offset (atomic acquire-and-release).Batched controlled-block emission
try_holds the block’s AND ladder for the duration of the body walk, advancing the offset so the leaf cascades emitted inside the body draw from the qubits after the held ladder. The offset is rewound when thewithblock exits, so sibling batches reuse the same range.
Constructor¶
def __init__(self, first_index: int, count: int, *, counting: bool = False) -> NoneInitialize the pool.
Parameters:
| Name | Type | Description |
|---|---|---|
first_index | int | Physical index of the first reserved ancilla qubit. |
count | int | Number of reserved ancilla qubits. Must be non-negative. Ignored in counting mode. |
counting | bool | When True the pool is unbounded and only records the peak concurrent usage (take / try_hold never fail), so a dry-run emission can measure how many ancillas a real emission would need. Defaults to False. |
Raises:
ValueError— Ifcountis negative.
Attributes¶
count: int Return the number of reserved ancilla qubits.peak: int Return the peak concurrent usage recorded in counting mode.
Methods¶
take¶
def take(self, count: int) -> list[int] | NoneReturn count clean ancilla indices from the current offset.
Parameters:
| Name | Type | Description |
|---|---|---|
count | int | Number of ancilla qubits requested. |
Returns:
list[int] | None — list[int] | None: The next count reserved physical
indices starting at the current offset, or None when the
unheld remainder of the pool is smaller than the request
(an estimation bug surfaced by the caller). In counting
mode the request always succeeds and the peak usage is
recorded instead.
Raises:
ValueError— Ifcountis negative — a caller bug rather than a shortfall, which a plain> countcheck would silently turn into an empty list (and, viatry_hold, a negative offset).
try_hold¶
def try_hold(self, count: int) -> Iterator[list[int] | None]Reserve count ancillas for the duration of a with block.
Used by batched controlled-block emission to keep an AND ladder
live while the block body is walked under a single control. The
offset advances so that take/try_hold calls made inside
the body draw from the qubits after the held range, and it is
rewound on exit (including on exception) so sibling batches reuse
the same range. When the unheld remainder cannot satisfy the
request the caller receives None and must fall back to
per-gate emission rather than treating it as an error — the
demand estimate legitimately reserves fewer ancillas than a
naive batch would want (e.g. a statically empty loop body).
Parameters:
| Name | Type | Description |
|---|---|---|
count | int | Number of contiguous ancilla qubits to hold. |
Yields:
list[int] | None — list[int] | None: The held physical indices, or None when the
unheld remainder is too small to satisfy the request.
qamomile.circuit.transpiler.passes.emit_support.multi_control_gate_emission¶
Lower primitive gates with one or more quantum controls.
Overview¶
| Function | Description |
|---|---|
clean_ancilla_toffoli_ladder | Return the arithmetic for the named clean-ancilla recipe. |
emit_controlled_gate | Emit a controlled version of a gate. |
emit_multi_controlled_gate | Emit one gate under an arbitrary number of accumulated controls. |
emit_multi_controlled_on_clean_ancillas | Lower an irreducible multi-controlled gate via a Toffoli cascade. |
emit_single_controlled_primitive | Emit one singly-controlled single-qubit gate from a resolved angle. |
reject_duplicate_physical_indices | Reject a multi-qubit gate whose qubits resolve to the same physical qubit. |
| Class | Description |
|---|---|
EmitError | Report an engine failure to emit one semantic operation. |
GateOperation | Quantum gate operation. |
GateOperationType | |
StandardEmitPass | Standard emit pass implementation using GateEmitter protocol. |
Functions¶
clean_ancilla_toffoli_ladder [source]¶
def clean_ancilla_toffoli_ladder(num_controls: int | sp.Expr) -> CleanAncillaToffoliLadder[Any]Return the arithmetic for the named clean-ancilla recipe.
The caller owns recipe selection and must use the result on a branch where at least two controls are active. Keeping validation outside this helper lets symbolic resource expressions construct inactive Piecewise branches without prematurely rejecting them.
Parameters:
| Name | Type | Description |
|---|---|---|
num_controls | int | sp.Expr | Concrete or symbolic control count. |
Returns:
CleanAncillaToffoliLadder[Any] — CleanAncillaToffoliLadder[Any]: Compute, total-Toffoli, and clean-
ancilla requirements in the same numeric domain as the input.
emit_controlled_gate [source]¶
def emit_controlled_gate(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: GateOperation,
control_idx: int,
target_indices: list[int],
bindings: dict[str, Any],
) -> NoneEmit a controlled version of a gate.
Resolves the rotation angle for rotation-like gates and dispatches
single-target gate kinds through
:func:emit_single_controlled_primitive; SWAP is lowered here
via its Fredkin conjugation because it needs two targets.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
op | GateOperation | Gate operation to control. |
control_idx | int | Physical control qubit. |
target_indices | list[int] | Physical qubits for the gate’s own operands, in operand order. An empty list is a no-op. |
bindings | dict[str, Any] | Bindings used to resolve rotation angles. |
Raises:
EmitError— If the gate type is unsupported in controlled decomposition, or a controlled SWAP has fewer than two targets.
emit_multi_controlled_gate [source]¶
def emit_multi_controlled_gate(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: GateOperation,
control_indices: list[int],
target_indices: list[int],
bindings: dict[str, Any],
) -> NoneEmit one gate under an arbitrary number of accumulated controls.
Structurally reduces multi-qubit gate types to single-target forms
by absorbing their own control qubits into the control set
(CX -> X, CZ -> Z, CP -> P, TOFFOLI -> X; SWAP
and RZZ via their standard CX conjugations), then emits:
one control: via :func:
emit_controlled_gate(the existing single-control dispatch),two controls on X / Z: via
emit_toffoli(Z conjugated by H),anything else: via the engine’s
_emit_irreducible_multi_controlled_gatehook, whose base implementation raises a descriptiveEmitError.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. Subclass overrides of _emit_irreducible_multi_controlled_gate are respected for the irreducible tail. |
circuit | Any | Engine circuit being emitted into. |
op | GateOperation | Gate operation whose operands are already resolved to target_indices. |
control_indices | list[int] | Physical control qubits. Must be non-empty. |
target_indices | list[int] | Physical qubits for the gate’s own operands, in operand order. |
bindings | dict[str, Any] | Bindings used to resolve rotation angles. |
Raises:
EmitError— Ifcontrol_indicesis empty, the gate has fewer resolved targets than its type requires, or the reduction bottoms out on an engine without multi-control support.
emit_multi_controlled_on_clean_ancillas [source]¶
def emit_multi_controlled_on_clean_ancillas(
emit_pass: 'StandardEmitPass',
circuit: Any,
gate_type: GateOperationType,
control_indices: list[int],
target_idx: int,
angle: Any,
ancilla_indices: list[int],
) -> NoneLower an irreducible multi-controlled gate via a Toffoli cascade.
Implements the standard clean-ancilla construction (arXiv:2307.07478,
Appendix A.3): the logical AND of the n controls is accumulated
onto n - 1 clean ancillas with a cascade of Toffoli gates, the
gate is applied once under a single control (the last ancilla)
through :func:emit_single_controlled_primitive, and the cascade is
uncomputed in reverse order. The cost is 2 * (n - 1) Toffoli
gates plus one singly-controlled gate, and every ancilla returns to
|0>, so the same pool may be reused by subsequent gates.
Unlike a dense 2**(n+1) unitary-matrix lowering, this scales
linearly in the control count and keeps rotation angles symbolic,
so runtime-parametric multi-controlled rotations are supported.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
gate_type | GateOperationType | Single-qubit gate kind to apply under the controls. |
control_indices | list[int] | Physical control qubits; at least two. |
target_idx | int | Physical target qubit. |
angle | Any | Resolved rotation angle (concrete number or engine parameter expression) for rotation-like gates, or None for fixed gates. |
ancilla_indices | list[int] | Clean (|0>) ancilla qubits; at least len(control_indices) - 1 entries. |
Raises:
EmitError— If fewer than two controls or too few ancillas are supplied (both indicate a caller bug), or the gate type is unsupported by the single-control dispatch.
emit_single_controlled_primitive [source]¶
def emit_single_controlled_primitive(
emit_pass: 'StandardEmitPass',
circuit: Any,
gate_type: GateOperationType | None,
control_idx: int,
target_idx: int,
angle: Any,
) -> NoneEmit one singly-controlled single-qubit gate from a resolved angle.
This is the single-control dispatch shared by
:func:emit_controlled_gate (which resolves the angle from the IR
operation first) and the Toffoli-cascade lowering of irreducible
multi-controlled gates (which arrives with the angle already
resolved). Fixed phase-family gates (S / T and daggers) are
emitted as controlled phases.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
gate_type | GateOperationType | None | Single-qubit gate kind. None (a gate operation without a type) is rejected like any other unsupported kind. |
control_idx | int | Physical control qubit. |
target_idx | int | Physical target qubit. |
angle | Any | Resolved rotation angle (concrete number or engine parameter expression) for P / RX / RY / RZ; ignored for fixed gates. |
Raises:
EmitError— Ifgate_typeis not a single-qubit gate kind supported in controlled decomposition.
reject_duplicate_physical_indices [source]¶
def reject_duplicate_physical_indices(
gate_label: str,
physical_indices: list[int],
operand_names: list[str] | None = None,
) -> NoneReject 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:
| Name | Type | Description |
|---|---|---|
gate_label | str | Human-readable name of the gate for the message (e.g. "CX" or "controlled gate"). |
physical_indices | list[int] | The resolved physical qubit indices the gate acts on, in operand order. |
operand_names | list[str] | None | Optional 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:
QubitAliasError— If any physical qubit index repeats.
Classes¶
EmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
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,
) -> NoneAttributes¶
gate_type: GateOperationType | Noneoperation_kind: OperationKindqubit_operands: list[Value] Qubit operands (excluding the theta parameter if present).signature: Signaturetheta: Value | None Angle parameter for rotation gates, orNonefor fixed gates.
Methods¶
fixed¶
@classmethod
def fixed(
cls,
gate_type: GateOperationType,
qubits: list[Value],
results: list[Value],
) -> 'GateOperation'Create a fixed gate (H, X, CX, SWAP, …) with no angle parameter.
rotation¶
@classmethod
def rotation(
cls,
gate_type: GateOperationType,
qubits: list[Value],
theta: Value,
results: list[Value],
) -> 'GateOperation'Create a rotation gate (RX, RY, RZ, P, CP, RZZ) with an angle.
GateOperationType [source]¶
class GateOperationType(enum.Enum)Attributes¶
CPCXCZHPRXRYRZRZZSSDGSWAPTTDGTOFFOLIXYZ
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:
| Name | Type | Description |
|---|---|---|
gate_emitter | GateEmitter[T] | Instruction builder used during the semantic traversal. |
bindings | dict[str, Any] | None | Compile-time parameter bindings. |
parameters | list[str] | None | Parameter names preserved at runtime. |
composite_emitters | list[CompositeGateEmitter[T]] | None | Optional callable-preservation or lowering hooks. |
engine_name | str | None | Diagnostic 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¶
engine_name
qamomile.circuit.transpiler.passes.emit_support.pauli_evolve_emission¶
Pauli evolution emission helper for StandardEmitPass.
Extracted from standard_emit.py to isolate the Hamiltonian
decomposition logic from the main emit dispatch.
The emit_pauli_evolve function is the default implementation.
Engine-specific emit passes (e.g., QiskitEmitPass) may override
the corresponding _emit_pauli_evolve method; calling
super()._emit_pauli_evolve(...) will ultimately delegate here.
Overview¶
| Function | Description |
|---|---|
emit_pauli_evolve | Emit Pauli evolution: exp(-i * gamma * H). |
emit_resolved_global_phase | Emit an already resolved standalone phase without discarding it. |
is_exact_real_zero | Return whether a value is a concrete real scalar equal to zero. |
is_zero_evolution_time | Return whether a resolved evolution time is the numeric identity. |
resolve_angle_value | Resolve a bare angle Value to a concrete float or engine parameter. |
validate_hamiltonian_within_register | Validate that a Hamiltonian fits within the target qubit register. |
validate_hermitian_hamiltonian | Validate every coefficient before Pauli-evolution emission starts. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
EmitError | Report an engine failure to emit one semantic operation. |
Hamiltonian | Represents a quantum Hamiltonian as a sum of Pauli operator products. |
PauliEvolveOp | Pauli evolution operation: exp(-i * gamma * H). |
QubitAddress | Typed key for qubit/clbit physical-index maps. |
StandardEmitPass | Standard emit pass implementation using GateEmitter protocol. |
Functions¶
emit_pauli_evolve [source]¶
def emit_pauli_evolve(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: PauliEvolveOp,
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> NoneEmit Pauli evolution: exp(-i * gamma * H).
Resolves the Hamiltonian from bindings and decomposes each term using the Pauli gadget technique:
Basis change per qubit (X->H, Y->Sdg*H, Z->identity)
CNOT ladder + RZ
Undo basis change
Subclasses can override this for engine-native implementations (e.g., Qiskit PauliEvolutionGate).
emit_resolved_global_phase [source]¶
def emit_resolved_global_phase(emit_pass: 'StandardEmitPass', circuit: Any, angle: Any) -> NoneEmit an already resolved standalone phase without discarding it.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Circuit representation being emitted into. |
angle | Any | Resolved phase angle. |
Raises:
EmitError— If the selected emitter cannot preserve the phase.
is_exact_real_zero [source]¶
def is_exact_real_zero(value: Any) -> boolReturn whether a value is a concrete real scalar equal to zero.
The comparison intentionally has no tolerance: a tiny nonzero value must remain observable, while engine parameter expressions remain unresolved.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Any | Concrete numeric value or engine parameter expression. |
Returns:
bool — True only for a non-boolean real scalar exactly equal to
bool — zero.
is_zero_evolution_time [source]¶
def is_zero_evolution_time(gamma: Any) -> boolReturn whether a resolved evolution time is the numeric identity.
Python and NumPy real scalars share the same rule. Engine parameter objects deliberately remain nonzero here: their runtime value is unknown even if they support comparison with Python numbers.
Parameters:
| Name | Type | Description |
|---|---|---|
gamma | Any | Concrete float or engine-native parameter expression. |
Returns:
bool — True only for a concrete numeric zero.
resolve_angle_value [source]¶
def resolve_angle_value(
emit_pass: 'StandardEmitPass',
theta: Any,
bindings: dict[str, Any],
) -> float | AnyResolve a bare angle Value to a concrete float or engine parameter.
Shared core of :func:resolve_angle so operations carrying a standalone
angle Value reuse the exact same resolution order as rotation-gate thetas.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass providing the resolver and engine-parameter factory. |
theta | Any | Angle Value to resolve. |
bindings | dict[str, Any] | Active compile-time bindings. |
Returns:
float | Any — float | Any: A concrete float when the angle is bound, or a
engine parameter expression when it stays symbolic.
Raises:
EmitError— If the angle is missing or cannot be resolved to a concrete value or engine parameter. Emitting0.0in this case would silently change the requested unitary.
validate_hamiltonian_within_register [source]¶
def validate_hamiltonian_within_register(num_h_qubits: int, register_size: int) -> NoneValidate that a Hamiltonian fits within the target qubit register.
A Hamiltonian acting on fewer qubits than the register is embedded
into the register’s qubit space (identity on the untouched qubits)
by acting only on its declared qubits; only a Hamiltonian larger
than the register is a genuine error. Every PauliEvolveOp emit
path (shared, engine-native, and controlled) must apply this same
rule through this helper so the size contract cannot drift between
engines.
Parameters:
| Name | Type | Description |
|---|---|---|
num_h_qubits | int | Number of qubits the Hamiltonian acts on (Hamiltonian.num_qubits). |
register_size | int | Resolved element count of the target qubit register. |
Raises:
EmitError— If the Hamiltonian acts on more qubits than the register provides.
validate_hermitian_hamiltonian [source]¶
def validate_hermitian_hamiltonian(hamiltonian: Hamiltonian) -> NoneValidate every coefficient before Pauli-evolution emission starts.
This validation deliberately completes before the zero-time shortcut and before any circuit mutation. Consequently, malformed Hamiltonians fail consistently for controlled and uncontrolled evolution, and a late invalid term cannot leave a partially emitted circuit behind.
Parameters:
| Name | Type | Description |
|---|---|---|
hamiltonian | Hamiltonian | Hamiltonian whose constant and Pauli-term coefficients must be real within HERMITIAN_IMAG_ATOL. |
Raises:
EmitError— If the constant or any Pauli-term coefficient is non-finite or has an imaginary component outside the Hermiticity tolerance.
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,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]EmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
operation
Hamiltonian [source]¶
class HamiltonianRepresents a quantum Hamiltonian as a sum of Pauli operator products.
The Hamiltonian is stored as a dictionary where keys are tuples of PauliOperators and values are their corresponding coefficients.
Example:
>>> H = Hamiltonian()
>>> H.add_term((PauliOperator(Pauli.X, 0), PauliOperator(Pauli.Y, 1)), 0.5)
>>> H.add_term((PauliOperator(Pauli.Z, 2),), 1.0)
>>> print(H.terms)
{(X0, Y1): 0.5, (Z2,): 1.0}Constructor¶
def __init__(self, num_qubits: int | None = None) -> NoneAttributes¶
constant: float | complexnum_qubits: int Calculates the number of qubits in the Hamiltonian.terms: dict[tuple[PauliOperator, ...], complex] Getter for the terms of the Hamiltonian.
Methods¶
add_term¶
def add_term(self, operators: tuple[PauliOperator, ...], coeff: float | complex)Adds a term to the Hamiltonian.
This method adds a product of Pauli operators with a given coefficient to the Hamiltonian. If the term already exists, the coefficients are summed.
Parameters:
| Name | Type | Description |
|---|---|---|
operators | Tuple[PauliOperator, ...] | A tuple of PauliOperators representing the term. |
coeff | Union[float, complex] | The coefficient of the term. |
Example:
>>> H = Hamiltonian()
>>> H.add_term((PauliOperator(Pauli.X, 0), PauliOperator(Pauli.Y, 1)), 0.5)
>>> H.add_term((PauliOperator(Pauli.X, 0), PauliOperator(Pauli.Y, 1)), 0.5j)
>>> print(H.terms)
{(X0, Y1): (0.5+0.5j)}copy¶
def copy(self) -> HamiltonianReturn an independent copy sharing no mutable state with self.
Produces a new Hamiltonian with the same terms, constant,
and declared _num_qubits. The underlying _terms dict
is fresh, so subsequent add_term / constant mutations
on either instance do not affect the other. PauliOperator
instances inside the term tuples are reused — they are
dataclass(frozen=True) values and safely shared.
Returns:
Hamiltonian — A shallow-cloned Hamiltonian instance.
Example:
>>> H = Hamiltonian()
>>> H.add_term((PauliOperator(Pauli.Z, 0),), 1.0)
>>> H2 = H.copy()
>>> H2.add_term((PauliOperator(Pauli.X, 1),), 0.5)
>>> H.num_qubits # unchanged by H2's mutation
1identity¶
@classmethod
def identity(
cls,
coeff: float | complex = 1.0,
num_qubits: int | None = None,
) -> HamiltonianCreate a scalar times identity Hamiltonian.
remap_qubits¶
def remap_qubits(self, qubit_map: dict[int, int]) -> HamiltonianRemap qubit indices according to the given mapping.
This is used to translate Pauli indices (logical indices within an expval call) to physical qubit indices in the actual quantum circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit_map | dict[int, int] | Mapping from logical index to physical index. e.g., {0: 5, 1: 3} maps logical index 0 → physical qubit 5 |
Returns:
Hamiltonian — New Hamiltonian with remapped qubit indices.
single_pauli¶
@classmethod
def single_pauli(cls, pauli: Pauli, index: int, coeff: float | complex = 1.0) -> HamiltonianCreate a single Pauli term Hamiltonian.
to_latex¶
def to_latex(self) -> strConverts the Hamiltonian to a LaTeX representation.
This function does not add constant term when we show the Hamiltonian. This function does not add $ symbols.
Returns:
str —
A LaTeX representation of the Hamiltonian.
import qamomile.observable as qm_o
import IPython.display as ipd
h = qm_o.Hamiltonian()
h += -qm_o.X(0) * qm_o.Y(1) - 2.0 * qm_o.Z(0) * qm_o.Z(1)
# Show the Hamiltonian in LaTeX at Jupyter Notebook
ipd.display(ipd.Latex("$" + h.to_latex() + "$"))to_numpy¶
def to_numpy(self) -> np.ndarrayConvert the Hamiltonian to a dense NumPy matrix.
Qubit 0 is mapped to the least-significant bit of computational-basis
indices, matching :meth:qamomile.linalg.HermitianMatrix.to_hamiltonian.
The returned array has shape (2**n, 2**n) where n is
:attr:num_qubits.
zero¶
@classmethod
def zero(cls, num_qubits: int | None = None) -> HamiltonianCreate a zero Hamiltonian.
PauliEvolveOp [source]¶
class PauliEvolveOp(Operation)Pauli evolution operation: exp(-i * gamma * H).
This operation applies the time evolution of a Pauli Hamiltonian to a quantum register.
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
evolved_qubits: Value The evolved quantum register result.gamma: Value The evolution time parameter.observable: Value The Observable parameter operand.operation_kind: OperationKind PauliEvolveOp is QUANTUM - transforms quantum state.qubits: Value The quantum register operand.signature: Signature
QubitAddress [source]¶
class QubitAddressTyped 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) -> NoneAttributes¶
element_index: int | Noneis_array_element: bool True if this address refers to an array element.uuid: str
Methods¶
from_composite_key¶
@classmethod
def from_composite_key(cls, key: str) -> QubitAddressParse 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) -> boolTrue if this address belongs to the given array.
with_element¶
def with_element(self, index: int) -> QubitAddressCreate an array-element address from this array’s base UUID.
StandardEmitPass [source]¶
class StandardEmitPass(EmitPass[T], Generic[T])Standard emit pass implementation using GateEmitter protocol.
This class provides orchestration for semantic IR traversal while
delegating circuit instruction construction to a GateEmitter. The
concrete compiler use is CircuitLoweringPass; SDK targets materialize
its immutable result instead of subclassing this class.
Parameters:
| Name | Type | Description |
|---|---|---|
gate_emitter | GateEmitter[T] | Instruction builder used during the semantic traversal. |
bindings | dict[str, Any] | None | Compile-time parameter bindings. |
parameters | list[str] | None | Parameter names preserved at runtime. |
composite_emitters | list[CompositeGateEmitter[T]] | None | Optional callable-preservation or lowering hooks. |
engine_name | str | None | Diagnostic 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¶
engine_name
qamomile.circuit.transpiler.passes.emit_support.physical_index_map¶
Helpers for mutating physical-index maps during emission.
Overview¶
| Function | Description |
|---|---|
array_element_mapping | Collect physical indices for the elements of an array value. |
array_element_mappings | Collect array element mappings for multiple source arrays. |
copy_array_element_aliases | Copy array element aliases from a source array to a result array. |
map_array_element_aliases | Map explicit array element aliases to a result array. |
map_array_result_group | Map an array-valued result to a physical index group. |
| Class | Description |
|---|---|
QubitAddress | Typed key for qubit/clbit physical-index maps. |
Functions¶
array_element_mapping [source]¶
def array_element_mapping(source_uuid: str, index_map: Mapping[QubitAddress, int]) -> dict[int, int]Collect physical indices for the elements of an array value.
Parameters:
| Name | Type | Description |
|---|---|---|
source_uuid | str | UUID of the array whose element addresses should be collected. |
index_map | Mapping[QubitAddress, int] | Physical-index map to read. |
Returns:
dict[int, int] — dict[int, int]: Mapping from element index to physical index.
array_element_mappings [source]¶
def array_element_mappings(
source_uuids: set[str],
index_map: Mapping[QubitAddress, int],
) -> dict[str, dict[int, int]]Collect array element mappings for multiple source arrays.
Parameters:
| Name | Type | Description |
|---|---|---|
source_uuids | set[str] | UUIDs of the arrays whose element addresses should be collected. |
index_map | Mapping[QubitAddress, int] | Physical-index map to read. |
Returns:
dict[str, dict[int, int]] — dict[str, dict[int, int]]: Mapping from each requested source UUID to
its element-index-to-physical-index mapping.
copy_array_element_aliases [source]¶
def copy_array_element_aliases(source_uuid: str, result_uuid: str, index_map: PhysicalIndexMap) -> NoneCopy array element aliases from a source array to a result array.
Parameters:
| Name | Type | Description |
|---|---|---|
source_uuid | str | UUID of the source array whose element addresses are already present in index_map. |
result_uuid | str | UUID of the result array that should alias the same physical resources element by element. |
index_map | PhysicalIndexMap | Mutable physical-index map updated in place with any missing result element addresses and the result base address. |
map_array_element_aliases [source]¶
def map_array_element_aliases(
result_uuid: str,
element_mapping: Mapping[int, int],
index_map: PhysicalIndexMap,
*,
map_base_address: bool = True,
) -> NoneMap explicit array element aliases to a result array.
Parameters:
| Name | Type | Description |
|---|---|---|
result_uuid | str | UUID of the result array that should receive the element aliases. |
element_mapping | Mapping[int, int] | Physical indices keyed by result element index. |
index_map | PhysicalIndexMap | Mutable physical-index map updated in place with missing result element addresses and, when requested, the result base address. |
map_base_address | bool | Whether to map the scalar base address for the result array to its lowest-index element. Defaults to True. |
map_array_result_group [source]¶
def map_array_result_group(result_uuid: str, index_group: list[int], index_map: PhysicalIndexMap) -> NoneMap an array-valued result to a physical index group.
Parameters:
| Name | Type | Description |
|---|---|---|
result_uuid | str | UUID of the array-valued result whose element addresses should be registered. |
index_group | list[int] | Physical indices for the result elements, in result-local element order. |
index_map | PhysicalIndexMap | Mutable physical-index map updated in place with element addresses and, when available, the base result address. |
Classes¶
QubitAddress [source]¶
class QubitAddressTyped 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) -> NoneAttributes¶
element_index: int | Noneis_array_element: bool True if this address refers to an array element.uuid: str
Methods¶
from_composite_key¶
@classmethod
def from_composite_key(cls, key: str) -> QubitAddressParse 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) -> boolTrue if this address belongs to the given array.
with_element¶
def with_element(self, index: int) -> QubitAddressCreate an array-element address from this array’s base UUID.
qamomile.circuit.transpiler.passes.emit_support.qubit_address¶
Typed key for qubit/clbit physical-index maps.
Replaces the ad-hoc f"{uuid}_{index}" string convention with an
explicit, hashable value object that makes the construction/parsing
contract type-safe.
Overview¶
| Class | Description |
|---|---|
QubitAddress | Typed key for qubit/clbit physical-index maps. |
Classes¶
QubitAddress [source]¶
class QubitAddressTyped 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) -> NoneAttributes¶
element_index: int | Noneis_array_element: bool True if this address refers to an array element.uuid: str
Methods¶
from_composite_key¶
@classmethod
def from_composite_key(cls, key: str) -> QubitAddressParse 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) -> boolTrue if this address belongs to the given array.
with_element¶
def with_element(self, index: int) -> QubitAddressCreate an array-element address from this array’s base UUID.
qamomile.circuit.transpiler.passes.emit_support.resource_allocator¶
Resource allocation helpers for emission.
Overview¶
| Function | Description |
|---|---|
array_physical_region | Resolve a one-dimensional array to its ordered physical region. |
copy_array_element_aliases | Copy array element aliases from a source array to a result array. |
genuine_input_values | Return an operation’s input values that count as genuine reads. |
map_merge_outputs | Register merge output UUIDs to the same physical resources as their sources. |
remap_static_merge_outputs | Remap merge outputs for a compile-time constant IfOperation. |
resolve_condition_address_detailed | Resolve a condition / source Value to its clbit_map key. |
resolve_if_condition | Resolve an if-condition to a compile-time boolean. |
resolve_loop_bounds | Resolve for-loop bounds (start, stop, step) from operands. |
resolve_qubit_key | Resolve a qubit Value to its allocation key. |
resolve_root_qubit_address | Resolve an array-element value to its root (array_uuid, index). |
validated_loop_indexset | Build an engine-safe Python range for resolved loop bounds. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
BinOp | Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN). |
BitType | Type representing a classical bit. |
CastOperation | Type cast operation for creating aliases over the same quantum resources. |
CompOp | Comparison operation (EQ, NEQ, LT, LE, GT, GE). |
ConcreteControlledU | Controlled-U with concrete (int) number of controls. |
CondOp | Conditional logical operation (AND, OR). |
ControlledUOperation | Base class for controlled-U operations. |
EmitError | Report an engine failure to emit one semantic operation. |
ForItemsOperation | Represents iteration over dict/iterable items. |
ForOperation | Represents a for loop operation. |
GateOperation | Quantum gate operation. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
IfOperation | Represents an if-else conditional operation. |
InverseBlockOperation | Represent an inverse qkernel/block as a first-class IR operation. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
MeasureOperation | |
MeasureQFixedOperation | Measure a quantum fixed-point number. |
MeasureVectorOperation | Measure a vector of qubits. |
NotOp | |
PauliEvolveOp | Pauli evolution operation: exp(-i * gamma * H). |
ProjectOperation | Project a qubit in one Pauli basis and keep the projected state. |
QInitOperation | Initialize the qubit |
QubitAddress | Typed key for qubit/clbit physical-index maps. |
ResetOperation | Reset a qubit to the |0> state and return the fresh handle. |
ResourceAllocator | Allocates qubit and classical bit indices from operations. |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
SymbolicControlledU | Controlled-U with symbolic (Value) number of controls. |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
ValueResolver | Resolves Value objects to concrete indices or values. |
WhileOperation | Represents a while loop operation. |
Functions¶
array_physical_region [source]¶
def array_physical_region(array: 'ArrayValue') -> tuple[str, tuple[int, ...]] | NoneResolve a one-dimensional array to its ordered physical region.
The region is expressed independently of SSA version UUIDs: the first
element is the root array’s logical_id and the second is the ordered
tuple of root-space indices addressed by the array. This makes a root
register and its full view compare equal while keeping partial, strided,
reordered, and different-root registers distinct.
Parameters:
| Name | Type | Description |
|---|---|---|
array | ArrayValue | Root array or nested sliced view to resolve. The array must be one-dimensional and have a compile-time integer length; every slice bound in its ancestry must also be constant. |
Returns:
tuple[str, tuple[int, ...]] | None — tuple[str, tuple[int, ...]] | None: (root_logical_id, indices)
when the complete ordered coverage is statically known, otherwise
None. Symbolic shapes or slice bounds remain unresolved so
callers can defer to emit-time physical mappings.
copy_array_element_aliases [source]¶
def copy_array_element_aliases(source_uuid: str, result_uuid: str, index_map: PhysicalIndexMap) -> NoneCopy array element aliases from a source array to a result array.
Parameters:
| Name | Type | Description |
|---|---|---|
source_uuid | str | UUID of the source array whose element addresses are already present in index_map. |
result_uuid | str | UUID of the result array that should alias the same physical resources element by element. |
index_map | PhysicalIndexMap | Mutable physical-index map updated in place with any missing result element addresses and the result base address. |
genuine_input_values [source]¶
def genuine_input_values(op: Operation) -> list[ValueBase]Return an operation’s input values that count as genuine reads.
Structured operations derive reads from their explicit region interface:
enclosing operands, captures, loop initializers, and region yields.
Block arguments and operation results are definitions, while legacy
rebind records are diagnostics rather than dataflow. Leaf operations keep
their ordinary all_input_values contract.
Parameters:
| Name | Type | Description |
|---|---|---|
op | Operation | Operation to inspect. |
Returns:
list[ValueBase] — list[ValueBase]: Semantic reads in interface order.
map_merge_outputs [source]¶
def map_merge_outputs(
if_op: IfOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
resolve_scalar_qubit: Any = None,
bindings: dict[str, Any] | None = None,
resolver: ValueResolver | None = None,
reject_runtime_bit_mux: bool = False,
allowed_mixed_bit_outputs: frozenset[str] | set[str] | None = None,
) -> NoneRegister merge output UUIDs to the same physical resources as their sources.
Runtime-if counterpart of :func:remap_static_merge_outputs: both
branches may execute, so quantum merges are validated to sit on
identical physical resources, and classical Bit merges consolidate
both branches’ clbits only when the complete source-alias partition is
representable without overwriting an independently live value. Outputs
already registered are left untouched.
Parameters:
| Name | Type | Description |
|---|---|---|
if_op | IfOperation | The runtime if-else whose merged outputs need physical-resource registration; merges are read through iter_merges. |
qubit_map | QubitMap | Address-to-physical-qubit map, mutated in place. |
clbit_map | ClbitMap | Address-to-physical-clbit map, mutated in place. |
resolve_scalar_qubit | Any | Optional callable (source, qubit_map) -> int | None used to resolve scalar qubit sources that are not directly registered (e.g. array elements). Defaults to None, restricting resolution to direct and root-array lookups. |
bindings | dict[str, Any] | None | Active bindings used to fold a classical Bit merge source’s symbolic Vector[Bit] element index / slice bounds (e.g. an unrolled loop variable). Defaults to None (empty), restricting element resolution to constant indices. |
resolver | ValueResolver | None | Resolver used with bindings to fold non-constant element indices; None restricts to constants. Defaults to None. |
reject_runtime_bit_mux | bool | When True, raise EmitError for a runtime Bit merge that requires an at-runtime mux, mixes a pre-existing source with a branch-local measurement, or has incompatible source-sharing partitions across multiple outputs. Two all-branch-local source sets remain eligible only when their alias partitions match. Defaults to False. |
allowed_mixed_bit_outputs | frozenset[str] | set[str] | None | Merge result UUIDs whose pre-existing source is proven dead after the merge. This includes safe ordinary-if updates and phi-like loop condition remeasurements. Defaults to None. |
Raises:
EmitError— If a quantum merge’s branches resolve to different physical resources (or only one branch resolves), which a single-execution branch cannot realize; or, whenreject_runtime_bit_muxis True, if a runtimeBitmerge multiplexes two distinct pre-existing measured clbits/regions or has a non-identity branch source with no physical clbit (unrepresentable in the clbit-aliasing model), mixes external and branch-local provenance, or would collapse distinct merge slots.
remap_static_merge_outputs [source]¶
def remap_static_merge_outputs(
if_op: IfOperation,
condition_value: bool,
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any] | None = None,
resolver: ValueResolver | None = None,
) -> NoneRemap merge outputs for a compile-time constant IfOperation.
Registers each merged output under the physical resource of the branch selected by the resolved condition, so downstream operations referencing the merge output resolve to the surviving branch’s qubit / clbit. Outputs already registered are left untouched.
Parameters:
| Name | Type | Description |
|---|---|---|
if_op | IfOperation | The if-else whose condition resolved at compile time; merges are read through iter_merges. |
condition_value | bool | The resolved condition, selecting which branch’s source the outputs alias. |
qubit_map | QubitMap | Address-to-physical-qubit map, mutated in place. |
clbit_map | ClbitMap | Address-to-physical-clbit map, mutated in place. |
bindings | dict[str, Any] | None | Active bindings used to fold a merge source’s symbolic Vector[Bit] element index / slice bounds (e.g. an unrolled loop variable). Defaults to None (empty), restricting element resolution to constant indices. |
resolver | ValueResolver | None | Resolver used with bindings to fold non-constant element indices; None restricts to constants. Defaults to None. |
resolve_condition_address_detailed [source]¶
def resolve_condition_address_detailed(
condition: Value,
bindings: dict[str, Any],
resolver: ValueResolver | None = None,
) -> tuple[QubitAddress, bool]Resolve a condition / source Value to its clbit_map key.
Single source of truth (shared by control_flow_emission.emit_if /
emit_while, the Qiskit / CUDA-Q engines, ResourceAllocator’s
loop-carried / merge aliasing, and the merge-output mapping helpers here)
for turning a runtime control-flow condition — or a merge source Value —
into the address its classical bit is registered under.
Scalar measurement results register under QubitAddress(bit.uuid),
while a Vector[Bit] element s[i] (s = qmc.measure(register))
registers under QubitAddress(root_array.uuid, root_index). The
element index and every slice_start / slice_step along the
parent’s slice_of chain are resolved the same way — taken directly
when constant, otherwise folded through bindings via resolver —
and composed into the root index via root_index = start + step * view_local_index repeated along the chain.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | Value | The condition operand or merge source Value. |
bindings | dict[str, Any] | Active emit-time bindings used to fold symbolic indices / slice bounds. May be empty for callers that only have constant addresses to resolve (e.g. the allocator’s pre-emit pass). |
resolver | ValueResolver | None | Resolver exposing resolve_int_value; None restricts resolution to constants. Defaults to None. |
Returns:
tuple[QubitAddress, bool] — tuple[QubitAddress, bool]: (address, resolved_as_element).
resolved_as_element is True only when condition is a
Vector[Bit] element whose index (and any slice bounds)
resolved to concrete ints, giving the root-space
QubitAddress(root.uuid, root_index). It is False for a
plain scalar, or when an element’s index / slice bound could
not be resolved (the scalar UUID fallback). Callers that mutate
clbit_map should trust the address as a vector key only when
this flag is True, to avoid aliasing an unresolved element
onto an unrelated scalar slot.
resolve_if_condition [source]¶
def resolve_if_condition(condition: Any, bindings: dict[str, Any]) -> bool | NoneResolve an if-condition to a compile-time boolean.
resolve_loop_bounds [source]¶
def resolve_loop_bounds(
resolver: Any,
op: ForOperation,
bindings: dict[str, Any],
) -> tuple[int | None, int | None, int | None]Resolve for-loop bounds (start, stop, step) from operands.
Missing operands use defaults: start=0, stop=1, step=1. Returns None for bounds that cannot be resolved to concrete ints.
resolve_qubit_key [source]¶
def resolve_qubit_key(qubit: 'Value') -> tuple[QubitAddress | None, bool]Resolve a qubit Value to its allocation key.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | Value | Qubit value to resolve. Array elements with a constant index are resolved through their full slice_of chain to the root array address. |
Returns:
tuple[QubitAddress | None, bool] — tuple[QubitAddress | None, bool]: (address, is_array_element).
address is the root-space address for a resolvable array
element, None for an array element whose index or slice
bounds are symbolic at this binding-free stage, and a scalar
UUID address for non-array qubits. A negative constant index
(or an out-of-contract slice bound) also yields None:
resolve_root_qubit_address refuses it rather than letting it
silently address a wrong root slot.
resolve_root_qubit_address [source]¶
def resolve_root_qubit_address(value: 'Value') -> tuple[str, int] | NoneResolve 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:
| Name | Type | Description |
|---|---|---|
value | Value | The value to resolve. Expected to be an array element (parent_array set with a single constant element_indices entry). |
Returns:
tuple[str, int] | None — tuple[str, int] | None: (root_array_uuid, composed_index) when
value is an array element with a constant index whose entire
slice_of chain has constant slice_start / slice_step.
None when value is not an array element, when its index is
non-constant, or when any slice bound in the chain is non-constant
(those cases are deferred to the emit-time resolver, which has
bindings available). Also None for a negative constant index
or a chain frame with negative slice_start / non-positive
slice_step — composing those would silently address a wrong
root slot, so they are refused rather than guessed (the frontend
rejects them at trace time; this guard covers programmatically
constructed IR).
validated_loop_indexset [source]¶
def validated_loop_indexset(start: int, stop: int, step: int) -> rangeBuild an engine-safe Python range for resolved loop bounds.
Parameters:
| Name | Type | Description |
|---|---|---|
start | int | Inclusive loop start. |
stop | int | Exclusive loop stop. |
step | int | Nonzero loop step. |
Returns:
range — The resolved loop index set when its cardinality fits Python’s
platform-sized sequence protocol.
Raises:
EmitError— Ifstepis zero or the range cardinality exceeds what Python/engine loop APIs can represent without overflow.
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,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]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,
) -> NoneAttributes¶
kind: BinOpKind | Noneoperation_kind: OperationKindsignature: Signature
BitType [source]¶
class BitType(ClassicalTypeMixin, ValueType)Type representing a classical bit.
CastOperation [source]¶
class CastOperation(Operation)Type cast operation for creating aliases over the same quantum resources.
This operation does NOT allocate new qubits. It creates a new Value that references the same underlying quantum resources with a different type.
Use cases:
Vector[Qubit] -> QFixed (after QPE, for phase measurement)
Vector[Qubit] -> QUInt (for quantum arithmetic)
QUInt -> QFixed (reinterpret bits with different encoding)
QFixed -> QUInt (reinterpret bits with different encoding)
operands: [source_value] - The value being cast results: [cast_result] - The new value with target type (same physical qubits)
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
source_type: ValueType | None = None,
target_type: ValueType | None = None,
qubit_mapping: list[str] = list(),
) -> NoneAttributes¶
num_qubits: int Number of qubits involved in the cast.operation_kind: OperationKind Cast stays in the same segment as its source (QUANTUM for quantum types).qubit_mapping: list[str]signature: Signature Return the type signature of this cast operation.source_type: ValueType | Nonetarget_type: ValueType | None
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,
) -> NoneAttributes¶
kind: CompOpKind | Noneoperation_kind: OperationKindsignature: Signature
ConcreteControlledU [source]¶
class ConcreteControlledU(ControlledUOperation)Controlled-U with concrete (int) number of controls.
Operand layout: [ctrl_0, ..., ctrl_n, tgt_0, ..., tgt_m, params...]
Result layout: [ctrl_0', ..., ctrl_n', tgt_0', ..., tgt_m']
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
power: int | Value = 1,
block: Block | None = None,
num_controls: int = 1,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
control_operands: list[Value]control_value: int | Nonenum_controls: intparam_operands: list[Value] Get classical/object operands after the concrete control prefix.signature: Signature Build the concrete controlled call signature.target_operands: list[Value] Return the wrapped callable’s target and parameter operands.
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,
) -> NoneAttributes¶
kind: CondOpKind | Noneoperation_kind: OperationKindsignature: Signature
ControlledUOperation [source]¶
class ControlledUOperation(Operation)Base class for controlled-U operations.
Two concrete subclasses handle distinct operand layouts:
ConcreteControlledU: Fixednum_controls: int, individual qubit operands.SymbolicControlledU: Symbolicnum_controls: Value, vector-based control operands; optionalcontrol_indicesselects a subset of the control vector to act as controls (the rest pass through).
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(),
) -> NoneAttributes¶
block: Block | Nonebody_operands: list[Value] Get the wrapped callable’s complete argument list.callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_operands: list[Value] Get the control qubit values.is_symbolic_num_controls: bool Whether num_controls is symbolic (Value) rather than concrete.num_controls: int | Valueoperation_kind: OperationKindparam_operands: list[Value] Get the controlled operation’s classical/object arguments.power: int | Valuesignature: Signaturetarget_operands: list[Value] Get the target qubit values (arguments to U).
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationEmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
operation
ForItemsOperation [source]¶
class ForItemsOperation(HasNestedOps, Operation)Represents iteration over dict/iterable items.
Example:
for (i, j), Jij in qmc.items(ising):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]key_is_vector: boolkey_var_values: tuple[Value, ...] | Nonekey_vars: list[str]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]operation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signaturevalue_var: strvalue_var_value: Value | None
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the items-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt items-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationGateOperation [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,
) -> NoneAttributes¶
gate_type: GateOperationType | Noneoperation_kind: OperationKindqubit_operands: list[Value] Qubit operands (excluding the theta parameter if present).signature: Signaturetheta: Value | None Angle parameter for rotation gates, orNonefor fixed gates.
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 HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
InverseBlockOperation [source]¶
class InverseBlockOperation(Operation)Represent an inverse qkernel/block as a first-class IR operation.
The operation stores both the original forward block and a Qamomile-built
inverse implementation block. Emitters may use source_block with a
engine-native inverse/adjoint primitive, then fall back to
implementation_block when native inversion is unavailable.
Operands are ordered as scalar control qubits, target quantum operands,
then classical/object parameters. Results mirror the quantum operand
layout: control results first, then one target result per target operand.
Vector target operands therefore count as one operand/result while
contributing their scalar width to num_target_qubits.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_control_qubits: int = 0,
num_target_qubits: int = 0,
custom_name: str = '',
source_block: Block | None = None,
implementation_block: Block | None = None,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_qubits: list[‘Value’] Return control quantum operands.control_value: int | Nonecustom_name: strimplementation_block: Block | Nonename: str Return a human-readable inverse operation name.num_control_qubits: intnum_target_qubits: intoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return classical/object parameter operands.signature: Signature Return the operation signature.source_block: Block | Nonetarget_qubits: list[‘Value’] Return target quantum operands.
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[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. |
definition | CallableDef | None | Optional 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,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueor an Oracle control-partition field has an invalid Python type.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width, or if Oracle invocation and definition control metadata disagree.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of relevant callable implementations.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return a conservative union of measurement-derived results.name: str Return the display name for this invocation.num_added_control_qubits: int Return controls introduced by a frontend control transform.num_body_external_control_qubits: int Return control operands generic lowering adds outside a base body.num_control_qubits: int Return the number of leading control-qubit operands.num_declared_control_qubits: int Return controls included in an opaque Oracle’s base definition.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
effective_body¶
def effective_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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 | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None, which only selects engine-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
require_body | bool | Whether 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name used for implementation selection. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
select_body¶
def select_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> CallableBodySelectionSelect 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
MeasureOperation [source]¶
class MeasureOperation(Operation)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
MeasureQFixedOperation [source]¶
class MeasureQFixedOperation(Operation)Measure a quantum fixed-point number.
This operation measures all qubits in a QFixed register and produces a Float result. During transpilation, this is lowered to individual MeasureOperations plus a DecodeQFixedOperation.
operands: [QFixed value (contains qubit_values in params)] results: [Float value]
Encoding:
For QPE phase (int_bits=0):
Qubits are stored least-significant first. For n qubits,
bit i has weight 2**(-n + i).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_bits: int = 0,
int_bits: int = 0,
) -> NoneAttributes¶
int_bits: intnum_bits: intoperation_kind: OperationKindsignature: Signature
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()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
NotOp [source]¶
class NotOp(Operation)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
input: Valueoperation_kind: OperationKindoutput: Valuesignature: Signature
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()) -> NoneAttributes¶
evolved_qubits: Value The evolved quantum register result.gamma: Value The evolution time parameter.observable: Value The Observable parameter operand.operation_kind: OperationKind PauliEvolveOp is QUANTUM - transforms quantum state.qubits: Value The quantum register operand.signature: Signature
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',
) -> NoneAttributes¶
axis: stroperation_kind: OperationKindsignature: Signature
QInitOperation [source]¶
class QInitOperation(Operation)Initialize the qubit
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
QubitAddress [source]¶
class QubitAddressTyped 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) -> NoneAttributes¶
element_index: int | Noneis_array_element: bool True if this address refers to an array element.uuid: str
Methods¶
from_composite_key¶
@classmethod
def from_composite_key(cls, key: str) -> QubitAddressParse 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) -> boolTrue if this address belongs to the given array.
with_element¶
def with_element(self, index: int) -> QubitAddressCreate an array-element address from this array’s base UUID.
ResetOperation [source]¶
class ResetOperation(Operation)Reset a qubit to the |0> state and return the fresh handle.
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
ResourceAllocator [source]¶
class ResourceAllocatorAllocates qubit and classical bit indices from operations.
This class handles the first pass of circuit emission: determining how many physical qubits and classical bits are needed and mapping Value UUIDs to their physical indices.
New physical indices are assigned via monotonic counters
(_next_qubit_index / _next_clbit_index) so that alias
entries — which reuse an existing physical index — never inflate
the counter. Using len(map) would cause sparse (gapped)
physical indices because alias keys increase the map size without
adding new physical resources.
Constructor¶
def __init__(self, resolver: ValueResolver | None = None) -> NoneInitialize allocator state.
Parameters:
| Name | Type | Description |
|---|---|---|
resolver | ValueResolver | None | Emit value resolver that carries runtime parameter names and binding lookup rules. Defaults to None, which creates a resolver without runtime parameters. |
Attributes¶
safe_mixed_bit_merge_outputs: frozenset[str] Return mixed-provenance Bit merges proven safe to alias.
Methods¶
allocate¶
def allocate(
self,
operations: list[Operation],
bindings: dict[str, Any] | None = None,
initial_qubit_map: QubitMap | None = None,
initial_clbit_map: ClbitMap | None = None,
public_output_uuids: frozenset[str] | set[str] | None = None,
) -> tuple[QubitMap, ClbitMap]Allocate qubit and clbit indices for all operations.
Parameters:
| Name | Type | Description |
|---|---|---|
operations | list[Operation] | Operations to allocate resources for. |
bindings | dict[str, Any] | None | Optional variable bindings for resolving dynamic sizes. Defaults to None (treated as an empty mapping). |
initial_qubit_map | QubitMap | None | Optional pre-populated qubit address mapping. Used by callers that need to seed the allocator with bindings established outside the operation list — for instance, the inner-block emitter in blockvalue_to_gate pre-allocates Vector[Qubit] input elements (the inner block has no QInitOperation for inputs, so per-element entries must be supplied here or the assertion in _allocate_gate fires). The map is copied; allocation continues from max(values) + 1 so new QInitOperation allocations inside operations do not collide. Defaults to None (treated as empty). |
initial_clbit_map | ClbitMap | None | Optional pre-populated clbit address mapping. Same semantics as initial_qubit_map but for classical bits. Defaults to None. |
public_output_uuids | frozenset[str] | set[str] | None | Program outputs that must remain live after this operation tree. Defaults to None, which disables dead-source approval for mixed prior/fresh Bit merges. |
Returns:
tuple[QubitMap, ClbitMap] — tuple[QubitMap, ClbitMap]: (qubit_map, clbit_map) where
each maps QubitAddress to a physical index. If an
initial map was supplied, its entries are preserved
verbatim in the returned map.
preserving_analysis_state¶
def preserving_analysis_state(self) -> Iterator[None]Preserve segment-level analysis state across a nested allocation.
allocate recomputes the measurement-taint set, the safe
mixed-merge allowlist, and the monotonic resource counters for
the operation list it receives. Nested sub-circuit emission
(controlled blocks, native inverses) reuses the SEGMENT
allocator on a different operation list mid-emission; without a
snapshot that leaves the sub-block’s analysis state behind, and
later resolve_iteration_maps replays of the enclosing
segment consult the wrong taint/allowlist sets — silently
disarming the runtime-mux guards.
Yields:
None — The nested allocation and emission run inside the
snapshot; the segment state is restored on exit even
when the nested work raises.
resolve_iteration_maps¶
def resolve_iteration_maps(
self,
operations: list[Operation],
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any],
) -> tuple[QubitMap, ClbitMap]Resolve resource aliases for one statically replayed iteration.
The initial allocation walks an unrolled loop body only once, before
its loop variable has a concrete value. A nested runtime condition
such as while measured[index]: therefore cannot select its root
clbit during that first walk. Replaying the allocator over copies of
the already-complete maps with the iteration binding present resolves
those aliases without allocating another physical resource. The
caller uses the returned maps for that iteration only; the same body
UUIDs may legitimately alias different measured-vector elements in
later iterations.
Parameters:
| Name | Type | Description |
|---|---|---|
operations | list[Operation] | Statically replayed loop body. |
qubit_map | QubitMap | Complete enclosing qubit map. |
clbit_map | ClbitMap | Complete enclosing clbit map. |
bindings | dict[str, Any] | Iteration-local UUID bindings, including the concrete range index or items-loop key/value identities. |
Returns:
tuple[QubitMap, ClbitMap] — tuple[QubitMap, ClbitMap]: Per-iteration copies with conditional
aliases resolved for the supplied bindings.
Raises:
EmitError— If resolving the bound body exposes an invalid quantum merge, classical-bit merge, array size, or while-condition lineage — or if replay unexpectedly allocates a new physical qubit or clbit instead of only adding or changing aliases.
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(),
) -> NoneAttributes¶
case_blocks: list[Block]case_callable_attrs: list[dict[str, Any]]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
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]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed replacement values. |
Returns:
Operation — Rebuilt SELECT operation with matching values replaced.
SymbolicControlledU [source]¶
class SymbolicControlledU(ControlledUOperation)Controlled-U with symbolic (Value) number of controls.
Operand layout: [ctrl_arg_0, ..., ctrl_arg_{k-1}, tgt_0, ..., tgt_m, params...]
Result layout: [ctrl_arg_0', ..., ctrl_arg_{k-1}', tgt_0', ..., tgt_m']
The number of control arguments k is recorded in
num_control_args; the default k = 1 corresponds to the
historical single-pool form (operands[0] is a
Vector[Qubit] / VectorView whose length equals
num_controls, or whose control_indices-selected subset
does). When k > 1 the control prefix is a heterogeneous
sequence of scalar Qubit values and ArrayValues whose
total qubit count is num_controls; the emit pass walks them
in order to recover the per-physical-qubit control set.
When control_indices is None the entire control prefix
is used as active controls (one-arg form: len(ctrl_vector) == num_controls; multi-arg form: the qubit-count sum of the
prefix args equals num_controls). When non-None, the
listed indices select exactly num_controls slots from a
single-arg pool to act as controls; combining
control_indices with the multi-arg control prefix is
rejected at frontend time.
Each control_indices entry is stored as a Value of
UIntType regardless of whether the frontend passed an
int literal or a UInt handle, so all downstream
value-substitution passes see a uniform shape.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
power: int | Value = 1,
block: Block | None = None,
num_controls: Value = (lambda: Value(type=(UIntType()), name=''))(),
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_indices: tuple[Value, ...] | None = None,
num_control_args: int = 1,
) -> NoneAttributes¶
control_indices: tuple[Value, ...] | Nonecontrol_operands: list[Value]is_symbolic_num_controls: boolnum_control_args: intnum_controls: Valueparam_operands: list[Value] Get classical/object operands after the symbolic control prefix.signature: Signaturetarget_operands: list[Value] Return the wrapped callable’s target and parameter operands.
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationValue [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
ValueResolver [source]¶
class ValueResolverResolves Value objects to concrete indices or values.
Constructor¶
def __init__(self, parameters: set[str] | None = None)Create an emit-time resolver.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | set[str] | None | Names preserved as engine runtime parameters. Defaults to None. |
Attributes¶
parameters
Methods¶
bind_block_params¶
def bind_block_params(
self,
block_value: Any,
param_operands: list['Value'],
bindings: dict[str, Any],
*,
parameter_factory: Callable[[str, str], Any] | None = None,
) -> dict[str, Any]Create local bindings by matching block inputs to call-site operands.
Parameters:
| Name | Type | Description |
|---|---|---|
block_value | Any | Nested block whose classical/object inputs are bound. Objects without input_values receive no additional local bindings for compatibility with optional engine recipes. |
param_operands | list[Value] | Classical/object call-site operands in the controlled operation’s signature order. |
bindings | dict[str, Any] | Parent emit-time bindings used to resolve the call-site operands. |
parameter_factory | Callable[[str, str], Any] | None | Optional engine parameter factory used when an operand is a declared runtime parameter rather than a concrete binding. Defaults to None so standalone resolver use remains engine-neutral. |
Returns:
dict[str, Any] — dict[str, Any]: Parent bindings with each inner formal rebound under
both its UUID and sanctioned parameter-name key.
get_parameter_key¶
def get_parameter_key(self, value: 'Value', bindings: dict[str, Any]) -> str | NoneGet the engine parameter key for a symbolic scalar.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Scalar value or array element to identify. |
bindings | dict[str, Any] | Active bindings used to resolve element indices and slice offsets. |
Returns:
str | None — str | None: Scalar name or root-array indexed key, or None
when an array element’s root location is unresolved.
lookup_in_bindings¶
def lookup_in_bindings(
self,
value: Any,
bindings: dict[str, Any],
*,
index_array: bool = False,
) -> AnyCanonical resolution chain for a Value against bindings.
All other resolver methods (resolve_bound_value,
resolve_classical_value, resolve_int_value,
resolve_operand_for_binding) wrap this single chain. Centralizing
precedence here prevents the historical drift where one resolver
checked is_parameter before UUID and another checked it after,
which manifested as obscure binding failures when name-keyed writes
were dropped from the emit pass.
Resolution order (each step returns immediately on a hit):
valueis already a concrete Python scalar (nouuid).value.uuidis inbindings— return that. This is where emit-time-computed intermediates (evaluate_binop/evaluate_classical_predicateresults) and merge aliases live.A compile-time array or dict payload stored in typed metadata.
value.is_constant()— returnvalue.get_const().value.is_parameter()and its parameter name is inbindings— return that.(When
index_array=True)valueis an array element with a resolvable parent inbindings— index into it.A non-empty display name is present in
bindings. This is a compatibility bridge for programmatically constructed Values and older transforms that do not carry parameter metadata; UUID and explicit parameter provenance always take precedence.
Compiler-created temporaries are anonymous and compiler-internal writers use UUID keys, so the compatibility bridge cannot merge two same-named temporaries. Kernel parameters should normally resolve via explicit parameter metadata, while loop variables and intermediates remain UUID-keyed.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Any | The IR value (or already-concrete Python scalar) to resolve. |
bindings | dict[str, Any] | The active bindings dictionary. |
index_array | bool | When True, also resolve array-element accesses via parent_array indexing. Off by default because not all callers want to index into bound containers. |
Returns:
Any — The resolved Python value, or None if no step matched.
resolve_bound_value¶
def resolve_bound_value(self, value: 'Value', bindings: dict[str, Any]) -> AnyResolve a Value to its raw bound Python object.
Wraps :meth:lookup_in_bindings with index_array=True so that
arr[i] accesses against a bound container resolve to the
element. Does not coerce the result — callers that need a
numeric scalar should go through :meth:resolve_classical_value.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Value to resolve. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
Any — Raw bound object, or None when unresolved.
resolve_classical_value¶
def resolve_classical_value(self, value: 'Value', bindings: dict[str, Any]) -> AnyResolve a classical Value to a concrete Python value.
Numeric bindings are normalized to native Python scalars
regardless of whether they come from a direct binding or from
array-element indexing, so downstream isinstance(x, (int, float)) checks are stable when callers bind np.pi/4 or
the like. bool is preserved (not coerced to int).
Non-numeric values (Hamiltonians, strings, dict values, …)
pass through unchanged.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Classical value to resolve. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
Any — Resolved native scalar/object, or None when unresolved.
resolve_int_value¶
def resolve_int_value(self, val: Any, bindings: dict[str, Any]) -> int | NoneResolve a value to an integer, or None when unresolvable.
Unresolvable symbolic Values must return None. The previous
return 0 fallback caused silent loop elision when parameter
shape dims (gamma_dim0) reached this resolver without being
folded into constants — downstream loop-bound resolution saw 0 and
quietly emitted an empty loop. Returning None propagates the
failure to emit_for_unrolled, which converts it into a hard
compile error.
resolve_operand_for_binding¶
def resolve_operand_for_binding(self, operand: Any, bindings: dict[str, Any]) -> AnyResolve an operand to a concrete value for block parameter binding.
Used when calling a sub-block (e.g. a controlled-U body): each param operand at the call site must resolve to a value to seed the callee’s parameter bindings.
Parameters:
| Name | Type | Description |
|---|---|---|
operand | Any | Call-site value or already-concrete operand. |
bindings | dict[str, Any] | Parent emit-time bindings. |
Returns:
Any — Resolved value, or None when the operand is symbolic.
resolve_qubit_index¶
def resolve_qubit_index(self, v: 'Value', qubit_map: QubitMap, bindings: dict[str, Any]) -> int | NoneResolve a qubit value to its physical index.
Parameters:
| Name | Type | Description |
|---|---|---|
v | Value | Scalar or indexed qubit value. |
qubit_map | QubitMap | Physical resource mapping. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
int | None — int | None: Physical index, or None when unresolved.
resolve_qubit_index_detailed¶
def resolve_qubit_index_detailed(
self,
v: 'Value',
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> QubitResolutionResultResolve a Value to a physical qubit index with detailed failure info.
Parameters:
| Name | Type | Description |
|---|---|---|
v | Value | The qubit Value to resolve. May be a scalar qubit or an array element (possibly through a sliced view chain). |
qubit_map | QubitMap | Mapping from QubitAddress to physical qubit indices built by the resource allocator. |
bindings | dict[str, Any] | Active emit-time bindings used to resolve symbolic element indices and slice bounds. |
Returns:
QubitResolutionResult — Success with the physical index, or a
failure carrying a ResolutionFailureReason — including
NEGATIVE_INDEX when a resolved element index is negative
or a resolved slice bound violates the frontend contract
(non-negative start, positive step); composing those through
the affine map would silently address a wrong root slot.
resolve_slice_chain¶
def resolve_slice_chain(
self,
av: 'ArrayValue',
bindings: dict[str, Any],
*,
operation: str = 'emit',
) -> tuple['ArrayValue', int, int]Walk an ArrayValue’s slice_of chain and return root + affine map.
Composes the nested affine maps so that a view-local index i
corresponds to the root-space index start + step * i. For a
root ArrayValue (no slice_of chain), returns (av, 0, 1)
so callers can always apply the same formula uniformly.
Parameters:
| Name | Type | Description |
|---|---|---|
av | 'ArrayValue' | The possibly-sliced ArrayValue whose root and affine mapping should be resolved. |
bindings | dict[str, Any] | Compile-time parameter bindings; required when any slice_start / slice_step in the chain is symbolic. |
operation | str | Human-readable name of the enclosing emit operation. Used only in the EmitError message when a symbolic slice bound cannot be resolved. Defaults to "emit". |
Returns:
'ArrayValue' — Tuple (root_array, start, step) where root_array is
int — the underlying non-sliced ArrayValue, and start/step
int — are Python int values satisfying
tuple['ArrayValue', int, int] — view[i] == root_array[start + step * i].
Raises:
EmitError— If anyslice_startorslice_stepin the chain resolves to a non-numeric or unbound value, or to bounds violating the frontend contract (negative start or non-positive step).
Example:
>>> # For ``view = q[1::2]`` where ``q`` has 4 qubits:
>>> resolver.resolve_slice_chain(view_av, bindings={})
(q_av, 1, 2)WhileOperation [source]¶
class WhileOperation(HasNestedOps, Operation)Represents a while loop operation.
Only measurement-backed conditions are supported: the condition must
be a Bit value produced by qmc.measure(). Non-measurement
conditions (classical variables, constants, comparisons) are rejected
by ValidateWhileContractPass before reaching engine emit.
Example::
bit = qmc.measure(q)
while bit:
q = qmc.h(q)
bit = qmc.measure(q)Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
operations: list[Operation] = list(),
max_iterations: int | None = None,
loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
region_args: tuple[RegionArg, ...] = (),
captures: tuple[ValueBase, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]max_iterations: int | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the while body and its complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt while operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, rebind-record, and region-arg values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
qamomile.circuit.transpiler.passes.emit_support.value_resolver¶
Value resolution helpers for emission.
Overview¶
| Function | Description |
|---|---|
block_parameter_binding_keys | Return the sanctioned emit-binding keys for an inner formal. |
pair_block_parameter_operands | Pair a block’s classical/object inputs with call-site operands. |
resolve_qubit_key | Resolve a qubit Value to its allocation key. |
resolve_root_qubit_address | Resolve an array-element value to its root (array_uuid, index). |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
EmitError | Report an engine failure to emit one semantic operation. |
QubitAddress | Typed key for qubit/clbit physical-index maps. |
QubitResolutionResult | Result of attempting to resolve a qubit index. |
ResolutionFailureReason | Categorizes why qubit index resolution failed. |
Value | A typed SSA value in the IR. |
ValueResolver | Resolves Value objects to concrete indices or values. |
Functions¶
block_parameter_binding_keys [source]¶
def block_parameter_binding_keys(parameter: ValueBase) -> tuple[str, ...]Return the sanctioned emit-binding keys for an inner formal.
Emit resolution accepts a kernel parameter name before its UUID for public API compatibility, so an operation-owned fresh scope must write both keys. Keeping the key choice here prevents individual emit paths from reviving a parent binding that merely shares the inner formal’s display name.
Parameters:
| Name | Type | Description |
|---|---|---|
parameter | ValueBase | Classical/object formal input being bound. |
Returns:
tuple[str, ...] — tuple[str, ...]: UUID followed by the formal parameter provenance name
and nonempty display-name compatibility key, without duplicates.
pair_block_parameter_operands [source]¶
def pair_block_parameter_operands(
block: Block,
param_operands: Sequence[ValueBase],
) -> list[tuple[ValueBase, ValueBase]]Pair a block’s classical/object inputs with call-site operands.
Both compile-time lowering and emission bind an operation-owned block’s non-quantum inputs by their declaration order. Keeping the filtering and pairing here ensures those stages cannot adopt different positional conventions.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Operation-owned block whose formal inputs define the declaration order. |
param_operands | Sequence[ValueBase] | Classical or object operands at the call site, already ordered according to the operation signature. |
Returns:
list[tuple[ValueBase, ValueBase]] — list[tuple[ValueBase, ValueBase]]: (formal, actual) pairs in
list[tuple[ValueBase, ValueBase]] — declaration order. Missing actual operands leave trailing formals
list[tuple[ValueBase, ValueBase]] — unpaired, so they can remain symbolic and be provided at emit time.
resolve_qubit_key [source]¶
def resolve_qubit_key(qubit: 'Value') -> tuple[QubitAddress | None, bool]Resolve a qubit Value to its allocation key.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | Value | Qubit value to resolve. Array elements with a constant index are resolved through their full slice_of chain to the root array address. |
Returns:
tuple[QubitAddress | None, bool] — tuple[QubitAddress | None, bool]: (address, is_array_element).
address is the root-space address for a resolvable array
element, None for an array element whose index or slice
bounds are symbolic at this binding-free stage, and a scalar
UUID address for non-array qubits. A negative constant index
(or an out-of-contract slice bound) also yields None:
resolve_root_qubit_address refuses it rather than letting it
silently address a wrong root slot.
resolve_root_qubit_address [source]¶
def resolve_root_qubit_address(value: 'Value') -> tuple[str, int] | NoneResolve 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:
| Name | Type | Description |
|---|---|---|
value | Value | The value to resolve. Expected to be an array element (parent_array set with a single constant element_indices entry). |
Returns:
tuple[str, int] | None — tuple[str, int] | None: (root_array_uuid, composed_index) when
value is an array element with a constant index whose entire
slice_of chain has constant slice_start / slice_step.
None when value is not an array element, when its index is
non-constant, or when any slice bound in the chain is non-constant
(those cases are deferred to the emit-time resolver, which has
bindings available). Also None for a negative constant index
or a chain frame with negative slice_start / non-positive
slice_step — composing those would silently address a wrong
root slot, so they are refused rather than guessed (the frontend
rejects them at trace time; this guard covers programmatically
constructed IR).
Classes¶
ArrayValue [source]¶
class ArrayValue(Value[T])An array of typed IR values.
When slice_of is set, this array is a strided view over another
array. Element accesses on a sliced ArrayValue resolve to
physical slots on the root parent via the affine map
parent_index = slice_start + slice_step * view_local_index,
applied recursively along slice_of chains. The emit-time
resolver walks this chain to produce the final qubit index; passes
that substitute or clone values must treat slice_of /
slice_start / slice_step as Value references that need to
track through the same mapping as parent_array.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
shape: tuple[Value, ...] = tuple(),
slice_of: 'ArrayValue | None' = None,
slice_start: 'Value | None' = None,
slice_step: 'Value | None' = None,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]EmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
operation
QubitAddress [source]¶
class QubitAddressTyped 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) -> NoneAttributes¶
element_index: int | Noneis_array_element: bool True if this address refers to an array element.uuid: str
Methods¶
from_composite_key¶
@classmethod
def from_composite_key(cls, key: str) -> QubitAddressParse 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) -> boolTrue if this address belongs to the given array.
with_element¶
def with_element(self, index: int) -> QubitAddressCreate an array-element address from this array’s base UUID.
QubitResolutionResult [source]¶
class QubitResolutionResultResult of attempting to resolve a qubit index.
Constructor¶
def __init__(
self,
success: bool,
index: int | None = None,
failure_reason: ResolutionFailureReason | None = None,
failure_details: str = '',
) -> NoneAttributes¶
failure_details: strfailure_reason: ResolutionFailureReason | Noneindex: int | Nonesuccess: bool
ResolutionFailureReason [source]¶
class ResolutionFailureReason(Enum)Categorizes why qubit index resolution failed.
Attributes¶
ARRAY_ELEMENT_NOT_IN_QUBIT_MAPDIRECT_UUID_NOT_FOUNDINDEX_NOT_NUMERICNEGATIVE_INDEXNESTED_ARRAY_RESOLUTION_FAILEDSYMBOLIC_INDEX_NOT_BOUNDUNKNOWN
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueResolver [source]¶
class ValueResolverResolves Value objects to concrete indices or values.
Constructor¶
def __init__(self, parameters: set[str] | None = None)Create an emit-time resolver.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | set[str] | None | Names preserved as engine runtime parameters. Defaults to None. |
Attributes¶
parameters
Methods¶
bind_block_params¶
def bind_block_params(
self,
block_value: Any,
param_operands: list['Value'],
bindings: dict[str, Any],
*,
parameter_factory: Callable[[str, str], Any] | None = None,
) -> dict[str, Any]Create local bindings by matching block inputs to call-site operands.
Parameters:
| Name | Type | Description |
|---|---|---|
block_value | Any | Nested block whose classical/object inputs are bound. Objects without input_values receive no additional local bindings for compatibility with optional engine recipes. |
param_operands | list[Value] | Classical/object call-site operands in the controlled operation’s signature order. |
bindings | dict[str, Any] | Parent emit-time bindings used to resolve the call-site operands. |
parameter_factory | Callable[[str, str], Any] | None | Optional engine parameter factory used when an operand is a declared runtime parameter rather than a concrete binding. Defaults to None so standalone resolver use remains engine-neutral. |
Returns:
dict[str, Any] — dict[str, Any]: Parent bindings with each inner formal rebound under
both its UUID and sanctioned parameter-name key.
get_parameter_key¶
def get_parameter_key(self, value: 'Value', bindings: dict[str, Any]) -> str | NoneGet the engine parameter key for a symbolic scalar.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Scalar value or array element to identify. |
bindings | dict[str, Any] | Active bindings used to resolve element indices and slice offsets. |
Returns:
str | None — str | None: Scalar name or root-array indexed key, or None
when an array element’s root location is unresolved.
lookup_in_bindings¶
def lookup_in_bindings(
self,
value: Any,
bindings: dict[str, Any],
*,
index_array: bool = False,
) -> AnyCanonical resolution chain for a Value against bindings.
All other resolver methods (resolve_bound_value,
resolve_classical_value, resolve_int_value,
resolve_operand_for_binding) wrap this single chain. Centralizing
precedence here prevents the historical drift where one resolver
checked is_parameter before UUID and another checked it after,
which manifested as obscure binding failures when name-keyed writes
were dropped from the emit pass.
Resolution order (each step returns immediately on a hit):
valueis already a concrete Python scalar (nouuid).value.uuidis inbindings— return that. This is where emit-time-computed intermediates (evaluate_binop/evaluate_classical_predicateresults) and merge aliases live.A compile-time array or dict payload stored in typed metadata.
value.is_constant()— returnvalue.get_const().value.is_parameter()and its parameter name is inbindings— return that.(When
index_array=True)valueis an array element with a resolvable parent inbindings— index into it.A non-empty display name is present in
bindings. This is a compatibility bridge for programmatically constructed Values and older transforms that do not carry parameter metadata; UUID and explicit parameter provenance always take precedence.
Compiler-created temporaries are anonymous and compiler-internal writers use UUID keys, so the compatibility bridge cannot merge two same-named temporaries. Kernel parameters should normally resolve via explicit parameter metadata, while loop variables and intermediates remain UUID-keyed.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Any | The IR value (or already-concrete Python scalar) to resolve. |
bindings | dict[str, Any] | The active bindings dictionary. |
index_array | bool | When True, also resolve array-element accesses via parent_array indexing. Off by default because not all callers want to index into bound containers. |
Returns:
Any — The resolved Python value, or None if no step matched.
resolve_bound_value¶
def resolve_bound_value(self, value: 'Value', bindings: dict[str, Any]) -> AnyResolve a Value to its raw bound Python object.
Wraps :meth:lookup_in_bindings with index_array=True so that
arr[i] accesses against a bound container resolve to the
element. Does not coerce the result — callers that need a
numeric scalar should go through :meth:resolve_classical_value.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Value to resolve. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
Any — Raw bound object, or None when unresolved.
resolve_classical_value¶
def resolve_classical_value(self, value: 'Value', bindings: dict[str, Any]) -> AnyResolve a classical Value to a concrete Python value.
Numeric bindings are normalized to native Python scalars
regardless of whether they come from a direct binding or from
array-element indexing, so downstream isinstance(x, (int, float)) checks are stable when callers bind np.pi/4 or
the like. bool is preserved (not coerced to int).
Non-numeric values (Hamiltonians, strings, dict values, …)
pass through unchanged.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | Classical value to resolve. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
Any — Resolved native scalar/object, or None when unresolved.
resolve_int_value¶
def resolve_int_value(self, val: Any, bindings: dict[str, Any]) -> int | NoneResolve a value to an integer, or None when unresolvable.
Unresolvable symbolic Values must return None. The previous
return 0 fallback caused silent loop elision when parameter
shape dims (gamma_dim0) reached this resolver without being
folded into constants — downstream loop-bound resolution saw 0 and
quietly emitted an empty loop. Returning None propagates the
failure to emit_for_unrolled, which converts it into a hard
compile error.
resolve_operand_for_binding¶
def resolve_operand_for_binding(self, operand: Any, bindings: dict[str, Any]) -> AnyResolve an operand to a concrete value for block parameter binding.
Used when calling a sub-block (e.g. a controlled-U body): each param operand at the call site must resolve to a value to seed the callee’s parameter bindings.
Parameters:
| Name | Type | Description |
|---|---|---|
operand | Any | Call-site value or already-concrete operand. |
bindings | dict[str, Any] | Parent emit-time bindings. |
Returns:
Any — Resolved value, or None when the operand is symbolic.
resolve_qubit_index¶
def resolve_qubit_index(self, v: 'Value', qubit_map: QubitMap, bindings: dict[str, Any]) -> int | NoneResolve a qubit value to its physical index.
Parameters:
| Name | Type | Description |
|---|---|---|
v | Value | Scalar or indexed qubit value. |
qubit_map | QubitMap | Physical resource mapping. |
bindings | dict[str, Any] | Active UUID/parameter bindings. |
Returns:
int | None — int | None: Physical index, or None when unresolved.
resolve_qubit_index_detailed¶
def resolve_qubit_index_detailed(
self,
v: 'Value',
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> QubitResolutionResultResolve a Value to a physical qubit index with detailed failure info.
Parameters:
| Name | Type | Description |
|---|---|---|
v | Value | The qubit Value to resolve. May be a scalar qubit or an array element (possibly through a sliced view chain). |
qubit_map | QubitMap | Mapping from QubitAddress to physical qubit indices built by the resource allocator. |
bindings | dict[str, Any] | Active emit-time bindings used to resolve symbolic element indices and slice bounds. |
Returns:
QubitResolutionResult — Success with the physical index, or a
failure carrying a ResolutionFailureReason — including
NEGATIVE_INDEX when a resolved element index is negative
or a resolved slice bound violates the frontend contract
(non-negative start, positive step); composing those through
the affine map would silently address a wrong root slot.
resolve_slice_chain¶
def resolve_slice_chain(
self,
av: 'ArrayValue',
bindings: dict[str, Any],
*,
operation: str = 'emit',
) -> tuple['ArrayValue', int, int]Walk an ArrayValue’s slice_of chain and return root + affine map.
Composes the nested affine maps so that a view-local index i
corresponds to the root-space index start + step * i. For a
root ArrayValue (no slice_of chain), returns (av, 0, 1)
so callers can always apply the same formula uniformly.
Parameters:
| Name | Type | Description |
|---|---|---|
av | 'ArrayValue' | The possibly-sliced ArrayValue whose root and affine mapping should be resolved. |
bindings | dict[str, Any] | Compile-time parameter bindings; required when any slice_start / slice_step in the chain is symbolic. |
operation | str | Human-readable name of the enclosing emit operation. Used only in the EmitError message when a symbolic slice bound cannot be resolved. Defaults to "emit". |
Returns:
'ArrayValue' — Tuple (root_array, start, step) where root_array is
int — the underlying non-sliced ArrayValue, and start/step
int — are Python int values satisfying
tuple['ArrayValue', int, int] — view[i] == root_array[start + step * i].
Raises:
EmitError— If anyslice_startorslice_stepin the chain resolves to a non-numeric or unbound value, or to bounds violating the frontend contract (negative start or non-positive step).
Example:
>>> # For ``view = q[1::2]`` where ``q`` has 4 qubits:
>>> resolver.resolve_slice_chain(view_av, bindings={})
(q_av, 1, 2)qamomile.circuit.transpiler.passes.entrypoint_validation¶
Entrypoint validation pass for top-level transpilation.
Overview¶
| Class | Description |
|---|---|
Block | Unified block representation for all pipeline stages. |
BlockKind | Classification of block structure for pipeline stages. |
EntrypointValidationError | Error when a top-level transpilation entrypoint has unsupported I/O. |
EntrypointValidationPass | Validate top-level entrypoint constraints. |
Pass | Base class for all compiler passes. |
ValidationError | Error during validation (e.g., non-classical I/O). |
Classes¶
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
EntrypointValidationError [source]¶
class EntrypointValidationError(ValidationError)Error when a top-level transpilation entrypoint has unsupported I/O.
EntrypointValidationPass [source]¶
class EntrypointValidationPass(Pass[Block, Block])Validate top-level entrypoint constraints.
Attributes¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockPass [source]¶
class Pass(ABC, Generic[InputT, OutputT])Base class for all compiler passes.
Attributes¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute 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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable validation failure. |
value_name | str | None | Related IR value name. Defaults to None. |
Attributes¶
value_name
qamomile.circuit.transpiler.passes.eval_utils¶
Preserve compiler imports for the shared classical IR evaluator.
Evaluation semantics live in ir.classical_eval so frontend tracing and
compiler passes use the same pure operations without reversing dependencies.
Overview¶
| Function | Description |
|---|---|
evaluate_binop_values | Evaluate a binary arithmetic operation on two concrete values. |
evaluate_compop_values | Evaluate a comparison operation on two concrete values. |
evaluate_condop_values | Evaluate a logical and/or operation on two concrete values. |
evaluate_notop_value | Evaluate a logical-not operation on a concrete value. |
evaluate_runtime_op_values | Evaluate a lowered runtime-classical expression on concrete operands. |
evaluate_unary_math_value | Evaluate one unary mathematical operation on a concrete value. |
fold_classical_op | Fold a classical op to a concrete value, respecting the given policy. |
| Class | Description |
|---|---|
FoldPolicy | Policy controlling how fold_classical_op treats parameters. |
Functions¶
evaluate_binop_values [source]¶
def evaluate_binop_values(
kind: BinOpKind | None,
left: float | int,
right: float | int,
) -> float | int | NoneEvaluate a binary arithmetic operation on two concrete values.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | BinOpKind | None | Arithmetic operation to apply. |
left | float | int | Left numeric operand. |
right | float | int | Right numeric operand. |
Returns:
float | int | None — float | int | None: Result, or None on division by zero, unknown
kind, or arithmetic error.
evaluate_compop_values [source]¶
def evaluate_compop_values(kind: CompOpKind | None, left: Any, right: Any) -> bool | NoneEvaluate a comparison operation on two concrete values.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | CompOpKind | None | Comparison operation to apply. |
left | Any | Left operand. |
right | Any | Right operand. |
Returns:
bool | None — bool | None: Boolean result, or None on unknown kind or type
incompatibility.
evaluate_condop_values [source]¶
def evaluate_condop_values(kind: CondOpKind | None, left: Any, right: Any) -> bool | NoneEvaluate a logical and/or operation on two concrete values.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | CondOpKind | None | Boolean operation to apply. |
left | Any | Left operand. |
right | Any | Right operand. |
Returns:
bool | None — bool | None: Boolean result, or None on unknown kind.
evaluate_notop_value [source]¶
def evaluate_notop_value(operand: Any) -> bool | NoneEvaluate a logical-not operation on a concrete value.
Parameters:
| Name | Type | Description |
|---|---|---|
operand | Any | Operand to negate. |
Returns:
bool | None — bool | None: Boolean negation, or None on type error.
evaluate_runtime_op_values [source]¶
def evaluate_runtime_op_values(kind: RuntimeOpKind | None, operands: list[Any]) -> Any | NoneEvaluate a lowered runtime-classical expression on concrete operands.
Delegates to the same family evaluators used by BinOp, CompOp,
CondOp, and NotOp so lowering an operation changes only when it is
evaluated, not its scalar semantics.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | RuntimeOpKind | None | Unified lowered operation kind. |
operands | list[Any] | Concrete operands in IR order. NOT requires one operand; every other kind requires two. |
Returns:
Any | None — Any | None: Evaluated numeric or boolean result, or None when the
kind/arity is invalid or the underlying operation fails.
evaluate_unary_math_value [source]¶
def evaluate_unary_math_value(kind: UnaryMathOpKind | None, operand: float | int) -> float | int | NoneEvaluate one unary mathematical operation on a concrete value.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | UnaryMathOpKind | None | Mathematical operation to apply. |
operand | float | int | Concrete numeric operand. |
Returns:
float | int | None — float | int | None: Computed value, or None for an invalid domain
or missing operation kind.
fold_classical_op [source]¶
def fold_classical_op(
op: 'BinOp | CompOp | CondOp | NotOp | UnaryMathOp',
operand_resolver: Callable[[Any], Any],
parameters: set[str],
policy: FoldPolicy,
) -> Any | NoneFold a classical op to a concrete value, respecting the given policy.
The caller supplies an operand_resolver callable that knows how
to look up a Value in the caller’s context (a concrete_values
map, an emit bindings dict + ValueResolver, or any other
source). This function handles:
The parameter guard (skips folding when an operand is a runtime parameter or parameter-array element under
EMIT_RESPECT_PARAMS).Strict scalar-only typing (rejects engine
Exprobjects and other non-numeric values that would spuriously fold toTrue).Kind dispatch via the underlying
evaluate_*_valuesprimitives.
Parameters:
| Name | Type | Description |
|---|---|---|
op | BinOp | CompOp | CondOp | NotOp | UnaryMathOp | Classical op to fold using the supplied operand resolver. |
operand_resolver | Callable[[Any], Any] | Map each operand Value to a resolved Python scalar (or None when unresolvable). |
parameters | set[str] | Runtime parameter names. Used only when policy is EMIT_RESPECT_PARAMS. |
policy | FoldPolicy | Folding policy. See FoldPolicy docstring. |
Returns:
Any | None — Any | None: Folded numeric value or boolean predicate, or None
when an operand is symbolic, missing, or a runtime parameter
under the policy.
Classes¶
FoldPolicy [source]¶
class FoldPolicy(enum.Enum)Policy controlling how fold_classical_op treats parameters.
COMPILE_TIME is for passes that have no notion of runtime
parameters (e.g. compile_time_if_lowering); every operand the
resolver returns is treated as a real value to fold.
EMIT_RESPECT_PARAMS is for emit-time passes where some Values
may correspond to runtime engine parameters whose concrete values
are placeholders or absent. Operands whose Value or
parent_array.name is in the active parameters set are
treated as symbolic and the fold returns None rather than
producing an incorrect concrete result.
Attributes¶
COMPILE_TIMEEMIT_RESPECT_PARAMS
qamomile.circuit.transpiler.passes.inline¶
Inline pass: resolve inline callable invocations to create an affine block.
Overview¶
| Function | Description |
|---|---|
count_inline_invokes | Count all inlineable calls reachable from an operation list. |
count_unrollable_inline_invokes | Count inlineable calls the inline/partial-eval loop can still resolve. |
find_return_operation | Find the ReturnOperation in a list of operations (expected at the end). |
walk_operations | Yield operations in preorder across every nested control-flow region. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
Block | Unified block representation for all pipeline stages. |
BlockKind | Classification of block structure for pipeline stages. |
CallPolicy | Describe the default lowering policy for a callable call. |
CallTransform | Describe the requested transform of a callable implementation. |
ControlledUOperation | Base class for controlled-U operations. |
DictValue | A dictionary value stored as stable ordered entries. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
InlinePass | Inline qkernel callables to create an affine block. |
InverseBlockOperation | Represent an inverse qkernel/block as a first-class IR operation. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
Pass | Base class for all compiler passes. |
QubitConsumedError | Qubit handle used after being consumed by a previous operation. |
ReturnOperation | Explicit return operation marking the end of a block with return values. |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
TupleValue | A tuple of IR values for structured data. |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
Constants¶
ValueLike:TypeAlias='Value | ArrayValue | TupleValue | DictValue'
Functions¶
count_inline_invokes [source]¶
def count_inline_invokes(operations: list[Operation]) -> intCount all inlineable calls reachable from an operation list.
Recurses into InverseBlockOperation / ControlledUOperation /
SelectOperation nested blocks and into HasNestedOps bodies, so
calls hidden inside control flow or operation-owned blocks are counted.
unroll_recursion uses this as the primary termination signal
(count == 0 means the block is fully inlined).
Parameters:
| Name | Type | Description |
|---|---|---|
operations | list[Operation] | Operations to scan. |
Returns:
int — Total number of inlineable calls reachable from operations.
count_unrollable_inline_invokes [source]¶
def count_unrollable_inline_invokes(operations: list[Operation]) -> intCount inlineable calls the inline/partial-eval loop can still resolve.
This mirrors :func:count_inline_invokes but does not descend into
a ControlledUOperation.block, an InverseBlockOperation’s nested
blocks, or a SelectOperation case block. A call still inside one of
those operation-owned blocks after a full inline pass is a
self-recursive call that inline’s cycle guard could not unroll — it stops
after one layer and does not re-enter the operation-owned block — so no
later unroll_recursion iteration can resolve it. Folding compile-time
ifs there never removes the trapped call itself. Such a call is
therefore not unrollable. Calls at the top level or inside For /
If / While bodies are unrollable and are counted.
The unroll loop uses this to tell two failure modes apart: a non-zero
:func:count_inline_invokes with a zero count_unrollable_inline_invokes
means every residual call is trapped inside a controlled / inverted
block (i.e. a recursive qkernel was passed to qmc.control /
qmc.inverse), as opposed to a genuinely non-terminating top-level
recursion.
Parameters:
| Name | Type | Description |
|---|---|---|
operations | list[Operation] | Operations to scan. |
Returns:
int — Number of inlineable calls reachable without entering a
ControlledUOperation.block, InverseBlockOperation nested
block, or SelectOperation case block.
find_return_operation [source]¶
def find_return_operation(operations: list[Operation]) -> ReturnOperation | NoneFind the ReturnOperation in a list of operations (expected at the end).
walk_operations [source]¶
def walk_operations(operations: Sequence[Operation]) -> Iterable[Operation]Yield operations in preorder across every nested control-flow region.
Parameters:
| Name | Type | Description |
|---|---|---|
operations | Sequence[Operation] | Top-level semantic operations. |
Returns:
Iterable[Operation] — Iterable[Operation]: Preorder traversal including nested operations.
Classes¶
ArrayValue [source]¶
class ArrayValue(Value[T])An array of typed IR values.
When slice_of is set, this array is a strided view over another
array. Element accesses on a sliced ArrayValue resolve to
physical slots on the root parent via the affine map
parent_index = slice_start + slice_step * view_local_index,
applied recursively along slice_of chains. The emit-time
resolver walks this chain to produce the final qubit index; passes
that substitute or clone values must treat slice_of /
slice_start / slice_step as Value references that need to
track through the same mapping as parent_array.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
shape: tuple[Value, ...] = tuple(),
slice_of: 'ArrayValue | None' = None,
slice_start: 'Value | None' = None,
slice_step: 'Value | None' = None,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
CallPolicy [source]¶
class CallPolicy(enum.Enum)Describe the default lowering policy for a callable call.
Attributes¶
INLINENATIVE_FIRSTPRESERVE_BOX
CallTransform [source]¶
class CallTransform(enum.Enum)Describe the requested transform of a callable implementation.
Attributes¶
CONTROLLEDCONTROLLED_INVERSEDIRECTINVERSEis_controlled: bool Return whether the transform adds coherent controls.is_inverse: bool Return whether the transform requests inverse application.
Methods¶
inverted¶
def inverted(self) -> CallTransformToggle inverse application while preserving coherent control.
Returns:
CallTransform — Transform with the inverse component toggled.
ControlledUOperation [source]¶
class ControlledUOperation(Operation)Base class for controlled-U operations.
Two concrete subclasses handle distinct operand layouts:
ConcreteControlledU: Fixednum_controls: int, individual qubit operands.SymbolicControlledU: Symbolicnum_controls: Value, vector-based control operands; optionalcontrol_indicesselects a subset of the control vector to act as controls (the rest pass through).
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(),
) -> NoneAttributes¶
block: Block | Nonebody_operands: list[Value] Get the wrapped callable’s complete argument list.callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_operands: list[Value] Get the control qubit values.is_symbolic_num_controls: bool Whether num_controls is symbolic (Value) rather than concrete.num_controls: int | Valueoperation_kind: OperationKindparam_operands: list[Value] Get the controlled operation’s classical/object arguments.power: int | Valuesignature: Signaturetarget_operands: list[Value] Get the target qubit values (arguments to U).
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationDictValue [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()))(),
) -> NoneAttributes¶
entries: tuple[tuple[TupleValue | Value, Value], ...]logical_id: strmetadata: ValueMetadataname: strtype: DictTypeuuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> DictValueHasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
InlinePass [source]¶
class InlinePass(Pass[Block, Block])Inline qkernel callables to create an affine block.
This pass recursively inlines function calls while preserving control flow structures (For, If, While).
Input: Block with BlockKind.HIERARCHICAL (may contain callable calls) Output: Block with BlockKind.AFFINE (no inline callable calls)
Parameters:
| Name | Type | Description |
|---|---|---|
body_selector | Callable[[InvokeOperation], Block | None] | None | Optional body-selection hook for consumers whose configured strategy differs from InvokeOperation.strategy_name. The standard compiler leaves this unset. Defaults to None. |
preserve_bound_quantum_identity | bool | Whether cloned callee quantum values should retain the logical owner and array-element address of their bound caller operands. Resource liveness analysis enables this so an inline call does not create phantom owners or erase lane identities. Defaults to False. |
preserve_bound_array_identity | bool | Whether cloned callee array values should retain the logical lineage of bound caller arrays. Resource classical-state analysis enables this so loop-carried stores remain connected across an inlined call. Defaults to False. |
Constructor¶
def __init__(
self,
body_selector: Callable[[InvokeOperation], Block | None] | None = None,
*,
inline_prefix_factory: Callable[[InvokeOperation, tuple[tuple[ArrayValue, tuple[ArrayValue, ...]], ...]], Sequence[Operation]] | None = None,
preserve_bound_quantum_identity: bool = False,
preserve_bound_array_identity: bool = False,
) -> NoneInitialize the pass with body-selection and identity policies.
Parameters:
| Name | Type | Description |
|---|---|---|
body_selector | Callable[[InvokeOperation], Block | None] | None | Consumer-specific selector used for inline-policy calls. Defaults to the invocation’s ordinary effective body. |
preserve_bound_quantum_identity | bool | Whether cloned quantum SSA values descending from a formal input retain the actual caller operand’s logical owner and array-element address. Defaults to False. |
preserve_bound_array_identity | bool | Whether cloned array SSA values descending from a formal input retain the actual caller array’s logical lineage. Defaults to False. |
Attributes¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockInline all inline-policy callable invocations.
Self-recursive qkernel invocations are unrolled one level per call:
the inner self-call is substituted but left intact so the outer
fixed-point loop can fold the base-case if between iterations.
The output kind is AFFINE when no inlineable calls remain,
otherwise HIERARCHICAL.
InverseBlockOperation [source]¶
class InverseBlockOperation(Operation)Represent an inverse qkernel/block as a first-class IR operation.
The operation stores both the original forward block and a Qamomile-built
inverse implementation block. Emitters may use source_block with a
engine-native inverse/adjoint primitive, then fall back to
implementation_block when native inversion is unavailable.
Operands are ordered as scalar control qubits, target quantum operands,
then classical/object parameters. Results mirror the quantum operand
layout: control results first, then one target result per target operand.
Vector target operands therefore count as one operand/result while
contributing their scalar width to num_target_qubits.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_control_qubits: int = 0,
num_target_qubits: int = 0,
custom_name: str = '',
source_block: Block | None = None,
implementation_block: Block | None = None,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_qubits: list[‘Value’] Return control quantum operands.control_value: int | Nonecustom_name: strimplementation_block: Block | Nonename: str Return a human-readable inverse operation name.num_control_qubits: intnum_target_qubits: intoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return classical/object parameter operands.signature: Signature Return the operation signature.source_block: Block | Nonetarget_qubits: list[‘Value’] Return target quantum operands.
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[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. |
definition | CallableDef | None | Optional 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,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueor an Oracle control-partition field has an invalid Python type.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width, or if Oracle invocation and definition control metadata disagree.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of relevant callable implementations.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return a conservative union of measurement-derived results.name: str Return the display name for this invocation.num_added_control_qubits: int Return controls introduced by a frontend control transform.num_body_external_control_qubits: int Return control operands generic lowering adds outside a base body.num_control_qubits: int Return the number of leading control-qubit operands.num_declared_control_qubits: int Return controls included in an opaque Oracle’s base definition.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
effective_body¶
def effective_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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 | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None, which only selects engine-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
require_body | bool | Whether 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name used for implementation selection. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
select_body¶
def select_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> CallableBodySelectionSelect 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
Pass [source]¶
class Pass(ABC, Generic[InputT, OutputT])Base class for all compiler passes.
Attributes¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute the pass transformation.
QubitConsumedError [source]¶
class QubitConsumedError(AffineTypeError)Qubit handle used after being consumed by a previous operation.
Each qubit handle can only be used once. After a gate operation, you must reassign the result to use the new handle.
Example of incorrect code:
q1 = qm.h(q) q2 = qm.x(q) # ERROR: q was already consumed by h()
Correct code:
q = qm.h(q) # Reassign to capture new handle q = qm.x(q) # Use the reassigned handle
ReturnOperation [source]¶
class ReturnOperation(Operation)Explicit return operation marking the end of a block with return values.
This operation represents an explicit return statement in the IR. It takes the values to be returned as operands and produces no results (it is a terminal operation that transfers control flow back to the caller).
operands: [Value, ...] - The values to return (may be empty for void returns) results: [] - Always empty (terminal operation)
Example:
A function that returns two values (a UInt and a Float):
ReturnOperation(
operands=[uint_value, float_value],
results=[],
)
The signature would be:
operands=[ParamHint("return_0", UIntType()), ParamHint("return_1", FloatType())]
results=[]Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKind Return CLASSICAL as this is a control flow operation without quantum effects.signature: Signature Return the signature with operands for each return value and no results.
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(),
) -> NoneAttributes¶
case_blocks: list[Block]case_callable_attrs: list[dict[str, Any]]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
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]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed replacement values. |
Returns:
Operation — Rebuilt SELECT operation with matching values replaced.
TupleValue [source]¶
class TupleValue(_MetadataValueMixin, ValueBase)A tuple of IR values for structured data.
Constructor¶
def __init__(
self,
name: str,
elements: tuple[ValueLike, ...] = tuple(),
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> NoneAttributes¶
elements: tuple[ValueLike, ...]logical_id: strmetadata: ValueMetadataname: strtype: ‘TupleType’uuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> TupleValueValue [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
qamomile.circuit.transpiler.passes.parameter_shape_resolution¶
Compile-time resolution of symbolic Vector parameter shape dimensions.
Qiskit / CUDA-Q / QuriParts circuits are fixed-structure at compile time:
loop bounds and array lengths must be concrete to emit a valid circuit.
Top-level Vector[Float] / Vector[UInt] parameters are created with
symbolic {name}_dim{i} Values (see
qamomile.circuit.frontend.func_to_block.create_dummy_input), so when a
kernel queries arr.shape[i] the IR references those symbolic Values in
loop operands, array allocations, etc.
This pass walks the HIERARCHICAL block before inlining and, for every
input array whose name is bound to a concrete array-like value in
bindings, replaces its symbolic shape dim Values with constant Values
holding the runtime length. After this pass the downstream pipeline can
unroll for i in qmc.range(arr.shape[0]) loops normally.
Parameters without a concrete binding (e.g. the library QAOA pattern where
only p is bound and gammas.shape is never queried) are left
untouched — their symbolic dims simply do not flow into any compile-time
structure decision, so they are harmless.
Overview¶
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
Block | Unified block representation for all pipeline stages. |
BlockKind | Classification of block structure for pipeline stages. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
ParameterShapeResolutionPass | Substitute symbolic parameter array shape dims with concrete constants. |
Pass | Base class for all compiler passes. |
UIntType | Type representing an unsigned integer. |
ValidationError | Error during validation (e.g., non-classical I/O). |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
Constants¶
ValueLike:TypeAlias='Value | ArrayValue | TupleValue | DictValue'
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,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
HasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
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) -> NoneInitialize parameter-shape resolution.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Compile-time bindings keyed by entrypoint argument name. Defaults to None. |
Attributes¶
name: str Return the pass name.
Methods¶
run¶
def run(self, input: Block) -> BlockReplace resolvable symbolic array dimensions with constants.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Hierarchical semantic block to rewrite. |
Returns:
Block — Rewritten block preserving all display, ABI, parameter, and
stage metadata.
Raises:
ValidationError— Ifinputis not hierarchical.
Pass [source]¶
class Pass(ABC, Generic[InputT, OutputT])Base class for all compiler passes.
Attributes¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute the pass transformation.
UIntType [source]¶
class UIntType(ClassicalTypeMixin, ValueType)Type representing an unsigned integer.
ValidationError [source]¶
class ValidationError(QamomileCompileError)Error during validation (e.g., non-classical I/O).
Constructor¶
def __init__(self, message: str, value_name: str | None = None)Initialize a validation diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable validation failure. |
value_name | str | None | Related IR value name. Defaults to None. |
Attributes¶
value_name
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
qamomile.circuit.transpiler.passes.partial_eval¶
Partial evaluation pass for compile-time simplification.
Overview¶
| Function | Description |
|---|---|
block_parameter_binding_keys | Return the sanctioned emit-binding keys for an inner formal. |
pair_block_parameter_operands | Pair a block’s classical/object inputs with call-site operands. |
reject_control_flow_quantum_discard | Reject control-flow-internal quantum rebinds that discard state. |
reject_loop_carried_classical_rebinds | Reject in-loop classical scalar rebinds that cannot compile correctly. |
reject_self_referential_loop_stores | Reject in-loop classical element stores that read the same array. |
| Class | Description |
|---|---|
Block | Unified block representation for all pipeline stages. |
BlockKind | Classification of block structure for pipeline stages. |
CompileTimeIfLoweringPass | Lowers compile-time resolvable IfOperations before separation. |
ConstantFoldingPass | Evaluates constant expressions at compile time. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
PartialEvaluationPass | Fold constants and lower compile-time control flow. |
Pass | Base class for all compiler passes. |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
UnifiedValueResolver | Resolve IR Values to concrete Python values. |
ValidationError | Error during validation (e.g., non-classical I/O). |
Functions¶
block_parameter_binding_keys [source]¶
def block_parameter_binding_keys(parameter: ValueBase) -> tuple[str, ...]Return the sanctioned emit-binding keys for an inner formal.
Emit resolution accepts a kernel parameter name before its UUID for public API compatibility, so an operation-owned fresh scope must write both keys. Keeping the key choice here prevents individual emit paths from reviving a parent binding that merely shares the inner formal’s display name.
Parameters:
| Name | Type | Description |
|---|---|---|
parameter | ValueBase | Classical/object formal input being bound. |
Returns:
tuple[str, ...] — tuple[str, ...]: UUID followed by the formal parameter provenance name
and nonempty display-name compatibility key, without duplicates.
pair_block_parameter_operands [source]¶
def pair_block_parameter_operands(
block: Block,
param_operands: Sequence[ValueBase],
) -> list[tuple[ValueBase, ValueBase]]Pair a block’s classical/object inputs with call-site operands.
Both compile-time lowering and emission bind an operation-owned block’s non-quantum inputs by their declaration order. Keeping the filtering and pairing here ensures those stages cannot adopt different positional conventions.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Operation-owned block whose formal inputs define the declaration order. |
param_operands | Sequence[ValueBase] | Classical or object operands at the call site, already ordered according to the operation signature. |
Returns:
list[tuple[ValueBase, ValueBase]] — list[tuple[ValueBase, ValueBase]]: (formal, actual) pairs in
list[tuple[ValueBase, ValueBase]] — declaration order. Missing actual operands leave trailing formals
list[tuple[ValueBase, ValueBase]] — unpaired, so they can remain symbolic and be provided at emit time.
reject_control_flow_quantum_discard [source]¶
def reject_control_flow_quantum_discard(operations: list[Operation], bindings: dict[str, Any] | None = None) -> NoneReject 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:
consuming the original inside the branch before rebinding (
if cond: qmc.measure(q); q = qmc.qubit(...)). Scalar consumption is judged at the wire’s final in-branch version (:func:_wire_terminally_consumed), so gating the original and then dropping the gated state (if cond: q = qmc.x(q); q = qmc.qubit("fresh")) is a discard, not a consumption; whole-register rebinds keep the coarser any-touch granularity, where element or view reads count;ordinary quantum rebinds through gates (
q = qmc.h(q)) — the pre-branch value is carried out through the merge;rebinds whose pre-branch value is still owned outside the if (a value consumed before the if, or an alias referenced after it);
handle exchanges where every pre-branch value is carried by some merge of the same side (
q1, q2 = q2, q1).
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:
| Name | Type | Description |
|---|---|---|
operations | list[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. |
bindings | dict[str, Any] | None | Compile-time parameter bindings used to resolve IfOperation conditions, matching what CompileTimeIfLoweringPass will later resolve. Defaults to None (no bindings). |
Raises:
QubitRebindError— If a runtime if branch rebinds a quantum variable whose pre-branch value has no consumer in that branch, no merge carrying it out of that side, and no reference outside the if — or a loop body rebinds a quantum variable whose incoming value it never consumes and whose pre-loop value has no owner outside the loop.
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,
) -> NoneReject 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:
| Name | Type | Description |
|---|---|---|
operations | list[Operation] | Operations to scan. Recurses through all control flow. |
bindings | dict[str, Any] | None | Compile-time parameter bindings used to resolve IfOperation conditions, matching what CompileTimeIfLoweringPass will later resolve. Defaults to None (no bindings). |
output_values | list[ValueLike] | None | The 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:
ValidationError— If a loop body rebinds a classical scalar whose pre-loop value the body still reads (directly, through classical arithmetic, through a surviving merge, or as an embedded constant from a plain-Python initialization), or if a while condition’s pre-loop value is read after the loop.
reject_self_referential_loop_stores [source]¶
def reject_self_referential_loop_stores(operations: list[Operation], bindings: dict[str, Any] | None = None) -> NoneReject 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:
| Name | Type | Description |
|---|---|---|
operations | list[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). |
bindings | dict[str, Any] | None | Compile-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:
ValidationError— If a store inside a loop transitively reads an element of the same logical array it writes.
Classes¶
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
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:
Evaluates conditions including expression-derived ones (
CompOp,CondOp,NotOp,BinOp, andUnaryMathOpchains).Replaces resolved
IfOperations with selected-branch operations.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:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Compile-time bindings visible in the current block. Defaults to no bindings. |
preserved_condition_uuids | AbstractSet[str] | None | Conditions that must remain unresolved so a later validation pass can inspect their dataflow. Defaults to an empty set. |
_under_controlled_unitary | bool | Internal 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_ids | frozenset[int] | None | Internal recursion-path guard for operation-owned blocks. Defaults to an empty set. |
Attributes¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockLower every compile-time resolvable IfOperation in the block.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Block 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:
ValidationError— Ifinput.kindisANALYZED(the pass must run before dependency analysis commits to a representation), or if a compile-time branch selects a symbolic-bound slice-view cast source whose root index space is not resolvable.
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 splitConstructor¶
def __init__(self, bindings: dict[str, Any] | None = None, *, strip_slice_ops: bool = True)Create a constant-folding pass.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Compile-time parameter bindings used when folding BinOps that reference declared parameters. |
strip_slice_ops | bool | When 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¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockFold resolvable classical values throughout a block.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Affine or hierarchical block to rewrite. |
Returns:
Block — Copy with folded operations and output values.
Raises:
ValidationError— If the block is neither affine nor hierarchical.
HasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
PartialEvaluationPass [source]¶
class PartialEvaluationPass(Pass[Block, Block])Fold constants and lower compile-time control flow.
Constructor¶
def __init__(self, bindings: dict[str, Any] | None = None)Attributes¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockFold constants and lower compile-time control flow.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Block to evaluate. AFFINE in the normal pipeline; HIERARCHICAL is also accepted for the self-recursion unroll loop (see inline comment). |
Returns:
Block — Block with constants folded and compile-time-resolvable
IfOperations lowered.
Raises:
ValidationError— If the block kind is notAFFINE/HIERARCHICAL, or if one of the classical pre-fold rejection checks fires (a classical element store inside a loop reads an element of the array it writes, or a loop body rebinds a classical scalar whose pre-loop value it still reads).QubitRebindError— If a runtime if branch or a loop body rebinds a quantum variable to a different quantum value — a fresh allocation or another existing register — in a shape the control-flow discard check cannot prove safe (seereject_control_flow_quantum_discard).
Pass [source]¶
class Pass(ABC, Generic[InputT, OutputT])Base class for all compiler passes.
Attributes¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute 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(),
) -> NoneAttributes¶
case_blocks: list[Block]case_callable_attrs: list[dict[str, Any]]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
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]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed replacement values. |
Returns:
Operation — Rebuilt SELECT operation with matching values replaced.
ValueResolver [source]¶
class ValueResolverResolve IR Values to concrete Python values.
Parameters:
| Name | Type | Description |
|---|---|---|
context | dict[str, Any] | None | UUID-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. |
bindings | dict[str, Any] | None | Name-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:
| Name | Type | Description |
|---|---|---|
context | dict[str, Any] | None | UUID-keyed map of already-resolved values. Defaults to None. |
bindings | dict[str, Any] | None | Name-keyed parameter bindings supplied by the user. Defaults to None. |
Methods¶
resolve¶
def resolve(self, value: Any) -> Any | NoneResolve 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:
| Name | Type | Description |
|---|---|---|
value | Any | The Value-like object or already concrete value to resolve. |
Returns:
Any | None — Any | None: The resolved concrete value, the original
concrete value for non-Value inputs, or None when no
resolution rule applies.
ValidationError [source]¶
class ValidationError(QamomileCompileError)Error during validation (e.g., non-classical I/O).
Constructor¶
def __init__(self, message: str, value_name: str | None = None)Initialize a validation diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable validation failure. |
value_name | str | None | Related IR value name. Defaults to None. |
Attributes¶
value_name
qamomile.circuit.transpiler.passes.region_capture¶
Materialize explicit capture lists on structured semantic IR regions.
Overview¶
| Function | Description |
|---|---|
genuine_input_values | Return an operation’s input values that count as genuine reads. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
Block | Unified block representation for all pipeline stages. |
DictValue | A dictionary value stored as stable ordered entries. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
Pass | Base class for all compiler passes. |
RegionCapturePass | Populate explicit captures for every structured control-flow region. |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
TupleValue | A tuple of IR values for structured data. |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
Functions¶
genuine_input_values [source]¶
def genuine_input_values(op: Operation) -> list[ValueBase]Return an operation’s input values that count as genuine reads.
Structured operations derive reads from their explicit region interface:
enclosing operands, captures, loop initializers, and region yields.
Block arguments and operation results are definitions, while legacy
rebind records are diagnostics rather than dataflow. Leaf operations keep
their ordinary all_input_values contract.
Parameters:
| Name | Type | Description |
|---|---|---|
op | Operation | Operation to inspect. |
Returns:
list[ValueBase] — list[ValueBase]: Semantic reads in interface order.
Classes¶
ArrayValue [source]¶
class ArrayValue(Value[T])An array of typed IR values.
When slice_of is set, this array is a strided view over another
array. Element accesses on a sliced ArrayValue resolve to
physical slots on the root parent via the affine map
parent_index = slice_start + slice_step * view_local_index,
applied recursively along slice_of chains. The emit-time
resolver walks this chain to produce the final qubit index; passes
that substitute or clone values must treat slice_of /
slice_start / slice_step as Value references that need to
track through the same mapping as parent_array.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
shape: tuple[Value, ...] = tuple(),
slice_of: 'ArrayValue | None' = None,
slice_start: 'Value | None' = None,
slice_step: 'Value | None' = None,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
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()))(),
) -> NoneAttributes¶
entries: tuple[tuple[TupleValue | Value, Value], ...]logical_id: strmetadata: ValueMetadataname: strtype: DictTypeuuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> DictValueHasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[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. |
definition | CallableDef | None | Optional 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,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueor an Oracle control-partition field has an invalid Python type.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width, or if Oracle invocation and definition control metadata disagree.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of relevant callable implementations.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return a conservative union of measurement-derived results.name: str Return the display name for this invocation.num_added_control_qubits: int Return controls introduced by a frontend control transform.num_body_external_control_qubits: int Return control operands generic lowering adds outside a base body.num_control_qubits: int Return the number of leading control-qubit operands.num_declared_control_qubits: int Return controls included in an opaque Oracle’s base definition.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
effective_body¶
def effective_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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 | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None, which only selects engine-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
require_body | bool | Whether 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name used for implementation selection. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
select_body¶
def select_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> CallableBodySelectionSelect 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
Pass [source]¶
class Pass(ABC, Generic[InputT, OutputT])Base class for all compiler passes.
Attributes¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute the pass transformation.
RegionCapturePass [source]¶
class RegionCapturePass(Pass[Block, Block])Populate explicit captures for every structured control-flow region.
The pass derives captures from the current semantic IR, so it can normalize hand-built and deserialized blocks as well as frontend output. The pass preserves existing block identity while replacing structured operations with capture-annotated values. Running it repeatedly is idempotent.
Constructor¶
def __init__(self) -> NoneInitialize an empty reachable-block visitation set.
Attributes¶
name: str Return the compiler-visible pass name.
Methods¶
run¶
def run(self, input: Block) -> BlockPopulate explicit captures throughout one block graph.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Semantic entrypoint whose reachable regions should be normalized. |
Returns:
Block — The input entrypoint with capture lists populated on every
reachable structured-control operation.
SelectOperation [source]¶
class SelectOperation(Operation)Quantum multiplexer: apply case_blocks[i] when the index reads i.
Concrete operand layout:
[idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...].
Symbolic-width operand layout:
[idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...].
Results mirror the quantum operand grouping.
A concrete index register is normalized to one scalar Qubit operand
per physical index qubit. A symbolic-width register instead retains each
leading caller argument as one scalar or array operand until its bound
shape is known. Whole-Vector[Qubit] / scalar targets follow and keep
their shapes, and classical parameters shared across every case come last.
Index bit order is LSB-first: idx_0 is the least-significant
bit, matching Qamomile’s qubit-zero convention. Case i is selected
when index qubit j reads bit j of i. len(case_blocks)
need not be a power of two; index values >= len(case_blocks) apply
no operation (identity).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_index_qubits: int | Value = 0,
case_blocks: list[Block] = list(),
num_index_args: int = 0,
case_callable_attrs: list[dict[str, Any]] = list(),
) -> NoneAttributes¶
case_blocks: list[Block]case_callable_attrs: list[dict[str, Any]]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
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]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed replacement values. |
Returns:
Operation — Rebuilt SELECT operation with matching values replaced.
TupleValue [source]¶
class TupleValue(_MetadataValueMixin, ValueBase)A tuple of IR values for structured data.
Constructor¶
def __init__(
self,
name: str,
elements: tuple[ValueLike, ...] = tuple(),
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> NoneAttributes¶
elements: tuple[ValueLike, ...]logical_id: strmetadata: ValueMetadataname: strtype: ‘TupleType’uuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> TupleValueValue [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
qamomile.circuit.transpiler.passes.region_validation¶
Validation of explicit structured-region interfaces.
Overview¶
| Function | Description |
|---|---|
genuine_input_values | Return an operation’s input values that count as genuine reads. |
validate_region_args | Validate the SSA identities owned by a loop’s region arguments. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
Block | Unified block representation for all pipeline stages. |
DictValue | A dictionary value stored as stable ordered entries. |
ForItemsOperation | Represents iteration over dict/iterable items. |
ForOperation | Represents a for loop operation. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
IfOperation | Represents an if-else conditional operation. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
Pass | Base class for all compiler passes. |
RegionValidationPass | Verify dominance and signatures for every explicit semantic region. |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
TupleValue | A tuple of IR values for structured data. |
ValidationError | Error during validation (e.g., non-classical I/O). |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
WhileOperation | Represents a while loop operation. |
Functions¶
genuine_input_values [source]¶
def genuine_input_values(op: Operation) -> list[ValueBase]Return an operation’s input values that count as genuine reads.
Structured operations derive reads from their explicit region interface:
enclosing operands, captures, loop initializers, and region yields.
Block arguments and operation results are definitions, while legacy
rebind records are diagnostics rather than dataflow. Leaf operations keep
their ordinary all_input_values contract.
Parameters:
| Name | Type | Description |
|---|---|---|
op | Operation | Operation to inspect. |
Returns:
list[ValueBase] — list[ValueBase]: Semantic reads in interface order.
validate_region_args [source]¶
def validate_region_args(op: ForOperation | ForItemsOperation | WhileOperation) -> tuple[RegionArg, ...]Validate the SSA identities owned by a loop’s region arguments.
A loop owns several definition namespaces: its iteration variables,
every RegionArg.block_arg, and every RegionArg.result. Those
identities must be pairwise disjoint. Otherwise different stages can
assign incompatible meanings to one UUID: a UUID-keyed environment has
only one slot, so binding either the iteration variable or the carried
value overwrites the other and makes both reads observe the same value.
Parameters:
| Name | Type | Description |
|---|---|---|
op | ForOperation | ForItemsOperation | WhileOperation | Loop operation whose region arguments should be validated. |
Returns:
tuple[RegionArg, ...] — tuple[RegionArg, ...]: The validated op.region_args tuple.
Raises:
ValueError— If result counts or positions disagree, slot types differ, or any loop-owned definition identity collides with another definition or with a region initializer/body yield.
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,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
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()))(),
) -> NoneAttributes¶
entries: tuple[tuple[TupleValue | Value, Value], ...]logical_id: strmetadata: ValueMetadataname: strtype: DictTypeuuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> DictValueForItemsOperation [source]¶
class ForItemsOperation(HasNestedOps, Operation)Represents iteration over dict/iterable items.
Example:
for (i, j), Jij in qmc.items(ising):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]key_is_vector: boolkey_var_values: tuple[Value, ...] | Nonekey_vars: list[str]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]operation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signaturevalue_var: strvalue_var_value: Value | None
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the items-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt items-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationHasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[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. |
definition | CallableDef | None | Optional 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,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueor an Oracle control-partition field has an invalid Python type.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width, or if Oracle invocation and definition control metadata disagree.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of relevant callable implementations.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return a conservative union of measurement-derived results.name: str Return the display name for this invocation.num_added_control_qubits: int Return controls introduced by a frontend control transform.num_body_external_control_qubits: int Return control operands generic lowering adds outside a base body.num_control_qubits: int Return the number of leading control-qubit operands.num_declared_control_qubits: int Return controls included in an opaque Oracle’s base definition.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
effective_body¶
def effective_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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 | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None, which only selects engine-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
require_body | bool | Whether 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name used for implementation selection. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
select_body¶
def select_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> CallableBodySelectionSelect 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
Pass [source]¶
class Pass(ABC, Generic[InputT, OutputT])Base class for all compiler passes.
Attributes¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute the pass transformation.
RegionValidationPass [source]¶
class RegionValidationPass(Pass[Block, Block])Verify dominance and signatures for every explicit semantic region.
Constructor¶
def __init__(self) -> NoneInitialize an empty reachable-block visitation set.
Attributes¶
name: str Return the compiler-visible pass name.
Methods¶
run¶
def run(self, input: Block) -> BlockValidate a block graph and return it unchanged.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Semantic entrypoint whose regions should be verified. |
Returns:
Block — The validated input block.
Raises:
ValidationError— If a region has an undeclared capture, violates dominance, or has an inconsistent block/yield signature.
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(),
) -> NoneAttributes¶
case_blocks: list[Block]case_callable_attrs: list[dict[str, Any]]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
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]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed replacement values. |
Returns:
Operation — Rebuilt SELECT operation with matching values replaced.
TupleValue [source]¶
class TupleValue(_MetadataValueMixin, ValueBase)A tuple of IR values for structured data.
Constructor¶
def __init__(
self,
name: str,
elements: tuple[ValueLike, ...] = tuple(),
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> NoneAttributes¶
elements: tuple[ValueLike, ...]logical_id: strmetadata: ValueMetadataname: strtype: ‘TupleType’uuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> TupleValueValidationError [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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable validation failure. |
value_name | str | None | Related IR value name. Defaults to None. |
Attributes¶
value_name
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]max_iterations: int | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the while body and its complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt while operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, rebind-record, and region-arg values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
qamomile.circuit.transpiler.passes.separate¶
Segmentation pass: Split a block into executable program steps.
Overview¶
| Function | Description |
|---|---|
array_physical_region | Resolve a one-dimensional array to its ordered physical region. |
array_static_length | Resolve a one-dimensional array’s compile-time length. |
arrays_share_physical_region | Return whether two arrays denote the same ordered physical region. |
collect_value_like_uuids | Collect UUIDs contained in a value-like IR object. |
genuine_input_values | Return an operation’s input values that count as genuine reads. |
lower_measure_qfixed | Lower MeasureQFixedOperation to MeasureVectorOperation plus decode. |
lower_measure_qint | Lower MeasureQIntOperation to vector measurement plus integer decode. |
lower_operations | Lower packed-register measurements before segmentation. |
materialize_return | Synchronize output_values from ReturnOperation. |
packed_register_type_width | Return the type-declared width of a packed quantum register type. |
walk_operations | Yield operations in preorder across every nested control-flow region. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
BitType | Type representing a classical bit. |
Block | Unified block representation for all pipeline stages. |
CastOperation | Type cast operation for creating aliases over the same quantum resources. |
ClassicalSegment | A segment of pure classical operations. |
ClassicalStep | A classical execution step. |
ControlFlowVisitor | Base class for visiting operations with control flow handling. |
DecodeQFixedOperation | Decode measured bits to float (classical operation). |
DecodeQIntOperation | Decode least-significant-first measurement bits to an unsigned integer. |
DictValue | A dictionary value stored as stable ordered entries. |
ExpvalOp | Expectation value operation. |
ExpvalSegment | A segment for expectation value computation. |
ExpvalStep | An expectation-value execution step. |
ForItemsOperation | Represents iteration over dict/iterable items. |
ForOperation | Represents a for loop operation. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
HybridBoundary | Represents a measurement or encode operation at quantum/classical boundary. |
IfOperation | Represents an if-else conditional operation. |
MeasureQFixedOperation | Measure a quantum fixed-point number. |
MeasureQIntOperation | Measure an unsigned quantum integer as one abstract hybrid operation. |
MeasureVectorOperation | Measure a vector of qubits. |
MultipleQuantumSegmentsError | Raised when a program cannot fit the single-quantum-segment model. |
NisqSegmentationStrategy | Single-quantum-segment planning strategy for current Qamomile runtimes. |
OperationKind | Classification of operations for classical/quantum separation. |
Pass | Base class for all compiler passes. |
ProgramABI | Runtime-visible ABI for a segmented program. |
ProgramPlan | Execution plan for a hybrid quantum/classical program. |
QuantumSegment | A segment of pure quantum operations. |
QuantumStep | A quantum execution step. |
QubitType | Type representing a quantum bit (qubit). |
ReturnOperation | Explicit return operation marking the end of a block with return values. |
RuntimeClassicalExpr | A classical expression known to require runtime evaluation. |
Segment | Base class for separated computation segments. |
SegmentationPass | Segment a block into a strategy-specific executable program plan. |
SegmentationStrategy | Execution-model-specific strategy for building a ProgramPlan. |
SeparationError | Error during quantum/classical separation. |
TupleValue | A tuple of IR values for structured data. |
UIntType | Type representing an unsigned integer. |
ValidateWhileContractPass | Validates that all WhileOperation conditions are measurement-backed. |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
ValueResolver | Resolve IR Values to concrete Python values. |
WhileOperation | Represents a while loop operation. |
Constants¶
ValueLike:TypeAlias='Value | ArrayValue | TupleValue | DictValue'
Functions¶
array_physical_region [source]¶
def array_physical_region(array: 'ArrayValue') -> tuple[str, tuple[int, ...]] | NoneResolve a one-dimensional array to its ordered physical region.
The region is expressed independently of SSA version UUIDs: the first
element is the root array’s logical_id and the second is the ordered
tuple of root-space indices addressed by the array. This makes a root
register and its full view compare equal while keeping partial, strided,
reordered, and different-root registers distinct.
Parameters:
| Name | Type | Description |
|---|---|---|
array | ArrayValue | Root array or nested sliced view to resolve. The array must be one-dimensional and have a compile-time integer length; every slice bound in its ancestry must also be constant. |
Returns:
tuple[str, tuple[int, ...]] | None — tuple[str, tuple[int, ...]] | None: (root_logical_id, indices)
when the complete ordered coverage is statically known, otherwise
None. Symbolic shapes or slice bounds remain unresolved so
callers can defer to emit-time physical mappings.
array_static_length [source]¶
def array_static_length(array: 'ArrayValue') -> int | NoneResolve a one-dimensional array’s compile-time length.
Parameters:
| Name | Type | Description |
|---|---|---|
array | ArrayValue | Array 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') -> boolReturn whether two arrays denote the same ordered physical region.
Parameters:
| Name | Type | Description |
|---|---|---|
left | ArrayValue | First root array or sliced view. |
right | ArrayValue | Second root array or sliced view. |
Returns:
bool — True for the same SSA value/version lineage, when both arrays
resolve to the same root logical identity and ordered root indices,
or when both resolve to empty regions (whose root is unobservable).
Returns False for non-empty divergent regions and unresolved
symbolic coverage.
collect_value_like_uuids [source]¶
def collect_value_like_uuids(value: 'ValueLike') -> set[str]Collect UUIDs contained in a value-like IR object.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ValueLike | Value-like object to inspect. |
Returns:
set[str] — set[str]: UUIDs for value itself, recursively contained tuple/dict
elements, and array view/element dependencies.
genuine_input_values [source]¶
def genuine_input_values(op: Operation) -> list[ValueBase]Return an operation’s input values that count as genuine reads.
Structured operations derive reads from their explicit region interface:
enclosing operands, captures, loop initializers, and region yields.
Block arguments and operation results are definitions, while legacy
rebind records are diagnostics rather than dataflow. Leaf operations keep
their ordinary all_input_values contract.
Parameters:
| Name | Type | Description |
|---|---|---|
op | Operation | Operation to inspect. |
Returns:
list[ValueBase] — list[ValueBase]: Semantic reads in interface order.
lower_measure_qfixed [source]¶
def lower_measure_qfixed(
op: MeasureQFixedOperation,
cast_source: ArrayValue | None = None,
) -> list[Operation]Lower MeasureQFixedOperation to MeasureVectorOperation plus decode.
Carrier keys are read exclusively from the operand’s required cast metadata.
Parameters:
| Name | Type | Description |
|---|---|---|
op | MeasureQFixedOperation | QFixed measurement to lower. |
cast_source | ArrayValue | None | Source vector for a deferred-width cast. Defaults to None for concrete carrier lists. |
Returns:
list[Operation] — list[Operation]: Ordered vector measurement and fixed-point decode.
Raises:
SeparationError— If cast metadata is missing or the carrier width cannot be resolved at plan time (see :func:_build_register_measurement_arrays).
lower_measure_qint [source]¶
def lower_measure_qint(
op: MeasureQIntOperation,
cast_source: ArrayValue | None = None,
) -> list[Operation]Lower MeasureQIntOperation to vector measurement plus integer decode.
Parameters:
| Name | Type | Description |
|---|---|---|
op | MeasureQIntOperation | Unsigned quantum-integer measurement to lower. |
cast_source | ArrayValue | None | Source vector for a deferred-width cast. Defaults to None for concrete carrier lists. |
Returns:
list[Operation] — list[Operation]: Ordered vector measurement and unsigned-integer
decode.
Raises:
SeparationError— If the carrier width cannot be resolved at plan time (see :func:_build_register_measurement_arrays).
lower_operations [source]¶
def lower_operations(block: Block) -> BlockLower packed-register measurements before segmentation.
QFixed and QInt measurements become one ordered vector measurement plus a type-specific host-side decode operation.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Block whose top-level high-level operations should be lowered. |
Returns:
Block — Block with top-level packed-register measurements split into
quantum measurement and classical decode operations.
Raises:
SeparationError— If a QFixed or QInt measurement occurs inside control flow, where the decoded result cannot cross the segment boundary, or if a measured register’s carrier width cannot be resolved at plan time.
materialize_return [source]¶
def materialize_return(block: Block) -> BlockSynchronize output_values from ReturnOperation.
Uses ReturnOperation.operands as the source of truth for return values, ensuring consistency between the operation stream and block metadata.
packed_register_type_width [source]¶
def packed_register_type_width(value_type: ValueType) -> int | NoneReturn the type-declared width of a packed quantum register type.
Unlike :func:static_quantum_width, this helper consults only the type
and never runtime carrier or fixed-point metadata, so it distinguishes a
register whose width is known to be zero (returns 0) from one whose
width is symbolic (returns None). static_quantum_width cannot make
that distinction for a QFixed whose frontend qfixed metadata records
num_bits=0 for a symbolic layout.
Parameters:
| Name | Type | Description |
|---|---|---|
value_type | ValueType | Type to inspect. Only QUIntType and QFixedType describe packed registers. |
Returns:
int | None — int | None: QUIntType.width or QFixedType.integer_bits + fractional_bits when every component is a compile-time
non-negative integer; None when any component is symbolic or
when value_type is not a packed register type.
walk_operations [source]¶
def walk_operations(operations: Sequence[Operation]) -> Iterable[Operation]Yield operations in preorder across every nested control-flow region.
Parameters:
| Name | Type | Description |
|---|---|---|
operations | Sequence[Operation] | Top-level semantic operations. |
Returns:
Iterable[Operation] — Iterable[Operation]: Preorder traversal including nested operations.
Classes¶
ArrayValue [source]¶
class ArrayValue(Value[T])An array of typed IR values.
When slice_of is set, this array is a strided view over another
array. Element accesses on a sliced ArrayValue resolve to
physical slots on the root parent via the affine map
parent_index = slice_start + slice_step * view_local_index,
applied recursively along slice_of chains. The emit-time
resolver walks this chain to produce the final qubit index; passes
that substitute or clone values must treat slice_of /
slice_start / slice_step as Value references that need to
track through the same mapping as parent_array.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
shape: tuple[Value, ...] = tuple(),
slice_of: 'ArrayValue | None' = None,
slice_start: 'Value | None' = None,
slice_step: 'Value | None' = None,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]BitType [source]¶
class BitType(ClassicalTypeMixin, ValueType)Type representing a classical bit.
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
CastOperation [source]¶
class CastOperation(Operation)Type cast operation for creating aliases over the same quantum resources.
This operation does NOT allocate new qubits. It creates a new Value that references the same underlying quantum resources with a different type.
Use cases:
Vector[Qubit] -> QFixed (after QPE, for phase measurement)
Vector[Qubit] -> QUInt (for quantum arithmetic)
QUInt -> QFixed (reinterpret bits with different encoding)
QFixed -> QUInt (reinterpret bits with different encoding)
operands: [source_value] - The value being cast results: [cast_result] - The new value with target type (same physical qubits)
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
source_type: ValueType | None = None,
target_type: ValueType | None = None,
qubit_mapping: list[str] = list(),
) -> NoneAttributes¶
num_qubits: int Number of qubits involved in the cast.operation_kind: OperationKind Cast stays in the same segment as its source (QUANTUM for quantum types).qubit_mapping: list[str]signature: Signature Return the type signature of this cast operation.source_type: ValueType | Nonetarget_type: ValueType | None
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(),
) -> NoneAttributes¶
kind: SegmentKind
ClassicalStep [source]¶
class ClassicalStepA classical execution step.
Constructor¶
def __init__(self, segment: ClassicalSegment, role: str = 'classical') -> NoneAttributes¶
role: strsegment: ClassicalSegment
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 += 1Methods¶
visit_operation¶
def visit_operation(self, op: Operation) -> NoneProcess a single operation. Override in subclasses.
visit_operations¶
def visit_operations(self, operations: list[Operation]) -> NoneVisit all operations including nested control flow.
DecodeQFixedOperation [source]¶
class DecodeQFixedOperation(Operation)Decode measured bits to float (classical operation).
This operation converts a sequence of classical bits from qubit measurements into a floating-point number using fixed-point encoding.
The decoding formula for least-significant-first storage:
float_value = Σ bit[i] * 2^(int_bits - num_bits + i)
For QPE phase (int_bits=0):
bit[0] has weight 2**(-num_bits) and bit[-1] has weight 0.5.
Example:
bits = [1, 0, 1] with int_bits=0
→ 0.101 (MSB-first display) = 0.5 + 0.125 = 0.625operands: [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,
) -> NoneAttributes¶
int_bits: intnum_bits: intoperation_kind: OperationKindsignature: Signature
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:
| Name | Type | Description |
|---|---|---|
operands | list[Value] | Single measured ArrayValue[Bit] operand. |
results | list[Value] | Single decoded UIntType result. |
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
num_bits: int | None Return the bit count derived from the bit-array operand.operation_kind: OperationKind Classify integer decoding as host-side classical work.signature: Signature Return the integer-decoder signature.
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()))(),
) -> NoneAttributes¶
entries: tuple[tuple[TupleValue | Value, Value], ...]logical_id: strmetadata: ValueMetadataname: strtype: DictTypeuuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> DictValueExpvalOp [source]¶
class ExpvalOp(Operation)Expectation value operation.
This operation computes the expectation value <psi|H|psi> where psi is the quantum state and H is the Hamiltonian observable.
The operation bridges quantum and classical computation:
Input: quantum state (qubits) + Observable reference
Output: classical Float (expectation value)
Example IR:
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
hamiltonian: Value Alias for observable (deprecated, use observable instead).observable: Value The Observable parameter operand.operation_kind: OperationKind ExpvalOp is HYBRID - bridges quantum state to classical value.output: Value The expectation value result.qubits: Value The quantum register operand.signature: Signature
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 = '',
) -> NoneAttributes¶
hamiltonian_value: Value | Nonekind: SegmentKindqubits_value: Value | Noneresult_ref: str
ExpvalStep [source]¶
class ExpvalStepAn expectation-value execution step.
Constructor¶
def __init__(self, segment: ExpvalSegment, quantum_step_index: int = 0) -> NoneAttributes¶
quantum_step_index: intsegment: ExpvalSegment
ForItemsOperation [source]¶
class ForItemsOperation(HasNestedOps, Operation)Represents iteration over dict/iterable items.
Example:
for (i, j), Jij in qmc.items(ising):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]key_is_vector: boolkey_var_values: tuple[Value, ...] | Nonekey_vars: list[str]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]operation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signaturevalue_var: strvalue_var_value: Value | None
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the items-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt items-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationHasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
HybridBoundary [source]¶
class HybridBoundaryRepresents a measurement or encode operation at quantum/classical boundary.
These operations bridge quantum and classical segments.
Constructor¶
def __init__(
self,
operation: Operation,
source_segment_index: int,
target_segment_index: int,
value_ref: str,
) -> NoneAttributes¶
operation: Operationsource_segment_index: inttarget_segment_index: intvalue_ref: str
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
MeasureQFixedOperation [source]¶
class MeasureQFixedOperation(Operation)Measure a quantum fixed-point number.
This operation measures all qubits in a QFixed register and produces a Float result. During transpilation, this is lowered to individual MeasureOperations plus a DecodeQFixedOperation.
operands: [QFixed value (contains qubit_values in params)] results: [Float value]
Encoding:
For QPE phase (int_bits=0):
Qubits are stored least-significant first. For n qubits,
bit i has weight 2**(-n + i).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_bits: int = 0,
int_bits: int = 0,
) -> NoneAttributes¶
int_bits: intnum_bits: intoperation_kind: OperationKindsignature: Signature
MeasureQIntOperation [source]¶
class MeasureQIntOperation(Operation)Measure an unsigned quantum integer as one abstract hybrid operation.
The carrier sequence is least-significant-bit first: carrier i has
integer weight 2**i. Planning lowers this operation to one vector
measurement followed by a host-side DecodeQIntOperation.
The carrier width is not stored on the operation: it is derived from the
register operand’s type and carrier metadata through num_bits.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[Value] | Single QUIntType register operand. |
results | list[Value] | Single decoded UIntType result. |
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
num_bits: int | None Return the carrier count derived from the register operand.operation_kind: OperationKind Classify QInt measurement as a quantum-to-classical bridge.signature: Signature Return the packed-register measurement signature.
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()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
MultipleQuantumSegmentsError [source]¶
class MultipleQuantumSegmentsError(SeparationError)Raised when a program cannot fit the single-quantum-segment model.
Qamomile enforces a single quantum circuit execution pattern:
[Classical Prep] → Quantum Circuit → [Classical Post/Expval]
The error fires when segmentation finds more than one quantum segment
(classical work that must execute between two quantum regions, e.g.
quantum operations resuming after a qmc.expval), or when a
classical value feeding a quantum gate is also consumed by classical
work and therefore cannot be absorbed into the quantum segment.
Note that a loop bound left as a runtime parameter is diagnosed
earlier, by SymbolicShapeValidationPass, with a dedicated
“Cannot unroll loop” message — it does not reach segmentation.
Example:
Incorrect — quantum operations resume after an expectation value,
which closes the quantum segment::
@qmc.qkernel
def kernel(obs: qmc.Observable) -> tuple[qmc.Float, qmc.Bit]:
q = qmc.qubit("q")
q = qmc.h(q)
e = qmc.expval(q, obs) # quantum segment ends here
q2 = qmc.qubit("q2")
q2 = qmc.x(q2) # second quantum segment -> error
return e, qmc.measure(q2)
Correct — keep all quantum operations in one contiguous region and
take the expectation value at the end::
@qmc.qkernel
def kernel(obs: qmc.Observable) -> qmc.Float:
q = qmc.qubit("q")
q = qmc.h(q)
return qmc.expval(q, obs)NisqSegmentationStrategy [source]¶
class NisqSegmentationStrategy(SegmentationStrategy)Single-quantum-segment planning strategy for current Qamomile runtimes.
Methods¶
create_plan¶
def create_plan(
self,
segments: list[Segment],
block: Block,
boundaries: list[HybridBoundary],
) -> ProgramPlanBuild the current single-quantum-segment NISQ plan.
Parameters:
| Name | Type | Description |
|---|---|---|
segments | list[Segment] | Ordered classical, quantum, and expval segments. |
block | Block | Lowered block providing parameters and outputs. |
boundaries | list[HybridBoundary] | Recorded hybrid transitions. |
Returns:
ProgramPlan — Plan with one quantum step and surrounding classical
or expectation-value steps.
Raises:
SeparationError— If no quantum segment exists.MultipleQuantumSegmentsError— If more than one quantum segment would require unsupported JIT-style execution.
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¶
CLASSICALCONTROLHYBRIDQUANTUM
Pass [source]¶
class Pass(ABC, Generic[InputT, OutputT])Base class for all compiler passes.
Attributes¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute the pass transformation.
ProgramABI [source]¶
class ProgramABIRuntime-visible ABI for a segmented program.
Constructor¶
def __init__(
self,
public_inputs: dict[str, ValueLike] = dict(),
output_values: list[ValueLike] = list(),
) -> NoneAttributes¶
output_values: list[ValueLike]public_inputs: dict[str, ValueLike]
ProgramPlan [source]¶
class ProgramPlanExecution plan for a hybrid quantum/classical program.
Structure:
[Optional] Classical preprocessing (parameter computation, etc.)
Single quantum segment (REQUIRED)
[Optional] Expval segment OR classical postprocessing
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(),
) -> NoneAttributes¶
abi: ProgramABIboundaries: list[HybridBoundary]parameters: dict[str, Value]steps: list[ProgramStep]
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,
) -> NoneAttributes¶
kind: SegmentKindnum_qubits: intqubit_values: list[Value]
QuantumStep [source]¶
class QuantumStepA quantum execution step.
Constructor¶
def __init__(self, segment: QuantumSegment) -> NoneAttributes¶
segment: QuantumSegment
QubitType [source]¶
class QubitType(QuantumTypeMixin, ValueType)Type representing a quantum bit (qubit).
ReturnOperation [source]¶
class ReturnOperation(Operation)Explicit return operation marking the end of a block with return values.
This operation represents an explicit return statement in the IR. It takes the values to be returned as operands and produces no results (it is a terminal operation that transfers control flow back to the caller).
operands: [Value, ...] - The values to return (may be empty for void returns) results: [] - Always empty (terminal operation)
Example:
A function that returns two values (a UInt and a Float):
ReturnOperation(
operands=[uint_value, float_value],
results=[],
)
The signature would be:
operands=[ParamHint("return_0", UIntType()), ParamHint("return_1", FloatType())]
results=[]Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKind Return CLASSICAL as this is a control flow operation without quantum effects.signature: Signature Return the signature with operands for each return value and no results.
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:
Binary kinds (EQ/NEQ/LT/LE/GT/GE/AND/OR/ADD/SUB/MUL/DIV/FLOORDIV/MOD/POW):
operands = [lhs, rhs].Unary kind (NOT):
operands = [val].Ternary kind (SELECT):
operands = [condition, true_value, false_value]— the runtime form of a branch merge (result = true_value if condition else false_value).Result:
results = [output_value].
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,
) -> NoneAttributes¶
kind: RuntimeOpKind | Noneoperation_kind: OperationKindsignature: Signature
Segment [source]¶
class Segment(ABC)Base class for separated computation segments.
Constructor¶
def __init__(
self,
operations: list[Operation] = list(),
input_refs: list[str] = list(),
output_refs: list[str] = list(),
) -> NoneAttributes¶
input_refs: list[str]kind: SegmentKind Return the kind of this segment.operations: list[Operation]output_refs: list[str]
SegmentationPass [source]¶
class SegmentationPass(Pass[Block, ProgramPlan])Segment a block into a strategy-specific executable program plan.
This pass:
Materializes return operations (syncs output_values from ReturnOperation)
Splits the operation list into quantum and classical segments
Builds a ProgramPlan via the configured segmentation strategy
Input: Block (typically ANALYZED or AFFINE) Output: ProgramPlan
Constructor¶
def __init__(self, strategy: SegmentationStrategy | None = None) -> NoneAttributes¶
name: str
Methods¶
run¶
def run(self, input: Block) -> ProgramPlanLower and segment a block into a program plan.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Block whose while contract and hybrid operations should be lowered before segmentation. |
Returns:
ProgramPlan — Strategy-produced execution plan.
Raises:
ValidationError— If a runtime while violates its contract.SeparationError— If the strategy finds no quantum segment.MultipleQuantumSegmentsError— If the strategy finds multiple quantum segments.
SegmentationStrategy [source]¶
class SegmentationStrategy(ABC)Execution-model-specific strategy for building a ProgramPlan.
Methods¶
create_plan¶
def create_plan(
self,
segments: list[Segment],
block: Block,
boundaries: list[HybridBoundary],
) -> ProgramPlanBuild a program plan from segmented operations.
Parameters:
| Name | Type | Description |
|---|---|---|
segments | list[Segment] | Ordered execution segments. |
block | Block | Lowered source block carrying the public ABI. |
boundaries | list[HybridBoundary] | Quantum/classical boundaries. |
Returns:
ProgramPlan — Strategy-specific executable plan.
Raises:
NotImplementedError— Always; subclasses must implement planning.
SeparationError [source]¶
class SeparationError(QamomileCompileError)Error during quantum/classical separation.
TupleValue [source]¶
class TupleValue(_MetadataValueMixin, ValueBase)A tuple of IR values for structured data.
Constructor¶
def __init__(
self,
name: str,
elements: tuple[ValueLike, ...] = tuple(),
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> NoneAttributes¶
elements: tuple[ValueLike, ...]logical_id: strmetadata: ValueMetadataname: strtype: ‘TupleType’uuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> TupleValueUIntType [source]¶
class UIntType(ClassicalTypeMixin, ValueType)Type representing an unsigned integer.
ValidateWhileContractPass [source]¶
class ValidateWhileContractPass(Pass[Block, Block])Validates that all WhileOperation conditions are measurement-backed.
Builds a producer map (result UUID → producing Operation instance) and checks every WhileOperation operand against it. A valid condition must be:
A
ValuewithBitTypeMeasurement-backed: produced by
MeasureOperationdirectly, or anIfOperationmerge 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¶
name: str
Methods¶
run¶
def run(self, block: Block) -> BlockValidate all WhileOperations and return block unchanged.
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
ValueResolver [source]¶
class ValueResolverResolve IR Values to concrete Python values.
Parameters:
| Name | Type | Description |
|---|---|---|
context | dict[str, Any] | None | UUID-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. |
bindings | dict[str, Any] | None | Name-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:
| Name | Type | Description |
|---|---|---|
context | dict[str, Any] | None | UUID-keyed map of already-resolved values. Defaults to None. |
bindings | dict[str, Any] | None | Name-keyed parameter bindings supplied by the user. Defaults to None. |
Methods¶
resolve¶
def resolve(self, value: Any) -> Any | NoneResolve 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:
| Name | Type | Description |
|---|---|---|
value | Any | The Value-like object or already concrete value to resolve. |
Returns:
Any | None — Any | None: The resolved concrete value, the original
concrete value for non-Value inputs, or None when no
resolution rule applies.
WhileOperation [source]¶
class WhileOperation(HasNestedOps, Operation)Represents a while loop operation.
Only measurement-backed conditions are supported: the condition must
be a Bit value produced by qmc.measure(). Non-measurement
conditions (classical variables, constants, comparisons) are rejected
by ValidateWhileContractPass before reaching engine emit.
Example::
bit = qmc.measure(q)
while bit:
q = qmc.h(q)
bit = qmc.measure(q)Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
operations: list[Operation] = list(),
max_iterations: int | None = None,
loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
region_args: tuple[RegionArg, ...] = (),
captures: tuple[ValueBase, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]max_iterations: int | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the while body and its complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt while operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, rebind-record, and region-arg values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
qamomile.circuit.transpiler.passes.slice_borrow_check¶
Post-fold block-wide slice-view borrow check.
Mirrors the slice-view subset of the frontend’s
ArrayBase._borrowed_indices borrow-tracker semantics on the IR
after :class:ConstantFoldingPass has resolved slice bounds to
concrete values. The pass exists to catch bugs the trace-time
checker cannot see on its own — slices whose bounds were UInt
at trace time so their covered slot set was not enumerable until
bindings were applied:
Aliasing between a (now-concrete) slice view and another live view of the same root parent (raised as :class:
QubitBorrowConflictErrorfrom :meth:_register_slice_bulk_borrow_if_new).A view whose newly-concrete coverage hits a slot that was consumed by a destructive operation earlier in the block (raised as :class:
QubitConsumedErrorwhile registering the view in :meth:_register_slice_bulk_borrow_if_newor inspecting its operands in :meth:_process_operand_borrows).A slice ownership release, drain, or refresh that crosses a control-flow boundary the current state merge cannot represent safely (raised as :class:
ValidationErrorfrom the corresponding snapshot guard).
Slice views are otherwise treated as affine at the kernel
boundary: a view that goes out of scope without being slice-
assigned back to the parent is no longer flagged here. This
mirrors how element borrows on locally-allocated registers behave
— natural ancilla / scratch-register patterns such as
Deutsch-Jozsa’s ancilla = qs[n] and Simon’s
qs2 = qs[n:2*n] (used by the oracle, then discarded
unmeasured) compile cleanly. The genuine hazards stay covered:
measure(parent)(or any otherparent.consume()site) while a view is live raisesUnreturnedBorrowErrorfrom the frontend’sArrayBase.consume/validate_all_returned.Returning the parent with an outstanding borrow raises
UnreturnedBorrowErrorfromqamomile.circuit.frontend.func_to_block._validate_returned_arrays.Direct
q[i]access on a slot a view currently owns is caught at the frontend’s element-access path / this pass’s :meth:_process_operand_borrowsfor symbolic-bound views.Overlapping live views and use-after-destroy are caught at registration time (see the two error sites above).
The creation of a direct element borrow (q[i]) is intentionally
not observed here because element access emits no IR operation.
Later uses of that element do appear as operation operands, however,
so :meth:_process_operand_borrows can reject a use that collides
with a live slice view. The frontend trace-time validator
(qamomile.circuit.frontend.func_to_block._validate_returned_arrays and
ArrayBase.validate_all_returned) remains the source of truth for
unreturned direct-element borrows that have no observable operand use.
State shape: a single dict keyed by a 2-tuple
(root_logical_id, slot_descriptor) where
root_logical_id is the logical_id of the root parent
ArrayValue (after walking the slice_of chain) and
slot_descriptor is f"const:<idx>" for slots covered by
compile-time-constant slices. Symbolic-bound slices (those whose
bounds remain non-constant post-fold) are not enumerated into
per-qubit slots; the pass records only an exact "sym:<descriptor>"
entry so a later SSA-version refresh of the same symbolic slice
descriptor can update the owner without claiming any new concrete
range.
Namespacing by root logical_id is required so that borrow /
consumed state on one register (a) does not block access to
the identically-named slot on another register (b); without
it, measure(a[1::2]) would incorrectly mark b[1] and
b[3] as destroyed.
Values are either an :class:ArrayValue (the slice view that owns
the slot) or a _ConsumedSlotMarker (a slot already destroyed by
a prior destructive view consume). isinstance on the value
dispatches the two violation messages.
Overview¶
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
BinOp | Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN). |
BinOpKind | |
Block | Unified block representation for all pipeline stages. |
BlockKind | Classification of block structure for pipeline stages. |
CastOperation | Type cast operation for creating aliases over the same quantum resources. |
CompOp | Comparison operation (EQ, NEQ, LT, LE, GT, GE). |
ExpvalOp | Expectation value operation. |
ForOperation | Represents a for loop operation. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
IfMerge | One branch-merge slot of an :class:IfOperation. |
IfOperation | Represents an if-else conditional operation. |
MeasureOperation | |
MeasureVectorOperation | Measure a vector of qubits. |
Pass | Base class for all compiler passes. |
QubitBorrowConflictError | Qubit slot inaccessible because another live handle borrows it. |
QubitConsumedError | Qubit handle used after being consumed by a previous operation. |
SliceBorrowCheckPass | Post-fold linearity checker for sliced views and borrow state. |
UIntType | Type representing an unsigned integer. |
ValidationError | Error during validation (e.g., non-classical I/O). |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
Constants¶
ArrayResourceKey:TypeAlias=tuple[str, object, ConstBoundToken | ValueBoundToken]BoundToken:TypeAlias=ConstBoundToken | ValueBoundToken | MinBoundTokenConstBoundToken:TypeAlias=tuple[Literal['const'], int]MinBoundToken:TypeAlias=tuple[Literal['min'], object, object]Owner=ArrayValue | _ConsumedSlotMarkerBorrow-state owner discriminant.ValueBoundToken:TypeAlias=tuple[Literal['value'], str, int]
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,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]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,
) -> NoneAttributes¶
kind: BinOpKind | Noneoperation_kind: OperationKindsignature: Signature
BinOpKind [source]¶
class BinOpKind(enum.Enum)Attributes¶
ADDDIVFLOORDIVMINMODMULPOWSUB
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
CastOperation [source]¶
class CastOperation(Operation)Type cast operation for creating aliases over the same quantum resources.
This operation does NOT allocate new qubits. It creates a new Value that references the same underlying quantum resources with a different type.
Use cases:
Vector[Qubit] -> QFixed (after QPE, for phase measurement)
Vector[Qubit] -> QUInt (for quantum arithmetic)
QUInt -> QFixed (reinterpret bits with different encoding)
QFixed -> QUInt (reinterpret bits with different encoding)
operands: [source_value] - The value being cast results: [cast_result] - The new value with target type (same physical qubits)
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
source_type: ValueType | None = None,
target_type: ValueType | None = None,
qubit_mapping: list[str] = list(),
) -> NoneAttributes¶
num_qubits: int Number of qubits involved in the cast.operation_kind: OperationKind Cast stays in the same segment as its source (QUANTUM for quantum types).qubit_mapping: list[str]signature: Signature Return the type signature of this cast operation.source_type: ValueType | Nonetarget_type: ValueType | None
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,
) -> NoneAttributes¶
kind: CompOpKind | Noneoperation_kind: OperationKindsignature: Signature
ExpvalOp [source]¶
class ExpvalOp(Operation)Expectation value operation.
This operation computes the expectation value <psi|H|psi> where psi is the quantum state and H is the Hamiltonian observable.
The operation bridges quantum and classical computation:
Input: quantum state (qubits) + Observable reference
Output: classical Float (expectation value)
Example IR:
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
hamiltonian: Value Alias for observable (deprecated, use observable instead).observable: Value The Observable parameter operand.operation_kind: OperationKind ExpvalOp is HYBRID - bridges quantum state to classical value.output: Value The expectation value result.qubits: Value The quantum register operand.signature: Signature
ForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationHasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
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¶
false_value: Valueindex: intis_identity: bool Whether both branches merge the same underlying value.result: Valuetrue_value: Value
Methods¶
select¶
def select(self, taken: bool) -> ValueReturn the branch source selected by a resolved condition.
Parameters:
| Name | Type | Description |
|---|---|---|
taken | bool | The condition’s truth value (True selects the true branch). |
Returns:
Value — true_value when taken is true, else
false_value.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[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()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
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()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
Pass [source]¶
class Pass(ABC, Generic[InputT, OutputT])Base class for all compiler passes.
Attributes¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute the pass transformation.
QubitBorrowConflictError [source]¶
class QubitBorrowConflictError(AffineTypeError)Qubit slot inaccessible because another live handle borrows it.
Raised when a qubit slot cannot be accessed because another live
handle currently borrows it — a slice view that has not been
returned, an outstanding element borrow, or any future borrow form
Qamomile may add. The same error is used whether the conflict is
discovered while tracing concrete indices or after symbolic slice
bounds are resolved during transpilation. Unlike
:class:QubitConsumedError, the slot is not destroyed: releasing the
borrowing handle (slice assignment, element write-back, etc.) restores
access.
Example of incorrect code (overlapping slice views)::
a = q[0:3] # q[0..2] now borrowed by ``a``
b = q[2:5] # ERROR: q[2] is still borrowed by ``a``Correct code::
a = q[0:3]
q[0:3] = a # return ``a`` first
b = q[2:5] # now safeExample 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 borrowedCorrect code::
q0 = qubits[0]
q0 = qmc.h(q0)
qubits[0] = q0 # return the element first
q1 = qubits[1] # now safeQubitConsumedError [source]¶
class QubitConsumedError(AffineTypeError)Qubit handle used after being consumed by a previous operation.
Each qubit handle can only be used once. After a gate operation, you must reassign the result to use the new handle.
Example of incorrect code:
q1 = qm.h(q) q2 = qm.x(q) # ERROR: q was already consumed by h()
Correct code:
q = qm.h(q) # Reassign to capture new handle q = qm.x(q) # Use the reassigned handle
SliceBorrowCheckPass [source]¶
class SliceBorrowCheckPass(Pass[Block, Block])Post-fold linearity checker for sliced views and borrow state.
Runs after :class:ConstantFoldingPass (so slice bounds are
concrete where possible) and before segmentation / emit. Walks
the operations of the root block in order, maintaining a borrow
state map modelled on the frontend’s
:attr:ArrayBase._borrowed_indices — a single dict whose
values are slice-view ArrayValue owners or the
_ConsumedSlotMarker sentinel. Creating a direct element borrow
(q[i]) emits no IR operation, but later operand uses remain visible
to this pass; the frontend validator handles an unreturned borrow with
no observable operand use.
The pass does not flag a leftover slice view at block end —
slice views are affine at the kernel boundary, mirroring how
element borrows behave on a locally-allocated register (the
frontend’s
qamomile.circuit.frontend.func_to_block._validate_returned_arrays
covers the genuine leak: returning the parent with a live borrow).
Anything that actually clashes with a live view (direct slot access,
destructive parent consume, overlapping views, use-after-destroy) is
rejected at the eager check points listed in the module docstring.
Constructor¶
def __init__(self) -> NoneInitialize per-run mutable state to safe defaults.
Attributes¶
name: str Return the pass identifier for tracing/logging.
Methods¶
run¶
def run(self, input: Block) -> BlockRun the borrow tracker over input.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Block 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:
ValidationError— If called on an unexpected block kind or slice ownership cannot be propagated safely across a control-flow boundary.QubitBorrowConflictError— If a slice view and a direct access collide or two live views may overlap.QubitConsumedError— If an operand accesses a destroyed slot or a stale slice version attempts to replace its live successor.
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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable validation failure. |
value_name | str | None | Related IR value name. Defaults to None. |
Attributes¶
value_name
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
qamomile.circuit.transpiler.passes.standard_emit¶
Shared semantic-to-circuit lowering engine.
This module provides the legacy-named StandardEmitPass used internally
by CircuitLoweringPass to walk Qamomile semantic IR and construct the
engine-neutral circuit-family IR.
The actual emission logic is decomposed into focused modules under
emit_support/. This class serves as the orchestrator with thin
wrappers that delegate to those module functions. SDK engines do not
subclass this engine; they consume the resulting immutable circuit program.
Overview¶
| Function | Description |
|---|---|
blockvalue_to_gate | Convert a Block to an engine gate. |
clean_ancilla_toffoli_ladder | Return the arithmetic for the named clean-ancilla recipe. |
emit_controlled_fallback | Fallback emission for controlled-U when gate conversion fails. |
emit_controlled_u | Emit a controlled operation for every concrete operand layout. |
emit_for | Emit a for loop. |
emit_for_items | Emit for-items loop (always unrolled). |
emit_gate | Emit a single gate operation. |
emit_global_phase | Emit a standalone phase when the lowering adapter collects it. |
emit_if | Emit if/else operation. |
emit_inverse_block | Emit a first-class inverse block operation. |
emit_invoke_operation | Emit an invoke operation. |
emit_measure | Emit a single measurement. |
emit_measure_qfixed | Emit QFixed measurement. |
emit_measure_vector | Emit vector measurement. |
emit_multi_controlled_on_clean_ancillas | Lower an irreducible multi-controlled gate via a Toffoli cascade. |
emit_pauli_evolve | Emit Pauli evolution: exp(-i * gamma * H). |
emit_while | Emit while loop operation. |
evaluate_binop | Evaluate a BinOp and store the result in bindings. |
evaluate_classical_predicate | Evaluate a CompOp/CondOp/NotOp at emit time and bind its boolean result. |
evaluate_dict_getitem | Evaluate a DictGetItemOperation and store the result in bindings. |
handle_cast | Handle CastOperation - update qubit_map without emitting gates. |
mark_updated_while_condition | Record that a while update may overwrite its initial snapshot clbit. |
reject_stale_runtime_condition | Reject rereading a measurement snapshot overwritten by an earlier loop. |
split_parameter_key | Split an emitted scalar key into its root name and array indices. |
| Class | Description |
|---|---|
BinOp | Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN). |
CastOperation | Type cast operation for creating aliases over the same quantum resources. |
CompOp | Comparison operation (EQ, NEQ, LT, LE, GT, GE). |
CompositeGateEmitter | Protocol for preserving or lowering boxed callable operations. |
CondOp | Conditional logical operation (AND, OR). |
ControlBatchProfile | Describe resolved work and the engine’s exact-two-control choice. |
ControlledUOperation | Base class for controlled-U operations. |
CountingEmitter | A no-op gate emitter that lets a real emission walk run for counting. |
DictGetItemOperation | Look up one entry of a Dict by a (possibly symbolic) key. |
EmitContext | Bindings container with semantic slots, dict-compatible. |
EmitError | Report an engine failure to emit one semantic operation. |
EmitPass | Base class for engine-specific emission passes. |
ForItemsOperation | Represents iteration over dict/iterable items. |
ForOperation | Represents a for loop operation. |
GateEmitter | Protocol for engine-specific gate emission. |
GateOperation | Quantum gate operation. |
GateOperationType | |
GlobalPhaseOperation | Multiply the complete quantum state by exp(i * phase). |
HasNestedOps | Mixin for operations that contain nested operation lists. |
IfOperation | Represents an if-else conditional operation. |
InverseBlockOperation | Represent an inverse qkernel/block as a first-class IR operation. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
MeasureOperation | |
MeasureQFixedOperation | Measure a quantum fixed-point number. |
MeasureQIntOperation | Measure an unsigned quantum integer as one abstract hybrid operation. |
MeasureVectorOperation | Measure a vector of qubits. |
NotOp | |
OperationKind | Classification of operations for classical/quantum separation. |
ParameterContainerKind | Classify the public container that owns one engine scalar slot. |
PauliEvolveOp | Pauli evolution operation: exp(-i * gamma * H). |
ProjectOperation | Project a qubit in one Pauli basis and keep the projected state. |
QInitOperation | Initialize the qubit |
ResetOperation | Reset a qubit to the |0> state and return the fresh handle. |
ReturnQuantumArrayElementOperation | Validate a branch-selected quantum element’s array return at emit time. |
RuntimeClassicalExpr | A classical expression known to require runtime evaluation. |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
StandardEmitPass | Standard emit pass implementation using GateEmitter protocol. |
StoreArrayElementOperation | Store a classical scalar into one element of a classical array. |
Value | A typed SSA value in the IR. |
WhileOperation | Represents a while loop operation. |
Functions¶
blockvalue_to_gate [source]¶
def blockvalue_to_gate(
emit_pass: 'StandardEmitPass',
block_value: Any,
num_qubits: int,
bindings: dict[str, Any],
input_operands: list[Any] | None = None,
operation_name: str = 'ControlledUOperation',
) -> AnyConvert a Block to an engine gate.
Pre-populates local_qubit_map with one entry per quantum input in
declaration order, then runs the allocator over the block’s body.
For Vector[Qubit] inputs (ArrayValue with a quantum element
type) the entry expands into per-element QubitAddress(uuid, i)
keys — the inner block has no QInitOperation for inputs, so
without these the allocator’s element-resolution assertion fires for
every qs[i] reference in the body.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The emit pass driving the conversion. Used for its _allocator, _emitter, _resolver, and _emit_operations. |
block_value | Any | The inner block to convert. Expected to expose operations and input_values; anything else returns None (the caller falls back to gate-by-gate decomposition). |
num_qubits | int | Total physical qubits the resulting gate will occupy in the parent circuit. Used as the fallback length for a single Vector[Qubit] input whose shape is symbolic and unresolvable from bindings, and as the sub-circuit width when the block has no qubit-producing operations. |
bindings | dict[str, Any] | Parameter bindings forwarded to the allocator and _emit_operations. Also consulted when resolving Vector[Qubit] input shapes. |
input_operands | list[Any] | None | Optional call-site operands corresponding to block_value.input_values. Quantum operands propagate actual Vector[Qubit] shapes into the nested block before the vector-aware input qubit map is populated; classical operands are resolved into local bindings before the nested block is emitted. Defaults to None. |
operation_name | str | Operation name used in diagnostics when input binding fails. Defaults to "ControlledUOperation". |
Returns:
Any — An engine gate object produced by
emit_pass._emitter.circuit_to_gate, or None when the
conversion is unable to proceed (missing operations,
allocator / emitter exception, etc.) so the caller can fall
back to gate-by-gate emission.
clean_ancilla_toffoli_ladder [source]¶
def clean_ancilla_toffoli_ladder(num_controls: int | sp.Expr) -> CleanAncillaToffoliLadder[Any]Return the arithmetic for the named clean-ancilla recipe.
The caller owns recipe selection and must use the result on a branch where at least two controls are active. Keeping validation outside this helper lets symbolic resource expressions construct inactive Piecewise branches without prematurely rejecting them.
Parameters:
| Name | Type | Description |
|---|---|---|
num_controls | int | sp.Expr | Concrete or symbolic control count. |
Returns:
CleanAncillaToffoliLadder[Any] — CleanAncillaToffoliLadder[Any]: Compute, total-Toffoli, and clean-
ancilla requirements in the same numeric domain as the input.
emit_controlled_fallback [source]¶
def emit_controlled_fallback(
emit_pass: 'StandardEmitPass',
circuit: Any,
block_value: Any,
num_controls: int,
control_indices: list[int],
target_indices: list[int],
power: int,
bindings: dict[str, Any],
batch_profile: ControlBatchProfile | None = None,
) -> NoneFallback emission for controlled-U when gate conversion fails.
Decomposes the block body gate-by-gate under the full control set.
A block-local qubit map ties the block’s formal quantum inputs to
target_indices, so every inner gate is emitted on the physical
qubit its operand resolves to — multi-target inner blocks are
supported. Nested ControlledUOperations compose their controls
with the outer ones; irreducible multi-controlled single-qubit
gates route through the engine’s
_emit_irreducible_multi_controlled_gate hook. Subclasses may
still override this method to emit controlled blocks natively
(e.g. CUDA-Q’s cudaq.control helper kernels).
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being built. |
block_value | Any | Block whose operations should be controlled. |
num_controls | int | Number of control qubits. |
control_indices | list[int] | Physical indices of control qubits. |
target_indices | list[int] | Physical indices of target qubits. |
power | int | Number of controlled body repetitions. |
bindings | dict[str, Any] | Parameter bindings visible in the body. |
batch_profile | ControlBatchProfile | None | Previously resolved body profile for this exact block and binding scope. Defaults to None, which lets the controlled walker compute it. |
Raises:
EmitError— Ifnum_controlsdisagrees withcontrol_indices, the block’s quantum inputs cannot be mapped ontotarget_indices, or an inner operation cannot be lowered under the accumulated controls (e.g. an irreducible multi-controlled gate on an engine without the multi-control hook).
emit_controlled_u [source]¶
def emit_controlled_u(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: ControlledUOperation,
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> NoneEmit a controlled operation for every concrete operand layout.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
op | ControlledUOperation | Concrete or symbolic controlled operation. |
qubit_map | QubitMap | Logical-to-physical map, mutated with results. |
bindings | dict[str, Any] | Bindings visible at the call site. |
Raises:
EmitError— If controls, targets, power, or body parameters cannot be resolved, or the engine cannot lower the controlled operation.
emit_for [source]¶
def emit_for(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: ForOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any],
force_unroll: bool = False,
) -> NoneEmit a for loop.
emit_for_items [source]¶
def emit_for_items(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: ForItemsOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any],
) -> NoneEmit for-items loop (always unrolled).
This handles iteration over Dict items, e.g.: for (i, j), Jij in qmc.items(ising): ...
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The emit pass (for resolver access). |
circuit | Any | The engine circuit being built. |
op | ForItemsOperation | The for-items loop being unrolled. |
qubit_map | QubitMap | Current qubit address mapping. |
clbit_map | ClbitMap | Current classical bit address mapping. |
bindings | dict[str, Any] | Current emit-time bindings. |
Raises:
EmitError— If the iterated dict is a runtime parameter — its key structure is unknown at compile time, so the loop cannot be unrolled.ValueError— If the dict entries cannot be resolved for any other reason.
emit_gate [source]¶
def emit_gate(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: GateOperation,
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> NoneEmit a single gate operation.
emit_global_phase [source]¶
def emit_global_phase(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: GlobalPhaseOperation,
bindings: dict[str, Any],
) -> NoneEmit a standalone phase when the lowering adapter collects it.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Circuit representation being emitted into. |
op | GlobalPhaseOperation | Global-phase operation to emit. |
bindings | dict[str, Any] | Active emit bindings. |
Raises:
EmitError— If the adapter cannot preserve or resolve the phase.
emit_if [source]¶
def emit_if(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: IfOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any],
) -> NoneEmit if/else operation.
Handles two condition types:
Compile-time constant (plain Python
int/boolfrom@qkernelAST transformer closure variables, constant-folded Values, or Values resolvable viabindings): the active branch is emitted unconditionally, the inactive branch is discarded. No enginec_if/if_testis needed.Runtime condition (measurement
Valuethat cannot be resolved at compile time): delegates to the engine’semit_if_start/emit_else_start/emit_if_endprotocol.
emit_inverse_block [source]¶
def emit_inverse_block(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: InverseBlockOperation,
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> NoneEmit a first-class inverse block operation.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
op | InverseBlockOperation | Inverse block operation to emit. |
qubit_map | QubitMap | Current quantum value to physical qubit map. |
bindings | dict[str, Any] | Active emit bindings. |
Raises:
EmitError— If an inverse block has missing blocks, unresolved qubit operands, or no available native/fallback emission path.
emit_invoke_operation [source]¶
def emit_invoke_operation(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: InvokeOperation,
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> NoneEmit an invoke operation.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted. |
op | InvokeOperation | Invocation to emit. |
qubit_map | QubitMap | Current qubit allocation map. |
bindings | dict[str, Any] | Active emit bindings. |
Raises:
EmitError— If the invocation is opaque and has neither an executable body nor a selected native emitter.
emit_measure [source]¶
def emit_measure(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: MeasureOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any] | None = None,
) -> NoneEmit a single measurement.
Resolves the qubit operand using the full resolver (handles both scalar qubits and array element qubits with composite keys).
Raises:
EmitError— If the qubit or clbit cannot be resolved to a physical address. A dropped measurement is never recoverable inside a quantum segment — the emitted circuit would silently return results with a measured bit missing — so this is a hard error rather than a warning. The most common trigger is ameasure(q[i])whose indexiis an unresolved native-loop parameter;LoopAnalyzer.should_unrollis expected to have forced such loops to unroll before emit, so reaching this path indicates a real resolution failure.
emit_measure_qfixed [source]¶
def emit_measure_qfixed(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: MeasureQFixedOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
) -> NoneEmit QFixed measurement.
emit_measure_vector [source]¶
def emit_measure_vector(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: MeasureVectorOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any],
) -> NoneEmit vector measurement.
Resolves the qubit operand’s slice_of chain so that measuring a
view (measure(q[1::2])) correctly targets the root parent’s
physical qubits.
Behaviour for unresolvable inputs differs by case:
Unknown vector length (
_resolve_sizereturnsNone) — the function defers silently. This handles transpile-only paths (e.g. unbound parameter-size arrays) where downstream late- binding callers still handle the emit correctly.Resolvable length but a sliced view that resolves to zero physical qubits — raises
EmitError. Previously this produced executions returning[(None, N)], a data-integrity hazard, so the silent path is intentionally narrowed to view-on-empty cases only.Resolvable length but slice bounds are themselves symbolic — raises
EmitErrorfromresolve_slice_chain.
Raises:
EmitError— When a sliced view resolves to zero physical qubits, or when slice bounds remain symbolic at emit time.
emit_multi_controlled_on_clean_ancillas [source]¶
def emit_multi_controlled_on_clean_ancillas(
emit_pass: 'StandardEmitPass',
circuit: Any,
gate_type: GateOperationType,
control_indices: list[int],
target_idx: int,
angle: Any,
ancilla_indices: list[int],
) -> NoneLower an irreducible multi-controlled gate via a Toffoli cascade.
Implements the standard clean-ancilla construction (arXiv:2307.07478,
Appendix A.3): the logical AND of the n controls is accumulated
onto n - 1 clean ancillas with a cascade of Toffoli gates, the
gate is applied once under a single control (the last ancilla)
through :func:emit_single_controlled_primitive, and the cascade is
uncomputed in reverse order. The cost is 2 * (n - 1) Toffoli
gates plus one singly-controlled gate, and every ancilla returns to
|0>, so the same pool may be reused by subsequent gates.
Unlike a dense 2**(n+1) unitary-matrix lowering, this scales
linearly in the control count and keeps rotation angles symbolic,
so runtime-parametric multi-controlled rotations are supported.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Active emit pass. |
circuit | Any | Engine circuit being emitted into. |
gate_type | GateOperationType | Single-qubit gate kind to apply under the controls. |
control_indices | list[int] | Physical control qubits; at least two. |
target_idx | int | Physical target qubit. |
angle | Any | Resolved rotation angle (concrete number or engine parameter expression) for rotation-like gates, or None for fixed gates. |
ancilla_indices | list[int] | Clean (|0>) ancilla qubits; at least len(control_indices) - 1 entries. |
Raises:
EmitError— If fewer than two controls or too few ancillas are supplied (both indicate a caller bug), or the gate type is unsupported by the single-control dispatch.
emit_pauli_evolve [source]¶
def emit_pauli_evolve(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: PauliEvolveOp,
qubit_map: QubitMap,
bindings: dict[str, Any],
) -> NoneEmit Pauli evolution: exp(-i * gamma * H).
Resolves the Hamiltonian from bindings and decomposes each term using the Pauli gadget technique:
Basis change per qubit (X->H, Y->Sdg*H, Z->identity)
CNOT ladder + RZ
Undo basis change
Subclasses can override this for engine-native implementations (e.g., Qiskit PauliEvolutionGate).
emit_while [source]¶
def emit_while(
emit_pass: 'StandardEmitPass',
circuit: Any,
op: WhileOperation,
qubit_map: QubitMap,
clbit_map: ClbitMap,
bindings: dict[str, Any],
) -> NoneEmit while loop operation.
evaluate_binop [source]¶
def evaluate_binop(emit_pass: 'StandardEmitPass', op: BinOp, bindings: dict[str, Any]) -> NoneEvaluate a BinOp and store the result in bindings.
Tries the shared fold_classical_op first for a clean concrete
fold (which already encapsulates the runtime-parameter guard).
Falls back to creating engine Parameter symbols and doing
symbolic arithmetic when one or both operands are runtime
parameters — that’s the path that lets rx(q, gamma * 2) produce
a circuit with a single Parameter("gamma") * 2 expression rather
than baking in a placeholder.
evaluate_classical_predicate [source]¶
def evaluate_classical_predicate(
emit_pass: 'StandardEmitPass',
op: 'CompOp | CondOp | NotOp',
bindings: dict[str, Any],
) -> NoneEvaluate a CompOp/CondOp/NotOp at emit time and bind its boolean result.
Mirrors the predicate evaluation already done by
compile_time_if_lowering and classical_executor so that an
IfOperation whose condition reaches emit unfolded — typically
because its operands depend on a loop variable bound only at emit time
by emit_for_items / emit_for_unrolled — can still be resolved
via resolve_if_condition.
Delegates the actual fold (including runtime-parameter guard and
strict scalar typing) to fold_classical_op so that all three
callers of the same kind dispatch share one implementation. There
is no symbolic-Parameter fallback for predicates: a runtime classical
expression cannot be expressed as a folded scalar, so the op is left
unbound and downstream emit handles it as a runtime condition.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | 'StandardEmitPass' | The active emit pass (for resolver access). |
op | 'CompOp | CondOp | NotOp' | The predicate op to evaluate. |
bindings | dict[str, Any] | Current parameter/loop-variable bindings; mutated in place on successful evaluation. No-op when operands are unresolvable (e.g. measurement bits) or evaluation raises. |
Returns:
None — None.
evaluate_dict_getitem [source]¶
def evaluate_dict_getitem(
emit_pass: 'StandardEmitPass',
op: DictGetItemOperation,
bindings: dict[str, Any],
) -> NoneEvaluate a DictGetItemOperation and store the result in bindings.
Resolves each key component (typically a for-items loop variable
bound by UUID in bindings), looks the key up in the dict’s
resolved entries, and writes the value into bindings under the
result UUID so downstream ops (BinOps feeding gate angles) can
consume it.
When the dict is a declared runtime parameter
(transpile(..., parameters=["coeffs"])), there are no entries to
look up; the resolved key instead names one engine parameter
(coeffs[3] / coeffs[(0, 1)]) which is stored under the
result UUID. Repeated lookups of the same key share one engine
parameter via _get_or_create_parameter.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | The emit pass (for resolver access). |
op | DictGetItemOperation | The lookup op being evaluated. |
bindings | dict[str, Any] | Current emit-time bindings. |
Raises:
EmitError— If a key component or the dict entries cannot be resolved, or the key is not present in the dict.
handle_cast [source]¶
def handle_cast(emit_pass: 'StandardEmitPass', op: CastOperation, qubit_map: QubitMap) -> NoneHandle CastOperation - update qubit_map without emitting gates.
mark_updated_while_condition [source]¶
def mark_updated_while_condition(
emit_pass: 'StandardEmitPass',
operation: WhileOperation,
clbit_map: ClbitMap,
bindings: dict[str, Any],
) -> NoneRecord that a while update may overwrite its initial snapshot clbit.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Emit pass carrying path-local overwrite state. |
operation | WhileOperation | Emitted while operation. |
clbit_map | ClbitMap | Current per-iteration clbit aliases. |
bindings | dict[str, Any] | Active emit-time bindings. |
reject_stale_runtime_condition [source]¶
def reject_stale_runtime_condition(
emit_pass: 'StandardEmitPass',
condition: Value,
clbit_map: ClbitMap,
bindings: dict[str, Any],
) -> NoneReject rereading a measurement snapshot overwritten by an earlier loop.
Parameters:
| Name | Type | Description |
|---|---|---|
emit_pass | StandardEmitPass | Emit pass carrying path-local overwrite state. |
condition | Value | Runtime if/while condition about to be emitted. |
clbit_map | ClbitMap | Current per-iteration clbit aliases. |
bindings | dict[str, Any] | Active emit-time bindings. |
Raises:
EmitError— If an earlier runtime while update on the same control-flow path reused this immutable measurement snapshot’s clbit.
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:
| Name | Type | Description |
|---|---|---|
name | str | Engine parameter key such as theta or angles[1][0]. |
Returns:
tuple[str, tuple[int, ...] | None] — tuple[str, tuple[int, ...] | None]: Root parameter name and its
concrete index tuple, or None for a scalar parameter.
Classes¶
BinOp [source]¶
class BinOp(BinaryOperationBase)Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: BinOpKind | None = None,
) -> NoneAttributes¶
kind: BinOpKind | Noneoperation_kind: OperationKindsignature: Signature
CastOperation [source]¶
class CastOperation(Operation)Type cast operation for creating aliases over the same quantum resources.
This operation does NOT allocate new qubits. It creates a new Value that references the same underlying quantum resources with a different type.
Use cases:
Vector[Qubit] -> QFixed (after QPE, for phase measurement)
Vector[Qubit] -> QUInt (for quantum arithmetic)
QUInt -> QFixed (reinterpret bits with different encoding)
QFixed -> QUInt (reinterpret bits with different encoding)
operands: [source_value] - The value being cast results: [cast_result] - The new value with target type (same physical qubits)
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
source_type: ValueType | None = None,
target_type: ValueType | None = None,
qubit_mapping: list[str] = list(),
) -> NoneAttributes¶
num_qubits: int Number of qubits involved in the cast.operation_kind: OperationKind Cast stays in the same segment as its source (QUANTUM for quantum types).qubit_mapping: list[str]signature: Signature Return the type signature of this cast operation.source_type: ValueType | Nonetarget_type: ValueType | None
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,
) -> NoneAttributes¶
kind: CompOpKind | Noneoperation_kind: OperationKindsignature: Signature
CompositeGateEmitter [source]¶
class CompositeGateEmitter(Protocol[C])Protocol for preserving or lowering boxed callable operations.
The concrete compiler installs a semantic emitter that boxes every executable callable into circuit IR with its identity and fallback body. Native SDK selection happens later, through target capabilities and legalization; this traversal hook must not import or select an engine.
Methods¶
can_emit¶
def can_emit(self, gate_type: CompositeGateType) -> boolCheck whether this emitter handles the given callable kind.
Parameters:
| Name | Type | Description |
|---|---|---|
gate_type | CompositeGateType | Callable kind to check. |
Returns:
bool — True if this emitter handles the callable kind.
emit¶
def emit(
self,
circuit: C,
op: InvokeOperation,
qubit_indices: list[int],
bindings: dict[str, Any],
) -> boolPreserve or lower the boxed callable into the output builder.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | C | Output builder receiving the callable representation. |
op | InvokeOperation | Invocation to preserve or lower. |
qubit_indices | list[int] | Physical qubit indices for the operation. |
bindings | dict[str, Any] | Parameter bindings for the operation. |
Returns:
bool — True if handled, or False to use the generic fallback
bool — decomposition.
CondOp [source]¶
class CondOp(BinaryOperationBase)Conditional logical operation (AND, OR).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: CondOpKind | None = None,
) -> NoneAttributes¶
kind: CondOpKind | Noneoperation_kind: OperationKindsignature: Signature
ControlBatchProfile [source]¶
class ControlBatchProfileDescribe resolved work and the engine’s exact-two-control choice.
Parameters:
| Name | Type | Description |
|---|---|---|
weight | int | Controlled work clamped to zero, one, or two. |
selects_exact_two | bool | Whether the engine selects a shared carrier when exactly two outer controls are present. |
Constructor¶
def __init__(self, weight: int = 0, selects_exact_two: bool = False) -> NoneAttributes¶
decision_complete: bool Return whether later work cannot change the batching decision.selects_exact_two: boolweight: int
ControlledUOperation [source]¶
class ControlledUOperation(Operation)Base class for controlled-U operations.
Two concrete subclasses handle distinct operand layouts:
ConcreteControlledU: Fixednum_controls: int, individual qubit operands.SymbolicControlledU: Symbolicnum_controls: Value, vector-based control operands; optionalcontrol_indicesselects a subset of the control vector to act as controls (the rest pass through).
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(),
) -> NoneAttributes¶
block: Block | Nonebody_operands: list[Value] Get the wrapped callable’s complete argument list.callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_operands: list[Value] Get the control qubit values.is_symbolic_num_controls: bool Whether num_controls is symbolic (Value) rather than concrete.num_controls: int | Valueoperation_kind: OperationKindparam_operands: list[Value] Get the controlled operation’s classical/object arguments.power: int | Valuesignature: Signaturetarget_operands: list[Value] Get the target qubit values (arguments to U).
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationCountingEmitter [source]¶
class CountingEmitterA no-op gate emitter that lets a real emission walk run for counting.
Wraps the real engine emitter, delegating capability queries so
control-flow lowering matches real emission while turning every gate
emission into a no-op and every gate/sub-circuit construction into a
None that forces the cascade-prone fallback path. Used by isolated
analysis-emission transactions for ancilla sizing and zero-work semantic
validation; the object is passed where a GateEmitter[T] is expected
via a cast.
Constructor¶
def __init__(self, real: Any) -> NoneWrap a real emitter for a counting run.
Parameters:
| Name | Type | Description |
|---|---|---|
real | Any | The engine emitter whose capability answers should be mirrored so the walk makes the same structural choices. |
Attributes¶
measurement_mode: MeasurementMode Delegate the measurement mode to the wrapped emitter.
Methods¶
append_gate¶
def append_gate(self, circuit: Any, gate: Any, qubits: list[int]) -> NoneCount appending a prebuilt gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
gate | Any | Ignored gate object (never built in counting mode). |
qubits | list[int] | Ignored qubit indices the gate acts on. |
circuit_to_gate¶
def circuit_to_gate(self, circuit: Any, name: str = 'U') -> AnyForce the fallback path by declining to build a reusable gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
name | str | Ignored gate name. Defaults to "U". |
Returns:
Any — Always None.
combine_symbolic¶
def combine_symbolic(self, kind: Any, lhs: Any, rhs: Any) -> _CountingParameterReturn a placeholder for a symbolic angle combination.
Parameters:
| Name | Type | Description |
|---|---|---|
kind | Any | Ignored binary-op kind. |
lhs | Any | Ignored left operand. |
rhs | Any | Ignored right operand. |
Returns:
_CountingParameter — A placeholder symbolic angle.
create_circuit¶
def create_circuit(self, num_qubits: int, num_clbits: int) -> _CountingCircuitReturn a placeholder circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
num_qubits | int | Ignored. |
num_clbits | int | Ignored. |
Returns:
_CountingCircuit — A stateless placeholder.
create_parameter¶
def create_parameter(self, name: str) -> _CountingParameterReturn an arithmetic-absorbing placeholder parameter.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Ignored. |
Returns:
_CountingParameter — A placeholder runtime parameter.
emit_barrier¶
def emit_barrier(self, circuit: Any, qubits: list[int]) -> NoneCount a barrier as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubits | list[int] | Ignored qubit indices spanned by the barrier. |
emit_ch¶
def emit_ch(self, circuit: Any, control: int, target: int) -> NoneCount a CH gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
emit_cp¶
def emit_cp(self, circuit: Any, control: int, target: int, angle: Any) -> NoneCount a controlled-phase gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
angle | Any | Ignored phase angle. |
emit_crx¶
def emit_crx(self, circuit: Any, control: int, target: int, angle: Any) -> NoneCount a CRX gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
angle | Any | Ignored rotation angle. |
emit_cry¶
def emit_cry(self, circuit: Any, control: int, target: int, angle: Any) -> NoneCount a CRY gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
angle | Any | Ignored rotation angle. |
emit_crz¶
def emit_crz(self, circuit: Any, control: int, target: int, angle: Any) -> NoneCount a CRZ gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
angle | Any | Ignored rotation angle. |
emit_cx¶
def emit_cx(self, circuit: Any, control: int, target: int) -> NoneCount a CX gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
emit_cy¶
def emit_cy(self, circuit: Any, control: int, target: int) -> NoneCount a CY gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
emit_cz¶
def emit_cz(self, circuit: Any, control: int, target: int) -> NoneCount a CZ gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control | int | Ignored control qubit index. |
target | int | Ignored target qubit index. |
emit_else_start¶
def emit_else_start(self, circuit: Any, context: Any) -> NoneCount the start of a native else branch as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
context | Any | Ignored branch context from emit_if_start. |
emit_for_loop_end¶
def emit_for_loop_end(self, circuit: Any, context: Any) -> NoneCount the end of a native for loop as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
context | Any | Ignored loop context from emit_for_loop_start. |
emit_for_loop_start¶
def emit_for_loop_start(self, circuit: Any, indexset: range) -> AnyReturn a placeholder loop variable for a native-for-loop count.
Unlike the other control-flow hooks, emit_for’s return value is
bound as the loop variable (via _bind_loop_var) and the body is
then walked once. A real native-loop emitter returns a symbolic
loop parameter, so return the arithmetic-absorbing
:class:_CountingParameter rather than None — otherwise a
body that carries the loop value into an angle or index expression
during counting would see None and fail. (No pool-reserving
engine supports native for loops today, so this is future-proofing.)
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored. |
indexset | range | Ignored. |
Returns:
Any — A placeholder loop variable.
emit_global_phase¶
def emit_global_phase(self, circuit: Any, angle: Any) -> NoneAccept a standalone phase during the internal counting walk.
The counting emitter observes only peak clean-ancilla demand. It does not materialize any gate, including a phase that the wrapped real emitter will preserve during the subsequent emission walk.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
angle | Any | Ignored phase angle. |
emit_h¶
def emit_h(self, circuit: Any, qubit: int) -> NoneCount an H gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_if_end¶
def emit_if_end(self, circuit: Any, context: Any) -> NoneCount the end of a native if/else block as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
context | Any | Ignored branch context from emit_if_start. |
emit_if_start¶
def emit_if_start(self, circuit: Any, clbit: int, value: int = 1) -> AnyCount the start of a native if branch as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
clbit | int | Ignored predicate classical bit index. |
value | int | Ignored predicate value to match. Defaults to 1. |
Returns:
Any — Always None (a null branch context).
emit_measure¶
def emit_measure(self, circuit: Any, qubit: int, clbit: int) -> NoneCount a measurement as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored measured qubit index. |
clbit | int | Ignored destination classical bit index. |
emit_p¶
def emit_p(self, circuit: Any, qubit: int, angle: Any) -> NoneCount a phase gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
angle | Any | Ignored phase angle. |
emit_reset¶
def emit_reset(self, circuit: Any, qubit: int) -> NoneCount a reset as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored reset qubit index. |
emit_rx¶
def emit_rx(self, circuit: Any, qubit: int, angle: Any) -> NoneCount an RX gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
angle | Any | Ignored rotation angle. |
emit_ry¶
def emit_ry(self, circuit: Any, qubit: int, angle: Any) -> NoneCount an RY gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
angle | Any | Ignored rotation angle. |
emit_rz¶
def emit_rz(self, circuit: Any, qubit: int, angle: Any) -> NoneCount an RZ gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
angle | Any | Ignored rotation angle. |
emit_rzz¶
def emit_rzz(self, circuit: Any, qubit1: int, qubit2: int, angle: Any) -> NoneCount an RZZ gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit1 | int | Ignored first qubit index. |
qubit2 | int | Ignored second qubit index. |
angle | Any | Ignored rotation angle. |
emit_s¶
def emit_s(self, circuit: Any, qubit: int) -> NoneCount an S gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_sdg¶
def emit_sdg(self, circuit: Any, qubit: int) -> NoneCount an Sdg gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_swap¶
def emit_swap(self, circuit: Any, qubit1: int, qubit2: int) -> NoneCount a SWAP gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit1 | int | Ignored first qubit index. |
qubit2 | int | Ignored second qubit index. |
emit_t¶
def emit_t(self, circuit: Any, qubit: int) -> NoneCount a T gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_tdg¶
def emit_tdg(self, circuit: Any, qubit: int) -> NoneCount a Tdg gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_toffoli¶
def emit_toffoli(self, circuit: Any, control1: int, control2: int, target: int) -> NoneCount a Toffoli gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
control1 | int | Ignored first control qubit index. |
control2 | int | Ignored second control qubit index. |
target | int | Ignored target qubit index. |
emit_while_end¶
def emit_while_end(self, circuit: Any, context: Any) -> NoneCount the end of a native while loop as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
context | Any | Ignored loop context from emit_while_start. |
emit_while_start¶
def emit_while_start(self, circuit: Any, clbit: int, value: int = 1) -> AnyCount the start of a native while loop as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
clbit | int | Ignored predicate classical bit index. |
value | int | Ignored predicate value to match. Defaults to 1. |
Returns:
Any — Always None (a null loop context).
emit_x¶
def emit_x(self, circuit: Any, qubit: int) -> NoneCount an X gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_y¶
def emit_y(self, circuit: Any, qubit: int) -> NoneCount a Y gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
emit_z¶
def emit_z(self, circuit: Any, qubit: int) -> NoneCount a Z gate as a no-op.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | Any | Ignored placeholder circuit. |
qubit | int | Ignored target qubit index. |
gate_controlled¶
def gate_controlled(self, gate: Any, num_controls: int) -> AnyDecline to build a real controlled gate.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | Any | Ignored gate object. |
num_controls | int | Ignored number of control qubits. |
Returns:
Any — Always None.
gate_inverse¶
def gate_inverse(self, gate: Any) -> AnyDecline to build a real inverse gate.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | Any | Ignored gate object. |
Returns:
Any — Always None.
gate_power¶
def gate_power(self, gate: Any, power: int) -> AnyDecline to build a real powered gate.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | Any | Ignored gate object. |
power | int | Ignored exponent. |
Returns:
Any — Always None.
supports_for_loop¶
def supports_for_loop(self) -> boolDelegate native-for-loop support to the wrapped emitter.
Returns:
bool — The real emitter’s answer, so loops unroll (or not) the
same way real emission would.
supports_gate_inverse¶
def supports_gate_inverse(self) -> boolForce the inverse-by-emission fallback path.
Returns:
bool — Always False.
supports_if_else¶
def supports_if_else(self) -> boolDelegate native if/else support to the wrapped emitter.
Returns:
bool — The real emitter’s answer.
supports_reusable_gates¶
def supports_reusable_gates(self) -> boolForce the gate-by-gate fallback path.
Returns:
bool — Always False.
supports_while_loop¶
def supports_while_loop(self) -> boolDelegate native while-loop support to the wrapped emitter.
Returns:
bool — The real emitter’s answer.
DictGetItemOperation [source]¶
class DictGetItemOperation(Operation)Look up one entry of a Dict by a (possibly symbolic) key.
This is the IR form of d[key] on a Dict handle. The key
components may be symbolic (e.g. loop variables of a for-items
loop); the lookup is resolved at emit time when the key values and
the dict’s bound data are both concrete.
operands: [DictValue, *key_component_values] results: [looked-up scalar value]
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
key_arity: int = 1,
) -> NoneAttributes¶
dict_value: Value Value: The DictValue being indexed (operands[0]).key_arity: intkey_values: tuple[Value, ...] tuple[Value, ...]: The key component values.operation_kind: OperationKindsignature: Signature
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
TrueConstructor¶
def __init__(self, *args: Any = (), **kwargs: Any = {}) -> NoneMethods¶
bind_param¶
def bind_param(self, name: str, value: Any) -> NoneRegister a kernel parameter binding (by name).
bind_params¶
def bind_params(self, params: dict[str, Any]) -> NoneRegister 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) -> strReturn 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:
| Name | Type | Description |
|---|---|---|
user_bindings | dict[str, Any] | None | The 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) -> AnyGet array data by ArrayValue.uuid, or None.
get_dict_data¶
def get_dict_data(self, uuid: str) -> AnyGet dict data by DictValue.uuid, or None.
get_loop_var¶
def get_loop_var(self, uuid: str) -> AnyGet a loop variable binding by Value UUID, or None if absent.
get_observable¶
def get_observable(self, uuid: str) -> AnyGet a Pauli observable by Value UUID, or None.
get_runtime_expr¶
def get_runtime_expr(self, uuid: str) -> AnyGet 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) -> NoneBind a loop iteration variable, keyed by Value UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
uuid | str | loop_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. |
value | Any | The bound iteration value (int / Hamiltonian item / etc.). |
display_name | str | None | Reserved 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]) -> NoneRestore 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:
| Name | Type | Description |
|---|---|---|
snapshot | dict[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) -> NoneBind array data by ArrayValue.uuid.
Parameters:
| Name | Type | Description |
|---|---|---|
uuid | str | The array Value’s UUID. |
data | Any | The bound iterable / sequence / Vector handle. |
display_name | str | None | Reserved 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) -> NoneBind dict data by DictValue.uuid.
Parameters:
| Name | Type | Description |
|---|---|---|
uuid | str | The dict Value’s UUID. |
data | Any | The bound dict / iterable. |
display_name | str | None | Reserved 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) -> NoneBind a Pauli observable by Value UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
uuid | str | The observable Value’s UUID. |
observable | Any | A qm_o.Hamiltonian (or engine-equivalent). |
display_name | str | None | Reserved for debug-only display. It is not used as a binding key. |
set_runtime_expr¶
def set_runtime_expr(self, uuid: str, expr: Any) -> NoneBind 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) -> NoneBind an emit-time-computed intermediate by Value UUID.
Use for BinOp / CompOp / CondOp / NotOp results,
merge aliases, and other UUID-identified intermediates.
snapshot_state¶
def snapshot_state(self) -> dict[str, Any]Capture the dict body and every semantic slot for later restore.
Used to run a throwaway dry-run emission (ancilla demand counting)
against the same context object and then roll it back, so the count
run’s intermediate fold results and parameters do not leak into the
real emission. Unlike copy this records enough to restore this
object in place, preserving its identity for callers that hold a
reference to it.
Returns:
dict[str, Any] — dict[str, Any]: A snapshot passable to restore_state.
EmitError [source]¶
class EmitError(QamomileCompileError)Report an engine failure to emit one semantic operation.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related 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):
returnConstructor¶
def __init__(self, message: str, operation: str | None = None)Initialize an engine emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
operation
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:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Values to bind parameters to. If not provided, parameters must be bound at execution time. |
parameters | list[str] | None | List of parameter names to preserve as engine parameters. |
Raises:
ValueError— If a name appears in bothbindingsandparameters. This is the innermost emit-side choke point: it catches the overlap even when anEmitPassis constructed directly (e.g. viaTranspiler._create_emit_pass), bypassing thetranspile/emitwrappers. A name in both is ambiguous and would otherwise silently bake the binding while dropping the runtime parameter (see #354).
Attributes¶
bindingsname: strparameters
Methods¶
run¶
def run(self, input: ProgramPlan) -> ExecutableProgram[T]Emit engine code from a program plan.
Parameters:
| Name | Type | Description |
|---|---|---|
input | ProgramPlan | Segmented 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:
EmitError— If expectation-value evaluation is combined with a measurement, projection, or reset operation, or if a planned segment cannot be emitted.
ForItemsOperation [source]¶
class ForItemsOperation(HasNestedOps, Operation)Represents iteration over dict/iterable items.
Example:
for (i, j), Jij in qmc.items(ising):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]key_is_vector: boolkey_var_values: tuple[Value, ...] | Nonekey_vars: list[str]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]operation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signaturevalue_var: strvalue_var_value: Value | None
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the items-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt items-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationGateEmitter [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¶
measurement_mode: MeasurementMode Return the measurement mode for this engine.
Methods¶
append_gate¶
def append_gate(self, circuit: T, gate: Any, qubits: list[int]) -> NoneAppend a gate to the circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | T | The circuit to append to |
gate | Any | The gate to append (from circuit_to_gate) |
qubits | list[int] | Target qubit indices |
circuit_to_gate¶
def circuit_to_gate(self, circuit: T, name: str = 'U') -> AnyConvert a circuit to a reusable gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | T | The circuit to convert |
name | str | Label 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) -> TCreate a new empty circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
num_qubits | int | Number of qubits in the circuit |
num_clbits | int | Number of classical bits in the circuit |
Returns:
T — A new engine-specific circuit object
create_parameter¶
def create_parameter(self, name: str) -> AnyCreate a symbolic parameter for the engine.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Parameter name (e.g., “gammas[0]”) |
Returns:
Any — Engine-specific parameter object
emit_barrier¶
def emit_barrier(self, circuit: T, qubits: list[int]) -> NoneEmit barrier on specified qubits.
emit_ch¶
def emit_ch(self, circuit: T, control: int, target: int) -> NoneEmit controlled-Hadamard gate.
emit_cp¶
def emit_cp(self, circuit: T, control: int, target: int, angle: float | Any) -> NoneEmit controlled-Phase gate.
emit_crx¶
def emit_crx(self, circuit: T, control: int, target: int, angle: float | Any) -> NoneEmit controlled-RX gate.
emit_cry¶
def emit_cry(self, circuit: T, control: int, target: int, angle: float | Any) -> NoneEmit controlled-RY gate.
emit_crz¶
def emit_crz(self, circuit: T, control: int, target: int, angle: float | Any) -> NoneEmit controlled-RZ gate.
emit_cx¶
def emit_cx(self, circuit: T, control: int, target: int) -> NoneEmit CNOT gate.
emit_cy¶
def emit_cy(self, circuit: T, control: int, target: int) -> NoneEmit controlled-Y gate.
emit_cz¶
def emit_cz(self, circuit: T, control: int, target: int) -> NoneEmit CZ gate.
emit_else_start¶
def emit_else_start(self, circuit: T, context: Any) -> NoneStart the else branch.
emit_for_loop_end¶
def emit_for_loop_end(self, circuit: T, context: Any) -> NoneEnd a native for loop context.
emit_for_loop_start¶
def emit_for_loop_start(self, circuit: T, indexset: range) -> AnyStart 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) -> NoneEmit Hadamard gate.
emit_if_end¶
def emit_if_end(self, circuit: T, context: Any) -> NoneEnd the if/else block.
emit_if_start¶
def emit_if_start(self, circuit: T, clbit: int, value: int = 1) -> AnyStart a native if context.
Returns context for the if/else block.
emit_measure¶
def emit_measure(self, circuit: T, qubit: int, clbit: int) -> NoneEmit measurement operation.
emit_p¶
def emit_p(self, circuit: T, qubit: int, angle: float | Any) -> NoneEmit Phase gate (P(θ) = diag(1, e^(iθ))).
emit_reset¶
def emit_reset(self, circuit: T, qubit: int) -> NoneEmit a reset-to-zero operation.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | T | Engine circuit to emit into. |
qubit | int | Physical qubit index to reset. |
Raises:
NotImplementedError— If the engine cannot represent reset.
emit_rx¶
def emit_rx(self, circuit: T, qubit: int, angle: float | Any) -> NoneEmit RX rotation gate.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | T | The circuit to emit to |
qubit | int | Target qubit index |
angle | float | Any | Rotation angle (float or engine parameter) |
emit_ry¶
def emit_ry(self, circuit: T, qubit: int, angle: float | Any) -> NoneEmit RY rotation gate.
emit_rz¶
def emit_rz(self, circuit: T, qubit: int, angle: float | Any) -> NoneEmit RZ rotation gate.
emit_rzz¶
def emit_rzz(self, circuit: T, qubit1: int, qubit2: int, angle: float | Any) -> NoneEmit RZZ gate (exp(-i * θ/2 * Z⊗Z)).
emit_s¶
def emit_s(self, circuit: T, qubit: int) -> NoneEmit S gate (√Z).
emit_sdg¶
def emit_sdg(self, circuit: T, qubit: int) -> NoneEmit S-dagger gate (inverse of S).
emit_swap¶
def emit_swap(self, circuit: T, qubit1: int, qubit2: int) -> NoneEmit SWAP gate.
emit_t¶
def emit_t(self, circuit: T, qubit: int) -> NoneEmit T gate (√S).
emit_tdg¶
def emit_tdg(self, circuit: T, qubit: int) -> NoneEmit T-dagger gate (inverse of T).
emit_toffoli¶
def emit_toffoli(self, circuit: T, control1: int, control2: int, target: int) -> NoneEmit Toffoli (CCX) gate.
emit_while_end¶
def emit_while_end(self, circuit: T, context: Any) -> NoneEnd the while loop context.
emit_while_start¶
def emit_while_start(self, circuit: T, clbit: int, value: int = 1) -> AnyStart a native while loop context.
emit_x¶
def emit_x(self, circuit: T, qubit: int) -> NoneEmit Pauli-X gate.
emit_y¶
def emit_y(self, circuit: T, qubit: int) -> NoneEmit Pauli-Y gate.
emit_z¶
def emit_z(self, circuit: T, qubit: int) -> NoneEmit Pauli-Z gate.
gate_controlled¶
def gate_controlled(self, gate: Any, num_controls: int) -> AnyCreate controlled version of a gate.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | Any | The gate to control |
num_controls | int | Number of control qubits |
Returns:
Any — New controlled gate
gate_inverse¶
def gate_inverse(self, gate: Any) -> AnyCreate an engine-native inverse gate when supported.
Parameters:
| Name | Type | Description |
|---|---|---|
gate | Any | Engine-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) -> AnyCreate gate raised to a power (U^n).
Parameters:
| Name | Type | Description |
|---|---|---|
gate | Any | The gate to raise to a power |
power | int | The power to raise to |
Returns:
Any — New gate representing gate^power
supports_for_loop¶
def supports_for_loop(self) -> boolCheck if engine supports native for loops.
supports_gate_inverse¶
def supports_gate_inverse(self) -> boolReturn 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) -> boolCheck if engine supports native if/else.
supports_reusable_gates¶
def supports_reusable_gates(self) -> boolReturn 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) -> boolCheck if engine supports native while loops.
GateOperation [source]¶
class GateOperation(Operation)Quantum gate operation.
For rotation gates (RX, RY, RZ, P, CP, RZZ), the angle parameter is
stored as the last element of operands. Use the theta
property for typed read access and the rotation / fixed factory
class-methods for type-safe construction.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
gate_type: GateOperationType | None = None,
) -> NoneAttributes¶
gate_type: GateOperationType | Noneoperation_kind: OperationKindqubit_operands: list[Value] Qubit operands (excluding the theta parameter if present).signature: Signaturetheta: Value | None Angle parameter for rotation gates, orNonefor fixed gates.
Methods¶
fixed¶
@classmethod
def fixed(
cls,
gate_type: GateOperationType,
qubits: list[Value],
results: list[Value],
) -> 'GateOperation'Create a fixed gate (H, X, CX, SWAP, …) with no angle parameter.
rotation¶
@classmethod
def rotation(
cls,
gate_type: GateOperationType,
qubits: list[Value],
theta: Value,
results: list[Value],
) -> 'GateOperation'Create a rotation gate (RX, RY, RZ, P, CP, RZZ) with an angle.
GateOperationType [source]¶
class GateOperationType(enum.Enum)Attributes¶
CPCXCZHPRXRYRZRZZSSDGSWAPTTDGTOFFOLIXYZ
GlobalPhaseOperation [source]¶
class GlobalPhaseOperation(Operation)Multiply the complete quantum state by exp(i * phase).
Global phase has no target qubit and does not create a new quantum value. Keeping the phase as the operation’s sole ordinary operand lets generic IR passes substitute, serialize, and analyze it without a special value-field protocol. A surrounding controlled-unitary lowering turns the operation into an observable phase gate on the accumulated controls.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[Value] | Exactly one scalar FloatType phase angle in radians. |
results | list[Value] | Must be empty because global phase changes no qubit identity. |
Raises:
ValueError— If the operand/result layout is invalid or the phase is not a scalarFloatTypevalue.
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKind Classify global phase as a quantum operation.phase: Value Return the scalar phase-angle operand.signature: Signature Return the zero-qubit operation signature.
HasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
InverseBlockOperation [source]¶
class InverseBlockOperation(Operation)Represent an inverse qkernel/block as a first-class IR operation.
The operation stores both the original forward block and a Qamomile-built
inverse implementation block. Emitters may use source_block with a
engine-native inverse/adjoint primitive, then fall back to
implementation_block when native inversion is unavailable.
Operands are ordered as scalar control qubits, target quantum operands,
then classical/object parameters. Results mirror the quantum operand
layout: control results first, then one target result per target operand.
Vector target operands therefore count as one operand/result while
contributing their scalar width to num_target_qubits.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_control_qubits: int = 0,
num_target_qubits: int = 0,
custom_name: str = '',
source_block: Block | None = None,
implementation_block: Block | None = None,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_qubits: list[‘Value’] Return control quantum operands.control_value: int | Nonecustom_name: strimplementation_block: Block | Nonename: str Return a human-readable inverse operation name.num_control_qubits: intnum_target_qubits: intoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return classical/object parameter operands.signature: Signature Return the operation signature.source_block: Block | Nonetarget_qubits: list[‘Value’] Return target quantum operands.
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[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. |
definition | CallableDef | None | Optional 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,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueor an Oracle control-partition field has an invalid Python type.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width, or if Oracle invocation and definition control metadata disagree.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of relevant callable implementations.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return a conservative union of measurement-derived results.name: str Return the display name for this invocation.num_added_control_qubits: int Return controls introduced by a frontend control transform.num_body_external_control_qubits: int Return control operands generic lowering adds outside a base body.num_control_qubits: int Return the number of leading control-qubit operands.num_declared_control_qubits: int Return controls included in an opaque Oracle’s base definition.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
effective_body¶
def effective_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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 | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None, which only selects engine-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
require_body | bool | Whether 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name used for implementation selection. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
select_body¶
def select_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> CallableBodySelectionSelect 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
MeasureOperation [source]¶
class MeasureOperation(Operation)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
MeasureQFixedOperation [source]¶
class MeasureQFixedOperation(Operation)Measure a quantum fixed-point number.
This operation measures all qubits in a QFixed register and produces a Float result. During transpilation, this is lowered to individual MeasureOperations plus a DecodeQFixedOperation.
operands: [QFixed value (contains qubit_values in params)] results: [Float value]
Encoding:
For QPE phase (int_bits=0):
Qubits are stored least-significant first. For n qubits,
bit i has weight 2**(-n + i).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_bits: int = 0,
int_bits: int = 0,
) -> NoneAttributes¶
int_bits: intnum_bits: intoperation_kind: OperationKindsignature: Signature
MeasureQIntOperation [source]¶
class MeasureQIntOperation(Operation)Measure an unsigned quantum integer as one abstract hybrid operation.
The carrier sequence is least-significant-bit first: carrier i has
integer weight 2**i. Planning lowers this operation to one vector
measurement followed by a host-side DecodeQIntOperation.
The carrier width is not stored on the operation: it is derived from the
register operand’s type and carrier metadata through num_bits.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[Value] | Single QUIntType register operand. |
results | list[Value] | Single decoded UIntType result. |
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
num_bits: int | None Return the carrier count derived from the register operand.operation_kind: OperationKind Classify QInt measurement as a quantum-to-classical bridge.signature: Signature Return the packed-register measurement signature.
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()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
NotOp [source]¶
class NotOp(Operation)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
input: Valueoperation_kind: OperationKindoutput: Valuesignature: Signature
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¶
CLASSICALCONTROLHYBRIDQUANTUM
ParameterContainerKind [source]¶
class ParameterContainerKind(enum.StrEnum)Classify the public container that owns one engine scalar slot.
Attributes¶
ARRAYDICTSCALAR
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()) -> NoneAttributes¶
evolved_qubits: Value The evolved quantum register result.gamma: Value The evolution time parameter.observable: Value The Observable parameter operand.operation_kind: OperationKind PauliEvolveOp is QUANTUM - transforms quantum state.qubits: Value The quantum register operand.signature: Signature
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',
) -> NoneAttributes¶
axis: stroperation_kind: OperationKindsignature: Signature
QInitOperation [source]¶
class QInitOperation(Operation)Initialize the qubit
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
ResetOperation [source]¶
class ResetOperation(Operation)Reset a qubit to the |0> state and return the fresh handle.
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
ReturnQuantumArrayElementOperation [source]¶
class ReturnQuantumArrayElementOperation(Operation)Validate a branch-selected quantum element’s array return at emit time.
Most quantum element assignments are verified structurally by the frontend and emit no IR. A compile-time conditional can instead select different element indices on its branches; only the unrolled emit context knows which source index survived. This operation carries both the requested target indices and the conditional source indices so emission can prove they resolve to the same physical slot before treating the assignment as a borrow return.
Operand convention:
[array, returned_qubit, *target_indices, *source_indices]. The
target and source halves have equal nonzero arity, inferred from the
operand count. The operation has no results and emits no engine gate.
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
array: ArrayValue Return the quantum array receiving the borrowed element.index_arity: int Return the number of target (and source) index operands.operation_kind: OperationKind Classify the return validator as a quantum operation.returned_value: Value Return the quantum value being returned.signature: Signature Return the deferred validator’s operand-only signature.source_indices: tuple[Value, ...] Return the branch-merged borrow-source indices.target_indices: tuple[Value, ...] Return the user-written assignment indices.
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:
Binary kinds (EQ/NEQ/LT/LE/GT/GE/AND/OR/ADD/SUB/MUL/DIV/FLOORDIV/MOD/POW):
operands = [lhs, rhs].Unary kind (NOT):
operands = [val].Ternary kind (SELECT):
operands = [condition, true_value, false_value]— the runtime form of a branch merge (result = true_value if condition else false_value).Result:
results = [output_value].
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,
) -> NoneAttributes¶
kind: RuntimeOpKind | Noneoperation_kind: OperationKindsignature: Signature
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(),
) -> NoneAttributes¶
case_blocks: list[Block]case_callable_attrs: list[dict[str, Any]]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
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]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed replacement values. |
Returns:
Operation — Rebuilt SELECT operation with matching values replaced.
StandardEmitPass [source]¶
class StandardEmitPass(EmitPass[T], Generic[T])Standard emit pass implementation using GateEmitter protocol.
This class provides orchestration for semantic IR traversal while
delegating circuit instruction construction to a GateEmitter. The
concrete compiler use is CircuitLoweringPass; SDK targets materialize
its immutable result instead of subclassing this class.
Parameters:
| Name | Type | Description |
|---|---|---|
gate_emitter | GateEmitter[T] | Instruction builder used during the semantic traversal. |
bindings | dict[str, Any] | None | Compile-time parameter bindings. |
parameters | list[str] | None | Parameter names preserved at runtime. |
composite_emitters | list[CompositeGateEmitter[T]] | None | Optional callable-preservation or lowering hooks. |
engine_name | str | None | Diagnostic 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¶
engine_name
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:
Compile time:
ConstantFoldingPassfolds the store when the source array contents, the index, and the stored value are all compile-time resolvable, attaching the updatedconst_arraymetadata to the result value.Runtime: otherwise the store executes host-side in a classical segment via
ClassicalExecutor(e.g. for measurement-derivedVector[Bit]contents). It must never reach a quantum segment; engine emit rejects it explicitly.
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 bitsConstructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
array: ArrayValue ArrayValue: The array version the store reads from.index_values: tuple[Value, ...] tuple[Value, ...]: The element indices being written.operation_kind: OperationKindsignature: Signature Return the operation’s dynamic array/qubit/index signature.stored_value: Value Value: The scalar being written into the array.
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of 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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]max_iterations: int | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the while body and its complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt while operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, rebind-record, and region-arg values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
qamomile.circuit.transpiler.passes.strip_slice_ops¶
Strip SliceArrayOperation / ReleaseSliceViewOperation after the linearity check.
Both ops are purely declarative — the resulting sliced ArrayValue
carries all the emit-time metadata on its own (slice_of /
slice_start / slice_step), and the release marker only exists
so SliceBorrowCheckPass can observe explicit slice-assignment
borrow-returns in program order. ConstantFoldingPass keeps these
ops around when strip_slice_ops=False so the downstream linearity
check can see them. Once the linearity check has run, both ops are
unneeded; segmentation and emission expect a pure quantum-op stream
without classical slice declarations in the middle. This pass removes
them and leaves the block otherwise unchanged.
Overview¶
| Class | Description |
|---|---|
Block | Unified block representation for all pipeline stages. |
ForItemsOperation | Represents iteration over dict/iterable items. |
ForOperation | Represents a for loop operation. |
OperationTransformer | Base class for transforming operations with control flow handling. |
Pass | Base class for all compiler passes. |
StripSliceArrayOpsPass | Remove SliceArrayOperation / ReleaseSliceViewOperation nodes. |
Classes¶
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
ForItemsOperation [source]¶
class ForItemsOperation(HasNestedOps, Operation)Represents iteration over dict/iterable items.
Example:
for (i, j), Jij in qmc.items(ising):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]key_is_vector: boolkey_var_values: tuple[Value, ...] | Nonekey_vars: list[str]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]operation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signaturevalue_var: strvalue_var_value: Value | None
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the items-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt items-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationOperationTransformer [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 | NoneTransform 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¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute the pass transformation.
StripSliceArrayOpsPass [source]¶
class StripSliceArrayOpsPass(Pass[Block, Block])Remove SliceArrayOperation / ReleaseSliceViewOperation nodes.
Both ops are only meaningful to SliceBorrowCheckPass as
view-declaration / release markers; downstream passes (analyze,
plan, emit) neither need nor expect them. Dropping them here
keeps the segmentation quantum-op-only.
Attributes¶
name: str Return the pass name.
Methods¶
run¶
def run(self, input: Block) -> BlockDrop slice marker ops from input.
Walks the operation tree (including nested control flow) and
returns a structurally identical block with every
SliceArrayOperation and ReleaseSliceViewOperation node
removed. The sliced ArrayValue results remain reachable
through later operands’ parent_array chains, so emit-time
resolution is unaffected.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Block that has completed SliceBorrowCheckPass. |
Returns:
Block — A new block with all slice marker ops removed.
qamomile.circuit.transpiler.passes.substitution¶
Substitution pass for replacing callable bodies and strategies.
This pass allows replacing:
Inline callable bodies (QKernel subroutines) with alternative implementations
InvokeOperation strategies with specified decomposition strategies
Example:
# Replace a custom oracle with an optimized version
config = SubstitutionConfig(
rules=[
SubstitutionRule(source_name="my_oracle", target=optimized_oracle),
SubstitutionRule(source_name="qft", strategy="approximate_k2"),
]
)
pass = SubstitutionPass(config)
new_block = pass.run(block)Overview¶
| Function | Description |
|---|---|
check_signature_compatibility | Check signature compatibility between two Blocks. |
create_substitution_pass | Convenience factory for creating a SubstitutionPass. |
| Class | Description |
|---|---|
Block | Unified block representation for all pipeline stages. |
BlockKind | Classification of block structure for pipeline stages. |
CallableDef | Describe a compiler-facing callable definition. |
CallableRef | Identify a callable independently of its Python object. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
Pass | Base class for all compiler passes. |
QKernel | Decorator class for Qamomile quantum kernels. |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
SignatureCompatibilityError | Error raised when signatures are incompatible during substitution. |
SubstitutionConfig | Configuration for the substitution pass. |
SubstitutionPass | Pass that substitutes call operations and callable strategies. |
SubstitutionRule | A single substitution rule. |
ValidationError | Error during validation (e.g., non-classical I/O). |
Functions¶
check_signature_compatibility [source]¶
def check_signature_compatibility(source: Block, target: Block, strict: bool = True) -> tuple[bool, str | None]Check signature compatibility between two Blocks.
Parameters:
| Name | Type | Description |
|---|---|---|
source | Block | The source Block being replaced |
target | Block | The target Block to replace with |
strict | bool | If True, require exact type matches |
Returns:
bool — Tuple of (is_compatible, error_message).
str | None — If compatible, error_message is None.
create_substitution_pass [source]¶
def create_substitution_pass(
block_replacements: dict[str, 'Block | QKernel'] | None = None,
*,
strategy_overrides: dict[str, str] | None = None,
validate_signatures: bool = True,
) -> SubstitutionPassConvenience factory for creating a SubstitutionPass.
Parameters:
| Name | Type | Description |
|---|---|---|
block_replacements | dict[str, 'Block | QKernel'] | None | Map of block name to replacement |
strategy_overrides | dict[str, str] | None | Map of gate name to strategy name |
validate_signatures | bool | If True, validate signature compatibility when replacing blocks. Default is True. |
Returns:
SubstitutionPass — Configured SubstitutionPass
Example:
pass = create_substitution_pass(
block_replacements={"my_oracle": optimized_oracle},
strategy_overrides={"qft": "approximate_k2", "iqft": "approximate_k2"},
)Classes¶
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
CallableDef [source]¶
class CallableDefDescribe a compiler-facing callable definition.
Parameters:
| Name | Type | Description |
|---|---|---|
ref | CallableRef | Stable callable identity. |
signature | Signature | None | Optional callable signature. |
body | Block | None | Standard IR body, or None for opaque calls. |
body_ref | CallableBodyRef | None | Reference to a standard body that is intentionally deferred. Defaults to None. |
implementations | list[CallableImplementation] | Alternative native or strategy-specific implementations. |
opaque_cost | Any | None | Explicit cost contract for a bodyless callable. Body-backed callables must leave this as None. |
default_policy | CallPolicy | Default call lowering policy. |
attrs | dict[str, Any] | Serializer-friendly definition metadata. |
Constructor¶
def __init__(
self,
ref: CallableRef,
signature: Signature | None = None,
body: Block | None = None,
body_ref: CallableBodyRef | None = None,
implementations: list[CallableImplementation] = list(),
opaque_cost: Any | None = None,
default_policy: CallPolicy = CallPolicy.INLINE,
attrs: dict[str, Any] = dict(),
) -> NoneAttributes¶
attrs: dict[str, Any]body: Block | Nonebody_ref: CallableBodyRef | Nonedefault_policy: CallPolicyimplementations: list[CallableImplementation]opaque_cost: Any | Noneref: CallableRefsignature: Signature | None
Methods¶
effects_for¶
def effects_for(self, transform: CallTransform = CallTransform.DIRECT) -> 'KernelEffect'Return cached semantic effects for one call transform.
Parameters:
| Name | Type | Description |
|---|---|---|
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
Returns:
'KernelEffect' — Union of relevant implementation-body effects.
implementation_for¶
def implementation_for(
self,
*,
transform: CallTransform = CallTransform.DIRECT,
engine: str | None = None,
strategy: str | None = None,
require_body: bool = False,
) -> CallableImplementation | NoneReturn the best matching implementation candidate.
Parameters:
| Name | Type | Description |
|---|---|---|
transform | CallTransform | Requested call transform. |
engine | str | None | Requested engine name. |
strategy | str | None | Requested strategy name. |
require_body | bool | Whether candidates without an IR body should be excluded before ranking. Defaults to False. |
Returns:
CallableImplementation | None — CallableImplementation | None: Matching implementation, if any.
measurement_result_indices_for¶
def measurement_result_indices_for(self, transform: CallTransform = CallTransform.DIRECT) -> frozenset[int]Return measured result positions for one call transform.
Parameters:
| Name | Type | Description |
|---|---|---|
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
Returns:
frozenset[int] — frozenset[int]: Result indices carrying measurement provenance.
CallableRef [source]¶
class CallableRefIdentify a callable independently of its Python object.
Parameters:
| Name | Type | Description |
|---|---|---|
namespace | str | Stable namespace such as "qamomile.stdlib" or "user". |
name | str | Stable callable name within the namespace. |
version | str | Schema or behavior version for the callable. |
Constructor¶
def __init__(self, namespace: str, name: str, version: str = '1') -> NoneAttributes¶
name: strnamespace: strversion: str
HasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[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. |
definition | CallableDef | None | Optional 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,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueor an Oracle control-partition field has an invalid Python type.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width, or if Oracle invocation and definition control metadata disagree.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of relevant callable implementations.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return a conservative union of measurement-derived results.name: str Return the display name for this invocation.num_added_control_qubits: int Return controls introduced by a frontend control transform.num_body_external_control_qubits: int Return control operands generic lowering adds outside a base body.num_control_qubits: int Return the number of leading control-qubit operands.num_declared_control_qubits: int Return controls included in an opaque Oracle’s base definition.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
effective_body¶
def effective_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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 | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None, which only selects engine-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
require_body | bool | Whether 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name used for implementation selection. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
select_body¶
def select_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> CallableBodySelectionSelect 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
Pass [source]¶
class Pass(ABC, Generic[InputT, OutputT])Base class for all compiler passes.
Attributes¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute the pass transformation.
QKernel [source]¶
class QKernel(QKernelBuildMixin, QKernelVisualizationMixin, Generic[P, R])Decorator class for Qamomile quantum kernels.
Constructor¶
def __init__(self, func: Callable[P, R]) -> NoneAttributes¶
block: Block Compile the function to a hierarchical Block if not already compiled.effects: KernelEffect Return cached semantic effects of this qkernel.funcinput_types: dict[str, Any] Return resolved and frozen frontend input annotations.nameoutput_types: list[Any] Return the resolved frontend annotation for every output slot.raw_funcreturn_type: Any Return the resolved and frozen complete return annotation.signature
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(),
) -> NoneAttributes¶
case_blocks: list[Block]case_callable_attrs: list[dict[str, Any]]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
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]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed replacement values. |
Returns:
Operation — Rebuilt SELECT operation with matching values replaced.
SignatureCompatibilityError [source]¶
class SignatureCompatibilityError(Exception)Error raised when signatures are incompatible during substitution.
SubstitutionConfig [source]¶
class SubstitutionConfigConfiguration for the substitution pass.
Constructor¶
def __init__(self, rules: list[SubstitutionRule] = list()) -> NoneAttributes¶
rules: list[SubstitutionRule]
Methods¶
get_rule_for_name¶
def get_rule_for_name(self, name: str) -> SubstitutionRule | NoneFind a rule matching the given name.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Name to look up |
Returns:
SubstitutionRule | None — Matching SubstitutionRule or None
SubstitutionPass [source]¶
class SubstitutionPass(Pass[Block, Block])Pass that substitutes call operations and callable strategies.
This pass traverses the block and applies substitution rules:
For inline InvokeOperation: replaces the callable body with the target
For boxed InvokeOperation: sets the strategy field
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) -> NoneInitialize the pass with configuration.
Parameters:
| Name | Type | Description |
|---|---|---|
config | SubstitutionConfig | Substitution configuration with rules |
Attributes¶
name: str Return pass name.
Methods¶
run¶
def run(self, input: Block) -> BlockApply substitutions to the block.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Block to transform |
Returns:
Block — Block with substitutions applied
SubstitutionRule [source]¶
class SubstitutionRuleA single substitution rule.
Constructor¶
def __init__(
self,
source_name: str,
target: 'Block | QKernel | None' = None,
strategy: str | None = None,
validate_signature: bool = True,
) -> NoneAttributes¶
source_name: strstrategy: str | Nonetarget: ‘Block | QKernel | None’validate_signature: bool
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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable validation failure. |
value_name | str | None | Related IR value name. Defaults to None. |
Attributes¶
value_name
qamomile.circuit.transpiler.passes.symbolic_shape_validation¶
Reject unresolved values that determine compile-time circuit structure.
Qamomile circuits are fixed-structure at compile time: loop bounds determine how many gates are emitted, and SELECT index widths determine reusable-call arity, while controlled-unitary widths, powers, and selected control indices determine coherent-control structure. These values must be resolvable before emit. This pass catches two failure families early — right before segmentation — with an actionable diagnostic, instead of letting them surface downstream as inconsistent errors:
Unresolved parameter shape dims (e.g.
gamma_dim0): a loop bound reads a parameter array’s length, but no concrete binding was provided soParameterShapeResolutionPasscould not fold it.Runtime-parameter-dependent bounds (e.g.
qmc.range(n)withparameters=["n"]): the bound depends — directly or through a chain of classical arithmetic — on a kernel argument left as a runtime parameter. Runtime parameters are bound per execution, after the circuit structure is frozen, so such a loop can never be unrolled. Without this check the failure surfaces inconsistently downstream: as an emit-timeValueError(“Cannot unroll loop”) when the bound is the parameter itself, or as a misleadingMultipleQuantumSegmentsErrorblaming measurement-dependent control flow when a bound expression strands its classical op between quantum ops at segmentation.
The same early diagnostic applies to symbolic controlled-unitary structure
(num_controls, power, and control_indices) and to loops stored in
operation-owned SELECT/control blocks.
Bounds that depend only on enclosing loop variables (e.g. a nested
qmc.range(i + 1) inside qmc.range(p)) are resolvable during
emit-time unrolling and are left alone, as are measurement-derived
values (handled by the runtime control-flow machinery).
The library QAOA pattern (p bound to an int, for layer in qmc.range(p), gammas kept as runtime parameters for gate angles)
is unaffected — compile-time-bound counters are folded to constants by
partial_eval before this pass runs.
Overview¶
| Function | Description |
|---|---|
pair_block_operands | Pair all block inputs with category-grouped call-site operands. |
reachable_nested_regions | Return nested regions that may execute for one control-flow operation. |
same_exact_typed_constant | Return whether two scalar Values carry the same exact typed constant. |
static_loop_trip_count | Resolve the exact trip count of a compile-time loop. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
Block | Unified block representation for all pipeline stages. |
BlockKind | Classification of block structure for pipeline stages. |
ControlFlowVisitor | Base class for visiting operations with control flow handling. |
ForItemsOperation | Represents iteration over dict/iterable items. |
ForOperation | Represents a for loop operation. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
IfOperation | Represents an if-else conditional operation. |
OperationKind | Classification of operations for classical/quantum separation. |
Pass | Base class for all compiler passes. |
QamomileCompileError | Base class for all Qamomile compilation errors. |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
SymbolicShapeValidationPass | Reject unresolvable values that determine emitted circuit structure. |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
WhileOperation | Represents a while loop operation. |
Functions¶
pair_block_operands [source]¶
def pair_block_operands(
block: Block,
operands: Sequence[ValueBase],
) -> list[tuple[ValueBase, ValueBase]]Pair all block inputs with category-grouped call-site operands.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Operation-owned block whose inputs are being bound. |
operands | Sequence[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:
| Name | Type | Description |
|---|---|---|
operation | HasNestedOps | Structured-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) -> boolReturn 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:
| Name | Type | Description |
|---|---|---|
left | Value | First scalar value to compare. |
right | Value | Second scalar value to compare. |
Returns:
bool — True only for constants of the same IR type and Python type
with equal value representations.
static_loop_trip_count [source]¶
def static_loop_trip_count(operation: ForOperation | ForItemsOperation) -> int | NoneResolve the exact trip count of a compile-time loop.
Parameters:
| Name | Type | Description |
|---|---|---|
operation | ForOperation | ForItemsOperation | Counted or items loop whose cardinality should be inspected. |
Returns:
int | None — int | None: Exact non-negative trip count, or None when the loop
cardinality is unresolved.
Classes¶
ArrayValue [source]¶
class ArrayValue(Value[T])An array of typed IR values.
When slice_of is set, this array is a strided view over another
array. Element accesses on a sliced ArrayValue resolve to
physical slots on the root parent via the affine map
parent_index = slice_start + slice_step * view_local_index,
applied recursively along slice_of chains. The emit-time
resolver walks this chain to produce the final qubit index; passes
that substitute or clone values must treat slice_of /
slice_start / slice_step as Value references that need to
track through the same mapping as parent_array.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
shape: tuple[Value, ...] = tuple(),
slice_of: 'ArrayValue | None' = None,
slice_start: 'Value | None' = None,
slice_step: 'Value | None' = None,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
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 += 1Methods¶
visit_operation¶
def visit_operation(self, op: Operation) -> NoneProcess a single operation. Override in subclasses.
visit_operations¶
def visit_operations(self, operations: list[Operation]) -> NoneVisit all operations including nested control flow.
ForItemsOperation [source]¶
class ForItemsOperation(HasNestedOps, Operation)Represents iteration over dict/iterable items.
Example:
for (i, j), Jij in qmc.items(ising):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]key_is_vector: boolkey_var_values: tuple[Value, ...] | Nonekey_vars: list[str]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]operation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signaturevalue_var: strvalue_var_value: Value | None
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the items-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt items-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationHasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
OperationKind [source]¶
class OperationKind(enum.Enum)Classification of operations for classical/quantum separation.
This enum is used to categorize operations during compilation to determine which parts run on classical hardware vs quantum hardware.
Values:
QUANTUM: Pure quantum operations (gates, qubit allocation) CLASSICAL: Pure classical operations (arithmetic, comparisons) HYBRID: Operations that bridge classical and quantum (measurement, encode/decode) CONTROL: Control flow structures (for, while, if)
Attributes¶
CLASSICALCONTROLHYBRIDQUANTUM
Pass [source]¶
class Pass(ABC, Generic[InputT, OutputT])Base class for all compiler passes.
Attributes¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute the pass transformation.
QamomileCompileError [source]¶
class QamomileCompileError(Exception)Base class for all Qamomile compilation errors.
SelectOperation [source]¶
class SelectOperation(Operation)Quantum multiplexer: apply case_blocks[i] when the index reads i.
Concrete operand layout:
[idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...].
Symbolic-width operand layout:
[idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...].
Results mirror the quantum operand grouping.
A concrete index register is normalized to one scalar Qubit operand
per physical index qubit. A symbolic-width register instead retains each
leading caller argument as one scalar or array operand until its bound
shape is known. Whole-Vector[Qubit] / scalar targets follow and keep
their shapes, and classical parameters shared across every case come last.
Index bit order is LSB-first: idx_0 is the least-significant
bit, matching Qamomile’s qubit-zero convention. Case i is selected
when index qubit j reads bit j of i. len(case_blocks)
need not be a power of two; index values >= len(case_blocks) apply
no operation (identity).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_index_qubits: int | Value = 0,
case_blocks: list[Block] = list(),
num_index_args: int = 0,
case_callable_attrs: list[dict[str, Any]] = list(),
) -> NoneAttributes¶
case_blocks: list[Block]case_callable_attrs: list[dict[str, Any]]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
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]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed replacement values. |
Returns:
Operation — Rebuilt SELECT operation with matching values replaced.
SymbolicShapeValidationPass [source]¶
class SymbolicShapeValidationPass(Pass[Block, Block])Reject unresolvable values that determine emitted circuit structure.
Runs two checks on every ForOperation bound, symbolic SELECT index
width, and symbolic controlled-unitary structural field, walking nested
control flow and operation-owned SELECT/control blocks recursively:
Unresolved parameter array shape dims, recognized by the
{array}_dim{i}naming convention.Bounds whose dataflow traces back to a runtime parameter (an entry of
Block.parameters), directly or through classical arithmetic. Dependencies on enclosing loop variables are exempt — those resolve during emit-time unrolling.
Input: BlockKind.ANALYZED (runs after AnalyzePass).
Output: same block unchanged, or raises QamomileCompileError.
Attributes¶
name: str Return the pass name used in pipeline diagnostics.
Methods¶
run¶
def run(self, input: Block) -> BlockValidate compile-time structure throughout the analyzed block.
Checks loop bounds, SELECT widths, and controlled-unitary structural fields at top level, in ordinary control-flow bodies, and in operation-owned SELECT/control blocks.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | The block to validate. Must be BlockKind.ANALYZED; other kinds pass through unchanged (the pass is defensive and avoids false positives on partially-built IR). |
Returns:
Block — input, unchanged, when validation succeeds.
Raises:
QamomileCompileError— If any checked structural value is an unresolved parameter shape dim or depends on a runtime parameter.
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]max_iterations: int | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the while body and its complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt while operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, rebind-record, and region-arg values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
qamomile.circuit.transpiler.passes.validate_while¶
WhileOperation contract validation pass.
Validates that all WhileOperation conditions are measurement-backed
Bit values. A condition is measurement-backed if it originates from
qmc.measure() either directly or through merged branches where
every leaf is itself measurement-backed (e.g. if sel: bit = measure(q1) else: bit = measure(q2)).
All other while patterns (classical variables, constants, comparison
results, non-measurement branch leaves) are rejected with a clear
ValidationError before reaching engine-specific emit passes.
This pass runs after lower_compile_time_ifs and before analyze.
Overview¶
| Function | Description |
|---|---|
build_producer_map | Walk operations recursively, mapping result UUIDs to producer instances. |
is_measurement_backed | Recursively check whether a value traces back to measurement operations. |
resolve_root_array_index | Fold a view-local element index into the root array’s index space. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
BitType | Type representing a classical bit. |
Block | Unified block representation for all pipeline stages. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
IfOperation | Represents an if-else conditional operation. |
MeasureOperation | |
MeasureVectorOperation | Measure a vector of qubits. |
Pass | Base class for all compiler passes. |
ProjectOperation | Project a qubit in one Pauli basis and keep the projected state. |
RuntimeClassicalExpr | A classical expression known to require runtime evaluation. |
RuntimeOpKind | Unified kind for RuntimeClassicalExpr covering all classical |
StoreArrayElementOperation | Store a classical scalar into one element of a classical array. |
ValidateWhileContractPass | Validates that all WhileOperation conditions are measurement-backed. |
ValidationError | Error during validation (e.g., non-classical I/O). |
Value | A typed SSA value in the IR. |
WhileOperation | Represents a while loop operation. |
Functions¶
build_producer_map [source]¶
def build_producer_map(operations: list[Operation], producer_map: dict[str, Operation]) -> NoneWalk 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:
| Name | Type | Description |
|---|---|---|
operations | list[Operation] | Operations to walk, recursing into all HasNestedOps bodies. IfOperation merge outputs are on results, so they map to the IfOperation itself. |
producer_map | dict[str, Operation] | Mutable map from result UUID to the producing operation; updated in place. |
is_measurement_backed [source]¶
def is_measurement_backed(
value: Value,
producer_map: dict[str, Operation],
visiting: set[str] | None = None,
) -> boolRecursively check whether a value traces back to measurement operations.
Returns True if the value is produced by MeasureOperation /
MeasureVectorOperation directly, if it is an element access of a
measured Vector[Bit] (its parent_array — possibly through a
slice_of view chain — is measurement-backed), or if it is an
IfOperation merge output where every reachable leaf source is
itself measurement-backed.
Uses backtracking on visiting so that the same value can be
reached from multiple independent merge branches without false negatives.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | The IR value to trace. |
producer_map | dict[str, Operation] | Map from result UUID to the operation that produced it. |
visiting | set[str] | None | UUIDs on the current DFS path, used to break cycles. Defaults to None (fresh traversal). |
Returns:
bool — True if the value is measurement-backed.
resolve_root_array_index [source]¶
def resolve_root_array_index(array: 'ArrayValue', index: int) -> tuple['ArrayValue', int] | NoneFold a view-local element index into the root array’s index space.
Walks the slice_of chain root-ward, composing each strided view’s
affine map parent_index = start + step * local_index. This is the
array-level counterpart of :func:resolve_root_qubit_address (which
starts from an array-element Value); both must stay consistent with
the composite carrier keys "<root_uuid>_<root_index>" registered by
QInitOperation at emit time.
Parameters:
| Name | Type | Description |
|---|---|---|
array | ArrayValue | Array the index is local to. May be a root array (slice_of unset) or an arbitrarily nested strided view. |
index | int | Element index in array’s own index space. |
Returns:
tuple['ArrayValue', int] | None — tuple[ArrayValue, int] | None: (root_array, composed_index) when
every slice bound on the chain is compile-time constant and
satisfies the frontend contract (non-negative slice_start,
positive slice_step). None when any slice_start /
slice_step on the chain is missing, symbolic, or violates
that contract; callers must then defer resolution rather than
guess. Out-of-contract bounds would compose index onto a
wrong root slot, so they are refused here too (the frontend
rejects them at trace time; this guard covers programmatically
constructed IR).
Classes¶
ArrayValue [source]¶
class ArrayValue(Value[T])An array of typed IR values.
When slice_of is set, this array is a strided view over another
array. Element accesses on a sliced ArrayValue resolve to
physical slots on the root parent via the affine map
parent_index = slice_start + slice_step * view_local_index,
applied recursively along slice_of chains. The emit-time
resolver walks this chain to produce the final qubit index; passes
that substitute or clone values must treat slice_of /
slice_start / slice_step as Value references that need to
track through the same mapping as parent_array.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
shape: tuple[Value, ...] = tuple(),
slice_of: 'ArrayValue | None' = None,
slice_start: 'Value | None' = None,
slice_step: 'Value | None' = None,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]BitType [source]¶
class BitType(ClassicalTypeMixin, ValueType)Type representing a classical bit.
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
HasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend 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:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
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:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
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]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[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]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[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()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
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()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
Pass [source]¶
class Pass(ABC, Generic[InputT, OutputT])Base class for all compiler passes.
Attributes¶
name: str Human-readable name for this pass.
Methods¶
run¶
def run(self, input: InputT) -> OutputTExecute the pass transformation.
ProjectOperation [source]¶
class ProjectOperation(Operation)Project a qubit in one Pauli basis and keep the projected state.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
axis: str = 'z',
) -> NoneAttributes¶
axis: stroperation_kind: OperationKindsignature: Signature
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:
Binary kinds (EQ/NEQ/LT/LE/GT/GE/AND/OR/ADD/SUB/MUL/DIV/FLOORDIV/MOD/POW):
operands = [lhs, rhs].Unary kind (NOT):
operands = [val].Ternary kind (SELECT):
operands = [condition, true_value, false_value]— the runtime form of a branch merge (result = true_value if condition else false_value).Result:
results = [output_value].
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,
) -> NoneAttributes¶
kind: RuntimeOpKind | Noneoperation_kind: OperationKindsignature: Signature
RuntimeOpKind [source]¶
class RuntimeOpKind(enum.Enum)Unified kind for RuntimeClassicalExpr covering all classical
op families that can appear at runtime.
The split between this enum and the per-family BinOpKind /
CompOpKind / CondOpKind is intentional: compile-time-foldable
classical ops keep their original IR types so the existing fold
pipeline (constant_fold → compile_time_if_lowering → emit-time
evaluate_classical_predicate) is undisturbed. Only ops identified
as runtime-evaluation-only by ClassicalLoweringPass get rewritten
to RuntimeClassicalExpr with a member of this enum.
Attributes¶
ADDANDDIVEQFLOORDIVGEGTLELTMODMULNEQNOTORPOWSELECTSUB
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:
Compile time:
ConstantFoldingPassfolds the store when the source array contents, the index, and the stored value are all compile-time resolvable, attaching the updatedconst_arraymetadata to the result value.Runtime: otherwise the store executes host-side in a classical segment via
ClassicalExecutor(e.g. for measurement-derivedVector[Bit]contents). It must never reach a quantum segment; engine emit rejects it explicitly.
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 bitsConstructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
array: ArrayValue ArrayValue: The array version the store reads from.index_values: tuple[Value, ...] tuple[Value, ...]: The element indices being written.operation_kind: OperationKindsignature: Signature Return the operation’s dynamic array/qubit/index signature.stored_value: Value Value: The scalar being written into the array.
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:
A
ValuewithBitTypeMeasurement-backed: produced by
MeasureOperationdirectly, or anIfOperationmerge 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¶
name: str
Methods¶
run¶
def run(self, block: Block) -> BlockValidate 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:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable validation failure. |
value_name | str | None | Related IR value name. Defaults to None. |
Attributes¶
value_name
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of 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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]max_iterations: int | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the while body and its complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt while operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, rebind-record, and region-arg values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
qamomile.circuit.transpiler.passes.value_mapping¶
Compatibility exports for shared IR value-mapping utilities.
Overview¶
| Class | Description |
|---|---|
UUIDRemapper | Clones values and operations with fresh UUIDs and logical_ids. |
ValueSubstitutor | Substitute IR values in operations using a UUID-keyed mapping. |
Classes¶
UUIDRemapper [source]¶
class UUIDRemapperClones values and operations with fresh UUIDs and logical_ids.
Used during inlining to create unique identities for values when a block is called multiple times.
Constructor¶
def __init__(self)Initialize empty identity, value, and block remapping caches.
Attributes¶
logical_id_remap: dict[str, str] Get the mapping from old logical IDs to new logical IDs.uuid_remap: dict[str, str] Get the mapping from old UUIDs to new UUIDs.
Methods¶
clone_block¶
def clone_block(self, block: Block) -> BlockClone an executable block namespace with fresh value identities.
Callable definitions and inverse source blocks are semantic provenance shared with the original graph. Transform implementations, controlled bodies, and SELECT cases are executable children and are cloned recursively.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Block whose interface, operations, and executable owned blocks should be cloned. |
Returns:
Block — Structurally equivalent block whose values have fresh UUIDs
and logical IDs.
Raises:
ValueError— If the owned block graph is recursive.
clone_operation¶
def clone_operation(self, op: Operation) -> OperationClone an operation with fresh UUIDs for all values.
Cloning goes through the Operation.all_input_values() /
Operation.replace_values() protocol so every Value-typed
field — including subclass extras (ControlledUOperation.power,
ForOperation.loop_var_value, ForItemsOperation.key_var_values
etc.) — is cloned consistently with the body references that
point to it. Without this, a subclass field could keep an old
UUID while body operands referencing the same logical Value got
fresh UUIDs, breaking identity-by-UUID lookups at emit time.
Parameters:
| Name | Type | Description |
|---|---|---|
op | Operation | Operation to clone. |
Returns:
Operation — A clone of op with every owned Value (operands,
results, subclass-extra fields) and every nested-body Value
reassigned a fresh UUID / logical_id, and with
CastOperation.qubit_mapping carrier keys remapped.
clone_operations¶
def clone_operations(self, operations: list[Operation]) -> list[Operation]Clone a list of operations with fresh UUIDs.
Parameters:
| Name | Type | Description |
|---|---|---|
operations | list[Operation] | Operations to clone in order. |
Returns:
list[Operation] — list[Operation]: Cloned operations, each with fresh UUIDs, in the
same order as operations.
clone_value¶
def clone_value(self, value: ValueBase) -> ValueBaseClone any value type with a fresh UUID and logical_id.
Handles Value, ArrayValue, TupleValue, and DictValue through
the unified ValueBase protocol. Nested values (tuple elements, dict
entries, parent_array / element_indices / shape / slice
fields) and embedded metadata references are cloned consistently.
Results are cached by source UUID so a repeated clone returns the
same instance.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ValueBase | The value to clone. |
Returns:
ValueBase — The cloned value of the same concrete type, with a
fresh UUID / logical_id and its nested values and metadata
references remapped through this remapper.
ValueSubstitutor [source]¶
class ValueSubstitutorSubstitute IR values in operations using a UUID-keyed mapping.
Parameters:
| Name | Type | Description |
|---|---|---|
value_map | Mapping[str, ValueBase] | Mapping from original value UUIDs to replacement values. |
transitive | bool | Whether substitutions should chase chains such as A -> B -> C to the terminal value. Defaults to False. |
Constructor¶
def __init__(self, value_map: Mapping[str, ValueBase], transitive: bool = False)Initialize the substitutor.
Parameters:
| Name | Type | Description |
|---|---|---|
value_map | Mapping[str, ValueBase] | Mapping from original value UUIDs to replacement values. |
transitive | bool | Whether substitutions should chase chains to their terminal value. Defaults to False. |
Methods¶
substitute_operation¶
def substitute_operation(self, op: Operation) -> OperationSubstitute values in an operation.
Parameters:
| Name | Type | Description |
|---|---|---|
op | Operation | Operation whose operands, results, and subclass-specific value fields should be substituted. |
Returns:
Operation — Operation with all mapped value references replaced.
substitute_value¶
def substitute_value(self, value: ValueBase) -> ValueBaseSubstitute a single value.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ValueBase | Value to replace or rebuild. |
Returns:
ValueBase — Replacement value, rebuilt value with substituted
ValueBase — metadata, or the original value when nothing maps.
qamomile.circuit.transpiler.prepared¶
Program-level semantic input for target-specific compilation pipelines.
Overview¶
| Function | Description |
|---|---|
prepare_module | Collect a hierarchical block into an immutable program-level view. |
| Class | Description |
|---|---|
Block | Unified block representation for all pipeline stages. |
CallableDef | Describe a compiler-facing callable definition. |
CallableRef | Identify a callable independently of its Python object. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
PreparedModule | Hold a prepared entrypoint and its reachable callable definitions. |
ProgramABI | Runtime-visible ABI for a segmented program. |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
Functions¶
prepare_module [source]¶
def prepare_module(entrypoint: Block, bindings: Mapping[str, Any] | None = None) -> PreparedModuleCollect 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:
| Name | Type | Description |
|---|---|---|
entrypoint | Block | Hierarchical entrypoint after target-independent frontend preparation. |
bindings | Mapping[str, Any] | None | Compile-time values that cannot be embedded in scalar value metadata, such as Hamiltonians. Defaults to None. |
Returns:
PreparedModule — Entrypoint, reachable definitions, call graph, and
public ABI. :class:QamomileCompiler creates a deep target-owned
snapshot before invoking a target pipeline.
Classes¶
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
CallableDef [source]¶
class CallableDefDescribe a compiler-facing callable definition.
Parameters:
| Name | Type | Description |
|---|---|---|
ref | CallableRef | Stable callable identity. |
signature | Signature | None | Optional callable signature. |
body | Block | None | Standard IR body, or None for opaque calls. |
body_ref | CallableBodyRef | None | Reference to a standard body that is intentionally deferred. Defaults to None. |
implementations | list[CallableImplementation] | Alternative native or strategy-specific implementations. |
opaque_cost | Any | None | Explicit cost contract for a bodyless callable. Body-backed callables must leave this as None. |
default_policy | CallPolicy | Default call lowering policy. |
attrs | dict[str, Any] | Serializer-friendly definition metadata. |
Constructor¶
def __init__(
self,
ref: CallableRef,
signature: Signature | None = None,
body: Block | None = None,
body_ref: CallableBodyRef | None = None,
implementations: list[CallableImplementation] = list(),
opaque_cost: Any | None = None,
default_policy: CallPolicy = CallPolicy.INLINE,
attrs: dict[str, Any] = dict(),
) -> NoneAttributes¶
attrs: dict[str, Any]body: Block | Nonebody_ref: CallableBodyRef | Nonedefault_policy: CallPolicyimplementations: list[CallableImplementation]opaque_cost: Any | Noneref: CallableRefsignature: Signature | None
Methods¶
effects_for¶
def effects_for(self, transform: CallTransform = CallTransform.DIRECT) -> 'KernelEffect'Return cached semantic effects for one call transform.
Parameters:
| Name | Type | Description |
|---|---|---|
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
Returns:
'KernelEffect' — Union of relevant implementation-body effects.
implementation_for¶
def implementation_for(
self,
*,
transform: CallTransform = CallTransform.DIRECT,
engine: str | None = None,
strategy: str | None = None,
require_body: bool = False,
) -> CallableImplementation | NoneReturn the best matching implementation candidate.
Parameters:
| Name | Type | Description |
|---|---|---|
transform | CallTransform | Requested call transform. |
engine | str | None | Requested engine name. |
strategy | str | None | Requested strategy name. |
require_body | bool | Whether candidates without an IR body should be excluded before ranking. Defaults to False. |
Returns:
CallableImplementation | None — CallableImplementation | None: Matching implementation, if any.
measurement_result_indices_for¶
def measurement_result_indices_for(self, transform: CallTransform = CallTransform.DIRECT) -> frozenset[int]Return measured result positions for one call transform.
Parameters:
| Name | Type | Description |
|---|---|---|
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
Returns:
frozenset[int] — frozenset[int]: Result indices carrying measurement provenance.
CallableRef [source]¶
class CallableRefIdentify a callable independently of its Python object.
Parameters:
| Name | Type | Description |
|---|---|---|
namespace | str | Stable namespace such as "qamomile.stdlib" or "user". |
name | str | Stable callable name within the namespace. |
version | str | Schema or behavior version for the callable. |
Constructor¶
def __init__(self, namespace: str, name: str, version: str = '1') -> NoneAttributes¶
name: strnamespace: strversion: str
HasNestedOps [source]¶
class HasNestedOpsMixin 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]]) -> OperationReturn 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]) -> OperationReturn 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:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[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. |
definition | CallableDef | None | Optional 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,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueor an Oracle control-partition field has an invalid Python type.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width, or if Oracle invocation and definition control metadata disagree.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of relevant callable implementations.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return a conservative union of measurement-derived results.name: str Return the display name for this invocation.num_added_control_qubits: int Return controls introduced by a frontend control transform.num_body_external_control_qubits: int Return control operands generic lowering adds outside a base body.num_control_qubits: int Return the number of leading control-qubit operands.num_declared_control_qubits: int Return controls included in an opaque Oracle’s base definition.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
effective_body¶
def effective_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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 | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None, which only selects engine-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
require_body | bool | Whether 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name used for implementation selection. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
select_body¶
def select_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> CallableBodySelectionSelect 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
PreparedModule [source]¶
class PreparedModuleHold a prepared entrypoint and its reachable callable definitions.
Parameters:
| Name | Type | Description |
|---|---|---|
entrypoint_ref | CallableRef | Stable symbol assigned to the program entrypoint. |
entrypoint | Block | Hierarchical semantic block for the entrypoint. |
definitions | Mapping[CallableRef, CallableDef] | Reachable callable definitions keyed by their stable symbols. |
definition_variants | Mapping[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_graph | Mapping[CallableRef, frozenset[CallableRef]] | Directed caller-to-callee relation, including the entrypoint symbol. |
abi | ProgramABI | Classical public input and output contract. |
bindings | Mapping[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],
) -> NoneAttributes¶
abi: ProgramABIbindings: Mapping[str, Any]call_graph: Mapping[CallableRef, frozenset[CallableRef]]definition_variants: Mapping[CallableRef, tuple[CallableDef, ...]]definitions: Mapping[CallableRef, CallableDef]entrypoint: Blockentrypoint_ref: CallableRef
Methods¶
body¶
def body(self, ref: CallableRef) -> BlockReturn the semantic body associated with a program symbol.
Parameters:
| Name | Type | Description |
|---|---|---|
ref | CallableRef | Entrypoint or callable symbol to resolve. |
Returns:
Block — Hierarchical semantic body for ref.
Raises:
KeyError— Ifrefis neither the entrypoint nor a reachable body-backed callable definition.
owned_snapshot¶
def owned_snapshot(self) -> PreparedModuleCreate 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 ProgramABIRuntime-visible ABI for a segmented program.
Constructor¶
def __init__(
self,
public_inputs: dict[str, ValueLike] = dict(),
output_values: list[ValueLike] = list(),
) -> NoneAttributes¶
output_values: list[ValueLike]public_inputs: dict[str, ValueLike]
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(),
) -> NoneAttributes¶
case_blocks: list[Block]case_callable_attrs: list[dict[str, Any]]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
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]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed replacement values. |
Returns:
Operation — Rebuilt SELECT operation with matching values replaced.
qamomile.circuit.transpiler.program_graph¶
Public compiler support for direct program-graph targets.
Overview¶
| Function | Description |
|---|---|
inline_callables | Expand inline-policy callables once with the compiler’s default policy. |
reject_control_flow_quantum_discard | Reject control-flow-internal quantum rebinds that discard state. |
validate_program_graph_semantics | Validate shared semantics for a direct program-graph target. |
| Class | Description |
|---|---|
Block | Unified block representation for all pipeline stages. |
CallPolicy | Describe the default lowering policy for a callable call. |
InlinePass | Inline qkernel callables to create an affine block. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
PreparedModule | Hold a prepared entrypoint and its reachable callable definitions. |
ValidateWhileContractPass | Validates that all WhileOperation conditions are measurement-backed. |
Functions¶
inline_callables [source]¶
def inline_callables(
block: Block,
*,
body_selector: Callable[[InvokeOperation], Block | None] | None = None,
) -> BlockExpand 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:
| Name | Type | Description |
|---|---|---|
block | Block | Hierarchical or traced semantic block to rewrite. |
body_selector | Callable[[InvokeOperation], Block | None] | None | Optional 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:
QubitConsumedError— If an invocation binds the same quantum resource to multiple formal operands.
reject_control_flow_quantum_discard [source]¶
def reject_control_flow_quantum_discard(operations: list[Operation], bindings: dict[str, Any] | None = None) -> NoneReject 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:
consuming the original inside the branch before rebinding (
if cond: qmc.measure(q); q = qmc.qubit(...)). Scalar consumption is judged at the wire’s final in-branch version (:func:_wire_terminally_consumed), so gating the original and then dropping the gated state (if cond: q = qmc.x(q); q = qmc.qubit("fresh")) is a discard, not a consumption; whole-register rebinds keep the coarser any-touch granularity, where element or view reads count;ordinary quantum rebinds through gates (
q = qmc.h(q)) — the pre-branch value is carried out through the merge;rebinds whose pre-branch value is still owned outside the if (a value consumed before the if, or an alias referenced after it);
handle exchanges where every pre-branch value is carried by some merge of the same side (
q1, q2 = q2, q1).
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:
| Name | Type | Description |
|---|---|---|
operations | list[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. |
bindings | dict[str, Any] | None | Compile-time parameter bindings used to resolve IfOperation conditions, matching what CompileTimeIfLoweringPass will later resolve. Defaults to None (no bindings). |
Raises:
QubitRebindError— If a runtime if branch rebinds a quantum variable whose pre-branch value has no consumer in that branch, no merge carrying it out of that side, and no reference outside the if — or a loop body rebinds a quantum variable whose incoming value it never consumes and whose pre-loop value has no owner outside the loop.
validate_program_graph_semantics [source]¶
def validate_program_graph_semantics(program: PreparedModule) -> NoneValidate 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:
| Name | Type | Description |
|---|---|---|
program | PreparedModule | Prepared entrypoint and callable bodies. |
Raises:
ValidationError— If a while condition is not measurement-backed.AffineTypeError— If structured control flow discards a quantum value.QubitConsumedError— If callable inlining binds one quantum resource to multiple formal operands.
Classes¶
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
CallPolicy [source]¶
class CallPolicy(enum.Enum)Describe the default lowering policy for a callable call.
Attributes¶
INLINENATIVE_FIRSTPRESERVE_BOX
InlinePass [source]¶
class InlinePass(Pass[Block, Block])Inline qkernel callables to create an affine block.
This pass recursively inlines function calls while preserving control flow structures (For, If, While).
Input: Block with BlockKind.HIERARCHICAL (may contain callable calls) Output: Block with BlockKind.AFFINE (no inline callable calls)
Parameters:
| Name | Type | Description |
|---|---|---|
body_selector | Callable[[InvokeOperation], Block | None] | None | Optional body-selection hook for consumers whose configured strategy differs from InvokeOperation.strategy_name. The standard compiler leaves this unset. Defaults to None. |
preserve_bound_quantum_identity | bool | Whether cloned callee quantum values should retain the logical owner and array-element address of their bound caller operands. Resource liveness analysis enables this so an inline call does not create phantom owners or erase lane identities. Defaults to False. |
preserve_bound_array_identity | bool | Whether cloned callee array values should retain the logical lineage of bound caller arrays. Resource classical-state analysis enables this so loop-carried stores remain connected across an inlined call. Defaults to False. |
Constructor¶
def __init__(
self,
body_selector: Callable[[InvokeOperation], Block | None] | None = None,
*,
inline_prefix_factory: Callable[[InvokeOperation, tuple[tuple[ArrayValue, tuple[ArrayValue, ...]], ...]], Sequence[Operation]] | None = None,
preserve_bound_quantum_identity: bool = False,
preserve_bound_array_identity: bool = False,
) -> NoneInitialize the pass with body-selection and identity policies.
Parameters:
| Name | Type | Description |
|---|---|---|
body_selector | Callable[[InvokeOperation], Block | None] | None | Consumer-specific selector used for inline-policy calls. Defaults to the invocation’s ordinary effective body. |
preserve_bound_quantum_identity | bool | Whether cloned quantum SSA values descending from a formal input retain the actual caller operand’s logical owner and array-element address. Defaults to False. |
preserve_bound_array_identity | bool | Whether cloned array SSA values descending from a formal input retain the actual caller array’s logical lineage. Defaults to False. |
Attributes¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockInline all inline-policy callable invocations.
Self-recursive qkernel invocations are unrolled one level per call:
the inner self-call is substituted but left intact so the outer
fixed-point loop can fold the base-case if between iterations.
The output kind is AFFINE when no inlineable calls remain,
otherwise HIERARCHICAL.
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[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. |
definition | CallableDef | None | Optional 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,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueor an Oracle control-partition field has an invalid Python type.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width, or if Oracle invocation and definition control metadata disagree.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of relevant callable implementations.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return a conservative union of measurement-derived results.name: str Return the display name for this invocation.num_added_control_qubits: int Return controls introduced by a frontend control transform.num_body_external_control_qubits: int Return control operands generic lowering adds outside a base body.num_control_qubits: int Return the number of leading control-qubit operands.num_declared_control_qubits: int Return controls included in an opaque Oracle’s base definition.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
effective_body¶
def effective_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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 | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None, which only selects engine-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
require_body | bool | Whether 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name used for implementation selection. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
select_body¶
def select_body(
self,
*,
engine: str | None = None,
strategy: str | None = None,
) -> CallableBodySelectionSelect 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:
| Name | Type | Description |
|---|---|---|
engine | str | None | Engine name to match. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
PreparedModule [source]¶
class PreparedModuleHold a prepared entrypoint and its reachable callable definitions.
Parameters:
| Name | Type | Description |
|---|---|---|
entrypoint_ref | CallableRef | Stable symbol assigned to the program entrypoint. |
entrypoint | Block | Hierarchical semantic block for the entrypoint. |
definitions | Mapping[CallableRef, CallableDef] | Reachable callable definitions keyed by their stable symbols. |
definition_variants | Mapping[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_graph | Mapping[CallableRef, frozenset[CallableRef]] | Directed caller-to-callee relation, including the entrypoint symbol. |
abi | ProgramABI | Classical public input and output contract. |
bindings | Mapping[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],
) -> NoneAttributes¶
abi: ProgramABIbindings: Mapping[str, Any]call_graph: Mapping[CallableRef, frozenset[CallableRef]]definition_variants: Mapping[CallableRef, tuple[CallableDef, ...]]definitions: Mapping[CallableRef, CallableDef]entrypoint: Blockentrypoint_ref: CallableRef
Methods¶
body¶
def body(self, ref: CallableRef) -> BlockReturn the semantic body associated with a program symbol.
Parameters:
| Name | Type | Description |
|---|---|---|
ref | CallableRef | Entrypoint or callable symbol to resolve. |
Returns:
Block — Hierarchical semantic body for ref.
Raises:
KeyError— Ifrefis neither the entrypoint nor a reachable body-backed callable definition.
owned_snapshot¶
def owned_snapshot(self) -> PreparedModuleCreate a deep, target-owned snapshot of prepared semantics.
The semantic IR intentionally remains mutable while compiler passes are being developed. Copying the entrypoint and definition registry as one object graph preserves shared callable bodies while preventing one target from mutating the source module observed by another.
Returns:
PreparedModule — Deep snapshot with read-only definition and call
graph registries.
ValidateWhileContractPass [source]¶
class ValidateWhileContractPass(Pass[Block, Block])Validates that all WhileOperation conditions are measurement-backed.
Builds a producer map (result UUID → producing Operation instance) and checks every WhileOperation operand against it. A valid condition must be:
A
ValuewithBitTypeMeasurement-backed: produced by
MeasureOperationdirectly, or anIfOperationmerge 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¶
name: str
Methods¶
run¶
def run(self, block: Block) -> BlockValidate all WhileOperations and return block unchanged.
qamomile.circuit.transpiler.program_orchestrator¶
Orchestration logic for compiled quantum-classical programs.
This module is internal. Users interact with ExecutableProgram.sample()/run().
Overview¶
| Function | Description |
|---|---|
flatten_user_bindings | Flatten public arrays and dictionaries into scalar ABI keys. |
resolve_runtime_array_location | Resolve local array indices through runtime-bound slice views. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
CircuitInvocation | Keep an emitted circuit and runtime parameter values together. |
ClassicalExecutor | Executes classical segments in Python. |
ClassicalStep | A classical execution step. |
CompiledClassicalSegment | A classical segment ready for Python execution. |
CompiledExpvalSegment | A compiled expectation value segment with concrete Hamiltonian. |
CompiledQuantumSegment | A quantum segment with emitted engine circuit. |
CompositeExecutionHandle | Aggregate several independently submitted executions. |
DictValue | A dictionary value stored as stable ordered entries. |
EstimateRequest | Describe one Hamiltonian expectation execution. |
ExecutableProgram | A fully compiled program ready for execution. |
ExecutionContext | Holds global state during program execution. |
ExecutionError | Error during program execution. |
ExecutionHandle | Expose an engine execution without forcing immediate result retrieval. |
ExecutionSnapshotKind | Identify the reconstruction contract of an execution snapshot node. |
ExpvalJob | Job for expectation value computation. |
ExpvalStep | An expectation-value execution step. |
JobKind | Identify the public operation needed to reconstruct a typed job. |
JobSnapshot | Store operation metadata and lossless raw execution reconstruction. |
MappedExecutionHandle | Lazily transform another execution handle’s result. |
ParameterMetadata | Describe every scalar slot and runtime array in a compiled segment. |
ProgramOrchestrator | Orchestrates execution of compiled quantum-classical programs. |
QuantumExecutor | Abstract base class for quantum backend execution. |
QuantumStep | A quantum execution step. |
RunJob | Job for single execution. |
SampleJob | Job for sampling execution (multiple shots). |
SampleRequest | Describe one sampling execution. |
TupleValue | A tuple of IR values for structured data. |
Value | A typed SSA value in the IR. |
Constants¶
EstimationAccuracy:TypeAlias=Exact | ShotBased | TargetPrecisionValueLike:TypeAlias='Value | ArrayValue | TupleValue | DictValue'
Functions¶
flatten_user_bindings [source]¶
def flatten_user_bindings(bindings: Mapping[str, Any] | None) -> dict[str, Any]Flatten public arrays and dictionaries into scalar ABI keys.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | Mapping[str, Any] | None | Raw user bindings keyed by kernel parameter name. |
Returns:
dict[str, Any] — dict[str, Any]: Scalar and dictionary entries keyed by emitted ABI
names.
resolve_runtime_array_location [source]¶
def resolve_runtime_array_location(
array: ArrayValue,
indices: tuple[int, ...],
resolve_int: Callable[[Value], int | None],
) -> tuple[ArrayValue, tuple[int, ...]] | NoneResolve local array indices through runtime-bound slice views.
Parameters:
| Name | Type | Description |
|---|---|---|
array | ArrayValue | Array whose local indices should be resolved. May be a root array or a slice_of view chain. |
indices | tuple[int, ...] | Concrete indices in array’s local coordinate space. |
resolve_int | Callable[[Value], int | None] | Callback used to evaluate slice_start / slice_step values against the current runtime state. |
Returns:
tuple[ArrayValue, tuple[int, ...]] | None — tuple[ArrayValue, tuple[int, ...]] | None: The root array and indices
in root coordinates, or None when a slice bound is unresolved
or violates the frontend slice contract.
Classes¶
ArrayValue [source]¶
class ArrayValue(Value[T])An array of typed IR values.
When slice_of is set, this array is a strided view over another
array. Element accesses on a sliced ArrayValue resolve to
physical slots on the root parent via the affine map
parent_index = slice_start + slice_step * view_local_index,
applied recursively along slice_of chains. The emit-time
resolver walks this chain to produce the final qubit index; passes
that substitute or clone values must treat slice_of /
slice_start / slice_step as Value references that need to
track through the same mapping as parent_array.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
shape: tuple[Value, ...] = tuple(),
slice_of: 'ArrayValue | None' = None,
slice_start: 'Value | None' = None,
slice_step: 'Value | None' = None,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]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:
| Name | Type | Description |
|---|---|---|
circuit | CircuitT | Emitted engine circuit or kernel artifact. |
bindings | Mapping[str, Any] | Flattened Qamomile runtime bindings. |
parameter_metadata | ParameterMetadata | Mapping from public parameter names to engine parameter objects. |
Constructor¶
def __init__(
self,
circuit: CircuitT,
bindings: Mapping[str, Any],
parameter_metadata: ParameterMetadata,
) -> NoneAttributes¶
bindings: Mapping[str, Any]circuit: CircuitTparameter_metadata: ParameterMetadata
ClassicalExecutor [source]¶
class ClassicalExecutorExecutes 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:
| Name | Type | Description |
|---|---|---|
segment | ClassicalSegment | Ordered classical operations and declared outputs to evaluate. |
context | ExecutionContext | Per-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:
ExecutionError— If an operation is unsupported or a required runtime value is unavailable.
resolve_value¶
def resolve_value(self, value: ValueLike, context: ExecutionContext) -> AnyResolve a typed classical output using the execution interpreter.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ValueLike | Scalar, array, tuple, or dictionary output. |
context | ExecutionContext | Runtime bindings and computed values keyed by their IR identities or public parameter names. |
Returns:
Any — Concrete value with tuple and dictionary structure retained.
Raises:
ExecutionError— If a required value is absent from the context and its compile-time metadata.
ClassicalStep [source]¶
class ClassicalStepA classical execution step.
Constructor¶
def __init__(self, segment: ClassicalSegment, role: str = 'classical') -> NoneAttributes¶
role: strsegment: ClassicalSegment
CompiledClassicalSegment [source]¶
class CompiledClassicalSegmentA classical segment ready for Python execution.
Constructor¶
def __init__(self, segment: ClassicalSegment) -> NoneAttributes¶
segment: ClassicalSegment
CompiledExpvalSegment [source]¶
class CompiledExpvalSegmentA 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(),
) -> NoneAttributes¶
hamiltonian: ‘qm_o.Hamiltonian’quantum_segment_index: intqubit_map: dict[int, int]result_ref: strsegment: ExpvalSegment
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,
) -> NoneAttributes¶
circuit: Tclbit_map: ClbitMapimplicit_output_qubit_indices: tuple[int, ...] | Nonemeasurement_qubit_map: dict[int, int]parameter_metadata: ParameterMetadataqubit_map: QubitMapsegment: QuantumSegment
CompositeExecutionHandle [source]¶
class CompositeExecutionHandle(ExecutionHandle[tuple[ResultT, ...]])Aggregate several independently submitted executions.
Parameters:
| Name | Type | Description |
|---|---|---|
handles | Sequence[ExecutionHandle[ResultT]] | Child executions in stable result order. |
Constructor¶
def __init__(self, handles: Sequence[ExecutionHandle[ResultT]]) -> NoneInitialize an ordered execution aggregate.
Parameters:
| Name | Type | Description |
|---|---|---|
handles | Sequence[ExecutionHandle[ResultT]] | Child executions. |
Attributes¶
native: object | None Return every child provider-native task.
Methods¶
cancel¶
def cancel(self) -> NoneAttempt 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:
ExceptionGroup— If any child status lookup or cancellation fails.
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) -> objectReturn 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:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Total local wait budget in seconds. |
Returns:
tuple[ResultT, ...] — tuple[ResultT, ...]: Ordered child results.
Raises:
TimeoutError— If the total wait budget expires.Exception— Any child execution failure.
result_async¶
def result_async(self, timeout: float | None = None) -> tuple[ResultT, ...]Return all child results asynchronously.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Total local wait budget in seconds. |
Returns:
tuple[ResultT, ...] — tuple[ResultT, ...]: Ordered child results.
Raises:
TimeoutError— If the total wait budget expires.Exception— Any child execution failure.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture all children with their original tuple boundaries.
Returns:
ExecutionSnapshot — Ordered nested execution structure.
Raises:
ValueError— If a child has no supported reconstruction contract.TypeError— If a local child contains unsupported result objects.
status¶
def status(self) -> JobStatusAggregate child statuses without hiding partial completion.
Returns:
JobStatus — Aggregate execution status.
DictValue [source]¶
class DictValue(_MetadataValueMixin, ValueBase)A dictionary value stored as stable ordered entries.
Constructor¶
def __init__(
self,
name: str,
entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> NoneAttributes¶
entries: tuple[tuple[TupleValue | Value, Value], ...]logical_id: strmetadata: ValueMetadataname: strtype: DictTypeuuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> DictValueEstimateRequest [source]¶
class EstimateRequest(Generic[CircuitT])Describe one Hamiltonian expectation execution.
Parameters:
| Name | Type | Description |
|---|---|---|
invocation | CircuitInvocation[CircuitT] | Circuit and runtime inputs. |
hamiltonian | qm_o.Hamiltonian | Observable to evaluate. |
accuracy | EstimationAccuracy | None | Explicit accuracy policy. None uses the executor’s configured default. |
Constructor¶
def __init__(
self,
invocation: CircuitInvocation[CircuitT],
hamiltonian: qm_o.Hamiltonian,
accuracy: EstimationAccuracy | None = None,
) -> NoneAttributes¶
accuracy: EstimationAccuracy | Nonehamiltonian: qm_o.Hamiltonianinvocation: CircuitInvocation[CircuitT]
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 typeConstructor¶
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(),
) -> NoneAttributes¶
compiled_classical: list[CompiledClassicalSegment]compiled_expval: list[CompiledExpvalSegment]compiled_quantum: list[CompiledQuantumSegment[T]]has_parameters: bool Check if this program has unbound parameters.output_values: list[ValueLike]parameter_names: list[str] Get list of parameter names that need binding.plan: ProgramPlan | Nonequantum_circuit: T Get the single quantum circuit.
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 | NoneGet 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] | ExpvalJobRestore 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:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine adapter configured with the provider credentials and target used by the original job. |
snapshot | JobSnapshot | Snapshot returned by the original public job’s snapshot() method. |
bindings | dict[str, Any] | None | Original 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:
ExecutionError— If the snapshot operation or execution shape does not match this executable program.NotImplementedError— If the executor cannot restore the referenced provider execution.ValueError— If required bindings are missing or invalid.
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] | ExpvalJobSubmit one execution and return its lazy result job.
Parameters:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine-specific quantum executor. |
bindings | dict[str, Any] | None | Parameter 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} |
estimation | EstimationAccuracy | None | Optional 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:
ExecutionError— If no quantum circuit to executeValueError— If required parameters are missing
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:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine-specific quantum executor. |
shots | int | Number of shots to run. |
bindings | dict[str, Any] | None | Parameter 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:
ExecutionError— If no quantum circuit to executeValueError— If required parameters are missing
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 ExecutionContextHolds 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) -> Anyget_many¶
def get_many(self, keys: list[str]) -> dict[str, Any]has¶
def has(self, key: str) -> boolset¶
def set(self, key: str, value: Any) -> Noneupdate¶
def update(self, values: dict[str, Any]) -> NoneExecutionError [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¶
native: object | None Return the wrapped provider-native task when available.
Methods¶
cancel¶
def cancel(self) -> NoneRequest 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) -> objectReturn 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) -> ResultTWait for and return the engine-neutral raw result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. None delegates the wait policy to the provider. |
Returns:
ResultT — Raw result normalized by the engine executor.
Raises:
TimeoutError— If the local wait expires before completion.
result_async¶
def result_async(self, timeout: float | None = None) -> ResultTWait asynchronously for the engine-neutral raw result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. Defaults to provider behavior when None. |
Returns:
ResultT — Raw result normalized by the engine executor.
Raises:
TimeoutError— If the local wait expires before completion.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture 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:
ValueError— If references are absent or their grouping is unknown.
status¶
def status(self) -> JobStatusReturn the current provider-independent execution status.
Returns:
JobStatus — Current normalized status.
ExecutionSnapshotKind [source]¶
class ExecutionSnapshotKind(StrEnum)Identify the reconstruction contract of an execution snapshot node.
Attributes¶
COMPOSITELOCALREMOTE
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]) -> NoneInitialize expval job.
Parameters:
| Name | Type | Description |
|---|---|---|
exp_val | float | ExecutionHandle[float] | Completed value or deferred expectation execution. |
Methods¶
result¶
def result(self, timeout: float | None = None) -> floatWait for and return the expectation value.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
float — Expectation value.
result_async¶
def result_async(self, timeout: float | None = None) -> floatWait asynchronously for and return the expectation value.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
float — Expectation value.
ExpvalStep [source]¶
class ExpvalStepAn expectation-value execution step.
Constructor¶
def __init__(self, segment: ExpvalSegment, quantum_step_index: int = 0) -> NoneAttributes¶
quantum_step_index: intsegment: ExpvalSegment
JobKind [source]¶
class JobKind(StrEnum)Identify the public operation needed to reconstruct a typed job.
Attributes¶
RUNSAMPLE
JobSnapshot [source]¶
class JobSnapshotStore 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:
| Name | Type | Description |
|---|---|---|
kind | JobKind | Public operation that created the job. |
executions | tuple[ExecutionReference, ...] | Ordered provider reference inventory. Empty for entirely local structured executions. For legacy snapshots, these references also specify the result layout. |
shots | int | None | Sampling shot count. Required for sample jobs and absent for run jobs. |
execution | ExecutionSnapshot | None | Ordered remote/local execution tree. None denotes the legacy flat-reference format. When present, executions must exactly match its remote leaves. |
Raises:
ValueError— If legacy references are empty, the reference inventory disagrees with the tree, or shots disagree with the operation kind.TypeError— If operation kind, references, tree, or shots have incompatible types.
Constructor¶
def __init__(
self,
kind: JobKind,
executions: tuple[ExecutionReference, ...],
shots: int | None = None,
execution: ExecutionSnapshot | None = None,
) -> NoneAttributes¶
execution: ExecutionSnapshot | Noneexecutions: tuple[ExecutionReference, ...]kind: JobKindshots: int | None
Methods¶
from_dict¶
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> JobSnapshotReconstruct a validated snapshot from JSON-compatible data.
Parameters:
| Name | Type | Description |
|---|---|---|
data | Mapping[str, Any] | Mapping produced by :meth:to_dict. |
Returns:
JobSnapshot — Validated typed-job restoration snapshot.
Raises:
KeyError— If operation kind, references, or a version 2 tree is absent.TypeError— If metadata, references, or local values have wrong types.ValueError— If a version, field, tree, or reference is invalid.
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:
TypeError— If local values were mutated to unsupported types.ValueError— If local values or references were mutated to invalid data.
MappedExecutionHandle [source]¶
class MappedExecutionHandle(ExecutionHandle[MappedT], Generic[ResultT, MappedT])Lazily transform another execution handle’s result.
Parameters:
| Name | Type | Description |
|---|---|---|
source | ExecutionHandle[ResultT] | Underlying execution handle. |
transform | Callable[[ResultT], MappedT] | Result transformation. |
snapshot_source | bool | Whether 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,
) -> NoneInitialize a lazy mapped execution.
Parameters:
| Name | Type | Description |
|---|---|---|
source | ExecutionHandle[ResultT] | Underlying execution handle. |
transform | Callable[[ResultT], MappedT] | Result transformation. |
snapshot_source | bool | Allow source snapshots only when the owner rebuilds the transformation on restore. Defaults to False. |
Attributes¶
native: object | None Return the source provider-native task.
Methods¶
cancel¶
def cancel(self) -> NoneForward 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) -> objectReturn 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) -> MappedTRetrieve and transform the source result once.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
MappedT — Cached transformed result.
Raises:
Exception— Any source or transformation failure.
result_async¶
def result_async(self, timeout: float | None = None) -> MappedTRetrieve and transform the source result asynchronously.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
MappedT — Cached transformed result.
Raises:
Exception— Any source or transformation failure.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture 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:
ValueError— If the mapping has no declared restoration contract.TypeError— If a local source value cannot be saved.
status¶
def status(self) -> JobStatusReturn the source execution status.
Returns:
JobStatus — Current mapped execution status.
ParameterMetadata [source]¶
class ParameterMetadataDescribe every scalar slot and runtime array in a compiled segment.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | list[ParameterInfo] | Ordered scalar engine slots. Defaults to an empty list. |
arrays | dict[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(),
) -> NoneAttributes¶
arrays: dict[str, ParameterArrayInfo]parameters: list[ParameterInfo]
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 | NoneFind one scalar slot by its full emitted key.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Full engine parameter key. |
Returns:
ParameterInfo | None — ParameterInfo | None: Matching slot, or None when absent.
merge¶
@classmethod
def merge(cls, metadata: Sequence[ParameterMetadata]) -> ParameterMetadataMerge parameter manifests from multiple quantum segments.
Parameters:
| Name | Type | Description |
|---|---|---|
metadata | Sequence[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:
| Name | Type | Description |
|---|---|---|
bindings | Mapping[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) -> NoneValidate user array rank and every concrete ABI dimension.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | Mapping[str, Any] | None | Raw public bindings before scalar flattening. None means no validation is needed. |
Raises:
ValueError— If a supplied array has the wrong rank or exceeds a dimension whose ABI extent is known exactly.
validate_required_bindings¶
def validate_required_bindings(self, indexed_bindings: Mapping[str, Any]) -> NoneReject missing scalar slots in an indexed binding map.
Parameters:
| Name | Type | Description |
|---|---|---|
indexed_bindings | Mapping[str, Any] | Flattened user bindings. |
Raises:
ValueError— If one or more emitted scalar slots are missing.
ProgramOrchestrator [source]¶
class ProgramOrchestrator(Generic[T])Orchestrates execution of compiled quantum-classical programs.
This is an internal class that handles the runtime execution logic.
Users should use ExecutableProgram.sample() and
ExecutableProgram.run() instead.
Constructor¶
def __init__(self, program: ExecutableProgram[T]) -> NoneMethods¶
restore¶
def restore(
self,
executor: QuantumExecutor[T],
snapshot: JobSnapshot,
bindings: dict[str, Any] | None,
) -> SampleJob[Any] | RunJob[Any] | ExpvalJobRestore provider executions and rebuild the typed public job.
Parameters:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine adapter configured with the credentials and target needed to restore provider jobs. |
snapshot | JobSnapshot | Operation metadata and provider references captured from the original public job. |
bindings | dict[str, Any] | None | Original runtime bindings used to rebuild classical pre- and post-processing context. |
Returns:
SampleJob[Any] | RunJob[Any] | ExpvalJob — SampleJob[Any] | RunJob[Any] | ExpvalJob: Lazy typed job with the
same public result conversion as the original execution.
Raises:
ExecutionError— If the snapshot reference shape does not match the executable program.NotImplementedError— If the executor cannot restore a reference.ValueError— If runtime bindings or snapshot metadata are invalid.TypeError— If mutable snapshot values have unsupported types.
run¶
def run(
self,
executor: QuantumExecutor[T],
bindings: dict[str, Any] | None,
estimation: EstimationAccuracy | None = None,
) -> RunJob[Any] | ExpvalJobSubmit one execution and return its lazy public job.
Parameters:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine execution adapter. |
bindings | dict[str, Any] | None | Runtime public bindings. |
estimation | EstimationAccuracy | None | Optional expectation accuracy policy. Defaults to the executor configuration. |
Returns:
RunJob[Any] | ExpvalJob — RunJob[Any] | ExpvalJob: Deferred public result job.
run_expval¶
def run_expval(
self,
executor: QuantumExecutor[T],
bindings: dict[str, Any] | None,
estimation: EstimationAccuracy | None = None,
) -> ExpvalJobSubmit a pure expectation execution through the public run path.
Parameters:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine execution adapter. |
bindings | dict[str, Any] | None | Runtime public bindings. |
estimation | EstimationAccuracy | None | Optional expectation accuracy policy. |
Returns:
ExpvalJob — Deferred expectation result.
Raises:
ExecutionError— If the program does not produce a pure expectation job.
sample¶
def sample(
self,
executor: QuantumExecutor[T],
shots: int,
bindings: dict[str, Any] | None,
) -> SampleJob[Any]Submit sampling and return a lazy typed-result job.
Parameters:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine execution adapter. |
shots | int | Positive number of requested samples. |
bindings | dict[str, Any] | None | Runtime public bindings. |
Returns:
SampleJob[Any] — SampleJob[Any]: Deferred typed sample job.
Raises:
ExecutionError— If the plan contains expectation-value steps.ValueError— If shots or runtime bindings are invalid.
QuantumExecutor [source]¶
class QuantumExecutor(ABC, Generic[T])Abstract base class for quantum backend execution.
To implement a custom executor:
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).
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.
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¶
capabilities: ExecutionCapabilities Describe backend execution features available through this adapter.
Methods¶
bind_invocation¶
def bind_invocation(self, invocation: CircuitInvocation[T]) -> TBind one invocation for a backend without native input submission.
Parameters:
| Name | Type | Description |
|---|---|---|
invocation | CircuitInvocation[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,
) -> TBind parameter values to the circuit.
Default implementation returns the circuit unchanged. Override for backends that support parametric circuits.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | T | The parameterized circuit |
bindings | dict[str, Any] | Dict mapping parameter names (indexed format) to values. e.g., {“gammas[0]”: 0.1, “gammas[1]”: 0.2} |
parameter_metadata | ParameterMetadata | Metadata 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,
) -> floatEstimate 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:
| Name | Type | Description |
|---|---|---|
circuit | T | The quantum circuit (state preparation ansatz) |
hamiltonian | 'qm_o.Hamiltonian' | The qamomile.observable.Hamiltonian to measure |
params | Sequence[float] | None | Optional parameter values for parametric circuits |
Returns:
float — The estimated expectation value
Raises:
NotImplementedError— If the executor does not support estimation
execute¶
def execute(self, circuit: T, shots: int) -> dict[str, int]Execute the circuit and return bitstring counts.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | T | The quantum circuit to execute |
shots | int | Number 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:
| Name | Type | Description |
|---|---|---|
reference | ExecutionReference | Provider execution reference. |
Returns:
ExecutionHandle[Any] — ExecutionHandle[Any]: Restored provider-backed handle.
Raises:
NotImplementedError— If this executor cannot restore jobs.
submit_estimate¶
def submit_estimate(self, request: EstimateRequest[T]) -> ExecutionHandle[float]Submit an expectation request through the synchronous path.
Parameters:
| Name | Type | Description |
|---|---|---|
request | EstimateRequest[T] | Circuit, Hamiltonian, and optional accuracy policy. |
Returns:
ExecutionHandle[float] — ExecutionHandle[float]: Completed compatibility handle.
Raises:
NotImplementedError— If an explicit accuracy policy is requested from an executor that has not implemented request submission.
submit_estimates¶
def submit_estimates(
self,
requests: Sequence[EstimateRequest[T]],
) -> ExecutionHandle[tuple[float, ...]]Submit an ordered collection of expectation requests.
Parameters:
| Name | Type | Description |
|---|---|---|
requests | Sequence[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:
| Name | Type | Description |
|---|---|---|
request | SampleRequest[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:
| Name | Type | Description |
|---|---|---|
requests | Sequence[SampleRequest[T]] | Sampling requests. |
Returns:
ExecutionHandle[tuple[dict[str, int], ...]] — ExecutionHandle[tuple[dict[str, int], ...]]: Composite result
handle preserving request order.
QuantumStep [source]¶
class QuantumStepA quantum execution step.
Constructor¶
def __init__(self, segment: QuantumSegment) -> NoneAttributes¶
segment: QuantumSegment
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,
) -> NoneInitialize run job.
Parameters:
| Name | Type | Description |
|---|---|---|
raw_counts | dict[str, int] | ExecutionHandle[dict[str, int]] | None | Counts or deferred counts. May be None with value_handle. |
result_converter | Callable[[str], T] | None | Function converting one bitstring. May be None with value_handle. |
value_handle | ExecutionHandle[T] | None | Handle already producing the final public value. Defaults to None. |
Raises:
ValueError— If neither a valid counts source norvalue_handleis supplied.
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:
| Name | Type | Description |
|---|---|---|
handle | ExecutionHandle[T] | Final-value execution handle. |
Returns:
RunJob[T] — RunJob[T]: Public run job delegating to handle.
result¶
def result(self, timeout: float | None = None) -> TWait for and return the single public result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
T — Public kernel return value.
result_async¶
def result_async(self, timeout: float | None = None) -> TWait asynchronously for the single public result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum 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,
) -> NoneInitialize sample job.
Parameters:
| Name | Type | Description |
|---|---|---|
raw_counts | dict[str, int] | ExecutionHandle[dict[str, int]] | Counts or a deferred counts execution. |
result_converter | Callable[[dict[str, int]], list[tuple[T, int]]] | Function converting raw counts to typed values. |
shots | int | Number of requested shots. |
Methods¶
result¶
def result(self, timeout: float | None = None) -> SampleResult[T]Wait for and return the typed sample result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum 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:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
SampleResult[T] — SampleResult[T]: Aggregated typed result.
SampleRequest [source]¶
class SampleRequest(Generic[CircuitT])Describe one sampling execution.
Parameters:
| Name | Type | Description |
|---|---|---|
invocation | CircuitInvocation[CircuitT] | Circuit and runtime inputs. |
shots | int | Number of requested samples. |
Raises:
ValueError— Ifshotsis not positive.
Constructor¶
def __init__(self, invocation: CircuitInvocation[CircuitT], shots: int) -> NoneAttributes¶
invocation: CircuitInvocation[CircuitT]shots: int
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()))(),
) -> NoneAttributes¶
elements: tuple[ValueLike, ...]logical_id: strmetadata: ValueMetadataname: strtype: ‘TupleType’uuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> TupleValueValue [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
qamomile.circuit.transpiler.quantum_executor¶
Abstract base class for quantum backend execution.
This module provides a simple interface for implementing custom quantum executors. Executors bridge Qamomile’s compiled circuits to various quantum backends including local simulators and cloud quantum devices.
Basic Example (Local Simulator): from qiskit_aer import AerSimulator
class MyExecutor(QuantumExecutor[QuantumCircuit]):
def __init__(self):
self.backend = AerSimulator()
def execute(self, circuit: QuantumCircuit, shots: int) -> dict[str, int]:
from qiskit import transpile
if circuit.num_clbits == 0:
circuit = circuit.copy()
circuit.measure_all()
transpiled = transpile(circuit, self.backend)
job = self.backend.run(transpiled, shots=shots)
return job.result().get_counts()Cloud Backend Example (IBM Quantum): from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2
class IBMQuantumExecutor(QuantumExecutor[QuantumCircuit]):
def __init__(self, backend_name: str = "ibm_brisbane"):
self.service = QiskitRuntimeService()
self.backend_name = backend_name
def execute(self, circuit: QuantumCircuit, shots: int) -> dict[str, int]:
from qiskit.transpiler.preset_passmanagers import (
generate_preset_pass_manager,
)
backend = self.service.backend(self.backend_name)
pm = generate_preset_pass_manager(backend=backend, optimization_level=1)
transpiled = pm.run(circuit)
sampler = SamplerV2(backend)
job = sampler.run([transpiled], shots=shots)
return job.result()[0].data.meas.get_counts()
def bind_parameters(self, circuit, bindings, metadata):
# Use helper method for easy conversion
return circuit.assign_parameters(metadata.to_binding_dict(bindings))Bitstring Format:
The execute() method returns dict[str, int] where keys are bitstrings in big-endian format (leftmost bit = highest qubit index). Example: {“011”: 512, “100”: 488} for 3 qubits
Overview¶
| Class | Description |
|---|---|
CircuitInvocation | Keep an emitted circuit and runtime parameter values together. |
CompletedExecutionHandle | Wrap an already available result for synchronous executors. |
CompositeExecutionHandle | Aggregate several independently submitted executions. |
EstimateRequest | Describe one Hamiltonian expectation execution. |
ExecutionCapabilities | Declare the execution features implemented by one executor. |
ExecutionHandle | Expose an engine execution without forcing immediate result retrieval. |
ExecutionReference | Store secret-free identifiers needed to restore remote execution. |
ParameterMetadata | Describe every scalar slot and runtime array in a compiled segment. |
QuantumExecutor | Abstract base class for quantum backend execution. |
SampleRequest | Describe one sampling execution. |
Classes¶
CircuitInvocation [source]¶
class CircuitInvocation(Generic[CircuitT])Keep an emitted circuit and runtime parameter values together.
Engines may bind the values into a new circuit or submit them through a native parameter-input API. Keeping both forms available preserves native parameter sweeps and provider-side compilation caches.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | CircuitT | Emitted engine circuit or kernel artifact. |
bindings | Mapping[str, Any] | Flattened Qamomile runtime bindings. |
parameter_metadata | ParameterMetadata | Mapping from public parameter names to engine parameter objects. |
Constructor¶
def __init__(
self,
circuit: CircuitT,
bindings: Mapping[str, Any],
parameter_metadata: ParameterMetadata,
) -> NoneAttributes¶
bindings: Mapping[str, Any]circuit: CircuitTparameter_metadata: ParameterMetadata
CompletedExecutionHandle [source]¶
class CompletedExecutionHandle(ExecutionHandle[ResultT])Wrap an already available result for synchronous executors.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ResultT | Completed execution value. |
Constructor¶
def __init__(self, value: ResultT) -> NoneInitialize an immediately completed execution.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ResultT | Completed execution value. |
Methods¶
result¶
def result(self, timeout: float | None = None) -> ResultTReturn the completed value without waiting.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Ignored compatibility timeout. |
Returns:
ResultT — Stored execution value.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture the already available raw result without waiting.
Returns:
ExecutionSnapshot — Owned, type-preserving local value.
Raises:
TypeError— If the value contains unsupported result objects.ValueError— If the value is nonfinite or cyclic.
status¶
def status(self) -> JobStatusReturn the completed status.
Returns:
JobStatus — Always :attr:JobStatus.COMPLETED.
CompositeExecutionHandle [source]¶
class CompositeExecutionHandle(ExecutionHandle[tuple[ResultT, ...]])Aggregate several independently submitted executions.
Parameters:
| Name | Type | Description |
|---|---|---|
handles | Sequence[ExecutionHandle[ResultT]] | Child executions in stable result order. |
Constructor¶
def __init__(self, handles: Sequence[ExecutionHandle[ResultT]]) -> NoneInitialize an ordered execution aggregate.
Parameters:
| Name | Type | Description |
|---|---|---|
handles | Sequence[ExecutionHandle[ResultT]] | Child executions. |
Attributes¶
native: object | None Return every child provider-native task.
Methods¶
cancel¶
def cancel(self) -> NoneAttempt 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:
ExceptionGroup— If any child status lookup or cancellation fails.
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) -> objectReturn 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:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Total local wait budget in seconds. |
Returns:
tuple[ResultT, ...] — tuple[ResultT, ...]: Ordered child results.
Raises:
TimeoutError— If the total wait budget expires.Exception— Any child execution failure.
result_async¶
def result_async(self, timeout: float | None = None) -> tuple[ResultT, ...]Return all child results asynchronously.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Total local wait budget in seconds. |
Returns:
tuple[ResultT, ...] — tuple[ResultT, ...]: Ordered child results.
Raises:
TimeoutError— If the total wait budget expires.Exception— Any child execution failure.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture all children with their original tuple boundaries.
Returns:
ExecutionSnapshot — Ordered nested execution structure.
Raises:
ValueError— If a child has no supported reconstruction contract.TypeError— If a local child contains unsupported result objects.
status¶
def status(self) -> JobStatusAggregate child statuses without hiding partial completion.
Returns:
JobStatus — Aggregate execution status.
EstimateRequest [source]¶
class EstimateRequest(Generic[CircuitT])Describe one Hamiltonian expectation execution.
Parameters:
| Name | Type | Description |
|---|---|---|
invocation | CircuitInvocation[CircuitT] | Circuit and runtime inputs. |
hamiltonian | qm_o.Hamiltonian | Observable to evaluate. |
accuracy | EstimationAccuracy | None | Explicit accuracy policy. None uses the executor’s configured default. |
Constructor¶
def __init__(
self,
invocation: CircuitInvocation[CircuitT],
hamiltonian: qm_o.Hamiltonian,
accuracy: EstimationAccuracy | None = None,
) -> NoneAttributes¶
accuracy: EstimationAccuracy | Nonehamiltonian: qm_o.Hamiltonianinvocation: CircuitInvocation[CircuitT]
ExecutionCapabilities [source]¶
class ExecutionCapabilitiesDeclare the execution features implemented by one executor.
Parameters:
| Name | Type | Description |
|---|---|---|
supports_async_sampling | bool | Whether sampling submission returns before provider execution completes. Defaults to False. |
supports_async_estimation | bool | Whether expectation submission returns before provider execution completes. Defaults to False. |
supports_estimation | bool | Whether expectation-value execution is implemented. Defaults to False. |
supports_cancellation | bool | Whether provider-backed handles can request cancellation. Defaults to False. |
supports_restoration | bool | Whether execution references can recreate provider-backed handles. Defaults to False. |
supports_native_batch | bool | Whether multiple logical requests can be submitted through one provider-native batch or job. Defaults to False. |
supports_native_parameter_inputs | bool | Whether runtime values remain separate from emitted circuits during provider submission. Defaults to False. |
estimation_accuracy | frozenset[EstimationPolicyType] | Explicit per-request accuracy policies accepted by the executor. An empty set means only executor-configured estimation behavior is available. |
Raises:
ValueError— If an unknown estimation policy type is declared or estimation features are declared without estimation support.
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(),
) -> NoneAttributes¶
estimation_accuracy: frozenset[EstimationPolicyType]supports_async_estimation: boolsupports_async_sampling: boolsupports_cancellation: boolsupports_estimation: boolsupports_native_batch: boolsupports_native_parameter_inputs: boolsupports_restoration: bool
ExecutionHandle [source]¶
class ExecutionHandle(ABC, Generic[ResultT])Expose an engine execution without forcing immediate result retrieval.
Attributes¶
native: object | None Return the wrapped provider-native task when available.
Methods¶
cancel¶
def cancel(self) -> NoneRequest 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) -> objectReturn 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) -> ResultTWait for and return the engine-neutral raw result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. None delegates the wait policy to the provider. |
Returns:
ResultT — Raw result normalized by the engine executor.
Raises:
TimeoutError— If the local wait expires before completion.
result_async¶
def result_async(self, timeout: float | None = None) -> ResultTWait asynchronously for the engine-neutral raw result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. Defaults to provider behavior when None. |
Returns:
ResultT — Raw result normalized by the engine executor.
Raises:
TimeoutError— If the local wait expires before completion.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture 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:
ValueError— If references are absent or their grouping is unknown.
status¶
def status(self) -> JobStatusReturn the current provider-independent execution status.
Returns:
JobStatus — Current normalized status.
ExecutionReference [source]¶
class ExecutionReferenceStore secret-free identifiers needed to restore remote execution.
Parameters:
| Name | Type | Description |
|---|---|---|
provider | str | Stable provider or adapter name. |
job_ids | tuple[str, ...] | One or more provider job identifiers. |
target | str | None | Provider target or device identifier. Defaults to None. |
group_id | str | None | Session, batch, program, or parent identifier. Defaults to None. |
context | Mapping[str, str] | Additional non-secret identifiers needed to restore the job. Defaults to an empty mapping. |
Raises:
ValueError— If the provider name or any job identifier is empty.TypeError— If identifiers or context have incompatible types.
Constructor¶
def __init__(
self,
provider: str,
job_ids: tuple[str, ...],
target: str | None = None,
group_id: str | None = None,
context: Mapping[str, str] = dict(),
) -> NoneAttributes¶
context: Mapping[str, str]group_id: str | Nonejob_ids: tuple[str, ...]provider: strtarget: str | None
Methods¶
from_dict¶
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionReferenceReconstruct a provider reference from JSON-compatible data.
Parameters:
| Name | Type | Description |
|---|---|---|
data | Mapping[str, Any] | Mapping produced by :meth:to_dict. |
Returns:
ExecutionReference — Validated provider execution reference.
Raises:
KeyError— If a required provider or job identifier field is absent.TypeError— If a field has an incompatible type.ValueError— If provider or job identifiers are empty.
to_dict¶
def to_dict(self) -> dict[str, Any]Convert the provider reference to JSON-compatible data.
Returns:
dict[str, Any] — dict[str, Any]: Provider identifiers and decoding context without
credentials or SDK objects.
ParameterMetadata [source]¶
class ParameterMetadataDescribe every scalar slot and runtime array in a compiled segment.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | list[ParameterInfo] | Ordered scalar engine slots. Defaults to an empty list. |
arrays | dict[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(),
) -> NoneAttributes¶
arrays: dict[str, ParameterArrayInfo]parameters: list[ParameterInfo]
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 | NoneFind one scalar slot by its full emitted key.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Full engine parameter key. |
Returns:
ParameterInfo | None — ParameterInfo | None: Matching slot, or None when absent.
merge¶
@classmethod
def merge(cls, metadata: Sequence[ParameterMetadata]) -> ParameterMetadataMerge parameter manifests from multiple quantum segments.
Parameters:
| Name | Type | Description |
|---|---|---|
metadata | Sequence[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:
| Name | Type | Description |
|---|---|---|
bindings | Mapping[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) -> NoneValidate user array rank and every concrete ABI dimension.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | Mapping[str, Any] | None | Raw public bindings before scalar flattening. None means no validation is needed. |
Raises:
ValueError— If a supplied array has the wrong rank or exceeds a dimension whose ABI extent is known exactly.
validate_required_bindings¶
def validate_required_bindings(self, indexed_bindings: Mapping[str, Any]) -> NoneReject missing scalar slots in an indexed binding map.
Parameters:
| Name | Type | Description |
|---|---|---|
indexed_bindings | Mapping[str, Any] | Flattened user bindings. |
Raises:
ValueError— If one or more emitted scalar slots are missing.
QuantumExecutor [source]¶
class QuantumExecutor(ABC, Generic[T])Abstract base class for quantum backend execution.
To implement a custom executor:
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).
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.
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¶
capabilities: ExecutionCapabilities Describe backend execution features available through this adapter.
Methods¶
bind_invocation¶
def bind_invocation(self, invocation: CircuitInvocation[T]) -> TBind one invocation for a backend without native input submission.
Parameters:
| Name | Type | Description |
|---|---|---|
invocation | CircuitInvocation[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,
) -> TBind parameter values to the circuit.
Default implementation returns the circuit unchanged. Override for backends that support parametric circuits.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | T | The parameterized circuit |
bindings | dict[str, Any] | Dict mapping parameter names (indexed format) to values. e.g., {“gammas[0]”: 0.1, “gammas[1]”: 0.2} |
parameter_metadata | ParameterMetadata | Metadata 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,
) -> floatEstimate 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:
| Name | Type | Description |
|---|---|---|
circuit | T | The quantum circuit (state preparation ansatz) |
hamiltonian | 'qm_o.Hamiltonian' | The qamomile.observable.Hamiltonian to measure |
params | Sequence[float] | None | Optional parameter values for parametric circuits |
Returns:
float — The estimated expectation value
Raises:
NotImplementedError— If the executor does not support estimation
execute¶
def execute(self, circuit: T, shots: int) -> dict[str, int]Execute the circuit and return bitstring counts.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | T | The quantum circuit to execute |
shots | int | Number 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:
| Name | Type | Description |
|---|---|---|
reference | ExecutionReference | Provider execution reference. |
Returns:
ExecutionHandle[Any] — ExecutionHandle[Any]: Restored provider-backed handle.
Raises:
NotImplementedError— If this executor cannot restore jobs.
submit_estimate¶
def submit_estimate(self, request: EstimateRequest[T]) -> ExecutionHandle[float]Submit an expectation request through the synchronous path.
Parameters:
| Name | Type | Description |
|---|---|---|
request | EstimateRequest[T] | Circuit, Hamiltonian, and optional accuracy policy. |
Returns:
ExecutionHandle[float] — ExecutionHandle[float]: Completed compatibility handle.
Raises:
NotImplementedError— If an explicit accuracy policy is requested from an executor that has not implemented request submission.
submit_estimates¶
def submit_estimates(
self,
requests: Sequence[EstimateRequest[T]],
) -> ExecutionHandle[tuple[float, ...]]Submit an ordered collection of expectation requests.
Parameters:
| Name | Type | Description |
|---|---|---|
requests | Sequence[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:
| Name | Type | Description |
|---|---|---|
request | SampleRequest[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:
| Name | Type | Description |
|---|---|---|
requests | Sequence[SampleRequest[T]] | Sampling requests. |
Returns:
ExecutionHandle[tuple[dict[str, int], ...]] — ExecutionHandle[tuple[dict[str, int], ...]]: Composite result
handle preserving request order.
SampleRequest [source]¶
class SampleRequest(Generic[CircuitT])Describe one sampling execution.
Parameters:
| Name | Type | Description |
|---|---|---|
invocation | CircuitInvocation[CircuitT] | Circuit and runtime inputs. |
shots | int | Number of requested samples. |
Raises:
ValueError— Ifshotsis not positive.
Constructor¶
def __init__(self, invocation: CircuitInvocation[CircuitT], shots: int) -> NoneAttributes¶
invocation: CircuitInvocation[CircuitT]shots: int
qamomile.circuit.transpiler.result¶
EmitResult data structures for transpiler output.
Overview¶
| Class | Description |
|---|---|
ClassicalMapping | Maps a logical Value to a classical value or measurement result slot. |
EmitResult | Structured result from Transpiler.emit(). |
OutputMapping | Maps Block output position to a physical resource. |
QubitMapping | Maps a logical Value to a physical qubit index. |
Classes¶
ClassicalMapping [source]¶
class ClassicalMappingMaps a logical Value to a classical value or measurement result slot.
Constructor¶
def __init__(
self,
value_uuid: str,
value_name: str,
value: Union[int, float, bool, None],
clbit_index: Union[int, None] = None,
) -> NoneAttributes¶
clbit_index: Union[int, None]value: Union[int, float, bool, None]value_name: strvalue_uuid: str
EmitResult [source]¶
class EmitResult(Generic[T])Structured result from Transpiler.emit().
Contains the engine-specific circuit along with mapping information that tracks the correspondence between logical Values and physical qubit/clbit indices.
Constructor¶
def __init__(
self,
circuit: T,
qubit_mappings: list[QubitMapping],
classical_mappings: list[ClassicalMapping],
output_mappings: list[OutputMapping],
num_qubits: int,
num_clbits: int = 0,
) -> NoneAttributes¶
circuit: Tclassical_mappings: list[ClassicalMapping]num_clbits: intnum_qubits: intoutput_mappings: list[OutputMapping]qubit_mappings: list[QubitMapping]
Methods¶
get_measurement_clbit_indices¶
def get_measurement_clbit_indices(self) -> list[int]Get clbit indices for all measurement outputs in order.
get_output_mapping_by_index¶
def get_output_mapping_by_index(self, index: int) -> Union[OutputMapping, None]Get output mapping by tuple index.
get_output_qubit_indices¶
def get_output_qubit_indices(self) -> list[int]Get qubit indices for all quantum outputs in order.
get_qubit_index_by_name¶
def get_qubit_index_by_name(self, name: str) -> Union[int, None]Look up qubit index by Value name.
OutputMapping [source]¶
class OutputMappingMaps Block output position to a physical resource.
Constructor¶
def __init__(
self,
output_index: int,
value_uuid: str,
value_name: str,
kind: str,
physical_index: Union[int, None],
classical_value: Union[int, float, bool, None] = None,
) -> NoneAttributes¶
classical_value: Union[int, float, bool, None]kind: stroutput_index: intphysical_index: Union[int, None]value_name: strvalue_uuid: str
QubitMapping [source]¶
class QubitMappingMaps a logical Value to a physical qubit index.
Constructor¶
def __init__(self, value_uuid: str, value_name: str, qubit_index: int) -> NoneAttributes¶
qubit_index: intvalue_name: strvalue_uuid: str
qamomile.circuit.transpiler.segments¶
Data structures for segmented quantum/classical execution plans.
Overview¶
| Class | Description |
|---|---|
ClassicalSegment | A segment of pure classical operations. |
ClassicalStep | A classical execution step. |
ExpvalSegment | A segment for expectation value computation. |
ExpvalStep | An expectation-value execution step. |
HybridBoundary | Represents a measurement or encode operation at quantum/classical boundary. |
MultipleQuantumSegmentsError | Raised when a program cannot fit the single-quantum-segment model. |
ProgramABI | Runtime-visible ABI for a segmented program. |
ProgramPlan | Execution plan for a hybrid quantum/classical program. |
QuantumSegment | A segment of pure quantum operations. |
QuantumStep | A quantum execution step. |
Segment | Base class for separated computation segments. |
SegmentKind | Type of computation segment. |
SeparationError | Error during quantum/classical separation. |
Value | A typed SSA value in the IR. |
Constants¶
ProgramStep:TypeAlias=ClassicalStep | QuantumStep | ExpvalStepValueLike:TypeAlias='Value | ArrayValue | TupleValue | DictValue'
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(),
) -> NoneAttributes¶
kind: SegmentKind
ClassicalStep [source]¶
class ClassicalStepA classical execution step.
Constructor¶
def __init__(self, segment: ClassicalSegment, role: str = 'classical') -> NoneAttributes¶
role: strsegment: ClassicalSegment
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 = '',
) -> NoneAttributes¶
hamiltonian_value: Value | Nonekind: SegmentKindqubits_value: Value | Noneresult_ref: str
ExpvalStep [source]¶
class ExpvalStepAn expectation-value execution step.
Constructor¶
def __init__(self, segment: ExpvalSegment, quantum_step_index: int = 0) -> NoneAttributes¶
quantum_step_index: intsegment: ExpvalSegment
HybridBoundary [source]¶
class HybridBoundaryRepresents a measurement or encode operation at quantum/classical boundary.
These operations bridge quantum and classical segments.
Constructor¶
def __init__(
self,
operation: Operation,
source_segment_index: int,
target_segment_index: int,
value_ref: str,
) -> NoneAttributes¶
operation: Operationsource_segment_index: inttarget_segment_index: intvalue_ref: str
MultipleQuantumSegmentsError [source]¶
class MultipleQuantumSegmentsError(SeparationError)Raised when a program cannot fit the single-quantum-segment model.
Qamomile enforces a single quantum circuit execution pattern:
[Classical Prep] → Quantum Circuit → [Classical Post/Expval]
The error fires when segmentation finds more than one quantum segment
(classical work that must execute between two quantum regions, e.g.
quantum operations resuming after a qmc.expval), or when a
classical value feeding a quantum gate is also consumed by classical
work and therefore cannot be absorbed into the quantum segment.
Note that a loop bound left as a runtime parameter is diagnosed
earlier, by SymbolicShapeValidationPass, with a dedicated
“Cannot unroll loop” message — it does not reach segmentation.
Example:
Incorrect — quantum operations resume after an expectation value,
which closes the quantum segment::
@qmc.qkernel
def kernel(obs: qmc.Observable) -> tuple[qmc.Float, qmc.Bit]:
q = qmc.qubit("q")
q = qmc.h(q)
e = qmc.expval(q, obs) # quantum segment ends here
q2 = qmc.qubit("q2")
q2 = qmc.x(q2) # second quantum segment -> error
return e, qmc.measure(q2)
Correct — keep all quantum operations in one contiguous region and
take the expectation value at the end::
@qmc.qkernel
def kernel(obs: qmc.Observable) -> qmc.Float:
q = qmc.qubit("q")
q = qmc.h(q)
return qmc.expval(q, obs)ProgramABI [source]¶
class ProgramABIRuntime-visible ABI for a segmented program.
Constructor¶
def __init__(
self,
public_inputs: dict[str, ValueLike] = dict(),
output_values: list[ValueLike] = list(),
) -> NoneAttributes¶
output_values: list[ValueLike]public_inputs: dict[str, ValueLike]
ProgramPlan [source]¶
class ProgramPlanExecution plan for a hybrid quantum/classical program.
Structure:
[Optional] Classical preprocessing (parameter computation, etc.)
Single quantum segment (REQUIRED)
[Optional] Expval segment OR classical postprocessing
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(),
) -> NoneAttributes¶
abi: ProgramABIboundaries: list[HybridBoundary]parameters: dict[str, Value]steps: list[ProgramStep]
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,
) -> NoneAttributes¶
kind: SegmentKindnum_qubits: intqubit_values: list[Value]
QuantumStep [source]¶
class QuantumStepA quantum execution step.
Constructor¶
def __init__(self, segment: QuantumSegment) -> NoneAttributes¶
segment: QuantumSegment
Segment [source]¶
class Segment(ABC)Base class for separated computation segments.
Constructor¶
def __init__(
self,
operations: list[Operation] = list(),
input_refs: list[str] = list(),
output_refs: list[str] = list(),
) -> NoneAttributes¶
input_refs: list[str]kind: SegmentKind Return the kind of this segment.operations: list[Operation]output_refs: list[str]
SegmentKind [source]¶
class SegmentKind(Enum)Type of computation segment.
Attributes¶
CLASSICALEXPVALQUANTUM
SeparationError [source]¶
class SeparationError(QamomileCompileError)Error during quantum/classical separation.
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
qamomile.circuit.transpiler.target¶
Protocols for explicit target planning and lowering pipelines.
Overview¶
| Class | Description |
|---|---|
CompilationTarget | Define the contract implemented by every compilation target. |
CompiledProgram | Package an artifact with its ABI, diagnostics, and provenance. |
PreparedModule | Hold a prepared entrypoint and its reachable callable definitions. |
Classes¶
CompilationTarget [source]¶
class CompilationTarget(Protocol[PlanT, ArtifactT])Define the contract implemented by every compilation target.
Attributes¶
name: str Return the stable target name.
Methods¶
compile¶
def compile(self, program: PreparedModule, plan: PlanT) -> CompiledProgram[ArtifactT]Lower and materialize a prepared program for this target.
Parameters:
| Name | Type | Description |
|---|---|---|
program | PreparedModule | Prepared semantic program. |
plan | PlanT | Decisions returned by :meth:plan. |
Returns:
CompiledProgram[ArtifactT] — CompiledProgram[ArtifactT]: Target-native artifact and metadata.
plan¶
def plan(self, program: PreparedModule) -> PlanTChoose target-specific lowering decisions for a program.
Parameters:
| Name | Type | Description |
|---|---|---|
program | PreparedModule | Prepared semantic program. |
Returns:
PlanT — Immutable target-specific compilation plan.
validate¶
def validate(self, artifact: ArtifactT) -> NoneValidate a materialized artifact with target-native rules.
Parameters:
| Name | Type | Description |
|---|---|---|
artifact | ArtifactT | Target-native artifact to validate. |
Raises:
Exception— If target-native validation rejects the artifact.
CompiledProgram [source]¶
class CompiledProgram(Generic[ArtifactT])Package an artifact with its ABI, diagnostics, and provenance.
Parameters:
| Name | Type | Description |
|---|---|---|
artifact | ArtifactT | Target-native circuit, graph, module, or package. |
abi | ProgramABI | Runtime-visible input and output contract. |
metadata | CompilationMetadata | Target and pipeline provenance. |
diagnostics | tuple[CompilationDiagnostic, ...] | Non-fatal compilation diagnostics. Defaults to an empty tuple. |
Constructor¶
def __init__(
self,
artifact: ArtifactT,
abi: ProgramABI,
metadata: CompilationMetadata,
diagnostics: tuple[CompilationDiagnostic, ...] = (),
) -> NoneAttributes¶
abi: ProgramABIartifact: ArtifactTdiagnostics: tuple[CompilationDiagnostic, ...]metadata: CompilationMetadata
PreparedModule [source]¶
class PreparedModuleHold a prepared entrypoint and its reachable callable definitions.
Parameters:
| Name | Type | Description |
|---|---|---|
entrypoint_ref | CallableRef | Stable symbol assigned to the program entrypoint. |
entrypoint | Block | Hierarchical semantic block for the entrypoint. |
definitions | Mapping[CallableRef, CallableDef] | Reachable callable definitions keyed by their stable symbols. |
definition_variants | Mapping[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_graph | Mapping[CallableRef, frozenset[CallableRef]] | Directed caller-to-callee relation, including the entrypoint symbol. |
abi | ProgramABI | Classical public input and output contract. |
bindings | Mapping[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],
) -> NoneAttributes¶
abi: ProgramABIbindings: Mapping[str, Any]call_graph: Mapping[CallableRef, frozenset[CallableRef]]definition_variants: Mapping[CallableRef, tuple[CallableDef, ...]]definitions: Mapping[CallableRef, CallableDef]entrypoint: Blockentrypoint_ref: CallableRef
Methods¶
body¶
def body(self, ref: CallableRef) -> BlockReturn the semantic body associated with a program symbol.
Parameters:
| Name | Type | Description |
|---|---|---|
ref | CallableRef | Entrypoint or callable symbol to resolve. |
Returns:
Block — Hierarchical semantic body for ref.
Raises:
KeyError— Ifrefis neither the entrypoint nor a reachable body-backed callable definition.
owned_snapshot¶
def owned_snapshot(self) -> PreparedModuleCreate a deep, target-owned snapshot of prepared semantics.
The semantic IR intentionally remains mutable while compiler passes are being developed. Copying the entrypoint and definition registry as one object graph preserves shared callable bodies while preventing one target from mutating the source module observed by another.
Returns:
PreparedModule — Deep snapshot with read-only definition and call
graph registries.
qamomile.circuit.transpiler.transpiler¶
Base transpiler class for engine-specific compilation.
Overview¶
| Function | Description |
|---|---|
count_inline_invokes | Count all inlineable calls reachable from an operation list. |
count_unrollable_inline_invokes | Count inlineable calls the inline/partial-eval loop can still resolve. |
lower_compile_time_ifs_preserving_loop_conditions | Specialize compile-time branches without erasing loop conditions. |
validate_bindings_parameters_disjoint | Enforce the project rule that bindings and parameters are disjoint. |
validate_circuit_shot_context | Reject shot context only in reachable circuit-family bodies. |
without_static_bindings | Remove compile-time object bindings already consumed by qkernel build. |
| Class | Description |
|---|---|
AffineValidationPass | Validate affine type semantics at IR level. |
AnalyzePass | Analyze and validate an affine block. |
ArrayBoundsValidationPass | Reject reachable element accesses and views outside array bounds. |
Block | Unified block representation for all pipeline stages. |
BlockKind | Classification of block structure for pipeline stages. |
CompileTimeIfLoweringPass | Lowers compile-time resolvable IfOperations before separation. |
ConstantFoldingPass | Evaluates constant expressions at compile time. |
EmitPass | Base class for engine-specific emission passes. |
ExecutableProgram | A fully compiled program ready for execution. |
FrontendTransformError | Error during frontend AST-to-builder lowering. |
InlinePass | Inline qkernel callables to create an affine block. |
ParameterShapeResolutionPass | Substitute symbolic parameter array shape dims with concrete constants. |
PartialEvaluationPass | Fold constants and lower compile-time control flow. |
PreparedModule | Hold a prepared entrypoint and its reachable callable definitions. |
ProgramPlan | Execution plan for a hybrid quantum/classical program. |
QKernelLike | Describe the frontend surface required by compiler entrypoints. |
QamomileCompileError | Base class for all Qamomile compilation errors. |
QamomileCompiler | Prepare Qamomile semantics and dispatch explicit target compilation. |
SegmentationPass | Segment a block into a strategy-specific executable program plan. |
SliceBorrowCheckPass | Post-fold linearity checker for sliced views and borrow state. |
SubstitutionPass | Pass that substitutes call operations and callable strategies. |
SymbolicShapeValidationPass | Reject unresolvable values that determine emitted circuit structure. |
Transpiler | Base class for engine-specific transpilers. |
Constants¶
TranspilerConfig=CompilerConfigBackward name for :class:CompilerConfigduring engine migration.
Functions¶
count_inline_invokes [source]¶
def count_inline_invokes(operations: list[Operation]) -> intCount all inlineable calls reachable from an operation list.
Recurses into InverseBlockOperation / ControlledUOperation /
SelectOperation nested blocks and into HasNestedOps bodies, so
calls hidden inside control flow or operation-owned blocks are counted.
unroll_recursion uses this as the primary termination signal
(count == 0 means the block is fully inlined).
Parameters:
| Name | Type | Description |
|---|---|---|
operations | list[Operation] | Operations to scan. |
Returns:
int — Total number of inlineable calls reachable from operations.
count_unrollable_inline_invokes [source]¶
def count_unrollable_inline_invokes(operations: list[Operation]) -> intCount inlineable calls the inline/partial-eval loop can still resolve.
This mirrors :func:count_inline_invokes but does not descend into
a ControlledUOperation.block, an InverseBlockOperation’s nested
blocks, or a SelectOperation case block. A call still inside one of
those operation-owned blocks after a full inline pass is a
self-recursive call that inline’s cycle guard could not unroll — it stops
after one layer and does not re-enter the operation-owned block — so no
later unroll_recursion iteration can resolve it. Folding compile-time
ifs there never removes the trapped call itself. Such a call is
therefore not unrollable. Calls at the top level or inside For /
If / While bodies are unrollable and are counted.
The unroll loop uses this to tell two failure modes apart: a non-zero
:func:count_inline_invokes with a zero count_unrollable_inline_invokes
means every residual call is trapped inside a controlled / inverted
block (i.e. a recursive qkernel was passed to qmc.control /
qmc.inverse), as opposed to a genuinely non-terminating top-level
recursion.
Parameters:
| Name | Type | Description |
|---|---|---|
operations | list[Operation] | Operations to scan. |
Returns:
int — Number of inlineable calls reachable without entering a
ControlledUOperation.block, InverseBlockOperation nested
block, or SelectOperation case block.
lower_compile_time_ifs_preserving_loop_conditions [source]¶
def lower_compile_time_ifs_preserving_loop_conditions(block: Block, bindings: dict[str, Any] | None = None) -> BlockSpecialize compile-time branches without erasing loop conditions.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Block whose resolvable compile-time branches should be lowered. |
bindings | dict[str, Any] | None | Compile-time input bindings used for condition resolution. Defaults to None. |
Returns:
Block — Specialized block with loop-carried conditions preserved.
Raises:
ValidationError— If specialization encounters invalid IR.
validate_bindings_parameters_disjoint [source]¶
def validate_bindings_parameters_disjoint(bindings: dict[str, Any] | None, parameters: list[str] | None) -> NoneEnforce 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:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Compile-time bindings keyed by argument name, or None. None is treated as empty. |
parameters | list[str] | None | Argument names to keep as runtime parameters, or None. None is treated as empty. |
Returns:
None — None
Raises:
ValueError— If any name appears in bothbindingsandparameters.
Example:
>>> validate_bindings_parameters_disjoint({"theta": 0.5}, ["phi"])
>>> validate_bindings_parameters_disjoint({"theta": 0.5}, ["theta"])
Traceback (most recent call last):
...
ValueError: Parameter name(s) ['theta'] appear in both ...validate_circuit_shot_context [source]¶
def validate_circuit_shot_context(block: Block, bindings: dict[str, Any] | None, *, target: str) -> NoneReject shot context only in reachable circuit-family bodies.
Circuit lowering selects engine-generic callable decompositions using
the circuit_ir selector. Backend-specific alternatives are metadata
for other consumers and must not impose their capabilities here.
Specialize operation-owned bodies in their own parameter scope before
inspecting them, just as the entrypoint is inspected after pruning.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Partially evaluated circuit entrypoint. |
bindings | dict[str, Any] | None | Compile-time entrypoint bindings. |
target | str | Target name used in capability errors. |
Raises:
TargetCapabilityError— If a reachable selected body reads the shot.ValidationError— If nested compile-time specialization is invalid.ValueError— If a selected callable body violates its call contract.
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:
| Name | Type | Description |
|---|---|---|
input_types | Mapping[str, Any] | QKernel input annotations by name. |
bindings | Mapping[str, Any] | None | User-provided compile-time values. |
Returns:
dict[str, Any] — dict[str, Any]: Ordinary scalar, array, and structural bindings only.
Classes¶
AffineValidationPass [source]¶
class AffineValidationPass(Pass[Block, Block])Validate affine type semantics at IR level.
This pass serves as a safety net to catch affine type violations
that may have bypassed the frontend checks. It verifies that each
quantum value is used (consumed) at most once. It does NOT detect
“never consumed” / silent-discard patterns; the branch-internal and
loop-body discard cases are rejected separately by
reject_control_flow_quantum_discard in
qamomile.circuit.transpiler.passes.analyze.
Input: Block (any kind) Output: Same Block (unchanged, validation only)
Attributes¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockValidate affine type semantics in the block.
Raises:
ValidationError— If the block kind is not AFFINE.AffineTypeError— If a quantum value is consumed multiple times.
AnalyzePass [source]¶
class AnalyzePass(Pass[Block, Block])Analyze and validate an affine block.
This pass:
Builds a dependency graph between values (used locally for validation)
Validates that quantum ops don’t depend on non-parameter classical results
Checks that block inputs/outputs are classical
Input: Block with BlockKind.AFFINE Output: Block with BlockKind.ANALYZED
Attributes¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockAnalyze the block and validate dependencies.
ArrayBoundsValidationPass [source]¶
class ArrayBoundsValidationPass(Pass[Block, Block])Reject reachable element accesses and views outside array bounds.
This pass runs after partial evaluation has resolved binding-dependent
slice extents and before declarative slice operations are stripped. It
deliberately skips statically zero-trip loop bodies so an unreachable
access does not become a false-positive compilation error. Exact loop
replay is capped by MAX_STATIC_REPLAY_TRIPS; the conservative fallback
validates one reachable body instance, including first-iteration constants
when available, and never publishes speculative final results.
Attributes¶
name: str Return the stable pass identifier.
Methods¶
run¶
def run(self, input: Block) -> BlockValidate reachable array element operands in one semantic block.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Post-partial-evaluation affine or hierarchical block whose concrete array extents should be checked. |
Returns:
Block — input unchanged when every reachable access and view is
valid or still symbolic.
Raises:
ValidationError— Ifinputhas an unsupported block kind, a reachable constant index is outside a resolved array extent, or a concrete view descriptor exceeds its physical root.
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
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:
Evaluates conditions including expression-derived ones (
CompOp,CondOp,NotOp,BinOp, andUnaryMathOpchains).Replaces resolved
IfOperations with selected-branch operations.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:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Compile-time bindings visible in the current block. Defaults to no bindings. |
preserved_condition_uuids | AbstractSet[str] | None | Conditions that must remain unresolved so a later validation pass can inspect their dataflow. Defaults to an empty set. |
_under_controlled_unitary | bool | Internal 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_ids | frozenset[int] | None | Internal recursion-path guard for operation-owned blocks. Defaults to an empty set. |
Attributes¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockLower every compile-time resolvable IfOperation in the block.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Block 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:
ValidationError— Ifinput.kindisANALYZED(the pass must run before dependency analysis commits to a representation), or if a compile-time branch selects a symbolic-bound slice-view cast source whose root index space is not resolvable.
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 splitConstructor¶
def __init__(self, bindings: dict[str, Any] | None = None, *, strip_slice_ops: bool = True)Create a constant-folding pass.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Compile-time parameter bindings used when folding BinOps that reference declared parameters. |
strip_slice_ops | bool | When 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¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockFold resolvable classical values throughout a block.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Affine or hierarchical block to rewrite. |
Returns:
Block — Copy with folded operations and output values.
Raises:
ValidationError— If the block is neither affine nor hierarchical.
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:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Values to bind parameters to. If not provided, parameters must be bound at execution time. |
parameters | list[str] | None | List of parameter names to preserve as engine parameters. |
Raises:
ValueError— If a name appears in bothbindingsandparameters. This is the innermost emit-side choke point: it catches the overlap even when anEmitPassis constructed directly (e.g. viaTranspiler._create_emit_pass), bypassing thetranspile/emitwrappers. A name in both is ambiguous and would otherwise silently bake the binding while dropping the runtime parameter (see #354).
Attributes¶
bindingsname: strparameters
Methods¶
run¶
def run(self, input: ProgramPlan) -> ExecutableProgram[T]Emit engine code from a program plan.
Parameters:
| Name | Type | Description |
|---|---|---|
input | ProgramPlan | Segmented 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:
EmitError— If expectation-value evaluation is combined with a measurement, projection, or reset operation, or if a planned segment cannot be emitted.
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 typeConstructor¶
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(),
) -> NoneAttributes¶
compiled_classical: list[CompiledClassicalSegment]compiled_expval: list[CompiledExpvalSegment]compiled_quantum: list[CompiledQuantumSegment[T]]has_parameters: bool Check if this program has unbound parameters.output_values: list[ValueLike]parameter_names: list[str] Get list of parameter names that need binding.plan: ProgramPlan | Nonequantum_circuit: T Get the single quantum circuit.
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 | NoneGet 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] | ExpvalJobRestore 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:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine adapter configured with the provider credentials and target used by the original job. |
snapshot | JobSnapshot | Snapshot returned by the original public job’s snapshot() method. |
bindings | dict[str, Any] | None | Original 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:
ExecutionError— If the snapshot operation or execution shape does not match this executable program.NotImplementedError— If the executor cannot restore the referenced provider execution.ValueError— If required bindings are missing or invalid.
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] | ExpvalJobSubmit one execution and return its lazy result job.
Parameters:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine-specific quantum executor. |
bindings | dict[str, Any] | None | Parameter 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} |
estimation | EstimationAccuracy | None | Optional 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:
ExecutionError— If no quantum circuit to executeValueError— If required parameters are missing
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:
| Name | Type | Description |
|---|---|---|
executor | QuantumExecutor[T] | Engine-specific quantum executor. |
shots | int | Number of shots to run. |
bindings | dict[str, Any] | None | Parameter 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:
ExecutionError— If no quantum circuit to executeValueError— If required parameters are missing
Example:
job = executable.sample(executor, shots=1000, bindings={"gamma": [0.5]})
result = job.result()
print(result.results) # [(0.25, 500), (0.75, 500)]FrontendTransformError [source]¶
class FrontendTransformError(QamomileCompileError)Error during frontend AST-to-builder lowering.
InlinePass [source]¶
class InlinePass(Pass[Block, Block])Inline qkernel callables to create an affine block.
This pass recursively inlines function calls while preserving control flow structures (For, If, While).
Input: Block with BlockKind.HIERARCHICAL (may contain callable calls) Output: Block with BlockKind.AFFINE (no inline callable calls)
Parameters:
| Name | Type | Description |
|---|---|---|
body_selector | Callable[[InvokeOperation], Block | None] | None | Optional body-selection hook for consumers whose configured strategy differs from InvokeOperation.strategy_name. The standard compiler leaves this unset. Defaults to None. |
preserve_bound_quantum_identity | bool | Whether cloned callee quantum values should retain the logical owner and array-element address of their bound caller operands. Resource liveness analysis enables this so an inline call does not create phantom owners or erase lane identities. Defaults to False. |
preserve_bound_array_identity | bool | Whether cloned callee array values should retain the logical lineage of bound caller arrays. Resource classical-state analysis enables this so loop-carried stores remain connected across an inlined call. Defaults to False. |
Constructor¶
def __init__(
self,
body_selector: Callable[[InvokeOperation], Block | None] | None = None,
*,
inline_prefix_factory: Callable[[InvokeOperation, tuple[tuple[ArrayValue, tuple[ArrayValue, ...]], ...]], Sequence[Operation]] | None = None,
preserve_bound_quantum_identity: bool = False,
preserve_bound_array_identity: bool = False,
) -> NoneInitialize the pass with body-selection and identity policies.
Parameters:
| Name | Type | Description |
|---|---|---|
body_selector | Callable[[InvokeOperation], Block | None] | None | Consumer-specific selector used for inline-policy calls. Defaults to the invocation’s ordinary effective body. |
preserve_bound_quantum_identity | bool | Whether cloned quantum SSA values descending from a formal input retain the actual caller operand’s logical owner and array-element address. Defaults to False. |
preserve_bound_array_identity | bool | Whether cloned array SSA values descending from a formal input retain the actual caller array’s logical lineage. Defaults to False. |
Attributes¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockInline all inline-policy callable invocations.
Self-recursive qkernel invocations are unrolled one level per call:
the inner self-call is substituted but left intact so the outer
fixed-point loop can fold the base-case if between iterations.
The output kind is AFFINE when no inlineable calls remain,
otherwise HIERARCHICAL.
ParameterShapeResolutionPass [source]¶
class ParameterShapeResolutionPass(Pass[Block, Block])Substitute symbolic parameter array shape dims with concrete constants.
Input: BlockKind.HIERARCHICAL (runs before InlinePass).
Output: same block kind, with matching shape dim Values constant-folded.
Constructor¶
def __init__(self, bindings: dict[str, Any] | None = None) -> NoneInitialize parameter-shape resolution.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Compile-time bindings keyed by entrypoint argument name. Defaults to None. |
Attributes¶
name: str Return the pass name.
Methods¶
run¶
def run(self, input: Block) -> BlockReplace resolvable symbolic array dimensions with constants.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Hierarchical semantic block to rewrite. |
Returns:
Block — Rewritten block preserving all display, ABI, parameter, and
stage metadata.
Raises:
ValidationError— Ifinputis not hierarchical.
PartialEvaluationPass [source]¶
class PartialEvaluationPass(Pass[Block, Block])Fold constants and lower compile-time control flow.
Constructor¶
def __init__(self, bindings: dict[str, Any] | None = None)Attributes¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockFold constants and lower compile-time control flow.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Block to evaluate. AFFINE in the normal pipeline; HIERARCHICAL is also accepted for the self-recursion unroll loop (see inline comment). |
Returns:
Block — Block with constants folded and compile-time-resolvable
IfOperations lowered.
Raises:
ValidationError— If the block kind is notAFFINE/HIERARCHICAL, or if one of the classical pre-fold rejection checks fires (a classical element store inside a loop reads an element of the array it writes, or a loop body rebinds a classical scalar whose pre-loop value it still reads).QubitRebindError— If a runtime if branch or a loop body rebinds a quantum variable to a different quantum value — a fresh allocation or another existing register — in a shape the control-flow discard check cannot prove safe (seereject_control_flow_quantum_discard).
PreparedModule [source]¶
class PreparedModuleHold a prepared entrypoint and its reachable callable definitions.
Parameters:
| Name | Type | Description |
|---|---|---|
entrypoint_ref | CallableRef | Stable symbol assigned to the program entrypoint. |
entrypoint | Block | Hierarchical semantic block for the entrypoint. |
definitions | Mapping[CallableRef, CallableDef] | Reachable callable definitions keyed by their stable symbols. |
definition_variants | Mapping[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_graph | Mapping[CallableRef, frozenset[CallableRef]] | Directed caller-to-callee relation, including the entrypoint symbol. |
abi | ProgramABI | Classical public input and output contract. |
bindings | Mapping[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],
) -> NoneAttributes¶
abi: ProgramABIbindings: Mapping[str, Any]call_graph: Mapping[CallableRef, frozenset[CallableRef]]definition_variants: Mapping[CallableRef, tuple[CallableDef, ...]]definitions: Mapping[CallableRef, CallableDef]entrypoint: Blockentrypoint_ref: CallableRef
Methods¶
body¶
def body(self, ref: CallableRef) -> BlockReturn the semantic body associated with a program symbol.
Parameters:
| Name | Type | Description |
|---|---|---|
ref | CallableRef | Entrypoint or callable symbol to resolve. |
Returns:
Block — Hierarchical semantic body for ref.
Raises:
KeyError— Ifrefis neither the entrypoint nor a reachable body-backed callable definition.
owned_snapshot¶
def owned_snapshot(self) -> PreparedModuleCreate a deep, target-owned snapshot of prepared semantics.
The semantic IR intentionally remains mutable while compiler passes are being developed. Copying the entrypoint and definition registry as one object graph preserves shared callable bodies while preventing one target from mutating the source module observed by another.
Returns:
PreparedModule — Deep snapshot with read-only definition and call
graph registries.
ProgramPlan [source]¶
class ProgramPlanExecution plan for a hybrid quantum/classical program.
Structure:
[Optional] Classical preprocessing (parameter computation, etc.)
Single quantum segment (REQUIRED)
[Optional] Expval segment OR classical postprocessing
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(),
) -> NoneAttributes¶
abi: ProgramABIboundaries: list[HybridBoundary]parameters: dict[str, Value]steps: list[ProgramStep]
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¶
block: Block Return the cached hierarchical body block.effects: KernelEffect Return cached semantic effects of the qkernel body.input_types: dict[str, Any] Return frontend input annotations by parameter name.name: str Return the user-facing callable name.output_types: list[Any] Return frontend output annotations.signature: inspect.Signature Return the Python call signature.
Methods¶
build¶
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> BlockBuild a traced body block.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | list[str] | None | Runtime parameter names to preserve. Defaults to None. |
**kwargs | Any | Compile-time bindings for non-parameter arguments. |
Returns:
Block — Traced hierarchical body block.
QamomileCompileError [source]¶
class QamomileCompileError(Exception)Base class for all Qamomile compilation errors.
QamomileCompiler [source]¶
class QamomileCompilerPrepare Qamomile semantics and dispatch explicit target compilation.
Parameters:
| Name | Type | Description |
|---|---|---|
config | CompilerConfig | None | Shared frontend and substitution configuration. Defaults to :class:CompilerConfig. |
Constructor¶
def __init__(self, config: CompilerConfig | None = None) -> NoneInitialize the target-neutral compiler.
Parameters:
| Name | Type | Description |
|---|---|---|
config | CompilerConfig | None | Shared frontend configuration. Defaults to :class:CompilerConfig. |
Attributes¶
config
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:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | Top-level qkernel-like entrypoint. |
target | CompilationTarget[PlanT, ArtifactT] | Target planner, lowerer, materializer, and validator. |
bindings | dict[str, Any] | None | Compile-time bindings. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
Returns:
CompiledProgram[ArtifactT] — CompiledProgram[ArtifactT]: Validated target-native artifact.
Raises:
Exception— If semantic preparation, target compilation, or target-native validation fails.
prepare¶
def prepare(
self,
kernel: QKernelLike,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> PreparedModulePrepare a hierarchical semantic module without destroying calls.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | Top-level qkernel-like entrypoint. |
bindings | dict[str, Any] | None | Compile-time bindings used for tracing and shape resolution. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
Returns:
PreparedModule — Program-level semantic input for target planning.
Raises:
ValueError— If bindings overlap runtime parameters.EntrypointValidationError— If the top-level kernel has quantum inputs or outputs.
to_block¶
def to_block(
self,
kernel: QKernelLike,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> BlockTrace a qkernel-like object into a hierarchical semantic block.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | Frontend object to trace. |
bindings | dict[str, Any] | None | Compile-time argument values. Defaults to None. |
parameters | list[str] | None | Argument names retained as runtime parameters. Defaults to None. |
Returns:
Block — Hierarchical Qamomile semantic block.
Raises:
ValueError— Ifbindingsandparametersoverlap or frontend argument construction fails.TypeError— If specialization is requested for a block-only qkernel-like object that has nobuildmethod.
SegmentationPass [source]¶
class SegmentationPass(Pass[Block, ProgramPlan])Segment a block into a strategy-specific executable program plan.
This pass:
Materializes return operations (syncs output_values from ReturnOperation)
Splits the operation list into quantum and classical segments
Builds a ProgramPlan via the configured segmentation strategy
Input: Block (typically ANALYZED or AFFINE) Output: ProgramPlan
Constructor¶
def __init__(self, strategy: SegmentationStrategy | None = None) -> NoneAttributes¶
name: str
Methods¶
run¶
def run(self, input: Block) -> ProgramPlanLower and segment a block into a program plan.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Block whose while contract and hybrid operations should be lowered before segmentation. |
Returns:
ProgramPlan — Strategy-produced execution plan.
Raises:
ValidationError— If a runtime while violates its contract.SeparationError— If the strategy finds no quantum segment.MultipleQuantumSegmentsError— If the strategy finds multiple quantum segments.
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) -> NoneInitialize per-run mutable state to safe defaults.
Attributes¶
name: str Return the pass identifier for tracing/logging.
Methods¶
run¶
def run(self, input: Block) -> BlockRun the borrow tracker over input.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Block 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:
ValidationError— If called on an unexpected block kind or slice ownership cannot be propagated safely across a control-flow boundary.QubitBorrowConflictError— If a slice view and a direct access collide or two live views may overlap.QubitConsumedError— If an operand accesses a destroyed slot or a stale slice version attempts to replace its live successor.
SubstitutionPass [source]¶
class SubstitutionPass(Pass[Block, Block])Pass that substitutes call operations and callable strategies.
This pass traverses the block and applies substitution rules:
For inline InvokeOperation: replaces the callable body with the target
For boxed InvokeOperation: sets the strategy field
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) -> NoneInitialize the pass with configuration.
Parameters:
| Name | Type | Description |
|---|---|---|
config | SubstitutionConfig | Substitution configuration with rules |
Attributes¶
name: str Return pass name.
Methods¶
run¶
def run(self, input: Block) -> BlockApply substitutions to the block.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | Block to transform |
Returns:
Block — Block with substitutions applied
SymbolicShapeValidationPass [source]¶
class SymbolicShapeValidationPass(Pass[Block, Block])Reject unresolvable values that determine emitted circuit structure.
Runs two checks on every ForOperation bound, symbolic SELECT index
width, and symbolic controlled-unitary structural field, walking nested
control flow and operation-owned SELECT/control blocks recursively:
Unresolved parameter array shape dims, recognized by the
{array}_dim{i}naming convention.Bounds whose dataflow traces back to a runtime parameter (an entry of
Block.parameters), directly or through classical arithmetic. Dependencies on enclosing loop variables are exempt — those resolve during emit-time unrolling.
Input: BlockKind.ANALYZED (runs after AnalyzePass).
Output: same block unchanged, or raises QamomileCompileError.
Attributes¶
name: str Return the pass name used in pipeline diagnostics.
Methods¶
run¶
def run(self, input: Block) -> BlockValidate compile-time structure throughout the analyzed block.
Checks loop bounds, SELECT widths, and controlled-unitary structural fields at top level, in ordinary control-flow bodies, and in operation-owned SELECT/control blocks.
Parameters:
| Name | Type | Description |
|---|---|---|
input | Block | The block to validate. Must be BlockKind.ANALYZED; other kinds pass through unchanged (the pass is defensive and avoids false positives on partially-built IR). |
Returns:
Block — input, unchanged, when validation succeeds.
Raises:
QamomileCompileError— If any checked structural value is an unresolved parameter shape dim or depends on a runtime parameter.
Transpiler [source]¶
class Transpiler(ABC, Generic[T])Base class for engine-specific transpilers.
Provides the full compilation pipeline from qkernel-like frontend objects to executable programs.
Example:
>>> from qamomile.circuit.transpiler import TranspilerConfig
>>> from qamomile.qiskit import QiskitTranspiler
>>> transpiler = QiskitTranspiler()
>>> executable = transpiler.transpile(kernel, bindings={"theta": 0.5})
>>> circuit = executable.get_first_circuit()
>>> config = TranspilerConfig.with_strategies({"qft": "approximate_k2"})
>>> transpiler.set_config(config)Attributes¶
MAX_UNROLL_DEPTH: intconfig: TranspilerConfig Get the transpiler configuration.
Methods¶
affine_validate¶
def affine_validate(self, block: Block) -> BlockPass 1.5: Validate affine type semantics.
This is a safety net to catch affine type violations that may have bypassed frontend checks. Validates that quantum values are used at most once.
analyze¶
def analyze(self, block: Block) -> BlockPass 2: Validate and analyze dependencies.
array_bounds_check¶
def array_bounds_check(self, block: Block) -> BlockPass 1.85: Reject reachable accesses outside resolved array bounds.
Runs after :meth:partial_eval so binding-dependent view extents and
indices are concrete where possible, and before declarative slice
operations are stripped. Statically zero-trip loop bodies are skipped
because their element accesses are unreachable.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Post-fold affine or hierarchical block to validate. |
Returns:
Block — The input block unchanged after successful validation.
Raises:
ValidationError— If a reachable constant element index is outside a resolved root-array or view-local extent.
classical_lowering¶
def classical_lowering(self, block: Block) -> BlockPass 2.25: Lower measurement-derived classical ops.
Identifies CompOp / CondOp / NotOp / BinOp
instances whose operand dataflow traces back to a measurement and
rewrites them to RuntimeClassicalExpr. Compile-time-foldable
and emit-time-foldable (loop-bound, parameter-bound) classical
ops are left unchanged.
Runs after analyze so the measurement-taint analysis has the
full dependency graph available, and before
validate_symbolic_shapes / plan / emit so downstream
passes can rely on the cleaner IR (in particular: future
segmentation work can dispatch on RuntimeClassicalExpr type
instead of the BitType-only heuristic).
constant_fold¶
def constant_fold(self, block: Block, bindings: dict[str, Any] | None = None) -> BlockPass 1.5: Fold constant expressions.
Evaluates BinOp operations when all operands are constants
or bound parameters. This prevents quantum segment splitting
from parametric expressions like phase * 2.
emit¶
def emit(
self,
separated: ProgramPlan,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> ExecutableProgram[T]Pass 4: Generate engine-specific code.
Parameters:
| Name | Type | Description |
|---|---|---|
separated | ProgramPlan | The separated program to emit |
bindings | dict[str, Any] | None | Parameter values to bind at compile time |
parameters | list[str] | None | Parameter names to preserve as engine parameters |
Raises:
ValueError— If a name appears in bothbindingsandparameters. This check also runs intranspileandto_block/build, butemitis a public step-by-step entry point that bypasses those, so the guard is repeated here to prevent a name from being silently baked in (its runtime parameter dropped) when the step-by-step API is driven directly.
executor¶
def executor(self, **kwargs: Any = {}) -> QuantumExecutor[T]Create a quantum executor for this engine.
inline¶
def inline(self, block: Block) -> BlockPass 1: Inline all inline-policy callable invocations.
lower_compile_time_ifs¶
def lower_compile_time_ifs(self, block: Block, bindings: dict[str, Any] | None = None) -> BlockPass 1.75: Lower compile-time resolvable IfOperations.
Evaluates IfOperation conditions (including expression-derived conditions via CompOp/CondOp/NotOp) and replaces resolved ones with selected-branch operations. Merge outputs are substituted with selected-branch values throughout the block.
This prevents SegmentationPass from seeing classical-only compile-time IfOperations that would otherwise split quantum segments.
partial_eval¶
def partial_eval(self, block: Block, bindings: dict[str, Any] | None = None) -> BlockPass 1.75: Fold constants and lower compile-time control flow.
plan¶
def plan(self, block: Block) -> ProgramPlanPass 3: Lower and split into a program plan.
Validates C→Q→C pattern with single quantum segment.
plan_circuit¶
def plan_circuit(
self,
prepared: PreparedModule,
bindings: dict[str, Any] | None = None,
) -> ProgramPlanLower a prepared semantic module into the circuit execution model.
This is the destructive circuit-family path: inline-policy calls are
flattened, compile-time structure is evaluated, affine and borrow
invariants are checked, measurement-dependent classical expressions
are classified, and the result is segmented into C-to-Q-to-C steps.
Program-graph targets must compile :class:PreparedModule directly
instead of invoking this method.
Parameters:
| Name | Type | Description |
|---|---|---|
prepared | PreparedModule | Hierarchical semantic program returned by :meth:prepare. |
bindings | dict[str, Any] | None | Compile-time bindings used for recursion unrolling and partial evaluation. Defaults to None. |
Returns:
ProgramPlan — Circuit-family host-orchestrated execution plan.
Raises:
QamomileCompileError— If validation, partial evaluation, or segmentation rejects the program.
prepare¶
def prepare(
self,
kernel: QKernelLike,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> PreparedModulePrepare a qkernel for target-specific planning and lowering.
This phase preserves callable boundaries. It performs tracing, entrypoint validation, configured substitutions, and parameter-shape resolution, then collects the reachable callable graph into a program-level semantic view.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | QKernel or qkernel-like frontend object to prepare as a top-level entrypoint. |
bindings | dict[str, Any] | None | Compile-time values used while tracing and resolving parameter shapes. Defaults to None. |
parameters | list[str] | None | Argument names preserved as runtime parameters. Defaults to None. |
Returns:
PreparedModule — Hierarchical entrypoint, reachable callables,
call graph, and public ABI.
Raises:
ValueError— If a name appears in bothbindingsandparameters.EntrypointValidationError— If the top-level kernel uses quantum inputs or outputs.
resolve_parameter_shapes¶
def resolve_parameter_shapes(self, block: Block, bindings: dict[str, Any] | None = None) -> BlockPass 0.75: Resolve symbolic Vector parameter shape dims.
Qamomile circuits are compile-time fixed-structure. Parameter
Vector[Float] / Vector[UInt] inputs carry symbolic
{name}_dim{i} shape Values so frontend code like
arr.shape[0] returns a usable handle. This pass looks at
bindings and, for every parameter array that has a concrete
binding, substitutes those symbolic dims with constants so that
downstream loop-bound resolution sees fixed lengths.
Parameters without a concrete binding are left as-is; their symbolic dims are harmless as long as no compile-time structure decision depends on them (the library QAOA pattern).
set_config¶
def set_config(self, config: TranspilerConfig) -> NoneSet the transpiler configuration.
Parameters:
| Name | Type | Description |
|---|---|---|
config | TranspilerConfig | Transpiler configuration to use |
slice_borrow_check¶
def slice_borrow_check(self, block: Block) -> BlockPass 1.9: Post-fold slice-view linearity checker.
Runs after :meth:partial_eval has resolved slice bounds to
concrete values. Catches the slice-view linearity violations
that the trace-time frontend check cannot detect on its own —
specifically, slices whose bounds were symbolic at trace
time (so the frontend bulk-borrow tracker had to skip them)
and aliasing scenarios that only become visible once those
bounds are folded to constants:
A view whose newly-concrete coverage overlaps another live view of the same root parent.
A view whose newly-concrete coverage hits a slot that was consumed by a destructive operation earlier in the block.
Slice ownership changes that cannot be represented safely across control-flow boundaries.
Creating a direct element borrow (q[i]) emits no IR operation,
so this pass cannot observe the borrow site itself. Later uses of
that element do appear as operation operands and are checked for
conflicts with live slice views. Trace-time validation in
:func:qamomile.circuit.frontend.func_to_block._validate_returned_arrays
covers unreturned direct-element borrows that have no observable
operand use.
The pass is a pass-through for the IR — it only raises on violations and leaves the block unchanged on success.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Post-fold affine or hierarchical block to validate. |
Returns:
Block — The input block unchanged after successful validation.
Raises:
QubitBorrowConflictError— If live slice ownership conflicts with another view or direct access.QubitConsumedError— If a slice or operand accesses a slot already destroyed by a destructive operation.ValidationError— If the block kind is invalid or ownership cannot be propagated safely through control flow.
strip_slice_ops¶
def strip_slice_ops(self, block: Block) -> BlockPass 1.95: Remove SliceArrayOperation nodes from the block.
PartialEvaluationPass keeps these declarative ops through
constant folding so :meth:slice_borrow_check can use them
as view-declaration markers. Once the linearity check has run,
segmentation and downstream passes expect a classical-op-free
quantum stream — this pass performs that cleanup.
substitute¶
def substitute(self, block: Block) -> BlockPass 0.5: Apply substitutions (optional).
This pass rewrites inline callable targets and sets strategy names on boxed InvokeOperations based on config.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Block to transform |
Returns:
Block — Block with substitutions applied
to_block¶
def to_block(
self,
kernel: QKernelLike,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> BlockConvert a qkernel-like frontend object to a Block.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | QKernel or qkernel-like frontend object to convert. |
bindings | dict[str, Any] | None | Concrete values to bind at trace time, including values used to resolve array shapes. |
parameters | list[str] | None | Names to keep as unbound runtime parameters. |
Returns:
Block — Hierarchical block for the frontend object.
Raises:
ValueError— If a name appears in bothbindingsandparameters(propagated fromkernel.build), violating the bindings/parameters disjointness rule.
Always uses kernel.build() so Python defaults, required arguments,
runtime parameters, and array shapes follow one validated entry path.
to_circuit¶
def to_circuit(self, kernel: QKernelLike, bindings: dict[str, Any] | None = None) -> TCompile and extract just the quantum circuit.
This is a convenience method for when you just want the engine circuit without the full executable.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | QKernel or qkernel-like frontend object to compile. |
bindings | dict[str, Any] | None | Parameter values to bind. |
Returns:
T — Engine-specific quantum circuit.
transpile¶
def transpile(
self,
kernel: QKernelLike,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> ExecutableProgram[T]Full compilation pipeline from a qkernel-like object to executable.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | QKernel or qkernel-like frontend object to compile. |
bindings | dict[str, Any] | None | Parameter values to bind (also resolves array shapes). Names in bindings and parameters must be disjoint — a name is either compile-time bound or runtime symbolic, never both. |
parameters | list[str] | None | Parameter names to preserve as engine parameters. Scalars/arrays of float/int/UInt are supported, plus Dict[K, Float]: each constant-key subscript lookup (d[key]) becomes one engine parameter named "d[<key>]", and the execution-time binding bindings={"d": {...}} is decomposed per key onto those parameters. A Dict runtime parameter is recorded in Block.param_slots as a slot whose type is a DictType (compile-time-bound Dicts and Tuple arguments stay out of the slot manifest); its emitted per-key parameters are visible via ExecutableProgram.parameter_names. |
Returns:
ExecutableProgram[T] — ExecutableProgram[T]: Executable wrapping the engine circuit
and the parameter metadata needed to re-bind runtime
parameters, ready for execution.
Raises:
ValueError— If a name appears in bothbindingsandparameters. A name being in both is ambiguous (placeholder value vs runtime symbol) and used to silently miscompile control-flow predicates that depended on parameter-array elements; rejecting the overlap up front keeps the contract unambiguous.QamomileCompileError— If compilation fails (validation, dependency errors)
Pipeline:
prepare: Trace and validate the entrypoint, apply configured substitutions, resolve parameter shapes, and preserve the reachable callable graph.
plan_circuit: Inline inline-policy calls, unroll recursion, validate affine and borrow rules, partially evaluate compile-time structure, analyze dependencies, and segment the program into the host-orchestrated C-to-Q-to-C model.
lower: Convert each quantum segment to immutable, engine-neutral
CircuitProgramIR.legalize: Select native intrinsics and Pauli-evolution realizations from target capabilities and compilation policy.
verify: Prove circuit structure and target legality before constructing engine objects.
materialize: Convert the legalized circuit IR to engine-native artifacts and preserve the executable ABI.
unroll_recursion¶
def unroll_recursion(self, block: Block, bindings: dict[str, Any] | None = None) -> BlockFixed-point loop of inline and branch lowering for recursion.
Each iteration unrolls one layer of self-referential inline
callable invocation and then lowers its compile-time base-case
IfOperation. Loop-carried Bit conditions remain visible until the
final validation pass so first-iteration constants cannot erase a real
backedge read. Terminates when no
inline callable invocation remains (success), when every residual call
is trapped inside an operation-owned block whose recursive callable
contract is unsupported (control / inverse / select over a recursive
kernel — raises a targeted error, see below), or when
MAX_UNROLL_DEPTH is reached (genuinely non-terminating top-level
recursion — raises).
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | The block to unroll. May be HIERARCHICAL (still containing self-referential callable invocations) or already AFFINE (returned unchanged). |
bindings | dict[str, Any] | None | Compile-time bindings used by condition lowering to select the base case. Defaults to None, meaning no bindings are applied. |
Returns:
Block — The fully unrolled, AFFINE block once no
inline callable invocation remains. Returned unchanged when the
input already has no calls.
Raises:
FrontendTransformError— If every remaining inline callable invocation is trapped inside aControlledUOperation.block, anInverseBlockOperationblock, or aSelectOperation.case_blocksentry (a self-recursive kernel was passed toqmc.control,qmc.inverse, orqmc.select), or if a genuinely non-terminating top-level recursion does not converge withinMAX_UNROLL_DEPTHiterations. The two cases carry distinct, cause-specific messages.
validate_symbolic_shapes¶
def validate_symbolic_shapes(self, block: Block) -> BlockPass 2.5: Reject unresolvable ForOperation loop bounds.
Runs after analyze so dependency info is complete. Raises
QamomileCompileError with an actionable message when a
gamma_dim0-style symbolic Value reaches a ForOperation
bound without being folded to a constant by
ParameterShapeResolutionPass, or when a loop bound depends
(directly or through classical arithmetic) on a runtime
parameter — loop bounds are compile-time structure and must be
provided via bindings, not parameters.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | The analyzed block to validate. |
Returns:
Block — block, unchanged, when validation succeeds.
Raises:
QamomileCompileError— If a loop bound is an unresolved parameter shape dim or depends on a runtime parameter.
qamomile.circuit.transpiler.value_resolver¶
Unified value resolution for transpiler passes.
Several transpiler passes need to resolve an IR Value to a concrete
Python value (int, float, bool). Each pass previously carried its own
copy of the resolution logic with slightly different lookup orders and
naming conventions.
ValueResolver consolidates those into a single class with a
deterministic resolution order:
Context map — caller-supplied
UUID → concrete valuedict (e.g.folded_values,concrete_values).Container metadata — whole compile-time arrays and dictionaries.
Constant —
value.is_constant() → value.get_const().Compile-time array element —
arr[i]orarr[a:b][i]resolves from the root array’sconst_arraymetadata or binding.Bindings by parameter name —
value.is_parameter() → bindings[param_name]. This is the only name-keyed rule: resolution never falls back to the displayValue.name, which is excluded from canonical hashing and carries no binding provenance.Returns
Noneif none of the above match.
Overview¶
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
Value | A typed SSA value in the IR. |
ValueResolver | Resolve IR Values to concrete Python values. |
Classes¶
ArrayValue [source]¶
class ArrayValue(Value[T])An array of typed IR values.
When slice_of is set, this array is a strided view over another
array. Element accesses on a sliced ArrayValue resolve to
physical slots on the root parent via the affine map
parent_index = slice_start + slice_step * view_local_index,
applied recursively along slice_of chains. The emit-time
resolver walks this chain to produce the final qubit index; passes
that substitute or clone values must treat slice_of /
slice_start / slice_step as Value references that need to
track through the same mapping as parent_array.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
shape: tuple[Value, ...] = tuple(),
slice_of: 'ArrayValue | None' = None,
slice_start: 'Value | None' = None,
slice_step: 'Value | None' = None,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of engine resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueResolver [source]¶
class ValueResolverResolve IR Values to concrete Python values.
Parameters:
| Name | Type | Description |
|---|---|---|
context | dict[str, Any] | None | UUID-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. |
bindings | dict[str, Any] | None | Name-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:
| Name | Type | Description |
|---|---|---|
context | dict[str, Any] | None | UUID-keyed map of already-resolved values. Defaults to None. |
bindings | dict[str, Any] | None | Name-keyed parameter bindings supplied by the user. Defaults to None. |
Methods¶
resolve¶
def resolve(self, value: Any) -> Any | NoneResolve 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:
| Name | Type | Description |
|---|---|---|
value | Any | The 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.