# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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
# ══════════════════════════════════════════════════════════════════════════
from abc import ABC, abstractmethod
from collections.abc import Mapping
from types import MappingProxyType
from typing import Any, ClassVar, override
from pydantic import BaseModel, ConfigDict, model_validator
from bragi_quantum.datalayer.models.device import set_nested_value
from bragi_quantum.experiments.abstract.errors import ExperimentParameterError
from bragi_quantum.experiments.abstract.parameter_fields import (
fields_by_category,
is_variant_field,
metadata_field,
)
from bragi_quantum.experiments.abstract.variant_types import is_finite_type
from bragi_quantum.experiments.abstract.variant_types import (
legal_variant_combinations as _compute_legal_variant_combinations,
)
CustomParameters = dict[str, dict[str, Any]]
ParameterCombination = Mapping[str, Any]
[docs]
class BaseParameters(BaseModel):
"""
Configuration parameters for a Calibration Node.
Pydantic ensures these are validated before a node execution begins.
Every field is a single default value applied to all elements. To override a
field for specific elements, populate ``custom_parameters`` with a mapping
``{field_name: {element_name: value}}``; ``for_qubit`` / ``for_coupler`` then
resolve a copy of these parameters with that element's overrides applied (and
defaults everywhere else). Values are plain data, so ``custom_parameters``
round-trips through JSON/YAML config files.
"""
model_config = ConfigDict(extra="forbid", strict=True)
invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()
@override
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
super().__pydantic_init_subclass__(**kwargs)
for name, info in cls.model_fields.items():
if is_variant_field(cls, name) and not is_finite_type(info.annotation):
raise ExperimentParameterError(
f"{cls.__name__}.{name} is marked variant=True but "
f"{info.annotation!r} is not a finite type (bool, "
"Literal[...], Enum, or a union of those). Variant-"
"defining fields must have an enumerable set of values — "
"see abstract/variant_types.py:is_finite_type."
)
for combination in cls.invalid_variant_combinations:
for field_name in combination:
if not is_variant_field(cls, field_name):
raise ExperimentParameterError(
f"{cls.__name__}.invalid_variant_combinations "
f"references {field_name!r}, which isn't a variant-"
f"defining field."
)
cls.invalid_variant_combinations = tuple(
MappingProxyType(dict(combination))
for combination in cls.invalid_variant_combinations
)
cls.legal_variant_combinations = _compute_legal_variant_combinations(cls)
@model_validator(mode="after")
def _reject_invalid_variant_combinations(self) -> "BaseParameters":
for combination in self.invalid_variant_combinations:
if all(
getattr(self, field) == value for field, value in combination.items()
):
raise ExperimentParameterError(
f"{type(self).__name__}: {combination} is not a valid "
f"combination of variant-defining fields."
)
return self
# Identity / targeting — not tunable knobs; changing one identifies a
# different run rather than re-processing the same data.
name: str = metadata_field(default="")
# Use default_factory to ensure each instance gets a fresh list
qubits: list[str] = metadata_field(default_factory=list)
couplers: list[str] = metadata_field(default_factory=list)
# Per-field, per-element overrides: {field_name: {element_name: value}}. Only
# the fields and elements that should differ from the defaults need listing.
# Structural (a container of overrides), so categorised as metadata.
custom_parameters: CustomParameters = metadata_field(default_factory=dict)
[docs]
def by_category(self) -> dict[str, dict[str, Any]]:
"""Return this instance's field *values* grouped by category.
Maps each category (``"metadata"``, ``"data_acquisition"``,
``"analysis"``, and ``"uncategorized"`` if any field is unlabelled) to
an ``{field_name: value}`` dict. Only non-empty categories are included.
Complements :func:`fields_by_category`, which returns field *names* from
the class; this returns the concrete values from the instance — handy
for inspecting or displaying a parameter set (e.g. in a notebook)::
>>> for cat, fields in params.by_category().items():
... print(cat, fields)
"""
grouped: dict[str, dict[str, Any]] = {}
for name, names in fields_by_category(self).items():
if names:
grouped[name] = {n: getattr(self, n) for n in names}
return grouped
[docs]
def show(self) -> str:
"""Return a human-readable listing of the parameters grouped by category.
Printing the result gives a quick overview of a parameter set and which
knobs are re-tunable at reanalysis (the ``analysis`` group)::
>>> print(params.show())
Metadata fields (``name``, ``qubits``, ``couplers``) are populated by
the orchestrator when a node actually runs; on a bare instance they are
still unset and rendered as ``(unset)`` rather than ``''`` / ``[]``.
"""
def _fmt(value: Any) -> str:
if value is None or (
isinstance(value, (str, list, tuple, dict, set)) and len(value) == 0
):
return "(unset)"
return repr(value)
lines: list[str] = [f"{type(self).__name__}:"]
for category, fields in self.by_category().items():
lines.append(f" [{category}]")
width = max((len(n) for n in fields), default=0)
for name, value in fields.items():
lines.append(f" {name:<{width}} = {_fmt(value)}")
return "\n".join(lines)
def _for_element(self, element: str) -> "BaseParameters":
"""Return a copy of these parameters with ``element``'s overrides applied.
Fields without an override for this element keep their default value, so
downstream code can keep reading plain scalar fields (e.g.
``parameters.upper_threshold``) and transparently get the per-element value.
"""
unknown = set(self.custom_parameters) - set(type(self).model_fields)
if unknown:
raise ValueError(
f"Unknown custom_parameters field(s): {sorted(unknown)}. "
f"Valid fields: {sorted(type(self).model_fields)}"
)
# Structural/identity fields and variant-defining fields aren't
# per-element measurement settings, so neither may be overridden here.
base_fields = set(BaseParameters.model_fields)
variant_fields = {
name
for name in type(self).model_fields
if is_variant_field(type(self), name)
}
disallowed = set(self.custom_parameters) & (base_fields | variant_fields)
if disallowed:
raise ValueError(
f"custom_parameters cannot override {sorted(disallowed)}: "
f"structural/identity or variant-defining fields are not "
f"per-element measurement settings."
)
patch = {
field: by_element[element]
for field, by_element in self.custom_parameters.items()
if element in by_element
}
if not patch:
return self
return self.model_copy(update=patch)
[docs]
def for_qubit(self, qubit: str) -> "BaseParameters":
"""Resolve these parameters for ``qubit`` (applying any per-qubit overrides)."""
return self._for_element(qubit)
[docs]
def for_coupler(self, coupler: str) -> "BaseParameters":
"""Resolve these parameters for ``coupler`` (applying any per-coupler overrides)."""
return self._for_element(coupler)
[docs]
def resolved_by_qubit(self) -> dict[str, "BaseParameters"]:
"""Return ``{qubit: resolved_parameters}`` for every qubit in ``self.qubits``.
Convenience for nodes building a per-qubit sample space: instead of
repeating ``{q: self.parameters.for_qubit(q) for q in ...}`` in each node,
call ``resolved = self.parameters.resolved_by_qubit()`` once and read
``resolved[q].<field>``. Qubits without overrides map to ``self`` (no
copy), so this is cheap.
"""
return {qubit: self.for_qubit(qubit) for qubit in self.qubits}
[docs]
def resolved_by_coupler(self) -> dict[str, "BaseParameters"]:
"""Return ``{coupler: resolved_parameters}`` for every coupler in ``self.couplers``.
Coupler-node analogue of :meth:`resolved_by_qubit`.
"""
return {coupler: self.for_coupler(coupler) for coupler in self.couplers}
[docs]
class BaseQoi(BaseModel, ABC):
"""
Base class for Quantities of Interest (QOI).
This stores the results of an experiment/analysis to be
persisted back into the bragi_quantum.datalayer models.
"""
is_successful: bool = False
timestamp: str | None = None
_Hz_to_GHz: float = 1e-9
_amp_to_milliamp: float = 1e3
@property
def Hz_to_GHz(self):
return self._Hz_to_GHz
@property
def _amp_to_milliamp(self):
return self._amp_to_milliamp
[docs]
@abstractmethod
def to_dict(self) -> dict[str, Any]:
"""
Returns the calculated QOIs as a dictionary.
The keys should match the attribute paths in the bragi_quantum.datalayer models
(e.g., {'rxy.amp180': 0.5}).
"""
return {}
[docs]
def update_model(self, model: Any):
"""
Directly injects the QOI results into a bragi_quantum.datalayer model instance
(e.g., an ExtendedTransmon).
"""
results = self.to_dict()
# We can leverage the 'set_nested_value' utility we wrote earlier
# to apply these results directly to the Python object.
for path, value in results.items():
try:
set_nested_value(model, path, value)
except AttributeError:
# Log or handle cases where a result doesn't map to the model
pass