Source code for bragi_quantum.datalayer.utils.device.spi

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


# This code is part of Tergite
#
# (C) Copyright Tong Liu 2024
# (C) Copyright Stefan Hill 2024, 2025
# (C) Copyright Chalmers Next Labs 2025
# (C) Copyright Michele Faucci Giannelli 2025
# (C) Copyright Eleftherios Moschandreou 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/utils/hardware/spi.py


"""
Module for controlling the Qblox SPI Rack DACs.

This module provides the SpiDAC class to manage S4g modules for
coupler biasing and flux control within the bragi_quantum.datalayer framework.
"""

import sys
import time

from colorama import Fore, Style
from colorama import init as colorama_init
from qblox_instruments import SpiRack
from qcodes import validators
from rich.progress import Progress

from bragi_quantum.datalayer.utils.logging import logger

colorama_init()


[docs] class SpiDAC: """ Expert handler for the Qblox SPI Rack and its S4g DAC modules. This class manages the connection to the physical SPI rack and provides methods for safe, ramped current control. Attributes: port (str): Serial port address for the SPI rack. is_dummy (bool): Whether to run in dummy mode. spi (SpiRack): The QCoDeS driver for the SPI rack. dacs_dictionary (dict): Mapping of coupler names to QCoDeS DAC objects. """ def __init__(self, port: str, is_dummy: bool = False): """ Initializes the SPI Rack connection. Args: port: The serial port (e.g., 'COM4' or '/dev/ttyUSB0'). is_dummy: If True, operates in simulation mode. """ self.port = port self.is_dummy = is_dummy self.dacs_dictionary = {} # Fixed instrument name: a second SpiRack in one process would clash with it self.spi = SpiRack("spi_rack", self.port, is_dummy=self.is_dummy) # Perform hardware diagnostics if not self.is_dummy: self._perform_diagnostics() def _perform_diagnostics(self) -> None: """ Performs diagnostic checks on SPI Rack hardware. Logs temperature and voltage information for troubleshooting. Unlocks SPI communication for write operations (critical after power-up). """ try: # Read and log hardware status temperature = self.spi.get_temperature() battery = self.spi.get_battery() logger.info( f"SPI Rack diagnostics: " f"Temperature={temperature:.1f}°C, " f"Battery+={battery[0]:.2f}V, " f"Battery-={battery[1]:.2f}V" ) # CRITICAL: Unlock SPI communication after power-up # Without this, module initialization will fail due to SPI write protection self.spi.unlock() logger.debug("SPI communication unlocked for module initialization") except Exception as e: logger.warning(f"Diagnostic check failed (non-critical): {e}")
[docs] def add_coupler_dac(self, coupler_name: str, module_number: int, dac_name: str): """ Registers and configures a specific DAC channel for a coupler. Args: coupler_name: Name of the coupler (e.g., 'c0_c1'). module_number: Slot number of the S4g module in the rack. dac_name: Name of the DAC channel (e.g., 'dac0'). """ spi_mod_name = f"module{module_number}" if self.is_dummy: self.dacs_dictionary[coupler_name] = f"Dummy_DAC_{spi_mod_name}_{dac_name}" return # Dynamically add the S4g module if not already present if spi_mod_name not in self.spi.instrument_modules: try: # First attempt: default behavior (reset_currents defaults to True) self.spi.add_spi_module(module_number, "S4g") except ValueError as e: error_str = str(e) if "Span" in error_str and "should not be used" in error_str: # Hardware is in corrupted state - log this clearly logger.error( f"SPI module {module_number} hardware corruption detected: {e}. " f"The DAC has invalid span settings. Attempting recovery with explicit reset..." ) # Try again with explicitly forced reset try: self.spi.add_spi_module( module_number, "S4g", reset_currents=True ) logger.warning( f"SPI module {module_number} recovered after hardware reset." ) except ValueError as e2: logger.error( f"SPI module {module_number} recovery failed. Hardware may require manual intervention. " f"Error: {e2}" ) raise else: raise module = self.spi.instrument_modules[spi_mod_name] this_dac = module.instrument_modules[dac_name] # WARNING: this command is bugged on the SPI firmware. When a DAC is operated # for the first time, it sets the current to the minimum -0.25mA, which causes # significant and dangerous heating. this_dac.span("range_min_bi") # Hardware safety limits (±3.1 mA) this_dac.current.vals = validators.Numbers(min_value=-3.1e-3, max_value=3.1e-3) # Default Ramping Configuration this_dac.ramping_enabled(True) this_dac.ramp_rate(300e-6) # 300 uA/s this_dac.ramp_max_step(1e-6) # 1 uA steps self.dacs_dictionary[coupler_name] = this_dac
[docs] def set_dacs_zero(self) -> None: """Sets all registered DACs to zero current safely.""" if self.is_dummy: logger.info("Dummy: Setting all DACs to zero.") return self.spi.set_dacs_zero()
[docs] def set_dac_currents( self, dac_values: dict[str, float], simultaneous: bool = True ) -> None: """ Sets currents for multiple couplers using either simultaneous or serial ramping. Args: dac_values: Dictionary mapping coupler names to current values in Amperes. simultaneous: If True, ramps all channels at once. """ if self.is_dummy: for name, val in dac_values.items(): logger.info(f"Dummy DAC {name} target: {val * 1e3:.4f} mA") return if simultaneous: self.ramp_current_simultaneously(dac_values) else: self.ramp_current_serially(dac_values)
[docs] def ramp_current_simultaneously(self, dac_values: dict[str, float]): """ Starts ramping all specified DACs and waits for all to finish. Args: dac_values: Mapping of coupler names to target currents (A). """ active_dacs = [] # Trigger all ramps for coupler, target_current in dac_values.items(): if coupler in self.dacs_dictionary: dac = self.dacs_dictionary[coupler] dac.current(target_current) active_dacs.append((coupler, dac)) if not active_dacs: return logger.info(f"{Fore.YELLOW}Ramping currents simultaneously...{Style.RESET_ALL}") # Monitor the ramping while any(dac.is_ramping() for _, dac in active_dacs): currents_str = ", ".join( [f"{c}: {d.current() * 1e3:.3f}" for c, d in active_dacs] ) sys.stdout.write(f"\r{currents_str} mA") sys.stdout.flush() time.sleep(0.5) print() # Newline after progress logger.info(f"{Fore.GREEN}Simultaneous ramping finished.{Style.RESET_ALL}")
[docs] def ramp_current_serially(self, dac_values: dict[str, float]): """ Ramps currents one by one with a progress bar for detailed monitoring. Args: dac_values: Mapping of coupler names to target currents (A). """ for coupler, target_current in dac_values.items(): if coupler not in self.dacs_dictionary: logger.warning(f"Coupler {coupler} not found in SPI configuration.") continue dac = self.dacs_dictionary[coupler] initial_current_mA = dac.current() * 1000 target_mA = target_current * 1000 total_range = abs(target_mA - initial_current_mA) if total_range < 1e-7: # Already at target continue dac.current(target_current) with Progress() as progress: task = progress.add_task( f"[yellow]Ramping {coupler}...", total=total_range ) while dac.is_ramping(): try: current_mA = dac.current() * 1000 progress.update( task, completed=abs(current_mA - initial_current_mA), description=f"[cyan]{coupler}: {current_mA:.4f} -> {target_mA:.4f} mA", ) if abs(current_mA - target_mA) < 0.005: break time.sleep(0.1) except Exception as e: logger.error(f"Error during ramping {coupler}: {e}") break logger.info(f"{Fore.GREEN}Serial ramping finished.{Style.RESET_ALL}")
[docs] def print_currents(self): """Prints the current of all registered DACs.""" for coupler, dac in self.dacs_dictionary.items(): val = dac.current() * 1e3 if not self.is_dummy else 0.0 logger.info(f"{coupler}: {val:.4f} mA")
[docs] def close(self): """Safely closes the connection to the SPI Rack.""" self.spi.close() logger.info("SPI rack connection closed.")