Source code for bragi_quantum.experiments.nodes.coupler.resonator_spectroscopy_vs_current.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:
#
#   Axel Andersson, axean@chalmers.se
#   Michele Faucci Giannelli, faucci@chalmers.se
#   Matteo Robbiati, robbiati@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


# This code is part of Tergite
#
# (C) Copyright Eleftherios Moschandreou 2023, 2024
# (C) Copyright Michele Faucci Giannelli 2024, 2025
# (C) Copyright Stefan Hill 2024
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
#
# Modified from tergite-autocalibration
# (https://github.com/tergite/tergite-autocalibration), file:
#   tergite_autocalibration/lib/nodes/coupler/spectroscopy/analysis.py


"""
Analysis for resonator spectroscopy as a function of coupler DC current.

Ported from tergite-autocalibration
(lib/nodes/coupler/spectroscopy/analysis.py). Each coupler dataset holds a
resonator spectroscopy per DC-current point for both of the coupler's qubits;
every spectroscopy is fitted individually and the fitted resonator frequency
is tracked versus current. A sudden jump in the tracked frequency (or a gap
where the fit fails) marks a current at which the coupler crosses the
resonator — the "crossing currents" reported as this node's QOI.

The dataset's data variables are named after each *qubit* (e.g. ``q06``,
``q07``), not after the coupler (``q06_q07``) — so unlike a plain qubit/coupler
analysis, an element ("q06_q07") cannot be sliced out with the generic
``slice_element`` helper. ``ResonatorSpectroscopyVsCurrentAnalysis`` overrides
``analyse_element``/``_process`` to group the coupler's two qubit variables
directly, mirroring the former ``_group_by_coupler``.
"""

from typing import override

import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots

from bragi_quantum.datalayer.utils.logging import logger
from bragi_quantum.datalayer.visualization.plot_style import (
    FIT_COLOR,
    PAIR_COLORS,
    style_layout,
)
from bragi_quantum.experiments.abstract.analysis import Analysis
from bragi_quantum.experiments.abstract.parameters import BaseQoi
from bragi_quantum.experiments.nodes.coupler.resonator_spectroscopy_vs_current.parameters import (
    ResonatorSpectroscopyVsCurrentParameters,
    ResonatorSpectroscopyVsCurrentQOI,
)
from bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.analysis import (
    ResonatorSpectroscopyAnalysis,
)
from bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.parameters import (
    ResonatorSpectroscopyQOI,
)
from bragi_quantum.experiments.utils.dataset_utils import as_dataset


def _find_crossing_currents(
    currents: list[float],
    frequencies: list[float],
    threshold: float,
    spurious_threshold: float,
    min_interval: float,
    resonator_crossings: list[float] = [],
    resonator_crossings_interval: float = 0.15e-3,
) -> list[float]:
    """
    Detect the currents at which the tracked frequency jumps by more than
    ``threshold`` Hz, treating zeros as failed fits (gaps).

    Ported verbatim from tergite-autocalibration. Groups of consecutive jumps
    within ``min_interval`` Amps are collapsed into their mean current;
    candidates within ``resonator_crossings_interval`` of a known resonator
    crossing are discarded (used by the qubit-spectroscopy variant).
    """
    # Step 1: Clean up spurious values and fill in small gaps
    freqs = list(frequencies).copy()

    for i in range(1, len(freqs) - 1):
        prev, curr, nxt = freqs[i - 1], freqs[i], freqs[i + 1]

        # Fill single zero gap if neighboring values are close
        if curr == 0 and abs(prev - nxt) < spurious_threshold:
            freqs[i] = (prev + nxt) / 2

        # Remove isolated non-zero point between zeros
        if prev == 0 and nxt == 0:
            freqs[i] = 0

    # Step 2: Find significant jumps across zero gaps
    temp_crossings = []
    crossing_currents = []

    i = 0
    while i < len(freqs) - 1:
        # Look ahead to next non-zero point
        j = i + 1
        while j < len(freqs) and freqs[j] == 0:
            j += 1
        if j >= len(freqs):
            break

        if freqs[i] == 0:
            i += 1
            continue

        # Detect transition
        if abs(freqs[i] - freqs[j]) > threshold:
            temp_crossings.append(currents[i])
            temp_crossings.extend(currents[i + 1 : j])
            temp_crossings.append(currents[j])

        # Evaluate grouping for minimum interval
        if temp_crossings:
            span = currents[j] - min(temp_crossings)
            if span > min_interval or j == len(freqs) - 1:
                mid_current = np.mean(temp_crossings)
                too_close = any(
                    abs(mid_current - rc) <= resonator_crossings_interval
                    for rc in resonator_crossings
                )

                if not too_close:
                    crossing_currents.append(float(mid_current))
                temp_crossings = []

        i += 1

    return crossing_currents


class _QubitCurrentTracker:
    """Fits a per-current resonator spectroscopy trace and tracks crossings
    for one qubit of a coupler. Plain helper (not an ``Analysis``) held by
    ``ResonatorSpectroscopyVsCurrentAnalysis`` — one instance per qubit."""

    def __init__(
        self, parameters: ResonatorSpectroscopyVsCurrentParameters, qubit: str
    ):
        self.parameters = parameters
        self.qubit = qubit
        self.detected_frequencies = []
        self.detected_frequency_errors = []
        self.detected_currents = []
        self.spectroscopy_analyses: list[ResonatorSpectroscopyAnalysis] = []
        self.crossing_currents: list[float] = []
        self.n_crossing = 0
        self.frequencies_coord = None
        self.current_coord = None
        self.frequencies = None
        self.dc_currents = None
        self.magnitudes = None
        self.data_var = None

    def fit(self, dataset) -> list[float]:
        """Fit every per-current resonator spectroscopy and detect the
        crossing currents from the resulting frequency-vs-current trace.
        ``dataset`` is already restricted to this qubit's data variable(s)."""
        self.data_var = next(iter(dataset.data_vars))
        for coord in dataset[self.data_var].coords:
            if "frequencies" in str(coord):
                self.frequencies_coord = coord
            elif "currents" in str(coord):
                self.current_coord = coord

        self.dc_currents = dataset[self.current_coord]
        self.frequencies = dataset[self.frequencies_coord]
        S21 = dataset.isel(ReIm=0) + 1j * dataset.isel(ReIm=1)
        self.magnitudes = np.abs(S21)

        for current in self.dc_currents.values:
            ds_at_current = dataset.sel({self.current_coord: current})
            ds_at_current = ds_at_current.drop_vars(
                [coord for coord in ds_at_current.coords if "currents" in str(coord)]
            )

            freq_analysis = ResonatorSpectroscopyAnalysis(
                self.parameters, ResonatorSpectroscopyQOI
            )
            qoi = freq_analysis.process_qubit(ds_at_current, self.qubit)
            self.spectroscopy_analyses.append(freq_analysis)

            resonator_frequency = (
                qoi.minimum_frequency if qoi.is_successful else float("nan")
            )

            if not np.isnan(resonator_frequency):
                self.detected_frequencies.append(resonator_frequency)
                self.detected_frequency_errors.append(freq_analysis.minimum_freq_err)
            else:
                self.detected_frequencies.append(0)
                self.detected_frequency_errors.append(float("nan"))
            self.detected_currents.append(float(current))

        self.crossing_currents = _find_crossing_currents(
            self.detected_currents,
            self.detected_frequencies,
            threshold=self.parameters.crossing_threshold,
            spurious_threshold=self.parameters.spurious_threshold,
            min_interval=self.parameters.min_crossing_interval,
        )
        self.n_crossing = len(self.crossing_currents)

        if self.n_crossing == 0:
            logger.info(f"No crossings detected for {self.qubit}.")

        return self.crossing_currents

    # ------------------------------------------------------------------
    # Plotting (plotly)
    # ------------------------------------------------------------------

    def add_heatmap_trace(
        self, fig, row: int = 1, col: int = 1, showscale: bool = False
    ) -> None:
        """Raw |S21| magnitude map with the tracked frequency vs current and
        the detected crossings overlaid."""
        magnitudes = self.magnitudes[self.data_var].transpose(
            str(self.frequencies_coord), str(self.current_coord)
        )
        # Normalize each current column to [0, 1] so the resonator dip stays
        # visible even when the overall transmission level drifts with current.
        magnitude_map = magnitudes.values
        col_min = np.nanmin(magnitude_map, axis=0, keepdims=True)
        col_max = np.nanmax(magnitude_map, axis=0, keepdims=True)
        col_span = np.where(col_max > col_min, col_max - col_min, 1)
        magnitude_map = (magnitude_map - col_min) / col_span

        fig.add_trace(
            go.Heatmap(
                z=magnitude_map,
                x=self.dc_currents.values,
                y=self.frequencies.values,
                colorscale="Viridis",
                showscale=showscale,
            ),
            row=row,
            col=col,
        )
        error_y = [e if np.isfinite(e) else 0.0 for e in self.detected_frequency_errors]
        fig.add_trace(
            go.Scatter(
                x=self.detected_currents,
                y=self.detected_frequencies,
                error_y={"type": "data", "array": error_y},
                mode="markers",
                marker={"color": FIT_COLOR, "size": 6},
                showlegend=False,
            ),
            row=row,
            col=col,
        )
        for crossing in self.crossing_currents[:4]:
            fig.add_vline(
                x=crossing,
                line={"color": "grey", "dash": "dash", "width": 2},
                row=row,
                col=col,
            )
        fig.update_yaxes(
            range=[float(self.frequencies.min()), float(self.frequencies.max())],
            title_text="Frequency (Hz)",
            row=row,
            col=col,
        )
        fig.update_xaxes(title_text="Coupler current (A)", row=row, col=col)

    def spectroscopy_grid_figure(self, title: str):
        """One figure tiling every per-current resonator fit, with a gold box
        highlighting the current bins nearest to each crossing."""
        n_analyses = len(self.spectroscopy_analyses)
        if n_analyses == 0:
            return None

        ncols = min(int(np.ceil(np.sqrt(n_analyses))), 6)
        nrows = int(np.ceil(n_analyses / ncols))
        titles = [f"{current * 1e3:.2f} mA" for current in self.detected_currents]

        fig = make_subplots(
            rows=nrows,
            cols=ncols,
            subplot_titles=titles,
            horizontal_spacing=max(0.02, 0.1 / ncols),
            vertical_spacing=max(0.05, 0.14 / nrows),
        )
        for i, ana in enumerate(self.spectroscopy_analyses):
            ana.add_traces(fig, row=i // ncols + 1, col=i % ncols + 1)

        currents = np.array(self.detected_currents)
        for crossing in self.crossing_currents:
            idx = int(np.argmin(np.abs(currents - crossing)))
            row, col = idx // ncols + 1, idx % ncols + 1
            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},
            )

        style_layout(
            fig,
            width=ncols * 320,
            height=nrows * 300 + 80,
            title=f"{title} — {self.qubit}",
        )
        return fig


[docs] class ResonatorSpectroscopyVsCurrentAnalysis(Analysis): """Runs the frequency-vs-current analysis for both qubits of one coupler and packages their crossing currents into a single QOI (unified, plotly). Replaces the former ``ResonatorSpectroscopyVsCurrentQubitAnalysis`` + ``ResonatorSpectroscopyVsCurrentCouplerAnalysis`` + ``ResonatorSpectroscopyVsCurrentNodeAnalysis``. """ element_kind = "coupler" parameters: ResonatorSpectroscopyVsCurrentParameters def __init__( self, parameters, qoi_cls: "type[ResonatorSpectroscopyVsCurrentQOI] | None" = None, **kwargs, ): super().__init__(parameters, qoi_cls, **kwargs) self.q1_name = "" self.q2_name = "" self.q1: _QubitCurrentTracker | None = None self.q2: _QubitCurrentTracker | None = None
[docs] @override def plot_title(self) -> str: return f"Coupler {self.element}"
# ------------------------------------------------------------------ # Execution: coupler data variables are named after each qubit, not the # coupler, so the default slice_element (matching a variable literally # named `element`) does not apply — group by the coupler's qubits here. # ------------------------------------------------------------------
[docs] @override def analyse_element(self, dataset, element: str) -> BaseQoi: ds_full = as_dataset(dataset) return self._process(ds_full, element)
@override def _process(self, dataset, element: str) -> BaseQoi: self.element = element self.coupler = element self.dataset = dataset self.q1_name, self.q2_name = element.split("_") self.qoi = self.compute_qoi() return self.qoi
[docs] @override def compute_qoi(self) -> BaseQoi: self.q1 = _QubitCurrentTracker(self.parameters, self.q1_name) self.q2 = _QubitCurrentTracker(self.parameters, self.q2_name) crossing_currents = {} for qubit_name, tracker in [(self.q1_name, self.q1), (self.q2_name, self.q2)]: qubit_data_vars = [ data_var for data_var in self.dataset.data_vars if qubit_name in data_var ] ds = self.dataset[qubit_data_vars] crossing_currents[qubit_name] = tracker.fit(ds) return self.qoi_cls(is_successful=True, crossing_currents=crossing_currents)
# ------------------------------------------------------------------ # Plotting # ------------------------------------------------------------------
[docs] @override def add_traces(self, fig, row: int = 1, col: int = 1) -> None: """Both qubits' tracked frequency-vs-current traces overlaid (main plot). The raw |S21| heatmaps and per-current fit grids move to support_figures(). The two qubits' absolute resonator frequencies typically differ by tens/hundreds of MHz, which would swamp a shared y-axis and hide the (kHz-scale) jumps this plot exists to show — so each trace is centred on its own median frequency (failed-fit zeros excluded) and plotted in kHz deviation instead of absolute Hz. """ legend = row == 1 and col == 1 for tracker, color, name in [ (self.q1, PAIR_COLORS[0], self.q1_name), (self.q2, PAIR_COLORS[1], self.q2_name), ]: freqs = np.array(tracker.detected_frequencies) currents = np.array(tracker.detected_currents) valid = freqs != 0 baseline = np.median(freqs[valid]) if valid.any() else 0.0 fig.add_trace( go.Scatter( x=currents[valid], y=(freqs[valid] - baseline) / 1e3, mode="markers", marker={"color": color, "size": 5}, name=name, legendgroup=name, showlegend=legend, ), row=row, col=col, ) for crossing in tracker.crossing_currents[:4]: fig.add_vline( x=crossing, line={"color": color, "dash": "dash", "width": 1.5}, row=row, col=col, ) fig.update_xaxes(title_text="Coupler current (A)", row=row, col=col) fig.update_yaxes( title_text="Δ Resonator frequency (kHz, per-qubit median)", row=row, col=col )
[docs] @override def support_figures(self): figures = [] for tracker, qubit_name in [(self.q1, self.q1_name), (self.q2, self.q2_name)]: heat_fig = make_subplots(rows=1, cols=1) tracker.add_heatmap_trace(heat_fig, 1, 1, showscale=True) style_layout( heat_fig, width=700, height=450, title=f"{self.parameters.name} — {qubit_name}", ) figures.append( ( heat_fig, f"{self.parameters.name}_{self.coupler}_{qubit_name}_trace.png", ) ) grid_fig = tracker.spectroscopy_grid_figure(self.parameters.name) if grid_fig is not None: figures.append( ( grid_fig, f"{self.parameters.name}_{self.coupler}_{qubit_name}_spectroscopies.png", ) ) return figures