Source code for bragi_quantum.gui.replay

# ══════════════════════════════════════════════════════════════════════════
#     ___   ___ ___   _      _   ___
#    / _ \ / __|_  ) | |    /_\ | _ )
#   | (_) | (__ / /  | |__ / _ \| _ \
#    \__\_\\___/___| |____/_/ \_\___/
#
#   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
#   Adrián Navarro Fuentes, adrianfu@chalmers.se
#   Yanchen Lin, linya@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


"""
Replay analysis on a saved calibration session.

Given a step from the session timeline plus an element name (qubit or
coupler) and a plot name, this module:

  1. Resolves the HDF5 dataset file for the step.
  2. Imports the recorded analysis / parameters / QOI classes (allowlisted).
  3. Re-instantiates the analysis with the recorded parameters.
  4. Calls analyse_element against the saved data — this re-runs the fit and
     rebuilds the in-memory state figure() needs.
  5. Calls analysis.figure() to build the plotly figure.
  6. Either encodes it to PNG bytes via kaleido (render_to_png) or returns its
     JSON for the browser to draw interactively with plotly.js
     (render_figure_json).

The server uses this from request handlers; the CLI uses it for sanity
checks at startup.
"""

from __future__ import annotations

import json
import logging
from functools import lru_cache
from pathlib import Path
from types import SimpleNamespace, UnionType
from typing import Any, Union, get_args, get_origin

import xarray as xr

from bragi_quantum.experiments.abstract.parameter_fields import (
    ParameterReadRecorder,
    fields_by_category,
)
from bragi_quantum.gui.figure_quantize import unescape_slashes
from bragi_quantum.gui.registry import safe_import_class

logger = logging.getLogger(__name__)


[docs] class ReplayError(RuntimeError): """Raised for any expected failure of replay (bad step, missing data, etc)."""
[docs] class PlotRenderError(RuntimeError): """Raised when re-fitting or rendering a plot fails. Carries the analysis fields read before the failure, so the UI can still offer them for re-tuning (e.g. a filter the plot requires). """ def __init__(self, message: str, analysis_fields: list[str]) -> None: super().__init__(message) self.analysis_fields = analysis_fields
# --------------------------------------------------------------------------- # # Timeline / dataset access # # --------------------------------------------------------------------------- #
[docs] def load_timeline(session_root: Path) -> list[dict[str, Any]]: timeline_file = Path(session_root) / "session_timeline.json" if not timeline_file.exists(): raise ReplayError(f"no session_timeline.json in {session_root}") with open(timeline_file, encoding="utf-8") as f: data = json.load(f) if not isinstance(data, list): raise ReplayError("session_timeline.json is not a list") return data
[docs] def find_step(timeline: list[dict[str, Any]], step_index: int) -> dict[str, Any]: for s in timeline: if s.get("step_index") == step_index: return s raise ReplayError(f"step_index {step_index} not found in timeline")
[docs] def resolve_dataset_path( step: dict[str, Any], session_root: Path | None = None ) -> Path: """ Pick the HDF5 file for a step. Datasets are saved as `dataset_<run_name>_<count>.hdf5` with monotonically increasing counts; we pick the highest count (the most recent run for this name). `dataset_dir` may be an absolute path (sessions recorded after the fix) or a relative path (older sessions recorded before root_path.resolve() was added to the orchestrator). When relative, it is resolved against `session_root` if provided, then against cwd. """ meta = step.get("replot_meta") or {} dataset_dir = meta.get("dataset_dir") basename = meta.get("dataset_basename") if not dataset_dir or not basename: raise ReplayError( f"step {step.get('step_index')} has no dataset metadata; " "cannot replot. Re-run the session with the latest qc2 to record it." ) d = Path(dataset_dir) if not d.is_absolute(): # dataset_dir was recorded relative to the project root (the cwd when # the calibration ran). Try candidates in order of likelihood: # 1. relative to cwd right now # 2. relative to the project root inferred from session_root # (session_root = <project_root>/calibration_outputs/<session_id>, # so project_root = session_root.parent.parent) # 3. relative to session_root itself (future-proof) resolved = False candidates_to_try = [Path(".")] if session_root is not None: sr = Path(session_root) candidates_to_try.append(sr.parent.parent) # project root candidates_to_try.append(sr.parent) # calibration_outputs candidates_to_try.append(sr) # session folder itself for base in candidates_to_try: candidate = (base / d).resolve() if candidate.is_dir(): d = candidate resolved = True break if not resolved: d = d.resolve() if not d.is_dir(): raise ReplayError(f"dataset directory does not exist: {d}") candidates = sorted(d.glob(f"dataset_{basename}_*.hdf5")) if not candidates: raise ReplayError(f"no dataset files matching dataset_{basename}_*.hdf5 in {d}") return candidates[-1]
@lru_cache(maxsize=64) def _open_dataset_cached(path_str: str, mtime_ns: int) -> xr.Dataset: """ Open an HDF5 dataset and keep it cached. The cache key includes the file mtime so an overwrite invalidates the cached handle on the next call. """ return xr.open_dataset(path_str, engine="h5netcdf")
[docs] def open_dataset(path: Path) -> xr.Dataset: return _open_dataset_cached(str(path), path.stat().st_mtime_ns)
# --------------------------------------------------------------------------- # # Analysis re-instantiation # # --------------------------------------------------------------------------- # def _reconstruct_parameters(meta: dict[str, Any], recorded: dict[str, Any]) -> Any: """ Re-create the parameters object from its recorded dict. Strategy: try to import and instantiate the real Pydantic class first (works in the full lab environment). If that fails due to missing hardware dependencies (qblox_scheduler, quantify_core, etc.), fall back to a SimpleNamespace populated from the recorded dict — the analysis classes only do plain attribute access on parameters, so a namespace is sufficient for replay. """ mod = meta.get("parameters_module") cls = meta.get("parameters_class") if mod and cls: try: ParamsCls = safe_import_class(mod, cls) return ParamsCls(**recorded) except Exception as e: logger.debug( f"Could not import/instantiate {cls} ({e}); " "falling back to SimpleNamespace for replay." ) # Fallback: plain namespace — sufficient for attribute access in analysis. return SimpleNamespace(**recorded) def _import_analysis(meta: dict[str, Any]) -> Any: mod = meta.get("analysis_module") cls = meta.get("analysis_class") if not (mod and cls): raise ReplayError("analysis class metadata missing from timeline step") try: return safe_import_class(mod, cls) except ImportError as e: raise ReplayError( f"Could not import analysis class {cls} from {mod}: {e}. " "Make sure all lab dependencies (quantify_core, qblox_scheduler, etc.) " "are installed in the environment running qc2-show." ) from e def _import_qoi(meta: dict[str, Any]) -> Any: mod = meta.get("qoi_module") cls = meta.get("qoi_class") if not (mod and cls): return None try: return safe_import_class(mod, cls) except ImportError as e: logger.debug(f"Could not import QOI class {cls}: {e}; proceeding without it.") return None def _session_root_from_step(step: dict[str, Any]) -> Path | None: """Best-effort: infer session root from dataset_dir in replot_meta.""" meta = step.get("replot_meta") or {} dataset_dir = meta.get("dataset_dir") if not dataset_dir: return None p = Path(dataset_dir) # dataset_dir is <session_root>/<node_name>; parent is session root. return p.parent if p.is_absolute() else None def _analysis_field_names(params: Any) -> set[str] | None: """Names of the ``analysis``-category fields, or None if not introspectable. These are the only fields safe to re-tune at reanalysis time — acquisition fields (sweep ranges, repetitions, …) describe how the *stored* data was taken and must not change. """ try: names = fields_by_category(params).get("analysis", []) return set(names) if names else set() except Exception: return None def _apply_overrides(params: Any, overrides: dict[str, Any] | None) -> Any: """Return ``params`` with ``overrides`` applied to its analysis fields. Overrides are restricted to analysis-category fields when they can be introspected. The real pydantic class is re-validated (so ``"0.5"`` coerces to ``float`` and bad values raise); a SimpleNamespace fallback is patched by attribute. """ if not overrides: return params allowed = _analysis_field_names(params) if allowed is not None: rejected = set(overrides) - allowed if rejected: raise ReplayError( f"cannot re-tune non-analysis field(s) {sorted(rejected)}; " f"tunable fields: {sorted(allowed)}" ) filtered = {k: v for k, v in overrides.items() if allowed is None or k in allowed} if not filtered: return params # Real pydantic parameters: rebuild with validation so types coerce. if hasattr(params, "model_dump") and hasattr(type(params), "model_validate"): try: return type(params).model_validate({**params.model_dump(), **filtered}) except Exception as exc: raise ReplayError(f"invalid analysis parameter override: {exc}") from exc # SimpleNamespace fallback (hardware deps missing): plain attribute set. for key, value in filtered.items(): setattr(params, key, value) return params def _widget_kind(annotation: Any) -> str: """UI-widget-kind hint (``"number"``/``"bool"``/``"text"``) for a field annotation. Unwraps ``X | None``/``Optional[X]`` to ``X`` first, so e.g. an int-or-None analysis field still renders as a number input rather than falling through to a bare text box that sends the server an un-coerced string. """ if get_origin(annotation) in (Union, UnionType): non_none = [a for a in get_args(annotation) if a is not type(None)] if len(non_none) == 1: annotation = non_none[0] if annotation is bool: return "bool" if annotation in (int, float): return "number" return "text"
[docs] def analysis_fields_for_step(step: dict[str, Any]) -> list[dict[str, Any]]: """Describe the re-tunable (analysis-category) parameters for a step. Returns ``[{name, value, kind, default, description}]`` where ``value`` is the value the run actually used (from the recorded parameters), ``kind`` is a UI hint (``"number"`` / ``"bool"`` / ``"text"``) and ``description`` (or ``None``) is the field's pydantic description, shown as a form placeholder. Empty when the parameters class or its categories cannot be introspected. """ meta = step.get("replot_meta") or {} recorded = step.get("parameters") or {} mod, cls = meta.get("parameters_module"), meta.get("parameters_class") if not (mod and cls): return [] try: ParamsCls = safe_import_class(mod, cls) names = fields_by_category(ParamsCls).get("analysis", []) except Exception as exc: logger.debug(f"cannot introspect analysis fields for step: {exc}") return [] try: from pydantic_core import PydanticUndefined except Exception: # pragma: no cover PydanticUndefined = object() fields: list[dict[str, Any]] = [] model_fields = getattr(ParamsCls, "model_fields", {}) for name in names: info = model_fields.get(name) default = getattr(info, "default", None) if default is PydanticUndefined: default = None fields.append( { "name": name, "value": recorded.get(name, default), "kind": _widget_kind(getattr(info, "annotation", None)), "default": default, "description": getattr(info, "description", None), } ) return fields
[docs] def build_analysis_for_element( step: dict[str, Any], element: str, session_root: Path | None = None, overrides: dict[str, Any] | None = None, n_selected_elements: int = 1, analysis_field_reads: set[str] | None = None, ) -> Any: """ Re-instantiate the analysis and run it on a single element so that its internal state (fit results, cached arrays) is populated and plotting can proceed. Slicing is delegated to the unified analysis' ``analyse_element`` (no duplicated slicing here). ``overrides`` re-tunes analysis-category parameters before the fit re-runs (the reanalysis path); acquisition/metadata fields cannot be overridden. ``n_selected_elements`` is how many elements the caller's UI currently has selected together (e.g. bragi_quantum.gui's marquee multi-select) — some analyses use it to skip expensive per-element plots when rendering many at once. ``analysis_field_reads``, when given, collects every analysis field the fit (and any later plotting on the returned analysis) reads, even if it raises. """ meta = step.get("replot_meta") or {} if not meta: raise ReplayError( f"step {step.get('step_index')} has no replot metadata; cannot replot." ) AnalysisCls = _import_analysis(meta) QoiCls = _import_qoi(meta) params = _reconstruct_parameters(meta, step.get("parameters") or {}) params = _apply_overrides(params, overrides) if analysis_field_reads is not None: # Track exactly the fields the reanalyse form offers. params = ParameterReadRecorder( params, [field["name"] for field in analysis_fields_for_step(step)], read_fields=analysis_field_reads, ) analysis = AnalysisCls(parameters=params, qoi_cls=QoiCls) analysis.n_selected_elements = n_selected_elements _root = session_root or _session_root_from_step(step) dataset = open_dataset(resolve_dataset_path(step, _root)) if not hasattr(analysis, "analyse_element"): raise ReplayError( f"{type(analysis).__name__} is not a unified Analysis " "(no analyse_element); cannot replot." ) # analyse_element slices the full node dataset down to `element` and fits it. analysis.analyse_element(dataset, element) return analysis
# --------------------------------------------------------------------------- # # Plot listing & rendering # # --------------------------------------------------------------------------- #
[docs] def list_plots_for_element( step: dict[str, Any], element: str, session_root: Path | None = None ) -> list[str]: """ Return the list of plot names available for this (step, element). Cheap path: if the analysis class exposes a class-level (or instance-cheap) `list_plots`, we instantiate without running the fit. That works when list_plots is static. For analyses where the available plots depend on runtime data, we fall back to a full replay. """ meta = step.get("replot_meta") or {} AnalysisCls = _import_analysis(meta) QoiCls = _import_qoi(meta) params = _reconstruct_parameters(meta, step.get("parameters") or {}) try: ana = AnalysisCls(parameters=params, qoi_cls=QoiCls) return list(ana.list_plots()) except Exception: ana = build_analysis_for_element(step, element, session_root=session_root) return list(ana.list_plots())
[docs] def render_to_png( step: dict[str, Any], element: str, plot_name: str, session_root: Path | None = None, overrides: dict[str, Any] | None = None, n_selected_elements: int = 1, ) -> bytes: """ Render the plot for the given (step, element) as a plotly figure and return PNG bytes (via kaleido). ``overrides`` re-tunes analysis parameters. """ analysis = build_analysis_for_element( step, element, session_root=session_root, overrides=overrides, n_selected_elements=n_selected_elements, ) available = analysis.list_plots() if plot_name not in available: raise ReplayError( f"plot {plot_name!r} not available for element {element} at " f"step {step.get('step_index')}; available: {available}" ) # analyse_element populated the instance for this single element, so # figure() renders it. Export via kaleido. fig = analysis.figure(plot_name=plot_name) return fig.to_image(format="png", scale=2)
[docs] def render_figure_json( step: dict[str, Any], element: str, plot_name: str, session_root: Path | None = None, overrides: dict[str, Any] | None = None, n_selected_elements: int = 1, ) -> tuple[str, list[str]]: """ Render the plot as plotly JSON (drawn interactively by plotly.js), plus the sorted analysis fields the fit and this plot read, i.e. those worth offering for re-tuning on this plot. A failed fit/render raises ``PlotRenderError``. ``overrides`` re-tunes analysis parameters before the fit re-runs. ``n_selected_elements`` is how many elements are selected together in the caller's UI (see :func:`build_analysis_for_element`). """ analysis_field_reads: set[str] = set() try: analysis = build_analysis_for_element( step, element, session_root=session_root, overrides=overrides, n_selected_elements=n_selected_elements, analysis_field_reads=analysis_field_reads, ) available = analysis.list_plots() if plot_name not in available: raise ReplayError( f"plot {plot_name!r} not available for element {element} at " f"step {step.get('step_index')}; available: {available}" ) figure_json = unescape_slashes(analysis.figure(plot_name=plot_name).to_json()) except ReplayError: raise except Exception as exc: raise PlotRenderError(str(exc), sorted(analysis_field_reads)) from exc return figure_json, sorted(analysis_field_reads)
# --------------------------------------------------------------------------- # # Top-level helpers used by the server # # --------------------------------------------------------------------------- #
[docs] def step_summary(step: dict[str, Any]) -> dict[str, Any]: """A small JSON-safe summary of a step for the /steps endpoint.""" meta = step.get("replot_meta") or {} return { "step_index": step.get("step_index"), "kind": step.get("kind"), "node_name": step.get("node_name"), "node_class": step.get("node_class"), "target_qubits": list(step.get("target_qubits") or []), "element_kind": meta.get("element_kind", "qubit"), "replot_available": bool(meta.get("analysis_module")), }