# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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
# Michele Faucci Giannelli, faucci@chalmers.se
# Yanchen Lin, linya@chalmers.se
# ══════════════════════════════════════════════════════════════════════════
"""
Module containing the main orchestrator for the QC2 Calibration Toolkit.
"""
from __future__ import annotations
import datetime
import logging
import re
from collections.abc import Generator
from contextlib import contextmanager
from pathlib import Path
from typing import Any
import yaml
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, model_validator
from qblox_scheduler.backends.qblox_backend import QbloxHardwareCompilationConfig
from bragi_quantum.api.handlers.data import RedisDataHandler, SnapshotDataHandler
from bragi_quantum.api.handlers.hardware import (
autocomplete_hardware_options,
create_hardware_agent,
)
from bragi_quantum.api.logging.banner import log_session_banner
from bragi_quantum.api.logging.noisy_loggers import (
DEFAULT_NOISY_LOGGERS,
silence_noisy_loggers,
)
from bragi_quantum.datalayer.managing.redis import (
populate_initial_redis_parameters,
)
from bragi_quantum.datalayer.managing.session import (
ActiveSession,
SessionContext,
SessionOptions,
)
from bragi_quantum.datalayer.models.device import DeviceConfiguration
from bragi_quantum.datalayer.utils.logging.script_save_helper import copy_run_script
from bragi_quantum.datalayer.visualization.pdf_report import (
create_default_header,
create_text_page,
merge_pdfs,
)
from bragi_quantum.gui.rendering.html_rendering import (
create_html_rendering,
create_multi_session_html,
)
# Module-level logger, used by every method in this file.
logger = logging.getLogger(__name__)
# Capture warnings from the `warnings` module and redirect them to the logging system.
logging.captureWarnings(True)
def _require_uniform_dummy_state(dummy_by_cluster: dict[str, bool]) -> bool:
"""Return whether all clusters are dummy, or raise if they disagree.
A run is either fully real or fully dummy — a mix would silently mask
real hardware behind a "measurement" mode that partially never touches
it, so it is rejected outright rather than treated as real.
"""
dummy_flags = set(dummy_by_cluster.values())
if len(dummy_flags) > 1:
raise RuntimeError(
"Mixed real/dummy clusters are not supported: all connected "
f"clusters must share the same dummy-ness, got {dummy_by_cluster}."
)
return bool(dummy_by_cluster) and dummy_flags == {True}
[docs]
class CalibrationOrchestrator(BaseModel):
"""
The Calibration Orchestrator is the main API tool in the QC2 Lab
calibration toolkit.
This is the interface to any calibration or characterization pipeline,
and can be used to execute experiments, modify device parameters,
customize data handling and experiments' report.
The orchestrator automatically initializes on instantiation by:
1. Loading device configuration from device_templates_dir/{experiment_template_name}/device.yaml
2. Loading cluster configuration from device_templates_dir/{experiment_template_name}/cluster.yaml
3. Loading SPI DAC configuration from device_templates_dir/{experiment_template_name}/spi.yaml
4. Connecting to the cluster
All context variables are exposed through SessionContext,
and run-specific options (execution_mode, timeouts, IPs, etc.) are managed via SessionOptions.
Minimal Args:
experiment_template_name: String identifier linking to device_templates_dir/{name}/ directory.
data_handler: Data storage backend (RedisConfig or SnapshotConfig). Defaults to RedisConfig.
"""
model_config = ConfigDict(strict=True, arbitrary_types_allowed=True, extra="forbid")
experiment_template_name: str
data_handler: RedisDataHandler | SnapshotDataHandler = Field(
default_factory=RedisDataHandler
)
load_calibration_state: bool = Field(
default=False,
description="When True, after building the device from device.yaml (topology + "
"core defaults), overlay previously calibrated values stored in Redis onto the "
"live device. Seeding then preserves existing Redis values; when False, Redis is "
"re-seeded from the template and the device keeps the YAML defaults.",
)
output_root: Path = Field(
default=Path("."),
description="Directory under which calibration_outputs/ is written. "
"Defaults to the current working directory.",
)
name: str = Field(
default="",
description="Optional human-readable label for this run.",
)
device_templates_dir: Path | None = Field(
default=None,
description="Base directory containing {experiment_template_name}/"
"{device,cluster,spi}.yaml. Not required to be named device_templates. "
"Defaults to output_root/device_templates; set this explicitly to keep "
"templates elsewhere, e.g. outside version control. "
"This is a special case: most templates should live in the default, "
"version-controlled location, and this field is only for situations "
"such as trying out untracked template variants. Overriding it "
"carelessly can lead to unexpected code execution.",
)
generate_pdf_report: bool = Field(
default=True,
description="Whether to generate the per-run PDF calibration report. "
"When False, no PDF is initialized or written and SessionOptions.pdf_report_filepath "
"is forced to None for every session in this run.",
)
save_run_script: bool = Field(
default=True,
description="Whether to save a copy of the run script into output folder.",
)
reset_clusters: bool = Field(
default=False,
description="Whether to reset every connected cluster instrument "
"the first time this orchestrator connects to hardware (or on any "
"real <-> dummy reconnect). Cluster connections are cached for the "
"orchestrator's lifetime.",
)
noisy_loggers: tuple[str, ...] = Field(
default=DEFAULT_NOISY_LOGGERS,
description="Third-party loggers restricted to WARNING and above on "
"instantiation, to cut down on chatter from dependencies during a "
"calibration run. Override with your own set of logger names to "
"silence a different list.",
)
# Private attributes device-related
_device_config: Any | None = PrivateAttr(default=None)
_device: Any | None = PrivateAttr(default=None)
# Private attributes cluster-related
# Cluster and SPI are initialized lazily on first real session to avoid unnecessary connections
_cluster_config: QbloxHardwareCompilationConfig | None = PrivateAttr(default=None)
_clusters: list[Any] = PrivateAttr(default_factory=list)
_agent: Any | None = PrivateAttr(default=None)
_cluster_connected: bool = PrivateAttr(default=False)
_connected_dummy: bool = PrivateAttr(default=False)
# Private attributes, SPI DAC related
_spi_config: dict | None = PrivateAttr(default=None)
_spi_dac_handler: Any | None = PrivateAttr(default=None)
# Physical wiring map (optional, documentation-only: not used to drive
# hardware, but snapshotted into the session timeline for the report's
# Device Wiring section)
_wiring_config: dict | None = PrivateAttr(default=None)
# PDF report path (per run, set once at orchestrator init)
_pdf_report_path: Path | None = PrivateAttr(default=None)
_run_datetime: str | None = PrivateAttr(default=None)
# Track executed sessions for multi-session HTML aggregation
_executed_sessions: list[str] = PrivateAttr(default_factory=list)
# Holds the active log FileHandler for the current session, so it can be
# detached from the root logger once the session ends.
_log_handler: logging.FileHandler | None = PrivateAttr(default=None)
_prev_root_level: int | None = PrivateAttr(default=None)
@classmethod
def _sanitize_for_dirname(cls, name: str) -> str:
"""Make an arbitrary run or session name safe to splice into a directory name.
Only affects the directory name on disk.
"""
# Characters disallowed (or awkward) in directory names on Windows,
# macOS, and Linux, plus control characters.
_INVALID_DIRNAME_CHARS = re.compile(r'[<>:"/\\|?*\x00-\x1f]')
sanitized = re.sub(r"\s+", "_", name.strip())
sanitized = _INVALID_DIRNAME_CHARS.sub("", sanitized)
return sanitized.strip("._")
@property
def _run_output_dir(self) -> Path:
"""Absolute output directory for this run:
output_root/calibration_outputs/<datetime>[_<sanitized_name>].
"""
sanitized_name = self._sanitize_for_dirname(self.name) if self.name else ""
dir_name = (
self._run_datetime
if not sanitized_name
else f"{self._run_datetime}_{sanitized_name}"
)
return (self.output_root / "calibration_outputs" / dir_name).resolve()
@staticmethod
def _setup_logging() -> None:
"""Give the root logger a console handler, mirroring logging.basicConfig.
Runs on every orchestrator instantiation instead of at module import,
and is a no-op if the application (or a previous orchestrator) already
configured a handler.
"""
root = logging.getLogger()
if not root.handlers:
root.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
handler.setLevel(logging.INFO)
root.addHandler(handler)
@model_validator(mode="after")
def _initialize_orchestrator(self) -> CalibrationOrchestrator:
"""Initialize device from templates. Set datetime_hour once for all sessions. Cluster and SPI are connected lazily on first real session."""
self._setup_logging()
silence_noisy_loggers(self.noisy_loggers)
if self.device_templates_dir is None:
self.device_templates_dir = self.output_root / "device_templates"
self._load_device()
# Load cluster and SPI configs but do not connect yet
self._load_cluster_config()
self._load_spi_config()
self._load_wiring_config()
# Set run datetime once for all sessions in this orchestrator instance
self._run_datetime = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
# Initialize PDF report directory once, unless PDF reporting is disabled
if self.generate_pdf_report:
pdf_dir = self._run_output_dir
pdf_dir.mkdir(parents=True, exist_ok=True)
self._pdf_report_path = pdf_dir / "calibration_report.pdf"
self._initialize_pdf_report_once()
# Snapshot the script that launched this run, for provenance.
if self.save_run_script:
run_dir = self._run_output_dir
run_dir.mkdir(parents=True, exist_ok=True)
copy_run_script(run_dir)
return self
@property
def device(self) -> Any:
"""Expose the loaded (qblox) QuantumDevice to users."""
return self._device
@property
def device_config(self) -> Any:
"""Expose the DeviceConfiguration wrapping the device.
This is the structure that also holds ``extended_state`` — the analysis
quantities not reflected in the live QuantumDevice, kept element-by-element
and node-by-node.
"""
return self._device_config
def _load_device(self) -> None:
"""Load and hydrate the device from device_templates_dir/{experiment_template_name}/device.yaml or snapshot."""
is_snapshot_mode = self.data_handler.database_type == "snapshot"
# Determine path
if is_snapshot_mode:
path = self.data_handler.snapshot_dir / "snapshot.json"
else:
path = (
self.device_templates_dir
/ self.experiment_template_name
/ "device.yaml"
)
if not path.exists():
raise FileNotFoundError(f"Device data not found at {path}")
if path.suffix == ".json" or is_snapshot_mode:
self._load_device_from_snapshot(path)
elif path.suffix in [".yaml", ".yml"]:
self._load_device_from_yaml(path)
else:
raise ValueError(f"Unsupported device file format: {path.suffix}")
logger.info("✅ Device loaded and hydrated successfully.")
def _load_device_from_snapshot(self, path: Path) -> None:
"""Load device from Qblox snapshot JSON."""
logger.info(f"📂 Loading Device from Qblox Snapshot: {path.name}")
self._device_config = DeviceConfiguration.from_snapshot(path)
self._device = self._device_config.configure_device(
name=self.experiment_template_name, is_snapshot=True
)
def _load_device_from_yaml(self, path: Path) -> None:
"""Load device from YAML config and reconcile with Redis.
device.yaml always provides topology and core defaults. Redis is then
seeded from those defaults: as *seed-if-missing* when load_calibration_state
is set (so previously calibrated values survive), or as a full re-seed
otherwise. When load_calibration_state is set, the calibrated values stored
in Redis are finally overlaid onto the live device.
"""
logger.info(f"📂 Loading Device from YAML Config: {path.name}")
self._device_config = DeviceConfiguration.from_yaml(path)
self._device = self._device_config.configure_device(
name=self.experiment_template_name,
is_snapshot=False,
)
if isinstance(self.data_handler, RedisDataHandler):
populate_initial_redis_parameters(
device_config=self._device_config,
redis_connection=self.data_handler.conn,
force=not self.load_calibration_state,
)
if self.load_calibration_state:
logger.info(
"🔄 Overlaying calibrated values from Redis onto the live device."
)
self._device_config.load_calibration_state(self.data_handler.conn)
def _load_cluster_config(self) -> None:
"""Load cluster configuration from device_templates_dir/{experiment_template_name}/cluster.yaml."""
config_path = (
self.device_templates_dir / self.experiment_template_name / "cluster.yaml"
)
if not config_path.exists():
raise FileNotFoundError(
f"Cluster configuration not found at {config_path}!"
)
with open(config_path, encoding="utf-8") as f:
full_config = yaml.safe_load(f)
self._cluster_config = autocomplete_hardware_options(
QbloxHardwareCompilationConfig(**full_config)
)
logger.info("📂 Loaded cluster configuration.")
def _load_spi_config(self) -> None:
"""Load SPI DAC configuration from device_templates_dir/{experiment_template_name}/spi.yaml."""
spi_config_path = (
self.device_templates_dir / self.experiment_template_name / "spi.yaml"
)
if spi_config_path.exists():
with open(spi_config_path, encoding="utf-8") as f:
self._spi_config = yaml.safe_load(f)
logger.info("📂 Loaded SPI DAC configuration.")
else:
logger.warning(
f"⚠️ SPI DAC configuration not found at {spi_config_path}. Skipping SPI DAC initialization."
)
self._spi_config = None
def _load_wiring_config(self) -> None:
"""Load the physical wiring map from device_templates_dir/{experiment_template_name}/wiring.yaml.
Optional: describes chip line -> sample-holder port -> HD fridge line
(see any wiring.yaml header for the schema). It is recorded into the
session timeline so the HTML report can render the Device Wiring
section faithfully to the run, and is not used to drive hardware.
"""
wiring_config_path = (
self.device_templates_dir / self.experiment_template_name / "wiring.yaml"
)
if wiring_config_path.exists():
with open(wiring_config_path, encoding="utf-8") as f:
self._wiring_config = yaml.safe_load(f)
logger.info("📂 Loaded device wiring map.")
else:
self._wiring_config = None
def _connect_cluster(self, execution_mode: str = "measurement") -> None:
"""
Connect to the cluster with specified execution mode via HardwareAgent.
Args:
execution_mode: Execution mode ('measurement' or 'dummy').
Can be overridden per-run via SessionOptions in calibration_session().
"""
is_dummy = execution_mode == "dummy"
cluster_info = {
name: desc.ip
for name, desc in self._cluster_config.hardware_description.items()
if getattr(desc, "ip", None)
}
if cluster_info:
logger.info(f"🌐 Detected Clusters: {cluster_info}")
# Create and configure HardwareAgent
self._agent = create_hardware_agent(
cluster_config=self._cluster_config,
quantum_device=self._device,
reset_clusters=self.reset_clusters,
is_dummy=is_dummy,
)
named_clusters = self._agent.get_clusters()
self._clusters = list(named_clusters.values())
# The connected Cluster objects are the source of truth for dummy-ness:
# requesting create_dummy_connections yields clusters whose `.is_dummy`
# is True. We trust the cluster, not the requested mode string.
self._cluster_connected = True
self._connected_dummy = _require_uniform_dummy_state(
{name: c.is_dummy for name, c in named_clusters.items()}
)
logger.info(
f"✅ Cluster initialized (mode: {execution_mode}, "
f"dummy cluster: {self._connected_dummy})"
)
[docs]
@contextmanager
def calibration_session(
self, session_options: SessionOptions | None = None
) -> Generator[None]:
"""Context manager that provisions a single ActiveSession for the lifetime of the `with` block."""
opts, context = self._build_session_context(session_options)
session_id = context.session_id
log_session_banner(opts.session_name)
ActiveSession.start(context)
logger.info("🟢 Calibration Session started (ID: %s)", session_id)
# Track this session for multi-session HTML aggregation. Stored
# sanitized, matching the actual "session_<...>" folder on disk —
# create_multi_session_html builds its iframe links from this list.
sanitized_session_id = self._sanitize_for_dirname(session_id)
if sanitized_session_id not in self._executed_sessions:
self._executed_sessions.append(sanitized_session_id)
# Save logs to a file under session folder
self._setup_session_log_file(opts)
session_status = "complete"
try:
yield self
except Exception:
session_status = "error"
logger.exception(
"💥 Calibration Session aborted due to an unhandled exception."
)
raise
finally:
# Stamp the session's completion status on its timeline *before* the
# session context is torn down (ActiveSession.stop clears it). This
# is what flips step 0 from "running" to "complete"/"error", so the
# viewer can stop the spinner only when the session is really done.
try:
ActiveSession.get_session_timeline().finalize(session_status)
except Exception as e:
logger.warning(f"⚠️ Could not finalize session timeline: {e}")
# Generate HTML rendering of device topology (stored in session root)
try:
html_render_path = context.root_path / "html_rendering.html"
create_html_rendering(
qubits=self._device_config.qubits,
couplers=self._device_config.couplers,
redis_connection=context.redis_connection,
output_path=html_render_path,
session_root_path=context.root_path,
)
logger.info(f"📊 HTML rendering saved to {html_render_path}")
except Exception as e:
logger.warning(f"⚠️ Could not generate HTML rendering: {e}")
# Write the timing traces
ActiveSession.write_timing_trace_events(context.root_path)
ActiveSession.stop()
logger.info("🔴 Calibration Session stopped.")
self._teardown_session_log_file()
def _setup_session_log_file(self, opts: SessionOptions) -> None:
"""Attach a file handler to the root logger for the duration of the session."""
root = logging.getLogger()
log_path = (
self._run_output_dir
/ f"session_{self._sanitize_for_dirname(opts.session_name)}"
/ "logs.txt"
).resolve()
log_path.parent.mkdir(parents=True, exist_ok=True)
file_handler = logging.FileHandler(log_path, encoding="utf-8")
file_handler.setFormatter(
logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
)
file_handler.setLevel(opts.save_log_level)
root.addHandler(file_handler)
self._log_handler = file_handler
# Open the gate so DEBUG records reach the file handler; restored
# to its previous value once the session ends.
self._prev_root_level = root.level
root.setLevel(logging.DEBUG)
def _teardown_session_log_file(self) -> None:
"""Detach and close the session's file handler, restoring the root logger level."""
if self._log_handler is not None:
root = logging.getLogger()
root.removeHandler(self._log_handler)
self._log_handler.close()
self._log_handler = None
if self._prev_root_level is not None:
root.setLevel(self._prev_root_level)
self._prev_root_level = None
def _build_session_context(self, session_options: SessionOptions | None) -> tuple:
"""Build SessionOptions and SessionContext for a calibration session."""
opts = session_options if session_options is not None else SessionOptions()
# Set absolute PDF report path at run datetime level (shared across all
# sessions in this run), or force it off entirely when PDF reporting is
# disabled for this orchestrator — regardless of what the caller's
# SessionOptions requested.
if self.generate_pdf_report:
opts.pdf_report_filepath = str(
self._run_output_dir / "calibration_report.pdf"
)
else:
opts.pdf_report_filepath = None
# Connect cluster lazily on the first session. Dummy mode connects a
# *simulated* cluster (create_dummy_connections) so the full
# compile → execute → acquire path runs without hardware. The
# connection is cached; we reconnect only if the requested dummy-ness
# differs from the dummy-ness of the cluster currently connected
# (decided by `Cluster.is_dummy` in `_connect_cluster`, not by the
# mode string).
want_dummy = opts.execution_mode == "dummy"
if not self._cluster_connected or self._connected_dummy != want_dummy:
self._connect_cluster(execution_mode=opts.execution_mode)
# Use stored run_datetime (set once at orchestrator init)
# Create session subdirectory with session_name
root_path = (
self._run_output_dir
/ f"session_{self._sanitize_for_dirname(opts.session_name)}"
)
redis_connection = (
self.data_handler.conn
if isinstance(self.data_handler, RedisDataHandler)
else None
)
spi_dac_handler = None
if self._spi_config and opts.spi_serial_port is not None:
# Dummy sessions get a simulated SPI rack so coupler DC-current
# nodes run hardware-free (mirroring the dummy Qblox cluster).
wants_dummy = opts.execution_mode == "dummy"
if (
self._spi_dac_handler is not None
and self._spi_dac_handler.is_dummy != wants_dummy
):
# Mode switched within this process: drop the cached handler
# (closing its QCoDeS instrument frees the "spi_rack" name).
self._spi_dac_handler.spi.close()
self._spi_dac_handler = None
# Cache SPI DAC on first session - reuse for subsequent sessions
if self._spi_dac_handler is None:
self._spi_dac_handler = self._device_config.create_spi_dac(
spi_config=self._spi_config,
spi_serial_port=opts.spi_serial_port,
is_dummy=wants_dummy,
)
spi_dac_handler = self._spi_dac_handler
# Populate SessionContext with all necessary information for nodes to run
context = SessionContext(
session_id=opts.session_name,
experiment_template_name=self.experiment_template_name,
device_templates_dir=self.device_templates_dir,
run_name=self.name,
root_path=root_path,
device_config=self._device_config,
device=self._device,
hardware_agent=self._agent,
redis_connection=redis_connection,
spi_dac_handler=spi_dac_handler,
cluster_config=self._cluster_config,
spi_config=self._spi_config,
session_options=opts,
wiring_config=self._wiring_config,
)
return opts, context
[docs]
def run_node(self, node: Any, session_options: SessionOptions | None = None) -> Any:
"""
Executes a single calibration node.
This method safely wraps the node execution in `calibration_session`.
If called standalone, it starts and stops the session. If called within
an existing `with orchestrator.calibration_session():` block, it reuses
the ongoing session — the same session_id, root path, PDF report, and
timeline are shared across all nodes run inside the outer block, so a
multi-node script produces a single set of output artifacts.
Args:
node: An instantiated calibration node (e.g., QubitSpectroscopyNode).
session_options (Optional[SessionOptions]): Configuration options for the run.
Ignored when running inside an existing session — the outer
session's options take precedence.
Returns:
The result of the node's execution (typically the aggregated QOI).
"""
# If an existing session is detected, run the node directly without starting a new session
if ActiveSession._current is not None:
if session_options is not None:
logger.debug(
"run_node called inside an active session; ignoring "
"the session_options argument and using the outer session's options."
)
logger.info("▶️ Starting execution of node: %s", node.__class__.__name__)
ActiveSession.record_node_boundary(node)
result = node.execute()
return result
# TODO: maybe not?
# No active session detected, so we start a new session for this node
with self.calibration_session(session_options=session_options):
logger.info("▶️ Starting execution of node: %s", node.__class__.__name__)
ActiveSession.record_node_boundary(node)
result = node.execute()
return result
def _initialize_pdf_report_once(self) -> None:
"""Initialize the PDF report once at orchestrator startup with header."""
if self._pdf_report_path is None:
return
self._pdf_report_path.parent.mkdir(parents=True, exist_ok=True)
temp_pdf_path = self._pdf_report_path.parent / "history_header.pdf"
timestring = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
header_text = create_default_header(timestring)
# Create initial PDF with header
create_text_page(
paragraphs=header_text,
output_path=temp_pdf_path,
title="QC2 Calibration Toolkit – Initialization Log",
)
if self._pdf_report_path.exists():
merge_pdfs(self._pdf_report_path, temp_pdf_path, self._pdf_report_path)
else:
temp_pdf_path.rename(self._pdf_report_path)
logger.info("📄 PDF report initialized at %s", self._pdf_report_path)
[docs]
def generate_html_report(self) -> None:
"""
Generate a master HTML file that aggregates all executed sessions.
This method should be called after all sessions are complete to create
a single HTML page with tabs for each session.
"""
if not self._executed_sessions:
logger.warning("⚠️ No sessions have been executed yet")
return
if self._run_datetime is None:
logger.warning("⚠️ run_datetime not initialized")
return
run_datetime_path = self._run_output_dir
try:
master_html_path = run_datetime_path / "index.html"
create_multi_session_html(
session_names=self._executed_sessions,
datetime_hour_path=run_datetime_path,
output_path=master_html_path,
generated_at=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
generated_by="bragi_quantum.api",
run_name=self.name,
)
logger.info(
"🎯 Master HTML with all sessions generated at %s", master_html_path
)
except Exception as e:
logger.warning(f"⚠️ Could not generate master HTML: {e}")