feat(lamni): loop settings - lamni.rt_settings, baseline device lamni_loop_settings, trigger source at scan start
CI for csaxs_bec / test (push) Successful in 8m43s
CI for csaxs_bec / test (push) Successful in 8m43s
LaMNI web HMI loop settings (LamNI LAMNIcontrol/loopsettings/lamni.json on mpc-lamni, 2026-11-19) in BEC, as flOMNI / OMNY: - lamni.rt_settings (plugins/LamNI/lamni_realtime_system.py): the flOMNI client with the LaMNI device and texts; standard() / large_steps() apply the two profiles; tracker shortcuts refused (LaMNI has no laser tracker). - lamni_loop_settings (devices/omny/lamni_loop_settings.py, copy of omny_loop_settings with the LaMNI settings): baseline device, every scan file holds the loop settings it ran with. - LamniFermatScan.set_trigger_source() in prepare_setup (as the flOMNI scan): at the beamline (ddg1 real) the hardware trigger, else the soft trigger with exp_time x frames_per_trigger; at the beamline a failure aborts. - ptycho_lamni.yaml: device lamni_loop_settings (host mpc-lamni.psi.ch); API token NOT filled in (to be entered, token or token_file ~/.lamni_webhmi_token). Tests: device, client, scan trigger source (offline, local HTTP stand-in); all LaMNI tests pass (763). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01M8zoDygkWk6LupmHh3tyET
This commit is contained in:
1 parent
37f25e45e8
commit
ea0ade0715
8 files changed
+569
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
|
||||
|
||||
@@ -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)
|
||||
@@ -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: ""
|
||||
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())
|
||||
@@ -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
|
||||
@@ -521,6 +523,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 +587,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,
|
||||
|
||||
@@ -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")
|
||||
@@ -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")
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user