# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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:
#
# Matteo Robbiati, robbiati@chalmers.se
# Axel Andersson, axean@chalmers.se
# ══════════════════════════════════════════════════════════════════════════
"""
Analysis classes for readout amplitude optimisation.
For each swept RO amplitude, an LDA classifier is fitted to the single-shot IQ
cloud (states |0> and |1>, or |0>, |1>, |2>). The optimal amplitude is the one
that maximises the trace-normalised confusion-matrix diagonal (assignment fidelity).
Dataset coordinate expectations (after configure_dataset):
- one coord whose name contains "amplitudes" → amplitude sweep axis
- one coord whose name contains "state" → prepared qubit state
- one coord whose name contains "shot" → individual shot index
"""
from typing import override
import numpy as np
import plotly.graph_objects as go
from numpy.linalg import inv
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.metrics import confusion_matrix
from bragi_quantum.datalayer.managing.session import ActiveSession
from bragi_quantum.datalayer.visualization.plot_style import (
DATA_COLOR,
STATE_COLORS,
label_box,
style_layout,
)
from bragi_quantum.experiments.abstract.analysis import Analysis
from bragi_quantum.experiments.abstract.parameters import BaseQoi
from bragi_quantum.experiments.fitting_tools.models.classification import (
ThreeClassBoundary,
TwoClassBoundary,
)
from bragi_quantum.experiments.nodes.readout.ro_amplitude_optimization.parameters import (
ROThreeStateAmplitudeOptimizationQOI,
ROTwoStateAmplitudeOptimizationQOI,
)
[docs]
class ROAmplitudeOptimizationAnalysis(Analysis):
"""Shared per-qubit LDA machinery for RO amplitude optimisation (unified,
plotly).
Replaces the former ``ROAmplitudeOptimizationQubitAnalysis`` +
``RO{Two,Three}StateAmplitudeOptimizationNodeAnalysis``. Subclasses
(``ROTwoStateAmplitudeOptimizationAnalysis`` /
``ROThreeStateAmplitudeOptimizationAnalysis``) implement the
state-count-specific parts of ``fit()`` and the IQ-cloud support figure.
"""
element_kind = "qubit"
def __init__(self, parameters, qoi_cls=None, **kwargs):
super().__init__(parameters, qoi_cls, **kwargs)
self.fit_results = {}
self.amplitude_coord = None
self.state_coord = None
self.shot_coord = None
[docs]
@override
def plot_title(self) -> str:
return f"Qubit {self.element}"
# ------------------------------------------------------------------
# Coordinate extraction / shot stacking
# ------------------------------------------------------------------
def _extract_coords_and_stack(self) -> None:
for coord in self.S21[self.data_var].coords:
coord_str = str(coord)
if "amplitudes" in coord_str:
self.amplitude_coord = coord_str
self.amplitudes = self.S21.coords[coord_str]
self.number_of_amplitudes = self.amplitudes.size
elif "state" in coord_str:
self.state_coord = coord_str
self.unique_qubit_states = self.S21[coord_str].values
elif "shot" in coord_str:
self.shot_coord = coord_str
if self.amplitude_coord is None:
raise ValueError(
f"No 'amplitudes' coordinate found in {list(self.S21[self.data_var].coords)}"
)
if self.state_coord is None:
raise ValueError(
f"No 'state' coordinate found in {list(self.S21[self.data_var].coords)}"
)
if self.shot_coord is None:
raise ValueError(
f"No 'shot' coordinate found in {list(self.S21[self.data_var].coords)}"
)
self.S21_stacked = self.S21.stack(shots=[self.shot_coord, self.state_coord])
self.qubit_states = self.S21_stacked[self.state_coord].values
self.fit_results = {}
[docs]
def IQ(self, index: int) -> np.ndarray:
"""Extract (N_shots, 2) IQ array for the amplitude at position ``index``."""
iq_complex = self.S21_stacked[self.data_var].isel({self.amplitude_coord: index})
return np.array([iq_complex.real.values, iq_complex.imag.values]).T
[docs]
def run_initial_fitting(self):
"""Fit LDA for every amplitude and record fidelity + confusion matrix."""
self.fidelities = []
self.cms = []
states_sent = self.qubit_states
self.lda = LinearDiscriminantAnalysis(solver="svd", store_covariance=True)
for index, _ in enumerate(self.amplitudes):
iq = self.IQ(index)
classified = self.lda.fit(iq, states_sent).predict(iq)
cm_norm = confusion_matrix(states_sent, classified, normalize="true")
self.fidelities.append(np.trace(cm_norm) / len(self.unique_qubit_states))
self.cms.append(cm_norm)
self.optimal_index = int(np.argmax(self.fidelities))
self.optimal_amplitude = float(self.amplitudes.values[self.optimal_index])
self.optimal_inv_cm = inv(self.cms[self.optimal_index])
def _punchout_amplitude(self) -> "float | None":
"""Fetch the punchout amplitude from the active device (for plot reference)."""
try:
return float(
ActiveSession.get().device.elements[self.qubit].measure.pulse_amp
)
except Exception:
return None
# ------------------------------------------------------------------
# Main plot: assignment fidelity vs RO amplitude
# ------------------------------------------------------------------
[docs]
@override
def add_traces(self, fig, row: int = 1, col: int = 1) -> None:
punchout_amp = self._punchout_amplitude()
if punchout_amp is not None:
fig.add_vline(
x=punchout_amp,
line={"color": "black", "dash": "dot"},
row=row,
col=col,
)
fig.add_trace(
go.Scatter(
x=self.amplitudes.values,
y=self.fidelities,
mode="lines",
line={"color": DATA_COLOR},
showlegend=False,
),
row=row,
col=col,
)
fig.add_trace(
go.Scatter(
x=[self.optimal_amplitude],
y=[self.fidelities[self.optimal_index]],
mode="markers",
marker={"symbol": "star", "size": 14, "color": "red"},
showlegend=False,
),
row=row,
col=col,
)
label = (
f"opt amp = {self.optimal_amplitude:.4f}<br>"
f"fidelity = {self.fidelities[self.optimal_index]:.4f}"
)
if punchout_amp is not None:
label += f"<br>punchout = {punchout_amp:.4f}"
label_box(
fig,
label,
row=row,
col=col,
x=0.02,
y=0.02,
xanchor="left",
yanchor="bottom",
align="left",
)
fig.update_xaxes(title_text="RO amplitude", row=row, col=col)
fig.update_yaxes(title_text="Assignment fidelity", row=row, col=col)
[docs]
class ROTwoStateAmplitudeOptimizationAnalysis(ROAmplitudeOptimizationAnalysis):
"""Optimal RO amplitude for the 2-state (|0>, |1>) discrimination (unified,
plotly).
Replaces the former ``ROTwoStateAmplitudeOptimizationQubitAnalysis`` +
``ROTwoStateAmplitudeOptimizationNodeAnalysis``.
"""
def __init__(
self,
parameters,
qoi_cls: "type[ROTwoStateAmplitudeOptimizationQOI] | None" = None,
**kwargs,
):
super().__init__(parameters, qoi_cls, **kwargs)
def _align_on_y_axis(
self,
iq_points: np.ndarray,
classified: np.ndarray,
boundary_angle_rad: float,
absolute_threshold: float,
) -> "tuple[np.ndarray, float, float]":
"""Rotate IQ so |0> is on I<0 and |1> is on I>0 (Thresholded Acquisition convention)."""
rot = np.pi / 2 - boundary_angle_rad
R = np.array([[np.cos(rot), -np.sin(rot)], [np.sin(rot), np.cos(rot)]])
mirror = np.array(
[[np.cos(np.pi), -np.sin(np.pi)], [np.sin(np.pi), np.cos(np.pi)]]
)
rotated = iq_points @ R.T
c0 = np.mean(rotated[classified == 0, 0])
c1 = np.mean(rotated[classified == 1, 0])
if c0 > c1:
rot += np.pi
rotated = rotated @ mirror.T
c0 = np.mean(rotated[classified == 0, 0])
c1 = np.mean(rotated[classified == 1, 0])
threshold = (
absolute_threshold if c0 < absolute_threshold < c1 else -absolute_threshold
)
if not c0 < threshold < c1:
raise ValueError("Threshold is at an improper value.")
return rotated, rot, threshold
[docs]
@override
def compute_qoi(self) -> BaseQoi:
self._extract_coords_and_stack()
self.run_initial_fitting()
states = self.qubit_states
opt_iq = self.IQ(self.optimal_index)
classified = self.lda.fit(opt_iq, states).predict(opt_iq)
correct = states == classified
tp0 = correct[states == 0]
tp1 = correct[states == 1]
IQ0 = opt_iq[states == 0]
IQ1 = opt_iq[states == 1]
boundary = TwoClassBoundary(self.lda)
self.theta_rad = boundary.theta_rad
self.y_intercept = float(boundary.y_intercept)
self.absolute_threshold = boundary.threshold
self.centers = boundary.centers
self.lamda = boundary.lamda
aligned_iq, rotation_angle_rad, threshold = self._align_on_y_axis(
opt_iq, classified, self.theta_rad, self.absolute_threshold
)
self.threshold = threshold
self.rotation_angle_degrees = float(np.rad2deg(rotation_angle_rad))
self.rotated_IQ0_tp = aligned_iq[states == 0][tp0]
self.rotated_IQ0_fp = aligned_iq[states == 0][~tp0]
self.rotated_IQ1_tp = aligned_iq[states == 1][tp1]
self.rotated_IQ1_fp = aligned_iq[states == 1][~tp1]
self.IQ0_tp = IQ0[tp0]
self.IQ0_fp = IQ0[~tp0]
self.IQ1_tp = IQ1[tp1]
self.IQ1_fp = IQ1[~tp1]
x_min = min(opt_iq[:, 0].min(), 0)
x_max = max(opt_iq[:, 0].max(), 0)
y_min = min(opt_iq[:, 1].min(), 0)
y_max = max(opt_iq[:, 1].max(), 0)
delta = max(x_max - x_min, y_max - y_min)
cd = float(np.linalg.norm(self.centers[0] - self.centers[1]))
self.x_limits = (x_min - cd / 2, x_min + delta + cd / 2)
self.y_limits = (y_min - cd / 2, y_min + delta + cd / 2)
self.x_space = np.linspace(opt_iq[:, 0].min(), opt_iq[:, 0].max(), 100)
return self.qoi_cls(
is_successful=True,
amplitude=self.optimal_amplitude,
rotation=self.rotation_angle_degrees,
threshold=self.threshold,
fidelity=float(self.fidelities[self.optimal_index]),
lda_coef_0=float(self.lda.coef_[0][0]),
lda_coef_1=float(self.lda.coef_[0][1]),
lda_intercept=float(self.lda.intercept_[0]),
center_I_0=float(self.centers[0][0]),
center_Q_0=float(self.centers[0][1]),
center_I_1=float(self.centers[1][0]),
center_Q_1=float(self.centers[1][1]),
)
def _iq_cloud_figure(self):
fig = go.Figure()
mark_size = 7
fig.add_trace(
go.Scatter(
x=self.IQ0_tp[:, 0],
y=self.IQ0_tp[:, 1],
mode="markers",
marker={"size": mark_size, "color": "blue"},
name="send 0 → read 0",
)
)
fig.add_trace(
go.Scatter(
x=self.IQ0_fp[:, 0],
y=self.IQ0_fp[:, 1],
mode="markers",
marker={"size": mark_size, "color": "dodgerblue", "symbol": "x"},
name="send 0 → read 1 (error)",
)
)
fig.add_trace(
go.Scatter(
x=self.IQ1_tp[:, 0],
y=self.IQ1_tp[:, 1],
mode="markers",
marker={"size": mark_size, "color": "red"},
name="send 1 → read 1",
)
)
fig.add_trace(
go.Scatter(
x=self.IQ1_fp[:, 0],
y=self.IQ1_fp[:, 1],
mode="markers",
marker={"size": mark_size, "color": "orange", "symbol": "x"},
name="send 1 → read 0 (error)",
)
)
fig.add_trace(
go.Scatter(
x=self.centers[:, 0],
y=self.centers[:, 1],
mode="markers",
marker={"size": 10, "color": "brown"},
name="LDA centers",
)
)
fig.add_trace(
go.Scatter(
x=[0],
y=[self.y_intercept],
mode="markers",
marker={"size": 10, "color": "black", "symbol": "cross"},
name="y-intercept",
)
)
fig.add_trace(
go.Scatter(
x=self.x_space,
y=self.lamda * self.x_space + self.y_intercept,
mode="lines",
line={"color": DATA_COLOR, "width": 2},
name=f"angle: {self.rotation_angle_degrees:.1f}°",
)
)
fig.add_hline(y=0, line={"color": "black", "width": 1})
fig.add_vline(x=0, line={"color": "black", "width": 1})
fig.update_xaxes(title_text="I", range=list(self.x_limits))
fig.update_yaxes(
title_text="Q", range=list(self.y_limits), scaleanchor="x", scaleratio=1
)
style_layout(
fig,
width=620,
height=620,
title=f"{self.parameters.name} — {self.qubit} — IQ cloud at optimal amplitude",
)
return fig
def _rotated_iq_figure(self):
fig = go.Figure()
mark_size = 7
fig.add_trace(
go.Scatter(
x=self.rotated_IQ0_tp[:, 0],
y=self.rotated_IQ0_tp[:, 1],
mode="markers",
marker={"size": mark_size, "color": "blue"},
name="send 0 → read 0",
)
)
fig.add_trace(
go.Scatter(
x=self.rotated_IQ0_fp[:, 0],
y=self.rotated_IQ0_fp[:, 1],
mode="markers",
marker={"size": mark_size, "color": "dodgerblue", "symbol": "x"},
name="send 0 → read 1 (error)",
)
)
fig.add_trace(
go.Scatter(
x=self.rotated_IQ1_tp[:, 0],
y=self.rotated_IQ1_tp[:, 1],
mode="markers",
marker={"size": mark_size, "color": "red"},
name="send 1 → read 1",
)
)
fig.add_trace(
go.Scatter(
x=self.rotated_IQ1_fp[:, 0],
y=self.rotated_IQ1_fp[:, 1],
mode="markers",
marker={"size": mark_size, "color": "orange", "symbol": "x"},
name="send 1 → read 0 (error)",
)
)
fig.add_vline(
x=self.threshold,
line={"color": "purple", "width": 3},
annotation_text=f"threshold: {self.threshold:.4f}",
)
fig.add_hline(y=0, line={"color": "black", "width": 1})
fig.add_vline(x=0, line={"color": "black", "width": 1})
fig.update_xaxes(title_text="I (rotated)")
fig.update_yaxes(title_text="Q (rotated)", scaleanchor="x", scaleratio=1)
style_layout(
fig,
width=620,
height=620,
title=f"{self.parameters.name} — {self.qubit} — rotated IQ / threshold",
)
return fig
[docs]
class ROThreeStateAmplitudeOptimizationAnalysis(ROAmplitudeOptimizationAnalysis):
"""Optimal RO amplitude for the 3-state (|0>, |1>, |2>) discrimination
(unified, plotly).
Replaces the former ``ROThreeStateAmplitudeOptimizationQubitAnalysis`` +
``ROThreeStateAmplitudeOptimizationNodeAnalysis``.
"""
def __init__(
self,
parameters,
qoi_cls: "type[ROThreeStateAmplitudeOptimizationQOI] | None" = None,
**kwargs,
):
super().__init__(parameters, qoi_cls, **kwargs)
[docs]
@override
def compute_qoi(self) -> BaseQoi:
self._extract_coords_and_stack()
self.run_initial_fitting()
y = self.qubit_states
opt_iq = self.IQ(self.optimal_index)
self.lda.fit(opt_iq, y)
self.boundary = ThreeClassBoundary(self.lda)
self.centroid_I, self.centroid_Q = self.boundary.centroid
self.omega_01 = self.boundary.omega_01
self.omega_12 = self.boundary.omega_12
self.omega_20 = self.boundary.omega_20
opt_classified = self.lda.predict(opt_iq)
correct = y == opt_classified
self.IQ0_tp = opt_iq[(y == 0) & correct]
self.IQ0_fp = opt_iq[(y == 0) & ~correct]
self.IQ1_tp = opt_iq[(y == 1) & correct]
self.IQ1_fp = opt_iq[(y == 1) & ~correct]
self.IQ2_tp = opt_iq[(y == 2) & correct]
self.IQ2_fp = opt_iq[(y == 2) & ~correct]
inv_cm_str = ",".join(str(e) for e in self.optimal_inv_cm.flatten().tolist())
return self.qoi_cls(
is_successful=True,
amplitude=self.optimal_amplitude,
centroid_I=float(self.centroid_I),
centroid_Q=float(self.centroid_Q),
omega_01=float(self.omega_01),
omega_12=float(self.omega_12),
omega_20=float(self.omega_20),
inv_cm_opt=inv_cm_str,
fidelity=float(self.fidelities[self.optimal_index]),
)
def _iq_cloud_figure(self):
fig = go.Figure()
mark_size = 7
for state, tp, fp in (
(0, self.IQ0_tp, self.IQ0_fp),
(1, self.IQ1_tp, self.IQ1_fp),
(2, self.IQ2_tp, self.IQ2_fp),
):
fig.add_trace(
go.Scatter(
x=tp[:, 0],
y=tp[:, 1],
mode="markers",
marker={"size": mark_size, "color": STATE_COLORS[state]["tp"]},
name=f"send {state} → read {state}",
)
)
for state, tp, fp in (
(0, self.IQ0_tp, self.IQ0_fp),
(1, self.IQ1_tp, self.IQ1_fp),
(2, self.IQ2_tp, self.IQ2_fp),
):
fig.add_trace(
go.Scatter(
x=fp[:, 0],
y=fp[:, 1],
mode="markers",
marker={
"size": mark_size,
"color": STATE_COLORS[state]["fp"],
"symbol": "x",
},
showlegend=False,
)
)
for pair, color in [
((0, 1), "blueviolet"),
((1, 2), "firebrick"),
((2, 0), "cyan"),
]:
i_vals, q_vals = self.boundary.boundary_line(*pair)
fig.add_trace(
go.Scatter(
x=i_vals,
y=q_vals,
mode="lines",
line={"color": color, "width": 3},
showlegend=False,
)
)
fig.add_trace(
go.Scatter(
x=[self.centroid_I],
y=[self.centroid_Q],
mode="markers",
marker={"symbol": "star", "size": 16, "color": "black"},
name="centroid",
)
)
fig.update_xaxes(title_text="I")
fig.update_yaxes(title_text="Q", scaleanchor="x", scaleratio=1)
style_layout(
fig,
width=620,
height=620,
title=f"{self.parameters.name} — {self.qubit} — IQ cloud at optimal amplitude",
)
return fig
def _confusion_matrix_figure(self):
cm = self.cms[self.optimal_index]
labels = [str(int(s)) for s in self.unique_qubit_states]
fig = go.Figure(
data=go.Heatmap(
z=cm,
x=labels,
y=labels,
colorscale="Blues",
zmin=0,
zmax=1,
colorbar={"title": "Fraction"},
)
)
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
fig.add_annotation(
x=labels[j],
y=labels[i],
text=f"{cm[i, j]:.2f}",
showarrow=False,
font={"color": "white" if cm[i, j] > 0.5 else "black"},
)
fig.update_xaxes(title_text="Predicted label")
fig.update_yaxes(title_text="True label", autorange="reversed")
style_layout(
fig,
width=420,
height=420,
title=f"{self.parameters.name} — {self.qubit} — confusion matrix at optimal amplitude",
)
return fig