Source code for bragi_quantum.experiments.nodes.coupler.qubit_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
#   Joel Sandås, joel.sandas@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 qubit (two-tone) spectroscopy as a function of coupler DC current.

Ported from tergite-autocalibration
(lib/nodes/coupler/spectroscopy/analysis.py). Each coupler dataset holds a
qubit spectroscopy per DC-current point for both of the coupler's qubits;
every spectroscopy is fitted individually and the fitted qubit 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 qubit —
the "crossing currents" reported as this node's QOI. Candidates too close to
a resonator crossing (stored in Redis by resonator_spectroscopy_vs_current)
are discarded as readout artefacts.

Like ``resonator_spectroscopy_vs_current``, the dataset's data variables are
named after each *qubit*, not the coupler — so ``QubitSpectroscopyVsCurrentAnalysis``
overrides ``analyse_element``/``_process`` to group the coupler's two qubit
variables directly rather than relying on the generic ``slice_element``.
"""

import ast
import os
from concurrent.futures import ProcessPoolExecutor
from typing import override

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

from bragi_quantum.datalayer.managing.session import ActiveSession
from bragi_quantum.datalayer.utils.logging import logger
from bragi_quantum.datalayer.visualization.plot_style import (
    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.qubit_spectroscopy_vs_current.parameters import (
    QubitSpectroscopyVsCurrentParameters,
    QubitSpectroscopyVsCurrentQOI,
)
from bragi_quantum.experiments.nodes.coupler.resonator_spectroscopy_vs_current.analysis import (
    _find_crossing_currents,
)
from bragi_quantum.experiments.nodes.qubit_control.spectroscopy.analysis import (
    QubitSpectroscopyAnalysis,
)
from bragi_quantum.experiments.nodes.qubit_control.spectroscopy.parameters import (
    QubitSpectroscopy01QOI,
)
from bragi_quantum.experiments.utils.dataset_utils import as_dataset


def _fit_current_slice(
    parameters: QubitSpectroscopyVsCurrentParameters,
    dataset: xr.Dataset,
    qubit: str,
) -> QubitSpectroscopyAnalysis:
    """
    Fit one current's 1-D qubit spectroscopy trace.

    Module-level (rather than a method) so it can be pickled and sent to a
    worker process: the per-current fits are independent, CPU-bound Lorentzian
    curve fits that don't release the GIL for problems this small, so threads
    would not run them in parallel — a process pool is used instead.
    """
    freq_analysis = QubitSpectroscopyAnalysis(parameters, QubitSpectroscopy01QOI)
    freq_analysis.process_qubit(dataset, qubit)
    return freq_analysis


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

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

    def fit(self, dataset) -> list[float]:
        """Fit every per-current qubit 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)

        current_slices = []
        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)]
            )
            current_slices.append(ds_at_current)

        # Every current's fit is independent (a small, CPU-bound Lorentzian
        # curve fit) — fan them out across processes instead of running the
        # ~50-100 fits one at a time.
        max_workers = self.parameters.max_fit_workers or os.cpu_count() or 1
        max_workers = max(1, min(max_workers, len(current_slices)))
        chunksize = max(1, len(current_slices) // (max_workers * 4))
        # Default ("fork" on Linux) start method: "spawn" re-imports the full
        # numpy/scipy/lmfit stack in every worker on every pool, which for
        # this workload (small per-current fits, a fresh pool per qubit) costs
        # more than the fits themselves — measured ~3x slower than serial.
        with ProcessPoolExecutor(max_workers=max_workers) as pool:
            self.spectroscopy_analyses = list(
                pool.map(
                    _fit_current_slice,
                    [self.parameters] * len(current_slices),
                    current_slices,
                    [self.qubit] * len(current_slices),
                    chunksize=chunksize,
                )
            )

        for current, freq_analysis in zip(
            self.dc_currents.values, self.spectroscopy_analyses
        ):
            qoi = freq_analysis.qoi
            qubit_frequency = qoi.frequency if qoi.is_successful else float("nan")

            if not np.isnan(qubit_frequency):
                self.detected_frequencies.append(qubit_frequency)
                self.detected_frequency_errors.append(qoi.frequency_error)
            else:
                self.detected_frequencies.append(0)
                self.detected_frequency_errors.append(float("nan"))
            self.detected_currents.append(float(current))

        smoothed_frequencies = self._smooth_frequencies(self.detected_frequencies)
        self.crossing_currents = _find_crossing_currents(
            self.detected_currents,
            smoothed_frequencies,
            threshold=self.parameters.crossing_threshold,
            spurious_threshold=self.parameters.spurious_threshold,
            min_interval=self.parameters.min_crossing_interval,
            resonator_crossings=self.resonator_crossing_points,
            resonator_crossings_interval=self.parameters.resonator_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

    @staticmethod
    def _smooth_frequencies(frequencies, window=5):
        """
        Local moving average over non-zero (i.e. detected) points, used to
        suppress peak-detection noise where the fitted frequency merely hops
        back and forth between two nearby values from one current point to
        the next. A single point flickering between two values gets averaged
        away, while a genuine avoided crossing - a shift sustained over many
        points - survives.
        """
        n = len(frequencies)
        half = window // 2
        smoothed = list(frequencies)
        for i, value in enumerate(frequencies):
            if value == 0:
                continue
            lo, hi = max(0, i - half), min(n, i + half + 1)
            neighborhood = [f for f in frequencies[lo:hi] if f != 0]
            if neighborhood:
                smoothed[i] = sum(neighborhood) / len(neighborhood)
        return smoothed

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

    def add_trace(self, fig, row: int = 1, col: int = 1) -> None:
        """Plot the raw |S21| magnitude map with the tracked qubit 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 qubit line 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(
                x=self.dc_currents.values,
                y=self.frequencies.values,
                z=magnitude_map,
                colorscale="Viridis",
                showscale=False,
            ),
            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": "red", "size": 6},
                showlegend=False,
            ),
            row=row,
            col=col,
        )
        for crossing in self.crossing_currents:
            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())],
            row=row,
            col=col,
        )
        fig.update_xaxes(title_text="Coupler current (A)", row=row, col=col)
        fig.update_yaxes(title_text="Frequency (Hz)", row=row, col=col)

    def spectroscopy_grid_figure(self, title: str):
        """One figure tiling every per-current qubit spectroscopy 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 QubitSpectroscopyVsCurrentAnalysis(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 ``QubitSpectroscopyVsCurrentQubitAnalysis`` + ``QubitSpectroscopyVsCurrentCouplerAnalysis`` + ``QubitSpectroscopyVsCurrentNodeAnalysis``. """ element_kind = "coupler" parameters: QubitSpectroscopyVsCurrentParameters def __init__( self, parameters, qoi_cls: "type[QubitSpectroscopyVsCurrentQOI] | None" = None, **kwargs, ): super().__init__(parameters, qoi_cls, **kwargs) self.q1_name = "" self.q2_name = "" self.q1: _QubitCrossingTracker | None = None self.q2: _QubitCrossingTracker | 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 def _get_resonator_crossing_points(self, qubit: str) -> list[float]: """ Read the resonator crossing currents stored in Redis by a previous resonator_spectroscopy_vs_current run, so the qubit-crossing detection can discard candidates that are actually resonator crossings. Returns an empty list when there is no active session, no Redis connection, or no stored crossings (e.g. in analysis-only tests). """ try: redis_connection = ActiveSession.get().redis_connection except RuntimeError: return [] if redis_connection is None: return [] stored = redis_connection.hget( f"couplers:{self.coupler}", f"resonator_crossing_points_{qubit}" ) if not stored: return [] try: return [float(c) for c in ast.literal_eval(stored)] except (ValueError, SyntaxError): logger.warning( f"Could not parse stored resonator crossing points for " f"{self.coupler}/{qubit}: {stored!r}" ) return []
[docs] @override def compute_qoi(self) -> BaseQoi: self.q1 = _QubitCrossingTracker(self.parameters, self.q1_name) self.q2 = _QubitCrossingTracker(self.parameters, self.q2_name) crossing_currents = {} for qubit_name, tracker in [(self.q1_name, self.q1), (self.q2_name, self.q2)]: tracker.resonator_crossing_points = self._get_resonator_crossing_points( qubit_name ) 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 per-current fit grids move to support_figures(). As with resonator_spectroscopy_vs_current, the two qubits' absolute frequencies typically differ by tens/hundreds of MHz, which would swamp a shared y-axis — so each trace is centred on its own median frequency (failed-fit zeros excluded) and plotted in kHz deviation. """ 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: 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="Δ Qubit 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)]: trace_fig = make_subplots(rows=1, cols=1) tracker.add_trace(trace_fig, 1, 1) style_layout( trace_fig, width=700, height=450, title=f"{self.parameters.name} — {qubit_name}", ) figures.append( ( trace_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