Skip to content

memq_dqc.visualization

visualization

Visualization helpers for memq_dqc.

ExecutionFrame dataclass

ExecutionFrame(
    time: float, events: tuple[ScheduleEvent, ...]
)

One rendered instant of a schedule playback.

Attributes:

Name Type Description
time float

Schedule time this frame depicts, in scheduler time units.

events tuple[ScheduleEvent, ...]

Events in flight at time, ordered as in the schedule.

NetworkExecutionAnimation

NetworkExecutionAnimation(
    network: NetworkGraph,
    schedule: OperationSchedule,
    *,
    mode: PlaybackMode = "events",
    num_frames: int = 240,
    interval: int = 400,
    repeat: bool = True,
    title: str | None = None,
    figsize: tuple[float, float] | None = None,
    pos: dict[PhysicalQubit, tuple[float, float]]
    | None = None,
    show_labels: bool = True,
    controls: bool = False,
)

Playable animation of a schedule over a physical-qubit network graph.

Instances build their figure and frame list eagerly, then expose the animation for display (show), notebook embedding (to_jshtml), or export (save).

Initialize the animation and render its first frame.

Parameters:

Name Type Description Default
network NetworkGraph

Network the schedule was produced for.

required
schedule OperationSchedule

Operation schedule to play back.

required
mode PlaybackMode

"events" or "time" playback.

'events'
num_frames int

Frame count for "time" mode.

240
interval int

Delay between frames in milliseconds.

400
repeat bool

Whether playback loops.

True
title str | None

Figure title, or None for a generated summary.

None
figsize tuple[float, float] | None

Figure size in inches.

None
pos dict[PhysicalQubit, tuple[float, float]] | None

Explicit node positions, or None for the clustered layout.

None
show_labels bool

Whether to label nodes with physical-qubit names.

True
controls bool

Whether to attach play/pause and scrub widgets.

False

Raises:

Type Description
ValueError

If the schedule is empty, mode is unknown, or the schedule references qubits absent from the network.

Source code in src/memq_dqc/visualization/execution_animator.py
def __init__(
    self,
    network: NetworkGraph,
    schedule: OperationSchedule,
    *,
    mode: PlaybackMode = "events",
    num_frames: int = 240,
    interval: int = 400,
    repeat: bool = True,
    title: str | None = None,
    figsize: tuple[float, float] | None = None,
    pos: dict[PhysicalQubit, tuple[float, float]] | None = None,
    show_labels: bool = True,
    controls: bool = False,
) -> None:
    """Initialize the animation and render its first frame.

    Args:
        network: Network the schedule was produced for.
        schedule: Operation schedule to play back.
        mode: ``"events"`` or ``"time"`` playback.
        num_frames: Frame count for ``"time"`` mode.
        interval: Delay between frames in milliseconds.
        repeat: Whether playback loops.
        title: Figure title, or ``None`` for a generated summary.
        figsize: Figure size in inches.
        pos: Explicit node positions, or ``None`` for the clustered
            layout.
        show_labels: Whether to label nodes with physical-qubit names.
        controls: Whether to attach play/pause and scrub widgets.

    Raises:
        ValueError: If the schedule is empty, ``mode`` is unknown, or the
            schedule references qubits absent from the network.
    """
    if not schedule.operations:
        raise ValueError(
            "Cannot animate an empty schedule: it has no operations."
        )
    if mode not in ("events", "time"):
        raise ValueError(
            f"Unknown playback mode {mode!r}. Expected 'events' or 'time'."
        )

    self._network = network
    self._schedule = schedule
    self._mode: PlaybackMode = mode
    self._nodes: list[PhysicalQubit] = list(network.graph.nodes)
    self._label_to_node = _build_label_index(self._nodes)
    _validate_schedule_qubits(schedule, self._label_to_node)

    self._event_nodes = {
        id(event): self._event_node_set(event)
        for event in schedule.operations
    }
    self._frames = _build_frames(schedule, mode, num_frames)
    self._pos = (
        dict(pos) if pos is not None else qpu_clustered_layout(network)
    )

    self._fig, self._ax = plt.subplots(
        figsize=figsize
        if figsize is not None
        else _auto_figsize(self._pos)
    )
    # Node size follows the layout rather than being fixed, so a QPU
    # holding many qubits does not render as a pile of overlapping discs.
    self._node_size, self._label_fontsize = _node_metrics(self._pos)
    self._controls_enabled = controls
    self._play_button: Button | None = None
    self._slider: Slider | None = None
    self._playing = True
    self._draw_static(title=title, show_labels=show_labels)

    self._anim = FuncAnimation(
        self._fig,
        self._render_frame,
        frames=len(self._frames),
        interval=interval,
        repeat=repeat,
        blit=False,
        cache_frame_data=False,
    )
    if controls:
        self._attach_controls()
    self._render_frame(0)

figure property

figure: Figure

Return the matplotlib figure hosting the animation.

axes property

axes: Axes

Return the axes the network graph is drawn on.

animation property

animation: FuncAnimation

Return the underlying matplotlib animation.

frames property

frames: tuple[ExecutionFrame, ...]

Return the frames this animation plays through.

show

show() -> None

Display the animation in an interactive window with controls.

Attaches play/pause and scrub widgets if they are not already present, then blocks on the active matplotlib backend.

Source code in src/memq_dqc/visualization/execution_animator.py
def show(self) -> None:
    """Display the animation in an interactive window with controls.

    Attaches play/pause and scrub widgets if they are not already present,
    then blocks on the active matplotlib backend.
    """
    if not self._controls_enabled:
        self._attach_controls()
        self._controls_enabled = True
    plt.show()

save

save(
    path: str | PathLike[str],
    *,
    fps: int = 3,
    dpi: int = 150,
) -> None

Write the animation to a file.

The writer is chosen from the extension: .gif uses Pillow, .mp4 needs ffmpeg on the path, and .html writes a self-contained JavaScript player.

Parameters:

Name Type Description Default
path str | PathLike[str]

Destination path, including extension.

required
fps int

Frames per second in the written file.

3
dpi int

Output resolution in dots per inch.

150
Source code in src/memq_dqc/visualization/execution_animator.py
def save(
    self,
    path: str | PathLike[str],
    *,
    fps: int = 3,
    dpi: int = 150,
) -> None:
    """Write the animation to a file.

    The writer is chosen from the extension: ``.gif`` uses Pillow, ``.mp4``
    needs ffmpeg on the path, and ``.html`` writes a self-contained
    JavaScript player.

    Args:
        path: Destination path, including extension.
        fps: Frames per second in the written file.
        dpi: Output resolution in dots per inch.
    """
    self._anim.save(str(path), fps=fps, dpi=dpi)

to_jshtml

to_jshtml(*, fps: int = 3) -> str

Return a self-contained HTML player for notebook display.

Parameters:

Name Type Description Default
fps int

Frames per second for the embedded player.

3

Returns:

Type Description
str

HTML markup with play, pause, and scrub controls.

Source code in src/memq_dqc/visualization/execution_animator.py
def to_jshtml(self, *, fps: int = 3) -> str:
    """Return a self-contained HTML player for notebook display.

    Args:
        fps: Frames per second for the embedded player.

    Returns:
        HTML markup with play, pause, and scrub controls.
    """
    return self._anim.to_jshtml(fps=fps)

SvgDashboardPanel dataclass

SvgDashboardPanel(
    title: str,
    document: SvgDocument,
    description: str | None = None,
)

A single visualization card inside an HTML dashboard.

Parameters:

Name Type Description Default
title str

Card heading shown above the embedded SVG.

required
document SvgDocument

SVG document rendered inside the card.

required
description str | None

Optional supporting text shown under the title.

None

SvgDashboardSection dataclass

SvgDashboardSection(
    title: str,
    panels: Sequence[SvgDashboardPanel],
    description: str | None = None,
)

A grouped dashboard section containing one or more visualization cards.

Parameters:

Name Type Description Default
title str

Section heading shown in the dashboard.

required
panels Sequence[SvgDashboardPanel]

Visualization cards rendered within the section.

required
description str | None

Optional supporting text shown under the heading.

None

SvgDocument dataclass

SvgDocument(width: int, height: int, svg: str)

A standalone SVG visualization artifact.

Parameters:

Name Type Description Default
width int

Canvas width in pixels.

required
height int

Canvas height in pixels.

required
svg str

Full SVG markup for the document.

required

write_svg

write_svg(path: str | Path) -> Path

Write the SVG markup to disk.

Parameters:

Name Type Description Default
path str | Path

Destination SVG filepath.

required

Returns:

Type Description
Path

The resolved output path.

Source code in src/memq_dqc/visualization/svg_document.py
def write_svg(self, path: str | Path) -> Path:
    """Write the SVG markup to disk.

    Args:
        path: Destination SVG filepath.

    Returns:
        The resolved output path.
    """
    output_path = Path(path)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text(self.svg, encoding="utf-8")
    return output_path

to_html

to_html(*, title: str = 'Visualization') -> str

Wrap the SVG in a lightweight interactive HTML viewer.

Parameters:

Name Type Description Default
title str

Viewer title shown above the canvas.

'Visualization'

Returns:

Type Description
str

A standalone HTML document with pan and zoom controls.

Source code in src/memq_dqc/visualization/svg_document.py
    def to_html(self, *, title: str = "Visualization") -> str:
        """Wrap the SVG in a lightweight interactive HTML viewer.

        Args:
            title: Viewer title shown above the canvas.

        Returns:
            A standalone HTML document with pan and zoom controls.
        """
        svg_markup = self.svg.replace(
            "<svg ",
            '<svg class="viewer__svg" ',
            1,
        )
        escaped_title = escape(title)
        return f"""<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <title>{escaped_title}</title>
  <style>
    :root {{
      color-scheme: light;
      --panel: #ffffff;
      --panel-border: #d8deea;
      --surface: #f6f3ff;
      --surface-accent: rgba(72, 1, 176, 0.06);
      --text: #102a43;
      --muted: #52606d;
      --accent: #4801b0;
      --accent-bright: #d702fe;
    }}
    * {{
      box-sizing: border-box;
    }}
    body {{
      margin: 0;
      min-height: 100vh;
      font-family: "IBM Plex Sans", "Helvetica Neue", sans-serif;
      color: var(--text);
      background:
        radial-gradient(circle at top left, var(--surface-accent), transparent 32%),
        linear-gradient(180deg, #fcfbff 0%, #f6f7fb 100%);
    }}
    .app {{
      min-height: 100vh;
      display: grid;
      grid-template-rows: auto 1fr;
      gap: 16px;
      padding: 18px;
    }}
    .toolbar {{
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 16px;
      padding: 16px 18px;
      border: 1px solid var(--panel-border);
      border-radius: 16px;
      background: rgba(255, 255, 255, 0.9);
      backdrop-filter: blur(12px);
      box-shadow: 0 14px 40px rgba(16, 42, 67, 0.08);
    }}
    .title-block h1 {{
      margin: 0;
      font-size: 22px;
      line-height: 1.2;
    }}
    .title-block p {{
      margin: 6px 0 0;
      color: var(--muted);
      font-size: 13px;
    }}
    .controls {{
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }}
    .controls button {{
      border: 1px solid var(--panel-border);
      border-radius: 10px;
      background: var(--panel);
      color: var(--text);
      padding: 8px 12px;
      font: inherit;
      cursor: pointer;
    }}
    .controls button:hover {{
      border-color: var(--accent-bright);
      color: var(--accent);
    }}
    .viewport {{
      position: relative;
      overflow: hidden;
      border: 1px solid var(--panel-border);
      border-radius: 18px;
      background:
        linear-gradient(90deg, rgba(72, 1, 176, 0.05) 1px, transparent 1px),
        linear-gradient(rgba(72, 1, 176, 0.05) 1px, transparent 1px),
        linear-gradient(180deg, #fffefe 0%, #f5f3ff 100%);
      background-size: 28px 28px, 28px 28px, 100% 100%;
      box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.7);
      min-height: 640px;
      touch-action: none;
      cursor: grab;
    }}
    .viewport.is-dragging {{
      cursor: grabbing;
    }}
    .canvas {{
      position: absolute;
      left: 0;
      top: 0;
      transform-origin: 0 0;
      will-change: transform;
    }}
    .viewer__svg {{
      display: block;
      overflow: visible;
      box-shadow: 0 18px 44px rgba(16, 42, 67, 0.12);
      border-radius: 16px;
    }}
    @media (max-width: 900px) {{
      .toolbar {{
        align-items: flex-start;
        flex-direction: column;
      }}
      .viewport {{
        min-height: 520px;
      }}
    }}
  </style>
</head>
<body>
  <div class="app">
    <header class="toolbar">
      <div class="title-block">
        <h1>{escaped_title}</h1>
        <p>Drag to pan, scroll to zoom, or use the fit/reset controls.</p>
      </div>
      <div class="controls">
        <button type="button" data-action="zoom-out">-</button>
        <button type="button" data-action="zoom-in">+</button>
        <button type="button" data-action="fit">Fit</button>
        <button type="button" data-action="reset">100%</button>
      </div>
    </header>
    <main class="viewport">
      <div class="canvas">
        {svg_markup}
      </div>
    </main>
  </div>
  <script>
    const viewport = document.querySelector(".viewport");
    const canvas = document.querySelector(".canvas");
    const baseWidth = {self.width};
    const baseHeight = {self.height};
    const state = {{
      scale: 1,
      x: 0,
      y: 0,
      minScale: 0.08,
      maxScale: 8,
      pointerId: null,
      originX: 0,
      originY: 0,
    }};

    function applyTransform() {{
      canvas.style.transform =
        `translate(${{state.x}}px, ${{state.y}}px) scale(${{state.scale}})`;
    }}

    function fitToViewport() {{
      const padding = 32;
      const scale = Math.min(
        (viewport.clientWidth - padding * 2) / baseWidth,
        (viewport.clientHeight - padding * 2) / baseHeight,
      );
      state.scale = Math.max(
        state.minScale,
        Math.min(state.maxScale, scale || 1),
      );
      state.x = (viewport.clientWidth - baseWidth * state.scale) / 2;
      state.y = (viewport.clientHeight - baseHeight * state.scale) / 2;
      applyTransform();
    }}

    function resetZoom() {{
      state.scale = 1;
      state.x = 24;
      state.y = 24;
      applyTransform();
    }}

    function zoomAt(clientX, clientY, deltaScale) {{
      const rect = viewport.getBoundingClientRect();
      const px = clientX - rect.left;
      const py = clientY - rect.top;
      const worldX = (px - state.x) / state.scale;
      const worldY = (py - state.y) / state.scale;
      const nextScale = Math.max(
        state.minScale,
        Math.min(state.maxScale, state.scale * deltaScale),
      );
      state.x = px - worldX * nextScale;
      state.y = py - worldY * nextScale;
      state.scale = nextScale;
      applyTransform();
    }}

    viewport.addEventListener("wheel", (event) => {{
      event.preventDefault();
      const deltaScale = event.deltaY < 0 ? 1.12 : 1 / 1.12;
      zoomAt(event.clientX, event.clientY, deltaScale);
    }}, {{ passive: false }});

    viewport.addEventListener("pointerdown", (event) => {{
      state.pointerId = event.pointerId;
      state.originX = event.clientX - state.x;
      state.originY = event.clientY - state.y;
      viewport.classList.add("is-dragging");
      viewport.setPointerCapture(event.pointerId);
    }});

    viewport.addEventListener("pointermove", (event) => {{
      if (state.pointerId !== event.pointerId) {{
        return;
      }}
      state.x = event.clientX - state.originX;
      state.y = event.clientY - state.originY;
      applyTransform();
    }});

    function releasePointer(event) {{
      if (state.pointerId !== event.pointerId) {{
        return;
      }}
      state.pointerId = null;
      viewport.classList.remove("is-dragging");
    }}

    viewport.addEventListener("pointerup", releasePointer);
    viewport.addEventListener("pointercancel", releasePointer);
    viewport.addEventListener("dblclick", fitToViewport);
    window.addEventListener("resize", fitToViewport);

    document
      .querySelector('[data-action="zoom-in"]')
      .addEventListener("click", () => {{
        const rect = viewport.getBoundingClientRect();
        zoomAt(rect.left + rect.width / 2, rect.top + rect.height / 2, 1.16);
      }});
    document
      .querySelector('[data-action="zoom-out"]')
      .addEventListener("click", () => {{
        const rect = viewport.getBoundingClientRect();
        zoomAt(rect.left + rect.width / 2, rect.top + rect.height / 2, 1 / 1.16);
      }});
    document
      .querySelector('[data-action="fit"]')
      .addEventListener("click", fitToViewport);
    document
      .querySelector('[data-action="reset"]')
      .addEventListener("click", resetZoom);

    fitToViewport();
  </script>
</body>
</html>
"""

write_html

write_html(
    path: str | Path, *, title: str = "Visualization"
) -> Path

Write the interactive HTML viewer to disk.

Parameters:

Name Type Description Default
path str | Path

Destination HTML filepath.

required
title str

Viewer title shown above the canvas.

'Visualization'

Returns:

Type Description
Path

The resolved output path.

Source code in src/memq_dqc/visualization/svg_document.py
def write_html(
    self, path: str | Path, *, title: str = "Visualization"
) -> Path:
    """Write the interactive HTML viewer to disk.

    Args:
        path: Destination HTML filepath.
        title: Viewer title shown above the canvas.

    Returns:
        The resolved output path.
    """
    output_path = Path(path)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text(self.to_html(title=title), encoding="utf-8")
    return output_path

write_png

write_png(path: str | Path) -> Path

Rasterize the SVG document to PNG.

Parameters:

Name Type Description Default
path str | Path

Destination PNG filepath.

required

Returns:

Type Description
Path

The resolved output path.

Raises:

Type Description
RuntimeError

If rsvg-convert is unavailable or conversion fails.

Source code in src/memq_dqc/visualization/svg_document.py
def write_png(self, path: str | Path) -> Path:
    """Rasterize the SVG document to PNG.

    Args:
        path: Destination PNG filepath.

    Returns:
        The resolved output path.

    Raises:
        RuntimeError: If ``rsvg-convert`` is unavailable or conversion
            fails.
    """
    converter = which("rsvg-convert")
    if converter is None:
        raise RuntimeError("rsvg-convert is required to write PNG output.")

    output_path = Path(path)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    result = run(
        [
            converter,
            "--format",
            "png",
            "--output",
            str(output_path),
        ],
        input=self.svg,
        text=True,
        capture_output=True,
        check=False,
    )
    if result.returncode != 0:
        raise RuntimeError(
            "rsvg-convert failed with exit code "
            f"{result.returncode}: {result.stderr.strip()}"
        )
    return output_path

plot_distributed_circuit

plot_distributed_circuit(
    circuit: Circuit,
    *,
    schedule: PartitionSchedule | None = None,
    windows: PartitionWindows | None = None,
    start_window: int = 0,
    max_windows: int | None = None,
    max_ops_per_window: int | None = None,
    title: str | None = None,
) -> SvgDocument

Render a distributed circuit view as SVG.

Wires represent QPU-local physical slots rather than global logical-qubit indices. Slot labels restart from zero inside each QPU group, and QPU boundaries are separated by dotted rules. Remote gates use a red dashed variant of the local-gate style, while state teleportation swaps are shown as forward-leaning connectors between QPU groups. If the circuit declares classical bits, they are rendered as double-line wires beneath the quantum rows, with dotted measurement arrows from M_z boxes to their targets.

Parameters:

Name Type Description Default
circuit Circuit

Circuit to render.

required
schedule PartitionSchedule | None

Optional partition schedule used for QPU-aware placement.

None
windows PartitionWindows | None

Optional partition windows aligned with schedule.

None
start_window int

First window to render.

0
max_windows int | None

Optional cap on the number of windows to render.

None
max_ops_per_window int | None

Optional cap on visible operations per window.

None
title str | None

Optional chart title.

None

Returns:

Type Description
SvgDocument

An SVG document containing the circuit visualization.

Raises:

Type Description
ValueError

If schedule and windows do not align or the selected window slice is empty.

Source code in src/memq_dqc/visualization/compiler_visualizer.py
def plot_distributed_circuit(
    circuit: Circuit,
    *,
    schedule: PartitionSchedule | None = None,
    windows: PartitionWindows | None = None,
    start_window: int = 0,
    max_windows: int | None = None,
    max_ops_per_window: int | None = None,
    title: str | None = None,
) -> SvgDocument:
    """Render a distributed circuit view as SVG.

    Wires represent QPU-local physical slots rather than global logical-qubit
    indices. Slot labels restart from zero inside each QPU group, and QPU
    boundaries are separated by dotted rules. Remote gates use a red dashed
    variant of the local-gate style, while state teleportation swaps are shown
    as forward-leaning connectors between QPU groups. If the circuit declares
    classical bits, they are rendered as double-line wires beneath the quantum
    rows, with dotted measurement arrows from ``M_z`` boxes to their targets.

    Args:
        circuit: Circuit to render.
        schedule: Optional partition schedule used for QPU-aware placement.
        windows: Optional partition windows aligned with ``schedule``.
        start_window: First window to render.
        max_windows: Optional cap on the number of windows to render.
        max_ops_per_window: Optional cap on visible operations per window.
        title: Optional chart title.

    Returns:
        An SVG document containing the circuit visualization.

    Raises:
        ValueError: If schedule and windows do not align or the selected
            window slice is empty.
    """
    if (schedule is None) != (windows is None):
        raise ValueError("schedule and windows must be provided together.")

    if schedule is None or windows is None:
        windows = [list(circuit.mono.ops)]
        schedule = [_single_qpu_assignment(circuit.mono.ops)]

    if len(schedule) != len(windows):
        raise ValueError("schedule and windows must have the same length.")
    if not schedule:
        raise ValueError("schedule must contain at least one window.")

    selected_windows = _select_windows(
        windows,
        start_window=start_window,
        max_windows=max_windows,
        max_ops_per_window=max_ops_per_window,
    )
    if not selected_windows:
        raise ValueError("Selected window slice is empty.")

    slot_layout = _build_slot_layout(schedule)
    classical_bits = _extract_classical_bits(circuit)
    classical_layout = (
        _build_classical_layout(classical_bits) if classical_bits else None
    )
    positions_by_window = [
        _assignment_positions(window) for window in schedule
    ]
    swap_schedule = synthesize_state_teleportation_swaps(schedule)
    header_visible = title != ""
    resolved_title = "Distributed Circuit View" if title is None else title
    legend_y = 24.0 if header_visible else 12.0

    header_height = 110.0 if header_visible else 62.0
    left_margin = 138.0
    bottom_padding = 44.0
    classical_section_gap = 28.0 if classical_layout is not None else 0.0
    op_step = 42.0
    inter_window_gap = 78.0
    trailing_padding = 26.0
    gate_column_count = sum(
        len(window.ops) + int(window.omitted_ops > 0)
        for window in selected_windows
    )
    body_width = (
        gate_column_count * op_step
        + max(0, len(selected_windows) - 1) * inter_window_gap
        + 24.0
    )
    plot_right = left_margin + body_width
    width = int(max(plot_right + trailing_padding, 620.0))
    classical_height = (
        classical_layout.total_height if classical_layout is not None else 0.0
    )
    height = int(
        header_height
        + slot_layout.total_height
        + classical_section_gap
        + classical_height
        + bottom_padding
    )
    canvas = SvgCanvas(width=width, height=height, background="#fffdfc")
    classical_top = (
        header_height + slot_layout.total_height + classical_section_gap
    )
    background_height = (
        slot_layout.total_height
        + 18.0
        + classical_section_gap
        + classical_height
    )

    x_cursor = left_margin
    window_bounds: list[tuple[int, float, float]] = []
    op_centers: dict[tuple[int, int], float] = {}
    teleport_centers: dict[int, float] = {}
    measurement_arrows: list[_MeasurementArrow] = []
    for offset, selected in enumerate(selected_windows):
        window_start = x_cursor
        for op_offset, _ in enumerate(selected.ops):
            op_centers[(selected.window_index, op_offset)] = (
                x_cursor + op_step / 2
            )
            x_cursor += op_step
        if selected.omitted_ops > 0:
            x_cursor += op_step
        window_end = x_cursor
        window_bounds.append((selected.window_index, window_start, window_end))
        if offset < len(selected_windows) - 1:
            teleport_centers[selected.window_index] = (
                x_cursor + inter_window_gap / 2
            )
            x_cursor += inter_window_gap

    if header_visible:
        _draw_title(
            canvas,
            width=width,
            center_x=46.0,
            title=resolved_title,
            subtitle=_circuit_subtitle(
                selected_windows, windows, max_ops_per_window
            ),
            anchor="start",
        )
    _draw_circuit_legend(
        canvas,
        x=width - _CIRCUIT_LEGEND_WIDTH - 24.0,
        y=legend_y,
    )
    _draw_circuit_background(
        canvas,
        bounds=window_bounds,
        top=header_height - 20.0,
        height=background_height,
    )
    _draw_slot_labels(
        canvas,
        slot_layout,
        left_margin=left_margin,
        right=plot_right,
        top=header_height,
    )
    _draw_slot_wires(
        canvas,
        slot_layout,
        left=left_margin,
        right=plot_right,
        top=header_height,
    )
    if classical_layout is not None:
        _draw_quantum_classical_separator(
            canvas,
            left=left_margin - 10.0,
            right=plot_right,
            y=classical_top - classical_section_gap / 2,
        )
        _draw_classical_labels(
            canvas,
            classical_layout,
            left_margin=left_margin,
            top=classical_top,
        )
        _draw_classical_wires(
            canvas,
            classical_layout,
            left=left_margin,
            right=plot_right,
            top=classical_top,
        )
    _draw_window_headers(canvas, window_bounds, y=header_height - 28.0)

    for selected in selected_windows:
        window_positions = positions_by_window[selected.window_index]
        for op_offset, op in enumerate(selected.ops):
            x_center = op_centers[(selected.window_index, op_offset)]
            slot_positions = tuple(
                window_positions[q] for q in op.qubit_indices
            )
            y_positions = tuple(
                header_height + slot_layout.y_by_position[pos]
                for pos in slot_positions
            )
            qpu_ids = tuple(position[0] for position in slot_positions)
            is_remote = len(set(qpu_ids)) > 1
            _draw_gate(
                canvas,
                x_center=x_center,
                y_positions=y_positions,
                label=_gate_label(op.name, is_remote),
                is_remote=is_remote,
            )
            cbit_key = _measurement_cbit_key(circuit, op)
            if cbit_key is not None and classical_layout is not None:
                measurement_arrows.append(
                    _MeasurementArrow(
                        x=x_center,
                        start_y=y_positions[0] + 11.0,
                        cbit_key=cbit_key,
                    )
                )

        if selected.omitted_ops > 0:
            omitted_x = _omitted_ops_x(
                bounds=window_bounds,
                window_index=selected.window_index,
            )
            canvas.text(
                x=omitted_x,
                y=header_height - 6.0,
                text=f"+{selected.omitted_ops} ops",
                fill=_MUTED_TEXT,
                font_size=11.0,
                anchor="middle",
            )

    for selected_index in range(len(selected_windows) - 1):
        selected = selected_windows[selected_index]
        next_selected = selected_windows[selected_index + 1]
        boundary_index = selected.window_index
        center_x = teleport_centers[boundary_index]
        for swap in swap_schedule[boundary_index]:
            _draw_teleport_pair(
                canvas,
                center_x=center_x,
                start_y=header_height + slot_layout.y_by_position[swap.pos0],
                end_y=header_height + slot_layout.y_by_position[swap.pos1],
            )
            _draw_teleport_pair(
                canvas,
                center_x=center_x + 5.0,
                start_y=header_height + slot_layout.y_by_position[swap.pos1],
                end_y=header_height + slot_layout.y_by_position[swap.pos0],
            )
        del next_selected

    if classical_layout is not None:
        for arrow in measurement_arrows:
            target_y = (
                classical_top + classical_layout.y_by_cbit[arrow.cbit_key]
            )
            _draw_measurement_arrow(
                canvas,
                x=arrow.x,
                start_y=arrow.start_y,
                end_y=target_y,
            )

    return canvas.to_document()

plot_operation_gantt

plot_operation_gantt(
    circuit: Circuit,
    *,
    schedule: PartitionSchedule | None = None,
    windows: PartitionWindows | None = None,
    start_window: int = 0,
    max_windows: int | None = None,
    max_ops_per_window: int | None = None,
    title: str | None = None,
) -> SvgDocument

Render an operation-level Gantt chart as SVG.

Time progresses left-to-right in unit intervals, and every operation spans one interval. Operations that share a DAG layer occupy the same time slot and are stacked on separate rows so parallel work appears vertically aligned instead of serialized along the x-axis.

Parameters:

Name Type Description Default
circuit Circuit

Circuit to render.

required
schedule PartitionSchedule | None

Optional partition schedule used for QPU-aware placement.

None
windows PartitionWindows | None

Optional partition windows aligned with schedule.

None
start_window int

First window to render.

0
max_windows int | None

Optional cap on the number of windows to render.

None
max_ops_per_window int | None

Optional cap on visible operations per window.

None
title str | None

Optional chart title.

None

Returns:

Type Description
SvgDocument

An SVG document containing the Gantt visualization.

Raises:

Type Description
ValueError

If schedule and windows do not align or the selected window slice is empty.

Source code in src/memq_dqc/visualization/compiler_visualizer.py
def plot_operation_gantt(
    circuit: Circuit,
    *,
    schedule: PartitionSchedule | None = None,
    windows: PartitionWindows | None = None,
    start_window: int = 0,
    max_windows: int | None = None,
    max_ops_per_window: int | None = None,
    title: str | None = None,
) -> SvgDocument:
    """Render an operation-level Gantt chart as SVG.

    Time progresses left-to-right in unit intervals, and every operation spans
    one interval. Operations that share a DAG layer occupy the same time slot
    and are stacked on separate rows so parallel work appears vertically
    aligned instead of serialized along the x-axis.

    Args:
        circuit: Circuit to render.
        schedule: Optional partition schedule used for QPU-aware placement.
        windows: Optional partition windows aligned with ``schedule``.
        start_window: First window to render.
        max_windows: Optional cap on the number of windows to render.
        max_ops_per_window: Optional cap on visible operations per window.
        title: Optional chart title.

    Returns:
        An SVG document containing the Gantt visualization.

    Raises:
        ValueError: If schedule and windows do not align or the selected
            window slice is empty.
    """
    if not hasattr(circuit, "mono"):
        raise ValueError(
            "plot_operation_gantt expects a Circuit plus aligned "
            "schedule/windows. Pass partitioner.circuit instead of "
            "partitioner.circuit.distributed."
        )

    if (schedule is None) != (windows is None):
        raise ValueError("schedule and windows must be provided together.")

    if schedule is None or windows is None:
        windows = [list(circuit.mono.ops)]
        schedule = [_single_qpu_assignment(circuit.mono.ops)]

    if len(schedule) != len(windows):
        raise ValueError("schedule and windows must have the same length.")
    if not schedule:
        raise ValueError("schedule must contain at least one window.")

    selected_windows = _select_windows(
        windows,
        start_window=start_window,
        max_windows=max_windows,
        max_ops_per_window=max_ops_per_window,
    )
    if not selected_windows:
        raise ValueError("Selected window slice is empty.")

    slot_layout = _build_slot_layout(schedule)
    positions_by_window = [
        _assignment_positions(window) for window in schedule
    ]
    remote_ops = _remote_op_ids(circuit, schedule, windows)
    header_visible = title != ""
    resolved_title = "Operation Gantt" if title is None else title
    legend_y = 24.0 if header_visible else 12.0

    header_height = 110.0 if header_visible else 62.0
    left_margin = 138.0
    right_padding = 28.0
    bottom_padding = 52.0
    bar_height = 18.0
    interval_width = 88.0
    axis_top = header_height - 6.0
    lane_top = header_height + 8.0

    tasks, window_time_bounds, total_intervals = _build_gantt_tasks(
        selected_windows,
        positions_by_window=positions_by_window,
        remote_ops=remote_ops,
    )
    plot_right = left_margin + max(1, total_intervals) * interval_width
    width = int(max(plot_right + right_padding, 760.0))
    height = int(header_height + slot_layout.total_height + bottom_padding)
    canvas = SvgCanvas(width=width, height=height, background="#fffdfc")

    if header_visible:
        _draw_title(
            canvas,
            width=width,
            center_x=46.0,
            title=resolved_title,
            subtitle=_circuit_subtitle(
                selected_windows,
                windows,
                max_ops_per_window,
            ),
            anchor="start",
        )
    _draw_gantt_legend(canvas, x=width - 252.0, y=legend_y)
    _draw_gantt_window_backgrounds(
        canvas,
        bounds=window_time_bounds,
        left_margin=left_margin,
        interval_width=interval_width,
        top=header_height - 18.0,
        height=slot_layout.total_height + 18.0,
    )
    _draw_slot_labels(
        canvas,
        slot_layout,
        left_margin=left_margin,
        right=plot_right,
        top=lane_top,
    )
    _draw_slot_wires(
        canvas,
        slot_layout,
        left=left_margin,
        right=plot_right,
        top=lane_top,
    )
    _draw_gantt_time_axis(
        canvas,
        total_intervals=total_intervals,
        left_margin=left_margin,
        interval_width=interval_width,
        top=axis_top,
        bottom=lane_top + slot_layout.total_height - 12.0,
        right=plot_right,
    )
    _draw_gantt_window_headers(
        canvas,
        bounds=window_time_bounds,
        left_margin=left_margin,
        interval_width=interval_width,
        y=header_height - 28.0,
    )

    for task in tasks:
        y_positions = tuple(
            lane_top + slot_layout.y_by_position[position]
            for position in task.slot_positions
        )
        _draw_gantt_operation(
            canvas,
            left=left_margin + task.time_index * interval_width + 10.0,
            right=left_margin + (task.time_index + 1) * interval_width - 10.0,
            y_positions=y_positions,
            label=_gate_label(task.op.name, task.is_remote),
            op_name=task.op.name,
            is_remote=task.is_remote,
            bar_height=bar_height,
        )

    for selected in selected_windows:
        if selected.omitted_ops > 0:
            omitted_x = _omitted_ops_x(
                bounds=[
                    (
                        window_index,
                        left_margin + start_time * interval_width,
                        left_margin + end_time * interval_width,
                    )
                    for window_index, start_time, end_time in window_time_bounds
                ],
                window_index=selected.window_index,
            )
            canvas.text(
                x=omitted_x,
                y=header_height - 6.0,
                text=f"+{selected.omitted_ops} ops",
                fill=_MUTED_TEXT,
                font_size=11.0,
                anchor="middle",
            )

    canvas.text(
        x=width / 2,
        y=height - 18.0,
        text="Time interval",
        fill=_MUTED_TEXT,
        font_size=12.0,
        anchor="middle",
    )

    return canvas.to_document()

plot_partition_flow

plot_partition_flow(
    schedule: PartitionSchedule,
    *,
    show_node_counts: bool | None = None,
    title: str | None = None,
) -> SvgDocument

Render an alluvial-style partition flow view as SVG.

Parameters:

Name Type Description Default
schedule PartitionSchedule

Timeline of partition assignments.

required
show_node_counts bool | None

Whether occupancy labels should be drawn inside the QPU boxes. If omitted, labels appear only for shorter schedules.

None
title str | None

Optional chart title.

None

Returns:

Type Description
SvgDocument

An SVG document containing the partition-flow visualization.

Source code in src/memq_dqc/visualization/compiler_visualizer.py
def plot_partition_flow(
    schedule: PartitionSchedule,
    *,
    show_node_counts: bool | None = None,
    title: str | None = None,
) -> SvgDocument:
    """Render an alluvial-style partition flow view as SVG.

    Args:
        schedule: Timeline of partition assignments.
        show_node_counts: Whether occupancy labels should be drawn inside the
            QPU boxes. If omitted, labels appear only for shorter schedules.
        title: Optional chart title.

    Returns:
        An SVG document containing the partition-flow visualization.
    """
    assignments = _assignment_maps(schedule)
    qpu_ids = _sorted_qpu_ids(schedule)
    if show_node_counts is None:
        show_node_counts = len(schedule) <= 30
    header_visible = title != ""
    resolved_title = "Partition Flow" if title is None else title

    top = 102.0 if header_visible else 74.0
    left = 54.0
    right = 18.0
    bottom = 36.0
    lane_step = 72.0
    window_step = 16.0 if len(schedule) > 60 else 22.0
    base_width = left + right + (len(schedule) - 1) * window_step + 18.0
    width = int(max(base_width, 480.0))
    height = int(top + bottom + max(1, len(qpu_ids) - 1) * lane_step + 36.0)
    canvas = SvgCanvas(width=width, height=height, background="#ffffff")

    if header_visible:
        _draw_title(
            canvas,
            width=width,
            title=resolved_title,
            subtitle="QPU occupancy and migration between partition windows",
        )
    _draw_flow_legend(canvas, x=left, y=16.0 if not header_visible else 72.0)

    y_by_qpu = {
        qpu_id: top + idx * lane_step for idx, qpu_id in enumerate(qpu_ids)
    }
    for qpu_id, y in y_by_qpu.items():
        canvas.line(
            x1=left - 6.0,
            y1=y,
            x2=width - right,
            y2=y,
            stroke="#e5e7eb",
            stroke_width=1.0,
        )
        canvas.text(
            x=left - 20.0,
            y=y + 5.0,
            text=f"QPU {qpu_id}",
            fill=_TEXT_COLOR,
            font_size=12.0,
            anchor="end",
        )

    transition_counts = _transition_counts(assignments)
    for window_idx, flows in transition_counts.items():
        x0 = left + window_idx * window_step
        x1 = x0 + window_step
        for (src_qpu, dst_qpu), count in sorted(flows.items()):
            y0 = y_by_qpu[src_qpu]
            y1 = y_by_qpu[dst_qpu]
            canvas.path(
                d=(
                    f"M {x0:.2f} {y0:.2f} "
                    f"C {x0 + window_step * 0.35:.2f} {y0:.2f}, "
                    f"{x1 - window_step * 0.35:.2f} {y1:.2f}, "
                    f"{x1:.2f} {y1:.2f}"
                ),
                stroke=_qpu_color(src_qpu),
                stroke_width=0.9 + count * 0.65,
                opacity=0.18 if src_qpu == dst_qpu else 0.42,
            )

    for window_idx, window in enumerate(schedule):
        x = left + window_idx * window_step
        for qpu, qubits in sorted(window.items(), key=lambda item: item[0].id):
            y = y_by_qpu[qpu.id]
            canvas.rect(
                x=x - 6.0,
                y=y - 16.0,
                width=12.0,
                height=32.0,
                fill="#ffffff",
                stroke=_qpu_color(qpu.id),
                stroke_width=1.0,
                rx=4.5,
            )
            if show_node_counts:
                canvas.text(
                    x=x,
                    y=y + 4.0,
                    text=str(len(qubits)),
                    fill=_TEXT_COLOR,
                    font_size=9.0,
                    anchor="middle",
                )

    return canvas.to_document()

plot_window_activity

plot_window_activity(
    circuit: Circuit,
    schedule: PartitionSchedule,
    windows: PartitionWindows,
    *,
    title: str | None = None,
) -> SvgDocument

Render per-window gate composition and movement pressure as SVG.

Parameters:

Name Type Description Default
circuit Circuit

Circuit providing the operation set.

required
schedule PartitionSchedule

Partition schedule aligned with windows.

required
windows PartitionWindows

Operation windows from the partitioner.

required
title str | None

Optional chart title.

None

Returns:

Type Description
SvgDocument

An SVG document containing the window-activity summary.

Source code in src/memq_dqc/visualization/compiler_visualizer.py
def plot_window_activity(
    circuit: Circuit,
    schedule: PartitionSchedule,
    windows: PartitionWindows,
    *,
    title: str | None = None,
) -> SvgDocument:
    """Render per-window gate composition and movement pressure as SVG.

    Args:
        circuit: Circuit providing the operation set.
        schedule: Partition schedule aligned with ``windows``.
        windows: Operation windows from the partitioner.
        title: Optional chart title.

    Returns:
        An SVG document containing the window-activity summary.
    """
    if len(schedule) != len(windows):
        raise ValueError("schedule and windows must have the same length.")
    if not schedule:
        raise ValueError("schedule must contain at least one window.")
    header_visible = title != ""
    resolved_title = "Window Activity" if title is None else title

    remote_ops = _remote_op_ids(circuit, schedule, windows)
    single_counts: list[int] = []
    local_two_counts: list[int] = []
    remote_two_counts: list[int] = []
    for window in windows:
        single_count = 0
        local_two_count = 0
        remote_two_count = 0
        for op in window:
            if len(op.qubits) == 1:
                single_count += 1
            elif op.op_id in remote_ops:
                remote_two_count += 1
            else:
                local_two_count += 1
        single_counts.append(single_count)
        local_two_counts.append(local_two_count)
        remote_two_counts.append(remote_two_count)

    movement = _movement_counts(_assignment_maps(schedule))
    max_ops = max(
        single + local + remote
        for single, local, remote in zip(
            single_counts,
            local_two_counts,
            remote_two_counts,
            strict=True,
        )
    )
    max_movement = max(movement, default=0)

    top = 110.0 if header_visible else 86.0
    left = 54.0
    right = 42.0
    bottom = 38.0
    chart_height = 246.0
    window_step = 14.0 if len(windows) > 80 else 22.0
    bar_width = max(5.0, min(18.0, window_step * 0.7))
    base_width = left + right + (len(windows) - 1) * window_step + 22.0
    width = int(max(base_width, 500.0))
    height = int(top + bottom + chart_height)
    canvas = SvgCanvas(width=width, height=height, background="#ffffff")

    if header_visible:
        _draw_title(
            canvas,
            width=width,
            title=resolved_title,
            subtitle="Stacked gate counts with movement pressure overlay",
        )
    _draw_activity_legend(
        canvas, x=left, y=16.0 if not header_visible else 72.0
    )

    chart_bottom = top + chart_height
    for tick in range(5):
        y = chart_bottom - chart_height * tick / 4
        canvas.line(
            x1=left,
            y1=y,
            x2=width - right,
            y2=y,
            stroke="#eef2f7",
            stroke_width=1.0,
        )
        value = max_ops * tick / 4
        canvas.text(
            x=left - 10.0,
            y=y + 4.0,
            text=f"{value:.0f}",
            fill=_MUTED_TEXT,
            font_size=10.0,
            anchor="end",
        )

    for window_idx in range(len(windows)):
        x = left + window_idx * window_step
        single_height = (
            chart_height * single_counts[window_idx] / max(1, max_ops)
        )
        local_height = (
            chart_height * local_two_counts[window_idx] / max(1, max_ops)
        )
        remote_height = (
            chart_height * remote_two_counts[window_idx] / max(1, max_ops)
        )
        current_top = chart_bottom
        for height_value, fill in (
            (single_height, "#dbeafe"),
            (local_height, "#c4b5fd"),
            (remote_height, "#d702fe"),
        ):
            if height_value <= 0:
                continue
            current_top -= height_value
            canvas.rect(
                x=x - bar_width / 2,
                y=current_top,
                width=bar_width,
                height=height_value,
                fill=fill,
                stroke="none",
                rx=2.0,
            )

    if movement:
        movement_points = []
        for offset, count in enumerate(movement, start=1):
            x = left + offset * window_step
            y = chart_bottom - chart_height * count / max(1, max_movement)
            movement_points.append((x, y))
        path_segments = [
            f"M {movement_points[0][0]:.2f} {movement_points[0][1]:.2f}"
        ]
        path_segments.extend(
            f"L {x:.2f} {y:.2f}" for x, y in movement_points[1:]
        )
        canvas.path(
            d=" ".join(path_segments),
            stroke="#4801b0",
            stroke_width=2.0,
        )
        for x, y in movement_points:
            canvas.circle(cx=x, cy=y, r=2.8, fill="#4801b0")
        for tick in range(5):
            y = chart_bottom - chart_height * tick / 4
            value = max_movement * tick / 4
            canvas.text(
                x=width - right + 10.0,
                y=y + 4.0,
                text=f"{value:.0f}",
                fill=_MUTED_TEXT,
                font_size=10.0,
                anchor="start",
            )

    canvas.text(
        x=width / 2,
        y=height - 18.0,
        text="Partition window",
        fill=_MUTED_TEXT,
        font_size=12.0,
        anchor="middle",
    )

    return canvas.to_document()

build_dag_networkx_graph

build_dag_networkx_graph(dag: CircuitDAG) -> DiGraph

Build an augmented NetworkX graph for DAG visualization.

The visualization graph adds synthetic input and output nodes for each qubit wire so the rendered layout reads like a circuit-flow graph rather than a generic dependency diagram.

Parameters:

Name Type Description Default
dag CircuitDAG

Circuit DAG to augment for visualization.

required

Returns:

Type Description
DiGraph

A directed graph containing qubit input nodes, operation nodes, qubit

DiGraph

output nodes, and dependency edges annotated by qubit labels.

Source code in src/memq_dqc/visualization/dag_visualizer.py
def build_dag_networkx_graph(dag: CircuitDAG) -> nx.DiGraph:
    """Build an augmented NetworkX graph for DAG visualization.

    The visualization graph adds synthetic input and output nodes for each
    qubit wire so the rendered layout reads like a circuit-flow graph rather
    than a generic dependency diagram.

    Args:
        dag: Circuit DAG to augment for visualization.

    Returns:
        A directed graph containing qubit input nodes, operation nodes, qubit
        output nodes, and dependency edges annotated by qubit labels.
    """
    graph = nx.DiGraph()
    qubits = _sorted_qubits(dag)

    for qubit_index, qubit in enumerate(qubits):
        label = _format_qubit_label(qubit)
        input_node = _input_node_id(qubit)
        output_node = _output_node_id(qubit)
        graph.add_node(
            input_node,
            kind="input",
            label=label,
            qubits=(qubit,),
            wire_index=qubit_index,
        )
        graph.add_node(
            output_node,
            kind="output",
            label=label,
            qubits=(qubit,),
            wire_index=qubit_index,
        )

    ops_by_qubit: dict[CircuitQubit, list[_VisualNode]] = defaultdict(list)
    for node_id in sorted(dag.graph.nodes):
        op = dag.graph.nodes[node_id]["op"]
        visual_node = ("op", op.op_id)
        graph.add_node(
            visual_node,
            kind="operation",
            label=op.name,
            op=op,
            qubits=op.qubits,
        )
        for qubit in op.qubits:
            ops_by_qubit[qubit].append(visual_node)

    for qubit in qubits:
        previous_node: _VisualNode = _input_node_id(qubit)
        for current_node in ops_by_qubit[qubit]:
            _add_qubit_edge(
                graph,
                previous_node,
                current_node,
                qubit,
            )
            previous_node = current_node
        _add_qubit_edge(
            graph,
            previous_node,
            _output_node_id(qubit),
            qubit,
        )

    return graph

plot_circuit_dag

plot_circuit_dag(
    circuit_or_dag: Circuit | CircuitDAG,
    *,
    ax: Axes | None = None,
    title: str = "Circuit DAG",
    show_edge_labels: bool = False,
) -> Axes

Render the monolithic circuit DAG.

Parameters:

Name Type Description Default
circuit_or_dag Circuit | CircuitDAG

Circuit or DAG to plot.

required
ax Axes | None

Existing axes to draw into.

None
title str

Plot title.

'Circuit DAG'
show_edge_labels bool

Whether qubit labels should be shown on edges.

False

Returns:

Type Description
Axes

The Matplotlib axes containing the rendered DAG.

Source code in src/memq_dqc/visualization/dag_visualizer.py
def plot_circuit_dag(
    circuit_or_dag: Circuit | CircuitDAG,
    *,
    ax: Axes | None = None,
    title: str = "Circuit DAG",
    show_edge_labels: bool = False,
) -> Axes:
    """Render the monolithic circuit DAG.

    Args:
        circuit_or_dag: Circuit or DAG to plot.
        ax: Existing axes to draw into.
        title: Plot title.
        show_edge_labels: Whether qubit labels should be shown on edges.

    Returns:
        The Matplotlib axes containing the rendered DAG.
    """
    return plot_dag(
        _resolve_circuit_dag(circuit_or_dag),
        ax=ax,
        title=title,
        show_edge_labels=show_edge_labels,
    )

plot_dag

plot_dag(
    dag: CircuitDAG,
    *,
    ax: Axes | None = None,
    title: str | None = None,
    show_edge_labels: bool = False,
) -> Axes

Render a circuit DAG as a top-to-bottom NetworkX graph.

Parameters:

Name Type Description Default
dag CircuitDAG

DAG to visualize.

required
ax Axes | None

Existing axes to draw into. A new figure and axes are created when omitted.

None
title str | None

Optional plot title.

None
show_edge_labels bool

Whether qubit labels should be shown on edges.

False

Returns:

Type Description
Axes

The Matplotlib axes containing the rendered DAG.

Source code in src/memq_dqc/visualization/dag_visualizer.py
def plot_dag(
    dag: CircuitDAG,
    *,
    ax: Axes | None = None,
    title: str | None = None,
    show_edge_labels: bool = False,
) -> Axes:
    """Render a circuit DAG as a top-to-bottom NetworkX graph.

    Args:
        dag: DAG to visualize.
        ax: Existing axes to draw into. A new figure and axes are created when
            omitted.
        title: Optional plot title.
        show_edge_labels: Whether qubit labels should be shown on edges.

    Returns:
        The Matplotlib axes containing the rendered DAG.
    """
    graph = build_dag_networkx_graph(dag)
    positions = _build_dag_positions(graph)

    if ax is None:
        _, ax = plt.subplots(figsize=_figure_size_for_graph(graph))

    node_kinds = {
        "input": [],
        "operation": [],
        "output": [],
    }
    for node, data in graph.nodes(data=True):
        node_kinds[data["kind"]].append(node)

    nx.draw_networkx_edges(
        graph,
        positions,
        ax=ax,
        edge_color=_EDGE_COLOR,
        arrows=True,
        arrowstyle="-|>",
        arrowsize=14,
        width=1.4,
        min_source_margin=10,
        min_target_margin=10,
    )
    nx.draw_networkx_nodes(
        graph,
        positions,
        nodelist=node_kinds["input"],
        node_color=_INPUT_NODE_COLOR,
        edgecolors="#355e1d",
        linewidths=1.0,
        node_size=760,
        ax=ax,
    )
    nx.draw_networkx_nodes(
        graph,
        positions,
        nodelist=node_kinds["operation"],
        node_color=_OPERATION_NODE_COLOR,
        edgecolors="#466392",
        linewidths=1.0,
        node_size=920,
        ax=ax,
    )
    nx.draw_networkx_nodes(
        graph,
        positions,
        nodelist=node_kinds["output"],
        node_color=_OUTPUT_NODE_COLOR,
        edgecolors="#8f2424",
        linewidths=1.0,
        node_size=760,
        ax=ax,
    )
    nx.draw_networkx_labels(
        graph,
        positions,
        labels={node: data["label"] for node, data in graph.nodes(data=True)},
        font_size=9,
        font_family="sans-serif",
        ax=ax,
    )

    if show_edge_labels:
        nx.draw_networkx_edge_labels(
            graph,
            positions,
            edge_labels={
                (u, v): data["label"] for u, v, data in graph.edges(data=True)
            },
            font_size=7,
            font_color="#374151",
            label_pos=0.55,
            rotate=False,
            bbox={"alpha": 0.0, "pad": 0.0},
            ax=ax,
        )

    if title is not None:
        ax.set_title(title)
    ax.set_axis_off()
    ax.invert_yaxis()
    ax.margins(x=0.16, y=0.08)
    return ax

plot_distributed_dag

plot_distributed_dag(
    circuit_or_dag: Circuit
    | DistributedCircuit
    | CircuitDAG,
    *,
    ax: Axes | None = None,
    title: str = "Distributed DAG",
    show_edge_labels: bool = False,
) -> Axes

Render the distributed circuit DAG.

Parameters:

Name Type Description Default
circuit_or_dag Circuit | DistributedCircuit | CircuitDAG

Circuit, distributed circuit wrapper, or DAG to plot.

required
ax Axes | None

Existing axes to draw into.

None
title str

Plot title.

'Distributed DAG'
show_edge_labels bool

Whether qubit labels should be shown on edges.

False

Returns:

Type Description
Axes

The Matplotlib axes containing the rendered DAG.

Raises:

Type Description
ValueError

If the circuit does not yet have a distributed DAG.

Source code in src/memq_dqc/visualization/dag_visualizer.py
def plot_distributed_dag(
    circuit_or_dag: Circuit | DistributedCircuit | CircuitDAG,
    *,
    ax: Axes | None = None,
    title: str = "Distributed DAG",
    show_edge_labels: bool = False,
) -> Axes:
    """Render the distributed circuit DAG.

    Args:
        circuit_or_dag: Circuit, distributed circuit wrapper, or DAG to plot.
        ax: Existing axes to draw into.
        title: Plot title.
        show_edge_labels: Whether qubit labels should be shown on edges.

    Returns:
        The Matplotlib axes containing the rendered DAG.

    Raises:
        ValueError: If the circuit does not yet have a distributed DAG.
    """
    return plot_dag(
        _resolve_distributed_dag(circuit_or_dag),
        ax=ax,
        title=title,
        show_edge_labels=show_edge_labels,
    )

animate_circuit_execution

animate_circuit_execution(
    network: NetworkGraph,
    schedule: OperationSchedule,
    *,
    mode: PlaybackMode = "events",
    num_frames: int = 240,
    interval: int = 400,
    repeat: bool = True,
    title: str | None = None,
    figsize: tuple[float, float] | None = None,
    pos: dict[PhysicalQubit, tuple[float, float]]
    | None = None,
    show_labels: bool = True,
    controls: bool = False,
) -> NetworkExecutionAnimation

Animate a schedule over its network graph.

Parameters:

Name Type Description Default
network NetworkGraph

Network the schedule was produced for. Its graph supplies the nodes (physical qubits) and the local/remote edges.

required
schedule OperationSchedule

Operation schedule to play back.

required
mode PlaybackMode

"events" for one frame per event boundary, or "time" for uniform time sampling across the makespan.

'events'
num_frames int

Number of frames to sample in "time" mode. Ignored in "events" mode, where the schedule fixes the frame count.

240
interval int

Delay between frames in milliseconds.

400
repeat bool

Whether playback loops back to the start when it finishes.

True
title str | None

Figure title. Defaults to a generated summary of the schedule.

None
figsize tuple[float, float] | None

Figure size in inches.

None
pos dict[PhysicalQubit, tuple[float, float]] | None

Explicit node positions. Defaults to qpu_clustered_layout.

None
show_labels bool

Whether to draw physical-qubit labels on the nodes.

True
controls bool

Whether to reserve space for, and attach, play/pause and scrub widgets. NetworkExecutionAnimation.show enables this automatically, so it is only needed when embedding the figure.

False

Returns:

Type Description
NetworkExecutionAnimation

The animation wrapper. Keep a reference to it for as long as playback

NetworkExecutionAnimation

should continue; dropping it lets the underlying timer be collected.

Raises:

Type Description
ValueError

If the schedule has no events, if mode is unknown, or if the schedule references qubits absent from the network.

Source code in src/memq_dqc/visualization/execution_animator.py
def animate_circuit_execution(
    network: NetworkGraph,
    schedule: OperationSchedule,
    *,
    mode: PlaybackMode = "events",
    num_frames: int = 240,
    interval: int = 400,
    repeat: bool = True,
    title: str | None = None,
    figsize: tuple[float, float] | None = None,
    pos: dict[PhysicalQubit, tuple[float, float]] | None = None,
    show_labels: bool = True,
    controls: bool = False,
) -> NetworkExecutionAnimation:
    """Animate a schedule over its network graph.

    Args:
        network: Network the schedule was produced for. Its graph supplies the
            nodes (physical qubits) and the local/remote edges.
        schedule: Operation schedule to play back.
        mode: ``"events"`` for one frame per event boundary, or ``"time"`` for
            uniform time sampling across the makespan.
        num_frames: Number of frames to sample in ``"time"`` mode. Ignored in
            ``"events"`` mode, where the schedule fixes the frame count.
        interval: Delay between frames in milliseconds.
        repeat: Whether playback loops back to the start when it finishes.
        title: Figure title. Defaults to a generated summary of the schedule.
        figsize: Figure size in inches.
        pos: Explicit node positions. Defaults to
            [qpu_clustered_layout][memq_dqc.visualization.execution_animator.qpu_clustered_layout].
        show_labels: Whether to draw physical-qubit labels on the nodes.
        controls: Whether to reserve space for, and attach, play/pause and
            scrub widgets. [NetworkExecutionAnimation.show][memq_dqc.visualization.execution_animator.NetworkExecutionAnimation.show] enables this
            automatically, so it is only needed when embedding the figure.

    Returns:
        The animation wrapper. Keep a reference to it for as long as playback
        should continue; dropping it lets the underlying timer be collected.

    Raises:
        ValueError: If the schedule has no events, if ``mode`` is unknown, or
            if the schedule references qubits absent from the network.
    """
    animation = NetworkExecutionAnimation(
        network=network,
        schedule=schedule,
        mode=mode,
        num_frames=num_frames,
        interval=interval,
        repeat=repeat,
        title=title,
        figsize=figsize,
        pos=pos,
        show_labels=show_labels,
        controls=controls,
    )
    return animation

qpu_clustered_layout

qpu_clustered_layout(
    network: NetworkGraph,
    *,
    cluster_scale: float = 0.45,
    seed: int = 7,
) -> dict[PhysicalQubit, tuple[float, float]]

Lay out a network graph as one visual cluster per QPU.

Each QPU's qubits are laid out with a spring layout over that QPU's local edges only, normalized into a disk, and then placed at a QPU centre spaced evenly around a circle. Intra-QPU edges therefore stay short and inside a cluster while inter-QPU edges visibly span between clusters, which is the property that makes the two connection types easy to tell apart.

The circle the centres sit on grows with the QPU count so that clusters never collide, and two QPUs are placed side by side rather than stacked.

Parameters:

Name Type Description Default
network NetworkGraph

Network whose graph should be laid out.

required
cluster_scale float

Radius of one QPU cluster in layout units.

0.45
seed int

Seed for the per-QPU spring layout, so layouts are reproducible.

7

Returns:

Type Description
dict[PhysicalQubit, tuple[float, float]]

Mapping of every physical qubit to its (x, y) position.

Source code in src/memq_dqc/visualization/execution_animator.py
def qpu_clustered_layout(
    network: NetworkGraph,
    *,
    cluster_scale: float = 0.45,
    seed: int = 7,
) -> dict[PhysicalQubit, tuple[float, float]]:
    """Lay out a network graph as one visual cluster per QPU.

    Each QPU's qubits are laid out with a spring layout over that QPU's local
    edges only, normalized into a disk, and then placed at a QPU centre spaced
    evenly around a circle. Intra-QPU edges therefore stay short and inside a
    cluster while inter-QPU edges visibly span between clusters, which is the
    property that makes the two connection types easy to tell apart.

    The circle the centres sit on grows with the QPU count so that clusters
    never collide, and two QPUs are placed side by side rather than stacked.

    Args:
        network: Network whose graph should be laid out.
        cluster_scale: Radius of one QPU cluster in layout units.
        seed: Seed for the per-QPU spring layout, so layouts are reproducible.

    Returns:
        Mapping of every physical qubit to its ``(x, y)`` position.
    """
    graph = network.graph
    qpu_ids = [
        qpu_id
        for qpu_id in network.qpu_ids()
        if any(node.qpu_id == qpu_id for node in graph.nodes)
    ]
    positions: dict[PhysicalQubit, tuple[float, float]] = {}
    num_qpus = len(qpu_ids)
    if num_qpus == 0:
        return positions

    network_radius = _network_radius(num_qpus, cluster_scale)
    for index, qpu_id in enumerate(qpu_ids):
        centre = _qpu_centre(index, num_qpus, network_radius)
        members = [node for node in graph.nodes if node.qpu_id == qpu_id]
        local_subgraph = graph.subgraph(members).copy()
        local_subgraph.remove_edges_from(
            [
                (u, v)
                for u, v, data in local_subgraph.edges(data=True)
                if data.get("connection_type") != "local"
            ]
        )
        local_positions = nx.spring_layout(
            local_subgraph,
            seed=seed,
            iterations=120,
        )
        for node, offset in _normalized_offsets(local_positions).items():
            positions[node] = (
                centre[0] + cluster_scale * offset[0],
                centre[1] + cluster_scale * offset[1],
            )
    return positions

plot_migration_timeline

plot_migration_timeline(
    partition: PartitionTimeline,
    *,
    title: str | None = None,
    window_entanglement_cost: list[float] | None = None,
) -> SvgDocument

Render moved-qubits-per-window as an SVG line chart.

Parameters:

Name Type Description Default
partition PartitionTimeline

Timeline of partitions (window -> QPU -> qubit set).

required
title str | None

Optional chart title.

None
window_entanglement_cost list[float] | None

Optional series to plot on a secondary axis.

None

Returns:

Type Description
SvgDocument

An SVG document containing the migration timeline.

Source code in src/memq_dqc/visualization/partition_visualizer.py
def plot_migration_timeline(
    partition: PartitionTimeline,
    *,
    title: str | None = None,
    window_entanglement_cost: list[float] | None = None,
) -> SvgDocument:
    """Render moved-qubits-per-window as an SVG line chart.

    Args:
        partition: Timeline of partitions (window -> QPU -> qubit set).
        title: Optional chart title.
        window_entanglement_cost: Optional series to plot on a secondary axis.

    Returns:
        An SVG document containing the migration timeline.
    """
    assignments, _ = _assignments_and_qpu_count(partition)
    movement = _movement_counts(assignments)
    window_indices = list(range(1, len(assignments)))
    if window_entanglement_cost is not None and len(
        window_entanglement_cost
    ) != len(movement):
        raise ValueError(
            "window_entanglement_cost must match number of transitions."
        )
    header_visible = title != ""
    resolved_title = "Migration Timeline" if title is None else title

    top = 102.0 if header_visible else 74.0
    left = 50.0
    right = 44.0 if window_entanglement_cost is not None else 18.0
    bottom = 36.0
    chart_height = 228.0
    window_step = 18.0 if len(window_indices) > 60 else 24.0
    base_width = (
        left + right + max(1, len(window_indices) - 1) * window_step + 20.0
    )
    width = int(max(base_width, 420.0))
    height = int(top + bottom + chart_height)
    canvas = SvgCanvas(width=width, height=height, background="#ffffff")

    if header_visible:
        _draw_title(
            canvas,
            width=width,
            title=resolved_title,
            subtitle="Moved logical qubits across adjacent partition windows",
        )

    max_primary = max(movement, default=0)
    max_secondary = max(window_entanglement_cost or [0.0], default=0.0)
    chart_bottom = top + chart_height
    for tick in range(5):
        y = chart_bottom - chart_height * tick / 4
        canvas.line(
            x1=left,
            y1=y,
            x2=width - right,
            y2=y,
            stroke="#eef2f7",
            stroke_width=1.0,
        )
        canvas.text(
            x=left - 8.0,
            y=y + 4.0,
            text=f"{max_primary * tick / 4:.0f}",
            fill=_MUTED_TEXT,
            font_size=10.0,
            anchor="end",
        )
        if window_entanglement_cost is not None:
            canvas.text(
                x=width - right + 8.0,
                y=y + 4.0,
                text=f"{max_secondary * tick / 4:.1f}",
                fill=_MUTED_TEXT,
                font_size=10.0,
                anchor="start",
            )

    if movement:
        points = []
        for offset, value in enumerate(movement):
            x = left + offset * window_step
            y = chart_bottom - chart_height * value / max(1, max_primary)
            points.append((x, y))
        _draw_polyline(canvas, points, stroke="#4801b0", stroke_width=2.0)
        for x, y in points:
            canvas.circle(cx=x, cy=y, r=3.0, fill="#4801b0")

    if window_entanglement_cost is not None and window_entanglement_cost:
        points = []
        for offset, value in enumerate(window_entanglement_cost):
            x = left + offset * window_step
            y = chart_bottom - chart_height * value / max(1.0, max_secondary)
            points.append((x, y))
        _draw_polyline(canvas, points, stroke="#d702fe", stroke_width=1.8)
        for x, y in points:
            canvas.circle(cx=x, cy=y, r=2.4, fill="#d702fe")

    for offset, window_index in enumerate(window_indices):
        if (
            len(window_indices) <= 12
            or offset % max(1, len(window_indices) // 10) == 0
        ):
            x = left + offset * window_step
            canvas.text(
                x=x,
                y=height - 18.0,
                text=str(window_index),
                fill=_MUTED_TEXT,
                font_size=10.0,
                anchor="middle",
            )

    canvas.text(
        x=width / 2,
        y=height - 4.0,
        text="Window transition",
        fill=_MUTED_TEXT,
        font_size=12.0,
        anchor="middle",
    )
    return canvas.to_document()

plot_partition_heatmap

plot_partition_heatmap(
    partition: PartitionTimeline,
    *,
    title: str | None = None,
    top_k_most_moved: int | None = None,
    sample_stride: int | None = None,
    sort_by_final_qpu: bool = False,
    x_tick_stride: int | None = 5,
    y_tick_fontsize: int = 8,
) -> SvgDocument

Render a qubit-vs-window partition heatmap as SVG.

Parameters:

Name Type Description Default
partition PartitionTimeline

Timeline of partitions (window -> QPU -> qubit set).

required
title str | None

Optional chart title.

None
top_k_most_moved int | None

If provided, keep only the qubits that moved most often across windows.

None
sample_stride int | None

If provided, keep every Nth qubit after filtering.

None
sort_by_final_qpu bool

Whether to group rows by the final window QPU.

False
x_tick_stride int | None

Window tick spacing. If None, show every window.

5
y_tick_fontsize int

Font size for y-axis labels.

8

Returns:

Type Description
SvgDocument

An SVG document containing the heatmap.

Source code in src/memq_dqc/visualization/partition_visualizer.py
def plot_partition_heatmap(
    partition: PartitionTimeline,
    *,
    title: str | None = None,
    top_k_most_moved: int | None = None,
    sample_stride: int | None = None,
    sort_by_final_qpu: bool = False,
    x_tick_stride: int | None = 5,
    y_tick_fontsize: int = 8,
) -> SvgDocument:
    """Render a qubit-vs-window partition heatmap as SVG.

    Args:
        partition: Timeline of partitions (window -> QPU -> qubit set).
        title: Optional chart title.
        top_k_most_moved: If provided, keep only the qubits that moved most
            often across windows.
        sample_stride: If provided, keep every Nth qubit after filtering.
        sort_by_final_qpu: Whether to group rows by the final window QPU.
        x_tick_stride: Window tick spacing. If None, show every window.
        y_tick_fontsize: Font size for y-axis labels.

    Returns:
        An SVG document containing the heatmap.
    """
    assignments, num_qpus = _assignments_and_qpu_count(partition)
    qubits = _collect_qubits(assignments)
    qubit_order = _order_qubits(
        qubits,
        assignments,
        top_k_most_moved=top_k_most_moved,
        sample_stride=sample_stride,
        sort_by_final_qpu=sort_by_final_qpu,
    )
    header_visible = title != ""
    resolved_title = "Partition Heatmap" if title is None else title

    cell_width = 10.0 if len(assignments) > 80 else 16.0
    cell_height = 10.0 if len(qubit_order) > 50 else 14.0
    left = 54.0
    top = 104.0 if header_visible else 78.0
    right = 18.0
    bottom = 36.0
    legend_height = 34.0
    base_width = left + right + len(assignments) * cell_width
    width = int(max(base_width, 420.0))
    height = int(top + bottom + len(qubit_order) * cell_height + legend_height)
    canvas = SvgCanvas(width=width, height=height, background="#ffffff")

    if header_visible:
        _draw_title(
            canvas,
            width=width,
            title=resolved_title,
            subtitle=(
                "QPU assignment of each logical qubit across partition windows"
            ),
        )
    _draw_heatmap_legend(
        canvas,
        num_qpus=num_qpus,
        x=left,
        y=16.0 if not header_visible else 72.0,
    )

    for row_index, qubit in enumerate(qubit_order):
        y = top + row_index * cell_height
        if row_index % 2 == 0:
            canvas.rect(
                x=left,
                y=y,
                width=len(assignments) * cell_width,
                height=cell_height,
                fill="#f8fafc",
                opacity=0.9,
            )
        canvas.text(
            x=left - 10.0,
            y=y + cell_height * 0.72,
            text=str(qubit),
            fill=_TEXT_COLOR,
            font_size=float(y_tick_fontsize),
            anchor="end",
        )
        for col_index, assignment in enumerate(assignments):
            value = assignment.get(qubit)
            fill = "#e2e8f0" if value is None else _qpu_color(value)
            canvas.rect(
                x=left + col_index * cell_width,
                y=y,
                width=cell_width,
                height=cell_height,
                fill=fill,
                stroke="#ffffff",
                stroke_width=0.5,
            )

    if x_tick_stride is None:
        x_tick_stride = 1
    for window_index in range(0, len(assignments), max(1, x_tick_stride)):
        x = left + window_index * cell_width + cell_width / 2
        canvas.text(
            x=x,
            y=height - 18.0,
            text=str(window_index),
            fill=_MUTED_TEXT,
            font_size=10.0,
            anchor="middle",
        )

    canvas.text(
        x=width / 2,
        y=height - 4.0,
        text="Partition window",
        fill=_MUTED_TEXT,
        font_size=12.0,
        anchor="middle",
    )
    canvas.text(
        x=16.0,
        y=height / 2,
        text="Logical qubit",
        fill=_MUTED_TEXT,
        font_size=12.0,
    )
    return canvas.to_document()

build_svg_dashboard_html

build_svg_dashboard_html(
    sections: Sequence[SvgDashboardSection],
    *,
    title: str = "Visualization Dashboard",
) -> str

Build a standalone HTML dashboard for multiple SVG visualizations.

Parameters:

Name Type Description Default
sections Sequence[SvgDashboardSection]

Ordered dashboard sections to render.

required
title str

Document title shown at the top of the dashboard.

'Visualization Dashboard'

Returns:

Type Description
str

A standalone HTML document with all provided visualizations embedded.

Source code in src/memq_dqc/visualization/svg_document.py
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
def build_svg_dashboard_html(
    sections: Sequence[SvgDashboardSection],
    *,
    title: str = "Visualization Dashboard",
) -> str:
    """Build a standalone HTML dashboard for multiple SVG visualizations.

    Args:
        sections: Ordered dashboard sections to render.
        title: Document title shown at the top of the dashboard.

    Returns:
        A standalone HTML document with all provided visualizations embedded.
    """
    escaped_title = escape(title)
    nav_links = "\n".join(
        (
            '<a class="dashboard__nav-link" '
            f'href="#{_slugify(section.title)}">{escape(section.title)}</a>'
        )
        for section in sections
    )
    sections_markup = "\n".join(
        _dashboard_section_markup(section) for section in sections
    )
    return f"""<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <title>{escaped_title}</title>
  <style>
    :root {{
      color-scheme: light;
      --page: #f3f7fb;
      --page-accent: #e3eefb;
      --panel: rgba(255, 255, 255, 0.92);
      --panel-border: #cad7e6;
      --text: #102a43;
      --muted: #52606d;
      --accent: #0f766e;
      --accent-soft: rgba(15, 118, 110, 0.10);
      --shadow: 0 20px 48px rgba(16, 42, 67, 0.10);
    }}
    * {{
      box-sizing: border-box;
    }}
    html {{
      scroll-behavior: smooth;
    }}
    body {{
      margin: 0;
      color: var(--text);
      font-family: "IBM Plex Sans", "Helvetica Neue", sans-serif;
      background:
        radial-gradient(circle at top right, var(--page-accent), transparent 28%),
        linear-gradient(180deg, #fbfdff 0%, var(--page) 100%);
    }}
    .dashboard {{
      width: min(1500px, calc(100vw - 32px));
      margin: 0 auto;
      padding: 24px 0 40px;
    }}
    .dashboard__hero {{
      position: sticky;
      top: 0;
      z-index: 10;
      display: grid;
      gap: 14px;
      margin-bottom: 20px;
      padding: 18px 20px;
      border: 1px solid var(--panel-border);
      border-radius: 20px;
      background: rgba(248, 251, 255, 0.88);
      backdrop-filter: blur(14px);
      box-shadow: var(--shadow);
    }}
    .dashboard__hero h1 {{
      margin: 0;
      font-size: clamp(28px, 4vw, 42px);
      line-height: 1.05;
      letter-spacing: -0.03em;
    }}
    .dashboard__hero p {{
      margin: 0;
      color: var(--muted);
      font-size: 14px;
    }}
    .dashboard__nav {{
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }}
    .dashboard__nav-link {{
      border: 1px solid var(--panel-border);
      border-radius: 999px;
      padding: 7px 12px;
      color: var(--text);
      text-decoration: none;
      background: #ffffff;
    }}
    .dashboard__nav-link:hover {{
      border-color: var(--accent);
      color: var(--accent);
      background: var(--accent-soft);
    }}
    .dashboard__section {{
      display: grid;
      gap: 14px;
      margin-bottom: 28px;
      padding: 0;
      border: none;
      border-radius: 0;
      background: transparent;
      box-shadow: none;
    }}
    .dashboard__section-header {{
      display: grid;
      gap: 6px;
    }}
    .dashboard__section-header h2 {{
      margin: 0;
      font-size: 24px;
      line-height: 1.1;
    }}
    .dashboard__section-header p {{
      margin: 0;
      color: var(--muted);
      font-size: 14px;
    }}
    .dashboard__featured {{
      display: grid;
    }}
    .dashboard__grid {{
      display: grid;
      grid-template-columns: repeat(2, minmax(0, 1fr));
      gap: 16px;
      align-items: start;
    }}
    .dashboard-card {{
      display: grid;
      gap: 12px;
      padding: 0;
      border: none;
      border-radius: 0;
      background: transparent;
      min-width: 0;
    }}
    .dashboard-card--featured {{
      gap: 14px;
      padding: 18px;
    }}
    .dashboard-card__header {{
      display: grid;
      gap: 4px;
    }}
    .dashboard-card--featured .dashboard-card__header h3 {{
      font-size: 20px;
    }}
    .dashboard-card__header h3 {{
      margin: 0;
      font-size: 16px;
      line-height: 1.15;
    }}
    .dashboard-card__header p {{
      margin: 0;
      color: var(--muted);
      font-size: 13px;
    }}
    .dashboard-card__viewport {{
      overflow: hidden;
      width: 100%;
      padding: 10px;
      border: none;
      border-radius: 14px;
      background: #ffffff;
      box-shadow: 0 10px 24px rgba(16, 42, 67, 0.08);
      display: block;
      cursor: zoom-in;
      appearance: none;
      text-align: left;
    }}
    .dashboard-card__svg {{
      display: block;
      width: 100%;
      max-width: 100%;
      height: auto;
      box-shadow: none;
    }}
    .dashboard-card__hint {{
      color: var(--muted);
      font-size: 12px;
    }}
    .dashboard-modal {{
      position: fixed;
      inset: 0;
      z-index: 100;
      display: grid;
      place-items: center;
      padding: 20px;
      background: rgba(16, 42, 67, 0.68);
      backdrop-filter: blur(8px);
    }}
    .dashboard-modal[hidden] {{
      display: none;
    }}
    .dashboard-modal__sheet {{
      width: min(1440px, 100%);
      max-height: calc(100vh - 40px);
      display: grid;
      grid-template-rows: auto 1fr;
      gap: 12px;
      padding: 16px;
      border-radius: 18px;
      background: #f8fbff;
      box-shadow: 0 24px 60px rgba(16, 42, 67, 0.28);
    }}
    .dashboard-modal__header {{
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      gap: 16px;
    }}
    .dashboard-modal__title {{
      margin: 0;
      font-size: 18px;
      line-height: 1.15;
    }}
    .dashboard-modal__description {{
      margin: 4px 0 0;
      color: var(--muted);
      font-size: 13px;
    }}
    .dashboard-modal__close {{
      border: 1px solid var(--panel-border);
      border-radius: 999px;
      padding: 8px 12px;
      background: #ffffff;
      color: var(--text);
      font: inherit;
      cursor: pointer;
    }}
    .dashboard-modal__viewport {{
      overflow: auto;
      padding: 12px;
      border-radius: 14px;
      background: #ffffff;
    }}
    .dashboard-modal__viewport svg {{
      display: block;
      width: 100%;
      height: auto;
    }}
    @media (max-width: 1180px) {{
      .dashboard__grid {{
        grid-template-columns: 1fr;
      }}
    }}
    @media (max-width: 720px) {{
      .dashboard {{
        width: min(100vw - 20px, 1500px);
        padding-top: 10px;
      }}
      .dashboard__hero {{
        position: static;
      }}
      .dashboard__section {{
        padding: 16px;
      }}
    }}
  </style>
</head>
<body>
  <main class="dashboard">
    <header class="dashboard__hero">
      <div>
        <h1>{escaped_title}</h1>
        <p>One standalone HTML view for every generated visualization.</p>
      </div>
      <nav class="dashboard__nav">
        {nav_links}
      </nav>
    </header>
    {sections_markup}
  </main>
  <div class="dashboard-modal" hidden>
    <div class="dashboard-modal__sheet" role="dialog" aria-modal="true">
      <div class="dashboard-modal__header">
        <div>
          <h2 class="dashboard-modal__title"></h2>
          <p class="dashboard-modal__description"></p>
        </div>
        <button class="dashboard-modal__close" type="button">Close</button>
      </div>
      <div class="dashboard-modal__viewport"></div>
    </div>
  </div>
  <script>
    const svgNamespace = "http://www.w3.org/2000/svg";

    function wrapSvgContent(svg) {{
      const background = svg.querySelector(":scope > .svg-document__background");
      if (background) {{
        background.remove();
      }}
      let group = svg.querySelector(":scope > g.dashboard-crop-group");
      if (group) {{
        return group;
      }}
      group = document.createElementNS(svgNamespace, "g");
      group.setAttribute("class", "dashboard-crop-group");
      for (const child of [...svg.childNodes]) {{
        if (child === group) {{
          continue;
        }}
        group.appendChild(child);
      }}
      svg.appendChild(group);
      return group;
    }}

    function cropSvg(svg) {{
      const group = wrapSvgContent(svg);
      const bbox = group.getBBox();
      const padX = Math.max(12, bbox.width * 0.03);
      const padY = Math.max(12, bbox.height * 0.05);
      svg.setAttribute(
        "viewBox",
        `${{bbox.x - padX}} ${{bbox.y - padY}} `
          + `${{bbox.width + padX * 2}} ${{bbox.height + padY * 2}}`,
      );
      svg.removeAttribute("width");
      svg.removeAttribute("height");
      svg.dataset.cropped = "true";
    }}

    const modal = document.querySelector(".dashboard-modal");
    const modalTitle = document.querySelector(".dashboard-modal__title");
    const modalDescription = document.querySelector(
      ".dashboard-modal__description",
    );
    const modalViewport = document.querySelector(".dashboard-modal__viewport");
    const modalClose = document.querySelector(".dashboard-modal__close");

    function openModal(viewport) {{
      const title = viewport.dataset.panelTitle || "Visualization";
      const description = viewport.dataset.panelDescription || "";
      const svg = viewport.querySelector("svg");
      if (!svg) {{
        return;
      }}
      modalTitle.textContent = title;
      modalDescription.textContent = description;
      modalViewport.replaceChildren(svg.cloneNode(true));
      modal.hidden = false;
      document.body.style.overflow = "hidden";
    }}

    function closeModal() {{
      modal.hidden = true;
      modalViewport.replaceChildren();
      document.body.style.overflow = "";
    }}

    for (const svg of document.querySelectorAll(".dashboard-card__svg")) {{
      cropSvg(svg);
    }}

    for (const viewport of document.querySelectorAll(".dashboard-card__viewport")) {{
      viewport.addEventListener("click", () => openModal(viewport));
    }}

    modalClose.addEventListener("click", closeModal);
    modal.addEventListener("click", (event) => {{
      if (event.target === modal) {{
        closeModal();
      }}
    }});
    window.addEventListener("keydown", (event) => {{
      if (event.key === "Escape" && !modal.hidden) {{
        closeModal();
      }}
    }});
  </script>
</body>
</html>
"""

write_svg_dashboard_html

write_svg_dashboard_html(
    path: str | Path,
    sections: Sequence[SvgDashboardSection],
    *,
    title: str = "Visualization Dashboard",
) -> Path

Write a standalone SVG dashboard HTML document to disk.

Parameters:

Name Type Description Default
path str | Path

Destination HTML filepath.

required
sections Sequence[SvgDashboardSection]

Ordered dashboard sections to render.

required
title str

Document title shown at the top of the dashboard.

'Visualization Dashboard'

Returns:

Type Description
Path

The resolved output path.

Source code in src/memq_dqc/visualization/svg_document.py
def write_svg_dashboard_html(
    path: str | Path,
    sections: Sequence[SvgDashboardSection],
    *,
    title: str = "Visualization Dashboard",
) -> Path:
    """Write a standalone SVG dashboard HTML document to disk.

    Args:
        path: Destination HTML filepath.
        sections: Ordered dashboard sections to render.
        title: Document title shown at the top of the dashboard.

    Returns:
        The resolved output path.
    """
    output_path = Path(path)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text(
        build_svg_dashboard_html(sections, title=title),
        encoding="utf-8",
    )
    return output_path