# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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
# Yanchen Lin, linya@chalmers.se
# Matteo Robbiati, robbiati@chalmers.se
# Michele Faucci Giannelli, faucci@chalmers.se
# ══════════════════════════════════════════════════════════════════════════
"""
Module containing classes that fit and plot data from a T2* (Ramsey)
experiment.
"""
from typing import override
import numpy as np
from bragi_quantum.datalayer.utils.logging import logger
from bragi_quantum.experiments.fitting_tools.models.ramsey import RamseyModel
from bragi_quantum.experiments.nodes.characterization.coherence_analysis import (
SECONDS_TO_MICROSECONDS,
CoherenceAnalysis,
)
from bragi_quantum.experiments.nodes.characterization.t2.parameters import (
T2QOI,
T2Parameters,
)
[docs]
class T2Analysis(CoherenceAnalysis):
"""
Analysis that fits a damped Ramsey oscillation to a single qubit's T2*
delay sweep, repeated independently ``t2_repetitions`` times.
Every delay point is a single hardware-averaged value (``repetitions``
hardware-averaged shots collapse into it — that averaging is not a
coordinate this analysis has access to). Each of the ``t2_repetitions``
independent sweeps is projected onto the |0>-|1> calibration axis using
*its own* calibration points (``project`` broadcasts per slice of the
outer ``t2_repetitions`` dimension, never averaging calibration points
across repeats) and fitted separately to an exponentially decaying
sinusoid (``RamseyModel``), seeded with the known (signed)
``artificial_detuning_Hz`` so each fit converges on the physically
correct oscillation frequency rather than an arbitrary sign. A fit whose
frequency lands at or beyond the delay sampling's Nyquist limit is
rejected as an alias, and a fit whose amplitude implausibly exceeds the
trace's own peak-to-peak/2 is rejected as a runaway fit. The reported
T2* is the mean of the per-repeat fits and its error is the plain
standard deviation across those repeats.
Delays (and so ``t2``/``tau``) are fitted and reported in microseconds;
``frequency``/``frequency_error`` stay in Hz,
matching ``artificial_detuning_Hz`` — the fitted oscillation frequency
is converted between the fit's native cycles/microsecond and Hz at the
fit/report boundary.
"""
label = "T2*"
repetitions_key = "t2_repetitions"
model_cls = RamseyModel
time_param = "tau"
peak_to_peak_per_amplitude = 2.0
parameters: T2Parameters
def __init__(self, parameters: T2Parameters, qoi_cls: type[T2QOI]):
super().__init__(parameters, qoi_cls)
self.frequency = None
self.frequency_error = None
self.phase = None
self.last_params = None
@override
def _fit_repeat(self, trace: np.ndarray) -> dict[str, float] | None:
# Seed with the signed artificial detuning (converted to
# cycles/microsecond) so the fit converges on the correct sign.
result = self._fit(
trace,
freq_guess=self.parameters.artificial_detuning_Hz / SECONDS_TO_MICROSECONDS,
)
if result is None:
return None
# Nyquist limit set by the delay sampling, in MHz (delays are in
# microseconds, and the fit's "frequency" is already cyclic, so no
# unit conversion is needed). Largest gap sets the tightest bound
# for non-uniform delays.
nyquist_freq = 0.5 / np.max(np.diff(self.delays))
fitted_frequency = float(result.params["frequency"].value)
if abs(fitted_frequency) >= nyquist_freq:
logger.warning(
f"⚠️ {self._element_name}: fitted frequency "
f"{abs(fitted_frequency):.2f} MHz exceeds the "
f"{nyquist_freq:.2f} MHz Nyquist limit for this delay "
"sampling — rejecting as an aliased fit."
)
return None
self.last_params = result.params
return {
"time": float(result.params["tau"].value),
"offset": float(result.params["offset"].value),
"amplitude": float(result.params["amplitude"].value),
# Back from the fit's cycles/microsecond to Hz.
"frequency": fitted_frequency * SECONDS_TO_MICROSECONDS,
"phase": float(result.params["phase"].value),
}
@override
def _aggregate(self) -> None:
super()._aggregate()
self.frequency, self.frequency_error = self._mean_std("frequency")
self.phase, _ = self._mean_std("phase")
@override
def _decay_curve(self, delays: np.ndarray, time: float) -> np.ndarray:
# The last successful fit's parameter set, with the values overridden
# to the cross-repeat means (amplitude, offset, frequency and phase
# held there while only the time varies).
params = self.last_params.copy()
params["tau"].value = time
# Back to the fit's native cycles/microsecond units.
params["frequency"].value = self.frequency / SECONDS_TO_MICROSECONDS
params["amplitude"].value = self.amplitude
params["offset"].value = self.offset
params["phase"].value = self.phase
return self.model.eval(params, t=delays)
@override
def _summary_lines(self) -> list[str]:
return [
(
f"frequency = {self.frequency / 1e3:.2f} ± "
f"{self.frequency_error / 1e3:.2f} kHz"
)
]
@override
def _build_qoi(self) -> T2QOI:
return self.qoi_cls(
is_successful=True,
t2=self.time,
t2_error=self.time_error,
offset=self.offset,
offset_error=self.offset_error,
amplitude=self.amplitude,
amplitude_error=self.amplitude_error,
frequency=self.frequency,
frequency_error=self.frequency_error,
tau=self.time,
tau_error=self.time_error,
)