# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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
# Hong Quan Trinh, hongq@student.chalmers.se
# Michele Faucci Giannelli, faucci@chalmers.se
# Tyra Cortinez Samenius, cortinez@chalmers.se
# Abdullah-Al Amin, alamina@chalmers.se
# Matteo Robbiati, robbiati@chalmers.se
# ══════════════════════════════════════════════════════════════════════════
# This code is part of Tergite
#
# (C) Copyright Eleftherios Moschandreou 2023
# (C) Copyright Michele Faucci Giannelli 2024
# (C) Copyright Stefan Hill 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/nodes/readout/resonator_spectroscopy/analysis.py
"""
Module containing classes that fit data from a resonator spectroscopy experiment.
One model is used here: :data:`~bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.model.hanger_with_delay_model`
(:func:`~bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.model.hanger_with_delay`) —
the full complex hanger response (resonance dip, amplitude tilt,
impedance-mismatch asymmetry, and cable propagation delay), fit directly
against complex IQ data. See :mod:`bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.model`.
Punchout (readout-amplitude calibration) reuses this exact same fit, one call
per amplitude slice — a punchout trace is not a different kind of resonator
sweep, so it doesn't need a different model or a special mode flag.
"""
from typing import override
import numpy as np
import plotly.graph_objects as go
from lmfit.model import ModelResult
from plotly.subplots import make_subplots
from uncertainties import ufloat
# bragi_quantum.datalayer and bragi_quantum.experiments Imports
from bragi_quantum.datalayer.utils.logging import logger
from bragi_quantum.datalayer.visualization.plot_style import (
DATA_COLOR,
DEFAULT_DENSE_GRID_POINTS,
FIT_COLOR,
PLOTLY_TEMPLATE,
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.resonator_spectroscopy.model import (
calculate_minimum_frequency,
guess_hanger_with_delay,
hanger_with_delay_model,
r_squared,
)
from bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.parameters import (
ResonatorSpectroscopyBaseQOI,
ResonatorSpectroscopyParameters,
)
[docs]
class ResonatorSpectroscopyAnalysis(Analysis):
"""
Fit the data of a resonator spectroscopy experiment.
Replaces the former ``ResonatorSpectroscopyBaseQubitAnalysis`` /
``ResonatorSpectroscopyQubitAnalysis`` (per-qubit) + ``…NodeAnalysis``
(node-level). ``ResonatorSpectroscopy1Analysis`` / ``…2Analysis`` add the
state-1/2 markers.
"""
element_kind = "qubit"
parameters: ResonatorSpectroscopyParameters
def __init__(
self,
parameters: ResonatorSpectroscopyParameters,
qoi_cls: type[BaseQoi] | None = None,
):
"""
Initializes the base resonator analysis.
Args:
parameters (ResonatorSpectroscopyParameters): The validated node parameters.
qoi_cls (Type[BaseQoi]): The QOI class used to store results.
"""
super().__init__(parameters, qoi_cls)
self.fit_result: ModelResult = None
self.s21_complex: np.ndarray = None
self.minimum_freq = 0.0
self.minimum_freq_err = 0.0
self.kappa = float("nan")
self.kappa_err = float("nan")
self.propagation_delay = float("nan")
self.propagation_delay_err = float("nan")
self.fit_y = None
# Dense frequency axis shared between fitting helpers and plotter.
self._f_dense: np.ndarray = None
# The (frequency, complex-data) region self.fit_result was actually fit
# on, so R^2 is scored against that region alone rather than the full
# sweep.
self._fit_domain_f: np.ndarray = None
self._fit_domain_s21: np.ndarray = None
[docs]
def resonator_analysis(self) -> None:
"""
Executes the fitting routine on the dataset populated by the abstract layer.
Fits the complex hanger-with-delay model directly against the raw
complex IQ data.
"""
# Coordinates and variables extracted via DataSchema contract
for coord_name in self.dataset.coords:
if "frequencies" in str(coord_name):
self.frequencies = self.dataset.coords[coord_name].values
break
# self.magnitudes/self.S21 are populated automatically by the Analysis
# base's _process. Select self.data_var explicitly rather than
# converting the whole dataset, so any extra data variables can never
# be stacked in.
self.s21_values = self.magnitudes[self.data_var].values.flatten()
# Complex raw data, same order as s21_values — this is what gets fit.
self.s21_complex = self.S21[self.data_var].values.flatten()
# Dense frequency grid used for plotting and minimum extraction.
self._f_dense = np.linspace(
self.frequencies[0], self.frequencies[-1], DEFAULT_DENSE_GRID_POINTS
)
try:
if self._is_wide_range_spectroscopy():
self._analyze_spectroscopy_in_slide_windows()
else:
self._fit_with_flexible_model()
if self.fit_result is not None and not self.fit_result.success:
logger.info("Fit was unsuccessful.")
logger.info(f"Reason: {self.fit_result.message}")
except Exception as e:
logger.error("Could not fit the resonator data")
logger.error(e)
self.fit_result = None
if self.fit_result is None or not self.fit_result.success:
logger.warning(f"Fit failed for qubit {self.qubit}.")
return
fitted_parameters = self.fit_result.params
fr_ufloat = ufloat(
fitted_parameters["fr"].value, fitted_parameters["fr"].stderr or 0.0
)
Ql_ufloat = ufloat(
fitted_parameters["Ql"].value, fitted_parameters["Ql"].stderr or 0.0
)
Qe_ufloat = ufloat(
fitted_parameters["Qe"].value, fitted_parameters["Qe"].stderr or 0.0
)
theta_ufloat = ufloat(
fitted_parameters["theta"].value,
fitted_parameters["theta"].stderr or 0.0,
)
# Closed-form minimum — see model.calculate_minimum_frequency.
min_freq_ufloat = calculate_minimum_frequency(
fr_ufloat, Ql_ufloat, Qe_ufloat, theta_ufloat
)
self.minimum_freq = min_freq_ufloat.nominal_value
self.minimum_freq_err = min_freq_ufloat.std_dev
kappa_ufloat = fr_ufloat / Ql_ufloat
self.kappa = kappa_ufloat.nominal_value
self.kappa_err = kappa_ufloat.std_dev
logger.info(
f"Analytic minimum: {self.minimum_freq:.6E} Hz "
f"(fr = {fitted_parameters['fr'].value:.6E} Hz, shift = "
f"{(self.minimum_freq - fitted_parameters['fr'].value):.2E} Hz)"
)
# Raw data minimum — the frequency bin of the resonator dip in the
# raw magnitude trace, kept for downstream consumers.
self.min_freq_data = self.frequencies[np.argmin(np.abs(self.s21_values))]
phi_v_ufloat = ufloat(
fitted_parameters["phi_v"].value,
fitted_parameters["phi_v"].stderr or 0.0,
)
prop_delay_ufloat = -phi_v_ufloat / (2 * np.pi)
self.propagation_delay = prop_delay_ufloat.nominal_value
self.propagation_delay_err = prop_delay_ufloat.std_dev
def _fit_with_flexible_model(self) -> None:
"""
Fit the complex hanger-with-delay model directly against the raw
complex IQ data, so the propagation delay and impedance mismatch are
constrained jointly by magnitude *and* phase.
"""
guess = guess_hanger_with_delay(self.s21_complex, f=self.frequencies)
self.fit_result = hanger_with_delay_model.fit(
self.s21_complex,
params=guess,
f=self.frequencies,
nan_policy="omit",
)
self._fit_domain_f = self.frequencies
self._fit_domain_s21 = self.s21_complex
# Evaluate on the dense grid for smooth plotting.
self.fit_y = hanger_with_delay_model.eval(
self.fit_result.params if self.fit_result.params else guess,
f=self._f_dense,
)
if self.fit_result.success:
logger.info("✅ Complex hanger-with-delay fit successful")
else:
logger.warning(
f"Complex hanger-with-delay fit unsuccessful: {self.fit_result.message}"
)
def _analyze_spectroscopy_in_slide_windows(self) -> None:
"""
Iterates through the data in sliding windows to find a valid resonance peak.
This path exists only because a wide sweep can contain more than one
dip-like feature, and a single fit over the whole window would land
on the wrong one — not because it's a different model or caller
(punchout amplitude slices are almost always narrow enough to take
the plain :meth:`_fit_with_flexible_model` path instead).
"""
for start in range(
0,
len(self.frequencies) - self.parameters.slide_window_size,
self.parameters.slide_window_step,
):
end = start + self.parameters.slide_window_size
guess = guess_hanger_with_delay(
self.s21_complex[start:end],
f=self.frequencies[start:end],
)
current_fit = hanger_with_delay_model.fit(
self.s21_complex[start:end],
params=guess,
f=self.frequencies[start:end],
)
if current_fit.success and current_fit.errorbars:
window_s21 = self.s21_complex[start:end]
window_fit = hanger_with_delay_model.eval(
current_fit.params, f=self.frequencies[start:end]
)
window_r_squared = r_squared(window_s21, window_fit)
if (
window_r_squared > self.parameters.min_r_squared
and current_fit.params["Ql"].value
> self.parameters.slide_window_min_ql
and current_fit.params["Qe"].value
< self.parameters.slide_window_max_qe
):
self.fit_result = current_fit
self._fit_domain_f = self.frequencies[start:end]
self._fit_domain_s21 = self.s21_complex[start:end]
self.fit_y = hanger_with_delay_model.eval(
self.fit_result.params,
f=self._f_dense,
)
logger.debug(f"Found good fit for {self.qubit}")
break
else:
logger.debug(
f"Fit not good enough for {self.qubit} in range {start}-{end}, trying next window"
)
logger.debug(f"R^2: {window_r_squared}")
logger.debug(f"Ql: {current_fit.params['Ql'].value}")
logger.debug(f"Qe: {current_fit.params['Qe'].value}")
if self.fit_result is None or not self.fit_result.success:
logger.info(f"Could not find good fit in sliding windows for {self.qubit}")
# fallback to fitting the whole data
guess = guess_hanger_with_delay(self.s21_complex, f=self.frequencies)
self.fit_result = hanger_with_delay_model.fit(
self.s21_complex, params=guess, f=self.frequencies
)
self._fit_domain_f = self.frequencies
self._fit_domain_s21 = self.s21_complex
self.fit_y = hanger_with_delay_model.eval(
self.fit_result.params,
f=self._f_dense,
)
def _is_wide_range_spectroscopy(self) -> bool:
"""Checks if the dataset requires a sliding window approach."""
return (
len(self.frequencies)
> self.parameters.sample_size_for_sliding_window_analysis
)
def _fit_r_squared(self) -> float:
"""R^2 of ``self.fit_result``, evaluated over ``self._fit_domain_*``
(whatever subset it was actually fit on — see the ``__init__`` note).
"""
fit_complex = hanger_with_delay_model.eval(
self.fit_result.params, f=self._fit_domain_f
)
return r_squared(self._fit_domain_s21, fit_complex)
[docs]
def create_qoi_object(self) -> ResonatorSpectroscopyBaseQOI:
"""Populate the specific Quantity of Interest structure."""
fitted_parameters = self.fit_result.params
return self.qoi_cls(
is_successful=True,
fitted_frequency=fitted_parameters["fr"].value,
fitted_frequency_error=fitted_parameters["fr"].stderr,
ql=fitted_parameters["Ql"].value,
ql_error=fitted_parameters["Ql"].stderr,
qe=fitted_parameters["Qe"].value,
qe_error=fitted_parameters["Qe"].stderr,
theta=fitted_parameters["theta"].value,
theta_error=fitted_parameters["theta"].stderr,
r_squared=self._fit_r_squared(),
amplitude=fitted_parameters["A"].value,
amplitude_error=fitted_parameters["A"].stderr,
minimum_frequency=self.minimum_freq,
minimum_frequency_error=self.minimum_freq_err,
kappa=self.kappa,
kappa_error=self.kappa_err,
propagation_delay=self.propagation_delay,
propagation_delay_error=self.propagation_delay_err,
)
[docs]
def is_good_fit(self, fit_result: ModelResult) -> bool:
"""Validate if the provided fit meets the quality constraints.
Gated on R^2 (:func:`~bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.model.r_squared`,
*not* lmfit's own ``rsquared`` — see that function's docstring), used
for both the final fit and the sliding-window candidate search.
Without a real per-point noise estimate (no SSRO), any chi-squared
threshold would depend on an assumed error scale that doesn't track
the real SNR, so chi-squared has no fixed meaning across
qubits/amplitudes and isn't tracked anywhere in this module.
Used uniformly by every caller — the plain resonator_spectroscopy
node and punchout call this same check. Always called with
``self.fit_result`` in practice, which is what ``_fit_r_squared``
scores against.
"""
if fit_result is None or not fit_result.success or not fit_result.errorbars:
return False
return (
self._fit_r_squared() > self.parameters.min_r_squared
and abs(fit_result.params["theta"].value) < self.parameters.max_abs_theta
)
[docs]
@override
def compute_qoi(self) -> BaseQoi:
"""Run the resonator fit and return the QOI.
Used as-is by every state (0/1/2) and every caller (plain
resonator_spectroscopy and punchout) — they all fit the same model
and gate on the same :meth:`is_good_fit`, so there's nothing left to
specialize here.
"""
self.resonator_analysis()
if self.fit_result is None or not self.is_good_fit(self.fit_result):
if self.fit_result is None:
logger.warning(
f"Qubit {self.qubit} fit result is None. Fit did not converge."
)
elif not self.fit_result.success:
logger.warning(
f"Qubit {self.qubit} fit was unsuccessful. "
f"Reason: {self.fit_result.message}"
)
else:
logger.warning(
f"Qubit {self.qubit} does not pass good fit criteria: "
f"R^2 ({self._fit_r_squared():.4f}), "
f"theta {self.fit_result.params['theta'].value}. "
f"Freq is {self.minimum_freq}. Fit may be unreliable."
)
return self.qoi_cls(is_successful=False)
return self.create_qoi_object()
[docs]
@override
def plot_title(self) -> str:
return f"Resonator |{self.parameters.readout_state}⟩ Spectroscopy for {self.element}"
[docs]
@override
def add_traces(self, fig, row: int = 1, col: int = 1) -> None:
"""Draw the fitted model (magnitude) over the raw data (plotly).
The fit curve is drawn on the dense frequency grid (_f_dense) so it
looks smooth even for narrow resonances. The black vertical line is
placed at the closed-form magnitude minimum, so it always lands
exactly on the dip regardless of background slope.
"""
data = np.abs(self.s21_values)
if self.fit_result is None:
fig.add_trace(
go.Scatter(
x=self.frequencies,
y=data,
mode="lines",
line={"color": DATA_COLOR},
showlegend=False,
),
row=row,
col=col,
)
else:
# Raw data points — sparse measurement grid.
fig.add_trace(
go.Scatter(
x=self.frequencies,
y=data,
mode="markers",
marker={"size": 3, "color": DATA_COLOR},
showlegend=False,
),
row=row,
col=col,
)
# Fitted curve on the dense grid.
fit_curve = self.fit_y
if fit_curve is None:
fit_curve = hanger_with_delay_model.eval(
self.fit_result.params, f=self._f_dense
)
fig.add_trace(
go.Scatter(
x=self._f_dense,
y=np.abs(fit_curve),
mode="lines",
line={"color": FIT_COLOR, "width": 2},
showlegend=False,
),
row=row,
col=col,
)
if self.fit_result.success and self.fit_result.errorbars:
fr = self.fit_result.params["fr"]
ql = self.fit_result.params["Ql"]
qe = self.fit_result.params["Qe"]
th = self.fit_result.params["theta"]
fig.add_vline(
x=self.minimum_freq, line={"color": "black"}, row=row, col=col
)
fig.add_vline(x=fr.value, line={"color": "blue"}, row=row, col=col)
# Per-subplot legend: each entry carries its trace colour inline.
label = (
f"<span style='color:{DATA_COLOR}'>●</span> data<br>"
f"<span style='color:{FIT_COLOR}'>▬</span> resonator fit<br>"
f"<span style='color:blue'>│</span> Fit freq = "
f"{fr.value:.6E} ± {fr.stderr:.1E} Hz<br>"
f"<span style='color:black'>│</span> Min freq = "
f"{self.minimum_freq:.6E} ± {self.minimum_freq_err:.1E} Hz<br>"
f"R² = {self._fit_r_squared():.4f}<br>"
f"Ql = {ql.value:.1f} ± {ql.stderr:.1f} | "
f"Qe = {qe.value:.1f} ± {qe.stderr:.1f}<br>"
f"Theta = {th.value:.2f} ± {th.stderr:.2f} rad<br>"
f"κ/2π = {self.kappa / 1e6:.3f} ± {self.kappa_err / 1e6:.3f} MHz<br>"
f"Prop. delay = {self.propagation_delay * 1e9:.2f} ± "
f"{self.propagation_delay_err * 1e9:.2f} ns"
)
label_box(fig, label, row=row, col=col, align="left", font_size=8)
fig.update_xaxes(title_text="Frequency (Hz)", row=row, col=col)
fig.update_yaxes(title_text="|S21|", row=row, col=col)
def _simple_fit(analysis: "ResonatorSpectroscopyAnalysis") -> BaseQoi:
"""Fit + QOI for the state-1/2 variants (no good-fit gate)."""
analysis.resonator_analysis()
if analysis.fit_result is None:
logger.warning(
f"Qubit {analysis.qubit} fit result is None. Fit did not converge."
)
return analysis.qoi_cls(is_successful=False)
if not analysis.fit_result.success:
logger.warning(
f"Qubit {analysis.qubit} fit was unsuccessful. "
f"Reason: {analysis.fit_result.message}"
)
return analysis.qoi_cls(is_successful=False)
return analysis.create_qoi_object()
[docs]
class ResonatorSpectroscopy1Analysis(ResonatorSpectroscopyAnalysis):
"""Resonator spectroscopy specialised for state 1."""
[docs]
@override
def compute_qoi(self) -> BaseQoi:
return _simple_fit(self)
[docs]
@override
def add_traces(self, fig, row: int = 1, col: int = 1) -> None:
super().add_traces(fig, row, col)
try:
ro_freq = float(self.transmon.clock_freqs.readout)
chi_01 = ro_freq - self.minimum_freq
fig.add_vline(
x=self.minimum_freq,
line={"color": "green", "dash": "dash"},
annotation_text=f"|1⟩ 2·χ01={chi_01 / 1e3:.0f} kHz",
row=row,
col=col,
)
fig.add_vline(
x=ro_freq,
line={"color": "blue", "dash": "dash"},
annotation_text="|0⟩",
row=row,
col=col,
)
except AttributeError:
pass
[docs]
class ResonatorSpectroscopy2Analysis(ResonatorSpectroscopyAnalysis):
"""Resonator spectroscopy specialised for state 2."""
[docs]
@override
def compute_qoi(self) -> BaseQoi:
return _simple_fit(self)
[docs]
@override
def add_traces(self, fig, row: int = 1, col: int = 1) -> None:
super().add_traces(fig, row, col)
try:
ro_freq = float(self.transmon.clock_freqs.readout)
ro_freq_1 = float(self.transmon.extended_clock_freqs.readout_1)
chi_01 = ro_freq - ro_freq_1
chi_12 = ro_freq_1 - self.minimum_freq
fig.add_vline(
x=self.minimum_freq,
line={"color": "red"},
annotation_text=f"|2⟩ 2·χ12={chi_12 / 1e3:.0f} kHz",
row=row,
col=col,
)
fig.add_vline(
x=ro_freq_1,
line={"color": "green", "dash": "dash"},
annotation_text=f"|1⟩ 2·χ01={chi_01 / 1e3:.0f} kHz",
row=row,
col=col,
)
fig.add_vline(
x=ro_freq,
line={"color": "blue", "dash": "dash"},
annotation_text="|0⟩",
row=row,
col=col,
)
except AttributeError:
pass