From 2ebbbb6b8057dde9c3474e0e89784a882f9836b8 Mon Sep 17 00:00:00 2001 From: wyzula-jan Date: Sat, 3 Oct 2026 17:01:29 +0200 Subject: [PATCH] feat(devices): add LaserDelay positioner for the delay card and RF phase shifter --- superxas_bec/devices/laser_delay.py | 819 ++++++++++++++++++++++++++++ 1 file changed, 819 insertions(+) create mode 100644 superxas_bec/devices/laser_delay.py diff --git a/superxas_bec/devices/laser_delay.py b/superxas_bec/devices/laser_delay.py new file mode 100644 index 0000000..adae6b2 --- /dev/null +++ b/superxas_bec/devices/laser_delay.py @@ -0,0 +1,819 @@ +""" +Laser delay positioner for SuperXAS (X10DA): delay card plus RF phase shifter. + +Port of the beamline scientist's ``DelayLaser.py`` (Duetto laser, timing mode ``DelayAndPhase``, +external trigger from the event receiver, phase shifter 2 in ES4). All times are in ns. + +How a delay ``t`` (X-ray minus laser, as read on the oscilloscope) is set: + +* **Delay card (coarse + fine).** ``t1 = (-offset_t - t) mod laser_period``; + ``DELAY = int(t1 / 2)`` (units of 2 ns) and ``FINE = int((t1 mod 2) / 0.009999)`` + (units of 0.01 ns). The divisor 0.009999 instead of 0.01 is taken over from the script on + purpose: it stops values such as ``0.5 / 0.01 = 49.99999...`` from being truncated one unit low. +* **Phase shifter (two voltages V1 = vmax cos(phi), V2 = vmax sin(phi)).** Target phase + ``P = (-t mod cavity_period) - offset_phase_t``. The move is relative: ``dP = P - phase_t`` + where ``phase_t`` is the phase stored by the previous move (``phase_reference="stored"``, the + script's behaviour) or the phase read back from V1/V2 (``phase_reference="readback"``). The ramp + always starts at the phase read back from V1/V2 and walks in steps of + ``sign(dP) * rf_period / steps_per_rf_period`` with ``step_sleep`` seconds between steps; the + last step lands exactly on ``readback + dP``. Afterwards ``P`` is stored as the new ``phase_t``. + +The stored phase is "unwrapped": the voltages only encode the phase modulo one RF period, while the +stored value keeps track of how many RF periods the shifter has been turned. That is why the script +(and the default ``phase_reference="stored"``) computes ``dP`` from the stored value. If somebody +changes V1/V2 outside this device, stored and read-back phase no longer agree modulo the RF +period; the ``phase_mismatch`` signal shows the difference and a warning is logged at the start of +every move. + +Calibration (the script's ``CurrentSituation``, run after every laser restart) reads the EVR laser +period, the delay card and the phase shifter and combines them with the oscilloscope reading +``s`` = X-ray minus laser: ``offset_t = -(2 DELAY + 0.01 FINE) - s`` and +``offset_phase_t = -phase_t - (s mod cavity_period)``. The script kept these numbers in a file +``Timing.offset``; here they are config signals on the device (see ``LASER_DELAY.md``). + +The readback of the positioner is the last commanded delay. After ``calibrate(s)`` it is ``s``, +because the model maps the current settings to ``t = s``. It is NaN before calibration and after an +interrupted move. +""" + +from __future__ import annotations + +import functools +import math +import threading +import time +from dataclasses import asdict, dataclass +from typing import TYPE_CHECKING, Callable + +import numpy as np +from bec_lib.logger import bec_logger +from ophyd import Component as Cpt +from ophyd import EpicsSignal, EpicsSignalRO +from ophyd import FormattedComponent as FCpt +from ophyd import Kind, Signal +from ophyd.positioner import PositionerBase +from ophyd.signal import InternalSignal, SignalRO +from ophyd.utils import InvalidState, LimitError +from ophyd_devices import DeviceStatus, PSIDeviceBase, StatusBase +from ophyd_devices.interfaces.base_classes.psi_device_base import DeviceStoppedError + +if TYPE_CHECKING: # pragma: no cover + from bec_lib.devicemanager import DeviceManagerBase, ScanInfo + +logger = bec_logger.logger + +#: Delay card coarse unit in ns (``X10DA-ES2-TIM:SET1-DELAY``). +DELAY_CARD_COARSE_UNIT = 2.0 +#: Delay card fine unit in ns (``X10DA-ES2-TIM:SET1-FINE``), used when reading the card. +DELAY_CARD_FINE_UNIT = 0.01 +#: Divisor used when *writing* the fine value. Kept from the script (see module docstring). +DELAY_CARD_FINE_DIVISOR = 0.009999 + +PHASE_REFERENCES = ("stored", "readback") + + +class LaserDelayNotCalibratedError(RuntimeError): + """Raised when a move is requested before the device has been calibrated.""" + + +class LaserDelayBusyError(RuntimeError): + """Raised when an action needs the device idle while a move is still running.""" + + +# --------------------------------------------------------------------------------------------- # +# Maths, kept as plain functions so that they can be checked against the reference script. # +# --------------------------------------------------------------------------------------------- # + + +def delay_card_setting(total_t: float, laser_period: float) -> tuple[int, int]: + """Coarse and fine delay card values for a total delay, exactly as the script's MoveDelayCard. + + Args: + total_t (float): ``-offset_t - t`` in ns. + laser_period (float): laser period in ns. + + Returns: + tuple[int, int]: ``(DELAY, FINE)``, in units of 2 ns and 0.01 ns. + """ + t1 = total_t % laser_period + coarse = int(t1 / DELAY_CARD_COARSE_UNIT) + fine = int((t1 % DELAY_CARD_COARSE_UNIT) / DELAY_CARD_FINE_DIVISOR) + return coarse, fine + + +def delay_card_time(coarse: float, fine: float) -> float: + """Delay in ns currently set on the delay card (script: ``DelayCardT``).""" + return DELAY_CARD_COARSE_UNIT * coarse + DELAY_CARD_FINE_UNIT * fine + + +def phase_from_voltages(v1: float, v2: float, rf_period: float) -> float: + """Phase shifter delay in ns from the two voltages (script: ``GetPhaseT``), in [-rf/2, rf/2].""" + phi = np.arctan2(v2, v1) + return rf_period * phi / (2 * np.pi) + + +def voltages_for_phase(phase_t: float, rf_period: float, vmax: float) -> tuple[float, float]: + """V1 and V2 for a phase shifter delay in ns (script: ``SetVoltages``).""" + phi = 2 * np.pi * phase_t / rf_period + return vmax * np.cos(phi), vmax * np.sin(phi) + + +def phase_ramp_offsets(delta: float, rf_period: float, steps_per_rf_period: int) -> np.ndarray: + """Intermediate phase offsets (relative to the ramp start) of a phase shifter move. + + Same values as the script's ``arange(0, RelativeDelay, DelayStep)``. The final step to exactly + ``delta`` is not included. The script fails on ``delta == 0`` (numpy cannot size the range); + here the ramp is simply empty and only the final step is written. + """ + if delta == 0: + return np.empty(0) + step = np.sign(delta) * rf_period / steps_per_rf_period + return np.arange(0, delta, step) + + +def wrap_phase(value: float, rf_period: float) -> float: + """Wrap a phase difference in ns into [-rf/2, rf/2).""" + return (value + rf_period / 2) % rf_period - rf_period / 2 + + +@dataclass(frozen=True) +class LaserDelayCalibration: + """Calibration of the delay, the four numbers of the script's ``Timing.offset`` file.""" + + laser_period: float + offset_t: float + offset_phase_t: float + phase_t: float + + def as_dict(self) -> dict[str, float]: + """Plain dictionary (RPC friendly).""" + return {key: float(value) for key, value in asdict(self).items()} + + +@dataclass(frozen=True) +class _Constants: + rf_period: float + cavity_period: float + vmax: float + steps_per_rf_period: int + step_sleep: float + phase_reference: str + + +# --------------------------------------------------------------------------------------------- # +# Signals # +# --------------------------------------------------------------------------------------------- # + + +class CheckedSignal(Signal): + """Soft signal that validates every write, used for tunable constants. + + Writes come from the constructor and from runtime ``deviceConfig`` updates + (``dev.laser_delay.set_device_config({...})``), so a bad value is rejected instead of being + used in the next move. + """ + + def __init__(self, *args, validator: Callable[[object], None] | None = None, **kwargs): + self._validator = validator + super().__init__(*args, **kwargs) + + def check_value(self, value): + super().check_value(value) + if self._validator is not None: + self._validator(value) + + +class ComputedPhaseSignal(SignalRO): + """Read-only signal whose value is computed by the parent device on every read. + + ``compute`` names a method of the parent that takes no arguments and returns a float. + """ + + def __init__(self, *args, compute: str, **kwargs): + self._compute = compute + super().__init__(*args, value=math.nan, **kwargs) + + def get(self, **kwargs): + value = float(getattr(self.parent, self._compute)()) + self._readback = value + self._metadata["timestamp"] = time.time() + return value + + +def _positive_number(name: str) -> Callable[[object], None]: + def check(value): + try: + number = float(value) + except (TypeError, ValueError) as exc: + raise ValueError(f"{name} must be a number, got {value!r}") from exc + if not math.isfinite(number) or number <= 0: + raise ValueError(f"{name} must be a positive finite number, got {value!r}") + + return check + + +def _non_negative_number(name: str) -> Callable[[object], None]: + def check(value): + try: + number = float(value) + except (TypeError, ValueError) as exc: + raise ValueError(f"{name} must be a number, got {value!r}") from exc + if not math.isfinite(number) or number < 0: + raise ValueError(f"{name} must be a non-negative finite number, got {value!r}") + + return check + + +def _positive_integer(name: str) -> Callable[[object], None]: + def check(value): + try: + number = float(value) + except (TypeError, ValueError) as exc: + raise ValueError(f"{name} must be an integer, got {value!r}") from exc + if isinstance(value, bool) or not number.is_integer() or number < 1: + raise ValueError(f"{name} must be a positive integer, got {value!r}") + + return check + + +def _phase_reference(value): + if value not in PHASE_REFERENCES: + raise ValueError(f"phase_reference must be one of {PHASE_REFERENCES}, got {value!r}") + + +# --------------------------------------------------------------------------------------------- # +# Device # +# --------------------------------------------------------------------------------------------- # + + +class LaserDelay(PSIDeviceBase, PositionerBase): + """Scannable laser delay (ns) at SuperXAS: delay card plus slowly ramped RF phase shifter. + + Usage (BEC client):: + + dev.laser_delay.calibrate(546.04 - 546.92) # scope: X-ray minus laser, after laser restart + scans.mv(dev.laser_delay, 1.2) + scans.line_scan(dev.laser_delay, -5, 5, steps=21, exp_time=1, relative=False) + + A move writes the delay card, then ramps the phase shifter voltages (up to a few hundred steps + of ``step_sleep`` seconds). It runs in a background task; ``stop()`` interrupts the ramp between + two steps and leaves the voltages at the last written step. + + Args: + name (str): device name. + prefix (str): unused, kept for the common device signature. PV names are given in full. + delay_coarse_pv (str): delay card coarse PV (units of 2 ns). + delay_fine_pv (str): delay card fine PV (units of 0.01 ns). + evr_period_pv (str): event receiver laser trigger period PV (µs). + phase_v1_pv (str): phase shifter voltage V1 (cos) PV. + phase_v2_pv (str): phase shifter voltage V2 (sin) PV. + rf_period (float): RF period in ns (script ``RFPeriod``). + cavity_period (float): laser cavity period in ns (script ``CavityPeriod``, Duetto). + vmax (float): phase shifter voltage amplitude (script ``Vmax``). + steps_per_rf_period (int): phase ramp steps per RF period (script ``NumStepsPerPeriod``). + step_sleep (float): seconds between two phase ramp steps. + phase_reference (str): ``"stored"`` (script behaviour) or ``"readback"``; what the relative + phase move is computed from, see module docstring. + limits (list[float] | None): optional soft limits ``[low, high]`` in ns. + """ + + USER_ACCESS = ["calibrate", "set_calibration", "get_calibration", "plan_move"] + + # Readback: last commanded delay (named like the device, hinted) + readback = Cpt( + InternalSignal, value=math.nan, kind=Kind.hinted, doc="Last commanded delay in ns" + ) + motor_is_moving = Cpt(InternalSignal, value=0, kind=Kind.omitted, doc="1 while a move runs") + + # Hardware + delay_coarse = FCpt( + EpicsSignal, "{self._delay_coarse_pv}", kind=Kind.normal, doc="Delay card, units of 2 ns" + ) + delay_fine = FCpt( + EpicsSignal, "{self._delay_fine_pv}", kind=Kind.normal, doc="Delay card, units of 0.01 ns" + ) + evr_period = FCpt( + EpicsSignalRO, "{self._evr_period_pv}", kind=Kind.config, doc="EVR laser period in µs" + ) + phase_v1 = FCpt(EpicsSignal, "{self._phase_v1_pv}", kind=Kind.normal, doc="Phase shifter V1") + phase_v2 = FCpt(EpicsSignal, "{self._phase_v2_pv}", kind=Kind.normal, doc="Phase shifter V2") + + # Derived from the hardware on every read + phase_readback = Cpt( + ComputedPhaseSignal, + compute="read_phase", + kind=Kind.normal, + doc="Phase shifter delay in ns from V1/V2, wrapped to one RF period", + ) + phase_mismatch = Cpt( + ComputedPhaseSignal, + compute="read_phase_mismatch", + kind=Kind.normal, + doc="Stored minus read-back phase in ns, modulo the RF period (0 when consistent)", + ) + + # Calibration (script: Timing.offset). Written by calibrate()/set_calibration() and by moves. + laser_period = Cpt(InternalSignal, value=math.nan, kind=Kind.config, doc="Laser period in ns") + offset_t = Cpt(InternalSignal, value=math.nan, kind=Kind.config, doc="Delay card offset in ns") + offset_phase_t = Cpt( + InternalSignal, value=math.nan, kind=Kind.config, doc="Phase shifter offset in ns" + ) + phase_t = Cpt( + InternalSignal, + value=math.nan, + kind=Kind.config, + doc="Stored (unwrapped) phase shifter delay in ns", + ) + + # Tunable constants (deviceConfig; runtime changes via set_device_config apply to the next move) + rf_period = Cpt( + CheckedSignal, value=2.0, kind=Kind.config, validator=_positive_number("rf_period") + ) + cavity_period = Cpt( + CheckedSignal, value=12.01, kind=Kind.config, validator=_positive_number("cavity_period") + ) + vmax = Cpt(CheckedSignal, value=1.0, kind=Kind.config, validator=_positive_number("vmax")) + steps_per_rf_period = Cpt( + CheckedSignal, + value=36, + kind=Kind.config, + validator=_positive_integer("steps_per_rf_period"), + ) + step_sleep = Cpt( + CheckedSignal, value=0.1, kind=Kind.config, validator=_non_negative_number("step_sleep") + ) + phase_reference = Cpt( + CheckedSignal, value="stored", kind=Kind.config, validator=_phase_reference + ) + + # Soft limits (BEC publishes them as the device limits) + low_limit_travel = Cpt(Signal, value=0.0, kind=Kind.omitted) + high_limit_travel = Cpt(Signal, value=0.0, kind=Kind.omitted) + + # pylint: disable=too-many-arguments,too-many-locals + def __init__( + self, + prefix: str = "", + *, + name: str, + delay_coarse_pv: str = "X10DA-ES2-TIM:SET1-DELAY", + delay_fine_pv: str = "X10DA-ES2-TIM:SET1-FINE", + evr_period_pv: str = "X10DA-ES2-TIM:EVR-FPS2", + phase_v1_pv: str = "X10DA-ES4:AO-02", + phase_v2_pv: str = "X10DA-ES4:AO-01", + rf_period: float = 2.0, + cavity_period: float = 12.01, + vmax: float = 1.0, + steps_per_rf_period: int = 36, + step_sleep: float = 0.1, + phase_reference: str = "stored", + limits: list[float] | tuple[float, float] | None = None, + scan_info: ScanInfo | None = None, + device_manager: DeviceManagerBase | None = None, + **kwargs, + ): + self._delay_coarse_pv = delay_coarse_pv + self._delay_fine_pv = delay_fine_pv + self._evr_period_pv = evr_period_pv + self._phase_v1_pv = phase_v1_pv + self._phase_v2_pv = phase_v2_pv + self._move_lock = threading.RLock() # guards _move_status and _move_stop + self._hw_lock = threading.Lock() # held by the move task while it writes PVs + self._move_stop = threading.Event() # one event per move, set to interrupt that move + self._move_status: StatusBase | None = None + super().__init__( + prefix=prefix, name=name, scan_info=scan_info, device_manager=device_manager, **kwargs + ) + self.readback.name = self.name + self._position = math.nan + # Constants: validated by CheckedSignal.check_value, a bad value fails here. + self.rf_period.put(float(rf_period)) + self.cavity_period.put(float(cavity_period)) + self.vmax.put(float(vmax)) + self.steps_per_rf_period.put(steps_per_rf_period) + self.step_sleep.put(float(step_sleep)) + self.phase_reference.put(phase_reference) + if limits is not None: + if len(limits) != 2: + raise ValueError(f"limits must be [low, high], got {limits!r}") + self.low_limit_travel.put(float(limits[0])) + self.high_limit_travel.put(float(limits[1])) + + # ----------------------------------------------------------------------------------------- # + # Positioner interface # + # ----------------------------------------------------------------------------------------- # + + @property + def egu(self) -> str: + """Engineering unit of the position.""" + return "ns" + + @property + def limits(self) -> tuple[float, float]: + """Soft limits (low, high). Equal values mean no limits.""" + return (self.low_limit_travel.get(), self.high_limit_travel.get()) + + @property + def moving(self) -> bool: + """True while a move runs (also while a stopped move finishes its current step).""" + with self._move_lock: + pending = self._move_status is not None and not self._move_status.done + return pending or self._hw_lock.locked() + + def check_value(self, value) -> None: + """Check that the requested delay is a finite number within the soft limits.""" + try: + number = float(value) + except (TypeError, ValueError) as exc: + raise ValueError(f"{self.name}: delay must be a number, got {value!r}") from exc + if not math.isfinite(number): + raise ValueError(f"{self.name}: delay must be finite, got {value!r}") + low, high = self.limits + if low < high and not low <= number <= high: + raise LimitError(f"{self.name}: {number} ns is outside the limits [{low}, {high}]") + + # pylint: disable=arguments-differ + def move(self, position, moved_cb=None, timeout: float | None = None, wait: bool = False): + """Move to a delay ``position`` (ns). Returns a status that finishes when the ramp is done. + + Raises: + LaserDelayNotCalibratedError: if the device was never calibrated. + LaserDelayBusyError: if a previous move is still running. + """ + target = float(position) + self.check_value(target) + self._require_calibration() # refuse early; the task takes its own snapshot later + with self._move_lock: + if self._move_status is not None and not self._move_status.done: + raise LaserDelayBusyError( + f"{self.name} is still moving; wait for the move to finish or stop it first." + ) + stop_event = threading.Event() + status = DeviceStatus( + self, timeout=timeout, description=f"{self.name}: move to {target} ns" + ) + # Any failure of the status (stop, timeout) also ends the ramp. + status.add_callback(functools.partial(self._on_move_status_done, stop_event)) + if moved_cb is not None: + status.add_callback(functools.partial(moved_cb, obj=self)) + self._move_status = status + self._move_stop = stop_event + self.motor_is_moving.put(1, internal=True) + self.task_handler.submit_task(self._move_task, task_args=(target, status, stop_event)) + if wait: + status.wait(timeout=timeout) + return status + + # ----------------------------------------------------------------------------------------- # + # User access # + # ----------------------------------------------------------------------------------------- # + + def calibrate(self, scope_xray_minus_laser: float) -> dict[str, float]: + """Calibrate from an oscilloscope reading (the script's ``CurrentSituation``). + + Run after every laser restart, with the laser and X-ray signals on the scope: + ``dev.laser_delay.calibrate(546.04 - 546.92)``. + + Args: + scope_xray_minus_laser (float): X-ray minus laser time on the scope, in ns. + + Returns: + dict: the new calibration (``laser_period``, ``offset_t``, ``offset_phase_t``, + ``phase_t``). + """ + s = float(scope_xray_minus_laser) + if not math.isfinite(s): + raise ValueError( + f"{self.name}: scope reading must be finite, got {scope_xray_minus_laser!r}" + ) + self._require_idle("calibrate") + constants = self._constants() + # Same reading order as the script: EVR, DELAY, FINE, V1, V2. + laser_period = 1000 * self.evr_period.get() + if not math.isfinite(laser_period) or laser_period <= 0: + raise ValueError( + f"{self.name}: laser period from {self._evr_period_pv} is {laser_period} ns; " + "is the laser triggered by the event receiver?" + ) + dt1 = self.delay_coarse.get() + dt2 = self.delay_fine.get() + delay_card_t = delay_card_time(dt1, dt2) + v1 = self.phase_v1.get() + v2 = self.phase_v2.get() + phase_t = phase_from_voltages(v1, v2, constants.rf_period) + ph = s % constants.cavity_period + offset_phase_t = -phase_t - ph + offset_t = -delay_card_t - s + if math.hypot(v1, v2) < 0.5 * constants.vmax: + logger.warning( + f"{self.name}: phase shifter amplitude {math.hypot(v1, v2):.3f} V is far below " + f"vmax={constants.vmax}; the read-back phase may be meaningless." + ) + calibration = LaserDelayCalibration( + laser_period=float(laser_period), + offset_t=float(offset_t), + offset_phase_t=float(offset_phase_t), + phase_t=float(phase_t), + ) + self._store_calibration(calibration, current_delay=s) + logger.info( + f"{self.name}: calibrated with scope X-ray minus laser = {s} ns: " + f"{calibration.as_dict()}" + ) + return calibration.as_dict() + + def set_calibration( + self, + laser_period: float, + offset_t: float, + offset_phase_t: float, + phase_t: float, + current_delay: float | None = None, + ) -> dict[str, float]: + """Set the calibration directly, e.g. after a BEC restart, from a previous calibration. + + The argument order is the order of the script's ``Timing.offset`` file, so + ``set_calibration(*[float(x) for x in numpy.loadtxt("Timing.offset")])`` takes over the + script's state. ``phase_t`` must be the stored phase of the last move (``get_calibration()`` + after that move), not a fresh read-back: the voltages only know the phase modulo one RF + period. + + Args: + laser_period (float): laser period in ns. + offset_t (float): delay card offset in ns. + offset_phase_t (float): phase shifter offset in ns. + phase_t (float): stored phase shifter delay in ns. + current_delay (float | None): the delay the hardware is at, shown as readback. + NaN if None. + """ + values = { + "laser_period": laser_period, + "offset_t": offset_t, + "offset_phase_t": offset_phase_t, + "phase_t": phase_t, + } + for key, value in values.items(): + if not math.isfinite(float(value)): + raise ValueError(f"{self.name}: {key} must be finite, got {value!r}") + if float(laser_period) <= 0: + raise ValueError(f"{self.name}: laser_period must be positive, got {laser_period!r}") + self._require_idle("set_calibration") + calibration = LaserDelayCalibration(**{key: float(val) for key, val in values.items()}) + delay = math.nan if current_delay is None else float(current_delay) + self._store_calibration(calibration, current_delay=delay) + logger.info(f"{self.name}: calibration set to {calibration.as_dict()}") + return calibration.as_dict() + + def get_calibration(self) -> dict[str, float]: + """Current calibration (NaN values when not calibrated).""" + return LaserDelayCalibration( + laser_period=float(self.laser_period.get()), + offset_t=float(self.offset_t.get()), + offset_phase_t=float(self.offset_phase_t.get()), + phase_t=float(self.phase_t.get()), + ).as_dict() + + def plan_move(self, position: float) -> dict: + """Dry run of a move: what would be written, without writing anything. + + Reads V1/V2 for the ramp start. Useful to compare with the script before the first move. + + Returns: + dict: ``delay_coarse``, ``delay_fine``, ``phase_target``, ``phase_start``, + ``phase_delta``, ``phase_steps`` (puts of V1/V2 incl. the last one) and + ``estimated_duration_s``. + """ + target = float(position) + self.check_value(target) + calibration = self._require_calibration() + constants = self._constants() + total_t = -calibration.offset_t - target + coarse, fine = delay_card_setting(total_t, calibration.laser_period) + phase_target = (-target) % constants.cavity_period - calibration.offset_phase_t + phase_start = self._read_phase(constants.rf_period) + reference = calibration.phase_t if constants.phase_reference == "stored" else phase_start + delta = phase_target - reference + offsets = phase_ramp_offsets(delta, constants.rf_period, constants.steps_per_rf_period) + n_puts = len(offsets) + 1 + return { + "target": target, + "delay_coarse": coarse, + "delay_fine": fine, + "phase_target": float(phase_target), + "phase_start": float(phase_start), + "phase_delta": float(delta), + "phase_steps": n_puts, + "estimated_duration_s": n_puts * constants.step_sleep, + } + + # ----------------------------------------------------------------------------------------- # + # Readbacks used by the computed signals # + # ----------------------------------------------------------------------------------------- # + + def read_phase(self) -> float: + """Phase shifter delay in ns read back from V1/V2 (wrapped to one RF period).""" + return self._read_phase(float(self.rf_period.get())) + + def _read_phase(self, rf_period: float) -> float: + v1 = self.phase_v1.get() + v2 = self.phase_v2.get() + return float(phase_from_voltages(v1, v2, rf_period)) + + def read_phase_mismatch(self) -> float: + """Stored minus read-back phase in ns, wrapped to [-rf/2, rf/2). NaN if uncalibrated.""" + stored = float(self.phase_t.get()) + if not math.isfinite(stored): + return math.nan + rf_period = float(self.rf_period.get()) + return float(wrap_phase(stored - self.read_phase(), rf_period)) + + # ----------------------------------------------------------------------------------------- # + # PSIDeviceBase hooks # + # ----------------------------------------------------------------------------------------- # + + def on_stop(self) -> None: + """Interrupt a running phase ramp between two steps and fail its status.""" + with self._move_lock: + self._move_stop.set() + status = self._move_status + if status is not None: + self._finish_status(status, DeviceStoppedError(f"Device {self.name} has been stopped")) + + def on_destroy(self) -> None: + """Interrupt a running move; the task handler is shut down by the base class.""" + self._move_stop.set() + + # ----------------------------------------------------------------------------------------- # + # Internals # + # ----------------------------------------------------------------------------------------- # + + def _constants(self) -> _Constants: + return _Constants( + rf_period=float(self.rf_period.get()), + cavity_period=float(self.cavity_period.get()), + vmax=float(self.vmax.get()), + steps_per_rf_period=int(self.steps_per_rf_period.get()), + step_sleep=float(self.step_sleep.get()), + phase_reference=str(self.phase_reference.get()), + ) + + def _calibration(self) -> LaserDelayCalibration: + return LaserDelayCalibration( + laser_period=float(self.laser_period.get()), + offset_t=float(self.offset_t.get()), + offset_phase_t=float(self.offset_phase_t.get()), + phase_t=float(self.phase_t.get()), + ) + + def _require_calibration(self) -> LaserDelayCalibration: + calibration = self._calibration() + values = calibration.as_dict().values() + if not all(math.isfinite(v) for v in values) or calibration.laser_period <= 0: + raise LaserDelayNotCalibratedError( + f"{self.name} is not calibrated. Run dev.{self.name}.calibrate() after the laser is on, or restore a previous calibration with " + f"dev.{self.name}.set_calibration(...). Current calibration: " + f"{calibration.as_dict()}" + ) + return calibration + + def _require_idle(self, action: str) -> None: + if self.moving: + raise LaserDelayBusyError(f"{self.name}: cannot {action} while a move is running.") + + def _store_calibration(self, calibration: LaserDelayCalibration, current_delay: float) -> None: + self.laser_period.put(calibration.laser_period, internal=True) + self.offset_t.put(calibration.offset_t, internal=True) + self.offset_phase_t.put(calibration.offset_phase_t, internal=True) + self.phase_t.put(calibration.phase_t, internal=True) + self._update_readback(current_delay) + + def _update_readback(self, value: float) -> None: + self.readback.put(float(value), internal=True) + self._set_position(float(value)) # runs the "readback" subscription (BEC update) + + @staticmethod + def _on_move_status_done(stop_event: threading.Event, status: StatusBase) -> None: + if not status.success: + stop_event.set() + + @staticmethod + def _finish_status(status: StatusBase, exc: Exception | None = None) -> None: + if status.done: + return + try: + if exc is None: + status.set_finished() + else: + status.set_exception(exc) + except InvalidState: + pass # resolved concurrently (stop vs. end of move) + + def _write_phase(self, phase_t: float, constants: _Constants) -> None: + v1, v2 = voltages_for_phase(phase_t, constants.rf_period, constants.vmax) + self.phase_v1.put(float(v1)) + self.phase_v2.put(float(v2)) + + def _move_task(self, target: float, status: StatusBase, stop_event: threading.Event) -> None: + """Body of the move, run by the task handler. Never raises; resolves ``status``. + + Readback, ``motor_is_moving`` and the hardware lock are all settled before the status + resolves, so whoever waits on the status sees the final state. Calibration and constants + are read only once the hardware lock is held: a move queued right behind a stopped one + must see the phase bookkeeping of that stopped move. + """ + error = None + with self._hw_lock: + try: + calibration = self._require_calibration() + constants = self._constants() + self._execute_move(target, calibration, constants, stop_event) + except Exception as exc: # pylint: disable=broad-except + error = exc + if not isinstance(exc, DeviceStoppedError): + logger.error(f"{self.name}: move to {target} ns failed: {exc}") + with self._move_lock: + if self._move_status is status: # no newer move queued behind this one + self.motor_is_moving.put(0, internal=True) + self._finish_status(status, error) + + def _execute_move( + self, + target: float, + calibration: LaserDelayCalibration, + constants: _Constants, + stop_event: threading.Event, + ) -> None: + """The script's SetDelay: delay card, then the phase shifter ramp, then bookkeeping.""" + if stop_event.is_set(): + raise DeviceStoppedError(f"Device {self.name} has been stopped") + total_t = -calibration.offset_t - target + phase_target = (-target) % constants.cavity_period - calibration.offset_phase_t + coarse, fine = delay_card_setting(total_t, calibration.laser_period) + + written_any = False + done_offset = None + completed = False + reference = calibration.phase_t + try: + self.delay_coarse.put(coarse) + written_any = True + self.delay_fine.put(fine) + + phase_start = self._read_phase(constants.rf_period) + if constants.phase_reference == "readback": + reference = phase_start + else: + mismatch = wrap_phase(calibration.phase_t - phase_start, constants.rf_period) + if abs(mismatch) > constants.rf_period / (2 * constants.steps_per_rf_period): + logger.warning( + f"{self.name}: stored phase and V1/V2 read-back differ by " + f"{mismatch:.4f} ns modulo the RF period (voltages changed outside BEC?). " + "The ramp starts at the read-back, so this move ends that far from the " + "intended phase." + ) + delta = phase_target - reference + offsets = phase_ramp_offsets(delta, constants.rf_period, constants.steps_per_rf_period) + logger.info( + f"{self.name}: move to {target} ns: DELAY={coarse}, FINE={fine}, phase " + f"{phase_start:.4f} -> +{delta:.4f} ns in {len(offsets) + 1} steps " + f"(~{(len(offsets) + 1) * constants.step_sleep:.1f} s)" + ) + for offset in offsets: + if stop_event.is_set(): + raise DeviceStoppedError(f"Device {self.name} has been stopped") + self._write_phase(phase_start + offset, constants) + done_offset = offset + if stop_event.wait(constants.step_sleep): + raise DeviceStoppedError(f"Device {self.name} has been stopped") + if stop_event.is_set(): + raise DeviceStoppedError(f"Device {self.name} has been stopped") + self._write_phase(phase_start + delta, constants) + done_offset = delta + completed = True + # The script also sleeps after the last step; a stop now no longer matters. + stop_event.wait(constants.step_sleep) + finally: + if completed: + self.phase_t.put(float(phase_target), internal=True) + self._update_readback(target) + else: + if done_offset is not None: + # Keep stored and real (unwrapped) phase consistent for the next move. + self.phase_t.put(float(reference + done_offset), internal=True) + if written_any: + self._update_readback(math.nan) + + +class SimLaserDelay(LaserDelay): + """LaserDelay without EPICS: soft signals replace the five PVs (local demo BEC, tests). + + The ``*_pv`` arguments are accepted and ignored. Start values: laser period 2.0002 µs, + delay card 150 / 37 (300.37 ns), V1 = 1, V2 = 0. + """ + + delay_coarse = Cpt(Signal, value=150, kind=Kind.normal, doc="Delay card, units of 2 ns") + delay_fine = Cpt(Signal, value=37, kind=Kind.normal, doc="Delay card, units of 0.01 ns") + evr_period = Cpt(Signal, value=2.0002, kind=Kind.config, doc="EVR laser period in µs") + phase_v1 = Cpt(Signal, value=1.0, kind=Kind.normal, doc="Phase shifter V1") + phase_v2 = Cpt(Signal, value=0.0, kind=Kind.normal, doc="Phase shifter V2")