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