# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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
# ══════════════════════════════════════════════════════════════════════════
from copy import deepcopy
from pathlib import Path
from qblox_scheduler import QuantumDevice
from qblox_scheduler.backends.qblox_backend import QbloxHardwareCompilationConfig
from qblox_scheduler.qblox.hardware_agent import HardwareAgent
from bragi_quantum.datalayer.utils.logging import logger
[docs]
def create_hardware_agent(
cluster_config: QbloxHardwareCompilationConfig,
quantum_device: QuantumDevice,
*,
reset_clusters: bool = False,
is_dummy: bool = False,
output_dir: Path | None = None,
) -> HardwareAgent:
"""Create and configure HardwareAgent with cluster connections and AMC settings."""
if output_dir is None:
output_dir = Path.home() / ".qblox_output"
output_dir.mkdir(parents=True, exist_ok=True)
agent = HardwareAgent(
hardware_configuration=cluster_config,
quantum_device_configuration=quantum_device,
output_dir=output_dir,
create_dummy_connections=is_dummy,
)
agent.connect_clusters()
# qblox-instruments==1.3.0 introduced async cluster communication that
# races with AMC (auto_lo_cal/auto_sideband_cal), producing NaN
# acquisitions; confirmed by Qblox support, unresolved as of 1.3.1
# (issue #377). Force the pre-1.3.0 synchronous path per their workaround
# until there's an official fix -- remove this block once that lands.
for cluster_name in agent.get_clusters():
ic_component = agent.instrument_coordinator.get_component(f"ic_{cluster_name}")
ic_component._supports_async = False
if reset_clusters:
for cluster_name, cluster in agent.get_clusters().items():
logger.info(f"⚠️ Resetting Cluster '{cluster_name}'")
cluster.reset()
return agent
# Clocks multiplexed onto the same output, per port type.
_PORT_RELATED_CLOCKS: dict[str, list[str]] = {
"res": [".ro", ".ro1", ".ro2", ".ro_2st_opt", ".ro_3st_opt"],
"mw": [".01", ".12"],
"fl": [".cz"],
}
# Options fixed by the shared analog path. Per-state options (e.g.
# digitization_thresholds) must NOT be added here.
_AUTOCOMPLETED_HARDWARE_OPTIONS: tuple[str, ...] = (
"modulation_frequencies",
"output_att",
"input_att",
"input_gain",
"mixer_corrections",
)
[docs]
def autocomplete_hardware_options(
hardware_config: QbloxHardwareCompilationConfig,
) -> QbloxHardwareCompilationConfig:
"""Fill in physical-analog-path hardware options for related clocks.
The compiler looks these options up by exact portclock string, so a clock
the device template doesn't define gets no attenuation/gain/mixer
correction at all, instead of inheriting from the related clock sharing
its output. Called once per cluster config, from the orchestrator's
``_load_cluster_config()``.
Parameters
----------
hardware_config
Cluster configuration, completed in place.
Returns
-------
QbloxHardwareCompilationConfig
The same object, with missing related-clock keys added. Existing keys
are never overwritten.
"""
hw_options = getattr(hardware_config, "hardware_options", None)
if hw_options is None:
return hardware_config
ports = _connectivity_ports(hardware_config)
for option_name in _AUTOCOMPLETED_HARDWARE_OPTIONS:
option_dict = getattr(hw_options, option_name, None)
if not option_dict:
continue
_repeat_option_across_related(option_dict, ports)
return hardware_config
def _connectivity_ports(hardware_config: QbloxHardwareCompilationConfig) -> set[str]:
"""Collect the port names referenced in the connectivity graph.
Parameters
----------
hardware_config
Cluster configuration whose ``connectivity.graph`` is read; it may be a
NetworkX DiGraph or a plain list of ``(src, dst)`` tuples.
Returns
-------
set[str]
Port names such as ``'q01:res'``, empty if there is no connectivity.
"""
ports: set[str] = set()
conn = getattr(hardware_config, "connectivity", None)
if conn is None:
return ports
graph = getattr(conn, "graph", None)
if graph is None:
return ports
edges = list(graph.edges) if hasattr(graph, "edges") else (graph or [])
for edge in edges:
if isinstance(edge, (list, tuple)) and len(edge) == 2:
ports.add(edge[1])
return ports
def _related_portclocks(portclock: str, ports: set[str]) -> list[str]:
"""List every portclock sharing one portclock's physical port.
Parameters
----------
portclock
Portclock string of the form ``<port>-<qubit><clock>``.
ports
Port names present in the connectivity graph.
Returns
-------
list[str]
The related portclocks in ``_PORT_RELATED_CLOCKS`` order, or empty if
``portclock`` doesn't parse, its port is unknown, or its clock isn't a
known related clock for that port type.
"""
port, _, clock = portclock.partition("-")
if not clock or port not in ports or ":" not in port:
return []
qubit_name, port_suffix = port.rsplit(":", maxsplit=1)
if not clock.startswith(qubit_name):
return []
related_clocks = _PORT_RELATED_CLOCKS.get(port_suffix, [])
if clock.removeprefix(qubit_name) not in related_clocks:
return []
return [f"{port}-{qubit_name}{suffix}" for suffix in related_clocks]
def _repeat_option_across_related(option_dict: dict, ports: set[str]) -> None:
"""Fill in missing related-clock keys of one hardware_options dict, in place.
Each filled-in key is inserted right after the entry it was copied from, so
the result keeps the device template's order with each port's clocks
grouped together.
Parameters
----------
option_dict
One hardware_options field, keyed by portclock; mutated in place.
ports
Port names present in the connectivity graph.
"""
ordered: dict = {}
for portclock, value in option_dict.items():
ordered[portclock] = value
for related in _related_portclocks(portclock, ports):
if related in ordered:
continue
# An explicit entry is only moved next to the others, never replaced.
ordered[related] = (
option_dict[related] if related in option_dict else deepcopy(value)
)
option_dict.clear()
option_dict.update(ordered)