Source code for bragi_quantum.experiments.nodes.qubit_control.motzoi_parameter.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:
#
#   Matteo Robbiati, robbiati@chalmers.se
#   Michele Faucci Giannelli, faucci@chalmers.se
#   Tyra Cortinez Samenius, cortinez@chalmers.se
#   Yanchen Lin, linya@chalmers.se
#   Axel Andersson, axean@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


# This code is part of Tergite
#
# (C) Copyright Eleftherios Moschandreou 2023, 2025
# (C) Copyright Michele Faucci Giannelli 2024
# (C) Copyright Stefan Hill 2024, 2025
#
# 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/qubit_control/motzoi_parameter/analysis.py


"""
Module containing classes that fit and plot data from a Motzoi (DRAG beta)
calibration experiment.

For each motzoi value two complementary circuits are measured (X.Y90 and
Y.X90). The readout magnitude of each circuit varies ~linearly with the motzoi
parameter; the optimal beta is the intersection of the two fitted lines.
"""

from typing import override

import numpy as np
import plotly.graph_objects as go
import uncertainties as unc
from lmfit.models import LinearModel
from plotly.subplots import make_subplots

from bragi_quantum.datalayer.visualization.plot_style import (
    QUALITATIVE_PALETTE,
    failure_box,
    label_box,
    style_layout,
)
from bragi_quantum.experiments.abstract.analysis import Analysis
from bragi_quantum.experiments.abstract.parameters import BaseQoi
from bragi_quantum.experiments.nodes.qubit_control.motzoi_parameter.parameters import (
    MotzoiBaseQOI,
    MotzoiParameters,
)


def _rgba(hex_color: str, alpha: float) -> str:
    """Convert a ``#rrggbb`` colour to a plotly ``rgba(...)`` string."""
    h = hex_color.lstrip("#")
    r, g, b = int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
    return f"rgba({r},{g},{b},{alpha})"


_CIRCUIT_COLORS = QUALITATIVE_PALETTE[:2]
_CIRCUIT_LABELS = {
    "01": ["X, Y90", "Y, X90"],
    "12": ["X, X12, Y90_12", "X, Y12, X90_12"],
}


[docs] class MotzoiAnalysis(Analysis): """Extract the optimal motzoi (DRAG beta) for a qubit (unified, plotly). Two complementary circuits (X.Y90, Y.X90) each vary ~linearly with the motzoi parameter; the optimal beta is the intersection of the two fitted lines. Replaces the former ``MotzoiQubitAnalysis`` + ``MotzoiNodeAnalysis``. """ element_kind = "qubit" parameters: MotzoiParameters def __init__( self, parameters, qoi_cls: "type[MotzoiBaseQOI] | None" = None, **kwargs ): super().__init__(parameters, qoi_cls, **kwargs) self.mw_motzois_coord: str = "" self.circ_coord: str = "" self.motzoi_vals: np.ndarray = np.array([]) self.line_results: list = [] self.optimal_motzoi: float = None self.uncertainty: float = None self.analysis_successful: bool = False
[docs] @override def plot_title(self) -> str: return f"Motzoi for {self.element}"
@property def _circuit_labels(self) -> list[str]: return _CIRCUIT_LABELS[self.parameters.transition]
[docs] @override def compute_qoi(self) -> BaseQoi: coords = self.dataset[self.data_var].coords self.mw_motzois_coord = next( str(c) for c in coords if "motzoi" in str(c).lower() ) self.circ_coord = next(str(c) for c in coords if "circ" in str(c).lower()) self.motzoi_vals = self.dataset.coords[self.mw_motzois_coord].values y0, y1 = self._circuit_data() self._fit_linear_lines(y0, y1) if len(self.line_results) == 2 and all(r.success for r in self.line_results): self.optimal_motzoi, self.uncertainty = self._compute_intersection() else: self.optimal_motzoi, self.uncertainty = None, None in_range = ( self.optimal_motzoi is not None and np.isfinite(self.optimal_motzoi) and ( self.motzoi_vals.min() <= self.optimal_motzoi <= self.motzoi_vals.max() ) ) if not in_range: self.analysis_successful = False self.optimal_motzoi = np.nan self.uncertainty = np.nan else: self.analysis_successful = True return self.qoi_cls( is_successful=self.analysis_successful, motzoi=self.optimal_motzoi, motzoi_error=self.uncertainty, )
def _circuit_data(self): """Magnitude of each circuit vs motzoi (circ_idx 0 = X.Y90, 1 = Y.X90).""" mag = self.magnitudes[self.data_var] return ( mag.sel({self.circ_coord: 0}).values.flatten(), mag.sel({self.circ_coord: 1}).values.flatten(), ) def _fit_linear_lines(self, y0: np.ndarray, y1: np.ndarray) -> None: """Fit a LinearModel to each of the two circuit sweeps.""" self.line_results = [] model = LinearModel() x = self.motzoi_vals for y in (y0, y1): params = model.guess(y, x=x) self.line_results.append(model.fit(y, params, x=x)) def _compute_intersection(self) -> tuple: """Intersection x = (b2 - b1) / (a1 - a2) with error propagation.""" r0, r1 = self.line_results a1 = unc.ufloat(r0.params["slope"].value, r0.params["slope"].stderr or 0.0) b1 = unc.ufloat( r0.params["intercept"].value, r0.params["intercept"].stderr or 0.0 ) a2 = unc.ufloat(r1.params["slope"].value, r1.params["slope"].stderr or 0.0) b2 = unc.ufloat( r1.params["intercept"].value, r1.params["intercept"].stderr or 0.0 ) denom = a1 - a2 if abs(denom.nominal_value) < 1e-30: return None, None beta = (b2 - b1) / denom return beta.nominal_value, beta.std_dev def _add_line_band(self, fig, result, color, x_fine, row, col): """Draw the 1σ uncertainty band for a fitted line (plotly filled area).""" if result.covar is None: return y_fine = result.eval(x=x_fine) dely = result.eval_uncertainty(sigma=1, x=x_fine) fig.add_trace( go.Scatter( x=np.concatenate([x_fine, x_fine[::-1]]), y=np.concatenate([y_fine + dely, (y_fine - dely)[::-1]]), fill="toself", fillcolor=_rgba(color, 0.15), line={"width": 0}, hoverinfo="skip", showlegend=False, ), row=row, col=col, )
[docs] @override def add_traces(self, fig, row: int = 1, col: int = 1) -> None: legend = row == 1 and col == 1 x = self.motzoi_vals x_fine = np.linspace(x.min(), x.max(), 400) circ = self._circuit_data() for i, (result, color, label) in enumerate( zip(self.line_results, _CIRCUIT_COLORS, self._circuit_labels) ): fig.add_trace( go.Scatter( x=x, y=circ[i], mode="markers", marker={"color": color, "size": 5}, name=f"{label} data", legendgroup=label, showlegend=legend, ), row=row, col=col, ) fig.add_trace( go.Scatter( x=x_fine, y=result.eval(x=x_fine), mode="lines", line={"color": color, "width": 2}, name=f"{label} fit", legendgroup=label, showlegend=legend, ), row=row, col=col, ) self._add_line_band(fig, result, color, x_fine, row, col) if self.analysis_successful: fig.add_vline( x=self.optimal_motzoi, line={"color": "black", "dash": "dash"}, row=row, col=col, ) y_inter = self.line_results[0].eval(x=np.array([self.optimal_motzoi]))[0] fig.add_trace( go.Scatter( x=[self.optimal_motzoi], y=[y_inter], mode="markers", marker={"color": "black", "size": 8}, error_x={"type": "data", "array": [self.uncertainty]}, name="β", showlegend=False, ), row=row, col=col, ) label_box( fig, f"β = {self.optimal_motzoi:.3e} ± {self.uncertainty:.3e}", row=row, col=col, x=0.5, y=0.02, xanchor="center", yanchor="bottom", align="center", ) else: failure_box( fig, "Analysis failed — expand range or check traces.", row=row, col=col ) fig.update_xaxes(title_text="Motzoi parameter", row=row, col=col) fig.update_yaxes(title_text="|IQ|", row=row, col=col)
[docs] @override def support_figures(self): """One figure per qubit: the two circuit fits side by side.""" x = self.motzoi_vals x_fine = np.linspace(x.min(), x.max(), 400) circ = self._circuit_data() fig = make_subplots(rows=1, cols=2, subplot_titles=self._circuit_labels) for i, (result, color) in enumerate(zip(self.line_results, _CIRCUIT_COLORS)): c = i + 1 fig.add_trace( go.Scatter( x=x, y=circ[i], mode="markers", marker={"color": color, "size": 5}, showlegend=False, ), row=1, col=c, ) fig.add_trace( go.Scatter( x=x_fine, y=result.eval(x=x_fine), mode="lines", line={"color": color, "width": 2}, showlegend=False, ), row=1, col=c, ) self._add_line_band(fig, result, color, x_fine, 1, c) fig.add_annotation( row=1, col=c, xref="x domain", yref="y domain", x=0.02, y=0.98, xanchor="left", yanchor="top", showarrow=False, text=( f"slope={result.params['slope'].value:.3e}<br>" f"b={result.params['intercept'].value:.3e}" ), font={"size": 8}, ) fig.update_xaxes(title_text="MW Motzoi Amplitude", row=1, col=c) fig.update_yaxes(title_text="Magnitude", row=1, col=c) style_layout( fig, width=900, height=400, title=f"{self.parameters.name} — {self.qubit}" ) return [(fig, f"{self.parameters.name}_{self.qubit}_traces.png")]