Source code for bragi_quantum.gui.rendering.html_rendering

# ══════════════════════════════════════════════════════════════════════════
#     ___   ___ ___   _      _   ___
#    / _ \ / __|_  ) | |    /_\ | _ )
#   | (_) | (__ / /  | |__ / _ \| _ \
#    \__\_\\___/___| |____/_/ \_\___/
#
#   QC2 @ CHALMERS CALIBRATION TOOLKIT
#   (c) 2026 Chalmers University of Technology and Project Contributors
# ──────────────────────────────────────────────────────────────────────────
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       https://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
# ──────────────────────────────────────────────────────────────────────────
#   CONTRIBUTORS list:
#
#   Matteo Robbiati, robbiati@chalmers.se
#   Axel Andersson, axean@chalmers.se
#   Yanchen Lin, linya@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


"""
Interactive HTML device visualization showing qubit topology, couplers, live
parameters from Redis, per-element execution history, and a session-level
pipeline (DAG) view of executed steps.
"""

import html
import json
import logging
import math
import re
from html import escape
from pathlib import Path
from typing import Any

from plotly.offline import get_plotlyjs

from bragi_quantum.datalayer.managing.time_tracing import TIMING_CATEGORY_COLORS
from bragi_quantum.gui.rendering.templates import load as _load_template

logger = logging.getLogger(__name__)

_RENDERING_DIR = Path(__file__).parent
_RESOURCES_DIR = _RENDERING_DIR.parents[3] / "resources"


[docs] def create_html_rendering( qubits: list[str], couplers: list[str], redis_connection: Any | None = None, output_path: Path | None = None, session_root_path: Path | None = None, session_timeline: list[dict[str, Any]] | None = None, replot_endpoint_override: str | None = None, pipeline_href: str = "/pipeline", plotly_src: str | None = None, ) -> str: """ Create an interactive HTML device visualization. The QPU-topology diagram itself is rendered client-side by ``wiring-logic.js`` from the wiring blob (see rendering/wiring.py); this function embeds the data blobs and page scaffolding. Args: qubits: List of qubit names (e.g., ['q16', 'q17', ...]) couplers: List of coupler names (e.g., ['q16_q17', 'q17_q18', ...]) redis_connection: Optional Redis connection for fetching live parameters output_path: Optional path to save the HTML file session_root_path: Optional path to session root for loading execution history, session timeline, and the timing trace. session_timeline: Optional pre-loaded session timeline. If not provided and session_root_path is given, will attempt to load it. plotly_src: URL to load plotly.js from. If None, plotly.js is inlined so the page works offline. Returns: HTML content as string """ qubit_positions = _calculate_qubit_positions(qubits) coupler_connections = _parse_coupling_map(couplers) qubit_params: dict[str, dict[str, Any]] = {} coupler_params: dict[str, dict[str, Any]] = {} if redis_connection: qubit_params = _fetch_parameters_from_redis( qubits, "transmons", redis_connection ) coupler_params = _fetch_parameters_from_redis( couplers, "couplers", redis_connection ) # Load timeline if not provided if session_timeline is None and session_root_path: session_timeline = _load_session_timeline(Path(session_root_path)) if session_timeline is None: session_timeline = [] # Extract element kinds from timeline element_kinds = _extract_element_kinds(session_timeline) session_log = ( _load_session_log(Path(session_root_path)) if session_root_path else {"exists": False, "text": "", "path": ""} ) svg_content = _generate_device_svg( qubit_positions, coupler_connections, qubits, couplers ) timing_trace_events = ( _load_timing_trace_events(Path(session_root_path)) if session_root_path else None ) html_content = _generate_html_template( svg_content, qubits, couplers, qubit_params, coupler_params, session_timeline, element_kinds, session_log, session_root_path=session_root_path, replot_endpoint_override=replot_endpoint_override, pipeline_href=pipeline_href, timing_trace_events=timing_trace_events, plotly_src=plotly_src, ) if output_path: output_path.parent.mkdir(parents=True, exist_ok=True) with open(output_path, "w", encoding="utf-8") as f: f.write(html_content) logger.info(f"✅ Device visualization saved to {output_path}") return html_content
def _calculate_qubit_positions(qubits: list[str]) -> dict[str, tuple[float, float]]: """Calculate 2D grid positions for qubits based on their indices.""" positions: dict[str, tuple[float, float]] = {} indices: list[tuple[int, str]] = [] for q in qubits: try: idx = int(q.replace("q", "")) indices.append((idx, q)) except ValueError: indices.append((len(indices), q)) indices.sort() cols = 5 spacing = 120 for row, (_idx, name) in enumerate(indices): col = row % cols row_num = row // cols x = col * spacing + 100 y = row_num * spacing + 100 positions[name] = (x, y) return positions def _parse_coupling_map(couplers: list[str]) -> list[tuple[str, str]]: """Parse coupler names like 'q16_q17' into pairs.""" connections: list[tuple[str, str]] = [] for coupler in couplers: parts = coupler.split("_") if len(parts) >= 2: connections.append((parts[0], parts[1])) return connections def _sanitize_floats(obj): """Recursively replace non-JSON-safe floats (Inf, NaN) with None.""" if isinstance(obj, float): return None if (math.isnan(obj) or math.isinf(obj)) else obj if isinstance(obj, dict): return {k: _sanitize_floats(v) for k, v in obj.items()} if isinstance(obj, list): return [_sanitize_floats(v) for v in obj] return obj def _load_session_timeline(session_root_path: Path) -> list[dict[str, Any]]: """Load ordered session timeline (step 0 = start config, then nodes).""" timeline_file = session_root_path / "session_timeline.json" if timeline_file.exists(): try: with open(timeline_file, encoding="utf-8") as f: # parse_constant allows Python to read Infinity/NaN from # non-standard JSON; we then sanitise before embedding in HTML. data = json.loads( f.read(), parse_constant=lambda c: ( float(c) if c in ("-Infinity", "Infinity", "NaN") else None ), ) if isinstance(data, list): return _sanitize_floats(data) except Exception as e: logger.debug(f"Could not load session timeline: {e}") return [] def _load_session_log(session_root_path: Path) -> dict[str, Any]: """Load logs.txt for embedding in the session report (full content, no cap).""" log_file = session_root_path / "logs.txt" log_path = str(log_file.resolve()) if not log_file.exists(): return {"exists": False, "text": "", "path": log_path} try: return { "exists": True, "text": log_file.read_text(encoding="utf-8", errors="replace"), "path": log_path, } except OSError as e: logger.debug(f"Could not load session log: {e}") return {"exists": False, "text": "", "path": log_path} def _load_timing_trace_events(session_root_path: Path) -> dict[str, Any] | None: """Load timing_trace_events.json (Chrome/Perfetto Trace Event Format) for the session's inline Timing Trace chart, or None if absent/unreadable — e.g. the session predates timing trace collection, or it was disabled. """ timing_trace_file = session_root_path / "timing_trace_events.json" if not timing_trace_file.exists(): return None try: return json.loads(timing_trace_file.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as e: logger.debug(f"Could not load trace events: {e}") return None def _fetch_parameters_from_redis( names: list[str], key_prefix: str, redis_connection: Any ) -> dict[str, dict[str, Any]]: """Fetch calibration parameters for each name (qubit or coupler) from Redis. ``key_prefix`` picks the Redis hash namespace: ``"transmons"`` for qubits, ``"couplers"`` for couplers. """ params: dict[str, dict[str, Any]] = {} for name in names: try: raw = redis_connection.hgetall(f"{key_prefix}:{name}") processed: dict[str, Any] = {} for field, value in raw.items(): field_str = field.decode() if isinstance(field, bytes) else field value_str = value.decode() if isinstance(value, bytes) else value try: processed[field_str] = float(value_str) except (ValueError, TypeError): processed[field_str] = value_str params[name] = processed except Exception as e: logger.debug(f"Could not fetch parameters for {name}: {e}") params[name] = {} return params def _extract_element_kinds(timeline: list[dict[str, Any]]) -> dict[str, str]: """ Extract element kind (qubit/coupler) mapping from timeline. Args: timeline: Session timeline list Returns: Dict mapping element_name -> "qubit" | "coupler" """ kinds: dict[str, str] = {} for step in timeline: if step.get("kind") == "node": meta = step.get("replot_meta") or {} kind = meta.get("element_kind", "qubit") for el in step.get("target_qubits") or []: kinds[el] = kind return kinds def _generate_html_template( svg_content: str, qubits: list[str], couplers: list[str], qubit_params: dict[str, dict[str, Any]], coupler_params: dict[str, dict[str, Any]], session_timeline: list[dict[str, Any]], element_kinds: dict[str, str], session_log: dict[str, Any], session_root_path: Path | None = None, replot_endpoint_override: str | None = None, pipeline_href: str = "/pipeline", timing_trace_events: dict[str, Any] | None = None, plotly_src: str | None = None, ) -> str: """Generate complete HTML page with embedded JS from interaction-logic.js.""" timeline_json = json.dumps(_sanitize_floats(session_timeline)) element_kinds_json = json.dumps(element_kinds) session_log_json = json.dumps(session_log) timing_trace_events_json = json.dumps(_sanitize_floats(timing_trace_events)) timing_colors_json = json.dumps(TIMING_CATEGORY_COLORS) from bragi_quantum.gui.rendering.wiring import build_wiring_blob wiring_blob = build_wiring_blob(session_timeline) wiring_json = json.dumps(_sanitize_floats(wiring_blob)) device_json = json.dumps( { "qubits": {q: qubit_params.get(q, {}) for q in qubits}, "couplers": {c: coupler_params.get(c, {}) for c in couplers}, } ) # This session's own identity, in the exact same form pipeline.py's # NodeInfo.tab_name uses (see _build_pipeline_data) — lets # interaction-logic.js's "Go to whole pipeline" button tell the Whole # Pipeline tab which session it's jumping back from, so it can # highlight/scroll to the matching node rather than just the graph # section. Both derive it the same way from the same directory name, so # the two always agree. tab_name_json = json.dumps( Path(session_root_path).name[len("session_") :] if session_root_path else None ) # Embed the replot server endpoint if available. In the single-session # flow we prefer the endpoint written next to the HTML file; in the # multi-session flow the server passes an explicit per-session route. replot_endpoint_val = "null" if replot_endpoint_override: replot_endpoint_val = json.dumps(replot_endpoint_override) elif session_root_path: ep_file = Path(session_root_path) / "replot_endpoint.txt" if ep_file.exists(): ep = ep_file.read_text().strip() if ep: replot_endpoint_val = json.dumps(ep) # No plotly_src -> inline the bundle so the page is self-contained offline. plotly_script = ( f'<script src="{escape(plotly_src)}"></script>' if plotly_src else f"<script>{get_plotlyjs()}</script>" ) html = ( _load_template("replot.html") .replace("@@INLINE_CSS@@", _load_template("replot.css")) .replace("@@SVG_CONTENT@@", svg_content) .replace("@@REPLOT_ENDPOINT@@", replot_endpoint_val) .replace("@@PIPELINE_HREF@@", pipeline_href) .replace("@@TIMELINE_JSON@@", timeline_json) .replace("@@DEVICE_JSON@@", device_json) .replace("@@TAB_NAME_JSON@@", tab_name_json) .replace("@@ELEMENT_KINDS_JSON@@", element_kinds_json) .replace("@@SESSION_LOG_JSON@@", session_log_json) .replace("@@TIMING_TRACE_EVENTS_JSON@@", timing_trace_events_json) .replace("@@TIMING_CATEGORY_COLORS_JSON@@", timing_colors_json) .replace("@@PLOTLY_SCRIPT@@", plotly_script) .replace("@@COMMON_JS@@", _load_template("common.js")) .replace("@@LOG_SEARCH_FILTER_JS@@", _load_template("log-searcher-filter.js")) .replace("@@INTERACTION_JS@@", _load_template("interaction-logic.js")) .replace("@@WIRING_JS@@", _load_template("wiring-logic.js")) .replace("@@WIRING_JSON@@", wiring_json) .replace("@@TIMING_TRACE_JS@@", _load_template("timing-trace-logic.js")) ) return html
[docs] def create_whole_pipeline_html() -> str: """ Build the shared, cross-session "whole pipeline" page. The page is data-driven: at load time its JS fetches ``/pipeline/data`` from the serving app to learn about every session and its executed node steps, draws a single Mermaid graph (nodes coloured per session), and — when a node is clicked — fetches and renders that node's already-stored PNGs in a carousel (``/pipeline/node-plots`` + ``/pipeline/png``). """ return ( _load_template("pipeline.html") .replace("@@PIPELINE_CSS@@", _load_template("pipeline.css")) .replace("@@COMMON_JS@@", _load_template("common.js")) .replace("@@TIMING_TRACE_JS@@", _load_template("timing-trace-logic.js")) .replace( "@@PIPELINE_SESSION_NAV_JS@@", _load_template("pipeline-session-nav.js") ) .replace("@@PYTHON_HIGHLIGHT_JS@@", _load_template("python-highlighter.js")) .replace("@@YAML_HIGHLIGHT_JS@@", _load_template("yaml-highlighter.js")) .replace("@@RUN_SETUP_JS@@", _load_template("run-setup.js")) .replace("@@FEED_COMMENTS_JS@@", _load_template("feed-comments.js")) .replace("@@CALIBRATION_FEED_JS@@", _load_template("calibration-feed.js")) .replace("@@PIPELINE_GRAPH_JS@@", _load_template("pipeline-graph.js")) .replace("@@PIPELINE_JS@@", _load_template("pipeline-logic.js")) )
def _whole_pipeline_tab_markup( pipeline_url: str = "/pipeline", is_active: bool = False ) -> tuple[str, str]: """Return (tab_button_html, tab_content_html) for the shared pipeline tab.""" active_class = "active" if is_active else "" button = ( f'<button class="tab-button {active_class}" data-pipeline-tab="1" ' "onclick=\"openTab(event, 'whole-pipeline')\">🧭 Whole Pipeline</button>" ) # Strip the body { ... } rule — the outer page already sets body styles. pipeline_tab_css = re.sub(r"\bbody\s*\{[^}]*\}", "", _load_template("pipeline.css")) content = ( _load_template("pipeline_tab.html") .replace("@@PIPELINE_TAB_CSS@@", pipeline_tab_css) .replace("@@TIMING_TRACE_JS@@", _load_template("timing-trace-logic.js")) .replace( "@@PIPELINE_SESSION_NAV_JS@@", _load_template("pipeline-session-nav.js") ) .replace("@@PYTHON_HIGHLIGHT_JS@@", _load_template("python-highlighter.js")) .replace("@@YAML_HIGHLIGHT_JS@@", _load_template("yaml-highlighter.js")) .replace("@@RUN_SETUP_JS@@", _load_template("run-setup.js")) .replace("@@FEED_COMMENTS_JS@@", _load_template("feed-comments.js")) .replace("@@CALIBRATION_FEED_JS@@", _load_template("calibration-feed.js")) .replace("@@PIPELINE_GRAPH_JS@@", _load_template("pipeline-graph.js")) .replace("@@PIPELINE_JS@@", _load_template("pipeline-logic.js")) .replace('data-pipeline-url="/pipeline"', f'data-pipeline-url="{pipeline_url}"') ) if is_active: content = content.replace('style="display: none"', 'style="display: block"', 1) return button, content def _generate_device_svg( positions: dict[str, tuple[float, float]], connections: list[tuple[str, str]], qubits: list[str], couplers: list[str], ) -> str: """Generate SVG content showing device topology with qubits and couplers.""" coupler_positions: dict[str, tuple[float, float]] = {} for coupler_name, (q1, q2) in zip(couplers, connections): if q1 in positions and q2 in positions: x1, y1 = positions[q1] x2, y2 = positions[q2] coupler_positions[coupler_name] = ((x1 + x2) / 2, (y1 + y2) / 2) all_positions = {**positions, **coupler_positions} if not all_positions: width, height = 400, 300 else: max_x = max(p[0] for p in all_positions.values()) + 80 max_y = max(p[1] for p in all_positions.values()) + 80 width = max(int(max_x), 400) height = max(int(max_y), 300) svg_parts: list[str] = [ ( f'<svg width="100%" height="{height}" viewBox="0 0 {width} {height}" ' 'xmlns="http://www.w3.org/2000/svg" style="background-color: #f9f9f9;">' ) ] for q1, q2 in connections: if q1 in positions and q2 in positions: x1, y1 = positions[q1] x2, y2 = positions[q2] svg_parts.append( f'<line x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}" ' 'stroke="#555" stroke-width="2" />' ) for qubit, (x, y) in positions.items(): svg_parts.append( f'<g class="device-node" data-type="qubit" data-name="{qubit}" ' f'style="cursor: pointer;">' f'<circle cx="{x}" cy="{y}" r="22" fill="rgba(255, 184, 184, 1)" stroke="#222" ' f'stroke-width="2" />' f'<text x="{x}" y="{y + 5}" text-anchor="middle" ' f'font-family="sans-serif" font-size="13" fill="#222" ' f'font-weight="bold">{qubit}</text>' f"</g>" ) # Size coupler boxes to fit the longest label. # Approximate glyph width at font-size 9px ~5.8px; add 10px horizontal padding. max_coupler_label = max((len(c) for c in coupler_positions), default=7) c_w = max(36, int(max_coupler_label * 5.8 + 10)) c_h = 22 c_rx = 6 for coupler, (x, y) in coupler_positions.items(): svg_parts.append( f'<g class="device-node" data-type="coupler" data-name="{coupler}" ' f'style="cursor: pointer;">' f'<rect x="{x - c_w / 2:.1f}" y="{y - c_h / 2:.1f}" ' f'width="{c_w}" height="{c_h}" rx="{c_rx}" ' f'fill="rgba(253, 255, 184, 1)" stroke="#222" stroke-width="2" />' f'<text x="{x}" y="{y + 4}" text-anchor="middle" ' f'font-family="sans-serif" font-size="9" fill="#222" ' f'font-weight="bold">{coupler}</text>' f"</g>" ) svg_parts.append("</svg>") return "\n".join(svg_parts)
[docs] def create_multi_session_html( session_names: list[str], datetime_hour_path: Path, output_path: Path | None = None, incomplete_session_names: list[str] | None = None, pipeline_url: str = "/pipeline", generated_at: str = "", generated_by: str = "", run_name: str = "", ) -> str: """ Create a master HTML page that aggregates multiple session renderings. Args: session_names: Session names with complete data (get an iframe tab each). datetime_hour_path: Path to the run directory containing all sessions. output_path: Optional path to write the HTML to disk. incomplete_session_names: Session folders that exist but have no session_timeline.json (e.g. cancelled mid-run). Retained for API compatibility but not rendered as tabs. pipeline_url: Base URL for the whole-pipeline tab (e.g. /pipeline/run_ts). generated_at: ISO-formatted timestamp of when this page was rendered. generated_by: Human-readable source label (e.g. "qc2-show", "bragi_quantum.api"). run_name: The orchestrator's ``name`` (e.g. from the session timeline's ``start_config.run_name``), shown as the header subtitle. Falls back to a generic subtitle when the run has no name. """ datetime_hour_path = Path(datetime_hour_path) incomplete_session_names = incomplete_session_names or [] # "Whole Pipeline" is the leftmost, default-active tab — a first-time # viewer lands on the cross-session overview instead of an arbitrary # single session's report. Its iframe targets the live /pipeline route # served by qc2-show; it is inert when the file is opened directly off # disk (no server). tabs_html, content_html = _whole_pipeline_tab_markup(pipeline_url, is_active=True) tabs_html += "\n" content_html += "\n" for i, session_name in enumerate(session_names): label = f"📊 {session_name}" tabs_html += f'<button class="tab-button" onclick="openTab(event, \'session-{i}\')" data-session="{session_name}">{label}</button>\n' relative_html_path = f"session_{session_name}/html_rendering.html" # No session is visible at first (Whole Pipeline is the default tab), so # every session sets its src from data-src on first click (see # multi-session-tab.js). content_html += f'<div id="session-{i}" class="tab-content" data-session="{session_name}" style="display: none;"><iframe data-src="{relative_html_path}" style="width: 100%; height: 100vh; border: none;"></iframe></div>\n' logo_svg = (_RESOURCES_DIR / "qc2_logo_white.svg").read_text(encoding="utf-8") # Strip the XML declaration (invalid inside HTML) and add a viewBox so the # SVG scales correctly when CSS height is set without explicit width/height attrs. logo_svg = re.sub(r"<\?xml[^?]*\?>", "", logo_svg).strip() logo_svg = re.sub( r"(<svg\b[^>]*?)(\s*width=['\"][^'\"]*['\"])?(\s*height=['\"][^'\"]*['\"])?(\s*>)", r'\1 viewBox="0 0 537 427"\4', logo_svg, count=1, ) subtitle = ( html.escape(run_name) if run_name else "Interactive device characterization and parameter visualization" ) master_html = ( _load_template("multi_session.html") .replace("@@MULTI_SESSION_CSS@@", _load_template("multi_session.css")) .replace("@@COMMON_JS@@", _load_template("common.js")) .replace("@@LOGO_SVG@@", logo_svg) .replace("@@TABS_HTML@@", tabs_html) .replace("@@CONTENT_HTML@@", content_html) .replace("@@OPEN_TAB_JS@@", _load_template("multi-session-tab.js")) .replace("@@SUBTITLE@@", subtitle) ) if output_path: output_path.parent.mkdir(parents=True, exist_ok=True) with open(output_path, "w", encoding="utf-8") as f: f.write(master_html) logger.info(f"✅ Master HTML (all sessions) saved to {output_path}") return master_html