feat(devices): keep the laser delay calibration across restarts and verify it before moving

This commit is contained in:
wyzula_j committed 2026-10-12 11:36:59 +02:00
1 parent 4630ef1c6b
commit 70c08e9c11
5 files changed
+1610 -212

No files matched your search

@@ -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("<path to superxas_bec>/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
@@ -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
File diff suppressed because it is too large. Load diff
+629 -35
View File
@@ -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)
+29 -3
View File
@@ -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 == []