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

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

qamomile.braket.transpiler

Transpile and execute Qamomile programs with Amazon Braket.

Overview

ClassDescription
BraketExecutionHandleWrap one Braket task or a task batch without blocking submission.
BraketExecutionOptionsConfigure Braket task and batch submission without flat kwargs.
BraketExecutorSubmit Braket circuits to a local simulator or injected AWS device.
BraketMaterializerConvert verified circuit IR to an Amazon Braket circuit.
BraketTranspilerTranspile Qamomile quantum kernels to Amazon Braket circuits.
CircuitInvocationKeep an emitted circuit and runtime parameter values together.
CompletedExecutionHandleWrap an already available result for synchronous executors.
EmitPassBase class for engine-specific emission passes.
EstimateRequestDescribe one Hamiltonian expectation execution.
ExactRequest an analytic expectation value without shot noise.
ExecutionCapabilitiesDeclare the execution features implemented by one executor.
ExecutionHandleExpose an engine execution without forcing immediate result retrieval.
ExecutionReferenceStore secret-free identifiers needed to restore remote execution.
SampleRequestDescribe one sampling execution.
SegmentationPassSegment a block into a strategy-specific executable program plan.
ShotBasedRequest a shot-based expectation value.
TargetPrecisionRequest an expectation value at a provider target precision.
TranspilerBase class for engine-specific transpilers.

Classes

BraketExecutionHandle [source]

class BraketExecutionHandle(ExecutionHandle[ResultT], Generic[ResultT])

Wrap one Braket task or a task batch without blocking submission.

Parameters:

NameTypeDescription
tasksSequence[Any]Provider quantum tasks when individually addressable.
result_loaderCallable[[], Sequence[Any]]Blocking raw-result loader that does not perform implicit retries unless configured.
decoderCallable[[Sequence[Any]], ResultT]Engine result decoder.
referenceExecutionReference | NoneSerializable AWS reference.
reference_factoryCallable[[], ExecutionReference | None] | NoneDynamic reference builder for batches that explicitly resubmit failed tasks. Defaults to none.
nativeobjectNative Braket task or batch object.
poll_interval_secondsfloatLocal status polling interval.
default_timeout_secondsfloat | NoneDefault local result timeout. Defaults to no timeout.
allow_unsuccessful_loaderboolWhether the result loader owns explicit recovery from failed child tasks. Defaults to false.

Constructor

def __init__(
    self,
    *,
    tasks: Sequence[Any],
    result_loader: Callable[[], Sequence[Any]],
    decoder: Callable[[Sequence[Any]], ResultT],
    reference: ExecutionReference | None,
    reference_factory: Callable[[], ExecutionReference | None] | None = None,
    native: object,
    poll_interval_seconds: float = 1.0,
    default_timeout_seconds: float | None = None,
    allow_unsuccessful_loader: bool = False,
) -> None

Initialize a Braket-backed execution handle.

Parameters:

NameTypeDescription
tasksSequence[Any]Individually addressable Braket tasks.
result_loaderCallable[[], Sequence[Any]]Blocking loader.
decoderCallable[[Sequence[Any]], ResultT]Result decoder.
referenceExecutionReference | NoneSerializable AWS reference.
reference_factoryCallable[[], ExecutionReference | None] | NoneDynamic reference builder. Defaults to none.
nativeobjectNative task or batch.
poll_interval_secondsfloatPositive local polling interval.
default_timeout_secondsfloat | NonePositive default local result timeout. Defaults to no timeout.
allow_unsuccessful_loaderboolWhether failed children may be handled by the explicit result loader. Defaults to false.

Raises:

Attributes

Methods

cancel
def cancel(self) -> None

Request best-effort cancellation of every unfinished task.

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

Return cached-or-provider metadata for every task.

Returns:

Mapping[str, Any] — Mapping[str, Any]: Child task metadata in submission order.

raw_status
def raw_status(self) -> object

Return raw task states in stable order.

Returns:

object — One state string or a tuple of state strings.

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

Return the logical Braket execution reference.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Empty for local tasks, otherwise one reference containing every task ARN.

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

Wait for and decode all Braket task results.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local status-wait time in seconds. None uses the configured Braket polling timeout when one exists, otherwise waits indefinitely. Expiration does not cancel remote tasks.

Returns:

ResultT — Decoded engine-neutral result.

Raises:

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture an AWS reference or an already retrieved local result.

AWS tasks retain their provider references after result retrieval. Local tasks require a successful result() call first; this method never retrieves results or waits for another result caller.

Returns:

ExecutionSnapshot — One remote reference or a detached local value.

Raises:

status
def status(self) -> JobStatus

Return the aggregate Braket task status.

Returns:

JobStatus — Provider-independent aggregate status.


BraketExecutionOptions [source]

class BraketExecutionOptions

Configure Braket task and batch submission without flat kwargs.

Parameters:

NameTypeDescription
s3_destination_foldertuple[str, str] | NoneS3 bucket and prefix for AWS task results. Defaults to the SDK configuration.
reservation_arnstr | NoneDirect reservation ARN. Defaults to None.
max_parallelint | NoneMaximum AWS batch concurrency. Defaults to the SDK configuration.
poll_timeout_secondsfloat | NoneProvider result polling timeout and default local result-wait limit. Defaults to the SDK configuration with no local limit.
poll_interval_secondsfloat | NoneProvider status polling interval. Defaults to the SDK configuration.
batch_max_retriesintMaximum explicit Braket batch resubmissions. Defaults to zero to prevent implicit additional QPU cost.
task_optionsMapping[str, Any]Additional device.run options.
batch_optionsMapping[str, Any]Additional device.run_batch options.

Raises:

Constructor

def __init__(
    self,
    s3_destination_folder: tuple[str, str] | None = None,
    reservation_arn: str | None = None,
    max_parallel: int | None = None,
    poll_timeout_seconds: float | None = None,
    poll_interval_seconds: float | None = None,
    batch_max_retries: int = 0,
    task_options: Mapping[str, Any] = dict(),
    batch_options: Mapping[str, Any] = dict(),
) -> None

Attributes

Methods

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

Build keyword arguments for a Braket task batch.

Returns:

dict[str, Any] — dict[str, Any]: Validated device.run_batch keyword arguments.

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

Build keyword arguments for one Braket task.

Returns:

dict[str, Any] — dict[str, Any]: Validated device.run keyword arguments.


BraketExecutor [source]

class BraketExecutor(QuantumExecutor['Circuit'])

Submit Braket circuits to a local simulator or injected AWS device.

The default device is created lazily, so importing qamomile.braket remains safe when the optional SDK dependency is absent.

Parameters:

NameTypeDescription
deviceAnyBraket device exposing run and optionally run_batch. Defaults to LocalSimulator.
estimation_shotsintShots used for expectation values. Zero uses exact state-vector expectation on compatible devices. Defaults to zero.
optionsBraketExecutionOptions | NoneStructured task and batch submission policy. Defaults to SDK behavior with no batch retry.
run_kwargsMapping[str, Any] | NoneExtra keyword arguments passed to every device task. This compatibility argument is deprecated in favor of options. Defaults to none.

Constructor

def __init__(
    self,
    device: Any = None,
    *,
    estimation_shots: int = 0,
    options: BraketExecutionOptions | None = None,
    run_kwargs: Mapping[str, Any] | None = None,
) -> None

Initialize the Braket executor.

Parameters:

NameTypeDescription
deviceAnyBraket device or compatible test double. Defaults to a lazily created local simulator.
estimation_shotsintNon-negative expectation task shots. Defaults to zero for exact local estimation.
optionsBraketExecutionOptions | NoneStructured execution options. Defaults to SDK behavior with retry disabled.
run_kwargsMapping[str, Any] | NoneExtra task options copied for each run. Kept for compatibility; cannot be combined with options. Defaults to none.

Raises:

Attributes

Methods

bind_parameters
def bind_parameters(
    self,
    circuit: 'Circuit',
    bindings: dict[str, Any],
    parameter_metadata: ParameterMetadata,
) -> 'Circuit'

Bind Qamomile runtime parameters into a Braket circuit.

Parameters:

NameTypeDescription
circuitCircuitParameterized Braket circuit.
bindingsdict[str, Any]Values keyed by flattened Qamomile parameter name.
parameter_metadataParameterMetadataCompiled parameter ABI.

Returns:

'Circuit' — New circuit with all required parameters bound.

Raises:

estimate
def estimate(
    self,
    circuit: 'Circuit',
    hamiltonian: 'qm_o.Hamiltonian',
    params: Sequence[float] | None = None,
) -> float

Estimate a Qamomile Hamiltonian expectation value.

Exact estimation submits one Braket task containing one result type per Pauli term. Shot-based estimation submits one task per term so non-commuting terms remain valid on devices with sampled result types.

Parameters:

NameTypeDescription
circuitCircuitBound Braket state-preparation circuit.
hamiltonianqm_o.HamiltonianHamiltonian to evaluate.
paramsSequence[float] | NonePositional parameter values for direct executor use. Qamomile normally binds before calling this method. Defaults to none.

Returns:

float — Real expectation value including the constant term.

Raises:

execute
def execute(self, circuit: 'Circuit', shots: int) -> dict[str, int]

Sample a Braket circuit and return Qamomile-ordered counts.

Parameters:

NameTypeDescription
circuitCircuitBound Braket state-preparation circuit.
shotsintNumber of measurement shots.

Returns:

dict[str, int] — dict[str, int]: Counts with the highest qubit index on the left. A zero-qubit circuit returns {"": shots}.

Raises:

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

Restore AWS quantum tasks from their serializable references.

Parameters:

NameTypeDescription
referenceExecutionReferenceReference returned by a prior Braket execution handle.

Returns:

ExecutionHandle[Any] — ExecutionHandle[Any]: Restored sampling or expectation handle.

Raises:

submit_estimate
def submit_estimate(self, request: EstimateRequest['Circuit']) -> ExecutionHandle[float]

Submit Braket expectation tasks without retrieving their results.

Parameters:

NameTypeDescription
requestEstimateRequest[Circuit]Circuit, observable, inputs, and accuracy policy.

Returns:

ExecutionHandle[float] — ExecutionHandle[float]: Lazy exact or shot-based result handle.

Raises:

submit_sample
def submit_sample(self, request: SampleRequest['Circuit']) -> ExecutionHandle[dict[str, int]]

Submit a native Braket sampling task without waiting for results.

Parameters:

NameTypeDescription
requestSampleRequest[Circuit]Circuit, native parameter inputs, and shot count.

Returns:

ExecutionHandle[dict[str, int]] — ExecutionHandle[dict[str, int]]: Lazy Braket execution handle.


BraketMaterializer [source]

class BraketMaterializer

Convert verified circuit IR to an Amazon Braket circuit.

Attributes

Methods

materialize
def materialize(
    self,
    program: CircuitProgram,
    parameter_names: tuple[str, ...] = (),
) -> MaterializedCircuit[Any]

Build a Braket circuit and static-measurement metadata.

Parameters:

NameTypeDescription
programCircuitProgramVerified target-legal circuit program.
parameter_namestuple[str, ...]Public parameter ABI names. Defaults to an empty tuple.

Returns:

MaterializedCircuit[Any] — MaterializedCircuit[Any]: Braket circuit and binding metadata.

Raises:


BraketTranspiler [source]

class BraketTranspiler(Transpiler['Circuit'])

Transpile Qamomile quantum kernels to Amazon Braket circuits.

Methods

executor
def executor(
    self,
    device: Any = None,
    *,
    estimation_shots: int = 0,
    options: BraketExecutionOptions | None = None,
    run_kwargs: Mapping[str, Any] | None = None,
) -> BraketExecutor

Create a Braket executor.

Parameters:

NameTypeDescription
deviceAnyBraket local simulator, AWS device, or compatible test double. Defaults to a local simulator.
estimation_shotsintShots for expectation tasks. Defaults to zero for exact estimation.
optionsBraketExecutionOptions | NoneStructured submission, polling, concurrency, and retry policy. Defaults to SDK behavior with retry disabled.
run_kwargsMapping[str, Any] | NoneExtra device task options. Compatibility form; cannot be combined with options. Defaults to none.

Returns:

BraketExecutor — Configured task-backed executor.

Raises:


CircuitInvocation [source]

class CircuitInvocation(Generic[CircuitT])

Keep an emitted circuit and runtime parameter values together.

Engines may bind the values into a new circuit or submit them through a native parameter-input API. Keeping both forms available preserves native parameter sweeps and provider-side compilation caches.

Parameters:

NameTypeDescription
circuitCircuitTEmitted engine circuit or kernel artifact.
bindingsMapping[str, Any]Flattened Qamomile runtime bindings.
parameter_metadataParameterMetadataMapping from public parameter names to engine parameter objects.

Constructor

def __init__(
    self,
    circuit: CircuitT,
    bindings: Mapping[str, Any],
    parameter_metadata: ParameterMetadata,
) -> None

Attributes


CompletedExecutionHandle [source]

class CompletedExecutionHandle(ExecutionHandle[ResultT])

Wrap an already available result for synchronous executors.

Parameters:

NameTypeDescription
valueResultTCompleted execution value.

Constructor

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

Initialize an immediately completed execution.

Parameters:

NameTypeDescription
valueResultTCompleted execution value.

Methods

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

Return the completed value without waiting.

Parameters:

NameTypeDescription
timeoutfloat | NoneIgnored compatibility timeout.

Returns:

ResultT — Stored execution value.

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture the already available raw result without waiting.

Returns:

ExecutionSnapshot — Owned, type-preserving local value.

Raises:

status
def status(self) -> JobStatus

Return the completed status.

Returns:

JobStatus — Always :attr:JobStatus.COMPLETED.


EmitPass [source]

class EmitPass(Pass[ProgramPlan, ExecutableProgram[T]], Generic[T])

Base class for engine-specific emission passes.

Subclasses implement _emit_quantum_segment() to generate engine-specific quantum circuits.

Input: ProgramPlan Output: ExecutableProgram with compiled segments

Constructor

def __init__(
    self,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
)

Initialize with optional parameter bindings.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneValues to bind parameters to. If not provided, parameters must be bound at execution time.
parameterslist[str] | NoneList of parameter names to preserve as engine parameters.

Raises:

Attributes

Methods

run
def run(self, input: ProgramPlan) -> ExecutableProgram[T]

Emit engine code from a program plan.

Parameters:

NameTypeDescription
inputProgramPlanSegmented plan whose quantum and classical steps should be compiled.

Returns:

ExecutableProgram[T] — ExecutableProgram[T]: Executable program containing all compiled segments and the public output contract.

Raises:


EstimateRequest [source]

class EstimateRequest(Generic[CircuitT])

Describe one Hamiltonian expectation execution.

Parameters:

NameTypeDescription
invocationCircuitInvocation[CircuitT]Circuit and runtime inputs.
hamiltonianqm_o.HamiltonianObservable to evaluate.
accuracyEstimationAccuracy | NoneExplicit accuracy policy. None uses the executor’s configured default.

Constructor

def __init__(
    self,
    invocation: CircuitInvocation[CircuitT],
    hamiltonian: qm_o.Hamiltonian,
    accuracy: EstimationAccuracy | None = None,
) -> None

Attributes


Exact [source]

class Exact

Request an analytic expectation value without shot noise.

Constructor

def __init__(self) -> None

ExecutionCapabilities [source]

class ExecutionCapabilities

Declare the execution features implemented by one executor.

Parameters:

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

Raises:

Constructor

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

Attributes


ExecutionHandle [source]

class ExecutionHandle(ABC, Generic[ResultT])

Expose an engine execution without forcing immediate result retrieval.

Attributes

Methods

cancel
def cancel(self) -> None

Request best-effort cancellation.

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

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

Return optional provider execution metadata.

Returns:

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

raw_status
def raw_status(self) -> object

Return provider-specific status information.

Returns:

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

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

Return serializable remote execution references.

Returns:

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

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

Wait for and return the engine-neutral raw result.

Parameters:

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

Returns:

ResultT — Raw result normalized by the engine executor.

Raises:

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

Wait asynchronously for the engine-neutral raw result.

Parameters:

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

Returns:

ResultT — Raw result normalized by the engine executor.

Raises:

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture one remote execution without fetching its result.

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

Returns:

ExecutionSnapshot — One opaque provider execution.

Raises:

status
def status(self) -> JobStatus

Return the current provider-independent execution status.

Returns:

JobStatus — Current normalized status.


ExecutionReference [source]

class ExecutionReference

Store secret-free identifiers needed to restore remote execution.

Parameters:

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

Raises:

Constructor

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

Attributes

Methods

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

Reconstruct a provider reference from JSON-compatible data.

Parameters:

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

Returns:

ExecutionReference — Validated provider execution reference.

Raises:

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

Convert the provider reference to JSON-compatible data.

Returns:

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


SampleRequest [source]

class SampleRequest(Generic[CircuitT])

Describe one sampling execution.

Parameters:

NameTypeDescription
invocationCircuitInvocation[CircuitT]Circuit and runtime inputs.
shotsintNumber of requested samples.

Raises:

Constructor

def __init__(self, invocation: CircuitInvocation[CircuitT], shots: int) -> None

Attributes


SegmentationPass [source]

class SegmentationPass(Pass[Block, ProgramPlan])

Segment a block into a strategy-specific executable program plan.

This pass:

  1. Materializes return operations (syncs output_values from ReturnOperation)

  2. Splits the operation list into quantum and classical segments

  3. Builds a ProgramPlan via the configured segmentation strategy

Input: Block (typically ANALYZED or AFFINE) Output: ProgramPlan

Constructor

def __init__(self, strategy: SegmentationStrategy | None = None) -> None

Attributes

Methods

run
def run(self, input: Block) -> ProgramPlan

Lower and segment a block into a program plan.

Parameters:

NameTypeDescription
inputBlockBlock whose while contract and hybrid operations should be lowered before segmentation.

Returns:

ProgramPlan — Strategy-produced execution plan.

Raises:


ShotBased [source]

class ShotBased

Request a shot-based expectation value.

Parameters:

NameTypeDescription
shotsintPositive number of measurement shots.

Raises:

Constructor

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

Attributes


TargetPrecision [source]

class TargetPrecision

Request an expectation value at a provider target precision.

Parameters:

NameTypeDescription
precisionfloatPositive absolute target precision.

Raises:

Constructor

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

Attributes


Transpiler [source]

class Transpiler(ABC, Generic[T])

Base class for engine-specific transpilers.

Provides the full compilation pipeline from qkernel-like frontend objects to executable programs.

Example:

>>> from qamomile.circuit.transpiler import TranspilerConfig
>>> from qamomile.qiskit import QiskitTranspiler
>>> transpiler = QiskitTranspiler()
>>> executable = transpiler.transpile(kernel, bindings={"theta": 0.5})
>>> circuit = executable.get_first_circuit()
>>> config = TranspilerConfig.with_strategies({"qft": "approximate_k2"})
>>> transpiler.set_config(config)

Attributes

Methods

affine_validate
def affine_validate(self, block: Block) -> Block

Pass 1.5: Validate affine type semantics.

This is a safety net to catch affine type violations that may have bypassed frontend checks. Validates that quantum values are used at most once.

analyze
def analyze(self, block: Block) -> Block

Pass 2: Validate and analyze dependencies.

array_bounds_check
def array_bounds_check(self, block: Block) -> Block

Pass 1.85: Reject reachable accesses outside resolved array bounds.

Runs after :meth:partial_eval so binding-dependent view extents and indices are concrete where possible, and before declarative slice operations are stripped. Statically zero-trip loop bodies are skipped because their element accesses are unreachable.

Parameters:

NameTypeDescription
blockBlockPost-fold affine or hierarchical block to validate.

Returns:

Block — The input block unchanged after successful validation.

Raises:

classical_lowering
def classical_lowering(self, block: Block) -> Block

Pass 2.25: Lower measurement-derived classical ops.

Identifies CompOp / CondOp / NotOp / BinOp instances whose operand dataflow traces back to a measurement and rewrites them to RuntimeClassicalExpr. Compile-time-foldable and emit-time-foldable (loop-bound, parameter-bound) classical ops are left unchanged.

Runs after analyze so the measurement-taint analysis has the full dependency graph available, and before validate_symbolic_shapes / plan / emit so downstream passes can rely on the cleaner IR (in particular: future segmentation work can dispatch on RuntimeClassicalExpr type instead of the BitType-only heuristic).

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

Pass 1.5: Fold constant expressions.

Evaluates BinOp operations when all operands are constants or bound parameters. This prevents quantum segment splitting from parametric expressions like phase * 2.

emit
def emit(
    self,
    separated: ProgramPlan,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> ExecutableProgram[T]

Pass 4: Generate engine-specific code.

Parameters:

NameTypeDescription
separatedProgramPlanThe separated program to emit
bindingsdict[str, Any] | NoneParameter values to bind at compile time
parameterslist[str] | NoneParameter names to preserve as engine parameters

Raises:

executor
def executor(self, **kwargs: Any = {}) -> QuantumExecutor[T]

Create a quantum executor for this engine.

inline
def inline(self, block: Block) -> Block

Pass 1: Inline all inline-policy callable invocations.

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

Pass 1.75: Lower compile-time resolvable IfOperations.

Evaluates IfOperation conditions (including expression-derived conditions via CompOp/CondOp/NotOp) and replaces resolved ones with selected-branch operations. Merge outputs are substituted with selected-branch values throughout the block.

This prevents SegmentationPass from seeing classical-only compile-time IfOperations that would otherwise split quantum segments.

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

Pass 1.75: Fold constants and lower compile-time control flow.

plan
def plan(self, block: Block) -> ProgramPlan

Pass 3: Lower and split into a program plan.

Validates C→Q→C pattern with single quantum segment.

plan_circuit
def plan_circuit(
    self,
    prepared: PreparedModule,
    bindings: dict[str, Any] | None = None,
) -> ProgramPlan

Lower a prepared semantic module into the circuit execution model.

This is the destructive circuit-family path: inline-policy calls are flattened, compile-time structure is evaluated, affine and borrow invariants are checked, measurement-dependent classical expressions are classified, and the result is segmented into C-to-Q-to-C steps. Program-graph targets must compile :class:PreparedModule directly instead of invoking this method.

Parameters:

NameTypeDescription
preparedPreparedModuleHierarchical semantic program returned by :meth:prepare.
bindingsdict[str, Any] | NoneCompile-time bindings used for recursion unrolling and partial evaluation. Defaults to None.

Returns:

ProgramPlan — Circuit-family host-orchestrated execution plan.

Raises:

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

Prepare a qkernel for target-specific planning and lowering.

This phase preserves callable boundaries. It performs tracing, entrypoint validation, configured substitutions, and parameter-shape resolution, then collects the reachable callable graph into a program-level semantic view.

Parameters:

NameTypeDescription
kernelQKernelLikeQKernel or qkernel-like frontend object to prepare as a top-level entrypoint.
bindingsdict[str, Any] | NoneCompile-time values used while tracing and resolving parameter shapes. Defaults to None.
parameterslist[str] | NoneArgument names preserved as runtime parameters. Defaults to None.

Returns:

PreparedModule — Hierarchical entrypoint, reachable callables, call graph, and public ABI.

Raises:

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

Pass 0.75: Resolve symbolic Vector parameter shape dims.

Qamomile circuits are compile-time fixed-structure. Parameter Vector[Float] / Vector[UInt] inputs carry symbolic {name}_dim{i} shape Values so frontend code like arr.shape[0] returns a usable handle. This pass looks at bindings and, for every parameter array that has a concrete binding, substitutes those symbolic dims with constants so that downstream loop-bound resolution sees fixed lengths.

Parameters without a concrete binding are left as-is; their symbolic dims are harmless as long as no compile-time structure decision depends on them (the library QAOA pattern).

set_config
def set_config(self, config: TranspilerConfig) -> None

Set the transpiler configuration.

Parameters:

NameTypeDescription
configTranspilerConfigTranspiler configuration to use
slice_borrow_check
def slice_borrow_check(self, block: Block) -> Block

Pass 1.9: Post-fold slice-view linearity checker.

Runs after :meth:partial_eval has resolved slice bounds to concrete values. Catches the slice-view linearity violations that the trace-time frontend check cannot detect on its own — specifically, slices whose bounds were symbolic at trace time (so the frontend bulk-borrow tracker had to skip them) and aliasing scenarios that only become visible once those bounds are folded to constants:

  1. A view whose newly-concrete coverage overlaps another live view of the same root parent.

  2. A view whose newly-concrete coverage hits a slot that was consumed by a destructive operation earlier in the block.

  3. Slice ownership changes that cannot be represented safely across control-flow boundaries.

Creating a direct element borrow (q[i]) emits no IR operation, so this pass cannot observe the borrow site itself. Later uses of that element do appear as operation operands and are checked for conflicts with live slice views. Trace-time validation in :func:qamomile.circuit.frontend.func_to_block._validate_returned_arrays covers unreturned direct-element borrows that have no observable operand use.

The pass is a pass-through for the IR — it only raises on violations and leaves the block unchanged on success.

Parameters:

NameTypeDescription
blockBlockPost-fold affine or hierarchical block to validate.

Returns:

Block — The input block unchanged after successful validation.

Raises:

strip_slice_ops
def strip_slice_ops(self, block: Block) -> Block

Pass 1.95: Remove SliceArrayOperation nodes from the block.

PartialEvaluationPass keeps these declarative ops through constant folding so :meth:slice_borrow_check can use them as view-declaration markers. Once the linearity check has run, segmentation and downstream passes expect a classical-op-free quantum stream — this pass performs that cleanup.

substitute
def substitute(self, block: Block) -> Block

Pass 0.5: Apply substitutions (optional).

This pass rewrites inline callable targets and sets strategy names on boxed InvokeOperations based on config.

Parameters:

NameTypeDescription
blockBlockBlock to transform

Returns:

Block — Block with substitutions applied

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

Convert a qkernel-like frontend object to a Block.

Parameters:

NameTypeDescription
kernelQKernelLikeQKernel or qkernel-like frontend object to convert.
bindingsdict[str, Any] | NoneConcrete values to bind at trace time, including values used to resolve array shapes.
parameterslist[str] | NoneNames to keep as unbound runtime parameters.

Returns:

Block — Hierarchical block for the frontend object.

Raises:

Always uses kernel.build() so Python defaults, required arguments, runtime parameters, and array shapes follow one validated entry path.

to_circuit
def to_circuit(self, kernel: QKernelLike, bindings: dict[str, Any] | None = None) -> T

Compile and extract just the quantum circuit.

This is a convenience method for when you just want the engine circuit without the full executable.

Parameters:

NameTypeDescription
kernelQKernelLikeQKernel or qkernel-like frontend object to compile.
bindingsdict[str, Any] | NoneParameter values to bind.

Returns:

T — Engine-specific quantum circuit.

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

Full compilation pipeline from a qkernel-like object to executable.

Parameters:

NameTypeDescription
kernelQKernelLikeQKernel or qkernel-like frontend object to compile.
bindingsdict[str, Any] | NoneParameter values to bind (also resolves array shapes). Names in bindings and parameters must be disjoint — a name is either compile-time bound or runtime symbolic, never both.
parameterslist[str] | NoneParameter names to preserve as engine parameters. Scalars/arrays of float/int/UInt are supported, plus Dict[K, Float]: each constant-key subscript lookup (d[key]) becomes one engine parameter named "d[<key>]", and the execution-time binding bindings={"d": {...}} is decomposed per key onto those parameters. A Dict runtime parameter is recorded in Block.param_slots as a slot whose type is a DictType (compile-time-bound Dicts and Tuple arguments stay out of the slot manifest); its emitted per-key parameters are visible via ExecutableProgram.parameter_names.

Returns:

ExecutableProgram[T] — ExecutableProgram[T]: Executable wrapping the engine circuit and the parameter metadata needed to re-bind runtime parameters, ready for execution.

Raises:

Pipeline:

  1. prepare: Trace and validate the entrypoint, apply configured substitutions, resolve parameter shapes, and preserve the reachable callable graph.

  2. plan_circuit: Inline inline-policy calls, unroll recursion, validate affine and borrow rules, partially evaluate compile-time structure, analyze dependencies, and segment the program into the host-orchestrated C-to-Q-to-C model.

  3. lower: Convert each quantum segment to immutable, engine-neutral CircuitProgram IR.

  4. legalize: Select native intrinsics and Pauli-evolution realizations from target capabilities and compilation policy.

  5. verify: Prove circuit structure and target legality before constructing engine objects.

  6. materialize: Convert the legalized circuit IR to engine-native artifacts and preserve the executable ABI.

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

Fixed-point loop of inline and branch lowering for recursion.

Each iteration unrolls one layer of self-referential inline callable invocation and then lowers its compile-time base-case IfOperation. Loop-carried Bit conditions remain visible until the final validation pass so first-iteration constants cannot erase a real backedge read. Terminates when no inline callable invocation remains (success), when every residual call is trapped inside an operation-owned block whose recursive callable contract is unsupported (control / inverse / select over a recursive kernel — raises a targeted error, see below), or when MAX_UNROLL_DEPTH is reached (genuinely non-terminating top-level recursion — raises).

Parameters:

NameTypeDescription
blockBlockThe block to unroll. May be HIERARCHICAL (still containing self-referential callable invocations) or already AFFINE (returned unchanged).
bindingsdict[str, Any] | NoneCompile-time bindings used by condition lowering to select the base case. Defaults to None, meaning no bindings are applied.

Returns:

Block — The fully unrolled, AFFINE block once no inline callable invocation remains. Returned unchanged when the input already has no calls.

Raises:

validate_symbolic_shapes
def validate_symbolic_shapes(self, block: Block) -> Block

Pass 2.5: Reject unresolvable ForOperation loop bounds.

Runs after analyze so dependency info is complete. Raises QamomileCompileError with an actionable message when a gamma_dim0-style symbolic Value reaches a ForOperation bound without being folded to a constant by ParameterShapeResolutionPass, or when a loop bound depends (directly or through classical arithmetic) on a runtime parameter — loop bounds are compile-time structure and must be provided via bindings, not parameters.

Parameters:

NameTypeDescription
blockBlockThe analyzed block to validate.

Returns:

Blockblock, unchanged, when validation succeeds.

Raises: