# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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
# Matteo Robbiati, robbiati@chalmers.se
# ══════════════════════════════════════════════════════════════════════════
"""
Analysis for CZ phase calibration.
Ported from tergite-autocalibration (lib/nodes/coupler/cz_phases/analysis.py).
Each coupler dataset holds a Ramsey-phase scan on the target qubit, for both
values of ``control_ons``, for each of the coupler's two qubits (only the
Target qubit's data is fit with a cosine; the Control qubit's is not expected
to oscillate and is shown as a flat reference).
Like ``cz_parametrization``, the dataset's data variables are named after
each *qubit*, not the coupler — so ``CZPhasesAnalysis`` overrides
``analyse_element``/``_process`` to group the coupler's two qubit variables
directly rather than relying on the generic ``slice_element``.
"""
from typing import override
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from bragi_quantum.datalayer.visualization.plot_style import (
PLOTLY_TEMPLATE,
QUALITATIVE_PALETTE,
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.cz import CZModel
from bragi_quantum.experiments.nodes.coupler.cz_phases.parameters import (
CZPhasesParameters,
)
from bragi_quantum.experiments.utils.dataset_utils import as_dataset
_SERIES_COLORS = [QUALITATIVE_PALETTE[0], QUALITATIVE_PALETTE[3]]
def _fit_qubit_phase_scan(
magnitudes: np.ndarray, phases: np.ndarray, *, fit: bool
) -> dict:
"""
Fit (or, for the Control qubit, simply summarize) a 2-row
(control_on x phase) magnitude map.
Only the Target qubit's data is fit with :class:`CZModel`; the Control
qubit's curve is a flat mean per ``control_on`` row (matching
tergite-autocalibration's ``CZPhasesSSROQubitAnalysis``, where a fit is
only ever attempted for the Target qubit).
"""
fit_phase_grid = np.linspace(phases[0], phases[-1], 400)
fit_results = []
fitted_curves = []
for row in magnitudes:
curve = None
if fit:
try:
model = CZModel()
guess = model.guess(row, drive_amp=phases)
fit_result = model.fit(row, params=guess, drive_amp=phases)
curve = model.eval(fit_result.params, drive_amp=fit_phase_grid)
fit_results.append(fit_result)
except Exception:
curve = None
if curve is None:
curve = np.full(400, np.mean(row))
fitted_curves.append(curve)
if fit and len(fit_results) == 2:
cz_values = np.array([r.params["cz"].value for r in fit_results])
cz_errors = np.array([r.params["cz"].stderr or 0.0 for r in fit_results])
cphase = float((cz_values[1] - cz_values[0]) % 360)
err = float(np.sqrt(np.sum(cz_errors**2)))
opt_cz = cz_values.tolist()
else:
cphase, err, opt_cz = 0.0, 0.0, [0.0, 0.0]
try:
pop_loss = float(np.diff(np.mean(magnitudes, axis=0)[::-1])[0])
except Exception:
pop_loss = 0.0
return {
"magnitudes": magnitudes,
"fit_phase_grid": fit_phase_grid,
"fitted_curves": fitted_curves,
"cphase": cphase,
"err": err,
"opt_cz": opt_cz,
"pop_loss": pop_loss,
}
[docs]
class CZPhasesAnalysis(Analysis):
"""
Fits a coupler's Control and Target qubit Ramsey-phase scans and packages
the CZ (conditional or local) phase into a single QOI.
"""
element_kind = "coupler"
parameters: CZPhasesParameters
def __init__(
self,
parameters,
qoi_cls: "type[BaseQoi] | None" = None,
**kwargs,
):
super().__init__(parameters, qoi_cls, **kwargs)
self.q1_name = ""
self.q2_name = ""
self.control_name = ""
self.target_name = ""
self.phases = None
self.control_fit: dict | None = None
self.target_fit: dict | 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 (see module docstring) — 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 (control_ons, ramsey_phases, |S21|) scan for one qubit."""
da = self.dataset[qubit]
s21 = da.isel(ReIm=0) + 1j * da.isel(ReIm=1)
control_coord = f"{qubit}_control_ons"
phase_coord = f"{qubit}_ramsey_phases"
magnitudes = np.abs(s21).transpose(control_coord, phase_coord)
return (
magnitudes.coords[control_coord].values,
magnitudes.coords[phase_coord].values,
magnitudes.values,
)
[docs]
@override
def compute_qoi(self) -> BaseQoi:
transition = self.parameters.cz_transition
if transition == "20":
control_name, target_name = self.q2_name, self.q1_name
elif transition == "02":
control_name, target_name = self.q1_name, self.q2_name
else:
raise ValueError(
f"Unknown cz_transition {transition!r} for {self.coupler}; "
"expected '20' or '02'."
)
if self.parameters.swap_control_and_target:
control_name, target_name = target_name, control_name
self.control_name, self.target_name = control_name, target_name
_, _, control_magnitudes = self._qubit_magnitude_map(control_name)
_, phases, target_magnitudes = self._qubit_magnitude_map(target_name)
self.phases = phases
self.control_fit = _fit_qubit_phase_scan(
control_magnitudes, self.phases, fit=False
)
self.target_fit = _fit_qubit_phase_scan(
target_magnitudes, self.phases, fit=True
)
if not self.parameters.local_phases:
return self.qoi_cls(
is_successful=True,
cz_phase=self.target_fit["cphase"],
cz_phase_error=self.target_fit["err"],
cz_pop_loss=self.target_fit["pop_loss"],
)
if self.parameters.swap_control_and_target:
return self.qoi_cls(
is_successful=True,
cz_local_control=self.target_fit["cphase"],
cz_local_control_error=self.target_fit["err"],
)
return self.qoi_cls(
is_successful=True,
cz_local_target=self.target_fit["cphase"],
cz_local_target_error=self.target_fit["err"],
)
# ------------------------------------------------------------------
# Plotting (plotly) — both qubits of the coupler side by side, each its
# own subplot.
# ------------------------------------------------------------------
def _series_labels(self):
if self.parameters.local_phases:
return ["Gate Off", "Gate On"]
return ["Control Off", "Control On"]
def _panel_data(self):
"""(qubit name, role label, fit result) per panel."""
return [
(self.control_name, "Control", self.control_fit),
(self.target_name, "Target", self.target_fit),
]
[docs]
@override
def add_traces(self, fig, row: int = 1, col: int = 1) -> None:
"""Draw both qubits' Ramsey-phase scans side by side at (row, col) and (row, col+1)."""
legend = row == 1 and col == 1
series_labels = self._series_labels()
name_prefix = "Local Phase" if self.parameters.local_phases else "CZ"
for offset, (qubit, role, fit) in enumerate(self._panel_data()):
c = col + offset
for i, series_label in enumerate(series_labels):
color = _SERIES_COLORS[i]
fig.add_trace(
go.Scatter(
x=self.phases,
y=fit["magnitudes"][i],
mode="markers",
marker={"size": 6, "color": color},
name=f"S21 {series_label}",
legendgroup=series_label,
showlegend=legend,
),
row=row,
col=c,
)
fig.add_trace(
go.Scatter(
x=fit["fit_phase_grid"],
y=fit["fitted_curves"][i],
mode="lines",
line={"color": color, "width": 2},
legendgroup=series_label,
showlegend=False,
),
row=row,
col=c,
)
for opt_phase in fit["opt_cz"]:
fig.add_vline(
x=opt_phase,
line={"color": "gray", "dash": "dash", "width": 1.5},
row=row,
col=c,
)
label_box(
fig,
f"{name_prefix} = {fit['cphase']:.1f}±{fit['err']:.1f}<br>"
f"pop_loss = {fit['pop_loss']:.2f}",
row=row,
col=c,
)
fig.update_xaxes(title_text="Phase (deg)", row=row, col=c)
fig.update_yaxes(title_text="S21 Magnitude", row=row, col=c)
def _subplot_titles(self):
return [f"{role} — {qubit}" for qubit, role, _ in self._panel_data()]
@override
def _render_figure(self, fig, plot_name: str) -> None:
make_subplots(
rows=1,
cols=2,
subplot_titles=self._subplot_titles(),
horizontal_spacing=0.15,
figure=fig,
)
self.add_traces(fig, 1, 1)
fig.update_layout(
template=PLOTLY_TEMPLATE,
showlegend=True,
width=1120,
height=520,
margin={"t": 80, "b": 40, "r": 40},
)
@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 = [
f"{w.coupler}: {title}" for w in workers for title in w._subplot_titles()
]
make_subplots(
rows=nrows,
cols=2,
subplot_titles=subplot_titles,
horizontal_spacing=0.15,
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=True,
width=2 * 460 + 120,
height=nrows * 430 + 90,
margin={"t": 90, "b": 40, "r": 40},
)