# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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
# Abdullah-Al Amin, alamina@chalmers.se
# Yanchen Lin, linya@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
# (C) Copyright Michele Faucci Giannelli 2024, 2025
# (C) Copyright Pontus Vikstål 2024, 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/base/node.py
import abc
from pathlib import Path
from typing import Any, override
import numpy as np
import xarray
from colorama import init as colorama_init
from qblox_scheduler import QuantumDevice
from qblox_scheduler.qblox.hardware_agent import HardwareAgent
from qblox_scheduler.schedules.schedule import CompiledSchedule
from qcodes.instrument import Instrument
import bragi_quantum.experiments.utils.dataset_utils as ds_utils
from bragi_quantum.datalayer.managing.dataset import save_dataset
from bragi_quantum.datalayer.managing.redis import (
record_calibration_metadata,
update_redis_trusted_values,
)
from bragi_quantum.datalayer.managing.session import ActiveSession
from bragi_quantum.datalayer.managing.time_tracing import TimingTraceCategory
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.logging import logger
from bragi_quantum.datalayer.utils.mode import ExecutionMode
from bragi_quantum.experiments.abstract.analysis import Analysis
from bragi_quantum.experiments.abstract.errors import (
ExperimentBuildingError,
ExperimentParameterError,
)
from bragi_quantum.experiments.abstract.measurement import BaseMeasurement
from bragi_quantum.experiments.abstract.parameters import BaseParameters, BaseQoi
from bragi_quantum.experiments.utils import calibration_points as cal
from bragi_quantum.experiments.utils.schedule_execution import execute_schedule
from bragi_quantum.experiments.utils.timing import timed
colorama_init()
[docs]
class BaseNode(abc.ABC):
measurement_cls: "BaseMeasurement"
analysis_cls: "Analysis"
# Automatically append per-state calibration points (on dedicated CAL_
# acquisition channels) after the user schedule, provided every qubit has
# a calibrated X gate. Opt-in: a node's schedule_function must return a
# schedule with repetitions == 1 (its averaging expressed as a loop
# register) before this can be enabled, so it defaults to False until
# each node is migrated.
append_calibration_points: bool = False
# With append_calibration_points=True, fail the build instead of silently
# continuing if calibration points can't be appended.
require_calibration_points: bool = False
def __init__(
self,
parameters: BaseParameters,
qoi_cls: BaseQoi,
):
self.parameters = parameters
self.qoi_cls = qoi_cls
self.name = parameters.name
self.node_dictionary = {}
self._results = {}
self.schedule_samplespace = {}
self.external_samplespace = {}
self.all_qubits = parameters.qubits
# Resolve per-qubit custom_parameters overrides ONCE, here in the base, so
# every node reads measurement-time fields per qubit (via
# ``self.parameters_by_qubit[q].<field>``) without re-implementing — or
# forgetting — the resolution. Overrides are applied at compile time, and
# forgetting to apply them is exactly the class of bug this prevents.
# (Coupler nodes additionally get ``parameters_by_coupler``; see CouplerNode.)
self.parameters_by_qubit = parameters.resolved_by_qubit()
self.element_type: str = None # 'qubit' or 'coupler'
# These may be modified while the node runs
self.outer_schedule_samplespace = {}
self.reduced_external_samplespace = {}
self.schedule_keywords = {}
# Track dataset path for bragi_quantum.gui replot metadata
self.dataset_directory: Path | None = None
self.dataset_basename: str = self.parameters.name
# Initialize from active SessionContext
self._initialize_from_session()
# Initialize samplespace after device configuration is set up
# (required for properties that depend on device_manager)
try:
self.samplespace = self.schedule_samplespace | self.external_samplespace
except Exception:
self.samplespace = {} # Fallback if properties aren't ready yet
def _initialize_from_session(self) -> None:
"""
Retrieve hardware configuration, device, and execution options from active SessionContext.
This replaces the previous approach of manually passing parameters through the call stack.
"""
# TODO: remove initialization of all these attributes because we can directly
# assign an attribute which his the session itself
try:
session = ActiveSession.get()
except RuntimeError:
raise RuntimeError(
"Node initialization requires an active calibration session. "
"Ensure you are using CalibrationOrchestrator.calibration_session() context."
)
# Retrieve device configuration and related objects from session
self.device: QuantumDevice = session.device
self._validate_requested_components()
# DeviceConfiguration wrapping the device; holds extended_state, the
# analysis quantities not reflected in the live QuantumDevice.
self.device_config = session.device_config
self.hardware_agent: HardwareAgent = session.hardware_agent
self.spi_manager: SpiDAC = session.spi_dac_handler
# TODO: we should support the case where REDIS is not used
self.redis_connection = session.redis_connection
# Retrieve execution options from session
pdf_filepath = session.session_options.pdf_report_filepath
if pdf_filepath:
# If relative path, resolve against session root; otherwise use absolute path
if (
isinstance(pdf_filepath, (str, Path))
and not Path(pdf_filepath).is_absolute()
):
self.pdf_report_path = session.root_path / pdf_filepath
else:
self.pdf_report_path = (
Path(pdf_filepath)
if isinstance(pdf_filepath, str)
else pdf_filepath
)
else:
self.pdf_report_path = None
self.produce_support_figures = session.session_options.produce_support_figures
self._save_cluster_metadata_to_disk = (
session.session_options.save_cluster_metadata_to_disk
)
# Store execution mode for later use in measure_node/calibrate
self._execution_mode = session.session_options.execution_mode
# Extract cluster names from hardware_description section. A config may
# describe multiple clusters
hardware_desc = (
session.cluster_config.hardware_description
if session.cluster_config
else {}
)
self._cluster_names = list(hardware_desc.keys()) if hardware_desc else []
def _validate_requested_components(self) -> None:
"""Fail fast if ``parameters.qubits``/``couplers`` names aren't on the device.
Names must match the device config exactly (no normalization is applied
anywhere in the toolkit), so a typo or a stale naming convention would
otherwise only surface as a ``KeyError`` deep inside schedule/samplespace
construction. Checking here, right after the device becomes available,
catches it before any node-specific work starts.
"""
unknown_qubits = sorted(set(self.parameters.qubits) - set(self.device.elements))
unknown_couplers = sorted(
set(self.parameters.couplers) - set(self.device.edges)
)
if not unknown_qubits and not unknown_couplers:
return
problems = []
if unknown_qubits:
problems.append(f"qubit(s) {unknown_qubits}")
if unknown_couplers:
problems.append(f"coupler(s) {unknown_couplers}")
raise ExperimentParameterError(
f"Unknown {' and '.join(problems)} requested; device has qubits "
f"{sorted(self.device.elements)} and couplers {sorted(self.device.edges)}."
)
def _detect_element_kind(self) -> str:
"""Determine whether this node operates on qubits or couplers."""
# Prefer explicit assignment, then read the analysis class's element_kind.
if self.element_type:
return self.element_type
return getattr(self.analysis_cls, "element_kind", "qubit")
def _build_replot_metadata(self) -> dict[str, Any]:
"""
Build metadata needed for replaying this node's analysis via bragi_quantum.gui.
This metadata allows the replot server to re-instantiate the analysis class,
rebuild fit results, and render plots on demand using recorded parameters
and measurement data.
Returns:
Dict with keys:
- analysis_module: Module path of the analysis class
- analysis_class: Name of the analysis class
- parameters_module: Module path of the parameters class
- parameters_class: Name of the parameters class
- qoi_module: Module path of the QOI class (optional)
- qoi_class: Name of the QOI class (optional)
- dataset_dir: Directory containing HDF5 measurement files
- dataset_basename: Base name for dataset files (e.g., "resonator_wide")
- element_kind: "qubit" or "coupler"
"""
meta: dict[str, Any] = {
"analysis_module": self.analysis_cls.__module__,
"analysis_class": self.analysis_cls.__name__,
"parameters_module": self.parameters.__class__.__module__,
"parameters_class": self.parameters.__class__.__name__,
"element_kind": self._detect_element_kind(),
}
# Optional: QOI class
if self.qoi_cls:
meta["qoi_module"] = self.qoi_cls.__module__
meta["qoi_class"] = self.qoi_cls.__name__
# Dataset location (set during measure_node by subclasses)
if hasattr(self, "dataset_directory") and self.dataset_directory:
meta["dataset_dir"] = str(self.dataset_directory)
meta["dataset_basename"] = getattr(
self, "dataset_basename", self.parameters.name
)
return meta
[docs]
def measure_node(self, *, execution_mode: ExecutionMode) -> xarray.Dataset:
"""
To be implemented by the Classes that define the Node Type:
ScheduleNode or ExternalParameterNode
"""
return xarray.Dataset()
@abc.abstractmethod
def _build_measurement(self):
"""Polymorphic hook implemented by subclasses"""
raise NotImplementedError
[docs]
def execute(self):
"""
Execute the full calibration pipeline for this node.
Derives the data path from the active session's root path, using a
unique per-invocation folder so repeated runs don't collide.
"""
session = ActiveSession.get()
dir_name = ActiveSession.next_node_dir_name(self.name)
data_path = session.root_path / dir_name
data_path.mkdir(parents=True, exist_ok=True)
# Store so _build_replot_metadata() can find it when recording the
# timeline step after analysis completes.
self.dataset_directory = data_path
self.calibrate(data_path)
return self._results
[docs]
def pre_measurement_operation(self):
"""
To be implemented by the child measurement nodes
"""
[docs]
def initial_operation(self):
"""
To be implemented by the child measurement nodes.
This is called before the execution of each and every iteration
of the samples of the external samplespace.
See coupler_spectroscopy for examples.
"""
[docs]
def final_operation(self):
"""
To be implemented by the child measurement nodes.
This is called after ALL the iteration samples of the
external samplespace have been executed.
e.g. set back the dc_current to 0 in coupler_spectroscopy.
See coupler_spectroscopy for examples.
"""
[docs]
def precompile(self, schedule_samplespace: dict) -> CompiledSchedule:
with timed(
"Schedule build took: ", timing_category=TimingTraceCategory.PREPARATION
):
measurement_obj = self._build_measurement()
schedule = measurement_obj.schedule_function(
**schedule_samplespace,
**self.schedule_keywords,
)
if self.append_calibration_points:
if schedule.repetitions != 1:
raise ExperimentBuildingError(
f"{type(measurement_obj).__name__}.schedule_function returned a "
f"schedule {schedule.name!r} with repetitions={schedule.repetitions}. "
"In bragi_quantum.experiments's assumptions, this argument must be 1. Express "
"schedule-level averaging with a loop register instead: "
"`with schedule.loop(self.make_repetition_domain(repetitions)): ...` "
"(the loop variable must not appear in any measure_system coords)."
)
# The repetitions == 1 contract above guarantees a true top-level
# tail position: the calibration block lands after the user's
# loops but inside the same compiled program, and carries its own
# repetition loop register — static regardless of the node's loop
# style.
calib_schedule = measurement_obj.calibration_points_schedule(
self.parameters.repetitions
)
if calib_schedule is not None:
schedule.add(calib_schedule, label=cal.CALIBRATION_POINTS_LABEL)
logger.info("📌 Appended calibration points.")
elif self.require_calibration_points:
raise ExperimentBuildingError(
f"{type(self).__name__} requires calibration points "
"(require_calibration_points=True) but they could not be "
"appended: not every qubit in this node has a calibrated "
"X gate."
)
else:
logger.warning(
"📌⚠️ Calibration points requested (append_calibration_points=True) "
"but skipped: not every qubit in this node has a calibrated X gate."
)
logger.info(f"📋 Schedule created: {schedule.name}")
logger.info(f" Operations count: {len(schedule.operations)}")
# Log schedule resources (clocks, parameters)
if hasattr(schedule, "resources"):
logger.info(" Schedule resources:")
for res_name, res_info in schedule.resources.items():
logger.info(f" - {res_name}: {res_info}")
with timed(
"Compilation took: ", timing_category=TimingTraceCategory.PREPARATION
):
compiled_schedule = self.hardware_agent.compile(schedule)
# Compiler drops the name; restore it (no property setter, but it's a dict key).
compiled_schedule["name"] = schedule.name
if self.append_calibration_points and calib_schedule is not None:
# Verify against the compiled artifact itself — appending the
# block pre-compile (above) is not proof it survived compilation
# (e.g. a compiler-restructuring regression could silently drop
# it; that's the very bug that motivated this check).
if not cal.has_calibration_points(compiled_schedule):
raise cal.CalibrationPointsError(
"📌⚠️ Calibration points were appended before compilation but "
"could not be found in the compiled schedule — compilation "
"may have dropped them."
)
# Log compiled schedule details
logger.info(
f" Compiled schedule instructions: {len(compiled_schedule.instructions) if hasattr(compiled_schedule, 'instructions') else 'N/A'}"
)
logger.info(
f" Compiled schedule resources: {list(compiled_schedule.resources.keys()) if hasattr(compiled_schedule, 'resources') else 'N/A'}"
)
return compiled_schedule
[docs]
def measure_compiled_schedule(
self,
compiled_schedule: CompiledSchedule,
*,
execution_mode: ExecutionMode | None = None,
measurement: tuple[int, int] = (1, 1),
) -> xarray.Dataset:
"""
Execute a measurement for a node and save the resulting dataset.
Args:
compiled_schedule (CompiledSchedule): The compiled schedule to execute.
execution_mode (ExecutionMode | None): The execution mode. If None, falls
back to the active session's session_options.
measurement (tuple): Tuple of (current_measurement, total_measurements).
Returns:
xarray.Dataset: The dataset containing the measurement results.
"""
if execution_mode is None:
execution_mode = ExecutionMode[self._execution_mode.lower()]
logger.info("Executing measurement via HardwareAgent...")
logger.info(f" Cluster mode: {execution_mode}")
raw_dataset = execute_schedule(
compiled_schedule,
self.hardware_agent,
execution_mode=execution_mode,
measurement=measurement,
data_path=self.dataset_directory,
cluster_names=self._cluster_names,
save_cluster_metadata_to_disk=self._save_cluster_metadata_to_disk,
)
# Check raw data from cluster for NaN values
logger.info("Measurement completed. Inspecting acquired data...")
for var in raw_dataset.data_vars:
data = raw_dataset[var].values.flatten()
nan_count = np.sum(np.isnan(data))
total = len(data)
logger.info(
f"Raw cluster data [{var}]: {total} points, {nan_count} NaN values"
)
if nan_count == 0 and total > 0:
logger.info(f" ✓ Data range: [{np.min(data):.6e}, {np.max(data):.6e}]")
elif nan_count > 0 and nan_count < total:
valid_data = data[~np.isnan(data)]
logger.warning(f" ⚠️ Partial NaN: {nan_count}/{total} invalid")
if len(valid_data) > 0:
logger.info(
f" Valid data range: [{np.min(valid_data):.6e}, {np.max(valid_data):.6e}]"
)
else:
logger.error(f" ❌ ALL DATA IS NaN! ({nan_count}/{total})")
logger.error(
f" Dataset structure: data_vars={list(raw_dataset.data_vars)}, coords={list(raw_dataset.coords)}"
)
logger.error(f" Dimensions: {dict(raw_dataset.dims)}")
# Log dataset attributes that might indicate measurement failure
if hasattr(raw_dataset, "attrs"):
logger.info(f"Dataset attributes: {raw_dataset.attrs}")
# temporary fix for automatic mixer correction
# The problem: when running multiple measurements in the same node, the mixer
# correction values are not updated on the consecutive measurements
with timed(
"Invalidate cluster parameter cache took: ",
timing_category=TimingTraceCategory.MEASUREMENT,
):
for cluster_name in self._cluster_names:
cluster_obj = Instrument.find_instrument(cluster_name)
cluster_obj._invalidate_qcodes_parameter_cache()
with timed(
"Configure dataset took: ", timing_category=TimingTraceCategory.MEASUREMENT
):
result_dataset = self.configure_dataset(raw_dataset)
logger.info("Finished measurement")
return result_dataset
[docs]
def calibrate(self, data_path: Path):
"""
Execute the calibration workflow for this node.
Args:
data_path (Path): Directory where measurement results will be saved.
"""
# Convert execution_mode string to ExecutionMode enum (values are lowercase)
try:
execution_mode = ExecutionMode[self._execution_mode.lower()]
except KeyError:
valid_modes = [m.name for m in ExecutionMode]
raise ValueError(
f"Invalid execution_mode: '{self._execution_mode}'. "
f"Valid modes are: {valid_modes}"
)
# Analysis-only nodes (no measurement class) have nothing to measure;
# their analysis input comes from redis, not an acquisition dataset.
if self.measurement_cls is not None:
result_dataset = self.measure_node(execution_mode=execution_mode)
# TODO: FIX --> this is now returning an empty dataset
save_dataset(result_dataset, self.name, data_path)
self.post_process(data_path)
logger.info("analysis completed")
def _apply_qoi_to_device(self, element_id: str, qoi: "BaseQoi") -> None:
"""Apply calibrated QOI values to the live QuantumDevice object.
Parses to_redis_dict() keys of the form 'submodule:field' and assigns the
value directly on the element. Logs each update and warns for keys that
don't map to an existing submodule or field.
"""
if not qoi.is_successful:
return
if "_" in element_id:
element = self.device.edges.get(element_id)
else:
element = self.device.elements.get(element_id)
if element is None:
logger.warning(
f"Element '{element_id}' not found in device — skipping device update."
)
return
for redis_key, result in qoi.to_redis_dict().items():
parts = redis_key.split(":")
if len(parts) != 2:
continue
submodule_name, field_name = parts
submodule = getattr(element, submodule_name, None)
if submodule is None:
logger.warning(
f"Device update skipped: '{element_id}' has no submodule '{submodule_name}'."
)
continue
if not hasattr(submodule, field_name):
logger.warning(
f"Device update skipped: '{element_id}.{submodule_name}' has no field '{field_name}'."
)
continue
setattr(submodule, field_name, result["value"])
logger.info(
f"Device updated: {element_id}.{submodule_name}.{field_name} = {result['value']}"
)
[docs]
def post_process(self, data_path: Path):
"""
Execute post-measurement analysis and generate reports.
This always runs (unless in dummy mode) to ensure plots and reports are generated.
"""
# Skip fitting dummy acquisition data — but analysis-only nodes read
# their input from redis, not from a measured dataset, so they always
# run their analysis regardless of mode.
if self._execution_mode == "dummy" and self.measurement_cls is not None:
logger.info("⏭️ Skipping analysis in dummy mode")
return
try:
logger.info(f"📊 Starting analysis for {self.parameters.name}...")
analysis: Analysis = self.analysis_cls(
parameters=self.parameters,
qoi_cls=self.qoi_cls,
)
# Updating attributes for report generation
analysis.pdf_report_path = self.pdf_report_path
analysis.produce_support_figures = self.produce_support_figures
dataset_file = data_path / f"dataset_{self.parameters.name}_0.hdf5"
with timed(
"Analysis fit took: ", timing_category=TimingTraceCategory.ANALYSIS
):
self._results = analysis.run(dataset_file)
analysis.save(data_path)
logger.info(
f"✅ Analysis completed. Generated {len(self._results)} results."
)
# Build a single results dict for the timeline below.
results_by_element: dict = {}
for element_id_, qois_ in self._results.items():
params_dict = (
qois_.model_dump() if hasattr(qois_, "model_dump") else dict(qois_)
)
results_by_element[element_id_] = params_dict
# Record this node as the next step in the session timeline.
try:
timeline = ActiveSession.get_session_timeline()
node_params = (
self.parameters.model_dump(mode="json")
if hasattr(self.parameters, "model_dump")
else dict(self.parameters)
)
with timed(
"Session timeline record took: ",
timing_category=TimingTraceCategory.LOGGING,
):
timeline.record_node_execution(
node_name=self.parameters.name,
node_class=self.__class__.__name__,
parameters=node_params,
target_qubits=list(results_by_element.keys()),
results=results_by_element,
replot_meta=self._build_replot_metadata(),
)
except Exception as e:
logger.warning(f"Could not record session timeline step: {e}")
for element_id_, qois_ in self._results.items():
self._apply_qoi_to_device(element_id_, qois_)
# Mirror the full analysis output (including quantities the live
# QuantumDevice cannot hold) into the DeviceConfiguration.
if self.device_config is not None:
self.device_config.record_analysis_results(
element_id_, self.name, qois_
)
update_redis_trusted_values(
self.name,
element_id_,
qoi=qois_,
redis_connection=self.redis_connection,
)
# Record cross-cutting metadata once per node run: last experiment
# timestamp, last node, and the components it successfully calibrated.
calibrated_components = [
element_id_
for element_id_, qois_ in self._results.items()
if getattr(qois_, "is_successful", False)
]
if self.redis_connection is not None and calibrated_components:
record_calibration_metadata(
redis_connection=self.redis_connection,
node=self.name,
components=calibrated_components,
)
except Exception as e:
logger.error(f"❌ Analysis failed for {self.parameters.name}: {e}")
logger.error(f"Traceback: {e.__traceback__}")
raise # Re-raise to let orchestra know analysis failed
return self._results
def _extract_calibration_points(
self, ds: xarray.Dataset
) -> tuple[xarray.Dataset, dict[str, xarray.DataArray]]:
"""Split calibration-point acquisitions off their dedicated channels.
The calibration block appended by
:meth:`BaseMeasurement.calibration_points_schedule` acquires on
dedicated ``CAL_<n>`` acquisition channels, so the calibration data
arrives as its own ``CAL_<n>`` data variables (with a ``<qubit>_CAL``
coordinate holding the prepared-state labels) and never touches the
sweep's flat acquisition dimensions.
Returns the dataset without the ``CAL_*`` variables and coordinates,
together with a dict mapping ``"<qubit>_CAL"`` to a
``DataArray(CAL=[...])`` holding the hardware-averaged complex IQ
value per prepared state. ``calibration_points_schedule`` requires
every qubit to have a calibrated X gate before it produces any block
at all, so whenever calibration data is present every qubit here
shares the same ``CAL`` labels.
"""
channel_to_qubit = {
int(t.measure.acq_channel): t.name for t in self.transmons.values()
}
calib_data_vars: dict[str, xarray.DataArray] = {}
for var in list(ds.data_vars):
name = str(var)
if not name.startswith("CAL_"):
continue
qubit_name = channel_to_qubit[int(name.removeprefix("CAL_"))]
acq_dim = next(d for d in ds[var].dims if str(d).startswith("acq_index"))
state_labels = ds.coords[f"{qubit_name}_CAL"].values.astype(float)
calib_da = (
ds[var]
.reset_coords(drop=True)
.rename({acq_dim: "CAL"})
.assign_coords(CAL=state_labels)
)
calib_data_vars[f"{qubit_name}_CAL"] = calib_da
ds = ds.drop_vars([var])
leftover_coords = [c for c in ds.coords if str(c).endswith("_CAL")]
if leftover_coords:
ds = ds.drop_vars(leftover_coords)
return ds, calib_data_vars
[docs]
class QubitNode(BaseNode, abc.ABC):
def __init__(
self,
parameters: BaseParameters,
qoi_cls: BaseQoi,
):
super().__init__(parameters, qoi_cls)
self.plots_per_qubit = 1 # can be 0 or 1 or 2
@override
def _build_measurement(self):
return self.measurement_cls(self.transmons)
@property
def transmons(self) -> dict[str, ExtendedTransmon]:
"""
Return transmons (qubits) restricted to this node's parameters.qubits.
"""
return {
k: v for k, v in self.device.elements.items() if k in self.parameters.qubits
}
@override
def __str__(self):
return f"Node representation for {self.name} on qubits {self.all_qubits}"
@override
def __format__(self, message):
return f"Node representation for {self.name} on qubits {self.all_qubits}"
@override
def __repr__(self):
return f"Node({self.name}, {self.all_qubits})"
[docs]
class CouplerNode(BaseNode, abc.ABC):
def __init__(
self,
parameters: BaseParameters,
qoi_cls: BaseQoi,
):
super().__init__(parameters, qoi_cls)
self.couplers = parameters.couplers
# Coupler analogue of BaseNode.parameters_by_qubit: resolve per-coupler
# overrides once so coupler nodes read ``self.parameters_by_coupler[c].<field>``.
self.parameters_by_coupler = parameters.resolved_by_coupler()
self.all_qubits = sorted(set(self.get_coupled_qubits()))
self.plots_per_qubit = 1 # can be 0 or 1 or 2
self.validate()
@override
def _build_measurement(self):
return self.measurement_cls(
self.device.qubits,
self.device.couplers,
)
@property
def edges(self) -> dict[str, ExtendedCompositeSquareEdge]:
"""
Return coupler edges restricted to this node's parameters.couplers.
"""
return {k: v for k, v in self.device.edges.items() if k in self.couplers}
[docs]
def get_coupled_qubits(self) -> list:
coupled_qubits = []
for coupler in self.couplers:
qubits = coupler.split(sep="_")
coupled_qubits.append(qubits[0])
coupled_qubits.append(qubits[1])
return coupled_qubits
[docs]
def validate(self) -> None:
all_coupled_qubits = []
for coupler in self.couplers:
all_coupled_qubits += coupler.split("_")
if len(all_coupled_qubits) > len(set(all_coupled_qubits)):
logger.info("Couplers share qubits")
raise ValueError("Improper Couplers")