# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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
# Matteo Robbiati, robbiati@chalmers.se
# ══════════════════════════════════════════════════════════════════════════
"""
The single-qubit Clifford group (24 elements) decomposed into physical XY
rotations, used to find the recovery/inverse operation of a random Clifford
sequence for randomized benchmarking.
Correctness is enforced at the group level, not the element level:
``S4ElementXY`` just turns its physical pulses into a Pauli Transfer Matrix
(PTM), while ``S4GroupPTM`` validates that its tabulated elements actually
form a group (closed, contains the identity, every element has an inverse)
rather than checking each element's angles in isolation.
``S4GroupPTM`` also builds a PTM -> index lookup table lazily on first use
and caches it for the group's lifetime (``functools.cached_property``). At
24 elements this barely matters, but it's built this way because it will:
the two-qubit Clifford group has 11,520 elements, and ``recovery()`` gets
called once per random RB sequence -- a linear scan over that many elements,
every time, is not something you want to pay for repeatedly.
Ported from tergite-autocalibration's
``utils/clifford_elements_decomposition.py``.
"""
from functools import cached_property
from typing import ClassVar, override
import numpy as np
from pydantic import BaseModel, ConfigDict, model_validator
from bragi_quantum.datalayer.utils.logging import logger
[docs]
class Clifford1XYdecomp_pulse(BaseModel):
"""A single physical rotation ``Rxy(theta, phi)``, in degrees."""
model_config = ConfigDict(strict=True, extra="forbid", frozen=True)
theta: int
phi: int
@model_validator(mode="after")
def _restrict_angles(self) -> "Clifford1XYdecomp_pulse":
if self.theta == 0:
if self.phi != 0:
raise ValueError("phi must be 0° if theta is 0°")
elif self.theta not in {-180, -90, 90, 180}:
raise ValueError(
f"theta must be 0° or one of ±90°/±180°, got {self.theta}°"
)
if self.phi not in {0, 90}:
raise ValueError(f"phi must be 0° or 90°, got {self.phi}°")
return self
[docs]
class S4ElementXY(BaseModel):
"""One of the 24 single-qubit Cliffords, decomposed into 1-3 physical XY pulses.
Modulo global phase, the single-qubit Clifford group is exactly the
rotational symmetry group of the octahedron whose vertices are the six
Pauli eigenstates on the Bloch sphere -- a group of order 24 isomorphic
to S4, the symmetric group on 4 elements.
"""
model_config = ConfigDict(strict=True, extra="forbid", frozen=True)
pulses: tuple[Clifford1XYdecomp_pulse, ...]
[docs]
@classmethod
def from_angles(cls, *pulses: tuple[int, int]) -> "S4ElementXY":
"""Build from ``(theta, phi)`` pairs, e.g. ``(90, 0)``."""
return cls(
pulses=tuple(
Clifford1XYdecomp_pulse(theta=theta, phi=phi) for theta, phi in pulses
)
)
# theta is only ever one of ±90° or ±180° (the only physical XY rotations
# used by the table below), at which cos/sin are each exactly one of
# -1, 0, 1 -- so instead of going through deg2rad and a floating-point
# comparison, the values are just looked up directly for the exact angle.
@staticmethod
def _x_ptm(theta: int) -> np.ndarray:
match theta:
case 90:
cos, sin = 0, 1
case -90:
cos, sin = 0, -1
case 180 | -180:
cos, sin = -1, 0
case _:
raise ValueError(f"Invalid angle: {theta}°")
return np.array(
[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, cos, -sin], [0, 0, sin, cos]],
dtype=np.int64,
)
@staticmethod
def _y_ptm(theta: int) -> np.ndarray:
match theta:
case 90:
cos, sin = 0, 1
case -90:
cos, sin = 0, -1
case 180 | -180:
cos, sin = -1, 0
case _:
raise ValueError(f"Invalid angle: {theta}°")
return np.array(
[[1, 0, 0, 0], [0, cos, 0, sin], [0, 0, 1, 0], [0, -sin, 0, cos]],
dtype=np.int64,
)
[docs]
def to_ptm(self) -> np.ndarray:
"""The 4x4 Pauli Transfer Matrix of the composed physical pulses.
Unlike the raw 2x2 unitary, the PTM represents conjugation
``rho -> U rho U^dagger`` rather than ``U`` itself, so any global
phase on ``U`` cancels out; this makes the PTM a faithful
representation of PU(2) (unitaries modulo global phase) instead of
U(2), which is what "which Clifford is this" actually means physically.
"""
matrix = np.identity(4, dtype=np.int64)
for pulse in self.pulses:
if pulse.theta == 0 and pulse.phi == 0:
return matrix
if pulse.phi == 0:
ptm = self._x_ptm(pulse.theta)
elif pulse.phi == 90:
ptm = self._y_ptm(pulse.theta)
else:
raise ValueError(f"phi must be 0° or 90°, got {pulse.phi}°")
matrix = np.matmul(ptm, matrix, dtype=np.int64)
return matrix
[docs]
class S4GroupPTM(BaseModel):
"""The 24-element single-qubit Clifford group.
Rather than checking each ``S4ElementXY``'s angles in isolation, this
validates that the tabulated elements actually satisfy the group axioms
as PTMs: exactly 24 distinct elements, closed under composition,
containing the identity, and every element has an inverse within the set.
``elements`` is a ``ClassVar``, not a field: there is exactly one
single-qubit Clifford group, its 24 elements are a fixed mathematical
fact, not per-instance configuration.
"""
model_config = ConfigDict(strict=True, extra="forbid", frozen=True)
elements: ClassVar[tuple[S4ElementXY, ...]] = (
S4ElementXY.from_angles((0, 0)), # 0
S4ElementXY.from_angles((90, 90), (90, 0)), # 1
S4ElementXY.from_angles((-90, 0), (-90, 90)), # 2
S4ElementXY.from_angles((180, 0)), # 3
S4ElementXY.from_angles((-90, 90), (-90, 0)), # 4
S4ElementXY.from_angles((90, 0), (-90, 90)), # 5
S4ElementXY.from_angles((180, 90)), # 6
S4ElementXY.from_angles((-90, 90), (90, 0)), # 7
S4ElementXY.from_angles((90, 0), (90, 90)), # 8
S4ElementXY.from_angles((180, 0), (180, 90)), # 9
S4ElementXY.from_angles((90, 90), (-90, 0)), # 10
S4ElementXY.from_angles((-90, 0), (90, 90)), # 11
S4ElementXY.from_angles((90, 90), (180, 0)), # 12
S4ElementXY.from_angles((-90, 0)), # 13
S4ElementXY.from_angles((90, 0), (-90, 90), (-90, 0)), # 14
S4ElementXY.from_angles((-90, 90)), # 15
S4ElementXY.from_angles((90, 0)), # 16
S4ElementXY.from_angles((90, 0), (90, 90), (90, 0)), # 17
S4ElementXY.from_angles((-90, 90), (180, 0)), # 18
S4ElementXY.from_angles((90, 0), (180, 90)), # 19
S4ElementXY.from_angles((90, 0), (-90, 90), (90, 0)), # 20
S4ElementXY.from_angles((90, 90)), # 21
S4ElementXY.from_angles((-90, 0), (180, 90)), # 22
S4ElementXY.from_angles((90, 0), (90, 90), (-90, 0)), # 23
)
def __len__(self) -> int:
return len(self.elements)
def __getitem__(self, index):
return self.elements[index]
@override
def __iter__(self):
return iter(self.elements)
@cached_property
def _ptm_lookup(self) -> dict[bytes, int]:
"""Maps each element's PTM (as exact-integer bytes) to its index.
Built lazily on first access and cached for the group's lifetime --
note this relies on ``cached_property`` writing straight into
``self.__dict__``, which bypasses pydantic's ``frozen=True``
``__setattr__`` guard rather than going through it. That's why this
works on a frozen model at all; don't "simplify" it into a plain
``@property`` recomputed every call, and don't refactor the model to
block direct ``__dict__`` writes without re-checking this still works.
"""
logger.info("💾 Caching PTM lookup table for S4GroupPTM")
return {
element.to_ptm().tobytes(): i for i, element in enumerate(self.elements)
}
[docs]
def index_of(self, ptm: np.ndarray) -> int:
"""The index of the element whose PTM is ``ptm``.
Only meaningful for a PTM that is actually one of the group's own
elements (e.g. a product or inverse of tabulated PTMs) -- guaranteed
to be found by the group axioms checked in ``_check_group_axioms``.
"""
return self._ptm_lookup[ptm.tobytes()]
[docs]
def net_ptm(self, rng_sequence: np.ndarray) -> np.ndarray:
"""The composed PTM of the physical pulses for a sequence of element indices."""
matrix = np.identity(4, dtype=np.int64)
for index in rng_sequence:
matrix = np.matmul(self.elements[index].to_ptm(), matrix, dtype=np.int64)
return matrix
[docs]
def recovery(self, rng_sequence: np.ndarray) -> tuple[int, S4ElementXY]:
"""Find the Clifford (and its index) that inverts the net Clifford
operation of ``rng_sequence``, so appending it recovers the identity.
The group is closed and every element has an inverse (checked once,
by ``_check_group_axioms``), so the recovery element is guaranteed to
exist -- no defensive "not found" handling needed. Since every PTM
here is an orthogonal integer matrix, its inverse is just its
transpose, so there's no need for ``np.linalg.inv`` either.
"""
index = self.index_of(self.net_ptm(rng_sequence).T)
logger.debug(f"{index=}")
return index, self.elements[index]
@model_validator(mode="after")
def _check_group_axioms(self) -> "S4GroupPTM":
ptms = [element.to_ptm() for element in self.elements]
if len(ptms) != 24:
raise ValueError(
f"the single-qubit Clifford group has 24 elements, got {len(ptms)}"
)
seen = set()
for i, ptm in enumerate(ptms):
key = ptm.tobytes()
if key in seen:
raise ValueError(f"element {i} duplicates an earlier element's PTM")
seen.add(key)
# from here on, reuse (and thereby build) the cached lookup table
# rather than a fresh linear scan per check -- with 24 elements it's
# a wash, but this is what keeps closure below O(n^2) instead of
# O(n^3) once the table this validates is the 11,520-element
# two-qubit group instead.
lookup = self._ptm_lookup
if np.identity(4, dtype=np.int64).tobytes() not in lookup:
raise ValueError("group does not contain the identity element")
for i, a in enumerate(ptms):
for j, b in enumerate(ptms):
if np.matmul(a, b, dtype=np.int64).tobytes() not in lookup:
raise ValueError(
f"group is not closed under composition: element {i} "
f"followed by element {j} is not one of the 24 elements"
)
for i, ptm in enumerate(ptms):
if ptm.T.tobytes() not in lookup:
raise ValueError(f"element {i} has no inverse within the group")
return self
# Shared singleton -- instantiating S4GroupPTM re-triggers its lazy PTM
# lookup-table build (and log line) each time, so every caller imports this
# instead of constructing their own.
CLIFFORD_GRP_1Q = S4GroupPTM()