# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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
# Michele Faucci Giannelli, faucci@chalmers.se
# ══════════════════════════════════════════════════════════════════════════
# This code is part of Tergite
#
# (C) Copyright Eleftherios Moschandreou 2024
# (C) Copyright Stefan Hill 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/nodes/schedule_node.py
import abc
from typing import override
import numpy as np
import xarray as xr
from bragi_quantum.datalayer.utils.logging import logger
# bragi_quantum.datalayer Imports
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, BaseQoi
from bragi_quantum.experiments.utils.measurement_utils import reduce_samplespace
from bragi_quantum.experiments.utils.validators import (
MixedSamplespace,
Samplespace,
SimpleSamplespace,
get_batched_dimensions,
get_number_of_batches,
reduce_batch,
)
[docs]
class ScheduleNode(BaseNode, abc.ABC):
"""
A Node specialized for experiments defined entirely by pulse schedules.
This class handles the complexity of mapping experimental parameters to
hardware execution, specifically addressing hardware limits:
1. Standard execution for small/simple schedules.
2. Batching for schedules exceeding QCM_RF instruction limits.
3. Outer-looping for schedules exceeding QRM_RF measurement memory limits.
"""
def __init__(self, parameters, qoi_cls):
"""
Initialize ScheduleNode with support for dynamic sample space overrides (batching).
"""
super().__init__(parameters, qoi_cls)
@property
def outer_schedule_dimensions(self) -> int:
"""
Calculate the size of the outer samplespace.
The outer samplespace is used when an experiment must be split into
multiple hardware executions because the number of measurement points
exceeds hardware memory.
Example:
self.outer_samplespace = {'cz_amp': {'q1_q2': np.array([0.1, 0.2, 0.3])}}
returns 3.
Returns:
int: The number of iterations required in the outer loop.
"""
outer_settable_quantities = self.outer_schedule_samplespace.keys()
if len(outer_settable_quantities) > 1:
raise NotImplementedError(
"Multidimensional Outer Samplespace is not yet supported."
)
settable = next(iter(outer_settable_quantities))
measured_elements = self.outer_schedule_samplespace[settable].keys()
first_element = next(iter(measured_elements))
dimensions = len(self.outer_schedule_samplespace[settable][first_element])
return dimensions
[docs]
@override
def measure_node(self, *, execution_mode: ExecutionMode) -> xr.Dataset:
"""
The main entry point for executing the node's measurement.
Args:
execution_mode: The mode of execution (real, dummy, or re-analyse).
Returns:
xr.Dataset: The combined dataset from the schedule measurements.
"""
return self.measure_schedule_node(execution_mode=execution_mode)
[docs]
def measure_schedule_node(self, *, execution_mode: ExecutionMode) -> xr.Dataset:
"""
Orchestrate the measurement sequence based on schedule complexity.
It branches into three paths:
1. Simple: A single compilation and execution.
2. Mixed/Batched: Splitting schedules that have too many pulse
instructions for the QCM_RF sequencers.
3. Outer-Looped: Splitting measurements that have too many
acquisition points for the QRM_RF memory.
Returns:
xr.Dataset: The final merged experimental data.
"""
# PATH 1: No outer memory-limit looping required
if self.outer_schedule_samplespace == {}:
validated_samplespace = Samplespace(self.schedule_samplespace)
# Path 1a: Standard execution (fits in hardware instructions)
if isinstance(validated_samplespace.root, SimpleSamplespace):
"""
This correspond to simple cluster schedules
"""
compiled_schedule = self.precompile(self.schedule_samplespace)
result_dataset = self.measure_compiled_schedule(
compiled_schedule,
execution_mode=execution_mode,
)
# Path 1b: Batched execution (bypassing instruction limits)
elif isinstance(validated_samplespace.root, MixedSamplespace):
"""
This correspond to schedules with instructions number
greater than the instructions limit of the QCM_RF
"""
batched_schedule_samplespace = self.schedule_samplespace
number_of_batches = get_number_of_batches(batched_schedule_samplespace)
batched_dimensions = get_batched_dimensions(
batched_schedule_samplespace
)
result_dataset = xr.Dataset(
coords={coord: [] for coord in batched_dimensions}
)
for batch_index in range(number_of_batches):
reduced_schedule_samplespace = reduce_batch(
batched_schedule_samplespace, batch_index
)
# Temporary update of the node's samplespace for compilation
self.schedule_samplespace = reduced_schedule_samplespace
compiled_schedule = self.precompile(reduced_schedule_samplespace)
ds = self.measure_compiled_schedule(
compiled_schedule,
execution_mode=execution_mode,
measurement=(batch_index, number_of_batches),
)
# Combine batch data along coordinates
result_dataset = xr.combine_by_coords(
[result_dataset, ds], data_vars="minimal"
)
# Restore original samplespace
self.schedule_samplespace = batched_schedule_samplespace
# PATH 2: Outer-looping required (memory limit workaround)
else:
"""
This correspond to schedules where the measurement points
are more than the memory limit of the QRM_RF.
For example large single shots measurements
"""
logger.info("Schedule exceeds measurement memory; initiating outer loop.")
iterations = self.outer_schedule_dimensions
outer_dim = next(iter(self.outer_schedule_samplespace.keys()))
result_dataset = xr.Dataset()
for current_iteration in range(iterations):
reduced_outer_samplespace = reduce_samplespace(
current_iteration, self.outer_schedule_samplespace
)
# Extract the current value of the outer sweep variable
element_dict = next(iter(reduced_outer_samplespace.values()))
current_value = next(iter(element_dict.values()))
# Merge inner and current outer samplespace
samplespace = self.schedule_samplespace | reduced_outer_samplespace
compiled_schedule = self.precompile(samplespace)
ds = self.measure_compiled_schedule(
compiled_schedule,
execution_mode=execution_mode,
measurement=(current_iteration, iterations),
)
# Expand with outer dimension coordinate for merging
ds = ds.expand_dims({outer_dim: np.array([current_value])})
result_dataset = xr.merge(
[ds, result_dataset], compat="no_conflicts", join="outer"
)
return result_dataset
[docs]
class ScheduleQubitNode(ScheduleNode, QubitNode):
"""
A ScheduleNode specifically configured for single-qubit elements.
"""
def __init__(
self,
parameters: BaseParameters,
qoi_cls: type[BaseQoi],
**kwargs,
):
"""
Initializes a qubit-specific schedule node.
"""
super().__init__(
parameters=parameters,
qoi_cls=qoi_cls,
**kwargs,
)
[docs]
class ScheduleCouplerNode(ScheduleNode, CouplerNode):
"""
A ScheduleNode specifically configured for multi-qubit coupler elements.
"""
def __init__(
self,
parameters: BaseParameters,
qoi_cls: type[BaseQoi],
**kwargs,
):
"""
Initializes a coupler-specific schedule node.
"""
super().__init__(
parameters=parameters,
qoi_cls=qoi_cls,
**kwargs,
)