Source code for bragi_quantum.experiments.utils.calibration_points

# ══════════════════════════════════════════════════════════════════════════
#     ___   ___ ___   _      _   ___
#    / _ \ / __|_  ) | |    /_\ | _ )
#   | (_) | (__ / /  | |__ / _ \| _ \
#    \__\_\\___/___| |____/_/ \_\___/
#
#   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
#   Matteo Robbiati, robbiati@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


"""
Calibration-points block: schedule-side detection, dataset-side lookup and
projection, and the exceptions raised when it can't be found.

Import wholesale: ``from bragi_quantum.experiments.utils import calibration_points as cal``.
"""

import numpy as np
import xarray as xr
from qblox_scheduler.operations.control_flow_library import (
    ConditionalOperation,
    ControlFlowOperation,
    LoopOperation,
)
from qblox_scheduler.schedules.schedule import TimeableScheduleBase

CALIBRATION_POINTS_LABEL = "calibration_points"
REQUIRED_STATES = frozenset({0.0, 1.0})


[docs] class CalibrationPointsError(KeyError): """Base class for calibration-point lookup failures. Subclasses ``KeyError`` so existing ``except KeyError`` sites still work. """
[docs] class NoCalibrationPointsError(CalibrationPointsError): """No ``<element>_CAL`` data variable found in the dataset."""
[docs] class PartialCalibrationPointsError(CalibrationPointsError): """``<element>_CAL`` exists but is missing a required ``CAL`` state."""
# -- Schedule-side: does the compiled schedule actually contain the block? -- def _walk_labels(sched_or_op): """Yield every schedulable label found anywhere in ``sched_or_op``. Parameters ---------- sched_or_op : TimeableScheduleBase or ControlFlowOperation or Operation Schedule or operation to search, recursively. Yields ------ str or None Each schedulable's label, in traversal order. """ if isinstance(sched_or_op, TimeableScheduleBase): for schedulable in sched_or_op.schedulables.values(): yield schedulable.get("label") operation = sched_or_op.operations[schedulable["operation_id"]] yield from _walk_labels(operation) elif isinstance( sched_or_op, (LoopOperation, ConditionalOperation, ControlFlowOperation) ): yield from _walk_labels(sched_or_op.body)
[docs] def has_calibration_points(schedule) -> bool: """Whether ``schedule`` contains a schedulable labeled ``CALIBRATION_POINTS_LABEL``. Parameters ---------- schedule : TimeableScheduleBase A schedule, typically already compiled (see ``BaseNode.precompile``). Returns ------- bool """ return CALIBRATION_POINTS_LABEL in _walk_labels(schedule)
# -- Dataset-side: reading calibration points back off an acquired dataset --
[docs] def element_has_calibration_data(dataset: xr.Dataset, element_name: str) -> bool: """Whether ``dataset`` carries a ``<element_name>_CAL`` variable at all. Parameters ---------- dataset : xr.Dataset This element's (already-sliced) dataset. element_name : str The qubit/coupler name, e.g. ``"q06"``. Returns ------- bool """ return f"{element_name}_CAL" in dataset
[docs] def available_calibration_states(dataset: xr.Dataset, element_name: str) -> frozenset: """The ``CAL`` state values present for ``element_name``. Parameters ---------- dataset : xr.Dataset This element's (already-sliced) dataset. element_name : str The qubit/coupler name, e.g. ``"q06"``. Returns ------- frozenset[float] Empty if ``element_name`` has no calibration data at all. """ if not element_has_calibration_data(dataset, element_name): return frozenset() da = dataset[f"{element_name}_CAL"] return frozenset(np.atleast_1d(da.coords["CAL"].values).tolist())
[docs] def get_calibration_complex( dataset: xr.Dataset, element_name: str, *, required_states: frozenset = REQUIRED_STATES, ) -> xr.DataArray: """Return ``element_name``'s calibration IQ values as complex numbers. Parameters ---------- dataset : xr.Dataset This element's (already-sliced) dataset. element_name : str The qubit/coupler name, e.g. ``"q06"``. required_states : frozenset[float], optional ``CAL`` values that must be present. By default ``{0.0, 1.0}``. Returns ------- xr.DataArray Complex IQ values, one per ``CAL`` state (and any outer dimensions, e.g. repetitions, preserved unaveraged). Raises ------ NoCalibrationPointsError No ``<element_name>_CAL`` variable at all. PartialCalibrationPointsError The variable exists but is missing one or more of ``required_states``. """ calib_var = f"{element_name}_CAL" if not element_has_calibration_data(dataset, element_name): raise NoCalibrationPointsError( f"No calibration data found for {element_name}. Expected data " f"variable '{calib_var}'." ) da = dataset[calib_var] calib = da.isel(ReIm=0) + 1j * da.isel(ReIm=1) available = available_calibration_states(dataset, element_name) missing = set(required_states) - available if missing: raise PartialCalibrationPointsError( f"Calibration data for {element_name} is missing state(s) " f"{sorted(missing)} (only {sorted(available)} present). Expected " f"data variable '{calib_var}' to carry {sorted(required_states)}." ) return calib
[docs] def project_onto_calibration( complex_data: xr.DataArray, calib: xr.DataArray, *, low: float = 0, high: float = 1, ) -> xr.DataArray: """Rotate and normalize IQ data onto the *low*-*high* axis ``calib`` defines. ``CAL=low`` maps to 0, ``CAL=high`` maps to 1. Normalization is applied per slice of any outer dimensions ``calib`` carries (e.g. repetitions): xarray broadcasting pairs each slice of ``complex_data`` with its own calibration points, never an average of them. Parameters ---------- complex_data : xr.DataArray Complex-valued IQ data whose outer dimensions align with ``calib``. Typically ``self.S21[self.data_var]``. calib : xr.DataArray This element's calibration points, from ``get_calibration_complex``. low : float, optional Calibrated state mapped to 0. By default the ground state (0). high : float, optional Calibrated state mapped to 1. By default the first excited state (1). Returns ------- xr.DataArray Real-valued, same shape as ``complex_data``, near 0 at *low* and near 1 at *high*. """ calib_low = calib.sel(CAL=float(low), drop=True) calib_high = calib.sel(CAL=float(high), drop=True) displacement = calib_high - calib_low # Translating by calib_low, rotating by -angle(displacement) and scaling # by 1/|displacement| is, on the real axis, the same as projecting onto # the displacement vector: Re[(z - c0) * conj(d)] / |d|^2. projected = (complex_data - calib_low) * displacement.conj() return projected.real / (np.abs(displacement) ** 2)
[docs] def dataset_has_calibration_points_for_all_qubits( dataset: xr.Dataset, element_name: str, *, required_states: frozenset = REQUIRED_STATES, ) -> bool: """Whether ``get_calibration_complex`` would succeed for ``element_name``. Never raises; use to decide upfront (e.g. to label a plot axis) without needing to catch ``project``'s ``CalibrationPointsError``. Parameters ---------- dataset : xr.Dataset This element's (already-sliced) dataset. element_name : str The qubit/coupler name, e.g. ``"q06"``. required_states : frozenset[float], optional ``CAL`` values that must be present. By default ``{0.0, 1.0}``. Returns ------- bool """ try: get_calibration_complex(dataset, element_name, required_states=required_states) except CalibrationPointsError: return False return True
[docs] def project( dataset: xr.Dataset, element_name: str, complex_data: xr.DataArray, *, low: float = 0, high: float = 1, ) -> xr.DataArray: """``get_calibration_complex`` + ``project_onto_calibration``. Parameters ---------- dataset : xr.Dataset This element's (already-sliced) dataset. element_name : str The qubit/coupler name, e.g. ``"q06"``. complex_data : xr.DataArray Complex-valued IQ data. Typically ``self.S21[self.data_var]``. low : float, optional Calibrated state mapped to 0. By default the ground state (0). high : float, optional Calibrated state mapped to 1. By default the first excited state (1). Returns ------- xr.DataArray Real-valued, same shape as ``complex_data``, near 0 at *low* and near 1 at *high*. Raises ------ CalibrationPointsError Calibration data for ``element_name`` is missing or doesn't cover both ``low`` and ``high``. Callers that want to degrade gracefully (e.g. fall back to raw magnitude) should catch this themselves — that's a judgment call for the analysis, not this module. """ calib = get_calibration_complex( dataset, element_name, required_states=frozenset({float(low), float(high)}), ) return project_onto_calibration(complex_data, calib, low=low, high=high)