Merge branch 'main' into fixes/sastt_beamtime
CI for csaxs_bec / test (push) Successful in 4m19s
CI for csaxs_bec / test (pull_request) Successful in 4m21s

This commit is contained in:
holler committed 2026-11-23 16:58:21 +01:00
commit 7249f104dc
28 files changed
+1783 -50

No files matched your search

@@ -400,6 +400,12 @@ class LamNI(
self.device_manager = client.device_manager
self.init = LaMNIInitStages(client)
# operating settings of the real-time loop (web HMI loop settings on mpc-lamni, staff only;
# lamni_realtime_system.py): lamni.rt_settings.show() / .standard() / .large_steps() / .help()
from csaxs_bec.bec_ipython_client.plugins.LamNI.lamni_realtime_system import LamniRealtimeSystem
self.rt_settings = LamniRealtimeSystem(device_manager=self.device_manager)
# Correction state: corr_pos_x/y/angle (+ _2 iteration) are now
# global-var-backed properties defined in LamNIAlignmentMixin, so
# they are NOT initialized as plain lists here -- doing so would
@@ -2426,7 +2432,15 @@ class LamNI(
# equivalent addition -- no flat-field/empty-frame step here
# (unlike Flomni's collect_empty_frames()), since LamNI has no
# way to retract the sample out of the beam.
self._tomo_scan_at_angle(0, 1)
#
# Skipped for tomo_type 4 (angle file): the file may override
# the scan parameters per angle, so a 0-degree shot with the
# normal tomo parameters could end up as e.g. a low-resolution
# projection inside a high-resolution tomogram. The angle file
# is the sole source of projections there -- put 0 in the file
# if one is wanted. Mirrors Flomni.
if self.tomo_type != 4:
self._tomo_scan_at_angle(0, 1)
try:
with scans.dataset_id_on_hold:
@@ -0,0 +1,89 @@
"""lamni.rt_settings: the operating settings of the LaMNI real-time loop.
BEAMLINE SCIENTISTS / LOCAL CONTACT ONLY - not for users. These settings change how the detector trigger and the
sample-stage moves (target shaper, ramp rate) work; a wrong combination can spoil a beamtime's data. The rules refuse
combinations that do not work, but not ones that are only unsuitable for an experiment.
The settings, the parameters they map onto, the profiles and the rules live in the LamNI instrument repository
(LAMNIcontrol/loopsettings/lamni.json) and are applied by the web HMI on the loop machine mpc-lamni (RT-system
webhmi/loopsettings.py). This client only talks to its REST API (/api/settings); it holds no logic of its own, so the
web page (tab "Loop settings") and BEC always behave the same way. Same commands as flomni.rt_settings / omny.rt_settings
(2026-11-19).
lamni.rt_settings.show() all settings, rules, scan state
lamni.rt_settings.set(trigger_tolerance_nm=5) change (refused if a rule objects)
lamni.rt_settings.check(slew_rate_um_s=5000) dry run
lamni.rt_settings.profiles() the profiles: standard (default) / large_steps
lamni.rt_settings.standard() profile standard: max error ~10 nm, 0.2-2 um steps
lamni.rt_settings.large_steps() profile large_steps: 3-8 um steps, ~50 nm, twice as fast
lamni.rt_settings.save_as_default() write the live values into the .xmp files
Changes are live only: the next start of the control loop uses the .xmp files again (profile standard).
Connection: through the BEC device lamni_loop_settings (RPC; the API token is in its device config, ptycho_lamni.yaml)
when it exists and is enabled, else directly to the web HMI (devices/omny/webhmi_client.py: URL http://<rtx host>:8080
with port-80 fallback, token from token_file / ~/.flomni_webhmi_token or FLOMNI_WEBHMI_TOKEN_FILE).
"""
from csaxs_bec.bec_ipython_client.plugins.flomni.flomni_realtime_system import ( # noqa: F401
FlomniRealtimeSystem,
RealtimeSystemError,
)
_MODULE_DOC = __doc__
STAFF_ONLY = ("lamni.rt_settings: beamline scientists / local contact only - not for users "
"(LaMNI loop settings: LamNI LAMNIcontrol/tuning_guide.md, section 2b).")
NO_TRACKER = "LaMNI has no laser tracker: the tracking settings exist on flOMNI / OMNY only"
class LamniRealtimeSystem(FlomniRealtimeSystem):
"""lamni.rt_settings: the flOMNI client with the LaMNI device and texts. Requests go through the BEC device
lamni_loop_settings (RPC api_get / api_post; the token is in its device config) when it exists and is enabled;
otherwise directly to the web HMI of the rtx host (mpc-lamni)."""
DEVICE = "lamni_loop_settings"
STAFF_ONLY = STAFF_ONLY
DOC = _MODULE_DOC
HELP_EXAMPLE = "slew_rate_um_s"
def trigger_set_tolerance_nm(self, tolerance_nm: float):
"""|sample position - target| x and y (interferometer) within this (nm) for the hold time (averaged over
trigger_filter_ms); 5 standard, 25 large_steps. 0 = the former criterion (on-target flags of PID_x / PID_y)."""
return self.set(trigger_tolerance_nm=tolerance_nm)
def trigger_set_soft(self, enable: bool, exposure_ms: float = None):
"""Soft trigger (working without detector): True = no hardware trigger leaves the loop, every trigger starts
an emulated exposure of exposure_ms (default: unchanged); False = hardware trigger. Never saved as default (the
loop starts with the hardware trigger). Only between scans."""
return super().trigger_set_soft(enable, exposure_ms)
def standard(self) -> dict:
"""Profile standard (the default): trigger 5 nm / 2 ms average / 5 ms hold, full shaper, 2000 um/s; 0.2-2 um
steps, max error during the exposure about 5-7 nm."""
return self.apply_profile("standard")
def large_steps(self) -> dict:
"""Profile large_steps: trigger 25 nm / 2 ms average / 2 ms hold, full shaper, 5000 um/s; 3-8 um steps about
twice as fast as standard, max error during the exposure about 20-30 nm (below 50 nm)."""
return self.apply_profile("large_steps")
# LaMNI has no laser tracker
def tracking_targets(self):
raise RealtimeSystemError(NO_TRACKER)
def tracking_show(self):
raise RealtimeSystemError(NO_TRACKER)
def tracking_set_target_y(self, val: float):
raise RealtimeSystemError(NO_TRACKER)
def tracking_set_target_z(self, val: float):
raise RealtimeSystemError(NO_TRACKER)
def tracking_set_interferometer_threshold(self, val: float):
raise RealtimeSystemError(NO_TRACKER)
def tracking_set_psd_threshold_low(self, val: float):
raise RealtimeSystemError(NO_TRACKER)
@@ -187,8 +187,7 @@ class TomoAngleFileMixin:
def _init_angle_file_progress(self, file_angles: AngleFileResult, projection_number) -> None:
"""Fill the progress fields that are already known from the file, so the
GUI shows the real tomo type/total (and sub-tomogram 1) during the
preparation steps and the 0-deg reference shot that precede the loop,
instead of the blank reset defaults (tomo type 0, projection 0)."""
preparation steps (e.g. empty frames) that precede the loop, instead of the blank reset defaults (tomo type 0, projection 0)."""
self.progress["tomo_type"] = "Angles from file"
self.progress["total_projections"] = (
len(file_angles.angles) if file_angles.is_complete else 0
@@ -197,9 +196,12 @@ class TomoAngleFileMixin:
self.progress["subtomo"] = 1
def _run_angle_file_loop(self, file_angles: AngleFileResult, projection_number) -> None:
"""Acquire the angles of tomo_type 4 in file order (no extra 0-deg
damage-estimation shots: sub-tomogram numbers in a user file are just
labels, put 0-deg lines in the file instead). Waits for lines to be
"""Acquire the angles of tomo_type 4 in file order. The file is the
sole source of projections: no initial 0-deg shot at the start of a
new tomogram (it would use the normal tomo parameters, not the
file's per-angle ones) and no extra 0-deg damage-estimation shots
(sub-tomogram numbers in a user file are just labels) -- put 0-deg
lines in the file instead. Waits for lines to be
appended while the file has no 'END' marker."""
error = self._TOMO_PARAMS_ERROR
self.progress["tomo_type"] = "Angles from file"
@@ -2827,7 +2827,16 @@ class Flomni(
# projection), included in reconstruction like any other
# projection -- not a flat-field/reference-only frame like
# collect_empty_frames() above. Logged under subtomo_number=1.
self._tomo_scan_at_angle(0, 1)
#
# Skipped for tomo_type 4 (angle file): the file may override
# the scan parameters (step, exp_time, frames_per_trigger, ...)
# per angle, so a 0-degree shot taken with the normal tomo
# parameters could be e.g. a low-resolution projection inside a
# high-resolution tomogram, which breaks loading the projections
# for further processing. The angle file is the sole source of
# projections there -- put 0 in the file if one is wanted.
if self.tomo_type != 4:
self._tomo_scan_at_angle(0, 1)
try:
with scans.dataset_id_on_hold:
@@ -27,6 +27,8 @@ from csaxs_bec.devices.omny.webhmi_client import WebHmiClient
from csaxs_bec.devices.omny.webhmi_client import WebHmiError as RealtimeSystemError # name kept for BEC users
_MODULE_DOC = __doc__ # help() prints it (a class body's __doc__ would be the class docstring)
STAFF_ONLY = ("flomni.rt_settings: beamline scientists / local contact only - not for users "
"(plugins/flomni/docs/local_contact_only-realtime_system.md).")
@@ -45,6 +47,10 @@ class FlomniRealtimeSystem(WebHmiClient):
devices/omny/webhmi_client.py; token from token_file / ~/.flomni_webhmi_token)."""
DEVICE = "flomni_loop_settings"
# texts per instrument (OMNY: plugins/omny/omny_realtime_system.py subclasses this class, 2026-11-17)
STAFF_ONLY = STAFF_ONLY
DOC = _MODULE_DOC
HELP_EXAMPLE = "move_beyond_um_x"
def __init__(self, url=None, token_file=None, device_manager=None, timeout=5.0, token=None):
super().__init__(url=url, token=token, token_file=token_file, device_manager=device_manager, timeout=timeout)
@@ -92,7 +98,7 @@ class FlomniRealtimeSystem(WebHmiClient):
wanted = (group,) if isinstance(group, str) else tuple(group or ())
groups = {g["name"]: g for g in snap["groups"]}
sc = snap.get("scan") or {}
print(STAFF_ONLY)
print(self.STAFF_ONLY)
print(f"Loop settings {snap.get('instrument', '')} ({self.route}) - "
+ (f"scan running (mode {_fmt(sc.get('mode'))})" if sc.get("active") else "no scan"))
for gname, g in groups.items():
@@ -264,18 +270,18 @@ class FlomniRealtimeSystem(WebHmiClient):
does, unit, range, the loop parameters it sets, live and saved value), from the definition on the loop
machine (the same text as the tooltips of the web HMI tab)."""
if name is None:
print(__doc__.split("\n\nConnection:")[0])
print(self.DOC.split("\n\nConnection:")[0])
print("\nShortcuts: trigger_show(), trigger_set_tolerance_nm(v), trigger_set_hold_ms(v),"
" trigger_set_after_move(True/False), trigger_set_soft(True/False, exposure_ms), tracking_targets(), tracking_show(), tracking_set_target_y(v),"
" tracking_set_target_z(v), tracking_set_interferometer_threshold(v), tracking_set_psd_threshold_low(v);"
" profiles(), unsaved(), get(name)")
print('Explanations: help("all") or help("<setting>"), e.g. help("move_beyond_um_x")')
print(f'Explanations: help("all") or help("<setting>"), e.g. help("{self.HELP_EXAMPLE}")')
return
snap = self.read()
settings = {s["name"]: s for s in snap["settings"]}
groups = {g["name"]: g for g in snap["groups"]}
if name == "all":
print(STAFF_ONLY)
print(self.STAFF_ONLY)
for gname, g in groups.items():
rows = [s for s in snap["settings"] if s["group"] == gname]
if not rows:
@@ -291,7 +297,7 @@ class FlomniRealtimeSystem(WebHmiClient):
if s is None:
raise RealtimeSystemError(f"unknown setting '{name}'; help('all') lists them")
g = groups.get(s["group"], {})
print(STAFF_ONLY)
print(self.STAFF_ONLY)
print(f"{s['name']} - {s.get('title', '')} (group {g.get('title', s['group'])}"
+ (", only between scans)" if g.get("interlock") else ")"))
if s.get("help"):
@@ -0,0 +1,184 @@
"""
Default beamline states for the tomography sessions (LamNI, OMNY, flOMNI).
The scan interlock of these sessions (`bec.builtin_actors.scan_interlock`) watches the beamline
states. set_default_beamline_states() makes the defined states exactly DEFAULT_BEAMLINE_STATES:
if the states in BEC differ, all of them are deleted and the defaults are added again.
Beamline states are global (stored in Redis), not per client. If they already match, nothing
is changed, so starting another client, e.g. during a running tomography scan, does not
touch the states the interlock is watching.
"""
from __future__ import annotations
import time
from bec_lib import bec_logger
from bec_lib.bl_states import DeviceWithinLimitsStateConfig
logger = bec_logger.logger
DEFAULT_BEAMLINE_STATES = [
DeviceWithinLimitsStateConfig(
name="curr_device_within_limits_state",
device="curr",
signal="curr",
low_limit=380.0,
tolerance=0.1,
),
DeviceWithinLimitsStateConfig(
name="idgap_device_within_limits_state",
device="idgap",
signal="idgap",
high_limit=8.0,
tolerance=0.1,
),
DeviceWithinLimitsStateConfig(
name="shutter_device_within_limits_state",
device="shutter",
signal="shutter",
low_limit=0.5,
tolerance=0.1,
),
DeviceWithinLimitsStateConfig(
name="ofb_device_within_limits_state",
device="ofb",
signal="ofb",
low_limit=0.5,
tolerance=0.1,
),
DeviceWithinLimitsStateConfig(
name="shutter_es_device_within_limits_state",
device="shutter_es",
signal="shutter_es",
low_limit=0.5,
tolerance=0.1,
),
]
# Extra states per session (added to the defaults). The scan interlock watches them only in their
# session: set_default_beamline_states() adds them to the interlock there and removes them from it
# in the other sessions, so a flOMNI/LamNI session is never locked by a state that does not exist.
SESSION_BEAMLINE_STATES = {
# OMNY vacuum (csaxs_bec.devices.omny.omny_vcs, Mirko 2026-11-17): measurement_ok = 1 when the
# vacuum PLC is alive, EXPVG1 + EXPVG2 OPEN and WI2VG1 CLOSED; without it the measurement stops.
"omny": [
DeviceWithinLimitsStateConfig(
name="omny_vacuum",
device="omny_vcs",
signal="omny_vcs_measurement_ok",
low_limit=0.5,
high_limit=1.5,
tolerance=0.1,
),
],
}
SESSION_STATE_NAMES = {state.name for states in SESSION_BEAMLINE_STATES.values() for state in states}
def beamline_states_for_session(session: str | None, devices=None) -> list:
"""DEFAULT_BEAMLINE_STATES + the session's extra states (only those whose device is loaded,
when `devices` is given)."""
extra = SESSION_BEAMLINE_STATES.get((session or "").lower(), [])
if devices is not None:
skipped = [state.name for state in extra if state.device not in devices]
if skipped:
print(f"Beamline states {', '.join(skipped)} skipped: their device is not loaded.")
extra = [state for state in extra if state.device in devices]
return list(DEFAULT_BEAMLINE_STATES) + extra
def _sync_interlock(bec, states) -> None:
"""Session states in the scan interlock: watched (required "valid") when defined, removed
from the watch list when not. The default states' interlock entries are not touched."""
try:
actors = getattr(bec, "builtin_actors", None)
interlock = getattr(actors, "scan_interlock", None) if actors is not None else None
if interlock is None:
return
watched = interlock.states_watched or {}
active = {state.name for state in states}
for name in sorted(SESSION_STATE_NAMES):
if name in active and name not in watched:
interlock.add_state_to_interlock(name, "valid")
logger.info(f"Beamline state {name} added to the scan interlock.")
elif name not in active and name in watched:
interlock.remove_state_from_interlock(name)
logger.info(f"Beamline state {name} removed from the scan interlock.")
except Exception as exc: # pylint: disable=broad-except
logger.warning(f"Scan interlock not updated: {exc}")
def _definition(state) -> tuple:
return (state.state_type, tuple(sorted(state.model_dump().items(), key=lambda kv: kv[0])))
def set_default_beamline_states(bec, states=None, ready_timeout: float = 5.0, session: str | None = None) -> bool:
"""
Make the beamline states in BEC exactly `states` (default: DEFAULT_BEAMLINE_STATES plus the
session's extra states, SESSION_BEAMLINE_STATES), then keep the session states' scan interlock
entries in step (_sync_interlock).
Never raises: problems are logged and printed, so the client startup always continues.
Returns:
True if the states match the defaults afterwards (changed or already correct).
"""
if states is None:
devices = getattr(getattr(bec, "device_manager", None), "devices", None)
states = beamline_states_for_session(session, devices)
ok = _apply_states(bec, states, ready_timeout)
if ok:
_sync_interlock(bec, states)
return ok
def _apply_states(bec, states, ready_timeout: float) -> bool:
try:
manager = getattr(bec, "beamline_states", None)
if manager is None:
logger.warning("Beamline states are not available in this BEC client.")
return False
deadline = time.monotonic() + ready_timeout
while not manager.ready and time.monotonic() < deadline:
time.sleep(0.05)
if not manager.ready:
logger.warning("Beamline states were not loaded from Redis; defaults not applied.")
return False
# pylint: disable=protected-access
current = {_definition(state) for state in manager._states.values()}
if current == {_definition(state) for state in states}:
logger.info("Beamline states already match the defaults.")
return True
devices = bec.device_manager.devices
missing = [state.name for state in states if state.device not in devices]
if missing:
# do not clear the existing states if the defaults cannot all be added
print(
"Beamline states not changed: the devices of"
f" {', '.join(missing)} are not loaded in this configuration."
)
return False
for name in list(manager._states):
manager.delete(name)
failed = []
for state in states:
try:
manager.add(state)
except Exception as exc: # pylint: disable=broad-except
failed.append(f"{state.name}: {exc}")
if failed:
print("Failed to add beamline states:\n " + "\n ".join(failed))
return False
logger.success(f"Beamline states set to the {len(states)} defaults.")
return True
except Exception as exc: # pylint: disable=broad-except
logger.warning(f"Setting the default beamline states failed: {exc}")
print(f"Setting the default beamline states failed: {exc}")
return False
@@ -144,4 +144,10 @@ def _check_account_mismatch():
if _args.session.lower() == "lamni" or _args.session.lower() == "flomni" or _args.session.lower() == "omny":
_check_account_mismatch()
_check_account_mismatch()
# DEFAULT BEAMLINE STATES (watched by the scan interlock of the tomography scans),
# plus the session's own states (OMNY: omny_vacuum)
from csaxs_bec.bec_ipython_client.startup.beamline_states import set_default_beamline_states
set_default_beamline_states(bec, session=_args.session.lower())
@@ -1253,7 +1253,9 @@ class OMNY_XRayEye(BECWidget, QWidget):
self.live_preview_toggle.blockSignals(False)
return
self.image.disconnect_monitor(CAMERA[0], self._live_view_signal)
# An empty device disconnects the current monitor. This is the public way that
# every bec_widgets version has; Image.disconnect_monitor is gone with the DataAPI.
self.image.image(device="", signal="")
self.live_preview_toggle.checked = enabled
self.live_preview_toggle.blockSignals(False)
@@ -1263,7 +1265,7 @@ class OMNY_XRayEye(BECWidget, QWidget):
channel self.image is currently displaying -- see the permanent
subscription set up in __init__ and the note in
set_live_view_signal() about why this is needed."""
data = self.image._get_payload_data(msg) # pylint: disable=protected-access
data = msg.get("data") # the payload of a device_preview message
if data is not None:
self._last_smear_composite = data
@@ -1278,8 +1280,8 @@ class OMNY_XRayEye(BECWidget, QWidget):
changes here unless a caller explicitly requests it.
"""
if signal != self._live_view_signal:
self.image.disconnect_monitor(CAMERA[0], self._live_view_signal)
self._live_view_signal = signal
# image() disconnects the monitor it has before it connects the new one.
self.image.image(device=CAMERA[0], signal=signal)
if hasattr(self.image, "_autorange_on_next_update"):
self.image._autorange_on_next_update = False
@@ -428,3 +428,26 @@ omny_xray_gui:
readoutPriority: on_request
deviceTags:
- ptycho_lamni
# ############################################################
# ############ LaMNI real-time loop settings ##################
# ############################################################
# The loop settings (detector trigger, soft trigger, target shaper, ramp rate; LamNI LAMNIcontrol/loopsettings, profiles
# standard / large_steps) stored with every scan: read from the web HMI on the loop machine at the start of each scan
# (baseline). Web HMI down: available = 0, the scan continues. The user commands lamni.rt_settings go through this
# device (RPC), so the token is needed only here.
# token: the web HMI API token (~/loop-data/webhmi/api_token on mpc-lamni). Not filled in yet (2026-11-19): enter it
# here as for flOMNI / OMNY, or put it into token_file on the machine of the device server.
lamni_loop_settings:
description: LaMNI real-time loop settings (web HMI loop settings, snapshot at scan start)
deviceClass: csaxs_bec.devices.omny.lamni_loop_settings.LamniLoopSettings
deviceConfig:
host: mpc-lamni.psi.ch
token: "FkoqBdwcjS6OIhG2oLrx_WL2xjOi7lPGmUHNvlDx6Sw"
token_file: ~/.lamni_webhmi_token
timeout: 2.0
enabled: true
onFailure: buffer
readOnly: true
readoutPriority: baseline
deviceTags:
- ptycho_lamni
@@ -0,0 +1,165 @@
"""lamni_loop_settings: the operating settings of the LaMNI real-time loop as a baseline device (2026-11-19, Mirko).
Same as omny_loop_settings / flomni_loop_settings (the code is a copy of devices/omny/omny_loop_settings.py with the
LaMNI setting list): read at the start of every scan (readoutPriority: baseline; the LaMNI Fermat scan calls
read_baseline_devices in prepare_scan), so each scan file holds the loop settings it ran with: detector trigger
(tolerance, hold, filter, minimum delay, after a move, soft trigger), target shaper scale and ramp rate (definition:
LamNI LAMNIcontrol/loopsettings/lamni.json, profiles standard / large_steps; served by the web HMI on mpc-lamni,
GET /api/settings).
Signals: one per setting (float, NaN when not available; names = the setting names), and
available 1 = read from the web HMI, 0 = not available (the scan continues; message says why)
message "" or the reason it is not available
unsaved number of settings whose live value differs from the .xmp (not saved as default)
inconsistent number of settings whose parameters disagree
rules_violated number of violated error rules
definition path and sha1 of the definition file on the loop machine
snapshot_json JSON: every setting (value, saved, unsaved, consistent, unit), the violated rules, the
scan state, the definition path and sha1
deviceConfig: token (the API token itself, ~/loop-data/webhmi/api_token on mpc-lamni), else token_file, optional url /
host (default: the host of the rtx device config) / timeout (default 2 s for the scan snapshot).
lamni.rt_settings (the user commands, plugins/LamNI/lamni_realtime_system.py) calls api_get / api_post of this device
by RPC, so the token is needed only here.
"""
import json
import math
import time
from ophyd import Component as Cpt
from ophyd import Device, Kind, Signal
from csaxs_bec.devices.omny.webhmi_client import WebHmiClient, WebHmiError
# the settings of lamni.json (2026-11-19); a setting added to the definition later is in snapshot_json only until it
# is added here
SETTINGS = (
"trigger_tolerance_nm", "trigger_hold_ms", "trigger_filter_ms", "trigger_min_delay_ms", "trigger_on_move",
"trigger_soft", "soft_exposure_ms", "soft_latency_ms",
"target_shaper_scale", "slew_rate_um_s",
)
RETRY_AFTER_FAILURE_S = 60.0 # web HMI not reachable: no new attempt for this long (a tomogram does not wait each time)
class LamniLoopSettings(Device):
USER_ACCESS = ["show", "snapshot", "api_get", "api_post"]
available = Cpt(Signal, value=0, kind=Kind.normal)
message = Cpt(Signal, value="", kind=Kind.normal)
unsaved = Cpt(Signal, value=-1, kind=Kind.normal)
inconsistent = Cpt(Signal, value=-1, kind=Kind.normal)
rules_violated = Cpt(Signal, value=-1, kind=Kind.normal)
definition = Cpt(Signal, value="", kind=Kind.normal)
snapshot_json = Cpt(Signal, value="", kind=Kind.normal)
# one signal per setting
locals().update({_n: Cpt(Signal, value=math.nan, kind=Kind.normal) for _n in SETTINGS})
def __init__(self, prefix="", *, name, token=None, token_file=None, url=None, host=None, timeout=2.0,
device_manager=None, **kwargs):
super().__init__(prefix, name=name, **kwargs)
self._client = WebHmiClient(url=url, token=token, token_file=token_file, host=host,
device_manager=device_manager, timeout=timeout, client_name="BEC baseline")
# requests of lamni.rt_settings (RPC from the client, below): longer timeout, no back-off
self._api = WebHmiClient(url=url, token=token, token_file=token_file, host=host,
device_manager=device_manager, timeout=max(timeout, 10.0), client_name="BEC")
self._failed_at = None
self._last = None
def _unavailable(self, reason):
self.available.put(0)
self.message.put(str(reason))
for n in ("unsaved", "inconsistent", "rules_violated"):
getattr(self, n).put(-1)
self.definition.put("")
self.snapshot_json.put("")
for n in SETTINGS:
getattr(self, n).put(math.nan)
def update(self):
"""Read the settings from the web HMI into the signals. Never raises: not available -> available 0."""
now = time.time()
if self._failed_at is not None and now - self._failed_at < RETRY_AFTER_FAILURE_S:
return # keep the 'not available' values of the last failure
try:
snap = self._client.settings()
except WebHmiError as exc:
self._failed_at = now
self._unavailable(f"{exc} (next attempt after {RETRY_AFTER_FAILURE_S:.0f} s)")
return
except Exception as exc: # noqa: BLE001 (a broken answer must not stop a scan)
self._failed_at = now
self._unavailable(f"unexpected answer from the web HMI: {exc}")
return
self._failed_at = None
self._last = snap
values = {s["name"]: s for s in snap.get("settings", [])}
for n in SETTINGS:
v = values.get(n, {}).get("value")
getattr(self, n).put(float(v) if isinstance(v, (int, float)) else math.nan) # bool is an int too
self.unsaved.put(sum(1 for s in values.values() if s.get("unsaved")))
self.inconsistent.put(sum(1 for s in values.values() if not s.get("consistent", True)))
self.rules_violated.put(sum(1 for r in snap.get("rules", []) if not r.get("ok") and r.get("severity") == "error"))
self.definition.put(f"{snap.get('definition', '')} sha1 {snap.get('definition_sha1', '?')}")
missing = [n for n in values if n not in SETTINGS]
self.message.put(f"settings not stored as own signals (in snapshot_json): {', '.join(missing)}" if missing else "")
# compact: values and flags only (help texts and parameter mappings are in the definition, see its sha1)
compact = {
"instrument": snap.get("instrument"), "definition": snap.get("definition"),
"definition_sha1": snap.get("definition_sha1"), "scan": snap.get("scan"),
"settings": {n: {"value": s.get("value"), "saved": s.get("saved"), "unsaved": s.get("unsaved"),
"consistent": s.get("consistent"), "unit": s.get("unit", "")}
for n, s in values.items()},
"rules_violated": [{"name": r.get("name"), "severity": r.get("severity"), "message": r.get("message")}
for r in snap.get("rules", []) if not r.get("ok")],
}
self.snapshot_json.put(json.dumps(compact, separators=(",", ":")))
self.available.put(1)
def read(self):
self.update()
return super().read()
# ── RPC for lamni.rt_settings: the user commands go through this device, so the API token is needed only
# in its device config (device server), not on the client. Not called set / put: the device server treats
# those names as ophyd writes (refused on a readOnly device).
_API_PATHS = ("/api/settings", "/api/status")
def _check_path(self, path):
if not any(path == p or path.startswith(p + "/") for p in self._API_PATHS):
raise WebHmiError(f"path {path!r} not allowed (only /api/settings*, /api/status)")
def api_get(self, path: str = "/api/settings") -> dict:
"""GET a web HMI loop-settings endpoint; returns its JSON. Errors raise (passed to the client)."""
self._check_path(path)
return self._api._request(path)
def api_post(self, path: str, body: dict = None) -> dict:
"""POST to a web HMI loop-settings endpoint (plan / apply / save); returns its JSON."""
self._check_path(path)
return self._api._request(path, body or {})
def snapshot(self) -> dict:
"""Read now and return {setting: value} (empty when not available)."""
self._failed_at = None # an explicit request always tries
self.update()
if not self.available.get():
return {}
return {n: getattr(self, n).get() for n in SETTINGS}
def show(self):
"""Print the settings as they would be stored with a scan now."""
snap = self.snapshot()
if not snap:
print(f"loop settings not available: {self.message.get()}")
return
for n, v in snap.items():
print(f" {n:30s} {v:g}")
print(f"unsaved {self.unsaved.get()}, inconsistent {self.inconsistent.get()}, "
f"rules violated {self.rules_violated.get()}; {self.definition.get()}")
if self.message.get():
print(self.message.get())
+72 -3
View File
@@ -15,6 +15,7 @@ from prettytable import PrettyTable
from csaxs_bec.devices.omny.rt.rt_ophyd import (
format_scan_timing,
RtCommunicationError,
RtDataMonitor,
RtError,
RtReadbackSignal,
RtSetpointSignal,
@@ -485,6 +486,7 @@ class RtFlomniController(Controller):
raise RtError("Cannot start scan because no target positions are planned.")
# hier exception
# start a point-by-point scan (for cont scan in flomni it would be "sa")
logger.info("RtFlomniController: Starting scan.")
self.socket_put_and_receive("sd")
@retry_once
@@ -774,7 +776,7 @@ class RtFlomniMotor(Device, PositionerBase):
class RtFlomniFlyer(Device):
USER_ACCESS = ["controller"]
USER_ACCESS = ["controller", "data_timeout", "scan_timeout", "fetch_diagnostics"]
data = Cpt(
AsyncMultiSignal,
name="data",
@@ -811,9 +813,13 @@ class RtFlomniFlyer(Device):
port=2222,
socket_cls=SocketIO,
device_manager=None,
data_timeout: float | None = 5.0,
# 300 s: top-up refills hold the RT scan on purpose (Mirko 2026-11-22)
scan_timeout: float | None = 300.0,
**kwargs,
):
super().__init__(prefix=prefix, name=name, parent=parent, **kwargs)
self._data_monitor = RtDataMonitor(data_timeout=data_timeout, scan_timeout=scan_timeout)
self.shutdown_event = threading.Event()
self.controller = RtFlomniController(
socket_cls=socket_cls, socket_host=host, socket_port=port, device_manager=device_manager
@@ -829,6 +835,53 @@ class RtFlomniFlyer(Device):
self.scan_done_event = threading.Event()
self.scan_done_event.set()
@property
def data_timeout(self) -> float | None:
"""Seconds without progress before logging a warning (default: 5).
Set to None to suppress the warning while leaving scan_timeout independent.
"""
return self._data_monitor.data_timeout
@data_timeout.setter
def data_timeout(self, value: float | None) -> None:
self._data_monitor.data_timeout = value
@property
def scan_timeout(self) -> float | None:
"""Seconds without progress before failing the scan (default: 300).
Progress means an advancing controller position until the first sample,
then receipt of new samples. Set to None to disable timeout failures.
Readout can then wait until progress resumes, the controller finishes,
or the scan is stopped.
"""
return self._data_monitor.scan_timeout
@scan_timeout.setter
def scan_timeout(self, value: float | None) -> None:
self._data_monitor.scan_timeout = value
def fetch_diagnostics(self) -> dict:
"""Return scan status, feedback state, and recent controller commands."""
diagnostics = {}
try:
mode, planned, current = self.controller.get_scan_status()
diagnostics["scan_status"] = {
"mode": mode,
"planned_positions": planned,
"current_position": current,
}
except Exception as exc:
diagnostics["scan_status_error"] = f"{type(exc).__name__}: {exc}"
try:
diagnostics["feedback_running"] = self.controller.feedback_is_running()
except Exception as exc:
diagnostics["feedback_error"] = f"{type(exc).__name__}: {exc}"
with self.controller._lock:
diagnostics["command_history"] = list(self.controller.command_history)
return diagnostics
def read_positions_from_sampler(self, status: DeviceStatus):
"""
Read the positions from the sampler and update the data signal.
@@ -864,6 +917,18 @@ class RtFlomniFlyer(Device):
read_counter = read_counter + 1
signals = self._get_signals_from_table(return_table)
self.data.set(signals)
self._data_monitor.sample_received()
if mode > 0 and not self.shutdown_event.is_set():
exception = self._data_monitor.check(
self.name,
mode=mode,
planned_positions=number_of_positions_planned,
position=current_position_in_scan,
)
if exception is not None:
status.set_exception(exception)
return
self._t_scan_end = time.monotonic() # scan finished in the RT loop (statistics)
@@ -958,6 +1023,7 @@ class RtFlomniFlyer(Device):
self.scan_done_event.clear()
while not self.controller._min_scan_buffer_reached and not self.shutdown_event.wait(0.001):
...
self._data_monitor.reset()
self.controller.start_scan()
self._t_kickoff = time.monotonic()
self._t_scan_end = None
@@ -981,7 +1047,10 @@ class RtFlomniFlyer(Device):
def stop(self, *, success=False):
self.shutdown_event.set()
self.scan_done_event.set()
if self.readout_thread is not None:
if (
self.readout_thread is not None
and self.readout_thread is not threading.current_thread()
):
self.readout_thread.join()
return super().stop(success=success)
@@ -991,4 +1060,4 @@ if __name__ == "__main__":
socket_cls=SocketIO, socket_host="mpc-flomni.psi.ch", socket_port=2222, device_manager=None
)
rtcontroller.on()
rtcontroller.laser_tracker_on()
rtcontroller.laser_tracker_on()
+89 -5
View File
@@ -13,7 +13,12 @@ from ophyd_devices.utils.controller import Controller, retry_once, threadlocked
from ophyd_devices.utils.socket import SocketIO, SocketSignal, raise_if_disconnected
from prettytable import PrettyTable
from csaxs_bec.devices.omny.rt.rt_ophyd import RtCommunicationError, RtError, format_scan_timing
from csaxs_bec.devices.omny.rt.rt_ophyd import (
RtCommunicationError,
RtDataMonitor,
RtError,
format_scan_timing,
)
logger = bec_logger.logger
@@ -217,6 +222,7 @@ class RtLamniController(Controller):
raise RtError("Cannot start scan because no target positions are planned.")
# hier exception
# start a point-by-point scan (for cont scan in flomni it would be "sa")
logger.info("RtLamniController: Starting scan.")
self.socket_put_and_receive("sd")
def feedback_is_running(self) -> bool:
@@ -361,8 +367,19 @@ class RtLamniController(Controller):
raise RuntimeError("lsamy center is not defined")
lsamx_center = lsamx_user_params.get("center")
lsamy_center = lsamy_user_params.get("center")
self.device_manager.devices.lsamx.obj.move(lsamx_center, wait=True)
self.device_manager.devices.lsamy.obj.move(lsamy_center, wait=True)
# lsamx and lsamy move at the same time (was one after the other; Mirko 2026-11-19).
# The same parallel move is used by umv(dev.lsamx, ..., dev.lsamy, ...) in x_ray_eye_align.
lsamx = self.device_manager.devices.lsamx.obj
lsamy = self.device_manager.devices.lsamy.obj
status_x = lsamx.move(lsamx_center, wait=False)
status_y = lsamy.move(lsamy_center, wait=False)
try:
status_x.wait()
status_y.wait()
except KeyboardInterrupt:
lsamx.stop()
lsamy.stop()
raise
self.socket_put("J1")
_waitforfeedbackctr = 0
@@ -694,7 +711,7 @@ class RtLamniMotor(Device, PositionerBase):
class RtLamniFlyer(Device):
USER_ACCESS = ["controller"]
USER_ACCESS = ["controller", "data_timeout", "scan_timeout", "fetch_diagnostics"]
data = Cpt(
AsyncMultiSignal,
name="data",
@@ -740,9 +757,13 @@ class RtLamniFlyer(Device):
port=3333,
socket_cls=SocketIO,
device_manager=None,
data_timeout: float | None = 5.0,
# 300 s: top-up refills hold the RT scan on purpose (Mirko 2026-11-22)
scan_timeout: float | None = 300.0,
**kwargs,
):
super().__init__(prefix=prefix, name=name, parent=parent, **kwargs)
self._data_monitor = RtDataMonitor(data_timeout=data_timeout, scan_timeout=scan_timeout)
self.shutdown_event = threading.Event()
self.controller = RtLamniController(
socket_cls=socket_cls, socket_host=host, socket_port=port, device_manager=device_manager
@@ -759,6 +780,53 @@ class RtLamniFlyer(Device):
self.scan_done_event = threading.Event()
self.scan_done_event.set()
@property
def data_timeout(self) -> float | None:
"""Seconds without progress before logging a warning (default: 5).
Set to None to suppress the warning while leaving scan_timeout independent.
"""
return self._data_monitor.data_timeout
@data_timeout.setter
def data_timeout(self, value: float | None) -> None:
self._data_monitor.data_timeout = value
@property
def scan_timeout(self) -> float | None:
"""Seconds without progress before failing the scan (default: 300).
Progress means an advancing controller position until the first sample,
then receipt of new samples. Set to None to disable timeout failures.
Readout can then wait until progress resumes, the controller finishes,
or the scan is stopped.
"""
return self._data_monitor.scan_timeout
@scan_timeout.setter
def scan_timeout(self, value: float | None) -> None:
self._data_monitor.scan_timeout = value
def fetch_diagnostics(self) -> dict:
"""Return scan status, feedback state, and recent controller commands."""
diagnostics = {}
try:
mode, planned, current = self.controller.get_scan_status()
diagnostics["scan_status"] = {
"mode": mode,
"planned_positions": planned,
"current_position": current,
}
except Exception as exc:
diagnostics["scan_status_error"] = f"{type(exc).__name__}: {exc}"
try:
diagnostics["feedback_running"] = self.controller.feedback_is_running()
except Exception as exc:
diagnostics["feedback_error"] = f"{type(exc).__name__}: {exc}"
with self.controller._lock:
diagnostics["command_history"] = list(self.controller.command_history)
return diagnostics
def stage(self):
self.shutdown_event.clear()
self.scan_done_event.set()
@@ -783,6 +851,7 @@ class RtLamniFlyer(Device):
self.scan_done_event.clear()
while not self.controller._min_scan_buffer_reached and not self.shutdown_event.wait(0.001):
...
self._data_monitor.reset()
self.controller.start_scan()
self._t_kickoff = time.monotonic()
self._t_scan_end = None
@@ -806,7 +875,10 @@ class RtLamniFlyer(Device):
def stop(self, *, success=False):
self.shutdown_event.set()
self.scan_done_event.set()
if self.readout_thread is not None:
if (
self.readout_thread is not None
and self.readout_thread is not threading.current_thread()
):
self.readout_thread.join()
return super().stop(success=success)
@@ -846,6 +918,18 @@ class RtLamniFlyer(Device):
read_counter = read_counter + 1
signals = self._get_signals_from_table(return_table)
self.data.set(signals)
self._data_monitor.sample_received()
if mode > 0 and not self.shutdown_event.is_set():
exception = self._data_monitor.check(
self.name,
mode=mode,
planned_positions=number_of_positions_planned,
position=current_position_in_scan,
)
if exception is not None:
status.set_exception(exception)
return
self._t_scan_end = time.monotonic() # scan finished in the RT loop (statistics)
+71 -2
View File
@@ -23,6 +23,7 @@ if builtins.__dict__.get("bec") is not None:
from csaxs_bec.devices.omny.rt.rt_ophyd import (
RtCommunicationError,
RtDataMonitor,
RtError,
RtReadbackSignal,
RtSetpointSignal,
@@ -874,6 +875,7 @@ class RtOMNYController(Controller):
raise RtError("Cannot start scan because no target positions are planned.")
# hier exception
# start a point-by-point scan (for cont scan in flomni it would be "sa")
logger.info("RtOMNYController: Starting scan.")
self.socket_put_and_receive("sd")
@retry_once
@@ -1161,7 +1163,7 @@ class RtOMNYMotor(Device, PositionerBase):
class RtOMNYFlyer(Device):
USER_ACCESS = ["controller"]
USER_ACCESS = ["controller", "data_timeout", "scan_timeout", "fetch_diagnostics"]
data = Cpt(
AsyncMultiSignal,
@@ -1205,9 +1207,13 @@ class RtOMNYFlyer(Device):
port=2222,
socket_cls=SocketIO,
device_manager=None,
data_timeout: float | None = 5.0,
# 300 s: top-up refills hold the RT scan on purpose (Mirko 2026-11-22)
scan_timeout: float | None = 300.0,
**kwargs,
):
super().__init__(prefix=prefix, name=name, parent=parent, **kwargs)
self._data_monitor = RtDataMonitor(data_timeout=data_timeout, scan_timeout=scan_timeout)
self.shutdown_event = threading.Event()
self.controller = RtOMNYController(
socket_cls=socket_cls, socket_host=host, socket_port=port, device_manager=device_manager
@@ -1218,6 +1224,53 @@ class RtOMNYFlyer(Device):
self.scan_done_event = threading.Event()
self.scan_done_event.set()
@property
def data_timeout(self) -> float | None:
"""Seconds without progress before logging a warning (default: 5).
Set to None to suppress the warning while leaving scan_timeout independent.
"""
return self._data_monitor.data_timeout
@data_timeout.setter
def data_timeout(self, value: float | None) -> None:
self._data_monitor.data_timeout = value
@property
def scan_timeout(self) -> float | None:
"""Seconds without progress before failing the scan (default: 300).
Progress means an advancing controller position until the first sample,
then receipt of new samples. Set to None to disable timeout failures.
Readout can then wait until progress resumes, the controller finishes,
or the scan is stopped.
"""
return self._data_monitor.scan_timeout
@scan_timeout.setter
def scan_timeout(self, value: float | None) -> None:
self._data_monitor.scan_timeout = value
def fetch_diagnostics(self) -> dict:
"""Return scan status, feedback state, and recent controller commands."""
diagnostics = {}
try:
mode, planned, current = self.controller.get_scan_status()
diagnostics["scan_status"] = {
"mode": mode,
"planned_positions": planned,
"current_position": current,
}
except Exception as exc:
diagnostics["scan_status_error"] = f"{type(exc).__name__}: {exc}"
try:
diagnostics["feedback_running"] = self.controller.feedback_is_running()
except Exception as exc:
diagnostics["feedback_error"] = f"{type(exc).__name__}: {exc}"
with self.controller._lock:
diagnostics["command_history"] = list(self.controller.command_history)
return diagnostics
def stage(self):
self.shutdown_event.clear()
self.scan_done_event.set()
@@ -1234,6 +1287,7 @@ class RtOMNYFlyer(Device):
self.scan_done_event.clear()
while not self.controller._min_scan_buffer_reached and not self.shutdown_event.wait(0.001):
...
self._data_monitor.reset()
self.controller.start_scan()
self.shutdown_event.wait(0.1)
status = DeviceStatus(self)
@@ -1255,7 +1309,10 @@ class RtOMNYFlyer(Device):
def stop(self, *, success=False):
self.shutdown_event.set()
self.scan_done_event.set()
if self.readout_thread is not None:
if (
self.readout_thread is not None
and self.readout_thread is not threading.current_thread()
):
self.readout_thread.join()
return super().stop(success=success)
@@ -1292,6 +1349,18 @@ class RtOMNYFlyer(Device):
read_counter = read_counter + 1
signals = self._get_signals_from_table(return_table)
self.data.set(signals)
self._data_monitor.sample_received()
if mode > 0 and not self.shutdown_event.is_set():
exception = self._data_monitor.check(
self.name,
mode=mode,
planned_positions=number_of_positions_planned,
position=current_position_in_scan,
)
if exception is not None:
status.set_exception(exception)
return
if self.shutdown_event.wait(0.05):
logger.info("Shutdown event set, stopping readout.")
+126 -3
View File
@@ -1,9 +1,9 @@
"""
This module contains base signals for RT devices. Controller and motors are implemented in the
bespoke modules such as `rt_flomni_ophyd.py` or `rt_lamni_ophyd.py`.
This module contains base signals and data monitoring for RT devices. Controllers and motors are
implemented in bespoke modules such as `rt_flomni_ophyd.py` or `rt_lamni_ophyd.py`.
"""
import functools
import math
import time
from bec_lib import bec_logger
@@ -46,6 +46,129 @@ class BECConfigError(Exception):
pass
class RtDataMonitor:
"""Track gaps in scan progress for an owning RT flyer.
Both deadlines start at kickoff. While waiting for the first sampler batch,
each new highest controller position resets the deadlines. After the first
sample, each received sample resets them. The readout loop checks both
deadlines after draining available samples, between socket calls.
Set either timeout to `None` to disable it independently. With
`data_timeout=None`, the monitor skips the stall warning. With
`scan_timeout=None`, a stall can leave readout waiting until progress
resumes, the controller finishes, or the scan is stopped. Other
controller errors and cancellation still apply.
"""
def __init__(
self, data_timeout: float | None = 5.0, scan_timeout: float | None = 300.0
) -> None:
"""Configure the warning and failure thresholds for stalled progress.
Args:
data_timeout (float | None): Seconds without progress before logging one
warning per stall. Defaults to 5 seconds. Pass None to disable warnings.
scan_timeout (float | None): Seconds without progress before failing the
flyer completion status. Defaults to 300 seconds (top-up refills hold
the RT scan on purpose). Pass None to disable
timeout failures.
Raises:
ValueError: If an enabled timeout is non-finite or less than or equal to zero.
"""
self.data_timeout = data_timeout
self.scan_timeout = scan_timeout
self._last_progress_time: float | None = None
self._initial_position: int | None = None
self._data_timeout_logged = False
@staticmethod
def _validate_timeout(value: float | None, name: str) -> float | None:
if value is None:
return None
value = float(value)
if not math.isfinite(value) or value <= 0:
raise ValueError(f"{name} must be a finite, positive number of seconds.")
return value
@property
def data_timeout(self) -> float | None:
"""Seconds without progress before logging a warning, or None to skip the warning."""
return self._data_timeout
@data_timeout.setter
def data_timeout(self, value: float | None) -> None:
self._data_timeout = self._validate_timeout(value, "data_timeout")
@property
def scan_timeout(self) -> float | None:
"""Seconds without progress before failing the scan, or None to keep waiting for progress."""
return self._scan_timeout
@scan_timeout.setter
def scan_timeout(self, value: float | None) -> None:
self._scan_timeout = self._validate_timeout(value, "scan_timeout")
def reset(self) -> None:
"""Start monitoring a new scan at kickoff."""
self._initial_position = 0
self._record_progress()
def sample_received(self) -> None:
"""Switch to monitoring sample receipt and record this sample."""
self._initial_position = None
self._record_progress()
def _record_progress(self) -> None:
self._last_progress_time = time.monotonic()
self._data_timeout_logged = False
def check(
self, device_name: str, *, mode: int, planned_positions: int, position: int
) -> TimeoutError | None:
"""Check the deadlines using the latest controller status.
Args:
device_name (str): Flyer name used in warnings and errors.
mode (int): Latest controller scan mode.
planned_positions (int): Number of points planned by the controller.
position (int): Current scan position reported by the controller.
Returns:
TimeoutError | None: Exception to set on the flyer completion status
if the scan timeout expires, or None to continue. A warning can
be logged while readout continues.
"""
if self._last_progress_time is None:
return
if self._initial_position is not None and position > self._initial_position:
self._initial_position = position
self._record_progress()
elapsed = time.monotonic() - self._last_progress_time
progress = (
"RT controller progress"
if self._initial_position is not None
else "RT samples received"
)
scan_timeout = self.scan_timeout
if scan_timeout is not None and elapsed >= scan_timeout:
return TimeoutError(
f"No {progress} on {device_name} for {elapsed:.1f} s "
f"(scan_timeout={scan_timeout:g} s)."
)
data_timeout = self.data_timeout
if data_timeout is None or elapsed < data_timeout or self._data_timeout_logged:
return
self._data_timeout_logged = True
logger.warning(
f"No {progress} on {device_name} for {elapsed:.1f} s "
f"(data_timeout={data_timeout:g} s). "
f"Last RT status: mode={mode}, planned_positions={planned_positions}, "
f"current_position={position}"
)
class RtSignalBase(SocketSignal):
def __init__(self, signal_name, **kwargs):
self.signal_name = signal_name
+1
View File
@@ -248,6 +248,7 @@ class FlomniFermatScan(ScanBase):
status = self.actions.complete(device=self.dev.rt_positions, wait=False)
while not status.done:
self.at_each_point()
status.wait()
@scan_hook
def at_each_point(self):
+62
View File
@@ -20,6 +20,8 @@ import time
from typing import Annotated
import numpy as np
from bec_lib import messages
from bec_lib.alarm_handler import Alarms
from bec_lib.logger import bec_logger
from bec_lib.scan_args import DefaultArgType, ScanArgument, Units
from bec_server.scan_server.errors import ScanAbortion
@@ -229,6 +231,7 @@ class LamniFermatScan(ScanBase):
while not status.done:
self.at_each_point()
time.sleep(1)
status.wait()
@scan_hook
def at_each_point(self):
@@ -521,6 +524,62 @@ class LamniFermatScan(ScanBase):
)
self.dev.lsamrot.set(angle).wait()
def at_beamline(self) -> tuple[bool, str]:
"""
Is this session at the beamline? True when ddg1 is configured with a real (not simulated) device class
(as the flOMNI scan, flomni_fermat_scan.py; LaMNI soft trigger 2026-11-19). A failing check counts as beamline,
so the hardware trigger is the fallback.
Returns:
(at_beamline, reason)
"""
try:
devices = self.device_manager.devices
if "ddg1" in devices:
cls = str((getattr(devices["ddg1"], "_config", None) or {}).get("deviceClass", ""))
if ".sim." not in cls and "Simulated" not in cls:
return True, f"ddg1 is {cls or 'not simulated'}"
return False, "ddg1 simulated or absent"
except Exception as exc: # pylint: disable=broad-except
return True, f"beamline check failed ({exc}), treated as beamline"
def set_trigger_source(self):
"""
Set the trigger source of the LaMNI loop (loop setting trigger_soft, web HMI via lamni_loop_settings): at the
beamline the hardware trigger (the loop's default); otherwise the soft trigger with the exposure
exp_time x frames_per_trigger, so a scan runs without detector. At the beamline the scan is aborted if the
hardware trigger cannot be confirmed (with the soft trigger the detector would not be triggered while LaMNI
exposes internally). Without the device lamni_loop_settings nothing is changed (warning).
"""
at_bl, reason = self.at_beamline()
if at_bl:
changes = {"trigger_soft": 0}
else:
changes = {"trigger_soft": 1,
"soft_exposure_ms": float(self.exp_time) * float(self.frames_per_trigger) * 1000.0}
try:
res = self.dev.lamni_loop_settings.api_post(
"/api/settings/apply", {"changes": changes, "profile": None, "adjust": False}
)
errors = [] if res and res.get("ok") else list((res or {}).get("errors") or ["no answer"])
except Exception as exc: # pylint: disable=broad-except
errors = [str(exc)]
source = "hardware" if at_bl else "soft"
if errors:
text = f"LaMNI trigger source {source} ({reason}) not set: {'; '.join(errors)}"
if at_bl:
raise ScanAbortion(text + ". At the beamline the hardware trigger must be confirmed.")
logger.warning(text)
self.device_manager.connector.raise_alarm(
severity=Alarms.WARNING,
info=messages.ErrorInfo(
error_message=text, compact_error_message=text, exception_type="TriggerSource",
device="lamni_loop_settings",
),
)
return
logger.info(f"LaMNI trigger source: {source} ({reason}), {changes}")
def prepare_setup(self):
"""
Prepare the setup for the scan:
@@ -529,8 +588,11 @@ class LamniFermatScan(ScanBase):
- Compute the total shift based on the center, stitch, and user-defined shifts, and
move to the new scan center using the interferometer feedback.
- Transfer the positions to the RT controller by adding them to the trajectory generator.
- Set the trigger source of the LaMNI loop: hardware at the beamline, soft otherwise.
"""
self.dev.rtx.controller.clear_trajectory_generator()
# Trigger source of the LaMNI loop (before the baseline read, so the scan file holds the source in use)
self.set_trigger_source()
self.lamni_rotation(self.angle)
total_shift_x, total_shift_y = LamniFermatScan._compute_total_shift(
center_x=self.center_x,
+1
View File
@@ -221,6 +221,7 @@ class OmnyFermatScan(ScanBase):
while not status.done:
self.at_each_point()
time.sleep(1)
status.wait()
@scan_hook
def at_each_point(self):
@@ -0,0 +1,147 @@
from types import SimpleNamespace
from bec_lib.bl_states import DeviceWithinLimitsStateConfig
from csaxs_bec.bec_ipython_client.startup.beamline_states import (
DEFAULT_BEAMLINE_STATES,
beamline_states_for_session,
set_default_beamline_states,
)
DEFAULT_DEVICES = {"curr", "idgap", "shutter", "ofb", "shutter_es"}
class FakeStateManager:
def __init__(self, states=(), ready=True, fail_on=()):
self._states = {state.name: state for state in states}
self.ready = ready
self.fail_on = set(fail_on)
self.calls = []
def delete(self, name):
self.calls.append(("delete", name))
self._states.pop(name, None)
def add(self, state):
self.calls.append(("add", state.name))
if state.name in self.fail_on:
raise TimeoutError("no initial status")
self._states[state.name] = state
def _bec(manager, devices=DEFAULT_DEVICES):
return SimpleNamespace(
beamline_states=manager, device_manager=SimpleNamespace(devices=set(devices))
)
def _names(manager):
return set(manager._states)
def test_defaults_match_the_beamline_setup():
by_name = {state.name: state.model_dump() for state in DEFAULT_BEAMLINE_STATES}
assert by_name["curr_device_within_limits_state"]["low_limit"] == 380.0
assert by_name["idgap_device_within_limits_state"]["high_limit"] == 8.0
assert {state.device for state in DEFAULT_BEAMLINE_STATES} == DEFAULT_DEVICES
assert all(state.tolerance == 0.1 for state in DEFAULT_BEAMLINE_STATES)
def test_other_states_are_cleared_and_defaults_added():
extra = DeviceWithinLimitsStateConfig(name="extra_state", device="curr", low_limit=1.0)
manager = FakeStateManager([extra])
assert set_default_beamline_states(_bec(manager))
assert _names(manager) == {state.name for state in DEFAULT_BEAMLINE_STATES}
assert manager.calls[0] == ("delete", "extra_state")
def test_changed_limit_is_reset():
changed = [
state.model_copy(update={"low_limit": 300.0})
if state.name == "curr_device_within_limits_state"
else state
for state in DEFAULT_BEAMLINE_STATES
]
manager = FakeStateManager(changed)
assert set_default_beamline_states(_bec(manager))
assert manager._states["curr_device_within_limits_state"].low_limit == 380.0
def test_matching_states_are_left_untouched():
manager = FakeStateManager(DEFAULT_BEAMLINE_STATES)
assert set_default_beamline_states(_bec(manager))
assert manager.calls == []
def test_missing_device_keeps_the_existing_states():
extra = DeviceWithinLimitsStateConfig(name="extra_state", device="curr", low_limit=1.0)
manager = FakeStateManager([extra])
assert not set_default_beamline_states(_bec(manager, DEFAULT_DEVICES - {"idgap"}))
assert manager.calls == []
assert _names(manager) == {"extra_state"}
def test_failed_add_does_not_raise():
manager = FakeStateManager(fail_on={"ofb_device_within_limits_state"})
assert not set_default_beamline_states(_bec(manager))
assert "shutter_es_device_within_limits_state" in _names(manager)
def test_not_ready_or_unavailable_does_not_raise():
assert not set_default_beamline_states(_bec(FakeStateManager(ready=False)), ready_timeout=0.1)
assert not set_default_beamline_states(SimpleNamespace(beamline_states=None))
assert not set_default_beamline_states(object())
# ── session states (OMNY vacuum) and their scan interlock entries ────────────────────────────
class FakeInterlock:
def __init__(self, watched=None):
self.states_watched = dict(watched or {})
def add_state_to_interlock(self, name, required_value=None):
self.states_watched[name] = [required_value]
def remove_state_from_interlock(self, name):
self.states_watched.pop(name, None)
def _bec_il(manager, interlock, devices=DEFAULT_DEVICES | {"omny_vcs"}):
b = _bec(manager, devices)
b.builtin_actors = SimpleNamespace(scan_interlock=interlock)
return b
def test_omny_session_adds_the_vacuum_state_and_watches_it():
manager, il = FakeStateManager(DEFAULT_BEAMLINE_STATES), FakeInterlock({"curr_device_within_limits_state": ["valid"]})
assert set_default_beamline_states(_bec_il(manager, il), session="omny")
vac = manager._states["omny_vacuum"]
assert (vac.device, vac.signal, vac.low_limit, vac.high_limit) == ("omny_vcs", "omny_vcs_measurement_ok", 0.5, 1.5)
assert _names(manager) == {s.name for s in DEFAULT_BEAMLINE_STATES} | {"omny_vacuum"}
assert il.states_watched["omny_vacuum"] == ["valid"]
assert il.states_watched["curr_device_within_limits_state"] == ["valid"] # default entries untouched
def test_other_session_removes_the_vacuum_state_from_the_interlock():
omny = beamline_states_for_session("omny")
manager, il = FakeStateManager(omny), FakeInterlock({"omny_vacuum": ["valid"], "shutter_device_within_limits_state": ["valid"]})
assert set_default_beamline_states(_bec_il(manager, il), session="flomni")
assert "omny_vacuum" not in _names(manager)
assert "omny_vacuum" not in il.states_watched
assert "shutter_device_within_limits_state" in il.states_watched
def test_omny_session_without_vcs_device_keeps_the_defaults(capsys):
manager, il = FakeStateManager(), FakeInterlock()
assert set_default_beamline_states(_bec_il(manager, il, DEFAULT_DEVICES), session="omny")
assert _names(manager) == {s.name for s in DEFAULT_BEAMLINE_STATES}
assert "omny_vacuum" not in il.states_watched
assert "skipped" in capsys.readouterr().out
def test_matching_omny_states_untouched_but_interlock_synced():
manager, il = FakeStateManager(beamline_states_for_session("omny")), FakeInterlock()
assert set_default_beamline_states(_bec_il(manager, il), session="omny")
assert manager.calls == []
assert il.states_watched == {"omny_vacuum": ["valid"]}
@@ -355,8 +355,8 @@ def test_angle_file_scan_follows_file_order_and_subtomos(monkeypatch, tmp_path):
flomni.tomo_scan()
# (0, 1): unconditional 0-deg reference shot at the start of a new tomogram
assert recorded == [(0, 1), (10.0, 1), (170.0, 1), (270.0, 2), (5.5, 3)]
# no initial 0-deg shot: for tomo_type 4 the file is the only source of projections
assert recorded == [(10.0, 1), (170.0, 1), (270.0, 2), (5.5, 3)]
assert flomni.progress["total_projections"] == 4
assert flomni.progress["tomo_type"] == "Angles from file"
@@ -407,8 +407,9 @@ def test_angle_file_missing_raises_before_any_acquisition(monkeypatch, tmp_path)
def test_angle_file_ignores_golden_zero_deg_damage_flag(monkeypatch, tmp_path):
"""No extra 0-deg shots at sub-tomogram transitions for type 4 -- only
the unconditional reference shot at the start of a new tomogram."""
"""No 0-deg shots at all for type 4 -- neither at sub-tomogram
transitions nor the initial reference shot at the start of a new
tomogram (it would use the normal tomo parameters, not the file's)."""
flomni = make_flomni_for_angle_file(monkeypatch, tmp_path, "10 1\n20 2\n30 3\n40 5\nEND\n")
flomni.golden_projections_at_0_deg_for_damage_estimation = 1
recorded = []
@@ -416,7 +417,7 @@ def test_angle_file_ignores_golden_zero_deg_damage_flag(monkeypatch, tmp_path):
flomni.tomo_scan()
assert recorded == [(0, 1), (10.0, 1), (20.0, 2), (30.0, 3), (40.0, 5)]
assert recorded == [(10.0, 1), (20.0, 2), (30.0, 3), (40.0, 5)]
def test_max_scan_angle_is_362_only_for_type_4():
@@ -452,8 +453,7 @@ def test_angle_file_accepts_physical_overtravel_range(monkeypatch, tmp_path):
flomni.tomo_scan() # exercises the real _tomo_scan_at_angle(), not a stub
# 0: unconditional 0-deg reference shot at the start of a new tomogram
assert recorded == [0, -2.0, -0.1, 361.0, 362.0]
assert recorded == [-2.0, -0.1, 361.0, 362.0]
# ── tomo_type 4: live append -- wait at EOF without 'END', poll, pick up ────
@@ -475,8 +475,7 @@ def test_angle_file_waits_then_picks_up_appended_lines(monkeypatch, tmp_path):
flomni.tomo_scan()
# (0, 1): unconditional 0-deg reference shot at the start of a new tomogram
assert recorded == [(0, 1), (5.0, 1), (10.0, 1), (20.0, 1)]
assert recorded == [(5.0, 1), (10.0, 1), (20.0, 1)]
assert len(sleep_calls) == 1
assert flomni.progress["total_projections"] == 3
@@ -529,12 +528,11 @@ def test_angle_file_heartbeat_refreshed_while_waiting(monkeypatch, tmp_path):
flomni.tomo_scan()
# (0, 1) reference shot, then (5.0, 1) -- both before any wait tick, so no
# heartbeat has been written yet (the stub above never sets one itself).
# (5.0, 1) comes before any wait tick, so no heartbeat has been written
# yet (the stub above never sets one itself).
assert recorded_heartbeats[0] is None
assert recorded_heartbeats[1] is None
# (10.0, 1) is only reached after the wait tick refreshed the heartbeat.
assert recorded_heartbeats[2] is not None
assert recorded_heartbeats[1] is not None
# ── tomo_type 4: per-line acquisition overrides (step=/exptime=/frames=) ───
@@ -554,7 +552,6 @@ def test_angle_file_overrides_reach_tomo_scan_at_angle_and_are_sticky(monkeypatc
flomni.tomo_scan()
assert recorded == [
(0, 1, {}), # unconditional 0-deg reference shot at tomogram start
(10.0, 1, {}),
(20.0, 1, {"step": 0.5}),
(30.0, 1, {"step": 0.5}), # sticky: step carries forward
@@ -727,7 +724,7 @@ def test_resume_does_not_reset_progress(monkeypatch, tmp_path):
assert flomni.progress["estimated_remaining_time"] == 42.0
def test_angle_file_progress_shows_type_and_total_before_the_zero_deg_shot(monkeypatch, tmp_path):
def test_angle_file_progress_shows_type_and_total_and_skips_zero_deg_shot(monkeypatch, tmp_path):
flomni = make_flomni_for_angle_file(monkeypatch, tmp_path, "10\n20\nEND\n")
seen = []
flomni._tomo_scan_at_angle = lambda angle, subtomo, **kw: seen.append(
@@ -736,7 +733,10 @@ def test_angle_file_progress_shows_type_and_total_before_the_zero_deg_shot(monke
flomni.tomo_scan()
assert seen[0] == (0, "Angles from file", 2) # the initial 0-deg shot
# no initial 0-deg shot for tomo_type 4: the file is the only source of
# projections (a 0-deg shot would use the normal tomo parameters)
assert [a for a, _, _ in seen] == [10, 20]
assert seen[0] == (10, "Angles from file", 2)
def test_flomni_gui_progress_survives_zero_total(monkeypatch):
@@ -0,0 +1,99 @@
"""Tests for lamni.rt_settings (lamni_realtime_system.py, 2026-11-19): the flOMNI loop-settings client with the LaMNI
device and texts. A small local HTTP server stands in for the web HMI on mpc-lamni."""
import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from unittest import mock
import pytest
from csaxs_bec.bec_ipython_client.plugins.flomni.flomni_realtime_system import FlomniRealtimeSystem
from csaxs_bec.bec_ipython_client.plugins.LamNI.lamni_realtime_system import (
LamniRealtimeSystem,
RealtimeSystemError,
)
TOKEN = "lamni-client-token-0123456789"
SNAP = {
"instrument": "LaMNI", "note": "Live only.", "scan": {"mode": 0, "active": False, "text": ""},
"groups": [{"name": "trigger", "title": "Detector trigger"}, {"name": "motion", "title": "Sample stage moves"}],
"settings": [
{"name": "trigger_tolerance_nm", "group": "trigger", "unit": "nm", "value": 5.0, "saved": 5.0,
"unsaved": False, "consistent": True, "issues": [], "info": None},
{"name": "slew_rate_um_s", "group": "motion", "unit": "um/s", "value": 2000.0, "saved": 2000.0,
"unsaved": False, "consistent": True, "issues": [], "info": None},
],
"rules": [],
"profiles": [{"name": "standard", "title": "Standard", "help": "", "values": {}},
{"name": "large_steps", "title": "Large steps, fast", "help": "", "values": {}}],
}
class _Handler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def do_GET(self):
ok = self.headers.get("Authorization") == "Bearer " + TOKEN
data = json.dumps(SNAP if ok else {"detail": "login required"}).encode()
self.send_response(200 if ok else 401)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
@pytest.fixture
def url():
srv = HTTPServer(("127.0.0.1", 0), _Handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
yield f"http://127.0.0.1:{srv.server_address[1]}"
srv.shutdown()
def test_lamni_client_is_the_flomni_client_with_lamni_device_and_texts():
assert issubclass(LamniRealtimeSystem, FlomniRealtimeSystem)
assert LamniRealtimeSystem.DEVICE == "lamni_loop_settings"
assert LamniRealtimeSystem.DOC.startswith("lamni.rt_settings")
assert "lamni.rt_settings" in LamniRealtimeSystem.STAFF_ONLY
assert FlomniRealtimeSystem.DOC.startswith("flomni.rt_settings") # flOMNI unchanged
def test_direct_read_and_show(url, capsys):
rts = LamniRealtimeSystem(url=url, token=TOKEN)
assert rts.get("slew_rate_um_s") == 2000.0
rts.show()
out = capsys.readouterr().out
assert "lamni.rt_settings: beamline scientists" in out and "Loop settings LaMNI" in out
def test_help_prints_the_lamni_text(url, capsys):
LamniRealtimeSystem(url=url, token=TOKEN).help()
out = capsys.readouterr().out
assert out.startswith("lamni.rt_settings: the operating settings of the LaMNI real-time loop")
assert 'help("slew_rate_um_s")' in out
def test_no_tracker_on_lamni(url):
with pytest.raises(RealtimeSystemError, match="no laser tracker"):
LamniRealtimeSystem(url=url, token=TOKEN).tracking_targets()
def test_profile_shortcuts_apply_the_named_profiles():
rts = LamniRealtimeSystem(url="http://127.0.0.1:1", token=TOKEN)
with mock.patch.object(LamniRealtimeSystem, "apply_profile", return_value={"ok": True}) as ap:
rts.standard()
rts.large_steps()
assert [c.args[0] for c in ap.call_args_list] == ["standard", "large_steps"]
def test_routes_through_the_lamni_device():
dm = mock.MagicMock()
dm.devices.lamni_loop_settings.enabled = True
dm.devices.lamni_loop_settings.api_get.return_value = SNAP
rts = LamniRealtimeSystem(device_manager=dm)
assert rts.route == "device lamni_loop_settings"
assert rts.get("trigger_tolerance_nm") == 5.0
dm.devices.lamni_loop_settings.api_get.assert_called_with("/api/settings")
@@ -107,7 +107,7 @@ def test_scan_follows_file_order_and_reports_progress(monkeypatch, tmp_path):
lamni.tomo_scan(force=True)
assert recorded == [(0, 1), (10.0, 1), (170.0, 1), (270.0, 2), (362.0, 3)]
assert recorded == [(10.0, 1), (170.0, 1), (270.0, 2), (362.0, 3)]
assert lamni.progress["total_projections"] == 4
assert lamni.progress["tomo_type"] == "Angles from file"
@@ -175,7 +175,6 @@ def test_per_line_overrides_are_sticky_and_passed_to_scan_at_angle(monkeypatch,
lamni.tomo_scan(force=True)
assert calls == [
(0, {}),
(10.0, {}),
(20.0, {"step": 0.5, "exp_time": 2.0, "frames_per_trigger": 3}),
(30.0, {"step": 0.7, "exp_time": 2.0, "frames_per_trigger": 3}),
@@ -259,7 +258,7 @@ def test_queue_job_line_shows_angle_file_for_type_4():
assert "angles=" not in line
def test_progress_shows_type_and_total_before_the_zero_deg_shot(monkeypatch, tmp_path):
def test_progress_shows_type_and_total_and_skips_zero_deg_shot(monkeypatch, tmp_path):
lamni = make_lamni_for_angle_file(monkeypatch, tmp_path, "10\n20\nEND\n")
seen = []
lamni._tomo_scan_at_angle = lambda angle, subtomo: seen.append(
@@ -268,4 +267,7 @@ def test_progress_shows_type_and_total_before_the_zero_deg_shot(monkeypatch, tmp
lamni.tomo_scan(force=True)
assert seen[0] == (0, "Angles from file", 2) # the initial 0-deg shot
# no initial 0-deg shot for tomo_type 4: the file is the only source of
# projections (a 0-deg shot would use the normal tomo parameters)
assert [a for a, _, _ in seen] == [10, 20]
assert seen[0] == (10, "Angles from file", 2)
@@ -33,7 +33,10 @@ def dialog(qapp):
client = mock.MagicMock()
client.get_global_var.return_value = registry
client.device_manager.devices = {"keithley": mock.MagicMock(limits=(0.0, 3.0))}
return CommandJobBuilderDialog(client)
builder = CommandJobBuilderDialog(client)
yield builder
builder.close()
builder.deleteLater()
def _add_step(dialog, action, **values):
@@ -0,0 +1,71 @@
"""Tests for the live view of OMNY_XRayEye.
The X-ray eye drives its embedded bec_widgets Image only through the public
``image(device, signal)``, so it works with the Image before and after its move to the BEC
DataAPI, where ``disconnect_monitor`` and ``_get_payload_data`` no longer exist.
"""
import numpy as np
import pytest
from bec_widgets.tests.fake_devices import FakeDevice
from bec_widgets.tests.fixtures import * # noqa: F401,F403 the shared widget test bed
from bec_widgets.tests.utils import create_widget
from csaxs_bec.bec_widgets.widgets.xray_eye.x_ray_eye import CAMERA, OMNY_XRayEye
# pylint: disable=protected-access,redefined-outer-name
@pytest.fixture
def xray_eye(qtbot, mocked_client, monkeypatch):
"""The X-ray eye on a client that has the camera with its two 2D preview signals."""
camera = FakeDevice(CAMERA[0])
for signal in (CAMERA[1], "smear_preview"):
camera._info["signals"][signal] = {
"obj_name": signal,
"signal_class": "PreviewSignal",
"component_name": signal,
"describe": {"signal_info": {"ndim": 2}},
}
# the devices the widget reads once when it is built; there is no device server here
gui, shutter = FakeDevice("omny_xray_gui"), FakeDevice("fsh")
for device in (gui, shutter):
monkeypatch.setattr(device, "read", lambda *args, **kwargs: {})
mocked_client.device_manager.add_devices([camera, gui, shutter])
return create_widget(qtbot, OMNY_XRayEye, client=mocked_client)
def test_live_view_connects_and_disconnects_the_camera(xray_eye):
xray_eye.on_live_view_enabled(True)
assert (xray_eye.image.device, xray_eye.image.signal) == CAMERA
assert xray_eye.live_preview_toggle.checked is True
xray_eye.on_live_view_enabled(False)
assert xray_eye.image.device == ""
assert xray_eye.live_preview_toggle.checked is False
xray_eye.on_live_view_enabled(True)
assert (xray_eye.image.device, xray_eye.image.signal) == CAMERA
def test_live_view_signal_can_be_switched(xray_eye):
xray_eye.on_live_view_enabled(True)
xray_eye.set_live_view_signal("smear_preview")
assert (xray_eye.image.device, xray_eye.image.signal) == (CAMERA[0], "smear_preview")
assert xray_eye.smear_preview_toggle.checked is True
xray_eye.set_live_view_signal()
assert (xray_eye.image.device, xray_eye.image.signal) == CAMERA
assert xray_eye.smear_preview_toggle.checked is False
def test_last_smear_preview_is_cached_and_shown_on_switch(xray_eye):
composite = np.arange(12, dtype=float).reshape(3, 4)
xray_eye._on_smear_preview_cached_update({"data": composite}, {})
xray_eye._on_smear_preview_cached_update({}, {}) # a message without data keeps the cache
xray_eye.set_live_view_signal("smear_preview")
np.testing.assert_array_equal(xray_eye._last_smear_composite, composite)
np.testing.assert_array_equal(xray_eye.image.main_image.raw_data, composite)
@@ -0,0 +1,78 @@
"""Tests for the baseline device lamni_loop_settings (devices/omny/lamni_loop_settings.py, 2026-11-19): the loop settings
of the LaMNI web HMI stored with every scan. A small local HTTP server stands in for the web HMI (/api/settings)."""
import json
import math
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
import pytest
from csaxs_bec.devices.omny.lamni_loop_settings import SETTINGS, LamniLoopSettings
from csaxs_bec.devices.omny.webhmi_client import WebHmiError
TOKEN = "lamni-device-token-0123456789"
SNAP = {
"instrument": "LaMNI", "definition": "/home/control/LamNI/LAMNIcontrol/loopsettings/lamni.json",
"definition_sha1": "b" * 40, "scan": {"mode": 0, "active": False, "text": ""},
"settings": [
{"name": "trigger_tolerance_nm", "value": 10.0, "unsaved": False, "consistent": True},
{"name": "target_shaper_scale", "value": 1.0, "unsaved": True, "consistent": True},
{"name": "slew_rate_um_s", "value": 2000.0, "unsaved": False, "consistent": True},
{"name": "trigger_soft", "value": 0, "unsaved": False, "consistent": True},
],
"rules": [],
}
class _Handler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def do_GET(self):
code, body = (200, SNAP) if self.headers.get("Authorization") == "Bearer " + TOKEN else (401, {"detail": "no"})
data = json.dumps(body).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
@pytest.fixture
def url():
srv = HTTPServer(("127.0.0.1", 0), _Handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
yield f"http://127.0.0.1:{srv.server_address[1]}"
srv.shutdown()
def test_lamni_settings_list():
assert "slew_rate_um_s" in SETTINGS and "target_shaper_scale" in SETTINGS and "trigger_soft" in SETTINGS
assert not any(n.startswith(("fzp", "abbe", "tracking", "psd")) or n == "trigger_topup" for n in SETTINGS)
def test_read_stores_the_omny_settings(url):
dev = LamniLoopSettings(name="lamni_loop_settings", url=url, token=TOKEN)
r = dev.read()
assert r["lamni_loop_settings_available"]["value"] == 1
assert r["lamni_loop_settings_slew_rate_um_s"]["value"] == 2000.0
assert r["lamni_loop_settings_trigger_tolerance_nm"]["value"] == 10.0
assert r["lamni_loop_settings_unsaved"]["value"] == 1
assert math.isnan(r["lamni_loop_settings_trigger_hold_ms"]["value"]) # not in this answer
assert json.loads(r["lamni_loop_settings_snapshot_json"]["value"])["instrument"] == "LaMNI"
def test_wrong_token_is_not_available_and_does_not_raise(url):
dev = LamniLoopSettings(name="lamni_loop_settings", url=url, token="wrong-token-0123456789")
r = dev.read()
assert r["lamni_loop_settings_available"]["value"] == 0
assert "401" in r["lamni_loop_settings_message"]["value"]
def test_rpc_paths_are_restricted(url):
dev = LamniLoopSettings(name="lamni_loop_settings", url=url, token=TOKEN)
assert dev.api_get("/api/settings")["instrument"] == "LaMNI"
with pytest.raises(WebHmiError):
dev.api_get("/api/terminal")
+248
View File
@@ -0,0 +1,248 @@
"""RT progress warnings and timeouts use the status already polled by the flyer."""
import contextlib
import importlib
import threading
from collections import deque
from types import SimpleNamespace
from unittest import mock
import pytest
from csaxs_bec.devices.omny.rt import rt_ophyd
@contextlib.contextmanager
def rt_warnings():
"""Record only the RT data monitor's own warnings.
rt_ophyd.logger is the shared BEC logger: background threads left over from other
tests (e.g. WebpageGenerator, random test order) can log warnings meanwhile and
must not count as monitor warnings. Other warnings pass through unchanged.
"""
recorder = mock.MagicMock()
original = rt_ophyd.logger.warning
def warning(msg, *args, **kwargs):
if isinstance(msg, str) and msg.startswith("No RT "):
recorder(msg, *args, **kwargs)
else:
original(msg, *args, **kwargs)
with mock.patch.object(rt_ophyd.logger, "warning", side_effect=warning):
yield recorder
@pytest.fixture(params=[("flomni", "RtFlomni"), ("lamni", "RtLamni"), ("omny", "RtOMNY")])
def flyer(request, monkeypatch):
suffix, class_prefix = request.param
module = importlib.import_module(f"csaxs_bec.devices.omny.rt.rt_{suffix}_ophyd")
controller = mock.Mock()
controller._lock = threading.RLock()
controller._min_scan_buffer_reached = True
controller.command_history = deque(["[PUT]: sd", "[GET]: scan started"])
controller.get_scan_status.return_value = (2, 10, 6)
controller.feedback_is_running.return_value = True
controller.socket_put_and_receive.side_effect = lambda command: ",".join(
[command[1:]] + ["0"] * 24
)
monkeypatch.setattr(module, f"{class_prefix}Controller", lambda **kwargs: controller)
device = getattr(module, f"{class_prefix}Flyer")(name="rt_positions", data_timeout=3)
monkeypatch.setattr(device.data, "set", mock.Mock())
monkeypatch.setattr(device.progress, "put", mock.Mock())
yield device
device.destroy()
@pytest.fixture
def clock(monkeypatch):
clock = SimpleNamespace(now=100)
monkeypatch.setattr(rt_ophyd, "time", SimpleNamespace(monotonic=lambda: clock.now))
return clock
def run_readout(flyer, clock, states, *, finish=False, failure=False):
"""Poll scripted (elapsed seconds, mode, position) without sleeping or hardware."""
origin = clock.now
states = iter(states)
def next_status():
try:
elapsed, mode, position = next(states)
except StopIteration:
flyer.shutdown_event.set()
return (2, 10, 0)
clock.now = origin + elapsed
return mode, 10, position
flyer.controller.get_scan_status.side_effect = next_status
flyer.shutdown_event = mock.Mock(wraps=threading.Event())
flyer.shutdown_event.wait.side_effect = lambda timeout: flyer.shutdown_event.is_set()
status = flyer.kickoff()
assert status.done and status.success
status = flyer.complete()
flyer.readout_thread.join(timeout=2)
assert not flyer.readout_thread.is_alive()
if failure:
with pytest.raises(TimeoutError, match="scan_timeout"):
status.wait(timeout=1)
assert status.done and not status.success
else:
status.wait(timeout=1)
assert status.success
if finish:
assert not flyer.shutdown_event.is_set()
return status
@pytest.mark.parametrize("mode", [2, 3])
def test_warns_once_at_configured_timeout_without_samples(flyer, clock, mode):
with rt_warnings() as warning:
run_readout(flyer, clock, [(0, mode, 0), (2.999, mode, 0)])
warning.assert_not_called()
run_readout(flyer, clock, [(0, mode, 0), (3, mode, 0), (4, mode, 0), (20, mode, 0)])
warning.assert_called_once()
assert "data_timeout=3 s" in warning.call_args.args[0]
assert f"mode={mode}, planned_positions=10, current_position=0" in warning.call_args.args[0]
flyer.data.set.assert_not_called()
def test_samples_rearm_warning_and_new_scan_resets_timeout(flyer, clock):
with rt_warnings() as warning:
run_readout(
flyer, clock, [(0, 2, 0), (3, 2, 0), (4, 2, 6), (6.999, 2, 6), (7, 2, 6), (20, 2, 6)]
)
assert flyer.data.set.call_count == 5
assert warning.call_count == 2
warning.reset_mock()
run_readout(flyer, clock, [(0, 2, 0), (2.999, 2, 0)])
warning.assert_not_called()
run_readout(flyer, clock, [(0, 2, 0), (3, 2, 0)])
warning.assert_called_once()
def test_available_samples_are_read_before_timeout_check(flyer, clock):
with rt_warnings() as warning:
run_readout(flyer, clock, [(0, 2, 0), (4, 2, 6), (6.999, 2, 6)])
warning.assert_not_called()
assert flyer.data.set.call_count == 5
def test_finished_scan_drains_samples_without_stall_warning(flyer, clock):
with rt_warnings() as warning:
run_readout(flyer, clock, [(0, 2, 0), (70, 0, 3)], finish=True)
warning.assert_not_called()
assert flyer.data.set.call_count == 10
def test_diagnostics_include_status_feedback_and_history(flyer):
assert flyer.fetch_diagnostics() == {
"scan_status": {"mode": 2, "planned_positions": 10, "current_position": 6},
"feedback_running": True,
"command_history": ["[PUT]: sd", "[GET]: scan started"],
}
def test_diagnostics_preserve_other_fields_when_a_query_fails(flyer):
flyer.controller.get_scan_status.side_effect = TimeoutError("status unavailable")
diagnostics = flyer.fetch_diagnostics()
assert diagnostics["scan_status_error"] == "TimeoutError: status unavailable"
assert diagnostics["feedback_running"] is True
assert diagnostics["command_history"]
flyer.controller.feedback_is_running.side_effect = RuntimeError("feedback unavailable")
assert flyer.fetch_diagnostics()["feedback_error"] == "RuntimeError: feedback unavailable"
def test_stopped_device_does_not_warn(flyer, clock):
flyer._data_monitor.reset()
clock.now += 10
flyer.shutdown_event.set()
with rt_warnings() as warning:
status = mock.Mock()
flyer.read_positions_from_sampler(status)
status.set_finished.assert_called_once_with()
warning.assert_not_called()
@pytest.mark.parametrize("mode", [2, 3])
def test_scan_timeout_fails_status_without_stopping_axes(flyer, clock, mode):
flyer.scan_timeout = 8
with rt_warnings() as warning:
status = run_readout(
flyer, clock, [(0, mode, 0), (3, mode, 0), (7.999, mode, 0), (8, mode, 0)], failure=True
)
warning.assert_called_once()
assert "scan_timeout=8 s" in str(status.exception())
assert flyer.controller.get_scan_status.call_count == 4
flyer.controller.feedback_is_running.assert_not_called()
flyer.controller.socket_put_and_receive.assert_not_called()
assert flyer.shutdown_event.is_set()
assert flyer.scan_done_event.is_set()
flyer.controller.stop_all_axes.assert_not_called()
def test_received_points_reset_scan_timeout(flyer, clock):
flyer.scan_timeout = 8
status = run_readout(
flyer, clock, [(0, 2, 0), (7, 2, 6), (14.999, 2, 6), (15, 2, 6)], failure=True
)
assert "for 8.0 s" in str(status.exception())
assert flyer.data.set.call_count == 5
def test_default_scan_timeout_is_five_minutes(flyer, clock):
assert flyer.scan_timeout == 300
status = run_readout(flyer, clock, [(0, 2, 0), (299.999, 2, 0), (300, 2, 0)], failure=True)
assert "scan_timeout=300 s" in str(status.exception())
@pytest.mark.parametrize("name", ["data_timeout", "scan_timeout"])
@pytest.mark.parametrize("timeout", [0, -1, float("nan"), float("inf")])
def test_invalid_timeouts_are_rejected(name, timeout):
with pytest.raises(ValueError, match="finite, positive"):
rt_ophyd.RtDataMonitor(**{name: timeout})
def test_slow_first_batch_keeps_scan_alive_while_controller_advances(flyer, clock):
flyer.data_timeout = 15
states = [(0, 2, 0), (11, 2, 1), (22, 2, 2), (33, 2, 3), (44, 2, 4)]
states += [(55, 2, 5), (60, 2, 5), (66, 2, 6), (77, 0, 10)]
with rt_warnings() as warning:
run_readout(flyer, clock, states, finish=True)
warning.assert_not_called()
assert flyer.data.set.call_count == 10
def test_initial_position_must_reach_a_new_high_to_reset_timeout(flyer, clock):
flyer.scan_timeout = 8
states = [(0, 2, 0), (2, 2, 1), (8, 2, 0), (9, 2, 1), (10, 2, 1)]
status = run_readout(flyer, clock, states, failure=True)
assert "No RT controller progress" in str(status.exception())
def test_controller_progress_cannot_mask_stalled_sample_readout(clock):
monitor = rt_ophyd.RtDataMonitor(data_timeout=3, scan_timeout=8)
monitor.reset()
monitor.sample_received()
clock.now += 3
assert monitor.check("rt_positions", mode=2, planned_positions=10, position=7) is None
clock.now += 5
error = monitor.check("rt_positions", mode=2, planned_positions=10, position=8)
assert isinstance(error, TimeoutError)
assert "No RT samples received" in str(error)
@pytest.mark.parametrize(
("data_timeout", "scan_timeout", "warns", "fails"),
[(None, 8, False, True), (3, None, True, False), (None, None, False, False)],
)
def test_timeouts_can_be_disabled_independently(flyer, clock, data_timeout, scan_timeout, warns, fails):
flyer.data_timeout = data_timeout
flyer.scan_timeout = scan_timeout
states = [(0, 2, 0), (3, 2, 0), (8, 2, 0), (70, 2, 0), (71, 0, 10)]
with rt_warnings() as warning:
run_readout(flyer, clock, states, finish=not fails, failure=fails)
assert warning.call_count == int(warns)
@@ -0,0 +1,80 @@
from unittest import mock
import pytest
from ophyd_devices.tests.utils import SocketMock
from csaxs_bec.devices.omny.rt.rt_lamni_ophyd import RtLamniController
@pytest.fixture()
def rt_lamni():
RtLamniController._reset_controller()
rt = RtLamniController(
name="rt_lamni",
socket_cls=SocketMock,
socket_host="localhost",
socket_port=3333,
device_manager=mock.MagicMock(),
)
yield rt
RtLamniController._reset_controller()
def _prepare(rt):
"""Coarse stages with a center, lsamrot at 0, Galil ready; returns a mock recording the call order."""
devices = rt.device_manager.devices
devices.lsamrot.obj.readback.get.return_value = 0.0
devices.lsamx.user_parameter = {"center": 1.5}
devices.lsamy.user_parameter = {"center": -2.5}
devices.lsamx.obj.controller.lgalil_is_air_off_and_orchestra_enabled.return_value = 1
order = mock.MagicMock()
status_x, status_y = mock.MagicMock(name="status_x"), mock.MagicMock(name="status_y")
devices.lsamx.obj.move.return_value = status_x
devices.lsamy.obj.move.return_value = status_y
order.attach_mock(devices.lsamx.obj.move, "move_x")
order.attach_mock(devices.lsamy.obj.move, "move_y")
order.attach_mock(status_x.wait, "wait_x")
order.attach_mock(status_y.wait, "wait_y")
return order
def test_feedback_enable_with_reset_moves_lsamx_lsamy_together(rt_lamni):
order = _prepare(rt_lamni)
with (
mock.patch.object(rt_lamni, "feedback_status_angle_lamni", return_value=True),
mock.patch.object(rt_lamni, "feedback_disable"),
mock.patch.object(rt_lamni, "clear_trajectory_generator"),
mock.patch.object(rt_lamni, "get_axis_by_name"),
mock.patch.object(rt_lamni, "set_device_read_write"),
mock.patch.object(rt_lamni, "socket_put_and_receive", return_value="0,0,0"),
mock.patch.object(rt_lamni, "socket_put") as socket_put,
mock.patch("time.sleep"),
):
order.attach_mock(socket_put, "socket_put")
rt_lamni.feedback_enable_with_reset()
names = [c[0] for c in order.mock_calls if c[0] in ("move_x", "move_y", "wait_x", "wait_y")
or (c[0] == "socket_put" and c.args == ("J1",))]
# both moves are started (without waiting) before the first wait; J1 only after both are done
assert names == ["move_x", "move_y", "wait_x", "wait_y", "socket_put"]
assert order.move_x.call_args == mock.call(1.5, wait=False)
assert order.move_y.call_args == mock.call(-2.5, wait=False)
def test_feedback_enable_with_reset_ctrl_c_stops_both_axes(rt_lamni):
_prepare(rt_lamni)
devices = rt_lamni.device_manager.devices
devices.lsamx.obj.move.return_value.wait.side_effect = KeyboardInterrupt
with (
mock.patch.object(rt_lamni, "feedback_status_angle_lamni", return_value=True),
mock.patch.object(rt_lamni, "feedback_disable"),
mock.patch.object(rt_lamni, "clear_trajectory_generator"),
mock.patch.object(rt_lamni, "get_axis_by_name"),
mock.patch.object(rt_lamni, "socket_put") as socket_put,
mock.patch("time.sleep"),
pytest.raises(KeyboardInterrupt),
):
rt_lamni.feedback_enable_with_reset()
devices.lsamx.obj.stop.assert_called_once()
devices.lsamy.obj.stop.assert_called_once()
assert mock.call("J1") not in socket_put.mock_calls
@@ -120,3 +120,51 @@ def test_ddg1_armed_in_pre_scan_and_reset_after_scan():
scan.dev.ddg1.set_trigger.reset_mock()
LamniFermatScan.on_exception(scan, RuntimeError("boom"))
scan.dev.ddg1.set_trigger.assert_called_once_with(TRIGGERSOURCE.SINGLE_SHOT.value)
# ── trigger source of the LaMNI loop (soft trigger away from the beamline, 2026-11-19) ──────────────────────────
def _trigger_stub(ddg1_class, api_result=None, api_exc=None):
"""A stand-in for a LamniFermatScan with the attributes at_beamline() / set_trigger_source() touch."""
scan = mock.MagicMock()
devices = {}
if ddg1_class is not None:
ddg1 = mock.MagicMock()
ddg1._config = {"deviceClass": ddg1_class}
devices["ddg1"] = ddg1
scan.device_manager.devices = devices
scan.exp_time = 0.05
scan.frames_per_trigger = 2
if api_exc is not None:
scan.dev.lamni_loop_settings.api_post.side_effect = api_exc
else:
scan.dev.lamni_loop_settings.api_post.return_value = api_result if api_result is not None else {"ok": True}
scan.at_beamline = lambda: LamniFermatScan.at_beamline(scan)
return scan
def test_trigger_source_hardware_at_the_beamline():
scan = _trigger_stub("csaxs_bec.devices.epics.delay_generator_csaxs.DDG1")
LamniFermatScan.set_trigger_source(scan)
path, body = scan.dev.lamni_loop_settings.api_post.call_args.args
assert path == "/api/settings/apply" and body["changes"] == {"trigger_soft": 0}
def test_trigger_source_soft_without_beamline_uses_the_exposure():
scan = _trigger_stub("ophyd_devices.sim.sim_ddg.SimulatedDDG")
LamniFermatScan.set_trigger_source(scan)
_, body = scan.dev.lamni_loop_settings.api_post.call_args.args
assert body["changes"] == {"trigger_soft": 1, "soft_exposure_ms": 100.0} # 0.05 s x 2 frames
def test_trigger_source_failure_aborts_only_at_the_beamline():
import pytest
from bec_server.scan_server.errors import ScanAbortion
scan = _trigger_stub("csaxs_bec.devices.epics.delay_generator_csaxs.DDG1", api_exc=RuntimeError("web HMI down"))
with pytest.raises(ScanAbortion, match="hardware trigger must be confirmed"):
LamniFermatScan.set_trigger_source(scan)
scan = _trigger_stub(None, api_result={"ok": False, "errors": ["a scan is running"]})
LamniFermatScan.set_trigger_source(scan) # soft trigger: warning only
scan.device_manager.connector.raise_alarm.assert_called_once()
+48
View File
@@ -0,0 +1,48 @@
"""RT completion errors must propagate out of the scan's polling loop."""
from contextlib import nullcontext
from types import SimpleNamespace
from unittest import mock
import pytest
from bec_lib import messages
from bec_server.scan_server.errors import DeviceInstructionError
from bec_server.scan_server.scans.scan_status import ScanStatus
from csaxs_bec.scans.flomni_fermat_scan import FlomniFermatScan
from csaxs_bec.scans.lamni_fermat_scan import LamniFermatScan
from csaxs_bec.scans.omny_fermat_scan import OmnyFermatScan
@pytest.mark.parametrize("scan_cls", [FlomniFermatScan, LamniFermatScan, OmnyFermatScan])
@pytest.mark.parametrize("failed", [False, True])
def test_rt_scan_checks_completed_readout_result(scan_cls, failed):
status = ScanStatus(instruction_handler=mock.Mock())
if failed:
status.set_failed(
messages.ErrorInfo(
error_message="No RT scan points received within scan_timeout",
compact_error_message="RT scan timed out",
exception_type="TimeoutError",
device="rt_positions",
)
)
else:
status.set_done()
scan = SimpleNamespace(
actions=mock.Mock(),
exp_time=0.1,
frames_per_trigger=1,
dev=SimpleNamespace(rt_positions="rt_positions"),
at_each_point=mock.Mock(),
_scan_modifier=None,
_scan_modifier_hooks={},
)
scan.actions._scan_hook_context.side_effect = lambda _: nullcontext()
scan.actions.complete.return_value = status
if failed:
with pytest.raises(DeviceInstructionError, match="RT scan timed out"):
scan_cls.scan_core(scan)
else:
scan_cls.scan_core(scan)
scan.actions.complete.assert_called_once_with(device="rt_positions", wait=False)