# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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
# Amr Osman, amr.osman@chalmers.se
# ══════════════════════════════════════════════════════════════════════════
# This code is part of Tergite
#
# (C) Copyright Eleftherios Moschandreou 2023, 2024
# (C) Copyright Liangyu Chen 2023, 2024
# (C) Copyright Amr Osman 2024
# (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/qubit_control/rabi_oscillations/analysis.py
"""
Module containing classes that model, fit and plot data from Rabi and N-Rabi
experiments.
* ``RabiQubitAnalysis`` fits a cosine to a 1-D amplitude sweep and returns the
pi-pulse amplitude.
* ``NRabiQubitAnalysis`` fits a joint 2-D cosine model to all repetition slices
simultaneously, constraining each slice to frequency r·f₀ with a shared shift
(the optimal amplitude correction). The joint fit quality naturally detects
failures without per-slice thresholds or combinatorial root selection.
"""
from itertools import product as iproduct
from typing import override
import lmfit
import numpy as np
import plotly.graph_objects as go
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,
QUALITATIVE_PALETTE,
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.rabi import NRabiModel, RabiModel
from bragi_quantum.experiments.nodes.qubit_control.rabi_oscillations.parameters import (
NRabiBaseQOI,
NRabiParameters,
)
# --------------------------------------------------------------------------- #
# Rabi (1-D) analysis #
# --------------------------------------------------------------------------- #
[docs]
class RabiAnalysis(Analysis):
"""Fit a cosine to Rabi oscillation data (unified, parameter-driven).
Replaces the former ``RabiQubitAnalysis`` (per-qubit) + ``RabiNodeAnalysis``
(node-level) pair. Analyse one qubit with ``analyse_element(dataset, "q06")``
or every qubit in ``parameters.qubits`` with ``run(dataset)``.
"""
element_kind = "qubit"
[docs]
@override
def plot_title(self) -> str:
return f"Rabi Oscillations for {self.element}"
[docs]
@override
def compute_qoi(self) -> BaseQoi:
model = RabiModel()
for coord in self.dataset[self.data_var].coords:
if "amplitudes" in str(coord):
self.amplitude_coord = coord
self.amplitudes = self.dataset.coords[coord].values
# x-values for plotting the fitted curve
self.fit_plot_amplitudes = np.linspace(
self.amplitudes[0], self.amplitudes[-1], 400
)
magnitudes = self.magnitudes[self.data_var].values
guess = model.guess(magnitudes, drive_amp=self.amplitudes)
fit_result = model.fit(magnitudes, params=guess, drive_amp=self.amplitudes)
self.pi_amplitude = fit_result.params["amp180"].value
self.uncertainty = fit_result.params["amp180"].stderr
if self.uncertainty is None:
self.uncertainty = float("inf")
self.scaled_uncertainty = self.uncertainty / self.pi_amplitude
self.fit_y = model.eval(fit_result.params, drive_amp=self.fit_plot_amplitudes)
analysis_successful = (
self.scaled_uncertainty
< self.parameters.scaled_uncertainty_analysis_threshold
and self.pi_amplitude < self.parameters.pi_amplitude_analysis_threshold
)
return self.qoi_cls(
is_successful=analysis_successful,
amplitude=self.pi_amplitude,
amplitude_error=self.scaled_uncertainty,
)
[docs]
@override
def add_traces(self, fig, row: int = 1, col: int = 1) -> None:
label = (
f"π_ampl = {self.pi_amplitude:.2E} ± {self.uncertainty:.2E} (fullscale)<br>"
f"scaled uncertainty: {self.scaled_uncertainty:.2E}"
)
fig.add_trace(
go.Scatter(
x=self.amplitudes,
y=self.magnitudes[self.data_var].values,
mode="lines+markers",
line={"color": DATA_COLOR},
marker={"size": 4, "color": DATA_COLOR},
name="data",
showlegend=False,
),
row=row,
col=col,
)
fig.add_trace(
go.Scatter(
x=self.fit_plot_amplitudes,
y=self.fit_y,
mode="lines",
line={"color": FIT_COLOR, "width": 3},
name="fit",
hovertext=label,
showlegend=False,
),
row=row,
col=col,
)
label_box(fig, label, row=row, col=col)
fig.update_xaxes(title_text="Amplitude (fullscale)", row=row, col=col)
fig.update_yaxes(title_text="|S21|", row=row, col=col)
# --------------------------------------------------------------------------- #
# N-Rabi (2-D) analysis #
# --------------------------------------------------------------------------- #
[docs]
class NRabiAnalysis(Analysis):
"""
Analysis of N-Rabi oscillation data that determines the optimal microwave
amplitude correction for qubit control (unified, plotly).
Fits a joint 2-D model to all repetition slices simultaneously, constraining
slice r to frequency r·f₀ with a shared shift parameter. The shift IS the
correction — no root enumeration or combinatorial selection needed. Failed
experiments (data that does not satisfy the r·f₀ scaling) are detected by
the joint fit failing to converge or producing undefined errorbars. Replaces
the former ``NRabiQubitAnalysis`` + ``NRabiNodeAnalysis`` split.
"""
element_kind = "qubit"
parameters: NRabiParameters
def __init__(
self, parameters, qoi_cls: "type[NRabiBaseQOI] | None" = None, **kwargs
):
super().__init__(parameters, qoi_cls, **kwargs)
self.joint_result = None
self.joint_r2: float = 0.0
self.correction: np.ndarray = np.array([])
self.repetitions: np.ndarray = np.array([])
self.repetitions_coord: str = ""
self.mw_amplitudes_coord: str = ""
self.shift = 0.0
self.shift_uncertainty = 0.0
self.optimal_amp180 = 0.0
self.previous_amplitude = 0.0
self.previous_amplitude_error = 0.0
self.analysis_successful = False
@staticmethod
def _slice_zcs(f: float, shift: float, xmin: float, xmax: float):
"""Zero crossings of A·cos(2π·f·(x−shift)+π)+B in [xmin, xmax].
Returns [(value, polarity), ...] where polarity +1 = rising, -1 = falling.
k=0 is the first falling crossing to the left of the minimum (shift).
"""
hp = 0.5 / f
base = shift - 0.25 / f
k0 = int(np.ceil((xmin - base) / hp))
k1 = int(np.floor((xmax - base) / hp))
return [(base + k * hp, 1 if k % 2 == 1 else -1) for k in range(k0, k1 + 1)]
def _fit_joint(self):
x = self.correction
reps = self.repetitions
# Per-slice cosine pre-fit — two tiers:
# seed: cov >= 0.3 periods, used only for initialisation
# valid: also cov >= 0.5 and R² >= threshold, used in the joint fit
seed_model = NRabiModel()
seed_slices = [] # (rep, y, f, shift)
valid_slices = []
for rep in reps:
y = (
self.magnitudes[self.data_var]
.sel({self.repetitions_coord: rep})
.values.flatten()
)
sp = seed_model.guess(y, drive_amp=x)
try:
res = seed_model.fit(y, params=sp, drive_amp=x)
except Exception:
continue
if not res.success:
continue
f_fit = res.params["frequency"].value
shift_fit = res.params["shift"].value
f_cov = f_fit * (x.max() - x.min())
stderr = res.params["shift"].stderr
if f_cov >= 0.3:
seed_slices.append((rep, y, f_fit, shift_fit))
if (
f_cov >= 0.5
and res.errorbars
and res.rsquared >= self.parameters.sinusoidal_r2_threshold
and stderr is not None
and stderr > 0
):
valid_slices.append((rep, y, f_fit, shift_fit))
if not valid_slices:
self.joint_result = None
self.joint_r2 = 0.0
return None, None
# Initialisation: find a correction_guess that lands in the correct
# basin for the joint fit.
#
# When ≥ 2 seed slices (not in valid) contribute ZC candidates they
# jointly anchor the correct polarity → use polarity-consistent
# minimum-spread across all seed ZCs.
#
# Otherwise fall back to the minimum-|value| ZC of the valid slice;
# with only one extra ZC source a spurious tight pair can mislead the
# spread minimiser.
slice_zcs = []
for _, _, f, shift in seed_slices:
zcs = self._slice_zcs(f, shift, x.min(), x.max())
if zcs:
slice_zcs.append(zcs)
n_extra = len(slice_zcs) - len(valid_slices)
correction_guess = 0.0
if slice_zcs and len(valid_slices) == 1 and n_extra < 2:
# Min-|ZC| of the single valid slice
vals = [
v for v, _ in self._slice_zcs(*valid_slices[0][2:], x.min(), x.max())
]
correction_guess = min(vals, key=abs) if vals else 0.0
elif slice_zcs:
# Polarity-consistent minimum-spread across all seed ZCs
best_spread = np.inf
for polarity in (1, -1):
pol = [[v for v, p in s if p == polarity] for s in slice_zcs]
if any(not z for z in pol):
continue
for combo in iproduct(*pol):
spread = max(combo) - min(combo)
if spread < best_spread:
best_spread = spread
correction_guess = float(np.mean(combo))
if best_spread == np.inf:
all_vals = [v for s in slice_zcs for v, _ in s]
correction_guess = min(all_vals, key=abs)
# Joint sine fit: A_r·sin(2π·f_r·(x − correction)) + B_r.
# Frequencies are fixed to per-slice pre-fit values so the shared
# correction is the only inter-slice coupling.
valid_ys = np.stack([s[1] for s in valid_slices], axis=1)
valid_reps = [int(s[0]) for s in valid_slices]
def _make_params(c0: float) -> lmfit.Parameters:
params = lmfit.Parameters()
params.add("correction", value=c0, min=x.min(), max=x.max())
for rep, y, f_guess, _ in valid_slices:
r = int(rep)
params.add(f"frequency_{r}", value=f_guess, vary=False)
params.add(f"amplitude_{r}", value=(np.max(y) - np.min(y)) / 2)
params.add(f"offset_{r}", value=float(np.mean(y)))
return params
def _residual(params, x, valid_ys, valid_reps):
c = params["correction"].value
return np.concatenate(
[
valid_ys[:, i]
- (
params[f"amplitude_{r}"].value
* np.sin(2 * np.pi * params[f"frequency_{r}"].value * (x - c))
+ params[f"offset_{r}"].value
)
for i, r in enumerate(valid_reps)
]
)
try:
result = lmfit.minimize(
_residual,
_make_params(correction_guess),
args=(x, valid_ys, valid_reps),
method="least_squares",
)
except Exception:
self.joint_result = None
self.joint_r2 = 0.0
return None, None
self.joint_result = result
p = result.params
cv = p["correction"].value
r2s = []
for i, r in enumerate(valid_reps):
y = valid_ys[:, i]
yp = (
p[f"amplitude_{r}"].value
* np.sin(2 * np.pi * p[f"frequency_{r}"].value * (x - cv))
+ p[f"offset_{r}"].value
)
ss_tot = np.sum((y - np.mean(y)) ** 2)
r2s.append(1.0 - np.sum((y - yp) ** 2) / ss_tot if ss_tot > 0 else 0.0)
self.joint_r2 = float(np.mean(r2s))
stderr = p["correction"].stderr
if (
not result.success
or stderr is None
or stderr <= 0
or self.joint_r2 < self.parameters.joint_r2_threshold
):
return None, None
return cv, stderr
def _previous_amplitude(self) -> float:
"""
Fetch the current amp180 for this qubit from the active device.
``transition="01"`` -> ``rxy.amp180``, ``transition="12"`` ->
``r12.ef_amp180``. Returns 0.0 when no active session/device is
available.
"""
try:
transmon = ActiveSession.get().device.elements[self.qubit]
if self.parameters.transition == "01":
return float(transmon.rxy.amp180)
return float(transmon.r12.ef_amp180)
except Exception:
return 0.0
[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.mw_amplitudes_coord = coord
self.correction = self.dataset.coords[coord].values
elif "repetitions" in coord_str:
self.repetitions_coord = coord
self.repetitions = self.dataset.coords[coord].values
self.shift, self.shift_uncertainty = self._fit_joint()
self.previous_amplitude = self._previous_amplitude()
self.previous_amplitude_error = 0.0
if self.shift is None:
self.analysis_successful = False
self.optimal_amp180 = self.previous_amplitude
self.shift_uncertainty = 0.0
self.shift = 0.0
else:
self.analysis_successful = True
self.optimal_amp180 = self.previous_amplitude + self.shift
self.qoi_obj = self.qoi_cls(
is_successful=self.analysis_successful,
amplitude=self.optimal_amp180,
amplitude_error=self.previous_amplitude_error + self.shift_uncertainty,
correction=self.shift,
correction_error=self.shift_uncertainty,
)
return self.qoi_obj
[docs]
@override
def plot_title(self) -> str:
return f"N-Rabi for {self.element}"
[docs]
@override
def add_traces(self, fig, row: int = 1, col: int = 1) -> None:
da = self.magnitudes[self.data_var].transpose(
self.repetitions_coord, self.mw_amplitudes_coord
)
fig.add_trace(
go.Heatmap(
z=da.values,
x=self.correction,
y=self.repetitions,
colorscale="RdBu",
reversescale=True,
showscale=False,
),
row=row,
col=col,
)
if self.analysis_successful:
unc_str = (
f"±{self.shift_uncertainty:.4f}"
if self.shift_uncertainty is not None
else ""
)
fig.add_vline(
x=self.shift,
line={"color": "black", "width": 2, "dash": "dash"},
row=row,
col=col,
)
fig.add_annotation(
row=row,
col=col,
xref="x domain",
yref="y domain",
x=0.5,
y=1.02,
xanchor="center",
yanchor="bottom",
showarrow=False,
text=(
f"Correction: {self.shift:.4f} {unc_str} R²={self.joint_r2:.3f}"
),
font={"size": 9},
)
else:
fig.add_annotation(
row=row,
col=col,
xref="x domain",
yref="y domain",
x=0.5,
y=0.5,
xanchor="center",
yanchor="middle",
showarrow=False,
text="No correction — analysis failed;<br>expand range and/or check traces.",
font={"size": 10, "color": "red"},
bgcolor="rgba(255,255,255,0.8)",
bordercolor="red",
borderwidth=2,
)
fig.update_xaxes(title_text="mw amplitude correction", row=row, col=col)
fig.update_yaxes(title_text="Repetitions", row=row, col=col)