Source code for bragi_quantum.datalayer.managing.redis

# ══════════════════════════════════════════════════════════════════════════
#     ___   ___ ___   _      _   ___
#    / _ \ / __|_  ) | |    /_\ | _ )
#   | (_) | (__ / /  | |__ / _ \| _ \
#    \__\_\\___/___| |____/_/ \_\___/
#
#   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
#   Michele Faucci Giannelli, faucci@chalmers.se
#   Joel Sandås, joel.sandas@chalmers.se
#   Matteo Robbiati, robbiati@chalmers.se
#   Yanchen Lin, linya@chalmers.se
#   Emil Hogedal, emil.hogedal@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


# This code is part of Tergite
#
# (C) Copyright Eleftherios Moschandreou 2023, 2024
# (C) Copyright Liangyu Chen 2023, 2024
# (C) Copyright Stefan Hill 2024, 2025
# (C) Copyright Chalmers Next Labs AB 2024
# (C) Copyright Michele Faucci Giannelli 2025
#
# 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/redis.py


import datetime
import json
from typing import Any

import numpy as np

from bragi_quantum.datalayer.models.device import DeviceConfiguration
from bragi_quantum.datalayer.utils.logging import logger

# meta: Global hash holding cross-cutting calibration metadata.
# Distinct from the per-element ``cs:{element}`` status hashes (which record per-node state).
CALIBRATION_KEYS = {
    "meta": "calibration:meta",
    "couplers": "couplers",
    "transmons": "transmons",
    "cs": "cs",
}


[docs] def populate_initial_redis_parameters( device_config: DeviceConfiguration, redis_connection: Any, force: bool = False ): """ Seeds the initial parameters from the bragi_quantum.datalayer DeviceConfiguration into Redis. By default this is a *seed-if-missing* operation (``HSETNX``): YAML provides topology and core defaults, but any field already present in Redis — typically a previously calibrated value — is left untouched. This is what lets the device.yaml stay authoritative for defaults while Redis stays authoritative for calibrated state. Args: device_config: Source of the default parameters (``_raw_device_data`` with ``all`` inheritance already applied). redis_connection: Live Redis connection. force: When True, overwrites existing fields too (``HSET``). Use only for a deliberate clean re-seed from the template. """ write = ( (lambda key, field, value: redis_connection.hset(key, field, value)) if force else (lambda key, field, value: redis_connection.hsetnx(key, field, value)) ) mode = "overwriting" if force else "seed-if-missing" logger.info(f"Seeding initial parameters to Redis ({mode})...") # The _raw_device_data already has 'all' inheritance applied raw_data = device_config._raw_device_data # 1. Populate Qubits (Transmons) qubit_sect = raw_data.get("qubit", {}) for q_name, params in qubit_sect.items(): redis_key = f"transmons:{q_name}" for path, value in params.items(): # Tergite expects colons for submodules in Redis # e.g., 'measure.pulse_amp' -> 'measure:pulse_amp' redis_field = path.replace(".", ":") write(redis_key, redis_field, str(value)) logger.debug(f"Seeded Redis for {q_name}") # 2. Populate Couplers coupler_sect = raw_data.get("coupler", {}) for c_name, params in coupler_sect.items(): redis_key = f"couplers:{c_name}" for path, value in params.items(): redis_field = path.replace(".", ":") write(redis_key, redis_field, str(value)) logger.debug(f"Seeded Redis for {c_name}") logger.info("✅ Redis seeding from DeviceConfiguration complete.")
[docs] def record_calibration_metadata( redis_connection: Any, node: str, components: list, timestamp: str | None = None, ): """Update the global calibration metadata after a node finishes calibrating. A node typically calibrates several components (qubits/couplers) in parallel, so ``last_calibrated_components`` holds the full list calibrated in the last node execution. Stored under the ``calibration:meta`` hash: - ``last_experiment_at``: ISO timestamp of the last calibration experiment - ``last_node``: name of the last calibrated node - ``last_calibrated_components``: JSON list of the components calibrated by it """ if timestamp is None: timestamp = datetime.datetime.now().isoformat(timespec="seconds") redis_connection.hset( CALIBRATION_KEYS["meta"], mapping={ "last_experiment_at": timestamp, "last_node": node, "last_calibrated_components": json.dumps(list(components)), }, )
[docs] def read_calibration_metadata(redis_connection: Any) -> dict: """Return the global calibration metadata hash, decoding the components list. Returns an empty dict if no calibration metadata has been recorded yet. """ meta = redis_connection.hgetall(CALIBRATION_KEYS["meta"]) or {} if "last_calibrated_components" in meta: try: meta["last_calibrated_components"] = json.loads( meta["last_calibrated_components"] ) except (json.JSONDecodeError, TypeError): pass return meta
[docs] def read_calibration_values(redis_connection: Any, key: str, elements: list) -> dict: """Read the full calibration hash for each element under a key prefix. Each element has its own Redis hash (e.g. ``transmons:q06``, ``cs:q06``), fetched in full via ``HGETALL``. Elements that fail to read (e.g. Redis connection issues) are logged and resolve to ``None`` rather than raising, so one bad element doesn't abort the whole batch. """ result = {} for element in elements: redis_key = f"{key}:{element}" try: result[element] = redis_connection.hgetall(redis_key) except Exception as e: logger.warning(f"Failed to read Redis hash '{redis_key}'. {e}") result[element] = None return result
[docs] def read_all_calibration_values(redis_connection: Any) -> dict: """Read all calibration values from Redis, i.e. dump redis.""" meta = read_calibration_metadata(redis_connection) all_values = {} for key in [ CALIBRATION_KEYS["couplers"], CALIBRATION_KEYS["transmons"], CALIBRATION_KEYS["cs"], ]: try: all_values[key] = redis_connection.hgetall(key) except Exception as e: logger.warning(f"Failed to read all fields from Redis hash '{key}'. {e}") all_values[key] = {} return {"metadata": meta, "values": all_values}
np.set_printoptions(legacy="1.25")
[docs] def update_redis_trusted_values( node: str, this_element: str, qoi: Any = None, redis_connection: Any = None, ): """ Update the redis trusted values for the qubit or coupler. Args: node: The node name this_element: The element name (qubit or coupler) qoi: The quantity of interest as QOI wrapped object redis_connection: The Redis connection object redis_fields: List of redis fields for additional verification """ if "_" in this_element: name = "couplers" _qoi_items = dict(qoi.items()) if _are_two_qubit_in_qoi(_qoi_items, this_element): _save_parameters_in_qubits_in_coupler( node=node, this_element=this_element, name=name, qoi=qoi, redis_connection=redis_connection, ) else: _save_parameters_in_coupler( node=node, this_element=this_element, name=name, qoi=qoi, redis_connection=redis_connection, ) else: name = "transmons" _save_parameters_in_transmon( node=node, this_element=this_element, name=name, qoi=qoi, redis_connection=redis_connection, )
def _are_two_qubit_in_qoi(qoi: dict, coupler: str) -> bool: """True if ``qoi``'s keys are exactly the two qubits making up ``coupler``. Distinguishes a QOI keyed by qubit (``{"q16": ..., "q17": ...}``, one entry per qubit of the coupler) from one keyed by coupler-level field names — checked against the coupler's own name rather than a naming convention, so it works for any qubit name. """ return set(qoi) == set(coupler.split("_")) def _redis_safe_value(value: Any) -> Any: """Coerce a QOI value into something ``redis.hset`` accepts. ``hset`` only accepts flat scalars (str/int/float/bytes); a QOI's ``to_redis_dict()`` value can also be a list/tuple/``np.ndarray`` (e.g. integration weights) since the same dict is also ``setattr``'d directly onto the live device (see ``bragi_quantum.experiments.abstract.node.BaseNode._apply_qoi_to_device``), where it must stay an array-like. JSON-encode it here instead, at the point it actually reaches Redis — mirrors how ``record_calibration_metadata`` encodes ``last_calibrated_components``. Decode with ``json.loads`` on read. """ if isinstance(value, np.ndarray): value = value.tolist() if isinstance(value, (list, tuple)): return json.dumps(list(value)) return value def _save_parameters_in_transmon( node: str, this_element: str, name, qoi: Any, redis_connection: Any ): """ Saves the parameters for a single qubit in redis Args: node: Name of the node to update this_element: Name of the element to update, this will be e.g. q01 name: Name of the property to update e.g. the qubit frequency qoi: The QOI object with the value to update Raises: ValueError: if there are parameters in the qubit object that are not part of the node """ if qoi.is_successful: for qoi_name, qoi_result in qoi.to_redis_dict().items(): value = _redis_safe_value(qoi_result["value"]) redis_connection.hset(f"{name}:{this_element}", qoi_name, value) # Saving the error to the measured value error = qoi_result["error"] # TODO: is this reasonable? I am not sure we want error 0 in this case. # Convert None to 0.0 since Redis cannot store None values error = 0.0 if error is None else error redis_connection.hset(f"{name}:{this_element}", qoi_name + "_error", error) redis_connection.hset(f"cs:{this_element}", node, "calibrated") else: logger.warning(f"Analysis failed for {this_element}") def _save_parameters_in_coupler( node: str, this_element: str, name: str, qoi: Any, redis_connection: Any ): """ Saves the parameters for a coupler in redis Args: node: Name of the node to update this_element: Name of the element to update, this will be e.g. q01_q02 for the coupler name: Name of the property to update e.g. the dc current qoi: The QOI object with the value to update redis_fields: redis fields from the node to be updated, this is for verification Raises: ValueError: if there are parameters in the qubit object that are not part of the node """ if qoi.is_successful: for qoi_name, qoi_result in qoi.to_redis_dict().items(): value = _redis_safe_value(qoi_result["value"]) logger.info(f"Updating redis for {this_element} with {qoi_name}: {value}") redis_connection.hset(f"{name}:{this_element}", qoi_name, value) error = qoi_result["error"] # Convert None to 0.0 since Redis cannot store None values error = 0.0 if error is None else error logger.info( f"Updating redis for {this_element} with {qoi_name}_error: {error}" ) redis_connection.hset(f"{name}:{this_element}", qoi_name + "_error", error) redis_connection.hset(f"cs:{this_element}", node, "calibrated") else: logger.warning(f"Analysis failed for {this_element}") def _save_parameters_in_qubits_in_coupler( node: str, this_element: str, name: str, qoi: Any, redis_connection: Any ): """ Saves the parameters for the qubits connected to a coupler, in redis Args: node: Name of the node to update this_element: Name of the element to update, this will be e.g. q01_q02, the qubits are extracted inside the function name: Name of the property to update e.g. the qubit frequency qoi: A dictionary that maps from qubit to the respective QOI redis_fields: redis fields from the node to be updated, this is for verification """ if qoi.is_successful: qubits_in_coupler = [this_element[0:3], this_element[4:7]] for qubit in qubits_in_coupler: for transmon_parameter, value in qoi.to_redis_dict().items(): redis_connection.hset( f"{name}:{this_element}:{qubit}", transmon_parameter, _redis_safe_value(value["value"]), ) redis_connection.hset(f"cs:{this_element}", node, "calibrated") else: logger.warning(f"Analysis failed for {this_element}")