Source code for bragi_quantum.experiments.abstract.measurement

# ══════════════════════════════════════════════════════════════════════════
#     ___   ___ ___   _      _   ___
#    / _ \ / __|_  ) | |    /_\ | _ )
#   | (_) | (__ / /  | |__ / _ \| _ \
#    \__\_\\___/___| |____/_/ \_\___/
#
#   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
#   Emil Hogedal, emil.hogedal@chalmers.se
#   Michele Faucci Giannelli, faucci@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
#
# 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/measurement.py


import abc
from collections import OrderedDict
from collections.abc import Callable, Sequence
from typing import Literal, Protocol, override

import numpy as np
import qblox_scheduler.backends.qblox.constants as qblox_constants
from qblox_scheduler.operations.control_flow_library import ConditionalOperation
from qblox_scheduler.operations.gate_library import Measure, Reset, X
from qblox_scheduler.operations.loop_domains import (
    DType,
    LinearDomain,
    arange,
    linspace,
)
from qblox_scheduler.operations.operation import Operation
from qblox_scheduler.operations.pulse_library import IdlePulse
from qblox_scheduler.operations.variables import Variable
from qblox_scheduler.schedule import TimeableSchedule

from bragi_quantum.datalayer.models.gates import Measure_RO_2state_Opt, Rxy_12
from bragi_quantum.datalayer.models.qubit import ExtendedTransmon
from bragi_quantum.experiments.abstract.errors import ExperimentBuildingError
from bragi_quantum.experiments.utils.deprecation import deprecated


[docs] class SingleQubitGate(Protocol): """A callable that constructs a single-qubit gate or schedule from a qubit name.""" def __call__( self, qubit_name: str, /, **kwargs ) -> Operation | TimeableSchedule: ...
[docs] class BaseMeasurement(abc.ABC): def __init__(self, transmons: dict, couplers: dict = {}): self._transmons = transmons self.couplers = couplers self.qubits = list(self.transmons.keys()) @property def transmons(self) -> OrderedDict[str, ExtendedTransmon]: # NOTE: Technically you could use separate # acquisition channels on different submodules # but for the sake of my sanity lets not support that case for transmon in self._transmons.values(): submodules = { "measure": transmon.measure, "measure_1": transmon.measure_1, "measure_2": transmon.measure_2, "measure_2state_opt": transmon.measure_2state_opt, "measure_3state_opt": transmon.measure_3state_opt, } if len({sm.acq_channel for sm in submodules.values()}) > 1: raise ExperimentBuildingError( f"{transmon.name}: measure submodules must all agree on acq_channel, " f"got {[(name, sm.acq_channel) for name, sm in submodules.items()]}" ) ordered_transmons = OrderedDict( sorted( self._transmons.items(), key=lambda item: int(item[1].measure.acq_channel), ) ) return ordered_transmons @property @abc.abstractmethod def measure_gate_class(self) -> Measure: ...
[docs] @abc.abstractmethod def schedule_function(self, **kwargs) -> TimeableSchedule: """Build this measurement's schedule. Called by :meth:`BaseNode.precompile` as ``schedule_function(**schedule_samplespace, **self.schedule_keywords)`` -- keyword-only, with the keyword set varying per measurement (there's no shared signature to enforce beyond that). """
[docs] def point_schedule(self, *args) -> TimeableSchedule: raise NotImplementedError( "Point schedule method has not been implemented, " "so generic_1d_sweep or generic_2d_sweep methods cannot be " "used." )
[docs] def make_linear_domains( self, linear_setpoints: dict[str, np.ndarray], dtype: DType ) -> list[LinearDomain]: domains = [] for device_element in self.transmons: setpoints = np.asarray(linear_setpoints[device_element]) if len(setpoints) > 2: steps = np.diff(setpoints) if not np.allclose(steps, steps[0]): raise ExperimentBuildingError( f"Samplespace for {device_element!r} is not evenly " f"spaced (steps range from {steps.min()} to " f"{steps.max()})." ) domains.append( linspace( start=float(setpoints[0]), stop=float(setpoints[-1]), num=len(setpoints), dtype=dtype, ) ) return domains
[docs] def make_shot_indices(self, repetitions: int) -> LinearDomain: return arange(start=0, stop=repetitions, step=1, dtype=DType.NUMBER)
[docs] def excite_system(self, to_state: Literal[1, 2]) -> TimeableSchedule: """Excite all qubits to the given state (1 or 2) in parallel.""" if to_state < 1: raise ValueError("'to_state' must be a positive integer.") elif to_state > 2: raise NotImplementedError("'to_state' must be 1 or 2.") sched = TimeableSchedule("excite_system") # anchor ref op. for parallelism start_ref = sched.add(IdlePulse(duration=0.0)) for t in self.transmons.values(): match to_state: case 1: sched.add(X(t.name), ref_op=start_ref) case 2: sched.add(X(t.name), ref_op=start_ref) sched.add(Rxy_12(t.name)) return sched
[docs] @staticmethod def calibrated_gate_level(transmon: ExtendedTransmon) -> int: """Highest excited state this qubit's device model can prepare. Calibration values are NaN until a real value has been written by a successful calibration run. Returns 0 when even the X gate (0->1) is not calibrated, 1 when the X gate is calibrated, and 2 when the 1->2 pulse is calibrated too. """ if np.isnan(float(transmon.rxy.amp180)) or np.isnan( float(transmon.rxy.duration) ): return 0 if np.isnan(float(transmon.r12.ef_amp180)) or np.isnan( float(transmon.r12.ef_duration) ): return 1 return 2
[docs] def calibration_points_schedule(self, repetitions: int) -> TimeableSchedule | None: """Static per-state calibration block, appended by ``BaseNode.precompile``. Requires every qubit's X gate (0->1) to be calibrated; returns ``None`` otherwise (no partial calibration block for a subset of qubits). The shared state range is the lowest calibrated level across all qubits: for each state ``i`` in that range, the system is reset, excited to state ``i`` (all qubits together) and measured with the coordinate ``CAL=i`` on dedicated ``CAL_<n>`` acquisition channels (``CAL`` marks calibration data everywhere, like ``AR_`` marks active reset). ``BaseNode.configure_dataset`` extracts these into per-qubit ``<qubit>_CAL`` data variables. The block carries its own repetition loop register, so it runs identically regardless of the node's sweep/loop structure and its acquisitions are hardware-averaged over *repetitions*. """ levels = [self.calibrated_gate_level(t) for t in self.transmons.values()] max_state = min(levels, default=0) if max_state == 0: return None sched = TimeableSchedule("calibration_points") with sched.loop(self.make_shot_indices(repetitions)): for state in range(max_state + 1): sched.add(self.reset_system(method="passive")) if state: sched.add(self.excite_system(to_state=state)) sched.add( self.measure_system( coords={"CAL": state}, bin_mode="average_append", acq_channel_prefix="CAL_", ) ) return sched
[docs] def reset_system( self, /, *, method: Literal["passive", "active"] ) -> TimeableSchedule: reset_schedule = TimeableSchedule("reset_system") if method == "passive": reset_schedule.add(Reset(*self.transmons.keys())) elif method == "active": reset_schedule.add(self._active_reset_schedule()) else: raise NotImplementedError(f"Unknown reset method: {method}") return reset_schedule
[docs] @staticmethod def compute_stagger_times(durations: list[float]) -> list[float]: return np.cumsum([0] + durations[:-1]).tolist()
@staticmethod def _index_coord_value(x, qubit_idx: int) -> Variable | int | float | complex: if isinstance(x, np.ndarray): if x.ndim != 1: raise RuntimeError( f"Coordinate value must be a flat (1-D) array, got shape {x.shape}." ) return x[qubit_idx].item() if isinstance(x, Sequence) and not isinstance(x, str): return x[qubit_idx] return x def _active_reset_schedule(self) -> TimeableSchedule: active_reset_durations = [ ( transmon.measure_2state_opt.acq_delay + transmon.measure_2state_opt.integration_time + qblox_constants.TRIGGER_DELAY + transmon.rxy.duration + qblox_constants.MAX_MIN_INSTRUCTION_WAIT ) for transmon in self.transmons.values() ] stagger_times = self.compute_stagger_times(active_reset_durations) return self.measure_system( coords={}, bin_mode="average_append", acq_protocol="ThresholdedAcquisition", stagger=stagger_times, conditional_operation=X, measure_gate_class=Measure_RO_2state_Opt, acq_channel_prefix="AR_", )
[docs] def measure_system( self, /, *, coords: dict[str, list[Variable] | Variable | int | float | complex], bin_mode: Literal["average_append", "append"], acq_protocol: Literal[ "SSBIntegrationComplex", "Timetag", "TimetagTrace", "Trace", "TriggerCount", "ThresholdedTriggerCount", "NumericalSeparatedWeightedIntegration", "NumericalWeightedIntegration", "ThresholdedAcquisition", ] = "SSBIntegrationComplex", acq_channel_prefix: str | None = None, holdoff_time: Variable | float = 0.0, stagger: list[float] | float | Literal["trigger_network"] = 0.0, conditional_operation: SingleQubitGate | None = None, measure_gate_class: Measure | None = None, # ---- device overrides acq_delay: list[Variable] | None = None, pulse_amp: list[Variable] | None = None, pulse_duration: list[Variable] | None = None, freq: list[Variable] | None = None, acq_duration: list[Variable] | None = None, ) -> TimeableSchedule: """ Readout all qubits with configurable timing and optional conditional operations. Qubit names are prepended to all coordinate keys before passing to the measure gate. Device override parameters, if given, are indexed per qubit by position in :attr:`transmons`. Method Parameters ----------------- coords : dict[str, list[Variable] or Variable or int or float or complex] Coordinate labels and values attached to each acquisition. List values are indexed per qubit; scalars are broadcast to all qubits. holdoff_time : Variable or float, optional Idle time inserted before any measurements. By default 0.0. stagger : list[float] or float or "trigger_network", optional Start times for each measurement, relative to ``holdoff_time``. When specified as a fixed offset, then the start times are computed using :meth:`compute_stagger_times`. ``"trigger_network"`` uses a fixed offset based on trigger network timing constraints. By default `stagger=0.0` which corresponds to a simultaneous readout of all qubits. conditional_operation : SingleQubitGate, optional If provided, called with each qubit name and the result is wrapped in a :class:`~qblox_scheduler.operations.control_flow_library.ConditionalOperation` appended after its measurement. By default ``None``. measure_gate_class : Measure, optional Override the gate class used for measurement. Defaults to :attr:`measure_gate_class`. Measure gate parameters ----------------------- bin_mode : "average_append" or "append" Binning mode passed to the measure gate. acq_protocol : str, optional Acquisition protocol passed to the measure gate. By default ``"SSBIntegrationComplex"``. acq_channel_prefix : str, optional If set, the acquisition channel is set to ``f"{acq_channel_prefix}{qubit_idx}"`` instead of the default integer index. By default ``None``. Measure gate device override parameters --------------------------------------- acq_delay : list[Variable], optional Per-qubit device override for acquisition delay. pulse_amp : list[Variable], optional Per-qubit device override for measure pulse amplitude. pulse_duration : list[Variable], optional Per-qubit device override for measure pulse duration. freq : list[Variable], optional Per-qubit device override for readout frequency. acq_duration : list[Variable], optional Per-qubit device override for the acquisition duration (integration time / raw trace length). Returns ------- TimeableSchedule Schedule containing the staggered measurement of all qubits. """ if measure_gate_class is None: measure_gate_class = self.measure_gate_class N = len(self.transmons) if stagger == "trigger_network": # TODO: After testing this, put # the constant in a proper place stagger_times = self.compute_stagger_times([252e-9] * N) elif stagger == "sequential": raise NotImplementedError("TODO") elif isinstance(stagger, float): stagger_times = self.compute_stagger_times([stagger] * N) else: stagger_times = stagger buffer_times = np.flip(stagger_times).tolist() schedule = TimeableSchedule("measure_system") start_ref = schedule.add(IdlePulse(duration=0.0)) for mparam_idx, transmon in enumerate(self.transmons.values()): qubit_idx = int(transmon.measure.acq_channel) device_overrides = { kwarg_name: mparam[mparam_idx] for kwarg_name, mparam in zip( [ "acq_delay", "pulse_amp", "pulse_duration", "freq", "acq_duration", ], [acq_delay, pulse_amp, pulse_duration, freq, acq_duration], ) if mparam is not None } feedback_trigger_label = ( transmon.name if conditional_operation is not None else None ) if acq_channel_prefix is not None: acq_channel = f"{acq_channel_prefix}{qubit_idx}" else: acq_channel = qubit_idx schedule.add( measure_gate_class( transmon.name, acq_channel=acq_channel, coords={ f"{transmon.name}_{c}": self._index_coord_value(x, mparam_idx) for c, x in coords.items() }, acq_protocol=acq_protocol, feedback_trigger_label=feedback_trigger_label, bin_mode=bin_mode, **device_overrides, ), ref_op=start_ref, rel_time=stagger_times[mparam_idx] + self._index_coord_value(holdoff_time, mparam_idx), ) if conditional_operation is not None: schedule.add( ConditionalOperation( body=conditional_operation(transmon.name), qubit_name=transmon.name, ), rel_time=qblox_constants.TRIGGER_DELAY, ) schedule.add(IdlePulse(duration=buffer_times[mparam_idx])) return schedule
[docs] def generic_1d_sweep( self, /, *, linear_domains: list[LinearDomain], point_schedule: Callable[[list[Variable]], TimeableSchedule], shot_index: Variable | None = None, ) -> TimeableSchedule: sched = TimeableSchedule("generic_1d_loop") # NOTE: Assumes that linear domains list is # in the integer order of acquistion channel # of the device_elements with sched.loop(*linear_domains) as var: setpoint: list[Variable] = [var] if len(linear_domains) == 1 else var if shot_index is None: sched.add(point_schedule(setpoint)) else: sched.add(point_schedule(shot_index, setpoint)) return sched
[docs] def generic_2d_sweep( self, /, *, inner_linear_domains: list[LinearDomain], outer_linear_domains: list[LinearDomain], point_schedule: Callable[[list[Variable], list[Variable]], TimeableSchedule], shot_index: Variable | None = None, ) -> TimeableSchedule: sched = TimeableSchedule("generic_2d_loop") # NOTE: Assumes that linear domains list is # in the integer order of acquistion channel # of the device_elements # NOTE: Order of schedule_samplespace should # be (inner, outer) with sched.loop(*outer_linear_domains) as outer_var: setpoint_outer: list[Variable] = ( [outer_var] if len(outer_linear_domains) == 1 else outer_var ) with sched.loop(*inner_linear_domains) as inner_var: setpoint_inner: list[Variable] = ( [inner_var] if len(inner_linear_domains) == 1 else inner_var ) # let the point schedule definition handle parallelism if shot_index is None: sched.add(point_schedule(setpoint_outer, setpoint_inner)) else: sched.add( point_schedule(shot_index, setpoint_outer, setpoint_inner) ) return sched
[docs] @deprecated("generic_1d_sweep") def generic_1d_point(self, *args, **kwargs) -> TimeableSchedule: return self.generic_1d_sweep(*args, **kwargs)
[docs] @deprecated("generic_2d_sweep") def generic_2d_point(self, *args, **kwargs) -> TimeableSchedule: return self.generic_2d_sweep(*args, **kwargs)
@override def __str__(self): return f"Schedule on qubits {self.qubits}" @override def __format__(self, message): return f"Schedule on qubits {self.qubits}" @override def __repr__(self): return f"Schedule on qubits {self.qubits})"