Source code for bragi_quantum.experiments.nodes.characterization.randomized_benchmarking.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
#   Matteo Robbiati, robbiati@chalmers.se
#   Yanchen Lin, linya@chalmers.se
#   Michele Faucci Giannelli, faucci@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


"""
Module containing the class that classifies, fits and plots data from a
randomized benchmarking (RB) experiment.
"""

from typing import override

import numpy as np
import plotly.graph_objects as go
import xarray as xr
from plotly.subplots import make_subplots

from bragi_quantum.datalayer.visualization.plot_style import (
    STATE_COLORS,
    failure_box,
    label_box,
    style_layout,
)
from bragi_quantum.experiments.abstract.analysis import (
    DEFAULT_GRID_COLUMNS,
    Analysis,
)
from bragi_quantum.experiments.fitting_tools.models.randomized_benchmarking import (
    RBDecayModel,
)
from bragi_quantum.experiments.nodes.characterization.randomized_benchmarking.parameters import (
    RBQOI,
    RBParameters,
)
from bragi_quantum.experiments.utils import calibration_points as cal
from bragi_quantum.experiments.utils.analysis_field_utils import (
    parse_index_selector,
)

# RB should start near P(|0>) = 1 at m=0 Cliffords; well below this and the
# classification/calibration is untrustworthy, mirroring tergite's guard.
MINIMUM_INITIAL_GROUND_STATE_POPULATION = 0.88
IQ_CLOUD_MAX_CELL_SIZE = 250
IQ_CLOUD_MAX_GRID_WIDTH = 1000
IQ_CLOUD_LEGEND_WIDTH = 160


[docs] class RBAnalysis(Analysis): """ Analysis that classifies single-shot RB data into states 0/1/2 and fits the resulting population decays. Every shot is classified via nearest-centroid (Voronoi) comparison built from three pairwise calibration-axis projections (``bragi_quantum.experiments.utils.calibration_points.project_onto_calibration`` with ``(low, high)`` = (0, 1), (1, 2) and (0, 2)): treating each state's calibration population as bivariate Gaussian with shared covariance, each pairwise axis's 0.5 threshold is exactly that pair's Bayes decision boundary, so the state that wins both of its relevant pairwise comparisons is the globally nearest centroid (see ``_classify_shots``). All three axes are needed — |2> is not generally collinear with |0>-|1>, so a sequential two-axis check would silently misclassify. If the qubit's 1->2 pulse isn't calibrated (no ``CAL=2`` point), classification falls back to 0-vs-1 only and leakage/seepage are left unmeasured (NaN). Every one of the ``n_seeds`` independent random-Clifford realizations carries its OWN calibration points (never an average across seeds), so each seed's shots are classified against calibration measured in that same compiled schedule. State populations are then averaged across seeds; the seed-to-seed standard deviation is used as the fit weight — a sequence length whose population is well-determined across seeds pulls harder on the fit. """ element_kind = "qubit" expects_calibration_points = True parameters: RBParameters def __init__(self, parameters: RBParameters, qoi_cls: type[RBQOI]): super().__init__(parameters, qoi_cls) self.cliffords_coord = None self.shot_coord = None self.seeds_coord = None self.number_cliffords = None self.fit_n_cliffords = None self.has_leakage_calibration = False self.classified_state = None self.mean_p0 = None self.sigma_p0 = None self.mean_p1 = None self.mean_p2 = None self.mean_computational = None self.sigma_computational = None self.fidelity = None self.fidelity_error = None self.reduced_chi2 = None self.leakage = None self.leakage_error = None self.seepage = None self.seepage_error = None self.fit_y_state0 = None self.fit_y_computational = None def _classify_shots(self): """Return per-shot state labels (0/1/2), and whether CAL=2 was found. Nearest-centroid (Voronoi) classification via pairwise projections: under the shared-covariance bivariate-Gaussian assumption, each pairwise axis's 0.5 threshold is exactly that pair's Bayes decision boundary, and the state that wins both of its relevant pairwise comparisons is the globally nearest centroid. This needs all three pairwise axes (0-1, 1-2, 0-2) — the |2> centroid is not generally collinear with |0>-|1>, so a sequential "0-vs-rest then 1-vs-2" check on only two axes is not equivalent to nearest-centroid and silently misclassifies whenever |2> projects "behind" |0> on the 0-1 axis. """ element_name = self.qubit if self.qubit is not None else self.element shots = self.S21[self.data_var] calib = cal.get_calibration_complex(self.dataset, element_name) has_leakage_calibration = 2.0 in calib.coords["CAL"].values p01 = cal.project_onto_calibration(shots, calib, low=0, high=1) if not has_leakage_calibration: return xr.where(p01 < 0.5, 0, 1), False p12 = cal.project_onto_calibration(shots, calib, low=1, high=2) p02 = cal.project_onto_calibration(shots, calib, low=0, high=2) is_0 = (p01 < 0.5) & (p02 < 0.5) is_1 = (p01 >= 0.5) & (p12 < 0.5) state = xr.where(is_0, 0, xr.where(is_1, 1, 2)) return state, True
[docs] @override def compute_qoi(self) -> RBQOI: data_array = self.dataset[self.data_var] for coord in data_array.coords: coord_str = str(coord) if "cliffords" in coord_str: self.cliffords_coord = coord elif "shot_index" in coord_str: self.shot_coord = coord elif coord_str == "seeds": self.seeds_coord = coord try: state, self.has_leakage_calibration = self._classify_shots() except cal.CalibrationPointsError: return self.qoi_cls(is_successful=False) self.classified_state = state self.number_cliffords = self.dataset[self.cliffords_coord].values self.fit_n_cliffords = np.linspace( self.number_cliffords.min(), self.number_cliffords.max(), 400 ) n_shots = self.dataset.sizes[self.shot_coord] p0 = (state == 0).sum(dim=self.shot_coord) / n_shots p1 = (state == 1).sum(dim=self.shot_coord) / n_shots p2 = (state == 2).sum(dim=self.shot_coord) / n_shots p_computational = p0 + p1 self.mean_p0 = p0.mean(dim=self.seeds_coord).transpose(self.cliffords_coord) self.sigma_p0 = p0.std(dim=self.seeds_coord, ddof=1).transpose( self.cliffords_coord ) self.mean_p1 = p1.mean(dim=self.seeds_coord).transpose(self.cliffords_coord) self.mean_p2 = p2.mean(dim=self.seeds_coord).transpose(self.cliffords_coord) self.mean_computational = p_computational.mean(dim=self.seeds_coord).transpose( self.cliffords_coord ) self.sigma_computational = p_computational.std( dim=self.seeds_coord, ddof=1 ).transpose(self.cliffords_coord) mean_p0_values = self.mean_p0.values # Cliffords=0 is the shortest sequence and should sit at the start of # the (already sorted) coordinate array. if mean_p0_values[np.argmin(self.number_cliffords)] < ( MINIMUM_INITIAL_GROUND_STATE_POPULATION ): return self.qoi_cls(is_successful=False) fit_result_0 = self._fit_state0(mean_p0_values) if fit_result_0 is None: return self.qoi_cls(is_successful=False) self.fidelity = (1 + fit_result_0.params["p"].value) / 2 self.fidelity_error = (fit_result_0.params["p"].stderr or 0.0) / 2 self.reduced_chi2 = float(fit_result_0.redchi) self.fit_y_state0 = fit_result_0.eval(m=self.fit_n_cliffords) if self.has_leakage_calibration: self._fit_leakage_seepage() return self.qoi_cls( is_successful=True, fidelity=self.fidelity, fidelity_error=self.fidelity_error, reduced_chi2=self.reduced_chi2, leakage=self.leakage if self.leakage is not None else float("nan"), leakage_error=( self.leakage_error if self.leakage_error is not None else float("nan") ), seepage=self.seepage if self.seepage is not None else float("nan"), seepage_error=( self.seepage_error if self.seepage_error is not None else float("nan") ), )
def _fit_state0(self, mean_p0_values: np.ndarray): sigma = np.maximum(self.sigma_p0.values, 1e-6) model = RBDecayModel() guess = model.guess(mean_p0_values, m=self.number_cliffords) try: fit_result = model.fit( mean_p0_values, params=guess, m=self.number_cliffords, weights=1.0 / sigma, ) except Exception: try: fit_result = model.fit( mean_p0_values, params=guess, m=self.number_cliffords ) except Exception: return None if not fit_result.errorbars: return None return fit_result def _fit_leakage_seepage(self) -> None: computational_values = self.mean_computational.values sigma = np.maximum(self.sigma_computational.values, 1e-6) model = RBDecayModel() guess = model.guess(computational_values, m=self.number_cliffords) # Adjusted starting point for the (inverted-looking) leakage decay: # small amplitude, close-to-1 asymptote, near-unity depolarizing p. guess["A"].value = 0.01 guess["B"].value = 1.0 guess["p"].value = 0.98 try: fit_result = model.fit( computational_values, params=guess, m=self.number_cliffords, weights=1.0 / sigma, ) except Exception: try: fit_result = model.fit( computational_values, params=guess, m=self.number_cliffords ) except Exception: return self.fit_y_computational = fit_result.eval(m=self.fit_n_cliffords) # L = (1-B)(1-p), S = B(1-p): see Wood & Gambetta, "Quantification and # characterization of leakage errors", eq. 10-11. B_value = fit_result.params["B"].value p_value = fit_result.params["p"].value self.leakage = (1 - B_value) * (1 - p_value) self.seepage = B_value * (1 - p_value) if not fit_result.errorbars: self.leakage_error = float("nan") self.seepage_error = float("nan") return names = list(fit_result.params.keys()) B_index, p_index = names.index("B"), names.index("p") B_stderr = fit_result.params["B"].stderr p_stderr = fit_result.params["p"].stderr cov_B_p = fit_result.covar[B_index, p_index] self.leakage_error = float( np.sqrt( (1 - B_value) ** 2 * p_stderr**2 + (1 - p_value) ** 2 * B_stderr**2 + 2 * (1 - B_value) * (1 - p_value) * cov_B_p ) ) self.seepage_error = float( np.sqrt( B_value**2 * p_stderr**2 + (1 - p_value) ** 2 * B_stderr**2 - 2 * B_value * (1 - p_value) * cov_B_p ) )
[docs] @override def plot_title(self) -> str: return f"Randomized Benchmarking — {self.element}"
[docs] @override def list_plots(self): return ["main", "iq_cloud"]
@override def _render_figure(self, fig: "go.Figure", plot_name: str) -> None: """``"main"`` -> default population-decay path; ``"iq_cloud"`` -> single-shot IQ cloud at one (repetition, sequence-length) point.""" if plot_name == "main": super()._render_figure(fig, plot_name) return method = getattr(self, f"_{plot_name}_figure", None) if method is None: raise ValueError(f"Unknown plot '{plot_name}' for {type(self).__name__}") src = method() for trace in src.data: fig.add_trace(trace) fig.update_layout(src.to_dict().get("layout", {}))
[docs] @override def support_figures(self) -> "list[tuple[go.Figure, str]]": """The IQ-cloud figure, saved to disk alongside the main decay plot. Same figure as the interactive "iq_cloud" plot in bragi_quantum.gui; skipped when there's no calibration/classification to show it against. """ if self.number_cliffords is None or self.classified_state is None: return [] return [ ( self._iq_cloud_figure(), f"{self.parameters.name}_{self.element}_iq_cloud.png", ) ]
def _iq_cloud_cell_traces( self, fig: "go.Figure", seed_index: int, point_index: int, row: int, col: int, single_cell: bool, legend_entries: dict, ) -> None: """Add one (seed, sequence-length) cell's shots and calibration centers to ``fig``. Shot markers are translucent: size 7 for the single view, 3 for a grid cell. Each trace drawn records its legend entry (name and marker) in ``legend_entries``. """ selection = {self.seeds_coord: seed_index, self.cliffords_coord: point_index} iq = self.S21[self.data_var].isel(selection).values state = self.classified_state.isel(selection).values marker_style = {"size": 7 if single_cell else 3, "opacity": 0.4} for s, label in enumerate(("|0⟩", "|1⟩", "|2⟩")): mask = state == s if not np.any(mask): continue fig.add_trace( go.Scatter( x=iq[mask].real, y=iq[mask].imag, mode="markers", marker={**marker_style, "color": STATE_COLORS[s]["tp"]}, name=f"shots → {label}", showlegend=False, ), row=row, col=col, ) legend_entries[(0, s)] = ( f"shots → {label}", {"size": 8, "color": STATE_COLORS[s]["tp"]}, ) element_name = self.qubit if self.qubit is not None else self.element calib = cal.get_calibration_complex(self.dataset, element_name).isel( {self.seeds_coord: seed_index} ) for s, label in enumerate(("|0⟩", "|1⟩", "|2⟩")): if float(s) not in calib.coords["CAL"].values: continue center = complex(calib.sel(CAL=float(s)).values) center_marker = { "size": 18, "color": STATE_COLORS[s]["tp"], "symbol": "x", # White border keeps the cross visible on a same-colored shot cloud. "line": {"color": "white", "width": 2.5}, } fig.add_trace( go.Scatter( x=[center.real], y=[center.imag], mode="markers+text", marker=center_marker, text=[label], textposition="top center", textfont={"size": 13, "color": "black"}, name=f"{label} center", showlegend=False, ), row=row, col=col, ) # The legend swatch keeps the black border; the white one is for the plot. legend_entries[(1, s)] = ( f"{label} center", { **center_marker, "size": 12, "line": {"color": "black", "width": 1.5}, }, ) @staticmethod def _place_iq_cloud_title(fig) -> None: """Move the layout title to the very top, clear of the branding header.""" fig.update_layout( title={ "x": 0.5, "xanchor": "center", "y": 1 - 8 / fig.layout.height, "yanchor": "top", "font": {"size": 13}, } ) def _iq_cloud_figure(self): """Single-shot IQ cloud(s) for the selected seed/sequence-length point(s), colored by classified state, styled like ro_combined_optimization's IQ cloud. ``parameters.seed_number``/``clifford_sequence_index`` each take a 1-based index, comma list, or inclusive range (e.g. ``"1"``, ``"1,3"``, ``"2-4"``) — left blank, each defaults to a single point (first seed / last sequence-length point) rather than every point, to avoid defaulting to an unreadable full grid. Multiple selected points render as a grid of ``DEFAULT_GRID_COLUMNS`` cells per row, one cell per (seed, point) pair, filled row by row. Raises ``ValueError`` naming the field for a malformed or out-of-range selector. """ fig = go.Figure() if self.number_cliffords is None or self.classified_state is None: failure_box(fig, "IQ cloud unavailable — calibration points missing.") style_layout( fig, width=620, height=620, title=f"{self.parameters.name} — {self.element} — IQ cloud", ) return fig n_seeds = self.dataset.sizes[self.seeds_coord] n_points = self.number_cliffords.size seed_selector = self.parameters.seed_number if seed_selector is None or not seed_selector.strip(): seed_selector = "1" point_selector = self.parameters.clifford_sequence_index if point_selector is None or not point_selector.strip(): point_selector = str(n_points) seed_indices = parse_index_selector(seed_selector, n_seeds, "seed_number") point_indices = parse_index_selector( point_selector, n_points, "clifford_sequence_index" ) cells = [ (seed_index, point_index) for seed_index in seed_indices for point_index in point_indices ] single_cell = len(cells) == 1 n_cols = min(DEFAULT_GRID_COLUMNS, len(cells)) n_rows = -(-len(cells) // n_cols) # The calibration centers count towards the range too: a |2> center # can sit outside every shot's bounding box and would be cut off. element_name = self.qubit if self.qubit is not None else self.element calibration = cal.get_calibration_complex(self.dataset, element_name) all_iq = np.concatenate( [ self.S21[self.data_var] .isel({self.seeds_coord: seed_index, self.cliffords_coord: point_index}) .values.ravel() for seed_index in seed_indices for point_index in point_indices ] + [ calibration.isel({self.seeds_coord: seed_index}).values.ravel() for seed_index in seed_indices ] ) x_min, x_max = float(np.nanmin(all_iq.real)), float(np.nanmax(all_iq.real)) y_min, y_max = float(np.nanmin(all_iq.imag)), float(np.nanmax(all_iq.imag)) pad_x = 0.05 * (x_max - x_min) pad_y = 0.05 * (y_max - y_min) x_min, x_max = x_min - pad_x, x_max + pad_x y_min, y_max = y_min - pad_y, y_max + pad_y x_range, y_range = x_max - x_min, y_max - y_min if x_range > y_range: y_centre = (y_min + y_max) / 2 y_min, y_max = y_centre - x_range / 2, y_centre + x_range / 2 else: x_centre = (x_min + x_max) / 2 x_min, x_max = x_centre - y_range / 2, x_centre + y_range / 2 fig = make_subplots( rows=n_rows, cols=n_cols, horizontal_spacing=0.03, vertical_spacing=0.14 / n_rows, # Skip the unused trailing cells of the last row. specs=[ [ {} if r_idx * n_cols + c_idx < len(cells) else None for c_idx in range(n_cols) ] for r_idx in range(n_rows) ], subplot_titles=( None if single_cell else [ f"seed {seed_index + 1} · " f"{int(self.number_cliffords[point_index])} Cliffords" for seed_index, point_index in cells ] ), ) for ann in fig.layout.annotations: ann.font = {"size": 9} legend_entries: dict[tuple[int, int], tuple[str, dict]] = {} # Row-major fill, so cell ``i`` owns axes ``x{i + 1}``/``y{i + 1}``. for cell_idx, (seed_index, point_index) in enumerate(cells): row, col = divmod(cell_idx, n_cols) row, col = row + 1, col + 1 self._iq_cloud_cell_traces( fig, seed_index, point_index, row, col, single_cell, legend_entries ) fig.update_xaxes( range=[x_min, x_max], row=row, col=col, showticklabels=single_cell, ticks="outside" if single_cell else "", ) fig.update_yaxes( range=[y_min, y_max], row=row, col=col, showticklabels=single_cell, ticks="outside" if single_cell else "", ) # Square-aspect, synchronously zoomed/panned axes across every cell. axis_suffix = "" if cell_idx == 0 else str(cell_idx + 1) if cell_idx > 0: fig.layout[f"xaxis{axis_suffix}"].matches = "x" fig.layout[f"yaxis{axis_suffix}"].matches = "y" fig.layout[f"yaxis{axis_suffix}"].update( scaleanchor=f"x{axis_suffix}", scaleratio=1, constrain="domain" ) # Dedicated legend entries: the per-cell markers are too small to read there. for _, (name, marker) in sorted(legend_entries.items()): fig.add_trace( go.Scatter( x=[None], y=[None], mode="markers", marker=marker, name=name, showlegend=True, ), row=1, col=1, ) if single_cell: seed_index, point_index = cells[0] clifford_count = int(self.number_cliffords[point_index]) fig.update_xaxes(title_text="I") fig.update_yaxes(title_text="Q") style_layout( fig, width=540 + IQ_CLOUD_LEGEND_WIDTH, height=620, showlegend=True, title=f"{self.parameters.name} — {self.element} — IQ cloud", ) fig.update_layout(margin={"r": IQ_CLOUD_LEGEND_WIDTH, "t": 100, "b": 60}) self._place_iq_cloud_title(fig) # Above the plot: below it the footnote collides with the tick labels. fig.add_annotation( xref="paper", yref="paper", x=0.5, y=1, yshift=6, xanchor="center", yanchor="bottom", showarrow=False, text=( f"seed {seed_index + 1}/{n_seeds}" f" clifford_sequence {point_index + 1}/{n_points}" f" ({clifford_count} Cliffords)" ), font={"size": 11, "color": "gray"}, ) else: # Same cell sizing as ro_combined_optimization's iq_grid; the margins # (title on top, legend on the right) are added so they don't squash the cells. cell_size = min(IQ_CLOUD_MAX_CELL_SIZE, IQ_CLOUD_MAX_GRID_WIDTH // n_cols) cell_height = max(cell_size, 200) if n_rows <= 3 else cell_size style_layout( fig, width=cell_size * n_cols + 30 + IQ_CLOUD_LEGEND_WIDTH, height=cell_height * n_rows + 130, showlegend=True, title=f"{self.parameters.name} — {self.element} — IQ clouds", ) fig.update_layout( margin={"l": 30, "r": IQ_CLOUD_LEGEND_WIDTH, "t": 100, "b": 30} ) self._place_iq_cloud_title(fig) fig.update_layout( meta={ "seed_number": seed_selector, "clifford_sequence_index": point_selector, } ) return fig
[docs] @override def add_traces(self, fig, row: int = 1, col: int = 1) -> None: for values, name, color in ( (self.mean_p0, "P(|0⟩)", "blue"), (self.mean_p1, "P(|1⟩)", "red"), (self.mean_p2, "P(|2⟩)", "green"), ): if values is None: continue fig.add_trace( go.Scatter( x=self.number_cliffords, y=values.values, mode="markers", marker={"size": 6, "color": color}, name=name, showlegend=True, ), row=row, col=col, ) label_lines = [] if self.fit_y_state0 is not None: fig.add_trace( go.Scatter( x=self.fit_n_cliffords, y=self.fit_y_state0, mode="lines", line={"color": "blue", "width": 2, "dash": "dash"}, showlegend=False, ), row=row, col=col, ) label_lines.append( f"F_avg = {self.fidelity:.4f} ± {self.fidelity_error:.4f}" ) label_lines.append(f"χ²/DOF = {self.reduced_chi2:.2f}") if self.fit_y_computational is not None: fig.add_trace( go.Scatter( x=self.fit_n_cliffords, y=1 - self.fit_y_computational, mode="lines", line={"color": "green", "width": 2, "dash": "dash"}, showlegend=False, ), row=row, col=col, ) label_lines.append( f"Leakage = ({self.leakage * 1e3:.1f}±{self.leakage_error * 1e3:.1f})e-3" ) label_lines.append( f"Seepage = ({self.seepage * 1e3:.1f}±{self.seepage_error * 1e3:.1f})e-3" ) if label_lines: label_box(fig, "<br>".join(label_lines), row=row, col=col) elif self.fit_y_state0 is None: fig.add_annotation( text="RB fit failed — check calibration and initial fidelity.", xref="x domain", yref="y domain", x=0.5, y=0.5, xanchor="center", yanchor="middle", showarrow=False, font={"size": 10, "color": "red"}, row=row, col=col, ) fig.update_xaxes(title_text="Number of Cliffords", row=row, col=col) fig.update_yaxes(title_text="Population", row=row, col=col)