Source code for bragi_quantum.experiments.nodes.external_parameter_node

# ══════════════════════════════════════════════════════════════════════════
#     ___   ___ ___   _      _   ___
#    / _ \ / __|_  ) | |    /_\ | _ )
#   | (_) | (__ / /  | |__ / _ \| _ \
#    \__\_\\___/___| |____/_/ \_\___/
#
#   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
#   Abdullah-Al Amin, alamina@chalmers.se
#   Michele Faucci Giannelli, faucci@chalmers.se
#   Adrián Navarro Fuentes, adrianfu@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


# This code is part of Tergite
#
# (C) Copyright Eleftherios Moschandreou 2024
# (C) Copyright Stefan Hill 2024
# (C) Copyright Michele Faucci Giannelli 2025
# (C) Copyright Abdullah Al Amin 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/nodes/external_parameter_node.py


import abc
from typing import Any, override

import numpy as np
import xarray as xr

# bragi_quantum.datalayer Imports - Using bragi_quantum.datalayer as the foundation for shared types and logging
from bragi_quantum.datalayer.utils.logging import logger
from bragi_quantum.datalayer.utils.mode import ExecutionMode

# Local bragi_quantum.experiments Imports
from bragi_quantum.experiments.abstract.node import BaseNode, CouplerNode, QubitNode
from bragi_quantum.experiments.abstract.parameters import BaseParameters
from bragi_quantum.experiments.utils.measurement_utils import reduce_samplespace


[docs] class ExternalParameterNode(BaseNode, abc.ABC): """ Abstract base class for nodes involving external hardware parameters. These nodes are used for experiments where a parameter outside of the Quantify pulse schedule must be swept (e.g., DC currents from a DAC or magnetic fields). """
[docs] @override def pre_measurement_operation(self, reduced_ext_space: dict[str, Any]): """ Hook called before each hardware measurement. Subclasses implement this to set physical hardware values (like ramping a current) before the pulse schedule executes. Args: reduced_ext_space: The slice of the external samplespace for the current iteration. """
@property def external_dimensions(self) -> list[int]: """ Calculates the dimensions of the external samplespace. Supports multidimensional external sweeps. For example, if sweeping 'dc_current' (4 points) and 'offset' (3 points), it returns [4, 3]. Returns: List[int]: A list of lengths for each swept external quantity. """ external_settable_quantities = self.external_samplespace.keys() dimensions = [] for quantity in external_settable_quantities: # We assume all elements in a quantity sweep have the same length settable = next(iter(self.external_samplespace[quantity].keys())) dimensions.append(len(self.external_samplespace[quantity][settable])) return dimensions
[docs] class ExternalParameterFixedScheduleNode(ExternalParameterNode): """ A node where the pulse schedule is constant, but hardware parameters change. The schedule is compiled once, and then executed repeatedly for every point in the external samplespace. This is efficient for sweeps like flux-spectroscopy. """
[docs] @override def measure_node(self, *, execution_mode: ExecutionMode) -> xr.Dataset: """ Executes the measurement loop for a fixed schedule. Args: execution_mode: The execution mode (real, dummy, re-analyse). Returns: xr.Dataset: The merged dataset containing all external iterations. """ # We handle the first dimension of the external space iterations = self.external_dimensions[0] external_dim = next(iter(self.external_samplespace.keys())) result_dataset = xr.Dataset() # Optimization: Compile the schedule only once compiled_schedule = self.precompile(self.schedule_samplespace) self.initial_operation() for current_iteration in range(iterations): # Isolate the specific values for this hardware step self.reduced_external_samplespace = reduce_samplespace( current_iteration, self.external_samplespace ) # Extract the numerical value for coordinate expansion element_dict = next(iter(self.reduced_external_samplespace.values())) current_value = next(iter(element_dict.values())) # Set hardware values (e.g., set DAC current) self.pre_measurement_operation( reduced_ext_space=self.reduced_external_samplespace ) # Execute the pre-compiled schedule ds = self.measure_compiled_schedule( compiled_schedule, execution_mode=execution_mode, measurement=(current_iteration, iterations), ) # Expand the dataset with the external parameter as a dimension ds = ds.expand_dims({external_dim: np.array([current_value])}) result_dataset = xr.merge( [ds, result_dataset], compat="no_conflicts", join="outer", ) # Final cleanup (e.g., ramping currents back to zero) self.final_operation() return result_dataset
[docs] class ExternalParameterDifferentSchedulesNode(ExternalParameterNode): """ A node where the schedule changes alongside external hardware parameters. This is used for complex calibrations where the schedule keywords depend on the external sweep index. It includes logic to handle "active elements," allowing different elements (like couplers) to have different numbers of sweep points. """ def __init__(self, parameters: BaseParameters, **kwargs): super().__init__(parameters=parameters, **kwargs) self.external_keywords = {}
[docs] @override def measure_node(self, *, execution_mode: ExecutionMode) -> xr.Dataset: """ Executes a loop where schedules are re-compiled per iteration. """ _ = self.external_dimensions[0] external_dim = next(iter(self.external_samplespace.keys())) result_dataset = xr.Dataset() result_dataset_per_qubit: dict[str, xr.Dataset] = {} # Tracking iterations per element for non-uniform sweep lengths element_iterations = { element: len(self.external_samplespace[external_dim][element]) for element in self.external_samplespace[external_dim] } logger.info(f"Element sweep lengths: {element_iterations}") self.initial_operation() max_iterations = max(element_iterations.values()) for current_iteration in range(max_iterations): # Update schedule keywords from external parameters for external_key in self.external_keywords: extracted = self.external_keywords[external_key][current_iteration] self.schedule_keywords[external_key] = extracted self.reduced_external_samplespace = reduce_samplespace( current_iteration, self.external_samplespace ) # Determine which elements are still active (have not finished their sweep) active_elements = [ element for element, remaining in element_iterations.items() if remaining > 0 ] # Filter schedule_samplespace to include only active elements self.schedule_samplespace = { param: { qubit: values for qubit, values in elements_dict.items() if any(qubit in active_el for active_el in active_elements) } for param, elements_dict in self.schedule_samplespace.items() } # Safety check for empty samplespaces if not self.reduced_external_samplespace[external_dim]: continue element_dict = next(iter(self.reduced_external_samplespace.values())) if not element_dict: continue # Build coordinate expansions for the results coordinate_expansions = {} for element in active_elements: ext_dict = self.reduced_external_samplespace[external_dim] if element in ext_dict: coordinate_expansions[f"{external_dim}_{element}"] = np.array( [ext_dict[element]] ) # Must re-compile because schedule_keywords or active elements changed compiled_schedule = self.precompile(self.schedule_samplespace) self.pre_measurement_operation( reduced_ext_space=self.reduced_external_samplespace ) ds = self.measure_compiled_schedule( compiled_schedule, execution_mode=execution_mode, measurement=(current_iteration, max_iterations), ) # Package results per qubit and merge coordinates for var_name in ds.data_vars: qubit = var_name.removeprefix("y") if qubit not in result_dataset_per_qubit: result_dataset_per_qubit[qubit] = xr.Dataset() # Find coordinates relevant to this specific qubit relevant_coords = { c_name: val for c_name, val in coordinate_expansions.items() if qubit in c_name } var_data = ds[var_name] if relevant_coords: for dim, val in relevant_coords.items(): var_data = var_data.expand_dims({dim: val}).assign_coords( {dim: val} ) var_ds = xr.Dataset({var_name: var_data}) result_dataset_per_qubit[qubit] = xr.merge( [result_dataset_per_qubit[qubit], var_ds], compat="no_conflicts", join="outer", ) # Update progress for element in active_elements: element_iterations[element] -= 1 # Combine individual qubit datasets into the final result for var_ds in result_dataset_per_qubit.values(): result_dataset = xr.merge([result_dataset, var_ds], compat="no_conflicts") self.final_operation() return result_dataset
[docs] class ExternalParameterFixedScheduleQubitNode( ExternalParameterFixedScheduleNode, QubitNode ): """ Qubit-specific node for sweeps over external parameters with a fixed schedule. """ def __init__(self, parameters: BaseParameters, **kwargs): super().__init__(parameters=parameters, **kwargs)
[docs] class ExternalParameterDifferentSchedulesQubitNode( ExternalParameterDifferentSchedulesNode, QubitNode ): """ Qubit-specific node for sweeps over external parameters with varying schedules. """ def __init__(self, parameters: BaseParameters, **kwargs): super().__init__(parameters=parameters, **kwargs)
[docs] class ExternalParameterFixedScheduleCouplerNode( ExternalParameterFixedScheduleNode, CouplerNode ): """ Coupler-specific node for sweeps over external parameters with a fixed schedule. """ def __init__(self, parameters: BaseParameters, **kwargs): super().__init__(parameters=parameters, **kwargs)
[docs] class ExternalParameterDifferentSchedulesCouplerNode( ExternalParameterDifferentSchedulesNode, CouplerNode ): """ Coupler-specific node for sweeps over external parameters with varying schedules. """ def __init__(self, parameters: BaseParameters, **kwargs): super().__init__(parameters=parameters, **kwargs)