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

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

qamomile.circuit.visualization

Circuit visualization module.

This module provides static matplotlib-based circuit visualization with a Qiskit-inspired layout style.

Overview

ClassDescription
CircuitStyleStyle configuration for circuit visualization.
MatplotlibDrawerMatplotlib-based circuit drawer with Qiskit-style layout.

Classes

CircuitStyle [source]

class CircuitStyle

Style configuration for circuit visualization.

Constructor

def __init__(
    self,
    gate_width: float = 0.65,
    gate_height: float = 0.65,
    gate_corner_radius: float = 0.2,
    background_color: str = '#FFFFFF',
    wire_color: str = '#000000',
    gate_face_color: str = '#E8B878',
    gate_symbol_color: str = '#E8B878',
    gate_symbol_edge_color: str = '#000000',
    gate_text_color: str = '#000000',
    connection_line_color: str = '#000000',
    block_face_color: str = '#5B7F61',
    block_text_color: str = '#FFFFFF',
    block_border_color: str = '#4A6B50',
    block_box_edge_color: str = '#4A6B50',
    measure_face_color: str = '#D5CCC4',
    measure_symbol_color: str = '#6B5F55',
    for_loop_face_color: str = '#F0E4D0',
    for_loop_text_color: str = '#000000',
    for_loop_edge_color: str = '#C4A882',
    while_loop_face_color: str = '#E0D4F0',
    while_loop_text_color: str = '#000000',
    while_loop_edge_color: str = '#A88BC8',
    for_items_face_color: str = '#D0E8D0',
    for_items_text_color: str = '#000000',
    for_items_edge_color: str = '#90B890',
    if_face_color: str = '#F0D8D0',
    if_text_color: str = '#000000',
    if_edge_color: str = '#C8A898',
    expval_face_color: str = '#D4E8F0',
    expval_text_color: str = '#000000',
    expval_edge_color: str = '#8AB4C8',
    font_size: int = 13,
    subfont_size: int = 10,
    param_font_size: int = 9,
    margin: tuple[float, float, float, float] = (0.5, 0.1, 0.1, 0.3),
    gate_gap: float = 0.3,
    char_width_base: float = 0.12,
    char_width_bold: float = 0.14,
    char_width_gate: float = 0.14,
    char_width_block: float = 0.17,
    char_width_monospace: float = 0.17,
    text_padding: float = 0.25,
    border_padding_base: float = 0.3,
    border_padding_depth_factor: float = 0.1,
    min_left_margin: float = 0.3,
    label_height: float = 0.35,
    box_padding_x: float = 0.3,
    box_padding_y: float = 0.2,
    label_vertical_offset: float = 0.05,
    label_horizontal_padding: float = 0.1,
    initial_wire_position: float = 0.3,
    wire_extension: float = 0.3,
    operation_width_padding: float = 0.4,
    operation_content_padding: float = 0.6,
    line_height: float = 0.4,
    fallback_char_width: float = 0.15,
    fallback_text_height: float = 0.15,
    font_scaling_adjustment: float = 0.85,
    nested_margin: float = 0.15,
    border_extra_margin_right: float = 0.8,
    border_extra_margin_left: float = 0.3,
    folded_loop_width: float = 1.5,
    folded_call_block_width: float = 1.5,
    gate_text_padding: float = 0.1,
    nested_padding_decay: float = 0.85,
    min_block_padding: float = 0.1,
    power_wrapper_margin: float = 0.2,
    folded_box_text_v_padding: float = 0.15,
    max_folded_body_chars: int = 40,
    qubit_base_spacing: float = 1.0,
    qubit_clearance: float = 0.15,
    label_step_gap: float = 0.1,
    overlap_step_gap: float = 0.15,
    label_padding: float = 0.05,
    qubit_y_label_height: float = 0.25,
    figure_scale_factor: float = 0.8,
    figure_min_width: float = 4.0,
    figure_min_height: float = 2.0,
    x_left_min_bound: float = -1.0,
) -> None

Attributes


MatplotlibDrawer [source]

class MatplotlibDrawer

Matplotlib-based circuit drawer with Qiskit-style layout.

This drawer produces static matplotlib figures showing quantum circuits. It supports two modes:

Constructor

def __init__(self, graph: Block, style: CircuitStyle | None = None)

Initialize the drawer.

Parameters:

NameTypeDescription
graphBlockComputation graph to visualize.
styleCircuitStyle | NoneVisual style configuration. Uses DEFAULT_STYLE if None.

Raises:

Attributes

Methods

draw
def draw(
    self,
    inline: bool = False,
    fold_loops: bool = True,
    expand_composite: bool = False,
    inline_depth: int | None = None,
    fold_ifs: bool = False,
) -> Figure

Generate a matplotlib Figure of the circuit.

Parameters:

NameTypeDescription
inlineboolIf True, expand inline callable contents. If False, show calls as boxes.
fold_loopsboolIf True (default), display ForOperation as blocks instead of unrolling. If False, expand loops and show all iterations.
expand_compositeboolIf True, expand boxed InvokeOperation bodies. If False (default), show them as boxes.
inline_depthint | NoneMaximum nesting depth for inline expansion. None means unlimited. Affects inline calls, ControlledU, and boxed InvokeOperation nodes.
fold_ifsboolIf True, display IfOperation as folded summary blocks. If False (default), show if/else branches side by side.

Returns:

Figure — Matplotlib figure object.

draw_kernel
@classmethod
def draw_kernel(
    cls,
    kernel: Any,
    *,
    inline: bool = False,
    fold_loops: bool = True,
    fold_ifs: bool = False,
    expand_composite: bool = False,
    inline_depth: int | None = None,
    style: CircuitStyle | None = None,
    **kwargs: Any = {},
) -> Figure

Draw a QKernel, handling Vector[Qubit] params with integer sizes.

For kernels with Vector[Qubit] parameters, pass an integer to specify the array size (e.g., inputs=3 for a 3-qubit vector).

Parameters:

NameTypeDescription
kernelAnyA QKernel instance to visualize.
inlineboolIf True, expand inline callable contents.
fold_loopsboolIf True (default), display ForOperation as blocks.
fold_ifsboolIf True, display IfOperation as folded summary blocks. If False (default), show if/else branches side by side.
expand_compositeboolIf True, expand boxed InvokeOperation bodies.
inline_depthint | NoneMaximum nesting depth for inline expansion.
styleCircuitStyle | NoneVisual style configuration.
**kwargsAnyConcrete values for kernel arguments. For Vector[Qubit] parameters, pass an integer size.

Returns:

Figure — Matplotlib figure object.


qamomile.circuit.visualization.analyzer

Circuit analysis: IR inspection, value resolution, and label generation.

This module provides CircuitAnalyzer, which handles all IR-level analysis for the circuit visualization pipeline. It has no matplotlib dependency.

Overview

FunctionDescription
align_formal_operandsAlign split call-site operand pools to formal declaration order.
compute_border_paddingCompute border padding for a given nesting depth.
control_pattern_for_valueReturn the LSB-first activation pattern for a control value.
ClassDescription
ArrayValueAn array of typed IR values.
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
BinOpKind
BlockUnified block representation for all pipeline stages.
CallPolicyDescribe the default lowering policy for a callable call.
CallableBodySelectionDescribe one validated IR body selected for an invocation.
CastOperationType cast operation for creating aliases over the same quantum resources.
CircuitAnalyzerAnalyzes IR blocks for circuit visualization.
CircuitStyleStyle configuration for circuit visualization.
CompOpComparison operation (EQ, NEQ, LT, LE, GT, GE).
CompOpKind
ConcreteControlledUControlled-U with concrete (int) number of controls.
CondOpConditional logical operation (AND, OR).
CondOpKind
ControlledUOperationBase class for controlled-U operations.
DictValueA dictionary value stored as stable ordered entries.
ExpvalOpExpectation value operation.
ForItemsOperationRepresents iteration over dict/iterable items.
ForOperationRepresents a for loop operation.
GateOperationQuantum gate operation.
GateOperationType
GlobalPhaseOperationMultiply the complete quantum state by exp(i * phase).
HasNestedOpsMixin for operations that contain nested operation lists.
IfOperationRepresents an if-else conditional operation.
InverseBlockOperationRepresent an inverse qkernel/block as a first-class IR operation.
InvokeOperationRepresent a composite, stdlib, or oracle call.
MeasureOperation
MeasureQFixedOperationMeasure a quantum fixed-point number.
MeasureVectorOperationMeasure a vector of qubits.
NotOp
QInitOperationInitialize the qubit
QubitTypeType representing a quantum bit (qubit).
ReturnOperationExplicit return operation marking the end of a block with return values.
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
VFoldedBlockFolded control-flow block (For/While/ForItems/If).
VFoldedKindClassification of folded control-flow blocks.
VGateRepresent a pre-resolved gate, annotation, measurement, or block node.
VGateKindClassification of VGate nodes for rendering dispatch.
VInlineBlockRepresent an inlined callable or controlled body with a visible border.
VSkipZero-space node for QInit, Cast, or zero-iteration loops.
VUnfoldedKindClassification of unfolded control-flow sequences.
VUnfoldedSequenceUnfolded control-flow sequence (For/ForItems/If).
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.
VisualCircuitRoot container for the Visual IR tree.
WhileOperationRepresents a while loop operation.

Constants

Functions

align_formal_operands [source]

def align_formal_operands(
    formals: Sequence[ValueBase],
    quantum_operands: Sequence[ValueBase],
    parameter_operands: Sequence[ValueBase],
) -> list[ValueBase]

Align split call-site operand pools to formal declaration order.

Operation-owned call sites store quantum operands separately from classical/object operands, while a block keeps the Python declaration order and may interleave those categories. Reweaving the two pools here gives every consumer one canonical formal-to-actual convention.

Parameters:

NameTypeDescription
formalsSequence[ValueBase]Formal inputs in declaration order.
quantum_operandsSequence[ValueBase]Quantum actual operands in their call-site order.
parameter_operandsSequence[ValueBase]Classical/object actual operands in their call-site order.

Returns:

list[ValueBase] — list[ValueBase]: Actual operands aligned with formals. The list stops at the first category shortfall so a downstream positional pairing cannot silently consume an operand of the wrong category.


compute_border_padding [source]

def compute_border_padding(style: CircuitStyle, depth: int) -> float

Compute border padding for a given nesting depth.

Parameters:

NameTypeDescription
styleCircuitStyleVisual style configuration.
depthintNesting depth of the block.

Returns:

float — Border padding value, clamped to min_block_padding.


control_pattern_for_value [source]

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

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

Parameters:

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

Returns:

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

Raises:

Example:

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

Classes

ArrayValue [source]

class ArrayValue(Value[T])

An array of typed IR values.

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

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

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

Returns:

boolTrue iff slice_of is non-None.

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

BinOp [source]

class BinOp(BinaryOperationBase)

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

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

BinOpKind [source]

class BinOpKind(enum.Enum)
Attributes

Block [source]

class Block

Unified block representation for all pipeline stages.

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

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

Create an inline callable invocation against this block.

Parameters:

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

Returns:

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

Raises:

is_affine
def is_affine(self) -> bool

Return whether this block has passed affine validation.

Returns:

bool — True for AFFINE and ANALYZED blocks.

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

Return list of unbound parameter names.


CallPolicy [source]

class CallPolicy(enum.Enum)

Describe the default lowering policy for a callable call.

Attributes

CallableBodySelection [source]

class CallableBodySelection

Describe one validated IR body selected for an invocation.

Parameters:

NameTypeDescription
bodyBlock | NoneSelected IR body, or None when no composable body is available.
realized_transformCallTransformTransform already implemented by body.
operandstuple[ValueBase, ...]Call-site operands corresponding to the selected body’s formal inputs.
resultstuple[ValueBase, ...]Call-site results corresponding to the selected body’s formal outputs.
Constructor
def __init__(
    self,
    body: Block | None,
    realized_transform: CallTransform,
    operands: tuple[ValueBase, ...],
    results: tuple[ValueBase, ...],
) -> None
Attributes
Methods
map_result_indices
def map_result_indices(
    self,
    body_indices: Iterable[int],
    invocation_results: Sequence[ValueBase],
) -> frozenset[int]

Map selected-body output positions to invocation result positions.

Generic controlled lowering removes the external control prefix before aligning a direct body. Transform-specific implementations instead use the complete invocation ABI. Mapping through the selected call-site result values handles both layouts, including any quantum/non-quantum reordering performed while aligning a fallback body.

Parameters:

NameTypeDescription
body_indicesIterable[int]Selected-body output positions to map.
invocation_resultsSequence[ValueBase]Complete caller-side invocation results.

Returns:

frozenset[int] — frozenset[int]: Corresponding positions in invocation_results.


CastOperation [source]

class CastOperation(Operation)

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

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

Use cases:

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

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

CircuitAnalyzer [source]

class CircuitAnalyzer

Analyzes IR blocks for circuit visualization.

Handles qubit mapping, value resolution, label generation, and width estimation. Has no matplotlib dependency.

Constructor
def __init__(
    self,
    graph: 'Block',
    style: CircuitStyle,
    inline: bool = False,
    fold_loops: bool = True,
    expand_composite: bool = False,
    inline_depth: int | None = None,
    fold_ifs: bool = False,
)

Initialize the visualization analyzer.

Parameters:

NameTypeDescription
graphBlockComputation graph to analyze for rendering.
styleCircuitStyleVisual style configuration.
inlineboolWhether to expand inline callable contents.
fold_loopsboolWhether to render loop operations as folded summary blocks instead of materialized iterations.
expand_compositeboolWhether to expand composite gates.
inline_depthint | NoneMaximum nesting depth for inline expansion, or None for unlimited depth.
fold_ifsboolWhether to render IfOperation nodes as folded summary blocks instead of side-by-side branches.
Attributes
Methods
build_qubit_map
def build_qubit_map(self, graph: 'Block') -> tuple[dict[str, int], dict[int, str], int]

Build mapping from qubit logical_id to wire indices.

In SSA form, each operation creates new Values via next_version(), which preserves logical_id. This means all versions of a qubit share the same logical_id, so we only need logical_id-based tracking.

Parameters:

NameTypeDescription
graphBlockComputation block.

Returns:

dict[str, int] — tuple[dict[str, int], dict[int, str], int]: Logical-ID-to-wire dict[int, str] — mapping, display names by wire index, and total wire count.

build_visual_ir
def build_visual_ir(
    self,
    graph: 'Block',
    qubit_map: dict[str, int],
    qubit_names: dict[int, str],
    num_qubits: int,
) -> VisualCircuit

Build a Visual IR tree from the IR block.

Walks all operations, resolving labels, qubit indices, and widths into pre-computed VisualNode dataclasses. The resulting VisualCircuit can be consumed by Layout and Renderer without any Analyzer access.

Parameters:

NameTypeDescription
graph'Block'IR computation block.
qubit_mapdict[str, int]Mapping from logical_id to wire index.
qubit_namesdict[int, str]Mapping from wire index to display name.
num_qubitsintTotal number of qubit wires.

Returns:

VisualCircuit — VisualCircuit containing the VisualNode tree.


CircuitStyle [source]

class CircuitStyle

Style configuration for circuit visualization.

Constructor
def __init__(
    self,
    gate_width: float = 0.65,
    gate_height: float = 0.65,
    gate_corner_radius: float = 0.2,
    background_color: str = '#FFFFFF',
    wire_color: str = '#000000',
    gate_face_color: str = '#E8B878',
    gate_symbol_color: str = '#E8B878',
    gate_symbol_edge_color: str = '#000000',
    gate_text_color: str = '#000000',
    connection_line_color: str = '#000000',
    block_face_color: str = '#5B7F61',
    block_text_color: str = '#FFFFFF',
    block_border_color: str = '#4A6B50',
    block_box_edge_color: str = '#4A6B50',
    measure_face_color: str = '#D5CCC4',
    measure_symbol_color: str = '#6B5F55',
    for_loop_face_color: str = '#F0E4D0',
    for_loop_text_color: str = '#000000',
    for_loop_edge_color: str = '#C4A882',
    while_loop_face_color: str = '#E0D4F0',
    while_loop_text_color: str = '#000000',
    while_loop_edge_color: str = '#A88BC8',
    for_items_face_color: str = '#D0E8D0',
    for_items_text_color: str = '#000000',
    for_items_edge_color: str = '#90B890',
    if_face_color: str = '#F0D8D0',
    if_text_color: str = '#000000',
    if_edge_color: str = '#C8A898',
    expval_face_color: str = '#D4E8F0',
    expval_text_color: str = '#000000',
    expval_edge_color: str = '#8AB4C8',
    font_size: int = 13,
    subfont_size: int = 10,
    param_font_size: int = 9,
    margin: tuple[float, float, float, float] = (0.5, 0.1, 0.1, 0.3),
    gate_gap: float = 0.3,
    char_width_base: float = 0.12,
    char_width_bold: float = 0.14,
    char_width_gate: float = 0.14,
    char_width_block: float = 0.17,
    char_width_monospace: float = 0.17,
    text_padding: float = 0.25,
    border_padding_base: float = 0.3,
    border_padding_depth_factor: float = 0.1,
    min_left_margin: float = 0.3,
    label_height: float = 0.35,
    box_padding_x: float = 0.3,
    box_padding_y: float = 0.2,
    label_vertical_offset: float = 0.05,
    label_horizontal_padding: float = 0.1,
    initial_wire_position: float = 0.3,
    wire_extension: float = 0.3,
    operation_width_padding: float = 0.4,
    operation_content_padding: float = 0.6,
    line_height: float = 0.4,
    fallback_char_width: float = 0.15,
    fallback_text_height: float = 0.15,
    font_scaling_adjustment: float = 0.85,
    nested_margin: float = 0.15,
    border_extra_margin_right: float = 0.8,
    border_extra_margin_left: float = 0.3,
    folded_loop_width: float = 1.5,
    folded_call_block_width: float = 1.5,
    gate_text_padding: float = 0.1,
    nested_padding_decay: float = 0.85,
    min_block_padding: float = 0.1,
    power_wrapper_margin: float = 0.2,
    folded_box_text_v_padding: float = 0.15,
    max_folded_body_chars: int = 40,
    qubit_base_spacing: float = 1.0,
    qubit_clearance: float = 0.15,
    label_step_gap: float = 0.1,
    overlap_step_gap: float = 0.15,
    label_padding: float = 0.05,
    qubit_y_label_height: float = 0.25,
    figure_scale_factor: float = 0.8,
    figure_min_width: float = 4.0,
    figure_min_height: float = 2.0,
    x_left_min_bound: float = -1.0,
) -> None
Attributes

CompOp [source]

class CompOp(BinaryOperationBase)

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

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

CompOpKind [source]

class CompOpKind(enum.Enum)
Attributes

ConcreteControlledU [source]

class ConcreteControlledU(ControlledUOperation)

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

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

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

CondOp [source]

class CondOp(BinaryOperationBase)

Conditional logical operation (AND, OR).

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

CondOpKind [source]

class CondOpKind(enum.Enum)
Attributes

ControlledUOperation [source]

class ControlledUOperation(Operation)

Base class for controlled-U operations.

Two concrete subclasses handle distinct operand layouts:

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

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    power: int | Value = 1,
    block: Block | None = None,
    num_controls: int | Value = 1,
    callable_ref: CallableRef | None = None,
    callable_attrs: dict[str, Any] = dict(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]
replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

DictValue [source]

class DictValue(_MetadataValueMixin, ValueBase)

A dictionary value stored as stable ordered entries.

Constructor
def __init__(
    self,
    name: str,
    entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
    metadata: ValueMetadata = ValueMetadata(),
    uuid: str = (lambda: str(uuid.uuid4()))(),
    logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> DictValue

ExpvalOp [source]

class ExpvalOp(Operation)

Expectation value operation.

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

The operation bridges quantum and classical computation:

Example IR:

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

ForItemsOperation [source]

class ForItemsOperation(HasNestedOps, Operation)

Represents iteration over dict/iterable items.

Example:

for (i, j), Jij in qmc.items(ising):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    key_vars: list[str] = list(),
    value_var: str = '',
    key_is_vector: bool = False,
    key_var_values: tuple[Value, ...] | None = None,
    value_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include the per-key/value Value fields for cloning/substitution.

Same rationale as ForOperation.all_input_values: keep the IR identity fields in lockstep with body references so UUID-keyed lookups stay valid after inline cloning. Loop-carried rebind records and region arguments are included for the same reason.

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

Return the items-loop body with its explicit interface.

Returns:

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

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

Rebuild the items-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt items-loop operation.

Raises:

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

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    loop_var: str = '',
    loop_var_value: Value | None = None,
    operations: list[Operation] = list(),
    loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
    region_args: tuple[RegionArg, ...] = (),
    captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include loop_var_value so cloning/substitution stays consistent.

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

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

Return the range-loop body with its explicit interface.

Returns:

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

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

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

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

GateOperation [source]

class GateOperation(Operation)

Quantum gate operation.

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

Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    gate_type: GateOperationType | None = None,
) -> None
Attributes
Methods
fixed
@classmethod
def fixed(
    cls,
    gate_type: GateOperationType,
    qubits: list[Value],
    results: list[Value],
) -> 'GateOperation'

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

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

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


GateOperationType [source]

class GateOperationType(enum.Enum)
Attributes

GlobalPhaseOperation [source]

class GlobalPhaseOperation(Operation)

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

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

Parameters:

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

Raises:

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

HasNestedOps [source]

class HasNestedOps

Mixin for operations that contain nested operation lists.

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

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

Return all nested operation lists in this control flow op.

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

Return uniform views of every nested operation region.

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

Returns:

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

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

Return a copy with nested operation lists replaced.

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

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

Return a copy with replacement region operation sequences.

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

Parameters:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
def __init__(
    self,
    operands: list[Value] = list(),
    results: list[Value] = list(),
    true_operations: list[Operation] = list(),
    false_operations: list[Operation] = list(),
    true_yields: list[Value] = list(),
    false_yields: list[Value] = list(),
    branch_rebinds: tuple[BranchRebind, ...] = (),
    true_captures: tuple[ValueBase, ...] = (),
    false_captures: tuple[ValueBase, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

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

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

Parameters:

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

Raises:

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

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

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

Returns:

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

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

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

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

Yields:

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

Raises:

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

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

Returns:

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

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

Return the true and false branch interfaces.

Returns:

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

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

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

Parameters:

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

Returns:

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

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

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

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

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

Parameters:

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

Returns:

Operation — The rewritten operation.


InverseBlockOperation [source]

class InverseBlockOperation(Operation)

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

The operation stores both the original forward block and a Qamomile-built inverse implementation block. Emitters may use source_block with a 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,
) -> None
Attributes

InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[str, Any]Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly.
definitionCallableDef | NoneOptional callable definition.
Constructor
def __init__(
    self,
    operands: Sequence[ValueLike] | None = None,
    results: Sequence[ValueLike] | None = None,
    *,
    target: CallableRef | None = None,
    transform: CallTransform = CallTransform.DIRECT,
    attrs: dict[str, Any] | None = None,
    definition: CallableDef | None = None,
) -> None

Initialize an invocation operation.

Parameters:

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

Raises:

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

Select a body and report the transform it already realizes.

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

Parameters:

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

Returns:

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

Raises:

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

Return the implementation body selected for this invocation.

Parameters:

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

Returns:

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

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

Return the selected implementation for this invocation.

Parameters:

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

Returns:

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

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

Return measurement-derived results for one selected implementation.

Parameters:

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

Returns:

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

Raises:

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

Select and validate the composable body for this invocation.

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

Parameters:

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

Returns:

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

Raises:


MeasureOperation [source]

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

MeasureQFixedOperation [source]

class MeasureQFixedOperation(Operation)

Measure a quantum fixed-point number.

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

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

Encoding:

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

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

MeasureVectorOperation [source]

class MeasureVectorOperation(Operation)

Measure a vector of qubits.

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

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

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

NotOp [source]

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

QInitOperation [source]

class QInitOperation(Operation)

Initialize the qubit

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

QubitType [source]

class QubitType(QuantumTypeMixin, ValueType)

Type representing a quantum bit (qubit).


ReturnOperation [source]

class ReturnOperation(Operation)

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

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

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

Example:

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

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

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

SelectOperation [source]

class SelectOperation(Operation)

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

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

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

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

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

Return every value consumed by the SELECT operation.

Returns:

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

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

Replace operand and symbolic-width values by UUID.

Parameters:

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

Returns:

Operation — Rebuilt SELECT operation with matching values replaced.


VFoldedBlock [source]

class VFoldedBlock

Folded control-flow block (For/While/ForItems/If).

Rendered as a single box with header label and body summary text.

affected_qubits_precise is True when the analyzer determined the affected-qubit set from a precise iteration walk with all operands resolved; False when the conservative fallback was used and the set may over-approximate. Renderers use this to decide whether to mark participating wires with dots.

Constructor
def __init__(
    self,
    node_key: tuple,
    header_label: str,
    body_lines: list[str],
    affected_qubits: list[int],
    folded_width: float,
    kind: VFoldedKind,
    affected_qubits_precise: bool = True,
    condition_measure_node_key: tuple | None = None,
    condition_measure_qubit_indices: list[int] = list(),
) -> None
Attributes

VFoldedKind [source]

class VFoldedKind(enum.Enum)

Classification of folded control-flow blocks.

Attributes

VGate [source]

class VGate

Represent a pre-resolved gate, annotation, measurement, or block node.

Carries all information needed for layout and rendering:

For GLOBAL_PHASE, qubit_indices names the quantum scope whose horizontal position must stay synchronized. The renderer draws one floating annotation above the scope’s top wire; it does not draw a gate on any of those wires.

Parameters:

NameTypeDescription
node_keytupleStable identifier used to associate the node with layout coordinates.
labelstrTeX-formatted display label.
qubit_indiceslist[int]Resolved wire indices participating in the node.
estimated_widthfloatWidth reserved for layout.
kindVGateKindRendering strategy for the node.
gate_typeGateOperationType | NonePrimitive gate type used for specialized drawing, or None. Defaults to None.
has_paramboolWhether the displayed gate has a parameter. Defaults to False.
box_widthfloat | NoneExplicit width for block-style nodes, or None. Defaults to None.
control_countintNumber of leading control wires for a controlled block. Defaults to 0.
control_patterntuple[int, ...]Required basis bit for each leading control wire, aligned with qubit_indices. Zero denotes an open control and one denotes a filled control. Defaults to an empty tuple for non-controlled nodes.
powerintExponent displayed for a controlled block. Defaults to 1.
terminates_wireboolWhether a measurement ends its measured wire. Defaults to True.
Constructor
def __init__(
    self,
    node_key: tuple,
    label: str,
    qubit_indices: list[int],
    estimated_width: float,
    kind: VGateKind,
    gate_type: GateOperationType | None = None,
    has_param: bool = False,
    box_width: float | None = None,
    control_count: int = 0,
    control_pattern: tuple[int, ...] = (),
    power: int = 1,
    terminates_wire: bool = True,
) -> None
Attributes

VGateKind [source]

class VGateKind(enum.Enum)

Classification of VGate nodes for rendering dispatch.

Attributes

VInlineBlock [source]

class VInlineBlock

Represent an inlined callable or controlled body with a visible border.

Carries pre-resolved children, affected qubits, and pre-computed widths so that Layout and Renderer need no Analyzer access.

Parameters:

NameTypeDescription
node_keytupleStable identifier used for layout coordinates.
labelstrDisplay label for the inlined body.
childrenlist[VisualNode]Pre-resolved child visual nodes.
affected_qubitslist[int]Every wire occupied by the body.
control_qubit_indiceslist[int]Leading coherent-control wires in flattened operand order.
control_patterntuple[int, ...]Required bit for each control wire; zero denotes an open control and one a filled control.
powerintIntegral application count for controlled bodies.
depthintVisualization nesting depth.
border_paddingfloatPadding around the inlined body border.
max_gate_widthfloatMaximum child gate width.
label_widthfloatWidth required by the body label.
content_widthfloatWidth required by child nodes.
final_widthfloatFinal reserved width including wrappers.
Constructor
def __init__(
    self,
    node_key: tuple,
    label: str,
    children: list[VisualNode],
    affected_qubits: list[int],
    control_qubit_indices: list[int],
    control_pattern: tuple[int, ...],
    power: int,
    depth: int,
    border_padding: float,
    max_gate_width: float,
    label_width: float,
    content_width: float,
    final_width: float,
) -> None
Attributes

VSkip [source]

class VSkip

Zero-space node for QInit, Cast, or zero-iteration loops.

Constructor
def __init__(self, node_key: tuple = ()) -> None
Attributes

VUnfoldedKind [source]

class VUnfoldedKind(enum.Enum)

Classification of unfolded control-flow sequences.

Attributes

VUnfoldedSequence [source]

class VUnfoldedSequence

Unfolded control-flow sequence (For/ForItems/If).

For loops: iterations[i] = children of iteration i. For if: iterations[0] = true branch, iterations[1] = false branch (if exists).

Constructor
def __init__(
    self,
    node_key: tuple,
    iterations: list[list[VisualNode]],
    affected_qubits: list[int],
    kind: VUnfoldedKind,
    iteration_widths: list[float] = list(),
    condition_label: str | None = None,
    affected_qubits_precise: bool = True,
    condition_label_width: float = 0.0,
    branch_label_widths: list[float] = list(),
    condition_measure_node_key: tuple | None = None,
    condition_measure_qubit_indices: list[int] = list(),
) -> None
Attributes

Value [source]

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

A typed SSA value in the IR.

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

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

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

Create a new Value with incremented version and fresh UUID.

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


ValueBase [source]

class ValueBase

Nominal base for every typed IR value.

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

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

Return the scalar constant carried by this value.

Returns:

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

is_constant
def is_constant(self) -> bool

Return whether this value carries a scalar constant.

Returns:

bool — Whether scalar constant metadata is present.

is_parameter
def is_parameter(self) -> bool

Return whether this value represents a runtime parameter.

Returns:

bool — Whether parameter metadata is present.

next_version
def next_version(self) -> ValueBase

Create the next SSA version of this value.

Returns:

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

parameter_name
def parameter_name(self) -> str | None

Return the public parameter name carried by this value.

Returns:

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


VisualCircuit [source]

class VisualCircuit

Root container for the Visual IR tree.

Carries the node tree plus qubit mapping information needed by Layout and Renderer.

Constructor
def __init__(
    self,
    children: list[VisualNode],
    qubit_map: dict[str, int],
    qubit_names: dict[int, str],
    num_qubits: int,
    output_names: list[str] = list(),
) -> None
Attributes

WhileOperation [source]

class WhileOperation(HasNestedOps, Operation)

Represents a while loop operation.

Only measurement-backed conditions are supported: the condition must be a Bit value produced by qmc.measure(). Non-measurement conditions (classical variables, constants, comparisons) are rejected by ValidateWhileContractPass before reaching 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, ...] = (),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]

Include rebind records and region args for cloning/substitution.

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

Returns:

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

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

Return the while body with explicit boundary values.

Returns:

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

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

Rebuild the while body and its complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt while operation.

Raises:

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

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

Parameters:

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

Returns:

Operation — The rewritten operation.


qamomile.circuit.visualization.drawer

Matplotlib-based circuit visualization.

This module provides the MatplotlibDrawer facade that orchestrates circuit analysis, layout computation, and rendering.

Overview

ClassDescription
BlockUnified block representation for all pipeline stages.
BlockKindClassification of block structure for pipeline stages.
CircuitAnalyzerAnalyzes IR blocks for circuit visualization.
CircuitLayoutEngineComputes layout coordinates for circuit visualization.
CircuitStyleStyle configuration for circuit visualization.
MatplotlibDrawerMatplotlib-based circuit drawer with Qiskit-style layout.
MatplotlibRendererRenders circuit diagrams using matplotlib.

Classes

Block [source]

class Block

Unified block representation for all pipeline stages.

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

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

Create an inline callable invocation against this block.

Parameters:

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

Returns:

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

Raises:

is_affine
def is_affine(self) -> bool

Return whether this block has passed affine validation.

Returns:

bool — True for AFFINE and ANALYZED blocks.

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

Return list of unbound parameter names.


BlockKind [source]

class BlockKind(Enum)

Classification of block structure for pipeline stages.

Attributes

CircuitAnalyzer [source]

class CircuitAnalyzer

Analyzes IR blocks for circuit visualization.

Handles qubit mapping, value resolution, label generation, and width estimation. Has no matplotlib dependency.

Constructor
def __init__(
    self,
    graph: 'Block',
    style: CircuitStyle,
    inline: bool = False,
    fold_loops: bool = True,
    expand_composite: bool = False,
    inline_depth: int | None = None,
    fold_ifs: bool = False,
)

Initialize the visualization analyzer.

Parameters:

NameTypeDescription
graphBlockComputation graph to analyze for rendering.
styleCircuitStyleVisual style configuration.
inlineboolWhether to expand inline callable contents.
fold_loopsboolWhether to render loop operations as folded summary blocks instead of materialized iterations.
expand_compositeboolWhether to expand composite gates.
inline_depthint | NoneMaximum nesting depth for inline expansion, or None for unlimited depth.
fold_ifsboolWhether to render IfOperation nodes as folded summary blocks instead of side-by-side branches.
Attributes
Methods
build_qubit_map
def build_qubit_map(self, graph: 'Block') -> tuple[dict[str, int], dict[int, str], int]

Build mapping from qubit logical_id to wire indices.

In SSA form, each operation creates new Values via next_version(), which preserves logical_id. This means all versions of a qubit share the same logical_id, so we only need logical_id-based tracking.

Parameters:

NameTypeDescription
graphBlockComputation block.

Returns:

dict[str, int] — tuple[dict[str, int], dict[int, str], int]: Logical-ID-to-wire dict[int, str] — mapping, display names by wire index, and total wire count.

build_visual_ir
def build_visual_ir(
    self,
    graph: 'Block',
    qubit_map: dict[str, int],
    qubit_names: dict[int, str],
    num_qubits: int,
) -> VisualCircuit

Build a Visual IR tree from the IR block.

Walks all operations, resolving labels, qubit indices, and widths into pre-computed VisualNode dataclasses. The resulting VisualCircuit can be consumed by Layout and Renderer without any Analyzer access.

Parameters:

NameTypeDescription
graph'Block'IR computation block.
qubit_mapdict[str, int]Mapping from logical_id to wire index.
qubit_namesdict[int, str]Mapping from wire index to display name.
num_qubitsintTotal number of qubit wires.

Returns:

VisualCircuit — VisualCircuit containing the VisualNode tree.


CircuitLayoutEngine [source]

class CircuitLayoutEngine

Computes layout coordinates for circuit visualization.

Takes a VisualCircuit (pre-resolved Visual IR tree) and assigns x/y coordinates to each node. No Measure Phase is needed since widths are already computed in the Visual IR nodes.

Has no matplotlib dependency.

Constructor
def __init__(self, style: CircuitStyle)
Attributes
Methods
compute_layout
def compute_layout(self, vc: VisualCircuit) -> LayoutResult

Compute layout from a VisualCircuit.

Uses the Visual IR tree which carries all pre-resolved information (labels, qubit indices, widths). No Measure Phase is needed since widths are already computed in the Visual IR nodes.

Parameters:

NameTypeDescription
vcVisualCircuitVisualCircuit containing pre-resolved Visual IR nodes.

Returns:

LayoutResult — LayoutResult with all computed positions and sizing.


CircuitStyle [source]

class CircuitStyle

Style configuration for circuit visualization.

Constructor
def __init__(
    self,
    gate_width: float = 0.65,
    gate_height: float = 0.65,
    gate_corner_radius: float = 0.2,
    background_color: str = '#FFFFFF',
    wire_color: str = '#000000',
    gate_face_color: str = '#E8B878',
    gate_symbol_color: str = '#E8B878',
    gate_symbol_edge_color: str = '#000000',
    gate_text_color: str = '#000000',
    connection_line_color: str = '#000000',
    block_face_color: str = '#5B7F61',
    block_text_color: str = '#FFFFFF',
    block_border_color: str = '#4A6B50',
    block_box_edge_color: str = '#4A6B50',
    measure_face_color: str = '#D5CCC4',
    measure_symbol_color: str = '#6B5F55',
    for_loop_face_color: str = '#F0E4D0',
    for_loop_text_color: str = '#000000',
    for_loop_edge_color: str = '#C4A882',
    while_loop_face_color: str = '#E0D4F0',
    while_loop_text_color: str = '#000000',
    while_loop_edge_color: str = '#A88BC8',
    for_items_face_color: str = '#D0E8D0',
    for_items_text_color: str = '#000000',
    for_items_edge_color: str = '#90B890',
    if_face_color: str = '#F0D8D0',
    if_text_color: str = '#000000',
    if_edge_color: str = '#C8A898',
    expval_face_color: str = '#D4E8F0',
    expval_text_color: str = '#000000',
    expval_edge_color: str = '#8AB4C8',
    font_size: int = 13,
    subfont_size: int = 10,
    param_font_size: int = 9,
    margin: tuple[float, float, float, float] = (0.5, 0.1, 0.1, 0.3),
    gate_gap: float = 0.3,
    char_width_base: float = 0.12,
    char_width_bold: float = 0.14,
    char_width_gate: float = 0.14,
    char_width_block: float = 0.17,
    char_width_monospace: float = 0.17,
    text_padding: float = 0.25,
    border_padding_base: float = 0.3,
    border_padding_depth_factor: float = 0.1,
    min_left_margin: float = 0.3,
    label_height: float = 0.35,
    box_padding_x: float = 0.3,
    box_padding_y: float = 0.2,
    label_vertical_offset: float = 0.05,
    label_horizontal_padding: float = 0.1,
    initial_wire_position: float = 0.3,
    wire_extension: float = 0.3,
    operation_width_padding: float = 0.4,
    operation_content_padding: float = 0.6,
    line_height: float = 0.4,
    fallback_char_width: float = 0.15,
    fallback_text_height: float = 0.15,
    font_scaling_adjustment: float = 0.85,
    nested_margin: float = 0.15,
    border_extra_margin_right: float = 0.8,
    border_extra_margin_left: float = 0.3,
    folded_loop_width: float = 1.5,
    folded_call_block_width: float = 1.5,
    gate_text_padding: float = 0.1,
    nested_padding_decay: float = 0.85,
    min_block_padding: float = 0.1,
    power_wrapper_margin: float = 0.2,
    folded_box_text_v_padding: float = 0.15,
    max_folded_body_chars: int = 40,
    qubit_base_spacing: float = 1.0,
    qubit_clearance: float = 0.15,
    label_step_gap: float = 0.1,
    overlap_step_gap: float = 0.15,
    label_padding: float = 0.05,
    qubit_y_label_height: float = 0.25,
    figure_scale_factor: float = 0.8,
    figure_min_width: float = 4.0,
    figure_min_height: float = 2.0,
    x_left_min_bound: float = -1.0,
) -> None
Attributes

MatplotlibDrawer [source]

class MatplotlibDrawer

Matplotlib-based circuit drawer with Qiskit-style layout.

This drawer produces static matplotlib figures showing quantum circuits. It supports two modes:

Constructor
def __init__(self, graph: Block, style: CircuitStyle | None = None)

Initialize the drawer.

Parameters:

NameTypeDescription
graphBlockComputation graph to visualize.
styleCircuitStyle | NoneVisual style configuration. Uses DEFAULT_STYLE if None.

Raises:

Attributes
Methods
draw
def draw(
    self,
    inline: bool = False,
    fold_loops: bool = True,
    expand_composite: bool = False,
    inline_depth: int | None = None,
    fold_ifs: bool = False,
) -> Figure

Generate a matplotlib Figure of the circuit.

Parameters:

NameTypeDescription
inlineboolIf True, expand inline callable contents. If False, show calls as boxes.
fold_loopsboolIf True (default), display ForOperation as blocks instead of unrolling. If False, expand loops and show all iterations.
expand_compositeboolIf True, expand boxed InvokeOperation bodies. If False (default), show them as boxes.
inline_depthint | NoneMaximum nesting depth for inline expansion. None means unlimited. Affects inline calls, ControlledU, and boxed InvokeOperation nodes.
fold_ifsboolIf True, display IfOperation as folded summary blocks. If False (default), show if/else branches side by side.

Returns:

Figure — Matplotlib figure object.

draw_kernel
@classmethod
def draw_kernel(
    cls,
    kernel: Any,
    *,
    inline: bool = False,
    fold_loops: bool = True,
    fold_ifs: bool = False,
    expand_composite: bool = False,
    inline_depth: int | None = None,
    style: CircuitStyle | None = None,
    **kwargs: Any = {},
) -> Figure

Draw a QKernel, handling Vector[Qubit] params with integer sizes.

For kernels with Vector[Qubit] parameters, pass an integer to specify the array size (e.g., inputs=3 for a 3-qubit vector).

Parameters:

NameTypeDescription
kernelAnyA QKernel instance to visualize.
inlineboolIf True, expand inline callable contents.
fold_loopsboolIf True (default), display ForOperation as blocks.
fold_ifsboolIf True, display IfOperation as folded summary blocks. If False (default), show if/else branches side by side.
expand_compositeboolIf True, expand boxed InvokeOperation bodies.
inline_depthint | NoneMaximum nesting depth for inline expansion.
styleCircuitStyle | NoneVisual style configuration.
**kwargsAnyConcrete values for kernel arguments. For Vector[Qubit] parameters, pass an integer size.

Returns:

Figure — Matplotlib figure object.


MatplotlibRenderer [source]

class MatplotlibRenderer

Renders circuit diagrams using matplotlib.

Takes pre-computed layout coordinates and draws the circuit using matplotlib primitives.

Parameters:

NameTypeDescription
styleCircuitStyleVisual style configuration used for all drawing primitives.
Constructor
def __init__(self, style: CircuitStyle)
Attributes
Methods
render
def render(self, vc: VisualCircuit, layout: LayoutResult) -> Figure

Render the circuit from a VisualCircuit.

Uses the Visual IR tree which carries all pre-resolved information.

Parameters:

NameTypeDescription
vcVisualCircuitCircuit containing pre-resolved visual nodes.
layoutLayoutResultPre-computed layout coordinates and wire metadata.

Returns:

Figure — Rendered matplotlib figure.

Raises:


qamomile.circuit.visualization.geometry

Pure geometry utilities for circuit visualization.

Standalone functions for computing border padding and block box bounds, shared by Layout and Renderer without requiring Analyzer.

Overview

FunctionDescription
compute_block_box_boundsCompute outermost (box_left, box_right) for an inlined block border.
compute_border_paddingCompute border padding for a given nesting depth.
compute_nested_block_box_boundsCompute (inner_bounds, outer_bounds) for an inlined block border.
ClassDescription
CircuitStyleStyle configuration for circuit visualization.

Functions

compute_block_box_bounds [source]

def compute_block_box_bounds(
    style: CircuitStyle,
    name: str,
    start_x: float,
    end_x: float,
    depth: int,
    max_gate_width: float,
    power: int = 1,
) -> tuple[float, float]

Compute outermost (box_left, box_right) for an inlined block border.

Label expansion is right-only: box_left is always gate-based, box_right expands rightward if the label text needs more space.

Parameters:

NameTypeDescription
styleCircuitStyleVisual style configuration.
namestrBlock label text.
start_xfloatX position of the first gate in the block.
end_xfloatX position of the last gate in the block.
depthintNesting depth of the block.
max_gate_widthfloatWidth of the widest gate in the block.
powerintPower annotation value (displayed as “pow=N” when > 1).

Returns:

tuple[float, float] — Tuple of (box_left, box_right).


compute_border_padding [source]

def compute_border_padding(style: CircuitStyle, depth: int) -> float

Compute border padding for a given nesting depth.

Parameters:

NameTypeDescription
styleCircuitStyleVisual style configuration.
depthintNesting depth of the block.

Returns:

float — Border padding value, clamped to min_block_padding.


compute_nested_block_box_bounds [source]

def compute_nested_block_box_bounds(
    style: CircuitStyle,
    name: str,
    start_x: float,
    end_x: float,
    depth: int,
    max_gate_width: float,
    power: int = 1,
) -> tuple[tuple[float, float], tuple[float, float]]

Compute (inner_bounds, outer_bounds) for an inlined block border.

When power <= 1, inner_bounds == outer_bounds (no wrapper). When power > 1, outer_bounds expand by power_wrapper_margin and account for the “pow=N” label width.

Parameters:

NameTypeDescription
styleCircuitStyleVisual style configuration.
namestrBlock label text.
start_xfloatX position of the first gate in the block.
end_xfloatX position of the last gate in the block.
depthintNesting depth of the block.
max_gate_widthfloatWidth of the widest gate in the block.
powerintPower annotation value (displayed as “pow=N” when > 1).

Returns:

tuple[tuple[float, float], tuple[float, float]] — Tuple of ((inner_left, inner_right), (outer_left, outer_right)).

Classes

CircuitStyle [source]

class CircuitStyle

Style configuration for circuit visualization.

Constructor
def __init__(
    self,
    gate_width: float = 0.65,
    gate_height: float = 0.65,
    gate_corner_radius: float = 0.2,
    background_color: str = '#FFFFFF',
    wire_color: str = '#000000',
    gate_face_color: str = '#E8B878',
    gate_symbol_color: str = '#E8B878',
    gate_symbol_edge_color: str = '#000000',
    gate_text_color: str = '#000000',
    connection_line_color: str = '#000000',
    block_face_color: str = '#5B7F61',
    block_text_color: str = '#FFFFFF',
    block_border_color: str = '#4A6B50',
    block_box_edge_color: str = '#4A6B50',
    measure_face_color: str = '#D5CCC4',
    measure_symbol_color: str = '#6B5F55',
    for_loop_face_color: str = '#F0E4D0',
    for_loop_text_color: str = '#000000',
    for_loop_edge_color: str = '#C4A882',
    while_loop_face_color: str = '#E0D4F0',
    while_loop_text_color: str = '#000000',
    while_loop_edge_color: str = '#A88BC8',
    for_items_face_color: str = '#D0E8D0',
    for_items_text_color: str = '#000000',
    for_items_edge_color: str = '#90B890',
    if_face_color: str = '#F0D8D0',
    if_text_color: str = '#000000',
    if_edge_color: str = '#C8A898',
    expval_face_color: str = '#D4E8F0',
    expval_text_color: str = '#000000',
    expval_edge_color: str = '#8AB4C8',
    font_size: int = 13,
    subfont_size: int = 10,
    param_font_size: int = 9,
    margin: tuple[float, float, float, float] = (0.5, 0.1, 0.1, 0.3),
    gate_gap: float = 0.3,
    char_width_base: float = 0.12,
    char_width_bold: float = 0.14,
    char_width_gate: float = 0.14,
    char_width_block: float = 0.17,
    char_width_monospace: float = 0.17,
    text_padding: float = 0.25,
    border_padding_base: float = 0.3,
    border_padding_depth_factor: float = 0.1,
    min_left_margin: float = 0.3,
    label_height: float = 0.35,
    box_padding_x: float = 0.3,
    box_padding_y: float = 0.2,
    label_vertical_offset: float = 0.05,
    label_horizontal_padding: float = 0.1,
    initial_wire_position: float = 0.3,
    wire_extension: float = 0.3,
    operation_width_padding: float = 0.4,
    operation_content_padding: float = 0.6,
    line_height: float = 0.4,
    fallback_char_width: float = 0.15,
    fallback_text_height: float = 0.15,
    font_scaling_adjustment: float = 0.85,
    nested_margin: float = 0.15,
    border_extra_margin_right: float = 0.8,
    border_extra_margin_left: float = 0.3,
    folded_loop_width: float = 1.5,
    folded_call_block_width: float = 1.5,
    gate_text_padding: float = 0.1,
    nested_padding_decay: float = 0.85,
    min_block_padding: float = 0.1,
    power_wrapper_margin: float = 0.2,
    folded_box_text_v_padding: float = 0.15,
    max_folded_body_chars: int = 40,
    qubit_base_spacing: float = 1.0,
    qubit_clearance: float = 0.15,
    label_step_gap: float = 0.1,
    overlap_step_gap: float = 0.15,
    label_padding: float = 0.05,
    qubit_y_label_height: float = 0.25,
    figure_scale_factor: float = 0.8,
    figure_min_width: float = 4.0,
    figure_min_height: float = 2.0,
    x_left_min_bound: float = -1.0,
) -> None
Attributes

qamomile.circuit.visualization.layout

Circuit layout engine: coordinate computation from Visual IR.

This module provides CircuitLayoutEngine, which assigns x/y coordinates to pre-resolved Visual IR nodes. It has no matplotlib dependency.

Overview

FunctionDescription
compute_block_box_boundsCompute outermost (box_left, box_right) for an inlined block border.
compute_border_paddingCompute border padding for a given nesting depth.
ClassDescription
CircuitLayoutEngineComputes layout coordinates for circuit visualization.
CircuitStyleStyle configuration for circuit visualization.
LayoutResultResult of the layout computation.
LayoutStateMutable state shared across layout handler methods.
VFoldedBlockFolded control-flow block (For/While/ForItems/If).
VGateRepresent a pre-resolved gate, annotation, measurement, or block node.
VGateKindClassification of VGate nodes for rendering dispatch.
VInlineBlockRepresent an inlined callable or controlled body with a visible border.
VSkipZero-space node for QInit, Cast, or zero-iteration loops.
VUnfoldedKindClassification of unfolded control-flow sequences.
VUnfoldedSequenceUnfolded control-flow sequence (For/ForItems/If).
VisualCircuitRoot container for the Visual IR tree.

Functions

compute_block_box_bounds [source]

def compute_block_box_bounds(
    style: CircuitStyle,
    name: str,
    start_x: float,
    end_x: float,
    depth: int,
    max_gate_width: float,
    power: int = 1,
) -> tuple[float, float]

Compute outermost (box_left, box_right) for an inlined block border.

Label expansion is right-only: box_left is always gate-based, box_right expands rightward if the label text needs more space.

Parameters:

NameTypeDescription
styleCircuitStyleVisual style configuration.
namestrBlock label text.
start_xfloatX position of the first gate in the block.
end_xfloatX position of the last gate in the block.
depthintNesting depth of the block.
max_gate_widthfloatWidth of the widest gate in the block.
powerintPower annotation value (displayed as “pow=N” when > 1).

Returns:

tuple[float, float] — Tuple of (box_left, box_right).


compute_border_padding [source]

def compute_border_padding(style: CircuitStyle, depth: int) -> float

Compute border padding for a given nesting depth.

Parameters:

NameTypeDescription
styleCircuitStyleVisual style configuration.
depthintNesting depth of the block.

Returns:

float — Border padding value, clamped to min_block_padding.

Classes

CircuitLayoutEngine [source]

class CircuitLayoutEngine

Computes layout coordinates for circuit visualization.

Takes a VisualCircuit (pre-resolved Visual IR tree) and assigns x/y coordinates to each node. No Measure Phase is needed since widths are already computed in the Visual IR nodes.

Has no matplotlib dependency.

Constructor
def __init__(self, style: CircuitStyle)
Attributes
Methods
compute_layout
def compute_layout(self, vc: VisualCircuit) -> LayoutResult

Compute layout from a VisualCircuit.

Uses the Visual IR tree which carries all pre-resolved information (labels, qubit indices, widths). No Measure Phase is needed since widths are already computed in the Visual IR nodes.

Parameters:

NameTypeDescription
vcVisualCircuitVisualCircuit containing pre-resolved Visual IR nodes.

Returns:

LayoutResult — LayoutResult with all computed positions and sizing.


CircuitStyle [source]

class CircuitStyle

Style configuration for circuit visualization.

Constructor
def __init__(
    self,
    gate_width: float = 0.65,
    gate_height: float = 0.65,
    gate_corner_radius: float = 0.2,
    background_color: str = '#FFFFFF',
    wire_color: str = '#000000',
    gate_face_color: str = '#E8B878',
    gate_symbol_color: str = '#E8B878',
    gate_symbol_edge_color: str = '#000000',
    gate_text_color: str = '#000000',
    connection_line_color: str = '#000000',
    block_face_color: str = '#5B7F61',
    block_text_color: str = '#FFFFFF',
    block_border_color: str = '#4A6B50',
    block_box_edge_color: str = '#4A6B50',
    measure_face_color: str = '#D5CCC4',
    measure_symbol_color: str = '#6B5F55',
    for_loop_face_color: str = '#F0E4D0',
    for_loop_text_color: str = '#000000',
    for_loop_edge_color: str = '#C4A882',
    while_loop_face_color: str = '#E0D4F0',
    while_loop_text_color: str = '#000000',
    while_loop_edge_color: str = '#A88BC8',
    for_items_face_color: str = '#D0E8D0',
    for_items_text_color: str = '#000000',
    for_items_edge_color: str = '#90B890',
    if_face_color: str = '#F0D8D0',
    if_text_color: str = '#000000',
    if_edge_color: str = '#C8A898',
    expval_face_color: str = '#D4E8F0',
    expval_text_color: str = '#000000',
    expval_edge_color: str = '#8AB4C8',
    font_size: int = 13,
    subfont_size: int = 10,
    param_font_size: int = 9,
    margin: tuple[float, float, float, float] = (0.5, 0.1, 0.1, 0.3),
    gate_gap: float = 0.3,
    char_width_base: float = 0.12,
    char_width_bold: float = 0.14,
    char_width_gate: float = 0.14,
    char_width_block: float = 0.17,
    char_width_monospace: float = 0.17,
    text_padding: float = 0.25,
    border_padding_base: float = 0.3,
    border_padding_depth_factor: float = 0.1,
    min_left_margin: float = 0.3,
    label_height: float = 0.35,
    box_padding_x: float = 0.3,
    box_padding_y: float = 0.2,
    label_vertical_offset: float = 0.05,
    label_horizontal_padding: float = 0.1,
    initial_wire_position: float = 0.3,
    wire_extension: float = 0.3,
    operation_width_padding: float = 0.4,
    operation_content_padding: float = 0.6,
    line_height: float = 0.4,
    fallback_char_width: float = 0.15,
    fallback_text_height: float = 0.15,
    font_scaling_adjustment: float = 0.85,
    nested_margin: float = 0.15,
    border_extra_margin_right: float = 0.8,
    border_extra_margin_left: float = 0.3,
    folded_loop_width: float = 1.5,
    folded_call_block_width: float = 1.5,
    gate_text_padding: float = 0.1,
    nested_padding_decay: float = 0.85,
    min_block_padding: float = 0.1,
    power_wrapper_margin: float = 0.2,
    folded_box_text_v_padding: float = 0.15,
    max_folded_body_chars: int = 40,
    qubit_base_spacing: float = 1.0,
    qubit_clearance: float = 0.15,
    label_step_gap: float = 0.1,
    overlap_step_gap: float = 0.15,
    label_padding: float = 0.05,
    qubit_y_label_height: float = 0.25,
    figure_scale_factor: float = 0.8,
    figure_min_width: float = 4.0,
    figure_min_height: float = 2.0,
    x_left_min_bound: float = -1.0,
) -> None
Attributes

LayoutResult [source]

class LayoutResult

Result of the layout computation.

Constructor
def __init__(
    self,
    width: float,
    positions: dict[tuple, float],
    block_ranges: list[dict],
    max_depth: int,
    block_widths: dict[tuple, float],
    actual_width: float,
    first_gate_x: float,
    first_gate_half_width: float,
    qubit_y: list[float] = list(),
    qubit_end_positions: dict[int, float] = dict(),
    inlined_op_keys: set[tuple] = set(),
    gate_widths: dict[tuple, float] = dict(),
    folded_block_extents: dict[tuple, dict] = dict(),
    max_above: dict[int, float] = dict(),
    max_below: dict[int, float] = dict(),
) -> None
Attributes

LayoutState [source]

class LayoutState

Mutable state shared across layout handler methods.

Constructor
def __init__(
    self,
    positions: dict[tuple, float] = dict(),
    block_ranges: list[dict] = list(),
    block_widths: dict[tuple, float] = dict(),
    column: float = 1.0,
    max_depth: int = 0,
    actual_width: float = 1.0,
    first_gate_x: float | None = None,
    first_gate_half_width: float = 0.0,
    qubit_columns: dict[int, float] = _default_qubit_columns(),
    qubit_right_edges: dict[int, float] = dict(),
    qubit_end_positions: dict[int, float] = dict(),
    inlined_op_keys: set[tuple] = set(),
    gate_widths: dict[tuple, float] = dict(),
    folded_block_extents: dict[tuple, dict] = dict(),
    label_extents: list[dict] = list(),
) -> None
Attributes

VFoldedBlock [source]

class VFoldedBlock

Folded control-flow block (For/While/ForItems/If).

Rendered as a single box with header label and body summary text.

affected_qubits_precise is True when the analyzer determined the affected-qubit set from a precise iteration walk with all operands resolved; False when the conservative fallback was used and the set may over-approximate. Renderers use this to decide whether to mark participating wires with dots.

Constructor
def __init__(
    self,
    node_key: tuple,
    header_label: str,
    body_lines: list[str],
    affected_qubits: list[int],
    folded_width: float,
    kind: VFoldedKind,
    affected_qubits_precise: bool = True,
    condition_measure_node_key: tuple | None = None,
    condition_measure_qubit_indices: list[int] = list(),
) -> None
Attributes

VGate [source]

class VGate

Represent a pre-resolved gate, annotation, measurement, or block node.

Carries all information needed for layout and rendering:

For GLOBAL_PHASE, qubit_indices names the quantum scope whose horizontal position must stay synchronized. The renderer draws one floating annotation above the scope’s top wire; it does not draw a gate on any of those wires.

Parameters:

NameTypeDescription
node_keytupleStable identifier used to associate the node with layout coordinates.
labelstrTeX-formatted display label.
qubit_indiceslist[int]Resolved wire indices participating in the node.
estimated_widthfloatWidth reserved for layout.
kindVGateKindRendering strategy for the node.
gate_typeGateOperationType | NonePrimitive gate type used for specialized drawing, or None. Defaults to None.
has_paramboolWhether the displayed gate has a parameter. Defaults to False.
box_widthfloat | NoneExplicit width for block-style nodes, or None. Defaults to None.
control_countintNumber of leading control wires for a controlled block. Defaults to 0.
control_patterntuple[int, ...]Required basis bit for each leading control wire, aligned with qubit_indices. Zero denotes an open control and one denotes a filled control. Defaults to an empty tuple for non-controlled nodes.
powerintExponent displayed for a controlled block. Defaults to 1.
terminates_wireboolWhether a measurement ends its measured wire. Defaults to True.
Constructor
def __init__(
    self,
    node_key: tuple,
    label: str,
    qubit_indices: list[int],
    estimated_width: float,
    kind: VGateKind,
    gate_type: GateOperationType | None = None,
    has_param: bool = False,
    box_width: float | None = None,
    control_count: int = 0,
    control_pattern: tuple[int, ...] = (),
    power: int = 1,
    terminates_wire: bool = True,
) -> None
Attributes

VGateKind [source]

class VGateKind(enum.Enum)

Classification of VGate nodes for rendering dispatch.

Attributes

VInlineBlock [source]

class VInlineBlock

Represent an inlined callable or controlled body with a visible border.

Carries pre-resolved children, affected qubits, and pre-computed widths so that Layout and Renderer need no Analyzer access.

Parameters:

NameTypeDescription
node_keytupleStable identifier used for layout coordinates.
labelstrDisplay label for the inlined body.
childrenlist[VisualNode]Pre-resolved child visual nodes.
affected_qubitslist[int]Every wire occupied by the body.
control_qubit_indiceslist[int]Leading coherent-control wires in flattened operand order.
control_patterntuple[int, ...]Required bit for each control wire; zero denotes an open control and one a filled control.
powerintIntegral application count for controlled bodies.
depthintVisualization nesting depth.
border_paddingfloatPadding around the inlined body border.
max_gate_widthfloatMaximum child gate width.
label_widthfloatWidth required by the body label.
content_widthfloatWidth required by child nodes.
final_widthfloatFinal reserved width including wrappers.
Constructor
def __init__(
    self,
    node_key: tuple,
    label: str,
    children: list[VisualNode],
    affected_qubits: list[int],
    control_qubit_indices: list[int],
    control_pattern: tuple[int, ...],
    power: int,
    depth: int,
    border_padding: float,
    max_gate_width: float,
    label_width: float,
    content_width: float,
    final_width: float,
) -> None
Attributes

VSkip [source]

class VSkip

Zero-space node for QInit, Cast, or zero-iteration loops.

Constructor
def __init__(self, node_key: tuple = ()) -> None
Attributes

VUnfoldedKind [source]

class VUnfoldedKind(enum.Enum)

Classification of unfolded control-flow sequences.

Attributes

VUnfoldedSequence [source]

class VUnfoldedSequence

Unfolded control-flow sequence (For/ForItems/If).

For loops: iterations[i] = children of iteration i. For if: iterations[0] = true branch, iterations[1] = false branch (if exists).

Constructor
def __init__(
    self,
    node_key: tuple,
    iterations: list[list[VisualNode]],
    affected_qubits: list[int],
    kind: VUnfoldedKind,
    iteration_widths: list[float] = list(),
    condition_label: str | None = None,
    affected_qubits_precise: bool = True,
    condition_label_width: float = 0.0,
    branch_label_widths: list[float] = list(),
    condition_measure_node_key: tuple | None = None,
    condition_measure_qubit_indices: list[int] = list(),
) -> None
Attributes

VisualCircuit [source]

class VisualCircuit

Root container for the Visual IR tree.

Carries the node tree plus qubit mapping information needed by Layout and Renderer.

Constructor
def __init__(
    self,
    children: list[VisualNode],
    qubit_map: dict[str, int],
    qubit_names: dict[int, str],
    num_qubits: int,
    output_names: list[str] = list(),
) -> None
Attributes

qamomile.circuit.visualization.renderer

Matplotlib-based circuit rendering.

This module provides MatplotlibRenderer, which handles all matplotlib drawing operations for circuit visualization.

Overview

FunctionDescription
compute_block_box_boundsCompute outermost (box_left, box_right) for an inlined block border.
compute_border_paddingCompute border padding for a given nesting depth.
compute_nested_block_box_boundsCompute (inner_bounds, outer_bounds) for an inlined block border.
ClassDescription
CircuitStyleStyle configuration for circuit visualization.
LayoutResultResult of the layout computation.
MatplotlibRendererRenders circuit diagrams using matplotlib.
VFoldedBlockFolded control-flow block (For/While/ForItems/If).
VFoldedKindClassification of folded control-flow blocks.
VGateRepresent a pre-resolved gate, annotation, measurement, or block node.
VGateKindClassification of VGate nodes for rendering dispatch.
VInlineBlockRepresent an inlined callable or controlled body with a visible border.
VSkipZero-space node for QInit, Cast, or zero-iteration loops.
VUnfoldedKindClassification of unfolded control-flow sequences.
VUnfoldedSequenceUnfolded control-flow sequence (For/ForItems/If).
VisualCircuitRoot container for the Visual IR tree.

Functions

compute_block_box_bounds [source]

def compute_block_box_bounds(
    style: CircuitStyle,
    name: str,
    start_x: float,
    end_x: float,
    depth: int,
    max_gate_width: float,
    power: int = 1,
) -> tuple[float, float]

Compute outermost (box_left, box_right) for an inlined block border.

Label expansion is right-only: box_left is always gate-based, box_right expands rightward if the label text needs more space.

Parameters:

NameTypeDescription
styleCircuitStyleVisual style configuration.
namestrBlock label text.
start_xfloatX position of the first gate in the block.
end_xfloatX position of the last gate in the block.
depthintNesting depth of the block.
max_gate_widthfloatWidth of the widest gate in the block.
powerintPower annotation value (displayed as “pow=N” when > 1).

Returns:

tuple[float, float] — Tuple of (box_left, box_right).


compute_border_padding [source]

def compute_border_padding(style: CircuitStyle, depth: int) -> float

Compute border padding for a given nesting depth.

Parameters:

NameTypeDescription
styleCircuitStyleVisual style configuration.
depthintNesting depth of the block.

Returns:

float — Border padding value, clamped to min_block_padding.


compute_nested_block_box_bounds [source]

def compute_nested_block_box_bounds(
    style: CircuitStyle,
    name: str,
    start_x: float,
    end_x: float,
    depth: int,
    max_gate_width: float,
    power: int = 1,
) -> tuple[tuple[float, float], tuple[float, float]]

Compute (inner_bounds, outer_bounds) for an inlined block border.

When power <= 1, inner_bounds == outer_bounds (no wrapper). When power > 1, outer_bounds expand by power_wrapper_margin and account for the “pow=N” label width.

Parameters:

NameTypeDescription
styleCircuitStyleVisual style configuration.
namestrBlock label text.
start_xfloatX position of the first gate in the block.
end_xfloatX position of the last gate in the block.
depthintNesting depth of the block.
max_gate_widthfloatWidth of the widest gate in the block.
powerintPower annotation value (displayed as “pow=N” when > 1).

Returns:

tuple[tuple[float, float], tuple[float, float]] — Tuple of ((inner_left, inner_right), (outer_left, outer_right)).

Classes

CircuitStyle [source]

class CircuitStyle

Style configuration for circuit visualization.

Constructor
def __init__(
    self,
    gate_width: float = 0.65,
    gate_height: float = 0.65,
    gate_corner_radius: float = 0.2,
    background_color: str = '#FFFFFF',
    wire_color: str = '#000000',
    gate_face_color: str = '#E8B878',
    gate_symbol_color: str = '#E8B878',
    gate_symbol_edge_color: str = '#000000',
    gate_text_color: str = '#000000',
    connection_line_color: str = '#000000',
    block_face_color: str = '#5B7F61',
    block_text_color: str = '#FFFFFF',
    block_border_color: str = '#4A6B50',
    block_box_edge_color: str = '#4A6B50',
    measure_face_color: str = '#D5CCC4',
    measure_symbol_color: str = '#6B5F55',
    for_loop_face_color: str = '#F0E4D0',
    for_loop_text_color: str = '#000000',
    for_loop_edge_color: str = '#C4A882',
    while_loop_face_color: str = '#E0D4F0',
    while_loop_text_color: str = '#000000',
    while_loop_edge_color: str = '#A88BC8',
    for_items_face_color: str = '#D0E8D0',
    for_items_text_color: str = '#000000',
    for_items_edge_color: str = '#90B890',
    if_face_color: str = '#F0D8D0',
    if_text_color: str = '#000000',
    if_edge_color: str = '#C8A898',
    expval_face_color: str = '#D4E8F0',
    expval_text_color: str = '#000000',
    expval_edge_color: str = '#8AB4C8',
    font_size: int = 13,
    subfont_size: int = 10,
    param_font_size: int = 9,
    margin: tuple[float, float, float, float] = (0.5, 0.1, 0.1, 0.3),
    gate_gap: float = 0.3,
    char_width_base: float = 0.12,
    char_width_bold: float = 0.14,
    char_width_gate: float = 0.14,
    char_width_block: float = 0.17,
    char_width_monospace: float = 0.17,
    text_padding: float = 0.25,
    border_padding_base: float = 0.3,
    border_padding_depth_factor: float = 0.1,
    min_left_margin: float = 0.3,
    label_height: float = 0.35,
    box_padding_x: float = 0.3,
    box_padding_y: float = 0.2,
    label_vertical_offset: float = 0.05,
    label_horizontal_padding: float = 0.1,
    initial_wire_position: float = 0.3,
    wire_extension: float = 0.3,
    operation_width_padding: float = 0.4,
    operation_content_padding: float = 0.6,
    line_height: float = 0.4,
    fallback_char_width: float = 0.15,
    fallback_text_height: float = 0.15,
    font_scaling_adjustment: float = 0.85,
    nested_margin: float = 0.15,
    border_extra_margin_right: float = 0.8,
    border_extra_margin_left: float = 0.3,
    folded_loop_width: float = 1.5,
    folded_call_block_width: float = 1.5,
    gate_text_padding: float = 0.1,
    nested_padding_decay: float = 0.85,
    min_block_padding: float = 0.1,
    power_wrapper_margin: float = 0.2,
    folded_box_text_v_padding: float = 0.15,
    max_folded_body_chars: int = 40,
    qubit_base_spacing: float = 1.0,
    qubit_clearance: float = 0.15,
    label_step_gap: float = 0.1,
    overlap_step_gap: float = 0.15,
    label_padding: float = 0.05,
    qubit_y_label_height: float = 0.25,
    figure_scale_factor: float = 0.8,
    figure_min_width: float = 4.0,
    figure_min_height: float = 2.0,
    x_left_min_bound: float = -1.0,
) -> None
Attributes

LayoutResult [source]

class LayoutResult

Result of the layout computation.

Constructor
def __init__(
    self,
    width: float,
    positions: dict[tuple, float],
    block_ranges: list[dict],
    max_depth: int,
    block_widths: dict[tuple, float],
    actual_width: float,
    first_gate_x: float,
    first_gate_half_width: float,
    qubit_y: list[float] = list(),
    qubit_end_positions: dict[int, float] = dict(),
    inlined_op_keys: set[tuple] = set(),
    gate_widths: dict[tuple, float] = dict(),
    folded_block_extents: dict[tuple, dict] = dict(),
    max_above: dict[int, float] = dict(),
    max_below: dict[int, float] = dict(),
) -> None
Attributes

MatplotlibRenderer [source]

class MatplotlibRenderer

Renders circuit diagrams using matplotlib.

Takes pre-computed layout coordinates and draws the circuit using matplotlib primitives.

Parameters:

NameTypeDescription
styleCircuitStyleVisual style configuration used for all drawing primitives.
Constructor
def __init__(self, style: CircuitStyle)
Attributes
Methods
render
def render(self, vc: VisualCircuit, layout: LayoutResult) -> Figure

Render the circuit from a VisualCircuit.

Uses the Visual IR tree which carries all pre-resolved information.

Parameters:

NameTypeDescription
vcVisualCircuitCircuit containing pre-resolved visual nodes.
layoutLayoutResultPre-computed layout coordinates and wire metadata.

Returns:

Figure — Rendered matplotlib figure.

Raises:


VFoldedBlock [source]

class VFoldedBlock

Folded control-flow block (For/While/ForItems/If).

Rendered as a single box with header label and body summary text.

affected_qubits_precise is True when the analyzer determined the affected-qubit set from a precise iteration walk with all operands resolved; False when the conservative fallback was used and the set may over-approximate. Renderers use this to decide whether to mark participating wires with dots.

Constructor
def __init__(
    self,
    node_key: tuple,
    header_label: str,
    body_lines: list[str],
    affected_qubits: list[int],
    folded_width: float,
    kind: VFoldedKind,
    affected_qubits_precise: bool = True,
    condition_measure_node_key: tuple | None = None,
    condition_measure_qubit_indices: list[int] = list(),
) -> None
Attributes

VFoldedKind [source]

class VFoldedKind(enum.Enum)

Classification of folded control-flow blocks.

Attributes

VGate [source]

class VGate

Represent a pre-resolved gate, annotation, measurement, or block node.

Carries all information needed for layout and rendering:

For GLOBAL_PHASE, qubit_indices names the quantum scope whose horizontal position must stay synchronized. The renderer draws one floating annotation above the scope’s top wire; it does not draw a gate on any of those wires.

Parameters:

NameTypeDescription
node_keytupleStable identifier used to associate the node with layout coordinates.
labelstrTeX-formatted display label.
qubit_indiceslist[int]Resolved wire indices participating in the node.
estimated_widthfloatWidth reserved for layout.
kindVGateKindRendering strategy for the node.
gate_typeGateOperationType | NonePrimitive gate type used for specialized drawing, or None. Defaults to None.
has_paramboolWhether the displayed gate has a parameter. Defaults to False.
box_widthfloat | NoneExplicit width for block-style nodes, or None. Defaults to None.
control_countintNumber of leading control wires for a controlled block. Defaults to 0.
control_patterntuple[int, ...]Required basis bit for each leading control wire, aligned with qubit_indices. Zero denotes an open control and one denotes a filled control. Defaults to an empty tuple for non-controlled nodes.
powerintExponent displayed for a controlled block. Defaults to 1.
terminates_wireboolWhether a measurement ends its measured wire. Defaults to True.
Constructor
def __init__(
    self,
    node_key: tuple,
    label: str,
    qubit_indices: list[int],
    estimated_width: float,
    kind: VGateKind,
    gate_type: GateOperationType | None = None,
    has_param: bool = False,
    box_width: float | None = None,
    control_count: int = 0,
    control_pattern: tuple[int, ...] = (),
    power: int = 1,
    terminates_wire: bool = True,
) -> None
Attributes

VGateKind [source]

class VGateKind(enum.Enum)

Classification of VGate nodes for rendering dispatch.

Attributes

VInlineBlock [source]

class VInlineBlock

Represent an inlined callable or controlled body with a visible border.

Carries pre-resolved children, affected qubits, and pre-computed widths so that Layout and Renderer need no Analyzer access.

Parameters:

NameTypeDescription
node_keytupleStable identifier used for layout coordinates.
labelstrDisplay label for the inlined body.
childrenlist[VisualNode]Pre-resolved child visual nodes.
affected_qubitslist[int]Every wire occupied by the body.
control_qubit_indiceslist[int]Leading coherent-control wires in flattened operand order.
control_patterntuple[int, ...]Required bit for each control wire; zero denotes an open control and one a filled control.
powerintIntegral application count for controlled bodies.
depthintVisualization nesting depth.
border_paddingfloatPadding around the inlined body border.
max_gate_widthfloatMaximum child gate width.
label_widthfloatWidth required by the body label.
content_widthfloatWidth required by child nodes.
final_widthfloatFinal reserved width including wrappers.
Constructor
def __init__(
    self,
    node_key: tuple,
    label: str,
    children: list[VisualNode],
    affected_qubits: list[int],
    control_qubit_indices: list[int],
    control_pattern: tuple[int, ...],
    power: int,
    depth: int,
    border_padding: float,
    max_gate_width: float,
    label_width: float,
    content_width: float,
    final_width: float,
) -> None
Attributes

VSkip [source]

class VSkip

Zero-space node for QInit, Cast, or zero-iteration loops.

Constructor
def __init__(self, node_key: tuple = ()) -> None
Attributes

VUnfoldedKind [source]

class VUnfoldedKind(enum.Enum)

Classification of unfolded control-flow sequences.

Attributes

VUnfoldedSequence [source]

class VUnfoldedSequence

Unfolded control-flow sequence (For/ForItems/If).

For loops: iterations[i] = children of iteration i. For if: iterations[0] = true branch, iterations[1] = false branch (if exists).

Constructor
def __init__(
    self,
    node_key: tuple,
    iterations: list[list[VisualNode]],
    affected_qubits: list[int],
    kind: VUnfoldedKind,
    iteration_widths: list[float] = list(),
    condition_label: str | None = None,
    affected_qubits_precise: bool = True,
    condition_label_width: float = 0.0,
    branch_label_widths: list[float] = list(),
    condition_measure_node_key: tuple | None = None,
    condition_measure_qubit_indices: list[int] = list(),
) -> None
Attributes

VisualCircuit [source]

class VisualCircuit

Root container for the Visual IR tree.

Carries the node tree plus qubit mapping information needed by Layout and Renderer.

Constructor
def __init__(
    self,
    children: list[VisualNode],
    qubit_map: dict[str, int],
    qubit_names: dict[int, str],
    num_qubits: int,
    output_names: list[str] = list(),
) -> None
Attributes

qamomile.circuit.visualization.style

Circuit visualization style configuration.

This module provides style configuration for circuit drawings, inspired by Qiskit’s matplotlib drawer styling approach.

Overview

ClassDescription
CircuitStyleStyle configuration for circuit visualization.

Classes

CircuitStyle [source]

class CircuitStyle

Style configuration for circuit visualization.

Constructor
def __init__(
    self,
    gate_width: float = 0.65,
    gate_height: float = 0.65,
    gate_corner_radius: float = 0.2,
    background_color: str = '#FFFFFF',
    wire_color: str = '#000000',
    gate_face_color: str = '#E8B878',
    gate_symbol_color: str = '#E8B878',
    gate_symbol_edge_color: str = '#000000',
    gate_text_color: str = '#000000',
    connection_line_color: str = '#000000',
    block_face_color: str = '#5B7F61',
    block_text_color: str = '#FFFFFF',
    block_border_color: str = '#4A6B50',
    block_box_edge_color: str = '#4A6B50',
    measure_face_color: str = '#D5CCC4',
    measure_symbol_color: str = '#6B5F55',
    for_loop_face_color: str = '#F0E4D0',
    for_loop_text_color: str = '#000000',
    for_loop_edge_color: str = '#C4A882',
    while_loop_face_color: str = '#E0D4F0',
    while_loop_text_color: str = '#000000',
    while_loop_edge_color: str = '#A88BC8',
    for_items_face_color: str = '#D0E8D0',
    for_items_text_color: str = '#000000',
    for_items_edge_color: str = '#90B890',
    if_face_color: str = '#F0D8D0',
    if_text_color: str = '#000000',
    if_edge_color: str = '#C8A898',
    expval_face_color: str = '#D4E8F0',
    expval_text_color: str = '#000000',
    expval_edge_color: str = '#8AB4C8',
    font_size: int = 13,
    subfont_size: int = 10,
    param_font_size: int = 9,
    margin: tuple[float, float, float, float] = (0.5, 0.1, 0.1, 0.3),
    gate_gap: float = 0.3,
    char_width_base: float = 0.12,
    char_width_bold: float = 0.14,
    char_width_gate: float = 0.14,
    char_width_block: float = 0.17,
    char_width_monospace: float = 0.17,
    text_padding: float = 0.25,
    border_padding_base: float = 0.3,
    border_padding_depth_factor: float = 0.1,
    min_left_margin: float = 0.3,
    label_height: float = 0.35,
    box_padding_x: float = 0.3,
    box_padding_y: float = 0.2,
    label_vertical_offset: float = 0.05,
    label_horizontal_padding: float = 0.1,
    initial_wire_position: float = 0.3,
    wire_extension: float = 0.3,
    operation_width_padding: float = 0.4,
    operation_content_padding: float = 0.6,
    line_height: float = 0.4,
    fallback_char_width: float = 0.15,
    fallback_text_height: float = 0.15,
    font_scaling_adjustment: float = 0.85,
    nested_margin: float = 0.15,
    border_extra_margin_right: float = 0.8,
    border_extra_margin_left: float = 0.3,
    folded_loop_width: float = 1.5,
    folded_call_block_width: float = 1.5,
    gate_text_padding: float = 0.1,
    nested_padding_decay: float = 0.85,
    min_block_padding: float = 0.1,
    power_wrapper_margin: float = 0.2,
    folded_box_text_v_padding: float = 0.15,
    max_folded_body_chars: int = 40,
    qubit_base_spacing: float = 1.0,
    qubit_clearance: float = 0.15,
    label_step_gap: float = 0.1,
    overlap_step_gap: float = 0.15,
    label_padding: float = 0.05,
    qubit_y_label_height: float = 0.25,
    figure_scale_factor: float = 0.8,
    figure_min_width: float = 4.0,
    figure_min_height: float = 2.0,
    x_left_min_bound: float = -1.0,
) -> None
Attributes

qamomile.circuit.visualization.types

Shared data structures and constants for circuit visualization.

Overview

ClassDescription
LayoutResultResult of the layout computation.
LayoutStateMutable state shared across layout handler methods.

Classes

LayoutResult [source]

class LayoutResult

Result of the layout computation.

Constructor
def __init__(
    self,
    width: float,
    positions: dict[tuple, float],
    block_ranges: list[dict],
    max_depth: int,
    block_widths: dict[tuple, float],
    actual_width: float,
    first_gate_x: float,
    first_gate_half_width: float,
    qubit_y: list[float] = list(),
    qubit_end_positions: dict[int, float] = dict(),
    inlined_op_keys: set[tuple] = set(),
    gate_widths: dict[tuple, float] = dict(),
    folded_block_extents: dict[tuple, dict] = dict(),
    max_above: dict[int, float] = dict(),
    max_below: dict[int, float] = dict(),
) -> None
Attributes

LayoutState [source]

class LayoutState

Mutable state shared across layout handler methods.

Constructor
def __init__(
    self,
    positions: dict[tuple, float] = dict(),
    block_ranges: list[dict] = list(),
    block_widths: dict[tuple, float] = dict(),
    column: float = 1.0,
    max_depth: int = 0,
    actual_width: float = 1.0,
    first_gate_x: float | None = None,
    first_gate_half_width: float = 0.0,
    qubit_columns: dict[int, float] = _default_qubit_columns(),
    qubit_right_edges: dict[int, float] = dict(),
    qubit_end_positions: dict[int, float] = dict(),
    inlined_op_keys: set[tuple] = set(),
    gate_widths: dict[tuple, float] = dict(),
    folded_block_extents: dict[tuple, dict] = dict(),
    label_extents: list[dict] = list(),
) -> None
Attributes

qamomile.circuit.visualization.visual_ir

Visual IR: pre-resolved intermediate representation for circuit visualization.

This module defines the Visual IR node types that carry all resolved information (labels, qubit indices, widths) needed by Layout and Renderer. The Visual IR serves as the decoupling boundary between Analyzer (which understands IR semantics) and Layout/Renderer (which only need pre-resolved visual information).

Overview

ClassDescription
GateOperationType
VFoldedBlockFolded control-flow block (For/While/ForItems/If).
VFoldedKindClassification of folded control-flow blocks.
VGateRepresent a pre-resolved gate, annotation, measurement, or block node.
VGateKindClassification of VGate nodes for rendering dispatch.
VInlineBlockRepresent an inlined callable or controlled body with a visible border.
VSkipZero-space node for QInit, Cast, or zero-iteration loops.
VUnfoldedKindClassification of unfolded control-flow sequences.
VUnfoldedSequenceUnfolded control-flow sequence (For/ForItems/If).
VisualCircuitRoot container for the Visual IR tree.

Classes

GateOperationType [source]

class GateOperationType(enum.Enum)
Attributes

VFoldedBlock [source]

class VFoldedBlock

Folded control-flow block (For/While/ForItems/If).

Rendered as a single box with header label and body summary text.

affected_qubits_precise is True when the analyzer determined the affected-qubit set from a precise iteration walk with all operands resolved; False when the conservative fallback was used and the set may over-approximate. Renderers use this to decide whether to mark participating wires with dots.

Constructor
def __init__(
    self,
    node_key: tuple,
    header_label: str,
    body_lines: list[str],
    affected_qubits: list[int],
    folded_width: float,
    kind: VFoldedKind,
    affected_qubits_precise: bool = True,
    condition_measure_node_key: tuple | None = None,
    condition_measure_qubit_indices: list[int] = list(),
) -> None
Attributes

VFoldedKind [source]

class VFoldedKind(enum.Enum)

Classification of folded control-flow blocks.

Attributes

VGate [source]

class VGate

Represent a pre-resolved gate, annotation, measurement, or block node.

Carries all information needed for layout and rendering:

For GLOBAL_PHASE, qubit_indices names the quantum scope whose horizontal position must stay synchronized. The renderer draws one floating annotation above the scope’s top wire; it does not draw a gate on any of those wires.

Parameters:

NameTypeDescription
node_keytupleStable identifier used to associate the node with layout coordinates.
labelstrTeX-formatted display label.
qubit_indiceslist[int]Resolved wire indices participating in the node.
estimated_widthfloatWidth reserved for layout.
kindVGateKindRendering strategy for the node.
gate_typeGateOperationType | NonePrimitive gate type used for specialized drawing, or None. Defaults to None.
has_paramboolWhether the displayed gate has a parameter. Defaults to False.
box_widthfloat | NoneExplicit width for block-style nodes, or None. Defaults to None.
control_countintNumber of leading control wires for a controlled block. Defaults to 0.
control_patterntuple[int, ...]Required basis bit for each leading control wire, aligned with qubit_indices. Zero denotes an open control and one denotes a filled control. Defaults to an empty tuple for non-controlled nodes.
powerintExponent displayed for a controlled block. Defaults to 1.
terminates_wireboolWhether a measurement ends its measured wire. Defaults to True.
Constructor
def __init__(
    self,
    node_key: tuple,
    label: str,
    qubit_indices: list[int],
    estimated_width: float,
    kind: VGateKind,
    gate_type: GateOperationType | None = None,
    has_param: bool = False,
    box_width: float | None = None,
    control_count: int = 0,
    control_pattern: tuple[int, ...] = (),
    power: int = 1,
    terminates_wire: bool = True,
) -> None
Attributes

VGateKind [source]

class VGateKind(enum.Enum)

Classification of VGate nodes for rendering dispatch.

Attributes

VInlineBlock [source]

class VInlineBlock

Represent an inlined callable or controlled body with a visible border.

Carries pre-resolved children, affected qubits, and pre-computed widths so that Layout and Renderer need no Analyzer access.

Parameters:

NameTypeDescription
node_keytupleStable identifier used for layout coordinates.
labelstrDisplay label for the inlined body.
childrenlist[VisualNode]Pre-resolved child visual nodes.
affected_qubitslist[int]Every wire occupied by the body.
control_qubit_indiceslist[int]Leading coherent-control wires in flattened operand order.
control_patterntuple[int, ...]Required bit for each control wire; zero denotes an open control and one a filled control.
powerintIntegral application count for controlled bodies.
depthintVisualization nesting depth.
border_paddingfloatPadding around the inlined body border.
max_gate_widthfloatMaximum child gate width.
label_widthfloatWidth required by the body label.
content_widthfloatWidth required by child nodes.
final_widthfloatFinal reserved width including wrappers.
Constructor
def __init__(
    self,
    node_key: tuple,
    label: str,
    children: list[VisualNode],
    affected_qubits: list[int],
    control_qubit_indices: list[int],
    control_pattern: tuple[int, ...],
    power: int,
    depth: int,
    border_padding: float,
    max_gate_width: float,
    label_width: float,
    content_width: float,
    final_width: float,
) -> None
Attributes

VSkip [source]

class VSkip

Zero-space node for QInit, Cast, or zero-iteration loops.

Constructor
def __init__(self, node_key: tuple = ()) -> None
Attributes

VUnfoldedKind [source]

class VUnfoldedKind(enum.Enum)

Classification of unfolded control-flow sequences.

Attributes

VUnfoldedSequence [source]

class VUnfoldedSequence

Unfolded control-flow sequence (For/ForItems/If).

For loops: iterations[i] = children of iteration i. For if: iterations[0] = true branch, iterations[1] = false branch (if exists).

Constructor
def __init__(
    self,
    node_key: tuple,
    iterations: list[list[VisualNode]],
    affected_qubits: list[int],
    kind: VUnfoldedKind,
    iteration_widths: list[float] = list(),
    condition_label: str | None = None,
    affected_qubits_precise: bool = True,
    condition_label_width: float = 0.0,
    branch_label_widths: list[float] = list(),
    condition_measure_node_key: tuple | None = None,
    condition_measure_qubit_indices: list[int] = list(),
) -> None
Attributes

VisualCircuit [source]

class VisualCircuit

Root container for the Visual IR tree.

Carries the node tree plus qubit mapping information needed by Layout and Renderer.

Constructor
def __init__(
    self,
    children: list[VisualNode],
    qubit_map: dict[str, int],
    qubit_names: dict[int, str],
    num_qubits: int,
    output_names: list[str] = list(),
) -> None
Attributes