Persist one unbound qkernel and reconstruct it without Python source.
The protobuf format preserves the highest target-neutral static semantics: the qkernel interface, hierarchical IR body, shared callable definitions, and all value-identity relationships needed by later compiler passes. Random process-local UUID and logical-ID spellings are replaced by canonical graph-local identities. Invocation bindings, runtime values, prepared compiler modules, backend artifacts, resource estimates, and Python evaluation performed during tracing are outside the format.
After :func:deserialize, pass the returned :class:SerializedQKernel to an
ordinary Qamomile transpiler with fresh bindings and parameters.
Registered compile-time object arguments are stored only as typed binding
slots. Their concrete values are deliberately absent from the payload and must
be supplied through bindings after deserialization.
Overview¶
| Function | Description |
|---|---|
deserialize | Deserialize protobuf bytes into a static qkernel-like object. |
serialize | Serialize one unbound qkernel to canonical protobuf bytes. |
| Class | Description |
|---|---|
SerializedQKernel | A qkernel whose Python-independent semantic IR was deserialized. |
Constants¶
QAMOMILE_VERSION:str=version('qamomile')
Functions¶
deserialize [source]¶
def deserialize(payload: bytes) -> SerializedQKernelDeserialize protobuf bytes into a static qkernel-like object.
Parameters:
| Name | Type | Description |
|---|---|---|
payload | bytes | Bytes produced by :func:serialize. |
Returns:
SerializedQKernel — Reconstructed qkernel accepted by transpilers.
Raises:
TypeError— Ifpayloadis not bytes-like.ValueError— If parsing, version validation, or reconstruction fails.
serialize [source]¶
def serialize(kernel: QKernelLike) -> bytesSerialize one unbound qkernel to canonical protobuf bytes.
Independently traced equivalent qkernels produce identical bytes because process-local value identities are normalized before protobuf encoding.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | Static qkernel-like object to serialize. |
Returns:
bytes — Deterministic protobuf encoding.
Raises:
TypeError— If the qkernel contains an unsupported type or payload.ValueError— If the qkernel is bound, lowered, or malformed.
Classes¶
SerializedQKernel [source]¶
class SerializedQKernelA qkernel whose Python-independent semantic IR was deserialized.
The object implements the compiler-facing qkernel protocol. Its body is a
static, unbound hierarchical block, so :meth:build specializes existing
IR values instead of executing the original Python function again.
Constructor¶
def __init__(
self,
name: str,
signature: inspect.Signature,
input_types: dict[str, Any],
output_types: list[Any],
_block: Block,
_callable_definition: CallableDef,
) -> NoneAttributes¶
block: Block Return the cached unbound hierarchical body.effects: KernelEffect Return cached semantic effects of the preserved body.input_types: dict[str, Any]name: stroutput_types: list[Any]signature: inspect.Signature
Methods¶
build¶
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> BlockSpecialize the preserved IR for bindings and runtime parameters.
This method mirrors the public qkernel argument contract while avoiding Python re-tracing. Compile-time values replace the corresponding formal IR values; runtime parameters remain symbolic.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | list[str] | None | Names retained as backend runtime parameters. None auto-detects unbound parameterizable arguments. |
**kwargs | Any | Compile-time bindings keyed by qkernel argument. |
Returns:
Block — Specialized traced-stage body accepted by the normal
Qamomile compiler pipeline.
Raises:
TypeError— If a requested parameter or binding type is unsupported.ValueError— If arguments are unknown, missing, or present in bothparametersandkwargs.
qamomile.circuit.serialization.canonical¶
Canonicalize process-local identities in serialized qkernel graphs.
Overview¶
| Function | Description |
|---|---|
canonicalize_graph | Replace random value identities with deterministic graph-local IDs. |
Functions¶
canonicalize_graph [source]¶
def canonicalize_graph(envelope: dict[str, Any]) -> dict[str, Any]Replace random value identities with deterministic graph-local IDs.
Value-table order is the semantic encoder’s deterministic first-visit order. The rewrite preserves every equality and reference relationship while making independently traced instances of the same qkernel byte-identical.
Parameters:
| Name | Type | Description |
|---|---|---|
envelope | dict[str, Any] | Complete internal qkernel graph envelope. |
Returns:
dict[str, Any] — dict[str, Any]: A deep-copied envelope with canonical UUID and logical-ID
strings.
Raises:
ValueError— If the value table or an identity-bearing field is malformed.
qamomile.circuit.serialization.decode¶
Decode one static qkernel from the semantic protobuf graph model.
Overview¶
| Function | Description |
|---|---|
build_param_slots | Build a ParamSlot tuple for the classical arguments of a kernel. |
from_dict | Reconstruct a static qkernel from an internal graph envelope. |
get_static_binding_by_type_key | Return the adapter registered under a stable serialization key. |
handle_type_map | Map Handle type to ValueType. |
validate_qkernel_ir | Validate every operation and nested region reachable from a qkernel. |
validate_static_binding_slot | Validate a serialized IR slot against its installed adapter. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
SerializedQKernel | A qkernel whose Python-independent semantic IR was deserialized. |
Constants¶
QAMOMILE_VERSION:str=version('qamomile')ValueLike:TypeAlias='Value | ArrayValue | TupleValue | DictValue'
Functions¶
build_param_slots [source]¶
def build_param_slots(
signature: inspect.Signature,
input_types: dict[str, Any],
*,
parameters: list[str] | None = None,
kwargs: dict[str, Any] | None = None,
qubit_sizes: dict[str, int] | None = None,
bind_defaults: bool,
) -> tuple[ParamSlot, ...]Build a ParamSlot tuple for the classical arguments of a kernel.
Mirrors the argument-classification logic in
qkernel_build.create_traced_block so the resulting slot list reflects
the same decisions that drive symbolic-vs-bound input creation.
Classical scalar / array arguments are always included; a Dict
argument is included only when it is a runtime parameter (its slot
carries a DictType). Pure-quantum arguments, Tuple arguments,
and compile-time-bound Dict arguments are excluded and live in
Block.input_values instead.
Parameters:
| Name | Type | Description |
|---|---|---|
signature | inspect.Signature | The kernel function’s signature. |
input_types | dict[str, Any] | Resolved frontend type annotations keyed by argument name (typically QKernel.input_types or the equivalent computed in func_to_block). |
parameters | list[str] | None | Names explicitly requested as runtime parameters via parameters=[...]. None is treated as an empty list. |
kwargs | dict[str, Any] | None | Concrete values supplied via bindings / direct kwargs. None is treated as an empty dict. |
qubit_sizes | dict[str, int] | None | Optional mapping from Vector[Qubit] parameter names to their integer sizes; these are quantum inputs and are not included in the slot list. |
bind_defaults | bool | When True, Python signature defaults are treated as COMPILE_TIME_BOUND with bound_value=default. When False (e.g., the func_to_block path that does not bake in defaults), defaulted arguments stay RUNTIME_PARAMETER and the default appears only in ParamSlot.default. |
Returns:
tuple[ParamSlot, ...] — tuple[ParamSlot, ...]: One slot per classical argument, in the
order they appear in signature.parameters.
Raises:
TypeError— If a non-static classical annotation cannot be represented by an IR parameter type.
from_dict [source]¶
def from_dict(envelope: dict[str, Any]) -> SerializedQKernelReconstruct a static qkernel from an internal graph envelope.
Parameters:
| Name | Type | Description |
|---|---|---|
envelope | dict[str, Any] | Dictionary produced by :func:to_dict. |
Returns:
SerializedQKernel — QKernel-like object accepted by normal transpilers.
Raises:
ValueError— If the version, graph, interface, or references are malformed.
get_static_binding_by_type_key [source]¶
def get_static_binding_by_type_key(type_key: str) -> StaticBindingSpecReturn the adapter registered under a stable serialization key.
Parameters:
| Name | Type | Description |
|---|---|---|
type_key | str | Stable type key from serialized IR. |
Returns:
StaticBindingSpec — Matching registered adapter.
Raises:
KeyError— If the installed Qamomile distribution does not know the key.
handle_type_map [source]¶
def handle_type_map(handle_type: type[Handle] | type) -> ValueTypeMap Handle type to ValueType.
validate_qkernel_ir [source]¶
def validate_qkernel_ir(block: Block) -> NoneValidate every operation and nested region reachable from a qkernel.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Root unbound hierarchical qkernel block. |
Raises:
ValueError— If an operation violates its arity, type, SSA, callable, or region contract.
validate_static_binding_slot [source]¶
def validate_static_binding_slot(spec: StaticBindingSpec, slot: StaticBindingSlot) -> NoneValidate a serialized IR slot against its installed adapter.
Parameters:
| Name | Type | Description |
|---|---|---|
spec | StaticBindingSpec | Installed adapter contract. |
slot | StaticBindingSlot | IR manifest entry to validate. |
Raises:
ValueError— If the type key, projected field names, or field types do not exactly match the registered adapter.
Classes¶
ArrayValue [source]¶
class ArrayValue(Value[T])An array of typed IR values.
When slice_of is set, this array is a strided view over another
array. Element accesses on a sliced ArrayValue resolve to
physical slots on the root parent via the affine map
parent_index = slice_start + slice_step * view_local_index,
applied recursively along slice_of chains. The emit-time
resolver walks this chain to produce the final qubit index; passes
that substitute or clone values must treat slice_of /
slice_start / slice_step as Value references that need to
track through the same mapping as parent_array.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
shape: tuple[Value, ...] = tuple(),
slice_of: 'ArrayValue | None' = None,
slice_start: 'Value | None' = None,
slice_step: 'Value | None' = None,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]SerializedQKernel [source]¶
class SerializedQKernelA qkernel whose Python-independent semantic IR was deserialized.
The object implements the compiler-facing qkernel protocol. Its body is a
static, unbound hierarchical block, so :meth:build specializes existing
IR values instead of executing the original Python function again.
Constructor¶
def __init__(
self,
name: str,
signature: inspect.Signature,
input_types: dict[str, Any],
output_types: list[Any],
_block: Block,
_callable_definition: CallableDef,
) -> NoneAttributes¶
block: Block Return the cached unbound hierarchical body.effects: KernelEffect Return cached semantic effects of the preserved body.input_types: dict[str, Any]name: stroutput_types: list[Any]signature: inspect.Signature
Methods¶
build¶
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> BlockSpecialize the preserved IR for bindings and runtime parameters.
This method mirrors the public qkernel argument contract while avoiding Python re-tracing. Compile-time values replace the corresponding formal IR values; runtime parameters remain symbolic.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | list[str] | None | Names retained as backend runtime parameters. None auto-detects unbound parameterizable arguments. |
**kwargs | Any | Compile-time bindings keyed by qkernel argument. |
Returns:
Block — Specialized traced-stage body accepted by the normal
Qamomile compiler pipeline.
Raises:
TypeError— If a requested parameter or binding type is unsupported.ValueError— If arguments are unknown, missing, or present in bothparametersandkwargs.
qamomile.circuit.serialization.encode¶
Encode one unbound qkernel into the semantic protobuf graph model.
Overview¶
| Function | Description |
|---|---|
canonicalize_graph | Replace random value identities with deterministic graph-local IDs. |
get_static_binding_by_annotation | Return the adapter registered for a qkernel annotation. |
handle_type_map | Map Handle type to ValueType. |
is_array_type | Check if type is a Vector, Matrix, or Tensor subclass. |
is_dict_type | Check if type is a Dict handle type. |
is_tuple_type | Check if type is a Tuple handle type. |
qkernel_callable_attrs | Return compiler attrs for a qkernel invocation. |
qkernel_callable_ref | Return the compiler-facing callable reference for a qkernel. |
to_dict | Encode an unbound qkernel into an internal graph envelope. |
validate_qkernel_ir | Validate every operation and nested region reachable from a qkernel. |
validate_static_binding_slot | Validate a serialized IR slot against its installed adapter. |
| Class | Description |
|---|---|
BlockKind | Classification of block structure for pipeline stages. |
CallPolicy | Describe the default lowering policy for a callable call. |
CallableDef | Describe a compiler-facing callable definition. |
ParamKind | Lifecycle classification for a classical kernel argument. |
QKernelLike | Describe the frontend surface required by compiler entrypoints. |
ValueBase | Nominal base for every typed IR value. |
Constants¶
QAMOMILE_VERSION:str=version('qamomile')
Functions¶
canonicalize_graph [source]¶
def canonicalize_graph(envelope: dict[str, Any]) -> dict[str, Any]Replace random value identities with deterministic graph-local IDs.
Value-table order is the semantic encoder’s deterministic first-visit order. The rewrite preserves every equality and reference relationship while making independently traced instances of the same qkernel byte-identical.
Parameters:
| Name | Type | Description |
|---|---|---|
envelope | dict[str, Any] | Complete internal qkernel graph envelope. |
Returns:
dict[str, Any] — dict[str, Any]: A deep-copied envelope with canonical UUID and logical-ID
strings.
Raises:
ValueError— If the value table or an identity-bearing field is malformed.
get_static_binding_by_annotation [source]¶
def get_static_binding_by_annotation(annotation: Any) -> StaticBindingSpec | NoneReturn the adapter registered for a qkernel annotation.
Parameters:
| Name | Type | Description |
|---|---|---|
annotation | Any | Resolved qkernel parameter annotation. |
Returns:
StaticBindingSpec | None — StaticBindingSpec | None: Registered adapter, or None for an
StaticBindingSpec | None — ordinary qkernel argument.
handle_type_map [source]¶
def handle_type_map(handle_type: type[Handle] | type) -> ValueTypeMap Handle type to ValueType.
is_array_type [source]¶
def is_array_type(t: Any) -> boolCheck if type is a Vector, Matrix, or Tensor subclass.
is_dict_type [source]¶
def is_dict_type(t: Any) -> boolCheck if type is a Dict handle type.
is_tuple_type [source]¶
def is_tuple_type(t: Any) -> boolCheck if type is a Tuple handle type.
qkernel_callable_attrs [source]¶
def qkernel_callable_attrs(kernel: Any) -> dict[str, Any]Return compiler attrs for a qkernel invocation.
Composite metadata lives directly on QKernel. This helper is the
single translation point from that frontend state into serializer-safe IR
attributes, so direct, controlled, and inverse calls share one identity.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | Any | QKernel-like object carrying callable metadata. |
Returns:
dict[str, Any] — dict[str, Any]: Serializer-friendly callable attributes.
qkernel_callable_ref [source]¶
def qkernel_callable_ref(kernel: Any) -> CallableRefReturn the compiler-facing callable reference for a qkernel.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | Any | QKernel-like object carrying callable metadata. |
Returns:
CallableRef — Stable reference used by InvokeOperation call sites.
to_dict [source]¶
def to_dict(kernel: QKernelLike) -> dict[str, Any]Encode an unbound qkernel into an internal graph envelope.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | QKernel-like frontend object whose static body is preserved. |
Returns:
dict[str, Any] — dict[str, Any]: Internal graph record consumed by the protobuf bridge.
Raises:
TypeError— Ifkernelis not qkernel-like or contains an unsupported frontend type or process-local emitter.ValueError— If the body is specialized, non-hierarchical, or its interface disagrees with the signature.
validate_qkernel_ir [source]¶
def validate_qkernel_ir(block: Block) -> NoneValidate every operation and nested region reachable from a qkernel.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Root unbound hierarchical qkernel block. |
Raises:
ValueError— If an operation violates its arity, type, SSA, callable, or region contract.
validate_static_binding_slot [source]¶
def validate_static_binding_slot(spec: StaticBindingSpec, slot: StaticBindingSlot) -> NoneValidate a serialized IR slot against its installed adapter.
Parameters:
| Name | Type | Description |
|---|---|---|
spec | StaticBindingSpec | Installed adapter contract. |
slot | StaticBindingSlot | IR manifest entry to validate. |
Raises:
ValueError— If the type key, projected field names, or field types do not exactly match the registered adapter.
Classes¶
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
CallPolicy [source]¶
class CallPolicy(enum.Enum)Describe the default lowering policy for a callable call.
Attributes¶
INLINENATIVE_FIRSTPRESERVE_BOX
CallableDef [source]¶
class CallableDefDescribe a compiler-facing callable definition.
Parameters:
| Name | Type | Description |
|---|---|---|
ref | CallableRef | Stable callable identity. |
signature | Signature | None | Optional callable signature. |
body | Block | None | Standard IR body, or None for opaque calls. |
body_ref | CallableBodyRef | None | Reference to a standard body that is intentionally deferred. Defaults to None. |
implementations | list[CallableImplementation] | Alternative native or strategy-specific implementations. |
opaque_cost | Any | None | Explicit cost contract for a bodyless callable. Body-backed callables must leave this as None. |
default_policy | CallPolicy | Default call lowering policy. |
attrs | dict[str, Any] | Serializer-friendly definition metadata. |
Constructor¶
def __init__(
self,
ref: CallableRef,
signature: Signature | None = None,
body: Block | None = None,
body_ref: CallableBodyRef | None = None,
implementations: list[CallableImplementation] = list(),
opaque_cost: Any | None = None,
default_policy: CallPolicy = CallPolicy.INLINE,
attrs: dict[str, Any] = dict(),
) -> NoneAttributes¶
attrs: dict[str, Any]body: Block | Nonebody_ref: CallableBodyRef | Nonedefault_policy: CallPolicyimplementations: list[CallableImplementation]opaque_cost: Any | Noneref: CallableRefsignature: Signature | None
Methods¶
effects_for¶
def effects_for(self, transform: CallTransform = CallTransform.DIRECT) -> 'KernelEffect'Return cached semantic effects for one call transform.
Parameters:
| Name | Type | Description |
|---|---|---|
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
Returns:
'KernelEffect' — Union of relevant implementation-body effects.
implementation_for¶
def implementation_for(
self,
*,
transform: CallTransform = CallTransform.DIRECT,
backend: str | None = None,
strategy: str | None = None,
) -> CallableImplementation | NoneReturn the best matching implementation candidate.
Parameters:
| Name | Type | Description |
|---|---|---|
transform | CallTransform | Requested call transform. |
backend | str | None | Requested backend name. |
strategy | str | None | Requested strategy name. |
Returns:
CallableImplementation | None — CallableImplementation | None: Matching implementation, if any.
measurement_result_indices_for¶
def measurement_result_indices_for(self, transform: CallTransform = CallTransform.DIRECT) -> frozenset[int]Return measured result positions for one call transform.
Parameters:
| Name | Type | Description |
|---|---|---|
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
Returns:
frozenset[int] — frozenset[int]: Result indices carrying measurement provenance.
ParamKind [source]¶
class ParamKind(enum.Enum)Lifecycle classification for a classical kernel argument.
Values:
RUNTIME_PARAMETER: The argument is intended to be bound at
execution time by the backend (or, more generally, by the
outer caller in a hybrid loop). It survives the
compilation pipeline as a symbolic parameter.
COMPILE_TIME_BOUND: The argument was provided as a binding
(or via a Python default) and is folded into the IR by
resolve_parameter_shapes / partial_eval. No
symbolic counterpart remains in the emitted circuit.
Attributes¶
COMPILE_TIME_BOUNDRUNTIME_PARAMETER
QKernelLike [source]¶
class QKernelLike(Protocol)Describe the frontend surface required by compiler entrypoints.
This protocol is intentionally structural. It lets decorator-created
composites reuse the qkernel inspection and build interface without making
them inherit from QKernel or exposing the compiler-facing callable
descriptor model as a frontend concept.
Attributes¶
block: Block Return the cached hierarchical body block.effects: KernelEffect Return cached semantic effects of the qkernel body.input_types: dict[str, Any] Return frontend input annotations by parameter name.name: str Return the user-facing callable name.output_types: list[Any] Return frontend output annotations.signature: inspect.Signature Return the Python call signature.
Methods¶
build¶
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> BlockBuild a traced body block.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | list[str] | None | Runtime parameter names to preserve. Defaults to None. |
**kwargs | Any | Compile-time bindings for non-parameter arguments. |
Returns:
Block — Traced hierarchical body block.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
qamomile.circuit.serialization.graph_protobuf¶
Convert semantic IR graph records to the qkernel protobuf schema.
Overview¶
| Function | Description |
|---|---|
graph_dict_from_qkernel | Convert a qkernel protobuf into the internal semantic graph record. |
qkernel_from_graph_dict | Convert the internal static-qkernel graph record into protobuf. |
Constants¶
QAMOMILE_VERSION:str=version('qamomile')
Functions¶
graph_dict_from_qkernel [source]¶
def graph_dict_from_qkernel(message: pb.QKernel) -> dict[str, Any]Convert a qkernel protobuf into the internal semantic graph record.
Parameters:
| Name | Type | Description |
|---|---|---|
message | pb.QKernel | Parsed qkernel graph. |
Returns:
dict[str, Any] — dict[str, Any]: Graph record accepted by the semantic decoders.
Raises:
ValueError— If the version, interface, or a typed protobuf field is missing or inconsistent.
qkernel_from_graph_dict [source]¶
def qkernel_from_graph_dict(envelope: dict[str, Any]) -> pb.QKernelConvert the internal static-qkernel graph record into protobuf.
This bridge keeps graph construction separate from the canonical wire schema. The resulting bytes contain only protobuf fields, never JSON or a pickled Python dictionary.
Parameters:
| Name | Type | Description |
|---|---|---|
envelope | dict[str, Any] | Validated graph record from the qkernel encoder. |
Returns:
pb.QKernel — pb.QKernel: Canonical qkernel protobuf graph.
Raises:
ValueError— If the graph envelope or qkernel interface is malformed.TypeError— If a nested payload is outside the closed protobuf union.
qamomile.circuit.serialization.graph_protobuf.pb¶
Generated protocol buffer code.
Overview¶
Constants¶
ARRAY_VALUE:ValueKindBIN_OPERATION:OperationTypeBIT_TYPE:ValueTypeKindBLOCK_TYPE:ValueTypeKindCAST_OPERATION:OperationTypeCINIT_OPERATION:OperationTypeCOMP_OPERATION:OperationTypeCONCRETE_CONTROLLED_OPERATION:OperationTypeCOND_OPERATION:OperationTypeDECODE_QFIXED_OPERATION:OperationTypeDESCRIPTOR:_descriptor.FileDescriptorDICT_GET_ITEM_OPERATION:OperationTypeDICT_TYPE:ValueTypeKindDICT_VALUE:ValueKindEXPVAL_OPERATION:OperationTypeFLOAT_TYPE:ValueTypeKindFOR_ITEMS_OPERATION:OperationTypeFOR_OPERATION:OperationTypeFRONTEND_ANNOTATION_KIND_UNSPECIFIED:FrontendAnnotationKindGATE_OPERATION:OperationTypeGLOBAL_PHASE_OPERATION:OperationTypeIF_OPERATION:OperationTypeINVERSE_BLOCK_OPERATION:OperationTypeINVOKE_OPERATION:OperationTypeKEYWORD_ONLY:ParameterKindMEASURE_OPERATION:OperationTypeMEASURE_QFIXED_OPERATION:OperationTypeMEASURE_VECTOR_OPERATION:OperationTypeNOT_OPERATION:OperationTypeOBSERVABLE_TYPE:ValueTypeKindOPERATION_TYPE_UNSPECIFIED:OperationTypePARAMETER_KIND_UNSPECIFIED:ParameterKindPAULI_EVOLVE_OPERATION:OperationTypePOSITIONAL_ONLY:ParameterKindPOSITIONAL_OR_KEYWORD:ParameterKindPROJECT_OPERATION:OperationTypePYTHON_BOOL:FrontendAnnotationKindPYTHON_FLOAT:FrontendAnnotationKindPYTHON_INT:FrontendAnnotationKindPYTHON_TUPLE:FrontendAnnotationKindQAMOMILE_BIT:FrontendAnnotationKindQAMOMILE_DICT:FrontendAnnotationKindQAMOMILE_FLOAT:FrontendAnnotationKindQAMOMILE_MATRIX:FrontendAnnotationKindQAMOMILE_OBSERVABLE:FrontendAnnotationKindQAMOMILE_QFIXED:FrontendAnnotationKindQAMOMILE_QUBIT:FrontendAnnotationKindQAMOMILE_TENSOR:FrontendAnnotationKindQAMOMILE_TUPLE:FrontendAnnotationKindQAMOMILE_UINT:FrontendAnnotationKindQAMOMILE_VECTOR:FrontendAnnotationKindQFIXED_TYPE:ValueTypeKindQINIT_OPERATION:OperationTypeQUBIT_TYPE:ValueTypeKindQUINT_TYPE:ValueTypeKindRELEASE_SLICE_VIEW_OPERATION:OperationTypeRESET_OPERATION:OperationTypeRETURN_OPERATION:OperationTypeRETURN_QUANTUM_ARRAY_ELEMENT_OPERATION:OperationTypeRUNTIME_CLASSICAL_OPERATION:OperationTypeSELECT_OPERATION:OperationTypeSLICE_ARRAY_OPERATION:OperationTypeSTORE_ARRAY_ELEMENT_OPERATION:OperationTypeSYMBOLIC_CONTROLLED_OPERATION:OperationTypeTUPLE_TYPE:ValueTypeKindTUPLE_VALUE:ValueKindUINT_TYPE:ValueTypeKindUNARY_MATH_OPERATION:OperationTypeVALUE:ValueKindVALUE_KIND_UNSPECIFIED:ValueKindVALUE_TYPE_KIND_UNSPECIFIED:ValueTypeKindVAR_KEYWORD:ParameterKindVAR_POSITIONAL:ParameterKindWHILE_OPERATION:OperationType
Classes¶
ArrayRuntimeMetadata [source]¶
class ArrayRuntimeMetadata(_message.Message)Constructor¶
def __init__(
self,
const_array: _Optional[_Union[Payload, _Mapping]] = ...,
element_uuids: _Optional[_Iterable[str]] = ...,
element_logical_ids: _Optional[_Iterable[str]] = ...,
element_parent_uuids: _Optional[_Iterable[_Union[OptionalString, _Mapping]]] = ...,
element_parent_indices: _Optional[_Iterable[_Union[OptionalInteger, _Mapping]]] = ...,
) -> NoneAttributes¶
CONST_ARRAY_FIELD_NUMBER: intELEMENT_LOGICAL_IDS_FIELD_NUMBER: intELEMENT_PARENT_INDICES_FIELD_NUMBER: intELEMENT_PARENT_UUIDS_FIELD_NUMBER: intELEMENT_UUIDS_FIELD_NUMBER: intconst_array: Payloadelement_logical_ids: _containers.RepeatedScalarFieldContainer[str]element_parent_indices: _containers.RepeatedCompositeFieldContainer[OptionalInteger]element_parent_uuids: _containers.RepeatedCompositeFieldContainer[OptionalString]element_uuids: _containers.RepeatedScalarFieldContainer[str]
BigInteger [source]¶
class BigInteger(_message.Message)Constructor¶
def __init__(self, negative: bool = ..., magnitude: _Optional[bytes] = ...) -> NoneAttributes¶
MAGNITUDE_FIELD_NUMBER: intNEGATIVE_FIELD_NUMBER: intmagnitude: bytesnegative: bool
Block [source]¶
class Block(_message.Message)Constructor¶
def __init__(
self,
kind: _Optional[str] = ...,
name: _Optional[str] = ...,
label_args: _Optional[_Iterable[_Union[Payload, _Mapping]]] = ...,
input_value_refs: _Optional[_Iterable[str]] = ...,
output_value_refs: _Optional[_Iterable[str]] = ...,
output_names: _Optional[_Iterable[str]] = ...,
parameters: _Optional[_Iterable[_Union[NamedReference, _Mapping]]] = ...,
static_bindings: _Optional[_Iterable[_Union[StaticBindingSlot, _Mapping]]] = ...,
operations: _Optional[_Iterable[_Union[Operation, _Mapping]]] = ...,
) -> NoneAttributes¶
INPUT_VALUE_REFS_FIELD_NUMBER: intKIND_FIELD_NUMBER: intLABEL_ARGS_FIELD_NUMBER: intNAME_FIELD_NUMBER: intOPERATIONS_FIELD_NUMBER: intOUTPUT_NAMES_FIELD_NUMBER: intOUTPUT_VALUE_REFS_FIELD_NUMBER: intPARAMETERS_FIELD_NUMBER: intSTATIC_BINDINGS_FIELD_NUMBER: intinput_value_refs: _containers.RepeatedScalarFieldContainer[str]kind: strlabel_args: _containers.RepeatedCompositeFieldContainer[Payload]name: stroperations: _containers.RepeatedCompositeFieldContainer[Operation]output_names: _containers.RepeatedScalarFieldContainer[str]output_value_refs: _containers.RepeatedScalarFieldContainer[str]parameters: _containers.RepeatedCompositeFieldContainer[NamedReference]static_bindings: _containers.RepeatedCompositeFieldContainer[StaticBindingSlot]
BranchRebind [source]¶
class BranchRebind(_message.Message)Constructor¶
def __init__(
self,
var_name: _Optional[str] = ...,
before_ref: _Optional[str] = ...,
rebound_in_true: bool = ...,
rebound_in_false: bool = ...,
) -> NoneAttributes¶
BEFORE_REF_FIELD_NUMBER: intREBOUND_IN_FALSE_FIELD_NUMBER: intREBOUND_IN_TRUE_FIELD_NUMBER: intVAR_NAME_FIELD_NUMBER: intbefore_ref: strrebound_in_false: boolrebound_in_true: boolvar_name: str
CallableBodyRef [source]¶
class CallableBodyRef(_message.Message)Constructor¶
def __init__(
self,
ref: _Optional[_Union[CallableRef, _Mapping]] = ...,
kind: _Optional[str] = ...,
attrs: _Optional[_Union[Payload, _Mapping]] = ...,
) -> NoneAttributes¶
ATTRS_FIELD_NUMBER: intKIND_FIELD_NUMBER: intREF_FIELD_NUMBER: intattrs: Payloadkind: strref: CallableRef
CallableDefinition [source]¶
class CallableDefinition(_message.Message)Constructor¶
def __init__(
self,
ref: _Optional[_Union[CallableRef, _Mapping]] = ...,
signature: _Optional[_Union[Signature, _Mapping]] = ...,
body: _Optional[_Union[Block, _Mapping]] = ...,
body_ref: _Optional[_Union[CallableBodyRef, _Mapping]] = ...,
implementations: _Optional[_Iterable[_Union[CallableImplementation, _Mapping]]] = ...,
default_policy: _Optional[str] = ...,
attrs: _Optional[_Union[Payload, _Mapping]] = ...,
) -> NoneAttributes¶
ATTRS_FIELD_NUMBER: intBODY_FIELD_NUMBER: intBODY_REF_FIELD_NUMBER: intDEFAULT_POLICY_FIELD_NUMBER: intIMPLEMENTATIONS_FIELD_NUMBER: intREF_FIELD_NUMBER: intSIGNATURE_FIELD_NUMBER: intattrs: Payloadbody: Blockbody_ref: CallableBodyRefdefault_policy: strimplementations: _containers.RepeatedCompositeFieldContainer[CallableImplementation]ref: CallableRefsignature: Signature
CallableEntry [source]¶
class CallableEntry(_message.Message)Constructor¶
def __init__(
self,
id: _Optional[str] = ...,
definition: _Optional[_Union[CallableDefinition, _Mapping]] = ...,
) -> NoneAttributes¶
DEFINITION_FIELD_NUMBER: intID_FIELD_NUMBER: intdefinition: CallableDefinitionid: str
CallableImplementation [source]¶
class CallableImplementation(_message.Message)Constructor¶
def __init__(
self,
transform: _Optional[str] = ...,
backend: _Optional[str] = ...,
strategy: _Optional[str] = ...,
body: _Optional[_Union[Block, _Mapping]] = ...,
body_ref: _Optional[_Union[CallableBodyRef, _Mapping]] = ...,
attrs: _Optional[_Union[Payload, _Mapping]] = ...,
) -> NoneAttributes¶
ATTRS_FIELD_NUMBER: intBACKEND_FIELD_NUMBER: intBODY_FIELD_NUMBER: intBODY_REF_FIELD_NUMBER: intSTRATEGY_FIELD_NUMBER: intTRANSFORM_FIELD_NUMBER: intattrs: Payloadbackend: strbody: Blockbody_ref: CallableBodyRefstrategy: strtransform: str
CallableRef [source]¶
class CallableRef(_message.Message)Constructor¶
def __init__(
self,
namespace: _Optional[str] = ...,
name: _Optional[str] = ...,
version: _Optional[str] = ...,
) -> NoneAttributes¶
NAMESPACE_FIELD_NUMBER: intNAME_FIELD_NUMBER: intVERSION_FIELD_NUMBER: intname: strnamespace: strversion: str
CastMetadata [source]¶
class CastMetadata(_message.Message)Constructor¶
def __init__(
self,
source_uuid: _Optional[str] = ...,
qubit_uuids: _Optional[_Iterable[str]] = ...,
source_logical_id: _Optional[str] = ...,
qubit_logical_ids: _Optional[_Iterable[str]] = ...,
) -> NoneAttributes¶
QUBIT_LOGICAL_IDS_FIELD_NUMBER: intQUBIT_UUIDS_FIELD_NUMBER: intSOURCE_LOGICAL_ID_FIELD_NUMBER: intSOURCE_UUID_FIELD_NUMBER: intqubit_logical_ids: _containers.RepeatedScalarFieldContainer[str]qubit_uuids: _containers.RepeatedScalarFieldContainer[str]source_logical_id: strsource_uuid: str
Complex64 [source]¶
class Complex64(_message.Message)Constructor¶
def __init__(self, real_bits: _Optional[int] = ..., imag_bits: _Optional[int] = ...) -> NoneAttributes¶
IMAG_BITS_FIELD_NUMBER: intREAL_BITS_FIELD_NUMBER: intimag_bits: intreal_bits: int
DictRuntimeMetadata [source]¶
class DictRuntimeMetadata(_message.Message)Constructor¶
def __init__(
self,
bound_data: _Optional[_Iterable[_Union[PayloadEntry, _Mapping]]] = ...,
) -> NoneAttributes¶
BOUND_DATA_FIELD_NUMBER: intbound_data: _containers.RepeatedCompositeFieldContainer[PayloadEntry]
Float64 [source]¶
class Float64(_message.Message)Constructor¶
def __init__(self, bits: _Optional[int] = ...) -> NoneAttributes¶
BITS_FIELD_NUMBER: intbits: int
FrontendAnnotation [source]¶
class FrontendAnnotation(_message.Message)Constructor¶
def __init__(
self,
kind: _Optional[_Union[FrontendAnnotationKind, str]] = ...,
arguments: _Optional[_Iterable[_Union[FrontendAnnotation, _Mapping]]] = ...,
) -> NoneAttributes¶
ARGUMENTS_FIELD_NUMBER: intKIND_FIELD_NUMBER: intarguments: _containers.RepeatedCompositeFieldContainer[FrontendAnnotation]kind: FrontendAnnotationKind
FrontendAnnotationKind [source]¶
class FrontendAnnotationKind(int)Attributes¶
FRONTEND_ANNOTATION_KIND_UNSPECIFIED: FrontendAnnotationKindPYTHON_BOOL: FrontendAnnotationKindPYTHON_FLOAT: FrontendAnnotationKindPYTHON_INT: FrontendAnnotationKindPYTHON_TUPLE: FrontendAnnotationKindQAMOMILE_BIT: FrontendAnnotationKindQAMOMILE_DICT: FrontendAnnotationKindQAMOMILE_FLOAT: FrontendAnnotationKindQAMOMILE_MATRIX: FrontendAnnotationKindQAMOMILE_OBSERVABLE: FrontendAnnotationKindQAMOMILE_QFIXED: FrontendAnnotationKindQAMOMILE_QUBIT: FrontendAnnotationKindQAMOMILE_TENSOR: FrontendAnnotationKindQAMOMILE_TUPLE: FrontendAnnotationKindQAMOMILE_UINT: FrontendAnnotationKindQAMOMILE_VECTOR: FrontendAnnotationKind
Hamiltonian [source]¶
class Hamiltonian(_message.Message)Constructor¶
def __init__(
self,
terms: _Optional[_Iterable[_Union[HamiltonianTerm, _Mapping]]] = ...,
constant: _Optional[_Union[Number, _Mapping]] = ...,
num_qubits: _Optional[int] = ...,
) -> NoneAttributes¶
CONSTANT_FIELD_NUMBER: intNUM_QUBITS_FIELD_NUMBER: intTERMS_FIELD_NUMBER: intconstant: Numbernum_qubits: intterms: _containers.RepeatedCompositeFieldContainer[HamiltonianTerm]
HamiltonianTerm [source]¶
class HamiltonianTerm(_message.Message)Constructor¶
def __init__(
self,
operators: _Optional[_Iterable[_Union[PauliOperator, _Mapping]]] = ...,
coefficient: _Optional[_Union[Number, _Mapping]] = ...,
) -> NoneAttributes¶
COEFFICIENT_FIELD_NUMBER: intOPERATORS_FIELD_NUMBER: intcoefficient: Numberoperators: _containers.RepeatedCompositeFieldContainer[PauliOperator]
IntegerOrReference [source]¶
class IntegerOrReference(_message.Message)Constructor¶
def __init__(
self,
integer: _Optional[_Union[BigInteger, _Mapping]] = ...,
value_ref: _Optional[str] = ...,
) -> NoneAttributes¶
INTEGER_FIELD_NUMBER: intVALUE_REF_FIELD_NUMBER: intinteger: BigIntegervalue_ref: str
KernelParameter [source]¶
class KernelParameter(_message.Message)Constructor¶
def __init__(
self,
name: _Optional[str] = ...,
type: _Optional[_Union[KernelType, _Mapping]] = ...,
kind: _Optional[_Union[ParameterKind, str]] = ...,
has_default: bool = ...,
default: _Optional[_Union[Payload, _Mapping]] = ...,
differentiable: bool = ...,
static_binding_type: _Optional[str] = ...,
) -> NoneAttributes¶
DEFAULT_FIELD_NUMBER: intDIFFERENTIABLE_FIELD_NUMBER: intHAS_DEFAULT_FIELD_NUMBER: intKIND_FIELD_NUMBER: intNAME_FIELD_NUMBER: intSTATIC_BINDING_TYPE_FIELD_NUMBER: intTYPE_FIELD_NUMBER: intdefault: Payloaddifferentiable: boolhas_default: boolkind: ParameterKindname: strstatic_binding_type: strtype: KernelType
KernelType [source]¶
class KernelType(_message.Message)Constructor¶
def __init__(
self,
value_type: _Optional[_Union[ValueType, _Mapping]] = ...,
ndim: _Optional[int] = ...,
annotation: _Optional[_Union[FrontendAnnotation, _Mapping]] = ...,
) -> NoneAttributes¶
ANNOTATION_FIELD_NUMBER: intNDIM_FIELD_NUMBER: intVALUE_TYPE_FIELD_NUMBER: intannotation: FrontendAnnotationndim: intvalue_type: ValueType
LoopCarriedRebind [source]¶
class LoopCarriedRebind(_message.Message)Constructor¶
def __init__(
self,
var_name: _Optional[str] = ...,
before_ref: _Optional[str] = ...,
after_ref: _Optional[str] = ...,
before_synthesized: bool = ...,
) -> NoneAttributes¶
AFTER_REF_FIELD_NUMBER: intBEFORE_REF_FIELD_NUMBER: intBEFORE_SYNTHESIZED_FIELD_NUMBER: intVAR_NAME_FIELD_NUMBER: intafter_ref: strbefore_ref: strbefore_synthesized: boolvar_name: str
NamedReference [source]¶
class NamedReference(_message.Message)Constructor¶
def __init__(self, name: _Optional[str] = ..., value_ref: _Optional[str] = ...) -> NoneAttributes¶
NAME_FIELD_NUMBER: intVALUE_REF_FIELD_NUMBER: intname: strvalue_ref: str
NullValue [source]¶
class NullValue(_message.Message)Constructor¶
def __init__(self) -> NoneNumber [source]¶
class Number(_message.Message)Constructor¶
def __init__(
self,
integer: _Optional[_Union[BigInteger, _Mapping]] = ...,
floating: _Optional[_Union[Float64, _Mapping]] = ...,
complex: _Optional[_Union[Complex64, _Mapping]] = ...,
) -> NoneAttributes¶
COMPLEX_FIELD_NUMBER: intFLOATING_FIELD_NUMBER: intINTEGER_FIELD_NUMBER: intcomplex: Complex64floating: Float64integer: BigInteger
NumpyValue [source]¶
class NumpyValue(_message.Message)Constructor¶
def __init__(
self,
dtype: _Optional[str] = ...,
shape: _Optional[_Iterable[int]] = ...,
data: _Optional[bytes] = ...,
) -> NoneAttributes¶
DATA_FIELD_NUMBER: intDTYPE_FIELD_NUMBER: intSHAPE_FIELD_NUMBER: intdata: bytesdtype: strshape: _containers.RepeatedScalarFieldContainer[int]
Operation [source]¶
class Operation(_message.Message)Constructor¶
def __init__(
self,
operation_type: _Optional[_Union[OperationType, str]] = ...,
operand_refs: _Optional[_Iterable[str]] = ...,
result_refs: _Optional[_Iterable[str]] = ...,
gate_type: _Optional[str] = ...,
axis: _Optional[str] = ...,
num_bits: _Optional[int] = ...,
int_bits: _Optional[int] = ...,
key_arity: _Optional[int] = ...,
source_type: _Optional[_Union[ValueType, _Mapping]] = ...,
target_type: _Optional[_Union[ValueType, _Mapping]] = ...,
qubit_mapping: _Optional[_Iterable[str]] = ...,
expression_kind: _Optional[str] = ...,
loop_var: _Optional[str] = ...,
loop_var_value_ref: _Optional[str] = ...,
key_vars: _Optional[_Iterable[str]] = ...,
value_var: _Optional[str] = ...,
key_is_vector: bool = ...,
key_var_value_refs: _Optional[_Iterable[str]] = ...,
has_key_var_value_refs: bool = ...,
value_var_value_ref: _Optional[str] = ...,
max_iterations: _Optional[int] = ...,
loop_carried_rebinds: _Optional[_Iterable[_Union[LoopCarriedRebind, _Mapping]]] = ...,
region_args: _Optional[_Iterable[_Union[RegionArg, _Mapping]]] = ...,
body: _Optional[_Iterable[_Union[Operation, _Mapping]]] = ...,
true_body: _Optional[_Iterable[_Union[Operation, _Mapping]]] = ...,
false_body: _Optional[_Iterable[_Union[Operation, _Mapping]]] = ...,
true_yield_refs: _Optional[_Iterable[str]] = ...,
false_yield_refs: _Optional[_Iterable[str]] = ...,
branch_rebinds: _Optional[_Iterable[_Union[BranchRebind, _Mapping]]] = ...,
capture_refs: _Optional[_Iterable[str]] = ...,
true_capture_refs: _Optional[_Iterable[str]] = ...,
false_capture_refs: _Optional[_Iterable[str]] = ...,
num_controls: _Optional[int] = ...,
num_controls_ref: _Optional[str] = ...,
power: _Optional[_Union[IntegerOrReference, _Mapping]] = ...,
control_index_refs: _Optional[_Iterable[str]] = ...,
has_control_index_refs: bool = ...,
num_control_args: _Optional[int] = ...,
unitary_block: _Optional[_Union[Block, _Mapping]] = ...,
callable_ref: _Optional[_Union[CallableRef, _Mapping]] = ...,
callable_attrs: _Optional[_Union[Payload, _Mapping]] = ...,
control_value: _Optional[_Union[BigInteger, _Mapping]] = ...,
target: _Optional[_Union[CallableRef, _Mapping]] = ...,
transform: _Optional[str] = ...,
attrs: _Optional[_Union[Payload, _Mapping]] = ...,
definition_ref: _Optional[str] = ...,
num_control_qubits: _Optional[int] = ...,
num_target_qubits: _Optional[int] = ...,
custom_name: _Optional[str] = ...,
source_block: _Optional[_Union[Block, _Mapping]] = ...,
implementation_block: _Optional[_Union[Block, _Mapping]] = ...,
num_index_qubits: _Optional[int] = ...,
case_blocks: _Optional[_Iterable[_Union[Block, _Mapping]]] = ...,
num_index_qubits_ref: _Optional[str] = ...,
num_index_args: _Optional[int] = ...,
) -> NoneAttributes¶
ATTRS_FIELD_NUMBER: intAXIS_FIELD_NUMBER: intBODY_FIELD_NUMBER: intBRANCH_REBINDS_FIELD_NUMBER: intCALLABLE_ATTRS_FIELD_NUMBER: intCALLABLE_REF_FIELD_NUMBER: intCAPTURE_REFS_FIELD_NUMBER: intCASE_BLOCKS_FIELD_NUMBER: intCONTROL_INDEX_REFS_FIELD_NUMBER: intCONTROL_VALUE_FIELD_NUMBER: intCUSTOM_NAME_FIELD_NUMBER: intDEFINITION_REF_FIELD_NUMBER: intEXPRESSION_KIND_FIELD_NUMBER: intFALSE_BODY_FIELD_NUMBER: intFALSE_CAPTURE_REFS_FIELD_NUMBER: intFALSE_YIELD_REFS_FIELD_NUMBER: intGATE_TYPE_FIELD_NUMBER: intHAS_CONTROL_INDEX_REFS_FIELD_NUMBER: intHAS_KEY_VAR_VALUE_REFS_FIELD_NUMBER: intIMPLEMENTATION_BLOCK_FIELD_NUMBER: intINT_BITS_FIELD_NUMBER: intKEY_ARITY_FIELD_NUMBER: intKEY_IS_VECTOR_FIELD_NUMBER: intKEY_VARS_FIELD_NUMBER: intKEY_VAR_VALUE_REFS_FIELD_NUMBER: intLOOP_CARRIED_REBINDS_FIELD_NUMBER: intLOOP_VAR_FIELD_NUMBER: intLOOP_VAR_VALUE_REF_FIELD_NUMBER: intMAX_ITERATIONS_FIELD_NUMBER: intNUM_BITS_FIELD_NUMBER: intNUM_CONTROLS_FIELD_NUMBER: intNUM_CONTROLS_REF_FIELD_NUMBER: intNUM_CONTROL_ARGS_FIELD_NUMBER: intNUM_CONTROL_QUBITS_FIELD_NUMBER: intNUM_INDEX_ARGS_FIELD_NUMBER: intNUM_INDEX_QUBITS_FIELD_NUMBER: intNUM_INDEX_QUBITS_REF_FIELD_NUMBER: intNUM_TARGET_QUBITS_FIELD_NUMBER: intOPERAND_REFS_FIELD_NUMBER: intOPERATION_TYPE_FIELD_NUMBER: intPOWER_FIELD_NUMBER: intQUBIT_MAPPING_FIELD_NUMBER: intREGION_ARGS_FIELD_NUMBER: intRESULT_REFS_FIELD_NUMBER: intSOURCE_BLOCK_FIELD_NUMBER: intSOURCE_TYPE_FIELD_NUMBER: intTARGET_FIELD_NUMBER: intTARGET_TYPE_FIELD_NUMBER: intTRANSFORM_FIELD_NUMBER: intTRUE_BODY_FIELD_NUMBER: intTRUE_CAPTURE_REFS_FIELD_NUMBER: intTRUE_YIELD_REFS_FIELD_NUMBER: intUNITARY_BLOCK_FIELD_NUMBER: intVALUE_VAR_FIELD_NUMBER: intVALUE_VAR_VALUE_REF_FIELD_NUMBER: intattrs: Payloadaxis: strbody: _containers.RepeatedCompositeFieldContainer[Operation]branch_rebinds: _containers.RepeatedCompositeFieldContainer[BranchRebind]callable_attrs: Payloadcallable_ref: CallableRefcapture_refs: _containers.RepeatedScalarFieldContainer[str]case_blocks: _containers.RepeatedCompositeFieldContainer[Block]control_index_refs: _containers.RepeatedScalarFieldContainer[str]control_value: BigIntegercustom_name: strdefinition_ref: strexpression_kind: strfalse_body: _containers.RepeatedCompositeFieldContainer[Operation]false_capture_refs: _containers.RepeatedScalarFieldContainer[str]false_yield_refs: _containers.RepeatedScalarFieldContainer[str]gate_type: strhas_control_index_refs: boolhas_key_var_value_refs: boolimplementation_block: Blockint_bits: intkey_arity: intkey_is_vector: boolkey_var_value_refs: _containers.RepeatedScalarFieldContainer[str]key_vars: _containers.RepeatedScalarFieldContainer[str]loop_carried_rebinds: _containers.RepeatedCompositeFieldContainer[LoopCarriedRebind]loop_var: strloop_var_value_ref: strmax_iterations: intnum_bits: intnum_control_args: intnum_control_qubits: intnum_controls: intnum_controls_ref: strnum_index_args: intnum_index_qubits: intnum_index_qubits_ref: strnum_target_qubits: intoperand_refs: _containers.RepeatedScalarFieldContainer[str]operation_type: OperationTypepower: IntegerOrReferencequbit_mapping: _containers.RepeatedScalarFieldContainer[str]region_args: _containers.RepeatedCompositeFieldContainer[RegionArg]result_refs: _containers.RepeatedScalarFieldContainer[str]source_block: Blocksource_type: ValueTypetarget: CallableReftarget_type: ValueTypetransform: strtrue_body: _containers.RepeatedCompositeFieldContainer[Operation]true_capture_refs: _containers.RepeatedScalarFieldContainer[str]true_yield_refs: _containers.RepeatedScalarFieldContainer[str]unitary_block: Blockvalue_var: strvalue_var_value_ref: str
OperationType [source]¶
class OperationType(int)Attributes¶
BIN_OPERATION: OperationTypeCAST_OPERATION: OperationTypeCINIT_OPERATION: OperationTypeCOMP_OPERATION: OperationTypeCONCRETE_CONTROLLED_OPERATION: OperationTypeCOND_OPERATION: OperationTypeDECODE_QFIXED_OPERATION: OperationTypeDICT_GET_ITEM_OPERATION: OperationTypeEXPVAL_OPERATION: OperationTypeFOR_ITEMS_OPERATION: OperationTypeFOR_OPERATION: OperationTypeGATE_OPERATION: OperationTypeGLOBAL_PHASE_OPERATION: OperationTypeIF_OPERATION: OperationTypeINVERSE_BLOCK_OPERATION: OperationTypeINVOKE_OPERATION: OperationTypeMEASURE_OPERATION: OperationTypeMEASURE_QFIXED_OPERATION: OperationTypeMEASURE_VECTOR_OPERATION: OperationTypeNOT_OPERATION: OperationTypeOPERATION_TYPE_UNSPECIFIED: OperationTypePAULI_EVOLVE_OPERATION: OperationTypePROJECT_OPERATION: OperationTypeQINIT_OPERATION: OperationTypeRELEASE_SLICE_VIEW_OPERATION: OperationTypeRESET_OPERATION: OperationTypeRETURN_OPERATION: OperationTypeRETURN_QUANTUM_ARRAY_ELEMENT_OPERATION: OperationTypeRUNTIME_CLASSICAL_OPERATION: OperationTypeSELECT_OPERATION: OperationTypeSLICE_ARRAY_OPERATION: OperationTypeSTORE_ARRAY_ELEMENT_OPERATION: OperationTypeSYMBOLIC_CONTROLLED_OPERATION: OperationTypeUNARY_MATH_OPERATION: OperationTypeWHILE_OPERATION: OperationType
OptionalInteger [source]¶
class OptionalInteger(_message.Message)Constructor¶
def __init__(self, value: _Optional[int] = ...) -> NoneAttributes¶
VALUE_FIELD_NUMBER: intvalue: int
OptionalString [source]¶
class OptionalString(_message.Message)Constructor¶
def __init__(self, value: _Optional[str] = ...) -> NoneAttributes¶
VALUE_FIELD_NUMBER: intvalue: str
ParamHint [source]¶
class ParamHint(_message.Message)Constructor¶
def __init__(
self,
present: bool = ...,
name: _Optional[str] = ...,
type: _Optional[_Union[ValueType, _Mapping]] = ...,
) -> NoneAttributes¶
NAME_FIELD_NUMBER: intPRESENT_FIELD_NUMBER: intTYPE_FIELD_NUMBER: intname: strpresent: booltype: ValueType
ParameterKind [source]¶
class ParameterKind(int)Attributes¶
KEYWORD_ONLY: ParameterKindPARAMETER_KIND_UNSPECIFIED: ParameterKindPOSITIONAL_ONLY: ParameterKindPOSITIONAL_OR_KEYWORD: ParameterKindVAR_KEYWORD: ParameterKindVAR_POSITIONAL: ParameterKind
PauliOperator [source]¶
class PauliOperator(_message.Message)Constructor¶
def __init__(self, pauli: _Optional[str] = ..., index: _Optional[int] = ...) -> NoneAttributes¶
INDEX_FIELD_NUMBER: intPAULI_FIELD_NUMBER: intindex: intpauli: str
Payload [source]¶
class Payload(_message.Message)Constructor¶
def __init__(
self,
null_value: _Optional[_Union[NullValue, _Mapping]] = ...,
bool_value: bool = ...,
integer_value: _Optional[_Union[BigInteger, _Mapping]] = ...,
float_value: _Optional[_Union[Float64, _Mapping]] = ...,
string_value: _Optional[str] = ...,
bytes_value: _Optional[bytes] = ...,
list_value: _Optional[_Union[PayloadList, _Mapping]] = ...,
tuple_value: _Optional[_Union[PayloadList, _Mapping]] = ...,
set_value: _Optional[_Union[PayloadList, _Mapping]] = ...,
frozenset_value: _Optional[_Union[PayloadList, _Mapping]] = ...,
map_value: _Optional[_Union[PayloadMap, _Mapping]] = ...,
complex_value: _Optional[_Union[Complex64, _Mapping]] = ...,
numpy_array: _Optional[_Union[NumpyValue, _Mapping]] = ...,
numpy_scalar: _Optional[_Union[NumpyValue, _Mapping]] = ...,
hamiltonian: _Optional[_Union[Hamiltonian, _Mapping]] = ...,
) -> NoneAttributes¶
BOOL_VALUE_FIELD_NUMBER: intBYTES_VALUE_FIELD_NUMBER: intCOMPLEX_VALUE_FIELD_NUMBER: intFLOAT_VALUE_FIELD_NUMBER: intFROZENSET_VALUE_FIELD_NUMBER: intHAMILTONIAN_FIELD_NUMBER: intINTEGER_VALUE_FIELD_NUMBER: intLIST_VALUE_FIELD_NUMBER: intMAP_VALUE_FIELD_NUMBER: intNULL_VALUE_FIELD_NUMBER: intNUMPY_ARRAY_FIELD_NUMBER: intNUMPY_SCALAR_FIELD_NUMBER: intSET_VALUE_FIELD_NUMBER: intSTRING_VALUE_FIELD_NUMBER: intTUPLE_VALUE_FIELD_NUMBER: intbool_value: boolbytes_value: bytescomplex_value: Complex64float_value: Float64frozenset_value: PayloadListhamiltonian: Hamiltonianinteger_value: BigIntegerlist_value: PayloadListmap_value: PayloadMapnull_value: NullValuenumpy_array: NumpyValuenumpy_scalar: NumpyValueset_value: PayloadListstring_value: strtuple_value: PayloadList
PayloadEntry [source]¶
class PayloadEntry(_message.Message)Constructor¶
def __init__(
self,
key: _Optional[_Union[Payload, _Mapping]] = ...,
value: _Optional[_Union[Payload, _Mapping]] = ...,
) -> NoneAttributes¶
KEY_FIELD_NUMBER: intVALUE_FIELD_NUMBER: intkey: Payloadvalue: Payload
PayloadList [source]¶
class PayloadList(_message.Message)Constructor¶
def __init__(self, items: _Optional[_Iterable[_Union[Payload, _Mapping]]] = ...) -> NoneAttributes¶
ITEMS_FIELD_NUMBER: intitems: _containers.RepeatedCompositeFieldContainer[Payload]
PayloadMap [source]¶
class PayloadMap(_message.Message)Constructor¶
def __init__(
self,
entries: _Optional[_Iterable[_Union[PayloadEntry, _Mapping]]] = ...,
) -> NoneAttributes¶
ENTRIES_FIELD_NUMBER: intentries: _containers.RepeatedCompositeFieldContainer[PayloadEntry]
QFixedMetadata [source]¶
class QFixedMetadata(_message.Message)Constructor¶
def __init__(
self,
qubit_uuids: _Optional[_Iterable[str]] = ...,
num_bits: _Optional[int] = ...,
int_bits: _Optional[int] = ...,
) -> NoneAttributes¶
INT_BITS_FIELD_NUMBER: intNUM_BITS_FIELD_NUMBER: intQUBIT_UUIDS_FIELD_NUMBER: intint_bits: intnum_bits: intqubit_uuids: _containers.RepeatedScalarFieldContainer[str]
QKernel [source]¶
class QKernel(_message.Message)Constructor¶
def __init__(
self,
qamomile_version: _Optional[str] = ...,
name: _Optional[str] = ...,
parameters: _Optional[_Iterable[_Union[KernelParameter, _Mapping]]] = ...,
results: _Optional[_Iterable[_Union[KernelType, _Mapping]]] = ...,
body: _Optional[_Union[Block, _Mapping]] = ...,
value_table: _Optional[_Iterable[_Union[ValueNode, _Mapping]]] = ...,
callable_table: _Optional[_Iterable[_Union[CallableEntry, _Mapping]]] = ...,
callable_definition: _Optional[_Union[CallableDefinition, _Mapping]] = ...,
return_annotation: _Optional[_Union[FrontendAnnotation, _Mapping]] = ...,
) -> NoneAttributes¶
BODY_FIELD_NUMBER: intCALLABLE_DEFINITION_FIELD_NUMBER: intCALLABLE_TABLE_FIELD_NUMBER: intNAME_FIELD_NUMBER: intPARAMETERS_FIELD_NUMBER: intQAMOMILE_VERSION_FIELD_NUMBER: intRESULTS_FIELD_NUMBER: intRETURN_ANNOTATION_FIELD_NUMBER: intVALUE_TABLE_FIELD_NUMBER: intbody: Blockcallable_definition: CallableDefinitioncallable_table: _containers.RepeatedCompositeFieldContainer[CallableEntry]name: strparameters: _containers.RepeatedCompositeFieldContainer[KernelParameter]qamomile_version: strresults: _containers.RepeatedCompositeFieldContainer[KernelType]return_annotation: FrontendAnnotationvalue_table: _containers.RepeatedCompositeFieldContainer[ValueNode]
ReferencePair [source]¶
class ReferencePair(_message.Message)Constructor¶
def __init__(self, key_ref: _Optional[str] = ..., value_ref: _Optional[str] = ...) -> NoneAttributes¶
KEY_REF_FIELD_NUMBER: intVALUE_REF_FIELD_NUMBER: intkey_ref: strvalue_ref: str
RegionArg [source]¶
class RegionArg(_message.Message)Constructor¶
def __init__(
self,
var_name: _Optional[str] = ...,
init_ref: _Optional[str] = ...,
block_arg_ref: _Optional[str] = ...,
yielded_ref: _Optional[str] = ...,
result_ref: _Optional[str] = ...,
) -> NoneAttributes¶
BLOCK_ARG_REF_FIELD_NUMBER: intINIT_REF_FIELD_NUMBER: intRESULT_REF_FIELD_NUMBER: intVAR_NAME_FIELD_NUMBER: intYIELDED_REF_FIELD_NUMBER: intblock_arg_ref: strinit_ref: strresult_ref: strvar_name: stryielded_ref: str
RegisterWidth [source]¶
class RegisterWidth(_message.Message)Constructor¶
def __init__(self, concrete: _Optional[int] = ..., value_ref: _Optional[str] = ...) -> NoneAttributes¶
CONCRETE_FIELD_NUMBER: intVALUE_REF_FIELD_NUMBER: intconcrete: intvalue_ref: str
ScalarMetadata [source]¶
class ScalarMetadata(_message.Message)Constructor¶
def __init__(
self,
const_value: _Optional[_Union[Payload, _Mapping]] = ...,
parameter_name: _Optional[str] = ...,
) -> NoneAttributes¶
CONST_VALUE_FIELD_NUMBER: intPARAMETER_NAME_FIELD_NUMBER: intconst_value: Payloadparameter_name: str
Signature [source]¶
class Signature(_message.Message)Constructor¶
def __init__(
self,
operands: _Optional[_Iterable[_Union[ParamHint, _Mapping]]] = ...,
results: _Optional[_Iterable[_Union[ParamHint, _Mapping]]] = ...,
) -> NoneAttributes¶
OPERANDS_FIELD_NUMBER: intRESULTS_FIELD_NUMBER: intoperands: _containers.RepeatedCompositeFieldContainer[ParamHint]results: _containers.RepeatedCompositeFieldContainer[ParamHint]
StaticBindingField [source]¶
class StaticBindingField(_message.Message)Constructor¶
def __init__(self, name: _Optional[str] = ..., value_ref: _Optional[str] = ...) -> NoneAttributes¶
NAME_FIELD_NUMBER: intVALUE_REF_FIELD_NUMBER: intname: strvalue_ref: str
StaticBindingSlot [source]¶
class StaticBindingSlot(_message.Message)Constructor¶
def __init__(
self,
name: _Optional[str] = ...,
type_key: _Optional[str] = ...,
fields: _Optional[_Iterable[_Union[StaticBindingField, _Mapping]]] = ...,
) -> NoneAttributes¶
FIELDS_FIELD_NUMBER: intNAME_FIELD_NUMBER: intTYPE_KEY_FIELD_NUMBER: intfields: _containers.RepeatedCompositeFieldContainer[StaticBindingField]name: strtype_key: str
ValueKind [source]¶
class ValueKind(int)Attributes¶
ARRAY_VALUE: ValueKindDICT_VALUE: ValueKindTUPLE_VALUE: ValueKindVALUE: ValueKindVALUE_KIND_UNSPECIFIED: ValueKind
ValueMetadata [source]¶
class ValueMetadata(_message.Message)Constructor¶
def __init__(
self,
scalar: _Optional[_Union[ScalarMetadata, _Mapping]] = ...,
cast: _Optional[_Union[CastMetadata, _Mapping]] = ...,
qfixed: _Optional[_Union[QFixedMetadata, _Mapping]] = ...,
array_runtime: _Optional[_Union[ArrayRuntimeMetadata, _Mapping]] = ...,
dict_runtime: _Optional[_Union[DictRuntimeMetadata, _Mapping]] = ...,
) -> NoneAttributes¶
ARRAY_RUNTIME_FIELD_NUMBER: intCAST_FIELD_NUMBER: intDICT_RUNTIME_FIELD_NUMBER: intQFIXED_FIELD_NUMBER: intSCALAR_FIELD_NUMBER: intarray_runtime: ArrayRuntimeMetadatacast: CastMetadatadict_runtime: DictRuntimeMetadataqfixed: QFixedMetadatascalar: ScalarMetadata
ValueNode [source]¶
class ValueNode(_message.Message)Constructor¶
def __init__(
self,
value_kind: _Optional[_Union[ValueKind, str]] = ...,
uuid: _Optional[str] = ...,
logical_id: _Optional[str] = ...,
name: _Optional[str] = ...,
version: _Optional[int] = ...,
value_type: _Optional[_Union[ValueType, _Mapping]] = ...,
metadata: _Optional[_Union[ValueMetadata, _Mapping]] = ...,
parent_array_ref: _Optional[str] = ...,
element_index_refs: _Optional[_Iterable[str]] = ...,
shape_refs: _Optional[_Iterable[str]] = ...,
slice_of_ref: _Optional[str] = ...,
slice_start_ref: _Optional[str] = ...,
slice_step_ref: _Optional[str] = ...,
element_refs: _Optional[_Iterable[str]] = ...,
entry_refs: _Optional[_Iterable[_Union[ReferencePair, _Mapping]]] = ...,
) -> NoneAttributes¶
ELEMENT_INDEX_REFS_FIELD_NUMBER: intELEMENT_REFS_FIELD_NUMBER: intENTRY_REFS_FIELD_NUMBER: intLOGICAL_ID_FIELD_NUMBER: intMETADATA_FIELD_NUMBER: intNAME_FIELD_NUMBER: intPARENT_ARRAY_REF_FIELD_NUMBER: intSHAPE_REFS_FIELD_NUMBER: intSLICE_OF_REF_FIELD_NUMBER: intSLICE_START_REF_FIELD_NUMBER: intSLICE_STEP_REF_FIELD_NUMBER: intUUID_FIELD_NUMBER: intVALUE_KIND_FIELD_NUMBER: intVALUE_TYPE_FIELD_NUMBER: intVERSION_FIELD_NUMBER: intelement_index_refs: _containers.RepeatedScalarFieldContainer[str]element_refs: _containers.RepeatedScalarFieldContainer[str]entry_refs: _containers.RepeatedCompositeFieldContainer[ReferencePair]logical_id: strmetadata: ValueMetadataname: strparent_array_ref: strshape_refs: _containers.RepeatedScalarFieldContainer[str]slice_of_ref: strslice_start_ref: strslice_step_ref: struuid: strvalue_kind: ValueKindvalue_type: ValueTypeversion: int
ValueType [source]¶
class ValueType(_message.Message)Constructor¶
def __init__(
self,
kind: _Optional[_Union[ValueTypeKind, str]] = ...,
element_types: _Optional[_Iterable[_Union[ValueType, _Mapping]]] = ...,
key_type: _Optional[_Union[ValueType, _Mapping]] = ...,
value_type: _Optional[_Union[ValueType, _Mapping]] = ...,
integer_bits: _Optional[_Union[RegisterWidth, _Mapping]] = ...,
fractional_bits: _Optional[_Union[RegisterWidth, _Mapping]] = ...,
width: _Optional[_Union[RegisterWidth, _Mapping]] = ...,
) -> NoneAttributes¶
ELEMENT_TYPES_FIELD_NUMBER: intFRACTIONAL_BITS_FIELD_NUMBER: intINTEGER_BITS_FIELD_NUMBER: intKEY_TYPE_FIELD_NUMBER: intKIND_FIELD_NUMBER: intVALUE_TYPE_FIELD_NUMBER: intWIDTH_FIELD_NUMBER: intelement_types: _containers.RepeatedCompositeFieldContainer[ValueType]fractional_bits: RegisterWidthinteger_bits: RegisterWidthkey_type: ValueTypekind: ValueTypeKindvalue_type: ValueTypewidth: RegisterWidth
ValueTypeKind [source]¶
class ValueTypeKind(int)Attributes¶
BIT_TYPE: ValueTypeKindBLOCK_TYPE: ValueTypeKindDICT_TYPE: ValueTypeKindFLOAT_TYPE: ValueTypeKindOBSERVABLE_TYPE: ValueTypeKindQFIXED_TYPE: ValueTypeKindQUBIT_TYPE: ValueTypeKindQUINT_TYPE: ValueTypeKindTUPLE_TYPE: ValueTypeKindUINT_TYPE: ValueTypeKindVALUE_TYPE_KIND_UNSPECIFIED: ValueTypeKind
qamomile.circuit.serialization.kernel¶
Static qkernel implementation reconstructed from serialized IR.
Overview¶
| Function | Description |
|---|---|
auto_detect_parameters | Detect unbound classical arguments that should be runtime parameters. |
build_param_slots | Build a ParamSlot tuple for the classical arguments of a kernel. |
build_specialized_block | Trace a specialized sub-block for a call site. |
create_bound_input | Create a frontend handle for a compile-time-bound value. |
get_array_element_type | Extract the element type from an array type annotation. |
get_static_binding_by_annotation | Return the adapter registered for a qkernel annotation. |
get_static_binding_by_type_key | Return the adapter registered under a stable serialization key. |
is_array_type | Check if type is a Vector, Matrix, or Tensor subclass. |
materialize_static_field | Extract and validate one registered scalar field. |
materialize_static_member | Extract one registered qkernel-like member. |
qkernel_callable_def | Build the inline-by-default callable definition for a qkernel block. |
validate_bindings_parameters_disjoint | Enforce the project rule that bindings and parameters are disjoint. |
validate_kwargs | Validate compile-time bindings for QKernel.build. |
validate_parameters | Validate the explicit runtime parameter list. |
validate_static_binding | Validate one concrete compile-time object binding. |
validate_static_binding_slot | Validate a serialized IR slot against its installed adapter. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
Block | Unified block representation for all pipeline stages. |
BlockKind | Classification of block structure for pipeline stages. |
CInitOperation | Initialize the classical values (const, arguments etc) |
CallPolicy | Describe the default lowering policy for a callable call. |
CallTransform | Describe the requested transform of a callable implementation. |
CallableDef | Describe a compiler-facing callable definition. |
CallableImplementation | Describe one implementation candidate for a callable. |
CallableRef | Identify a callable independently of its Python object. |
CompositeGateType | Classify standard boxed quantum callables. |
ControlledUOperation | Base class for controlled-U operations. |
DictValue | A dictionary value stored as stable ordered entries. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
InverseBlockOperation | Represent an inverse qkernel/block as a first-class IR operation. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
KernelEffect | Describe non-unitary behavior reachable from a kernel body. |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
SerializedQKernel | A qkernel whose Python-independent semantic IR was deserialized. |
StaticBindingMemberSpec | Describe one deferred qkernel-valued member of a static binding. |
StaticBindingSpec | Register the closed qkernel surface of one compile-time object type. |
TupleValue | A tuple of IR values for structured data. |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
ValueSubstitutor | Substitute IR values in operations using a UUID-keyed mapping. |
Constants¶
ValueLike:TypeAlias='Value | ArrayValue | TupleValue | DictValue'
Functions¶
auto_detect_parameters [source]¶
def auto_detect_parameters(
signature: inspect.Signature,
input_types: dict[str, type],
kwargs: dict[str, Any],
) -> list[str]Detect unbound classical arguments that should be runtime parameters.
Parameters:
| Name | Type | Description |
|---|---|---|
signature | inspect.Signature | Python signature of the qkernel. |
input_types | dict[str, type] | Resolved frontend annotations keyed by parameter name. |
kwargs | dict[str, Any] | Compile-time bindings supplied to QKernel.build. |
Returns:
list[str] — list[str]: Parameter names that should remain symbolic.
build_param_slots [source]¶
def build_param_slots(
signature: inspect.Signature,
input_types: dict[str, Any],
*,
parameters: list[str] | None = None,
kwargs: dict[str, Any] | None = None,
qubit_sizes: dict[str, int] | None = None,
bind_defaults: bool,
) -> tuple[ParamSlot, ...]Build a ParamSlot tuple for the classical arguments of a kernel.
Mirrors the argument-classification logic in
qkernel_build.create_traced_block so the resulting slot list reflects
the same decisions that drive symbolic-vs-bound input creation.
Classical scalar / array arguments are always included; a Dict
argument is included only when it is a runtime parameter (its slot
carries a DictType). Pure-quantum arguments, Tuple arguments,
and compile-time-bound Dict arguments are excluded and live in
Block.input_values instead.
Parameters:
| Name | Type | Description |
|---|---|---|
signature | inspect.Signature | The kernel function’s signature. |
input_types | dict[str, Any] | Resolved frontend type annotations keyed by argument name (typically QKernel.input_types or the equivalent computed in func_to_block). |
parameters | list[str] | None | Names explicitly requested as runtime parameters via parameters=[...]. None is treated as an empty list. |
kwargs | dict[str, Any] | None | Concrete values supplied via bindings / direct kwargs. None is treated as an empty dict. |
qubit_sizes | dict[str, int] | None | Optional mapping from Vector[Qubit] parameter names to their integer sizes; these are quantum inputs and are not included in the slot list. |
bind_defaults | bool | When True, Python signature defaults are treated as COMPILE_TIME_BOUND with bound_value=default. When False (e.g., the func_to_block path that does not bake in defaults), defaulted arguments stay RUNTIME_PARAMETER and the default appears only in ParamSlot.default. |
Returns:
tuple[ParamSlot, ...] — tuple[ParamSlot, ...]: One slot per classical argument, in the
order they appear in signature.parameters.
Raises:
TypeError— If a non-static classical annotation cannot be represented by an IR parameter type.
build_specialized_block [source]¶
def build_specialized_block(
kernel: Any,
*,
parameters: list[str],
bindings: dict[str, Any],
qubit_sizes: dict[str, int],
) -> BlockTrace a specialized sub-block for a call site.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | Any | QKernel-like object to trace. |
parameters | list[str] | Classical argument names that remain symbolic in the specialized block. |
bindings | dict[str, Any] | Concrete Python values for classical arguments and caller-owned proxies for unresolved static bindings. |
qubit_sizes | dict[str, int] | First-axis sizes for Vector[Qubit] arguments supplied by the caller. |
Returns:
Block — Specialized hierarchical block ready to be invoked from the
Block — caller’s trace.
create_bound_input [source]¶
def create_bound_input(param_type: Any, name: str, value: Any) -> HandleCreate a frontend handle for a compile-time-bound value.
Parameters:
| Name | Type | Description |
|---|---|---|
param_type | Any | Frontend type annotation. |
name | str | QKernel parameter name. |
value | Any | Concrete compile-time binding. |
Returns:
Handle — Frontend handle carrying constant or runtime metadata.
Raises:
TypeError— Ifparam_typecannot be bound fromvalue.
get_array_element_type [source]¶
def get_array_element_type(param_type: Any) -> type | NoneExtract the element type from an array type annotation.
Parameters:
| Name | Type | Description |
|---|---|---|
param_type | Any | Frontend annotation such as Vector[Qubit]. |
Returns:
type | None — type | None: Element type when present, otherwise None.
get_static_binding_by_annotation [source]¶
def get_static_binding_by_annotation(annotation: Any) -> StaticBindingSpec | NoneReturn the adapter registered for a qkernel annotation.
Parameters:
| Name | Type | Description |
|---|---|---|
annotation | Any | Resolved qkernel parameter annotation. |
Returns:
StaticBindingSpec | None — StaticBindingSpec | None: Registered adapter, or None for an
StaticBindingSpec | None — ordinary qkernel argument.
get_static_binding_by_type_key [source]¶
def get_static_binding_by_type_key(type_key: str) -> StaticBindingSpecReturn the adapter registered under a stable serialization key.
Parameters:
| Name | Type | Description |
|---|---|---|
type_key | str | Stable type key from serialized IR. |
Returns:
StaticBindingSpec — Matching registered adapter.
Raises:
KeyError— If the installed Qamomile distribution does not know the key.
is_array_type [source]¶
def is_array_type(t: Any) -> boolCheck if type is a Vector, Matrix, or Tensor subclass.
materialize_static_field [source]¶
def materialize_static_field(spec: StaticBindingSpec, binding: Any, field_name: str) -> int | floatExtract and validate one registered scalar field.
Parameters:
| Name | Type | Description |
|---|---|---|
spec | StaticBindingSpec | Registered object contract. |
binding | Any | Validated concrete object. |
field_name | str | Registered field name. |
Returns:
int | float — int | float: Scalar value suitable for IR constant metadata.
Raises:
KeyError— Iffield_nameis not registered.TypeError— If the extracted value does not match its handle type.ValueError— If aUIntfield is negative.
materialize_static_member [source]¶
def materialize_static_member(
spec: StaticBindingSpec,
binding: Any,
member_name: str,
) -> tuple[Any, StaticBindingMemberSpec]Extract one registered qkernel-like member.
Parameters:
| Name | Type | Description |
|---|---|---|
spec | StaticBindingSpec | Registered object contract. |
binding | Any | Validated concrete object. |
member_name | str | Registered member name. |
Returns:
Any — tuple[Any, StaticBindingMemberSpec]: Concrete member and its adapter
StaticBindingMemberSpec — contract.
Raises:
KeyError— Ifmember_nameis not registered.TypeError— If the getter does not return a qkernel-like object.
qkernel_callable_def [source]¶
def qkernel_callable_def(kernel: Any, block: Block) -> CallableDefBuild the inline-by-default callable definition for a qkernel block.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | Any | QKernel-like object carrying callable metadata. |
block | Block | Implementation body for the qkernel. |
Returns:
CallableDef — Compiler-facing definition for the qkernel.
validate_bindings_parameters_disjoint [source]¶
def validate_bindings_parameters_disjoint(bindings: dict[str, Any] | None, parameters: list[str] | None) -> NoneEnforce the project rule that bindings and parameters are disjoint.
A kernel argument name must be resolved exactly one way: compile-time bound
(in bindings, baked into the emitted circuit) or runtime symbolic (in
parameters, surviving as a backend parameter). Listing the same name in
both is ambiguous and historically caused silent miscompilation — the
binding won the resolution race and the runtime parameter was silently
dropped from the emitted circuit (see #354). This is the single shared
checker so the rule is enforced identically at every entry point
(QKernel.build / Transpiler.to_block / Transpiler.emit /
Transpiler.transpile), not only in the top-level transpile wrapper.
Parameters:
| Name | Type | Description |
|---|---|---|
bindings | dict[str, Any] | None | Compile-time bindings keyed by argument name, or None. None is treated as empty. |
parameters | list[str] | None | Argument names to keep as runtime parameters, or None. None is treated as empty. |
Returns:
None — None
Raises:
ValueError— If any name appears in bothbindingsandparameters.
Example:
>>> validate_bindings_parameters_disjoint({"theta": 0.5}, ["phi"])
>>> validate_bindings_parameters_disjoint({"theta": 0.5}, ["theta"])
Traceback (most recent call last):
...
ValueError: Parameter name(s) ['theta'] appear in both ...validate_kwargs [source]¶
def validate_kwargs(
signature: inspect.Signature,
input_types: dict[str, type],
parameters: list[str],
kwargs: dict[str, Any],
) -> NoneValidate compile-time bindings for QKernel.build.
Parameters:
| Name | Type | Description |
|---|---|---|
signature | inspect.Signature | Python signature of the qkernel. |
input_types | dict[str, type] | Resolved frontend annotations keyed by parameter name. |
parameters | list[str] | Runtime parameter names. |
kwargs | dict[str, Any] | Compile-time bindings. |
Raises:
ValueError— If an unknown argument is supplied, or if a required non-parameter classical argument is missing.TypeError— If a static binding has a default value or a supplied object does not match its registered annotation.
validate_parameters [source]¶
def validate_parameters(input_types: dict[str, type], parameters: list[str]) -> NoneValidate the explicit runtime parameter list.
Parameters:
| Name | Type | Description |
|---|---|---|
input_types | dict[str, type] | Resolved qkernel input annotations. |
parameters | list[str] | Requested runtime parameter names. |
Raises:
ValueError— If a requested name is not a qkernel parameter.TypeError— If a requested parameter type cannot stay symbolic.
validate_static_binding [source]¶
def validate_static_binding(annotation: Any, name: str, value: Any) -> AnyValidate one concrete compile-time object binding.
Parameters:
| Name | Type | Description |
|---|---|---|
annotation | Any | Registered qkernel parameter annotation. |
name | str | Parameter name used in diagnostics. |
value | Any | Candidate binding value. |
Returns:
Any — The validated binding value.
Raises:
TypeError— If the annotation is not registered or the value has the wrong concrete type.
validate_static_binding_slot [source]¶
def validate_static_binding_slot(spec: StaticBindingSpec, slot: StaticBindingSlot) -> NoneValidate a serialized IR slot against its installed adapter.
Parameters:
| Name | Type | Description |
|---|---|---|
spec | StaticBindingSpec | Installed adapter contract. |
slot | StaticBindingSlot | IR manifest entry to validate. |
Raises:
ValueError— If the type key, projected field names, or field types do not exactly match the registered adapter.
Classes¶
ArrayValue [source]¶
class ArrayValue(Value[T])An array of typed IR values.
When slice_of is set, this array is a strided view over another
array. Element accesses on a sliced ArrayValue resolve to
physical slots on the root parent via the affine map
parent_index = slice_start + slice_step * view_local_index,
applied recursively along slice_of chains. The emit-time
resolver walks this chain to produce the final qubit index; passes
that substitute or clone values must treat slice_of /
slice_start / slice_step as Value references that need to
track through the same mapping as parent_array.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
shape: tuple[Value, ...] = tuple(),
slice_of: 'ArrayValue | None' = None,
slice_start: 'Value | None' = None,
slice_step: 'Value | None' = None,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
CInitOperation [source]¶
class CInitOperation(Operation)Initialize the classical values (const, arguments etc)
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
CallPolicy [source]¶
class CallPolicy(enum.Enum)Describe the default lowering policy for a callable call.
Attributes¶
INLINENATIVE_FIRSTPRESERVE_BOX
CallTransform [source]¶
class CallTransform(enum.Enum)Describe the requested transform of a callable implementation.
Attributes¶
CONTROLLEDDIRECTINVERSE
CallableDef [source]¶
class CallableDefDescribe a compiler-facing callable definition.
Parameters:
| Name | Type | Description |
|---|---|---|
ref | CallableRef | Stable callable identity. |
signature | Signature | None | Optional callable signature. |
body | Block | None | Standard IR body, or None for opaque calls. |
body_ref | CallableBodyRef | None | Reference to a standard body that is intentionally deferred. Defaults to None. |
implementations | list[CallableImplementation] | Alternative native or strategy-specific implementations. |
opaque_cost | Any | None | Explicit cost contract for a bodyless callable. Body-backed callables must leave this as None. |
default_policy | CallPolicy | Default call lowering policy. |
attrs | dict[str, Any] | Serializer-friendly definition metadata. |
Constructor¶
def __init__(
self,
ref: CallableRef,
signature: Signature | None = None,
body: Block | None = None,
body_ref: CallableBodyRef | None = None,
implementations: list[CallableImplementation] = list(),
opaque_cost: Any | None = None,
default_policy: CallPolicy = CallPolicy.INLINE,
attrs: dict[str, Any] = dict(),
) -> NoneAttributes¶
attrs: dict[str, Any]body: Block | Nonebody_ref: CallableBodyRef | Nonedefault_policy: CallPolicyimplementations: list[CallableImplementation]opaque_cost: Any | Noneref: CallableRefsignature: Signature | None
Methods¶
effects_for¶
def effects_for(self, transform: CallTransform = CallTransform.DIRECT) -> 'KernelEffect'Return cached semantic effects for one call transform.
Parameters:
| Name | Type | Description |
|---|---|---|
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
Returns:
'KernelEffect' — Union of relevant implementation-body effects.
implementation_for¶
def implementation_for(
self,
*,
transform: CallTransform = CallTransform.DIRECT,
backend: str | None = None,
strategy: str | None = None,
) -> CallableImplementation | NoneReturn the best matching implementation candidate.
Parameters:
| Name | Type | Description |
|---|---|---|
transform | CallTransform | Requested call transform. |
backend | str | None | Requested backend name. |
strategy | str | None | Requested strategy name. |
Returns:
CallableImplementation | None — CallableImplementation | None: Matching implementation, if any.
measurement_result_indices_for¶
def measurement_result_indices_for(self, transform: CallTransform = CallTransform.DIRECT) -> frozenset[int]Return measured result positions for one call transform.
Parameters:
| Name | Type | Description |
|---|---|---|
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
Returns:
frozenset[int] — frozenset[int]: Result indices carrying measurement provenance.
CallableImplementation [source]¶
class CallableImplementationDescribe one implementation candidate for a callable.
Parameters:
| Name | Type | Description |
|---|---|---|
transform | CallTransform | Transform this implementation realizes. |
backend | str | None | Backend name for native implementations. |
strategy | str | None | Strategy name such as "standard". |
body | Block | None | IR implementation body. A transform-specific body realizes that transform completely; a controlled body therefore includes control operands in its signature. |
body_ref | CallableBodyRef | None | Reference to a body that should be materialized by a later resolver. Defaults to None. |
emitter | Any | Backend-native emitter object. |
attrs | dict[str, Any] | Serializer-friendly implementation metadata. |
Constructor¶
def __init__(
self,
transform: CallTransform = CallTransform.DIRECT,
backend: str | None = None,
strategy: str | None = None,
body: Block | None = None,
body_ref: CallableBodyRef | None = None,
emitter: Any = None,
attrs: dict[str, Any] = dict(),
) -> NoneAttributes¶
attrs: dict[str, Any]backend: str | Nonebody: Block | Nonebody_ref: CallableBodyRef | Noneemitter: Anystrategy: str | Nonetransform: CallTransform
CallableRef [source]¶
class CallableRefIdentify a callable independently of its Python object.
Parameters:
| Name | Type | Description |
|---|---|---|
namespace | str | Stable namespace such as "qamomile.stdlib" or "user". |
name | str | Stable callable name within the namespace. |
version | str | Schema or behavior version for the callable. |
Constructor¶
def __init__(self, namespace: str, name: str, version: str = '1') -> NoneAttributes¶
name: strnamespace: strversion: str
CompositeGateType [source]¶
class CompositeGateType(enum.Enum)Classify standard boxed quantum callables.
Attributes¶
CUSTOMIQFTQFTQPE
ControlledUOperation [source]¶
class ControlledUOperation(Operation)Base class for controlled-U operations.
Two concrete subclasses handle distinct operand layouts:
ConcreteControlledU: Fixednum_controls: int, individual qubit operands.SymbolicControlledU: Symbolicnum_controls: Value, vector-based control operands; optionalcontrol_indicesselects a subset of the control vector to act as controls (the rest pass through).
All isinstance(op, ControlledUOperation) checks match every subclass.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
power: int | Value = 1,
block: Block | None = None,
num_controls: int | Value = 1,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
) -> NoneAttributes¶
block: Block | Nonecallable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_operands: list[Value] Get the control qubit values.is_symbolic_num_controls: bool Whether num_controls is symbolic (Value) rather than concrete.num_controls: int | Valueoperation_kind: OperationKindparam_operands: list[Value] Get the controlled operation’s classical/object arguments.power: int | Valuesignature: Signaturetarget_operands: list[Value] Get the target qubit values (arguments to U).
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationDictValue [source]¶
class DictValue(_MetadataValueMixin, ValueBase)A dictionary value stored as stable ordered entries.
Constructor¶
def __init__(
self,
name: str,
entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> NoneAttributes¶
entries: tuple[tuple[TupleValue | Value, Value], ...]logical_id: strmetadata: ValueMetadataname: strtype: DictTypeuuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> DictValueHasNestedOps [source]¶
class HasNestedOpsMixin for operations that contain nested operation lists.
nested_regions() is the canonical traversal API because it exposes
operations together with block arguments, captures, and yields.
nested_op_lists() / rebuild_nested() remain compatibility helpers
for specialized consumers while they migrate to the region interface.
Methods¶
nested_op_lists¶
def nested_op_lists(self) -> list[list[Operation]]Return all nested operation lists in this control flow op.
nested_regions¶
def nested_regions(self) -> tuple[Region, ...]Return uniform views of every nested operation region.
Subclasses with explicit block arguments, captures, or yields override
this method. The fallback keeps legacy operation-owned blocks visible
while consumers migrate from nested_op_lists.
Returns:
tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.
rebuild_nested¶
def rebuild_nested(self, new_lists: list[list[Operation]]) -> OperationReturn a copy with nested operation lists replaced.
new_lists must have the same length/order as nested_op_lists().
rebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationReturn a copy with replacement region operation sequences.
Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
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
backend-native inverse/adjoint primitive, then fall back to
implementation_block when native inversion is unavailable.
Operands are ordered as scalar control qubits, target quantum operands,
then classical/object parameters. Results mirror the quantum operand
layout: control results first, then one target result per target operand.
Vector target operands therefore count as one operand/result while
contributing their scalar width to num_target_qubits.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_control_qubits: int = 0,
num_target_qubits: int = 0,
custom_name: str = '',
source_block: Block | None = None,
implementation_block: Block | None = None,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_qubits: list[‘Value’] Return control quantum operands.control_value: int | Nonecustom_name: strimplementation_block: Block | Nonename: str Return a human-readable inverse operation name.num_control_qubits: intnum_target_qubits: intoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return classical/object parameter operands.signature: Signature Return the operation signature.source_block: Block | Nonetarget_qubits: list[‘Value’] Return target quantum operands.
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[str, Any] | Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly. |
definition | CallableDef | None | Optional callable definition. |
Constructor¶
def __init__(
self,
operands: Sequence[ValueLike] | None = None,
results: Sequence[ValueLike] | None = None,
*,
target: CallableRef | None = None,
transform: CallTransform = CallTransform.DIRECT,
attrs: dict[str, Any] | None = None,
definition: CallableDef | None = None,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueis not a PythonintorNone.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of the selected callable implementation.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return invocation result positions derived from measurement.name: str Return the display name for this invocation.num_control_qubits: int Return the number of leading control-qubit operands.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
Methods¶
effective_body¶
def effective_body(
self,
*,
backend: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
backend | str | None | Backend name to match. Defaults to None. |
strategy | str | None | Strategy name to match. Defaults to the invocation’s strategy_name attribute. |
Returns:
Block | None — Block | None: Selected implementation body, or the callable’s
Block | None — default body when no transform-specific implementation exists.
Block | None — A compiler may synthesize inverse or controlled behavior from this
Block | None — fallback body.
implementation_for¶
def implementation_for(
self,
*,
backend: str | None = None,
strategy: str | None = None,
) -> CallableImplementation | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
backend | str | None | Backend name to match. Defaults to None, which only selects backend-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
Returns:
CallableImplementation | None — CallableImplementation | None: Matching implementation candidate,
CallableImplementation | None — or None when the callable definition has no match.
KernelEffect [source]¶
class KernelEffect(enum.Flag)Describe non-unitary behavior reachable from a kernel body.
KernelEffect.NONE is the empty effect set and denotes unitary behavior.
Flags compose with bitwise union so one kernel can expose measurement,
reset, and measurement-backed feed-forward together.
Attributes¶
FEED_FORWARDMEASUREMENTNONERESETis_unitary: bool Return whether this is the empty effect set.
Methods¶
labels¶
def labels(self) -> tuple[str, ...]Return stable effect names for diagnostics and serialization.
Returns:
tuple[str, ...] — tuple[str, ...]: Active flag names in declaration order.
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,
) -> NoneAttributes¶
case_blocks: list[Block]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]Return every value consumed by the SELECT operation.
Returns:
list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width
value when present.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed replacement values. |
Returns:
Operation — Rebuilt SELECT operation with matching values replaced.
SerializedQKernel [source]¶
class SerializedQKernelA qkernel whose Python-independent semantic IR was deserialized.
The object implements the compiler-facing qkernel protocol. Its body is a
static, unbound hierarchical block, so :meth:build specializes existing
IR values instead of executing the original Python function again.
Constructor¶
def __init__(
self,
name: str,
signature: inspect.Signature,
input_types: dict[str, Any],
output_types: list[Any],
_block: Block,
_callable_definition: CallableDef,
) -> NoneAttributes¶
block: Block Return the cached unbound hierarchical body.effects: KernelEffect Return cached semantic effects of the preserved body.input_types: dict[str, Any]name: stroutput_types: list[Any]signature: inspect.Signature
Methods¶
build¶
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> BlockSpecialize the preserved IR for bindings and runtime parameters.
This method mirrors the public qkernel argument contract while avoiding Python re-tracing. Compile-time values replace the corresponding formal IR values; runtime parameters remain symbolic.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | list[str] | None | Names retained as backend runtime parameters. None auto-detects unbound parameterizable arguments. |
**kwargs | Any | Compile-time bindings keyed by qkernel argument. |
Returns:
Block — Specialized traced-stage body accepted by the normal
Qamomile compiler pipeline.
Raises:
TypeError— If a requested parameter or binding type is unsupported.ValueError— If arguments are unknown, missing, or present in bothparametersandkwargs.
StaticBindingMemberSpec [source]¶
class StaticBindingMemberSpecDescribe one deferred qkernel-valued member of a static binding.
Parameters:
| Name | Type | Description |
|---|---|---|
input_types | Mapping[str, Any] | Ordered frontend input annotations. |
output_types | tuple[Any, ...] | Ordered frontend result annotations. |
return_annotation | Any | Complete Python return annotation. |
getter | Callable[[Any], Any] | Extractor returning the concrete qkernel-like member. |
qubit_width_fields | Mapping[str, str] | Input-name to scalar field-name mapping used to specialize quantum vector widths. |
Constructor¶
def __init__(
self,
input_types: Mapping[str, Any],
output_types: tuple[Any, ...],
return_annotation: Any,
getter: Callable[[Any], Any],
qubit_width_fields: Mapping[str, str] = dict(),
) -> NoneAttributes¶
getter: Callable[[Any], Any]input_types: Mapping[str, Any]output_types: tuple[Any, ...]qubit_width_fields: Mapping[str, str]return_annotation: Any
StaticBindingSpec [source]¶
class StaticBindingSpecRegister the closed qkernel surface of one compile-time object type.
Parameters:
| Name | Type | Description |
|---|---|---|
annotation | type[Any] | Public qkernel parameter annotation. |
type_key | str | Stable serialization key. |
fields | Mapping[str, StaticBindingFieldSpec] | Scalar projections available while tracing. |
members | Mapping[str, StaticBindingMemberSpec] | Deferred callable members available while tracing. |
Constructor¶
def __init__(
self,
annotation: type[Any],
type_key: str,
fields: Mapping[str, StaticBindingFieldSpec],
members: Mapping[str, StaticBindingMemberSpec],
) -> NoneAttributes¶
annotation: type[Any]fields: Mapping[str, StaticBindingFieldSpec]members: Mapping[str, StaticBindingMemberSpec]type_key: str
TupleValue [source]¶
class TupleValue(_MetadataValueMixin, ValueBase)A tuple of IR values for structured data.
Constructor¶
def __init__(
self,
name: str,
elements: tuple[ValueLike, ...] = tuple(),
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> NoneAttributes¶
elements: tuple[ValueLike, ...]logical_id: strmetadata: ValueMetadataname: strtype: ‘TupleType’uuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> TupleValueValue [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of backend resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
ValueSubstitutor [source]¶
class ValueSubstitutorSubstitute IR values in operations using a UUID-keyed mapping.
Parameters:
| Name | Type | Description |
|---|---|---|
value_map | Mapping[str, ValueBase] | Mapping from original value UUIDs to replacement values. |
transitive | bool | Whether substitutions should chase chains such as A -> B -> C to the terminal value. Defaults to False. |
Constructor¶
def __init__(self, value_map: Mapping[str, ValueBase], transitive: bool = False)Initialize the substitutor.
Parameters:
| Name | Type | Description |
|---|---|---|
value_map | Mapping[str, ValueBase] | Mapping from original value UUIDs to replacement values. |
transitive | bool | Whether substitutions should chase chains to their terminal value. Defaults to False. |
Methods¶
substitute_operation¶
def substitute_operation(self, op: Operation) -> OperationSubstitute values in an operation.
Parameters:
| Name | Type | Description |
|---|---|---|
op | Operation | Operation whose operands, results, and subclass-specific value fields should be substituted. |
Returns:
Operation — Operation with all mapped value references replaced.
substitute_value¶
def substitute_value(self, value: ValueBase) -> ValueBaseSubstitute a single value.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ValueBase | Value to replace or rebuild. |
Returns:
ValueBase — Replacement value, rebuilt value with substituted
ValueBase — metadata, or the original value when nothing maps.
qamomile.circuit.serialization.proto¶
Generated protobuf schema for one target-neutral static qkernel.
qamomile.circuit.serialization.protobuf¶
Serialize and deserialize one static qkernel with protobuf.
Overview¶
| Function | Description |
|---|---|
deserialize | Deserialize protobuf bytes into a static qkernel-like object. |
graph_dict_from_qkernel | Convert a qkernel protobuf into the internal semantic graph record. |
qkernel_from_graph_dict | Convert the internal static-qkernel graph record into protobuf. |
serialize | Serialize one unbound qkernel to canonical protobuf bytes. |
| Class | Description |
|---|---|
QKernelLike | Describe the frontend surface required by compiler entrypoints. |
SerializedQKernel | A qkernel whose Python-independent semantic IR was deserialized. |
Functions¶
deserialize [source]¶
def deserialize(payload: bytes) -> SerializedQKernelDeserialize protobuf bytes into a static qkernel-like object.
Parameters:
| Name | Type | Description |
|---|---|---|
payload | bytes | Bytes produced by :func:serialize. |
Returns:
SerializedQKernel — Reconstructed qkernel accepted by transpilers.
Raises:
TypeError— Ifpayloadis not bytes-like.ValueError— If parsing, version validation, or reconstruction fails.
graph_dict_from_qkernel [source]¶
def graph_dict_from_qkernel(message: pb.QKernel) -> dict[str, Any]Convert a qkernel protobuf into the internal semantic graph record.
Parameters:
| Name | Type | Description |
|---|---|---|
message | pb.QKernel | Parsed qkernel graph. |
Returns:
dict[str, Any] — dict[str, Any]: Graph record accepted by the semantic decoders.
Raises:
ValueError— If the version, interface, or a typed protobuf field is missing or inconsistent.
qkernel_from_graph_dict [source]¶
def qkernel_from_graph_dict(envelope: dict[str, Any]) -> pb.QKernelConvert the internal static-qkernel graph record into protobuf.
This bridge keeps graph construction separate from the canonical wire schema. The resulting bytes contain only protobuf fields, never JSON or a pickled Python dictionary.
Parameters:
| Name | Type | Description |
|---|---|---|
envelope | dict[str, Any] | Validated graph record from the qkernel encoder. |
Returns:
pb.QKernel — pb.QKernel: Canonical qkernel protobuf graph.
Raises:
ValueError— If the graph envelope or qkernel interface is malformed.TypeError— If a nested payload is outside the closed protobuf union.
serialize [source]¶
def serialize(kernel: QKernelLike) -> bytesSerialize one unbound qkernel to canonical protobuf bytes.
Independently traced equivalent qkernels produce identical bytes because process-local value identities are normalized before protobuf encoding.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | Static qkernel-like object to serialize. |
Returns:
bytes — Deterministic protobuf encoding.
Raises:
TypeError— If the qkernel contains an unsupported type or payload.ValueError— If the qkernel is bound, lowered, or malformed.
Classes¶
QKernelLike [source]¶
class QKernelLike(Protocol)Describe the frontend surface required by compiler entrypoints.
This protocol is intentionally structural. It lets decorator-created
composites reuse the qkernel inspection and build interface without making
them inherit from QKernel or exposing the compiler-facing callable
descriptor model as a frontend concept.
Attributes¶
block: Block Return the cached hierarchical body block.effects: KernelEffect Return cached semantic effects of the qkernel body.input_types: dict[str, Any] Return frontend input annotations by parameter name.name: str Return the user-facing callable name.output_types: list[Any] Return frontend output annotations.signature: inspect.Signature Return the Python call signature.
Methods¶
build¶
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> BlockBuild a traced body block.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | list[str] | None | Runtime parameter names to preserve. Defaults to None. |
**kwargs | Any | Compile-time bindings for non-parameter arguments. |
Returns:
Block — Traced hierarchical body block.
SerializedQKernel [source]¶
class SerializedQKernelA qkernel whose Python-independent semantic IR was deserialized.
The object implements the compiler-facing qkernel protocol. Its body is a
static, unbound hierarchical block, so :meth:build specializes existing
IR values instead of executing the original Python function again.
Constructor¶
def __init__(
self,
name: str,
signature: inspect.Signature,
input_types: dict[str, Any],
output_types: list[Any],
_block: Block,
_callable_definition: CallableDef,
) -> NoneAttributes¶
block: Block Return the cached unbound hierarchical body.effects: KernelEffect Return cached semantic effects of the preserved body.input_types: dict[str, Any]name: stroutput_types: list[Any]signature: inspect.Signature
Methods¶
build¶
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> BlockSpecialize the preserved IR for bindings and runtime parameters.
This method mirrors the public qkernel argument contract while avoiding Python re-tracing. Compile-time values replace the corresponding formal IR values; runtime parameters remain symbolic.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | list[str] | None | Names retained as backend runtime parameters. None auto-detects unbound parameterizable arguments. |
**kwargs | Any | Compile-time bindings keyed by qkernel argument. |
Returns:
Block — Specialized traced-stage body accepted by the normal
Qamomile compiler pipeline.
Raises:
TypeError— If a requested parameter or binding type is unsupported.ValueError— If arguments are unknown, missing, or present in bothparametersandkwargs.
qamomile.circuit.serialization.schema¶
Expose the exact-distribution version policy for qkernel serialization.
The protobuf payload stores Qamomile’s complete installed distribution version rather than an independent integer schema counter. Development and local build metadata remain significant so different wire implementations cannot claim the same compatibility marker. The format provides no cross-version migration layer.
Constants¶
QAMOMILE_VERSION:str=version('qamomile')
qamomile.circuit.serialization.validation¶
Semantic validation for static qkernel IR at the serialization boundary.
Overview¶
| Function | Description |
|---|---|
collect_value_like_uuids | Collect UUIDs contained in a value-like IR object. |
get_static_binding_by_type_key | Return the adapter registered under a stable serialization key. |
is_plain_int | Return True if value is a Python int but not a bool. |
normalize_control_value | Normalize an integer activation state for a control register. |
pair_block_operands | Pair all block inputs with category-grouped call-site operands. |
resolve_root_qubit_address | Resolve an array-element value to its root (array_uuid, index). |
validate_qkernel_ir | Validate every operation and nested region reachable from a qkernel. |
validate_static_binding_slot | Validate a serialized IR slot against its installed adapter. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
BinOp | Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN). |
BinOpKind | |
BitType | Type representing a classical bit. |
Block | Unified block representation for all pipeline stages. |
CInitOperation | Initialize the classical values (const, arguments etc) |
CallPolicy | Describe the default lowering policy for a callable call. |
CallTransform | Describe the requested transform of a callable implementation. |
CallableDef | Describe a compiler-facing callable definition. |
CallableRef | Identify a callable independently of its Python object. |
CastOperation | Type cast operation for creating aliases over the same quantum resources. |
CompOp | Comparison operation (EQ, NEQ, LT, LE, GT, GE). |
CompOpKind | |
ConcreteControlledU | Controlled-U with concrete (int) number of controls. |
CondOp | Conditional logical operation (AND, OR). |
DecodeQFixedOperation | Decode measured bits to float (classical operation). |
DictGetItemOperation | Look up one entry of a Dict by a (possibly symbolic) key. |
DictValue | A dictionary value stored as stable ordered entries. |
FloatType | Type representing a floating-point number. |
ForOperation | Represents a for loop operation. |
HasNestedOps | Mixin for operations that contain nested operation lists. |
IfOperation | Represents an if-else conditional operation. |
NotOp | |
ObservableType | Type representing a Hamiltonian observable parameter. |
Operation | |
ParamHint | |
PauliEvolveOp | Pauli evolution operation: exp(-i * gamma * H). |
QFixedType | Quantum fixed-point type. |
QInitOperation | Initialize the qubit |
QubitType | Type representing a quantum bit (qubit). |
RegionArg | Explicit loop-carried value on a loop operation (MLIR-style iter_arg). |
ReleaseSliceViewOperation | Mark a slice view’s borrow as explicitly returned to its parent. |
ReturnQuantumArrayElementOperation | Validate a branch-selected quantum element’s array return at emit time. |
RuntimeClassicalExpr | A classical expression known to require runtime evaluation. |
RuntimeOpKind | Unified kind for RuntimeClassicalExpr covering all classical |
SliceArrayOperation | Construct a strided view of an ArrayValue. |
StaticBindingMemberSpec | Describe one deferred qkernel-valued member of a static binding. |
StaticBindingSlot | Declare one typed compile-time object required by a qkernel. |
StaticBindingSpec | Register the closed qkernel surface of one compile-time object type. |
StoreArrayElementOperation | Store a classical scalar into one element of a classical array. |
SymbolicControlledU | Controlled-U with symbolic (Value) number of controls. |
TupleValue | A tuple of IR values for structured data. |
UIntType | Type representing an unsigned integer. |
UnaryMathOp | Represent one pure unary mathematical expression. |
UnaryMathOpKind | Identify one abstract unary mathematical operation. |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
ValueType | Base class for all value types in the IR. |
WhileOperation | Represents a while loop operation. |
Constants¶
ValueLike:TypeAlias='Value | ArrayValue | TupleValue | DictValue'
Functions¶
collect_value_like_uuids [source]¶
def collect_value_like_uuids(value: 'ValueLike') -> set[str]Collect UUIDs contained in a value-like IR object.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ValueLike | Value-like object to inspect. |
Returns:
set[str] — set[str]: UUIDs for value itself, recursively contained tuple/dict
elements, and array view/element dependencies.
get_static_binding_by_type_key [source]¶
def get_static_binding_by_type_key(type_key: str) -> StaticBindingSpecReturn the adapter registered under a stable serialization key.
Parameters:
| Name | Type | Description |
|---|---|---|
type_key | str | Stable type key from serialized IR. |
Returns:
StaticBindingSpec — Matching registered adapter.
Raises:
KeyError— If the installed Qamomile distribution does not know the key.
is_plain_int [source]¶
def is_plain_int(value: object) -> boolReturn True if value is a Python int but not a bool.
bool is a subclass of int in Python, so isinstance(True, int)
is True. This helper distinguishes a genuine integer from a boolean,
which matters wherever a boolean must be rejected in an integer slot — for
example, validating decoded wire data or a register width.
Parameters:
| Name | Type | Description |
|---|---|---|
value | object | The value to test. |
Returns:
bool — True when value is an int and not a bool.
normalize_control_value [source]¶
def normalize_control_value(control_value: int | None, num_controls: int) -> int | NoneNormalize an integer activation state for a control register.
Control qubits follow Qamomile’s LSB-first integer convention: bit j
of control_value describes the j-th flattened control operand.
None and the all-ones value are the canonical ordinary-control state.
Parameters:
| Name | Type | Description |
|---|---|---|
control_value | int | None | Required computational-basis value, or None for the ordinary all-ones control state. |
num_controls | int | Concrete positive control-register width. |
Returns:
int | None — int | None: A non-default activation value, or None for all-ones.
Raises:
TypeError— Ifcontrol_valueis not a PythonintorNone.ValueError— Ifnum_controlsis not positive, or ifcontrol_valuedoes not fit in the control-register width.
pair_block_operands [source]¶
def pair_block_operands(
block: Block,
operands: Sequence[ValueBase],
) -> list[tuple[ValueBase, ValueBase]]Pair all block inputs with category-grouped call-site operands.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Operation-owned block whose inputs are being bound. |
operands | Sequence[ValueBase] | Call-site operands after any controls that are external to block have been removed. |
Returns:
list[tuple[ValueBase, ValueBase]] — list[tuple[ValueBase, ValueBase]]: Formal/actual pairs in the block’s
list[tuple[ValueBase, ValueBase]] — declaration order.
resolve_root_qubit_address [source]¶
def resolve_root_qubit_address(value: 'Value') -> tuple[str, int] | NoneResolve an array-element value to its root (array_uuid, index).
Walks the parent_array / slice_of chain and composes the nested
affine slice maps, so view[i] resolves to
(root_uuid, start + step * i) for the composed (start, step). The
returned pair is the build-stable identity of the physical qubit slot: the
root array’s QInitOperation always registers it as
QubitAddress(root_uuid, index), so this address resolves even when the
element’s own (per-version) UUID was never registered.
The transpiler’s resource allocator uses the same walk to resolve gate and measurement operands; this shared helper keeps both call sites consistent.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | The value to resolve. Expected to be an array element (parent_array set with a single constant element_indices entry). |
Returns:
tuple[str, int] | None — tuple[str, int] | None: (root_array_uuid, composed_index) when
value is an array element with a constant index whose entire
slice_of chain has constant slice_start / slice_step.
None when value is not an array element, when its index is
non-constant, or when any slice bound in the chain is non-constant
(those cases are deferred to the emit-time resolver, which has
bindings available). Also None for a negative constant index
or a chain frame with negative slice_start / non-positive
slice_step — composing those would silently address a wrong
root slot, so they are refused rather than guessed (the frontend
rejects them at trace time; this guard covers programmatically
constructed IR).
validate_qkernel_ir [source]¶
def validate_qkernel_ir(block: Block) -> NoneValidate every operation and nested region reachable from a qkernel.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Root unbound hierarchical qkernel block. |
Raises:
ValueError— If an operation violates its arity, type, SSA, callable, or region contract.
validate_static_binding_slot [source]¶
def validate_static_binding_slot(spec: StaticBindingSpec, slot: StaticBindingSlot) -> NoneValidate a serialized IR slot against its installed adapter.
Parameters:
| Name | Type | Description |
|---|---|---|
spec | StaticBindingSpec | Installed adapter contract. |
slot | StaticBindingSlot | IR manifest entry to validate. |
Raises:
ValueError— If the type key, projected field names, or field types do not exactly match the registered adapter.
Classes¶
ArrayValue [source]¶
class ArrayValue(Value[T])An array of typed IR values.
When slice_of is set, this array is a strided view over another
array. Element accesses on a sliced ArrayValue resolve to
physical slots on the root parent via the affine map
parent_index = slice_start + slice_step * view_local_index,
applied recursively along slice_of chains. The emit-time
resolver walks this chain to produce the final qubit index; passes
that substitute or clone values must treat slice_of /
slice_start / slice_step as Value references that need to
track through the same mapping as parent_array.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
shape: tuple[Value, ...] = tuple(),
slice_of: 'ArrayValue | None' = None,
slice_start: 'Value | None' = None,
slice_step: 'Value | None' = None,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]BinOp [source]¶
class BinOp(BinaryOperationBase)Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: BinOpKind | None = None,
) -> NoneAttributes¶
kind: BinOpKind | Noneoperation_kind: OperationKindsignature: Signature
BinOpKind [source]¶
class BinOpKind(enum.Enum)Attributes¶
ADDDIVFLOORDIVMINMODMULPOWSUB
BitType [source]¶
class BitType(ClassicalTypeMixin, ValueType)Type representing a classical bit.
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
CInitOperation [source]¶
class CInitOperation(Operation)Initialize the classical values (const, arguments etc)
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
CallPolicy [source]¶
class CallPolicy(enum.Enum)Describe the default lowering policy for a callable call.
Attributes¶
INLINENATIVE_FIRSTPRESERVE_BOX
CallTransform [source]¶
class CallTransform(enum.Enum)Describe the requested transform of a callable implementation.
Attributes¶
CONTROLLEDDIRECTINVERSE
CallableDef [source]¶
class CallableDefDescribe a compiler-facing callable definition.
Parameters:
| Name | Type | Description |
|---|---|---|
ref | CallableRef | Stable callable identity. |
signature | Signature | None | Optional callable signature. |
body | Block | None | Standard IR body, or None for opaque calls. |
body_ref | CallableBodyRef | None | Reference to a standard body that is intentionally deferred. Defaults to None. |
implementations | list[CallableImplementation] | Alternative native or strategy-specific implementations. |
opaque_cost | Any | None | Explicit cost contract for a bodyless callable. Body-backed callables must leave this as None. |
default_policy | CallPolicy | Default call lowering policy. |
attrs | dict[str, Any] | Serializer-friendly definition metadata. |
Constructor¶
def __init__(
self,
ref: CallableRef,
signature: Signature | None = None,
body: Block | None = None,
body_ref: CallableBodyRef | None = None,
implementations: list[CallableImplementation] = list(),
opaque_cost: Any | None = None,
default_policy: CallPolicy = CallPolicy.INLINE,
attrs: dict[str, Any] = dict(),
) -> NoneAttributes¶
attrs: dict[str, Any]body: Block | Nonebody_ref: CallableBodyRef | Nonedefault_policy: CallPolicyimplementations: list[CallableImplementation]opaque_cost: Any | Noneref: CallableRefsignature: Signature | None
Methods¶
effects_for¶
def effects_for(self, transform: CallTransform = CallTransform.DIRECT) -> 'KernelEffect'Return cached semantic effects for one call transform.
Parameters:
| Name | Type | Description |
|---|---|---|
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
Returns:
'KernelEffect' — Union of relevant implementation-body effects.
implementation_for¶
def implementation_for(
self,
*,
transform: CallTransform = CallTransform.DIRECT,
backend: str | None = None,
strategy: str | None = None,
) -> CallableImplementation | NoneReturn the best matching implementation candidate.
Parameters:
| Name | Type | Description |
|---|---|---|
transform | CallTransform | Requested call transform. |
backend | str | None | Requested backend name. |
strategy | str | None | Requested strategy name. |
Returns:
CallableImplementation | None — CallableImplementation | None: Matching implementation, if any.
measurement_result_indices_for¶
def measurement_result_indices_for(self, transform: CallTransform = CallTransform.DIRECT) -> frozenset[int]Return measured result positions for one call transform.
Parameters:
| Name | Type | Description |
|---|---|---|
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
Returns:
frozenset[int] — frozenset[int]: Result indices carrying measurement provenance.
CallableRef [source]¶
class CallableRefIdentify a callable independently of its Python object.
Parameters:
| Name | Type | Description |
|---|---|---|
namespace | str | Stable namespace such as "qamomile.stdlib" or "user". |
name | str | Stable callable name within the namespace. |
version | str | Schema or behavior version for the callable. |
Constructor¶
def __init__(self, namespace: str, name: str, version: str = '1') -> NoneAttributes¶
name: strnamespace: strversion: str
CastOperation [source]¶
class CastOperation(Operation)Type cast operation for creating aliases over the same quantum resources.
This operation does NOT allocate new qubits. It creates a new Value that references the same underlying quantum resources with a different type.
Use cases:
Vector[Qubit] -> QFixed (after QPE, for phase measurement)
Vector[Qubit] -> QUInt (for quantum arithmetic)
QUInt -> QFixed (reinterpret bits with different encoding)
QFixed -> QUInt (reinterpret bits with different encoding)
operands: [source_value] - The value being cast results: [cast_result] - The new value with target type (same physical qubits)
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
source_type: ValueType | None = None,
target_type: ValueType | None = None,
qubit_mapping: list[str] = list(),
) -> NoneAttributes¶
num_qubits: int Number of qubits involved in the cast.operation_kind: OperationKind Cast stays in the same segment as its source (QUANTUM for quantum types).qubit_mapping: list[str]signature: Signature Return the type signature of this cast operation.source_type: ValueType | Nonetarget_type: ValueType | None
CompOp [source]¶
class CompOp(BinaryOperationBase)Comparison operation (EQ, NEQ, LT, LE, GT, GE).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: CompOpKind | None = None,
) -> NoneAttributes¶
kind: CompOpKind | Noneoperation_kind: OperationKindsignature: Signature
CompOpKind [source]¶
class CompOpKind(enum.Enum)Attributes¶
EQGEGTLELTNEQ
ConcreteControlledU [source]¶
class ConcreteControlledU(ControlledUOperation)Controlled-U with concrete (int) number of controls.
Operand layout: [ctrl_0, ..., ctrl_n, tgt_0, ..., tgt_m, params...]
Result layout: [ctrl_0', ..., ctrl_n', tgt_0', ..., tgt_m']
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
power: int | Value = 1,
block: Block | None = None,
num_controls: int = 1,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
control_operands: list[Value]control_value: int | Nonenum_controls: intparam_operands: list[Value] Get classical/object operands after the concrete control prefix.signature: Signaturetarget_operands: list[Value]
CondOp [source]¶
class CondOp(BinaryOperationBase)Conditional logical operation (AND, OR).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: CondOpKind | None = None,
) -> NoneAttributes¶
kind: CondOpKind | Noneoperation_kind: OperationKindsignature: Signature
DecodeQFixedOperation [source]¶
class DecodeQFixedOperation(Operation)Decode measured bits to float (classical operation).
This operation converts a sequence of classical bits from qubit measurements into a floating-point number using fixed-point encoding.
The decoding formula for least-significant-first storage:
float_value = Σ bit[i] * 2^(int_bits - num_bits + i)
For QPE phase (int_bits=0):
bit[0] has weight 2**(-num_bits) and bit[-1] has weight 0.5.
Example:
bits = [1, 0, 1] with int_bits=0
→ 0.101 (MSB-first display) = 0.5 + 0.125 = 0.625operands: [ArrayValue of bits (vec[bit])] results: [Float value]
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_bits: int = 0,
int_bits: int = 0,
) -> NoneAttributes¶
int_bits: intnum_bits: intoperation_kind: OperationKindsignature: Signature
DictGetItemOperation [source]¶
class DictGetItemOperation(Operation)Look up one entry of a Dict by a (possibly symbolic) key.
This is the IR form of d[key] on a Dict handle. The key
components may be symbolic (e.g. loop variables of a for-items
loop); the lookup is resolved at emit time when the key values and
the dict’s bound data are both concrete.
operands: [DictValue, *key_component_values] results: [looked-up scalar value]
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
key_arity: int = 1,
) -> NoneAttributes¶
dict_value: Value Value: The DictValue being indexed (operands[0]).key_arity: intkey_values: tuple[Value, ...] tuple[Value, ...]: The key component values.operation_kind: OperationKindsignature: Signature
DictValue [source]¶
class DictValue(_MetadataValueMixin, ValueBase)A dictionary value stored as stable ordered entries.
Constructor¶
def __init__(
self,
name: str,
entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> NoneAttributes¶
entries: tuple[tuple[TupleValue | Value, Value], ...]logical_id: strmetadata: ValueMetadataname: strtype: DictTypeuuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> DictValueFloatType [source]¶
class FloatType(ClassicalTypeMixin, ValueType)Type representing a floating-point number.
ForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
loop_var: str = '',
loop_var_value: Value | None = None,
operations: list[Operation] = list(),
loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
region_args: tuple[RegionArg, ...] = (),
captures: tuple[ValueBase, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]Include loop_var_value so cloning/substitution stays consistent.
Without this override, UUIDRemapper would clone every body
reference to the loop variable to a fresh UUID, but leave
loop_var_value pointing at the un-cloned original — emit-time
UUID-keyed lookups for the loop variable would then miss.
Loop-carried rebind records and region arguments are included
for the same reason.
nested_op_lists¶
def nested_op_lists(self) -> list[list[Operation]]nested_regions¶
def nested_regions(self) -> tuple[Region, ...]Return the range-loop body with its explicit interface.
Returns:
tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction
value, carried-value formals, captures, and carried yields.
rebuild_nested¶
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationHasNestedOps [source]¶
class HasNestedOpsMixin for operations that contain nested operation lists.
nested_regions() is the canonical traversal API because it exposes
operations together with block arguments, captures, and yields.
nested_op_lists() / rebuild_nested() remain compatibility helpers
for specialized consumers while they migrate to the region interface.
Methods¶
nested_op_lists¶
def nested_op_lists(self) -> list[list[Operation]]Return all nested operation lists in this control flow op.
nested_regions¶
def nested_regions(self) -> tuple[Region, ...]Return uniform views of every nested operation region.
Subclasses with explicit block arguments, captures, or yields override
this method. The fallback keeps legacy operation-owned blocks visible
while consumers migrate from nested_op_lists.
Returns:
tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.
rebuild_nested¶
def rebuild_nested(self, new_lists: list[list[Operation]]) -> OperationReturn a copy with nested operation lists replaced.
new_lists must have the same length/order as nested_op_lists().
rebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationReturn a copy with replacement region operation sequences.
Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
true_operations: list[Operation] = list(),
false_operations: list[Operation] = list(),
true_yields: list[Value] = list(),
false_yields: list[Value] = list(),
branch_rebinds: tuple[BranchRebind, ...] = (),
true_captures: tuple[ValueBase, ...] = (),
false_captures: tuple[ValueBase, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend a branch-merge slot to this if-else.
The only sanctioned construction path for merges: it keeps the
yield lists and results index-aligned so iter_merges can
rely on the invariants it checks.
Parameters:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
all_input_values¶
def all_input_values(self) -> list[ValueBase]Include branch-yield values and rebind records for cloning/substitution.
The yields are subclass-specific Value fields (not operands —
see the class docstring), so generic passes reach them through
this override, mirroring ForItemsOperation.key_var_values.
Branch rebind records follow the loop operations’ rationale: the
recorded pre-branch values reference program values by identity,
so inline cloning must remap them in lockstep with operands.
Read-based checks must not treat the records as reads (see
_op_read_uuids in the analyze pass module).
Returns:
list[ValueBase] — list[ValueBase]: Base input values plus the true/false
yields and rebind-record values.
iter_merges¶
def iter_merges(self) -> Iterator[IfMerge]Iterate the branch-merge slots of this if-else.
This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.
Yields:
IfMerge — One entry per merged output, in result order.
Raises:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
nested_op_lists¶
def nested_op_lists(self) -> list[list[Operation]]Return the two branch bodies (merge yields are not operations).
Returns:
list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations].
The branch-merge yields are values, not operations, so
they are intentionally absent here.
nested_regions¶
def nested_regions(self) -> tuple[Region, ...]Return the true and false branch interfaces.
Returns:
tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with
branch-local captures and merge yields.
rebuild_nested¶
def rebuild_nested(self, new_lists: list[list[Operation]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[list[Operation]] | The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]). |
Returns:
Operation — A copy of this if-else with the branch bodies
swapped and all other fields (yields, rebinds) preserved.
rebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
NotOp [source]¶
class NotOp(Operation)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
input: Valueoperation_kind: OperationKindoutput: Valuesignature: Signature
ObservableType [source]¶
class ObservableType(ObjectTypeMixin, ValueType)Type representing a Hamiltonian observable parameter.
This is a reference type - the actual qamomile.observable.Hamiltonian is provided via bindings during transpilation. It cannot be constructed or manipulated within qkernels.
Example usage:
import qamomile.circuit as qm
import qamomile.observable as qm_o
# Build Hamiltonian in Python
H = qm_o.Z(0) * qm_o.Z(1)
@qm.qkernel
def vqe(q: qm.Vector[qm.Qubit], H: qm.Observable) -> qm.Float:
return qm.expval(q, H)
# H is passed as binding
executable = transpiler.transpile(vqe, bindings={"H": H})Constructor¶
def __init__(self) -> NoneOperation [source]¶
class Operation(abc.ABC)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operands: list[Value]operation_kind: OperationKind Return the kind of this operation for classical/quantum classification.results: list[Value]signature: Signature
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]Return all input Values including subclass-specific fields.
Generic passes should use this instead of accessing operands
directly to ensure no Value is missed. Subclasses override this
to include extra Value fields (e.g. ControlledUOperation.power).
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationReturn a copy with all Values substituted via mapping.
Handles operands, results, and subclass-specific Value
fields. Subclasses override to handle their extra fields.
ParamHint [source]¶
class ParamHintConstructor¶
def __init__(self, name: str, type: ValueType) -> NoneAttributes¶
name: strtype: ValueType
PauliEvolveOp [source]¶
class PauliEvolveOp(Operation)Pauli evolution operation: exp(-i * gamma * H).
This operation applies the time evolution of a Pauli Hamiltonian to a quantum register.
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
evolved_qubits: Value The evolved quantum register result.gamma: Value The evolution time parameter.observable: Value The Observable parameter operand.operation_kind: OperationKind PauliEvolveOp is QUANTUM - transforms quantum state.qubits: Value The quantum register operand.signature: Signature
QFixedType [source]¶
class QFixedType(QuantumTypeMixin, ValueType)Quantum fixed-point type.
Represents a quantum register encoding a fixed-point number with specified integer and fractional bits.
Constructor¶
def __init__(
self,
integer_bits: int | Value[UIntType] = 0,
fractional_bits: int | Value[UIntType] = 0,
) -> NoneAttributes¶
fractional_bits: int | Value[UIntType]integer_bits: int | Value[UIntType]
Methods¶
label¶
def label(self) -> strQInitOperation [source]¶
class QInitOperation(Operation)Initialize the qubit
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
QubitType [source]¶
class QubitType(QuantumTypeMixin, ValueType)Type representing a quantum bit (qubit).
RegionArg [source]¶
class RegionArgExplicit loop-carried value on a loop operation (MLIR-style iter_arg).
A RegionArg makes a loop-carried dependency explicit in the IR,
the way MLIR’s scf.for models iter_args / scf.yield:
On iteration 0 the body reads
block_argbound toinit.After each iteration,
block_argis rebound to that iteration’syieldedvalue.After the loop,
resultholds the final carried value (initwhen the loop ran zero iterations).
The loop body’s operations reference block_arg (the frontend
substitutes the traced pre-loop reads), and post-loop operations
reference result (the frontend rebinds the Python handle when it
closes the loop). result is also appended to the loop operation’s
results list so dependency analysis sees the loop as its
producer.
This subsumes the trace-once staleness that LoopCarriedRebind
records exist to reject: a rebind represented as a RegionArg is
a supported loop-carried value, not a miscompilation hazard.
Constructor¶
def __init__(
self,
var_name: str,
init: Value,
block_arg: Value,
yielded: Value,
result: Value,
) -> NoneAttributes¶
block_arg: Valueinit: Valueresult: Valuevar_name: stryielded: Value
ReleaseSliceViewOperation [source]¶
class ReleaseSliceViewOperation(Operation)Mark a slice view’s borrow as explicitly returned to its parent.
Emitted by :meth:Vector.__setitem__ when used with a slice index
(qs[a:b] = qmc.h(qs[a:b])). This op tells the post-fold
linearity checker
(:class:~qamomile.circuit.transpiler.passes.slice_borrow_check.SliceBorrowCheckPass)
that the view referenced in operands[0] no longer owns its
covered parent slots, mirroring the frontend’s
VectorView.consume(operation_name="slice assignment") borrow
release.
Like :class:SliceArrayOperation, this op is a declarative
classical-side marker that does not survive into the emit stream:
:class:~qamomile.circuit.transpiler.passes.strip_slice_ops.StripSliceArrayOpsPass
removes both :class:SliceArrayOperation and
:class:ReleaseSliceViewOperation after
:class:SliceBorrowCheckPass has observed them. Reaching emit
is a compiler-internal invariant violation and is rejected with a
RuntimeError from :mod:standard_emit.
Within a control-flow body (ForOperation / WhileOperation
/ IfOperation), this op only releases view borrows that were
created within the same body. Releasing a borrow that the
enclosing block has registered (an “outer-snapshot” borrow) is
rejected by SliceBorrowCheckPass with ValidationError — the
loop-merge semantics of the
pass cannot propagate entry deletions out of the body, so the only
way to keep the static check consistent is to forbid that pattern.
Example:
``qs[1:3] = qmc.h(qs[1:3])`` emits, after the broadcast loop::
ReleaseSliceViewOperation(
operands=[qmc_h_result_view], # slice_of=qs_value
results=[],
)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKind Release is classical — it updates borrow tracking metadata only.signature: Signature Return the type signature of this release operation.
ReturnQuantumArrayElementOperation [source]¶
class ReturnQuantumArrayElementOperation(Operation)Validate a branch-selected quantum element’s array return at emit time.
Most quantum element assignments are verified structurally by the frontend and emit no IR. A compile-time conditional can instead select different element indices on its branches; only the unrolled emit context knows which source index survived. This operation carries both the requested target indices and the conditional source indices so emission can prove they resolve to the same physical slot before treating the assignment as a borrow return.
Operand convention:
[array, returned_qubit, *target_indices, *source_indices]. The
target and source halves have equal nonzero arity, inferred from the
operand count. The operation has no results and emits no backend gate.
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
array: ArrayValue Return the quantum array receiving the borrowed element.index_arity: int Return the number of target (and source) index operands.operation_kind: OperationKind Classify the return validator as a quantum operation.returned_value: Value Return the quantum value being returned.signature: Signature Return the deferred validator’s operand-only signature.source_indices: tuple[Value, ...] Return the branch-merged borrow-source indices.target_indices: tuple[Value, ...] Return the user-written assignment indices.
RuntimeClassicalExpr [source]¶
class RuntimeClassicalExpr(Operation)A classical expression known to require runtime evaluation.
Lowered from CompOp / CondOp / NotOp / BinOp by
ClassicalLoweringPass when the op’s operand dataflow traces back
to a MeasureOperation (i.e. cannot be folded at compile-time, by
emit-time loop unrolling, or by compile_time_if_lowering). Backend
emit translates this 1:1 to a backend-native runtime expression
(e.g. qiskit.circuit.classical.expr.Expr).
Operand convention:
Binary kinds (EQ/NEQ/LT/LE/GT/GE/AND/OR/ADD/SUB/MUL/DIV/FLOORDIV/MOD/POW):
operands = [lhs, rhs].Unary kind (NOT):
operands = [val].Ternary kind (SELECT):
operands = [condition, true_value, false_value]— the runtime form of a branch merge (result = true_value if condition else false_value).Result:
results = [output_value].
The single-node + unified-kind shape (vs four parallel subclasses)
keeps the backend dispatch a single match op.kind instead of four
parallel hooks, and makes the IR self-documenting: a single
RuntimeClassicalExpr instance signals “runtime evaluation
required” regardless of which classical family it came from.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: RuntimeOpKind | None = None,
) -> NoneAttributes¶
kind: RuntimeOpKind | Noneoperation_kind: OperationKindsignature: Signature
RuntimeOpKind [source]¶
class RuntimeOpKind(enum.Enum)Unified kind for RuntimeClassicalExpr covering all classical
op families that can appear at runtime.
The split between this enum and the per-family BinOpKind /
CompOpKind / CondOpKind is intentional: compile-time-foldable
classical ops keep their original IR types so the existing fold
pipeline (constant_fold → compile_time_if_lowering → emit-time
evaluate_classical_predicate) is undisturbed. Only ops identified
as runtime-evaluation-only by ClassicalLoweringPass get rewritten
to RuntimeClassicalExpr with a member of this enum.
Attributes¶
ADDANDDIVEQFLOORDIVGEGTLELTMODMULNEQNOTORPOWSELECTSUB
SliceArrayOperation [source]¶
class SliceArrayOperation(Operation)Construct a strided view of an ArrayValue.
The op itself performs no quantum action — it records that the
result ArrayValue is a strided view of the operand parent
with the given start / step. The result’s
slice_of / slice_start / slice_step fields carry the
affine map used by the emit-time resolver.
SliceArrayOperation is classified as :attr:OperationKind.CLASSICAL
because slicing is pure index selection — no new quantum operation
is introduced. The pipeline keeps this op through
PartialEvaluationPass (which invokes
ConstantFoldingPass(..., strip_slice_ops=False)) so the
post-fold :class:~qamomile.circuit.transpiler.passes.slice_borrow_check.SliceBorrowCheckPass
can use it as a view-declaration marker; once that check has run,
StripSliceArrayOpsPass removes every SliceArrayOperation
/ ReleaseSliceViewOperation so segmentation
(:mod:~qamomile.circuit.transpiler.passes.separate) and the
downstream emit stage only see a pure quantum-op stream. By the
time :mod:~qamomile.circuit.transpiler.passes.separate runs the
op has therefore been stripped — reaching emit is a compiler-
internal invariant violation.
Example:
``q[1::2]`` on a ``Vector[Qubit]`` emits::
SliceArrayOperation(
operands=[q_value, uint_1, uint_2],
results=[sliced_value], # slice_of=q_value, slice_start=uint_1, slice_step=uint_2
)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKind Slice is classical — it selects indices without quantum action.signature: Signature Return the type signature of this slice operation.
StaticBindingMemberSpec [source]¶
class StaticBindingMemberSpecDescribe one deferred qkernel-valued member of a static binding.
Parameters:
| Name | Type | Description |
|---|---|---|
input_types | Mapping[str, Any] | Ordered frontend input annotations. |
output_types | tuple[Any, ...] | Ordered frontend result annotations. |
return_annotation | Any | Complete Python return annotation. |
getter | Callable[[Any], Any] | Extractor returning the concrete qkernel-like member. |
qubit_width_fields | Mapping[str, str] | Input-name to scalar field-name mapping used to specialize quantum vector widths. |
Constructor¶
def __init__(
self,
input_types: Mapping[str, Any],
output_types: tuple[Any, ...],
return_annotation: Any,
getter: Callable[[Any], Any],
qubit_width_fields: Mapping[str, str] = dict(),
) -> NoneAttributes¶
getter: Callable[[Any], Any]input_types: Mapping[str, Any]output_types: tuple[Any, ...]qubit_width_fields: Mapping[str, str]return_annotation: Any
StaticBindingSlot [source]¶
class StaticBindingSlotDeclare one typed compile-time object required by a qkernel.
The object itself is not an SSA value and never reaches a backend. Only registered scalar projections and deferred callable-member references may appear in the hierarchical body. A build must resolve the slot before the block advances to a compiler stage.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | QKernel argument name used by bindings. |
type_key | str | Stable key of the registered static-binding adapter. |
fields | tuple[StaticBindingField, ...] | Scalar projections referenced while tracing the unbound qkernel. |
Constructor¶
def __init__(
self,
name: str,
type_key: str,
fields: tuple[StaticBindingField, ...] = (),
) -> NoneAttributes¶
fields: tuple[StaticBindingField, ...]name: strtype_key: str
StaticBindingSpec [source]¶
class StaticBindingSpecRegister the closed qkernel surface of one compile-time object type.
Parameters:
| Name | Type | Description |
|---|---|---|
annotation | type[Any] | Public qkernel parameter annotation. |
type_key | str | Stable serialization key. |
fields | Mapping[str, StaticBindingFieldSpec] | Scalar projections available while tracing. |
members | Mapping[str, StaticBindingMemberSpec] | Deferred callable members available while tracing. |
Constructor¶
def __init__(
self,
annotation: type[Any],
type_key: str,
fields: Mapping[str, StaticBindingFieldSpec],
members: Mapping[str, StaticBindingMemberSpec],
) -> NoneAttributes¶
annotation: type[Any]fields: Mapping[str, StaticBindingFieldSpec]members: Mapping[str, StaticBindingMemberSpec]type_key: str
StoreArrayElementOperation [source]¶
class StoreArrayElementOperation(Operation)Store a classical scalar into one element of a classical array.
This is the IR form of array[index] = value for classical element
types (Bit / UInt / Float). Classical values are freely
copyable, so the store is an ordinary SSA rewrite: the operation
consumes the current array version and produces a new ArrayValue
version (same logical_id, fresh uuid) whose contents equal the
input array with the addressed element replaced. Quantum arrays never
use this operation — qubit element assignment is the return half of
the borrow-return idiom and emits no IR.
The operation is evaluated in one of two places:
Compile time:
ConstantFoldingPassfolds the store when the source array contents, the index, and the stored value are all compile-time resolvable, attaching the updatedconst_arraymetadata to the result value.Runtime: otherwise the store executes host-side in a classical segment via
ClassicalExecutor(e.g. for measurement-derivedVector[Bit]contents). It must never reach a quantum segment; backend emit rejects it explicitly.
Operand convention:
operands: [array (ArrayValue), stored_value (Value), *index_values]
results: [new_array (ArrayValue)]
Example:
@qmc.qkernel
def k() -> qmc.Vector[qmc.Bit]:
qs = qmc.qubit_array(2, "qs")
qs[0] = qmc.x(qs[0])
bits = qmc.measure(qs)
bits[1] = bits[0] # emits StoreArrayElementOperation
return bitsConstructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
array: ArrayValue ArrayValue: The array version the store reads from.index_values: tuple[Value, ...] tuple[Value, ...]: The element indices being written.operation_kind: OperationKindsignature: Signature Return the operation’s dynamic array/qubit/index signature.stored_value: Value Value: The scalar being written into the array.
SymbolicControlledU [source]¶
class SymbolicControlledU(ControlledUOperation)Controlled-U with symbolic (Value) number of controls.
Operand layout: [ctrl_arg_0, ..., ctrl_arg_{k-1}, tgt_0, ..., tgt_m, params...]
Result layout: [ctrl_arg_0', ..., ctrl_arg_{k-1}', tgt_0', ..., tgt_m']
The number of control arguments k is recorded in
num_control_args; the default k = 1 corresponds to the
historical single-pool form (operands[0] is a
Vector[Qubit] / VectorView whose length equals
num_controls, or whose control_indices-selected subset
does). When k > 1 the control prefix is a heterogeneous
sequence of scalar Qubit values and ArrayValues whose
total qubit count is num_controls; the emit pass walks them
in order to recover the per-physical-qubit control set.
When control_indices is None the entire control prefix
is used as active controls (one-arg form: len(ctrl_vector) == num_controls; multi-arg form: the qubit-count sum of the
prefix args equals num_controls). When non-None, the
listed indices select exactly num_controls slots from a
single-arg pool to act as controls; combining
control_indices with the multi-arg control prefix is
rejected at frontend time.
Each control_indices entry is stored as a Value of
UIntType regardless of whether the frontend passed an
int literal or a UInt handle, so all downstream
value-substitution passes see a uniform shape.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
power: int | Value = 1,
block: Block | None = None,
num_controls: Value = (lambda: Value(type=(UIntType()), name=''))(),
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_indices: tuple[Value, ...] | None = None,
num_control_args: int = 1,
) -> NoneAttributes¶
control_indices: tuple[Value, ...] | Nonecontrol_operands: list[Value]is_symbolic_num_controls: boolnum_control_args: intnum_controls: Valueparam_operands: list[Value] Get classical/object operands after the symbolic control prefix.signature: Signaturetarget_operands: list[Value]
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationTupleValue [source]¶
class TupleValue(_MetadataValueMixin, ValueBase)A tuple of IR values for structured data.
Constructor¶
def __init__(
self,
name: str,
elements: tuple[ValueLike, ...] = tuple(),
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> NoneAttributes¶
elements: tuple[ValueLike, ...]logical_id: strmetadata: ValueMetadataname: strtype: ‘TupleType’uuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> TupleValueUIntType [source]¶
class UIntType(ClassicalTypeMixin, ValueType)Type representing an unsigned integer.
UnaryMathOp [source]¶
class UnaryMathOp(Operation)Represent one pure unary mathematical expression.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[Value] | Single numeric input value. |
results | list[Value] | Single numeric result value. |
kind | UnaryMathOpKind | None | Mathematical operation to apply. |
Raises:
ValueError— Ifkindis missing or the operation does not have exactly one operand and one result.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: UnaryMathOpKind | None = None,
) -> NoneAttributes¶
input: Value Return the input value.kind: UnaryMathOpKind | Noneoperation_kind: OperationKind Classify the operation as classical.output: Value Return the output value.signature: Signature Return the typed unary signature.
UnaryMathOpKind [source]¶
class UnaryMathOpKind(enum.Enum)Identify one abstract unary mathematical operation.
Attributes¶
CEILLOG2
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of backend resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
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) -> boolis_object¶
def is_object(self) -> boolis_quantum¶
def is_quantum(self) -> boollabel¶
def label(self) -> strWhileOperation [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 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(),
max_iterations: int | None = None,
loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
region_args: tuple[RegionArg, ...] = (),
captures: tuple[ValueBase, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]max_iterations: int | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]Include rebind records and region args for cloning/substitution.
Same rationale as ForOperation.all_input_values: rebind
records and region arguments reference body/pre-loop values by
identity, so inline cloning must remap them in lockstep with
body operands.
Returns:
list[ValueBase] — list[ValueBase]: Base input values plus rebind-record and
region-argument values.
nested_op_lists¶
def nested_op_lists(self) -> list[list[Operation]]nested_regions¶
def nested_regions(self) -> tuple[Region, ...]Return the while body with explicit boundary values.
Returns:
tuple[Region, ...] — tuple[Region, ...]: One body region whose block arguments and
yields are aligned with region_args. The updated
condition, when present, is appended as the final yield.
rebuild_nested¶
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the while body and its complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt while operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, rebind-record, and region-arg values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.