Source code for bragi_quantum.experiments.nodes.readout.punchout.circularity

# ══════════════════════════════════════════════════════════════════════════
#     ___   ___ ___   _      _   ___
#    / _ \ / __|_  ) | |    /_\ | _ )
#   | (_) | (__ / /  | |__ / _ \| _ \
#    \__\_\\___/___| |____/_/ \_\___/
#
#   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:
#
#   Axel Andersson, axean@chalmers.se
#   Joel Sandås, joel.sandas@chalmers.se
#   Matteo Robbiati, robbiati@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


"""
IQ-cloud circularity tools for the punchout node's circularity end point
(``PunchoutParameters.bin_mode="append"``).

A cloud is the set of single-shot (I, Q) readings taken at one readout
amplitude, at that amplitude's fitted resonator dip. While the readout stays
in the linear regime the cloud is round; once it starts discriminating qubit
states it stretches, which also biases the resonator fit.
"""

import numpy as np
import plotly.graph_objects as go
import xarray as xr
from plotly.subplots import make_subplots
from scipy.stats import chi2 as chi2_dist

from bragi_quantum.datalayer.utils.logging import logger
from bragi_quantum.datalayer.visualization.plot_style import (
    DATA_COLOR,
    label_box,
    style_layout,
)


def _fit_ellipse(
    iq_shots: np.ndarray,
) -> tuple[np.ndarray | None, np.ndarray | None]:
    """Fit a bivariate Gaussian to IQ shots and return the mean and covariance.

    Returns (None, None) when the fit is not possible (too few points,
    non-finite covariance, or non-positive eigenvalues).
    """
    if iq_shots.shape[0] < 3:
        return None, None
    cov = np.cov(iq_shots.T)
    if not np.all(np.isfinite(cov)) or np.linalg.eigvalsh(cov)[0] <= 0:
        return None, None
    return iq_shots.mean(axis=0), cov


def _ellipse_xy(
    mean: np.ndarray, cov: np.ndarray, confidence: float = 0.99, n_points: int = 100
) -> tuple[np.ndarray, np.ndarray]:
    """Return (x, y) boundary points of a confidence ellipse for a plotly trace."""
    eigenvalues, eigenvectors = np.linalg.eigh(cov)
    theta = np.linspace(0, 2 * np.pi, n_points)
    circle = np.column_stack([np.cos(theta), np.sin(theta)])
    scale = np.sqrt(chi2_dist.ppf(confidence, df=2))
    points = (circle * scale * np.sqrt(eigenvalues)) @ eigenvectors.T + mean
    return points[:, 0], points[:, 1]


[docs] def iq_clouds_at_dip( raw_dataset: xr.Dataset, data_var: str, amplitude_coord: str, frequency_coord: str, amplitudes: list[float], resonator_analyses: list, ) -> list[np.ndarray | None]: """Return the (N, 2) single-shot IQ cloud at each amplitude's resonator dip. The dip is the minimum-|S21| frequency bin of that amplitude's resonator fit (``ana.min_freq_data``). An entry is ``None`` where the fit failed or the shots could not be selected, so callers can skip that amplitude. """ clouds: list[np.ndarray | None] = [] for amplitude, analysis in zip(amplitudes, resonator_analyses): try: shots = raw_dataset[data_var].sel( {amplitude_coord: amplitude, frequency_coord: analysis.min_freq_data} ) clouds.append( np.column_stack( [ shots.isel(ReIm=0).values.ravel(), shots.isel(ReIm=1).values.ravel(), ] ) ) except Exception: clouds.append(None) return clouds
[docs] def compute_circularities(clouds: list[np.ndarray | None]) -> list[float]: """Circularity of each IQ cloud: min/max covariance eigenvalue. 1.0 is a perfectly round (isotropic) cloud and 0.0 a fully elongated one; ``nan`` marks a cloud that is missing or too degenerate to fit. """ circularities = [] for cloud in clouds: _, cov = _fit_ellipse(cloud) if cloud is not None else (None, None) if cov is None: circularities.append(float("nan")) else: low, high = np.linalg.eigvalsh(cov) # sorted ascending circularities.append(float(low / high)) return circularities
[docs] def find_endpoint_by_circularity( detected_amplitudes: list[float], detected_frequencies: list, circularities: list[float], circularity_threshold: float, qubit: str, ) -> tuple[int | None, float | None, float | None]: """Return the last (index, amplitude, frequency) before circularity drops. Considers *all* amplitudes, so a transient dip in circularity (noise) does not end the search early: the end point is the highest amplitude still at or above *circularity_threshold* — more power is better as long as the readout stays in the linear regime. Falls back to the highest available circularity when nothing reaches the threshold, and returns (None, None, None) when no amplitude has a usable fit at all. """ candidates = [ (index, amplitude, frequency, circularity) for index, (amplitude, frequency, circularity) in enumerate( zip(detected_amplitudes, detected_frequencies, circularities) ) if amplitude > 0 and not np.isnan(circularity) and not np.isnan(frequency.nominal_value) ] if not candidates: logger.warning( f"Punchout analysis for qubit {qubit}: " "no positive amplitude with valid circularity and frequency found. " "Check the dataset and amplitude sweep range." ) return None, None, None circular = [c for c in candidates if c[3] >= circularity_threshold] if circular: index, amplitude, frequency, _ = max(circular, key=lambda c: c[1]) after = [ (a, c) for a, c in zip( detected_amplitudes[index + 1 :], circularities[index + 1 :] ) if not np.isnan(c) ] if after: logger.info( f"Punchout analysis for qubit {qubit}: circularity permanently " f"dropped below threshold {circularity_threshold:.3f} at amplitude " f"{after[0][0]:.4f} fullscale (circularity {after[0][1]:.3f})." ) else: index, amplitude, frequency, best = max(candidates, key=lambda c: c[3]) logger.warning( f"Punchout analysis for qubit {qubit}: no amplitude found with " f"circularity above threshold {circularity_threshold:.3f}. Selecting " f"amplitude {amplitude:.4f} fullscale with the highest available circularity " f"{best:.3f} ({circularity_threshold - best:.3f} below threshold)." ) return index, amplitude, frequency
[docs] def circularity_figure( amplitudes: list[float], circularities: list[float], circularity_threshold: float, end_point_index: int | None, ): """Standalone circularity-vs-amplitude chart: the threshold line and, if an end point was found, a green star marking it.""" valid = [i for i, c in enumerate(circularities) if not np.isnan(c)] if not valid: return None fig = go.Figure() fig.add_trace( go.Scatter( x=[amplitudes[i] for i in valid], y=[circularities[i] for i in valid], mode="lines+markers", line={"color": DATA_COLOR, "width": 1.5}, marker={"size": 6}, showlegend=False, ) ) fig.add_hline( y=circularity_threshold, line={"color": "black", "dash": "dash"}, annotation_text=f"threshold ({circularity_threshold * 100:.3g}%)", ) if end_point_index is not None: amplitude = amplitudes[end_point_index] circularity = circularities[end_point_index] fig.add_trace( go.Scatter( x=[amplitude], y=[circularity], mode="markers", marker={"color": "green", "symbol": "star", "size": 14}, showlegend=False, ) ) label_box( fig, f"optimal amp: {amplitude:.4g}<br>circularity: {circularity:.4g}", row=None, col=None, ) fig.update_xaxes(title_text="Readout pulse amplitude [fullscale]") fig.update_yaxes(title_text="Circularity (λ_min / λ_max)", range=[0, 1.05]) style_layout( fig, width=760, height=480, title="IQ-cloud circularity vs. readout pulse amplitude", ) return fig
[docs] def point_clouds_grid_figure( clouds: list[np.ndarray | None], amplitudes: list[float], end_point_index: int | None, ): """One IQ-cloud scatter (with a 99% confidence ellipse) per amplitude whose resonator fit succeeded; the amplitude selected as the circularity end point is outlined in green. Axis titles/tick labels are shown only on the grid's outer edge — with many amplitudes, repeating them on every cell just overlaps into noise. """ valid = [i for i, cloud in enumerate(clouds) if cloud is not None] if not valid: return None ncols = min(4, len(valid)) nrows = int(np.ceil(len(valid) / ncols)) endpoint_cell = valid.index(end_point_index) if end_point_index in valid else None fig = make_subplots( rows=nrows, cols=ncols, subplot_titles=[ ( f"★ {amplitudes[i]:.3f} fullscale" if cell == endpoint_cell else f"{amplitudes[i]:.3f} fullscale" ) for cell, i in enumerate(valid) ], horizontal_spacing=0.03, vertical_spacing=max(0.06, 0.16 / nrows), ) for cell, i in enumerate(valid): cloud = clouds[i] row, col = divmod(cell, ncols) row += 1 col += 1 fig.add_trace( go.Scatter( x=cloud[:, 0], y=cloud[:, 1], mode="markers", marker={"size": 3, "color": DATA_COLOR, "opacity": 0.4}, showlegend=False, ), row=row, col=col, ) # `scaleanchor="x"` always means "the figure's first x-axis", not # "this cell's own x-axis" — anchor to the axis the trace we just # added actually landed on instead. cell_xaxis = fig.data[-1].xaxis mean, cov = _fit_ellipse(cloud) if mean is not None: ellipse_x, ellipse_y = _ellipse_xy(mean, cov) fig.add_trace( go.Scatter( x=ellipse_x, y=ellipse_y, mode="lines", line={"color": "darkorange", "width": 1.5}, showlegend=False, ), row=row, col=col, ) fig.update_xaxes(showticklabels=(row == nrows), row=row, col=col) fig.update_yaxes( scaleanchor=cell_xaxis, scaleratio=1, showticklabels=(col == 1), row=row, col=col, ) if cell == endpoint_cell: 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": "green", "width": 3}, ) fig.update_xaxes(title_text="I [a.u.]", row=nrows) fig.update_yaxes(title_text="Q [a.u.]", col=1) for annotation in fig.layout.annotations: annotation.font = {"size": 9} style_layout(fig, width=ncols * 300, height=nrows * 280 + 60) return fig