Source code for bragi_quantum.experiments.nodes.coupler.cz_parametrization.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
#   Joel Sandås, joel.sandas@chalmers.se
#   Yanchen Lin, linya@chalmers.se
#   Matteo Robbiati, robbiati@chalmers.se
#   Michele Faucci Giannelli, faucci@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


"""
Analysis for CZ parametrization with a fixed pulse duration.

Ported from tergite-autocalibration
(lib/nodes/coupler/cz_parametrization/analysis.py). Each coupler dataset
holds a 2-D (frequency, amplitude) CZ-pulse scan per qubit of the coupler;
the qubit driven towards |2> is expected to show a magnitude maximum and the
qubit driven towards |0> a magnitude minimum at the same (frequency,
amplitude) point if a real CZ avoided crossing exists there.

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

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 (
    PLOTLY_TEMPLATE,
    label_box,
)
from bragi_quantum.experiments.abstract.analysis import Analysis
from bragi_quantum.experiments.abstract.parameters import BaseQoi
from bragi_quantum.experiments.nodes.coupler.cz_parametrization.parameters import (
    CZParametrizationFixDurationParameters,
)
from bragi_quantum.experiments.utils.dataset_utils import as_dataset


[docs] def spatial_coherence_zscore( magnitude_map: np.ndarray, n_shuffle: int = 200, seed: int = 0 ) -> float: """ Quantifies how spatially coherent a 2D magnitude map is, i.e. whether it contains a smooth blob/chevron rather than uncorrelated noise. A real feature varies smoothly between neighboring sweep points, so its total variation (mean absolute difference between adjacent pixels) is much lower than that of the same pixel values randomly shuffled, which destroys any spatial structure. Pure noise has no structure to destroy, so shuffling barely changes the total variation and the z-score stays near zero. The z-score is how many standard deviations below the shuffled-null mean the real total variation sits. """ map_range = magnitude_map.max() - magnitude_map.min() if map_range == 0: return 0.0 normalized = (magnitude_map - magnitude_map.min()) / map_range def total_variation(m: np.ndarray) -> float: return float(np.mean(np.abs(np.diff(m, axis=0)))) + float( np.mean(np.abs(np.diff(m, axis=1))) ) real_tv = total_variation(normalized) rng = np.random.default_rng(seed) flat = normalized.flatten() shuffled_tvs = np.empty(n_shuffle) for i in range(n_shuffle): rng.shuffle(flat) shuffled_tvs[i] = total_variation(flat.reshape(normalized.shape)) shuffled_std = shuffled_tvs.std() if shuffled_std == 0: return 0.0 return (shuffled_tvs.mean() - real_tv) / shuffled_std
def _normalize(raw: np.ndarray) -> np.ndarray: span = np.max(raw) - np.min(raw) if span == 0: return np.zeros_like(raw) return (raw - np.min(raw)) / span def _extremum_point( magnitudes: np.ndarray, frequencies: np.ndarray, amplitudes: np.ndarray, *, mode: str, ) -> list: """The (frequency, amplitude) of the map's max ('max') or min ('min').""" index = np.argmax(magnitudes) if mode == "max" else np.argmin(magnitudes) freq_idx, amp_idx = np.unravel_index(index, magnitudes.shape) return [float(frequencies[freq_idx]), float(amplitudes[amp_idx])]
[docs] class CombinedFrequencyVsAmplitudeAnalysis: """ Combines the results of a coupler's two qubit analyses in a CZ parametrization experiment. Finds the point of maximum q_to2-q_to0 magnitude difference and checks that it agrees with either the q_to2 max point or the q_to0 min point within tolerance, and that both qubits' magnitude maps show spatially coherent structure rather than just noise. If either check fails, the analysis fails. """ def __init__( self, result_to2: list, result_to0: list, max_diff_point: list, to2_raw_magnitudes: "np.ndarray | None" = None, to0_raw_magnitudes: "np.ndarray | None" = None, ): self.result_to2 = result_to2 self.result_to0 = result_to0 self.max_diff_point = max_diff_point self.to2_raw_magnitudes = to2_raw_magnitudes self.to0_raw_magnitudes = to0_raw_magnitudes self.frequency_tolerance = 2.5e6 # Hz self.amplitude_tolerance = 0.06 self.coherence_zscore_threshold = 5.0 if self.to2_raw_magnitudes is None or self.to0_raw_magnitudes is None: self.to2_zscore = 0.0 self.to0_zscore = 0.0 else: self.to2_zscore = spatial_coherence_zscore(self.to2_raw_magnitudes) self.to0_zscore = spatial_coherence_zscore(self.to0_raw_magnitudes)
[docs] def are_two_qubits_compatible(self) -> bool: """ Check if the maximum-difference point is near either the q_to2 max or the q_to0 min point, and that both qubits' magnitude maps show real spatial structure. """ position_ok = self._is_near_point(self.result_to2) or self._is_near_point( self.result_to0 ) return position_ok and self._has_significant_structure()
def _is_near_point(self, point: list) -> bool: freq_ok = abs(self.max_diff_point[0] - point[0]) < self.frequency_tolerance amp_ok = abs(self.max_diff_point[1] - point[1]) < self.amplitude_tolerance return bool(freq_ok and amp_ok) def _has_significant_structure(self) -> bool: """ Rejects maps that are indistinguishable from shuffled noise, even if their argmax/argmin happens to coincide with the combined max-diff point by chance. Skipped (treated as passing) when raw magnitude maps were not supplied. """ if self.to2_raw_magnitudes is None or self.to0_raw_magnitudes is None: return True return bool( self.to2_zscore > self.coherence_zscore_threshold and self.to0_zscore > self.coherence_zscore_threshold )
[docs] def best_parameters(self) -> list: """The point of maximum q_to2-q_to0 magnitude difference (the working point).""" return self.max_diff_point
[docs] def transition_quality(self) -> float: """ A score for ranking how good this transition region is across multiple candidate datasets (e.g. different parking currents): the weaker of the two qubits' spatial-coherence z-scores, mirroring the AND-gate used by ``_has_significant_structure``. Higher is a cleaner, more chevron-like map. """ return min(self.to2_zscore, self.to0_zscore)
[docs] class CZParametrizationFixDurationAnalysis(Analysis): """ Runs the frequency-vs-amplitude CZ parametrization analysis for both qubits of one coupler and packages the working point into a single QOI. """ element_kind = "coupler" parameters: CZParametrizationFixDurationParameters def __init__( self, parameters, qoi_cls: "type[BaseQoi] | None" = None, **kwargs, ): super().__init__(parameters, qoi_cls, **kwargs) self.q1_name = "" self.q2_name = "" self.frequencies = None self.amplitudes = None self.q1_magnitudes = None self.q2_magnitudes = None self.q_to2_name = "" self.q_to0_name = "" self.diff = None self.result_to2 = None self.result_to0 = None self.max_diff_point = None self.combined: CombinedFrequencyVsAmplitudeAnalysis | None = None
[docs] @override def plot_title(self) -> str: return f"{self.coupler}"
# ------------------------------------------------------------------ # 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 _qubit_magnitude_map(self, qubit: str): """The (frequencies, amplitudes, |S21|) 2-D scan for one qubit.""" da = self.dataset[qubit] s21 = da.isel(ReIm=0) + 1j * da.isel(ReIm=1) freq_coord = f"{qubit}_cz_pulse_frequencies" amp_coord = f"{qubit}_cz_pulse_amplitudes" magnitudes = np.abs(s21).transpose(freq_coord, amp_coord) return ( magnitudes.coords[freq_coord].values, magnitudes.coords[amp_coord].values, magnitudes.values, )
[docs] @override def compute_qoi(self) -> BaseQoi: q1_freqs, q1_amps, q1_mag = self._qubit_magnitude_map(self.q1_name) _, _, q2_mag = self._qubit_magnitude_map(self.q2_name) self.frequencies, self.amplitudes = q1_freqs, q1_amps self.q1_magnitudes, self.q2_magnitudes = q1_mag, q2_mag transition = self.parameters.cz_transition if transition == "20": self.q_to2_name, self.q_to0_name = self.q1_name, self.q2_name mag_to2, mag_to0 = q1_mag, q2_mag self.diff = _normalize(q1_mag) - _normalize(q2_mag) elif transition == "02": self.q_to2_name, self.q_to0_name = self.q2_name, self.q1_name mag_to2, mag_to0 = q2_mag, q1_mag self.diff = _normalize(q2_mag) - _normalize(q1_mag) else: raise ValueError( f"Unknown cz_transition {transition!r} for {self.coupler}; " "expected '20' or '02'." ) self.result_to2 = _extremum_point(mag_to2, q1_freqs, q1_amps, mode="max") self.result_to0 = _extremum_point(mag_to0, q1_freqs, q1_amps, mode="min") max_idx = np.unravel_index(np.argmax(self.diff), self.diff.shape) self.max_diff_point = [float(q1_freqs[max_idx[0]]), float(q1_amps[max_idx[1]])] self.combined = CombinedFrequencyVsAmplitudeAnalysis( self.result_to2, self.result_to0, self.max_diff_point, mag_to2, mag_to0 ) frequency_error = (q1_freqs[1] - q1_freqs[0]) / np.sqrt(12) amplitude_error = (q1_amps[1] - q1_amps[0]) / np.sqrt(12) if self.combined.are_two_qubits_compatible(): best_freq, best_amp = self.combined.best_parameters() return self.qoi_cls( is_successful=True, cz_pulse_frequency=best_freq, cz_pulse_frequency_error=frequency_error, cz_pulse_amplitude=best_amp, cz_pulse_amplitude_error=amplitude_error, cz_parametrization_transition_quality=self.combined.transition_quality(), ) logger.info(f"No valid CZ working point found for coupler {self.coupler}.") return self.qoi_cls( is_successful=False, cz_parametrization_transition_quality=self.combined.transition_quality(), )
# ------------------------------------------------------------------ # Plotting (plotly) # ------------------------------------------------------------------ def _magnitudes_for(self, qubit: str) -> np.ndarray: return self.q1_magnitudes if qubit == self.q1_name else self.q2_magnitudes def _panel_data(self): """(qubit name, raw magnitude map, its extremum point, marker color, extremum label) per panel.""" return [ ( self.q_to2_name, self._magnitudes_for(self.q_to2_name), self.result_to2, "red", "Max", ), ( self.q_to0_name, self._magnitudes_for(self.q_to0_name), self.result_to0, "orange", "Min", ), ] @staticmethod def _point_label(tag: str, point: list) -> str: return f"{tag}: freq={point[0] / 1e6:.3f} MHz, amp={point[1]:.3f} fullscale"
[docs] @override def add_traces(self, fig, row: int = 1, col: int = 1) -> None: """Draw both qubits' raw magnitude maps side by side at (row, col) and (row, col+1).""" legend = row == 1 and col == 1 compatible = ( self.combined is not None and self.combined.are_two_qubits_compatible() ) quality_text = ( f"Parking current: {self.parameters.parking_current * 1e3:.3f} mA<br>" f"Transition quality: {self.combined.transition_quality():.2f}<br>" f"Compatible: {'yes' if compatible else 'no'}" ) working_point_text = self._point_label( "Max difference point", self.max_diff_point ) for offset, (qubit, magnitudes, point, color, extremum_tag) in enumerate( self._panel_data() ): c = col + offset x_domain = fig.get_subplot(row, c).xaxis.domain y_domain = fig.get_subplot(row, c).yaxis.domain fig.add_trace( go.Heatmap( x=self.frequencies, y=self.amplitudes, z=magnitudes.T, colorscale="Viridis", showscale=True, colorbar={ "title": {"text": "|S21|", "side": "top", "font": {"size": 10}}, "x": x_domain[1] + 0.02, "xanchor": "left", "y": (y_domain[0] + y_domain[1]) / 2, "yanchor": "middle", "len": y_domain[1] - y_domain[0], "thickness": 12, "tickfont": {"size": 9}, }, ), row=row, col=c, ) fig.add_trace( go.Scatter( x=[point[0]], y=[point[1]], mode="markers", marker={"color": color, "size": 11, "symbol": "x"}, name=f"{qubit} optimum", showlegend=legend, ), row=row, col=c, ) fig.add_trace( go.Scatter( x=[self.max_diff_point[0]], y=[self.max_diff_point[1]], mode="markers", marker={ "color": "lime", "size": 16, "symbol": "circle-open", "line": {"color": "lime", "width": 3}, }, name="Working point", legendgroup="working_point", showlegend=legend, ), row=row, col=c, ) label_box( fig, f"{quality_text}<br>" f"{self._point_label(extremum_tag, point)}<br>" f"{working_point_text}", row=row, col=c, x=0.02, y=0.98, xanchor="left", yanchor="top", align="left", ) fig.update_xaxes(title_text="CZ pulse frequency (Hz)", row=row, col=c) fig.update_yaxes( title_text="CZ pulse amplitude (fullscale)", row=row, col=c )
@override def _render_figure(self, fig, plot_name: str) -> None: make_subplots( rows=1, cols=2, subplot_titles=[self.q_to2_name, self.q_to0_name], horizontal_spacing=0.18, figure=fig, ) self.add_traces(fig, 1, 1) fig.update_layout( template=PLOTLY_TEMPLATE, showlegend=False, width=1120, height=520, margin={"t": 80, "b": 40, "r": 90}, ) @override def _render_grid_figure(self, fig, ncols: int) -> None: workers = list(self.workers.values()) or ( [self] if self.element is not None else [] ) if not workers: raise ValueError("nothing analysed yet; call run(...) first") nrows = len(workers) subplot_titles = [ title for w in workers for title in (w.q_to2_name, w.q_to0_name) ] make_subplots( rows=nrows, cols=2, subplot_titles=subplot_titles, horizontal_spacing=0.16, vertical_spacing=max(0.06, 0.18 / nrows), figure=fig, ) for i, worker in enumerate(workers): worker.add_traces(fig, row=i + 1, col=1) fig.update_layout( template=PLOTLY_TEMPLATE, showlegend=False, width=2 * 460 + 120, height=nrows * 430 + 90, margin={"t": 90, "b": 40, "r": 90}, )