Source code for bragi_quantum.experiments.nodes.readout.punchout.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:
#
#   Matteo Robbiati, robbiati@chalmers.se
#   Hong Quan Trinh, hongq@student.chalmers.se
#   Michele Faucci Giannelli, faucci@chalmers.se
#   Axel Andersson, axean@chalmers.se
#   Joel Sandås, joel.sandas@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


# This code is part of Tergite
#
# (C) Copyright Eleftherios Moschandreou 2023
# (C) Copyright Stefan Hill 2024, 2025
# (C) Copyright Michele Faucci Giannelli 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/nodes/readout/punchout/analysis.py


"""
Module containing classes that analyse data from a punchout experiment.

For each readout pulse amplitude, the swept resonator trace is fitted with the
same ``ResonatorSpectroscopyAnalysis`` used by the plain
resonator_spectroscopy node — a punchout amplitude slice isn't a different
kind of resonator sweep, so it doesn't need special-cased fitting. Two end
point methods are supported, selected by ``PunchoutParameters.bin_mode``:

- Frequency shift (``bin_mode="average_append"``): the amplitude at which the
  fitted resonator frequency starts to shift away from its low-power value
  marks the punchout end point, and a scaled fraction of that amplitude is
  returned as the operating readout amplitude.
- Circularity (``bin_mode="append"``): the amplitude at which the single-shot
  IQ cloud at the resonator dip stops being circular (i.e. state
  discrimination starts to bias the resonator fit) marks the end point. This
  requires single-shot acquisitions (a ``shot_index`` dimension in the raw
  dataset).
"""

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 uncertainties import ufloat

from bragi_quantum.datalayer.utils.logging import logger
from bragi_quantum.datalayer.visualization.plot_style import (
    DATA_COLOR,
    FIT_COLOR,
    failure_box,
    label_box,
    style_layout,
)
from bragi_quantum.experiments.abstract.analysis import Analysis
from bragi_quantum.experiments.abstract.parameters import BaseQoi
from bragi_quantum.experiments.nodes.readout.punchout.circularity import (
    circularity_figure,
    compute_circularities,
    find_endpoint_by_circularity,
    iq_clouds_at_dip,
    point_clouds_grid_figure,
)
from bragi_quantum.experiments.nodes.readout.punchout.parameters import (
    PunchoutParameters,
)
from bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.analysis import (
    ResonatorSpectroscopyAnalysis,
)
from bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.parameters import (
    ResonatorSpectroscopyParameters,
    ResonatorSpectroscopyQOI,
)


[docs] class PunchoutAnalysis(Analysis): """Determine the operating readout amplitude for a qubit (unified, plotly). Replaces the former ``PunchoutQubitAnalysis`` + ``PunchoutNodeAnalysis``. For each readout amplitude the resonator trace is fitted (reusing ``ResonatorSpectroscopyAnalysis`` verbatim, one call per amplitude slice). Which end point method then runs — :meth:`_find_endpoint_frequency_shift` or :meth:`_find_endpoint_circularity` — is driven by ``self.parameters.bin_mode``, the same way ``self.parameters.readout_state`` drives which clock the measurement targets. """ element_kind = "qubit" parameters: PunchoutParameters def __init__(self, parameters, qoi_cls=None, **kwargs): super().__init__(parameters, qoi_cls, **kwargs) self.amplitude_coord = None self.frequency_coord = None self.amplitudes = None self.frequencies = None self.norm_magnitudes = None self.end_point_frequency = None self.end_point_amplitude = None self.best_amplitude = None self.detected_frequencies: list = [] self.detected_amplitudes: list = [] self.resonator_spectroscopy_analyses: list = [] self.end_point_index = None self.analysis_successful = False # Only populated for bin_mode="append" (circularity end point). self._raw_dataset: xr.Dataset | None = None self._iq_clouds: list[np.ndarray | None] = [] self.circularities: list[float] = []
[docs] @override def plot_title(self) -> str: return f"Punchout |{self.parameters.readout_state}⟩ for {self.element}"
@override def _process(self, dataset, element: str) -> BaseQoi: """Average over the shot dimension before the base class computes S21/magnitudes, so the rest of the analysis sees the same 2-D (amplitude x frequency) shape either way. The un-averaged dataset is kept for the circularity end point, which needs individual shots; an averaged acquisition has no shot dimension, so this is a no-op. """ shot_coord = next((c for c in dataset.coords if "shot" in str(c)), None) if shot_coord is not None: self._raw_dataset = dataset dataset = dataset.mean(dim=shot_coord) return super()._process(dataset, element)
[docs] @override def compute_qoi(self) -> BaseQoi: for coord in self.dataset[self.data_var].coords: coord_str = str(coord) if "amplitudes" in coord_str: self.amplitude_coord = coord elif "frequencies" in coord_str: self.frequency_coord = coord self.amplitudes = self.dataset.coords[self.amplitude_coord].values self.frequencies = self.dataset.coords[self.frequency_coord].values # Normalise each amplitude trace by its peak over frequency, so the # colour map is comparable across readout powers. mag_da = self.magnitudes[self.data_var] self.norm_magnitudes = mag_da / mag_da.max(dim=self.frequency_coord) for amplitude in self.amplitudes: dataset = self.dataset.sel({self.amplitude_coord: amplitude}) res_analysis = ResonatorSpectroscopyAnalysis( ResonatorSpectroscopyParameters( qubits=[self.qubit], min_r_squared=self.parameters.min_r_squared, max_abs_theta=self.parameters.max_abs_theta, ), ResonatorSpectroscopyQOI, ) # `dataset` is already reduced to this amplitude + qubit, so fit it # verbatim (process_qubit) rather than re-slicing with analyse_element. qoi = res_analysis.process_qubit(dataset, self.qubit) self.resonator_spectroscopy_analyses.append(res_analysis) self.detected_amplitudes.append(amplitude) self.detected_frequencies.append( ufloat(qoi.minimum_frequency, qoi.minimum_frequency_error or 0.0) if qoi.is_successful else ufloat(np.nan, 0.0) ) match self.parameters.bin_mode: case "average_append": self._find_endpoint_frequency_shift() case "append": self._find_endpoint_circularity() case _: raise NotImplementedError(f"{self.parameters.bin_mode=}") self.analysis_successful = self.end_point_index is not None if self.analysis_successful: return self.qoi_cls(is_successful=True, pulse_amp=self.best_amplitude) logger.error( f"Punchout analysis for qubit {self.qubit} failed: could not determine " "end point amplitude." ) self.best_amplitude = None return self.qoi_cls(is_successful=False)
def _find_endpoint_frequency_shift(self) -> None: """End point = last amplitude before the fitted resonator frequency shifts away from its running value by more than the configured thresholds (``bin_mode="average_append"``).""" for i, amplitude in enumerate(self.detected_amplitudes): resonator_frequency = self.detected_frequencies[i] if np.isnan(resonator_frequency.nominal_value): continue if self.end_point_index is None: self.end_point_frequency = resonator_frequency self.end_point_amplitude = amplitude self.end_point_index = i continue if ( i - self.end_point_index > self.parameters.max_consecutive_missing_points ): logger.info( f"Punchout analysis for qubit {self.qubit}: " f"too many consecutive missing points at amplitude {amplitude:0.4f} fullscale." ) break # Too many missing points; resonator shape probably strange if ( self.end_point_frequency - resonator_frequency ) > self.parameters.lower_threshold or ( resonator_frequency - self.end_point_frequency ) > self.parameters.upper_threshold: logger.info( f"Punchout analysis for qubit {self.qubit}: " f"frequency shift detected at amplitude {amplitude:0.4f} fullscale. " f"Previous frequency: {self.end_point_frequency:0.2f} Hz, " f"current frequency: {resonator_frequency:0.2f} Hz." ) break # Frequency shift detected — use last amplitude self.end_point_amplitude = amplitude self.end_point_frequency = resonator_frequency self.end_point_index = i if self.end_point_index is not None: self.best_amplitude = max( self.parameters.amplitude_scale_factor * self.end_point_amplitude, self.amplitudes[0], ) def _find_endpoint_circularity(self) -> None: """End point = highest amplitude whose single-shot IQ cloud at the resonator dip is still circular (``bin_mode="append"``). That amplitude is the operating point as-is: unlike the frequency-shift end point there is no scale factor, since the last circular amplitude is already the most power the readout takes while staying linear.""" if self._raw_dataset is None: logger.error( f"Punchout analysis for qubit {self.qubit}: no single-shot " "data available; circularity-based amplitude selection requires " "shots (a 'shot_index' dimension in the dataset)." ) return self._iq_clouds = iq_clouds_at_dip( self._raw_dataset, self.data_var, self.amplitude_coord, self.frequency_coord, self.detected_amplitudes, self.resonator_spectroscopy_analyses, ) self.circularities = compute_circularities(self._iq_clouds) self.end_point_index, self.end_point_amplitude, self.end_point_frequency = ( find_endpoint_by_circularity( self.detected_amplitudes, self.detected_frequencies, self.circularities, self.parameters.circularity_threshold, self.qubit, ) ) self.best_amplitude = self.end_point_amplitude
[docs] @override def add_traces(self, fig, row: int = 1, col: int = 1) -> None: """2-D colour map of normalized |S21| vs (readout amplitude, frequency), with the fitted resonator frequencies and selected operating point.""" legend = row == 1 and col == 1 z = self.norm_magnitudes if self.frequency_coord in z.dims and self.amplitude_coord in z.dims: z = z.transpose(self.frequency_coord, self.amplitude_coord) fig.add_trace( go.Heatmap( z=z.values, x=self.amplitudes, y=self.frequencies, colorscale="Viridis", colorbar={"title": "Norm |S21|"}, showscale=legend, ), row=row, col=col, ) fa, ff, ferr = [], [], [] for i, freq in enumerate(self.detected_frequencies): if not np.isnan(freq.nominal_value): fa.append(self.detected_amplitudes[i]) ff.append(freq.nominal_value) ferr.append(freq.std_dev) fig.add_trace( go.Scatter( x=fa, y=ff, mode="markers", marker={"color": DATA_COLOR, "size": 7}, name="fitted resonator freq.", legendgroup="fit", showlegend=legend, error_y={"type": "data", "array": ferr, "visible": True}, ), row=row, col=col, ) if self.analysis_successful: fig.add_vline( x=self.best_amplitude, line={"color": FIT_COLOR}, row=row, col=col ) fig.add_trace( go.Scatter( x=[self.end_point_amplitude], y=[self.end_point_frequency.nominal_value], mode="markers", marker={ "color": FIT_COLOR, "symbol": "x", "size": 12, "line": {"color": "black", "width": 1.5}, }, name="punchout endpoint", legendgroup="endpoint", showlegend=legend, ), row=row, col=col, ) label_box( fig, f"RO amp = {self.best_amplitude:0.3f} fullscale", row=row, col=col, x=0.02, y=0.98, xanchor="left", yanchor="top", align="left", ) fig.update_xaxes( title_text="Readout pulse amplitude [fullscale]", row=row, col=col ) fig.update_yaxes(title_text="Resonator frequency [Hz]", row=row, col=col)
[docs] @override def list_plots(self) -> list[str]: plots = ["main", "spectroscopies"] if self.parameters.bin_mode == "append": plots += ["circularity", "point_clouds"] return plots
@override def _render_figure(self, fig, plot_name: str) -> None: """``"main"`` uses the default 1×1 heatmap path; every other listed plot name is built standalone and merged (traces + layout) into ``fig`` instead — see :meth:`list_plots` for which are available.""" if plot_name == "main": super()._render_figure(fig, plot_name) return builder = { "spectroscopies": self._spectroscopies_figure, "circularity": self._circularity_figure, "point_clouds": self._point_clouds_figure, }.get(plot_name) if builder is None: raise ValueError(f"Unknown plot {plot_name!r} for {type(self).__name__}") src = builder() for trace in src.data: fig.add_trace(trace) fig.update_layout(src.to_dict().get("layout", {})) def _spectroscopies_figure(self): """One figure tiling every per-amplitude resonator fit; the punchout end-point amplitude is marked in its subplot title and outlined in green. Built on demand (see :meth:`list_plots`) rather than on every analysis run — with many amplitudes this is a lot of subplots to render for a diagnostic that's rarely needed.""" analyses = self.resonator_spectroscopy_analyses if not analyses: fig = go.Figure() failure_box(fig, "No per-amplitude resonator fits available.") return fig ncols = 4 nrows = int(np.ceil(len(analyses) / ncols)) titles = [] for i, amplitude in enumerate(self.detected_amplitudes): title = f"{amplitude:.3f} fullscale" if i == self.end_point_index: title = f"★ {title} (endpoint)" titles.append(title) fig = make_subplots( rows=nrows, cols=ncols, subplot_titles=titles, horizontal_spacing=0.04, vertical_spacing=max(0.05, 0.14 / nrows), ) for i, ana in enumerate(analyses): row, col = i // ncols + 1, i % ncols + 1 ana.add_traces(fig, row=row, col=col) if i == self.end_point_index: fig.add_shape( type="rect", xref="x domain", yref="y domain", x0=0, x1=1, y0=0, y1=1, row=row, col=col, line={"color": "green", "width": 3}, ) style_layout( fig, width=ncols * 360, height=nrows * 300 + 80, title=f"{self.parameters.name} — {self.qubit}", ) return fig def _circularity_figure(self): """Standalone circularity-vs-amplitude chart (``bin_mode="append"`` only) — see :meth:`circularity.circularity_figure`.""" fig = circularity_figure( self.detected_amplitudes, self.circularities, self.parameters.circularity_threshold, self.end_point_index, ) if fig is not None: return fig fig = go.Figure() failure_box(fig, "No circularity data available for this element.") return fig def _point_clouds_figure(self): """Per-amplitude single-shot IQ point clouds (``bin_mode="append"`` only) — see :meth:`circularity.point_clouds_grid_figure`.""" fig = point_clouds_grid_figure( self._iq_clouds, self.detected_amplitudes, self.end_point_index ) if fig is not None: return fig fig = go.Figure() failure_box(fig, "No single-shot IQ clouds available for this element.") return fig