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

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

qamomile.circuit.transpiler


qamomile.circuit.transpiler.capabilities

Backend capability definitions for transpiler optimization.

Overview

ClassDescription
BackendCapabilityCapabilities that a backend may support natively.
CapableBackendProtocol for backends that declare their capabilities.

Classes

BackendCapability [source]
class BackendCapability(enum.Flag)

Capabilities that a backend may support natively.

Use these flags to indicate which composite gates and features a backend supports, allowing the transpiler to use native implementations when available.

Attributes

CapableBackend [source]
class CapableBackend(Protocol)

Protocol for backends that declare their capabilities.

Implement this protocol in backend-specific EmitPass classes to enable capability-based optimizations.

Attributes
Methods
has_capability
def has_capability(self, cap: BackendCapability) -> bool

Check if this backend has a specific capability.

Parameters:

NameTypeDescription
capBackendCapabilityThe capability to check for.

Returns:

bool — True if the backend has the capability, False otherwise.


qamomile.circuit.transpiler.classical_executor

Classical segment executor for Python-based classical operations.

Overview

ClassDescription
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, POW).
BinOpKind
ClassicalExecutorExecutes classical segments in Python.
ClassicalSegmentA segment of pure classical operations.
CompOpComparison operation (EQ, NEQ, LT, LE, GT, GE).
CompOpKind
CondOpConditional logical operation (AND, OR).
CondOpKind
DecodeQFixedOperationDecode measured bits to float (classical operation).
ExecutionContextHolds global state during program execution.
ExecutionErrorError during program execution.
NotOp
ValueA typed value in the IR with SSA-style versioning.

Classes

BinOp [source]
class BinOp(BinaryOperationBase)

Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, POW).

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

BinOpKind [source]
class BinOpKind(enum.Enum)
Attributes

ClassicalExecutor [source]
class ClassicalExecutor

Executes classical segments in Python.

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

Execute classical operations and return outputs.

Interprets the operations list directly using Python.


ClassicalSegment [source]
class ClassicalSegment(Segment)

A segment of pure classical operations.

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

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

CompOp [source]
class CompOp(BinaryOperationBase)

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

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

CompOpKind [source]
class CompOpKind(enum.Enum)
Attributes

CondOp [source]
class CondOp(BinaryOperationBase)

Conditional logical operation (AND, OR).

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

CondOpKind [source]
class CondOpKind(enum.Enum)
Attributes

DecodeQFixedOperation [source]
class DecodeQFixedOperation(Operation)

Decode measured bits to float (classical operation).

This operation converts a sequence of classical bits from qubit measurements into a floating-point number using fixed-point encoding.

The decoding formula:

float_value = Σ bit[i] * 2^(int_bits - 1 - i)

For QPE phase (int_bits=0): float_value = 0.b0b1b2... = b00.5 + b10.25 + b2*0.125 + ...

Example:

bits = [1, 0, 1] with int_bits=0
→ 0.101 (binary) = 0.5 + 0.125 = 0.625

operands: [ArrayValue of bits (vec[bit])] results: [Float value]

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

ExecutionContext [source]
class ExecutionContext

Holds global state during program execution.

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

ExecutionError [source]
class ExecutionError(QamomileCompileError)

Error during program execution.


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

Value [source]
class Value(Generic[T])

A typed value in the IR with SSA-style versioning.

Value represents a single typed value (qubit, float, int, bit, etc.) with support for:

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
) -> None
Attributes
Methods
get_cast_qubit_logical_ids
def get_cast_qubit_logical_ids(self) -> list[str] | None

Get the underlying qubit logical_ids for this cast value.

get_cast_qubit_uuids
def get_cast_qubit_uuids(self) -> list[str] | None

Get the underlying qubit UUIDs for this cast value.

get_cast_source_logical_id
def get_cast_source_logical_id(self) -> str | None

Get the source value logical_id if this is a cast result.

get_cast_source_uuid
def get_cast_source_uuid(self) -> str | None

Get the source value UUID if this is a cast result.

get_const
def get_const(self) -> int | float | None

Get constant value if available, otherwise None.

get_lowered_bits
def get_lowered_bits(self) -> list[Value] | None

Get lowered bit list if available, otherwise None.

get_lowered_qubits
def get_lowered_qubits(self) -> list[Value] | None

Get lowered qubit list if available, otherwise None.

is_array_element
def is_array_element(self) -> bool

Check if this value is an element of an array.

is_cast_result
def is_cast_result(self) -> bool

Check if this value is the result of a CastOperation.

is_constant
def is_constant(self) -> bool

Check if this value is a constant.

is_parameter
def is_parameter(self) -> bool

Check if this value is an unbound parameter.

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

Create a new Value with incremented version (SSA style).

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter, otherwise None.

set_cast_metadata
def set_cast_metadata(
    self,
    source_uuid: str,
    qubit_uuids: list[str],
    source_logical_id: str | None = None,
    qubit_logical_ids: list[str] | None = None,
) -> None

Set cast metadata for this value.

set_lowered_bits
def set_lowered_bits(self, bits: list[Value]) -> None

Set lowered bit list.

set_lowered_qubits
def set_lowered_qubits(self, qubits: list[Value]) -> None

Set lowered qubit list.


qamomile.circuit.transpiler.compile_check

Overview

FunctionDescription
is_block_compilableCheck if a BlockValue is compilable.
ClassDescription
BlockValueRepresents a subroutine as a function block.

Functions

is_block_compilable [source]
def is_block_compilable(block: BlockValue) -> bool

Check if a BlockValue is compilable.

A BlockValue is considered compilable if all its operations are compilable. This function checks each operation in the block’s operations list.

Parameters:

NameTypeDescription
blockBlockValueThe BlockValue to check.

Returns: bool: True if the block is compilable, False otherwise.

Classes

BlockValue [source]
class BlockValue(Value[BlockType])

Represents a subroutine as a function block.

def func_block(a: UInt, b: UInt) -> tuple[UInt]: ...

BlockValue( name=“func_block”, inputs_type={“a”: UIntType(), “b”: UIntType()}, outputs_type=(UIntType(), ), operations=[...], )

Function to BlockValue conversion can be done via func_to_block function. Each Values in operations are dummy values. The execution of the BlockValue is corresponding to the BlockOperation.

Constructor
def __init__(
    self,
    type: BlockType = BlockType(),
    name: str = '',
    version: int = 0,
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
    label_args: list[str] = list(),
    input_values: list[Value] = list(),
    return_values: list[Value] = list(),
    operations: list[Operation] = list(),
) -> None
Attributes
Methods
call
def call(self, **kwargs: Value = {}) -> 'CallBlockOperation'

Create a CallBlockOperation to call this BlockValue.

Example:

block_value = BlockValue(
    name="func_block",
    inputs_type={"a": UIntType(), "b": UIntType()},
    outputs_type=(UIntType(), ),
    operations=[...],
)
a = Value(UIntType())
b = Value(UIntType())
call_op = block_value.call(a=a, b=b)

qamomile.circuit.transpiler.compiled_segments

Compiled segment structures for transpiled quantum circuits.

Overview

ClassDescription
ClassicalSegmentA segment of pure classical operations.
CompiledClassicalSegmentA classical segment ready for Python execution.
CompiledExpvalSegmentA compiled expectation value segment with concrete Hamiltonian.
CompiledQuantumSegmentA quantum segment with emitted backend circuit.
ExpvalSegmentA segment for expectation value computation.
ParameterMetadataMetadata for all parameters in a compiled segment.
QuantumSegmentA segment of pure quantum operations.

Classes

ClassicalSegment [source]
class ClassicalSegment(Segment)

A segment of pure classical operations.

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

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

CompiledClassicalSegment [source]
class CompiledClassicalSegment

A classical segment ready for Python execution.

Constructor
def __init__(self, segment: ClassicalSegment) -> None
Attributes

CompiledExpvalSegment [source]
class CompiledExpvalSegment

A compiled expectation value segment with concrete Hamiltonian.

This segment computes <psi|H|psi> where psi is the quantum state from a quantum circuit and H is a qamomile.observable.Hamiltonian.

Constructor
def __init__(
    self,
    segment: ExpvalSegment,
    hamiltonian: 'qm_o.Hamiltonian',
    quantum_segment_index: int = 0,
    result_ref: str = '',
    qubit_map: dict[int, int] = dict(),
) -> None
Attributes

CompiledQuantumSegment [source]
class CompiledQuantumSegment(Generic[T])

A quantum segment with emitted backend circuit.

Constructor
def __init__(
    self,
    segment: QuantumSegment,
    circuit: T,
    qubit_map: dict[str, int] = dict(),
    clbit_map: dict[str, int] = dict(),
    measurement_qubit_map: dict[int, int] = dict(),
    parameter_metadata: ParameterMetadata = ParameterMetadata(),
) -> None
Attributes

ExpvalSegment [source]
class ExpvalSegment(Segment)

A segment for expectation value computation.

Represents computing <psi|H|psi> where psi is the quantum state and H is a Hamiltonian observable.

This segment bridges a quantum circuit (state preparation) to a classical expectation value.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
    hamiltonian_value: Value | None = None,
    qubits_value: Value | None = None,
    result_ref: str = '',
) -> None
Attributes

ParameterMetadata [source]
class ParameterMetadata

Metadata for all parameters in a compiled segment.

Tracks parameter information for runtime binding.

Constructor
def __init__(self, parameters: list[ParameterInfo] = list()) -> None
Attributes
Methods
get_array_names
def get_array_names(self) -> set[str]

Get unique array/scalar parameter names.

get_ordered_params
def get_ordered_params(self) -> list[Any]

Get backend parameter objects in definition order.

Useful for backends that require positional parameter binding (e.g., QURI Parts).

Returns:

list[Any] — List of backend_param objects in the order they were defined.

Example:

# For QURI Parts that uses positional binding:
param_values = [bindings[p.name] for p in metadata.parameters]
bound_circuit = circuit.bind_parameters(param_values)
get_param_by_name
def get_param_by_name(self, name: str) -> ParameterInfo | None

Get parameter info by full name.

to_binding_dict
def to_binding_dict(self, bindings: dict[str, Any]) -> dict[Any, Any]

Convert indexed bindings to backend parameter bindings.

Transforms user-provided bindings (with indexed names like “gammas[0]”) into a dictionary mapping backend parameter objects to values. Useful for backends that use dict-based parameter binding (e.g., Qiskit).

Parameters:

NameTypeDescription
bindingsdict[str, Any]Dictionary mapping parameter names to values. e.g., {“gammas[0]”: 0.1, “gammas[1]”: 0.2, “theta”: 0.5}

Returns:

dict[Any, Any] — Dictionary mapping backend_param objects to values.

Example:

# For Qiskit that uses dict-based binding:
qiskit_bindings = metadata.to_binding_dict(bindings)
bound_circuit = circuit.assign_parameters(qiskit_bindings)

QuantumSegment [source]
class QuantumSegment(Segment)

A segment of pure quantum operations.

Contains quantum gates and qubit allocations. Will be emitted to a quantum circuit.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
    qubit_values: list[Value] = list(),
    num_qubits: int = 0,
) -> None
Attributes

qamomile.circuit.transpiler.emitter


qamomile.circuit.transpiler.emitter.emitter

Overview

ClassDescription
BlockValueRepresents a subroutine as a function block.
EmitResult
Emitter

Classes

BlockValue [source]
class BlockValue(Value[BlockType])

Represents a subroutine as a function block.

def func_block(a: UInt, b: UInt) -> tuple[UInt]: ...

BlockValue( name=“func_block”, inputs_type={“a”: UIntType(), “b”: UIntType()}, outputs_type=(UIntType(), ), operations=[...], )

Function to BlockValue conversion can be done via func_to_block function. Each Values in operations are dummy values. The execution of the BlockValue is corresponding to the BlockOperation.

Constructor
def __init__(
    self,
    type: BlockType = BlockType(),
    name: str = '',
    version: int = 0,
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
    label_args: list[str] = list(),
    input_values: list[Value] = list(),
    return_values: list[Value] = list(),
    operations: list[Operation] = list(),
) -> None
Attributes
Methods
call
def call(self, **kwargs: Value = {}) -> 'CallBlockOperation'

Create a CallBlockOperation to call this BlockValue.

Example:

block_value = BlockValue(
    name="func_block",
    inputs_type={"a": UIntType(), "b": UIntType()},
    outputs_type=(UIntType(), ),
    operations=[...],
)
a = Value(UIntType())
b = Value(UIntType())
call_op = block_value.call(a=a, b=b)

EmitResult [source]
class EmitResult(abc.ABC, Generic[T])
Attributes

Emitter [source]
class Emitter(abc.ABC, Generic[T])
Constructor
def __init__(
    self,
    block: BlockValue,
    bind: dict[str, int | float | list[int] | list[float]],
) -> None
Attributes
Methods
emit
def emit(self, block: BlockValue) -> EmitResult[T]

qamomile.circuit.transpiler.errors

Compilation error classes for Qamomile transpiler.

Overview

ClassDescription
AffineTypeErrorBase class for affine type violations.
DependencyErrorError when quantum operation depends on non-parameter classical value.
EmitErrorError during backend code emission.
ExecutionErrorError during program execution.
InliningErrorError during inline pass (inlining CallBlockOperations).
OperandResolutionInfoDetailed information about a single operand that failed to resolve.
QamomileCompileErrorBase class for all Qamomile compilation errors.
QubitAliasErrorSame qubit used multiple times in one operation.
QubitConsumedErrorQubit handle used after being consumed by a previous operation.
QubitIndexResolutionErrorError when qubit indices cannot be resolved during emission.
QubitRebindErrorQuantum variable reassigned from a different quantum source.
ResolutionFailureReasonCategorizes why qubit index resolution failed.
SeparationErrorError during quantum/classical separation.
UnreturnedBorrowErrorBorrowed array element not returned before array use.
ValidationErrorError during validation (e.g., non-classical I/O).

Classes

AffineTypeError [source]
class AffineTypeError(QamomileCompileError)

Base class for affine type violations.

Affine types enforce that quantum resources (qubits) are used at most once. This prevents common errors such as reusing a consumed qubit or aliasing.

Constructor
def __init__(
    self,
    message: str,
    handle_name: str | None = None,
    operation_name: str | None = None,
    first_use_location: str | None = None,
)
Attributes

DependencyError [source]
class DependencyError(QamomileCompileError)

Error when quantum operation depends on non-parameter classical value.

This error indicates that the program requires JIT compilation which is not yet supported.

Constructor
def __init__(
    self,
    message: str,
    quantum_op: str | None = None,
    classical_value: str | None = None,
)
Attributes

EmitError [source]
class EmitError(QamomileCompileError)

Error during backend code emission.

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

ExecutionError [source]
class ExecutionError(QamomileCompileError)

Error during program execution.


InliningError [source]
class InliningError(QamomileCompileError)

Error during inline pass (inlining CallBlockOperations).


OperandResolutionInfo [source]
class OperandResolutionInfo

Detailed information about a single operand that failed to resolve.

Constructor
def __init__(
    self,
    operand_name: str,
    operand_uuid: str,
    is_array_element: bool,
    parent_array_name: str | None,
    element_indices_names: list[str],
    failure_reason: ResolutionFailureReason,
    failure_details: str,
) -> None
Attributes

QamomileCompileError [source]
class QamomileCompileError(Exception)

Base class for all Qamomile compilation errors.


QubitAliasError [source]
class QubitAliasError(AffineTypeError)

Same qubit used multiple times in one operation.

Operations like cx() require distinct qubits for control and target. Using the same qubit in both positions is physically impossible and indicates a programming error.

Example of incorrect code:

q1, q2 = qm.cx(q, q) # ERROR: same qubit as control and target

Correct code:

q1, q2 = qm.cx(control, target) # Use distinct qubits


QubitConsumedError [source]
class QubitConsumedError(AffineTypeError)

Qubit handle used after being consumed by a previous operation.

Each qubit handle can only be used once. After a gate operation, you must reassign the result to use the new handle.

Example of incorrect code:

q1 = qm.h(q) q2 = qm.x(q) # ERROR: q was already consumed by h()

Correct code:

q = qm.h(q) # Reassign to capture new handle q = qm.x(q) # Use the reassigned handle


QubitIndexResolutionError [source]
class QubitIndexResolutionError(EmitError)

Error when qubit indices cannot be resolved during emission.

This error provides detailed diagnostic information about why qubit index resolution failed and suggests remediation steps.

Constructor
def __init__(
    self,
    gate_type: str,
    operand_infos: list[OperandResolutionInfo],
    available_bindings_keys: list[str],
    available_qubit_map_keys: list[str],
)
Attributes

QubitRebindError [source]
class QubitRebindError(AffineTypeError)

Quantum variable reassigned from a different quantum source.

When a quantum variable is reassigned, the RHS must consume the same variable (self-update pattern). Reassigning from a different quantum variable silently discards the original quantum state.

Example of incorrect code:

a = qm.h(b) # ERROR: ‘a’ was quantum, now overwritten from ‘b’ a = b # ERROR: ‘a’ was quantum, now overwritten from ‘b’

Correct patterns:

a = qm.h(a) # Self-update (OK) new = qm.h(b) # New binding (OK, ‘new’ wasn’t quantum before)


ResolutionFailureReason [source]
class ResolutionFailureReason(Enum)

Categorizes why qubit index resolution failed.

Attributes

SeparationError [source]
class SeparationError(QamomileCompileError)

Error during quantum/classical separation.


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 = qm.h(q0) q1 = qubits[1] # ERROR: q0 not returned yet

Correct code:

q0 = qubits[0] q0 = qm.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)
Attributes

qamomile.circuit.transpiler.executable

Executable program structure for compiled quantum-classical programs.

Overview

ClassDescription
ClassicalExecutorExecutes classical segments in Python.
CompiledClassicalSegmentA classical segment ready for Python execution.
CompiledExpvalSegmentA compiled expectation value segment with concrete Hamiltonian.
CompiledQuantumSegmentA quantum segment with emitted backend circuit.
ExecutableProgramA fully compiled program ready for execution.
ExecutionContextHolds global state during program execution.
ExecutionErrorError during program execution.
ExpvalJobJob for expectation value computation.
ParameterInfoInformation about a single unbound parameter in the circuit.
ParameterMetadataMetadata for all parameters in a compiled segment.
QuantumExecutorAbstract base class for quantum backend execution.
RunJobJob for single execution.
SampleJobJob for sampling execution (multiple shots).

Classes

ClassicalExecutor [source]
class ClassicalExecutor

Executes classical segments in Python.

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

Execute classical operations and return outputs.

Interprets the operations list directly using Python.


CompiledClassicalSegment [source]
class CompiledClassicalSegment

A classical segment ready for Python execution.

Constructor
def __init__(self, segment: ClassicalSegment) -> None
Attributes

CompiledExpvalSegment [source]
class CompiledExpvalSegment

A compiled expectation value segment with concrete Hamiltonian.

This segment computes <psi|H|psi> where psi is the quantum state from a quantum circuit and H is a qamomile.observable.Hamiltonian.

Constructor
def __init__(
    self,
    segment: ExpvalSegment,
    hamiltonian: 'qm_o.Hamiltonian',
    quantum_segment_index: int = 0,
    result_ref: str = '',
    qubit_map: dict[int, int] = dict(),
) -> None
Attributes

CompiledQuantumSegment [source]
class CompiledQuantumSegment(Generic[T])

A quantum segment with emitted backend circuit.

Constructor
def __init__(
    self,
    segment: QuantumSegment,
    circuit: T,
    qubit_map: dict[str, int] = dict(),
    clbit_map: dict[str, int] = dict(),
    measurement_qubit_map: dict[int, int] = dict(),
    parameter_metadata: ParameterMetadata = ParameterMetadata(),
) -> None
Attributes

ExecutableProgram [source]
class ExecutableProgram(Generic[T])

A fully compiled program ready for execution.

This is the Orchestrator - manages execution of mixed classical/quantum programs.

Example:

executable = transpiler.compile(kernel)

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

# Run: single shot, returns typed result
job = executable.run(executor)
result = job.result()  # Returns kernel's return type
Constructor
def __init__(
    self,
    compiled_quantum: list[CompiledQuantumSegment[T]] = list(),
    compiled_classical: list[CompiledClassicalSegment] = list(),
    compiled_expval: list[CompiledExpvalSegment] = list(),
    execution_order: list[tuple[str, int]] = list(),
    output_refs: list[str] = list(),
    num_output_bits: int = 0,
) -> None
Attributes
Methods
get_circuits
def get_circuits(self) -> list[T]

Get all quantum circuits in execution order.

get_first_circuit
def get_first_circuit(self) -> T | None

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

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

Execute once and return single result.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Backend-specific quantum executor.
bindingsdict[str, Any] | NoneParameter bindings. Supports two formats: - Vector: {“gammas”: [0.1, 0.2], “betas”: [0.3, 0.4]} - Indexed: {“gammas[0]”: 0.1, “gammas[1]”: 0.2}

Returns:

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

Raises:

Example:

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

Execute with multiple shots and return counts.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Backend-specific quantum executor.
shotsintNumber of shots to run.
bindingsdict[str, Any] | NoneParameter bindings. Supports two formats: - Vector: {“gammas”: [0.1, 0.2], “betas”: [0.3, 0.4]} - Indexed: {“gammas[0]”: 0.1, “gammas[1]”: 0.2}

Returns:

SampleJob[Any] — SampleJob that resolves to SampleResult with results.

Raises:

Example:

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

ExecutionContext [source]
class ExecutionContext

Holds global state during program execution.

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

ExecutionError [source]
class ExecutionError(QamomileCompileError)

Error during program execution.


ExpvalJob [source]
class ExpvalJob(Job[float])

Job for expectation value computation.

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

Constructor
def __init__(self, exp_val: float)

Initialize expval job.

Parameters:

NameTypeDescription
exp_valfloatThe computed expectation value
Methods
result
def result(self) -> float

Return the expectation value.

status
def status(self) -> JobStatus

Return job status.


ParameterInfo [source]
class ParameterInfo

Information about a single unbound parameter in the circuit.

Constructor
def __init__(
    self,
    name: str,
    array_name: str,
    index: int | None,
    backend_param: Any,
) -> None
Attributes

ParameterMetadata [source]
class ParameterMetadata

Metadata for all parameters in a compiled segment.

Tracks parameter information for runtime binding.

Constructor
def __init__(self, parameters: list[ParameterInfo] = list()) -> None
Attributes
Methods
get_array_names
def get_array_names(self) -> set[str]

Get unique array/scalar parameter names.

get_ordered_params
def get_ordered_params(self) -> list[Any]

Get backend parameter objects in definition order.

Useful for backends that require positional parameter binding (e.g., QURI Parts).

Returns:

list[Any] — List of backend_param objects in the order they were defined.

Example:

# For QURI Parts that uses positional binding:
param_values = [bindings[p.name] for p in metadata.parameters]
bound_circuit = circuit.bind_parameters(param_values)
get_param_by_name
def get_param_by_name(self, name: str) -> ParameterInfo | None

Get parameter info by full name.

to_binding_dict
def to_binding_dict(self, bindings: dict[str, Any]) -> dict[Any, Any]

Convert indexed bindings to backend parameter bindings.

Transforms user-provided bindings (with indexed names like “gammas[0]”) into a dictionary mapping backend parameter objects to values. Useful for backends that use dict-based parameter binding (e.g., Qiskit).

Parameters:

NameTypeDescription
bindingsdict[str, Any]Dictionary mapping parameter names to values. e.g., {“gammas[0]”: 0.1, “gammas[1]”: 0.2, “theta”: 0.5}

Returns:

dict[Any, Any] — Dictionary mapping backend_param objects to values.

Example:

# For Qiskit that uses dict-based binding:
qiskit_bindings = metadata.to_binding_dict(bindings)
bound_circuit = circuit.assign_parameters(qiskit_bindings)

QuantumExecutor [source]
class QuantumExecutor(ABC, Generic[T])

Abstract base class for quantum backend execution.

To implement a custom executor:

  1. execute() [Required] Execute circuit and return bitstring counts as dict[str, int]. Keys are bitstrings in big-endian format (e.g., “011” means q2=0, q1=1, q0=1).

  2. bind_parameters() [Optional] Bind parameter values to parametric circuits. Override if your executor supports parametric circuits (e.g., QAOA variational circuits). Use ParameterMetadata.to_binding_dict() for easy conversion.

  3. estimate() [Optional] Compute expectation values <psi|H|psi>. Override if your executor supports estimation primitives (e.g., Qiskit Estimator, QURI Parts).

Example (Minimal): class MyExecutor(QuantumExecutor[QuantumCircuit]): def init(self): from qiskit_aer import AerSimulator self.backend = AerSimulator()

    def execute(self, circuit, shots):
        from qiskit import transpile
        if circuit.num_clbits == 0:
            circuit = circuit.copy()
            circuit.measure_all()
        transpiled = transpile(circuit, self.backend)
        return self.backend.run(transpiled, shots=shots).result().get_counts()

Example (With Parameter Binding): def bind_parameters(self, circuit, bindings, metadata): # metadata.to_binding_dict() converts indexed names to backend params return circuit.assign_parameters(metadata.to_binding_dict(bindings))

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

Bind parameter values to the circuit.

Default implementation returns the circuit unchanged. Override for backends that support parametric circuits.

Parameters:

NameTypeDescription
circuitTThe parameterized circuit
bindingsdict[str, Any]Dict mapping parameter names (indexed format) to values. e.g., {“gammas[0]”: 0.1, “gammas[1]”: 0.2}
parameter_metadataParameterMetadataMetadata about circuit parameters

Returns:

T — New circuit with parameters bound

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

Estimate the expectation value of a Hamiltonian.

This method computes <psi|H|psi> where psi is the quantum state prepared by the circuit and H is the Hamiltonian.

Backends can override this method to provide optimized implementations using their native estimator primitives.

Parameters:

NameTypeDescription
circuitTThe quantum circuit (state preparation ansatz)
hamiltonian'qm_o.Hamiltonian'The qamomile.observable.Hamiltonian to measure
paramsSequence[float] | NoneOptional parameter values for parametric circuits

Returns:

float — The estimated expectation value

Raises:

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

Execute the circuit and return bitstring counts.

Parameters:

NameTypeDescription
circuitTThe quantum circuit to execute
shotsintNumber of measurement shots

Returns:

dict[str, int] — Dictionary mapping bitstrings to counts. dict[str, int] — {“00”: 512, “11”: 512}


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], result_converter: Callable[[str], T])

Initialize run job.

Parameters:

NameTypeDescription
raw_countsdict[str, int]Bitstring counts from executor (should have single entry)
result_converterCallable[[str], T]Function to convert bitstring to typed result
Methods
result
def result(self) -> T

Return the single result.

status
def status(self) -> JobStatus

Return job status.


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],
    result_converter: Callable[[dict[str, int]], list[tuple[T, int]]],
    shots: int,
)

Initialize sample job.

Parameters:

NameTypeDescription
raw_countsdict[str, int]Bitstring counts from executor (e.g., {“00”: 512, “11”: 512})
result_converterCallable[[dict[str, int]], list[tuple[T, int]]]Function to convert raw counts to typed results
shotsintNumber of shots executed
Methods
result
def result(self) -> SampleResult[T]

Return the sample result.

status
def status(self) -> JobStatus

Return job status.


qamomile.circuit.transpiler.execution_context

Execution context for quantum-classical program execution.

Overview

ClassDescription
ExecutionContextHolds global state during program execution.

Classes

ExecutionContext [source]
class ExecutionContext

Holds global state during program execution.

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

qamomile.circuit.transpiler.gate_emitter

GateEmitter protocol for backend-agnostic gate emission.

This module defines the GateEmitter protocol that backends implement to emit individual quantum gates. The StandardEmitPass uses this protocol to orchestrate circuit generation without backend-specific code.

Overview

ClassDescription
GateEmitterProtocol for backend-specific gate emission.
GateKindClassification of gates for emission.
GateSpecSpecification for a gate type.

Constants

Classes

GateEmitter [source]
class GateEmitter(Protocol[T])

Protocol for backend-specific gate emission.

Each backend implements this protocol to emit individual gates to their circuit representation.

Type parameter T is the backend’s circuit type (e.g., QuantumCircuit).

Methods
append_gate
def append_gate(self, circuit: T, gate: Any, qubits: list[int]) -> None

Append a gate to the circuit.

Parameters:

NameTypeDescription
circuitTThe circuit to append to
gateAnyThe gate to append (from circuit_to_gate)
qubitslist[int]Target qubit indices
circuit_to_gate
def circuit_to_gate(self, circuit: T, name: str = 'U') -> Any

Convert a circuit to a reusable gate.

Parameters:

NameTypeDescription
circuitTThe circuit to convert
namestrLabel for the gate

Returns:

Any — Backend-specific gate object, or None if not supported

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

Create a new empty circuit.

Parameters:

NameTypeDescription
num_qubitsintNumber of qubits in the circuit
num_clbitsintNumber of classical bits in the circuit

Returns:

T — A new backend-specific circuit object

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

Create a symbolic parameter for the backend.

Parameters:

NameTypeDescription
namestrParameter name (e.g., “gammas[0]”)

Returns:

Any — Backend-specific parameter object

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

Emit barrier on specified qubits.

emit_ch
def emit_ch(self, circuit: T, control: int, target: int) -> None

Emit controlled-Hadamard gate.

emit_cp
def emit_cp(self, circuit: T, control: int, target: int, angle: float | Any) -> None

Emit controlled-Phase gate.

emit_crx
def emit_crx(self, circuit: T, control: int, target: int, angle: float | Any) -> None

Emit controlled-RX gate.

emit_cry
def emit_cry(self, circuit: T, control: int, target: int, angle: float | Any) -> None

Emit controlled-RY gate.

emit_crz
def emit_crz(self, circuit: T, control: int, target: int, angle: float | Any) -> None

Emit controlled-RZ gate.

emit_cx
def emit_cx(self, circuit: T, control: int, target: int) -> None

Emit CNOT gate.

emit_cy
def emit_cy(self, circuit: T, control: int, target: int) -> None

Emit controlled-Y gate.

emit_cz
def emit_cz(self, circuit: T, control: int, target: int) -> None

Emit CZ gate.

emit_else_start
def emit_else_start(self, circuit: T, context: Any) -> None

Start the else branch.

emit_for_loop_end
def emit_for_loop_end(self, circuit: T, context: Any) -> None

End a native for loop context.

emit_for_loop_start
def emit_for_loop_start(self, circuit: T, indexset: range) -> Any

Start a native for loop context.

Returns a context manager or loop parameter, depending on backend.

emit_h
def emit_h(self, circuit: T, qubit: int) -> None

Emit Hadamard gate.

emit_if_end
def emit_if_end(self, circuit: T, context: Any) -> None

End the if/else block.

emit_if_start
def emit_if_start(self, circuit: T, clbit: int, value: int = 1) -> Any

Start a native if context.

Returns context for the if/else block.

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

Emit measurement operation.

emit_p
def emit_p(self, circuit: T, qubit: int, angle: float | Any) -> None

Emit Phase gate (P(θ) = diag(1, e^(iθ))).

emit_rx
def emit_rx(self, circuit: T, qubit: int, angle: float | Any) -> None

Emit RX rotation gate.

Parameters:

NameTypeDescription
circuitTThe circuit to emit to
qubitintTarget qubit index
anglefloat | AnyRotation angle (float or backend parameter)
emit_ry
def emit_ry(self, circuit: T, qubit: int, angle: float | Any) -> None

Emit RY rotation gate.

emit_rz
def emit_rz(self, circuit: T, qubit: int, angle: float | Any) -> None

Emit RZ rotation gate.

emit_rzz
def emit_rzz(self, circuit: T, qubit1: int, qubit2: int, angle: float | Any) -> None

Emit RZZ gate (exp(-i * θ/2 * Z⊗Z)).

emit_s
def emit_s(self, circuit: T, qubit: int) -> None

Emit S gate (√Z).

emit_sdg
def emit_sdg(self, circuit: T, qubit: int) -> None

Emit S-dagger gate (inverse of S).

emit_swap
def emit_swap(self, circuit: T, qubit1: int, qubit2: int) -> None

Emit SWAP gate.

emit_t
def emit_t(self, circuit: T, qubit: int) -> None

Emit T gate (√S).

emit_tdg
def emit_tdg(self, circuit: T, qubit: int) -> None

Emit T-dagger gate (inverse of T).

emit_toffoli
def emit_toffoli(self, circuit: T, control1: int, control2: int, target: int) -> None

Emit Toffoli (CCX) gate.

emit_while_end
def emit_while_end(self, circuit: T, context: Any) -> None

End the while loop context.

emit_while_start
def emit_while_start(self, circuit: T, clbit: int, value: int = 1) -> Any

Start a native while loop context.

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

Emit Pauli-X gate.

emit_y
def emit_y(self, circuit: T, qubit: int) -> None

Emit Pauli-Y gate.

emit_z
def emit_z(self, circuit: T, qubit: int) -> None

Emit Pauli-Z gate.

gate_controlled
def gate_controlled(self, gate: Any, num_controls: int) -> Any

Create controlled version of a gate.

Parameters:

NameTypeDescription
gateAnyThe gate to control
num_controlsintNumber of control qubits

Returns:

Any — New controlled gate

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

Create gate raised to a power (U^n).

Parameters:

NameTypeDescription
gateAnyThe gate to raise to a power
powerintThe power to raise to

Returns:

Any — New gate representing gate^power

supports_for_loop
def supports_for_loop(self) -> bool

Check if backend supports native for loops.

supports_if_else
def supports_if_else(self) -> bool

Check if backend supports native if/else.

supports_while_loop
def supports_while_loop(self) -> bool

Check if backend supports native while loops.


GateKind [source]
class GateKind(Enum)

Classification of gates for emission.

Attributes

GateSpec [source]
class GateSpec

Specification for a gate type.

Constructor
def __init__(
    self,
    kind: GateKind,
    num_qubits: int,
    has_angle: bool = False,
    num_controls: int = 0,
) -> None
Attributes

qamomile.circuit.transpiler.job

Job classes for quantum execution results.

Overview

ClassDescription
ExpvalJobJob for expectation value computation.
JobAbstract base class for quantum execution jobs.
JobStatusStatus of a quantum job.
RunJobJob for single execution.
SampleJobJob for sampling execution (multiple shots).
SampleResultResult of a sample() execution.

Classes

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)

Initialize expval job.

Parameters:

NameTypeDescription
exp_valfloatThe computed expectation value
Methods
result
def result(self) -> float

Return the expectation value.

status
def status(self) -> JobStatus

Return job status.


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.

Methods
result
def result(self) -> T

Wait for and return the result.

Blocks until the job completes.

Returns:

T — The execution result with the appropriate type.

Raises:

status
def status(self) -> JobStatus

Return the current job status.


JobStatus [source]
class JobStatus(Enum)

Status of a quantum job.

Attributes

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

Job for single execution.

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

Constructor
def __init__(self, raw_counts: dict[str, int], result_converter: Callable[[str], T])

Initialize run job.

Parameters:

NameTypeDescription
raw_countsdict[str, int]Bitstring counts from executor (should have single entry)
result_converterCallable[[str], T]Function to convert bitstring to typed result
Methods
result
def result(self) -> T

Return the single result.

status
def status(self) -> JobStatus

Return job status.


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],
    result_converter: Callable[[dict[str, int]], list[tuple[T, int]]],
    shots: int,
)

Initialize sample job.

Parameters:

NameTypeDescription
raw_countsdict[str, int]Bitstring counts from executor (e.g., {“00”: 512, “11”: 512})
result_converterCallable[[dict[str, int]], list[tuple[T, int]]]Function to convert raw counts to typed results
shotsintNumber of shots executed
Methods
result
def result(self) -> SampleResult[T]

Return the sample result.

status
def status(self) -> JobStatus

Return job status.


SampleResult [source]
class SampleResult(Generic[T])

Result of a sample() execution.

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

Example:

result.results  # [(0.25, 500), (0.75, 500)]
Constructor
def __init__(self, results: list[tuple[T, int]], shots: int) -> None
Attributes
Methods
most_common
def most_common(self, n: int = 1) -> list[tuple[T, int]]

Return the n most common results.

Parameters:

NameTypeDescription
nintNumber of results to return.

Returns:

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

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

Return probability distribution over results.

Returns:

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


qamomile.circuit.transpiler.orchestrator

Overview

FunctionDescription
separate_operations
ClassDescription
ClassicalRunnable
Operation
OperationKindClassification of operations for classical/quantum separation.
Orchestrator
QuantumRunnable
Runnable

Functions

separate_operations [source]
def separate_operations(
    operations: list[Operation],
    quantum_runnable_cls: type[QuantumRunnable],
    classical_runnable_cls: type[ClassicalRunnable],
) -> list[Runnable]

Classes

ClassicalRunnable [source]
class ClassicalRunnable(Runnable)

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

OperationKind [source]
class OperationKind(enum.Enum)

Classification of operations for classical/quantum separation.

This enum is used to categorize operations during compilation to determine which parts run on classical hardware vs quantum hardware.

Values:

QUANTUM: Pure quantum operations (gates, qubit allocation) CLASSICAL: Pure classical operations (arithmetic, comparisons) HYBRID: Operations that bridge classical and quantum (measurement, encode/decode) CONTROL: Control flow structures (for, while, if)

Attributes

Orchestrator [source]
class Orchestrator
Constructor
def __init__(
    self,
    global_variables: dict[str, float | int | bool | list] = dict(),
    operations: list[Runnable] = list(),
    return_ids: list[tuple[str, int]] = list(),
) -> None
Attributes
Methods
run
def run(self, **kwargs = {})

QuantumRunnable [source]
class QuantumRunnable(Runnable)

Runnable [source]
class Runnable(abc.ABC)
Constructor
def __init__(self, operations: list) -> None
Attributes
Methods
input_args
def input_args(self) -> dict[str, int | float | bool | list]
reset_global_vars
def reset_global_vars(self)
return_assingnments
def return_assingnments(self, return_values: list) -> dict[str, int | float | bool | list]
run
def run(self, *args = (), **kwargs = {})
set_global_vars
def set_global_vars(self, global_vars: dict[str, int | float | bool | list])

qamomile.circuit.transpiler.parameter_binding

Parameter binding structures for compiled quantum circuits.

Overview

ClassDescription
ParameterInfoInformation about a single unbound parameter in the circuit.
ParameterMetadataMetadata for all parameters in a compiled segment.

Classes

ParameterInfo [source]
class ParameterInfo

Information about a single unbound parameter in the circuit.

Constructor
def __init__(
    self,
    name: str,
    array_name: str,
    index: int | None,
    backend_param: Any,
) -> None
Attributes

ParameterMetadata [source]
class ParameterMetadata

Metadata for all parameters in a compiled segment.

Tracks parameter information for runtime binding.

Constructor
def __init__(self, parameters: list[ParameterInfo] = list()) -> None
Attributes
Methods
get_array_names
def get_array_names(self) -> set[str]

Get unique array/scalar parameter names.

get_ordered_params
def get_ordered_params(self) -> list[Any]

Get backend parameter objects in definition order.

Useful for backends that require positional parameter binding (e.g., QURI Parts).

Returns:

list[Any] — List of backend_param objects in the order they were defined.

Example:

# For QURI Parts that uses positional binding:
param_values = [bindings[p.name] for p in metadata.parameters]
bound_circuit = circuit.bind_parameters(param_values)
get_param_by_name
def get_param_by_name(self, name: str) -> ParameterInfo | None

Get parameter info by full name.

to_binding_dict
def to_binding_dict(self, bindings: dict[str, Any]) -> dict[Any, Any]

Convert indexed bindings to backend parameter bindings.

Transforms user-provided bindings (with indexed names like “gammas[0]”) into a dictionary mapping backend parameter objects to values. Useful for backends that use dict-based parameter binding (e.g., Qiskit).

Parameters:

NameTypeDescription
bindingsdict[str, Any]Dictionary mapping parameter names to values. e.g., {“gammas[0]”: 0.1, “gammas[1]”: 0.2, “theta”: 0.5}

Returns:

dict[Any, Any] — Dictionary mapping backend_param objects to values.

Example:

# For Qiskit that uses dict-based binding:
qiskit_bindings = metadata.to_binding_dict(bindings)
bound_circuit = circuit.assign_parameters(qiskit_bindings)

qamomile.circuit.transpiler.passes

Base classes for compiler passes.

Overview

ClassDescription
AffineTypeErrorBase class for affine type violations.
AffineValidationPassValidate affine type semantics at IR level.
CompileTimeIfLoweringPassLowers compile-time resolvable IfOperations before separation.
ConstantFoldingPassEvaluates constant expressions at compile time.
ControlFlowVisitorBase class for visiting operations with control flow handling.
DependencyErrorError when quantum operation depends on non-parameter classical value.
OperationCollectorCollects operations matching a predicate.
OperationTransformerBase class for transforming operations with control flow handling.
PassBase class for all compiler passes.
QamomileCompileErrorBase class for all Qamomile compilation errors.
UUIDRemapperClones values and operations with fresh UUIDs and logical_ids.
ValidateWhileContractPassValidates that all WhileOperation conditions are measurement-backed.
ValidationErrorError during validation (e.g., non-classical I/O).
ValueCollectorCollects Value UUIDs from operation operands and results.
ValueSubstitutorSubstitutes values in operations using a mapping.

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,
)
Attributes

AffineValidationPass [source]
class AffineValidationPass(Pass[Block, Block])

Validate affine type semantics at IR level.

This pass serves as a safety net to catch affine type violations that may have bypassed the frontend checks. It verifies:

  1. Each quantum value is used (consumed) at most once

  2. Quantum values are not silently discarded

Input: Block (any kind) Output: Same Block (unchanged, validation only)

Attributes
Methods
run
def run(self, input: Block) -> Block

Validate affine type semantics in the block.

Raises:


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. SeparatePass treats them as segment boundaries, causing MultipleQuantumSegmentsError for classical-only compile-time if after quantum init.

This pass:

  1. Evaluates conditions including expression-derived ones (CompOp, CondOp, NotOp chains).

  2. Replaces resolved IfOperations with selected-branch operations.

  3. Substitutes phi output UUIDs with selected-branch values in all subsequent operations and block outputs.

Constructor
def __init__(self, bindings: dict[str, Any] | None = None)
Attributes
Methods
run
def run(self, input: Block) -> Block

Run the compile-time if lowering pass.


ConstantFoldingPass [source]
class ConstantFoldingPass(Pass[Block, Block])

Evaluates constant expressions at compile time.

This pass folds BinOp operations when all operands are constants or bound parameters, eliminating unnecessary classical operations that would otherwise split quantum segments.

Example:

Before (with bindings={"phase": 0.5}):
    BinOp(phase * 2) -> classical segment split

After:
    Constant 1.0 -> no segment split
Constructor
def __init__(self, bindings: dict[str, Any] | None = None)
Attributes
Methods
run
def run(self, input: Block) -> Block

Run constant folding on the block.


ControlFlowVisitor [source]
class ControlFlowVisitor(ABC)

Base class for visiting operations with control flow handling.

Subclasses override visit_operation to define per-operation behavior. Control flow recursion is handled automatically by the base class.

Example:

class MeasurementCounter(ControlFlowVisitor):
    def __init__(self):
        self.count = 0

    def visit_operation(self, op: Operation) -> None:
        if isinstance(op, MeasureOperation):
            self.count += 1
Methods
visit_operation
def visit_operation(self, op: Operation) -> None

Process a single operation. Override in subclasses.

visit_operations
def visit_operations(self, operations: list[Operation]) -> None

Visit all operations including nested control flow.


DependencyError [source]
class DependencyError(QamomileCompileError)

Error when quantum operation depends on non-parameter classical value.

This error indicates that the program requires JIT compilation which is not yet supported.

Constructor
def __init__(
    self,
    message: str,
    quantum_op: str | None = None,
    classical_value: str | None = None,
)
Attributes

OperationCollector [source]
class OperationCollector(ControlFlowVisitor)

Collects operations matching a predicate.

Example:

collector = OperationCollector(lambda op: isinstance(op, MeasureOperation))
collector.visit_operations(block.operations)
measurements = collector.collected
Constructor
def __init__(self, predicate: Callable[[Operation], bool])
Attributes
Methods
visit_operation
def visit_operation(self, op: Operation) -> None

OperationTransformer [source]
class OperationTransformer(ABC)

Base class for transforming operations with control flow handling.

Subclasses override transform_operation to define per-operation transformation. Control flow recursion and rebuilding is handled automatically.

Example:

class OperationRenamer(OperationTransformer):
    def transform_operation(self, op: Operation) -> Operation:
        # Return modified operation
        return dataclasses.replace(op, ...)
Methods
transform_operation
def transform_operation(self, op: Operation) -> Operation | None

Transform a single operation. Return None to remove it.

transform_operations
def transform_operations(self, operations: list[Operation]) -> list[Operation]

Transform all operations including nested control flow.


Pass [source]
class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


QamomileCompileError [source]
class QamomileCompileError(Exception)

Base class for all Qamomile compilation errors.


UUIDRemapper [source]
class UUIDRemapper

Clones values and operations with fresh UUIDs and logical_ids.

Used during inlining to create unique identities for values when a block is called multiple times.

Constructor
def __init__(self)
Attributes
Methods
clone_operation
def clone_operation(self, op: Operation) -> Operation

Clone an operation with fresh UUIDs for all values.

clone_operations
def clone_operations(self, operations: list[Operation]) -> list[Operation]

Clone a list of operations with fresh UUIDs.

clone_value
def clone_value(self, value: ValueBase) -> ValueBase

Clone any value type with a fresh UUID and logical_id.

Handles Value, ArrayValue, TupleValue, and DictValue through the unified ValueBase protocol.


ValidateWhileContractPass [source]
class ValidateWhileContractPass(Pass[Block, Block])

Validates that all WhileOperation conditions are measurement-backed.

Builds a producer map (result UUID → producing Operation instance) and checks every WhileOperation operand against it. A valid condition must be:

  1. A Value with BitType

  2. Measurement-backed: produced by MeasureOperation directly, or by IfOperation / PhiOp where every reachable leaf source is itself measurement-backed.

Both operands[0] (initial condition) and operands[1] (loop-carried condition) are validated.

Raises ValidationError for any non-measurement while pattern.

Attributes
Methods
run
def run(self, block: Block) -> Block

Validate all WhileOperations and return block unchanged.


ValidationError [source]
class ValidationError(QamomileCompileError)

Error during validation (e.g., non-classical I/O).

Constructor
def __init__(self, message: str, value_name: str | None = None)
Attributes

ValueCollector [source]
class ValueCollector(ControlFlowVisitor)

Collects Value UUIDs from operation operands and results.

Constructor
def __init__(self)
Attributes
Methods
visit_operation
def visit_operation(self, op: Operation) -> None

ValueSubstitutor [source]
class ValueSubstitutor

Substitutes values in operations using a mapping.

Used during inlining to replace block parameters with caller arguments.

Constructor
def __init__(self, value_map: dict[str, ValueBase])
Methods
substitute_operation
def substitute_operation(self, op: Operation) -> Operation

Substitute values in an operation using the value map.

Handles control-flow operations (IfOperation, ForOperation, etc.) by recursing into their nested operation lists and phi_ops.

substitute_value
def substitute_value(self, v: ValueBase) -> ValueBase

Substitute a single value using the value map.

Handles all value types and array elements by substituting their parent_array if needed.


qamomile.circuit.transpiler.passes.affine_validate

Affine type validation pass: Verify quantum resources are used correctly.

Overview

ClassDescription
AffineTypeErrorBase class for affine type violations.
AffineValidationPassValidate affine type semantics at IR level.
BlockUnified block representation for all pipeline stages.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
IfOperationRepresents an if-else conditional operation.
PassBase class for all compiler passes.
ValueA typed value in the IR with SSA-style versioning.
WhileOperationRepresents a while loop operation.

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,
)
Attributes

AffineValidationPass [source]
class AffineValidationPass(Pass[Block, Block])

Validate affine type semantics at IR level.

This pass serves as a safety net to catch affine type violations that may have bypassed the frontend checks. It verifies:

  1. Each quantum value is used (consumed) at most once

  2. Quantum values are not silently discarded

Input: Block (any kind) Output: Same Block (unchanged, validation only)

Attributes
Methods
run
def run(self, input: Block) -> Block

Validate affine type semantics in the block.

Raises:


Block [source]
class Block

Unified block representation for all pipeline stages.

Replaces both BlockValue and Graph 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[Value] = list(),
    output_values: list[Value] = list(),
    operations: list[Operation] = list(),
    kind: BlockKind = BlockKind.HIERARCHICAL,
    parameters: dict[str, Value] = dict(),
    _dependency_graph: dict[str, set[str]] | None = None,
) -> None
Attributes
Methods
from_block_value
@classmethod
def from_block_value(
    cls,
    block_value: 'BlockValue',
    parameters: dict[str, Value] | None = None,
) -> 'Block'

Create a Block from a BlockValue.

Parameters:

NameTypeDescription
block_value'BlockValue'The BlockValue to convert
parametersdict[str, Value] | NoneOptional parameter bindings

Returns:

'Block' — A new Block in HIERARCHICAL state

is_affine
def is_affine(self) -> bool

Check if block contains no CallBlockOperations.

unbound_parameters
def unbound_parameters(self) -> list[str]

Return list of unbound parameter names.


ForItemsOperation [source]
class ForItemsOperation(Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    operations: list[Operation] = list(),
) -> None
Attributes

ForOperation [source]
class ForOperation(Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    operations: list[Operation] = list(),
) -> None
Attributes

IfOperation [source]
class IfOperation(Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    phi_ops: list[PhiOp] = list(),
) -> None
Attributes

Pass [source]
class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


Value [source]
class Value(Generic[T])

A typed value in the IR with SSA-style versioning.

Value represents a single typed value (qubit, float, int, bit, etc.) with support for:

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
) -> None
Attributes
Methods
get_cast_qubit_logical_ids
def get_cast_qubit_logical_ids(self) -> list[str] | None

Get the underlying qubit logical_ids for this cast value.

get_cast_qubit_uuids
def get_cast_qubit_uuids(self) -> list[str] | None

Get the underlying qubit UUIDs for this cast value.

get_cast_source_logical_id
def get_cast_source_logical_id(self) -> str | None

Get the source value logical_id if this is a cast result.

get_cast_source_uuid
def get_cast_source_uuid(self) -> str | None

Get the source value UUID if this is a cast result.

get_const
def get_const(self) -> int | float | None

Get constant value if available, otherwise None.

get_lowered_bits
def get_lowered_bits(self) -> list[Value] | None

Get lowered bit list if available, otherwise None.

get_lowered_qubits
def get_lowered_qubits(self) -> list[Value] | None

Get lowered qubit list if available, otherwise None.

is_array_element
def is_array_element(self) -> bool

Check if this value is an element of an array.

is_cast_result
def is_cast_result(self) -> bool

Check if this value is the result of a CastOperation.

is_constant
def is_constant(self) -> bool

Check if this value is a constant.

is_parameter
def is_parameter(self) -> bool

Check if this value is an unbound parameter.

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

Create a new Value with incremented version (SSA style).

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter, otherwise None.

set_cast_metadata
def set_cast_metadata(
    self,
    source_uuid: str,
    qubit_uuids: list[str],
    source_logical_id: str | None = None,
    qubit_logical_ids: list[str] | None = None,
) -> None

Set cast metadata for this value.

set_lowered_bits
def set_lowered_bits(self, bits: list[Value]) -> None

Set lowered bit list.

set_lowered_qubits
def set_lowered_qubits(self, qubits: list[Value]) -> None

Set lowered qubit list.


WhileOperation [source]
class WhileOperation(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 backend 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(),
) -> None
Attributes

qamomile.circuit.transpiler.passes.analyze

Analyze pass: Validate and analyze dependencies in an affine block.

Overview

ClassDescription
AnalyzePassAnalyze and validate an affine block.
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
ControlFlowVisitorBase class for visiting operations with control flow handling.
DependencyErrorError when quantum operation depends on non-parameter classical value.
MeasureOperation
OperationKindClassification of operations for classical/quantum separation.
PassBase class for all compiler passes.
ValidationErrorError during validation (e.g., non-classical I/O).
ValueA typed value in the IR with SSA-style versioning.
ValueBaseProtocol defining the common interface for all value types.

Classes

AnalyzePass [source]
class AnalyzePass(Pass[Block, Block])

Analyze and validate an affine block.

This pass:

  1. Builds a dependency graph between values

  2. Validates that quantum ops don’t depend on non-parameter classical results

  3. Checks that block inputs/outputs are classical

Input: Block with BlockKind.AFFINE Output: Block with BlockKind.ANALYZED (with _dependency_graph populated)

Attributes
Methods
run
def run(self, input: Block) -> Block

Analyze the block and validate dependencies.


Block [source]
class Block

Unified block representation for all pipeline stages.

Replaces both BlockValue and Graph 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[Value] = list(),
    output_values: list[Value] = list(),
    operations: list[Operation] = list(),
    kind: BlockKind = BlockKind.HIERARCHICAL,
    parameters: dict[str, Value] = dict(),
    _dependency_graph: dict[str, set[str]] | None = None,
) -> None
Attributes
Methods
from_block_value
@classmethod
def from_block_value(
    cls,
    block_value: 'BlockValue',
    parameters: dict[str, Value] | None = None,
) -> 'Block'

Create a Block from a BlockValue.

Parameters:

NameTypeDescription
block_value'BlockValue'The BlockValue to convert
parametersdict[str, Value] | NoneOptional parameter bindings

Returns:

'Block' — A new Block in HIERARCHICAL state

is_affine
def is_affine(self) -> bool

Check if block contains no CallBlockOperations.

unbound_parameters
def unbound_parameters(self) -> list[str]

Return list of unbound parameter names.


BlockKind [source]
class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

ControlFlowVisitor [source]
class ControlFlowVisitor(ABC)

Base class for visiting operations with control flow handling.

Subclasses override visit_operation to define per-operation behavior. Control flow recursion is handled automatically by the base class.

Example:

class MeasurementCounter(ControlFlowVisitor):
    def __init__(self):
        self.count = 0

    def visit_operation(self, op: Operation) -> None:
        if isinstance(op, MeasureOperation):
            self.count += 1
Methods
visit_operation
def visit_operation(self, op: Operation) -> None

Process a single operation. Override in subclasses.

visit_operations
def visit_operations(self, operations: list[Operation]) -> None

Visit all operations including nested control flow.


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,
)
Attributes

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

OperationKind [source]
class OperationKind(enum.Enum)

Classification of operations for classical/quantum separation.

This enum is used to categorize operations during compilation to determine which parts run on classical hardware vs quantum hardware.

Values:

QUANTUM: Pure quantum operations (gates, qubit allocation) CLASSICAL: Pure classical operations (arithmetic, comparisons) HYBRID: Operations that bridge classical and quantum (measurement, encode/decode) CONTROL: Control flow structures (for, while, if)

Attributes

Pass [source]
class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


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)
Attributes

Value [source]
class Value(Generic[T])

A typed value in the IR with SSA-style versioning.

Value represents a single typed value (qubit, float, int, bit, etc.) with support for:

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
) -> None
Attributes
Methods
get_cast_qubit_logical_ids
def get_cast_qubit_logical_ids(self) -> list[str] | None

Get the underlying qubit logical_ids for this cast value.

get_cast_qubit_uuids
def get_cast_qubit_uuids(self) -> list[str] | None

Get the underlying qubit UUIDs for this cast value.

get_cast_source_logical_id
def get_cast_source_logical_id(self) -> str | None

Get the source value logical_id if this is a cast result.

get_cast_source_uuid
def get_cast_source_uuid(self) -> str | None

Get the source value UUID if this is a cast result.

get_const
def get_const(self) -> int | float | None

Get constant value if available, otherwise None.

get_lowered_bits
def get_lowered_bits(self) -> list[Value] | None

Get lowered bit list if available, otherwise None.

get_lowered_qubits
def get_lowered_qubits(self) -> list[Value] | None

Get lowered qubit list if available, otherwise None.

is_array_element
def is_array_element(self) -> bool

Check if this value is an element of an array.

is_cast_result
def is_cast_result(self) -> bool

Check if this value is the result of a CastOperation.

is_constant
def is_constant(self) -> bool

Check if this value is a constant.

is_parameter
def is_parameter(self) -> bool

Check if this value is an unbound parameter.

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

Create a new Value with incremented version (SSA style).

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter, otherwise None.

set_cast_metadata
def set_cast_metadata(
    self,
    source_uuid: str,
    qubit_uuids: list[str],
    source_logical_id: str | None = None,
    qubit_logical_ids: list[str] | None = None,
) -> None

Set cast metadata for this value.

set_lowered_bits
def set_lowered_bits(self, bits: list[Value]) -> None

Set lowered bit list.

set_lowered_qubits
def set_lowered_qubits(self, qubits: list[Value]) -> None

Set lowered qubit list.


ValueBase [source]
class ValueBase(Protocol)

Protocol defining the common interface for all value types.

This protocol enables:

All value types (Value, ArrayValue, TupleValue, DictValue) implement this protocol.

Attributes
Methods
is_constant
def is_constant(self) -> bool

Check if this value is a constant.

is_parameter
def is_parameter(self) -> bool

Check if this value is an unbound parameter.

next_version
def next_version(self) -> ValueBase

Create a new SSA version with fresh uuid but same logical_id.

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter.


qamomile.circuit.transpiler.passes.compile_time_if_lowering

Compile-time IfOperation lowering pass.

Lowers compile-time resolvable IfOperations before the separate pass, replacing them with selected-branch operations and substituting phi outputs with selected-branch values throughout the block.

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

Overview

FunctionDescription
resolve_if_conditionResolve an if-condition to a compile-time boolean.
ClassDescription
ArrayValueAn array of values with shape information.
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, POW).
BinOpKind
BlockUnified block representation for all pipeline stages.
CompOpComparison operation (EQ, NEQ, LT, LE, GT, GE).
CompOpKind
CompileTimeIfLoweringPassLowers compile-time resolvable IfOperations before separation.
CondOpConditional logical operation (AND, OR).
CondOpKind
IfOperationRepresents an if-else conditional operation.
NotOp
PassBase class for all compiler passes.
PhiOpSSA Phi function: merge point after conditional branch.
ValueA typed value in the IR with SSA-style versioning.
ValueBaseProtocol defining the common interface for all value types.

Functions

resolve_if_condition [source]
def resolve_if_condition(condition: Any, bindings: dict[str, Any]) -> bool | None

Resolve an if-condition to a compile-time boolean.

Checks whether the condition can be statically evaluated at emit time. Plain Python values (int/bool captured by @qkernel from closure), constant-folded Values, and Values resolvable via bindings are all treated as compile-time constants.

Parameters:

NameTypeDescription
conditionAnyThe condition from IfOperation (plain value or Value object).
bindingsdict[str, Any]Current variable bindings (uuid → value and/or name → value).

Returns:

bool | NoneTrue/False for compile-time resolvable conditions, bool | NoneNone for runtime conditions that must be dispatched to the bool | None — backend’s conditional branching protocol.

Classes

ArrayValue [source]
class ArrayValue(Value[T])

An array of values with shape information.

ArrayValue extends Value to represent multi-dimensional arrays of typed values (e.g., qubit registers, parameter vectors).

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    params: dict[str, Any] = dict(),
    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(),
) -> None
Attributes
Methods
next_version
def next_version(self) -> ArrayValue[T]

Create a new ArrayValue with incremented version, preserving shape.


BinOp [source]
class BinOp(BinaryOperationBase)

Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, POW).

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

BinOpKind [source]
class BinOpKind(enum.Enum)
Attributes

Block [source]
class Block

Unified block representation for all pipeline stages.

Replaces both BlockValue and Graph 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[Value] = list(),
    output_values: list[Value] = list(),
    operations: list[Operation] = list(),
    kind: BlockKind = BlockKind.HIERARCHICAL,
    parameters: dict[str, Value] = dict(),
    _dependency_graph: dict[str, set[str]] | None = None,
) -> None
Attributes
Methods
from_block_value
@classmethod
def from_block_value(
    cls,
    block_value: 'BlockValue',
    parameters: dict[str, Value] | None = None,
) -> 'Block'

Create a Block from a BlockValue.

Parameters:

NameTypeDescription
block_value'BlockValue'The BlockValue to convert
parametersdict[str, Value] | NoneOptional parameter bindings

Returns:

'Block' — A new Block in HIERARCHICAL state

is_affine
def is_affine(self) -> bool

Check if block contains no CallBlockOperations.

unbound_parameters
def unbound_parameters(self) -> list[str]

Return list of unbound parameter names.


CompOp [source]
class CompOp(BinaryOperationBase)

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

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

CompOpKind [source]
class CompOpKind(enum.Enum)
Attributes

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. SeparatePass treats them as segment boundaries, causing MultipleQuantumSegmentsError for classical-only compile-time if after quantum init.

This pass:

  1. Evaluates conditions including expression-derived ones (CompOp, CondOp, NotOp chains).

  2. Replaces resolved IfOperations with selected-branch operations.

  3. Substitutes phi output UUIDs with selected-branch values in all subsequent operations and block outputs.

Constructor
def __init__(self, bindings: dict[str, Any] | None = None)
Attributes
Methods
run
def run(self, input: Block) -> Block

Run the compile-time if lowering pass.


CondOp [source]
class CondOp(BinaryOperationBase)

Conditional logical operation (AND, OR).

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

CondOpKind [source]
class CondOpKind(enum.Enum)
Attributes

IfOperation [source]
class IfOperation(Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    phi_ops: list[PhiOp] = list(),
) -> None
Attributes

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

Pass [source]
class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


PhiOp [source]
class PhiOp(Operation)

SSA Phi function: merge point after conditional branch.

This operation selects one of two values based on a condition. Used to merge values from different branches of an if-else statement.

Example:

if condition:
    x = x + 1  # true_value
else:
    x = x + 2  # false_value
# x is now PhiOp(condition, true_value, false_value)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

Value [source]
class Value(Generic[T])

A typed value in the IR with SSA-style versioning.

Value represents a single typed value (qubit, float, int, bit, etc.) with support for:

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
) -> None
Attributes
Methods
get_cast_qubit_logical_ids
def get_cast_qubit_logical_ids(self) -> list[str] | None

Get the underlying qubit logical_ids for this cast value.

get_cast_qubit_uuids
def get_cast_qubit_uuids(self) -> list[str] | None

Get the underlying qubit UUIDs for this cast value.

get_cast_source_logical_id
def get_cast_source_logical_id(self) -> str | None

Get the source value logical_id if this is a cast result.

get_cast_source_uuid
def get_cast_source_uuid(self) -> str | None

Get the source value UUID if this is a cast result.

get_const
def get_const(self) -> int | float | None

Get constant value if available, otherwise None.

get_lowered_bits
def get_lowered_bits(self) -> list[Value] | None

Get lowered bit list if available, otherwise None.

get_lowered_qubits
def get_lowered_qubits(self) -> list[Value] | None

Get lowered qubit list if available, otherwise None.

is_array_element
def is_array_element(self) -> bool

Check if this value is an element of an array.

is_cast_result
def is_cast_result(self) -> bool

Check if this value is the result of a CastOperation.

is_constant
def is_constant(self) -> bool

Check if this value is a constant.

is_parameter
def is_parameter(self) -> bool

Check if this value is an unbound parameter.

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

Create a new Value with incremented version (SSA style).

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter, otherwise None.

set_cast_metadata
def set_cast_metadata(
    self,
    source_uuid: str,
    qubit_uuids: list[str],
    source_logical_id: str | None = None,
    qubit_logical_ids: list[str] | None = None,
) -> None

Set cast metadata for this value.

set_lowered_bits
def set_lowered_bits(self, bits: list[Value]) -> None

Set lowered bit list.

set_lowered_qubits
def set_lowered_qubits(self, qubits: list[Value]) -> None

Set lowered qubit list.


ValueBase [source]
class ValueBase(Protocol)

Protocol defining the common interface for all value types.

This protocol enables:

All value types (Value, ArrayValue, TupleValue, DictValue) implement this protocol.

Attributes
Methods
is_constant
def is_constant(self) -> bool

Check if this value is a constant.

is_parameter
def is_parameter(self) -> bool

Check if this value is an unbound parameter.

next_version
def next_version(self) -> ValueBase

Create a new SSA version with fresh uuid but same logical_id.

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter.


qamomile.circuit.transpiler.passes.constant_fold

Constant folding pass for compile-time expression evaluation.

Overview

ClassDescription
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, POW).
BinOpKind
BlockUnified block representation for all pipeline stages.
ConstantFoldingPassEvaluates constant expressions at compile time.
ControlledUOperationControlled-U operation that applies a unitary block conditionally.
GateOperation
OperationTransformerBase class for transforming operations with control flow handling.
PassBase class for all compiler passes.
ValueA typed value in the IR with SSA-style versioning.
ValueBaseProtocol defining the common interface for all value types.

Classes

BinOp [source]
class BinOp(BinaryOperationBase)

Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, POW).

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

BinOpKind [source]
class BinOpKind(enum.Enum)
Attributes

Block [source]
class Block

Unified block representation for all pipeline stages.

Replaces both BlockValue and Graph 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[Value] = list(),
    output_values: list[Value] = list(),
    operations: list[Operation] = list(),
    kind: BlockKind = BlockKind.HIERARCHICAL,
    parameters: dict[str, Value] = dict(),
    _dependency_graph: dict[str, set[str]] | None = None,
) -> None
Attributes
Methods
from_block_value
@classmethod
def from_block_value(
    cls,
    block_value: 'BlockValue',
    parameters: dict[str, Value] | None = None,
) -> 'Block'

Create a Block from a BlockValue.

Parameters:

NameTypeDescription
block_value'BlockValue'The BlockValue to convert
parametersdict[str, Value] | NoneOptional parameter bindings

Returns:

'Block' — A new Block in HIERARCHICAL state

is_affine
def is_affine(self) -> bool

Check if block contains no CallBlockOperations.

unbound_parameters
def unbound_parameters(self) -> list[str]

Return list of unbound parameter names.


ConstantFoldingPass [source]
class ConstantFoldingPass(Pass[Block, Block])

Evaluates constant expressions at compile time.

This pass folds BinOp operations when all operands are constants or bound parameters, eliminating unnecessary classical operations that would otherwise split quantum segments.

Example:

Before (with bindings={"phase": 0.5}):
    BinOp(phase * 2) -> classical segment split

After:
    Constant 1.0 -> no segment split
Constructor
def __init__(self, bindings: dict[str, Any] | None = None)
Attributes
Methods
run
def run(self, input: Block) -> Block

Run constant folding on the block.


ControlledUOperation [source]
class ControlledUOperation(Operation)

Controlled-U operation that applies a unitary block conditionally.

The operands structure is:

The results structure is:

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_controls: int | Value = 1,
    power: int | Value = 1,
    target_indices: list[Value] | None = None,
    controlled_indices: list[Value] | None = None,
) -> None
Attributes

GateOperation [source]
class GateOperation(Operation)
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    gate_type: GateOperationType | None = None,
    theta: float | Value | None = None,
) -> None
Attributes

OperationTransformer [source]
class OperationTransformer(ABC)

Base class for transforming operations with control flow handling.

Subclasses override transform_operation to define per-operation transformation. Control flow recursion and rebuilding is handled automatically.

Example:

class OperationRenamer(OperationTransformer):
    def transform_operation(self, op: Operation) -> Operation:
        # Return modified operation
        return dataclasses.replace(op, ...)
Methods
transform_operation
def transform_operation(self, op: Operation) -> Operation | None

Transform a single operation. Return None to remove it.

transform_operations
def transform_operations(self, operations: list[Operation]) -> list[Operation]

Transform all operations including nested control flow.


Pass [source]
class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


Value [source]
class Value(Generic[T])

A typed value in the IR with SSA-style versioning.

Value represents a single typed value (qubit, float, int, bit, etc.) with support for:

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
) -> None
Attributes
Methods
get_cast_qubit_logical_ids
def get_cast_qubit_logical_ids(self) -> list[str] | None

Get the underlying qubit logical_ids for this cast value.

get_cast_qubit_uuids
def get_cast_qubit_uuids(self) -> list[str] | None

Get the underlying qubit UUIDs for this cast value.

get_cast_source_logical_id
def get_cast_source_logical_id(self) -> str | None

Get the source value logical_id if this is a cast result.

get_cast_source_uuid
def get_cast_source_uuid(self) -> str | None

Get the source value UUID if this is a cast result.

get_const
def get_const(self) -> int | float | None

Get constant value if available, otherwise None.

get_lowered_bits
def get_lowered_bits(self) -> list[Value] | None

Get lowered bit list if available, otherwise None.

get_lowered_qubits
def get_lowered_qubits(self) -> list[Value] | None

Get lowered qubit list if available, otherwise None.

is_array_element
def is_array_element(self) -> bool

Check if this value is an element of an array.

is_cast_result
def is_cast_result(self) -> bool

Check if this value is the result of a CastOperation.

is_constant
def is_constant(self) -> bool

Check if this value is a constant.

is_parameter
def is_parameter(self) -> bool

Check if this value is an unbound parameter.

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

Create a new Value with incremented version (SSA style).

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter, otherwise None.

set_cast_metadata
def set_cast_metadata(
    self,
    source_uuid: str,
    qubit_uuids: list[str],
    source_logical_id: str | None = None,
    qubit_logical_ids: list[str] | None = None,
) -> None

Set cast metadata for this value.

set_lowered_bits
def set_lowered_bits(self, bits: list[Value]) -> None

Set lowered bit list.

set_lowered_qubits
def set_lowered_qubits(self, qubits: list[Value]) -> None

Set lowered qubit list.


ValueBase [source]
class ValueBase(Protocol)

Protocol defining the common interface for all value types.

This protocol enables:

All value types (Value, ArrayValue, TupleValue, DictValue) implement this protocol.

Attributes
Methods
is_constant
def is_constant(self) -> bool

Check if this value is a constant.

is_parameter
def is_parameter(self) -> bool

Check if this value is an unbound parameter.

next_version
def next_version(self) -> ValueBase

Create a new SSA version with fresh uuid but same logical_id.

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter.


qamomile.circuit.transpiler.passes.control_flow_visitor

Control flow visitor for operation traversal.

Overview

ClassDescription
ControlFlowVisitorBase class for visiting operations with control flow handling.
ForOperationRepresents a for loop operation.
IfOperationRepresents an if-else conditional operation.
OperationCollectorCollects operations matching a predicate.
OperationTransformerBase class for transforming operations with control flow handling.
ValueCollectorCollects Value UUIDs from operation operands and results.
WhileOperationRepresents a while loop operation.

Classes

ControlFlowVisitor [source]
class ControlFlowVisitor(ABC)

Base class for visiting operations with control flow handling.

Subclasses override visit_operation to define per-operation behavior. Control flow recursion is handled automatically by the base class.

Example:

class MeasurementCounter(ControlFlowVisitor):
    def __init__(self):
        self.count = 0

    def visit_operation(self, op: Operation) -> None:
        if isinstance(op, MeasureOperation):
            self.count += 1
Methods
visit_operation
def visit_operation(self, op: Operation) -> None

Process a single operation. Override in subclasses.

visit_operations
def visit_operations(self, operations: list[Operation]) -> None

Visit all operations including nested control flow.


ForOperation [source]
class ForOperation(Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    operations: list[Operation] = list(),
) -> None
Attributes

IfOperation [source]
class IfOperation(Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    phi_ops: list[PhiOp] = list(),
) -> None
Attributes

OperationCollector [source]
class OperationCollector(ControlFlowVisitor)

Collects operations matching a predicate.

Example:

collector = OperationCollector(lambda op: isinstance(op, MeasureOperation))
collector.visit_operations(block.operations)
measurements = collector.collected
Constructor
def __init__(self, predicate: Callable[[Operation], bool])
Attributes
Methods
visit_operation
def visit_operation(self, op: Operation) -> None

OperationTransformer [source]
class OperationTransformer(ABC)

Base class for transforming operations with control flow handling.

Subclasses override transform_operation to define per-operation transformation. Control flow recursion and rebuilding is handled automatically.

Example:

class OperationRenamer(OperationTransformer):
    def transform_operation(self, op: Operation) -> Operation:
        # Return modified operation
        return dataclasses.replace(op, ...)
Methods
transform_operation
def transform_operation(self, op: Operation) -> Operation | None

Transform a single operation. Return None to remove it.

transform_operations
def transform_operations(self, operations: list[Operation]) -> list[Operation]

Transform all operations including nested control flow.


ValueCollector [source]
class ValueCollector(ControlFlowVisitor)

Collects Value UUIDs from operation operands and results.

Constructor
def __init__(self)
Attributes
Methods
visit_operation
def visit_operation(self, op: Operation) -> None

WhileOperation [source]
class WhileOperation(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 backend 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(),
) -> None
Attributes

qamomile.circuit.transpiler.passes.emit

Emit pass: Generate backend-specific code from separated program.

Overview

ClassDescription
ClassicalSegmentA segment of pure classical operations.
CompositeGateEmitterProtocol for backend-specific CompositeGate emitters.
CompositeGateOperationRepresents a composite gate (QPE, QFT, etc.) as a single operation.
CompositeGateTypeRegistry of known composite gate types.
EmitPassBase class for backend-specific emission passes.
ExecutableProgramA fully compiled program ready for execution.
ExpvalSegmentA segment for expectation value computation.
PassBase class for all compiler passes.
QuantumSegmentA segment of pure quantum operations.
SimplifiedProgramEnforces Classical → Quantum → Classical pattern.
ValueA typed value in the IR with SSA-style versioning.

Classes

ClassicalSegment [source]
class ClassicalSegment(Segment)

A segment of pure classical operations.

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

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

CompositeGateEmitter [source]
class CompositeGateEmitter(Protocol[C])

Protocol for backend-specific CompositeGate emitters.

Each backend can implement emitters for specific composite gate types (QPE, QFT, IQFT, etc.) using native backend libraries.

The emitter pattern allows:

  1. Backends to use native implementations when available (e.g., Qiskit QFT)

  2. Fallback to manual decomposition when native is unavailable

  3. Easy addition of new backends without modifying core code

Example:

class QiskitQFTEmitter:
    def can_emit(self, gate_type: CompositeGateType) -> bool:
        return gate_type in (CompositeGateType.QFT, CompositeGateType.IQFT)

    def emit(self, circuit, op, qubit_indices, bindings) -> bool:
        from qiskit.circuit.library import QFTGate
        qft_gate = QFTGate(len(qubit_indices))
        circuit.append(qft_gate, qubit_indices)
        return True
Methods
can_emit
def can_emit(self, gate_type: CompositeGateType) -> bool

Check if this emitter can handle the given gate type.

Parameters:

NameTypeDescription
gate_typeCompositeGateTypeThe CompositeGateType to check

Returns:

bool — True if this emitter supports native emission for the gate type

emit
def emit(
    self,
    circuit: C,
    op: CompositeGateOperation,
    qubit_indices: list[int],
    bindings: dict[str, Any],
) -> bool

Emit the composite gate to the circuit.

Parameters:

NameTypeDescription
circuitCThe backend-specific circuit to emit to
opCompositeGateOperationThe CompositeGateOperation to emit
qubit_indiceslist[int]Physical qubit indices for the operation
bindingsdict[str, Any]Parameter bindings for the operation

Returns:

bool — True if emission succeeded, False to fall back to manual decomposition


CompositeGateOperation [source]
class CompositeGateOperation(Operation)

Represents a composite gate (QPE, QFT, etc.) as a single operation.

CompositeGate allows representing complex multi-gate operations as a single atomic operation in the IR. This enables:

The operands structure depends on has_implementation:

The results structure:

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    gate_type: CompositeGateType = CompositeGateType.CUSTOM,
    num_control_qubits: int = 0,
    num_target_qubits: int = 0,
    custom_name: str = '',
    resource_metadata: ResourceMetadata | None = None,
    has_implementation: bool = True,
    composite_gate_instance: Any = None,
    strategy_name: str | None = None,
) -> None
Attributes

CompositeGateType [source]
class CompositeGateType(enum.Enum)

Registry of known composite gate types.

Attributes

EmitPass [source]
class EmitPass(Pass[SimplifiedProgram, ExecutableProgram[T]], Generic[T])

Base class for backend-specific emission passes.

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

Input: SimplifiedProgram (enforces C→Q→C pattern) 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 backend parameters.
Attributes
Methods
run
def run(self, input: SimplifiedProgram) -> ExecutableProgram[T]

Emit backend code from simplified program.


ExecutableProgram [source]
class ExecutableProgram(Generic[T])

A fully compiled program ready for execution.

This is the Orchestrator - manages execution of mixed classical/quantum programs.

Example:

executable = transpiler.compile(kernel)

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

# Run: single shot, returns typed result
job = executable.run(executor)
result = job.result()  # Returns kernel's return type
Constructor
def __init__(
    self,
    compiled_quantum: list[CompiledQuantumSegment[T]] = list(),
    compiled_classical: list[CompiledClassicalSegment] = list(),
    compiled_expval: list[CompiledExpvalSegment] = list(),
    execution_order: list[tuple[str, int]] = list(),
    output_refs: list[str] = list(),
    num_output_bits: int = 0,
) -> None
Attributes
Methods
get_circuits
def get_circuits(self) -> list[T]

Get all quantum circuits in execution order.

get_first_circuit
def get_first_circuit(self) -> T | None

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

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

Execute once and return single result.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Backend-specific quantum executor.
bindingsdict[str, Any] | NoneParameter bindings. Supports two formats: - Vector: {“gammas”: [0.1, 0.2], “betas”: [0.3, 0.4]} - Indexed: {“gammas[0]”: 0.1, “gammas[1]”: 0.2}

Returns:

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

Raises:

Example:

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

Execute with multiple shots and return counts.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Backend-specific quantum executor.
shotsintNumber of shots to run.
bindingsdict[str, Any] | NoneParameter bindings. Supports two formats: - Vector: {“gammas”: [0.1, 0.2], “betas”: [0.3, 0.4]} - Indexed: {“gammas[0]”: 0.1, “gammas[1]”: 0.2}

Returns:

SampleJob[Any] — SampleJob that resolves to SampleResult with results.

Raises:

Example:

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

ExpvalSegment [source]
class ExpvalSegment(Segment)

A segment for expectation value computation.

Represents computing <psi|H|psi> where psi is the quantum state and H is a Hamiltonian observable.

This segment bridges a quantum circuit (state preparation) to a classical expectation value.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
    hamiltonian_value: Value | None = None,
    qubits_value: Value | None = None,
    result_ref: str = '',
) -> None
Attributes

Pass [source]
class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


QuantumSegment [source]
class QuantumSegment(Segment)

A segment of pure quantum operations.

Contains quantum gates and qubit allocations. Will be emitted to a quantum circuit.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
    qubit_values: list[Value] = list(),
    num_qubits: int = 0,
) -> None
Attributes

SimplifiedProgram [source]
class SimplifiedProgram

Enforces Classical → Quantum → Classical pattern.

Structure:

This replaces SeparatedProgram to enforce Qamomile’s execution model: all quantum operations must be in a single quantum circuit.

Constructor
def __init__(
    self,
    quantum: QuantumSegment,
    classical_prep: ClassicalSegment | None = None,
    expval: ExpvalSegment | None = None,
    classical_post: ClassicalSegment | None = None,
    boundaries: list[HybridBoundary] = list(),
    parameters: dict[str, Value] = dict(),
    output_refs: list[str] = list(),
) -> None
Attributes

Value [source]
class Value(Generic[T])

A typed value in the IR with SSA-style versioning.

Value represents a single typed value (qubit, float, int, bit, etc.) with support for:

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
) -> None
Attributes
Methods
get_cast_qubit_logical_ids
def get_cast_qubit_logical_ids(self) -> list[str] | None

Get the underlying qubit logical_ids for this cast value.

get_cast_qubit_uuids
def get_cast_qubit_uuids(self) -> list[str] | None

Get the underlying qubit UUIDs for this cast value.

get_cast_source_logical_id
def get_cast_source_logical_id(self) -> str | None

Get the source value logical_id if this is a cast result.

get_cast_source_uuid
def get_cast_source_uuid(self) -> str | None

Get the source value UUID if this is a cast result.

get_const
def get_const(self) -> int | float | None

Get constant value if available, otherwise None.

get_lowered_bits
def get_lowered_bits(self) -> list[Value] | None

Get lowered bit list if available, otherwise None.

get_lowered_qubits
def get_lowered_qubits(self) -> list[Value] | None

Get lowered qubit list if available, otherwise None.

is_array_element
def is_array_element(self) -> bool

Check if this value is an element of an array.

is_cast_result
def is_cast_result(self) -> bool

Check if this value is the result of a CastOperation.

is_constant
def is_constant(self) -> bool

Check if this value is a constant.

is_parameter
def is_parameter(self) -> bool

Check if this value is an unbound parameter.

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

Create a new Value with incremented version (SSA style).

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter, otherwise None.

set_cast_metadata
def set_cast_metadata(
    self,
    source_uuid: str,
    qubit_uuids: list[str],
    source_logical_id: str | None = None,
    qubit_logical_ids: list[str] | None = None,
) -> None

Set cast metadata for this value.

set_lowered_bits
def set_lowered_bits(self, bits: list[Value]) -> None

Set lowered bit list.

set_lowered_qubits
def set_lowered_qubits(self, qubits: list[Value]) -> None

Set lowered qubit list.


qamomile.circuit.transpiler.passes.emit_base

Base classes for emit pass implementation.

This module provides backend-agnostic helper classes for resource allocation, value resolution, and loop analysis. These are used by StandardEmitPass to implement the emission logic without backend-specific code.

Overview

FunctionDescription
map_phi_outputsRegister phi output UUIDs to the same physical resources as their source operands.
remap_static_phi_outputsRemap phi outputs for a compile-time constant IfOperation.
resolve_if_conditionResolve an if-condition to a compile-time boolean.
ClassDescription
ArrayValueAn array of values with shape information.
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, POW).
BitTypeType representing a classical bit.
CastOperationType cast operation for creating aliases over the same quantum resources.
CompositeDecomposerDecomposes composite gates into primitive operations.
CompositeGateOperationRepresents a composite gate (QPE, QFT, etc.) as a single operation.
ControlledUOperationControlled-U operation that applies a unitary block conditionally.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
GateOperation
IfOperationRepresents an if-else conditional operation.
LoopAnalyzerAnalyzes loop structures to determine emission strategy.
MeasureOperation
MeasureQFixedOperationMeasure a quantum fixed-point number.
MeasureVectorOperationMeasure a vector of qubits.
PhiOpSSA Phi function: merge point after conditional branch.
QInitOperationInitialize the qubit
QubitResolutionResultResult of attempting to resolve a qubit index.
ResolutionFailureReasonCategorizes why qubit index resolution failed.
ResourceAllocatorAllocates qubit and classical bit indices from operations.
ValueA typed value in the IR with SSA-style versioning.
ValueResolverResolves Value objects to concrete indices or values.
WhileOperationRepresents a while loop operation.

Functions

map_phi_outputs [source]
def map_phi_outputs(
    phi_ops: list[Operation],
    qubit_map: dict[str, int],
    clbit_map: dict[str, int],
    resolve_scalar_qubit: Any = None,
) -> None

Register phi output UUIDs to the same physical resources as their source operands.

After an if-else block, PhiOp merges values from both branches. The phi output is a new Value with a new UUID that must map to the same physical qubit (or classical bit) as the branch values.

For ArrayValue phi outputs (e.g., qubit arrays), this copies all composite element keys {source_uuid}_{i}{output_uuid}_{i} so that subsequent element accesses on the phi output resolve to the correct physical qubits.

Parameters:

NameTypeDescription
phi_opslist[Operation]List of phi operations from an IfOperation.
qubit_mapdict[str, int]Mapping from UUID/composite key to physical qubit index.
clbit_mapdict[str, int]Mapping from UUID to physical classical bit index.
resolve_scalar_qubitAnyOptional callback (source, qubit_map) -> int | None for resolving scalar qubit values that are not directly in qubit_map (e.g., array element resolution). When None, ResourceAllocator._resolve_qubit_key is used as fallback.

Raises:


remap_static_phi_outputs [source]
def remap_static_phi_outputs(
    phi_ops: list[Operation],
    condition_value: bool,
    qubit_map: dict[str, int],
    clbit_map: dict[str, int],
) -> None

Remap phi outputs for a compile-time constant IfOperation.

When the condition is statically known, the dead branch is never allocated. Phi outputs are aliased directly to the selected branch’s source value, bypassing the two-branch merge validation in map_phi_outputs.

This is the shared implementation used by both the resource allocator (during allocation) and the emit pass (during emission) to ensure scalar and array quantum phi outputs are handled identically.

Parameters:

NameTypeDescription
phi_opslist[Operation]Phi operations from the IfOperation.
condition_valueboolThe resolved boolean condition.
qubit_mapdict[str, int]UUID-to-physical-qubit mapping (mutated in place).
clbit_mapdict[str, int]UUID-to-physical-clbit mapping (mutated in place).

resolve_if_condition [source]
def resolve_if_condition(condition: Any, bindings: dict[str, Any]) -> bool | None

Resolve an if-condition to a compile-time boolean.

Checks whether the condition can be statically evaluated at emit time. Plain Python values (int/bool captured by @qkernel from closure), constant-folded Values, and Values resolvable via bindings are all treated as compile-time constants.

Parameters:

NameTypeDescription
conditionAnyThe condition from IfOperation (plain value or Value object).
bindingsdict[str, Any]Current variable bindings (uuid → value and/or name → value).

Returns:

bool | NoneTrue/False for compile-time resolvable conditions, bool | NoneNone for runtime conditions that must be dispatched to the bool | None — backend’s conditional branching protocol.

Classes

ArrayValue [source]
class ArrayValue(Value[T])

An array of values with shape information.

ArrayValue extends Value to represent multi-dimensional arrays of typed values (e.g., qubit registers, parameter vectors).

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    params: dict[str, Any] = dict(),
    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(),
) -> None
Attributes
Methods
next_version
def next_version(self) -> ArrayValue[T]

Create a new ArrayValue with incremented version, preserving shape.


BinOp [source]
class BinOp(BinaryOperationBase)

Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, POW).

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

BitType [source]
class BitType(ClassicalTypeMixin, ValueType)

Type representing a classical bit.


CastOperation [source]
class CastOperation(Operation)

Type cast operation for creating aliases over the same quantum resources.

This operation does NOT allocate new qubits. It creates a new Value that references the same underlying quantum resources with a different type.

Use cases:

operands: [source_value] - The value being cast results: [cast_result] - The new value with target type (same physical qubits)

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    source_type: ValueType | None = None,
    target_type: ValueType | None = None,
    qubit_mapping: list[str] = list(),
) -> None
Attributes

CompositeDecomposer [source]
class CompositeDecomposer

Decomposes composite gates into primitive operations.

Provides algorithms for QFT, IQFT, and QPE decomposition that backends can use for fallback when native implementations are unavailable.

Methods
iqft_structure
@staticmethod
def iqft_structure(n: int) -> list[tuple[str, tuple[int, ...], float | None]]

Generate inverse QFT gate sequence.

Parameters:

NameTypeDescription
nintNumber of qubits

Returns:

list[tuple[str, tuple[int, ...], float | None]] — List of (gate_name, qubit_indices, angle) tuples

qft_structure
@staticmethod
def qft_structure(n: int) -> list[tuple[str, tuple[int, ...], float | None]]

Generate QFT gate sequence.

Parameters:

NameTypeDescription
nintNumber of qubits

Returns:

list[tuple[str, tuple[int, ...], float | None]] — List of (gate_name, qubit_indices, angle) tuples


CompositeGateOperation [source]
class CompositeGateOperation(Operation)

Represents a composite gate (QPE, QFT, etc.) as a single operation.

CompositeGate allows representing complex multi-gate operations as a single atomic operation in the IR. This enables:

The operands structure depends on has_implementation:

The results structure:

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    gate_type: CompositeGateType = CompositeGateType.CUSTOM,
    num_control_qubits: int = 0,
    num_target_qubits: int = 0,
    custom_name: str = '',
    resource_metadata: ResourceMetadata | None = None,
    has_implementation: bool = True,
    composite_gate_instance: Any = None,
    strategy_name: str | None = None,
) -> None
Attributes

ControlledUOperation [source]
class ControlledUOperation(Operation)

Controlled-U operation that applies a unitary block conditionally.

The operands structure is:

The results structure is:

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_controls: int | Value = 1,
    power: int | Value = 1,
    target_indices: list[Value] | None = None,
    controlled_indices: list[Value] | None = None,
) -> None
Attributes

ForItemsOperation [source]
class ForItemsOperation(Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    operations: list[Operation] = list(),
) -> None
Attributes

ForOperation [source]
class ForOperation(Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    operations: list[Operation] = list(),
) -> None
Attributes

GateOperation [source]
class GateOperation(Operation)
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    gate_type: GateOperationType | None = None,
    theta: float | Value | None = None,
) -> None
Attributes

IfOperation [source]
class IfOperation(Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    phi_ops: list[PhiOp] = list(),
) -> None
Attributes

LoopAnalyzer [source]
class LoopAnalyzer

Analyzes loop structures to determine emission strategy.

Determines whether loops should use native backend control flow or be unrolled at emission time.

Methods
should_unroll
def should_unroll(self, op: ForOperation, bindings: dict[str, Any]) -> bool

Determine if a ForOperation should be unrolled.

Parameters:

NameTypeDescription
opForOperationThe ForOperation to analyze
bindingsdict[str, Any]Current variable bindings

Returns:

bool — True if loop should be unrolled, False for native emission


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

MeasureQFixedOperation [source]
class MeasureQFixedOperation(Operation)

Measure a quantum fixed-point number.

This operation measures all qubits in a QFixed register and produces a Float result. During transpilation, this is lowered to individual MeasureOperations plus a DecodeQFixedOperation.

operands: [QFixed value (contains qubit_values in params)] results: [Float value]

Encoding:

For QPE phase (int_bits=0): float_value = 0.b0b1b2... = b00.5 + b10.25 + b2*0.125 + ...

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

MeasureVectorOperation [source]
class MeasureVectorOperation(Operation)

Measure a vector of qubits.

Takes a Vector[Qubit] (ArrayValue) and produces a Vector[Bit] (ArrayValue). This operation measures all qubits in the vector as a single operation.

operands: [ArrayValue of qubits] results: [ArrayValue of bits]

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

PhiOp [source]
class PhiOp(Operation)

SSA Phi function: merge point after conditional branch.

This operation selects one of two values based on a condition. Used to merge values from different branches of an if-else statement.

Example:

if condition:
    x = x + 1  # true_value
else:
    x = x + 2  # false_value
# x is now PhiOp(condition, true_value, false_value)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

QInitOperation [source]
class QInitOperation(Operation)

Initialize the qubit

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

QubitResolutionResult [source]
class QubitResolutionResult

Result of attempting to resolve a qubit index.

Constructor
def __init__(
    self,
    success: bool,
    index: int | None = None,
    failure_reason: ResolutionFailureReason | None = None,
    failure_details: str = '',
) -> None
Attributes

ResolutionFailureReason [source]
class ResolutionFailureReason(Enum)

Categorizes why qubit index resolution failed.

Attributes

ResourceAllocator [source]
class ResourceAllocator

Allocates qubit and classical bit indices from operations.

This class handles the first pass of circuit emission: determining how many physical qubits and classical bits are needed and mapping Value UUIDs to their physical indices.

New physical indices are assigned via monotonic counters (_next_qubit_index / _next_clbit_index) so that alias entries — which reuse an existing physical index — never inflate the counter. Using len(map) would cause sparse (gapped) physical indices because alias keys increase the map size without adding new physical resources.

Constructor
def __init__(self) -> None
Methods
allocate
def allocate(
    self,
    operations: list[Operation],
    bindings: dict[str, Any] | None = None,
) -> tuple[dict[str, int], dict[str, int]]

Allocate qubit and clbit indices for all operations.

Parameters:

NameTypeDescription
operationslist[Operation]List of operations to allocate resources for
bindingsdict[str, Any] | NoneOptional variable bindings for resolving dynamic sizes

Returns:

tuple[dict[str, int], dict[str, int]] — Tuple of (qubit_map, clbit_map) where each maps UUID to index


Value [source]
class Value(Generic[T])

A typed value in the IR with SSA-style versioning.

Value represents a single typed value (qubit, float, int, bit, etc.) with support for:

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
) -> None
Attributes
Methods
get_cast_qubit_logical_ids
def get_cast_qubit_logical_ids(self) -> list[str] | None

Get the underlying qubit logical_ids for this cast value.

get_cast_qubit_uuids
def get_cast_qubit_uuids(self) -> list[str] | None

Get the underlying qubit UUIDs for this cast value.

get_cast_source_logical_id
def get_cast_source_logical_id(self) -> str | None

Get the source value logical_id if this is a cast result.

get_cast_source_uuid
def get_cast_source_uuid(self) -> str | None

Get the source value UUID if this is a cast result.

get_const
def get_const(self) -> int | float | None

Get constant value if available, otherwise None.

get_lowered_bits
def get_lowered_bits(self) -> list[Value] | None

Get lowered bit list if available, otherwise None.

get_lowered_qubits
def get_lowered_qubits(self) -> list[Value] | None

Get lowered qubit list if available, otherwise None.

is_array_element
def is_array_element(self) -> bool

Check if this value is an element of an array.

is_cast_result
def is_cast_result(self) -> bool

Check if this value is the result of a CastOperation.

is_constant
def is_constant(self) -> bool

Check if this value is a constant.

is_parameter
def is_parameter(self) -> bool

Check if this value is an unbound parameter.

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

Create a new Value with incremented version (SSA style).

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter, otherwise None.

set_cast_metadata
def set_cast_metadata(
    self,
    source_uuid: str,
    qubit_uuids: list[str],
    source_logical_id: str | None = None,
    qubit_logical_ids: list[str] | None = None,
) -> None

Set cast metadata for this value.

set_lowered_bits
def set_lowered_bits(self, bits: list[Value]) -> None

Set lowered bit list.

set_lowered_qubits
def set_lowered_qubits(self, qubits: list[Value]) -> None

Set lowered qubit list.


ValueResolver [source]
class ValueResolver

Resolves Value objects to concrete indices or values.

Handles the mapping from IR Value objects to physical qubit indices, classical values, and parameter names during emission.

Constructor
def __init__(self, parameters: set[str] | None = None)

Initialize the resolver.

Parameters:

NameTypeDescription
parametersset[str] | NoneSet of parameter names to preserve as symbolic
Attributes
Methods
get_parameter_key
def get_parameter_key(self, value: 'Value', bindings: dict[str, Any]) -> str | None

Get parameter key if this value should be a symbolic parameter.

Parameters:

NameTypeDescription
value'Value'The Value to check
bindingsdict[str, Any]Current bindings (for resolving array indices)

Returns:

str | None — Parameter key (e.g., “gammas[0]”) if symbolic, None otherwise

resolve_classical_value
def resolve_classical_value(self, value: 'Value', bindings: dict[str, Any]) -> Any

Resolve a classical Value to a concrete Python value.

Parameters:

NameTypeDescription
value'Value'The Value to resolve
bindingsdict[str, Any]Current variable bindings

Returns:

Any — Resolved value (int, float, etc.), or None if cannot resolve

resolve_int_value
def resolve_int_value(self, val: Any, bindings: dict[str, Any]) -> int | None

Resolve a value to an integer (for loop bounds, etc.).

Parameters:

NameTypeDescription
valAnyThe value to resolve
bindingsdict[str, Any]Current variable bindings

Returns:

int | None — Integer value, or None if cannot resolve

resolve_qubit_index
def resolve_qubit_index(
    self,
    v: 'Value',
    qubit_map: dict[str, int],
    bindings: dict[str, Any],
) -> int | None

Resolve a Value to a physical qubit index.

Parameters:

NameTypeDescription
v'Value'The Value to resolve
qubit_mapdict[str, int]Mapping from UUID to qubit index
bindingsdict[str, Any]Current variable bindings

Returns:

int | None — Physical qubit index, or None if cannot resolve

resolve_qubit_index_detailed
def resolve_qubit_index_detailed(
    self,
    v: 'Value',
    qubit_map: dict[str, int],
    bindings: dict[str, Any],
) -> QubitResolutionResult

Resolve a Value to a physical qubit index with detailed failure info.

Parameters:

NameTypeDescription
v'Value'The Value to resolve
qubit_mapdict[str, int]Mapping from UUID to qubit index
bindingsdict[str, Any]Current variable bindings

Returns:

QubitResolutionResult — QubitResolutionResult with success status and either index or failure details


WhileOperation [source]
class WhileOperation(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 backend 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(),
) -> None
Attributes

qamomile.circuit.transpiler.passes.inline

Inline pass: Inline CallBlockOperations to create an affine block.

Overview

FunctionDescription
find_return_operationFind the ReturnOperation in a list of operations (expected at the end).
ClassDescription
ArrayValueAn array of values with shape information.
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
BlockValueRepresents a subroutine as a function block.
CallBlockOperation
CompositeGateOperationRepresents a composite gate (QPE, QFT, etc.) as a single operation.
CompositeGateTypeRegistry of known composite gate types.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
IfOperationRepresents an if-else conditional operation.
InlinePassInline all CallBlockOperations to create an affine block.
PassBase class for all compiler passes.
ReturnOperationExplicit return operation marking the end of a block with return values.
UUIDRemapperClones values and operations with fresh UUIDs and logical_ids.
ValueA typed value in the IR with SSA-style versioning.
ValueSubstitutorSubstitutes values in operations using a mapping.
WhileOperationRepresents a while loop operation.

Functions

find_return_operation [source]
def find_return_operation(operations: list[Operation]) -> ReturnOperation | None

Find the ReturnOperation in a list of operations (expected at the end).

Classes

ArrayValue [source]
class ArrayValue(Value[T])

An array of values with shape information.

ArrayValue extends Value to represent multi-dimensional arrays of typed values (e.g., qubit registers, parameter vectors).

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    params: dict[str, Any] = dict(),
    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(),
) -> None
Attributes
Methods
next_version
def next_version(self) -> ArrayValue[T]

Create a new ArrayValue with incremented version, preserving shape.


Block [source]
class Block

Unified block representation for all pipeline stages.

Replaces both BlockValue and Graph 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[Value] = list(),
    output_values: list[Value] = list(),
    operations: list[Operation] = list(),
    kind: BlockKind = BlockKind.HIERARCHICAL,
    parameters: dict[str, Value] = dict(),
    _dependency_graph: dict[str, set[str]] | None = None,
) -> None
Attributes
Methods
from_block_value
@classmethod
def from_block_value(
    cls,
    block_value: 'BlockValue',
    parameters: dict[str, Value] | None = None,
) -> 'Block'

Create a Block from a BlockValue.

Parameters:

NameTypeDescription
block_value'BlockValue'The BlockValue to convert
parametersdict[str, Value] | NoneOptional parameter bindings

Returns:

'Block' — A new Block in HIERARCHICAL state

is_affine
def is_affine(self) -> bool

Check if block contains no CallBlockOperations.

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

BlockValue [source]
class BlockValue(Value[BlockType])

Represents a subroutine as a function block.

def func_block(a: UInt, b: UInt) -> tuple[UInt]: ...

BlockValue( name=“func_block”, inputs_type={“a”: UIntType(), “b”: UIntType()}, outputs_type=(UIntType(), ), operations=[...], )

Function to BlockValue conversion can be done via func_to_block function. Each Values in operations are dummy values. The execution of the BlockValue is corresponding to the BlockOperation.

Constructor
def __init__(
    self,
    type: BlockType = BlockType(),
    name: str = '',
    version: int = 0,
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
    label_args: list[str] = list(),
    input_values: list[Value] = list(),
    return_values: list[Value] = list(),
    operations: list[Operation] = list(),
) -> None
Attributes
Methods
call
def call(self, **kwargs: Value = {}) -> 'CallBlockOperation'

Create a CallBlockOperation to call this BlockValue.

Example:

block_value = BlockValue(
    name="func_block",
    inputs_type={"a": UIntType(), "b": UIntType()},
    outputs_type=(UIntType(), ),
    operations=[...],
)
a = Value(UIntType())
b = Value(UIntType())
call_op = block_value.call(a=a, b=b)

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

CompositeGateOperation [source]
class CompositeGateOperation(Operation)

Represents a composite gate (QPE, QFT, etc.) as a single operation.

CompositeGate allows representing complex multi-gate operations as a single atomic operation in the IR. This enables:

The operands structure depends on has_implementation:

The results structure:

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    gate_type: CompositeGateType = CompositeGateType.CUSTOM,
    num_control_qubits: int = 0,
    num_target_qubits: int = 0,
    custom_name: str = '',
    resource_metadata: ResourceMetadata | None = None,
    has_implementation: bool = True,
    composite_gate_instance: Any = None,
    strategy_name: str | None = None,
) -> None
Attributes

CompositeGateType [source]
class CompositeGateType(enum.Enum)

Registry of known composite gate types.

Attributes

ForItemsOperation [source]
class ForItemsOperation(Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    operations: list[Operation] = list(),
) -> None
Attributes

ForOperation [source]
class ForOperation(Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    operations: list[Operation] = list(),
) -> None
Attributes

IfOperation [source]
class IfOperation(Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    phi_ops: list[PhiOp] = list(),
) -> None
Attributes

InlinePass [source]
class InlinePass(Pass[Block, Block])

Inline all CallBlockOperations to create an affine block.

This pass recursively inlines function calls while preserving control flow structures (For, If, While).

Input: Block with BlockKind.HIERARCHICAL (may contain CallBlockOperations) Output: Block with BlockKind.AFFINE (no CallBlockOperations)

Attributes
Methods
run
def run(self, input: Block) -> Block

Inline all CallBlockOperations.


Pass [source]
class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


ReturnOperation [source]
class ReturnOperation(Operation)

Explicit return operation marking the end of a block with return values.

This operation represents an explicit return statement in the IR. It takes the values to be returned as operands and produces no results (it is a terminal operation that transfers control flow back to the caller).

operands: [Value, ...] - The values to return (may be empty for void returns) results: [] - Always empty (terminal operation)

Example:

A function that returns two values (a UInt and a Float):

ReturnOperation(
    operands=[uint_value, float_value],
    results=[],
)

The signature would be:
    operands=[ParamHint("return_0", UIntType()), ParamHint("return_1", FloatType())]
    results=[]
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

UUIDRemapper [source]
class UUIDRemapper

Clones values and operations with fresh UUIDs and logical_ids.

Used during inlining to create unique identities for values when a block is called multiple times.

Constructor
def __init__(self)
Attributes
Methods
clone_operation
def clone_operation(self, op: Operation) -> Operation

Clone an operation with fresh UUIDs for all values.

clone_operations
def clone_operations(self, operations: list[Operation]) -> list[Operation]

Clone a list of operations with fresh UUIDs.

clone_value
def clone_value(self, value: ValueBase) -> ValueBase

Clone any value type with a fresh UUID and logical_id.

Handles Value, ArrayValue, TupleValue, and DictValue through the unified ValueBase protocol.


Value [source]
class Value(Generic[T])

A typed value in the IR with SSA-style versioning.

Value represents a single typed value (qubit, float, int, bit, etc.) with support for:

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
) -> None
Attributes
Methods
get_cast_qubit_logical_ids
def get_cast_qubit_logical_ids(self) -> list[str] | None

Get the underlying qubit logical_ids for this cast value.

get_cast_qubit_uuids
def get_cast_qubit_uuids(self) -> list[str] | None

Get the underlying qubit UUIDs for this cast value.

get_cast_source_logical_id
def get_cast_source_logical_id(self) -> str | None

Get the source value logical_id if this is a cast result.

get_cast_source_uuid
def get_cast_source_uuid(self) -> str | None

Get the source value UUID if this is a cast result.

get_const
def get_const(self) -> int | float | None

Get constant value if available, otherwise None.

get_lowered_bits
def get_lowered_bits(self) -> list[Value] | None

Get lowered bit list if available, otherwise None.

get_lowered_qubits
def get_lowered_qubits(self) -> list[Value] | None

Get lowered qubit list if available, otherwise None.

is_array_element
def is_array_element(self) -> bool

Check if this value is an element of an array.

is_cast_result
def is_cast_result(self) -> bool

Check if this value is the result of a CastOperation.

is_constant
def is_constant(self) -> bool

Check if this value is a constant.

is_parameter
def is_parameter(self) -> bool

Check if this value is an unbound parameter.

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

Create a new Value with incremented version (SSA style).

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter, otherwise None.

set_cast_metadata
def set_cast_metadata(
    self,
    source_uuid: str,
    qubit_uuids: list[str],
    source_logical_id: str | None = None,
    qubit_logical_ids: list[str] | None = None,
) -> None

Set cast metadata for this value.

set_lowered_bits
def set_lowered_bits(self, bits: list[Value]) -> None

Set lowered bit list.

set_lowered_qubits
def set_lowered_qubits(self, qubits: list[Value]) -> None

Set lowered qubit list.


ValueSubstitutor [source]
class ValueSubstitutor

Substitutes values in operations using a mapping.

Used during inlining to replace block parameters with caller arguments.

Constructor
def __init__(self, value_map: dict[str, ValueBase])
Methods
substitute_operation
def substitute_operation(self, op: Operation) -> Operation

Substitute values in an operation using the value map.

Handles control-flow operations (IfOperation, ForOperation, etc.) by recursing into their nested operation lists and phi_ops.

substitute_value
def substitute_value(self, v: ValueBase) -> ValueBase

Substitute a single value using the value map.

Handles all value types and array elements by substituting their parent_array if needed.


WhileOperation [source]
class WhileOperation(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 backend 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(),
) -> None
Attributes

qamomile.circuit.transpiler.passes.separate

Separate pass: Split a block into quantum and classical segments.

Overview

ClassDescription
ArrayValueAn array of values with shape information.
BitTypeType representing a classical bit.
BlockUnified block representation for all pipeline stages.
ClassicalSegmentA segment of pure classical operations.
ControlFlowVisitorBase class for visiting operations with control flow handling.
DecodeQFixedOperationDecode measured bits to float (classical operation).
ExpvalOpExpectation value operation.
ExpvalSegmentA segment for expectation value computation.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
HybridBoundaryRepresents a measurement or encode operation at quantum/classical boundary.
IfOperationRepresents an if-else conditional operation.
MeasureQFixedOperationMeasure a quantum fixed-point number.
MeasureVectorOperationMeasure a vector of qubits.
MultipleQuantumSegmentsErrorRaised when program has multiple quantum segments.
OperationKindClassification of operations for classical/quantum separation.
PassBase class for all compiler passes.
QuantumSegmentA segment of pure quantum operations.
QubitTypeType representing a quantum bit (qubit).
ReturnOperationExplicit return operation marking the end of a block with return values.
SegmentBase class for separated computation segments.
SeparatePassSeparate a block into quantum and classical segments.
SimplifiedProgramEnforces Classical → Quantum → Classical pattern.
UIntTypeType representing an unsigned integer.
ValueA typed value in the IR with SSA-style versioning.
ValueBaseProtocol defining the common interface for all value types.
WhileOperationRepresents a while loop operation.

Classes

ArrayValue [source]
class ArrayValue(Value[T])

An array of values with shape information.

ArrayValue extends Value to represent multi-dimensional arrays of typed values (e.g., qubit registers, parameter vectors).

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    params: dict[str, Any] = dict(),
    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(),
) -> None
Attributes
Methods
next_version
def next_version(self) -> ArrayValue[T]

Create a new ArrayValue with incremented version, preserving shape.


BitType [source]
class BitType(ClassicalTypeMixin, ValueType)

Type representing a classical bit.


Block [source]
class Block

Unified block representation for all pipeline stages.

Replaces both BlockValue and Graph 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[Value] = list(),
    output_values: list[Value] = list(),
    operations: list[Operation] = list(),
    kind: BlockKind = BlockKind.HIERARCHICAL,
    parameters: dict[str, Value] = dict(),
    _dependency_graph: dict[str, set[str]] | None = None,
) -> None
Attributes
Methods
from_block_value
@classmethod
def from_block_value(
    cls,
    block_value: 'BlockValue',
    parameters: dict[str, Value] | None = None,
) -> 'Block'

Create a Block from a BlockValue.

Parameters:

NameTypeDescription
block_value'BlockValue'The BlockValue to convert
parametersdict[str, Value] | NoneOptional parameter bindings

Returns:

'Block' — A new Block in HIERARCHICAL state

is_affine
def is_affine(self) -> bool

Check if block contains no CallBlockOperations.

unbound_parameters
def unbound_parameters(self) -> list[str]

Return list of unbound parameter names.


ClassicalSegment [source]
class ClassicalSegment(Segment)

A segment of pure classical operations.

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

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

ControlFlowVisitor [source]
class ControlFlowVisitor(ABC)

Base class for visiting operations with control flow handling.

Subclasses override visit_operation to define per-operation behavior. Control flow recursion is handled automatically by the base class.

Example:

class MeasurementCounter(ControlFlowVisitor):
    def __init__(self):
        self.count = 0

    def visit_operation(self, op: Operation) -> None:
        if isinstance(op, MeasureOperation):
            self.count += 1
Methods
visit_operation
def visit_operation(self, op: Operation) -> None

Process a single operation. Override in subclasses.

visit_operations
def visit_operations(self, operations: list[Operation]) -> None

Visit all operations including nested control flow.


DecodeQFixedOperation [source]
class DecodeQFixedOperation(Operation)

Decode measured bits to float (classical operation).

This operation converts a sequence of classical bits from qubit measurements into a floating-point number using fixed-point encoding.

The decoding formula:

float_value = Σ bit[i] * 2^(int_bits - 1 - i)

For QPE phase (int_bits=0): float_value = 0.b0b1b2... = b00.5 + b10.25 + b2*0.125 + ...

Example:

bits = [1, 0, 1] with int_bits=0
→ 0.101 (binary) = 0.5 + 0.125 = 0.625

operands: [ArrayValue of bits (vec[bit])] results: [Float value]

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

ExpvalOp [source]
class ExpvalOp(Operation)

Expectation value operation.

This operation computes the expectation value <psi|H|psi> where psi is the quantum state and H is the Hamiltonian observable.

The operation bridges quantum and classical computation:

Example IR:

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

ExpvalSegment [source]
class ExpvalSegment(Segment)

A segment for expectation value computation.

Represents computing <psi|H|psi> where psi is the quantum state and H is a Hamiltonian observable.

This segment bridges a quantum circuit (state preparation) to a classical expectation value.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
    hamiltonian_value: Value | None = None,
    qubits_value: Value | None = None,
    result_ref: str = '',
) -> None
Attributes

ForItemsOperation [source]
class ForItemsOperation(Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    operations: list[Operation] = list(),
) -> None
Attributes

ForOperation [source]
class ForOperation(Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    operations: list[Operation] = list(),
) -> None
Attributes

HybridBoundary [source]
class HybridBoundary

Represents a measurement or encode operation at quantum/classical boundary.

These operations bridge quantum and classical segments.

Constructor
def __init__(
    self,
    operation: Operation,
    source_segment_index: int,
    target_segment_index: int,
    value_ref: str,
) -> None
Attributes

IfOperation [source]
class IfOperation(Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    phi_ops: list[PhiOp] = list(),
) -> None
Attributes

MeasureQFixedOperation [source]
class MeasureQFixedOperation(Operation)

Measure a quantum fixed-point number.

This operation measures all qubits in a QFixed register and produces a Float result. During transpilation, this is lowered to individual MeasureOperations plus a DecodeQFixedOperation.

operands: [QFixed value (contains qubit_values in params)] results: [Float value]

Encoding:

For QPE phase (int_bits=0): float_value = 0.b0b1b2... = b00.5 + b10.25 + b2*0.125 + ...

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

MeasureVectorOperation [source]
class MeasureVectorOperation(Operation)

Measure a vector of qubits.

Takes a Vector[Qubit] (ArrayValue) and produces a Vector[Bit] (ArrayValue). This operation measures all qubits in the vector as a single operation.

operands: [ArrayValue of qubits] results: [ArrayValue of bits]

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

MultipleQuantumSegmentsError [source]
class MultipleQuantumSegmentsError(Exception)

Raised when program has multiple quantum segments.

Qamomile enforces a single quantum circuit execution pattern:

[Classical Prep] → Quantum Circuit → [Classical Post/Expval]

Your program has multiple quantum segments, suggesting quantum operations that depend on measurement results (JIT compilation not supported).


OperationKind [source]
class OperationKind(enum.Enum)

Classification of operations for classical/quantum separation.

This enum is used to categorize operations during compilation to determine which parts run on classical hardware vs quantum hardware.

Values:

QUANTUM: Pure quantum operations (gates, qubit allocation) CLASSICAL: Pure classical operations (arithmetic, comparisons) HYBRID: Operations that bridge classical and quantum (measurement, encode/decode) CONTROL: Control flow structures (for, while, if)

Attributes

Pass [source]
class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


QuantumSegment [source]
class QuantumSegment(Segment)

A segment of pure quantum operations.

Contains quantum gates and qubit allocations. Will be emitted to a quantum circuit.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
    qubit_values: list[Value] = list(),
    num_qubits: int = 0,
) -> None
Attributes

QubitType [source]
class QubitType(QuantumTypeMixin, ValueType)

Type representing a quantum bit (qubit).


ReturnOperation [source]
class ReturnOperation(Operation)

Explicit return operation marking the end of a block with return values.

This operation represents an explicit return statement in the IR. It takes the values to be returned as operands and produces no results (it is a terminal operation that transfers control flow back to the caller).

operands: [Value, ...] - The values to return (may be empty for void returns) results: [] - Always empty (terminal operation)

Example:

A function that returns two values (a UInt and a Float):

ReturnOperation(
    operands=[uint_value, float_value],
    results=[],
)

The signature would be:
    operands=[ParamHint("return_0", UIntType()), ParamHint("return_1", FloatType())]
    results=[]
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

Segment [source]
class Segment(ABC)

Base class for separated computation segments.

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

SeparatePass [source]
class SeparatePass(Pass[Block, SimplifiedProgram])

Separate a block into quantum and classical segments.

This pass:

  1. Materializes return operations (syncs output_values from ReturnOperation)

  2. Splits the operation list into quantum and classical segments

  3. Validates single quantum segment (enforces C→Q→C pattern)

Input: Block (typically ANALYZED or AFFINE) Output: SimplifiedProgram with single quantum segment and optional prep/post

Attributes
Methods
run
def run(self, input: Block) -> SimplifiedProgram

Separate the block into segments.


SimplifiedProgram [source]
class SimplifiedProgram

Enforces Classical → Quantum → Classical pattern.

Structure:

This replaces SeparatedProgram to enforce Qamomile’s execution model: all quantum operations must be in a single quantum circuit.

Constructor
def __init__(
    self,
    quantum: QuantumSegment,
    classical_prep: ClassicalSegment | None = None,
    expval: ExpvalSegment | None = None,
    classical_post: ClassicalSegment | None = None,
    boundaries: list[HybridBoundary] = list(),
    parameters: dict[str, Value] = dict(),
    output_refs: list[str] = list(),
) -> None
Attributes

UIntType [source]
class UIntType(ClassicalTypeMixin, ValueType)

Type representing an unsigned integer.


Value [source]
class Value(Generic[T])

A typed value in the IR with SSA-style versioning.

Value represents a single typed value (qubit, float, int, bit, etc.) with support for:

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
) -> None
Attributes
Methods
get_cast_qubit_logical_ids
def get_cast_qubit_logical_ids(self) -> list[str] | None

Get the underlying qubit logical_ids for this cast value.

get_cast_qubit_uuids
def get_cast_qubit_uuids(self) -> list[str] | None

Get the underlying qubit UUIDs for this cast value.

get_cast_source_logical_id
def get_cast_source_logical_id(self) -> str | None

Get the source value logical_id if this is a cast result.

get_cast_source_uuid
def get_cast_source_uuid(self) -> str | None

Get the source value UUID if this is a cast result.

get_const
def get_const(self) -> int | float | None

Get constant value if available, otherwise None.

get_lowered_bits
def get_lowered_bits(self) -> list[Value] | None

Get lowered bit list if available, otherwise None.

get_lowered_qubits
def get_lowered_qubits(self) -> list[Value] | None

Get lowered qubit list if available, otherwise None.

is_array_element
def is_array_element(self) -> bool

Check if this value is an element of an array.

is_cast_result
def is_cast_result(self) -> bool

Check if this value is the result of a CastOperation.

is_constant
def is_constant(self) -> bool

Check if this value is a constant.

is_parameter
def is_parameter(self) -> bool

Check if this value is an unbound parameter.

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

Create a new Value with incremented version (SSA style).

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter, otherwise None.

set_cast_metadata
def set_cast_metadata(
    self,
    source_uuid: str,
    qubit_uuids: list[str],
    source_logical_id: str | None = None,
    qubit_logical_ids: list[str] | None = None,
) -> None

Set cast metadata for this value.

set_lowered_bits
def set_lowered_bits(self, bits: list[Value]) -> None

Set lowered bit list.

set_lowered_qubits
def set_lowered_qubits(self, qubits: list[Value]) -> None

Set lowered qubit list.


ValueBase [source]
class ValueBase(Protocol)

Protocol defining the common interface for all value types.

This protocol enables:

All value types (Value, ArrayValue, TupleValue, DictValue) implement this protocol.

Attributes
Methods
is_constant
def is_constant(self) -> bool

Check if this value is a constant.

is_parameter
def is_parameter(self) -> bool

Check if this value is an unbound parameter.

next_version
def next_version(self) -> ValueBase

Create a new SSA version with fresh uuid but same logical_id.

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter.


WhileOperation [source]
class WhileOperation(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 backend 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(),
) -> None
Attributes

qamomile.circuit.transpiler.passes.standard_emit

Standard emit pass using GateEmitter protocol.

This module provides StandardEmitPass, a reusable emit pass implementation that uses the GateEmitter protocol for backend-specific gate emission.

Overview

FunctionDescription
map_phi_outputsRegister phi output UUIDs to the same physical resources as their source operands.
remap_static_phi_outputsRemap phi outputs for a compile-time constant IfOperation.
resolve_if_conditionResolve an if-condition to a compile-time boolean.
ClassDescription
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, POW).
BinOpKind
CastOperationType cast operation for creating aliases over the same quantum resources.
CompositeDecomposerDecomposes composite gates into primitive operations.
CompositeGateEmitterProtocol for backend-specific CompositeGate emitters.
CompositeGateOperationRepresents a composite gate (QPE, QFT, etc.) as a single operation.
CompositeGateTypeRegistry of known composite gate types.
ControlledUOperationControlled-U operation that applies a unitary block conditionally.
EmitErrorError during backend code emission.
EmitPassBase class for backend-specific emission passes.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
GateEmitterProtocol for backend-specific gate emission.
GateOperation
GateOperationType
IfOperationRepresents an if-else conditional operation.
LoopAnalyzerAnalyzes loop structures to determine emission strategy.
MeasureOperation
MeasureQFixedOperationMeasure a quantum fixed-point number.
MeasureVectorOperationMeasure a vector of qubits.
OperandResolutionInfoDetailed information about a single operand that failed to resolve.
QInitOperationInitialize the qubit
QubitIndexResolutionErrorError when qubit indices cannot be resolved during emission.
ResolutionFailureReasonCategorizes why qubit index resolution failed.
ResourceAllocatorAllocates qubit and classical bit indices from operations.
StandardEmitPassStandard emit pass implementation using GateEmitter protocol.
ValueA typed value in the IR with SSA-style versioning.
ValueResolverResolves Value objects to concrete indices or values.
WhileOperationRepresents a while loop operation.

Functions

map_phi_outputs [source]
def map_phi_outputs(
    phi_ops: list[Operation],
    qubit_map: dict[str, int],
    clbit_map: dict[str, int],
    resolve_scalar_qubit: Any = None,
) -> None

Register phi output UUIDs to the same physical resources as their source operands.

After an if-else block, PhiOp merges values from both branches. The phi output is a new Value with a new UUID that must map to the same physical qubit (or classical bit) as the branch values.

For ArrayValue phi outputs (e.g., qubit arrays), this copies all composite element keys {source_uuid}_{i}{output_uuid}_{i} so that subsequent element accesses on the phi output resolve to the correct physical qubits.

Parameters:

NameTypeDescription
phi_opslist[Operation]List of phi operations from an IfOperation.
qubit_mapdict[str, int]Mapping from UUID/composite key to physical qubit index.
clbit_mapdict[str, int]Mapping from UUID to physical classical bit index.
resolve_scalar_qubitAnyOptional callback (source, qubit_map) -> int | None for resolving scalar qubit values that are not directly in qubit_map (e.g., array element resolution). When None, ResourceAllocator._resolve_qubit_key is used as fallback.

Raises:


remap_static_phi_outputs [source]
def remap_static_phi_outputs(
    phi_ops: list[Operation],
    condition_value: bool,
    qubit_map: dict[str, int],
    clbit_map: dict[str, int],
) -> None

Remap phi outputs for a compile-time constant IfOperation.

When the condition is statically known, the dead branch is never allocated. Phi outputs are aliased directly to the selected branch’s source value, bypassing the two-branch merge validation in map_phi_outputs.

This is the shared implementation used by both the resource allocator (during allocation) and the emit pass (during emission) to ensure scalar and array quantum phi outputs are handled identically.

Parameters:

NameTypeDescription
phi_opslist[Operation]Phi operations from the IfOperation.
condition_valueboolThe resolved boolean condition.
qubit_mapdict[str, int]UUID-to-physical-qubit mapping (mutated in place).
clbit_mapdict[str, int]UUID-to-physical-clbit mapping (mutated in place).

resolve_if_condition [source]
def resolve_if_condition(condition: Any, bindings: dict[str, Any]) -> bool | None

Resolve an if-condition to a compile-time boolean.

Checks whether the condition can be statically evaluated at emit time. Plain Python values (int/bool captured by @qkernel from closure), constant-folded Values, and Values resolvable via bindings are all treated as compile-time constants.

Parameters:

NameTypeDescription
conditionAnyThe condition from IfOperation (plain value or Value object).
bindingsdict[str, Any]Current variable bindings (uuid → value and/or name → value).

Returns:

bool | NoneTrue/False for compile-time resolvable conditions, bool | NoneNone for runtime conditions that must be dispatched to the bool | None — backend’s conditional branching protocol.

Classes

BinOp [source]
class BinOp(BinaryOperationBase)

Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, POW).

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

BinOpKind [source]
class BinOpKind(enum.Enum)
Attributes

CastOperation [source]
class CastOperation(Operation)

Type cast operation for creating aliases over the same quantum resources.

This operation does NOT allocate new qubits. It creates a new Value that references the same underlying quantum resources with a different type.

Use cases:

operands: [source_value] - The value being cast results: [cast_result] - The new value with target type (same physical qubits)

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    source_type: ValueType | None = None,
    target_type: ValueType | None = None,
    qubit_mapping: list[str] = list(),
) -> None
Attributes

CompositeDecomposer [source]
class CompositeDecomposer

Decomposes composite gates into primitive operations.

Provides algorithms for QFT, IQFT, and QPE decomposition that backends can use for fallback when native implementations are unavailable.

Methods
iqft_structure
@staticmethod
def iqft_structure(n: int) -> list[tuple[str, tuple[int, ...], float | None]]

Generate inverse QFT gate sequence.

Parameters:

NameTypeDescription
nintNumber of qubits

Returns:

list[tuple[str, tuple[int, ...], float | None]] — List of (gate_name, qubit_indices, angle) tuples

qft_structure
@staticmethod
def qft_structure(n: int) -> list[tuple[str, tuple[int, ...], float | None]]

Generate QFT gate sequence.

Parameters:

NameTypeDescription
nintNumber of qubits

Returns:

list[tuple[str, tuple[int, ...], float | None]] — List of (gate_name, qubit_indices, angle) tuples


CompositeGateEmitter [source]
class CompositeGateEmitter(Protocol[C])

Protocol for backend-specific CompositeGate emitters.

Each backend can implement emitters for specific composite gate types (QPE, QFT, IQFT, etc.) using native backend libraries.

The emitter pattern allows:

  1. Backends to use native implementations when available (e.g., Qiskit QFT)

  2. Fallback to manual decomposition when native is unavailable

  3. Easy addition of new backends without modifying core code

Example:

class QiskitQFTEmitter:
    def can_emit(self, gate_type: CompositeGateType) -> bool:
        return gate_type in (CompositeGateType.QFT, CompositeGateType.IQFT)

    def emit(self, circuit, op, qubit_indices, bindings) -> bool:
        from qiskit.circuit.library import QFTGate
        qft_gate = QFTGate(len(qubit_indices))
        circuit.append(qft_gate, qubit_indices)
        return True
Methods
can_emit
def can_emit(self, gate_type: CompositeGateType) -> bool

Check if this emitter can handle the given gate type.

Parameters:

NameTypeDescription
gate_typeCompositeGateTypeThe CompositeGateType to check

Returns:

bool — True if this emitter supports native emission for the gate type

emit
def emit(
    self,
    circuit: C,
    op: CompositeGateOperation,
    qubit_indices: list[int],
    bindings: dict[str, Any],
) -> bool

Emit the composite gate to the circuit.

Parameters:

NameTypeDescription
circuitCThe backend-specific circuit to emit to
opCompositeGateOperationThe CompositeGateOperation to emit
qubit_indiceslist[int]Physical qubit indices for the operation
bindingsdict[str, Any]Parameter bindings for the operation

Returns:

bool — True if emission succeeded, False to fall back to manual decomposition


CompositeGateOperation [source]
class CompositeGateOperation(Operation)

Represents a composite gate (QPE, QFT, etc.) as a single operation.

CompositeGate allows representing complex multi-gate operations as a single atomic operation in the IR. This enables:

The operands structure depends on has_implementation:

The results structure:

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    gate_type: CompositeGateType = CompositeGateType.CUSTOM,
    num_control_qubits: int = 0,
    num_target_qubits: int = 0,
    custom_name: str = '',
    resource_metadata: ResourceMetadata | None = None,
    has_implementation: bool = True,
    composite_gate_instance: Any = None,
    strategy_name: str | None = None,
) -> None
Attributes

CompositeGateType [source]
class CompositeGateType(enum.Enum)

Registry of known composite gate types.

Attributes

ControlledUOperation [source]
class ControlledUOperation(Operation)

Controlled-U operation that applies a unitary block conditionally.

The operands structure is:

The results structure is:

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_controls: int | Value = 1,
    power: int | Value = 1,
    target_indices: list[Value] | None = None,
    controlled_indices: list[Value] | None = None,
) -> None
Attributes

EmitError [source]
class EmitError(QamomileCompileError)

Error during backend code emission.

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

EmitPass [source]
class EmitPass(Pass[SimplifiedProgram, ExecutableProgram[T]], Generic[T])

Base class for backend-specific emission passes.

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

Input: SimplifiedProgram (enforces C→Q→C pattern) 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 backend parameters.
Attributes
Methods
run
def run(self, input: SimplifiedProgram) -> ExecutableProgram[T]

Emit backend code from simplified program.


ForItemsOperation [source]
class ForItemsOperation(Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    operations: list[Operation] = list(),
) -> None
Attributes

ForOperation [source]
class ForOperation(Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    operations: list[Operation] = list(),
) -> None
Attributes

GateEmitter [source]
class GateEmitter(Protocol[T])

Protocol for backend-specific gate emission.

Each backend implements this protocol to emit individual gates to their circuit representation.

Type parameter T is the backend’s circuit type (e.g., QuantumCircuit).

Methods
append_gate
def append_gate(self, circuit: T, gate: Any, qubits: list[int]) -> None

Append a gate to the circuit.

Parameters:

NameTypeDescription
circuitTThe circuit to append to
gateAnyThe gate to append (from circuit_to_gate)
qubitslist[int]Target qubit indices
circuit_to_gate
def circuit_to_gate(self, circuit: T, name: str = 'U') -> Any

Convert a circuit to a reusable gate.

Parameters:

NameTypeDescription
circuitTThe circuit to convert
namestrLabel for the gate

Returns:

Any — Backend-specific gate object, or None if not supported

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

Create a new empty circuit.

Parameters:

NameTypeDescription
num_qubitsintNumber of qubits in the circuit
num_clbitsintNumber of classical bits in the circuit

Returns:

T — A new backend-specific circuit object

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

Create a symbolic parameter for the backend.

Parameters:

NameTypeDescription
namestrParameter name (e.g., “gammas[0]”)

Returns:

Any — Backend-specific parameter object

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

Emit barrier on specified qubits.

emit_ch
def emit_ch(self, circuit: T, control: int, target: int) -> None

Emit controlled-Hadamard gate.

emit_cp
def emit_cp(self, circuit: T, control: int, target: int, angle: float | Any) -> None

Emit controlled-Phase gate.

emit_crx
def emit_crx(self, circuit: T, control: int, target: int, angle: float | Any) -> None

Emit controlled-RX gate.

emit_cry
def emit_cry(self, circuit: T, control: int, target: int, angle: float | Any) -> None

Emit controlled-RY gate.

emit_crz
def emit_crz(self, circuit: T, control: int, target: int, angle: float | Any) -> None

Emit controlled-RZ gate.

emit_cx
def emit_cx(self, circuit: T, control: int, target: int) -> None

Emit CNOT gate.

emit_cy
def emit_cy(self, circuit: T, control: int, target: int) -> None

Emit controlled-Y gate.

emit_cz
def emit_cz(self, circuit: T, control: int, target: int) -> None

Emit CZ gate.

emit_else_start
def emit_else_start(self, circuit: T, context: Any) -> None

Start the else branch.

emit_for_loop_end
def emit_for_loop_end(self, circuit: T, context: Any) -> None

End a native for loop context.

emit_for_loop_start
def emit_for_loop_start(self, circuit: T, indexset: range) -> Any

Start a native for loop context.

Returns a context manager or loop parameter, depending on backend.

emit_h
def emit_h(self, circuit: T, qubit: int) -> None

Emit Hadamard gate.

emit_if_end
def emit_if_end(self, circuit: T, context: Any) -> None

End the if/else block.

emit_if_start
def emit_if_start(self, circuit: T, clbit: int, value: int = 1) -> Any

Start a native if context.

Returns context for the if/else block.

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

Emit measurement operation.

emit_p
def emit_p(self, circuit: T, qubit: int, angle: float | Any) -> None

Emit Phase gate (P(θ) = diag(1, e^(iθ))).

emit_rx
def emit_rx(self, circuit: T, qubit: int, angle: float | Any) -> None

Emit RX rotation gate.

Parameters:

NameTypeDescription
circuitTThe circuit to emit to
qubitintTarget qubit index
anglefloat | AnyRotation angle (float or backend parameter)
emit_ry
def emit_ry(self, circuit: T, qubit: int, angle: float | Any) -> None

Emit RY rotation gate.

emit_rz
def emit_rz(self, circuit: T, qubit: int, angle: float | Any) -> None

Emit RZ rotation gate.

emit_rzz
def emit_rzz(self, circuit: T, qubit1: int, qubit2: int, angle: float | Any) -> None

Emit RZZ gate (exp(-i * θ/2 * Z⊗Z)).

emit_s
def emit_s(self, circuit: T, qubit: int) -> None

Emit S gate (√Z).

emit_sdg
def emit_sdg(self, circuit: T, qubit: int) -> None

Emit S-dagger gate (inverse of S).

emit_swap
def emit_swap(self, circuit: T, qubit1: int, qubit2: int) -> None

Emit SWAP gate.

emit_t
def emit_t(self, circuit: T, qubit: int) -> None

Emit T gate (√S).

emit_tdg
def emit_tdg(self, circuit: T, qubit: int) -> None

Emit T-dagger gate (inverse of T).

emit_toffoli
def emit_toffoli(self, circuit: T, control1: int, control2: int, target: int) -> None

Emit Toffoli (CCX) gate.

emit_while_end
def emit_while_end(self, circuit: T, context: Any) -> None

End the while loop context.

emit_while_start
def emit_while_start(self, circuit: T, clbit: int, value: int = 1) -> Any

Start a native while loop context.

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

Emit Pauli-X gate.

emit_y
def emit_y(self, circuit: T, qubit: int) -> None

Emit Pauli-Y gate.

emit_z
def emit_z(self, circuit: T, qubit: int) -> None

Emit Pauli-Z gate.

gate_controlled
def gate_controlled(self, gate: Any, num_controls: int) -> Any

Create controlled version of a gate.

Parameters:

NameTypeDescription
gateAnyThe gate to control
num_controlsintNumber of control qubits

Returns:

Any — New controlled gate

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

Create gate raised to a power (U^n).

Parameters:

NameTypeDescription
gateAnyThe gate to raise to a power
powerintThe power to raise to

Returns:

Any — New gate representing gate^power

supports_for_loop
def supports_for_loop(self) -> bool

Check if backend supports native for loops.

supports_if_else
def supports_if_else(self) -> bool

Check if backend supports native if/else.

supports_while_loop
def supports_while_loop(self) -> bool

Check if backend supports native while loops.


GateOperation [source]
class GateOperation(Operation)
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    gate_type: GateOperationType | None = None,
    theta: float | Value | None = None,
) -> None
Attributes

GateOperationType [source]
class GateOperationType(enum.Enum)
Attributes

IfOperation [source]
class IfOperation(Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    phi_ops: list[PhiOp] = list(),
) -> None
Attributes

LoopAnalyzer [source]
class LoopAnalyzer

Analyzes loop structures to determine emission strategy.

Determines whether loops should use native backend control flow or be unrolled at emission time.

Methods
should_unroll
def should_unroll(self, op: ForOperation, bindings: dict[str, Any]) -> bool

Determine if a ForOperation should be unrolled.

Parameters:

NameTypeDescription
opForOperationThe ForOperation to analyze
bindingsdict[str, Any]Current variable bindings

Returns:

bool — True if loop should be unrolled, False for native emission


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

MeasureQFixedOperation [source]
class MeasureQFixedOperation(Operation)

Measure a quantum fixed-point number.

This operation measures all qubits in a QFixed register and produces a Float result. During transpilation, this is lowered to individual MeasureOperations plus a DecodeQFixedOperation.

operands: [QFixed value (contains qubit_values in params)] results: [Float value]

Encoding:

For QPE phase (int_bits=0): float_value = 0.b0b1b2... = b00.5 + b10.25 + b2*0.125 + ...

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

MeasureVectorOperation [source]
class MeasureVectorOperation(Operation)

Measure a vector of qubits.

Takes a Vector[Qubit] (ArrayValue) and produces a Vector[Bit] (ArrayValue). This operation measures all qubits in the vector as a single operation.

operands: [ArrayValue of qubits] results: [ArrayValue of bits]

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

OperandResolutionInfo [source]
class OperandResolutionInfo

Detailed information about a single operand that failed to resolve.

Constructor
def __init__(
    self,
    operand_name: str,
    operand_uuid: str,
    is_array_element: bool,
    parent_array_name: str | None,
    element_indices_names: list[str],
    failure_reason: ResolutionFailureReason,
    failure_details: str,
) -> None
Attributes

QInitOperation [source]
class QInitOperation(Operation)

Initialize the qubit

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

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],
)
Attributes

ResolutionFailureReason [source]
class ResolutionFailureReason(Enum)

Categorizes why qubit index resolution failed.

Attributes

ResourceAllocator [source]
class ResourceAllocator

Allocates qubit and classical bit indices from operations.

This class handles the first pass of circuit emission: determining how many physical qubits and classical bits are needed and mapping Value UUIDs to their physical indices.

New physical indices are assigned via monotonic counters (_next_qubit_index / _next_clbit_index) so that alias entries — which reuse an existing physical index — never inflate the counter. Using len(map) would cause sparse (gapped) physical indices because alias keys increase the map size without adding new physical resources.

Constructor
def __init__(self) -> None
Methods
allocate
def allocate(
    self,
    operations: list[Operation],
    bindings: dict[str, Any] | None = None,
) -> tuple[dict[str, int], dict[str, int]]

Allocate qubit and clbit indices for all operations.

Parameters:

NameTypeDescription
operationslist[Operation]List of operations to allocate resources for
bindingsdict[str, Any] | NoneOptional variable bindings for resolving dynamic sizes

Returns:

tuple[dict[str, int], dict[str, int]] — Tuple of (qubit_map, clbit_map) where each maps UUID to index


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

Standard emit pass implementation using GateEmitter protocol.

This class provides the orchestration logic for circuit emission while delegating backend-specific operations to a GateEmitter.

Parameters:

NameTypeDescription
gate_emitterGateEmitter[T]Backend-specific gate emitter
bindingsdict[str, Any] | NoneParameter bindings for the circuit
parameterslist[str] | NoneList of parameter names to preserve as backend parameters
composite_emitterslist[CompositeGateEmitter[T]] | NoneOptional list of CompositeGateEmitter for native implementations
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,
)

Value [source]
class Value(Generic[T])

A typed value in the IR with SSA-style versioning.

Value represents a single typed value (qubit, float, int, bit, etc.) with support for:

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
) -> None
Attributes
Methods
get_cast_qubit_logical_ids
def get_cast_qubit_logical_ids(self) -> list[str] | None

Get the underlying qubit logical_ids for this cast value.

get_cast_qubit_uuids
def get_cast_qubit_uuids(self) -> list[str] | None

Get the underlying qubit UUIDs for this cast value.

get_cast_source_logical_id
def get_cast_source_logical_id(self) -> str | None

Get the source value logical_id if this is a cast result.

get_cast_source_uuid
def get_cast_source_uuid(self) -> str | None

Get the source value UUID if this is a cast result.

get_const
def get_const(self) -> int | float | None

Get constant value if available, otherwise None.

get_lowered_bits
def get_lowered_bits(self) -> list[Value] | None

Get lowered bit list if available, otherwise None.

get_lowered_qubits
def get_lowered_qubits(self) -> list[Value] | None

Get lowered qubit list if available, otherwise None.

is_array_element
def is_array_element(self) -> bool

Check if this value is an element of an array.

is_cast_result
def is_cast_result(self) -> bool

Check if this value is the result of a CastOperation.

is_constant
def is_constant(self) -> bool

Check if this value is a constant.

is_parameter
def is_parameter(self) -> bool

Check if this value is an unbound parameter.

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

Create a new Value with incremented version (SSA style).

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter, otherwise None.

set_cast_metadata
def set_cast_metadata(
    self,
    source_uuid: str,
    qubit_uuids: list[str],
    source_logical_id: str | None = None,
    qubit_logical_ids: list[str] | None = None,
) -> None

Set cast metadata for this value.

set_lowered_bits
def set_lowered_bits(self, bits: list[Value]) -> None

Set lowered bit list.

set_lowered_qubits
def set_lowered_qubits(self, qubits: list[Value]) -> None

Set lowered qubit list.


ValueResolver [source]
class ValueResolver

Resolves Value objects to concrete indices or values.

Handles the mapping from IR Value objects to physical qubit indices, classical values, and parameter names during emission.

Constructor
def __init__(self, parameters: set[str] | None = None)

Initialize the resolver.

Parameters:

NameTypeDescription
parametersset[str] | NoneSet of parameter names to preserve as symbolic
Attributes
Methods
get_parameter_key
def get_parameter_key(self, value: 'Value', bindings: dict[str, Any]) -> str | None

Get parameter key if this value should be a symbolic parameter.

Parameters:

NameTypeDescription
value'Value'The Value to check
bindingsdict[str, Any]Current bindings (for resolving array indices)

Returns:

str | None — Parameter key (e.g., “gammas[0]”) if symbolic, None otherwise

resolve_classical_value
def resolve_classical_value(self, value: 'Value', bindings: dict[str, Any]) -> Any

Resolve a classical Value to a concrete Python value.

Parameters:

NameTypeDescription
value'Value'The Value to resolve
bindingsdict[str, Any]Current variable bindings

Returns:

Any — Resolved value (int, float, etc.), or None if cannot resolve

resolve_int_value
def resolve_int_value(self, val: Any, bindings: dict[str, Any]) -> int | None

Resolve a value to an integer (for loop bounds, etc.).

Parameters:

NameTypeDescription
valAnyThe value to resolve
bindingsdict[str, Any]Current variable bindings

Returns:

int | None — Integer value, or None if cannot resolve

resolve_qubit_index
def resolve_qubit_index(
    self,
    v: 'Value',
    qubit_map: dict[str, int],
    bindings: dict[str, Any],
) -> int | None

Resolve a Value to a physical qubit index.

Parameters:

NameTypeDescription
v'Value'The Value to resolve
qubit_mapdict[str, int]Mapping from UUID to qubit index
bindingsdict[str, Any]Current variable bindings

Returns:

int | None — Physical qubit index, or None if cannot resolve

resolve_qubit_index_detailed
def resolve_qubit_index_detailed(
    self,
    v: 'Value',
    qubit_map: dict[str, int],
    bindings: dict[str, Any],
) -> QubitResolutionResult

Resolve a Value to a physical qubit index with detailed failure info.

Parameters:

NameTypeDescription
v'Value'The Value to resolve
qubit_mapdict[str, int]Mapping from UUID to qubit index
bindingsdict[str, Any]Current variable bindings

Returns:

QubitResolutionResult — QubitResolutionResult with success status and either index or failure details


WhileOperation [source]
class WhileOperation(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 backend 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(),
) -> None
Attributes

qamomile.circuit.transpiler.passes.substitution

Substitution pass for replacing QKernel subroutines and composite gate strategies.

This pass allows replacing:

  1. CallBlockOperation targets (QKernel subroutines) with alternative implementations

  2. CompositeGateOperation strategies with specified decomposition strategies

Example:

# Replace a custom oracle with an optimized version
config = SubstitutionConfig(
    rules=[
        SubstitutionRule(source_name="my_oracle", target=optimized_oracle),
        SubstitutionRule(source_name="qft", strategy="approximate"),
    ]
)
pass = SubstitutionPass(config)
new_block = pass.run(block)

Overview

FunctionDescription
check_signature_compatibilityCheck signature compatibility between two BlockValues.
create_substitution_passConvenience factory for creating a SubstitutionPass.
ClassDescription
BlockUnified block representation for all pipeline stages.
BlockValueRepresents a subroutine as a function block.
CallBlockOperation
CompositeGateOperationRepresents a composite gate (QPE, QFT, etc.) as a single operation.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
IfOperationRepresents an if-else conditional operation.
PassBase class for all compiler passes.
QKernelDecorator class for Qamomile quantum kernels.
SignatureCompatibilityErrorError raised when signatures are incompatible during substitution.
SubstitutionConfigConfiguration for the substitution pass.
SubstitutionPassPass that substitutes CallBlockOperations and CompositeGateOperations.
SubstitutionRuleA single substitution rule.
WhileOperationRepresents a while loop operation.

Functions

check_signature_compatibility [source]
def check_signature_compatibility(
    source: 'BlockValue',
    target: 'BlockValue',
    strict: bool = True,
) -> tuple[bool, str | None]

Check signature compatibility between two BlockValues.

Parameters:

NameTypeDescription
source'BlockValue'The source BlockValue being replaced
target'BlockValue'The target BlockValue to replace with
strictboolIf True, require exact type matches

Returns:

bool — Tuple of (is_compatible, error_message). str | None — If compatible, error_message is None.


create_substitution_pass [source]
def create_substitution_pass(
    block_replacements: dict[str, 'BlockValue | QKernel'] | None = None,
    *,
    strategy_overrides: dict[str, str] | None = None,
    validate_signatures: bool = True,
) -> SubstitutionPass

Convenience factory for creating a SubstitutionPass.

Parameters:

NameTypeDescription
block_replacementsdict[str, 'BlockValue | QKernel'] | NoneMap of block name to replacement
strategy_overridesdict[str, str] | NoneMap of gate name to strategy name
validate_signaturesboolIf True, validate signature compatibility when replacing blocks. Default is True.

Returns:

SubstitutionPass — Configured SubstitutionPass

Example:

pass = create_substitution_pass(
    block_replacements={"my_oracle": optimized_oracle},
    strategy_overrides={"qft": "approximate", "iqft": "approximate"},
)

Classes

Block [source]
class Block

Unified block representation for all pipeline stages.

Replaces both BlockValue and Graph 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[Value] = list(),
    output_values: list[Value] = list(),
    operations: list[Operation] = list(),
    kind: BlockKind = BlockKind.HIERARCHICAL,
    parameters: dict[str, Value] = dict(),
    _dependency_graph: dict[str, set[str]] | None = None,
) -> None
Attributes
Methods
from_block_value
@classmethod
def from_block_value(
    cls,
    block_value: 'BlockValue',
    parameters: dict[str, Value] | None = None,
) -> 'Block'

Create a Block from a BlockValue.

Parameters:

NameTypeDescription
block_value'BlockValue'The BlockValue to convert
parametersdict[str, Value] | NoneOptional parameter bindings

Returns:

'Block' — A new Block in HIERARCHICAL state

is_affine
def is_affine(self) -> bool

Check if block contains no CallBlockOperations.

unbound_parameters
def unbound_parameters(self) -> list[str]

Return list of unbound parameter names.


BlockValue [source]
class BlockValue(Value[BlockType])

Represents a subroutine as a function block.

def func_block(a: UInt, b: UInt) -> tuple[UInt]: ...

BlockValue( name=“func_block”, inputs_type={“a”: UIntType(), “b”: UIntType()}, outputs_type=(UIntType(), ), operations=[...], )

Function to BlockValue conversion can be done via func_to_block function. Each Values in operations are dummy values. The execution of the BlockValue is corresponding to the BlockOperation.

Constructor
def __init__(
    self,
    type: BlockType = BlockType(),
    name: str = '',
    version: int = 0,
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
    label_args: list[str] = list(),
    input_values: list[Value] = list(),
    return_values: list[Value] = list(),
    operations: list[Operation] = list(),
) -> None
Attributes
Methods
call
def call(self, **kwargs: Value = {}) -> 'CallBlockOperation'

Create a CallBlockOperation to call this BlockValue.

Example:

block_value = BlockValue(
    name="func_block",
    inputs_type={"a": UIntType(), "b": UIntType()},
    outputs_type=(UIntType(), ),
    operations=[...],
)
a = Value(UIntType())
b = Value(UIntType())
call_op = block_value.call(a=a, b=b)

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

CompositeGateOperation [source]
class CompositeGateOperation(Operation)

Represents a composite gate (QPE, QFT, etc.) as a single operation.

CompositeGate allows representing complex multi-gate operations as a single atomic operation in the IR. This enables:

The operands structure depends on has_implementation:

The results structure:

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    gate_type: CompositeGateType = CompositeGateType.CUSTOM,
    num_control_qubits: int = 0,
    num_target_qubits: int = 0,
    custom_name: str = '',
    resource_metadata: ResourceMetadata | None = None,
    has_implementation: bool = True,
    composite_gate_instance: Any = None,
    strategy_name: str | None = None,
) -> None
Attributes

ForItemsOperation [source]
class ForItemsOperation(Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    operations: list[Operation] = list(),
) -> None
Attributes

ForOperation [source]
class ForOperation(Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    operations: list[Operation] = list(),
) -> None
Attributes

IfOperation [source]
class IfOperation(Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    phi_ops: list[PhiOp] = list(),
) -> None
Attributes

Pass [source]
class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


QKernel [source]
class QKernel(Generic[P, R])

Decorator class for Qamomile quantum kernels.

Constructor
def __init__(self, func: Callable[P, R]) -> None
Attributes
Methods
build
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> Graph

Build the computation graph by tracing this kernel.

Parameters:

NameTypeDescription
parameterslist[str] | NoneList of argument names to keep as unbound parameters. - None (default): Auto-detect parameters (non-Qubit args without value/default) - []: No parameters (all non-Qubit args must have value/default) - [“name”]: Explicit parameter list Only float, int, UInt, and their arrays are allowed as parameters.
**kwargsAnyConcrete values for non-parameter arguments.

Returns:

Graph — The traced computation graph ready for transpilation.

Raises:

Example:

@qm.qkernel
def circuit(q: Qubit, theta: float) -> Qubit:
    q = qm.rx(q, theta)
    return q

# Auto-detect theta as parameter
graph = circuit.build()

# Explicit parameter list
graph = circuit.build(parameters=["theta"])

# theta bound to concrete value
graph = circuit.build(theta=0.5)

# Transpile with binding
transpiler = QiskitTranspiler()
result = transpiler.emit(graph, binding={"theta": 0.5})
draw
def draw(
    self,
    inline: bool = False,
    fold_loops: bool = True,
    expand_composite: bool = False,
    inline_depth: int | None = None,
    **kwargs: Any = {},
) -> Any

Visualize the circuit using Matplotlib.

This method builds the computation graph and creates a static visualization. Parameters are auto-detected: non-Qubit arguments without concrete values are shown as symbolic parameters.

Parameters:

NameTypeDescription
inlineboolIf True, expand CallBlockOperation contents (inlining). If False (default), show CallBlockOperation as boxes.
fold_loopsboolIf True (default), display ForOperation as blocks instead of unrolling. If False, expand loops and show all iterations.
expand_compositeboolIf True, expand CompositeGateOperation (QFT, IQFT, etc.). If False (default), show as boxes. Independent of inline.
inline_depthint | NoneMaximum nesting depth for inline expansion. None means unlimited (default). 0 means no inlining, 1 means top-level only, etc. Only affects CallBlock/ControlledU, not CompositeGate.
**kwargsAnyConcrete values for arguments. Arguments not provided here (and without defaults) will be shown as symbolic parameters.

Returns:

Any — matplotlib.figure.Figure object.

Raises:

Example:

import qamomile.circuit as qm

@qm.qkernel
def inner(q: qm.Qubit) -> qm.Qubit:
    return qm.x(q)

@qm.qkernel
def circuit(q: qm.Qubit, theta: float) -> qm.Qubit:
    q = inner(q)
    q = qm.h(q)
    q = qm.rx(q, theta)
    return q

# Draw with auto-detected symbolic parameter (theta)
fig = circuit.draw()

# Draw with bound parameter
fig = circuit.draw(theta=0.5)

# Draw with blocks as boxes (default)
fig = circuit.draw()

# Draw with blocks expanded (inlined)
fig = circuit.draw(inline=True)

# Draw with loops folded (shown as blocks)
fig = circuit.draw(fold_loops=True)

# Draw with composite gates expanded
fig = circuit.draw(expand_composite=True)
estimate_resources
def estimate_resources(self, *, bindings: dict[str, Any] | None = None) -> ResourceEstimate

Estimate all resources for this kernel’s circuit.

Convenience method that delegates to the module-level estimate_resources function, eliminating the need to access .block directly.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneOptional concrete parameter bindings (scalars and dicts). Dict values trigger |key| cardinality substitution.

Returns:

ResourceEstimate — ResourceEstimate with qubits, gates, and parameters.

Example:

>>> @qm.qkernel
... def bell() -> qm.Vector[qm.Qubit]:
...     q = qm.qubit_array(2)
...     q[0] = qm.h(q[0])
...     q[0], q[1] = qm.cx(q[0], q[1])
...     return q
>>> est = bell.estimate_resources()
>>> print(est.qubits)  # 2

SignatureCompatibilityError [source]
class SignatureCompatibilityError(Exception)

Error raised when signatures are incompatible during substitution.


SubstitutionConfig [source]
class SubstitutionConfig

Configuration for the substitution pass.

Constructor
def __init__(self, rules: list[SubstitutionRule] = list()) -> None
Attributes
Methods
get_rule_for_name
def get_rule_for_name(self, name: str) -> SubstitutionRule | None

Find a rule matching the given name.

Parameters:

NameTypeDescription
namestrName to look up

Returns:

SubstitutionRule | None — Matching SubstitutionRule or None


SubstitutionPass [source]
class SubstitutionPass(Pass[Block, Block])

Pass that substitutes CallBlockOperations and CompositeGateOperations.

This pass traverses the block and applies substitution rules:

The pass preserves the block structure and only modifies matching operations.

Input: Block (any kind) Output: Block with substitutions applied (same kind as input)

Constructor
def __init__(self, config: SubstitutionConfig) -> None

Initialize the pass with configuration.

Parameters:

NameTypeDescription
configSubstitutionConfigSubstitution configuration with rules
Attributes
Methods
run
def run(self, input: Block) -> Block

Apply substitutions to the block.

Parameters:

NameTypeDescription
inputBlockBlock to transform

Returns:

Block — Block with substitutions applied


SubstitutionRule [source]
class SubstitutionRule

A single substitution rule.

Constructor
def __init__(
    self,
    source_name: str,
    target: 'BlockValue | QKernel | None' = None,
    strategy: str | None = None,
    validate_signature: bool = True,
) -> None
Attributes

WhileOperation [source]
class WhileOperation(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 backend 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(),
) -> None
Attributes

qamomile.circuit.transpiler.passes.validate_while

WhileOperation contract validation pass.

Validates that all WhileOperation conditions are measurement-backed Bit values. A condition is measurement-backed if it originates from qmc.measure() either directly or through phi-merged branches where every leaf is itself measurement-backed (e.g. if sel: bit = measure(q1) else: bit = measure(q2)).

All other while patterns (classical variables, constants, comparison results, non-measurement branch leaves) are rejected with a clear ValidationError before reaching backend-specific emit passes.

This pass runs after lower_compile_time_ifs and before analyze.

Overview

ClassDescription
BitTypeType representing a classical bit.
BlockUnified block representation for all pipeline stages.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
IfOperationRepresents an if-else conditional operation.
MeasureOperation
PassBase class for all compiler passes.
PhiOpSSA Phi function: merge point after conditional branch.
ValidateWhileContractPassValidates that all WhileOperation conditions are measurement-backed.
ValidationErrorError during validation (e.g., non-classical I/O).
ValueA typed value in the IR with SSA-style versioning.
WhileOperationRepresents a while loop operation.

Classes

BitType [source]
class BitType(ClassicalTypeMixin, ValueType)

Type representing a classical bit.


Block [source]
class Block

Unified block representation for all pipeline stages.

Replaces both BlockValue and Graph 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[Value] = list(),
    output_values: list[Value] = list(),
    operations: list[Operation] = list(),
    kind: BlockKind = BlockKind.HIERARCHICAL,
    parameters: dict[str, Value] = dict(),
    _dependency_graph: dict[str, set[str]] | None = None,
) -> None
Attributes
Methods
from_block_value
@classmethod
def from_block_value(
    cls,
    block_value: 'BlockValue',
    parameters: dict[str, Value] | None = None,
) -> 'Block'

Create a Block from a BlockValue.

Parameters:

NameTypeDescription
block_value'BlockValue'The BlockValue to convert
parametersdict[str, Value] | NoneOptional parameter bindings

Returns:

'Block' — A new Block in HIERARCHICAL state

is_affine
def is_affine(self) -> bool

Check if block contains no CallBlockOperations.

unbound_parameters
def unbound_parameters(self) -> list[str]

Return list of unbound parameter names.


ForItemsOperation [source]
class ForItemsOperation(Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    operations: list[Operation] = list(),
) -> None
Attributes

ForOperation [source]
class ForOperation(Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    operations: list[Operation] = list(),
) -> None
Attributes

IfOperation [source]
class IfOperation(Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    phi_ops: list[PhiOp] = list(),
) -> None
Attributes

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

Pass [source]
class Pass(ABC, Generic[InputT, OutputT])

Base class for all compiler passes.

Attributes
Methods
run
def run(self, input: InputT) -> OutputT

Execute the pass transformation.


PhiOp [source]
class PhiOp(Operation)

SSA Phi function: merge point after conditional branch.

This operation selects one of two values based on a condition. Used to merge values from different branches of an if-else statement.

Example:

if condition:
    x = x + 1  # true_value
else:
    x = x + 2  # false_value
# x is now PhiOp(condition, true_value, false_value)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

ValidateWhileContractPass [source]
class ValidateWhileContractPass(Pass[Block, Block])

Validates that all WhileOperation conditions are measurement-backed.

Builds a producer map (result UUID → producing Operation instance) and checks every WhileOperation operand against it. A valid condition must be:

  1. A Value with BitType

  2. Measurement-backed: produced by MeasureOperation directly, or by IfOperation / PhiOp where every reachable leaf source is itself measurement-backed.

Both operands[0] (initial condition) and operands[1] (loop-carried condition) are validated.

Raises ValidationError for any non-measurement while pattern.

Attributes
Methods
run
def run(self, block: Block) -> Block

Validate all WhileOperations and return block unchanged.


ValidationError [source]
class ValidationError(QamomileCompileError)

Error during validation (e.g., non-classical I/O).

Constructor
def __init__(self, message: str, value_name: str | None = None)
Attributes

Value [source]
class Value(Generic[T])

A typed value in the IR with SSA-style versioning.

Value represents a single typed value (qubit, float, int, bit, etc.) with support for:

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
) -> None
Attributes
Methods
get_cast_qubit_logical_ids
def get_cast_qubit_logical_ids(self) -> list[str] | None

Get the underlying qubit logical_ids for this cast value.

get_cast_qubit_uuids
def get_cast_qubit_uuids(self) -> list[str] | None

Get the underlying qubit UUIDs for this cast value.

get_cast_source_logical_id
def get_cast_source_logical_id(self) -> str | None

Get the source value logical_id if this is a cast result.

get_cast_source_uuid
def get_cast_source_uuid(self) -> str | None

Get the source value UUID if this is a cast result.

get_const
def get_const(self) -> int | float | None

Get constant value if available, otherwise None.

get_lowered_bits
def get_lowered_bits(self) -> list[Value] | None

Get lowered bit list if available, otherwise None.

get_lowered_qubits
def get_lowered_qubits(self) -> list[Value] | None

Get lowered qubit list if available, otherwise None.

is_array_element
def is_array_element(self) -> bool

Check if this value is an element of an array.

is_cast_result
def is_cast_result(self) -> bool

Check if this value is the result of a CastOperation.

is_constant
def is_constant(self) -> bool

Check if this value is a constant.

is_parameter
def is_parameter(self) -> bool

Check if this value is an unbound parameter.

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

Create a new Value with incremented version (SSA style).

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter, otherwise None.

set_cast_metadata
def set_cast_metadata(
    self,
    source_uuid: str,
    qubit_uuids: list[str],
    source_logical_id: str | None = None,
    qubit_logical_ids: list[str] | None = None,
) -> None

Set cast metadata for this value.

set_lowered_bits
def set_lowered_bits(self, bits: list[Value]) -> None

Set lowered bit list.

set_lowered_qubits
def set_lowered_qubits(self, qubits: list[Value]) -> None

Set lowered qubit list.


WhileOperation [source]
class WhileOperation(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 backend 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(),
) -> None
Attributes

qamomile.circuit.transpiler.passes.value_mapping

Value mapping utilities for IR transformations.

Overview

ClassDescription
ArrayValueAn array of values with shape information.
DictValueA dictionary mapping keys to values.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
GateOperation
IfOperationRepresents an if-else conditional operation.
TupleValueA tuple of values for structured data.
UUIDRemapperClones values and operations with fresh UUIDs and logical_ids.
ValueA typed value in the IR with SSA-style versioning.
ValueBaseProtocol defining the common interface for all value types.
ValueSubstitutorSubstitutes values in operations using a mapping.
WhileOperationRepresents a while loop operation.

Classes

ArrayValue [source]
class ArrayValue(Value[T])

An array of values with shape information.

ArrayValue extends Value to represent multi-dimensional arrays of typed values (e.g., qubit registers, parameter vectors).

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    params: dict[str, Any] = dict(),
    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(),
) -> None
Attributes
Methods
next_version
def next_version(self) -> ArrayValue[T]

Create a new ArrayValue with incremented version, preserving shape.


DictValue [source]
class DictValue

A dictionary mapping keys to values.

Used for structured data like Ising coefficients {(i, j): Jij}. Entries are stored as a list of (key, value) pairs for consistent ordering. Implements the ValueBase protocol for unified handling.

Constructor
def __init__(
    self,
    name: str,
    entries: list[tuple[TupleValue | Value, Value]] = list(),
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool

Check if all entries have constant values.

is_parameter
def is_parameter(self) -> bool

Check if this dict is a parameter (bound at transpile time).

next_version
def next_version(self) -> DictValue

Create a new DictValue with a fresh uuid but same logical_id.

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter.


ForItemsOperation [source]
class ForItemsOperation(Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    operations: list[Operation] = list(),
) -> None
Attributes

ForOperation [source]
class ForOperation(Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    operations: list[Operation] = list(),
) -> None
Attributes

GateOperation [source]
class GateOperation(Operation)
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    gate_type: GateOperationType | None = None,
    theta: float | Value | None = None,
) -> None
Attributes

IfOperation [source]
class IfOperation(Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    phi_ops: list[PhiOp] = list(),
) -> None
Attributes

TupleValue [source]
class TupleValue

A tuple of values for structured data.

Used for structured data like Ising model indices (i, j). Implements the ValueBase protocol for unified handling.

Constructor
def __init__(
    self,
    name: str,
    elements: tuple[Value, ...] = tuple(),
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool

Check if all elements are constants.

is_parameter
def is_parameter(self) -> bool

Check if this tuple is a parameter (has symbolic elements).

next_version
def next_version(self) -> TupleValue

Create a new TupleValue with a fresh uuid but same logical_id.

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter.


UUIDRemapper [source]
class UUIDRemapper

Clones values and operations with fresh UUIDs and logical_ids.

Used during inlining to create unique identities for values when a block is called multiple times.

Constructor
def __init__(self)
Attributes
Methods
clone_operation
def clone_operation(self, op: Operation) -> Operation

Clone an operation with fresh UUIDs for all values.

clone_operations
def clone_operations(self, operations: list[Operation]) -> list[Operation]

Clone a list of operations with fresh UUIDs.

clone_value
def clone_value(self, value: ValueBase) -> ValueBase

Clone any value type with a fresh UUID and logical_id.

Handles Value, ArrayValue, TupleValue, and DictValue through the unified ValueBase protocol.


Value [source]
class Value(Generic[T])

A typed value in the IR with SSA-style versioning.

Value represents a single typed value (qubit, float, int, bit, etc.) with support for:

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
) -> None
Attributes
Methods
get_cast_qubit_logical_ids
def get_cast_qubit_logical_ids(self) -> list[str] | None

Get the underlying qubit logical_ids for this cast value.

get_cast_qubit_uuids
def get_cast_qubit_uuids(self) -> list[str] | None

Get the underlying qubit UUIDs for this cast value.

get_cast_source_logical_id
def get_cast_source_logical_id(self) -> str | None

Get the source value logical_id if this is a cast result.

get_cast_source_uuid
def get_cast_source_uuid(self) -> str | None

Get the source value UUID if this is a cast result.

get_const
def get_const(self) -> int | float | None

Get constant value if available, otherwise None.

get_lowered_bits
def get_lowered_bits(self) -> list[Value] | None

Get lowered bit list if available, otherwise None.

get_lowered_qubits
def get_lowered_qubits(self) -> list[Value] | None

Get lowered qubit list if available, otherwise None.

is_array_element
def is_array_element(self) -> bool

Check if this value is an element of an array.

is_cast_result
def is_cast_result(self) -> bool

Check if this value is the result of a CastOperation.

is_constant
def is_constant(self) -> bool

Check if this value is a constant.

is_parameter
def is_parameter(self) -> bool

Check if this value is an unbound parameter.

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

Create a new Value with incremented version (SSA style).

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter, otherwise None.

set_cast_metadata
def set_cast_metadata(
    self,
    source_uuid: str,
    qubit_uuids: list[str],
    source_logical_id: str | None = None,
    qubit_logical_ids: list[str] | None = None,
) -> None

Set cast metadata for this value.

set_lowered_bits
def set_lowered_bits(self, bits: list[Value]) -> None

Set lowered bit list.

set_lowered_qubits
def set_lowered_qubits(self, qubits: list[Value]) -> None

Set lowered qubit list.


ValueBase [source]
class ValueBase(Protocol)

Protocol defining the common interface for all value types.

This protocol enables:

All value types (Value, ArrayValue, TupleValue, DictValue) implement this protocol.

Attributes
Methods
is_constant
def is_constant(self) -> bool

Check if this value is a constant.

is_parameter
def is_parameter(self) -> bool

Check if this value is an unbound parameter.

next_version
def next_version(self) -> ValueBase

Create a new SSA version with fresh uuid but same logical_id.

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter.


ValueSubstitutor [source]
class ValueSubstitutor

Substitutes values in operations using a mapping.

Used during inlining to replace block parameters with caller arguments.

Constructor
def __init__(self, value_map: dict[str, ValueBase])
Methods
substitute_operation
def substitute_operation(self, op: Operation) -> Operation

Substitute values in an operation using the value map.

Handles control-flow operations (IfOperation, ForOperation, etc.) by recursing into their nested operation lists and phi_ops.

substitute_value
def substitute_value(self, v: ValueBase) -> ValueBase

Substitute a single value using the value map.

Handles all value types and array elements by substituting their parent_array if needed.


WhileOperation [source]
class WhileOperation(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 backend 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(),
) -> None
Attributes

qamomile.circuit.transpiler.quantum_executor

Abstract base class for quantum backend execution.

This module provides a simple interface for implementing custom quantum executors. Executors bridge Qamomile’s compiled circuits to various quantum backends including local simulators and cloud quantum devices.

Basic Example (Local Simulator): from qiskit_aer import AerSimulator

class MyExecutor(QuantumExecutor[QuantumCircuit]):
    def __init__(self):
        self.backend = AerSimulator()

    def execute(self, circuit: QuantumCircuit, shots: int) -> dict[str, int]:
        from qiskit import transpile
        if circuit.num_clbits == 0:
            circuit = circuit.copy()
            circuit.measure_all()
        transpiled = transpile(circuit, self.backend)
        job = self.backend.run(transpiled, shots=shots)
        return job.result().get_counts()

Cloud Backend Example (IBM Quantum): from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2

class IBMQuantumExecutor(QuantumExecutor[QuantumCircuit]):
    def __init__(self, backend_name: str = "ibm_brisbane"):
        self.service = QiskitRuntimeService()
        self.backend_name = backend_name

    def execute(self, circuit: QuantumCircuit, shots: int) -> dict[str, int]:
        from qiskit.transpiler.preset_passmanagers import (
            generate_preset_pass_manager,
        )
        backend = self.service.backend(self.backend_name)
        pm = generate_preset_pass_manager(backend=backend, optimization_level=1)
        transpiled = pm.run(circuit)
        sampler = SamplerV2(backend)
        job = sampler.run([transpiled], shots=shots)
        return job.result()[0].data.meas.get_counts()

    def bind_parameters(self, circuit, bindings, metadata):
        # Use helper method for easy conversion
        return circuit.assign_parameters(metadata.to_binding_dict(bindings))

Bitstring Format:

The execute() method returns dict[str, int] where keys are bitstrings in big-endian format (leftmost bit = highest qubit index). Example: {“011”: 512, “100”: 488} for 3 qubits

Overview

ClassDescription
ParameterMetadataMetadata for all parameters in a compiled segment.
QuantumExecutorAbstract base class for quantum backend execution.

Classes

ParameterMetadata [source]
class ParameterMetadata

Metadata for all parameters in a compiled segment.

Tracks parameter information for runtime binding.

Constructor
def __init__(self, parameters: list[ParameterInfo] = list()) -> None
Attributes
Methods
get_array_names
def get_array_names(self) -> set[str]

Get unique array/scalar parameter names.

get_ordered_params
def get_ordered_params(self) -> list[Any]

Get backend parameter objects in definition order.

Useful for backends that require positional parameter binding (e.g., QURI Parts).

Returns:

list[Any] — List of backend_param objects in the order they were defined.

Example:

# For QURI Parts that uses positional binding:
param_values = [bindings[p.name] for p in metadata.parameters]
bound_circuit = circuit.bind_parameters(param_values)
get_param_by_name
def get_param_by_name(self, name: str) -> ParameterInfo | None

Get parameter info by full name.

to_binding_dict
def to_binding_dict(self, bindings: dict[str, Any]) -> dict[Any, Any]

Convert indexed bindings to backend parameter bindings.

Transforms user-provided bindings (with indexed names like “gammas[0]”) into a dictionary mapping backend parameter objects to values. Useful for backends that use dict-based parameter binding (e.g., Qiskit).

Parameters:

NameTypeDescription
bindingsdict[str, Any]Dictionary mapping parameter names to values. e.g., {“gammas[0]”: 0.1, “gammas[1]”: 0.2, “theta”: 0.5}

Returns:

dict[Any, Any] — Dictionary mapping backend_param objects to values.

Example:

# For Qiskit that uses dict-based binding:
qiskit_bindings = metadata.to_binding_dict(bindings)
bound_circuit = circuit.assign_parameters(qiskit_bindings)

QuantumExecutor [source]
class QuantumExecutor(ABC, Generic[T])

Abstract base class for quantum backend execution.

To implement a custom executor:

  1. execute() [Required] Execute circuit and return bitstring counts as dict[str, int]. Keys are bitstrings in big-endian format (e.g., “011” means q2=0, q1=1, q0=1).

  2. bind_parameters() [Optional] Bind parameter values to parametric circuits. Override if your executor supports parametric circuits (e.g., QAOA variational circuits). Use ParameterMetadata.to_binding_dict() for easy conversion.

  3. estimate() [Optional] Compute expectation values <psi|H|psi>. Override if your executor supports estimation primitives (e.g., Qiskit Estimator, QURI Parts).

Example (Minimal): class MyExecutor(QuantumExecutor[QuantumCircuit]): def init(self): from qiskit_aer import AerSimulator self.backend = AerSimulator()

    def execute(self, circuit, shots):
        from qiskit import transpile
        if circuit.num_clbits == 0:
            circuit = circuit.copy()
            circuit.measure_all()
        transpiled = transpile(circuit, self.backend)
        return self.backend.run(transpiled, shots=shots).result().get_counts()

Example (With Parameter Binding): def bind_parameters(self, circuit, bindings, metadata): # metadata.to_binding_dict() converts indexed names to backend params return circuit.assign_parameters(metadata.to_binding_dict(bindings))

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

Bind parameter values to the circuit.

Default implementation returns the circuit unchanged. Override for backends that support parametric circuits.

Parameters:

NameTypeDescription
circuitTThe parameterized circuit
bindingsdict[str, Any]Dict mapping parameter names (indexed format) to values. e.g., {“gammas[0]”: 0.1, “gammas[1]”: 0.2}
parameter_metadataParameterMetadataMetadata about circuit parameters

Returns:

T — New circuit with parameters bound

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

Estimate the expectation value of a Hamiltonian.

This method computes <psi|H|psi> where psi is the quantum state prepared by the circuit and H is the Hamiltonian.

Backends can override this method to provide optimized implementations using their native estimator primitives.

Parameters:

NameTypeDescription
circuitTThe quantum circuit (state preparation ansatz)
hamiltonian'qm_o.Hamiltonian'The qamomile.observable.Hamiltonian to measure
paramsSequence[float] | NoneOptional parameter values for parametric circuits

Returns:

float — The estimated expectation value

Raises:

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

Execute the circuit and return bitstring counts.

Parameters:

NameTypeDescription
circuitTThe quantum circuit to execute
shotsintNumber of measurement shots

Returns:

dict[str, int] — Dictionary mapping bitstrings to counts. dict[str, int] — {“00”: 512, “11”: 512}


qamomile.circuit.transpiler.result

EmitResult data structures for transpiler output.

Overview

ClassDescription
ClassicalMappingMaps a logical Value to a classical value or measurement result slot.
EmitResultStructured result from Transpiler.emit().
OutputMappingMaps Graph output position to physical resource.
QubitMappingMaps a logical Value to a physical qubit index.

Classes

ClassicalMapping [source]
class ClassicalMapping

Maps a logical Value to a classical value or measurement result slot.

Constructor
def __init__(
    self,
    value_uuid: str,
    value_name: str,
    value: Union[int, float, bool, None],
    clbit_index: Union[int, None] = None,
) -> None
Attributes

EmitResult [source]
class EmitResult(Generic[T])

Structured result from Transpiler.emit().

Contains the backend-specific circuit along with mapping information that tracks the correspondence between logical Values and physical qubit/clbit indices.

Constructor
def __init__(
    self,
    circuit: T,
    qubit_mappings: list[QubitMapping],
    classical_mappings: list[ClassicalMapping],
    output_mappings: list[OutputMapping],
    num_qubits: int,
    num_clbits: int = 0,
) -> None
Attributes
Methods
get_measurement_clbit_indices
def get_measurement_clbit_indices(self) -> list[int]

Get clbit indices for all measurement outputs in order.

get_output_mapping_by_index
def get_output_mapping_by_index(self, index: int) -> Union[OutputMapping, None]

Get output mapping by tuple index.

get_output_qubit_indices
def get_output_qubit_indices(self) -> list[int]

Get qubit indices for all quantum outputs in order.

get_qubit_index_by_name
def get_qubit_index_by_name(self, name: str) -> Union[int, None]

Look up qubit index by Value name.


OutputMapping [source]
class OutputMapping

Maps Graph output position to physical resource.

Constructor
def __init__(
    self,
    output_index: int,
    value_uuid: str,
    value_name: str,
    kind: str,
    physical_index: Union[int, None],
    classical_value: Union[int, float, bool, None] = None,
) -> None
Attributes

QubitMapping [source]
class QubitMapping

Maps a logical Value to a physical qubit index.

Constructor
def __init__(self, value_uuid: str, value_name: str, qubit_index: int) -> None
Attributes

qamomile.circuit.transpiler.segments

Data structures for separated quantum/classical segments.

Overview

ClassDescription
ClassicalSegmentA segment of pure classical operations.
ExpvalSegmentA segment for expectation value computation.
HybridBoundaryRepresents a measurement or encode operation at quantum/classical boundary.
MultipleQuantumSegmentsErrorRaised when program has multiple quantum segments.
QuantumSegmentA segment of pure quantum operations.
SegmentBase class for separated computation segments.
SegmentKindType of computation segment.
SimplifiedProgramEnforces Classical → Quantum → Classical pattern.
ValueA typed value in the IR with SSA-style versioning.

Classes

ClassicalSegment [source]
class ClassicalSegment(Segment)

A segment of pure classical operations.

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

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

ExpvalSegment [source]
class ExpvalSegment(Segment)

A segment for expectation value computation.

Represents computing <psi|H|psi> where psi is the quantum state and H is a Hamiltonian observable.

This segment bridges a quantum circuit (state preparation) to a classical expectation value.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
    hamiltonian_value: Value | None = None,
    qubits_value: Value | None = None,
    result_ref: str = '',
) -> None
Attributes

HybridBoundary [source]
class HybridBoundary

Represents a measurement or encode operation at quantum/classical boundary.

These operations bridge quantum and classical segments.

Constructor
def __init__(
    self,
    operation: Operation,
    source_segment_index: int,
    target_segment_index: int,
    value_ref: str,
) -> None
Attributes

MultipleQuantumSegmentsError [source]
class MultipleQuantumSegmentsError(Exception)

Raised when program has multiple quantum segments.

Qamomile enforces a single quantum circuit execution pattern:

[Classical Prep] → Quantum Circuit → [Classical Post/Expval]

Your program has multiple quantum segments, suggesting quantum operations that depend on measurement results (JIT compilation not supported).


QuantumSegment [source]
class QuantumSegment(Segment)

A segment of pure quantum operations.

Contains quantum gates and qubit allocations. Will be emitted to a quantum circuit.

Constructor
def __init__(
    self,
    operations: list[Operation] = list(),
    input_refs: list[str] = list(),
    output_refs: list[str] = list(),
    qubit_values: list[Value] = list(),
    num_qubits: int = 0,
) -> None
Attributes

Segment [source]
class Segment(ABC)

Base class for separated computation segments.

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

SegmentKind [source]
class SegmentKind(Enum)

Type of computation segment.

Attributes

SimplifiedProgram [source]
class SimplifiedProgram

Enforces Classical → Quantum → Classical pattern.

Structure:

This replaces SeparatedProgram to enforce Qamomile’s execution model: all quantum operations must be in a single quantum circuit.

Constructor
def __init__(
    self,
    quantum: QuantumSegment,
    classical_prep: ClassicalSegment | None = None,
    expval: ExpvalSegment | None = None,
    classical_post: ClassicalSegment | None = None,
    boundaries: list[HybridBoundary] = list(),
    parameters: dict[str, Value] = dict(),
    output_refs: list[str] = list(),
) -> None
Attributes

Value [source]
class Value(Generic[T])

A typed value in the IR with SSA-style versioning.

Value represents a single typed value (qubit, float, int, bit, etc.) with support for:

Constructor
def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    params: dict[str, Any] = dict(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
) -> None
Attributes
Methods
get_cast_qubit_logical_ids
def get_cast_qubit_logical_ids(self) -> list[str] | None

Get the underlying qubit logical_ids for this cast value.

get_cast_qubit_uuids
def get_cast_qubit_uuids(self) -> list[str] | None

Get the underlying qubit UUIDs for this cast value.

get_cast_source_logical_id
def get_cast_source_logical_id(self) -> str | None

Get the source value logical_id if this is a cast result.

get_cast_source_uuid
def get_cast_source_uuid(self) -> str | None

Get the source value UUID if this is a cast result.

get_const
def get_const(self) -> int | float | None

Get constant value if available, otherwise None.

get_lowered_bits
def get_lowered_bits(self) -> list[Value] | None

Get lowered bit list if available, otherwise None.

get_lowered_qubits
def get_lowered_qubits(self) -> list[Value] | None

Get lowered qubit list if available, otherwise None.

is_array_element
def is_array_element(self) -> bool

Check if this value is an element of an array.

is_cast_result
def is_cast_result(self) -> bool

Check if this value is the result of a CastOperation.

is_constant
def is_constant(self) -> bool

Check if this value is a constant.

is_parameter
def is_parameter(self) -> bool

Check if this value is an unbound parameter.

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

Create a new Value with incremented version (SSA style).

parameter_name
def parameter_name(self) -> str | None

Get the parameter name if this is a parameter, otherwise None.

set_cast_metadata
def set_cast_metadata(
    self,
    source_uuid: str,
    qubit_uuids: list[str],
    source_logical_id: str | None = None,
    qubit_logical_ids: list[str] | None = None,
) -> None

Set cast metadata for this value.

set_lowered_bits
def set_lowered_bits(self, bits: list[Value]) -> None

Set lowered bit list.

set_lowered_qubits
def set_lowered_qubits(self, qubits: list[Value]) -> None

Set lowered qubit list.


qamomile.circuit.transpiler.transpiler

Base transpiler class for backend-specific compilation.

Overview

ClassDescription
AffineValidationPassValidate affine type semantics at IR level.
AnalyzePassAnalyze and validate an affine block.
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
CompileTimeIfLoweringPassLowers compile-time resolvable IfOperations before separation.
ConstantFoldingPassEvaluates constant expressions at compile time.
DecompositionConfigConfiguration for decomposition strategy selection.
EmitPassBase class for backend-specific emission passes.
ExecutableProgramA fully compiled program ready for execution.
InlinePassInline all CallBlockOperations to create an affine block.
QKernelDecorator class for Qamomile quantum kernels.
QamomileCompileErrorBase class for all Qamomile compilation errors.
SeparatePassSeparate a block into quantum and classical segments.
SimplifiedProgramEnforces Classical → Quantum → Classical pattern.
SubstitutionConfigConfiguration for the substitution pass.
SubstitutionPassPass that substitutes CallBlockOperations and CompositeGateOperations.
SubstitutionRuleA single substitution rule.
TranspilerBase class for backend-specific transpilers.
TranspilerConfigConfiguration for the transpiler pipeline.
ValidateWhileContractPassValidates that all WhileOperation conditions are measurement-backed.

Classes

AffineValidationPass [source]
class AffineValidationPass(Pass[Block, Block])

Validate affine type semantics at IR level.

This pass serves as a safety net to catch affine type violations that may have bypassed the frontend checks. It verifies:

  1. Each quantum value is used (consumed) at most once

  2. Quantum values are not silently discarded

Input: Block (any kind) Output: Same Block (unchanged, validation only)

Attributes
Methods
run
def run(self, input: Block) -> Block

Validate affine type semantics in the block.

Raises:


AnalyzePass [source]
class AnalyzePass(Pass[Block, Block])

Analyze and validate an affine block.

This pass:

  1. Builds a dependency graph between values

  2. Validates that quantum ops don’t depend on non-parameter classical results

  3. Checks that block inputs/outputs are classical

Input: Block with BlockKind.AFFINE Output: Block with BlockKind.ANALYZED (with _dependency_graph populated)

Attributes
Methods
run
def run(self, input: Block) -> Block

Analyze the block and validate dependencies.


Block [source]
class Block

Unified block representation for all pipeline stages.

Replaces both BlockValue and Graph 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[Value] = list(),
    output_values: list[Value] = list(),
    operations: list[Operation] = list(),
    kind: BlockKind = BlockKind.HIERARCHICAL,
    parameters: dict[str, Value] = dict(),
    _dependency_graph: dict[str, set[str]] | None = None,
) -> None
Attributes
Methods
from_block_value
@classmethod
def from_block_value(
    cls,
    block_value: 'BlockValue',
    parameters: dict[str, Value] | None = None,
) -> 'Block'

Create a Block from a BlockValue.

Parameters:

NameTypeDescription
block_value'BlockValue'The BlockValue to convert
parametersdict[str, Value] | NoneOptional parameter bindings

Returns:

'Block' — A new Block in HIERARCHICAL state

is_affine
def is_affine(self) -> bool

Check if block contains no CallBlockOperations.

unbound_parameters
def unbound_parameters(self) -> list[str]

Return list of unbound parameter names.


BlockKind [source]
class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

CompileTimeIfLoweringPass [source]
class CompileTimeIfLoweringPass(Pass[Block, Block])

Lowers compile-time resolvable IfOperations before separation.

After constant folding, some IfOperation conditions are statically known but remain as control-flow nodes. SeparatePass treats them as segment boundaries, causing MultipleQuantumSegmentsError for classical-only compile-time if after quantum init.

This pass:

  1. Evaluates conditions including expression-derived ones (CompOp, CondOp, NotOp chains).

  2. Replaces resolved IfOperations with selected-branch operations.

  3. Substitutes phi output UUIDs with selected-branch values in all subsequent operations and block outputs.

Constructor
def __init__(self, bindings: dict[str, Any] | None = None)
Attributes
Methods
run
def run(self, input: Block) -> Block

Run the compile-time if lowering pass.


ConstantFoldingPass [source]
class ConstantFoldingPass(Pass[Block, Block])

Evaluates constant expressions at compile time.

This pass folds BinOp operations when all operands are constants or bound parameters, eliminating unnecessary classical operations that would otherwise split quantum segments.

Example:

Before (with bindings={"phase": 0.5}):
    BinOp(phase * 2) -> classical segment split

After:
    Constant 1.0 -> no segment split
Constructor
def __init__(self, bindings: dict[str, Any] | None = None)
Attributes
Methods
run
def run(self, input: Block) -> Block

Run constant folding on the block.


DecompositionConfig [source]
class DecompositionConfig

Configuration for decomposition strategy selection.

This configuration is passed to the transpiler to control which decomposition strategies are used for composite gates.

Constructor
def __init__(
    self,
    strategy_overrides: dict[str, str] = dict(),
    strategy_params: dict[str, dict[str, Any]] = dict(),
    default_strategy: str = 'standard',
) -> None
Attributes
Methods
get_strategy_for_gate
def get_strategy_for_gate(self, gate_name: str) -> str

Get the strategy name for a specific gate.

Parameters:

NameTypeDescription
gate_namestrThe gate name (e.g., “qft”, “iqft”)

Returns:

str — Strategy name to use

get_strategy_params
def get_strategy_params(self, strategy_name: str) -> dict[str, Any]

Get parameters for a specific strategy.

Parameters:

NameTypeDescription
strategy_namestrThe strategy name

Returns:

dict[str, Any] — Dictionary of parameters


EmitPass [source]
class EmitPass(Pass[SimplifiedProgram, ExecutableProgram[T]], Generic[T])

Base class for backend-specific emission passes.

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

Input: SimplifiedProgram (enforces C→Q→C pattern) 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 backend parameters.
Attributes
Methods
run
def run(self, input: SimplifiedProgram) -> ExecutableProgram[T]

Emit backend code from simplified program.


ExecutableProgram [source]
class ExecutableProgram(Generic[T])

A fully compiled program ready for execution.

This is the Orchestrator - manages execution of mixed classical/quantum programs.

Example:

executable = transpiler.compile(kernel)

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

# Run: single shot, returns typed result
job = executable.run(executor)
result = job.result()  # Returns kernel's return type
Constructor
def __init__(
    self,
    compiled_quantum: list[CompiledQuantumSegment[T]] = list(),
    compiled_classical: list[CompiledClassicalSegment] = list(),
    compiled_expval: list[CompiledExpvalSegment] = list(),
    execution_order: list[tuple[str, int]] = list(),
    output_refs: list[str] = list(),
    num_output_bits: int = 0,
) -> None
Attributes
Methods
get_circuits
def get_circuits(self) -> list[T]

Get all quantum circuits in execution order.

get_first_circuit
def get_first_circuit(self) -> T | None

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

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

Execute once and return single result.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Backend-specific quantum executor.
bindingsdict[str, Any] | NoneParameter bindings. Supports two formats: - Vector: {“gammas”: [0.1, 0.2], “betas”: [0.3, 0.4]} - Indexed: {“gammas[0]”: 0.1, “gammas[1]”: 0.2}

Returns:

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

Raises:

Example:

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

Execute with multiple shots and return counts.

Parameters:

NameTypeDescription
executorQuantumExecutor[T]Backend-specific quantum executor.
shotsintNumber of shots to run.
bindingsdict[str, Any] | NoneParameter bindings. Supports two formats: - Vector: {“gammas”: [0.1, 0.2], “betas”: [0.3, 0.4]} - Indexed: {“gammas[0]”: 0.1, “gammas[1]”: 0.2}

Returns:

SampleJob[Any] — SampleJob that resolves to SampleResult with results.

Raises:

Example:

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

InlinePass [source]
class InlinePass(Pass[Block, Block])

Inline all CallBlockOperations to create an affine block.

This pass recursively inlines function calls while preserving control flow structures (For, If, While).

Input: Block with BlockKind.HIERARCHICAL (may contain CallBlockOperations) Output: Block with BlockKind.AFFINE (no CallBlockOperations)

Attributes
Methods
run
def run(self, input: Block) -> Block

Inline all CallBlockOperations.


QKernel [source]
class QKernel(Generic[P, R])

Decorator class for Qamomile quantum kernels.

Constructor
def __init__(self, func: Callable[P, R]) -> None
Attributes
Methods
build
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> Graph

Build the computation graph by tracing this kernel.

Parameters:

NameTypeDescription
parameterslist[str] | NoneList of argument names to keep as unbound parameters. - None (default): Auto-detect parameters (non-Qubit args without value/default) - []: No parameters (all non-Qubit args must have value/default) - [“name”]: Explicit parameter list Only float, int, UInt, and their arrays are allowed as parameters.
**kwargsAnyConcrete values for non-parameter arguments.

Returns:

Graph — The traced computation graph ready for transpilation.

Raises:

Example:

@qm.qkernel
def circuit(q: Qubit, theta: float) -> Qubit:
    q = qm.rx(q, theta)
    return q

# Auto-detect theta as parameter
graph = circuit.build()

# Explicit parameter list
graph = circuit.build(parameters=["theta"])

# theta bound to concrete value
graph = circuit.build(theta=0.5)

# Transpile with binding
transpiler = QiskitTranspiler()
result = transpiler.emit(graph, binding={"theta": 0.5})
draw
def draw(
    self,
    inline: bool = False,
    fold_loops: bool = True,
    expand_composite: bool = False,
    inline_depth: int | None = None,
    **kwargs: Any = {},
) -> Any

Visualize the circuit using Matplotlib.

This method builds the computation graph and creates a static visualization. Parameters are auto-detected: non-Qubit arguments without concrete values are shown as symbolic parameters.

Parameters:

NameTypeDescription
inlineboolIf True, expand CallBlockOperation contents (inlining). If False (default), show CallBlockOperation as boxes.
fold_loopsboolIf True (default), display ForOperation as blocks instead of unrolling. If False, expand loops and show all iterations.
expand_compositeboolIf True, expand CompositeGateOperation (QFT, IQFT, etc.). If False (default), show as boxes. Independent of inline.
inline_depthint | NoneMaximum nesting depth for inline expansion. None means unlimited (default). 0 means no inlining, 1 means top-level only, etc. Only affects CallBlock/ControlledU, not CompositeGate.
**kwargsAnyConcrete values for arguments. Arguments not provided here (and without defaults) will be shown as symbolic parameters.

Returns:

Any — matplotlib.figure.Figure object.

Raises:

Example:

import qamomile.circuit as qm

@qm.qkernel
def inner(q: qm.Qubit) -> qm.Qubit:
    return qm.x(q)

@qm.qkernel
def circuit(q: qm.Qubit, theta: float) -> qm.Qubit:
    q = inner(q)
    q = qm.h(q)
    q = qm.rx(q, theta)
    return q

# Draw with auto-detected symbolic parameter (theta)
fig = circuit.draw()

# Draw with bound parameter
fig = circuit.draw(theta=0.5)

# Draw with blocks as boxes (default)
fig = circuit.draw()

# Draw with blocks expanded (inlined)
fig = circuit.draw(inline=True)

# Draw with loops folded (shown as blocks)
fig = circuit.draw(fold_loops=True)

# Draw with composite gates expanded
fig = circuit.draw(expand_composite=True)
estimate_resources
def estimate_resources(self, *, bindings: dict[str, Any] | None = None) -> ResourceEstimate

Estimate all resources for this kernel’s circuit.

Convenience method that delegates to the module-level estimate_resources function, eliminating the need to access .block directly.

Parameters:

NameTypeDescription
bindingsdict[str, Any] | NoneOptional concrete parameter bindings (scalars and dicts). Dict values trigger |key| cardinality substitution.

Returns:

ResourceEstimate — ResourceEstimate with qubits, gates, and parameters.

Example:

>>> @qm.qkernel
... def bell() -> qm.Vector[qm.Qubit]:
...     q = qm.qubit_array(2)
...     q[0] = qm.h(q[0])
...     q[0], q[1] = qm.cx(q[0], q[1])
...     return q
>>> est = bell.estimate_resources()
>>> print(est.qubits)  # 2

QamomileCompileError [source]
class QamomileCompileError(Exception)

Base class for all Qamomile compilation errors.


SeparatePass [source]
class SeparatePass(Pass[Block, SimplifiedProgram])

Separate a block into quantum and classical segments.

This pass:

  1. Materializes return operations (syncs output_values from ReturnOperation)

  2. Splits the operation list into quantum and classical segments

  3. Validates single quantum segment (enforces C→Q→C pattern)

Input: Block (typically ANALYZED or AFFINE) Output: SimplifiedProgram with single quantum segment and optional prep/post

Attributes
Methods
run
def run(self, input: Block) -> SimplifiedProgram

Separate the block into segments.


SimplifiedProgram [source]
class SimplifiedProgram

Enforces Classical → Quantum → Classical pattern.

Structure:

This replaces SeparatedProgram to enforce Qamomile’s execution model: all quantum operations must be in a single quantum circuit.

Constructor
def __init__(
    self,
    quantum: QuantumSegment,
    classical_prep: ClassicalSegment | None = None,
    expval: ExpvalSegment | None = None,
    classical_post: ClassicalSegment | None = None,
    boundaries: list[HybridBoundary] = list(),
    parameters: dict[str, Value] = dict(),
    output_refs: list[str] = list(),
) -> None
Attributes

SubstitutionConfig [source]
class SubstitutionConfig

Configuration for the substitution pass.

Constructor
def __init__(self, rules: list[SubstitutionRule] = list()) -> None
Attributes
Methods
get_rule_for_name
def get_rule_for_name(self, name: str) -> SubstitutionRule | None

Find a rule matching the given name.

Parameters:

NameTypeDescription
namestrName to look up

Returns:

SubstitutionRule | None — Matching SubstitutionRule or None


SubstitutionPass [source]
class SubstitutionPass(Pass[Block, Block])

Pass that substitutes CallBlockOperations and CompositeGateOperations.

This pass traverses the block and applies substitution rules:

The pass preserves the block structure and only modifies matching operations.

Input: Block (any kind) Output: Block with substitutions applied (same kind as input)

Constructor
def __init__(self, config: SubstitutionConfig) -> None

Initialize the pass with configuration.

Parameters:

NameTypeDescription
configSubstitutionConfigSubstitution configuration with rules
Attributes
Methods
run
def run(self, input: Block) -> Block

Apply substitutions to the block.

Parameters:

NameTypeDescription
inputBlockBlock to transform

Returns:

Block — Block with substitutions applied


SubstitutionRule [source]
class SubstitutionRule

A single substitution rule.

Constructor
def __init__(
    self,
    source_name: str,
    target: 'BlockValue | QKernel | None' = None,
    strategy: str | None = None,
    validate_signature: bool = True,
) -> None
Attributes

Transpiler [source]
class Transpiler(ABC, Generic[T])

Base class for backend-specific transpilers.

Provides the full compilation pipeline from QKernel to executable program.

Usage:

transpiler = QiskitTranspiler()

Option 1: Full pipeline

executable = transpiler.compile(kernel, bindings={“theta”: 0.5}) results = executable.run(transpiler.executor())

Option 2: Step-by-step

block = transpiler.to_block(kernel) substituted = transpiler.substitute(block) affine = transpiler.inline(substituted) validated = transpiler.affine_validate(affine) folded = transpiler.constant_fold(validated, bindings={“theta”: 0.5}) analyzed = transpiler.analyze(folded) separated = transpiler.separate(analyzed) executable = transpiler.emit(separated, bindings={“theta”: 0.5})

Option 3: Just get the circuit (no execution)

circuit = transpiler.to_circuit(kernel, bindings={“theta”: 0.5})

With configuration (strategy overrides)

config = TranspilerConfig.with_strategies({“qft”: “approximate”}) transpiler = QiskitTranspiler(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.

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: SimplifiedProgram,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> ExecutableProgram[T]

Pass 4: Generate backend-specific code.

Parameters:

NameTypeDescription
separatedSimplifiedProgramThe separated program to emit
bindingsdict[str, Any] | NoneParameter values to bind at compile time
parameterslist[str] | NoneParameter names to preserve as backend parameters
executor
def executor(self, **kwargs: Any = {}) -> QuantumExecutor[T]

Create a quantum executor for this backend.

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

Pass 1: Inline all CallBlockOperations.

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. Phi outputs are substituted with selected-branch values throughout the block.

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

separate
def separate(self, block: Block) -> SimplifiedProgram

Pass 3: Lower and split into quantum and classical segments.

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

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

Set the transpiler configuration.

Parameters:

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

Pass 0.5: Apply substitutions (optional).

This pass replaces CallBlockOperation targets and sets strategy names on CompositeGateOperations based on config.

Parameters:

NameTypeDescription
blockBlockBlock to transform

Returns:

Block — Block with substitutions applied

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

Convert a QKernel to a Block.

Parameters:

NameTypeDescription
kernelQKernelThe QKernel to convert
bindingsdict[str, Any] | NoneConcrete values to bind at trace time (resolves array shapes)
parameterslist[str] | NoneNames to keep as unbound parameters

When bindings or parameters are provided, uses kernel.build() to properly resolve array shapes from the bound data. Otherwise uses the cached block_value for efficiency.

to_circuit
def to_circuit(self, kernel: QKernel, 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 backend circuit without the full executable.

Parameters:

NameTypeDescription
kernelQKernelThe QKernel to compile
bindingsdict[str, Any] | NoneParameter values to bind

Returns:

T — Backend-specific quantum circuit

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

Full compilation pipeline from QKernel to executable.

Parameters:

NameTypeDescription
kernelQKernelThe QKernel to compile
bindingsdict[str, Any] | NoneParameter values to bind (also resolves array shapes)
parameterslist[str] | NoneParameter names to preserve as backend parameters

Returns:

ExecutableProgram[T] — ExecutableProgram ready for execution

Raises:

Pipeline:

  1. to_block: Convert QKernel to Block

  2. substitute: Apply substitutions (if configured)

  3. inline: Inline CallBlockOperations

  4. affine_validate: Validate affine type semantics

  5. constant_fold: Fold constant expressions 5.5. lower_compile_time_ifs: Lower compile-time IfOperations 5.8. validate_while_contract: Validate while conditions are measurement-backed

  6. analyze: Validate and analyze dependencies

  7. separate: Split into quantum/classical segments

  8. emit: Generate backend-specific code

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

Pass 1.8: Validate WhileOperation conditions are measurement-backed.

Rejects while patterns whose condition is not a measurement result (Bit from qmc.measure()). This prevents late ValueError at emit time for unsupported while forms.


TranspilerConfig [source]
class TranspilerConfig

Configuration for the transpiler pipeline.

This configuration allows customizing the compilation behavior, including decomposition strategies and subroutine substitutions.

Example:

config = TranspilerConfig(
    decomposition=DecompositionConfig(
        strategy_overrides={"qft": "approximate"},
    ),
    substitutions=SubstitutionConfig(
        rules=[
            SubstitutionRule("my_oracle", target=optimized_oracle),
        ],
    ),
)
transpiler = QiskitTranspiler(config=config)
Constructor
def __init__(
    self,
    decomposition: DecompositionConfig = DecompositionConfig(),
    substitutions: SubstitutionConfig = SubstitutionConfig(),
) -> None
Attributes
Methods
with_strategies
@classmethod
def with_strategies(
    cls,
    strategy_overrides: dict[str, str] | None = None,
    **kwargs: Any = {},
) -> 'TranspilerConfig'

Create config with strategy overrides.

Parameters:

NameTypeDescription
strategy_overridesdict[str, str] | NoneMap of gate name to strategy name
**kwargsAnyAdditional config options

Returns:

'TranspilerConfig' — TranspilerConfig instance

Example:

config = TranspilerConfig.with_strategies(
    strategy_overrides={"qft": "approximate", "iqft": "approximate"}
)

ValidateWhileContractPass [source]
class ValidateWhileContractPass(Pass[Block, Block])

Validates that all WhileOperation conditions are measurement-backed.

Builds a producer map (result UUID → producing Operation instance) and checks every WhileOperation operand against it. A valid condition must be:

  1. A Value with BitType

  2. Measurement-backed: produced by MeasureOperation directly, or by IfOperation / PhiOp where every reachable leaf source is itself measurement-backed.

Both operands[0] (initial condition) and operands[1] (loop-carried condition) are validated.

Raises ValidationError for any non-measurement while pattern.

Attributes
Methods
run
def run(self, block: Block) -> Block

Validate all WhileOperations and return block unchanged.