Source code for bragi_quantum.experiments.nodes.qubit_control.spectroscopy.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
#   Axel Andersson, axean@chalmers.se
#   Yanchen Lin, linya@chalmers.se
#   Michele Faucci Giannelli, faucci@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


"""
Module containing classes that fit and plot data from a qubit (two-tone)
spectroscopy experiment.

For each spectroscopy pulse amplitude, a Lorentzian + constant baseline is
fitted to the 1-D frequency trace.  The amplitude whose fitted peak_height is
largest (i.e. the tallest peak above the baseline) is selected as the optimal
operating point, and the Lorentzian center frequency is returned as the qubit
frequency.
"""

from dataclasses import dataclass
from typing import override

import numpy as np
import plotly.graph_objects as go
from lmfit.model import ModelResult
from lmfit.models import ConstantModel, LorentzianModel
from plotly.subplots import make_subplots

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.qubit_control.spectroscopy.parameters import (
    QubitSpectroscopyBaseQOI,
    QubitSpectroscopyParameters,
)


[docs] @dataclass class PeakFitResult: """Bundle the outcome of a single-trace Lorentzian peak fit. ``lorentzian_fitted_frequency``/``lorentzian_fitted_frequency_stderr`` are ``None`` when no peak was accepted; ``fit_result`` is the raw lmfit ``ModelResult`` kept for slice diagnostics. ``amplitude``/``raw_maximum`` are filled in by the caller for 2-D sweeps, where each slice corresponds to one spectroscopy pulse amplitude. """ lorentzian_fitted_frequency: float | None = None lorentzian_fitted_frequency_stderr: float | None = None significance: float = 0.0 fit_result: ModelResult | None = None amplitude: float | None = None raw_maximum: float | None = None
[docs] class QubitSpectroscopyAnalysis(Analysis): """ Fit data from a qubit (two-tone) spectroscopy experiment (unified, plotly). Iterates over the amplitude sweep axis, applies a significance-threshold peak-finder on each 1-D frequency trace, and picks the amplitude whose trace carries the highest significance as the calibrated operating point. A single class handles both the 0→1 and 1→2 transitions, selected by ``parameters.transition``. Replaces the former ``QubitSpectroscopyQubitAnalysis`` / ``QubitSpectroscopy12QubitAnalysis`` + ``QubitSpectroscopyNodeAnalysis``. """ element_kind = "qubit" parameters: QubitSpectroscopyParameters def __init__( self, parameters: QubitSpectroscopyParameters, qoi_cls: "type[QubitSpectroscopyBaseQOI] | None" = None, **kwargs, ): super().__init__(parameters, qoi_cls, **kwargs) self.frequencies = None self.amplitudes = None self.frequency_coord = None self.amplitude_coord = None self.qubit_freq: float = float("nan") self.qubit_freq_error: float = float("inf") self.spec_ampl: float = float("nan") self.slice_results: list[PeakFitResult] = []
[docs] @override def plot_title(self) -> str: return f"Qubit {self.parameters.transition} Spectroscopy for {self.element}"
# ------------------------------------------------------------------ # Coordinate extraction # ------------------------------------------------------------------ def _extract_coordinates(self) -> None: for coord in self.dataset[self.data_var].coords: coord_str = str(coord) if "frequencies" in coord_str: self.frequency_coord = coord self.frequencies = self.dataset.coords[coord].values elif "amplitudes" in coord_str: self.amplitude_coord = coord self.amplitudes = self.dataset.coords[coord].values # ------------------------------------------------------------------ # Peak-finding # ------------------------------------------------------------------ def _find_peak(self, magnitudes_1d: np.ndarray) -> PeakFitResult: """ Fit a Lorentzian + constant baseline to the 1-D magnitude trace. Return a ``PeakFitResult`` with ``lorentzian_fitted_frequency=None`` when the fit fails or the peak is rejected by any validation criterion: - peak_height > 1.5 * data_range: physically impossible (fit diverged). - |corr(amplitude, sigma)| >= 0.99: degenerate fit, peak shape unconstrained. - significance < threshold: peak too weak relative to noise. """ ydata = magnitudes_1d.flatten() xdata = self.frequencies data_range = float(ydata.max() - ydata.min()) lorentz = LorentzianModel(prefix="peak_") const = ConstantModel(prefix="bkg_") model = lorentz + const params = lorentz.guess(ydata, x=xdata) + const.guess(ydata, x=xdata) try: fit_result = model.fit(ydata, params, x=xdata, nan_policy="omit") except Exception: return PeakFitResult() if not fit_result.success: return PeakFitResult() peak_height = float(fit_result.params["peak_height"].value) # Reject fits where the Lorentzian height exceeds the actual data range — # this catches diverged fits where lmfit found a spurious solution. if peak_height > data_range * 1.5: return PeakFitResult() # Reject degenerate fits where amplitude and sigma are perfectly correlated # (the peak shape is unconstrained — tergite's criterion 3). cov = fit_result.covar if cov is not None: param_names = list(fit_result.params.keys()) ii = param_names.index("peak_amplitude") jj = param_names.index("peak_sigma") try: corr = abs(cov[ii, jj] / (np.sqrt(cov[ii, ii]) * np.sqrt(cov[jj, jj]))) if corr >= 0.99: return PeakFitResult() except (ValueError, ZeroDivisionError): pass lorentzian_fitted_frequency = fit_result.params["peak_center"].value sigma = fit_result.params["peak_sigma"].value mask = (xdata < lorentzian_fitted_frequency - 3 * sigma) | ( xdata > lorentzian_fitted_frequency + 3 * sigma ) off_peak = ydata[mask] if mask.any() else ydata baseline_std = float(np.std(off_peak)) if len(off_peak) > 1 else 1.0 significance = peak_height / baseline_std if baseline_std > 0 else 0.0 # Reject fits where significance is too low to trust as a real peak, return significance for diagnostics. if significance < self.parameters.significance_threshold: return PeakFitResult(significance=significance) # Accepted: frequency/error/fit_result all carry through for downstream use. lorentzian_fitted_frequency_stderr = float( fit_result.params["peak_center"].stderr or 0.0 ) return PeakFitResult( float(lorentzian_fitted_frequency), lorentzian_fitted_frequency_stderr, significance, fit_result, ) # ------------------------------------------------------------------ # Main analysis orchestrator (mirrors resonator_analysis) # ------------------------------------------------------------------
[docs] def qubit_spectroscopy_analysis(self) -> None: """ Executes the peak-finding routine on the dataset populated by the abstract layer. Supports both a 2-D sweep (frequency × amplitude) and a 1-D sweep (frequency only). """ self._extract_coordinates() self.slice_results = [] if self.amplitudes is not None and len(self.amplitudes) > 0: # 2-D case: iterate over amplitude slices for amp in self.amplitudes: mag_at_amp = self.magnitudes.sel({self.amplitude_coord: amp}) mag_1d = mag_at_amp[self.data_var].values.flatten() peak = self._find_peak(mag_1d) peak.amplitude = float(amp) peak.raw_maximum = float(np.max(mag_1d)) self.slice_results.append(peak) accepted = [ peak for peak in self.slice_results if peak.lorentzian_fitted_frequency is not None ] if accepted: # Pick the amplitude whose raw maximum is highest — this puts # the marker on the most yellow cell in the colorplot. best_peak = max(accepted, key=lambda peak: peak.raw_maximum) self.qubit_freq = best_peak.lorentzian_fitted_frequency self.qubit_freq_error = best_peak.lorentzian_fitted_frequency_stderr self.spec_ampl = best_peak.amplitude else: # 1-D case: single amplitude trace mag_1d = self.magnitudes.to_dataarray().values.flatten() peak = self._find_peak(mag_1d) if peak.lorentzian_fitted_frequency is not None: self.qubit_freq = peak.lorentzian_fitted_frequency self.qubit_freq_error = peak.lorentzian_fitted_frequency_stderr if np.isnan(self.qubit_freq): logger.warning( f"No peak above significance threshold found for {self.qubit}." )
[docs] def create_qoi_object(self) -> QubitSpectroscopyBaseQOI: return self.qoi_cls( is_successful=True, frequency=self.qubit_freq, frequency_error=self.qubit_freq_error, amplitude=self.spec_ampl, significance=( float(max(peak.significance for peak in self.slice_results)) if self.slice_results else 0.0 ), )
[docs] @override def compute_qoi(self) -> BaseQoi: self.qubit_spectroscopy_analysis() if np.isnan(self.qubit_freq): transition_label = "1→2 " if self.parameters.transition == "12" else "" logger.warning( f"Qubit {self.qubit}: no valid {transition_label}peak found. " "Marking as unsuccessful." ) return self.qoi_cls(is_successful=False) return self.create_qoi_object()
[docs] @override def add_traces(self, fig, row: int = 1, col: int = 1) -> None: legend = row == 1 and col == 1 if self.amplitudes is not None and len(self.amplitudes) > 0: # 2-D colour map: amplitude on Y, frequency on X mag_da = self.magnitudes[self.data_var] if ( self.frequency_coord in mag_da.dims and self.amplitude_coord in mag_da.dims ): mag_da = mag_da.transpose(self.amplitude_coord, self.frequency_coord) fig.add_trace( go.Heatmap( z=mag_da.values, x=self.frequencies, y=self.amplitudes, colorscale="Viridis", colorbar={"title": "|S21|"}, showscale=legend, ), row=row, col=col, ) if not np.isnan(self.qubit_freq): fig.add_trace( go.Scatter( x=[self.qubit_freq], y=[self.spec_ampl], mode="markers", marker={ "color": FIT_COLOR, "size": 10, "symbol": "x", "line": {"color": "black", "width": 1}, }, showlegend=False, ), row=row, col=col, ) label_box( fig, f"f = {self.qubit_freq * 1e-9:.4f} GHz<br>amp = {self.spec_ampl:.3f}", row=row, col=col, x=0.02, y=0.98, xanchor="left", yanchor="top", align="left", ) fig.update_yaxes(title_text="Spec. pulse amplitude", row=row, col=col) else: # 1-D trace mag_1d = self.magnitudes.to_dataarray().values.flatten() fig.add_trace( go.Scatter( x=self.frequencies, y=mag_1d, mode="lines+markers", marker={"size": 3, "color": DATA_COLOR}, line={"color": DATA_COLOR, "width": 1}, showlegend=False, ), row=row, col=col, ) if not np.isnan(self.qubit_freq): fig.add_vline( x=self.qubit_freq, line={"color": FIT_COLOR, "dash": "dash"}, row=row, col=col, ) label_box( fig, f"f = {self.qubit_freq * 1e-9:.4f} GHz", row=row, col=col, x=0.97, y=0.97, xanchor="right", yanchor="top", ) fig.update_yaxes(title_text="|S21|", row=row, col=col) if self.parameters.transition == "12": # Overlay the reference 01 frequency if available try: f01 = float(self.transmon.clock_freqs.f01) fig.add_vline( x=f01, line={"color": "blue", "dash": "dash"}, row=row, col=col ) except AttributeError: pass fig.update_xaxes(title_text="Frequency (Hz)", row=row, col=col)
[docs] @override def list_plots(self) -> "list[str]": return ["main", "slices"]
@override def _render_figure(self, fig: "go.Figure", plot_name: str) -> None: """Dispatch "main" to the default 1x1 path; "slices" merges :meth:`_slices_figure`'s traces/layout into ``fig`` instead.""" if plot_name == "main": super()._render_figure(fig, plot_name) return if plot_name != "slices": raise ValueError(f"Unknown plot '{plot_name}' for {type(self).__name__}") src = self._slices_figure() 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 per-amplitude slices grid, saved to disk. Only produced for the 2-D (frequency x amplitude) sweep — the 1-D case has nothing beyond what the main plot already shows. """ if self.amplitudes is None or len(self.amplitudes) == 0: return [] return [ (self._slices_figure(), f"{self.parameters.name}_{self.qubit}_slices.png") ]
def _slices_figure(self) -> "go.Figure": """Grid figure tiling every amplitude slice's raw trace and fit, with a gold box on the slice picked as the operating point — the same figure ``support_figures()`` saves to disk, also exposed as the interactive "slices" plot in bragi_quantum.gui.""" if self.amplitudes is None or len(self.amplitudes) == 0: fig = go.Figure() failure_box(fig, "No amplitude sweep in this dataset.") return fig n_amplitudes = len(self.amplitudes) ncols = min(int(np.ceil(np.sqrt(n_amplitudes))), 6) nrows = int(np.ceil(n_amplitudes / ncols)) titles = [f"amp = {amp:.3f}" for amp in self.amplitudes] fig = make_subplots( rows=nrows, cols=ncols, subplot_titles=titles, horizontal_spacing=max(0.02, 0.1 / ncols), vertical_spacing=max(0.05, 0.14 / nrows), ) for i, amp in enumerate(self.amplitudes): row, col = i // ncols + 1, i % ncols + 1 mag_1d = self.magnitudes.sel({self.amplitude_coord: amp})[ self.data_var ].values.flatten() fig.add_trace( go.Scatter( x=self.frequencies, y=mag_1d, mode="markers", marker={"size": 3, "color": DATA_COLOR}, showlegend=False, ), row=row, col=col, ) fit_result = self.slice_results[i].fit_result if fit_result is not None: fig.add_trace( go.Scatter( x=self.frequencies, y=fit_result.best_fit, mode="lines", line={"color": FIT_COLOR, "width": 1.5}, showlegend=False, ), row=row, col=col, ) fig.add_vline( x=fit_result.params["peak_center"].value, line={"color": FIT_COLOR, "dash": "dash"}, row=row, col=col, ) if not np.isnan(self.spec_ampl): best_idx = int( np.argmin(np.abs(np.asarray(self.amplitudes) - self.spec_ampl)) ) row, col = best_idx // ncols + 1, best_idx % ncols + 1 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": "gold", "width": 3}, ) style_layout( fig, width=ncols * 320, height=nrows * 300 + 80, title=f"{self.plot_title()} — per-amplitude slices", ) return fig