Source code for bragi_quantum.experiments.abstract.analysis

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


# This code is part of Tergite
#
# (C) Copyright Eleftherios Moschandreou 2023, 2024, 2025
# (C) Copyright Liangyu Chen 2023, 2024
# (C) Copyright Stefan Hill 2024
# (C) Copyright Michele Faucci Giannelli 2024
# (C) Copyright Pontus Vikstål 2024, 2025
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
#
# Modified from tergite-autocalibration
# (https://github.com/tergite/tergite-autocalibration), file:
#   tergite_autocalibration/lib/base/analysis.py


from abc import ABC, abstractmethod
from functools import cached_property
from pathlib import Path
from typing import Any

import numpy as np
import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots

from bragi_quantum.datalayer.managing.session import ActiveSession
from bragi_quantum.datalayer.managing.time_tracing import TimingTraceCategory
from bragi_quantum.datalayer.utils.logging import logger
from bragi_quantum.datalayer.visualization.figure_utils import (
    node_metadata_text,
    qc2_logo_data_uri,
)
from bragi_quantum.datalayer.visualization.pdf_report import (
    create_image_page,
    merge_pdfs,
)
from bragi_quantum.datalayer.visualization.plot_style import PLOTLY_TEMPLATE
from bragi_quantum.experiments.abstract.parameters import BaseParameters, BaseQoi
from bragi_quantum.experiments.utils import calibration_points as cal
from bragi_quantum.experiments.utils.dataset_utils import as_dataset, slice_element
from bragi_quantum.experiments.utils.timing import timed

# ---------------------------------------------------------------------------
# Unified, parameter-driven analysis
#
# The analysis is a function of its `parameters`:
# `run(dataset)` analyses every element in `parameters.qubits` (or
# `parameters.couplers`), and the set is restricted simply by overwriting that
# list. Plotting is plotly-native (`figure`/`grid_figure`), with PNG/PDF
# export for the pipeline.
# ---------------------------------------------------------------------------

DEFAULT_GRID_COLUMNS = 5


[docs] class Analysis(ABC): """Unified, parameter-driven analysis for a single calibration node. Usage:: analysis = RabiAnalysis(parameters, Rabi01QOI) analysis.set_parameters(qubits=["q06", "q12"]) # restrict the set results = analysis.run("data/dataset_rabi_0.hdf5") # {element: qoi} fig = analysis.figure("q06") # interactive plotly grid = analysis.grid_figure() # all analysed elements analysis.save(out_dir) # png + preview + pdf ``run`` loops over ``parameters.qubits`` (or ``parameters.couplers`` when ``element_kind == "coupler"``) and analyses each element on its own worker instance, so per-element fit state is preserved for plotting. A single element can also be analysed directly with ``analyse_element``. Subclasses implement two hooks: :meth:`compute_qoi` (populate fit/derived state from ``self.dataset`` / ``self.magnitudes`` and return the QOI) and :meth:`add_traces` (draw this element's plotly traces). """ element_kind: str = "qubit" # Set True on subclasses that use bragi_quantum.experiments.utils.calibration_points; # mirrors BaseNode.append_calibration_points. expects_calibration_points: bool = False def __init__( self, parameters: BaseParameters, qoi_cls: "type[BaseQoi] | None" = None, ): self.parameters = parameters self.qoi_cls = qoi_cls # populated by run(): element name -> worker instance / QOI self.workers: dict[str, Analysis] = {} self.results: dict[str, BaseQoi] = {} # per-element state (set when THIS instance analyses a single element) self.element: str | None = None # ``qubit`` / ``coupler`` mirror ``element`` for the active kind, so # per-node fit code can keep reading self.qubit / self.coupler. self.qubit: str | None = None self.coupler: str | None = None self.dataset = None self.S21 = None self.magnitudes = None self.data_var = None self.coord = None self.qoi: BaseQoi | None = None # legacy attributes set by the BaseNode orchestration (compat) self.pdf_report_path: Path | None = None self.produce_support_figures: bool = True # how many elements bragi_quantum.gui is rendering this plot for together (a # multi-element marquee selection in its UI); set by its replay path, # 1 otherwise. Lets a single-element analysis know it's part of a # batch render without depending on parameters.qubits (the node's # full run scope, which is unrelated to what's being viewed now). self.n_selected_elements: int = 1 # -- parameter interface ------------------------------------------------ #
[docs] def set_parameters(self, **overrides) -> "Analysis": """Update parameters in place (pydantic-revalidated) and return self.""" self.parameters = self.parameters.model_copy(update=overrides) return self
def _targets(self) -> "list[str]": if self.element_kind == "coupler": return list(self.parameters.couplers) return list(self.parameters.qubits) def _infer_targets(self, dataset) -> "list[str]": """Elements present in ``dataset`` (used when the parameters list none).""" variables = list(dataset.data_vars) if self.element_kind == "coupler": return [v for v in variables if "_" in v] return [v for v in variables if "_" not in v] def _params_for(self, element: str) -> BaseParameters: """Parameters resolved for ``element`` (applies any per-element overrides). Uses ``custom_parameters`` via ``for_coupler`` / ``for_qubit`` so a per-element analysis knob (e.g. a tighter threshold on one qubit) takes effect during ``run``. """ if self.element_kind == "coupler": return self.parameters.for_coupler(element) return self.parameters.for_qubit(element) # -- execution ---------------------------------------------------------- #
[docs] def analyse_element(self, dataset, element: str) -> BaseQoi: """Slice ``element`` from ``dataset`` (Dataset or path) and fit it here.""" element_ds = slice_element( dataset, element, kind=self.element_kind, node_name=getattr(self.parameters, "name", None), ) return self._process(element_ds, element)
def _process(self, dataset, element: str) -> BaseQoi: """Fit an already-sliced single-element ``dataset`` on this instance.""" self.element = element if self.element_kind == "coupler": self.coupler = element else: self.qubit = element self.dataset = dataset self.coord = dataset.coords # The main sweep variable is the qubit/coupler data itself; auxiliary # variables such as "<qubit>_CAL" must never be selected. data_vars = list(dataset.data_vars.keys()) non_calib = [v for v in data_vars if not str(v).endswith("_CAL")] self.data_var = (non_calib or data_vars)[0] self.S21 = dataset.isel(ReIm=0) + 1j * dataset.isel(ReIm=1) self.magnitudes = np.abs(self.S21) self.qoi = self.compute_qoi() return self.qoi @cached_property def has_calibration_points(self) -> bool: """Whether this element's calibration points are present and complete. Raises ``CalibrationPointsError`` if calibration points are present but ``expects_calibration_points`` is ``False`` — that combination means this analysis could use them but doesn't declare so. """ element_name = self.qubit if self.qubit is not None else self.element complete = cal.dataset_has_calibration_points_for_all_qubits( self.dataset, element_name ) if complete and not self.expects_calibration_points: raise cal.CalibrationPointsError( f"Calibration points found for {element_name} but " f"{type(self).__name__}.expects_calibration_points is False " "— set it to True if this analysis should use them." ) return complete # -- legacy per-element entry points ----------------------------------- # # ``process_qubit`` / ``process_coupler`` took an already-sliced dataset and # are still called by nodes that reuse a single-element analysis as a # building block (e.g. punchout, resonator-vs-current). Kept as thin # verbatim aliases until those callers move to ``analyse_element``.
[docs] def process_qubit(self, dataset, qubit_name: str) -> BaseQoi: return self._process(dataset, qubit_name)
[docs] def process_coupler(self, dataset, coupler_element: str) -> BaseQoi: return self._process(dataset, coupler_element)
[docs] def run(self, dataset) -> "dict[str, BaseQoi]": """Analyse the target elements; return ``{element: qoi}``. Targets are ``parameters.qubits`` / ``parameters.couplers``. If that list is empty, every matching element found in ``dataset`` is analysed — so ``run`` works out-of-the-box on a raw dataset, and a subset is selected simply by setting the parameters list. """ ds = as_dataset(dataset) logger.info(f"Opened dataset for {self.parameters.name}") targets = self._targets() or self._infer_targets(ds) self.workers, self.results = {}, {} if not targets: logger.warning( f"⚠️ No {self.element_kind}s found for {self.parameters.name}. " "Skipping analysis." ) return self.results for element in targets: worker = type(self)(self._params_for(element), self.qoi_cls) self.results[element] = worker.analyse_element(ds, element) self.workers[element] = worker return self.results
# -- per-node hooks ----------------------------------------------------- #
[docs] @abstractmethod def compute_qoi(self) -> BaseQoi: """Compute the QOI for the current element. Runs against ``self.dataset`` / ``self.magnitudes`` / ``self.data_var`` (already set for the current element) and should store whatever state :meth:`add_traces` needs on ``self``. """
[docs] @abstractmethod def add_traces(self, fig, row: int = 1, col: int = 1) -> None: """Add this element's plotly traces (and axis titles) to ``fig`` at (row, col)."""
[docs] def plot_title(self) -> str: """Title for this element's (sub)plot. Override per node if desired.""" return f"{self.element_kind.capitalize()} {self.element}"
[docs] def list_plots(self) -> "list[str]": """Names of the plots this analysis can render. Override for multi-plot nodes.""" return ["main"]
[docs] def support_figures(self) -> "list[tuple[Any, str]]": """Extra per-element diagnostic figures as ``(plotly_figure, filename)``. Called on each analysed element's worker during save. Default: none. Override for nodes with 1-D projections / per-slice diagnostics. """ return []
# -- plotting ----------------------------------------------------------- # def _worker_for(self, element: "str | None") -> "Analysis": if element is not None: return self.workers[element] if self.element is not None: return self if len(self.workers) == 1: return next(iter(self.workers.values())) raise ValueError( "specify an element: this analysis has " f"{len(self.workers)} analysed elements" )
[docs] def figure(self, element: "str | None" = None, plot_name: str = "main"): """Return a plotly Figure for one analysed ``element``.""" worker = self._worker_for(element) fig = go.Figure() worker._render_figure(fig, plot_name) self._apply_branding(fig) return fig
def _render_figure(self, fig: "go.Figure", plot_name: str) -> None: """Configure ``fig``'s subplot structure and populate it for ``plot_name``. Default: builds a 1×1 subplot and delegates to :meth:`add_traces`. Override to handle additional ``plot_name`` values; call ``super()`` to fall through to the default path. """ make_subplots(rows=1, cols=1, subplot_titles=[self.plot_title()], figure=fig) self.add_traces(fig, 1, 1) fig.update_layout( template=PLOTLY_TEMPLATE, showlegend=False, width=760, height=520, margin={"t": 80, "b": 40}, )
[docs] def grid_figure(self, ncols: int = DEFAULT_GRID_COLUMNS): """Return a plotly grid Figure over every analysed element.""" fig = go.Figure() self._render_grid_figure(fig, ncols) self._apply_branding(fig) return fig
def _render_grid_figure(self, fig: "go.Figure", ncols: int) -> None: """Configure ``fig`` as a grid of all analysed elements. Default: one cell per element, :meth:`add_traces` per cell. Override to build a different multi-element layout. """ workers = list(self.workers.values()) or ( [self] if self.element is not None else [] ) if not workers: raise ValueError("nothing analysed yet; call run(...) first") ncols = min(ncols, len(workers)) nrows = int(np.ceil(len(workers) / ncols)) make_subplots( rows=nrows, cols=ncols, subplot_titles=[w.plot_title() for w in workers], horizontal_spacing=0.05, vertical_spacing=max(0.06, 0.18 / nrows), figure=fig, ) for i, worker in enumerate(workers): worker.add_traces(fig, row=i // ncols + 1, col=i % ncols + 1) fig.update_layout( template=PLOTLY_TEMPLATE, showlegend=False, width=ncols * 460, height=nrows * 430 + 90, margin={"t": 90, "b": 40}, ) def _apply_branding(self, fig) -> None: """Add the QC2 logo (top-left) and metadata header into the figure's top margin. Offsets are in pixels (converted to paper fractions from the figure size) so the header/logo sit consistently regardless of grid shape. """ height = fig.layout.height or 500 width = fig.layout.width or 800 # Main title: bigger and bolder than the subplot titles, centered in the # top margin. title_shift = 52 fig.add_annotation( text=f"<b>{node_metadata_text(getattr(self.parameters, 'name', ''))}</b>", xref="paper", yref="paper", x=0.5, y=1.0, yshift=title_shift, xanchor="center", yanchor="middle", showarrow=False, font={"size": 22, "color": "#111"}, ) uri = qc2_logo_data_uri() if uri: logo_px = 46 # Vertically centred on the main title (same yshift, as paper units). fig.add_layout_image( { "source": uri, "xref": "paper", "yref": "paper", "x": 0.0, "y": 1.0 + title_shift / height, "sizex": logo_px / width, "sizey": logo_px / height, "xanchor": "left", "yanchor": "middle", "sizing": "contain", "layer": "above", } ) # -- export ------------------------------------------------------------- #
[docs] def save_png(self, path, *, grid: bool = True, scale: int = 2) -> "Path": """Write a PNG (grid of all elements by default) via kaleido.""" fig = self.grid_figure() if grid else self.figure() path = Path(path) fig.write_image(str(path), scale=scale) return path
# -- persistence -------------------------------------------------------- #
[docs] def save(self, out_dir) -> None: """Write this node's figures into ``out_dir`` (call after :meth:`run`). Produces the grid ``{name}.png`` + ``{name}_preview.png``, the per-element support figures, and — if ``pdf_report_path`` is set — merges them into the report PDF. This is the output half of the analysis; :meth:`run` does the analysis and populates the per-element workers used here. """ out_dir = Path(out_dir) logger.info(f"Saving plots for {self.parameters.name}") with timed( "Image generation took: ", timing_category=TimingTraceCategory.ANALYSIS, ): fig = self.grid_figure() grid_png = out_dir / f"{self.parameters.name}.png" preview_png = out_dir / f"{self.parameters.name}_preview.png" figs = [fig, fig] paths = [grid_png, preview_png] scales = [2, 1] support_entries: list[tuple[Any, Path]] = [] if self.produce_support_figures: workers = list(self.workers.values()) or ( [self] if self.element is not None else [] ) for worker in workers: for support_fig, name in worker.support_figures(): support_entries.append((support_fig, out_dir / name)) figs += [support_fig for support_fig, _ in support_entries] paths += [path for _, path in support_entries] scales += [2] * len(support_entries) # Batch all PNG exports into a single Kaleido/choreographer browser # session instead of one browser start/stop per plot. Unlike # fig.write_image(), write_images() does NOT fall back to each # figure's own layout.width/height — omitting them here silently # forces every image to plotly's global default (700x500), # squishing e.g. a 5x2 grid into a box a fraction of its intended # size. Pass them through explicitly so each PNG keeps the size set # by _render_grid_figure()/style_layout(). widths = [f.layout.width for f in figs] heights = [f.layout.height for f in figs] pio.write_images(figs, paths, scale=scales, width=widths, height=heights) logger.info(f"Plots saved to {preview_png} and {grid_png}") if self.pdf_report_path is not None: with timed( f"PDF report update ({self.parameters.name}) took: ", timing_category=TimingTraceCategory.LOGGING, ): self._add_plots_to_pdf_report(grid_png) for _, path in support_entries: self._add_plots_to_pdf_report(path)
def _add_plots_to_pdf_report(self, plot_path: "Path") -> None: """Merge ``plot_path`` into the history report PDF.""" temp_pdf = self.pdf_report_path.parent / f"{self.parameters.name}_temp.pdf" custom_name = "" try: session = ActiveSession.get() if hasattr(session, "session_options") and hasattr( session.session_options, "custom_name" ): custom_name = session.session_options.custom_name except (RuntimeError, AttributeError): pass create_image_page( image_path=plot_path, output_path=temp_pdf, node_name=self.parameters.name, custom_name=custom_name, unique_id=Path(plot_path).parent.name, ) if self.pdf_report_path.exists(): merge_pdfs( base_pdf=self.pdf_report_path, new_pdf=temp_pdf, output=self.pdf_report_path, ) else: self.pdf_report_path.parent.mkdir(parents=True, exist_ok=True) temp_pdf.rename(self.pdf_report_path)