Source code for bragi_quantum.gui.timeline

# ══════════════════════════════════════════════════════════════════════════
#     ___   ___ ___   _      _   ___
#    / _ \ / __|_  ) | |    /_\ | _ )
#   | (_) | (__ / /  | |__ / _ \| _ \
#    \__\_\\___/___| |____/_/ \_\___/
#
#   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:
#
#   Axel Andersson, axean@chalmers.se
#   Yanchen Lin, linya@chalmers.se
#   Matteo Robbiati, robbiati@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


"""The ``Timeline`` value object.

A calibration session's timeline is a flat ``list[dict]`` whose first step is a
``start_config`` followed by ``node`` steps. The same handful of pokes at that
raw shape — "give me the start config", "the qubits", "the node steps", "split a
file that holds several runs" — were duplicated a dozen times across the server.
``Timeline`` is the one place that knows the shape; everything else asks it.
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Any

from bragi_quantum.gui import replay

_START = "start_config"


[docs] @dataclass(frozen=True) class Timeline: steps: list[dict[str, Any]]
[docs] @classmethod def load(cls, session_root: Path) -> Timeline: """Load a session's timeline from disk; empty on any read failure.""" try: return cls(replay.load_timeline(session_root)) except Exception: return cls([])
@property def start_config(self) -> dict[str, Any]: """The leading ``start_config`` step, or ``{}`` if absent.""" s = self.steps return s[0] if s and s[0].get("kind") == _START else {} @property def qubits(self) -> list[str]: return list(self.start_config.get("qubits") or []) @property def couplers(self) -> list[str]: return list(self.start_config.get("couplers") or []) @property def node_steps(self) -> list[dict[str, Any]]: return [s for s in self.steps if s.get("kind") == "node"] @property def start_ts(self) -> str: """Sortable start timestamp (ISO strings sort chronologically).""" return str(self.start_config.get("timestamp") or "") @property def run_name(self) -> str: """The orchestrator's ``name`` (unsanitized) recorded at session start. Distinct from ``title()``'s ``session_options.run_name`` lookup, which disambiguates multiple runs replayed from one session folder — this is the top-level field ``SessionTimeline.record_start_config`` stamps from ``CalibrationOrchestrator.name``. """ return str(self.start_config.get("run_name") or "")
[docs] def split_runs(self) -> list[Timeline]: """Split a timeline that holds several runs into one ``Timeline`` per run. Empty in → empty out (a session with no timeline yields no run). A single ``start_config`` (or none) returns the whole thing unchanged. """ if not self.steps: return [] starts = [i for i, s in enumerate(self.steps) if s.get("kind") == _START] if len(starts) <= 1: return [self] segments: list[Timeline] = [] for i, start_idx in enumerate(starts): end_idx = starts[i + 1] if i + 1 < len(starts) else len(self.steps) segment = self.steps[start_idx:end_idx] if segment: segments.append(Timeline(segment)) return segments or [self]
[docs] def title(self, fallback_name: str) -> tuple[str, int]: """Human-readable session title and node-step count. Title joins ``session_id``, ``template_name`` and ``run_name`` (when distinct); falls back to ``fallback_name`` when the timeline is empty. """ if not self.steps: return fallback_name, 0 sc = self.start_config session_id = sc.get("session_id") or fallback_name template_name = sc.get("template_name") run_name = (sc.get("session_options") or {}).get("run_name") parts = [str(session_id)] if template_name: parts.append(str(template_name)) if run_name and run_name not in parts: parts.append(str(run_name)) return " · ".join(parts), len(self.node_steps)