# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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
# Adrián Navarro Fuentes, adrianfu@chalmers.se
# Michele Faucci Giannelli, faucci@chalmers.se
# ══════════════════════════════════════════════════════════════════════════
"""
Module containing classes that fit and plot data from a Ramsey-fringes
experiment.
For each artificial detuning a damped sinusoid is fitted to the delay trace to
extract its Ramsey frequency; a linear fit of fitted-vs-artificial detuning then
gives the frequency correction (its zero crossing).
"""
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 bragi_quantum.datalayer.managing.session import ActiveSession
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.fitting_tools.models.linear import (
FoldedLinearFitModel,
LinearFitModel,
)
from bragi_quantum.experiments.fitting_tools.models.ramsey import RamseyModel
from bragi_quantum.experiments.nodes.qubit_control.ramsey_fringes.parameters import (
RamseyBaseQOI,
RamseyParameters,
)
# The second pulse (Y90 / Rxy(theta=90, phi=90)) is rotated 90 deg from the
# first, so the population response is cos(2*pi*detuning*t + phase) with
# phase pinned near a fixed +-pi/2, independent of detuning's sign. Starting
# at the equator, the trace then moves down for positive detuning and up for
# negative detuning — RamseyModel.guess() reads this off the data directly
# (comparing the first two points, relative to this pinned phase) to seed
# frequency with the correct sign, and this phase pin keeps the fit from
# drifting onto the wrong-sign branch afterwards. Flip to -np.pi / 2 here if
# the very first real run with this sequence comes out with
# frequency_correction of the wrong sign — RamseyModel.guess() derives its
# up/down sign convention from this value directly, so nothing else needs to
# change to match.
_PHASE_GUESS = np.pi / 2
_PHASE_BOUND_HALFWIDTH = np.pi / 2
[docs]
class RamseyDetuningsAnalysis(Analysis):
"""Extract the frequency correction for one qubit (unified, plotly).
For each artificial detuning a damped sinusoid is fitted to the delay
trace to extract its Ramsey frequency; a linear fit of fitted-vs-artificial
detuning then gives the frequency correction (its zero crossing). Replaces
the former ``RamseyDetuningsQubitAnalysis`` + ``RamseyDetuningsNodeAnalysis``.
"""
element_kind = "qubit"
parameters: RamseyParameters
def __init__(
self,
parameters: RamseyParameters,
qoi_cls: "type[RamseyBaseQOI] | None" = None,
**kwargs,
):
super().__init__(parameters, qoi_cls, **kwargs)
self.analysis_successful = False
self.qubit_frequency = None
self.qubit_frequency_error = None
self.delay_coord = None
self.detuning_coord = None
self.ramsey_delays = None
self.artificial_detunings = None
self.all_artificial_detunings = None
self.fitted_detunings = None
self.fitted_detunings_error = None
self.raw_fitted_detunings = None
self.kept_mask = None
self.frequency_correction = None
self.frequency_correction_error = None
self.corrected_qubit_frequency = None
self.reduced_chi2 = None
self.r_squared = None
self.indexes_to_remove = []
self.r2_values = []
self.linear_fit_result: ModelResult = None
self.detuning_fit_results: list[ModelResult] = []
def _previous_frequency(self) -> float:
"""
Fetch the current transition frequency for this qubit from the device.
``transition="01"`` -> ``clock_freqs.f01``, ``transition="12"`` ->
``clock_freqs.f12``. Returns 0.0 when no active session/device is
available; the reported correction is independent of this value.
"""
try:
transmon = ActiveSession.get().device.elements[self.qubit]
if self.parameters.transition == "01":
return float(transmon.clock_freqs.f01)
return float(transmon.clock_freqs.f12)
except Exception:
return 0.0
[docs]
@override
def plot_title(self) -> str:
return f"Ramsey Correction for {self.element}"
[docs]
@override
def compute_qoi(self) -> BaseQoi:
for coord in self.dataset[self.data_var].coords:
coord_str = str(coord)
if "delay" in coord_str:
self.delay_coord = coord
self.ramsey_delays = self.dataset.coords[coord].values
elif "detuning" in coord_str:
self.detuning_coord = coord
self.artificial_detunings = self.dataset.coords[coord].values
self.qubit_frequency = self._previous_frequency()
self.qubit_frequency_error = 0.0
self.all_artificial_detunings = np.array(self.artificial_detunings)
# `analysis_sequence` (reanalysis-time, live-overridable in bragi_quantum.gui)
# takes precedence over `sequence` (recorded at acquisition time);
# `sequence`'s own default ("x90_x90") covers datasets recorded before
# either field existed, since that was the only sequence ever run then.
effective_sequence = (
self.parameters.analysis_sequence or self.parameters.sequence
)
model = RamseyModel()
fitted_detunings = []
fitted_detunings_error = []
raw_fitted_detunings = []
if effective_sequence == "x90_y90":
# For cos(2*pi*f*t + _PHASE_GUESS), the slope at t=0 is
# -2*pi*f*sin(_PHASE_GUESS) — so the sign of each trace's very
# first step (relative to _PHASE_GUESS) reveals the true sign of
# its beat frequency directly from the data, as long as
# sin(_PHASE_GUESS) is bounded away from zero (phase pinned near
# an odd multiple of pi/2, i.e. the oscillation starts at the
# model's offset/"equator" and visibly moves up or down — true for
# this X90-Y90 sequence). This is kept local to this node's
# analysis rather than in RamseyModel itself, since it's specific
# to this circuit's phase convention, not something every
# Ramsey-like circuit shares.
sin_phase_guess = np.sin(_PHASE_GUESS)
derive_sign_from_slope = abs(sin_phase_guess) > 0.5
else:
# x90_x90: the population response is an even cos(2*pi*f*t), so a
# single trace can never recover the sign at all (unlike x90_y90
# above) — bound frequency >=0 instead of trying to, same as
# before X90-Y90 existed. The outer fit below is a folded/V-shaped
# model to match, rather than a plain line.
model.set_param_hint("frequency", min=0)
for indx, detuning in enumerate(
self.dataset.coords[self.detuning_coord].values
):
magnitudes = (
self.magnitudes[self.data_var].isel({self.detuning_coord: indx}).values
)
if effective_sequence == "x90_y90":
# In the well-calibrated case the fitted beat frequency's
# magnitude should match the applied artificial detuning, so
# seed the fit with it rather than relying on the FFT peak —
# this is more reliable than the FFT guess for noisy/decaying
# traces. Its sign, when derivable (see derive_sign_from_slope
# above), comes from this trace's own initial slope instead of
# from `detuning`; _PHASE_GUESS/_PHASE_BOUND_HALFWIDTH then
# keep the fit from drifting onto the wrong-sign (degenerate
# mirror) branch afterwards. If the sign isn't derivable this
# way (e.g. _PHASE_GUESS were ever changed to something near a
# multiple of pi), fall back to seeding with `detuning`'s own
# sign unmodified.
if derive_sign_from_slope:
slope_sign = 1.0 if magnitudes[1] > magnitudes[0] else -1.0
freq_sign = -slope_sign * np.sign(sin_phase_guess)
freq_guess = freq_sign * abs(detuning)
else:
freq_guess = detuning
guess = model.guess(
magnitudes,
t=self.ramsey_delays,
freq_guess=freq_guess,
phase_guess=_PHASE_GUESS,
phase_bound_halfwidth=_PHASE_BOUND_HALFWIDTH,
)
else:
# No phase pinning here: frequency's own >=0 bound (set
# above) is what makes the fit well-posed, and phase is left
# to the generic FFT-based guess.
guess = model.guess(
magnitudes, t=self.ramsey_delays, freq_guess=abs(detuning)
)
fit_result = model.fit(magnitudes, params=guess, t=self.ramsey_delays)
self.detuning_fit_results.append(fit_result)
self.r2_values.append(fit_result.rsquared)
fitted_detuning = fit_result.params["frequency"].value
fitted_detuning_error = fit_result.params["frequency"].stderr
raw_fitted_detunings.append(fitted_detuning)
# Points are averaged, so chi2 is not meaningful; use r-squared.
if (
fitted_detuning_error is None
or fit_result.rsquared < self.parameters.min_r_squared_detune_fit
):
self.indexes_to_remove.append(indx)
continue
rel_error = fitted_detuning_error / abs(fitted_detuning)
if rel_error < self.parameters.minimum_relative_error_from_fits:
fitted_detuning_error = (
abs(fitted_detuning)
* self.parameters.minimum_relative_error_from_fits
)
fitted_detunings.append(fitted_detuning)
fitted_detunings_error.append(fitted_detuning_error)
self.raw_fitted_detunings = np.array(raw_fitted_detunings)
self.kept_mask = np.ones(len(raw_fitted_detunings), dtype=bool)
self.kept_mask[self.indexes_to_remove] = False
for indx in sorted(self.indexes_to_remove, reverse=True):
self.artificial_detunings = np.delete(self.artificial_detunings, indx)
if len(fitted_detunings) < 2:
self.analysis_successful = False
return self.qoi_cls(
is_successful=False,
frequency=self.qubit_frequency,
frequency_error=self.qubit_frequency_error,
)
# For x90_y90, each per-detuning fit already converged on the
# correctly-signed frequency (sign read from the trace's initial
# slope, phase pinned near _PHASE_GUESS to keep it there — see the fit
# loop above), so the fitted detunings need no further sign
# correction here. For x90_x90, these are magnitudes only (frequency
# bounded >=0 above) — the folded/V-shaped outer model below expects
# exactly that, rather than a signed fitted-vs-artificial relationship.
self.fitted_detunings = np.array(fitted_detunings)
self.fitted_detunings_error = np.array(fitted_detunings_error)
outer_model = (
LinearFitModel()
if effective_sequence == "x90_y90"
else FoldedLinearFitModel()
)
params = outer_model.guess(self.fitted_detunings, x=self.artificial_detunings)
self.linear_fit_result = outer_model.fit(
self.fitted_detunings,
params,
x=self.artificial_detunings,
weights=1.0 / self.fitted_detunings_error,
)
m = self.linear_fit_result.params["slope"].value
b = self.linear_fit_result.params["intercept"].value
stderr = np.array(
[
self.linear_fit_result.params["slope"].stderr,
self.linear_fit_result.params["intercept"].stderr,
]
)
self.reduced_chi2 = self.linear_fit_result.redchi
self.r_squared = self.linear_fit_result.rsquared
self.analysis_successful = (
self.r_squared > self.parameters.min_r_squared_line_fit
)
if self.analysis_successful:
self.frequency_correction = -b / m
self.frequency_correction_error = abs(b / m) * np.sqrt(
(stderr[1] / b) ** 2 + (stderr[0] / m) ** 2
)
self.corrected_qubit_frequency = (
self.qubit_frequency + self.frequency_correction
)
self.qubit_frequency_error = self.frequency_correction_error
return self.qoi_cls(
is_successful=True,
frequency=self.corrected_qubit_frequency,
frequency_error=self.frequency_correction_error,
chi2=self.reduced_chi2,
r_squared=self.r_squared,
)
return self.qoi_cls(
is_successful=False,
frequency=self.qubit_frequency,
frequency_error=self.qubit_frequency_error,
chi2=self.reduced_chi2,
r_squared=self.r_squared,
)
def _plot_excluded_points(self, fig, row: int, col: int) -> None:
"""Overlay detunings dropped by the per-detuning R^2 gate, for context."""
if self.kept_mask is None or self.kept_mask.all():
return
excluded = ~self.kept_mask
fig.add_trace(
go.Scatter(
x=self.all_artificial_detunings[excluded],
y=self.raw_fitted_detunings[excluded],
mode="markers",
marker={"symbol": "x", "color": "red", "size": 8},
name="excluded (per-detuning R² gate)",
showlegend=False,
),
row=row,
col=col,
)
def _add_linear_band(self, fig, x_fine, row, col):
if self.linear_fit_result.covar is None:
return
y_fine = self.linear_fit_result.eval(x=x_fine)
dely = self.linear_fit_result.eval_uncertainty(sigma=1, x=x_fine)
fig.add_trace(
go.Scatter(
x=np.concatenate([x_fine, x_fine[::-1]]),
y=np.concatenate([y_fine + dely, (y_fine - dely)[::-1]]),
fill="toself",
fillcolor="rgba(31,119,180,0.15)",
line={"width": 0},
hoverinfo="skip",
showlegend=False,
),
row=row,
col=col,
)
[docs]
@override
def add_traces(self, fig, row: int = 1, col: int = 1) -> None:
if (
self.analysis_successful
and self.linear_fit_result is not None
and self.linear_fit_result.success
and self.linear_fit_result.errorbars
):
x_fine = np.linspace(
self.artificial_detunings.min(), self.artificial_detunings.max(), 400
)
fig.add_trace(
go.Scatter(
x=self.artificial_detunings,
y=self.fitted_detunings,
error_y={"type": "data", "array": self.fitted_detunings_error},
mode="markers",
marker={"color": DATA_COLOR, "size": 6},
name="data",
showlegend=False,
),
row=row,
col=col,
)
self._plot_excluded_points(fig, row, col)
fig.add_trace(
go.Scatter(
x=x_fine,
y=self.linear_fit_result.eval(x=x_fine),
mode="lines",
line={"color": DATA_COLOR, "width": 2},
name="fit",
showlegend=False,
),
row=row,
col=col,
)
self._add_linear_band(fig, x_fine, row, col)
fig.add_vline(
x=self.frequency_correction,
line={"color": FIT_COLOR, "width": 2},
row=row,
col=col,
)
label_box(
fig,
f"correction: {int(self.frequency_correction) / 1e3} kHz<br>"
f"R²: {self.r_squared:.4f} (χ²/NDF: {self.reduced_chi2:.2f})<br>"
f"freq: {int(self.corrected_qubit_frequency) / 1e9:.6f} GHz<br>"
f"error: {self.qubit_frequency_error / 1e3:0.1f} kHz",
row=row,
col=col,
)
else:
if self.kept_mask is not None:
kept = self.kept_mask
if kept.any():
fig.add_trace(
go.Scatter(
x=self.all_artificial_detunings[kept],
y=self.raw_fitted_detunings[kept],
mode="markers",
marker={"color": "blue", "size": 6},
name="kept",
showlegend=False,
),
row=row,
col=col,
)
self._plot_excluded_points(fig, row, col)
elif self.fitted_detunings is not None:
fig.add_trace(
go.Scatter(
x=self.artificial_detunings,
y=self.fitted_detunings,
mode="markers",
marker={"color": "blue", "size": 6},
showlegend=False,
),
row=row,
col=col,
)
if self.reduced_chi2 is not None:
# Line fit ran, but its R^2 fell below min_r_squared_line_fit.
label = (
f"No correction<br>"
f"R²: {self.r_squared:.4f} (χ²/NDF: {self.reduced_chi2:.2f})<br>"
f"freq: {int(self.qubit_frequency) / 1e9:.2f} GHz<br>"
f"error: {self.qubit_frequency_error / 1e3:.2f} kHz"
)
elif self.r2_values:
# Fewer than 2 detunings passed min_r_squared_detune_fit, so no
# line fit was ever attempted — the per-detuning R^2s that
# caused the rejection are on the support figure instead.
n_kept = int(self.kept_mask.sum()) if self.kept_mask is not None else 0
label = (
f"No correction: kept {n_kept}/{len(self.r2_values)}<br>"
f"freq: {int(self.qubit_frequency) / 1e9:.2f} GHz (old value)"
)
else:
label = (
f"No correction, using old value<br>"
f"freq: {int(self.qubit_frequency) / 1e9:.2f} GHz<br>"
f"error: {self.qubit_frequency_error / 1e3:.2f} kHz"
)
failure_box(fig, label, row=row, col=col)
fig.add_vline(x=0, line={"color": "black", "width": 1}, row=row, col=col)
fig.update_xaxes(title_text="Artificial detuning (Hz)", row=row, col=col)
fig.update_yaxes(title_text="Fitted detuning (Hz)", row=row, col=col)
[docs]
@override
def list_plots(self) -> "list[str]":
return ["main", "detuning_fits"]
@override
def _render_figure(self, fig: "go.Figure", plot_name: str) -> None:
"""Dispatch "main" to the default 1x1 path; anything else to
``_{plot_name}_figure()``, merging its traces/layout into ``fig``."""
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", {}))
def _detuning_fits_figure(self) -> "go.Figure":
"""Grid of every per-detuning Ramsey trace with its fit, R^2, and
fitted detuning — the same figure ``support_figures()`` saves to disk,
also exposed as the interactive "detuning_fits" plot in bragi_quantum.gui."""
artificial_detunings = self.dataset.coords[self.detuning_coord].values
n_analyses = len(artificial_detunings)
ncols = 3 if n_analyses >= 5 else n_analyses
nrows = int(np.ceil(n_analyses / ncols))
fig = make_subplots(
rows=nrows,
cols=ncols,
subplot_titles=[
f"Detuning: {detuning / 1e6:.2f} MHz"
for detuning in artificial_detunings
],
)
for indx, _ in enumerate(artificial_detunings):
row, col = indx // ncols + 1, indx % ncols + 1
fit_result = self.detuning_fit_results[indx]
magnitudes = (
self.magnitudes[self.data_var].isel({self.detuning_coord: indx}).values
)
delays_fine = np.linspace(
self.ramsey_delays[0], self.ramsey_delays[-1], 400
)
fig.add_trace(
go.Scatter(
x=self.ramsey_delays,
y=magnitudes,
mode="markers",
marker={"size": 4, "color": DATA_COLOR},
showlegend=False,
),
row=row,
col=col,
)
fig.add_trace(
go.Scatter(
x=delays_fine,
y=fit_result.eval(fit_result.params, t=delays_fine),
mode="lines",
line={"color": FIT_COLOR, "width": 2},
showlegend=False,
),
row=row,
col=col,
)
if indx in self.indexes_to_remove:
label = (
f"R2: {fit_result.rsquared:.2f} "
f"(min {self.parameters.min_r_squared_detune_fit})<br>"
f"Success: {fit_result.success}<br>"
f"Error: {fit_result.errorbars}"
)
else:
freq = fit_result.params["frequency"].value / 1e6
freq_err = fit_result.params["frequency"].stderr / 1e6
label = (
f"R2: {fit_result.rsquared:.2f} "
f"(min {self.parameters.min_r_squared_detune_fit})<br>"
f"Fitted detuning:<br>{freq:.4f} ± {freq_err:.4f} MHz"
)
label_box(
fig,
label,
row=row,
col=col,
x=0.97,
y=0.97,
xanchor="right",
yanchor="top",
font_size=8,
)
fig.update_xaxes(title_text="Delay (s)", row=row, col=col)
fig.update_yaxes(title_text="Magnitude", row=row, col=col)
style_layout(
fig,
width=ncols * 380,
height=nrows * 320,
title=f"{self.parameters.name} — {self.qubit}",
)
return fig