# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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
# ══════════════════════════════════════════════════════════════════════════
"""
Helpers to load a saved node dataset and run a single-element analysis on it.
A node's HDF5 stores every element (qubit or coupler) as its own data variable
named after the element (``q06``, ``q06_q07``, ...). Before an analysis can run,
that full dataset must be sliced down to one element — the same operation the
node does internally in ``_analyze_all_qubits`` and that bragi_quantum.gui does when it
replays a plot. These helpers centralise that slicing so callers (scripts,
notebooks, reanalysis tooling) never have to touch xarray by hand.
"""
from __future__ import annotations
import os
from typing import Any
import numpy as np
import xarray as xr
from bragi_quantum.datalayer.models.qubit import ExtendedTransmon
from bragi_quantum.datalayer.utils.logging import logger
DatasetOrPath = xr.Dataset | str | os.PathLike
[docs]
def as_dataset(dataset: DatasetOrPath) -> xr.Dataset:
"""Return an open dataset, accepting either an ``xr.Dataset`` or a file path."""
if isinstance(dataset, (str, os.PathLike)):
return xr.open_dataset(dataset)
return dataset
[docs]
def slice_element(
dataset: DatasetOrPath,
element: str,
*,
kind: str = "qubit",
node_name: str | None = None,
) -> xr.Dataset:
"""Slice a single element out of a full node dataset.
Merges the data variable(s) named after ``element``, tags the result, and —
for qubits — restricts it to the element's own sweep coordinate. The returned
dataset is exactly what ``process_qubit`` / ``process_coupler`` expect.
Also picks up ``element``'s own ``"<element>_CAL"`` companion
variable (if present), so calibration-point data travels with its owning
qubit rather than being dropped by the slice — see
``bragi_quantum.experiments.utils.calibration_points.get_calibration_complex``/
``project``.
Args:
dataset: an open :class:`xarray.Dataset` or a path to an HDF5 file.
element: the qubit (``"q06"``) or coupler (``"q06_q07"``) to extract.
kind: ``"qubit"`` (default) or ``"coupler"``.
node_name: optional value recorded in ``ds.attrs["node"]``.
Returns:
The single-element dataset. If ``element`` is not present as a variable
(already a single-element dataset), it is returned unchanged.
"""
ds_full = as_dataset(dataset)
calib_var = f"{element}_CAL"
element_vars = [v for v in ds_full.data_vars if v == element or str(v) == calib_var]
if not element_vars:
return ds_full
ds = xr.merge([ds_full[v] for v in element_vars])
if node_name is not None:
ds.attrs["node"] = node_name
if kind == "coupler":
ds.attrs["coupler"] = element
else:
ds.attrs["qubit"] = element
# Only select along an indexed *dimension* coordinate for this element;
# a scalar coord (e.g. one already reduced by an upstream .sel) has no
# index and would raise on .sel(slice(None)).
matching = [c for c in ds.coords if element in c and c in ds.dims]
if matching:
ds = ds.sel({matching[0]: slice(None)})
return ds
[docs]
def validate_raw_dataset(
raw_ds: xr.Dataset, transmons: dict[str, ExtendedTransmon]
) -> None:
"""Raise/log on an empty or suspicious raw dataset before any processing."""
if len(raw_ds.data_vars) == 0:
raise ValueError(
f"Dataset is empty - no data variables found. "
f"This likely indicates a hardware issue or failed measurement. "
f"Expected data variables for qubits: {[t.name for t in transmons.values()]}"
)
if len(raw_ds.coords) == 0:
logger.warning(
"Dataset has no coordinates - this is unusual but may be valid for single-shot measurements"
)
logger.info(
f"Dataset validation passed: {len(raw_ds.data_vars)} data variables, "
f"{len(raw_ds.coords)} coordinates. "
f"Transmons in scope: {[t.name for t in transmons.values()]}"
)
[docs]
def drop_active_reset_and_extra_coords(
raw_ds: xr.Dataset, schedule_samplespace: dict[str, Any]
) -> xr.Dataset:
"""Drop AR (active reset) sample channels and coords outside the inner sweep.
The coordinate 'acq_index_<i>' is special: it corresponds to the flat
measurement-index dimension of channel <i> and must always be kept.
"""
ar_channels = list(
filter(
lambda k: isinstance(k, str) and k.startswith("AR_"),
raw_ds.data_vars,
),
)
extra_inner_sweep_coords = [
coord
for coord in raw_ds.coords
if not any(
(
coord.endswith((dimension_name, "shot_index"))
or coord.startswith("acq_index")
)
for dimension_name in schedule_samplespace
)
]
keys_to_drop = ar_channels + extra_inner_sweep_coords
return raw_ds.drop_vars(keys_to_drop) if keys_to_drop else raw_ds
[docs]
def sorted_by_acq_channel(
transmons: dict[str, ExtendedTransmon],
) -> list[ExtendedTransmon]:
return sorted(transmons.values(), key=lambda t: t.measure.acq_channel)
[docs]
def rename_channels_to_qubit_names(
ds: xr.Dataset, transmons: dict[str, ExtendedTransmon]
) -> xr.Dataset:
"""Invert the acquisition-channel-to-qubit-name mapping on the dataset's data vars.
The acquisition dimensions are created by measure_system using int(acq_channel),
so the cast here must match: an acq_channel overlaid from Redis can arrive as a
float (e.g. 0.0), which would otherwise produce "acq_index_0.0" and mismatch the
"acq_index_0" dimension the cluster actually returns.
"""
return ds.rename_vars(
name_dict={int(t.measure.acq_channel): t.name for t in transmons.values()}
)
[docs]
def resolve_dimension_names(
schedule_samplespace: dict[str, Any], raw_ds: xr.Dataset
) -> list[str]:
"""The sweep dimensions to reshape the flat acquisition index into.
Appends 'shot_index' when the dataset carries single-shot data, so the
multi-index built from it is aware of that extra dimension.
"""
dimension_names = list(schedule_samplespace.keys())
if any(c.endswith("shot_index") for c in raw_ds.coords):
dimension_names.append("shot_index")
return dimension_names
[docs]
def get_acq_index_dim_name(da: xr.DataArray, acq_channel: int) -> str:
"""Return the acquisition-index dimension name for *da*.
qblox-scheduler records the authoritative name in
``da.attrs["acq_index_dim_name"]`` — acquisition channels that share
identical ``coords`` in the schedule are merged into one such shared
dimension (e.g. ``"acq_index_0_1"``), so it is no longer safe to assume
every channel owns its own private ``acq_index_<channel>`` dimension.
Falls back to that legacy convention when the attribute is absent.
"""
return da.attrs.get("acq_index_dim_name") or f"acq_index_{acq_channel}"
[docs]
def filter_rows_for_channel(
da: xr.DataArray, acq_dim: str, anchor_coord: str
) -> xr.DataArray:
"""Keep only the rows of a (possibly shared) acquisition dimension for one channel.
When several channels share ``acq_dim``, rows belonging to other channels
carry NaN at *anchor_coord*. ``anchor_coord`` must be per-qubit distinct —
the first schedule_samplespace coordinate, built via make_linear_domains,
satisfies this. A no-op when the channel owns ``acq_dim`` outright (no
NaNs present).
"""
if anchor_coord not in da.coords or not da.coords[anchor_coord].isnull().any():
return da
valid = np.where(~da.coords[anchor_coord].isnull().values)[0]
return da.isel({acq_dim: valid.tolist()})
[docs]
def reshape_flat_acquisition_dim(
da: xr.DataArray, acq_dim: str, coord_names: list[str]
) -> xr.DataArray:
"""Replace the flat acquisition dimension with proper named coordinate dimensions.
For a single coordinate ``swap_dims`` is used to avoid xarray's
single-level-MultiIndex restriction on ``unstack``. For multiple
coordinates ``set_index`` + ``unstack`` builds an N-D grid.
"""
if len(coord_names) == 1:
da = da.swap_dims({acq_dim: coord_names[0]})
if acq_dim in da.coords:
da = da.drop_vars(acq_dim)
return da
return da.set_index({acq_dim: coord_names}).unstack(acq_dim)
[docs]
def build_channel_dataset(
ds: xr.Dataset,
transmon: ExtendedTransmon,
dimension_names: list[str],
) -> xr.Dataset:
"""Isolate and reshape one qubit's acquisition data out of its flat dim."""
qubit_name = transmon.name
da = ds[qubit_name]
acq_dim = get_acq_index_dim_name(da, int(transmon.measure.acq_channel))
coord_names = [f"{qubit_name}_{name}" for name in dimension_names]
da = filter_rows_for_channel(da, acq_dim, coord_names[0])
da = drop_unrelated_coords(da, coord_names)
da = reshape_flat_acquisition_dim(da, acq_dim, coord_names)
return xr.Dataset({qubit_name: da})
[docs]
def build_channel_datasets(
ds: xr.Dataset,
transmons: list[ExtendedTransmon],
dimension_names: list[str],
) -> list[xr.Dataset]:
return [build_channel_dataset(ds, t, dimension_names) for t in transmons]
[docs]
def merge_channel_datasets(datasets: list[xr.Dataset]) -> xr.Dataset:
return xr.merge(datasets)