Source code for bragi_quantum.experiments.registry

# ══════════════════════════════════════════════════════════════════════════
#     ___   ___ ___   _      _   ___
#    / _ \ / __|_  ) | |    /_\ | _ )
#   | (_) | (__ / /  | |__ / _ \| _ \
#    \__\_\\___/___| |____/_/ \_\___/
#
#   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
#   Yanchen Lin, linya@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


"""Access to the bragi_quantum.experiments node registry."""

import importlib
import typing
from dataclasses import dataclass, field
from importlib.resources import files
from typing import Any

import yaml
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator

from bragi_quantum.experiments.abstract.errors import ExperimentRegistryError

_REGISTRY_FILE = "nodes.yaml"


[docs] class RequiresSpec(BaseModel): """A variant's dependency on gates/parameters. See schema in nodes.yaml""" model_config = ConfigDict( extra="forbid", strict=True, frozen=True, validate_default=True ) measure_gate_class: str | None = None calibrated_gates: list[str] = Field(default_factory=list) calibrated_parameters: list[str] = Field(default_factory=list)
[docs] class VariantEntry(BaseModel): """One concrete variant of a node entry. See schema in nodes.yaml""" model_config = ConfigDict( extra="forbid", strict=True, frozen=True, validate_default=True ) name: str qoi: str parameters: dict[str, Any] = Field(default_factory=dict) requires: RequiresSpec | None = None calibrates: list[str] = Field(default_factory=list) show_in_graph: bool = True
[docs] class NodeEntry(BaseModel): """One registry entry. See schema in nodes.yaml""" model_config = ConfigDict( extra="forbid", strict=True, frozen=True, validate_default=True ) node: str analysis: str doc: str | None = None variants: list[VariantEntry] = Field(min_length=1)
[docs] class NodeCategory(BaseModel): """A group of entries sharing an import root (e.g. ``readout``).""" model_config = ConfigDict( extra="forbid", strict=True, frozen=True, validate_default=True ) package: str entries: dict[str, NodeEntry]
[docs] class NodeRegistryFile(BaseModel): """The validated shape of ``nodes.yaml``.""" model_config = ConfigDict( extra="forbid", strict=True, frozen=True, validate_default=True ) nodes: dict[str, NodeCategory] @model_validator(mode="after") def _variant_names_are_globally_unique(self) -> "NodeRegistryFile": # load_node_registry() flattens every entry's variants into one dict # keyed by name, so a collision anywhere would silently shadow one. seen: dict[str, str] = {} for cat_name, cat in self.nodes.items(): for entry_name, entry in cat.entries.items(): for variant in entry.variants: location = f"{cat_name}.{entry_name}" if variant.name in seen: raise ValueError( f"Duplicate variant name {variant.name!r}: " f"registered by both {seen[variant.name]!r} and " f"{location!r}." ) seen[variant.name] = location return self
def _import(package: str, target: str) -> type: """Import ``"module:ClassName"``, with the module relative to ``package``.""" module_name, _, class_name = target.partition(":") full_module = f"{package}.{module_name}" try: module = importlib.import_module(full_module) except ModuleNotFoundError as e: raise ExperimentRegistryError( f"Cannot import module {full_module!r}: {e}" ) from e try: return getattr(module, class_name) except AttributeError as e: raise ExperimentRegistryError( f"Module {full_module!r} has no attribute {class_name!r}" ) from e
[docs] @dataclass(frozen=True) class ExperimentNodeVariant: """A registered node variant, ready to be instantiated. Attributes: name: The stable registry name of the variant. node_cls: The node class to instantiate. qoi_cls: QOI class injected as ``qoi_cls``. analysis_cls: Analysis class injected as ``analysis_cls``. category: The top-level ``nodes.yaml`` category this variant's entry lives under (e.g. ``"readout"``). parameters: Fixed parameter values that define the variant (e.g. ``{"state": 1, "transition": "12"}``). These always win over caller-supplied overrides in :meth:`create`. requires: The variant's declared gate/parameter dependencies, if any. calibrates: The redis keys this variant's QOI writes. doc: The entry's ``docs/node-library/nodes/<doc>.md`` stem, if any. show_in_graph: Whether this variant should appear in the docs dependency graph. """ name: str node_cls: type qoi_cls: type analysis_cls: type category: str parameters: dict[str, Any] = field(default_factory=dict) requires: RequiresSpec | None = None calibrates: list[str] = field(default_factory=list) doc: str | None = None show_in_graph: bool = True @property def parameters_cls(self) -> type: """The node's Parameters model, from its ``__init__`` annotation.""" return typing.get_type_hints(self.node_cls.__init__)["parameters"]
[docs] def create(self, **parameter_overrides: Any): """Build the node: validate parameters, inject QOI/analysis classes. Must be called inside an active calibration session (node ``__init__`` requires it). ``parameter_overrides`` are free (sweep sizes, qubits, ...) but cannot override the spec's own ``parameters`` — those define the variant's identity. """ conflicts = parameter_overrides.keys() & self.parameters.keys() if conflicts: raise ExperimentRegistryError( f"{self.name!r} pins {sorted(conflicts)} to fixed values " f"({ {k: self.parameters[k] for k in sorted(conflicts)} }) " f"that define the variant's identity; caller passed " f"{ {k: parameter_overrides[k] for k in sorted(conflicts)} }, " f"which would silently be discarded." ) values = {"name": self.name, **parameter_overrides, **self.parameters} parameters = self.parameters_cls(**values) node = self.node_cls(parameters=parameters, qoi_cls=self.qoi_cls) node.analysis_cls = self.analysis_cls return node
[docs] def load_node_registry() -> dict[str, ExperimentNodeVariant]: """Return the registered node variants as ``{variant_name: ExperimentNodeVariant}``. Reads ``bragi_quantum.experiments/nodes.yaml``, validates it against :class:`NodeRegistryFile`, then imports each referenced class. Every entry's ``variants`` are flattened into this one dict, keyed by each variant's own ``name``. """ raw = ( files("bragi_quantum.experiments") .joinpath(_REGISTRY_FILE) .read_text(encoding="utf-8") ) try: registry = NodeRegistryFile.model_validate(yaml.safe_load(raw)) except ValidationError as e: raise ExperimentRegistryError(f"Invalid {_REGISTRY_FILE}: {e}") from e return { variant.name: ExperimentNodeVariant( name=variant.name, node_cls=_import(cat.package, entry.node), qoi_cls=_import(cat.package, variant.qoi), analysis_cls=_import(cat.package, entry.analysis), category=cat_name, parameters=variant.parameters, requires=variant.requires, calibrates=variant.calibrates, doc=entry.doc, show_in_graph=variant.show_in_graph, ) for cat_name, cat in registry.nodes.items() for entry in cat.entries.values() for variant in entry.variants }