# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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:
#
# Filip Eriksson, filieri@chalmers.se
# Joel Sandås, joel.sandas@chalmers.se
# Matteo Robbiati, robbiati@chalmers.se
# ══════════════════════════════════════════════════════════════════════════
"""
Analysis for the CZ wall finder.
Ported from tergite-autocalibration
(lib/nodes/coupler/cz_wall_finder/analysis.py). Each coupler dataset holds a
single-frequency amplitude sweep per qubit (reusing
CZParametrizationFixDuration's measurement, collapsed to one frequency
point); the "wall" is the amplitude at which a qubit's magnitude response
first drops below its own sweep mean, scanned from the highest amplitude
down. The coupler's wall amplitude is the more conservative (lower) of its
two qubits'.
Like cz_parametrization, the dataset's data variables are named after each
*qubit*, not the coupler, so ``CZWallFinderAnalysis`` 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.utils.logging import logger
from bragi_quantum.datalayer.visualization.plot_style import (
PLOTLY_TEMPLATE,
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_wall_finder.parameters import (
CZWallFinderParameters,
)
from bragi_quantum.experiments.utils.dataset_utils import as_dataset
# Reported wall amplitude when no wall is detected: "no restriction found",
# rather than a specific onset. Mirrors tergite-autocalibration's hardcoded
# default of 1.0.
NO_WALL_FOUND = 1.0
[docs]
def find_wall_amplitude(amplitudes: np.ndarray, magnitudes: np.ndarray) -> float:
"""
The amplitude at which ``magnitudes`` first drops below its own sweep
mean, scanning from the highest amplitude down -- the onset of the
"wall".
A wall is only searched for if the sweep shows a clear rise from its
first two points to its last three (more than 3 standard deviations of
the first two points' spread); flat/noisy sweeps report
:data:`NO_WALL_FOUND`.
"""
if magnitudes.size == 0:
raise ValueError("magnitude array is empty")
beginning = np.mean(magnitudes[:2])
deviation = np.std(magnitudes[:2])
end = np.mean(magnitudes[-3:])
mean = np.mean(magnitudes)
if end < beginning + 3 * deviation:
return NO_WALL_FOUND
for i in range(len(magnitudes)):
if magnitudes[-i - 1] < mean:
return float(amplitudes[-i - 1])
return NO_WALL_FOUND
[docs]
class CZWallFinderAnalysis(Analysis):
"""
Finds each coupler's CZ wall amplitude -- the lower of its two qubits'
wall amplitudes -- from a single-frequency amplitude sweep.
"""
element_kind = "coupler"
parameters: CZWallFinderParameters
def __init__(self, parameters, qoi_cls=None, **kwargs):
super().__init__(parameters, qoi_cls, **kwargs)
self.q1_name = ""
self.q2_name = ""
self.q1_amplitudes = None
self.q2_amplitudes = None
self.q1_magnitudes = None
self.q2_magnitudes = None
self.q1_wall = NO_WALL_FOUND
self.q2_wall = NO_WALL_FOUND
[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_amplitude_response(self, qubit: str) -> tuple[np.ndarray, np.ndarray]:
"""The (amplitudes, |S21|) 1-D sweep for one qubit, at its single
(fixed) CZ pulse frequency point."""
da = self.dataset[qubit]
freq_coord = f"{qubit}_cz_pulse_frequencies"
amp_coord = f"{qubit}_cz_pulse_amplitudes"
s21 = da.isel(ReIm=0) + 1j * da.isel(ReIm=1)
if freq_coord in s21.dims:
s21 = s21.isel({freq_coord: 0})
magnitudes = np.abs(s21).transpose(amp_coord)
return magnitudes.coords[amp_coord].values, magnitudes.values
[docs]
@override
def compute_qoi(self) -> BaseQoi:
self.q1_amplitudes, self.q1_magnitudes = self._qubit_amplitude_response(
self.q1_name
)
self.q2_amplitudes, self.q2_magnitudes = self._qubit_amplitude_response(
self.q2_name
)
self.q1_wall = find_wall_amplitude(self.q1_amplitudes, self.q1_magnitudes)
self.q2_wall = find_wall_amplitude(self.q2_amplitudes, self.q2_magnitudes)
wall = min(self.q1_wall, self.q2_wall)
logger.info(f"Wall found at {wall:.3f} fullscale for coupler {self.coupler}")
return self.qoi_cls(is_successful=True, coupler_wall_amplitude=wall)
# ------------------------------------------------------------------
# Plotting (plotly)
# ------------------------------------------------------------------
def _panel_data(self):
"""(qubit name, amplitudes, magnitudes, wall amplitude) per panel."""
return [
(self.q1_name, self.q1_amplitudes, self.q1_magnitudes, self.q1_wall),
(self.q2_name, self.q2_amplitudes, self.q2_magnitudes, self.q2_wall),
]
[docs]
@override
def add_traces(self, fig, row: int = 1, col: int = 1) -> None:
"""Draw both qubits' amplitude sweeps side by side at (row, col) and (row, col+1)."""
legend = row == 1 and col == 1
for offset, (qubit, amplitudes, magnitudes, wall) in enumerate(
self._panel_data()
):
c = col + offset
fig.add_trace(
go.Scatter(
x=amplitudes,
y=magnitudes,
mode="lines+markers",
line={"color": "royalblue"},
name=f"{qubit} |S21|",
showlegend=legend,
),
row=row,
col=c,
)
if wall < np.max(amplitudes):
fig.add_vline(
x=wall,
line={"color": "green", "dash": "dash"},
row=row,
col=c,
)
label_box(
fig,
f"Wall: {wall:.3f} fullscale",
row=row,
col=c,
x=0.02,
y=0.98,
xanchor="left",
yanchor="top",
align="left",
)
fig.update_xaxes(
title_text="CZ pulse amplitude (fullscale)", row=row, col=c
)
fig.update_yaxes(title_text="Magnitude", row=row, col=c)
@override
def _render_figure(self, fig, plot_name: str) -> None:
make_subplots(
rows=1,
cols=2,
subplot_titles=[self.q1_name, self.q2_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": 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 = [title for w in workers for title in (w.q1_name, w.q2_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 + 40,
height=nrows * 430 + 90,
margin={"t": 90, "b": 40},
)