# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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
# Matteo Robbiati, robbiati@chalmers.se
# Michele Faucci Giannelli, faucci@chalmers.se
# ══════════════════════════════════════════════════════════════════════════
"""
Module containing the class that computes, fits and plots purity from a
purity benchmarking experiment.
"""
from typing import override
import numpy as np
import plotly.graph_objects as go
from bragi_quantum.datalayer.managing.session import ActiveSession
from bragi_quantum.datalayer.utils.logging import logger
from bragi_quantum.datalayer.visualization.plot_style import label_box
from bragi_quantum.experiments.abstract.analysis import Analysis
from bragi_quantum.experiments.fitting_tools.models.randomized_benchmarking import (
RBDecayModel,
)
from bragi_quantum.experiments.nodes.characterization.purity_benchmarking.parameters import (
PurityBenchmarkingParameters,
PurityBenchmarkingQOI,
)
from bragi_quantum.experiments.utils import calibration_points as cal
# Basis codes carried by the "<qubit>_basis" coordinate, matching
# measurement.py's BASES = ("X", "Y", "Z"). Selected as floats since
# calibration-adjacent coordinates round-trip through HDF5 as float64 (see
# bragi_quantum.experiments.utils.calibration_points.project_onto_calibration's own CAL=float(...)
# selection).
X_BASIS, Y_BASIS, Z_BASIS = 0.0, 1.0, 2.0
# (dimension - 1) / dimension for a single qubit (dimension = 2), the
# coefficient in Zhu et al. (arXiv:2407.07960) eq. 13.
QUBIT_DIMENSION_FACTOR = 0.5
[docs]
class PurityBenchmarkingAnalysis(Analysis):
"""
Analysis that combines per-basis Pauli expectation values into a purity
and fits its decay against the number of Cliffords.
Every shot is hardware-averaged (never classified), and each of the
``n_seeds`` independent random-Clifford realizations carries its OWN
calibration points (never an average across seeds — mirrors
``RBAnalysis``): each seed's three basis measurements are projected onto
the |0>-|1> axis using calibration measured in that same compiled
schedule, converted to Pauli expectation values
(``x_exp = 2 * p_x - 1`` etc.) and combined into
``purity = x_exp**2 + y_exp**2 + z_exp**2``. Purity is then averaged
across seeds; the seed-to-seed standard deviation is used as the fit
weight, same as ``RBAnalysis``.
The purity decay parameter ``u`` (unitarity) alone already bounds the
*incoherent* (decoherence-limited) error, independent of any other
measurement — Wallman et al. ("Estimating the coherence of noise", New
J. Phys. 17 113020), restated as eq. 13 of Zhu et al. (arXiv:2407.07960):
``incoherent_error = (1/2)(1 - sqrt(u))`` for a single qubit. Combining
that with a companion randomized-benchmarking (RB) result for the same
qubit additionally isolates the *coherent* ("true", systematic /
calibration) error: ``coherent_error = total_error - incoherent_error``
(Zhu et al. eq. 14), where ``total_error = 1 - rb_fidelity`` is RB's
average gate error rate (Zhu et al. eq. 4). RB's result is read back from
Redis (the ``rb_fidelity`` trusted value written by
``RandomizedBenchmarking`` for this same qubit) — if none is found (RB
hasn't been run yet, or no active session), ``coherent_error`` is
reported as ``float("nan")`` rather than failing the analysis:
``incoherent_error`` never depends on it.
"""
element_kind = "qubit"
expects_calibration_points = True
parameters: PurityBenchmarkingParameters
def __init__(
self,
parameters: PurityBenchmarkingParameters,
qoi_cls: type[PurityBenchmarkingQOI],
):
super().__init__(parameters, qoi_cls)
self.cliffords_coord = None
self.basis_coord = None
self.seeds_coord = None
self.number_cliffords = None
self.fit_n_cliffords = None
self.purity_traces = None
self.mean_purity = None
self.sigma_purity = None
self.fidelity = None
self.fidelity_error = None
self.reduced_chi2 = None
self.fit_y = None
self.incoherent_error = None
self.incoherent_error_error = None
self.coherent_error = None
self.coherent_error_error = None
[docs]
@override
def compute_qoi(self) -> PurityBenchmarkingQOI:
data_array = self.dataset[self.data_var]
for coord in data_array.coords:
coord_str = str(coord)
if "cliffords" in coord_str:
self.cliffords_coord = coord
elif "basis" in coord_str:
self.basis_coord = coord
elif coord_str == "seeds":
self.seeds_coord = coord
element_name = self.qubit if self.qubit is not None else self.element
try:
calib = cal.get_calibration_complex(self.dataset, element_name)
except cal.CalibrationPointsError:
return self.qoi_cls(is_successful=False)
shots = self.S21[self.data_var]
projected = cal.project_onto_calibration(shots, calib, low=0, high=1)
x_exp = 2 * projected.sel({self.basis_coord: X_BASIS}) - 1
y_exp = 2 * projected.sel({self.basis_coord: Y_BASIS}) - 1
z_exp = 2 * projected.sel({self.basis_coord: Z_BASIS}) - 1
# Each exp value is a finite-shot sample mean of a +/-1-valued
# projective measurement, so naively squaring it is a biased
# estimator of the true <P>**2: E[m**2] = <P>**2 + (1-<P>**2)/N.
# Solving for <P>**2 gives the standard unbiased purity estimator
# (Wallman et al., New J. Phys. 17 113020 (2015), eq. 5):
# <P>**2_hat = (N * m**2 - 1) / (N - 1). Without this correction,
# purity is systematically overestimated by ~3/N per point (worse
# when the true Pauli expectations are small, e.g. deep into the
# decay), and individual (seed, cliffords) points can land above
# the physical purity<=1 bound even on average.
n_shots = self.parameters.repetitions
purity_raw = x_exp**2 + y_exp**2 + z_exp**2
purity = ((n_shots * purity_raw - 3) / (n_shots - 1)).transpose(
self.seeds_coord, self.cliffords_coord
)
self.number_cliffords = self.dataset[self.cliffords_coord].values
self.fit_n_cliffords = np.linspace(
self.number_cliffords.min(), self.number_cliffords.max(), 400
)
self.purity_traces = purity.values
self.mean_purity = purity.mean(dim=self.seeds_coord).transpose(
self.cliffords_coord
)
self.sigma_purity = purity.std(dim=self.seeds_coord, ddof=1).transpose(
self.cliffords_coord
)
fit_result = self._fit_purity(self.mean_purity.values)
if fit_result is None:
return self.qoi_cls(is_successful=False)
self.fidelity = fit_result.params["p"].value
self.fidelity_error = fit_result.params["p"].stderr or 0.0
self.reduced_chi2 = float(fit_result.redchi)
self.fit_y = fit_result.eval(m=self.fit_n_cliffords)
unitarity = max(self.fidelity, 0.0)
self.incoherent_error = QUBIT_DIMENSION_FACTOR * (1 - np.sqrt(unitarity))
# d(incoherent_error)/d(unitarity) = -1 / (4 * sqrt(unitarity)).
self.incoherent_error_error = self.fidelity_error / (
4 * np.sqrt(max(unitarity, 1e-6))
)
rb_fidelity, rb_fidelity_error = self._read_rb_fidelity(element_name)
if rb_fidelity is None:
self.coherent_error = float("nan")
self.coherent_error_error = float("nan")
else:
total_error = 1.0 - rb_fidelity
self.coherent_error = total_error - self.incoherent_error
self.coherent_error_error = float(
np.hypot(rb_fidelity_error, self.incoherent_error_error)
)
return self.qoi_cls(
is_successful=True,
purity_fidelity=self.fidelity,
purity_fidelity_error=self.fidelity_error,
reduced_chi2=self.reduced_chi2,
incoherent_error=self.incoherent_error,
incoherent_error_error=self.incoherent_error_error,
coherent_error=self.coherent_error,
coherent_error_error=self.coherent_error_error,
)
def _read_rb_fidelity(self, element_name: str) -> tuple[float | None, float | None]:
"""Read back the ``rb_fidelity`` trusted value for ``element_name``.
Written by ``RandomizedBenchmarking`` via
``update_redis_trusted_values`` (``transmons:{qubit}`` hash, fields
``rb_fidelity`` / ``rb_fidelity_error``) — there is no other
cross-node result-lookup mechanism in this codebase (mirrors
``cz_currents_from_spectroscopies``'s own raw Redis read).
Returns ``(None, None)`` if there's no active session or RB's result
isn't in Redis.
"""
redis_connection = None
try:
redis_connection = ActiveSession.get().redis_connection
except RuntimeError:
pass
if redis_connection is not None:
value = redis_connection.hget(f"transmons:{element_name}", "rb_fidelity")
if value is not None:
error = redis_connection.hget(
f"transmons:{element_name}", "rb_fidelity_error"
)
return float(value), float(error) if error is not None else 0.0
logger.warning(
f"⚠️ No 'rb_fidelity' found for {element_name} (no Redis value or "
"no active session) — run RandomizedBenchmarking first to get a "
"coherent_error decomposition. Reporting coherent_error as NaN."
)
return None, None
def _fit_purity(self, mean_purity_values: np.ndarray):
sigma = np.maximum(self.sigma_purity.values, 1e-6)
model = RBDecayModel()
guess = model.guess(mean_purity_values, m=self.number_cliffords)
try:
fit_result = model.fit(
mean_purity_values,
params=guess,
m=self.number_cliffords,
weights=1.0 / sigma,
)
except Exception:
try:
fit_result = model.fit(
mean_purity_values, params=guess, m=self.number_cliffords
)
except Exception:
return None
if not fit_result.errorbars:
return None
return fit_result
# TODO Fix this so e_coh can be seen in replotting, Issue #329
[docs]
@override
def plot_title(self) -> str:
return f"Purity Benchmarking — {self.element}"
[docs]
@override
def add_traces(self, fig, row: int = 1, col: int = 1) -> None:
if self.purity_traces is not None:
for seed_purity in self.purity_traces:
fig.add_trace(
go.Scatter(
x=self.number_cliffords,
y=seed_purity,
mode="markers",
marker={"size": 4, "color": "gray"},
opacity=0.3,
showlegend=False,
),
row=row,
col=col,
)
if self.mean_purity is not None:
fig.add_trace(
go.Scatter(
x=self.number_cliffords,
y=self.mean_purity.values,
mode="markers",
marker={"size": 7, "color": "blue"},
name="Mean purity",
showlegend=True,
),
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": "blue", "width": 2, "dash": "dash"},
showlegend=False,
),
row=row,
col=col,
)
label_lines = [
f"u = {self.fidelity:.4f} ± {self.fidelity_error:.4f}",
f"χ²/DOF = {self.reduced_chi2:.2f}",
f"ε_inc = {self.incoherent_error:.4f} ± {self.incoherent_error_error:.4f}",
]
if self.coherent_error is not None and not np.isnan(self.coherent_error):
label_lines.append(
f"ε_coh = {self.coherent_error:.4f} ± {self.coherent_error_error:.4f}"
)
else:
label_lines.append("ε_coh = N/A (no RB result)")
label_box(fig, "<br>".join(label_lines), row=row, col=col)
else:
fig.add_annotation(
text="Purity fit failed — check calibration.",
xref="x domain",
yref="y domain",
x=0.5,
y=0.5,
xanchor="center",
yanchor="middle",
showarrow=False,
font={"size": 10, "color": "red"},
row=row,
col=col,
)
fig.update_xaxes(title_text="Number of Cliffords", row=row, col=col)
fig.update_yaxes(title_text="Purity", row=row, col=col)