Source code for bragi_quantum.experiments.nodes.readout.ro_combined_optimization.analysis

# ══════════════════════════════════════════════════════════════════════════
#     ___   ___ ___   _      _   ___
#    / _ \ / __|_  ) | |    /_\ | _ )
#   | (_) | (__ / /  | |__ / _ \| _ \
#    \__\_\\___/___| |____/_/ \_\___/
#
#   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:
#
#   Adrián Navarro Fuentes, adrianfu@chalmers.se
#   Matteo Robbiati, robbiati@chalmers.se
#   Axel Andersson, axean@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


"""
Analysis classes for readout combined amplitude and frequency optimisation.

For each (amplitude, frequency) pair in the 2-D sweep, an LDA classifier is
fitted to the single-shot IQ cloud (states |0> and |1>, or |0>, |1>, |2>).
The optimal (amplitude, frequency) pair 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 "frequencies" → frequency sweep axis
    - one coord whose name contains "state"        → prepared qubit state
    - one coord whose name contains "loops"        → individual shot index
"""

from typing import override

import numpy as np
import plotly.colors as pcolors
import plotly.graph_objects as go
from numpy.linalg import inv
from plotly.subplots import make_subplots
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 (
    PLOTLY_TEMPLATE,
    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_combined_optimization.parameters import (
    ROThreeStateCombinedOptimizationQOI,
    ROTwoStateCombinedOptimizationQOI,
)
from bragi_quantum.experiments.utils.analysis_field_utils import (
    centered_index_selector,
    parse_index_selector,
)


[docs] class ROCombinedOptimizationAnalysis(Analysis): """Shared per-qubit LDA machinery for RO combined amplitude/frequency optimisation (unified, plotly). Replaces the former ``ROCombinedOptimizationQubitAnalysis`` + ``RO{Two,Three}StateCombinedOptimizationNodeAnalysis``. Subclasses (``ROTwoStateCombinedOptimizationAnalysis`` / ``ROThreeStateCombinedOptimizationAnalysis``) 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.frequency_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: if "ro_amplitudes" in coord: self.amplitude_coord = coord self.amplitudes = self.S21.coords[coord] self.number_of_amplitudes = self.amplitudes.size elif "ro_frequencies" in coord: self.frequency_coord = coord self.frequencies = self.S21.coords[coord] self.number_of_frequencies = self.frequencies.size elif "qubit_states" in coord: self.state_coord = coord self.unique_qubit_states = self.S21[coord].values elif "shot_index" in coord: self.shot_coord = coord if self.amplitude_coord is None: raise ValueError( f"No 'amplitudes' coordinate found in {list(self.S21[self.data_var].coords)}" ) if self.frequency_coord is None: raise ValueError( f"No 'frequencies' 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, amp_index: int, freq_index: int) -> np.ndarray: """Extract (N_shots, 2) IQ array for the given amplitude and frequency indices.""" iq_complex = self.S21_stacked[self.data_var].isel( {self.amplitude_coord: amp_index, self.frequency_coord: freq_index} ) return np.array([iq_complex.real.values, iq_complex.imag.values]).T
[docs] def run_initial_fitting(self): """Fit LDA for every (amplitude, frequency) pair and record fidelity + confusion matrix. store_covariance is skipped during the scan and only used when the optimal cell is re-fitted in compute_qoi. """ n_states = len(self.unique_qubit_states) states_sent = self.qubit_states n_amp = self.number_of_amplitudes n_freq = self.number_of_frequencies self.fidelities = np.zeros((n_amp, n_freq)) self.cms = [[None] * n_freq for _ in range(n_amp)] for ai in range(n_amp): for fi in range(n_freq): lda = LinearDiscriminantAnalysis(solver="svd", store_covariance=False) iq = self.IQ(ai, fi) classified = lda.fit(iq, states_sent).predict(iq) cm_norm = confusion_matrix(states_sent, classified, normalize="true") self.fidelities[ai, fi] = np.trace(cm_norm) / n_states self.cms[ai][fi] = cm_norm # self.lda is initialised here; it will be re-fitted on the optimal cell # inside compute_qoi (with store_covariance=True) before use. self.lda = LinearDiscriminantAnalysis(solver="svd", store_covariance=True) flat_idx = int(np.argmax(self.fidelities)) self.optimal_amp_index, self.optimal_freq_index = np.unravel_index( flat_idx, self.fidelities.shape ) self.optimal_amplitude = float(self.amplitudes.values[self.optimal_amp_index]) self.optimal_frequency = float(self.frequencies.values[self.optimal_freq_index]) self.optimal_inv_cm = inv( self.cms[self.optimal_amp_index][self.optimal_freq_index] ) # Frequency sweep is always centred on the nominal → exact recovery. self.ref_frequency = ( float(self.frequencies.values[0]) + float(self.frequencies.values[-1]) ) / 2 # Amplitude: in relative mode recover from sweep; in absolute mode read # the current device value from Redis (falls back to None in tests). p = self.parameters if p.amplitude_lower_fraction != p.amplitude_upper_fraction: self.ref_amplitude = ( float(self.amplitudes.values[0]) / p.amplitude_lower_fraction ) else: try: transmon = ActiveSession.get().device.elements[self.qubit] self.ref_amplitude = float(transmon.measure.pulse_amp) except Exception: self.ref_amplitude = None
# ------------------------------------------------------------------ # Main plot: fidelity heatmap vs (amplitude, frequency) # ------------------------------------------------------------------ def _fidelity_colorscale(self): """Non-linear Viridis colorscale spanning the actual fidelity range. Coarse bins from the data minimum to 0.8, then fine 0.5%-step bins from 0.8 to the data maximum — the high-fidelity region gets more colour resolution without wasting range on absent values. """ fmin = float(np.min(self.fidelities)) fmax = float(np.max(self.fidelities)) threshold = 0.8 coarse = np.linspace(fmin, min(threshold, fmax), 5) if fmax > threshold: fine = np.arange(threshold, fmax + 0.005, 0.005) fine = fine[fine <= fmax + 1e-9] fine[-1] = fmax levels = np.unique(np.concatenate([coarse, fine])).tolist() else: levels = coarse.tolist() zmin, zmax = levels[0], levels[-1] if zmax <= zmin: zmax = zmin + 1e-6 colors = pcolors.sample_colorscale("Viridis", np.linspace(0, 1, len(levels))) colorscale = [[(lv - zmin) / (zmax - zmin), c] for lv, c in zip(levels, colors)] return colorscale, zmin, zmax
[docs] @override def add_traces( self, fig, row: int = 1, col: int = 1, _coloraxis: "str | None" = None ) -> None: legend = row == 1 and col == 1 colorscale, zmin, zmax = self._fidelity_colorscale() if _coloraxis is not None: heatmap = go.Heatmap( z=self.fidelities, x=self.frequencies.values / 1e9, y=self.amplitudes.values, coloraxis=_coloraxis, ) else: heatmap = go.Heatmap( z=self.fidelities, x=self.frequencies.values / 1e9, y=self.amplitudes.values, colorscale=colorscale, zmin=zmin, zmax=zmax, colorbar={"title": "Fidelity", "thickness": 12, "len": 0.9}, showscale=True, ) fig.add_trace(heatmap, row=row, col=col) fig.add_trace( go.Scatter( x=[self.optimal_frequency / 1e9], y=[self.optimal_amplitude], mode="markers", marker={ "symbol": "star", "size": 14, "color": "red", "line": {"color": "black", "width": 1}, }, name="Optimal point", showlegend=legend, ), row=row, col=col, ) label = ( f'<span style="color:red">★</span> Optimal point<br>' f"fidelity={np.max(self.fidelities):.4f}<br>" f"amp={self.optimal_amplitude:.4f}<br>" f"freq={self.optimal_frequency / 1e9:.4f} GHz" ) if self.ref_amplitude is not None: fig.add_trace( go.Scatter( x=[self.ref_frequency / 1e9], y=[self.ref_amplitude], mode="markers", marker={"symbol": "star", "size": 14, "color": "black"}, name="Previous point", showlegend=legend, ), row=row, col=col, ) label += ( f'<br><span style="color:black">★</span> Previous point<br>' f"amp={self.ref_amplitude:.4f}<br>" f"freq={self.ref_frequency / 1e9:.4f} GHz" ) label_box( fig, label, row=row, col=col, x=0.02, y=0.98, xanchor="left", yanchor="top", align="left", font_size=14, ) fig.update_xaxes(title_text="RO frequency (GHz)", row=row, col=col) fig.update_yaxes(title_text="RO amplitude", row=row, col=col)
def _add_iq_cloud_traces(self, _fig, _row: int, _col: int) -> None: """Add IQ cloud traces at the optimal point into a subplot cell. Subclasses override.""" raise NotImplementedError # ------------------------------------------------------------------ # Multi-row grid figure: heatmap + IQ cloud (+ confusion matrix for 3-state) # ------------------------------------------------------------------ _grid_rows_per_qubit: int = 1 @override def _render_grid_figure(self, fig: "go.Figure", ncols: int) -> None: """Multi-row grid: heatmap + IQ cloud (+ confusion matrix for 3-state).""" 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") rows_per = getattr(workers[0], "_grid_rows_per_qubit", 1) ncols = min(ncols, len(workers)) ngroups = int(np.ceil(len(workers) / ncols)) nrows = ngroups * rows_per # subplot_titles go cell-by-cell in row-major order; only the heatmap # row of each qubit block gets a title. subplot_titles = [""] * (nrows * ncols) for i, worker in enumerate(workers): group = i // ncols col_idx = i % ncols subplot_titles[group * rows_per * ncols + col_idx] = worker.plot_title() make_subplots( rows=nrows, cols=ncols, subplot_titles=subplot_titles, horizontal_spacing=0.10, vertical_spacing=max(0.03, 0.12 / nrows), figure=fig, ) coloraxis_updates = {} for i, worker in enumerate(workers): group = i // ncols col = i % ncols + 1 heatmap_row = group * rows_per + 1 # Locate this subplot's axis domains (row-major numbering, 1-based). axis_n = (heatmap_row - 1) * ncols + col xkey = "xaxis" if axis_n == 1 else f"xaxis{axis_n}" ykey = "yaxis" if axis_n == 1 else f"yaxis{axis_n}" xd = list(fig.layout[xkey].domain) yd = list(fig.layout[ykey].domain) coloraxis_id = f"coloraxis{i + 1}" colorscale, zmin, zmax = worker._fidelity_colorscale() worker.add_traces(fig, heatmap_row, col, _coloraxis=coloraxis_id) coloraxis_updates[coloraxis_id] = { "colorscale": colorscale, "cmin": zmin, "cmax": zmax, "showscale": True, "colorbar": { "x": xd[1] + 0.005, "xanchor": "left", "y": (yd[0] + yd[1]) / 2, "yanchor": "middle", "len": yd[1] - yd[0], "lenmode": "fraction", "thickness": 8, "tickfont": {"size": 11}, "outlinewidth": 0, "title": { "text": "Assignment Fidelity", "side": "right", "font": {"size": 12}, }, }, } if rows_per >= 2: worker._add_iq_cloud_traces(fig, group * rows_per + 2, col) if rows_per >= 3: worker._add_confusion_matrix_traces(fig, group * rows_per + 3, col) fig.update_layout( **coloraxis_updates, template=PLOTLY_TEMPLATE, showlegend=False, width=ncols * 480 + 60, height=ngroups * rows_per * 360 + 90, margin={"t": 90, "b": 40, "r": 60}, ) @override def _render_figure(self, fig: "go.Figure", plot_name: str) -> None: """Dispatch to the correct figure renderer based on ``plot_name``. ``"main"`` → heatmap via the default 1×1 subplot path. Any other name → calls ``_{plot_name}_figure()`` on self and merges its traces and layout into the supplied ``fig``. """ if plot_name == "main": super()._render_figure(fig, plot_name) return method = getattr(self, f"_{plot_name}_figure", None) if method is None: raise ValueError(f"Unknown plot '{plot_name}' for {type(self).__name__}") src = method() for trace in src.data: fig.add_trace(trace) fig.update_layout(src.to_dict().get("layout", {})) # ------------------------------------------------------------------ # IQ-grid support figure (shared by 2-state / 3-state; state colouring # delegated to ``_scatter_states_trace``, overridden per subclass) # ------------------------------------------------------------------ def _scatter_states_trace( self, _fig, _iq: np.ndarray, _row: int, _col: int ) -> None: """Add IQ scatter traces coloured by prepared state. Subclasses override.""" raise NotImplementedError def _add_boundary_to_cell( self, _fig, _ai: int, _fi: int, _row: int, _col: int ) -> None: """Add discrimination boundary for a single grid cell. Subclasses override.""" def _iq_grid_figure(self): """Plot IQ clouds in a scatter grid, one cell per (amplitude, frequency) pair. iq_grid_row/iq_grid_col left blank each default to a 3-wide window centred on the optimal cell (shifted inward, not shrunk, if that would run past the edge of the sweep) — explicit values show that exact subset instead. """ n_amp = self.number_of_amplitudes n_freq = self.number_of_frequencies row_selector = getattr(self.parameters, "iq_grid_row", None) col_selector = getattr(self.parameters, "iq_grid_col", None) if row_selector is None or not row_selector.strip(): row_selector = centered_index_selector(self.optimal_amp_index, n_amp) if col_selector is None or not col_selector.strip(): col_selector = centered_index_selector(self.optimal_freq_index, n_freq) amp_indices = parse_index_selector(row_selector, n_amp, "iq_grid_row") freq_indices = parse_index_selector(col_selector, n_freq, "iq_grid_col") n_amp_show = len(amp_indices) n_freq_show = len(freq_indices) # A single selected cell is a zoomed-in diagnostic view (full I/Q # ticks, boundary line); a multi-cell grid instead labels each cell # with its row/column number so it stays legible at 100+ subplots. single_cell = n_amp_show == 1 and n_freq_show == 1 all_iq = np.vstack( [self.IQ(ai, fi) for ai in amp_indices for fi in freq_indices] ) x_min, x_max = float(np.nanmin(all_iq[:, 0])), float(np.nanmax(all_iq[:, 0])) y_min, y_max = float(np.nanmin(all_iq[:, 1])), float(np.nanmax(all_iq[:, 1])) pad_x = 0.05 * (x_max - x_min) pad_y = 0.05 * (y_max - y_min) x_min -= pad_x x_max += pad_x y_min -= pad_y y_max += pad_y x_range = x_max - x_min y_range = y_max - y_min if x_range > y_range: y_centre = (y_min + y_max) / 2 y_min = y_centre - x_range / 2 y_max = y_centre + x_range / 2 else: x_centre = (x_min + x_max) / 2 x_min = x_centre - y_range / 2 x_max = x_centre + y_range / 2 fig = make_subplots( rows=n_amp_show, cols=n_freq_show, horizontal_spacing=max(0.002, 0.06 / n_freq_show), vertical_spacing=max(0.002, 0.06 / n_amp_show), column_titles=( [ f"{float(self.frequencies.values[fi]) / 1e6:.2f} MHz" for fi in freq_indices ] if not single_cell else None ), ) for ann in fig.layout.annotations: ann.font = {"size": 9} for r_idx, ai in enumerate(amp_indices): for c_idx, fi in enumerate(freq_indices): row, col = r_idx + 1, c_idx + 1 self._scatter_states_trace(fig, self.IQ(ai, fi), row, col) if single_cell: self._add_boundary_to_cell(fig, ai, fi, row, col) fig.add_annotation( row=row, col=col, xref="x domain", yref="y domain", x=0.05, y=0.99, xanchor="left", yanchor="top", showarrow=False, text=f"F={self.fidelities[ai, fi]:.3f}", font={"size": 10}, bgcolor="rgba(255,255,255,0.6)", borderpad=2, ) if not single_cell: fig.add_annotation( row=row, col=col, xref="x domain", yref="y domain", x=0.95, y=0.05, xanchor="right", yanchor="bottom", showarrow=False, text=f"R{ai + 1}C{fi + 1}", font={"size": 9}, bgcolor="rgba(255,255,255,0.6)", borderpad=1, ) fig.update_xaxes( range=[x_min, x_max], row=row, col=col, showticklabels=single_cell, ticks="outside" if single_cell else "", ) # Left-column axis title (not a tick label) marks each row's # amplitude — the usual y-axis position, unaffected by # showticklabels below. single_cell labels its one cell's # axes "I"/"Q" instead (see below), so it's excluded here. fig.update_yaxes( range=[y_min, y_max], row=row, col=col, showticklabels=single_cell, ticks="outside" if single_cell else "", title_text=( f"{float(self.amplitudes.values[ai]):.3g}" if col == 1 and not single_cell else None ), title_font={"size": 9}, ) if ai == self.optimal_amp_index and fi == self.optimal_freq_index: fig.add_shape( type="rect", xref="x domain", yref="y domain", x0=0, x1=1, y0=0, y1=1, row=row, col=col, line={"color": "gold", "width": 3}, ) for r_idx in range(n_amp_show): for c_idx in range(n_freq_show): idx = r_idx * n_freq_show + c_idx + 1 xaxis_key = "xaxis" if idx == 1 else f"xaxis{idx}" yaxis_key = "yaxis" if idx == 1 else f"yaxis{idx}" x_ref = "x" if idx == 1 else f"x{idx}" if idx > 1: fig.layout[xaxis_key].matches = "x" fig.layout[yaxis_key].matches = "y" fig.layout[yaxis_key].update( scaleanchor=x_ref, scaleratio=1, constrain="domain" ) if single_cell: fig.update_xaxes(tickangle=-35, title_text="I", row=n_amp_show) fig.update_yaxes(title_text="Q", col=1) width = height = 380 amp_val = float(self.amplitudes.values[amp_indices[0]]) freq_val = float(self.frequencies.values[freq_indices[0]]) / 1e6 title = ( f"Qubit {self.qubit} — A={amp_val:.3g}, " f"f={freq_val:.2f} MHz — IQ cloud (gold border = optimal)" ) else: # Scale cell size to the number of columns shown, but cap at 250px # so a 2×2 selection stays reasonable and never exceeds 1000px wide. cell_size = min(250, 1000 // n_freq_show) width = max(cell_size * n_freq_show, 300) # For few rows the natural cell size can be very flat (e.g. 2×6 → # 166px cells). Enforce a 200px floor per cell when ≤3 rows so the # figure stays readable without affecting taller grids. cell_h = max(cell_size, 200) if n_amp_show <= 3 else cell_size height = max(cell_h * n_amp_show, 300) title = f"Qubit {self.qubit} — IQ clouds (gold border = optimal)" # Neither axis repeats its unit per cell (frequency's column # titles are bare "... MHz", amplitude's are bare numbers) — name # each axis once instead. Amplitude sits left of its values, # rotated to match their (default) vertical orientation; # frequency sits above its values, matching their horizontal one. fig.add_annotation( xref="paper", yref="paper", x=0, y=0.5, xanchor="right", yanchor="middle", xshift=-55, textangle=-90, showarrow=False, text="RO Amplitude", font={"size": 9}, ) fig.add_annotation( xref="paper", yref="paper", x=0.5, y=1, xanchor="center", yanchor="bottom", yshift=22, showarrow=False, text="RO Frequency", font={"size": 9}, ) fig.add_annotation( xref="paper", yref="paper", x=0.5, y=0, xanchor="center", yanchor="top", yshift=-28, showarrow=False, text=( "Every sub-plot is an IQ cloud, annotated with fidelity " "(top-left) and its row-column number (bottom-right)." ), font={"size": 9}, ) fig.update_layout(margin={"l": 110, "t": 120}) # Echo the row/col selection actually used (explicit or defaulted) # back to callers — bragi_quantum.gui's reanalyse form reads this to show the # effective iq_grid_row/iq_grid_col instead of leaving them blank. fig.update_layout( meta={"iq_grid_row": row_selector, "iq_grid_col": col_selector} ) style_layout( fig, width=width, height=height, title=title, ) return fig
[docs] class ROTwoStateCombinedOptimizationAnalysis(ROCombinedOptimizationAnalysis): """Optimal RO amplitude/frequency for the 2-state (|0>, |1>) discrimination. Replaces the former ``ROTwoStateCombinedOptimizationQubitAnalysis`` + ``ROTwoStateCombinedOptimizationNodeAnalysis``. """ def __init__( self, parameters, qoi_cls: "type[ROTwoStateCombinedOptimizationQOI] | 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_amp_index, self.optimal_freq_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, frequency=self.optimal_frequency, rotation=self.rotation_angle_degrees, threshold=self.threshold, fidelity=float( self.fidelities[self.optimal_amp_index, self.optimal_freq_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]), )
@override def _scatter_states_trace(self, fig, iq: np.ndarray, row: int, col: int) -> None: for state in (0, 1): mask = self.qubit_states == state fig.add_trace( go.Scatter( x=iq[mask, 0], y=iq[mask, 1], mode="markers", marker={ "size": 3, "color": STATE_COLORS[state]["tp"], "opacity": 0.4, }, showlegend=False, ), row=row, col=col, ) _grid_rows_per_qubit = 2 @override def _add_iq_cloud_traces(self, fig, row: int, col: int) -> None: all_pts = np.vstack([self.IQ0_tp, self.IQ0_fp, self.IQ1_tp, self.IQ1_fp]) xi, xa = float(all_pts[:, 0].min()), float(all_pts[:, 0].max()) yi, ya = float(all_pts[:, 1].min()), float(all_pts[:, 1].max()) dx, dy = xa - xi or 1e-6, ya - yi or 1e-6 xi -= 0.05 * dx xa += 0.05 * dx yi -= 0.05 * dy ya += 0.05 * dy dx, dy = xa - xi, ya - yi if dx > dy: cy = (yi + ya) / 2 yi, ya = cy - dx / 2, cy + dx / 2 else: cx = (xi + xa) / 2 xi, xa = cx - dy / 2, cx + dy / 2 for pts, color, symbol in [ (self.IQ0_tp, STATE_COLORS[0]["tp"], "circle"), (self.IQ1_tp, STATE_COLORS[1]["tp"], "circle"), (self.IQ0_fp, STATE_COLORS[0]["fp"], "x"), (self.IQ1_fp, STATE_COLORS[1]["fp"], "x"), ]: if len(pts): fig.add_trace( go.Scatter( x=pts[:, 0], y=pts[:, 1], mode="markers", marker={ "size": 4, "color": color, "symbol": symbol, "opacity": 0.5, }, showlegend=False, ), row=row, col=col, ) mid = self.centers.mean(axis=0) direction = np.array([1.0, self.lamda]) / np.hypot(1.0, self.lamda) proj = (all_pts - mid) @ direction pad = 0.15 * (proj.max() - proj.min()) t = np.array([proj.min() - pad, proj.max() + pad]) fig.add_trace( go.Scatter( x=mid[0] + t * direction[0], y=mid[1] + t * direction[1], mode="lines", line={"color": "purple", "width": 1.5}, showlegend=False, ), row=row, col=col, ) fig.update_xaxes(range=[xi, xa], title_text="I", row=row, col=col) fig.update_yaxes(range=[yi, ya], title_text="Q", row=row, col=col) @override def _add_boundary_to_cell(self, fig, ai: int, fi: int, row: int, col: int) -> None: iq = self.IQ(ai, fi) lda = LinearDiscriminantAnalysis(solver="svd", store_covariance=False) lda.fit(iq, self.qubit_states) b = TwoClassBoundary(lda) mid = lda.means_.mean(axis=0) direction = np.array([1.0, b.lamda]) / np.hypot(1.0, b.lamda) proj = (iq - mid) @ direction pad = 0.15 * (proj.max() - proj.min()) t = np.array([proj.min() - pad, proj.max() + pad]) fig.add_trace( go.Scatter( x=mid[0] + t * direction[0], y=mid[1] + t * direction[1], mode="lines", line={"color": "purple", "width": 1.5}, showlegend=False, ), row=row, col=col, ) 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.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.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_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": "green"}, name="LDA centers", ) ) # Compute square limits from data before drawing the boundary line so # the line endpoints stay within the padded data range. all_iq = np.vstack([self.IQ0_tp, self.IQ1_tp, self.IQ0_fp, self.IQ1_fp]) xi, xa = float(all_iq[:, 0].min()), float(all_iq[:, 0].max()) yi, ya = float(all_iq[:, 1].min()), float(all_iq[:, 1].max()) dx = xa - xi dy = ya - yi xi -= 0.05 * dx xa += 0.05 * dx yi -= 0.05 * dy ya += 0.05 * dy dx = xa - xi dy = ya - yi if dx > dy: cy = (yi + ya) / 2 yi = cy - dx / 2 ya = cy + dx / 2 else: cx = (xi + xa) / 2 xi = cx - dy / 2 xa = cx + dy / 2 # Draw the boundary line anchored at the midpoint between the two LDA # centroids and extended only as far as the data spread along the # boundary direction, so it never pushes the axes limits outward. mid = self.centers.mean(axis=0) direction = np.array([1.0, self.lamda]) / np.hypot(1.0, self.lamda) proj = (all_iq - mid) @ direction line_pad = 0.15 * (proj.max() - proj.min()) t = np.array([proj.min() - line_pad, proj.max() + line_pad]) fig.add_trace( go.Scatter( x=mid[0] + t * direction[0], y=mid[1] + t * direction[1], mode="lines", line={"color": "purple", "width": 2}, name=f"angle: {self.rotation_angle_degrees:.1f}° | threshold: {self.threshold:.4f}", ) ) fig.update_xaxes(title_text="I", range=[xi, xa]) fig.update_yaxes(title_text="Q", range=[yi, ya], scaleanchor="x", scaleratio=1) style_layout( fig, width=620, height=620, title=f"{self.parameters.name} — {self.qubit} — IQ cloud at optimal point", ) return fig
[docs] @override def list_plots(self): return ["main", "iq_cloud", "iq_grid"]
[docs] class ROThreeStateCombinedOptimizationAnalysis(ROCombinedOptimizationAnalysis): """Optimal RO amplitude/frequency for the 3-state (|0>, |1>, |2>) discrimination. Replaces the former ``ROThreeStateCombinedOptimizationQubitAnalysis`` + ``ROThreeStateCombinedOptimizationNodeAnalysis``. """ def __init__( self, parameters, qoi_cls: "type[ROThreeStateCombinedOptimizationQOI] | 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_amp_index, self.optimal_freq_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] return self.qoi_cls( is_successful=True, amplitude=self.optimal_amplitude, frequency=self.optimal_frequency, 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=self.optimal_inv_cm.flatten().tolist(), fidelity=float( self.fidelities[self.optimal_amp_index, self.optimal_freq_index] ), )
@override def _scatter_states_trace(self, fig, iq: np.ndarray, row: int, col: int) -> None: for state in (0, 1, 2): mask = self.qubit_states == state fig.add_trace( go.Scatter( x=iq[mask, 0], y=iq[mask, 1], mode="markers", marker={ "size": 3, "color": STATE_COLORS[state]["tp"], "opacity": 0.4, }, showlegend=False, ), row=row, col=col, ) _grid_rows_per_qubit = 3 @override def _add_iq_cloud_traces(self, fig, row: int, col: int) -> None: all_pts = np.vstack( [ self.IQ0_tp, self.IQ0_fp, self.IQ1_tp, self.IQ1_fp, self.IQ2_tp, self.IQ2_fp, ] ) xi, xa = float(all_pts[:, 0].min()), float(all_pts[:, 0].max()) yi, ya = float(all_pts[:, 1].min()), float(all_pts[:, 1].max()) dx, dy = xa - xi or 1e-6, ya - yi or 1e-6 xi -= 0.05 * dx xa += 0.05 * dx yi -= 0.05 * dy ya += 0.05 * dy dx, dy = xa - xi, ya - yi if dx > dy: cy = (yi + ya) / 2 yi, ya = cy - dx / 2, cy + dx / 2 else: cx = (xi + xa) / 2 xi, xa = cx - dy / 2, cx + dy / 2 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": 4, "color": STATE_COLORS[state]["tp"], "opacity": 0.5, }, showlegend=False, ), row=row, col=col, ) if len(fp): fig.add_trace( go.Scatter( x=fp[:, 0], y=fp[:, 1], mode="markers", marker={ "size": 4, "color": STATE_COLORS[state]["fp"], "symbol": "x", "opacity": 0.5, }, showlegend=False, ), row=row, col=col, ) 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": 1.5}, showlegend=False, ), row=row, col=col, ) fig.update_xaxes(range=[xi, xa], title_text="I", row=row, col=col) fig.update_yaxes(range=[yi, ya], title_text="Q", row=row, col=col) def _add_confusion_matrix_traces(self, fig, row: int, col: int) -> None: cm = self.cms[self.optimal_amp_index][self.optimal_freq_index] labels = [str(int(s)) for s in self.unique_qubit_states] fig.add_trace( go.Heatmap( z=cm, x=labels, y=labels, colorscale="Blues", zmin=0, zmax=1, showscale=False, ), row=row, col=col, ) 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", "size": 10}, row=row, col=col, ) fig.update_xaxes(title_text="Predicted", row=row, col=col) fig.update_yaxes(title_text="True", autorange="reversed", row=row, col=col) @override def _add_boundary_to_cell(self, fig, ai: int, fi: int, row: int, col: int) -> None: iq = self.IQ(ai, fi) lda = LinearDiscriminantAnalysis(solver="svd", store_covariance=True) lda.fit(iq, self.qubit_states) b = ThreeClassBoundary(lda) for pair, color in [ ((0, 1), "blueviolet"), ((1, 2), "firebrick"), ((2, 0), "cyan"), ]: i_vals, q_vals = b.boundary_line(*pair) fig.add_trace( go.Scatter( x=i_vals, y=q_vals, mode="lines", line={"color": color, "width": 1.5}, showlegend=False, ), row=row, col=col, ) 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 point", ) return fig def _confusion_matrix_figure(self): cm = self.cms[self.optimal_amp_index][self.optimal_freq_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 point", ) return fig
[docs] @override def list_plots(self): return ["main", "iq_cloud", "confusion_matrix", "iq_grid"]