Source code for bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.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:
#
#   Joel Sandås, joel.sandas@chalmers.se
#   Axel Andersson, axean@chalmers.se
#   Yanchen Lin, linya@chalmers.se
#   Matteo Robbiati, robbiati@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


"""
Analysis for two-qubit-gate randomized benchmarking (TQG RB).

Ported from tergite-autocalibration
(lib/nodes/coupler/tqg_randomized_benchmarking/analysis.py). Fits an
exponential decay to the |00> return probability, and a second exponential
decay to the population confined to the computational subspace (|00>, |01>,
|10>, |11>) to extract a leakage rate. When calibration points (n_cl < 0) are
present, per-seed IQ drift is corrected before classification using the
3-state readout boundary (centroid + omega_01/12/20) read from Redis.

``TQGRandomizedBenchmarkingInterleavedAnalysis`` additionally combines its own
decay parameter with the standard-RB run's decay parameter (read back from
Redis, written there from the SRB run's QOI) to derive the CZ *gate* fidelity.
"""

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.utils.logging import logger
from bragi_quantum.datalayer.visualization.plot_style import (
    PLOTLY_TEMPLATE,
    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.fitting_tools.models.randomized_benchmarking import (
    ExpDecayModelTQG,
)
from bragi_quantum.experiments.utils.classification_functions import assign_state
from bragi_quantum.experiments.utils.dataset_utils import as_dataset


def _fmt_val_err(value, error, precision: int = 4) -> str:
    """Format 'value' as 'value±error', omitting the error when it is unavailable."""
    text = f"{value:.{precision}f}"
    if error is not None and not np.isnan(error):
        text += f"±{error:.{precision}f}"
    return text


[docs] class TQGRandomizedBenchmarkingAnalysis(Analysis): """ Fits an exponential decay function to two-qubit-gate randomized benchmarking data for one coupler. """ element_kind = "coupler" suffix = "SRB" def __init__(self, parameters, qoi_cls: "type[BaseQoi] | None" = None, **kwargs): super().__init__(parameters, qoi_cls, **kwargs) self.name_qubit_1 = "" self.name_qubit_2 = "" self.number_cliffords_coord = None self.number_cliffords = None self.seed_coord = None self.seeds = None self.loops_coord = None self.number_of_loops = None self.raw_x = None self.raw_y = None self.raw_y_leakage = None self.raw_y_error = None self.p_00_per_seed = None self.p_leakage_per_seed = None self.p_error_per_seed = None self.fit_n_cliffords = None self.fit_y = None self.fit_y_comp = None self.fit_y_second = None self.y_comp_mean = None self.y_second_mean = None self.fidelity = None self.fidelity_stderr = None self.p_value = None self.p_error = None # Fit outputs, each None when its fit did not converge. self.fit_outputs: dict[str, float | None] = {}
[docs] @override def plot_title(self) -> str: return f"{self.coupler}"
# ------------------------------------------------------------------ # Execution: coupler data variables are named after each qubit, not the # coupler (like qubit_spectroscopy_vs_current / cz_parametrization). # ------------------------------------------------------------------
[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.name_qubit_1, self.name_qubit_2 = element.split("_") self.qoi = self.compute_qoi() return self.qoi # ------------------------------------------------------------------ # Redis-backed inputs: the 3-state readout classification boundary # (calibrated by ro_combined_optimization_3state) and the SRB<->IRB # decay-parameter handoff. # ------------------------------------------------------------------ @staticmethod def _redis_connection(): return ActiveSession.get().redis_connection def _read_boundary(self, qubit: str) -> dict: redis_connection = self._redis_connection() redis_key = f"transmons:{qubit}" return { "centroid_i": float( redis_connection.hget(redis_key, "measure_3state_opt:centroid_I") ), "centroid_q": float( redis_connection.hget(redis_key, "measure_3state_opt:centroid_Q") ), "omega_01": float( redis_connection.hget(redis_key, "measure_3state_opt:omega_01") ), "omega_12": float( redis_connection.hget(redis_key, "measure_3state_opt:omega_12") ), "omega_20": float( redis_connection.hget(redis_key, "measure_3state_opt:omega_20") ), } # ------------------------------------------------------------------ # Coordinate alignment: q1 and q2 each carry their own # "<qubit>_number_of_cliffords" / "<qubit>_shot_index" dimensions (built # independently per acquisition channel), even though both qubits of a # coupler share identical values. Renaming q2's onto q1's lets the rest # of this analysis treat the coupler as one aligned dataset. # ------------------------------------------------------------------ def _aligned_qubit_arrays(self): da1 = self.dataset[self.name_qubit_1] da2 = self.dataset[self.name_qubit_2] cliffords_1 = next(c for c in da1.coords if "cliffords" in str(c)) shot_1 = next(c for c in da1.coords if "shot_index" in str(c)) cliffords_2 = next(c for c in da2.coords if "cliffords" in str(c)) shot_2 = next(c for c in da2.coords if "shot_index" in str(c)) da2 = da2.rename({cliffords_2: cliffords_1, shot_2: shot_1}) self.number_cliffords_coord = cliffords_1 self.loops_coord = shot_1 seed_candidates = [c for c in da1.coords if "seed" in str(c)] self.seed_coord = seed_candidates[0] if seed_candidates else None return da1, da2 def _compute_joint_counts( self, boundary_1: dict, boundary_2: dict, drift_corrections=None ): iq1 = self.S21[self.name_qubit_1] iq2 = self.S21[self.name_qubit_2] if drift_corrections is not None: if drift_corrections.get(self.name_qubit_1) is not None: iq1 = iq1 - drift_corrections[self.name_qubit_1] if drift_corrections.get(self.name_qubit_2) is not None: iq2 = iq2 - drift_corrections[self.name_qubit_2] states1 = assign_state(iq1, **boundary_1) states2 = assign_state(iq2, **boundary_2) joint_counts = {} for s1 in [0, 1, 2]: for s2 in [0, 1, 2]: joint = (states1 == s1) & (states2 == s2) joint_counts[f"{s1}{s2}"] = joint.astype(int).sum(dim=self.loops_coord) return joint_counts def _compute_per_seed_drift_corrections(self, boundary_1: dict, boundary_2: dict): """Compute per-seed IQ drift corrections from embedded calibration steps. n_cl=0 -> state |0> reference (standard RB idle step) n_cl=-1 -> state |1> reference (X gate preparation) n_cl=-2 -> state |2> reference (X + Rxy_12 preparation) With all three states the centroid is re-estimated per seed and compared to the Redis value, giving an absolute correction. With only the n=0 step available (older datasets) the correction is relative (removes seed-to-seed drift but not long-term calibration offset). Returns a dict {qubit: xr.DataArray(dims=[seed_coord])} of complex IQ shifts to subtract from each seed's raw data before classification. """ clifford_values = self.S21[self.number_cliffords_coord].values n0_indices = np.where(clifford_values == 0)[0] n1_indices = np.where(clifford_values == -1)[0] n2_indices = np.where(clifford_values == -2)[0] has_state0 = len(n0_indices) > 0 has_full_cal = has_state0 and len(n1_indices) > 0 and len(n2_indices) > 0 corrections = {} for qubit, boundary in ( (self.name_qubit_1, boundary_1), (self.name_qubit_2, boundary_2), ): iq = self.S21[qubit] if not has_state0: logger.warning( f"No n=0 Clifford entry found; skipping drift correction for {qubit}" ) corrections[qubit] = None continue iq_0_per_seed = iq.isel( {self.number_cliffords_coord: int(n0_indices[0])} ).mean(dim=self.loops_coord) if has_full_cal: iq_1_per_seed = iq.isel( {self.number_cliffords_coord: int(n1_indices[0])} ).mean(dim=self.loops_coord) iq_2_per_seed = iq.isel( {self.number_cliffords_coord: int(n2_indices[0])} ).mean(dim=self.loops_coord) centroid_per_seed = ( iq_0_per_seed + iq_1_per_seed + iq_2_per_seed ) / 3.0 centroid_ref = complex(boundary["centroid_i"], boundary["centroid_q"]) drift = centroid_per_seed - centroid_ref logger.info( f"Drift correction for {qubit}: " + ", ".join( f"seed {i}: {float(drift.isel({self.seed_coord: i}).real):.4f}" f"+{float(drift.isel({self.seed_coord: i}).imag):.4f}j" for i in range(drift.sizes[self.seed_coord]) ) ) else: # Relative correction only: remove seed-to-seed offset of state-0 blob drift = iq_0_per_seed - iq_0_per_seed.mean(dim=self.seed_coord) corrections[qubit] = drift return corrections def _mean_and_sem(self, per_seed) -> tuple[float, float]: """Mean over seeds and Clifford lengths, with the standard error of that mean. Each Clifford length gives an independent seed-averaged estimate; the overall SEM combines those per-length SEMs in quadrature. """ n_seeds = per_seed.sizes[self.seed_coord] value = float(per_seed.mean(dim=self.seed_coord).mean().values) if n_seeds < 2: return value, np.nan per_clifford_sem = per_seed.std(dim=self.seed_coord, ddof=1) / np.sqrt(n_seeds) n_cliffords = per_clifford_sem.size error = float(np.sqrt(np.sum(per_clifford_sem.values**2))) / n_cliffords return value, error
[docs] @override def compute_qoi(self) -> BaseQoi: coupler = self.coupler da1, da2 = self._aligned_qubit_arrays() ds1 = da1.to_dataset(name=self.name_qubit_1) ds1[self.name_qubit_2] = da2 self.S21 = ds1.isel(ReIm=0) + 1j * ds1.isel(ReIm=1) self.number_cliffords = self.S21[self.number_cliffords_coord] if self.seed_coord is not None: self.seeds = self.S21[self.seed_coord].values self.number_of_loops = self.S21[self.loops_coord].size # If calibration steps (n_cl < 0) are present, compute per-seed drift # corrections before filtering them out of the RB data. clifford_values_all = self.number_cliffords.values has_calibration = np.any(clifford_values_all < 0) boundary_1 = self._read_boundary(self.name_qubit_1) boundary_2 = self._read_boundary(self.name_qubit_2) if has_calibration: drift_corrections = self._compute_per_seed_drift_corrections( boundary_1, boundary_2 ) rb_indices = np.where(clifford_values_all >= 0)[0] self.S21 = self.S21.isel({self.number_cliffords_coord: rb_indices}) self.number_cliffords = self.S21[self.number_cliffords_coord] else: drift_corrections = None joint_counts = self._compute_joint_counts( boundary_1, boundary_2, drift_corrections ) zeros_count = joint_counts["00"] # (M seeds, N cliffords) leakage_count = ( joint_counts["02"] + joint_counts["20"] + joint_counts["12"] + joint_counts["21"] + joint_counts["22"] ) error_count = joint_counts["01"] + joint_counts["10"] + joint_counts["11"] p_00_per_seed = zeros_count / self.number_of_loops p_leakage_per_seed = leakage_count / self.number_of_loops p_error_per_seed = error_count / self.number_of_loops y_mean = p_00_per_seed.mean(dim=self.seed_coord).values y_leakage_mean = p_leakage_per_seed.mean(dim=self.seed_coord).values y_error_mean = p_error_per_seed.mean(dim=self.seed_coord).values self.raw_x = self.number_cliffords.values self.raw_y = y_mean self.raw_y_leakage = y_leakage_mean self.raw_y_error = y_error_mean self.p_00_per_seed = p_00_per_seed self.p_leakage_per_seed = p_leakage_per_seed self.p_error_per_seed = p_error_per_seed model = ExpDecayModelTQG() model.set_param_hint("A", value=0.75) model.set_param_hint("B", value=0.2, min=0) model.set_param_hint("p", value=0.5, min=0) guess = model.guess(data=y_mean, m=self.number_cliffords.values) fit_result_00 = model.fit( y_mean, params=guess, m=self.number_cliffords.values, weights=1.0 ) self.fit_n_cliffords = np.linspace( self.number_cliffords.values[0], self.number_cliffords.values[-1], 400 ) self.fit_y = model.eval( fit_result_00.params, **{model.independent_vars[0]: self.fit_n_cliffords} ) # Compute and fit P_comp for standard RB comp_count = zeros_count + error_count # 00 + 01 + 10 + 11 p_comp_per_seed = comp_count / self.number_of_loops y_comp_mean = p_comp_per_seed.mean(dim=self.seed_coord).values self.y_comp_mean = y_comp_mean model = ExpDecayModelTQG() model.set_param_hint("A", value=0.2) model.set_param_hint("B", value=0.8, min=0) model.set_param_hint("p", value=0.95, min=0) guess_comp = model.guess(data=y_comp_mean, m=self.number_cliffords.values) fit_result_comp = model.fit( y_comp_mean, params=guess_comp, m=self.number_cliffords.values, weights=1.0 ) self.fit_outputs = {} if fit_result_comp.errorbars: p_L = fit_result_comp.params["p"].value a = fit_result_comp.params["B"].value L_1 = (1 - p_L) * (1 - a) L_2 = (1 - p_L) * a # Error propagation for L_1/L_2, taking the p-B covariance into # account (Wood and Gambetta, "Quantification and characterization # of leakage errors", eq 10 and eq 11). param_names = list(fit_result_comp.params.keys()) p_stderr = fit_result_comp.params["p"].stderr a_stderr = fit_result_comp.params["B"].stderr cov_a_p = fit_result_comp.covar[ param_names.index("B"), param_names.index("p") ] L_1_error = float( np.sqrt( (1 - a) ** 2 * p_stderr**2 + (1 - p_L) ** 2 * a_stderr**2 + 2 * (1 - a) * (1 - p_L) * cov_a_p ) ) L_2_error = float( np.sqrt( a**2 * p_stderr**2 + (1 - p_L) ** 2 * a_stderr**2 - 2 * a * (1 - p_L) * cov_a_p ) ) self.fit_outputs.update( p_L=p_L, p_L_error=p_stderr, a=a, a_error=a_stderr, L_1=L_1, L_1_error=L_1_error, L_2=L_2, L_2_error=L_2_error, ) self.fit_y_comp = model.eval( fit_result_comp.params, **{model.independent_vars[0]: self.fit_n_cliffords}, ) # Second fit: p_00 - p_comp / 4 y_second_per_seed = self.p_00_per_seed - p_comp_per_seed / 4 y_second_mean = y_second_per_seed.mean(dim=self.seed_coord).values self.y_second_mean = y_second_mean model = ExpDecayModelTQG() model.set_param_hint("A", value=0.75) model.set_param_hint("B", value=0) model.set_param_hint("p", value=0.5, min=0) guess_second = model.guess(data=y_second_mean, m=self.number_cliffords.values) fit_result_second = model.fit( y_second_mean, params=guess_second, m=self.number_cliffords.values, weights=1.0, ) if fit_result_second.success: p_r = fit_result_second.params["p"].value if not fit_result_second.errorbars: logger.warning( f"Second fit for {coupler} succeeded but errorbars unavailable; " f"p_r may be unreliable. Fit message: {fit_result_second.message}" ) p_r_error = np.nan else: p_r_error = float(fit_result_second.params["p"].stderr) self.fit_outputs.update(p_r=p_r, p_r_error=p_r_error) params_for_line = fit_result_second.params else: params_for_line = guess_second self.fit_y_second = model.eval( params_for_line, **{model.independent_vars[0]: self.fit_n_cliffords} ) if self.fidelity_stderr is None: self.fidelity_stderr = 0.0 if not fit_result_00.errorbars: logger.error( f"Fitting failed for coupler {coupler}: {fit_result_00.message}" ) return self.qoi_cls(is_successful=False) self.fidelity = (1 + 3 * fit_result_00.params["p"].value) / 4 self.fidelity_stderr = 3 * fit_result_00.params["p"].stderr / 4 self.p_value = fit_result_00.params["p"].value self.p_error = ( fit_result_00.params["p"].stderr if fit_result_00.errorbars else np.nan ) # Keep the raw P(00) fit's A/B too, so the curve can be redrawn later, # e.g. as an SRB reference line on the IRB plot. self.fit_outputs.update( tqg_rb_p=self.p_value, tqg_rb_p_error=self.p_error, tqg_rb_p_A=fit_result_00.params["A"].value, tqg_rb_p_A_error=fit_result_00.params["A"].stderr, tqg_rb_p_B=fit_result_00.params["B"].value, tqg_rb_p_B_error=fit_result_00.params["B"].stderr, ) leakage_value, _leakage_error = self._mean_and_sem(self.p_leakage_per_seed) error_rate_value, _error_rate_error = self._mean_and_sem(self.p_error_per_seed) return self.qoi_cls( is_successful=True, tqg_fidelity=self.fidelity, tqg_fidelity_error=self.fidelity_stderr, reduced_chi2=1.0, leakage=leakage_value, error_rate=error_rate_value, **self.fit_outputs, )
# ------------------------------------------------------------------ # Plotting (plotly) # ------------------------------------------------------------------
[docs] @override def add_traces(self, fig, row: int = 1, col: int = 1) -> None: legend = row == 1 and col == 1 if self.raw_y is None: failure_box(fig, "Analysis failed", row=row, col=col) return if self.p_00_per_seed is not None: for i in range(self.p_00_per_seed.sizes[self.seed_coord]): fig.add_trace( go.Scatter( x=self.raw_x, y=self.p_00_per_seed.isel({self.seed_coord: i}).values, mode="lines", line={"color": "black", "width": 0.5}, opacity=0.15, showlegend=False, ), row=row, col=col, ) fig.add_trace( go.Scatter( x=self.raw_x, y=self.raw_y, mode="markers", marker={"color": "black", "size": 6}, name="P(00) mean", showlegend=legend, ), row=row, col=col, ) if self.y_comp_mean is not None: fig.add_trace( go.Scatter( x=self.raw_x, y=self.y_comp_mean, mode="markers", marker={"color": "green", "size": 6}, name="P(comp) mean", showlegend=legend, ), row=row, col=col, ) if self.y_second_mean is not None: fig.add_trace( go.Scatter( x=self.raw_x, y=self.y_second_mean, mode="markers", marker={"color": "magenta", "size": 6}, name="P(00)-P(comp)/4 mean", showlegend=legend, ), row=row, col=col, ) if self.fit_y is not None: fig.add_trace( go.Scatter( x=self.fit_n_cliffords, y=self.fit_y, mode="lines", line={"color": "black", "width": 2, "dash": "dash"}, name="P(00) fit", showlegend=legend, ), row=row, col=col, ) if self.fit_y_comp is not None: fig.add_trace( go.Scatter( x=self.fit_n_cliffords, y=self.fit_y_comp, mode="lines", line={"color": "green", "width": 2, "dash": "dash"}, name="P(comp) fit", showlegend=legend, ), row=row, col=col, ) if self.fit_y_second is not None: fig.add_trace( go.Scatter( x=self.fit_n_cliffords, y=self.fit_y_second, mode="lines", line={"color": "magenta", "width": 2, "dash": "dash"}, name="second fit", showlegend=legend, ), row=row, col=col, ) label_lines = [] if self.fidelity is not None: label_lines.append( f"F_{self.suffix}={_fmt_val_err(self.fidelity, self.fidelity_stderr)}" ) if self.fit_outputs.get("L_1") is not None: label_lines.append( f"L1_{self.suffix}=" + _fmt_val_err(self.fit_outputs["L_1"], self.fit_outputs["L_1_error"]) ) if self.fit_outputs.get("p_r") is not None: label_lines.append( f"p_r_{self.suffix}=" + _fmt_val_err(self.fit_outputs["p_r"], self.fit_outputs["p_r_error"]) ) if getattr(self, "F_CZ", None) is not None: label_lines.append(f"F_CZ={_fmt_val_err(self.F_CZ, self.F_CZ_error)}") label_lines.append(f"L1_CZ={_fmt_val_err(self.L_1_CZ, self.L_1_CZ_error)}") if label_lines: label_box(fig, "<br>".join(label_lines), row=row, col=col) y_vals = [np.nanmin(self.raw_y), np.nanmax(self.raw_y)] for curve in (self.fit_y, self.fit_y_comp, self.fit_y_second): if curve is not None: y_vals.append(np.nanmin(curve)) y_vals.append(np.nanmax(curve)) ymin, ymax = min(y_vals), max(y_vals) if ymin >= 0 and ymax <= 1: fig.update_yaxes(range=[0, 1], row=row, col=col) else: margin = 0.05 * (ymax - ymin) if ymax > ymin else 0.1 fig.update_yaxes(range=[ymin - margin, ymax + margin], row=row, col=col) fig.update_xaxes(title_text="Number of Cliffords", row=row, col=col) fig.update_yaxes(title_text="Probability", row=row, col=col)
[docs] @override def support_figures(self): return []
[docs] class TQGRandomizedBenchmarkingInterleavedAnalysis(TQGRandomizedBenchmarkingAnalysis): """ Two-qubit-gate RB with the CZ Clifford interleaved into every sequence. Combines this run's decay parameter with the standard-RB run's decay parameter (read back from Redis) to derive the CZ gate fidelity. """ suffix = "IRB" def __init__(self, parameters, qoi_cls: "type[BaseQoi] | None" = None, **kwargs): super().__init__(parameters, qoi_cls, **kwargs) self.L_1_CZ = None self.L_1_CZ_error = None self.p_r_CZ = None self.p_r_CZ_error = None self.F_CZ = None self.F_CZ_error = None self.p_SRB = None self.srb_reference_curve = None def _propagate_cz_error( self, coupler: str, L_1_SRB: float, L_1_IRB: float, p_r_SRB: float, p_r_IRB: float, ) -> tuple[float, float, float]: """Propagate p_r/L_1 stderrs (SRB & IRB) into error bars on L_1_CZ, p_r_CZ, F_CZ. Falls back to NaN wherever an upstream stderr is missing or itself NaN (e.g. older Redis data without the error fields, or a fit that converged without error bars). """ redis_connection = self._redis_connection() p_r_SRB_error_str = redis_connection.hget( f"couplers:{coupler}", "p_r_SRB_error" ) L_1_SRB_error_str = redis_connection.hget( f"couplers:{coupler}", "L_1_SRB_error" ) if p_r_SRB_error_str is None or L_1_SRB_error_str is None: return np.nan, np.nan, np.nan p_r_SRB_error = float(p_r_SRB_error_str) L_1_SRB_error = float(L_1_SRB_error_str) L_1_IRB_error = self.fit_outputs["L_1_error"] p_r_IRB_error = self.fit_outputs["p_r_error"] if any( np.isnan(v) for v in (p_r_SRB_error, L_1_SRB_error, L_1_IRB_error, p_r_IRB_error) ): return np.nan, np.nan, np.nan # p_r_CZ = p_r_IRB / p_r_SRB p_r_CZ_error = float( abs(self.p_r_CZ) * np.sqrt((p_r_IRB_error / p_r_IRB) ** 2 + (p_r_SRB_error / p_r_SRB) ** 2) ) # L_1_CZ = 1 - (1 - L_1_IRB) / (1 - L_1_SRB) d_L1_CZ_d_L1_IRB = 1 / (1 - L_1_SRB) d_L1_CZ_d_L1_SRB = (1 - L_1_IRB) / (1 - L_1_SRB) ** 2 L_1_CZ_error = float( np.sqrt( (d_L1_CZ_d_L1_IRB * L_1_IRB_error) ** 2 + (d_L1_CZ_d_L1_SRB * L_1_SRB_error) ** 2 ) ) # F_CZ = 1 - 3/4 * (1 - p_r_CZ) - L_1_CZ / 4 F_CZ_error = float( np.sqrt((3 / 4 * p_r_CZ_error) ** 2 + (L_1_CZ_error / 4) ** 2) ) return L_1_CZ_error, p_r_CZ_error, F_CZ_error
[docs] @override def compute_qoi(self) -> BaseQoi: coupler = self.coupler qoi = super().compute_qoi() if not qoi.is_successful: return qoi # This run's own fit outputs come from memory; only the SRB run's are # read from Redis. redis_connection = self._redis_connection() p_r_SRB_str = redis_connection.hget(f"couplers:{coupler}", "p_r_SRB") p_r_SRB = float(p_r_SRB_str) if p_r_SRB_str is not None else None # Reconstruct the SRB raw P(00) fit curve (if available) over this # plot's clifford range, so it can be overlaid as a reference on the # IRB plot alongside the IRB P(00) curve. srb_p_str = redis_connection.hget(f"couplers:{coupler}", "tqg_rb_p_SRB") srb_A_str = redis_connection.hget(f"couplers:{coupler}", "tqg_rb_p_A_SRB") srb_B_str = redis_connection.hget(f"couplers:{coupler}", "tqg_rb_p_B_SRB") if srb_p_str is not None and srb_A_str is not None and srb_B_str is not None: self.p_SRB = float(srb_p_str) self.srb_reference_curve = float( srb_A_str ) * self.p_SRB**self.fit_n_cliffords + float(srb_B_str) L_1_SRB_str = redis_connection.hget(f"couplers:{coupler}", "L_1_SRB") L_1_IRB = self.fit_outputs.get("L_1") p_r_IRB = self.fit_outputs.get("p_r") if L_1_SRB_str and p_r_SRB and L_1_IRB is not None and p_r_IRB is not None: L_1_SRB = float(L_1_SRB_str) self.L_1_CZ = 1 - (1 - L_1_IRB) / (1 - L_1_SRB) self.p_r_CZ = p_r_IRB / p_r_SRB self.F_CZ = 1 - 3 / 4 * (1 - self.p_r_CZ) - self.L_1_CZ / 4 self.L_1_CZ_error, self.p_r_CZ_error, self.F_CZ_error = ( self._propagate_cz_error(coupler, L_1_SRB, L_1_IRB, p_r_SRB, p_r_IRB) ) if self.F_CZ is None: logger.warning( f"No SRB reference found for {coupler}; cannot compute CZ gate " "fidelity, keeping standard fidelity" ) return qoi self.fidelity = self.F_CZ self.fidelity_stderr = self.F_CZ_error return qoi.model_copy( update={"tqg_fidelity": self.F_CZ, "tqg_fidelity_error": self.F_CZ_error} )
[docs] @override def support_figures(self): if self.raw_y is None: return [] fig = go.Figure() make_subplots(rows=1, cols=1, figure=fig) if self.fit_y is not None: irb_label = f"IRB fit (p={self.p_value:.4f})" fig.add_trace( go.Scatter( x=self.fit_n_cliffords, y=self.fit_y, mode="lines", line={"color": "black", "width": 2, "dash": "dash"}, name=irb_label, ) ) if self.srb_reference_curve is not None: fig.add_trace( go.Scatter( x=self.fit_n_cliffords, y=self.srb_reference_curve, mode="lines", line={"color": "blue", "width": 2, "dash": "dash"}, name=f"SRB fit (p={self.p_SRB:.4f})", ) ) if self.L_1_CZ is not None and self.F_CZ is not None: label_box( fig, f"L1_CZ={_fmt_val_err(self.L_1_CZ, self.L_1_CZ_error)}<br>" f"F_CZ={_fmt_val_err(self.F_CZ, self.F_CZ_error)}", ) fig.update_xaxes(title_text="Number of Cliffords") fig.update_yaxes(title_text="P(00)") style_layout( fig, width=620, height=520, title=f"P(00): SRB vs IRB — {self.coupler}", showlegend=True, ) fig.update_layout(template=PLOTLY_TEMPLATE) fig_name = f"{self.parameters.name}_{self.coupler}_p00_srb_vs_irb.png" return [(fig, fig_name)]