# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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:
#
# Joel Sandås, joel.sandas@chalmers.se
# Axel Andersson, axean@chalmers.se
# Yanchen Lin, linya@chalmers.se
# Matteo Robbiati, robbiati@chalmers.se
# Michele Faucci Giannelli, faucci@chalmers.se
# ══════════════════════════════════════════════════════════════════════════
"""
Analysis for the CZ chevron: sweeping the frequency and duration of a
coupler's flux pulse (amplitude held fixed), to find the CZ working point.
Ported from tergite-autocalibration
(lib/nodes/coupler/cz_chevron/analysis.py), structured like the sibling
``cz_parametrization`` node (frequency vs. amplitude): each coupler dataset
holds a 2-D (frequency, duration) CZ-pulse scan per qubit, the qubit driven
towards |2> is expected to show a magnitude maximum and the qubit driven
towards |0> a magnitude minimum at the same (frequency, duration) point if a
real CZ avoided crossing exists there.
Unlike ``cz_parametrization``, the duration sweep is dense enough to resolve
a population oscillation, so the chosen duration is refined further: a
damped-sinusoid (Ramsey) model is fitted to the duration trace at the chosen
frequency for both qubits and their fitted periods are averaged. The same
fit is repeated at the 8 neighboring frequencies (9 total) to gauge how
reliably the oscillation resolves around the chosen point; if too many of
those fits fail, the working point is discarded even when the coarser
two-qubit-compatibility check passed.
Like ``cz_parametrization``, the dataset's data variables are named after
each *qubit*, not the coupler — so ``CZChevronAnalysis`` overrides
``analyse_element``/``_process`` to group the coupler's two qubit variables
directly rather than relying on the generic ``slice_element``.
"""
import json
from typing import override
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from bragi_quantum.datalayer.utils.logging import logger
from bragi_quantum.datalayer.visualization.plot_style import (
PAIR_COLORS,
PLOTLY_TEMPLATE,
failure_box,
label_box,
)
from bragi_quantum.experiments.abstract.analysis import Analysis
from bragi_quantum.experiments.abstract.parameters import BaseQoi
from bragi_quantum.experiments.fitting_tools.models.ramsey import RamseyModel
from bragi_quantum.experiments.nodes.coupler.cz_chevron.parameters import (
CZChevronParameters,
)
from bragi_quantum.experiments.utils.dataset_utils import as_dataset
def _normalize(raw: np.ndarray) -> np.ndarray:
span = np.max(raw) - np.min(raw)
if span == 0:
return np.zeros_like(raw)
return (raw - np.min(raw)) / span
def _extremum_point(
magnitudes: np.ndarray,
frequencies: np.ndarray,
durations: np.ndarray,
*,
mode: str,
) -> list:
"""The (frequency, duration) of the map's max ('max') or min ('min')."""
index = np.argmax(magnitudes) if mode == "max" else np.argmin(magnitudes)
freq_idx, duration_idx = np.unravel_index(index, magnitudes.shape)
return [float(frequencies[freq_idx]), float(durations[duration_idx])]
def _fit_period(durations: np.ndarray, magnitudes: np.ndarray):
"""Fit a damped sinusoid to one duration trace.
Returns ``(period, fit_result)``. ``period`` is ``None`` when the fit
fails to converge, or when the fitted period exceeds the scanned
duration range — that just means the fit found decay/noise curvature,
not a genuine oscillation, so it can't be used to refine the duration.
"""
model = RamseyModel()
guess = model.guess(magnitudes, t=durations)
fit_result = model.fit(magnitudes, params=guess, t=durations)
if not fit_result.success:
return None, fit_result
frequency = fit_result.params["frequency"].value
period = 1 / frequency if frequency != 0 else np.inf
if np.isinf(period) or period > durations[-1]:
return None, fit_result
return period, fit_result
[docs]
class CombinedFrequencyVsDurationAnalysis:
"""
Combines the results of a coupler's two qubit analyses in a CZ chevron
experiment. Finds the point of maximum q_to2-q_to0 magnitude difference
and checks that it agrees with either the q_to2 max point or the q_to0
min point within tolerance. If not, the analysis fails.
"""
def __init__(self, result_to2: list, result_to0: list, max_diff_point: list):
self.result_to2 = result_to2
self.result_to0 = result_to0
self.max_diff_point = max_diff_point
self.frequency_tolerance = 2.5e6 # Hz
self.duration_tolerance = 50e-9 # s
[docs]
def are_two_qubits_compatible(self) -> bool:
"""
Check if the maximum-difference point is near either the q_to2 max
or the q_to0 min point.
"""
return self._is_near_point(self.result_to2) or self._is_near_point(
self.result_to0
)
def _is_near_point(self, point: list) -> bool:
freq_ok = abs(self.max_diff_point[0] - point[0]) < self.frequency_tolerance
duration_ok = abs(self.max_diff_point[1] - point[1]) < self.duration_tolerance
return bool(freq_ok and duration_ok)
[docs]
def best_parameters(self) -> list:
"""The point of maximum q_to2-q_to0 magnitude difference (the working point)."""
return self.max_diff_point
[docs]
class CZChevronAnalysis(Analysis):
"""
Runs the frequency-vs-duration CZ chevron analysis for both qubits of
one coupler and packages the working point into a single QOI.
"""
element_kind = "coupler"
# Number of frequency bins on either side of the chosen working
# frequency used for the duration-fit reliability check and shown in the
# support-traces figure (9 total: chosen frequency +/- 4 neighbors).
SUPPORT_TRACE_HALF_WINDOW = 4
parameters: CZChevronParameters
def __init__(
self,
parameters,
qoi_cls: "type[BaseQoi] | None" = None,
**kwargs,
):
super().__init__(parameters, qoi_cls, **kwargs)
self.q1_name = ""
self.q2_name = ""
self.frequencies = None
self.durations = None
self.q1_magnitudes = None
self.q2_magnitudes = None
self.q_to2_name = ""
self.q_to0_name = ""
self.diff = None
self.result_to2 = None
self.result_to0 = None
self.max_diff_point = None
self.working_point = None
self.selected_freq_index = None
self.trace_fit_failure_fraction = 0.0
self.combined: CombinedFrequencyVsDurationAnalysis | None = None
[docs]
@override
def plot_title(self) -> str:
return f"{self.coupler}"
# ------------------------------------------------------------------
# Execution: coupler data variables are named after each qubit, not the
# coupler, so the default slice_element (matching a variable literally
# named `element`) does not apply — group by the coupler's qubits here.
# ------------------------------------------------------------------
[docs]
@override
def analyse_element(self, dataset, element: str) -> BaseQoi:
ds_full = as_dataset(dataset)
return self._process(ds_full, element)
@override
def _process(self, dataset, element: str) -> BaseQoi:
self.element = element
self.coupler = element
self.dataset = dataset
self.q1_name, self.q2_name = element.split("_")
self.qoi = self.compute_qoi()
return self.qoi
def _qubit_magnitude_map(self, qubit: str):
"""The (frequencies, durations, |S21|) 2-D scan for one qubit."""
da = self.dataset[qubit]
s21 = da.isel(ReIm=0) + 1j * da.isel(ReIm=1)
freq_coord = f"{qubit}_cz_pulse_frequencies"
duration_coord = f"{qubit}_cz_pulse_durations"
magnitudes = np.abs(s21).transpose(freq_coord, duration_coord)
return (
magnitudes.coords[freq_coord].values,
magnitudes.coords[duration_coord].values,
magnitudes.values,
)
def _duration_trace(self, qubit: str, freq_index: int) -> np.ndarray:
"""One qubit's magnitude-vs-duration trace at a given frequency index."""
magnitudes = self.q1_magnitudes if qubit == self.q1_name else self.q2_magnitudes
return magnitudes[freq_index, :]
[docs]
@override
def compute_qoi(self) -> BaseQoi:
q1_freqs, q1_durations, q1_mag = self._qubit_magnitude_map(self.q1_name)
_, _, q2_mag = self._qubit_magnitude_map(self.q2_name)
self.frequencies, self.durations = q1_freqs, q1_durations
self.q1_magnitudes, self.q2_magnitudes = q1_mag, q2_mag
transition = self.parameters.cz_transition
if transition == "20":
self.q_to2_name, self.q_to0_name = self.q1_name, self.q2_name
mag_to2, mag_to0 = q1_mag, q2_mag
self.diff = _normalize(q1_mag) - _normalize(q2_mag)
elif transition == "02":
self.q_to2_name, self.q_to0_name = self.q2_name, self.q1_name
mag_to2, mag_to0 = q2_mag, q1_mag
self.diff = _normalize(q2_mag) - _normalize(q1_mag)
else:
raise ValueError(
f"Unknown cz_transition {transition!r} for {self.coupler}; "
"expected '20' or '02'."
)
self.result_to2 = _extremum_point(mag_to2, q1_freqs, q1_durations, mode="max")
self.result_to0 = _extremum_point(mag_to0, q1_freqs, q1_durations, mode="min")
max_idx = np.unravel_index(np.argmax(self.diff), self.diff.shape)
self.max_diff_point = [
float(q1_freqs[max_idx[0]]),
float(q1_durations[max_idx[1]]),
]
self.selected_freq_index = int(
np.argmin(np.abs(q1_freqs - self.max_diff_point[0]))
)
self.combined = CombinedFrequencyVsDurationAnalysis(
self.result_to2, self.result_to0, self.max_diff_point
)
frequency_error = (q1_freqs[1] - q1_freqs[0]) / np.sqrt(12)
duration_error = (q1_durations[1] - q1_durations[0]) / np.sqrt(12)
trace_period_summary, self.trace_fit_failure_fraction = (
self._compute_trace_period_summary()
)
too_many_trace_fits_failed = (
self.trace_fit_failure_fraction
> self.parameters.trace_fit_failure_threshold
)
best_freq, best_duration = self._refine_duration_at_selected_frequency()
self.working_point = [best_freq, best_duration]
if self.combined.are_two_qubits_compatible() and not too_many_trace_fits_failed:
return self.qoi_cls(
is_successful=True,
cz_pulse_frequency=best_freq,
cz_pulse_frequency_error=frequency_error,
cz_pulse_duration=best_duration,
cz_pulse_duration_error=duration_error,
cz_chevron_trace_periods=json.dumps(trace_period_summary),
cz_chevron_trace_fit_failure_fraction=self.trace_fit_failure_fraction,
)
if too_many_trace_fits_failed:
logger.info(
f"Bad data: {self.trace_fit_failure_fraction * 100:.0f}% of chevron "
"support-trace fits failed (> "
f"{self.parameters.trace_fit_failure_threshold * 100:.0f}% threshold) "
f"for coupler {self.coupler} — discarding working point."
)
else:
logger.info(f"No valid CZ working point found for coupler {self.coupler}.")
return self.qoi_cls(
is_successful=False,
cz_chevron_trace_periods=json.dumps(trace_period_summary),
cz_chevron_trace_fit_failure_fraction=self.trace_fit_failure_fraction,
)
# ------------------------------------------------------------------
# Duration refinement via Ramsey fits of the neighboring duration traces
# ------------------------------------------------------------------
def _support_trace_indices(self) -> list:
n = len(self.frequencies)
half_window = self.SUPPORT_TRACE_HALF_WINDOW
return [
self.selected_freq_index + i
for i in range(-half_window, half_window + 1)
if 0 <= self.selected_freq_index + i < n
]
def _fit_both_qubits_at(self, freq_index: int):
"""(period_q1, fit_q1, period_q2, fit_q2) at one frequency index."""
trace_q1 = self._duration_trace(self.q1_name, freq_index)
trace_q2 = self._duration_trace(self.q2_name, freq_index)
period_q1, fit_q1 = _fit_period(self.durations, trace_q1)
period_q2, fit_q2 = _fit_period(self.durations, trace_q2)
return period_q1, fit_q1, period_q2, fit_q2
def _compute_trace_period_summary(self) -> "tuple[list, float]":
"""
Fit every duration trace neighboring the selected working point (the
same traces shown in the support-traces plot) and return the
[frequency, avg_period] pairs for the ones with a good fit, along
with the fraction of traces whose fit failed.
"""
indices = self._support_trace_indices()
if not indices:
return [], 0.0
summary = []
for idx in indices:
period_q1, _, period_q2, _ = self._fit_both_qubits_at(idx)
if period_q1 is not None and period_q2 is not None:
summary.append(
[float(self.frequencies[idx]), float((period_q1 + period_q2) / 2)]
)
failure_fraction = 1.0 - len(summary) / len(indices)
return summary, failure_fraction
def _refine_duration_at_selected_frequency(self) -> "tuple[float, float]":
"""The chosen (frequency, duration) working point.
The frequency is the combined max-diff-point frequency. The
duration is the average of both qubits' fitted oscillation periods
at that frequency when both resolve; otherwise falls back to twice
the max-diff-point duration (treating it as a half-period).
"""
best_freq = self.max_diff_point[0]
period_q1, _, period_q2, _ = self._fit_both_qubits_at(self.selected_freq_index)
if period_q1 is not None and period_q2 is not None:
duration = (period_q1 + period_q2) / 2
else:
duration = 2 * self.max_diff_point[1]
return best_freq, round(duration * 1e9) * 1e-9
# ------------------------------------------------------------------
# Plotting (plotly): main frequency-vs-duration heatmaps
# ------------------------------------------------------------------
def _magnitudes_for(self, qubit: str) -> np.ndarray:
return self.q1_magnitudes if qubit == self.q1_name else self.q2_magnitudes
def _panel_data(self):
"""Raw magnitude map per panel, in (q_to2, q_to0) order."""
return [
self._magnitudes_for(self.q_to2_name),
self._magnitudes_for(self.q_to0_name),
]
@staticmethod
def _point_label(tag: str, point: list) -> str:
return f"{tag}: freq={point[0] / 1e6:.3f} MHz, duration={point[1] * 1e9:.1f} ns"
[docs]
@override
def add_traces(self, fig, row: int = 1, col: int = 1) -> None:
"""Draw both qubits' raw magnitude maps side by side at (row, col) and (row, col+1)."""
legend = row == 1 and col == 1
compatible = (
self.combined is not None and self.combined.are_two_qubits_compatible()
)
too_many_failed = (
self.trace_fit_failure_fraction
> self.parameters.trace_fit_failure_threshold
)
quality_text = (
f"Parking current: {self.parameters.parking_current * 1e3:.3f} mA<br>"
f"Trace fit failure fraction: {self.trace_fit_failure_fraction:.2f}<br>"
f"Compatible: {'yes' if compatible else 'no'}"
)
working_point_text = self._point_label("Working point", self.working_point)
for offset, magnitudes in enumerate(self._panel_data()):
c = col + offset
x_domain = fig.get_subplot(row, c).xaxis.domain
y_domain = fig.get_subplot(row, c).yaxis.domain
fig.add_trace(
go.Heatmap(
x=self.frequencies,
y=self.durations,
z=magnitudes.T,
colorscale="RdBu_r",
showscale=True,
colorbar={
"title": {"text": "|S21|", "side": "top", "font": {"size": 10}},
"x": x_domain[1] + 0.02,
"xanchor": "left",
"y": (y_domain[0] + y_domain[1]) / 2,
"yanchor": "middle",
"len": y_domain[1] - y_domain[0],
"thickness": 12,
"tickfont": {"size": 9},
},
),
row=row,
col=c,
)
fig.add_trace(
go.Scatter(
x=[self.working_point[0]],
y=[self.working_point[1]],
mode="markers",
marker={
"color": "lime",
"size": 16,
"symbol": "circle-open",
"line": {"color": "lime", "width": 3},
},
name="Working point",
legendgroup="working_point",
showlegend=legend,
),
row=row,
col=c,
)
label_box(
fig,
f"{quality_text}<br>{working_point_text}",
row=row,
col=c,
x=0.02,
y=0.98,
xanchor="left",
yanchor="top",
align="left",
)
if not compatible or too_many_failed:
failure_box(fig, "Analysis failed", row=row, col=c)
fig.update_xaxes(title_text="CZ pulse frequency (Hz)", row=row, col=c)
fig.update_yaxes(title_text="Pulse duration (s)", row=row, col=c)
@override
def _render_figure(self, fig, plot_name: str) -> None:
make_subplots(
rows=1,
cols=2,
subplot_titles=[self.q_to2_name, self.q_to0_name],
horizontal_spacing=0.18,
figure=fig,
)
self.add_traces(fig, 1, 1)
fig.update_layout(
template=PLOTLY_TEMPLATE,
showlegend=False,
width=1120,
height=520,
margin={"t": 80, "b": 40, "r": 90},
)
@override
def _render_grid_figure(self, fig, ncols: int) -> None:
workers = list(self.workers.values()) or (
[self] if self.element is not None else []
)
if not workers:
raise ValueError("nothing analysed yet; call run(...) first")
nrows = len(workers)
subplot_titles = [
title for w in workers for title in (w.q_to2_name, w.q_to0_name)
]
make_subplots(
rows=nrows,
cols=2,
subplot_titles=subplot_titles,
horizontal_spacing=0.16,
vertical_spacing=max(0.06, 0.18 / nrows),
figure=fig,
)
for i, worker in enumerate(workers):
worker.add_traces(fig, row=i + 1, col=1)
fig.update_layout(
template=PLOTLY_TEMPLATE,
showlegend=False,
width=2 * 460 + 120,
height=nrows * 430 + 90,
margin={"t": 90, "b": 40, "r": 90},
)
# ------------------------------------------------------------------
# Support figure: 3x3 grid of duration traces around the working
# frequency, both qubits overlaid per panel.
# ------------------------------------------------------------------