Source code for bragi_quantum.datalayer.models.device

# ══════════════════════════════════════════════════════════════════════════
#     ___   ___ ___   _      _   ___
#    / _ \ / __|_  ) | |    /_\ | _ )
#   | (_) | (__ / /  | |__ / _ \| _ \
#    \__\_\\___/___| |____/_/ \_\___/
#
#   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:
#
#   Michele Faucci Giannelli, faucci@chalmers.se
#   Matteo Robbiati, robbiati@chalmers.se
#   Axel Andersson, axean@chalmers.se
#   Yanchen Lin, linya@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


# This code is part of Tergite
#
# (C) Copyright Eleftherios Moschandreou 2024
# (C) Copyright Stefan Hill 2024
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
#
# Modified from tergite-autocalibration
# (https://github.com/tergite/tergite-autocalibration), file:
#   tergite_autocalibration/lib/utils/device.py


from __future__ import annotations

import datetime
import json
import logging
from pathlib import Path
from typing import Any, Literal

import yaml
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, field_validator
from qblox_scheduler.device_under_test.quantum_device import (
    QuantumDevice,
)
from qblox_scheduler.json_utils import SchedulerJSONEncoder

from bragi_quantum.datalayer.models.coupler import ExtendedCompositeSquareEdge
from bragi_quantum.datalayer.models.qubit import ExtendedTransmon
from bragi_quantum.datalayer.utils.device.spi import SpiDAC
from bragi_quantum.datalayer.utils.nested import set_nested_value

logger = logging.getLogger(__name__)


# TODO: understand how to lighten the redundancy between qubit-transmon and coupler-edge
# device should have transmon and edges and we could keep the other notation for an higher
# level of abstraction
[docs] class DeviceConfiguration(BaseModel): """ Pydantic model managing the construction and hydration of the QuantumDevice. Supports loading from initial YAML configs or Qblox-standard JSON snapshots. """ model_config = ConfigDict(extra="forbid") qubits: list[str] = Field(default_factory=list) couplers: list[str] = Field(default_factory=list) name: str = Field(default="Unknown Device") owner: str = Field(default="Unknown Owner") last_cooldown: str = Field(default="Unknown") # date or ID of the cooldown # Chip-topology grid sketch, verbatim from device.yaml's `layout:` key. # See bragi_quantum.gui.rendering.device_layout for how it's parsed/rendered. layout: str | None = Field(default=None) # Analysis outputs not held by the live QuantumDevice, kept element-by-element # and node-by-node: {element_id: {node_name: BaseQoi}}. extended_state: dict[str, dict[str, Any]] = Field(default_factory=dict) _raw_device_data: dict[str, Any] = PrivateAttr(default_factory=dict) _transmons: dict[str, ExtendedTransmon] = PrivateAttr(default_factory=dict) _edges: dict[str, ExtendedCompositeSquareEdge] = PrivateAttr(default_factory=dict) _device: QuantumDevice | None = PrivateAttr(default=None) @field_validator("qubits") @classmethod def _validate_qubit_names(cls, v: list[str]) -> list[str]: """Reject qubit names that aren't plain alphanumeric ASCII. Names are matched against the config verbatim everywhere in the toolkit (no normalization is applied), so a name with spaces or symbols would only surface as a confusing lookup failure later. Underscore is also rejected here since it's the reserved qubit-pair separator in coupler names (``qA_qB``) — allowing it in a qubit name would make that split ambiguous. """ invalid = [q for q in v if not (q.isascii() and q.isalnum())] if invalid: raise ValueError( f"Qubit name(s) {invalid} are invalid: names must be " "alphanumeric ASCII characters only, with no spaces, " "underscores, or other symbols." ) return v @field_validator("couplers") @classmethod def _validate_coupler_names(cls, v: list[str]) -> list[str]: """Reject coupler names that aren't ``<qubitA>_<qubitB>`` with alphanumeric ASCII qubit names on both sides.""" invalid = [ c for c in v if len(parts := c.split("_")) != 2 or not all(p.isascii() and p.isalnum() for p in parts) ] if invalid: raise ValueError( f"Coupler name(s) {invalid} are invalid: names must be written " "as '<qubitA>_<qubitB>', where each qubit name is alphanumeric " "ASCII characters only, with no spaces or other symbols." ) return v
[docs] @classmethod def from_yaml(cls, path: Path) -> DeviceConfiguration: """Factory method to load initial hardware configuration from YAML.""" if not path.exists(): raise FileNotFoundError(f"Config not found: {path}") with open(path, encoding="utf-8") as f: full_data = yaml.safe_load(f) device_sect = full_data.get("device", {}) for cat in ["qubit", "resonator", "coupler"]: if cat in device_sect: data = device_sect[cat] defaults = data.pop("all", {}) for k, v in data.items(): if isinstance(v, dict): data[k] = {**defaults, **v} instance = cls( qubits=list(device_sect.get("qubit", {}).keys()), couplers=list(device_sect.get("coupler", {}).keys()), name=device_sect.get("name", "Unknown Device"), owner=device_sect.get("owner", "Unknown Owner"), last_cooldown=str(device_sect.get("last_cooldown", "Unknown")), layout=full_data.get("layout"), ) instance._raw_device_data = device_sect return instance
[docs] @classmethod def from_snapshot(cls, path: Path) -> DeviceConfiguration: """Factory method to load device state from a Qblox snapshot.json.""" if not path.exists(): raise FileNotFoundError(f"Snapshot not found: {path}") with open(path, encoding="utf-8") as f: snapshot_data = json.load(f) instruments = snapshot_data.get("instruments", {}) qubit_names = [] coupler_names = [] # Identify elements by looking for signature submodules in the snapshot for name, inst_data in instruments.items(): submodules = inst_data.get("submodules", {}) if "clock_freqs" in submodules or "rxy" in submodules: qubit_names.append(name) elif "cz" in submodules: coupler_names.append(name) instance = cls(qubits=qubit_names, couplers=coupler_names) instance._raw_device_data = instruments return instance
[docs] def configure_device( self, name: str, is_snapshot: bool = False, ) -> QuantumDevice: """Creates and hydrates the live QuantumDevice.""" safe_name = name.replace("-", "_").replace(" ", "_") device = QuantumDevice(name=f"Device_{safe_name}") # 1. Qubit Hydration for q_index, q_name in enumerate(self.qubits): transmon = ExtendedTransmon(q_name) transmon.measure.acq_channel = ( q_index # Default mapping: qubit index -> acquisition channel ) transmon.measure_1.acq_channel = q_index transmon.measure_2.acq_channel = q_index transmon.measure_2state_opt.acq_channel = q_index transmon.measure_3state_opt.acq_channel = q_index if is_snapshot: inst_data = self._raw_device_data.get(q_name, {}) self._hydrate_from_snapshot_recursive(transmon, inst_data) else: q_specs = self._raw_device_data.get("qubit", {}).get(q_name, {}) for path, value in q_specs.items(): set_nested_value(transmon, path, value) device.add_element(transmon) self._transmons[q_name] = transmon # 2. Coupler Hydration for c_name in self.couplers: p, c = c_name.split("_") if p not in self._transmons or c not in self._transmons: raise ValueError( f"Coupler {c_name!r} references qubit(s) not declared under " f"this device's 'qubit' section: {sorted({p, c} - set(self._transmons))}." ) edge = ExtendedCompositeSquareEdge(p, c) if is_snapshot: inst_data = self._raw_device_data.get(c_name, {}) self._hydrate_from_snapshot_recursive(edge, inst_data) else: c_specs = self._raw_device_data.get("coupler", {}).get(c_name, {}) for path, value in c_specs.items(): set_nested_value(edge, path, value) device.add_edge(edge) self._edges[c_name] = edge self._device = device return device
def _hydrate_from_snapshot_recursive(self, target_obj: Any, snapshot_sect: dict): """ Recursively maps the 'submodules' and 'parameters' structure of a QCoDeS snapshot into the live Python object. """ # Set parameters at this level params = snapshot_sect.get("parameters", {}) for p_name, p_data in params.items(): if hasattr(target_obj, p_name): val = p_data.get("value") # We use set_nested_value to handle QCoDeS parameter .set() logic if val is not None: try: set_nested_value(target_obj, p_name, val) except Exception: continue # Recurse into submodules submodules = snapshot_sect.get("submodules", {}) for s_name, s_data in submodules.items(): if hasattr(target_obj, s_name): self._hydrate_from_snapshot_recursive( getattr(target_obj, s_name), s_data )
[docs] def load_calibration_state(self, redis_connection: Any) -> None: """Overlay previously calibrated values from Redis onto the live device. Counterpart to the YAML hydration in :meth:`configure_device`: it reuses the same ``set_nested_value`` mechanism, so any value backed by a real qblox-scheduler parameter (a Transmon/Edge attribute) is applied in place, while values without such an attribute are silently skipped by ``set_nested_value`` (those live in :attr:`extended_state`). Each ``transmons:{q}`` / ``couplers:{c}`` hash holds calibrated values keyed by ``submodule:field``; ``*_error`` companions and flat keys are ignored. Must be called after :meth:`configure_device`. """ elements = { **{f"transmons:{q}": el for q, el in self._transmons.items()}, **{f"couplers:{c}": el for c, el in self._edges.items()}, } for redis_key, element in elements.items(): for field, value in redis_connection.hgetall(redis_key).items(): if ":" not in field or field.endswith("_error"): continue set_nested_value(element, field.replace(":", "."), value) logger.info("🔁 Loaded calibration state from Redis onto the device.")
[docs] def record_analysis_results(self, element_id: str, node: str, qoi: Any) -> None: """Record a node's analysis QOIs for one element into :attr:`extended_state`. Stores every quantity the analysis produced — including derived ones that have no qblox-scheduler attribute and are therefore not reflected in the live QuantumDevice — keyed by element and by node, giving a real-time, element-by-element / node-by-node record of calibration outputs. """ if not getattr(qoi, "is_successful", False): return qoi.timestamp = datetime.datetime.now().isoformat(timespec="seconds") self.extended_state.setdefault(element_id, {})[node] = qoi
[docs] def save_device( self, name: str, data_path: Path, file_format: Literal["yaml", "json"] = "yaml" ): # TODO: replace this for JSON with a proper qblox save_snapshot """Serializes the live QuantumDevice state to disk.""" if not self._device: raise RuntimeError("Device not configured.") serialized = json.dumps(self._device, cls=SchedulerJSONEncoder) decoded = json.loads(serialized) serial_device = { k: (json.loads(v) if isinstance(v, str) else v) for k, v in decoded.get("elements", {}).items() } data_path.mkdir(parents=True, exist_ok=True) target = data_path / f"{name}.{file_format}" with open(target, "w", encoding="utf-8") as f: if file_format == "yaml": yaml.dump(serial_device, f, sort_keys=False) else: json.dump(serial_device, f, indent=2) logger.info(f"✅ Device state saved at {target}")
[docs] def create_spi_dac( self, spi_config: dict[str, Any] | None = None, spi_serial_port: str = "/dev/ttyACM0", # TODO: this can be exposed at some point. In that case, we can move it to the SessionOptions. is_dummy: bool = False, ) -> SpiDAC: """ Creates and initializes an SpiDAC instance using the device configuration. This method reads the SPI hardware mapping from the provided spi_config dictionary and sets the initial currents based on the calibrated offsets or parking values from the device's couplers. Args: spi_config: Dictionary mapping coupler names to SPI configuration. Expected format: {coupler_name: {spi_module_number, dac_name}} spi_serial_port: Serial port address for the SPI rack (e.g., '/dev/ttyACM0', 'COM4'). is_dummy: If True, initializes a dummy interface for testing. Returns: A fully configured and initialized SpiDAC instance. """ # Initialize the hardware driver spi_handler = SpiDAC(port=str(spi_serial_port), is_dummy=is_dummy) initial_currents = {} # If spi_config is provided, configure DACs based on the loaded YAML configuration if spi_config: for coupler_name, coupler_info in spi_config.items(): # Only initialize DACs for couplers defined in this device if coupler_name not in self.couplers: logger.debug( f"Coupler '{coupler_name}' in SPI config but not in device - skipping" ) continue module_number = coupler_info.get("spi_module_number") dac_name = coupler_info.get("dac_name") if module_number and dac_name: # Register the DAC for this coupler spi_handler.add_coupler_dac( coupler_name=coupler_name, module_number=module_number, dac_name=dac_name, ) # Try to get initial currents from the coupler object if it exists if coupler_name in self._edges: coupler = self._edges[coupler_name] # Priority: 1. parking current (for operations) 2. bias offset (static) current = ( getattr(coupler, "cz_parking_current", None) or getattr(coupler, "bias_offset", None) or 0.0 ) initial_currents[coupler_name] = current else: logger.warning( f"Incomplete SPI config for coupler {coupler_name}. " f"Missing spi_module_number or dac_name. Skipping." ) else: logger.warning( "No SPI configuration provided. Skipping SPI DAC initialization." ) # Batch set the initial currents simultaneously for speed if initial_currents: spi_handler.set_dac_currents(initial_currents, simultaneous=True) return spi_handler
@property def transmons(self): return self._transmons @property def edges(self): return self._edges