From 70c08e9c11b7f94dcf03c657cbb06361c7e5ba6f Mon Sep 17 00:00:00 2001 From: wyzula-jan Date: Thu, 8 Oct 2026 22:48:41 +0200 Subject: [PATCH] feat(devices): keep the laser delay calibration across restarts and verify it before moving --- .../device_configs/laser_delay_sim.yaml | 8 +- .../device_configs/x10da_laser_delay.yaml | 14 +- superxas_bec/devices/laser_delay.py | 1104 ++++++++++++++--- tests/tests_devices/test_laser_delay.py | 664 +++++++++- .../tests_devices/test_laser_delay_golden.py | 32 +- 5 files changed, 1610 insertions(+), 212 deletions(-) diff --git a/superxas_bec/device_configs/laser_delay_sim.yaml b/superxas_bec/device_configs/laser_delay_sim.yaml index 463bae2..1f2ebf0 100644 --- a/superxas_bec/device_configs/laser_delay_sim.yaml +++ b/superxas_bec/device_configs/laser_delay_sim.yaml @@ -4,8 +4,11 @@ # SimLaserDelay: same device as LaserDelay but with soft signals instead of the five EPICS PVs, for a # local demo BEC. Add it to a running session: # bec.config.add_to_session("/superxas_bec/device_configs/laser_delay_sim.yaml") -# Then: dev.laser_delay.calibrate(-0.88); scans.line_scan(dev.laser_delay, -5, 5, steps=21, exp_time=0.1, relative=False) -# step_sleep is shortened so that demo moves take seconds instead of tens of seconds. +# Then: dev.laser_delay.calibrate(dev.laser_delay.sim_scope.get()) +# scans.line_scan(dev.laser_delay, -5, 5, steps=21, exp_time=0.1, relative=False) +# sim_scope is a simulated oscilloscope (X-ray minus laser), sim_response a pump-probe step at 0 ns. +# step_sleep is shortened so that demo moves take seconds instead of tens of seconds; set it to 0.1 +# to see the beamline timing. The calibration file is separate from the beamline one. laser_delay: readoutPriority: baseline @@ -13,6 +16,7 @@ laser_delay: deviceClass: superxas_bec.devices.laser_delay.SimLaserDelay deviceConfig: step_sleep: 0.01 + calibration_file: ~/.superxas_bec/laser_delay_sim_calibration.json deviceTags: - laser - timing diff --git a/superxas_bec/device_configs/x10da_laser_delay.yaml b/superxas_bec/device_configs/x10da_laser_delay.yaml index e464cd1..c1d9ec5 100644 --- a/superxas_bec/device_configs/x10da_laser_delay.yaml +++ b/superxas_bec/device_configs/x10da_laser_delay.yaml @@ -2,15 +2,18 @@ ## Laser delay (pump-probe) ## ################################### # Delay card X10DA-ES2-TIM:SET1 + RF phase shifter 2 (ES4) for the Duetto laser, external trigger. -# Usage and calibration: superxas_bec/devices/LASER_DELAY.md +# Usage and calibration: the LaserDelay docstrings in superxas_bec/devices/laser_delay.py; the user +# guide LASER_DELAY.md lives on the branch docs/laser-delay. # # readoutPriority baseline: every scan records the delay and the calibration once; a scan over # laser_delay elevates it to monitored. # onFailure buffer: if the timing or ES4 IOC is down, baseline readings fall back to the last value # instead of aborting unrelated scans. If the PVs are unreachable at startup, BEC disables only this # device (no I/O in __init__), the rest of the session loads. -# Calibration values are NOT config keys: run dev.laser_delay.calibrate(...) after every laser -# restart, or dev.laser_delay.set_calibration(...) to restore a previous one. +# Calibration values are NOT config keys: run dev.laser_delay.calibrate(...) after the laser restart +# or the weekly scope check. They are kept across BEC restarts in a JSON file on the device server +# host (calibration_file). dev.laser_delay.get_calibration_info() shows where, when and from which +# scope value, and whether the restored calibration was verified. laser_delay: readoutPriority: baseline @@ -27,8 +30,9 @@ laser_delay: vmax: 1.0 steps_per_rf_period: 36 step_sleep: 0.1 - phase_reference: stored - phase_path: script # "shortest" is opt-in, see LASER_DELAY.md + phase_path: script # "shortest" is opt-in, see the module docstring + fine_rollover: true # FINE 200 is written as the next coarse unit and 0 (open question) + calibration_file: ~/.superxas_bec/laser_delay_calibration.json deviceTags: - laser - timing diff --git a/superxas_bec/devices/laser_delay.py b/superxas_bec/devices/laser_delay.py index 391fbe4..999e97c 100644 --- a/superxas_bec/devices/laser_delay.py +++ b/superxas_bec/devices/laser_delay.py @@ -10,10 +10,11 @@ How a delay ``t`` (X-ray minus laser, as read on the oscilloscope) is set: ``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. + It can give ``FINE = 200``; by default (``fine_rollover``) that is written as ``DELAY + 1`` and + ``FINE = 0``, the same delay. * **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 + where ``phase_t`` is the phase stored by the previous move (the script's behaviour). 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``. @@ -22,34 +23,39 @@ How a delay ``t`` (X-ray minus laser, as read on the oscilloscope) is set: ``(-cavity_period/2, +cavity_period/2]`` and stores ``P - k * cavity_period``. That is only the same physical delay if the laser timing repeats every cavity period *and* the cavity period is a whole number of RF periods: with ``rf_period=2.0`` and ``cavity_period=12.01`` each folded period - leaves the phase shifter 0.01 ns away from where the script would put it (see ``LASER_DELAY.md``). + leaves the phase shifter 0.01 ns away from where the script would put it. 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. +(and this device) 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 move is refused when it exceeds one ramp step. 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``). +``Timing.offset``; here they are config signals on the device, kept across BEC restarts in a JSON +file (``calibration_file``) and checked against the hardware when the device connects. 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. +because the model maps the current settings to ``t = s``. It is NaN before calibration, while a move +runs and after an interrupted move. """ from __future__ import annotations import contextlib +import datetime import functools +import inspect +import json import math +import os import threading import time from dataclasses import asdict, dataclass +from pathlib import Path from typing import TYPE_CHECKING, Callable import numpy as np @@ -60,9 +66,10 @@ 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.utils import InvalidState, LimitError, ReadOnlyError from ophyd_devices import DeviceStatus, PSIDeviceBase, StatusBase from ophyd_devices.interfaces.base_classes.psi_device_base import DeviceStoppedError +from ophyd_devices.utils.psi_device_base_utils import TaskKilledError if TYPE_CHECKING: # pragma: no cover from bec_lib.devicemanager import DeviceManagerBase, ScanInfo @@ -75,8 +82,16 @@ DELAY_CARD_COARSE_UNIT = 2.0 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 +#: Fine units per coarse unit. The script can write FINE = 200 (see ``delay_card_setting``). +DELAY_CARD_FINE_PER_COARSE = 200 +#: Hard limit of the phase shifter voltages in V (ES4 analog outputs). +PHASE_VOLTAGE_LIMIT = 5.0 +#: A restored calibration older than this is reported with a warning (it is redone about weekly). +CALIBRATION_MAX_AGE_S = 7 * 24 * 3600 + +#: Fewest phase ramp steps per RF period (the script's 36: a step of 10 degrees). +MIN_STEPS_PER_RF_PERIOD = 36 -PHASE_REFERENCES = ("stored", "readback") PHASE_PATHS = ("script", "shortest") @@ -88,17 +103,33 @@ class LaserDelayBusyError(RuntimeError): """Raised when an action needs the device idle while a move is still running.""" +class LaserDelayHardwareError(RuntimeError): + """Raised when the hardware is not in the state a move or calibration needs.""" + + +class LaserDelayPersistenceError(RuntimeError): + """Raised by calibrate/set_calibration when the calibration could not be saved.""" + + # --------------------------------------------------------------------------------------------- # # 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. +def delay_card_setting( + total_t: float, laser_period: float, fine_rollover: bool = False +) -> tuple[int, int]: + """Coarse and fine delay card values for a total delay, as the script's MoveDelayCard. + + The script computes ``FINE = int((t1 mod 2) / 0.009999)``, which is 200 (2.00 ns) when + ``t1 mod 2 >= 1.9998``. With ``fine_rollover`` such a value is written as the next coarse unit + and ``FINE = 0`` instead (the same delay, and FINE stays within 0..199). Without it the values + are the script's, bit for bit. Args: total_t (float): ``-offset_t - t`` in ns. laser_period (float): laser period in ns. + fine_rollover (bool): carry ``FINE = 200`` into the coarse value. Returns: tuple[int, int]: ``(DELAY, FINE)``, in units of 2 ns and 0.01 ns. @@ -106,6 +137,10 @@ def delay_card_setting(total_t: float, laser_period: float) -> tuple[int, int]: t1 = total_t % laser_period coarse = int(t1 / DELAY_CARD_COARSE_UNIT) fine = int((t1 % DELAY_CARD_COARSE_UNIT) / DELAY_CARD_FINE_DIVISOR) + if fine_rollover and fine >= DELAY_CARD_FINE_PER_COARSE: + coarse, fine = coarse + 1, fine - DELAY_CARD_FINE_PER_COARSE + if (coarse * DELAY_CARD_COARSE_UNIT) >= laser_period: + coarse = 0 # one full laser period later is the same delay return coarse, fine @@ -171,6 +206,18 @@ class LaserDelayCalibration: """Plain dictionary (RPC friendly).""" return {key: float(value) for key, value in asdict(self).items()} + def is_valid(self) -> bool: + """All four numbers finite and a positive laser period.""" + values = self.as_dict().values() + return all(math.isfinite(v) for v in values) and self.laser_period > 0 + + +_EMPTY_CALIBRATION = LaserDelayCalibration(math.nan, math.nan, math.nan, math.nan) + + +def _utc_now() -> str: + return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds") + @dataclass(frozen=True) class _Constants: @@ -179,8 +226,13 @@ class _Constants: vmax: float steps_per_rf_period: int step_sleep: float - phase_reference: str phase_path: str + fine_rollover: bool + + @property + def step_ns(self) -> float: + """Size of one phase ramp step in ns.""" + return self.rf_period / self.steps_per_rf_period @dataclass(frozen=True) @@ -189,7 +241,7 @@ class PhasePlan: target: float # the script's ForPhaseShifter, P start: float # read back from V1/V2 - reference: float # what delta is measured from: stored phase or read-back + reference: float # what delta is measured from: the stored phase phase_t delta: float # relative ramp, folded for phase_path "shortest" cavity_wraps: int # k: stored_after = target - k * cavity_period (always 0 for "script") offsets: np.ndarray # intermediate ramp offsets, without the final step to delta @@ -204,9 +256,12 @@ class PhasePlan: def plan_phase_move( target_t: float, calibration: LaserDelayCalibration, constants: _Constants, start: float ) -> PhasePlan: - """Phase shifter ramp for a move to delay ``target_t``, starting at read-back phase ``start``.""" + """Phase shifter ramp for a move to delay ``target_t``, starting at read-back phase ``start``. + + The relative move is computed from the stored (unwrapped) phase, as in the script. + """ phase_target = (-target_t) % constants.cavity_period - calibration.offset_phase_t - reference = calibration.phase_t if constants.phase_reference == "stored" else start + reference = calibration.phase_t delta = phase_target - reference wraps = 0 if constants.phase_path == "shortest": @@ -233,21 +288,69 @@ class CheckedSignal(Signal): """Soft signal that validates every write, used for tunable constants and the soft limits. Writes come from the constructor, from runtime changes in the client - (``dev.laser_delay.step_sleep.set(0.05).wait()``, ``dev.laser_delay.limits = [-20, 20]``) and + (``dev.laser_delay.step_sleep.set(0.15).wait()``, ``dev.laser_delay.limits = [-20, 20]``) and from runtime ``deviceConfig`` updates, so a bad value is rejected instead of being used in the next move. + + ``validator`` is a callable taking the value, or the name of a method of the parent device + taking the value (for checks that depend on the device class). """ - def __init__(self, *args, validator: Callable[[object], None] | None = None, **kwargs): + def __init__(self, *args, validator: Callable[[object], None] | str | 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: + if isinstance(self._validator, str): + getattr(self.parent, self._validator)(value) + elif self._validator is not None: self._validator(value) +class _DeviceWritesOnly: # pylint: disable=no-member + """Mixin for the hardware signals: only the parent device's own code may write them. + + A move ramps the phase shifter and keeps the stored phase in step with it; a direct write + (``dev.laser_delay.phase_v1.set(...)`` from a client) would bypass the ramp, the voltage limit + and the bookkeeping. The parent allows writes per thread (``LaserDelay._hardware_writes``). + Values are also range-checked (``value_range``) in every case. + """ + + def __init__(self, *args, value_range: tuple[float, float] | None = None, **kwargs): + self._value_limits = value_range + super().__init__(*args, **kwargs) + + def check_value(self, value): + super().check_value(value) + if self._value_limits is not None: + low, high = self._value_limits + try: + number = float(value) + except (TypeError, ValueError) as exc: + raise ValueError(f"{self.name}: {value!r} is not a number") from exc + if not low <= number <= high: + raise ValueError(f"{self.name}: {number} is outside [{low}, {high}]") + + def put(self, value, *args, **kwargs): + parent = self.parent + if parent is not None and not parent.hardware_writes_allowed(): + raise ReadOnlyError( + f"{self.name} is written only by {parent.name} itself; move with " + f"umv(dev.{parent.name}, ) or a scan instead of writing it directly." + ) + self.check_value(value) + super().put(value, *args, **kwargs) + + +class _HardwareEpicsSignal(_DeviceWritesOnly, EpicsSignal): + """EPICS signal of the delay card or the phase shifter (written only by the device).""" + + +class _HardwareSoftSignal(_DeviceWritesOnly, CheckedSignal): + """Soft stand-in for a hardware PV in the simulation (written only by the device).""" + + class ComputedPhaseSignal(SignalRO): """Read-only signal whose value is computed by the parent device on every read. @@ -266,7 +369,7 @@ class ComputedPhaseSignal(SignalRO): class _ConstructorOnly: - """Read-only attribute for a constructor-only ``deviceConfig`` key (the PV names). + """Read-only attribute for a constructor-only ``deviceConfig`` key (PV names, storage). When a runtime ``deviceConfig`` update fails, BEC's device server re-applies the whole previous ``deviceConfig`` with ``setattr``/``Signal.set`` per key. Without an attribute of that name the @@ -319,40 +422,81 @@ def _positive_number(name: str) -> Callable[[object], None]: return check -def _non_negative_number(name: str) -> Callable[[object], None]: +def _phase_voltage_amplitude(value): + try: + number = float(value) + except (TypeError, ValueError) as exc: + raise ValueError(f"vmax must be a number, got {value!r}") from exc + if not math.isfinite(number) or not 0 < number <= PHASE_VOLTAGE_LIMIT: + raise ValueError( + f"vmax must be above 0 and at most the phase shifter hard limit of " + f"{PHASE_VOLTAGE_LIMIT} V, got {value!r}" + ) + + +def _steps_per_rf_period(value): + try: + number = float(value) + except (TypeError, ValueError) as exc: + raise ValueError(f"steps_per_rf_period must be an integer, got {value!r}") from exc + if isinstance(value, bool) or not number.is_integer() or number < MIN_STEPS_PER_RF_PERIOD: + raise ValueError( + f"steps_per_rf_period must be an integer of at least {MIN_STEPS_PER_RF_PERIOD} (a " + f"phase step of at most 1/{MIN_STEPS_PER_RF_PERIOD} of the RF period), got {value!r}" + ) + + +def _boolean(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}") + if not isinstance(value, (bool, np.bool_)): + raise ValueError(f"{name} must be True or False, 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}") - - def _phase_path(value): if value not in PHASE_PATHS: raise ValueError(f"phase_path must be one of {PHASE_PATHS}, got {value!r}") +# --------------------------------------------------------------------------------------------- # +# Calibration storage (kept across BEC restarts) # +# --------------------------------------------------------------------------------------------- # + + +class _FileCalibrationStore: + """Calibration kept in a JSON file on the device server host (like ``Timing.offset``).""" + + def __init__(self, path: str): + self.path = Path(os.path.expanduser(path)) + + def __str__(self) -> str: + return str(self.path) + + def load(self) -> dict | None: + """Saved content, or None if there is no file.""" + if not self.path.exists(): + return None + return json.loads(self.path.read_text(encoding="utf-8")) + + def save(self, content: dict) -> None: + """Write atomically (temporary file in the same directory, fsync, rename).""" + self.path.parent.mkdir(parents=True, exist_ok=True) + tmp = self.path.with_name(f".{self.path.name}.{os.getpid()}.{threading.get_ident()}.tmp") + try: + with open(tmp, "w", encoding="utf-8") as handle: + handle.write(json.dumps(content, indent=2)) + handle.flush() + os.fsync(handle.fileno()) + os.replace(tmp, self.path) + finally: + if tmp.exists(): + tmp.unlink() + + def destroy(self) -> None: + """Nothing to release.""" + + # --------------------------------------------------------------------------------------------- # # Device # # --------------------------------------------------------------------------------------------- # @@ -371,6 +515,11 @@ class LaserDelay(PSIDeviceBase, PositionerBase): 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. + Safety checks: the delay card and the phase shifter are written only by the device; voltages + above 5 V are never written; a move is refused when the phase shifter amplitude or phase does + not match the device's bookkeeping, or when a restored calibration could not be verified; every + write is read back. + Args: name (str): device name. prefix (str): unused, kept for the common device signature. PV names are given in full. @@ -381,17 +530,34 @@ class LaserDelay(PSIDeviceBase, PositionerBase): 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. + vmax (float): phase shifter voltage amplitude (script ``Vmax``), at most 5 V. + steps_per_rf_period (int): phase ramp steps per RF period (script ``NumStepsPerPeriod``), + at least 36. + step_sleep (float): seconds between two phase ramp steps, at least ``MIN_STEP_SLEEP``. phase_path (str): ``"script"`` (default, script behaviour) or ``"shortest"``: fold the relative phase move into half a cavity period either way. Opt-in, see module docstring. + fine_rollover (bool): write a fine value of 200 as the next coarse unit and 0 (default). + False writes 200 like the script. + calibration_file (str | None): JSON file on the device server host that keeps the + calibration across BEC restarts. None: the calibration is lost at every restart. limits (list[float] | None): optional soft limits ``[low, high]`` in ns. """ - USER_ACCESS = ["calibrate", "set_calibration", "get_calibration", "plan_move"] + USER_ACCESS = [ + "calibrate", + "set_calibration", + "get_calibration", + "get_calibration_info", + "plan_move", + ] + + #: Shortest allowed time between two phase ramp steps in s: the value the scientist tested. A + #: faster ramp needs their OK and a change here (the simulation overrides it). + MIN_STEP_SLEEP = 0.1 + #: A move or calibration is refused when hypot(V1, V2) differs from vmax by more than this. + AMPLITUDE_TOLERANCE = 0.1 + #: Read-back tolerance for the written phase shifter voltages, in V. + VOLTAGE_READBACK_TOLERANCE = 1e-3 # Readback: last commanded delay (named like the device, hinted) readback = Cpt( @@ -399,18 +565,38 @@ class LaserDelay(PSIDeviceBase, PositionerBase): ) motor_is_moving = Cpt(InternalSignal, value=0, kind=Kind.omitted, doc="1 while a move runs") - # Hardware + # Hardware (written only by the device itself) delay_coarse = FCpt( - EpicsSignal, "{self._delay_coarse_pv}", kind=Kind.normal, doc="Delay card, units of 2 ns" + _HardwareEpicsSignal, + "{self._delay_coarse_pv}", + kind=Kind.normal, + value_range=(0, 65535), + 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" + _HardwareEpicsSignal, + "{self._delay_fine_pv}", + kind=Kind.normal, + value_range=(0, DELAY_CARD_FINE_PER_COARSE), + 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") + phase_v1 = FCpt( + _HardwareEpicsSignal, + "{self._phase_v1_pv}", + kind=Kind.normal, + value_range=(-PHASE_VOLTAGE_LIMIT, PHASE_VOLTAGE_LIMIT), + doc="Phase shifter V1", + ) + phase_v2 = FCpt( + _HardwareEpicsSignal, + "{self._phase_v2_pv}", + kind=Kind.normal, + value_range=(-PHASE_VOLTAGE_LIMIT, PHASE_VOLTAGE_LIMIT), + doc="Phase shifter V2", + ) # Derived from the hardware on every read phase_readback = Cpt( @@ -439,7 +625,7 @@ class LaserDelay(PSIDeviceBase, PositionerBase): doc="Stored (unwrapped) phase shifter delay in ns", ) - # Tunable constants (deviceConfig). Runtime changes (dev.laser_delay.step_sleep.set(0.05)) apply + # Tunable constants (deviceConfig). Runtime changes (dev.laser_delay.step_sleep.set(0.15)) apply # to the next move. rf_period = Cpt( CheckedSignal, value=2.0, kind=Kind.config, validator=_positive_number("rf_period") @@ -447,20 +633,15 @@ class LaserDelay(PSIDeviceBase, PositionerBase): 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")) + vmax = Cpt(CheckedSignal, value=1.0, kind=Kind.config, validator=_phase_voltage_amplitude) 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 + CheckedSignal, value=36, kind=Kind.config, validator=_steps_per_rf_period ) + step_sleep = Cpt(CheckedSignal, value=0.1, kind=Kind.config, validator="_check_step_sleep") phase_path = Cpt(CheckedSignal, value="script", kind=Kind.config, validator=_phase_path) + fine_rollover = Cpt( + CheckedSignal, value=True, kind=Kind.config, validator=_boolean("fine_rollover") + ) # Soft limits (BEC publishes them as the device limits). Equal values mean no limits. low_limit_travel = Cpt( @@ -470,12 +651,13 @@ class LaserDelay(PSIDeviceBase, PositionerBase): CheckedSignal, value=0.0, kind=Kind.omitted, validator=_finite_number("high limit") ) - # PV names: constructor-only deviceConfig keys, see _ConstructorOnly + # Constructor-only deviceConfig keys, see _ConstructorOnly delay_coarse_pv = _ConstructorOnly() delay_fine_pv = _ConstructorOnly() evr_period_pv = _ConstructorOnly() phase_v1_pv = _ConstructorOnly() phase_v2_pv = _ConstructorOnly() + calibration_file = _ConstructorOnly() # pylint: disable=too-many-arguments,too-many-locals def __init__( @@ -493,8 +675,9 @@ class LaserDelay(PSIDeviceBase, PositionerBase): vmax: float = 1.0, steps_per_rf_period: int = 36, step_sleep: float = 0.1, - phase_reference: str = "stored", phase_path: str = "script", + fine_rollover: bool = True, + calibration_file: str | None = None, limits: list[float] | tuple[float, float] | None = None, scan_info: ScanInfo | None = None, device_manager: DeviceManagerBase | None = None, @@ -505,23 +688,30 @@ class LaserDelay(PSIDeviceBase, PositionerBase): self._evr_period_pv = evr_period_pv self._phase_v1_pv = phase_v1_pv self._phase_v2_pv = phase_v2_pv + self._calibration_file = calibration_file self._move_lock = threading.RLock() # guards _move_status and _move_stop self._hw_lock = threading.Lock() # held by the move task and by calibrate/set_calibration + self._hw_permit = threading.local() # per-thread permission to write the hardware signals self._move_stop = threading.Event() # one event per move, set to interrupt that move self._move_status: StatusBase | None = None + self._calibration_meta: dict = {} # calibrated_at, scope value of the last calibration + self._unverified: list[str] = [] # reasons the calibration may not match the hardware super().__init__( prefix=prefix, name=name, scan_info=scan_info, device_manager=device_manager, **kwargs ) self.readback.name = self.name self._position = math.nan + self._store: _FileCalibrationStore | None = None + if calibration_file: + self._store = _FileCalibrationStore(calibration_file) # 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) self.phase_path.put(phase_path) + self.fine_rollover.put(fine_rollover) if limits is not None: if len(limits) != 2: raise ValueError(f"limits must be [low, high], got {limits!r}") @@ -574,17 +764,28 @@ class LaserDelay(PSIDeviceBase, PositionerBase): """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. + LaserDelayNotCalibratedError: if the device is not calibrated, or a restored + calibration could not be verified. + + A move requested while another one runs is not raised: the returned status is already + failed with ``LaserDelayBusyError`` and the running move goes on. BEC's device server turns + an exception from ``set()`` into a status whose failure calls ``stop()`` (ophyd + ``DeviceStatus._handle_failure``), which would end the move that is 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." + status = self._refused( + LaserDelayBusyError( + f"{self.name} is still moving; wait for the move to finish or stop it first." + ), + position, ) + if wait: + status.wait(timeout=timeout) + return status + self.check_value(position) + target = float(position) + self._require_calibration() # refuse early; the task takes its own snapshot later stop_event = threading.Event() status = DeviceStatus( self, timeout=timeout, description=f"{self.name}: move to {target} ns" @@ -601,6 +802,73 @@ class LaserDelay(PSIDeviceBase, PositionerBase): status.wait(timeout=timeout) return status + ######################################## + # Beamline Specific Implementations # + ######################################## + + def on_init(self) -> None: + """ + Called when the device is initialized. + + No signals are connected at this point. If you like to + set default values on signals, please use on_connected instead. + """ + + def on_connected(self) -> None: + """ + Called after the device is connected and its signals are connected. + Default values for signals should be set here. + """ + # Restore the calibration from the store (the file), see _load_calibration. Never + # raises: the device connects uncalibrated if the restore fails. + try: + self._load_calibration() + except Exception as exc: # pylint: disable=broad-except + logger.error( + f"{self.name}: could not restore the calibration from {self._store}: {exc}. " + f"Calibrate again with dev.{self.name}.calibrate()." + ) + + def on_stage(self) -> DeviceStatus | StatusBase | None: + """ + Called while staging the device. + + Information about the upcoming scan can be accessed from the scan_info (self.scan_info.msg) object. + """ + + def on_unstage(self) -> DeviceStatus | StatusBase | None: + """Called while unstaging the device.""" + + def on_pre_scan(self) -> DeviceStatus | StatusBase | None: + """Called right before the scan starts on all devices automatically.""" + + def on_trigger(self) -> DeviceStatus | StatusBase | None: + """Called when the device is triggered.""" + + def on_complete(self) -> DeviceStatus | StatusBase | None: + """Called to inquire if a device has completed a scans.""" + + def on_kickoff(self) -> DeviceStatus | StatusBase | None: + """Called to kickoff a device for a fly scan. Has to be called explicitly.""" + + def on_stop(self) -> None: + """Called when the device is stopped.""" + # Interrupt a running phase ramp between two steps and fail its status. + self._interrupt_move(DeviceStoppedError(f"Device {self.name} has been stopped")) + + def on_destroy(self) -> None: + """Called when the device is destroyed. Cleanup resources here.""" + # Fail the move status before the base class kills the task: the kill can land anywhere + # in the task, including after the ramp but before the status is resolved, so whoever + # waits on it (a scan, umv) is released here. + self._interrupt_move(DeviceStoppedError(f"Device {self.name} has been destroyed")) + if self._store is not None: + self._store.destroy() + + ######################################## + # Helper Methods # + ######################################## + # ----------------------------------------------------------------------------------------- # # User access # # ----------------------------------------------------------------------------------------- # @@ -617,6 +885,9 @@ class LaserDelay(PSIDeviceBase, PositionerBase): Returns: dict: the new calibration (``laser_period``, ``offset_t``, ``offset_phase_t``, ``phase_t``). + + Raises: + LaserDelayPersistenceError: the calibration was applied but could not be saved. """ s = float(scope_xray_minus_laser) if not math.isfinite(s): @@ -624,7 +895,9 @@ class LaserDelay(PSIDeviceBase, PositionerBase): f"{self.name}: scope reading must be finite, got {scope_xray_minus_laser!r}" ) with self._exclusive_hardware("calibrate"): - return self._calibrate(s) + result = self._calibrate(s) + self._save_calibration(raise_on_error=True) + return result def _calibrate(self, s: float) -> dict[str, float]: constants = self._constants() @@ -640,21 +913,21 @@ class LaserDelay(PSIDeviceBase, PositionerBase): delay_card_t = delay_card_time(dt1, dt2) v1 = self.phase_v1.get() v2 = self.phase_v2.get() + problem = self._amplitude_problem(v1, v2, constants) + if problem: + raise LaserDelayHardwareError(f"{self.name}: cannot calibrate: {problem}") 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._calibration_meta = {"calibrated_at": _utc_now(), "scope_xray_minus_laser": s} + self._unverified = [] self._store_calibration(calibration, current_delay=s) logger.info( f"{self.name}: calibrated with scope X-ray minus laser = {s} ns: " @@ -670,13 +943,13 @@ class LaserDelay(PSIDeviceBase, PositionerBase): 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. + """Set the calibration directly, e.g. from the script's ``Timing.offset``. 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. + period. The next move still checks that the phase shifter matches ``phase_t``. Args: laser_period (float): laser period in ns. @@ -685,6 +958,9 @@ class LaserDelay(PSIDeviceBase, PositionerBase): 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. + + Raises: + LaserDelayPersistenceError: the calibration was applied but could not be saved. """ values = { "laser_period": laser_period, @@ -700,18 +976,45 @@ class LaserDelay(PSIDeviceBase, PositionerBase): calibration = LaserDelayCalibration(**{key: float(val) for key, val in values.items()}) delay = math.nan if current_delay is None else float(current_delay) with self._exclusive_hardware("set_calibration"): + self._calibration_meta = {"calibrated_at": _utc_now(), "scope_xray_minus_laser": None} + self._unverified = [] self._store_calibration(calibration, current_delay=delay) + self._save_calibration(raise_on_error=True) 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() + return self._calibration().as_dict() + + def get_calibration_info(self) -> dict: + """Calibration with its origin and state. + + Returns: + dict: ``calibration`` (as ``get_calibration``), ``current_delay``, ``calibrated_at`` + (UTC, ISO 8601), ``age_days``, ``scope_xray_minus_laser`` (None after + ``set_calibration``), ``verified`` (False after a restore that could not be checked + against the hardware: moves are refused), ``unverified_reasons`` and ``storage`` (the + file that keeps it across restarts, None if not kept). + """ + calibrated_at = self._calibration_meta.get("calibrated_at") + age_days = None + if calibrated_at: + try: + age = time.time() - datetime.datetime.fromisoformat(calibrated_at).timestamp() + age_days = round(age / 86400, 2) + except ValueError: + age_days = None + return { + "calibration": self.get_calibration(), + "current_delay": float(self.readback.get()), + "calibrated_at": calibrated_at, + "age_days": age_days, + "scope_xray_minus_laser": self._calibration_meta.get("scope_xray_minus_laser"), + "verified": self._calibration().is_valid() and not self._unverified, + "unverified_reasons": list(self._unverified), + "storage": str(self._store) if self._store is not None else None, + } def plan_move(self, position: float) -> dict: """Dry run of a move: what would be written, without writing anything. @@ -726,16 +1029,21 @@ class LaserDelay(PSIDeviceBase, PositionerBase): always 0 for ``phase_path="script"``, counts the folds since the calibration for ``"shortest"``), ``wrap_offset_ns`` (``-k * cavity_period`` modulo the RF period: how far the phase shifter ends from where the script would put it; 0.01 ns per fold with - the script's 2.0/12.01 ns), ``phase_steps`` (puts of V1/V2 incl. the last one) and - ``estimated_duration_s``. + the script's 2.0/12.01 ns), ``phase_steps`` (puts of V1/V2 incl. the last one), + ``estimated_duration_s`` and ``refused`` (why the move would be refused, or None). """ target = float(position) self.check_value(target) calibration = self._require_calibration() constants = self._constants() - coarse, fine = delay_card_setting(-calibration.offset_t - target, calibration.laser_period) - plan = plan_phase_move( - target, calibration, constants, start=self._read_phase(constants.rf_period) + coarse, fine = delay_card_setting( + -calibration.offset_t - target, calibration.laser_period, constants.fine_rollover + ) + v1, v2 = self.phase_v1.get(), self.phase_v2.get() + start = float(phase_from_voltages(v1, v2, constants.rf_period)) + plan = plan_phase_move(target, calibration, constants, start=start) + refused = self._amplitude_problem(v1, v2, constants) or self._phase_problem( + calibration, start, constants ) return { "target": target, @@ -749,6 +1057,7 @@ class LaserDelay(PSIDeviceBase, PositionerBase): "wrap_offset_ns": self._wrap_offset(plan.cavity_wraps, constants), "phase_steps": plan.n_puts, "estimated_duration_s": plan.n_puts * constants.step_sleep, + "refused": refused, } @staticmethod @@ -780,21 +1089,66 @@ class LaserDelay(PSIDeviceBase, PositionerBase): return float(wrap_phase(stored - self.read_phase(), rf_period)) # ----------------------------------------------------------------------------------------- # - # PSIDeviceBase hooks # + # Hardware write permission # # ----------------------------------------------------------------------------------------- # - def on_stop(self) -> None: - """Interrupt a running phase ramp between two steps and fail its status.""" - self._interrupt_move(DeviceStoppedError(f"Device {self.name} has been stopped")) + def hardware_writes_allowed(self) -> bool: + """True in a thread that is inside ``_hardware_writes`` (the device's own code).""" + return getattr(self._hw_permit, "depth", 0) > 0 - def on_destroy(self) -> None: - """Interrupt a running move and fail its status before the base class kills the task. + @contextlib.contextmanager + def _hardware_writes(self): + """Allow this thread to write the delay card and phase shifter signals.""" + self._hw_permit.depth = getattr(self._hw_permit, "depth", 0) + 1 + try: + yield + finally: + self._hw_permit.depth -= 1 - The base class shuts the task handler down by raising an exception in the task thread. That - can land anywhere in the task, including after the ramp but before the status is resolved, - so the status is failed here first; whoever waits on it (a scan, ``umv``) is released. - """ - self._interrupt_move(DeviceStoppedError(f"Device {self.name} has been destroyed")) + # ----------------------------------------------------------------------------------------- # + # Validators # + # ----------------------------------------------------------------------------------------- # + + def _check_step_sleep(self, value) -> None: + minimum = type(self).MIN_STEP_SLEEP + try: + number = float(value) + except (TypeError, ValueError) as exc: + raise ValueError(f"step_sleep must be a number, got {value!r}") from exc + if not math.isfinite(number) or number < minimum: + raise ValueError(f"step_sleep must be at least {minimum} s, got {value!r}") + + def _amplitude_problem(self, v1: float, v2: float, constants: _Constants) -> str | None: + """Why the phase shifter amplitude does not allow a ramp, or None.""" + amplitude = math.hypot(v1, v2) + if abs(amplitude - constants.vmax) > self.AMPLITUDE_TOLERANCE * constants.vmax: + return ( + f"phase shifter amplitude hypot(V1, V2) = {amplitude:.3f} V but vmax is " + f"{constants.vmax} V (ES4 IOC rebooted, voltages changed by hand, or vmax " + f"changed?). The first ramp step would jump the voltages. Restore V1/V2 to " + f"amplitude {constants.vmax} V outside BEC, or set vmax to the amplitude in use, " + f"then calibrate again." + ) + return None + + @staticmethod + def _phase_problem( + calibration: LaserDelayCalibration, start: float, constants: _Constants + ) -> str | None: + """Why the phase shifter does not match the stored phase, or None.""" + mismatch = wrap_phase(calibration.phase_t - start, constants.rf_period) + if abs(mismatch) > constants.step_ns: + return ( + f"the phase shifter is {mismatch:+.4f} ns (modulo the RF period) away from the " + f"stored phase, more than one ramp step ({constants.step_ns:.4f} ns). It was " + f"turned outside BEC, or a move was interrupted without bookkeeping. Calibrate " + f"again with the scope." + ) + return None + + # ----------------------------------------------------------------------------------------- # + # Internals # + # ----------------------------------------------------------------------------------------- # def _interrupt_move(self, exc: Exception) -> None: with self._move_lock: @@ -803,10 +1157,6 @@ class LaserDelay(PSIDeviceBase, PositionerBase): if status is not None: self._finish_status(status, exc) - # ----------------------------------------------------------------------------------------- # - # Internals # - # ----------------------------------------------------------------------------------------- # - def _constants(self) -> _Constants: return _Constants( rf_period=float(self.rf_period.get()), @@ -814,8 +1164,8 @@ class LaserDelay(PSIDeviceBase, PositionerBase): 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()), phase_path=str(self.phase_path.get()), + fine_rollover=bool(self.fine_rollover.get()), ) def _calibration(self) -> LaserDelayCalibration: @@ -828,14 +1178,19 @@ class LaserDelay(PSIDeviceBase, PositionerBase): 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: + if not calibration.is_valid(): 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()}" ) + if self._unverified: + raise LaserDelayNotCalibratedError( + f"{self.name}: the calibration does not match the hardware: " + f"{'; '.join(self._unverified)}. Moves are refused until " + f"dev.{self.name}.calibrate()." + ) return calibration @contextlib.contextmanager @@ -868,6 +1223,165 @@ class LaserDelay(PSIDeviceBase, PositionerBase): self.readback.put(float(value), internal=True) self._set_position(float(value)) # runs the "readback" subscription (BEC update) + def _mark_unverified(self, reason: str) -> None: + if reason not in self._unverified: + self._unverified.append(reason) + + # ----------------------------------------------------------------------------------------- # + # Calibration storage # + # ----------------------------------------------------------------------------------------- # + + def _extra_saved_state(self) -> dict: + """More content for the calibration file (used by the simulation).""" + return {} + + def _save_calibration( + self, move_in_progress: bool = False, raise_on_error: bool = False + ) -> bool: + """Write calibration, readback and the move marker to the store. + + Returns False (and logs an error) if the store could not be written; with + ``raise_on_error`` a ``LaserDelayPersistenceError`` is raised instead. + """ + if self._store is None: + return True + calibration = self._calibration() + if not calibration.is_valid(): + return True + readback = float(self.readback.get()) + content = { + "device": self.name, + "saved_at": _utc_now(), + **self._calibration_meta, + "calibration": calibration.as_dict(), + "constants": { + "rf_period": float(self.rf_period.get()), + "cavity_period": float(self.cavity_period.get()), + "vmax": float(self.vmax.get()), + }, + "current_delay": readback if math.isfinite(readback) else None, + "move_in_progress": move_in_progress, + **self._extra_saved_state(), + } + try: + self._store.save(content) + except Exception as exc: # pylint: disable=broad-except + message = ( + f"{self.name}: could not save the calibration to {self._store}: {exc}. It is " + f"active, but will be lost at the next restart." + ) + logger.error(message) + if raise_on_error: + raise LaserDelayPersistenceError(message) from exc + return False + return True + + def _read_saved_calibration(self) -> dict | None: + if self._store is None: + return None + return self._store.load() + + def _load_calibration(self) -> None: + """Restore the calibration from the store when the device connects. + + The four numbers are restored as they were saved. The calibration is *verified* only if the + last move finished, the laser period still matches the EVR, the phase shifter amplitude is + right, its phase matches the stored phase (modulo the RF period, within one step), the delay + card still shows the saved delay and ``rf_period``/``cavity_period``/``vmax`` are unchanged. + Otherwise moves are refused until the next ``calibrate``. The card check matters because + the phase check cannot see a change by whole RF periods; only a BEC move changes the card, + and that saves the marker first. The readback (the delay the hardware is at) is restored + only with a verified calibration. + """ + content = self._read_saved_calibration() + if content is None: + return + calibration = LaserDelayCalibration( + **{key: float(content["calibration"][key]) for key in asdict(_EMPTY_CALIBRATION)} + ) + if not calibration.is_valid(): + raise ValueError(f"not a valid calibration: {calibration.as_dict()}") + constants = self._constants() + reasons = [] + saved_constants = content.get("constants") or {} + for key in ("rf_period", "cavity_period", "vmax"): + if key in saved_constants and not math.isclose( + float(saved_constants[key]), getattr(constants, key), rel_tol=1e-9, abs_tol=1e-9 + ): + reasons.append( + f"{key} was {saved_constants[key]} at the calibration and is " + f"{getattr(constants, key)} now" + ) + if content.get("move_in_progress"): + reasons.append("the device server stopped during a move (the phase is unknown)") + evr_period = 1000 * float(self.evr_period.get()) + if not math.isclose(evr_period, calibration.laser_period, rel_tol=1e-9, abs_tol=1e-6): + reasons.append( + f"the laser period changed from {calibration.laser_period} to {evr_period} ns" + ) + v1, v2 = float(self.phase_v1.get()), float(self.phase_v2.get()) + problem = self._amplitude_problem(v1, v2, constants) + if problem is None: + start = float(phase_from_voltages(v1, v2, constants.rf_period)) + problem = self._phase_problem(calibration, start, constants) + if problem: + reasons.append(problem) + saved_delay = content.get("current_delay") + delay = math.nan if saved_delay is None else float(saved_delay) + if math.isfinite(delay): + expected = delay_card_setting( + -calibration.offset_t - delay, calibration.laser_period, constants.fine_rollover + ) + actual = (self.delay_coarse.get(), self.delay_fine.get()) + if not math.isclose( + delay_card_time(*expected), delay_card_time(*actual), abs_tol=0.005 + ): + reasons.append( + f"the delay card reads DELAY={actual[0]}, FINE={actual[1]} instead of " + f"DELAY={expected[0]}, FINE={expected[1]} for the saved delay {delay} ns (the " + f"delay was changed outside BEC?)" + ) + if reasons: + delay = math.nan + with self._exclusive_hardware("restore the calibration"): + self._calibration_meta = { + "calibrated_at": content.get("calibrated_at"), + "scope_xray_minus_laser": content.get("scope_xray_minus_laser"), + } + self._unverified = list(reasons) + self._store_calibration(calibration, current_delay=delay) + info = self.get_calibration_info() + summary = ( + f"{self.name}: restored the calibration from {self._store} (calibrated " + f"{info['calibrated_at']}): {calibration.as_dict()}, current delay {delay} ns" + ) + if reasons: + logger.warning( + f"{summary}. NOT VERIFIED, moves are refused until " + f"dev.{self.name}.calibrate(): {'; '.join(reasons)}" + ) + else: + logger.info(summary) + if info["age_days"] is not None and info["age_days"] * 86400 > CALIBRATION_MAX_AGE_S: + logger.warning( + f"{self.name}: the restored calibration is {info['age_days']} days old; it is " + "usually redone about once a week with the oscilloscope." + ) + + # ----------------------------------------------------------------------------------------- # + # Move # + # ----------------------------------------------------------------------------------------- # + + def _refused(self, exc: Exception, position) -> StatusBase: + """An already failed move status; ``call_stop_on_failure=False`` as nothing was started.""" + status = DeviceStatus( + self, + call_stop_on_failure=False, + description=f"{self.name}: move to {position!r} ns refused", + ) + status.set_exception(exc) + return status + @staticmethod def _on_move_status_done(stop_event: threading.Event, status: StatusBase) -> None: if not status.success: @@ -887,30 +1401,66 @@ class LaserDelay(PSIDeviceBase, PositionerBase): 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)) + if max(abs(v1), abs(v2)) > PHASE_VOLTAGE_LIMIT: + raise ValueError( + f"{self.name}: refusing to write V1={v1}, V2={v2}: above the phase shifter hard " + f"limit of {PHASE_VOLTAGE_LIMIT} V" + ) + with self._hardware_writes(): + self.phase_v1.put(float(v1)) + self.phase_v2.put(float(v2)) + + def _write_delay_card(self, coarse: int, fine: int) -> None: + with self._hardware_writes(): + self.delay_coarse.put(coarse) + self.delay_fine.put(fine) + actual = (self.delay_coarse.get(use_monitor=False), self.delay_fine.get(use_monitor=False)) + if actual != (coarse, fine): + raise LaserDelayHardwareError( + f"{self.name}: wrote DELAY={coarse}, FINE={fine} but the delay card reads " + f"DELAY={actual[0]}, FINE={actual[1]} (value clamped by the IOC?). The phase " + f"shifter was not touched." + ) + + def _check_phase_written(self, phase_t: float, constants: _Constants) -> None: + expected = voltages_for_phase(phase_t, constants.rf_period, constants.vmax) + actual = (self.phase_v1.get(use_monitor=False), self.phase_v2.get(use_monitor=False)) + if any(abs(a - e) > self.VOLTAGE_READBACK_TOLERANCE for a, e in zip(actual, expected)): + problem = ( + f"wrote V1={expected[0]:.4f}, V2={expected[1]:.4f} V but the phase shifter reads " + f"V1={actual[0]:.4f}, V2={actual[1]:.4f} V (value clamped by the IOC?)" + ) + self._mark_unverified(problem) + raise LaserDelayHardwareError(f"{self.name}: {problem}") 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. + Readback, ``motor_is_moving``, the store 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: + wrote = False try: calibration = self._require_calibration() constants = self._constants() - self._execute_move(target, calibration, constants, stop_event) - except Exception as exc: # pylint: disable=broad-except + wrote = self._execute_move(target, calibration, constants, stop_event) + except BaseException as exc: # pylint: disable=broad-except error = exc - if not isinstance(exc, DeviceStoppedError): + wrote = wrote or getattr(exc, "hardware_written", False) + if not isinstance(exc, (DeviceStoppedError, TaskKilledError)): logger.error(f"{self.name}: move to {target} ns failed: {exc}") + if wrote: + # Clears the move marker; the stored phase changes with every move. + self._save_calibration() 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) + if isinstance(error, TaskKilledError): + error = DeviceStoppedError(f"Device {self.name} has been destroyed") self._finish_status(status, error) def _execute_move( @@ -919,43 +1469,54 @@ class LaserDelay(PSIDeviceBase, PositionerBase): calibration: LaserDelayCalibration, constants: _Constants, stop_event: threading.Event, - ) -> None: - """The script's SetDelay: delay card, then the phase shifter ramp, then bookkeeping.""" + ) -> bool: + """The script's SetDelay: checks, delay card, phase shifter ramp, bookkeeping. + + Returns True if hardware was written. Nothing is written before all checks passed. An + exception raised after the first write carries ``hardware_written = True``. + """ if stop_event.is_set(): raise DeviceStoppedError(f"Device {self.name} has been stopped") - coarse, fine = delay_card_setting(-calibration.offset_t - target, calibration.laser_period) + v1, v2 = float(self.phase_v1.get()), float(self.phase_v2.get()) + problem = self._amplitude_problem(v1, v2, constants) + if problem: + raise LaserDelayHardwareError(f"{self.name}: move to {target} ns refused: {problem}") + start = float(phase_from_voltages(v1, v2, constants.rf_period)) + problem = self._phase_problem(calibration, start, constants) + if problem: + self._mark_unverified(problem) + raise LaserDelayHardwareError(f"{self.name}: move to {target} ns refused: {problem}") + coarse, fine = delay_card_setting( + -calibration.offset_t - target, calibration.laser_period, constants.fine_rollover + ) + plan = plan_phase_move(target, calibration, constants, start=start) + wraps = "" + if plan.cavity_wraps: + wraps = ( + f"; shortest path, {plan.cavity_wraps:+d} cavity period(s) from the script's " + f"phase: {self._wrap_offset(plan.cavity_wraps, constants):+.4f} ns (mod RF)" + ) + logger.info( + f"{self.name}: move to {target} ns: DELAY={coarse}, FINE={fine}, phase " + f"{plan.start:.4f} {plan.delta:+.4f} ns in {plan.n_puts} steps " + f"(~{plan.n_puts * constants.step_sleep:.1f} s){wraps}" + ) - written_any = False + # Mark the move before the first write: a crash from here on leaves the marker set. Without + # the marker a later restore could trust a phase that is whole RF periods stale (the phase + # check cannot see those), so the move is refused when the marker cannot be saved. + previous_readback = float(self.readback.get()) + self._update_readback(math.nan) + if not self._save_calibration(move_in_progress=True): + self._update_readback(previous_readback) + raise LaserDelayPersistenceError( + f"{self.name}: move to {target} ns refused: the move marker could not be saved to " + f"{self._store} (see the log). The hardware was not touched; fix the store and move " + f"again." + ) done_offset = None - plan = None try: - self.delay_coarse.put(coarse) - written_any = True - self.delay_fine.put(fine) - - plan = plan_phase_move( - target, calibration, constants, start=self._read_phase(constants.rf_period) - ) - if constants.phase_reference == "stored": - mismatch = wrap_phase(calibration.phase_t - plan.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." - ) - wraps = "" - if plan.cavity_wraps: - wraps = ( - f"; shortest path, {plan.cavity_wraps:+d} cavity period(s) from the script's " - f"phase: {self._wrap_offset(plan.cavity_wraps, constants):+.4f} ns (mod RF)" - ) - logger.info( - f"{self.name}: move to {target} ns: DELAY={coarse}, FINE={fine}, phase " - f"{plan.start:.4f} {plan.delta:+.4f} ns in {plan.n_puts} steps " - f"(~{plan.n_puts * constants.step_sleep:.1f} s){wraps}" - ) + self._write_delay_card(coarse, fine) for offset in plan.offsets: if stop_event.is_set(): raise DeviceStoppedError(f"Device {self.name} has been stopped") @@ -968,27 +1529,236 @@ class LaserDelay(PSIDeviceBase, PositionerBase): self._write_phase(plan.start + plan.delta, constants) done_offset = None self.phase_t.put(float(plan.stored_after), internal=True) + self._check_phase_written(plan.start + plan.delta, constants) # The script also sleeps after the last step; a stop now no longer matters. stop_event.wait(constants.step_sleep) self._update_readback(target) - except BaseException: + except BaseException as exc: if done_offset is not None: # Keep stored and real (unwrapped) phase consistent for the next move. self.phase_t.put(float(plan.reference + done_offset), internal=True) - if written_any: - self._update_readback(math.nan) + try: + exc.hardware_written = True + except AttributeError: + pass raise + return True + + +def _sim_range(name: str, low: float, high: float) -> 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 low <= number <= high: + raise ValueError(f"{name} must be within [{low}, {high}], got {value!r}") + + return check class SimLaserDelay(LaserDelay): - """LaserDelay without EPICS: soft signals replace the five PVs (local demo BEC, tests). + """LaserDelay without EPICS, with a simulated oscilloscope (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. + Soft signals replace the five PVs; the ``*_pv`` arguments are accepted and ignored. They refuse + what the IOCs are assumed to refuse: |V1|, |V2| above 5 V and FINE outside 0..199. Start values: + laser period 2.0002 µs, delay card 150 / 37 (300.37 ns), V1 = 1, V2 = 0. + + The simulated laser emits a pulse train with the cavity period, locked to the RF: turning the + phase shifter by ``x`` ns (tracked continuously, also across whole RF periods) shifts the train + by ``x`` ns. The delay card triggers the laser, which fires the first pulse of the train at or + after the trigger. ``sim_scope`` is the X-ray minus laser time an oscilloscope would show; it + starts at -0.88 ns, so ``calibrate(-0.88)`` (or + ``calibrate(dev.laser_delay.sim_scope.get())``) is a correct calibration. After any move + ``sim_scope`` should equal the readback within 0.01 ns. ``sim_response`` is a pump-probe signal: + a step of width ``sim_rise`` ns at ``sim_time_zero`` (scope time), plus noise. + + ``sim_set_hardware(...)`` changes the simulated PVs as somebody outside BEC would (caput, an IOC + reboot), to try the safety checks. + + Args: + sim_cavity_period (float | None): cavity period of the simulated laser in ns. None: the + device's ``cavity_period``. A different value shows what a wrong ``cavity_period`` + does. + sim_time_zero (float): scope delay of the pump-probe step in ns. + sim_rise (float): width of the step in ns. + sim_noise (float): standard deviation of the noise on ``sim_response``. """ - 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") + USER_ACCESS = LaserDelay.USER_ACCESS + ["sim_set_hardware"] + #: The simulation may ramp faster than the beamline (demo, tests). + MIN_STEP_SLEEP = 0.0 + + delay_coarse = Cpt( + _HardwareSoftSignal, + value=150, + kind=Kind.normal, + validator=_sim_range("delay_coarse", 0, 65535), + doc="Delay card, units of 2 ns", + ) + delay_fine = Cpt( + _HardwareSoftSignal, + value=37, + kind=Kind.normal, + validator=_sim_range("delay_fine", 0, DELAY_CARD_FINE_PER_COARSE - 1), + 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") + phase_v1 = Cpt( + _HardwareSoftSignal, + value=1.0, + kind=Kind.normal, + validator=_sim_range("phase_v1", -PHASE_VOLTAGE_LIMIT, PHASE_VOLTAGE_LIMIT), + doc="Phase shifter V1", + ) + phase_v2 = Cpt( + _HardwareSoftSignal, + value=0.0, + kind=Kind.normal, + validator=_sim_range("phase_v2", -PHASE_VOLTAGE_LIMIT, PHASE_VOLTAGE_LIMIT), + doc="Phase shifter V2", + ) + sim_scope = Cpt( + ComputedPhaseSignal, + compute="read_sim_scope", + kind=Kind.normal, + doc="Simulated oscilloscope: X-ray minus laser in ns", + ) + sim_response = Cpt( + ComputedPhaseSignal, + compute="read_sim_response", + kind=Kind.hinted, + doc="Simulated pump-probe signal", + ) + + #: Simulated X-ray arrival and laser pulse train (ns, delay card time scale). With the start + #: values a pulse sits half a cavity period after the trigger, and the scope shows -0.88 ns. + _SIM_XRAY_TIME = 305.495 + _SIM_TRAIN_OFFSET = 6.125 + + def __init__( + self, + prefix: str = "", + *, + name: str, + sim_cavity_period: float | None = None, + sim_time_zero: float = 0.0, + sim_rise: float = 0.3, + sim_noise: float = 0.01, + **kwargs, + ): + super().__init__(prefix=prefix, name=name, **kwargs) + self._sim_cavity_period = sim_cavity_period + self._sim_time_zero = float(sim_time_zero) + self._sim_rise = float(sim_rise) + self._sim_noise = float(sim_noise) + self._sim_rng = np.random.default_rng() + self._sim_lock = threading.Lock() + self._sim_angle = math.atan2(self.phase_v2.get(), self.phase_v1.get()) + self._sim_phase_turned = 0.0 # unwrapped phase shift in ns since the start + self.phase_v1.subscribe(self._sim_track_phase, run=False) + self.phase_v2.subscribe(self._sim_track_phase, run=False) + + def sim_set_hardware( + self, + delay_coarse: int | None = None, + delay_fine: int | None = None, + phase_v1: float | None = None, + phase_v2: float | None = None, + ) -> None: + """Change the simulated PVs as somebody outside BEC would (caput, IOC reboot). + + A voltage jump is followed by the simulated laser like any other phase change. + """ + with self._hardware_writes(): + for key, value in ( + ("delay_coarse", delay_coarse), + ("delay_fine", delay_fine), + ("phase_v1", phase_v1), + ("phase_v2", phase_v2), + ): + if value is not None: + getattr(self, key).put(value) + + def _sim_track_phase(self, *_, **__) -> None: + """Follow the phase shifter continuously, counting whole RF periods (the laser lock).""" + with self._sim_lock: + v1, v2 = self.phase_v1.get(), self.phase_v2.get() + if math.hypot(v1, v2) == 0: + return # no phase defined; the lock keeps the last one + angle = math.atan2(v2, v1) + turned = (angle - self._sim_angle + math.pi) % (2 * math.pi) - math.pi + self._sim_angle = angle + self._sim_phase_turned += float(self.rf_period.get()) * turned / (2 * math.pi) + + def on_connected(self) -> None: + """ + Called after the device is connected and its signals are connected. + Default values for signals should be set here. + """ + # Real IOCs and the laser keep their state across a BEC restart; soft signals do not. The + # calibration file therefore also keeps the simulated state; bring it back first, then + # restore the calibration like the real device. + try: + content = self._read_saved_calibration() + sim = (content or {}).get("sim") + if sim: + self.sim_set_hardware(**sim.get("hardware", {})) + with ( + self._sim_lock + ): # the puts above were tracked as turns; reset to the saved state + self._sim_angle = math.atan2(self.phase_v2.get(), self.phase_v1.get()) + self._sim_phase_turned = float(sim["phase_turned"]) + except Exception as exc: # pylint: disable=broad-except + logger.error(f"{self.name}: could not restore the simulated hardware: {exc}") + super().on_connected() + + def _extra_saved_state(self) -> dict: + hardware = { + "delay_coarse": int(self.delay_coarse.get()), + "delay_fine": int(self.delay_fine.get()), + "phase_v1": float(self.phase_v1.get()), + "phase_v2": float(self.phase_v2.get()), + } + with self._sim_lock: + return {"sim": {"phase_turned": self._sim_phase_turned, "hardware": hardware}} + + def read_sim_scope(self) -> float: + """X-ray minus laser in ns, as the oscilloscope would show it.""" + cavity = self._sim_cavity_period or float(self.cavity_period.get()) + trigger = delay_card_time(self.delay_coarse.get(), self.delay_fine.get()) + with self._sim_lock: + train = self._SIM_TRAIN_OFFSET + self._sim_phase_turned + laser = train + math.ceil((trigger - train) / cavity) * cavity + return self._SIM_XRAY_TIME - laser + + def read_sim_response(self) -> float: + """Pump-probe signal: step at ``sim_time_zero`` (scope time) plus noise.""" + x = (self.read_sim_scope() - self._sim_time_zero) / (math.sqrt(2) * self._sim_rise) + noise = self._sim_rng.normal(0, self._sim_noise) if self._sim_noise > 0 else 0.0 + return 0.5 * (1 + math.erf(x)) + noise + + +def _merged_signature(init: Callable, base_init: Callable) -> inspect.Signature: + """``init``'s own parameters plus the keyword parameters of ``base_init``. + + BEC's device server only passes ``deviceConfig`` keys (and ``device_manager``/``scan_info``) + that appear in the signature of the device class itself, so a subclass ``__init__`` that + forwards ``**kwargs`` has to show the base class parameters. + """ + own = [p for p in inspect.signature(init).parameters.values() if p.kind != p.VAR_KEYWORD] + names = {p.name for p in own} + base = [ + p + for p in inspect.signature(base_init).parameters.values() + if p.kind == p.KEYWORD_ONLY and p.name not in names + ] + var_kw = [ + p for p in inspect.signature(base_init).parameters.values() if p.kind == p.VAR_KEYWORD + ] + return inspect.signature(init).replace(parameters=own + base + var_kw) + + +SimLaserDelay.__init__.__signature__ = _merged_signature( + SimLaserDelay.__init__, LaserDelay.__init__ +) diff --git a/tests/tests_devices/test_laser_delay.py b/tests/tests_devices/test_laser_delay.py index ab8770b..f2a9a4f 100644 --- a/tests/tests_devices/test_laser_delay.py +++ b/tests/tests_devices/test_laser_delay.py @@ -5,6 +5,7 @@ from __future__ import annotations import functools +import json import math import threading import time @@ -21,14 +22,21 @@ from bec_server.device_server.devices.config_update_handler import ConfigUpdateH from bec_server.device_server.devices.device_serializer import get_device_base_class from bec_server.device_server.devices.devicemanager import DeviceManagerDS from ophyd.signal import ConnectionTimeoutError, InternalSignalError -from ophyd.utils import LimitError +from ophyd.utils import LimitError, ReadOnlyError from ophyd_devices.interfaces.base_classes.psi_device_base import DeviceStoppedError +from ophyd_devices.interfaces.protocols.bec_protocols import ( + BECDeviceProtocol, + BECPositionerProtocol, +) from ophyd_devices.tests.utils import MockPV, patched_device from superxas_bec.devices.laser_delay import ( + PHASE_VOLTAGE_LIMIT, LaserDelay, LaserDelayBusyError, + LaserDelayHardwareError, LaserDelayNotCalibratedError, + LaserDelayPersistenceError, SimLaserDelay, delay_card_setting, fold_phase_delta, @@ -42,6 +50,13 @@ CONFIG_DIR = Path(__file__).resolve().parents[2] / "superxas_bec" / "device_conf SCOPE = 546.04 - 546.92 +@pytest.fixture(autouse=True) +def fast_ramp(monkeypatch): + """Tests ramp without sleeping; the beamline minimum is tested on its own.""" + assert LaserDelay.MIN_STEP_SLEEP == 0.1 # the value the scientist tested + monkeypatch.setattr(LaserDelay, "MIN_STEP_SLEEP", 0.0) + + def record_puts(device: LaserDelay) -> list: """Record every put to the four written PVs, in order (thread safe enough for list.append).""" log: list[tuple[str, object]] = [] @@ -109,7 +124,6 @@ def test_default_pvs_constants_and_positioner_type(laser_delay): assert config["laser_delay_vmax"]["value"] == 1.0 assert config["laser_delay_steps_per_rf_period"]["value"] == 36 assert config["laser_delay_step_sleep"]["value"] == 0.0 - assert config["laser_delay_phase_reference"]["value"] == "stored" assert config["laser_delay_phase_path"]["value"] == "script" assert get_device_base_class(laser_delay) == "positioner" assert laser_delay.hints == {"fields": ["laser_delay"]} @@ -120,8 +134,13 @@ def test_default_pvs_constants_and_positioner_type(laser_delay): "calibrate", "set_calibration", "get_calibration", + "get_calibration_info", "plan_move", } + assert config["laser_delay_fine_rollover"]["value"] is True + assert laser_delay.calibration_file is None + assert isinstance(laser_delay, BECPositionerProtocol) + assert isinstance(laser_delay, BECDeviceProtocol) def test_config_overrides_pvs_and_constants(): @@ -138,7 +157,6 @@ def test_config_overrides_pvs_and_constants(): vmax=0.8, steps_per_rf_period=72, step_sleep=0.0, - phase_reference="readback", limits=[-20, 20], ) as device: assert [s.pvname for s in (device.delay_coarse, device.delay_fine, device.evr_period)] == [ @@ -154,7 +172,8 @@ def test_config_overrides_pvs_and_constants(): plan = device.plan_move(3.0) device.set(3.0).wait(timeout=10) phase_puts = log[2:] - # readback reference: the ramp goes from the read-back phase straight to the target + # first move after calibrate: the stored phase is the read-back, so the ramp goes from the + # read-back phase straight to the target assert plan["phase_delta"] == pytest.approx(plan["phase_target"] - plan["phase_start"]) expected_steps = len(phase_ramp_offsets(plan["phase_delta"], 2.0014, 72)) + 1 assert len(phase_puts) == 2 * expected_steps == 2 * plan["phase_steps"] @@ -173,13 +192,16 @@ def test_config_overrides_pvs_and_constants(): @pytest.mark.parametrize( "kwargs", [ - {"phase_reference": "both"}, + {"steps_per_rf_period": 35}, + {"vmax": 0.0}, {"phase_path": "fast"}, {"steps_per_rf_period": 0}, {"steps_per_rf_period": 2.5}, {"rf_period": -2.0}, {"cavity_period": 0}, {"vmax": float("nan")}, + {"vmax": 5.5}, + {"fine_rollover": "yes"}, {"step_sleep": -0.1}, {"limits": [1.0]}, {"limits": [5.0, -5.0]}, @@ -199,8 +221,8 @@ def test_runtime_constant_update_is_validated(calibrated): with pytest.raises(ValueError): calibrated.step_sleep.set(-1).wait(timeout=2) with pytest.raises(ValueError): - calibrated.phase_reference.set("sometimes").wait(timeout=2) - assert calibrated._constants().phase_reference == "stored" + calibrated.steps_per_rf_period.set(18).wait(timeout=2) + assert calibrated._constants().steps_per_rf_period == 36 with pytest.raises(ValueError): calibrated.phase_path.set("fastest").wait(timeout=2) calibrated.phase_path.set("shortest").wait(timeout=2) @@ -248,9 +270,9 @@ def test_runtime_config_update_errors_name_the_real_problem(): ) handler._update_config(msg, threading.Event()) - with pytest.raises(DeviceConfigError, match="phase_reference must be one of"): - update({"phase_reference": "readbak"}) - assert device.phase_reference.get() == "stored" + with pytest.raises(DeviceConfigError, match="phase_path must be one of"): + update({"phase_path": "fastest"}) + assert device.phase_path.get() == "script" with pytest.raises(DeviceConfigError, match="reloading the device config"): update({"phase_v1_pv": "X10DA-ES4:AO-03"}) assert device.phase_v1.pvname == "X10DA-ES4:AO-02" @@ -340,7 +362,8 @@ def test_calibration_publishes_readback_subscription(laser_delay): laser_delay.subscribe(lambda value, **_: values.append(value), event_type="readback", run=False) laser_delay.calibrate(SCOPE) laser_delay.set(1.0).wait(timeout=10) - assert values == [SCOPE, 1.0] + # NaN while the move runs: the delay is undefined until the ramp has finished + assert values[0] == SCOPE and math.isnan(values[1]) and values[2:] == [1.0] def test_set_calibration_restores_previous_state(laser_delay): @@ -414,8 +437,11 @@ def test_move_does_not_block_and_reports_moving(calibrated): assert not status.done assert calibrated.moving assert calibrated.motor_is_moving.get() == 1 + refused = calibrated.set(0.0) # not raised: a failed status, the running move goes on + assert refused.done and not refused.success with pytest.raises(LaserDelayBusyError): - calibrated.set(0.0) + refused.wait(timeout=1) + assert calibrated.moving and not status.done with pytest.raises(LaserDelayBusyError): calibrated.calibrate(SCOPE) calibrated.stop() @@ -651,7 +677,7 @@ def test_delay_card_write_failure_leaves_the_phase_shifter_alone(calibrated): assert calibrated.motor_is_moving.get() == 0 -def test_phase_read_failure_after_the_delay_card_fails_the_move(calibrated): +def test_phase_read_failure_refuses_the_move_before_any_write(calibrated): old_phase_t = calibrated.phase_t.get() log = record_puts(calibrated) with mock.patch.object( @@ -660,37 +686,43 @@ def test_phase_read_failure_after_the_delay_card_fails_the_move(calibrated): status = calibrated.set(-4.9) with pytest.raises(ConnectionTimeoutError): status.wait(timeout=5) - assert [pv for pv, _ in log] == ["X10DA-ES2-TIM:SET1-DELAY", "X10DA-ES2-TIM:SET1-FINE"] + assert log == [] assert calibrated.phase_t.get() == old_phase_t - assert math.isnan(calibrated.readback.get()) + assert calibrated.readback.get() == pytest.approx(SCOPE) # nothing moved assert not calibrated.moving -def test_stored_vs_readback_reference_when_voltages_were_touched(calibrated): +def test_move_refused_when_voltages_were_touched(calibrated): + """Somebody turned the phase shifter outside BEC: the next move is refused before any write, + and every later move too, until a new calibration.""" calibrated.set(1.0).wait(timeout=10) - # somebody turns the phase shifter by hand calibrated.phase_v1._read_pv.mock_data = 0.0 calibrated.phase_v2._read_pv.mock_data = 1.0 assert calibrated.read()["laser_delay_phase_mismatch"]["value"] != pytest.approx(0, abs=1e-3) - plan_stored = calibrated.plan_move(2.0) + assert "away from the stored phase" in calibrated.plan_move(2.0)["refused"] + log = record_puts(calibrated) + status = calibrated.set(2.0) + with pytest.raises(LaserDelayHardwareError, match="away from the stored phase"): + status.wait(timeout=10) + assert log == [] + assert calibrated.readback.get() == 1.0 # nothing was written + assert not calibrated.get_calibration_info()["verified"] + with pytest.raises(LaserDelayNotCalibratedError, match="does not match the hardware"): + calibrated.set(2.0) + calibrated.calibrate(SCOPE) calibrated.set(2.0).wait(timeout=10) - end_stored = calibrated.read_phase() - # stored: relative move from the stored phase, starting at the read-back -> offset persists - assert wrap_phase(end_stored - (0.5 + plan_stored["phase_delta"]), 2.0) == pytest.approx( - 0, abs=1e-9 - ) + assert calibrated.readback.get() == 2.0 - calibrated.phase_v1._read_pv.mock_data = 0.0 - calibrated.phase_v2._read_pv.mock_data = 1.0 - calibrated.phase_reference.put("readback") - plan_readback = calibrated.plan_move(3.0) - calibrated.set(3.0).wait(timeout=10) - # readback: lands on the target phase whatever the voltages were - assert plan_readback["phase_start"] == pytest.approx(0.5) - assert wrap_phase( - calibrated.read_phase() - plan_readback["phase_target"], 2.0 - ) == pytest.approx(0, abs=1e-9) - assert calibrated.phase_t.get() == plan_readback["phase_target"] + +def test_mismatch_below_one_step_is_accepted(calibrated): + """A V1 written without its V2 (IOC failure mid-pair) leaves less than one step: allowed.""" + calibrated.set(1.0).wait(timeout=10) + phase = calibrated.read_phase() + v1, v2 = voltages_for_phase(phase + 0.04, 2.0, 1.0) + calibrated.phase_v1._read_pv.mock_data = v1 + calibrated.phase_v2._read_pv.mock_data = v2 + calibrated.set(2.0).wait(timeout=10) + assert calibrated.readback.get() == 2.0 def test_plan_move_writes_nothing(calibrated): @@ -702,7 +734,7 @@ def test_plan_move_writes_nothing(calibrated): def test_first_move_after_calibration_can_ramp_two_cavity_periods(laser_delay): - """Documented in LASER_DELAY.md: dP = (-t mod cav) + (s mod cav) right after calibration.""" + """Module docstring: dP = (-t mod cav) + (s mod cav) right after calibration.""" laser_delay.calibrate(SCOPE) plan = laser_delay.plan_move(-4.9) assert plan["phase_delta"] == pytest.approx(4.9 + SCOPE % 12.01) @@ -891,3 +923,565 @@ def test_sim_device_moves_without_epics(): ) finally: device.destroy() + + +def test_sim_scope_follows_every_move_on_both_phase_paths(): + """The simulated oscilloscope shows the commanded delay after every move.""" + device = SimLaserDelay(name="laser_delay", step_sleep=0.0, sim_noise=0) + try: + assert device.sim_scope.get() == pytest.approx(-0.88) + device.calibrate(device.sim_scope.get()) + rng = np.random.default_rng(7) + for path in ("script", "shortest"): + device.phase_path.set(path).wait(timeout=2) + for target in rng.uniform(-40, 40, 25): + device.set(float(target)).wait(timeout=30) + assert device.sim_scope.get() == pytest.approx(target, abs=1e-6), path + device.set(-5.0).wait(timeout=30) + assert device.sim_response.get() == pytest.approx(0, abs=1e-6) + device.set(5.0).wait(timeout=30) + assert device.sim_response.get() == pytest.approx(1, abs=1e-6) + finally: + device.destroy() + + +def test_sim_scope_shows_a_wrong_calibration(): + device = SimLaserDelay(name="laser_delay", step_sleep=0.0, sim_noise=0) + try: + device.calibrate(-0.5) # scope misread by 0.38 ns + device.set(2.0).wait(timeout=30) + assert device.sim_scope.get() == pytest.approx(2.0 - 0.38) + finally: + device.destroy() + + +def test_sim_rejects_what_the_iocs_refuse(): + device = SimLaserDelay(name="laser_delay", step_sleep=0.0) + try: + with pytest.raises(ValueError): + device.sim_set_hardware(phase_v1=PHASE_VOLTAGE_LIMIT + 0.1) + with pytest.raises(ValueError): + device.sim_set_hardware(delay_fine=200) + finally: + device.destroy() + + +# --------------------------------------------------------------------------------------------- # +# Delay card fine value 200 # +# --------------------------------------------------------------------------------------------- # + + +def test_delay_card_fine_rollover(): + # t1 mod 2 = 1.99985 -> the script writes FINE 200 + assert delay_card_setting(301.99985, 2000.2) == (150, 200) + assert delay_card_setting(301.99985, 2000.2, fine_rollover=True) == (151, 0) + # the next coarse unit would be a full laser period: wrap to 0 + assert delay_card_setting(1999.99985, 2000.0, fine_rollover=True) == (0, 0) + rng = np.random.default_rng(3) + for total in rng.uniform(-5000, 5000, 5000): + script = delay_card_setting(total, 2000.2) + coarse, fine = delay_card_setting(total, 2000.2, fine_rollover=True) + assert 0 <= fine <= 199 + assert 2 * coarse + 0.01 * fine == pytest.approx(2 * script[0] + 0.01 * script[1]) + + +@pytest.mark.parametrize("rollover, expected", [(True, (151, 0)), (False, (150, 200))]) +def test_move_writes_rolled_over_fine_value(calibrated, rollover, expected): + calibrated.fine_rollover.set(rollover).wait(timeout=2) + offset_t = calibrated.get_calibration()["offset_t"] + target = -offset_t - 301.99985 # delay card total with FINE 200 + plan = calibrated.plan_move(target) + assert (plan["delay_coarse"], plan["delay_fine"]) == expected + log = record_puts(calibrated) + calibrated.set(target).wait(timeout=10) + assert [value for _, value in log[:2]] == list(expected) + + +# --------------------------------------------------------------------------------------------- # +# Phase shifter voltage limit # +# --------------------------------------------------------------------------------------------- # + + +def test_vmax_is_capped_at_the_hard_limit(calibrated): + calibrated.vmax.set(PHASE_VOLTAGE_LIMIT).wait(timeout=2) + with pytest.raises(ValueError, match="hard limit"): + calibrated.vmax.set(PHASE_VOLTAGE_LIMIT + 0.01).wait(timeout=2) + assert calibrated.vmax.get() == PHASE_VOLTAGE_LIMIT + + +# --------------------------------------------------------------------------------------------- # +# Calibration kept across BEC restarts # +# --------------------------------------------------------------------------------------------- # + + +@pytest.fixture +def caplog(): + """Messages logged by the device module (bec_logger is loguru, not std logging).""" + + class Log: + def __init__(self): + self.patcher = mock.patch("superxas_bec.devices.laser_delay.logger") + + @property + def text(self): + return "\n".join(str(c.args[0]) for c in self.mock.method_calls if c.args) + + log = Log() + log.mock = log.patcher.start() + yield log + log.patcher.stop() + + +@pytest.fixture +def calibration_file(tmp_path): + return tmp_path / "sub" / "laser_delay_calibration.json" + + +def make_device(calibration_file, **hardware): + """A fresh device (as after a BEC restart) on the given mocked hardware.""" + context = patched_device( + LaserDelay, name="laser_delay", step_sleep=0.0, calibration_file=str(calibration_file) + ) + device = context.__enter__() + set_hardware(device, **hardware) + return context, device + + +def hardware_of(device): + return { + "coarse": device.delay_coarse.get(), + "fine": device.delay_fine.get(), + "v1": device.phase_v1.get(), + "v2": device.phase_v2.get(), + } + + +def test_calibration_is_saved_after_calibrate_and_every_move(calibration_file): + context, device = make_device(calibration_file) + try: + device.calibrate(SCOPE) + saved = json.loads(calibration_file.read_text()) + assert saved["calibration"] == device.get_calibration() + assert saved["current_delay"] == pytest.approx(SCOPE) + assert saved["scope_xray_minus_laser"] == pytest.approx(SCOPE) + device.set(1.5).wait(timeout=10) + saved = json.loads(calibration_file.read_text()) + assert saved["calibration"]["phase_t"] == device.get_calibration()["phase_t"] + assert saved["current_delay"] == 1.5 + assert saved["move_in_progress"] is False + assert saved["constants"] == {"rf_period": 2.0, "cavity_period": 12.01, "vmax": 1.0} + info = device.get_calibration_info() + assert info["calibrated_at"] == saved["calibrated_at"] + assert info["age_days"] == pytest.approx(0, abs=0.01) + assert info["storage"] == str(calibration_file) + assert info["verified"] is True + finally: + context.__exit__(None, None, None) + + +def test_calibration_is_restored_after_a_restart(calibration_file): + context, device = make_device(calibration_file) + try: + device.calibrate(SCOPE) + device.set(1.5).wait(timeout=10) + before, hardware = device.get_calibration(), hardware_of(device) + plan_before = device.plan_move(-2.0) + finally: + context.__exit__(None, None, None) + context, device = make_device(calibration_file, **hardware) + try: + assert math.isnan(device.get_calibration()["phase_t"]) + device.on_connected() + assert device.get_calibration() == before + assert device.read()["laser_delay"]["value"] == 1.5 + assert device.plan_move(-2.0) == plan_before + finally: + context.__exit__(None, None, None) + + +def test_restore_with_turned_phase_shifter_refuses_moves(calibration_file, caplog): + context, device = make_device(calibration_file) + try: + device.calibrate(SCOPE) + device.set(1.5).wait(timeout=10) + before, hardware = device.get_calibration(), hardware_of(device) + finally: + context.__exit__(None, None, None) + hardware["v1"], hardware["v2"] = hardware["v2"], -hardware["v1"] # phase turned by hand + context, device = make_device(calibration_file, **hardware) + try: + device.on_connected() + assert device.get_calibration() == before + assert math.isnan(device.read()["laser_delay"]["value"]) + assert "NOT VERIFIED" in caplog.text + info = device.get_calibration_info() + assert ( + not info["verified"] and "away from the stored phase" in info["unverified_reasons"][0] + ) + with pytest.raises(LaserDelayNotCalibratedError, match="does not match the hardware"): + device.set(1.0) + finally: + context.__exit__(None, None, None) + + +def test_restore_after_a_crash_during_a_move_refuses_moves(calibration_file): + """The marker written before the first hardware write survives a crashed device server.""" + context, device = make_device(calibration_file) + try: + device.calibrate(SCOPE) + with mock.patch.object(device, "_write_phase", side_effect=SystemExit("crash")): + status = device.set(3.0) + with pytest.raises(Exception): + status.wait(timeout=10) + # simulate the crash: the end-of-move save never happened + content = json.loads(calibration_file.read_text()) + content["move_in_progress"] = True + calibration_file.write_text(json.dumps(content)) + hardware = hardware_of(device) + finally: + context.__exit__(None, None, None) + context, device = make_device(calibration_file, **hardware) + try: + device.on_connected() + assert "stopped during a move" in device.get_calibration_info()["unverified_reasons"][0] + with pytest.raises(LaserDelayNotCalibratedError): + device.set(1.0) + finally: + context.__exit__(None, None, None) + + +def test_move_marker_is_set_before_the_first_write(calibration_file): + context, device = make_device(calibration_file) + try: + device.calibrate(SCOPE) + seen = [] + original = device.delay_coarse._write_pv.put + + def check_marker(value, *args, **kwargs): + seen.append(json.loads(calibration_file.read_text())["move_in_progress"]) + return original(value, *args, **kwargs) + + device.delay_coarse._write_pv.put = check_marker + device.set(2.0).wait(timeout=10) + assert seen == [True] + assert json.loads(calibration_file.read_text())["move_in_progress"] is False + finally: + context.__exit__(None, None, None) + + +def test_restore_with_changed_laser_period_refuses_moves(calibration_file): + context, device = make_device(calibration_file) + try: + device.calibrate(SCOPE) + hardware = hardware_of(device) + finally: + context.__exit__(None, None, None) + context, device = make_device(calibration_file, evr=1.0, **hardware) + try: + device.on_connected() + assert "laser period changed" in device.get_calibration_info()["unverified_reasons"][0] + finally: + context.__exit__(None, None, None) + + +def test_restore_with_changed_delay_card_refuses_moves(calibration_file): + """A delay card that no longer shows the saved delay means the delay was changed outside BEC + (script, caput). The phase part of such a change can be whole RF periods, invisible to the phase + check, so the calibration is not verified until the next calibrate.""" + context, device = make_device(calibration_file) + try: + device.calibrate(SCOPE) + device.set(1.5).wait(timeout=10) + hardware = hardware_of(device) + finally: + context.__exit__(None, None, None) + hardware["fine"] = (hardware["fine"] + 50) % 200 + context, device = make_device(calibration_file, **hardware) + try: + device.on_connected() + info = device.get_calibration_info() + assert not info["verified"] and "delay card reads" in info["unverified_reasons"][0] + assert math.isnan(device.read()["laser_delay"]["value"]) + with pytest.raises(LaserDelayNotCalibratedError, match="does not match the hardware"): + device.set(1.0) + device.calibrate(SCOPE) + device.set(1.0).wait(timeout=10) + assert device.readback.get() == 1.0 + finally: + context.__exit__(None, None, None) + + +def test_restore_after_an_external_move_by_whole_rf_periods_refuses_moves(calibration_file): + """While BEC was down the script moved the delay by 2.0 ns (one RF period): the voltages are + exactly where the saved phase expects them, only the delay card tells. Without the card check the + next move would be 2.0 ns off while the readback claims the target.""" + context, device = make_device(calibration_file) + try: + device.calibrate(SCOPE) + device.set(5.0).wait(timeout=10) + saved = calibration_file.read_text() # BEC's last state: 5.0 ns + at_5 = hardware_of(device) + device.set(3.0).wait(timeout=10) # what the script does meanwhile: one RF period + hardware = hardware_of(device) + assert (hardware["v1"], hardware["v2"]) == pytest.approx((at_5["v1"], at_5["v2"]), abs=1e-9) + assert (hardware["coarse"], hardware["fine"]) != (at_5["coarse"], at_5["fine"]) + finally: + context.__exit__(None, None, None) + calibration_file.write_text(saved) # BEC never saw the script's move + context, device = make_device(calibration_file, **hardware) + try: + device.on_connected() + assert device.read_phase_mismatch() == pytest.approx(0, abs=1e-9) # phase check is blind + info = device.get_calibration_info() + assert not info["verified"] and "delay card reads" in info["unverified_reasons"][0] + with pytest.raises(LaserDelayNotCalibratedError): + device.set(4.0) + finally: + context.__exit__(None, None, None) + + +def test_restore_with_changed_constants_refuses_moves(calibration_file): + context, device = make_device(calibration_file) + try: + device.calibrate(SCOPE) + hardware = hardware_of(device) + finally: + context.__exit__(None, None, None) + context = patched_device( + LaserDelay, + name="laser_delay", + step_sleep=0.0, + cavity_period=12.0084, + calibration_file=str(calibration_file), + ) + device = context.__enter__() + set_hardware(device, **hardware) + try: + device.on_connected() + info = device.get_calibration_info() + assert not info["verified"] and "cavity_period was 12.01" in info["unverified_reasons"][0] + finally: + context.__exit__(None, None, None) + + +def test_old_calibration_is_restored_with_a_warning(calibration_file, caplog): + context, device = make_device(calibration_file) + try: + device.calibrate(SCOPE) + finally: + context.__exit__(None, None, None) + content = json.loads(calibration_file.read_text()) + content["calibrated_at"] = "2026-01-01T00:00:00+00:00" + calibration_file.write_text(json.dumps(content)) + context, device = make_device(calibration_file) + try: + device.on_connected() + assert device.read()["laser_delay"]["value"] == pytest.approx(SCOPE) + assert "days old" in caplog.text + finally: + context.__exit__(None, None, None) + + +def test_broken_calibration_file_leaves_the_device_uncalibrated(calibration_file, caplog): + calibration_file.parent.mkdir(parents=True) + calibration_file.write_text("{not json") + context, device = make_device(calibration_file) + try: + device.on_connected() # must not raise: the device still connects + assert "could not restore" in caplog.text + with pytest.raises(LaserDelayNotCalibratedError): + device.set(1.0) + finally: + context.__exit__(None, None, None) + + +def test_no_calibration_file_configured_writes_nothing(laser_delay, tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + laser_delay.on_connected() + laser_delay.calibrate(SCOPE) + assert laser_delay.get_calibration_info()["storage"] is None + assert not list(tmp_path.iterdir()) + + +def test_unwritable_calibration_store_refuses_the_move(tmp_path, caplog): + """Without the move marker a later restore could trust a stale phase: fail safe.""" + blocker = tmp_path / "file" + blocker.write_text("") + context, device = make_device(blocker / "cal.json") # parent is a file + try: + with pytest.raises(LaserDelayPersistenceError, match="will be lost at the next restart"): + device.calibrate(SCOPE) + assert device.get_calibration_info()["verified"] # applied anyway + log = record_puts(device) + status = device.set(1.0) + with pytest.raises(LaserDelayPersistenceError, match="move marker could not be saved"): + status.wait(timeout=10) + assert log == [] + assert device.readback.get() == pytest.approx(SCOPE) # nothing moved + assert device.motor_is_moving.get() == 0 and not device.moving + assert "could not save" in caplog.text + finally: + context.__exit__(None, None, None) + + +def test_sim_restart_restores_hardware_and_calibration(tmp_path): + path = tmp_path / "cal.json" + device = SimLaserDelay(name="laser_delay", step_sleep=0.0, sim_noise=0, calibration_file=path) + try: + device.on_connected() + device.calibrate(device.sim_scope.get()) + for target in (3.3, -7.1, 14.2): + device.set(target).wait(timeout=30) + finally: + device.destroy() + device = SimLaserDelay(name="laser_delay", step_sleep=0.0, sim_noise=0, calibration_file=path) + try: + device.on_connected() + assert device.read()["laser_delay"]["value"] == 14.2 + assert device.sim_scope.get() == pytest.approx(14.2) + device.set(-2.0).wait(timeout=30) + assert device.sim_scope.get() == pytest.approx(-2.0) + finally: + device.destroy() + + +# --------------------------------------------------------------------------------------------- # +# Safety checks (deployment audit 2026-10-08) # +# --------------------------------------------------------------------------------------------- # + + +def test_hardware_signals_refuse_direct_writes(calibrated): + """dev.laser_delay.phase_v1.set(...) from a client would bypass the ramp and the bookkeeping.""" + log = record_puts(calibrated) + for signal, value in ( + (calibrated.phase_v1, 0.5), + (calibrated.phase_v2, 7.5), + (calibrated.delay_coarse, 10), + (calibrated.delay_fine, 10), + ): + with pytest.raises(ReadOnlyError, match="written only by laser_delay"): + signal.put(value) + with pytest.raises(ReadOnlyError): + signal.set(value).wait(timeout=2) + assert log == [] + + +def test_hardware_writes_are_range_checked_even_for_the_device(calibrated): + with calibrated._hardware_writes(): + with pytest.raises(ValueError, match="outside"): + calibrated.phase_v1.put(PHASE_VOLTAGE_LIMIT + 0.01) + with pytest.raises(ValueError, match="outside"): + calibrated.delay_fine.put(201) + + +def test_direct_write_from_another_thread_during_a_move_is_refused(laser_delay): + """The permission is per thread: a client write while the move task writes is still refused.""" + laser_delay.step_sleep.put(0.02) + laser_delay.calibrate(SCOPE) + status = laser_delay.set(0.5) # crosses t = 0: a long ramp + assert wait_until(lambda: laser_delay.phase_v1._write_pv.mock_data != 0.6) + with pytest.raises(ReadOnlyError): + laser_delay.phase_v1.put(0.0) + laser_delay.stop() + with pytest.raises(DeviceStoppedError): + status.wait(timeout=5) + + +def test_beamline_minimum_step_sleep(monkeypatch): + monkeypatch.setattr(LaserDelay, "MIN_STEP_SLEEP", 0.1) # the real value, see fast_ramp + with pytest.raises(ValueError, match="at least 0.1"): + with patched_device(LaserDelay, name="laser_delay", step_sleep=0.05): + pass + with patched_device(LaserDelay, name="laser_delay") as device: + assert device.step_sleep.get() == 0.1 + with pytest.raises(ValueError, match="at least 0.1"): + device.step_sleep.set(0.05).wait(timeout=2) + device.step_sleep.set(0.15).wait(timeout=2) + assert SimLaserDelay.MIN_STEP_SLEEP == 0.0 + + +def test_busy_refusal_does_not_stop_the_running_move(laser_delay): + """BEC v4's mv ends without waiting; the next queued scan's set arrives while the ramp runs. The + refusal must not end that ramp: the device server turns an exception from set() into a status + whose failure calls stop(), so the refusal is an already failed status instead.""" + laser_delay.step_sleep.put(0.02) + laser_delay.calibrate(SCOPE) + log = record_puts(laser_delay) + first = laser_delay.set(0.5) # crosses t = 0: a long ramp + assert wait_until(lambda: len(log) >= 2 + 2 * 3) + refused = laser_delay.set(1.0) + assert refused.done and not refused.success + assert isinstance(refused.exception(), LaserDelayBusyError) + assert not refused._call_stop_on_failure # pylint: disable=protected-access + n_puts = len(log) + time.sleep(0.2) + assert len(log) > n_puts, "the running move was stopped by the refusal" + assert not first.done and laser_delay.moving + laser_delay.step_sleep.put(0.0) + first.wait(timeout=30) + assert laser_delay.readback.get() == 0.5 + + +def test_move_refused_when_the_amplitude_is_wrong(calibrated): + """ES4 IOC reboot (V1 = V2 = 0): the first ramp step would jump to vmax.""" + calibrated.phase_v1._read_pv.mock_data = 0.0 + calibrated.phase_v2._read_pv.mock_data = 0.0 + log = record_puts(calibrated) + status = calibrated.set(1.0) + with pytest.raises(LaserDelayHardwareError, match="amplitude"): + status.wait(timeout=5) + assert log == [] + with pytest.raises(LaserDelayHardwareError, match="amplitude"): + calibrated.calibrate(SCOPE) + + +def test_raising_vmax_at_runtime_does_not_jump_the_voltages(calibrated): + calibrated.vmax.set(5.0).wait(timeout=2) + log = record_puts(calibrated) + status = calibrated.set(1.0) + with pytest.raises(LaserDelayHardwareError, match="amplitude"): + status.wait(timeout=5) + assert log == [] + + +def test_readback_is_nan_while_moving(laser_delay): + laser_delay.step_sleep.put(0.02) + laser_delay.calibrate(SCOPE) + status = laser_delay.set(0.5) # crosses t = 0: about 200 steps of 0.02 s + assert wait_until(lambda: math.isnan(laser_delay.read()["laser_delay"]["value"])) + assert laser_delay.moving + status.wait(timeout=30) + assert laser_delay.read()["laser_delay"]["value"] == 0.5 + + +def test_clamped_delay_card_fails_the_move_before_the_phase_shifter(calibrated): + log = record_puts(calibrated) + original = calibrated.delay_fine.get + + def clamped(*args, **kwargs): + value = original(*args, **kwargs) + return min(value, 10) if kwargs.get("use_monitor") is False else value + + with mock.patch.object(calibrated.delay_fine, "get", side_effect=clamped): + status = calibrated.set(-0.5) # FINE above 10 + with pytest.raises(LaserDelayHardwareError, match="delay card reads"): + status.wait(timeout=5) + assert [pv for pv, _ in log] == ["X10DA-ES2-TIM:SET1-DELAY", "X10DA-ES2-TIM:SET1-FINE"] + assert math.isnan(calibrated.readback.get()) + assert calibrated.get_calibration_info()["verified"] # phase untouched: next move is fine + + +def test_clamped_phase_voltage_fails_the_move_and_refuses_the_next(calibrated): + original = calibrated.phase_v2.get + + def clamped(*args, **kwargs): + value = original(*args, **kwargs) + return value + 0.2 if kwargs.get("use_monitor") is False else value + + with mock.patch.object(calibrated.phase_v2, "get", side_effect=clamped): + status = calibrated.set(1.0) + with pytest.raises(LaserDelayHardwareError, match="phase shifter reads"): + status.wait(timeout=5) + assert not calibrated.get_calibration_info()["verified"] + with pytest.raises(LaserDelayNotCalibratedError): + calibrated.set(2.0) diff --git a/tests/tests_devices/test_laser_delay_golden.py b/tests/tests_devices/test_laser_delay_golden.py index 68132f3..1e8dac4 100644 --- a/tests/tests_devices/test_laser_delay_golden.py +++ b/tests/tests_devices/test_laser_delay_golden.py @@ -24,6 +24,7 @@ from ophyd_devices.tests.utils import patched_device from superxas_bec.devices.laser_delay import ( LaserDelay, + LaserDelayHardwareError, delay_card_setting, phase_from_voltages, phase_ramp_offsets, @@ -41,6 +42,13 @@ V2 = "X10DA-ES4:AO-01" FLOAT_TOL = 1e-12 + +@pytest.fixture(autouse=True) +def fast_ramp(monkeypatch): + """Tests ramp without sleeping; the beamline minimum is tested on its own.""" + monkeypatch.setattr(LaserDelay, "MIN_STEP_SLEEP", 0.0) + + # Two hardware states to start from (values as the IOCs would report them). STATE_A = {EVR: 2.0002, DELAY: 150, FINE: 37, V1: 0.6, V2: -0.8} STATE_B = {EVR: 1.0, DELAY: 10, FINE: 150, V1: -0.3, V2: 0.95} @@ -69,9 +77,6 @@ SCENARIOS = { ), "other_state_positive_scope": Scenario(STATE_B, 37.25, [37.25, 30.0, -3.33, 1000.0]), "other_state_wrap_short_period": Scenario(STATE_B, -14.58 + 15.46, [-990.0, 2.5, 999.99]), - "voltages_touched_between_moves": Scenario( - STATE_A, 546.04 - 546.92, [1.0, {V1: 0.0, V2: 1.0}, 2.0, {V1: -0.7, V2: -0.7}, -3.0] - ), } @@ -186,6 +191,7 @@ def set_pv_values(device: LaserDelay, values: dict) -> None: def run_device(scenario: Scenario, **device_kwargs) -> dict: """Run a scenario through the device (default configuration unless ``device_kwargs``).""" + device_kwargs.setdefault("fine_rollover", False) # the script writes FINE 200 with patched_device(LaserDelay, name="laser_delay", step_sleep=0.0, **device_kwargs) as device: set_pv_values(device, scenario.initial) log = record_puts(device) @@ -429,3 +435,23 @@ def test_phase_ramp_matches_script_for_many_moves(monkeypatch, tmp_path): assert len(actual) == len(expected) for exp, act in zip(expected, actual): assert_same_value(exp, act, f"phase ramp {relative}") + + +def test_device_refuses_where_the_script_follows_touched_voltages(monkeypatch, tmp_path): + """Voltages turned by hand between moves: the script ramps from the touched phase and ends + off by that amount; the device refuses the move and writes nothing (calibrate again).""" + scenario = Scenario(STATE_A, 546.04 - 546.92, [1.0, {V1: 0.0, V2: 1.0}, 2.0]) + expected = run_reference(scenario, monkeypatch, tmp_path) + assert len(expected["moves"]) == 2 # the script moves twice + with patched_device( + LaserDelay, name="laser_delay", step_sleep=0.0, fine_rollover=False + ) as device: + set_pv_values(device, scenario.initial) + device.calibrate(scenario.scope) + device.set(1.0).wait(timeout=30) + set_pv_values(device, {V1: 0.0, V2: 1.0}) + log = record_puts(device) + status = device.set(2.0) + with pytest.raises(LaserDelayHardwareError): + status.wait(timeout=30) + assert log == []