Source code for bragi_quantum.experiments.nodes.readout.ro_frequency_optimization.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
#   Axel Andersson, axean@chalmers.se
#   Michele Faucci Giannelli, faucci@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


# This code is part of Tergite
#
# (C) Copyright Eleftherios Moschandreou 2023, 2024
# (C) Copyright Liangyu Chen 2023, 2024
# (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/readout/ro_frequency_optimization/analysis.py


"""
Module containing classes that select the optimal readout frequency.

The resonator is probed with the qubit in each prepared state; the optimal
frequency maximises the |0>/|1> IQ separation (2-state) or the area of the
|0>,|1>,|2> triangle (3-state).
"""

from typing import override

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

from bragi_quantum.datalayer.managing.session import ActiveSession
from bragi_quantum.datalayer.visualization.plot_style import (
    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.readout.ro_frequency_optimization.parameters import (
    ROThreeStateFrequencyOptimizationQOI,
    ROTwoStateFrequencyOptimizationQOI,
)


[docs] class ROTwoStateFrequencyOptimizationAnalysis(Analysis): """Selects the readout frequency maximising the |0>/|1> IQ-plane separation (unified, plotly). Replaces the former ``ROTwoStateFrequencyOptimizationQubitAnalysis`` + ``ROTwoStateFrequencyOptimizationNodeAnalysis``. """ element_kind = "qubit" def __init__( self, parameters, qoi_cls: "type[ROTwoStateFrequencyOptimizationQOI] | None" = None, **kwargs, ): super().__init__(parameters, qoi_cls, **kwargs) self.frequencies = None self.frequency_coord = None self.qubit_states = None self.qubit_state_coord = None self.s21_0 = None self.s21_1 = None self.magnitudes_0 = None self.magnitudes_1 = None self.phase_0 = None self.phase_1 = None self.optimal_frequency = None self.index_of_max_distance = None
[docs] @override def plot_title(self) -> str: return f"RO frequency for {self.element}"
[docs] @override def compute_qoi(self) -> BaseQoi: for coord in self.dataset.coords: if "frequencies" in str(coord): self.frequencies = self.dataset[coord].values self.frequency_coord = coord elif "qubit_states" in str(coord): self.qubit_states = self.dataset[coord].values self.qubit_state_coord = coord self.s21_0 = self.S21[self.data_var].sel({self.qubit_state_coord: 0}) self.s21_1 = self.S21[self.data_var].sel({self.qubit_state_coord: 1}) self.magnitudes_0 = np.abs(self.s21_0) self.magnitudes_1 = np.abs(self.s21_1) self.phase_0 = np.angle(self.s21_0) self.phase_1 = np.angle(self.s21_1) distances = self.s21_1 - self.s21_0 self.optimal_frequency = np.abs(distances).idxmax().item() self.index_of_max_distance = np.abs(distances).argmax() return self.qoi_cls(frequency=self.optimal_frequency, is_successful=True)
def _readout_frequencies(self) -> "tuple[float | None, float | None]": """Fetch the |0> and |1> readout frequencies from the active device.""" try: transmon = ActiveSession.get().device.elements[self.qubit] ro_freq = float(transmon.clock_freqs.readout) ro_freq_1 = float(transmon.extended_clock_freqs.readout_1) return ( ro_freq if not np.isnan(ro_freq) else None, ro_freq_1 if not np.isnan(ro_freq_1) else None, ) except Exception: return None, None
[docs] @override def add_traces(self, fig, row: int = 1, col: int = 1) -> None: """|0> and |1> resonator traces on the IQ plane; the point maximising their separation is marked.""" f0 = self.s21_0[self.index_of_max_distance] f1 = self.s21_1[self.index_of_max_distance] ro_freq, ro_freq_1 = self._readout_frequencies() label = f"opt_ro: {int(self.optimal_frequency)}" if ro_freq is not None: label += f"<br>|0>_ro: {int(ro_freq)}" if ro_freq_1 is not None: label += f"<br>|1>_ro: {int(ro_freq_1)}" fig.add_trace( go.Scatter( x=self.s21_0.real, y=self.s21_0.imag, mode="lines+markers", marker={"size": 4, "color": "blue"}, line={"color": "blue"}, name="|0>", showlegend=False, ), row=row, col=col, ) fig.add_trace( go.Scatter( x=self.s21_1.real, y=self.s21_1.imag, mode="lines+markers", marker={"size": 4, "color": "red"}, line={"color": "red"}, name="|1>", showlegend=False, ), row=row, col=col, ) fig.add_trace( go.Scatter( x=[f0.real.item(), f1.real.item()], y=[f0.imag.item(), f1.imag.item()], mode="markers", marker={"symbol": "star", "size": 14, "color": "black"}, showlegend=False, ), row=row, col=col, ) label_box( fig, label, row=row, col=col, x=0.02, y=0.98, xanchor="left", yanchor="top", align="left", ) fig.update_xaxes(title_text="I quadrature (V)", row=row, col=col) fig.update_yaxes(title_text="Q quadrature (V)", row=row, col=col)
[docs] @override def support_figures(self): """|S21| magnitude and phase vs frequency for both traces, with the optimal frequency marked.""" fig = make_subplots(rows=2, cols=1, subplot_titles=["Magnitude", "Phase"]) fig.add_trace( go.Scatter( x=self.frequencies, y=self.magnitudes_0, mode="markers+lines", marker={"size": 4, "color": "blue"}, line={"color": "blue"}, showlegend=False, ), row=1, col=1, ) fig.add_trace( go.Scatter( x=self.frequencies, y=self.magnitudes_1, mode="markers+lines", marker={"size": 4, "color": "red"}, line={"color": "red"}, showlegend=False, ), row=1, col=1, ) fig.add_vline(x=self.optimal_frequency, line={"color": "black"}, row=1, col=1) fig.add_trace( go.Scatter( x=self.frequencies, y=self.phase_0, mode="markers+lines", marker={"size": 4, "color": "blue"}, line={"color": "blue"}, showlegend=False, ), row=2, col=1, ) fig.add_trace( go.Scatter( x=self.frequencies, y=self.phase_1, mode="markers+lines", marker={"size": 4, "color": "red"}, line={"color": "red"}, showlegend=False, ), row=2, col=1, ) fig.add_vline(x=self.optimal_frequency, line={"color": "black"}, row=2, col=1) fig.update_xaxes(title_text="Frequency (Hz)", row=2, col=1) fig.update_yaxes(title_text="|S21|", row=1, col=1) fig.update_yaxes(title_text="Phase (rad)", row=2, col=1) style_layout( fig, width=700, height=650, title=f"{self.parameters.name} — {self.qubit}" ) return [(fig, f"{self.parameters.name}_{self.qubit}_traces.png")]
[docs] class ROThreeStateFrequencyOptimizationAnalysis( ROTwoStateFrequencyOptimizationAnalysis ): """Selects the readout frequency maximising the area of the |0>,|1>,|2> triangle in the IQ plane (unified, plotly). Replaces the former ``ROThreeStateFrequencyOptimizationQubitAnalysis`` + ``ROThreeStateFrequencyOptimizationNodeAnalysis``. """ def __init__( self, parameters, qoi_cls: "type[ROThreeStateFrequencyOptimizationQOI] | None" = None, **kwargs, ): super().__init__(parameters, qoi_cls, **kwargs) self.s21_2 = None self.magnitudes_2 = None self.area = None self.optimal_distance = None
[docs] @override def compute_qoi(self) -> BaseQoi: super().compute_qoi() self.s21_2 = self.S21[self.data_var].sel({self.qubit_state_coord: 2}) self.magnitudes_2 = np.abs(self.s21_2) re_0, im_0 = self.s21_0.real, self.s21_0.imag re_1, im_1 = self.s21_1.real, self.s21_1.imag re_2, im_2 = self.s21_2.real, self.s21_2.imag distances_01 = np.sqrt((re_0 - re_1) ** 2 + (im_0 - im_1) ** 2) distances_12 = np.sqrt((re_1 - re_2) ** 2 + (im_1 - im_2) ** 2) distances_20 = np.sqrt((re_2 - re_0) ** 2 + (im_2 - im_0) ** 2) # Heron's formula for the area of the triangle spanned by the states. s = (distances_01 + distances_12 + distances_20) / 2 self.area = np.sqrt( s * (s - distances_01) * (s - distances_12) * (s - distances_20) ) self.optimal_frequency = self.area.idxmax().item() self.optimal_distance = self.area.max().item() return self.qoi_cls(frequency=self.optimal_frequency, is_successful=True)
[docs] @override def add_traces(self, fig, row: int = 1, col: int = 1) -> None: """|S21| magnitude of each state vs frequency, with the (rescaled) triangle area and its maximum overlaid — the node's only plot.""" legend = row == 1 and col == 1 for mag, color, name in [ (self.magnitudes_0, "blue", "0"), (self.magnitudes_1, "red", "1"), (self.magnitudes_2, "green", "2"), ]: fig.add_trace( go.Scatter( x=self.frequencies, y=mag, mode="lines", line={"color": color}, name=name, legendgroup=name, showlegend=legend, ), row=row, col=col, ) # Scale the area for visibility against the magnitude traces. fig.add_trace( go.Scatter( x=self.frequencies, y=self.area * 1.5e2, mode="lines", line={"color": "black", "dash": "dash"}, name="area", legendgroup="area", showlegend=legend, ), row=row, col=col, ) fig.add_trace( go.Scatter( x=[self.optimal_frequency], y=[self.optimal_distance * 1.5e2], mode="markers", marker={"symbol": "star", "size": 12, "color": "red"}, showlegend=False, ), row=row, col=col, ) fig.update_xaxes(title_text="RO frequency", row=row, col=col) fig.update_yaxes(title_text="IQ distance", row=row, col=col)
[docs] @override def support_figures(self): return []