# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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