# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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
# Michele Faucci Giannelli, faucci@chalmers.se
# Matteo Robbiati, robbiati@chalmers.se
# Joel Sandås, joel.sandas@chalmers.se
# ══════════════════════════════════════════════════════════════════════════
"""
Analysis for deriving candidate CZ working-point currents from spectroscopies.
Ported from tergite-autocalibration
(lib/nodes/coupler/cz_currents_from_spectroscopies/analysis.py). This node has
no measurement of its own: the qubit and resonator crossing currents stored in
Redis by qubit_spectroscopy_vs_current and resonator_spectroscopy_vs_current
are combined with the qubits' clock frequencies (from the session device) into
(frequency, current) points, a tunable-coupler frequency model is fitted
through them, and the currents at which the coupler frequency matches the CZ
avoided-crossing frequencies (20 and 02) are solved from the fit.
"""
import ast
import inspect
from typing import override
import numpy as np
import plotly.graph_objects as go
from scipy.optimize import curve_fit, fsolve
from bragi_quantum.datalayer.managing.session import ActiveSession
from bragi_quantum.datalayer.utils.logging import logger
from bragi_quantum.datalayer.visualization.plot_style import FIT_COLOR, label_box
from bragi_quantum.experiments.abstract.analysis import Analysis
from bragi_quantum.experiments.abstract.parameters import BaseQoi
from bragi_quantum.experiments.nodes.coupler.cz_currents_from_spectroscopies.parameters import (
CZCurrentsFromSpectroscopiesParameters,
)
from bragi_quantum.experiments.nodes.coupler.cz_transition_frequency import (
compute_transition_frequency,
)
_AMP_TO_MILLIAMP = 1e3
_HZ_TO_GHZ = 1e-9
[docs]
def coupler_freq(
x, bare_coupler_frequency, amplitude, offset, minimum_coupler_frequency
):
"""
Model function for the frequency of a tunable coupler.
Models the coupler frequency as a function of the DC current applied to
the coupler, using a cosine function to represent the modulation of the
frequency by the current.
Parameters:
x (float): The current applied to the coupler, in mA.
bare_coupler_frequency (float): The bare frequency of the coupler, in GHz.
amplitude (float): Amplitude of the modulation.
offset (float): Phase shift of the modulation, in mA.
minimum_coupler_frequency (float): This parameter is used to improve
fitting stability. Users should check its value as it is supposed
to be small.
Returns:
float: The frequency of the coupler at the given current, in GHz.
"""
return (
bare_coupler_frequency
* np.sqrt(np.abs(np.cos(np.pi * amplitude * (x - offset))))
+ minimum_coupler_frequency
)
[docs]
class CZCurrentsFromSpectroscopiesAnalysis(Analysis):
"""Derive candidate CZ working-point currents for every coupler (unified).
This is an analysis-only node: there is no measured dataset. For each
coupler it reads the qubit/resonator crossing currents from Redis and the
qubits' clock frequencies from the session device, fits the tunable-coupler
frequency model, and solves for the CZ avoided-crossing currents. Replaces
the former ``CZCurrentsFromSpectroscopiesCouplerAnalysis`` /
``...NodeAnalysis`` split.
"""
element_kind = "coupler"
parameters: CZCurrentsFromSpectroscopiesParameters
def __init__(self, parameters, qoi_cls=None, **kwargs):
super().__init__(parameters, qoi_cls, **kwargs)
self.name_qubit_1 = ""
self.name_qubit_2 = ""
self.fitted_parameters = None
self.fitted_parameters_errors = None
self.offset_guess = 0.0
self.cz_20_frequency = None
self.cz_02_frequency = None
self.cz_transition_frequency_20 = None
self.cz_transition_frequency_02 = None
self.sorted_cz_20_currents = []
self.sorted_cz_20_frequencies = []
self.sorted_cz_02_currents = []
self.sorted_cz_02_frequencies = []
self.all_crossings = None
self.best_fit_indices = []
self.qubit_1_crossings = []
self.qubit_2_crossings = []
self.qubits_params = {}
self.r1_freq = None
self.r2_freq = None
self.q1_freq = None
self.q2_freq = None
# -- execution (no dataset) -------------------------------------------- #
[docs]
@override
def run(self, dataset=None) -> "dict[str, BaseQoi]":
"""Analyse every coupler in ``parameters.couplers``.
Analysis-only: the ``dataset`` argument is accepted (the pipeline passes
the node's would-be HDF5 path) but ignored — inputs come from Redis and
the session device.
"""
self.workers, self.results = {}, {}
for coupler in self._targets():
worker = type(self)(self._params_for(coupler), self.qoi_cls)
self.results[coupler] = worker._process(None, coupler)
self.workers[coupler] = worker
return self.results
@override
def _process(self, dataset, element: str) -> BaseQoi:
"""Fit a single coupler from Redis/device inputs (no dataset)."""
self.element = element
self.coupler = element
self.dataset = dataset # unused, kept for interface compatibility
self._extract_qubit_names()
self._compute_transition_frequencies()
self.qoi = self.compute_qoi()
return self.qoi
def _extract_qubit_names(self):
self.name_qubit_1 = self.coupler.split("_")[0]
self.name_qubit_2 = self.coupler.split("_")[1]
def _compute_transition_frequencies(self):
"""
Raw CZ transition frequencies (Hz) for both avoided crossings,
computed from the qubits' live device clock frequencies. Saved to
Redis via the QOI so cz_parametrization / cz_chevron can reuse them
without recomputing on every run.
"""
device = ActiveSession.get().device
self.cz_transition_frequency_20 = compute_transition_frequency(
device, self.coupler, "20"
)
self.cz_transition_frequency_02 = compute_transition_frequency(
device, self.coupler, "02"
)
[docs]
@override
def plot_title(self) -> str:
return f"{self.coupler}"
# ------------------------------------------------------------------
# Input collection (Redis crossings + device clock frequencies)
# ------------------------------------------------------------------
def _get_crossing_points(self, qubit: str, key: str) -> list[float]:
"""
Read the crossing currents (in Amps) stored on the coupler's Redis
hash by the vs-current spectroscopy nodes (field ``<key>_<qubit>``).
"""
redis_connection = ActiveSession.get().redis_connection
stored = redis_connection.hget(f"couplers:{self.coupler}", f"{key}_{qubit}")
if not stored:
return []
try:
return [float(c) for c in ast.literal_eval(stored)]
except (ValueError, SyntaxError):
logger.warning(
f"Could not parse stored {key} for {self.coupler}/{qubit}: {stored!r}"
)
return []
def _get_flux_combined(
self, qubit_name: str, freq: float, crossing_type: str
) -> list:
"""
Retrieve crossing points for a qubit and combine them with the
frequency into (frequency_GHz, current_mA) fit points.
"""
crossings = self._get_crossing_points(qubit_name, crossing_type)
return [[freq, current * _AMP_TO_MILLIAMP] for current in crossings]
def _get_qubits_params_from_device(self, qubits: list[str]):
"""
Read the readout / f01 / f12 clock frequencies (in GHz) from the
active session's device. In tergite these came from Redis; in qc2 the
live device is the authoritative calibrated state.
"""
device = ActiveSession.get().device
for qubit in qubits:
clock_freqs = device.elements[qubit].clock_freqs
self.qubits_params[qubit] = {
"readout": float(clock_freqs.readout) * _HZ_TO_GHZ,
"f01": float(clock_freqs.f01) * _HZ_TO_GHZ,
"f12": float(clock_freqs.f12) * _HZ_TO_GHZ,
}
if self.parameters.calculate_wp:
ee = (
self.qubits_params[qubits[0]]["f01"]
+ self.qubits_params[qubits[1]]["f01"]
)
fg = (
self.qubits_params[qubits[0]]["f12"]
+ self.qubits_params[qubits[0]]["f01"]
)
gf = (
self.qubits_params[qubits[1]]["f01"]
+ self.qubits_params[qubits[1]]["f12"]
)
self.cz_20_frequency = np.abs(fg - ee)
self.cz_02_frequency = np.abs(gf - ee)
logger.info(
f"CZ 20 frequency: {self.cz_20_frequency} GHz, "
f"CZ 02 frequency: {self.cz_02_frequency} GHz, "
)
def _get_crossings_from_redis(self):
self.qubits_params = {}
self._get_qubits_params_from_device([self.name_qubit_1, self.name_qubit_2])
# Prepare flux tuning data
all_crossings = []
self.r1_freq = self.qubits_params[self.name_qubit_1]["readout"]
self.r2_freq = self.qubits_params[self.name_qubit_2]["readout"]
self.q1_freq = self.qubits_params[self.name_qubit_1]["f01"]
self.q2_freq = self.qubits_params[self.name_qubit_2]["f01"]
logger.debug(
f"Qubit 1: {self.name_qubit_1}, Qubit 2: {self.name_qubit_2}, "
f"Qubit 1 freq: {self.q1_freq}, Qubit 2 freq: {self.q2_freq}, "
f"Resonator 1 freq: {self.r1_freq}, Resonator 2 freq: {self.r2_freq}"
)
# Qubit 1: Combine qubit crossing points and resonator crossing points
self.qubit_1_crossings = self._get_flux_combined(
self.name_qubit_1, self.q1_freq, "qubit_crossing_points"
)
if len(self.qubit_1_crossings) >= self.parameters.minimum_qubit_crossing_points:
all_crossings.extend(self.qubit_1_crossings)
resonator_1_crossings = self._get_flux_combined(
self.name_qubit_1, self.r1_freq, "resonator_crossing_points"
)
if (
len(resonator_1_crossings)
>= self.parameters.minimum_resonator_crossing_points
):
all_crossings.extend(resonator_1_crossings)
# Qubit 2: Combine qubit crossing points and resonator crossing points
self.qubit_2_crossings = self._get_flux_combined(
self.name_qubit_2, self.q2_freq, "qubit_crossing_points"
)
if len(self.qubit_2_crossings) >= self.parameters.minimum_qubit_crossing_points:
all_crossings.extend(self.qubit_2_crossings)
resonator_2_crossings = self._get_flux_combined(
self.name_qubit_2, self.r2_freq, "resonator_crossing_points"
)
if (
len(resonator_2_crossings)
>= self.parameters.minimum_resonator_crossing_points
):
all_crossings.extend(resonator_2_crossings)
offset_guess_1 = self.initial_guess(self.qubit_1_crossings)
offset_guess_2 = self.initial_guess(self.qubit_2_crossings)
if abs(offset_guess_1 - offset_guess_2) < 0.5:
self.offset_guess = (offset_guess_1 + offset_guess_2) / 2
else:
self.offset_guess = 0
return all_crossings
[docs]
def initial_guess(self, qubit_currents):
"""
Estimate the current offset of the coupler modulation as the midpoint
of the widest gap between consecutive qubit crossing currents.
"""
if len(qubit_currents) > 1:
qubit_currents = [x[1] for x in qubit_currents]
offset_guess_index = np.argmax(np.diff(qubit_currents))
offset_guess = (
qubit_currents[offset_guess_index]
+ qubit_currents[offset_guess_index + 1]
) / 2
return offset_guess
return 0
# ------------------------------------------------------------------
# Fit and working-point calculation
# ------------------------------------------------------------------
[docs]
@override
def compute_qoi(self) -> BaseQoi:
self.all_crossings = np.array(self._get_crossings_from_redis())
if len(self.all_crossings) < self.parameters.min_total_crossing_points:
logger.error(
f"Found {len(self.all_crossings)} crossings, not enough crossing "
f"points found for coupler {self.coupler}."
)
return self.qoi_cls(is_successful=False)
self._fit_coupler_frequency()
if not self.is_fit_successful():
return self.qoi_cls(is_successful=False)
currents_20 = []
currents_02 = []
if self.parameters.calculate_wp:
self._calculate_potential_working_points()
if (
len(self.sorted_cz_20_currents) == 0
and len(self.sorted_cz_02_currents) == 0
):
logger.error(
f"No working points found for coupler {self.coupler} with the "
f"given CZ frequencies."
)
return self.qoi_cls(is_successful=False)
if len(self.sorted_cz_20_currents) > 0:
currents_20 = list(
np.asarray(self.sorted_cz_20_currents) / _AMP_TO_MILLIAMP
)
if len(self.sorted_cz_02_currents) > 0:
currents_02 = list(
np.asarray(self.sorted_cz_02_currents) / _AMP_TO_MILLIAMP
)
return self.qoi_cls(
is_successful=True,
cz_currents_from_spectroscopies_20=currents_20,
cz_currents_from_spectroscopies_02=currents_02,
cz_transition_frequency_20=self.cz_transition_frequency_20,
cz_transition_frequency_02=self.cz_transition_frequency_02,
coupler_frequency=self.fitted_parameters["bare_coupler_frequency"],
coupler_frequency_error=self.fitted_parameters_errors[
"bare_coupler_frequency"
],
coupler_amplitude=self.fitted_parameters["amplitude"],
coupler_amplitude_error=self.fitted_parameters_errors["amplitude"],
current_offset=self.fitted_parameters["offset"] / _AMP_TO_MILLIAMP,
current_offset_error=self.fitted_parameters_errors["offset"]
/ _AMP_TO_MILLIAMP,
coupler_minimum_frequency=self.fitted_parameters[
"minimum_coupler_frequency"
],
coupler_minimum_frequency_error=self.fitted_parameters_errors[
"minimum_coupler_frequency"
],
)
def _compute_candidate_offsets(
self, all_currents, all_frequencies, offset_lower, offset_upper
):
"""Data-driven starting points for the offset (sweet spot) seed."""
data_estimated_offset = all_currents[np.argmax(all_frequencies)]
return np.unique(
np.clip(
[
self.parameters.guess[2],
data_estimated_offset,
np.median(all_currents),
0.0,
offset_lower * 0.5,
offset_upper * 0.5,
self.offset_guess,
],
offset_lower,
offset_upper,
)
)
def _try_fit(
self,
currents_sub,
freqs_sub,
candidate_offsets,
offset_lower,
offset_upper,
bounds,
):
"""Return (popt, pcov, rmse) for the best seed, or None if all fail."""
sub_offset = currents_sub[np.argmax(freqs_sub)]
seeds = np.unique(
np.clip(
[*candidate_offsets, float(sub_offset)],
offset_lower,
offset_upper,
)
)
best = None
for offset_seed in seeds:
guess = list(self.parameters.guess)
guess[2] = float(offset_seed)
try:
popt, pcov = curve_fit(
coupler_freq,
currents_sub,
freqs_sub,
p0=guess,
bounds=bounds,
maxfev=10000,
)
except RuntimeError:
continue
if np.any(np.isnan(popt)) or np.any(np.isinf(popt)):
continue
residuals = freqs_sub - coupler_freq(currents_sub, *popt)
rmse = np.sqrt(np.mean(residuals**2))
if best is None or rmse < best[2]:
best = (popt, pcov, rmse)
return best
def _fit_coupler_frequency(self):
bounds = (self.parameters.lower_bounds, self.parameters.upper_bounds)
all_currents = self.all_crossings[:, 1]
all_frequencies = self.all_crossings[:, 0]
n_total = len(all_currents)
param_names = [
name for name in inspect.signature(coupler_freq).parameters if name != "x"
]
min_pts = max(len(param_names), self.parameters.min_total_crossing_points)
offset_lower = self.parameters.lower_bounds[2]
offset_upper = self.parameters.upper_bounds[2]
candidate_offsets = self._compute_candidate_offsets(
all_currents, all_frequencies, offset_lower, offset_upper
)
threshold = self.parameters.fit_quality_threshold
# Iterative outlier removal: fit the current active set, then drop the
# single point with the largest residual and repeat. Stops as soon as
# RMSE falls below the quality threshold, which naturally keeps as many
# points as possible. Works for any number of outliers in O(n) fits.
active = list(range(n_total))
best_popt = None
best_pcov = None
best_rmse = np.inf
self.best_fit_indices = list(range(n_total))
while len(active) >= min_pts:
currents_sub = all_currents[active]
freqs_sub = all_frequencies[active]
result = self._try_fit(
currents_sub,
freqs_sub,
candidate_offsets,
offset_lower,
offset_upper,
bounds,
)
if result is None:
# Fit failed entirely for this subset; drop the point furthest
# from the median frequency as a conservative heuristic.
worst = int(np.argmax(np.abs(freqs_sub - np.median(freqs_sub))))
active.pop(worst)
continue
popt, pcov, rmse = result
# Always track the best fit seen, even before threshold is met.
if rmse < best_rmse:
best_rmse = rmse
best_popt = popt
best_pcov = pcov
self.best_fit_indices = list(active)
if rmse < threshold:
logger.info(
f"Best fit uses {len(active)}/{n_total} crossing points, "
f"RMSE={best_rmse:.4f} GHz"
)
break
# Remove the point with the largest absolute residual.
residuals = freqs_sub - coupler_freq(currents_sub, *popt)
worst = int(np.argmax(np.abs(residuals)))
active.pop(worst)
else:
logger.warning(
f"No subset achieved RMSE < {threshold} GHz; "
f"using best available fit with RMSE={best_rmse:.4f} GHz."
)
if best_popt is None:
self.fitted_parameters = dict(zip(param_names, [np.nan] * len(param_names)))
self.fitted_parameters_errors = dict(
zip(param_names, [np.nan] * len(param_names))
)
logger.error("Fit failed: curve_fit did not converge for any subset.")
return
self.fitted_parameters = dict(zip(param_names, best_popt))
self.fitted_parameters_errors = dict(
zip(param_names, np.sqrt(np.diag(best_pcov)))
)
if not self.is_fit_successful():
logger.error("Fit failed: Optimized parameters contain NaN or Inf.")
else:
logger.info(
f"Fit succeeded: Optimized parameters are {self.fitted_parameters}"
)
def _calculate_potential_working_points(self):
if self.is_fit_successful():
if self.parameters.use_fix_frequency_step:
self.cz_20_frequency = self.parameters.fixed_frequency_step_in_GHz
self.cz_02_frequency = self.parameters.fixed_frequency_step_in_GHz
if self.cz_20_frequency < self.parameters.max_cz_frequency_in_GHz:
self.sorted_cz_20_currents, self.sorted_cz_20_frequencies = (
self._calculate_working_points(
self.cz_20_frequency,
self.qubits_params[self.name_qubit_1]["f01"],
self.qubits_params[self.name_qubit_2]["f01"],
)
)
else:
logger.warning(
f"CZ 20 frequency {self.cz_20_frequency} GHz is too high (max "
f"{self.parameters.max_cz_frequency_in_GHz} GHz due to electronics "
f"constraints), working point will not be calculated."
)
if self.cz_02_frequency < self.parameters.max_cz_frequency_in_GHz:
self.sorted_cz_02_currents, self.sorted_cz_02_frequencies = (
self._calculate_working_points(
self.cz_02_frequency,
self.qubits_params[self.name_qubit_2]["f01"],
self.qubits_params[self.name_qubit_1]["f01"],
)
)
else:
logger.warning(
f"CZ 02 frequency {self.cz_02_frequency} GHz is too high (max "
f"{self.parameters.max_cz_frequency_in_GHz} GHz due to electronics "
f"constraints), working point will not be calculated."
)
def _calculate_working_points(
self,
cz_step: float,
start_freq: float,
other_qubit_freq: float,
):
"""
Scan multiples of the CZ modulation frequency above ``start_freq`` and
solve the fitted coupler-frequency model for the currents at which the
coupler reaches each candidate gate frequency.
"""
flux_cz = []
freq_cz = []
offset = self.fitted_parameters["offset"]
amplitude = self.fitted_parameters["amplitude"]
# Distance from the sweet spot to the first zero on either side.
# Solutions more than one half-period away from the offset are on
# secondary arches and physically irrelevant for CZ operations.
half_period = 0.5 / amplitude
# Physical upper bound: the coupler frequency cannot exceed its
# maximum value. When resonator avoided crossings are absent this
# becomes the primary guard against placing working points in the
# steep region near the arch peak or on a secondary arch.
max_coupler_freq = (
self.fitted_parameters["bare_coupler_frequency"]
+ self.fitted_parameters["minimum_coupler_frequency"]
)
for i in range(1, self.parameters.max_number_of_wp):
gate_freq = start_freq + i * cz_step
if (
gate_freq < self.r1_freq
and gate_freq < self.r2_freq
and gate_freq > other_qubit_freq
and gate_freq < max_coupler_freq
):
# Seed fsolve symmetrically around the sweet spot so both
# starting points remain inside the main arch.
seed_delta = 0.4 * half_period
solutions = fsolve(
lambda x: (
coupler_freq(x, *self.fitted_parameters.values()) - gate_freq
),
[offset - seed_delta, offset + seed_delta],
)
for s in solutions:
if abs(s - offset) < half_period:
flux_cz.append(s)
freq_cz.append(gate_freq)
order = np.argsort(flux_cz)
return np.array(flux_cz)[order], np.array(freq_cz)[order]
[docs]
def is_fit_successful(self):
if self.fitted_parameters is None:
return False
return not (
np.any(np.isnan(list(self.fitted_parameters.values())))
or np.any(np.isinf(list(self.fitted_parameters.values())))
)
# ------------------------------------------------------------------
# Plotting (plotly)
# ------------------------------------------------------------------
[docs]
@override
def add_traces(self, fig, row: int = 1, col: int = 1) -> None:
legend = row == 1 and col == 1
if self.all_crossings is not None and np.ndim(self.all_crossings) == 2:
used = self.best_fit_indices or list(range(len(self.all_crossings)))
excluded = [i for i in range(len(self.all_crossings)) if i not in set(used)]
if used:
fig.add_trace(
go.Scatter(
x=self.all_crossings[used, 1],
y=self.all_crossings[used, 0],
mode="markers",
marker={"color": FIT_COLOR, "size": 7},
name="Crossing points (used)",
showlegend=legend,
),
row=row,
col=col,
)
if excluded:
fig.add_trace(
go.Scatter(
x=self.all_crossings[excluded, 1],
y=self.all_crossings[excluded, 0],
mode="markers",
marker={"color": "grey", "size": 7, "symbol": "circle-open"},
name="Crossing points (excluded)",
showlegend=legend,
),
row=row,
col=col,
)
offset = (
self.fitted_parameters["offset"]
if self.fitted_parameters is not None
else 0.0
)
flux = np.linspace(-3 + offset, 3 + offset, 1000)
if self.is_fit_successful():
fig.add_trace(
go.Scatter(
x=flux,
y=coupler_freq(flux, *list(self.fitted_parameters.values())),
mode="lines",
line={"color": FIT_COLOR, "width": 2},
name="Model fit",
showlegend=legend,
),
row=row,
col=col,
)
if self.parameters.calculate_wp:
fig.add_trace(
go.Scatter(
x=self.sorted_cz_20_currents,
y=self.sorted_cz_20_frequencies,
mode="markers",
marker={"color": "blue", "size": 8},
name="Candidate CZ (20)",
showlegend=legend,
),
row=row,
col=col,
)
fig.add_trace(
go.Scatter(
x=self.sorted_cz_02_currents,
y=self.sorted_cz_02_frequencies,
mode="markers",
marker={"color": "green", "size": 8},
name="Candidate CZ (02)",
showlegend=legend,
),
row=row,
col=col,
)
label_box(
fig,
f"Offset: {round(offset, 3)} mA<br>"
f"Minimum C<sub>f</sub>: "
f"{round(self.fitted_parameters['minimum_coupler_frequency'], 3)} GHz",
row=row,
col=col,
x=0.02,
y=0.98,
xanchor="left",
yanchor="top",
align="left",
)
fig.update_xaxes(
title_text="Current [mA]", range=[-3 + offset, 3 + offset], row=row, col=col
)
fig.update_yaxes(title_text="Frequency [GHz]", row=row, col=col)