Circuit visualization module.
This module provides static matplotlib-based circuit visualization with a Qiskit-inspired layout style.
Overview¶
| Class | Description |
|---|---|
CircuitStyle | Style configuration for circuit visualization. |
MatplotlibDrawer | Matplotlib-based circuit drawer with Qiskit-style layout. |
Classes¶
CircuitStyle [source]¶
class CircuitStyleStyle 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,
) -> NoneAttributes¶
background_color: strblock_border_color: strblock_box_edge_color: strblock_face_color: strblock_text_color: strborder_extra_margin_left: floatborder_extra_margin_right: floatborder_padding_base: floatborder_padding_depth_factor: floatbox_padding_x: floatbox_padding_y: floatchar_width_base: floatchar_width_block: floatchar_width_bold: floatchar_width_gate: floatchar_width_monospace: floatconnection_line_color: strexpval_edge_color: strexpval_face_color: strexpval_text_color: strfallback_char_width: floatfallback_text_height: floatfigure_min_height: floatfigure_min_width: floatfigure_scale_factor: floatfolded_box_text_v_padding: floatfolded_call_block_width: floatfolded_loop_width: floatfont_scaling_adjustment: floatfont_size: intfor_items_edge_color: strfor_items_face_color: strfor_items_text_color: strfor_loop_edge_color: strfor_loop_face_color: strfor_loop_text_color: strgate_corner_radius: floatgate_face_color: strgate_gap: floatgate_height: floatgate_symbol_color: strgate_symbol_edge_color: strgate_text_color: strgate_text_padding: floatgate_width: floatif_edge_color: strif_face_color: strif_text_color: strinitial_wire_position: floatlabel_height: floatlabel_horizontal_padding: floatlabel_padding: floatlabel_step_gap: floatlabel_vertical_offset: floatline_height: floatmargin: tuple[float, float, float, float]max_folded_body_chars: intmeasure_face_color: strmeasure_symbol_color: strmin_block_padding: floatmin_left_margin: floatnested_margin: floatnested_padding_decay: floatoperation_content_padding: floatoperation_width_padding: floatoverlap_step_gap: floatparam_font_size: intpower_wrapper_margin: floatqubit_base_spacing: floatqubit_clearance: floatqubit_y_label_height: floatsubfont_size: inttext_padding: floatwhile_loop_edge_color: strwhile_loop_face_color: strwhile_loop_text_color: strwire_color: strwire_extension: floatx_left_min_bound: float
MatplotlibDrawer [source]¶
class MatplotlibDrawerMatplotlib-based circuit drawer with Qiskit-style layout.
This drawer produces static matplotlib figures showing quantum circuits. It supports two modes:
Block mode (inline=False): Shows callable invocations as boxes
Inline mode (inline=True): Expands inline callable contents
Constructor¶
def __init__(self, graph: Block, style: CircuitStyle | None = None)Initialize the drawer.
Parameters:
| Name | Type | Description |
|---|---|---|
graph | Block | Computation graph to visualize. |
style | CircuitStyle | None | Visual style configuration. Uses DEFAULT_STYLE if None. |
Raises:
ValidationError— If compile-time if lowering rejectsgraph.ValueError— Ifgraphhas an unknownBlockKind.
Attributes¶
graphstyle
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,
) -> FigureGenerate a matplotlib Figure of the circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
inline | bool | If True, expand inline callable contents. If False, show calls as boxes. |
fold_loops | bool | If True (default), display ForOperation as blocks instead of unrolling. If False, expand loops and show all iterations. |
expand_composite | bool | If True, expand boxed InvokeOperation bodies. If False (default), show them as boxes. |
inline_depth | int | None | Maximum nesting depth for inline expansion. None means unlimited. Affects inline calls, ControlledU, and boxed InvokeOperation nodes. |
fold_ifs | bool | If 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 = {},
) -> FigureDraw 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:
| Name | Type | Description |
|---|---|---|
kernel | Any | A QKernel instance to visualize. |
inline | bool | If True, expand inline callable contents. |
fold_loops | bool | If True (default), display ForOperation as blocks. |
fold_ifs | bool | If True, display IfOperation as folded summary blocks. If False (default), show if/else branches side by side. |
expand_composite | bool | If True, expand boxed InvokeOperation bodies. |
inline_depth | int | None | Maximum nesting depth for inline expansion. |
style | CircuitStyle | None | Visual style configuration. |
**kwargs | Any | Concrete 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¶
| Function | Description |
|---|---|
align_formal_operands | Align split call-site operand pools to formal declaration order. |
compute_border_padding | Compute border padding for a given nesting depth. |
control_pattern_for_value | Return the LSB-first activation pattern for a control value. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
BinOp | Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN). |
BinOpKind | |
Block | Unified block representation for all pipeline stages. |
CallPolicy | Describe the default lowering policy for a callable call. |
CallableBodySelection | Describe one validated IR body selected for an invocation. |
CastOperation | Type cast operation for creating aliases over the same quantum resources. |
CircuitAnalyzer | Analyzes IR blocks for circuit visualization. |
CircuitStyle | Style configuration for circuit visualization. |
CompOp | Comparison operation (EQ, NEQ, LT, LE, GT, GE). |
CompOpKind | |
ConcreteControlledU | Controlled-U with concrete (int) number of controls. |
CondOp | Conditional logical operation (AND, OR). |
CondOpKind | |
ControlledUOperation | Base class for controlled-U operations. |
DictValue | A dictionary value stored as stable ordered entries. |
ExpvalOp | Expectation value operation. |
ForItemsOperation | Represents iteration over dict/iterable items. |
ForOperation | Represents a for loop operation. |
GateOperation | Quantum gate operation. |
GateOperationType | |
GlobalPhaseOperation | Multiply the complete quantum state by exp(i * phase). |
HasNestedOps | Mixin for operations that contain nested operation lists. |
IfOperation | Represents an if-else conditional operation. |
InverseBlockOperation | Represent an inverse qkernel/block as a first-class IR operation. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
MeasureOperation | |
MeasureQFixedOperation | Measure a quantum fixed-point number. |
MeasureVectorOperation | Measure a vector of qubits. |
NotOp | |
QInitOperation | Initialize the qubit |
QubitType | Type representing a quantum bit (qubit). |
ReturnOperation | Explicit return operation marking the end of a block with return values. |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
VFoldedBlock | Folded control-flow block (For/While/ForItems/If). |
VFoldedKind | Classification of folded control-flow blocks. |
VGate | Represent a pre-resolved gate, annotation, measurement, or block node. |
VGateKind | Classification of VGate nodes for rendering dispatch. |
VInlineBlock | Represent an inlined callable or controlled body with a visible border. |
VSkip | Zero-space node for QInit, Cast, or zero-iteration loops. |
VUnfoldedKind | Classification of unfolded control-flow sequences. |
VUnfoldedSequence | Unfolded control-flow sequence (For/ForItems/If). |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
VisualCircuit | Root container for the Visual IR tree. |
WhileOperation | Represents a while loop operation. |
Constants¶
ValueLike:TypeAlias='Value | ArrayValue | TupleValue | DictValue'
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:
| Name | Type | Description |
|---|---|---|
formals | Sequence[ValueBase] | Formal inputs in declaration order. |
quantum_operands | Sequence[ValueBase] | Quantum actual operands in their call-site order. |
parameter_operands | Sequence[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) -> floatCompute border padding for a given nesting depth.
Parameters:
| Name | Type | Description |
|---|---|---|
style | CircuitStyle | Visual style configuration. |
depth | int | Nesting 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:
| Name | Type | Description |
|---|---|---|
control_value | int | None | Required computational-basis value. None means the ordinary all-ones control state. |
num_controls | int | Concrete 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:
TypeError— Ifcontrol_valueis not a PythonintorNone.ValueError— If the width or activation value is invalid.
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,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]BinOp [source]¶
class BinOp(BinaryOperationBase)Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: BinOpKind | None = None,
) -> NoneAttributes¶
kind: BinOpKind | Noneoperation_kind: OperationKindsignature: Signature
BinOpKind [source]¶
class BinOpKind(enum.Enum)Attributes¶
ADDDIVFLOORDIVMINMODMULPOWSUB
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
CallPolicy [source]¶
class CallPolicy(enum.Enum)Describe the default lowering policy for a callable call.
Attributes¶
INLINENATIVE_FIRSTPRESERVE_BOX
CallableBodySelection [source]¶
class CallableBodySelectionDescribe one validated IR body selected for an invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
body | Block | None | Selected IR body, or None when no composable body is available. |
realized_transform | CallTransform | Transform already implemented by body. |
operands | tuple[ValueBase, ...] | Call-site operands corresponding to the selected body’s formal inputs. |
results | tuple[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, ...],
) -> NoneAttributes¶
body: Block | Noneimplements_controls: bool Return whether the selected body includes invocation controls.operands: tuple[ValueBase, ...]realized_transform: CallTransformresults: tuple[ValueBase, ...]
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:
| Name | Type | Description |
|---|---|---|
body_indices | Iterable[int] | Selected-body output positions to map. |
invocation_results | Sequence[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:
Vector[Qubit] -> QFixed (after QPE, for phase measurement)
Vector[Qubit] -> QUInt (for quantum arithmetic)
QUInt -> QFixed (reinterpret bits with different encoding)
QFixed -> QUInt (reinterpret bits with different encoding)
operands: [source_value] - The value being cast results: [cast_result] - The new value with target type (same physical qubits)
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
source_type: ValueType | None = None,
target_type: ValueType | None = None,
qubit_mapping: list[str] = list(),
) -> NoneAttributes¶
num_qubits: int Number of qubits involved in the cast.operation_kind: OperationKind Cast stays in the same segment as its source (QUANTUM for quantum types).qubit_mapping: list[str]signature: Signature Return the type signature of this cast operation.source_type: ValueType | Nonetarget_type: ValueType | None
CircuitAnalyzer [source]¶
class CircuitAnalyzerAnalyzes 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:
| Name | Type | Description |
|---|---|---|
graph | Block | Computation graph to analyze for rendering. |
style | CircuitStyle | Visual style configuration. |
inline | bool | Whether to expand inline callable contents. |
fold_loops | bool | Whether to render loop operations as folded summary blocks instead of materialized iterations. |
expand_composite | bool | Whether to expand composite gates. |
inline_depth | int | None | Maximum nesting depth for inline expansion, or None for unlimited depth. |
fold_ifs | bool | Whether to render IfOperation nodes as folded summary blocks instead of side-by-side branches. |
Attributes¶
expand_compositefold_ifsfold_loopsgraphinlineinline_depthstyle
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:
| Name | Type | Description |
|---|---|---|
graph | Block | Computation 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,
) -> VisualCircuitBuild 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:
| Name | Type | Description |
|---|---|---|
graph | 'Block' | IR computation block. |
qubit_map | dict[str, int] | Mapping from logical_id to wire index. |
qubit_names | dict[int, str] | Mapping from wire index to display name. |
num_qubits | int | Total number of qubit wires. |
Returns:
VisualCircuit — VisualCircuit containing the VisualNode tree.
CircuitStyle [source]¶
class CircuitStyleStyle 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,
) -> NoneAttributes¶
background_color: strblock_border_color: strblock_box_edge_color: strblock_face_color: strblock_text_color: strborder_extra_margin_left: floatborder_extra_margin_right: floatborder_padding_base: floatborder_padding_depth_factor: floatbox_padding_x: floatbox_padding_y: floatchar_width_base: floatchar_width_block: floatchar_width_bold: floatchar_width_gate: floatchar_width_monospace: floatconnection_line_color: strexpval_edge_color: strexpval_face_color: strexpval_text_color: strfallback_char_width: floatfallback_text_height: floatfigure_min_height: floatfigure_min_width: floatfigure_scale_factor: floatfolded_box_text_v_padding: floatfolded_call_block_width: floatfolded_loop_width: floatfont_scaling_adjustment: floatfont_size: intfor_items_edge_color: strfor_items_face_color: strfor_items_text_color: strfor_loop_edge_color: strfor_loop_face_color: strfor_loop_text_color: strgate_corner_radius: floatgate_face_color: strgate_gap: floatgate_height: floatgate_symbol_color: strgate_symbol_edge_color: strgate_text_color: strgate_text_padding: floatgate_width: floatif_edge_color: strif_face_color: strif_text_color: strinitial_wire_position: floatlabel_height: floatlabel_horizontal_padding: floatlabel_padding: floatlabel_step_gap: floatlabel_vertical_offset: floatline_height: floatmargin: tuple[float, float, float, float]max_folded_body_chars: intmeasure_face_color: strmeasure_symbol_color: strmin_block_padding: floatmin_left_margin: floatnested_margin: floatnested_padding_decay: floatoperation_content_padding: floatoperation_width_padding: floatoverlap_step_gap: floatparam_font_size: intpower_wrapper_margin: floatqubit_base_spacing: floatqubit_clearance: floatqubit_y_label_height: floatsubfont_size: inttext_padding: floatwhile_loop_edge_color: strwhile_loop_face_color: strwhile_loop_text_color: strwire_color: strwire_extension: floatx_left_min_bound: float
CompOp [source]¶
class CompOp(BinaryOperationBase)Comparison operation (EQ, NEQ, LT, LE, GT, GE).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: CompOpKind | None = None,
) -> NoneAttributes¶
kind: CompOpKind | Noneoperation_kind: OperationKindsignature: Signature
CompOpKind [source]¶
class CompOpKind(enum.Enum)Attributes¶
EQGEGTLELTNEQ
ConcreteControlledU [source]¶
class ConcreteControlledU(ControlledUOperation)Controlled-U with concrete (int) number of controls.
Operand layout: [ctrl_0, ..., ctrl_n, tgt_0, ..., tgt_m, params...]
Result layout: [ctrl_0', ..., ctrl_n', tgt_0', ..., tgt_m']
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
power: int | Value = 1,
block: Block | None = None,
num_controls: int = 1,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
control_operands: list[Value]control_value: int | Nonenum_controls: intparam_operands: list[Value] Get classical/object operands after the concrete control prefix.signature: Signature Build the concrete controlled call signature.target_operands: list[Value] Return the wrapped callable’s target and parameter operands.
CondOp [source]¶
class CondOp(BinaryOperationBase)Conditional logical operation (AND, OR).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: CondOpKind | None = None,
) -> NoneAttributes¶
kind: CondOpKind | Noneoperation_kind: OperationKindsignature: Signature
CondOpKind [source]¶
class CondOpKind(enum.Enum)Attributes¶
ANDOR
ControlledUOperation [source]¶
class ControlledUOperation(Operation)Base class for controlled-U operations.
Two concrete subclasses handle distinct operand layouts:
ConcreteControlledU: Fixednum_controls: int, individual qubit operands.SymbolicControlledU: Symbolicnum_controls: Value, vector-based control operands; optionalcontrol_indicesselects a subset of the control vector to act as controls (the rest pass through).
All isinstance(op, ControlledUOperation) checks match every subclass.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
power: int | Value = 1,
block: Block | None = None,
num_controls: int | Value = 1,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
) -> NoneAttributes¶
block: Block | Nonebody_operands: list[Value] Get the wrapped callable’s complete argument list.callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_operands: list[Value] Get the control qubit values.is_symbolic_num_controls: bool Whether num_controls is symbolic (Value) rather than concrete.num_controls: int | Valueoperation_kind: OperationKindparam_operands: list[Value] Get the controlled operation’s classical/object arguments.power: int | Valuesignature: Signaturetarget_operands: list[Value] Get the target qubit values (arguments to U).
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationDictValue [source]¶
class DictValue(_MetadataValueMixin, ValueBase)A dictionary value stored as stable ordered entries.
Constructor¶
def __init__(
self,
name: str,
entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> NoneAttributes¶
entries: tuple[tuple[TupleValue | Value, Value], ...]logical_id: strmetadata: ValueMetadataname: strtype: DictTypeuuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> DictValueExpvalOp [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:
Input: quantum state (qubits) + Observable reference
Output: classical Float (expectation value)
Example IR:
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
hamiltonian: Value Alias for observable (deprecated, use observable instead).observable: Value The Observable parameter operand.operation_kind: OperationKind ExpvalOp is HYBRID - bridges quantum state to classical value.output: Value The expectation value result.qubits: Value The quantum register operand.signature: Signature
ForItemsOperation [source]¶
class ForItemsOperation(HasNestedOps, Operation)Represents iteration over dict/iterable items.
Example:
for (i, j), Jij in qmc.items(ising):
bodyConstructor¶
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, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]key_is_vector: boolkey_var_values: tuple[Value, ...] | Nonekey_vars: list[str]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]operation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signaturevalue_var: strvalue_var_value: Value | None
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]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the items-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt items-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
loop_var: str = '',
loop_var_value: Value | None = None,
operations: list[Operation] = list(),
loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
region_args: tuple[RegionArg, ...] = (),
captures: tuple[ValueBase, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]Include loop_var_value so cloning/substitution stays consistent.
Without this override, UUIDRemapper would clone every body
reference to the loop variable to a fresh UUID, but leave
loop_var_value pointing at the un-cloned original — emit-time
UUID-keyed lookups for the loop variable would then miss.
Loop-carried rebind records and region arguments are included
for the same reason.
nested_op_lists¶
def nested_op_lists(self) -> list[list[Operation]]nested_regions¶
def nested_regions(self) -> tuple[Region, ...]Return the range-loop body with its explicit interface.
Returns:
tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction
value, carried-value formals, captures, and carried yields.
rebuild_nested¶
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationGateOperation [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,
) -> NoneAttributes¶
gate_type: GateOperationType | Noneoperation_kind: OperationKindqubit_operands: list[Value] Qubit operands (excluding the theta parameter if present).signature: Signaturetheta: Value | None Angle parameter for rotation gates, orNonefor fixed gates.
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¶
CPCXCZHPRXRYRZRZZSSDGSWAPTTDGTOFFOLIXYZ
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:
| Name | Type | Description |
|---|---|---|
operands | list[Value] | Exactly one scalar FloatType phase angle in radians. |
results | list[Value] | Must be empty because global phase changes no qubit identity. |
Raises:
ValueError— If the operand/result layout is invalid or the phase is not a scalarFloatTypevalue.
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKind Classify global phase as a quantum operation.phase: Value Return the scalar phase-angle operand.signature: Signature Return the zero-qubit operation signature.
HasNestedOps [source]¶
class HasNestedOpsMixin for operations that contain nested operation lists.
nested_regions() is the canonical traversal API because it exposes
operations together with block arguments, captures, and yields.
nested_op_lists() / rebuild_nested() remain compatibility helpers
for specialized consumers while they migrate to the region interface.
Methods¶
nested_op_lists¶
def nested_op_lists(self) -> list[list[Operation]]Return all nested operation lists in this control flow op.
nested_regions¶
def nested_regions(self) -> tuple[Region, ...]Return uniform views of every nested operation region.
Subclasses with explicit block arguments, captures, or yields override
this method. The fallback keeps legacy operation-owned blocks visible
while consumers migrate from nested_op_lists.
Returns:
tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.
rebuild_nested¶
def rebuild_nested(self, new_lists: list[list[Operation]]) -> OperationReturn a copy with nested operation lists replaced.
new_lists must have the same length/order as nested_op_lists().
rebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationReturn a copy with replacement region operation sequences.
Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
true_operations: list[Operation] = list(),
false_operations: list[Operation] = list(),
true_yields: list[Value] = list(),
false_yields: list[Value] = list(),
branch_rebinds: tuple[BranchRebind, ...] = (),
true_captures: tuple[ValueBase, ...] = (),
false_captures: tuple[ValueBase, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend a branch-merge slot to this if-else.
The only sanctioned construction path for merges: it keeps the
yield lists and results index-aligned so iter_merges can
rely on the invariants it checks.
Parameters:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
all_input_values¶
def all_input_values(self) -> list[ValueBase]Include branch-yield values and rebind records for cloning/substitution.
The yields are subclass-specific Value fields (not operands —
see the class docstring), so generic passes reach them through
this override, mirroring ForItemsOperation.key_var_values.
Branch rebind records follow the loop operations’ rationale: the
recorded pre-branch values reference program values by identity,
so inline cloning must remap them in lockstep with operands.
Read-based checks must not treat the records as reads (see
_op_read_uuids in the analyze pass module).
Returns:
list[ValueBase] — list[ValueBase]: Base input values plus the true/false
yields and rebind-record values.
iter_merges¶
def iter_merges(self) -> Iterator[IfMerge]Iterate the branch-merge slots of this if-else.
This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.
Yields:
IfMerge — One entry per merged output, in result order.
Raises:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
nested_op_lists¶
def nested_op_lists(self) -> list[list[Operation]]Return the two branch bodies (merge yields are not operations).
Returns:
list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations].
The branch-merge yields are values, not operations, so
they are intentionally absent here.
nested_regions¶
def nested_regions(self) -> tuple[Region, ...]Return the true and false branch interfaces.
Returns:
tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with
branch-local captures and merge yields.
rebuild_nested¶
def rebuild_nested(self, new_lists: list[list[Operation]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[list[Operation]] | The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]). |
Returns:
Operation — A copy of this if-else with the branch bodies
swapped and all other fields (yields, rebinds) preserved.
rebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
InverseBlockOperation [source]¶
class InverseBlockOperation(Operation)Represent an inverse qkernel/block as a first-class IR operation.
The operation stores both the original forward block and a Qamomile-built
inverse implementation block. Emitters may use source_block with a
backend-native inverse/adjoint primitive, then fall back to
implementation_block when native inversion is unavailable.
Operands are ordered as scalar control qubits, target quantum operands,
then classical/object parameters. Results mirror the quantum operand
layout: control results first, then one target result per target operand.
Vector target operands therefore count as one operand/result while
contributing their scalar width to num_target_qubits.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_control_qubits: int = 0,
num_target_qubits: int = 0,
custom_name: str = '',
source_block: Block | None = None,
implementation_block: Block | None = None,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_qubits: list[‘Value’] Return control quantum operands.control_value: int | Nonecustom_name: strimplementation_block: Block | Nonename: str Return a human-readable inverse operation name.num_control_qubits: intnum_target_qubits: intoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return classical/object parameter operands.signature: Signature Return the operation signature.source_block: Block | Nonetarget_qubits: list[‘Value’] Return target quantum operands.
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[str, Any] | Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly. |
definition | CallableDef | None | Optional callable definition. |
Constructor¶
def __init__(
self,
operands: Sequence[ValueLike] | None = None,
results: Sequence[ValueLike] | None = None,
*,
target: CallableRef | None = None,
transform: CallTransform = CallTransform.DIRECT,
attrs: dict[str, Any] | None = None,
definition: CallableDef | None = None,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueor an Oracle control-partition field has an invalid Python type.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width, or if Oracle invocation and definition control metadata disagree.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of relevant callable implementations.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return a conservative union of measurement-derived results.name: str Return the display name for this invocation.num_added_control_qubits: int Return controls introduced by a frontend control transform.num_body_external_control_qubits: int Return control operands generic lowering adds outside a base body.num_control_qubits: int Return the number of leading control-qubit operands.num_declared_control_qubits: int Return controls included in an opaque Oracle’s base definition.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
Methods¶
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:
| Name | Type | Description |
|---|---|---|
backend | str | None | Backend name to match. Defaults to None. |
strategy | str | None | Strategy name to match. Defaults to the invocation’s strategy_name attribute. |
Returns:
Block | None — 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
effective_body¶
def effective_body(
self,
*,
backend: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
backend | str | None | Backend name to match. Defaults to None. |
strategy | str | None | Strategy name to match. Defaults to the invocation’s strategy_name attribute. |
Returns:
Block | None — Block | None: Selected implementation body, or the callable’s
Block | None — default body when no transform-specific implementation exists.
Block | None — A compiler may synthesize inverse or controlled behavior from this
Block | None — fallback body.
implementation_for¶
def implementation_for(
self,
*,
backend: str | None = None,
strategy: str | None = None,
require_body: bool = False,
) -> CallableImplementation | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
backend | str | None | Backend name to match. Defaults to None, which only selects backend-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
require_body | bool | Whether 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:
| Name | Type | Description |
|---|---|---|
backend | str | None | Backend name used for implementation selection. Defaults to None. |
strategy | str | None | Strategy 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:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
select_body¶
def select_body(
self,
*,
backend: str | None = None,
strategy: str | None = None,
) -> CallableBodySelectionSelect 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:
| Name | Type | Description |
|---|---|---|
backend | str | None | Backend name to match. Defaults to None. |
strategy | str | None | Strategy name to match. Defaults to the invocation’s strategy_name attribute. |
Returns:
CallableBodySelection — Validated body, realized transform, and
CallableBodySelection — aligned call-site operands and results.
Raises:
ValueError— If the selected body disagrees with the invocation’s input or output contract.
MeasureOperation [source]¶
class MeasureOperation(Operation)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
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,
) -> NoneAttributes¶
int_bits: intnum_bits: intoperation_kind: OperationKindsignature: Signature
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()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
NotOp [source]¶
class NotOp(Operation)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
input: Valueoperation_kind: OperationKindoutput: Valuesignature: Signature
QInitOperation [source]¶
class QInitOperation(Operation)Initialize the qubit
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
QubitType [source]¶
class QubitType(QuantumTypeMixin, ValueType)Type representing a quantum bit (qubit).
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()) -> NoneAttributes¶
operation_kind: OperationKind Return CLASSICAL as this is a control flow operation without quantum effects.signature: Signature Return the signature with operands for each return value and no results.
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(),
) -> NoneAttributes¶
case_blocks: list[Block]case_callable_attrs: list[dict[str, Any]]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]Return every value consumed by the SELECT operation.
Returns:
list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width
value when present.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed replacement values. |
Returns:
Operation — Rebuilt SELECT operation with matching values replaced.
VFoldedBlock [source]¶
class VFoldedBlockFolded 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(),
) -> NoneAttributes¶
affected_qubits: list[int]affected_qubits_precise: boolbody_lines: list[str]condition_measure_node_key: tuple | Nonecondition_measure_qubit_indices: list[int]folded_width: floatheader_label: strkind: VFoldedKindnode_key: tuple
VFoldedKind [source]¶
class VFoldedKind(enum.Enum)Classification of folded control-flow blocks.
Attributes¶
FORFOR_ITEMSIFWHILE
VGate [source]¶
class VGateRepresent a pre-resolved gate, annotation, measurement, or block node.
Carries all information needed for layout and rendering:
label: TeX-formatted display text (e.g. “”)
qubit_indices: resolved wire indices for all operands
estimated_width: pre-computed width for layout
kind: determines rendering strategy
gate_type: for CX/SWAP/TOFFOLI special drawing
terminates_wire: whether a measurement node ends its measured wires
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:
| Name | Type | Description |
|---|---|---|
node_key | tuple | Stable identifier used to associate the node with layout coordinates. |
label | str | TeX-formatted display label. |
qubit_indices | list[int] | Resolved wire indices participating in the node. |
estimated_width | float | Width reserved for layout. |
kind | VGateKind | Rendering strategy for the node. |
gate_type | GateOperationType | None | Primitive gate type used for specialized drawing, or None. Defaults to None. |
has_param | bool | Whether the displayed gate has a parameter. Defaults to False. |
box_width | float | None | Explicit width for block-style nodes, or None. Defaults to None. |
control_count | int | Number of leading control wires for a controlled block. Defaults to 0. |
control_pattern | tuple[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. |
power | int | Exponent displayed for a controlled block. Defaults to 1. |
terminates_wire | bool | Whether 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,
) -> NoneAttributes¶
box_width: float | Nonecontrol_count: intcontrol_pattern: tuple[int, ...]estimated_width: floatgate_type: GateOperationType | Nonehas_param: boolkind: VGateKindlabel: strnode_key: tuplepower: intqubit_indices: list[int]terminates_wire: bool
VGateKind [source]¶
class VGateKind(enum.Enum)Classification of VGate nodes for rendering dispatch.
Attributes¶
BLOCK_BOXCOMPOSITE_BOXCONTROLLED_U_BOXEXPVALGATEGLOBAL_PHASEMEASUREMEASURE_VECTOR
VInlineBlock [source]¶
class VInlineBlockRepresent 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:
| Name | Type | Description |
|---|---|---|
node_key | tuple | Stable identifier used for layout coordinates. |
label | str | Display label for the inlined body. |
children | list[VisualNode] | Pre-resolved child visual nodes. |
affected_qubits | list[int] | Every wire occupied by the body. |
control_qubit_indices | list[int] | Leading coherent-control wires in flattened operand order. |
control_pattern | tuple[int, ...] | Required bit for each control wire; zero denotes an open control and one a filled control. |
power | int | Integral application count for controlled bodies. |
depth | int | Visualization nesting depth. |
border_padding | float | Padding around the inlined body border. |
max_gate_width | float | Maximum child gate width. |
label_width | float | Width required by the body label. |
content_width | float | Width required by child nodes. |
final_width | float | Final 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,
) -> NoneAttributes¶
affected_qubits: list[int]border_padding: floatchildren: list[VisualNode]content_width: floatcontrol_pattern: tuple[int, ...]control_qubit_indices: list[int]depth: intfinal_width: floatlabel: strlabel_width: floatmax_gate_width: floatnode_key: tuplepower: int
VSkip [source]¶
class VSkipZero-space node for QInit, Cast, or zero-iteration loops.
Constructor¶
def __init__(self, node_key: tuple = ()) -> NoneAttributes¶
node_key: tuple
VUnfoldedKind [source]¶
class VUnfoldedKind(enum.Enum)Classification of unfolded control-flow sequences.
Attributes¶
FORFOR_ITEMSIF
VUnfoldedSequence [source]¶
class VUnfoldedSequenceUnfolded 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(),
) -> NoneAttributes¶
affected_qubits: list[int]affected_qubits_precise: boolbranch_label_widths: list[float]condition_label: str | Nonecondition_label_width: floatcondition_measure_node_key: tuple | Nonecondition_measure_qubit_indices: list[int]iteration_widths: list[float]iterations: list[list[VisualNode]]kind: VUnfoldedKindnode_key: tuple
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of backend resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
VisualCircuit [source]¶
class VisualCircuitRoot 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(),
) -> NoneAttributes¶
children: list[VisualNode]num_qubits: intoutput_names: list[str]qubit_map: dict[str, int]qubit_names: dict[int, str]
WhileOperation [source]¶
class WhileOperation(HasNestedOps, Operation)Represents a while loop operation.
Only measurement-backed conditions are supported: the condition must
be a Bit value produced by qmc.measure(). Non-measurement
conditions (classical variables, constants, comparisons) are rejected
by ValidateWhileContractPass before reaching backend emit.
Example::
bit = qmc.measure(q)
while bit:
q = qmc.h(q)
bit = qmc.measure(q)Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
operations: list[Operation] = list(),
max_iterations: int | None = None,
loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
region_args: tuple[RegionArg, ...] = (),
captures: tuple[ValueBase, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]max_iterations: int | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]Include rebind records and region args for cloning/substitution.
Same rationale as ForOperation.all_input_values: rebind
records and region arguments reference body/pre-loop values by
identity, so inline cloning must remap them in lockstep with
body operands.
Returns:
list[ValueBase] — list[ValueBase]: Base input values plus rebind-record and
region-argument values.
nested_op_lists¶
def nested_op_lists(self) -> list[list[Operation]]nested_regions¶
def nested_regions(self) -> tuple[Region, ...]Return the while body with explicit boundary values.
Returns:
tuple[Region, ...] — tuple[Region, ...]: One body region whose block arguments and
yields are aligned with region_args. The updated
condition, when present, is appended as the final yield.
rebuild_nested¶
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the while body and its complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt while operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, rebind-record, and region-arg values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
qamomile.circuit.visualization.drawer¶
Matplotlib-based circuit visualization.
This module provides the MatplotlibDrawer facade that orchestrates circuit analysis, layout computation, and rendering.
Overview¶
| Class | Description |
|---|---|
Block | Unified block representation for all pipeline stages. |
BlockKind | Classification of block structure for pipeline stages. |
CircuitAnalyzer | Analyzes IR blocks for circuit visualization. |
CircuitLayoutEngine | Computes layout coordinates for circuit visualization. |
CircuitStyle | Style configuration for circuit visualization. |
MatplotlibDrawer | Matplotlib-based circuit drawer with Qiskit-style layout. |
MatplotlibRenderer | Renders circuit diagrams using matplotlib. |
Classes¶
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
BlockKind [source]¶
class BlockKind(Enum)Classification of block structure for pipeline stages.
Attributes¶
AFFINEANALYZEDHIERARCHICALTRACED
CircuitAnalyzer [source]¶
class CircuitAnalyzerAnalyzes 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:
| Name | Type | Description |
|---|---|---|
graph | Block | Computation graph to analyze for rendering. |
style | CircuitStyle | Visual style configuration. |
inline | bool | Whether to expand inline callable contents. |
fold_loops | bool | Whether to render loop operations as folded summary blocks instead of materialized iterations. |
expand_composite | bool | Whether to expand composite gates. |
inline_depth | int | None | Maximum nesting depth for inline expansion, or None for unlimited depth. |
fold_ifs | bool | Whether to render IfOperation nodes as folded summary blocks instead of side-by-side branches. |
Attributes¶
expand_compositefold_ifsfold_loopsgraphinlineinline_depthstyle
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:
| Name | Type | Description |
|---|---|---|
graph | Block | Computation 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,
) -> VisualCircuitBuild 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:
| Name | Type | Description |
|---|---|---|
graph | 'Block' | IR computation block. |
qubit_map | dict[str, int] | Mapping from logical_id to wire index. |
qubit_names | dict[int, str] | Mapping from wire index to display name. |
num_qubits | int | Total number of qubit wires. |
Returns:
VisualCircuit — VisualCircuit containing the VisualNode tree.
CircuitLayoutEngine [source]¶
class CircuitLayoutEngineComputes 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¶
style
Methods¶
compute_layout¶
def compute_layout(self, vc: VisualCircuit) -> LayoutResultCompute 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:
| Name | Type | Description |
|---|---|---|
vc | VisualCircuit | VisualCircuit containing pre-resolved Visual IR nodes. |
Returns:
LayoutResult — LayoutResult with all computed positions and sizing.
CircuitStyle [source]¶
class CircuitStyleStyle 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,
) -> NoneAttributes¶
background_color: strblock_border_color: strblock_box_edge_color: strblock_face_color: strblock_text_color: strborder_extra_margin_left: floatborder_extra_margin_right: floatborder_padding_base: floatborder_padding_depth_factor: floatbox_padding_x: floatbox_padding_y: floatchar_width_base: floatchar_width_block: floatchar_width_bold: floatchar_width_gate: floatchar_width_monospace: floatconnection_line_color: strexpval_edge_color: strexpval_face_color: strexpval_text_color: strfallback_char_width: floatfallback_text_height: floatfigure_min_height: floatfigure_min_width: floatfigure_scale_factor: floatfolded_box_text_v_padding: floatfolded_call_block_width: floatfolded_loop_width: floatfont_scaling_adjustment: floatfont_size: intfor_items_edge_color: strfor_items_face_color: strfor_items_text_color: strfor_loop_edge_color: strfor_loop_face_color: strfor_loop_text_color: strgate_corner_radius: floatgate_face_color: strgate_gap: floatgate_height: floatgate_symbol_color: strgate_symbol_edge_color: strgate_text_color: strgate_text_padding: floatgate_width: floatif_edge_color: strif_face_color: strif_text_color: strinitial_wire_position: floatlabel_height: floatlabel_horizontal_padding: floatlabel_padding: floatlabel_step_gap: floatlabel_vertical_offset: floatline_height: floatmargin: tuple[float, float, float, float]max_folded_body_chars: intmeasure_face_color: strmeasure_symbol_color: strmin_block_padding: floatmin_left_margin: floatnested_margin: floatnested_padding_decay: floatoperation_content_padding: floatoperation_width_padding: floatoverlap_step_gap: floatparam_font_size: intpower_wrapper_margin: floatqubit_base_spacing: floatqubit_clearance: floatqubit_y_label_height: floatsubfont_size: inttext_padding: floatwhile_loop_edge_color: strwhile_loop_face_color: strwhile_loop_text_color: strwire_color: strwire_extension: floatx_left_min_bound: float
MatplotlibDrawer [source]¶
class MatplotlibDrawerMatplotlib-based circuit drawer with Qiskit-style layout.
This drawer produces static matplotlib figures showing quantum circuits. It supports two modes:
Block mode (inline=False): Shows callable invocations as boxes
Inline mode (inline=True): Expands inline callable contents
Constructor¶
def __init__(self, graph: Block, style: CircuitStyle | None = None)Initialize the drawer.
Parameters:
| Name | Type | Description |
|---|---|---|
graph | Block | Computation graph to visualize. |
style | CircuitStyle | None | Visual style configuration. Uses DEFAULT_STYLE if None. |
Raises:
ValidationError— If compile-time if lowering rejectsgraph.ValueError— Ifgraphhas an unknownBlockKind.
Attributes¶
graphstyle
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,
) -> FigureGenerate a matplotlib Figure of the circuit.
Parameters:
| Name | Type | Description |
|---|---|---|
inline | bool | If True, expand inline callable contents. If False, show calls as boxes. |
fold_loops | bool | If True (default), display ForOperation as blocks instead of unrolling. If False, expand loops and show all iterations. |
expand_composite | bool | If True, expand boxed InvokeOperation bodies. If False (default), show them as boxes. |
inline_depth | int | None | Maximum nesting depth for inline expansion. None means unlimited. Affects inline calls, ControlledU, and boxed InvokeOperation nodes. |
fold_ifs | bool | If 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 = {},
) -> FigureDraw 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:
| Name | Type | Description |
|---|---|---|
kernel | Any | A QKernel instance to visualize. |
inline | bool | If True, expand inline callable contents. |
fold_loops | bool | If True (default), display ForOperation as blocks. |
fold_ifs | bool | If True, display IfOperation as folded summary blocks. If False (default), show if/else branches side by side. |
expand_composite | bool | If True, expand boxed InvokeOperation bodies. |
inline_depth | int | None | Maximum nesting depth for inline expansion. |
style | CircuitStyle | None | Visual style configuration. |
**kwargs | Any | Concrete values for kernel arguments. For Vector[Qubit] parameters, pass an integer size. |
Returns:
Figure — Matplotlib figure object.
MatplotlibRenderer [source]¶
class MatplotlibRendererRenders circuit diagrams using matplotlib.
Takes pre-computed layout coordinates and draws the circuit using matplotlib primitives.
Parameters:
| Name | Type | Description |
|---|---|---|
style | CircuitStyle | Visual style configuration used for all drawing primitives. |
Constructor¶
def __init__(self, style: CircuitStyle)Attributes¶
layout: LayoutResult | Nonequbit_end_positions: dict[int, float]qubit_names: dict[int, str]qubit_y: list[float]style
Methods¶
render¶
def render(self, vc: VisualCircuit, layout: LayoutResult) -> FigureRender the circuit from a VisualCircuit.
Uses the Visual IR tree which carries all pre-resolved information.
Parameters:
| Name | Type | Description |
|---|---|---|
vc | VisualCircuit | Circuit containing pre-resolved visual nodes. |
layout | LayoutResult | Pre-computed layout coordinates and wire metadata. |
Returns:
Figure — Rendered matplotlib figure.
Raises:
ValueError— If an inline block’s control indices and activation pattern have inconsistent lengths.
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¶
| Function | Description |
|---|---|
compute_block_box_bounds | Compute outermost (box_left, box_right) for an inlined block border. |
compute_border_padding | Compute border padding for a given nesting depth. |
compute_nested_block_box_bounds | Compute (inner_bounds, outer_bounds) for an inlined block border. |
| Class | Description |
|---|---|
CircuitStyle | Style 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:
| Name | Type | Description |
|---|---|---|
style | CircuitStyle | Visual style configuration. |
name | str | Block label text. |
start_x | float | X position of the first gate in the block. |
end_x | float | X position of the last gate in the block. |
depth | int | Nesting depth of the block. |
max_gate_width | float | Width of the widest gate in the block. |
power | int | Power 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) -> floatCompute border padding for a given nesting depth.
Parameters:
| Name | Type | Description |
|---|---|---|
style | CircuitStyle | Visual style configuration. |
depth | int | Nesting 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:
| Name | Type | Description |
|---|---|---|
style | CircuitStyle | Visual style configuration. |
name | str | Block label text. |
start_x | float | X position of the first gate in the block. |
end_x | float | X position of the last gate in the block. |
depth | int | Nesting depth of the block. |
max_gate_width | float | Width of the widest gate in the block. |
power | int | Power 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 CircuitStyleStyle 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,
) -> NoneAttributes¶
background_color: strblock_border_color: strblock_box_edge_color: strblock_face_color: strblock_text_color: strborder_extra_margin_left: floatborder_extra_margin_right: floatborder_padding_base: floatborder_padding_depth_factor: floatbox_padding_x: floatbox_padding_y: floatchar_width_base: floatchar_width_block: floatchar_width_bold: floatchar_width_gate: floatchar_width_monospace: floatconnection_line_color: strexpval_edge_color: strexpval_face_color: strexpval_text_color: strfallback_char_width: floatfallback_text_height: floatfigure_min_height: floatfigure_min_width: floatfigure_scale_factor: floatfolded_box_text_v_padding: floatfolded_call_block_width: floatfolded_loop_width: floatfont_scaling_adjustment: floatfont_size: intfor_items_edge_color: strfor_items_face_color: strfor_items_text_color: strfor_loop_edge_color: strfor_loop_face_color: strfor_loop_text_color: strgate_corner_radius: floatgate_face_color: strgate_gap: floatgate_height: floatgate_symbol_color: strgate_symbol_edge_color: strgate_text_color: strgate_text_padding: floatgate_width: floatif_edge_color: strif_face_color: strif_text_color: strinitial_wire_position: floatlabel_height: floatlabel_horizontal_padding: floatlabel_padding: floatlabel_step_gap: floatlabel_vertical_offset: floatline_height: floatmargin: tuple[float, float, float, float]max_folded_body_chars: intmeasure_face_color: strmeasure_symbol_color: strmin_block_padding: floatmin_left_margin: floatnested_margin: floatnested_padding_decay: floatoperation_content_padding: floatoperation_width_padding: floatoverlap_step_gap: floatparam_font_size: intpower_wrapper_margin: floatqubit_base_spacing: floatqubit_clearance: floatqubit_y_label_height: floatsubfont_size: inttext_padding: floatwhile_loop_edge_color: strwhile_loop_face_color: strwhile_loop_text_color: strwire_color: strwire_extension: floatx_left_min_bound: float
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¶
| Function | Description |
|---|---|
compute_block_box_bounds | Compute outermost (box_left, box_right) for an inlined block border. |
compute_border_padding | Compute border padding for a given nesting depth. |
| Class | Description |
|---|---|
CircuitLayoutEngine | Computes layout coordinates for circuit visualization. |
CircuitStyle | Style configuration for circuit visualization. |
LayoutResult | Result of the layout computation. |
LayoutState | Mutable state shared across layout handler methods. |
VFoldedBlock | Folded control-flow block (For/While/ForItems/If). |
VGate | Represent a pre-resolved gate, annotation, measurement, or block node. |
VGateKind | Classification of VGate nodes for rendering dispatch. |
VInlineBlock | Represent an inlined callable or controlled body with a visible border. |
VSkip | Zero-space node for QInit, Cast, or zero-iteration loops. |
VUnfoldedKind | Classification of unfolded control-flow sequences. |
VUnfoldedSequence | Unfolded control-flow sequence (For/ForItems/If). |
VisualCircuit | Root 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:
| Name | Type | Description |
|---|---|---|
style | CircuitStyle | Visual style configuration. |
name | str | Block label text. |
start_x | float | X position of the first gate in the block. |
end_x | float | X position of the last gate in the block. |
depth | int | Nesting depth of the block. |
max_gate_width | float | Width of the widest gate in the block. |
power | int | Power 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) -> floatCompute border padding for a given nesting depth.
Parameters:
| Name | Type | Description |
|---|---|---|
style | CircuitStyle | Visual style configuration. |
depth | int | Nesting depth of the block. |
Returns:
float — Border padding value, clamped to min_block_padding.
Classes¶
CircuitLayoutEngine [source]¶
class CircuitLayoutEngineComputes 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¶
style
Methods¶
compute_layout¶
def compute_layout(self, vc: VisualCircuit) -> LayoutResultCompute 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:
| Name | Type | Description |
|---|---|---|
vc | VisualCircuit | VisualCircuit containing pre-resolved Visual IR nodes. |
Returns:
LayoutResult — LayoutResult with all computed positions and sizing.
CircuitStyle [source]¶
class CircuitStyleStyle 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,
) -> NoneAttributes¶
background_color: strblock_border_color: strblock_box_edge_color: strblock_face_color: strblock_text_color: strborder_extra_margin_left: floatborder_extra_margin_right: floatborder_padding_base: floatborder_padding_depth_factor: floatbox_padding_x: floatbox_padding_y: floatchar_width_base: floatchar_width_block: floatchar_width_bold: floatchar_width_gate: floatchar_width_monospace: floatconnection_line_color: strexpval_edge_color: strexpval_face_color: strexpval_text_color: strfallback_char_width: floatfallback_text_height: floatfigure_min_height: floatfigure_min_width: floatfigure_scale_factor: floatfolded_box_text_v_padding: floatfolded_call_block_width: floatfolded_loop_width: floatfont_scaling_adjustment: floatfont_size: intfor_items_edge_color: strfor_items_face_color: strfor_items_text_color: strfor_loop_edge_color: strfor_loop_face_color: strfor_loop_text_color: strgate_corner_radius: floatgate_face_color: strgate_gap: floatgate_height: floatgate_symbol_color: strgate_symbol_edge_color: strgate_text_color: strgate_text_padding: floatgate_width: floatif_edge_color: strif_face_color: strif_text_color: strinitial_wire_position: floatlabel_height: floatlabel_horizontal_padding: floatlabel_padding: floatlabel_step_gap: floatlabel_vertical_offset: floatline_height: floatmargin: tuple[float, float, float, float]max_folded_body_chars: intmeasure_face_color: strmeasure_symbol_color: strmin_block_padding: floatmin_left_margin: floatnested_margin: floatnested_padding_decay: floatoperation_content_padding: floatoperation_width_padding: floatoverlap_step_gap: floatparam_font_size: intpower_wrapper_margin: floatqubit_base_spacing: floatqubit_clearance: floatqubit_y_label_height: floatsubfont_size: inttext_padding: floatwhile_loop_edge_color: strwhile_loop_face_color: strwhile_loop_text_color: strwire_color: strwire_extension: floatx_left_min_bound: float
LayoutResult [source]¶
class LayoutResultResult 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(),
) -> NoneAttributes¶
actual_width: floatblock_ranges: list[dict]block_widths: dict[tuple, float]first_gate_half_width: floatfirst_gate_x: floatfolded_block_extents: dict[tuple, dict]gate_widths: dict[tuple, float]inlined_op_keys: set[tuple]max_above: dict[int, float]max_below: dict[int, float]max_depth: intpositions: dict[tuple, float]qubit_end_positions: dict[int, float]qubit_y: list[float]width: float
LayoutState [source]¶
class LayoutStateMutable 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(),
) -> NoneAttributes¶
actual_width: floatblock_ranges: list[dict]block_widths: dict[tuple, float]column: floatfirst_gate_half_width: floatfirst_gate_x: float | Nonefolded_block_extents: dict[tuple, dict]gate_widths: dict[tuple, float]inlined_op_keys: set[tuple]label_extents: list[dict]max_depth: intpositions: dict[tuple, float]qubit_columns: dict[int, float]qubit_end_positions: dict[int, float]qubit_right_edges: dict[int, float]
VFoldedBlock [source]¶
class VFoldedBlockFolded 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(),
) -> NoneAttributes¶
affected_qubits: list[int]affected_qubits_precise: boolbody_lines: list[str]condition_measure_node_key: tuple | Nonecondition_measure_qubit_indices: list[int]folded_width: floatheader_label: strkind: VFoldedKindnode_key: tuple
VGate [source]¶
class VGateRepresent a pre-resolved gate, annotation, measurement, or block node.
Carries all information needed for layout and rendering:
label: TeX-formatted display text (e.g. “”)
qubit_indices: resolved wire indices for all operands
estimated_width: pre-computed width for layout
kind: determines rendering strategy
gate_type: for CX/SWAP/TOFFOLI special drawing
terminates_wire: whether a measurement node ends its measured wires
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:
| Name | Type | Description |
|---|---|---|
node_key | tuple | Stable identifier used to associate the node with layout coordinates. |
label | str | TeX-formatted display label. |
qubit_indices | list[int] | Resolved wire indices participating in the node. |
estimated_width | float | Width reserved for layout. |
kind | VGateKind | Rendering strategy for the node. |
gate_type | GateOperationType | None | Primitive gate type used for specialized drawing, or None. Defaults to None. |
has_param | bool | Whether the displayed gate has a parameter. Defaults to False. |
box_width | float | None | Explicit width for block-style nodes, or None. Defaults to None. |
control_count | int | Number of leading control wires for a controlled block. Defaults to 0. |
control_pattern | tuple[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. |
power | int | Exponent displayed for a controlled block. Defaults to 1. |
terminates_wire | bool | Whether 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,
) -> NoneAttributes¶
box_width: float | Nonecontrol_count: intcontrol_pattern: tuple[int, ...]estimated_width: floatgate_type: GateOperationType | Nonehas_param: boolkind: VGateKindlabel: strnode_key: tuplepower: intqubit_indices: list[int]terminates_wire: bool
VGateKind [source]¶
class VGateKind(enum.Enum)Classification of VGate nodes for rendering dispatch.
Attributes¶
BLOCK_BOXCOMPOSITE_BOXCONTROLLED_U_BOXEXPVALGATEGLOBAL_PHASEMEASUREMEASURE_VECTOR
VInlineBlock [source]¶
class VInlineBlockRepresent 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:
| Name | Type | Description |
|---|---|---|
node_key | tuple | Stable identifier used for layout coordinates. |
label | str | Display label for the inlined body. |
children | list[VisualNode] | Pre-resolved child visual nodes. |
affected_qubits | list[int] | Every wire occupied by the body. |
control_qubit_indices | list[int] | Leading coherent-control wires in flattened operand order. |
control_pattern | tuple[int, ...] | Required bit for each control wire; zero denotes an open control and one a filled control. |
power | int | Integral application count for controlled bodies. |
depth | int | Visualization nesting depth. |
border_padding | float | Padding around the inlined body border. |
max_gate_width | float | Maximum child gate width. |
label_width | float | Width required by the body label. |
content_width | float | Width required by child nodes. |
final_width | float | Final 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,
) -> NoneAttributes¶
affected_qubits: list[int]border_padding: floatchildren: list[VisualNode]content_width: floatcontrol_pattern: tuple[int, ...]control_qubit_indices: list[int]depth: intfinal_width: floatlabel: strlabel_width: floatmax_gate_width: floatnode_key: tuplepower: int
VSkip [source]¶
class VSkipZero-space node for QInit, Cast, or zero-iteration loops.
Constructor¶
def __init__(self, node_key: tuple = ()) -> NoneAttributes¶
node_key: tuple
VUnfoldedKind [source]¶
class VUnfoldedKind(enum.Enum)Classification of unfolded control-flow sequences.
Attributes¶
FORFOR_ITEMSIF
VUnfoldedSequence [source]¶
class VUnfoldedSequenceUnfolded 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(),
) -> NoneAttributes¶
affected_qubits: list[int]affected_qubits_precise: boolbranch_label_widths: list[float]condition_label: str | Nonecondition_label_width: floatcondition_measure_node_key: tuple | Nonecondition_measure_qubit_indices: list[int]iteration_widths: list[float]iterations: list[list[VisualNode]]kind: VUnfoldedKindnode_key: tuple
VisualCircuit [source]¶
class VisualCircuitRoot 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(),
) -> NoneAttributes¶
children: list[VisualNode]num_qubits: intoutput_names: list[str]qubit_map: dict[str, int]qubit_names: dict[int, str]
qamomile.circuit.visualization.renderer¶
Matplotlib-based circuit rendering.
This module provides MatplotlibRenderer, which handles all matplotlib drawing operations for circuit visualization.
Overview¶
| Function | Description |
|---|---|
compute_block_box_bounds | Compute outermost (box_left, box_right) for an inlined block border. |
compute_border_padding | Compute border padding for a given nesting depth. |
compute_nested_block_box_bounds | Compute (inner_bounds, outer_bounds) for an inlined block border. |
| Class | Description |
|---|---|
CircuitStyle | Style configuration for circuit visualization. |
LayoutResult | Result of the layout computation. |
MatplotlibRenderer | Renders circuit diagrams using matplotlib. |
VFoldedBlock | Folded control-flow block (For/While/ForItems/If). |
VFoldedKind | Classification of folded control-flow blocks. |
VGate | Represent a pre-resolved gate, annotation, measurement, or block node. |
VGateKind | Classification of VGate nodes for rendering dispatch. |
VInlineBlock | Represent an inlined callable or controlled body with a visible border. |
VSkip | Zero-space node for QInit, Cast, or zero-iteration loops. |
VUnfoldedKind | Classification of unfolded control-flow sequences. |
VUnfoldedSequence | Unfolded control-flow sequence (For/ForItems/If). |
VisualCircuit | Root 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:
| Name | Type | Description |
|---|---|---|
style | CircuitStyle | Visual style configuration. |
name | str | Block label text. |
start_x | float | X position of the first gate in the block. |
end_x | float | X position of the last gate in the block. |
depth | int | Nesting depth of the block. |
max_gate_width | float | Width of the widest gate in the block. |
power | int | Power 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) -> floatCompute border padding for a given nesting depth.
Parameters:
| Name | Type | Description |
|---|---|---|
style | CircuitStyle | Visual style configuration. |
depth | int | Nesting 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:
| Name | Type | Description |
|---|---|---|
style | CircuitStyle | Visual style configuration. |
name | str | Block label text. |
start_x | float | X position of the first gate in the block. |
end_x | float | X position of the last gate in the block. |
depth | int | Nesting depth of the block. |
max_gate_width | float | Width of the widest gate in the block. |
power | int | Power 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 CircuitStyleStyle 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,
) -> NoneAttributes¶
background_color: strblock_border_color: strblock_box_edge_color: strblock_face_color: strblock_text_color: strborder_extra_margin_left: floatborder_extra_margin_right: floatborder_padding_base: floatborder_padding_depth_factor: floatbox_padding_x: floatbox_padding_y: floatchar_width_base: floatchar_width_block: floatchar_width_bold: floatchar_width_gate: floatchar_width_monospace: floatconnection_line_color: strexpval_edge_color: strexpval_face_color: strexpval_text_color: strfallback_char_width: floatfallback_text_height: floatfigure_min_height: floatfigure_min_width: floatfigure_scale_factor: floatfolded_box_text_v_padding: floatfolded_call_block_width: floatfolded_loop_width: floatfont_scaling_adjustment: floatfont_size: intfor_items_edge_color: strfor_items_face_color: strfor_items_text_color: strfor_loop_edge_color: strfor_loop_face_color: strfor_loop_text_color: strgate_corner_radius: floatgate_face_color: strgate_gap: floatgate_height: floatgate_symbol_color: strgate_symbol_edge_color: strgate_text_color: strgate_text_padding: floatgate_width: floatif_edge_color: strif_face_color: strif_text_color: strinitial_wire_position: floatlabel_height: floatlabel_horizontal_padding: floatlabel_padding: floatlabel_step_gap: floatlabel_vertical_offset: floatline_height: floatmargin: tuple[float, float, float, float]max_folded_body_chars: intmeasure_face_color: strmeasure_symbol_color: strmin_block_padding: floatmin_left_margin: floatnested_margin: floatnested_padding_decay: floatoperation_content_padding: floatoperation_width_padding: floatoverlap_step_gap: floatparam_font_size: intpower_wrapper_margin: floatqubit_base_spacing: floatqubit_clearance: floatqubit_y_label_height: floatsubfont_size: inttext_padding: floatwhile_loop_edge_color: strwhile_loop_face_color: strwhile_loop_text_color: strwire_color: strwire_extension: floatx_left_min_bound: float
LayoutResult [source]¶
class LayoutResultResult 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(),
) -> NoneAttributes¶
actual_width: floatblock_ranges: list[dict]block_widths: dict[tuple, float]first_gate_half_width: floatfirst_gate_x: floatfolded_block_extents: dict[tuple, dict]gate_widths: dict[tuple, float]inlined_op_keys: set[tuple]max_above: dict[int, float]max_below: dict[int, float]max_depth: intpositions: dict[tuple, float]qubit_end_positions: dict[int, float]qubit_y: list[float]width: float
MatplotlibRenderer [source]¶
class MatplotlibRendererRenders circuit diagrams using matplotlib.
Takes pre-computed layout coordinates and draws the circuit using matplotlib primitives.
Parameters:
| Name | Type | Description |
|---|---|---|
style | CircuitStyle | Visual style configuration used for all drawing primitives. |
Constructor¶
def __init__(self, style: CircuitStyle)Attributes¶
layout: LayoutResult | Nonequbit_end_positions: dict[int, float]qubit_names: dict[int, str]qubit_y: list[float]style
Methods¶
render¶
def render(self, vc: VisualCircuit, layout: LayoutResult) -> FigureRender the circuit from a VisualCircuit.
Uses the Visual IR tree which carries all pre-resolved information.
Parameters:
| Name | Type | Description |
|---|---|---|
vc | VisualCircuit | Circuit containing pre-resolved visual nodes. |
layout | LayoutResult | Pre-computed layout coordinates and wire metadata. |
Returns:
Figure — Rendered matplotlib figure.
Raises:
ValueError— If an inline block’s control indices and activation pattern have inconsistent lengths.
VFoldedBlock [source]¶
class VFoldedBlockFolded 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(),
) -> NoneAttributes¶
affected_qubits: list[int]affected_qubits_precise: boolbody_lines: list[str]condition_measure_node_key: tuple | Nonecondition_measure_qubit_indices: list[int]folded_width: floatheader_label: strkind: VFoldedKindnode_key: tuple
VFoldedKind [source]¶
class VFoldedKind(enum.Enum)Classification of folded control-flow blocks.
Attributes¶
FORFOR_ITEMSIFWHILE
VGate [source]¶
class VGateRepresent a pre-resolved gate, annotation, measurement, or block node.
Carries all information needed for layout and rendering:
label: TeX-formatted display text (e.g. “”)
qubit_indices: resolved wire indices for all operands
estimated_width: pre-computed width for layout
kind: determines rendering strategy
gate_type: for CX/SWAP/TOFFOLI special drawing
terminates_wire: whether a measurement node ends its measured wires
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:
| Name | Type | Description |
|---|---|---|
node_key | tuple | Stable identifier used to associate the node with layout coordinates. |
label | str | TeX-formatted display label. |
qubit_indices | list[int] | Resolved wire indices participating in the node. |
estimated_width | float | Width reserved for layout. |
kind | VGateKind | Rendering strategy for the node. |
gate_type | GateOperationType | None | Primitive gate type used for specialized drawing, or None. Defaults to None. |
has_param | bool | Whether the displayed gate has a parameter. Defaults to False. |
box_width | float | None | Explicit width for block-style nodes, or None. Defaults to None. |
control_count | int | Number of leading control wires for a controlled block. Defaults to 0. |
control_pattern | tuple[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. |
power | int | Exponent displayed for a controlled block. Defaults to 1. |
terminates_wire | bool | Whether 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,
) -> NoneAttributes¶
box_width: float | Nonecontrol_count: intcontrol_pattern: tuple[int, ...]estimated_width: floatgate_type: GateOperationType | Nonehas_param: boolkind: VGateKindlabel: strnode_key: tuplepower: intqubit_indices: list[int]terminates_wire: bool
VGateKind [source]¶
class VGateKind(enum.Enum)Classification of VGate nodes for rendering dispatch.
Attributes¶
BLOCK_BOXCOMPOSITE_BOXCONTROLLED_U_BOXEXPVALGATEGLOBAL_PHASEMEASUREMEASURE_VECTOR
VInlineBlock [source]¶
class VInlineBlockRepresent 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:
| Name | Type | Description |
|---|---|---|
node_key | tuple | Stable identifier used for layout coordinates. |
label | str | Display label for the inlined body. |
children | list[VisualNode] | Pre-resolved child visual nodes. |
affected_qubits | list[int] | Every wire occupied by the body. |
control_qubit_indices | list[int] | Leading coherent-control wires in flattened operand order. |
control_pattern | tuple[int, ...] | Required bit for each control wire; zero denotes an open control and one a filled control. |
power | int | Integral application count for controlled bodies. |
depth | int | Visualization nesting depth. |
border_padding | float | Padding around the inlined body border. |
max_gate_width | float | Maximum child gate width. |
label_width | float | Width required by the body label. |
content_width | float | Width required by child nodes. |
final_width | float | Final 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,
) -> NoneAttributes¶
affected_qubits: list[int]border_padding: floatchildren: list[VisualNode]content_width: floatcontrol_pattern: tuple[int, ...]control_qubit_indices: list[int]depth: intfinal_width: floatlabel: strlabel_width: floatmax_gate_width: floatnode_key: tuplepower: int
VSkip [source]¶
class VSkipZero-space node for QInit, Cast, or zero-iteration loops.
Constructor¶
def __init__(self, node_key: tuple = ()) -> NoneAttributes¶
node_key: tuple
VUnfoldedKind [source]¶
class VUnfoldedKind(enum.Enum)Classification of unfolded control-flow sequences.
Attributes¶
FORFOR_ITEMSIF
VUnfoldedSequence [source]¶
class VUnfoldedSequenceUnfolded 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(),
) -> NoneAttributes¶
affected_qubits: list[int]affected_qubits_precise: boolbranch_label_widths: list[float]condition_label: str | Nonecondition_label_width: floatcondition_measure_node_key: tuple | Nonecondition_measure_qubit_indices: list[int]iteration_widths: list[float]iterations: list[list[VisualNode]]kind: VUnfoldedKindnode_key: tuple
VisualCircuit [source]¶
class VisualCircuitRoot 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(),
) -> NoneAttributes¶
children: list[VisualNode]num_qubits: intoutput_names: list[str]qubit_map: dict[str, int]qubit_names: dict[int, str]
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¶
| Class | Description |
|---|---|
CircuitStyle | Style configuration for circuit visualization. |
Classes¶
CircuitStyle [source]¶
class CircuitStyleStyle 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,
) -> NoneAttributes¶
background_color: strblock_border_color: strblock_box_edge_color: strblock_face_color: strblock_text_color: strborder_extra_margin_left: floatborder_extra_margin_right: floatborder_padding_base: floatborder_padding_depth_factor: floatbox_padding_x: floatbox_padding_y: floatchar_width_base: floatchar_width_block: floatchar_width_bold: floatchar_width_gate: floatchar_width_monospace: floatconnection_line_color: strexpval_edge_color: strexpval_face_color: strexpval_text_color: strfallback_char_width: floatfallback_text_height: floatfigure_min_height: floatfigure_min_width: floatfigure_scale_factor: floatfolded_box_text_v_padding: floatfolded_call_block_width: floatfolded_loop_width: floatfont_scaling_adjustment: floatfont_size: intfor_items_edge_color: strfor_items_face_color: strfor_items_text_color: strfor_loop_edge_color: strfor_loop_face_color: strfor_loop_text_color: strgate_corner_radius: floatgate_face_color: strgate_gap: floatgate_height: floatgate_symbol_color: strgate_symbol_edge_color: strgate_text_color: strgate_text_padding: floatgate_width: floatif_edge_color: strif_face_color: strif_text_color: strinitial_wire_position: floatlabel_height: floatlabel_horizontal_padding: floatlabel_padding: floatlabel_step_gap: floatlabel_vertical_offset: floatline_height: floatmargin: tuple[float, float, float, float]max_folded_body_chars: intmeasure_face_color: strmeasure_symbol_color: strmin_block_padding: floatmin_left_margin: floatnested_margin: floatnested_padding_decay: floatoperation_content_padding: floatoperation_width_padding: floatoverlap_step_gap: floatparam_font_size: intpower_wrapper_margin: floatqubit_base_spacing: floatqubit_clearance: floatqubit_y_label_height: floatsubfont_size: inttext_padding: floatwhile_loop_edge_color: strwhile_loop_face_color: strwhile_loop_text_color: strwire_color: strwire_extension: floatx_left_min_bound: float
qamomile.circuit.visualization.types¶
Shared data structures and constants for circuit visualization.
Overview¶
| Class | Description |
|---|---|
LayoutResult | Result of the layout computation. |
LayoutState | Mutable state shared across layout handler methods. |
Classes¶
LayoutResult [source]¶
class LayoutResultResult 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(),
) -> NoneAttributes¶
actual_width: floatblock_ranges: list[dict]block_widths: dict[tuple, float]first_gate_half_width: floatfirst_gate_x: floatfolded_block_extents: dict[tuple, dict]gate_widths: dict[tuple, float]inlined_op_keys: set[tuple]max_above: dict[int, float]max_below: dict[int, float]max_depth: intpositions: dict[tuple, float]qubit_end_positions: dict[int, float]qubit_y: list[float]width: float
LayoutState [source]¶
class LayoutStateMutable 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(),
) -> NoneAttributes¶
actual_width: floatblock_ranges: list[dict]block_widths: dict[tuple, float]column: floatfirst_gate_half_width: floatfirst_gate_x: float | Nonefolded_block_extents: dict[tuple, dict]gate_widths: dict[tuple, float]inlined_op_keys: set[tuple]label_extents: list[dict]max_depth: intpositions: dict[tuple, float]qubit_columns: dict[int, float]qubit_end_positions: dict[int, float]qubit_right_edges: dict[int, float]
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¶
| Class | Description |
|---|---|
GateOperationType | |
VFoldedBlock | Folded control-flow block (For/While/ForItems/If). |
VFoldedKind | Classification of folded control-flow blocks. |
VGate | Represent a pre-resolved gate, annotation, measurement, or block node. |
VGateKind | Classification of VGate nodes for rendering dispatch. |
VInlineBlock | Represent an inlined callable or controlled body with a visible border. |
VSkip | Zero-space node for QInit, Cast, or zero-iteration loops. |
VUnfoldedKind | Classification of unfolded control-flow sequences. |
VUnfoldedSequence | Unfolded control-flow sequence (For/ForItems/If). |
VisualCircuit | Root container for the Visual IR tree. |
Classes¶
GateOperationType [source]¶
class GateOperationType(enum.Enum)Attributes¶
CPCXCZHPRXRYRZRZZSSDGSWAPTTDGTOFFOLIXYZ
VFoldedBlock [source]¶
class VFoldedBlockFolded 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(),
) -> NoneAttributes¶
affected_qubits: list[int]affected_qubits_precise: boolbody_lines: list[str]condition_measure_node_key: tuple | Nonecondition_measure_qubit_indices: list[int]folded_width: floatheader_label: strkind: VFoldedKindnode_key: tuple
VFoldedKind [source]¶
class VFoldedKind(enum.Enum)Classification of folded control-flow blocks.
Attributes¶
FORFOR_ITEMSIFWHILE
VGate [source]¶
class VGateRepresent a pre-resolved gate, annotation, measurement, or block node.
Carries all information needed for layout and rendering:
label: TeX-formatted display text (e.g. “”)
qubit_indices: resolved wire indices for all operands
estimated_width: pre-computed width for layout
kind: determines rendering strategy
gate_type: for CX/SWAP/TOFFOLI special drawing
terminates_wire: whether a measurement node ends its measured wires
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:
| Name | Type | Description |
|---|---|---|
node_key | tuple | Stable identifier used to associate the node with layout coordinates. |
label | str | TeX-formatted display label. |
qubit_indices | list[int] | Resolved wire indices participating in the node. |
estimated_width | float | Width reserved for layout. |
kind | VGateKind | Rendering strategy for the node. |
gate_type | GateOperationType | None | Primitive gate type used for specialized drawing, or None. Defaults to None. |
has_param | bool | Whether the displayed gate has a parameter. Defaults to False. |
box_width | float | None | Explicit width for block-style nodes, or None. Defaults to None. |
control_count | int | Number of leading control wires for a controlled block. Defaults to 0. |
control_pattern | tuple[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. |
power | int | Exponent displayed for a controlled block. Defaults to 1. |
terminates_wire | bool | Whether 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,
) -> NoneAttributes¶
box_width: float | Nonecontrol_count: intcontrol_pattern: tuple[int, ...]estimated_width: floatgate_type: GateOperationType | Nonehas_param: boolkind: VGateKindlabel: strnode_key: tuplepower: intqubit_indices: list[int]terminates_wire: bool
VGateKind [source]¶
class VGateKind(enum.Enum)Classification of VGate nodes for rendering dispatch.
Attributes¶
BLOCK_BOXCOMPOSITE_BOXCONTROLLED_U_BOXEXPVALGATEGLOBAL_PHASEMEASUREMEASURE_VECTOR
VInlineBlock [source]¶
class VInlineBlockRepresent 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:
| Name | Type | Description |
|---|---|---|
node_key | tuple | Stable identifier used for layout coordinates. |
label | str | Display label for the inlined body. |
children | list[VisualNode] | Pre-resolved child visual nodes. |
affected_qubits | list[int] | Every wire occupied by the body. |
control_qubit_indices | list[int] | Leading coherent-control wires in flattened operand order. |
control_pattern | tuple[int, ...] | Required bit for each control wire; zero denotes an open control and one a filled control. |
power | int | Integral application count for controlled bodies. |
depth | int | Visualization nesting depth. |
border_padding | float | Padding around the inlined body border. |
max_gate_width | float | Maximum child gate width. |
label_width | float | Width required by the body label. |
content_width | float | Width required by child nodes. |
final_width | float | Final 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,
) -> NoneAttributes¶
affected_qubits: list[int]border_padding: floatchildren: list[VisualNode]content_width: floatcontrol_pattern: tuple[int, ...]control_qubit_indices: list[int]depth: intfinal_width: floatlabel: strlabel_width: floatmax_gate_width: floatnode_key: tuplepower: int
VSkip [source]¶
class VSkipZero-space node for QInit, Cast, or zero-iteration loops.
Constructor¶
def __init__(self, node_key: tuple = ()) -> NoneAttributes¶
node_key: tuple
VUnfoldedKind [source]¶
class VUnfoldedKind(enum.Enum)Classification of unfolded control-flow sequences.
Attributes¶
FORFOR_ITEMSIF
VUnfoldedSequence [source]¶
class VUnfoldedSequenceUnfolded 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(),
) -> NoneAttributes¶
affected_qubits: list[int]affected_qubits_precise: boolbranch_label_widths: list[float]condition_label: str | Nonecondition_label_width: floatcondition_measure_node_key: tuple | Nonecondition_measure_qubit_indices: list[int]iteration_widths: list[float]iterations: list[list[VisualNode]]kind: VUnfoldedKindnode_key: tuple
VisualCircuit [source]¶
class VisualCircuitRoot 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(),
) -> NoneAttributes¶
children: list[VisualNode]num_qubits: intoutput_names: list[str]qubit_map: dict[str, int]qubit_names: dict[int, str]