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.hugr.lowerer

Direct lowering from prepared Qamomile semantics to Guppy-compatible HUGR.

Overview

FunctionDescription
array_physical_regionResolve a one-dimensional array to its ordered physical region.
coerce_nonnegative_integralNormalize a real scalar with an integer value to a nonnegative integer.
control_pattern_for_valueReturn the LSB-first activation pattern for a control value.
is_close_zeroCheck if a given floating-point value is close to zero within a small tolerance.
resolve_root_array_indexFold a view-local element index into the root array’s index space.
resolve_root_qubit_addressResolve an array-element value to its root (array_uuid, index).
validate_region_argsValidate the SSA identities owned by a loop’s region arguments.
ClassDescription
ArrayValueAn array of typed IR values.
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
BinOpKind
BlockUnified block representation for all pipeline stages.
CInitOperationInitialize the classical values (const, arguments etc)
CallTransformDescribe the requested transform of a callable implementation.
CallableRefIdentify a callable independently of its Python object.
CastOperationType cast operation for creating aliases over the same quantum resources.
CompOpComparison operation (EQ, NEQ, LT, LE, GT, GE).
CompOpKind
ConcreteControlledUControlled-U with concrete (int) number of controls.
ControlledUOperationBase class for controlled-U operations.
DictValueA dictionary value stored as stable ordered entries.
ForOperationRepresents a for loop operation.
GateOperationQuantum gate operation.
GateOperationType
GlobalPhaseOperationMultiply the complete quantum state by exp(i * phase).
HasNestedOpsMixin for operations that contain nested operation lists.
HugrCompilationPlanDescribe the callable symbols emitted into one HUGR module.
HugrTargetPlan, lower, package, and validate a Guppy-compatible HUGR target.
IfOperationRepresents an if-else conditional operation.
InverseBlockOperationRepresent an inverse qkernel/block as a first-class IR operation.
InvokeOperationRepresent a composite, stdlib, or oracle call.
LoopCarriedRebindTrace-time record of a variable rebound inside a loop body.
MeasureOperation
MeasureQFixedOperationMeasure a quantum fixed-point number.
MeasureQIntOperationMeasure an unsigned quantum integer as one abstract hybrid operation.
MeasureVectorOperationMeasure a vector of qubits.
NotOp
PauliEvolveOpPauli evolution operation: exp(-i * gamma * H).
ProjectOperationProject a qubit in one Pauli basis and keep the projected state.
QInitOperationInitialize the qubit
ReleaseSliceViewOperationMark a slice view’s borrow as explicitly returned to its parent.
ResetOperationReset a qubit to the |0> state and return the fresh handle.
ReturnOperationExplicit return operation marking the end of a block with return values.
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
SliceArrayOperationConstruct a strided view of an ArrayValue.
TupleValueA tuple of IR values for structured data.
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.
ValueTypeBase class for all value types in the IR.
WhileOperationRepresents a while loop operation.

Constants

Functions

array_physical_region [source]

def array_physical_region(array: 'ArrayValue') -> tuple[str, tuple[int, ...]] | None

Resolve a one-dimensional array to its ordered physical region.

The region is expressed independently of SSA version UUIDs: the first element is the root array’s logical_id and the second is the ordered tuple of root-space indices addressed by the array. This makes a root register and its full view compare equal while keeping partial, strided, reordered, and different-root registers distinct.

Parameters:

NameTypeDescription
arrayArrayValueRoot array or nested sliced view to resolve. The array must be one-dimensional and have a compile-time integer length; every slice bound in its ancestry must also be constant.

Returns:

tuple[str, tuple[int, ...]] | None — tuple[str, tuple[int, ...]] | None: (root_logical_id, indices) when the complete ordered coverage is statically known, otherwise None. Symbolic shapes or slice bounds remain unresolved so callers can defer to emit-time physical mappings.


coerce_nonnegative_integral [source]

def coerce_nonnegative_integral(value: object, *, label: str) -> int

Normalize a real scalar with an integer value to a nonnegative integer.

Parameters:

NameTypeDescription
valueobjectCandidate Python, NumPy, or SymPy real scalar.
labelstrUser-facing field label used in diagnostics.

Returns:

int — Equivalent nonnegative Python integer.

Raises:


control_pattern_for_value [source]

def control_pattern_for_value(control_value: int | None, num_controls: int) -> tuple[int, ...]

Return the LSB-first activation pattern for a control value.

Parameters:

NameTypeDescription
control_valueint | NoneRequired computational-basis value. None means the ordinary all-ones control state.
num_controlsintConcrete positive control-register width.

Returns:

tuple[int, ...] — tuple[int, ...]: One 0/1 activation bit per flattened control, with the first control represented by bit zero.

Raises:

Example:

>>> control_pattern_for_value(2, 2)
(0, 1)
>>> control_pattern_for_value(None, 2)
(1, 1)

is_close_zero [source]

def is_close_zero(value: float, abs_tol: float = 1e-15) -> bool

Check if a given floating-point value is close to zero within a small tolerance.

Parameters:

NameTypeDescription
valuefloatThe floating-point value to check.
abs_tolfloatAbsolute tolerance passed to :func:math.isclose. Defaults to 1e-15.

Returns:

bool — True if the value is close to zero, False otherwise.


resolve_root_array_index [source]

def resolve_root_array_index(array: 'ArrayValue', index: int) -> tuple['ArrayValue', int] | None

Fold a view-local element index into the root array’s index space.

Walks the slice_of chain root-ward, composing each strided view’s affine map parent_index = start + step * local_index. This is the array-level counterpart of :func:resolve_root_qubit_address (which starts from an array-element Value); both must stay consistent with the composite carrier keys "<root_uuid>_<root_index>" registered by QInitOperation at emit time.

Parameters:

NameTypeDescription
arrayArrayValueArray the index is local to. May be a root array (slice_of unset) or an arbitrarily nested strided view.
indexintElement index in array’s own index space.

Returns:

tuple['ArrayValue', int] | None — tuple[ArrayValue, int] | None: (root_array, composed_index) when every slice bound on the chain is compile-time constant and satisfies the frontend contract (non-negative slice_start, positive slice_step). None when any slice_start / slice_step on the chain is missing, symbolic, or violates that contract; callers must then defer resolution rather than guess. Out-of-contract bounds would compose index onto a wrong root slot, so they are refused here too (the frontend rejects them at trace time; this guard covers programmatically constructed IR).


resolve_root_qubit_address [source]

def resolve_root_qubit_address(value: 'Value') -> tuple[str, int] | None

Resolve an array-element value to its root (array_uuid, index).

Walks the parent_array / slice_of chain and composes the nested affine slice maps, so view[i] resolves to (root_uuid, start + step * i) for the composed (start, step). The returned pair is the build-stable identity of the physical qubit slot: the root array’s QInitOperation always registers it as QubitAddress(root_uuid, index), so this address resolves even when the element’s own (per-version) UUID was never registered.

The transpiler’s resource allocator uses the same walk to resolve gate and measurement operands; this shared helper keeps both call sites consistent.

Parameters:

NameTypeDescription
valueValueThe value to resolve. Expected to be an array element (parent_array set with a single constant element_indices entry).

Returns:

tuple[str, int] | None — tuple[str, int] | None: (root_array_uuid, composed_index) when value is an array element with a constant index whose entire slice_of chain has constant slice_start / slice_step. None when value is not an array element, when its index is non-constant, or when any slice bound in the chain is non-constant (those cases are deferred to the emit-time resolver, which has bindings available). Also None for a negative constant index or a chain frame with negative slice_start / non-positive slice_step — composing those would silently address a wrong root slot, so they are refused rather than guessed (the frontend rejects them at trace time; this guard covers programmatically constructed IR).


validate_region_args [source]

def validate_region_args(op: ForOperation | ForItemsOperation | WhileOperation) -> tuple[RegionArg, ...]

Validate the SSA identities owned by a loop’s region arguments.

A loop owns several definition namespaces: its iteration variables, every RegionArg.block_arg, and every RegionArg.result. Those identities must be pairwise disjoint. Otherwise different stages can assign incompatible meanings to one UUID: a UUID-keyed environment has only one slot, so binding either the iteration variable or the carried value overwrites the other and makes both reads observe the same value.

Parameters:

NameTypeDescription
opForOperation | ForItemsOperation | WhileOperationLoop operation whose region arguments should be validated.

Returns:

tuple[RegionArg, ...] — tuple[RegionArg, ...]: The validated op.region_args tuple.

Raises:

Classes

ArrayValue [source]

class ArrayValue(Value[T])

An array of typed IR values.

When slice_of is set, this array is a strided view over another array. Element accesses on a sliced ArrayValue resolve to physical slots on the root parent via the affine map parent_index = slice_start + slice_step * view_local_index, applied recursively along slice_of chains. The emit-time resolver walks this chain to produce the final qubit index; passes that substitute or clone values must treat slice_of / slice_start / slice_step as Value references that need to track through the same mapping as parent_array.

Constructor

def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
    shape: tuple[Value, ...] = tuple(),
    slice_of: 'ArrayValue | None' = None,
    slice_start: 'Value | None' = None,
    slice_step: 'Value | None' = None,
) -> None

Attributes

Methods

is_slice
def is_slice(self) -> bool

Return True if this array is a strided view of another array.

Returns:

boolTrue iff slice_of is non-None.

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

BinOp [source]

class BinOp(BinaryOperationBase)

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

Constructor

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

Attributes


BinOpKind [source]

class BinOpKind(enum.Enum)

Attributes


Block [source]

class Block

Unified block representation for all pipeline stages.

Replaces the older traced and callable IR wrappers with a single structure. The kind field indicates which pipeline stage this block is at.

Constructor

def __init__(
    self,
    name: str = '',
    label_args: list[str] = list(),
    input_values: list[ValueLike] = list(),
    output_values: list[ValueLike] = list(),
    output_names: list[str] = list(),
    operations: list['Operation'] = list(),
    kind: BlockKind = BlockKind.HIERARCHICAL,
    parameters: dict[str, Value] = dict(),
    param_slots: tuple[ParamSlot, ...] = tuple(),
    static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> None

Attributes

Methods

call
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'

Create an inline callable invocation against this block.

Parameters:

NameTypeDescription
**kwargsValueLikeActual argument values keyed by self.label_args.

Returns:

'InvokeOperation' — Inline-policy invocation whose callable definition points at this block.

Raises:

is_affine
def is_affine(self) -> bool

Return whether this block has passed affine validation.

Returns:

bool — True for AFFINE and ANALYZED blocks.

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

Return list of unbound parameter names.


CInitOperation [source]

class CInitOperation(Operation)

Initialize the classical values (const, arguments etc)

Constructor

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

Attributes


CallTransform [source]

class CallTransform(enum.Enum)

Describe the requested transform of a callable implementation.

Attributes

Methods

inverted
def inverted(self) -> CallTransform

Toggle inverse application while preserving coherent control.

Returns:

CallTransform — Transform with the inverse component toggled.


CallableRef [source]

class CallableRef

Identify a callable independently of its Python object.

Parameters:

NameTypeDescription
namespacestrStable namespace such as "qamomile.stdlib" or "user".
namestrStable callable name within the namespace.
versionstrSchema or behavior version for the callable.

Constructor

def __init__(self, namespace: str, name: str, version: str = '1') -> None

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


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


ConcreteControlledU [source]

class ConcreteControlledU(ControlledUOperation)

Controlled-U with concrete (int) number of controls.

Operand layout: [ctrl_0, ..., ctrl_n, tgt_0, ..., tgt_m, params...] Result layout: [ctrl_0', ..., ctrl_n', tgt_0', ..., tgt_m']

Constructor

def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_value: int | None = None,
) -> None

Attributes


ControlledUOperation [source]

class ControlledUOperation(Operation)

Base class for controlled-U operations.

Two concrete subclasses handle distinct operand layouts:

All isinstance(op, ControlledUOperation) checks match every subclass.

Constructor

def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int | Value = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
) -> None

Attributes

Methods

all_input_values
def all_input_values(self) -> list[ValueBase]
replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

DictValue [source]

class DictValue(_MetadataValueMixin, ValueBase)

A dictionary value stored as stable ordered entries.

Constructor

def __init__(
    self,
    name: str,
    entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None

Attributes

Methods

is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> DictValue

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body

Constructor

def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None

Attributes

Methods

all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

Without this override, UUIDRemapper would clone every body reference to the loop variable to a fresh UUID, but leave loop_var_value pointing at the un-cloned original — emit-time UUID-keyed lookups for the loop variable would then miss. Loop-carried rebind records and region arguments are included for the same reason.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the range-loop body with its explicit interface.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction value, carried-value formals, captures, and carried yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

GateOperation [source]

class GateOperation(Operation)

Quantum gate operation.

For rotation gates (RX, RY, RZ, P, CP, RZZ), the angle parameter is stored as the last element of operands. Use the theta property for typed read access and the rotation / fixed factory class-methods for type-safe construction.

Constructor

def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    gate_type: GateOperationType | None = None,
) -> None

Attributes

Methods

fixed
@classmethod
def fixed(
    cls,
    gate_type: GateOperationType,
    qubits: list[Value],
    results: list[Value],
) -> 'GateOperation'

Create a fixed gate (H, X, CX, SWAP, …) with no angle parameter.

rotation
@classmethod
def rotation(
    cls,
    gate_type: GateOperationType,
    qubits: list[Value],
    theta: Value,
    results: list[Value],
) -> 'GateOperation'

Create a rotation gate (RX, RY, RZ, P, CP, RZZ) with an angle.


GateOperationType [source]

class GateOperationType(enum.Enum)

Attributes


GlobalPhaseOperation [source]

class GlobalPhaseOperation(Operation)

Multiply the complete quantum state by exp(i * phase).

Global phase has no target qubit and does not create a new quantum value. Keeping the phase as the operation’s sole ordinary operand lets generic IR passes substitute, serialize, and analyze it without a special value-field protocol. A surrounding controlled-unitary lowering turns the operation into an observable phase gate on the accumulated controls.

Parameters:

NameTypeDescription
operandslist[Value]Exactly one scalar FloatType phase angle in radians.
resultslist[Value]Must be empty because global phase changes no qubit identity.

Raises:

Constructor

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

Attributes


HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

nested_regions() is the canonical traversal API because it exposes operations together with block arguments, captures, and yields. nested_op_lists() / rebuild_nested() remain compatibility helpers for specialized consumers while they migrate to the region interface.

Methods

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return all nested operation lists in this control flow op.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return uniform views of every nested operation region.

Subclasses with explicit block arguments, captures, or yields override this method. The fallback keeps legacy operation-owned blocks visible while consumers migrate from nested_op_lists.

Returns:

tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with nested operation lists replaced.

new_lists must have the same length/order as nested_op_lists().

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Return a copy with replacement region operation sequences.

Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


HugrCompilationPlan [source]

class HugrCompilationPlan

Describe the callable symbols emitted into one HUGR module.

Parameters:

NameTypeDescription
definitionstuple[CallableRef, ...]Reachable body-backed callable definitions emitted as HUGR functions.

Constructor

def __init__(self, definitions: tuple[CallableRef, ...]) -> None

Attributes


HugrTarget [source]

class HugrTarget

Plan, lower, package, and validate a Guppy-compatible HUGR target.

Attributes

Methods

compile
def compile(
    self,
    program: PreparedModule,
    plan: HugrCompilationPlan,
) -> CompiledProgram[Any]

Lower a prepared semantic module directly to a HUGR package.

Parameters:

NameTypeDescription
programPreparedModulePrepared hierarchical semantic program.
planHugrCompilationPlanCallable emission plan.

Returns:

CompiledProgram[Any] — CompiledProgram[Any]: HUGR package and target metadata.

Raises:

plan
def plan(self, program: PreparedModule) -> HugrCompilationPlan

Select reachable body-backed callables for HUGR functions.

Parameters:

NameTypeDescription
programPreparedModulePrepared hierarchical semantic program.

Returns:

HugrCompilationPlan — Stable callable-definition order.

Raises:

validate
def validate(self, artifact: Any) -> None

Validate a HUGR package with the native Rust-backed validator.

Parameters:

NameTypeDescription
artifactAnyhugr.package.Package to validate.

Raises:


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body

Constructor

def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None

Attributes

Methods

add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append a branch-merge slot to this if-else.

The only sanctioned construction path for merges: it keeps the yield lists and results index-aligned so iter_merges can rely on the invariants it checks.

Parameters:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

all_input_values
def all_input_values(self) -> list[ValueBase]

Include branch-yield values and rebind records for cloning/substitution.

The yields are subclass-specific Value fields (not operands — see the class docstring), so generic passes reach them through this override, mirroring ForItemsOperation.key_var_values. Branch rebind records follow the loop operations’ rationale: the recorded pre-branch values reference program values by identity, so inline cloning must remap them in lockstep with operands. Read-based checks must not treat the records as reads (see _op_read_uuids in the analyze pass module).

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus the true/false yields and rebind-record values.

iter_merges
def iter_merges(self) -> Iterator[IfMerge]

Iterate the branch-merge slots of this if-else.

This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.

Yields:

IfMerge — One entry per merged output, in result order.

Raises:

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]

Return the two branch bodies (merge yields are not operations).

Returns:

list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations]. The branch-merge yields are values, not operations, so they are intentionally absent here.

nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the true and false branch interfaces.

Returns:

tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with branch-local captures and merge yields.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[list[Operation]]The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]).

Returns:

Operation — A copy of this if-else with the branch bodies swapped and all other fields (yields, rebinds) preserved.

rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


InverseBlockOperation [source]

class InverseBlockOperation(Operation)

Represent an inverse qkernel/block as a first-class IR operation.

The operation stores both the original forward block and a Qamomile-built inverse implementation block. Emitters may use source_block with a engine-native inverse/adjoint primitive, then fall back to implementation_block when native inversion is unavailable.

Operands are ordered as scalar control qubits, target quantum operands, then classical/object parameters. Results mirror the quantum operand layout: control results first, then one target result per target operand. Vector target operands therefore count as one operand/result while contributing their scalar width to num_target_qubits.

Constructor

def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_control_qubits: int = 0,
    num_target_qubits: int = 0,
    custom_name: str = '',
    source_block: Block | None = None,
    implementation_block: Block | None = None,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
    control_value: int | None = None,
) -> None

Attributes


InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.

Constructor

def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes

Methods

body_for_transform
def body_for_transform(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> tuple[Block | None, CallTransform]

Select a body and report the transform it already realizes.

A controlled-inverse invocation may reuse an explicitly registered inverse body when no implementation realizes both transforms. Keeping that fallback in the IR operation gives emitters and static analyses one selection rule while still letting each consumer apply the remaining coherent controls in its own representation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — tuple[Block | None, CallTransform]: Selected body and the transform CallTransform — already implemented by that body. The callable’s direct body is tuple[Block | None, CallTransform] — returned with DIRECT when no transform-specific body matches.

Raises:

effective_body
def effective_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

Block | None — Block | None: Selected implementation body, or the callable’s Block | None — default body when no transform-specific implementation exists. Block | None — A compiler may synthesize inverse or controlled behavior from this Block | None — fallback body.

implementation_for
def implementation_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
    require_body: bool = False,
) -> CallableImplementation | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None, which only selects engine-generic implementations.
strategystr | NoneStrategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used.
require_bodyboolWhether candidates without an IR body should be excluded before ranking. Defaults to False.

Returns:

CallableImplementation | None — CallableImplementation | None: Matching implementation candidate, CallableImplementation | None — or None when the callable definition has no match.

measurement_result_indices_for
def measurement_result_indices_for(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> frozenset[int]

Return measurement-derived results for one selected implementation.

Parameters:

NameTypeDescription
enginestr | NoneEngine name used for implementation selection. Defaults to None.
strategystr | NoneStrategy name used for implementation selection. Defaults to the invocation’s strategy_name.

Returns:

frozenset[int] — frozenset[int]: Caller-local result positions derived from measurement in the selected body.

Raises:

select_body
def select_body(
    self,
    *,
    engine: str | None = None,
    strategy: str | None = None,
) -> CallableBodySelection

Select and validate the composable body for this invocation.

The result carries the transform already realized by the body and the exact call-site values that bind to it. Consumers therefore cannot independently disagree about whether an invocation’s control prefix belongs to the selected implementation ABI.

Parameters:

NameTypeDescription
enginestr | NoneEngine name to match. Defaults to None.
strategystr | NoneStrategy name to match. Defaults to the invocation’s strategy_name attribute.

Returns:

CallableBodySelection — Validated body, realized transform, and CallableBodySelection — aligned call-site operands and results.

Raises:


LoopCarriedRebind [source]

class LoopCarriedRebind

Trace-time record of a variable rebound inside a loop body.

Two rebind families share this record type, distinguished by the type of before:

Constructor

def __init__(
    self,
    var_name: str,
    before: ValueBase,
    after: ValueBase,
    before_synthesized: bool = False,
) -> None

Attributes


MeasureOperation [source]

class MeasureOperation(Operation)

Constructor

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

Attributes


MeasureQFixedOperation [source]

class MeasureQFixedOperation(Operation)

Measure a quantum fixed-point number.

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

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

Encoding:

For QPE phase (int_bits=0): Qubits are stored least-significant first. For n qubits, bit i has weight 2**(-n + i).

Constructor

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

Attributes


MeasureQIntOperation [source]

class MeasureQIntOperation(Operation)

Measure an unsigned quantum integer as one abstract hybrid operation.

The carrier sequence is least-significant-bit first: carrier i has integer weight 2**i. Planning lowers this operation to one vector measurement followed by a host-side DecodeQIntOperation.

The carrier width is not stored on the operation: it is derived from the register operand’s type and carrier metadata through num_bits.

Parameters:

NameTypeDescription
operandslist[Value]Single QUIntType register operand.
resultslist[Value]Single decoded UIntType result.

Constructor

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

Attributes


MeasureVectorOperation [source]

class MeasureVectorOperation(Operation)

Measure a vector of qubits.

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

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

Constructor

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

Attributes


NotOp [source]

class NotOp(Operation)

Constructor

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

Attributes


PauliEvolveOp [source]

class PauliEvolveOp(Operation)

Pauli evolution operation: exp(-i * gamma * H).

This operation applies the time evolution of a Pauli Hamiltonian to a quantum register.

Constructor

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

Attributes


ProjectOperation [source]

class ProjectOperation(Operation)

Project a qubit in one Pauli basis and keep the projected state.

Constructor

def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    axis: str = 'z',
) -> None

Attributes


QInitOperation [source]

class QInitOperation(Operation)

Initialize the qubit

Constructor

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

Attributes


ReleaseSliceViewOperation [source]

class ReleaseSliceViewOperation(Operation)

Mark a slice view’s borrow as explicitly returned to its parent.

Emitted by :meth:Vector.__setitem__ when used with a slice index (qs[a:b] = qmc.h(qs[a:b])). This op tells the post-fold linearity checker (:class:~qamomile.circuit.transpiler.passes.slice_borrow_check.SliceBorrowCheckPass) that the view referenced in operands[0] no longer owns its covered parent slots, mirroring the frontend’s VectorView.consume(operation_name="slice assignment") borrow release.

Like :class:SliceArrayOperation, this op is a declarative classical-side marker that does not survive into the emit stream: :class:~qamomile.circuit.transpiler.passes.strip_slice_ops.StripSliceArrayOpsPass removes both :class:SliceArrayOperation and :class:ReleaseSliceViewOperation after :class:SliceBorrowCheckPass has observed them. Reaching emit is a compiler-internal invariant violation and is rejected with a RuntimeError from :mod:standard_emit.

Within a control-flow body (ForOperation / WhileOperation / IfOperation), this op only releases view borrows that were created within the same body. Releasing a borrow that the enclosing block has registered (an “outer-snapshot” borrow) is rejected by SliceBorrowCheckPass with ValidationError — the loop-merge semantics of the pass cannot propagate entry deletions out of the body, so the only way to keep the static check consistent is to forbid that pattern.

Example:

``qs[1:3] = qmc.h(qs[1:3])`` emits, after the broadcast loop::

    ReleaseSliceViewOperation(
        operands=[qmc_h_result_view],  # slice_of=qs_value
        results=[],
    )

Constructor

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

Attributes


ResetOperation [source]

class ResetOperation(Operation)

Reset a qubit to the |0> state and return the fresh handle.

Constructor

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

Attributes


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


SelectOperation [source]

class SelectOperation(Operation)

Quantum multiplexer: apply case_blocks[i] when the index reads i.

Concrete operand layout: [idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...]. Symbolic-width operand layout: [idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...]. Results mirror the quantum operand grouping.

A concrete index register is normalized to one scalar Qubit operand per physical index qubit. A symbolic-width register instead retains each leading caller argument as one scalar or array operand until its bound shape is known. Whole-Vector[Qubit] / scalar targets follow and keep their shapes, and classical parameters shared across every case come last.

Index bit order is LSB-first: idx_0 is the least-significant bit, matching Qamomile’s qubit-zero convention. Case i is selected when index qubit j reads bit j of i. len(case_blocks) need not be a power of two; index values >= len(case_blocks) apply no operation (identity).

Constructor

def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    num_index_qubits: int | Value = 0,
    case_blocks: list[Block] = list(),
    num_index_args: int = 0,
    case_callable_attrs: list[dict[str, Any]] = list(),
) -> None

Attributes

Methods

all_input_values
def all_input_values(self) -> list[ValueBase]

Return every value consumed by the SELECT operation.

Returns:

list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width value when present.

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed replacement values.

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


SliceArrayOperation [source]

class SliceArrayOperation(Operation)

Construct a strided view of an ArrayValue.

The op itself performs no quantum action — it records that the result ArrayValue is a strided view of the operand parent with the given start / step. The result’s slice_of / slice_start / slice_step fields carry the affine map used by the emit-time resolver.

SliceArrayOperation is classified as :attr:OperationKind.CLASSICAL because slicing is pure index selection — no new quantum operation is introduced. The pipeline keeps this op through PartialEvaluationPass (which invokes ConstantFoldingPass(..., strip_slice_ops=False)) so the post-fold :class:~qamomile.circuit.transpiler.passes.slice_borrow_check.SliceBorrowCheckPass can use it as a view-declaration marker; once that check has run, StripSliceArrayOpsPass removes every SliceArrayOperation / ReleaseSliceViewOperation so segmentation (:mod:~qamomile.circuit.transpiler.passes.separate) and the downstream emit stage only see a pure quantum-op stream. By the time :mod:~qamomile.circuit.transpiler.passes.separate runs the op has therefore been stripped — reaching emit is a compiler- internal invariant violation.

Example:

``q[1::2]`` on a ``Vector[Qubit]`` emits::

    SliceArrayOperation(
        operands=[q_value, uint_1, uint_2],
        results=[sliced_value],  # slice_of=q_value, slice_start=uint_1, slice_step=uint_2
    )

Constructor

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

Attributes


TupleValue [source]

class TupleValue(_MetadataValueMixin, ValueBase)

A tuple of IR values for structured data.

Constructor

def __init__(
    self,
    name: str,
    elements: tuple[ValueLike, ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None

Attributes

Methods

is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> TupleValue

Value [source]

class Value(_MetadataValueMixin, ValueBase, Generic[T])

A typed SSA value in the IR.

The name field is display-only: it labels the value for visualization and error messages and has no role in identity. Identity is carried by uuid (per-version) and logical_id (across versions).

An empty string (name="") is the anonymous marker used by auto-generated tmp values (arithmetic results, comparison results, coerced constants). Compiler-internal identity and writes use UUIDs or explicit parameter metadata. Compatibility readers may consult a non-empty label only after those identity channels, so anonymous temporaries cannot collide through a shared display key.

Constructor

def __init__(
    self,
    type: T,
    name: str,
    version: int = 0,
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
    parent_array: ArrayValue | None = None,
    element_indices: tuple[Value, ...] = (),
) -> None

Attributes

Methods

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

Create a new Value with incremented version and fresh UUID.

Metadata is intentionally preserved across versions so that parameter bindings and constant annotations remain accessible after the value is updated (e.g. by a gate application or a classical operation). The logical_id also stays the same: it identifies the same logical variable across SSA versions, independently of engine resource allocation. This applies to every Value regardless of its type (Qubit, Float, Bit, ...) -- it is not specific to qubits.


ValueBase [source]

class ValueBase

Nominal base for every typed IR value.

Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.

Attributes

Methods

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

Return the scalar constant carried by this value.

Returns:

int | float | bool | None — int | float | bool | None: Constant value, or None when the value is not constant.

is_constant
def is_constant(self) -> bool

Return whether this value carries a scalar constant.

Returns:

bool — Whether scalar constant metadata is present.

is_parameter
def is_parameter(self) -> bool

Return whether this value represents a runtime parameter.

Returns:

bool — Whether parameter metadata is present.

next_version
def next_version(self) -> ValueBase

Create the next SSA version of this value.

Returns:

ValueBase — A value with a fresh version UUID and preserved logical identity.

parameter_name
def parameter_name(self) -> str | None

Return the public parameter name carried by this value.

Returns:

str | None — str | None: Parameter name, or None for a non-parameter value.


ValueType [source]

class ValueType(abc.ABC)

Base class for all value types in the IR.

Type instances are compared by class - all instances of the same type class are considered equal. This allows using type instances as dictionary keys where all QubitType() instances match.

Methods

is_classical
def is_classical(self) -> bool
is_object
def is_object(self) -> bool
is_quantum
def is_quantum(self) -> bool
label
def label(self) -> str

WhileOperation [source]

class WhileOperation(HasNestedOps, Operation)

Represents a while loop operation.

Only measurement-backed conditions are supported: the condition must be a Bit value produced by qmc.measure(). Non-measurement conditions (classical variables, constants, comparisons) are rejected by ValidateWhileContractPass before reaching engine emit.

Example::

bit = qmc.measure(q)
while bit:
    q = qmc.h(q)
    bit = qmc.measure(q)

Constructor

def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    operations: list[Operation] = list(),
    max_iterations: int | None = None,
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None

Attributes

Methods

all_input_values
def all_input_values(self) -> list[ValueBase]

Include rebind records and region args for cloning/substitution.

Same rationale as ForOperation.all_input_values: rebind records and region arguments reference body/pre-loop values by identity, so inline cloning must remap them in lockstep with body operands.

Returns:

list[ValueBase] — list[ValueBase]: Base input values plus rebind-record and region-argument values.

nested_op_lists
def nested_op_lists(self) -> list[list[Operation]]
nested_regions
def nested_regions(self) -> tuple[Region, ...]

Return the while body with explicit boundary values.

Returns:

tuple[Region, ...] — tuple[Region, ...]: One body region whose block arguments and yields are aligned with region_args. The updated condition, when present, is appended as the final yield.

rebuild_nested
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the while body and its complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt while operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, rebind-record, and region-arg values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.