From d807f8219cf959ba9bb4a9641085e08b6a07d287 Mon Sep 17 00:00:00 2001 From: x10sa Date: Mon, 2 Nov 2026 11:36:28 +0100 Subject: [PATCH] WIP: copy everything from aare_bec_proto --- mx_bec/__init__.py | 3 + mx_bec/actor_manager.py | 114 ++++++++++++ mx_bec/actors/__init__.py | 21 +++ mx_bec/actors/core.py | 70 ++++++++ mx_bec/actors/mx_automation.py | 52 ++++++ mx_bec/configs/__init__.py | 16 ++ mx_bec/configs/mx_demo_config.yaml | 105 +++++++++++ mx_bec/constants.py | 6 + mx_bec/devices/__init__.py | 4 + mx_bec/devices/aerotech.py | 137 +++++++++++++++ mx_bec/devices/http.py | 253 +++++++++++++++++++++++++++ mx_bec/devices/sim_sample_changer.py | 108 ++++++++++++ mx_bec/devices/sim_stages.py | 28 +++ mx_bec/devices/smargopolo_smargon.py | 97 ++++++++++ mx_bec/endpoints.py | 66 +++++++ mx_bec/main.py | 32 ++++ mx_bec/messages.py | 24 +++ mx_bec/optical_centering.py | 60 +++++++ mx_bec/service.py | 98 +++++++++++ mx_bec/states/__init__.py | 51 ++++++ pyproject.toml | 21 ++- tests/unit/mock_smargopolo.py | 160 +++++++++++++++++ tests/unit/test_actor_manager.py | 119 +++++++++++++ tests/unit/test_actors.py | 85 +++++++++ tests/unit/test_demo_config.py | 13 ++ tests/unit/test_devices.py | 71 ++++++++ tests/unit/test_service.py | 109 ++++++++++++ tests/unit/test_smargon.py | 106 +++++++++++ 28 files changed, 2028 insertions(+), 1 deletion(-) create mode 100644 mx_bec/actor_manager.py create mode 100644 mx_bec/actors/__init__.py create mode 100644 mx_bec/actors/core.py create mode 100644 mx_bec/actors/mx_automation.py create mode 100644 mx_bec/configs/__init__.py create mode 100644 mx_bec/configs/mx_demo_config.yaml create mode 100644 mx_bec/constants.py create mode 100644 mx_bec/devices/aerotech.py create mode 100644 mx_bec/devices/http.py create mode 100644 mx_bec/devices/sim_sample_changer.py create mode 100644 mx_bec/devices/sim_stages.py create mode 100644 mx_bec/devices/smargopolo_smargon.py create mode 100644 mx_bec/endpoints.py create mode 100644 mx_bec/main.py create mode 100644 mx_bec/messages.py create mode 100644 mx_bec/optical_centering.py create mode 100644 mx_bec/service.py create mode 100644 mx_bec/states/__init__.py create mode 100644 tests/unit/mock_smargopolo.py create mode 100644 tests/unit/test_actor_manager.py create mode 100644 tests/unit/test_actors.py create mode 100644 tests/unit/test_demo_config.py create mode 100644 tests/unit/test_devices.py create mode 100644 tests/unit/test_service.py create mode 100644 tests/unit/test_smargon.py diff --git a/mx_bec/__init__.py b/mx_bec/__init__.py index e69de29..4a6e830 100644 --- a/mx_bec/__init__.py +++ b/mx_bec/__init__.py @@ -0,0 +1,3 @@ +from .service import AareBec + +__all__ = ["AareBec"] diff --git a/mx_bec/actor_manager.py b/mx_bec/actor_manager.py new file mode 100644 index 0000000..73868b7 --- /dev/null +++ b/mx_bec/actor_manager.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +import functools +from collections.abc import Callable, Iterable +from threading import Event, Thread +from typing import TYPE_CHECKING + +from bec_lib.config_values import RedisConfigValue +from bec_lib.endpoints import MessageEndpoints +from bec_lib.logger import bec_logger +from bec_lib.messages import BuiltinActorStateUpdatedNotification + +from mx_bec.actors import all_actor_classes +from mx_bec.actors.core import MXAutomationActor + +if TYPE_CHECKING: + from bec_lib.client import BECClient + +logger = bec_logger.logger + + +ActorClass = type[MXAutomationActor] +RunningActor = tuple[MXAutomationActor, Thread, Event] + + +class AareActorManager: + """Runs the MX automation actors on behalf of the AareBec service. + + Every actor class has an `enabled` flag in Redis (see `MXAutomationActor.config_endpoint`); + the manager starts an actor thread when its flag becomes true and stops it when it becomes + false. By default all actors in `mx_bec.actors` are managed; pass `actor_classes` + to override. + """ + + def __init__( + self, client: BECClient, actor_classes: Iterable[type[MXAutomationActor]] | None = None + ) -> None: + self._client = client + self._actor_classes = ( + list(actor_classes) if actor_classes is not None else all_actor_classes() + ) + self._actors_threads_and_stops: dict[ActorClass, RunningActor] = {} + self._enabled_flags: dict[ActorClass, RedisConfigValue[bool]] = {} + # RedisConfigValue only keeps weak references to subscribers, so hold the partials here. + self._enabled_callbacks: dict[ActorClass, Callable[[bool], None]] = {} + + for actor_class in self._actor_classes: + flag: RedisConfigValue[bool] = RedisConfigValue( + connector=self._client.connector, endpoint=actor_class.config_endpoint() + ) + callback = functools.partial(self._enabled_changed, actor_class) + flag.subscribe(callback) + self._enabled_flags[actor_class] = flag + self._enabled_callbacks[actor_class] = callback + + self._start_all() + + @property + def actor_classes(self) -> list[type[MXAutomationActor]]: + return list(self._actor_classes) + + @property + def running(self) -> list[type[MXAutomationActor]]: + return list(self._actors_threads_and_stops) + + def is_enabled(self, actor_class: type[MXAutomationActor]) -> bool: + return self._enabled_flags[actor_class].value + + def set_enabled(self, actor_class: type[MXAutomationActor], enabled: bool) -> None: + """Write the actor's enabled flag; the actor is started/stopped via the Redis callback.""" + self._enabled_flags[actor_class].value = enabled + + def _ping_clients(self, actor_name: str): + self._client.connector.send( + MessageEndpoints.builtin_actor_update_notif(actor_name), + BuiltinActorStateUpdatedNotification(actor_name=actor_name), + ) + + def _enabled_changed(self, actor_class: type[MXAutomationActor], enabled: bool): + (self._start_actor(actor_class) if enabled else self._stop_actor(actor_class)) + self._ping_clients(actor_class.__name__) + + def _start_all(self): + for actor_class in self._actor_classes: + if self._enabled_flags[actor_class].value: + self._start_actor(actor_class) + + def _start_actor(self, actor_class: type[MXAutomationActor]): + name = actor_class.__name__ + logger.info(f"Starting {name}") + if actor_class in self._actors_threads_and_stops: + logger.warning(f"Actor {name} is already active!") + return + actor = actor_class(self._client, name=name, exec_id=name) + t = Thread(target=actor.run, name=name) + self._actors_threads_and_stops[actor_class] = (actor, t, actor.stop_event) + t.start() + + def _stop_actor(self, actor_class: type[MXAutomationActor]): + logger.info(f"Stopping {actor_class.__name__}") + if (entry := self._actors_threads_and_stops.get(actor_class)) is None: + logger.warning(f"Actor {actor_class.__name__} is not active!") + return + actor, t, event = entry + event.set() + t.join() + del self._actors_threads_and_stops[actor_class] + del actor + + def shutdown(self): + for flag in self._enabled_flags.values(): + flag.unregister_all() + for actor_class in list(self._actors_threads_and_stops): + self._stop_actor(actor_class) diff --git a/mx_bec/actors/__init__.py b/mx_bec/actors/__init__.py new file mode 100644 index 0000000..c8122db --- /dev/null +++ b/mx_bec/actors/__init__.py @@ -0,0 +1,21 @@ +import inspect + +from .core import MXAutomationActor + + +def all_actor_classes() -> list[type[MXAutomationActor]]: + """Every concrete MXAutomationActor subclass defined in this package, in definition order.""" + # Importing the module is what registers its classes as subclasses. + from . import mx_automation # noqa: F401 + + found: list[type[MXAutomationActor]] = [] + pending = list(MXAutomationActor.__subclasses__()) + while pending: + cls = pending.pop(0) + pending.extend(cls.__subclasses__()) + if not inspect.isabstract(cls) and cls not in found: + found.append(cls) + return found + + +__all__ = ["MXAutomationActor", "all_actor_classes"] diff --git a/mx_bec/actors/core.py b/mx_bec/actors/core.py new file mode 100644 index 0000000..bc4bf58 --- /dev/null +++ b/mx_bec/actors/core.py @@ -0,0 +1,70 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Any, ClassVar + +from bec_lib.endpoints import EndpointInfo +from bec_lib.logger import bec_logger +from bec_server.actors.actor import SubscriptionActor + +from mx_bec.endpoints import ActorEndpoints +from mx_bec.messages import MXMeasurementSequenceMessage + +if TYPE_CHECKING: + from bec_lib.messages import BoolConfigDefaultFalse + from bec_lib.redis_connector import MessageObject + + from mx_bec.service import AareBec + +logger = bec_logger.logger + + +class MXAutomationActor(SubscriptionActor, ABC): + """Base for MX automation actors. + + Subclasses pick the sequence milestones they react to via `default_monitor_endpoints()` + (which must carry `MXMeasurementSequenceMessage`s), and implement `condition` / `action`. + Whenever a successful milestone message arrives it is stored in `last_message` and the + action table is evaluated. + """ + + config_key: ClassVar[str] + """Unique key used to build this actor's config endpoints, e.g. "optical_centering".""" + + def __init__(self, client: AareBec, name: str, exec_id: str): + # TODO aare protocols for aare actors which take only the aare client + self.action_table = {self.condition: self._action} + self.last_message: MXMeasurementSequenceMessage | None = None + super().__init__(client, name, exec_id) + + @classmethod + def config_endpoint(cls) -> EndpointInfo[type[BoolConfigDefaultFalse]]: + """Managed bool controlling whether the actor manager runs this actor.""" + return ActorEndpoints.enabled(cls.config_key) + + def evaluate(self, msg_obj: MessageObject[Any] | None = None, **_): + """Callback for the monitored endpoints. Called with a MessageObject whose value is the + milestone message; evaluates the action table if the step succeeded.""" + if msg_obj is not None: + msg = msg_obj.value + if not isinstance(msg, MXMeasurementSequenceMessage): + logger.warning(f"{self.name} ignoring unexpected message on {msg_obj.topic}: {msg}") + return + self.last_message = msg + if not msg.success: + logger.info(f"{self.name}: step failed for sample {msg.sample_id}, not acting") + return super().evaluate() + + @abstractmethod + def condition(self, client: AareBec) -> bool: + """Whether `action` should run; evaluated after every successful milestone message.""" + + @abstractmethod + def action(self, client: AareBec, sample_id: int) -> None: + """What to do when `.condition()` evaluates `True`.""" + + def _action(self, client: AareBec) -> None: + assert self.last_message is not None + sample_id = self.last_message.sample_id + self.last_message = None + self.action(client, sample_id) diff --git a/mx_bec/actors/mx_automation.py b/mx_bec/actors/mx_automation.py new file mode 100644 index 0000000..01784a4 --- /dev/null +++ b/mx_bec/actors/mx_automation.py @@ -0,0 +1,52 @@ +"""Actors chaining the steps of an automated MX measurement. + +Each actor listens to one milestone of the sequence and kicks off the next step. The actions +are stand-ins for now: they log and immediately publish the next milestone, so the chain can be +exercised end to end on the simulated beamline before the real procedures exist. +""" + +from bec_lib.endpoints import EndpointInfo +from bec_lib.logger import bec_logger + +from mx_bec.actors.core import MXAutomationActor +from mx_bec.endpoints import StateEndpoints +from mx_bec.messages import MXMeasurementSequenceMessage +from mx_bec.service import AareBec + +logger = bec_logger.logger + + +class OnSampleMountedRunOpticalCentering(MXAutomationActor): + """When a sample is mounted, run optical centering. Only runs if mounting reported success.""" + + config_key = "optical_centering_on_mount" + + def default_monitor_endpoints(self) -> set[EndpointInfo[type[MXMeasurementSequenceMessage]]]: + return {StateEndpoints.sample_mounted()} + + def condition(self, client: AareBec) -> bool: + return self.last_message is not None and self.last_message.success + + def action(self, client: AareBec, sample_id: int) -> None: + logger.info(f"{self.name}: running optical centering for sample {sample_id}") + client.tasks.run_optical_centering(sample_id) + + +class OnOpticalCenteringDoneRunXrayCentering(MXAutomationActor): + """When optical centering finished, run X-ray centering. Runs regardless of success.""" + + config_key = "xray_centering_after_optical" + + def default_monitor_endpoints(self) -> set[EndpointInfo[type[MXMeasurementSequenceMessage]]]: + return {StateEndpoints.optical_centering_done()} + + def condition(self, client: AareBec) -> bool: + return self.last_message is not None + + def action(self, client: AareBec, sample_id: int) -> None: + logger.info(f"{self.name}: running X-ray centering for sample {sample_id}") + # TODO: replace with the real centering procedure; publish the milestone from there. + client.connector.set_and_publish( + StateEndpoints.xray_centering_done(), + MXMeasurementSequenceMessage(sample_id=sample_id, success=True), + ) diff --git a/mx_bec/configs/__init__.py b/mx_bec/configs/__init__.py new file mode 100644 index 0000000..15f35b0 --- /dev/null +++ b/mx_bec/configs/__init__.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from bec_lib.client import BECClient + +MX_DEMO_CONFIG = Path(__file__).parent / "mx_demo_config.yaml" + + +def load_mx_demo_config(client: BECClient, force: bool = False) -> None: + """Replace the current BEC session's device config with the simulated MX beamline.""" + if client.config is None: + raise RuntimeError("BEC client is not started") + client.config.update_session_with_file(str(MX_DEMO_CONFIG), force=force) diff --git a/mx_bec/configs/mx_demo_config.yaml b/mx_bec/configs/mx_demo_config.yaml new file mode 100644 index 0000000..80044c7 --- /dev/null +++ b/mx_bec/configs/mx_demo_config.yaml @@ -0,0 +1,105 @@ +############################################################ +# Simulated MX beamline for the AareBEC prototype. +# +# Every device here is a simulation: either from ophyd_devices.sim or from +# mx_bec.devices. Load it into a running BEC with +# from mx_bec.configs import load_mx_demo_config +# load_mx_demo_config(bec) +############################################################ + +############################################################ +####################### Detector ########################### +############################################################ + +eiger: + readoutPriority: async + deviceClass: ophyd_devices.SimCamera + deviceConfig: + device_access: true + deviceTags: + - detector + enabled: true + readOnly: false + softwareTrigger: true + +############################################################ +##################### Sample stages ######################## +############################################################ + +# Aerotech rotation stage: x/y/z translation (mm) under the omega rotation axis (deg). +aerotech: + readoutPriority: baseline + deviceClass: mx_bec.devices.SimAerotechStage + deviceConfig: + deviceTags: + - sample stage + - aerotech + enabled: true + readOnly: false + +# Smargon mini-kappa goniometer head on top of the aerotech: x/y/z (mm), phi/chi (deg). +gonio: + readoutPriority: baseline + deviceClass: mx_bec.devices.SimGoniometer + deviceConfig: + deviceTags: + - sample stage + - goniometer + enabled: true + readOnly: false + +############################################################ +#################### Sample changer ######################## +############################################################ + +robot: + readoutPriority: baseline + deviceClass: mx_bec.devices.SimSampleChanger + deviceConfig: + mount_time: 2.0 + deviceTags: + - sample changer + enabled: true + readOnly: false + +############################################################ +################## Beamline conditions ##################### +############################################################ + +# Settable scalars so that beamline states / actors can be exercised by writing +# to them from the client, e.g. `dev.ring_current.set(0)` to simulate a beam dump. + +ring_current: + readoutPriority: monitored + deviceClass: ophyd_devices.sim.sim_signals.SetableSignal + deviceConfig: + value: 400.0 + deviceTags: + - beamline + enabled: true + readOnly: false + +fast_shutter: + readoutPriority: baseline + deviceClass: ophyd_devices.sim.sim_signals.SetableSignal + deviceConfig: + value: 0 + deviceTags: + - beamline + enabled: true + readOnly: false + +energy: + readoutPriority: baseline + deviceClass: ophyd_devices.SimPositioner + deviceConfig: + delay: 1 + limits: + - 5.0 + - 20.0 + tolerance: 0.001 + update_frequency: 400 + deviceTags: + - beamline + enabled: true + readOnly: false diff --git a/mx_bec/constants.py b/mx_bec/constants.py new file mode 100644 index 0000000..3e88485 --- /dev/null +++ b/mx_bec/constants.py @@ -0,0 +1,6 @@ +from enum import StrEnum + + +class AareBecWorkflowState(StrEnum): + IDLE = "IDLE" + SAMPLE_MOUNTED = "SAMPLE_MOUNTED" diff --git a/mx_bec/devices/__init__.py b/mx_bec/devices/__init__.py index e69de29..5c17ef7 100644 --- a/mx_bec/devices/__init__.py +++ b/mx_bec/devices/__init__.py @@ -0,0 +1,4 @@ +from .sim_sample_changer import RobotState, SimSampleChanger +from .sim_stages import SimAerotechStage, SimGoniometer + +__all__ = ["RobotState", "SimAerotechStage", "SimGoniometer", "SimSampleChanger"] diff --git a/mx_bec/devices/aerotech.py b/mx_bec/devices/aerotech.py new file mode 100644 index 0000000..f51bb50 --- /dev/null +++ b/mx_bec/devices/aerotech.py @@ -0,0 +1,137 @@ +from typing import ClassVar + +from bec_lib.logger import bec_logger +from ophyd import Component as Cpt +from ophyd import Kind +from ophyd.device import Device +from ophyd.signal import Signal +from requests import RequestException + +from .http import ( + TIMESTAMP_ID, + HttpDeviceControllerWithConfigVelocity, + HttpDeviceSignal, + HttpOphydDevice, + HttpVelocitySignal, + get_controller, +) + +logger = bec_logger.logger + + +class ValidatedHttpParams(Device): + """Group of config signals making up one AareScan request body. Whenever a config signal + changes, the body is validated by the server at `validate_endpoint` and the result is + published on the `valid` and `message` signals.""" + + validate_endpoint: ClassVar[str] + + valid = Cpt(Signal, kind=Kind.normal, value=False) + message = Cpt(Signal, kind=Kind.normal, value="") + + def __init__(self, prefix="", *, name, **kwargs): + super().__init__(prefix, name=name, **kwargs) + self._controller = get_controller(self) + for attr in self.configuration_attrs: + getattr(self, attr).subscribe(self._on_config_change, run=False) + + def request_body(self) -> dict: + return {attr: getattr(self, attr).get() for attr in self.configuration_attrs} + + def validate(self) -> tuple[bool, str]: + """Validate the current configuration, update `valid`/`message` and return them.""" + try: + result = self._controller.validate(self.validate_endpoint, self.request_body()) + except RequestException as exc: + result = False, f"Could not reach {self.validate_endpoint}: {exc}" + valid, message = result + if not valid: + logger.warning(f"{self.name} is invalid: {message}") + self.valid.put(valid) + self.message.put(message) + return result + + def _on_config_change(self, **kwargs): + self.validate() + + +class GridscanParameters(ValidatedHttpParams): + validate_endpoint = "/validate/grid_scan" + + grid_elem_count_y = Cpt(Signal, kind=Kind.config, dtype=int, value=0) + grid_elem_size_y_um = Cpt(Signal, kind=Kind.config, dtype=float, value=0.0) + grid_elem_size_x_um = Cpt(Signal, kind=Kind.config, dtype=float, value=0.0) + grid_elem_count_x = Cpt(Signal, kind=Kind.config, dtype=int, value=0) + time_per_element_sec = Cpt(Signal, kind=Kind.config, dtype=float, value=0.0) + + +class ScreeningParameters(ValidatedHttpParams): + validate_endpoint = "/validate/screening" + + rotation_deg = Cpt(Signal, kind=Kind.config, dtype=float, value=0.0) + wedge_deg = Cpt(Signal, kind=Kind.config, dtype=float, value=0.0) + time_per_element_sec = Cpt(Signal, kind=Kind.config, dtype=float, value=0.0) + steps = Cpt(Signal, kind=Kind.config, dtype=int, value=0) + + +class RotationScanParameters(ValidatedHttpParams): + validate_endpoint = "/validate/rotation_scan" + + rotation_deg = Cpt(Signal, kind=Kind.config, dtype=float, value=0.0) + total_time_sec = Cpt(Signal, kind=Kind.config, dtype=float, value=0.0) + start_pos_deg = Cpt(Signal, kind=Kind.config, dtype=float, value=0.0) + + +class AerotechController(HttpDeviceControllerWithConfigVelocity): + _readback_endpoint = "/status" + _target_endpoint = "/position" + + def __init__(self, *, prefix, **kwargs): + self._readbacks: dict[str, dict[str, float | bool]] = {} + super().__init__(prefix=prefix, **kwargs) + + def put(self, axis: str, val: float, velocity: float | None = None): + """Move the axis. If no velocity is given, the axis' velocity signal (if any) is used.""" + self._rest_post(body=self.params_for_move(axis, val, velocity)) + + def get_readback(self, axis_id: str) -> tuple[float, float] | None: + with self._readback_lock: + if axis_id not in self._readbacks or TIMESTAMP_ID not in self._readbacks: + return None + return self._readbacks.get(axis_id)["pos"], self._readbacks.get(TIMESTAMP_ID) # type: ignore + + +class Aerotech(HttpOphydDevice): + controller_class = AerotechController + + gridscan_config = Cpt(GridscanParameters) + screening_config = Cpt(ScreeningParameters) + rotation_config = Cpt(RotationScanParameters) + + x = Cpt(HttpDeviceSignal, axis_identifier="x", tolerance=0.01) + y = Cpt(HttpDeviceSignal, axis_identifier="y", tolerance=0.01) + z = Cpt(HttpDeviceSignal, axis_identifier="z", tolerance=0.01) + u = Cpt(HttpDeviceSignal, axis_identifier="u", tolerance=0.01) + vel_x_mm_s = Cpt(HttpVelocitySignal, axis_identifier="x", param_name="vel_x_mm_s") + vel_y_mm_s = Cpt(HttpVelocitySignal, axis_identifier="y", param_name="vel_y_mm_s") + vel_z_mm_s = Cpt(HttpVelocitySignal, axis_identifier="z", param_name="vel_z_mm_s") + vel_u_deg_s = Cpt(HttpVelocitySignal, axis_identifier="u", param_name="vel_u_deg_s") + + def wait_for_connection(self, **kwargs): # type: ignore + ret = super().wait_for_connection(**kwargs) + # Config signals only validate on change; publish the state of the initial values too. + for config in (self.gridscan_config, self.screening_config, self.rotation_config): + config.validate() + return ret + + +def _test(): + a = Aerotech(name="aerotech", prefix="http://mx-x10sa-queue-01:5234") + a.wait_for_connection() + return a + + +if __name__ == "__main__": + aerotech = _test() + print(aerotech.read()) + aerotech.stop() diff --git a/mx_bec/devices/http.py b/mx_bec/devices/http.py new file mode 100644 index 0000000..0e69acd --- /dev/null +++ b/mx_bec/devices/http.py @@ -0,0 +1,253 @@ +import time +from abc import ABC, abstractmethod +from threading import Event, RLock, Thread +from typing import Any + +from bec_lib.logger import bec_logger +from ophyd import Kind, OphydObject, Signal +from ophyd_devices import PSIDeviceBase +from ophyd_devices.utils.socket import SocketSignal +from requests import Response, Session + +logger = bec_logger.logger + +TIMESTAMP_ID = "__timestamp" +_POLL_INTERVAL_SLOW = 0.1 + + +def get_controller(obj: OphydObject) -> "HttpDeviceController": + """Return the HttpDeviceController of the root device of `obj`.""" + controller: HttpDeviceController | None = getattr(obj.root, "controller", None) + if controller is None: + raise TypeError( + f"{type(obj).__name__} must be used in a device with a HttpDeviceController" + ) + return controller + + +class HttpRestError(Exception): + """Error for rest calls from a HttpRestSignal.""" + + def __init__(self, resp: Response, *args: object, value: Any | None = None) -> None: + method, url = resp.request.method, resp.request.url + data = f"{value!s} to " if value is not None else "" + super().__init__( + f"Could not {method} {data}{url}. Code: {resp.status_code}. Reason: {resp.reason}.", + *args, + ) + + +class HttpDeviceController(OphydObject, ABC): + """Controller to consolidate polling loops and other REST calls for devices which communicate + with HTTP REST interfaces""" + + _readback_endpoint: str + _target_endpoint: str + + def __init__(self, *, prefix, **kwargs): + self._readbacks: dict + self._session = Session() + self._prefix = prefix + self._targets = {} + self._signal_registry: set[str] = set() + self._readback_poll_interval: float = _POLL_INTERVAL_SLOW + + super().__init__(**kwargs) + self._setup_readback() + + def _setup_readback(self): + self._stop_monitor_readback_event = Event() + self._readback_lock = RLock() + self._monitor_readback_thread = Thread( + target=self._monitor, + args=[ + self._readback_endpoint, + self._stop_monitor_readback_event, + self._readback_lock, + self._readbacks, + ], + ) + + def manual_update(self): + self._update_reading(self._readback_endpoint, self._readback_lock, self._readbacks) + + def _update_reading(self, endpoint: str, lock: RLock, buffer: dict): + data = self._rest_get(endpoint) + timestamp = time.monotonic() + with lock: + buffer.update(data) + buffer["__timestamp"] = timestamp + + def _monitor(self, endpoint: str, event: Event, lock: RLock, buffer: dict): + while not event.is_set(): + self._update_reading(endpoint, lock, buffer) + time.sleep(self._readback_poll_interval) + + def _clean_monitor(self): + if self._monitor_readback_thread.is_alive(): + self._stop_monitor_readback_event.set() + self._monitor_readback_thread.join(timeout=2) + if self._monitor_readback_thread.is_alive(): + raise RuntimeError("Failed to clean up Aerotech monitor thread.") + + def register(self, axis_id: str): + self._signal_registry.add(axis_id) + + def _rest_get(self, endpoint): + resp = self._session.get(self._prefix + endpoint) + if not resp.ok: + raise HttpRestError(resp) + return resp.json() + + def _rest_put(self, params: dict | None = None, body: dict | None = None): + resp = self._session.put(self._prefix + self._target_endpoint, params=params, json=body) + if not resp.ok: + raise HttpRestError(resp, value=params) + + def _rest_post( + self, params: dict | None = None, body: dict | None = None, endpoint: str | None = None + ): + endpoint = self._target_endpoint if endpoint is None else endpoint + resp = self._session.post(self._prefix + endpoint, params=params, json=body) + if not resp.ok: + raise HttpRestError(resp, value=params) + + def validate(self, endpoint: str, body: dict) -> tuple[bool, str]: + """POST `body` to a validation endpoint. Returns (valid, message); the message is the + server's error text for an invalid request and empty otherwise.""" + resp = self._session.post(self._prefix + endpoint, json=body) + if resp.ok: + return True, "" + try: + message = resp.json() + except ValueError: + message = resp.text + return False, str(message) + + def start_monitor(self): + """Start or restart the automonitor thread.""" + self._clean_monitor() + self._setup_readback() + self._monitor_readback_thread.start() + + def monitor_stopped(self): + return not self._monitor_readback_thread.is_alive() + + def put(self, axis: str, val: float): + self._rest_put({axis: val}) + + @abstractmethod + def get_readback(self, axis_id: str) -> tuple[float, float] | None: + """Return a tuple (reading, timestamp) if the axis_id exists""" + + def stop(self): + # There doesn't appear to be a stop endpoint on the server + # Best effort: set the target to the current position + pass + # TODO: self._rest_put(self._readbacks) + + +class HttpDeviceControllerWithConfigVelocity(HttpDeviceController): + """Controller for devices whose move request accepts a per-axis velocity parameter. The velocity + for each axis is held in a registered HttpVelocitySignal and sent along with every move.""" + + def __init__(self, *, prefix, **kwargs): + super().__init__(prefix=prefix, **kwargs) + self._velocity_signal_registry: dict[str, HttpVelocitySignal] = {} + + def register_velocity(self, axis_id: str, signal: "HttpVelocitySignal"): + self._velocity_signal_registry[axis_id] = signal + + def get_velocity(self, axis_id: str) -> float | None: + """Return the configured velocity for the axis, or None if it has no velocity signal.""" + if (signal := self._velocity_signal_registry.get(axis_id)) is None: + return None + return signal.get() + + def params_for_move(self, axis: str, val: float, velocity: float | None = None): + """Build the request params for a move. If no explicit velocity is given, the registered + velocity signal for the axis is used if one exists.""" + if (signal := self._velocity_signal_registry.get(axis)) is None: + if velocity is not None: + raise ValueError(f"Axis {axis} has no registered velocity signal") + return {axis: val} + if velocity is None: + velocity = signal.get() + return {axis: val, signal.param_name: velocity} + + +class HttpDeviceSignalBase(SocketSignal): + """Ophyd signal which gets and puts to a REST API rather than EPICS PVs, mediated through the Aerotech + Controller""" + + def __init__(self, *args, axis_identifier: str, **kwargs): + super().__init__(*args, **kwargs) + self._controller = get_controller(self) + self._axis_id = axis_identifier + + +class HttpDeviceSignal(HttpDeviceSignalBase): + def __init__(self, *args, axis_identifier: str, **kwargs): + super().__init__(*args, axis_identifier=axis_identifier, **kwargs) + self._controller.register(self._axis_id) + + def _socket_get(self): # type: ignore + self._readback, self.metadata["timestamp"] = self._controller.get_readback( + self._axis_id + ) or (0.0, 0.0) + return self._readback + + def _socket_set(self, val: float): + self._controller.put(self._axis_id, val) + + def get(self, **kwargs) -> float: + if self._controller.monitor_stopped(): + self._controller.start_monitor() + return super().get(**kwargs) + + +class HttpVelocitySignal(Signal): + """Config signal holding the velocity used for moves of one axis. Putting to it does not talk to + the controller; the value is sent as `param_name` with the next move of the axis.""" + + def __init__( + self, + *args, + axis_identifier: str, + param_name: str, + kind=Kind.config, + dtype=float, + value=1.0, + **kwargs, + ): + super().__init__(*args, kind=kind, dtype=dtype, value=value, **kwargs) + controller = get_controller(self) + if not isinstance(controller, HttpDeviceControllerWithConfigVelocity): + raise TypeError( + "HttpVelocitySignal must be used in a device with a HttpDeviceControllerWithConfigVelocity" + ) + self._controller = controller + self._axis_id = axis_identifier + self.param_name = param_name + self._controller.register_velocity(axis_id=self._axis_id, signal=self) + + +class HttpOphydDevice(PSIDeviceBase): + controller_class: type[HttpDeviceController] + + def __init__( + self, *, name: str, prefix: str = "", scan_info=None, device_manager=None, **kwargs + ): + self.controller = self.controller_class(prefix=prefix) + super().__init__( + name=name, prefix=prefix, scan_info=scan_info, device_manager=device_manager, **kwargs + ) + + def wait_for_connection(self, **kwargs): # type: ignore + self.controller.start_monitor() + self.controller.manual_update() + return super().wait_for_connection(**kwargs) + + def stop(self, *, success: bool = False) -> None: + self.controller.stop() + return super().stop(success=success) diff --git a/mx_bec/devices/sim_sample_changer.py b/mx_bec/devices/sim_sample_changer.py new file mode 100644 index 0000000..b44bb68 --- /dev/null +++ b/mx_bec/devices/sim_sample_changer.py @@ -0,0 +1,108 @@ +"""Simulated MX sample changer robot (TELL-like).""" + +from __future__ import annotations + +import enum +import threading +from typing import ClassVar + +from bec_lib.logger import bec_logger +from ophyd import Component as Cpt +from ophyd import DeviceStatus, Kind +from ophyd_devices.interfaces.base_classes.psi_device_base import DeviceStoppedError, PSIDeviceBase +from ophyd_devices.sim.sim_signals import SetableSignal + +logger = bec_logger.logger + + +class RobotState(enum.IntEnum): + IDLE = 0 + BUSY = 1 + ERROR = 2 + + +class SimSampleChanger(PSIDeviceBase): + """A minimal sample changer: mounts and unmounts a (puck, position) with a configurable delay. + + All signals are integers so that they can be used directly in BEC beamline states + (e.g. `DeviceWithinLimitsState` on `state` or `sample_mounted`). + + >>> robot = SimSampleChanger(name="robot") + >>> robot.mount(puck=1, position=3).wait() + """ + + USER_ACCESS: ClassVar[list[str]] = ["mount", "unmount", "reset"] + + state = Cpt(SetableSignal, value=int(RobotState.IDLE), kind=Kind.hinted) + sample_mounted = Cpt(SetableSignal, value=0, kind=Kind.normal) + mounted_puck = Cpt(SetableSignal, value=0, kind=Kind.normal) + mounted_position = Cpt(SetableSignal, value=0, kind=Kind.normal) + door_closed = Cpt(SetableSignal, value=1, kind=Kind.normal) + + mount_time = Cpt(SetableSignal, value=1.0, kind=Kind.config, doc="Mount/unmount time in s") + + def __init__(self, name: str, *, mount_time: float | None = None, **kwargs): + super().__init__(name=name, **kwargs) + self._mount_time_init = mount_time + self._stop_event = threading.Event() + self._worker: threading.Thread | None = None + + def on_connected(self) -> None: + if self._mount_time_init is not None: + self.mount_time.put(self._mount_time_init) + + def mount(self, puck: int, position: int) -> DeviceStatus: + """Mount the sample at `position` of `puck`. Returns a status that finishes once mounted.""" + return self._run_motion(lambda: self._set_mounted(puck, position)) + + def unmount(self) -> DeviceStatus: + """Unmount the current sample. Returns a status that finishes once the sample is back.""" + return self._run_motion(lambda: self._set_mounted(0, 0)) + + def _set_mounted(self, puck: int, position: int) -> None: + self.mounted_puck.put(puck) + self.mounted_position.put(position) + self.sample_mounted.put(int(puck > 0)) + + def _run_motion(self, on_done) -> DeviceStatus: + # Precondition failures raise instead of returning a failed status: a failed + # DeviceStatus calls device.stop(), which would abort a motion already in flight. + if self.state.get() != RobotState.IDLE: + raise RuntimeError(f"{self.name} is not idle") + if not self.door_closed.get(): + self.state.put(int(RobotState.ERROR)) + raise RuntimeError(f"{self.name}: hutch door is open") + + self.stopped = False + self._stop_event.clear() + self.state.put(int(RobotState.BUSY)) + status = DeviceStatus(self) + + def worker(): + try: + if self._stop_event.wait(timeout=self.mount_time.get()): + raise DeviceStoppedError(f"{self.name} was stopped") + on_done() + except DeviceStoppedError as exc: + logger.warning(f"{self.name} motion aborted: {exc}") + status.set_exception(exc) + else: + status.set_finished() + finally: + self.state.put(int(RobotState.IDLE)) + + self._worker = threading.Thread(target=worker, daemon=True) + self._worker.start() + return status + + def reset(self) -> None: + """Clear an error state.""" + if self.state.get() == RobotState.ERROR: + self.state.put(int(RobotState.IDLE)) + + def on_stop(self) -> None: + self._stop_event.set() + worker = self._worker + # A failed status calls device.stop() from the worker itself; don't join ourselves. + if worker is not None and worker.is_alive() and worker is not threading.current_thread(): + worker.join(timeout=1.0) diff --git a/mx_bec/devices/sim_stages.py b/mx_bec/devices/sim_stages.py new file mode 100644 index 0000000..6c62431 --- /dev/null +++ b/mx_bec/devices/sim_stages.py @@ -0,0 +1,28 @@ +"""Simulated MX sample stages, built from ophyd_devices SimPositioners.""" + +from ophyd import Component as Cpt +from ophyd import Device +from ophyd_devices.sim.sim_positioner import SimPositioner + + +class SimAerotechStage(Device): + """Simulated Aerotech rotation stage: a 3-axis translation under an omega rotation axis. + + omega is unbounded (low == high limit disables the SimPositioner limit check) so that + multi-turn rotation scans are possible; the translations are limited to a few mm. + """ + + x = Cpt(SimPositioner, name="x", limits=[-5, 5]) + y = Cpt(SimPositioner, name="y", limits=[-5, 5]) + z = Cpt(SimPositioner, name="z", limits=[-5, 5]) + omega = Cpt(SimPositioner, name="omega", limits=[0, 0]) + + +class SimGoniometer(Device): + """Simulated Smargon-style goniometer head mounted on top of the Aerotech stage.""" + + x = Cpt(SimPositioner, name="x", limits=[-5, 5]) + y = Cpt(SimPositioner, name="y", limits=[-5, 5]) + z = Cpt(SimPositioner, name="z", limits=[-5, 5]) + phi = Cpt(SimPositioner, name="phi", limits=[0, 0]) + chi = Cpt(SimPositioner, name="chi", limits=[0, 45]) diff --git a/mx_bec/devices/smargopolo_smargon.py b/mx_bec/devices/smargopolo_smargon.py new file mode 100644 index 0000000..29e8b09 --- /dev/null +++ b/mx_bec/devices/smargopolo_smargon.py @@ -0,0 +1,97 @@ +from typing import ClassVar + +import numpy as np +from ophyd import Component as Cpt + +from .http import HttpDeviceController, HttpDeviceSignal, HttpOphydDevice + +_TIMESTAMP_ID = "__timestamp" +_POLL_INTERVAL_SLOW = 0.1 + + +class SmargonController(HttpDeviceController): + """Controller to consolidate polling loops and other REST calls for the smargon""" + + _readback_endpoint = "/readbackSCS" + _target_endpoint = "/targetSCS" + + def __init__(self, *, prefix, **kwargs): + self._readbacks: dict[str, float] = {} + super().__init__(prefix=prefix, **kwargs) + + def get_readback(self, axis_id: str) -> tuple[float, float] | None: + with self._readback_lock: + if axis_id not in self._readbacks or _TIMESTAMP_ID not in self._readbacks: + return None + return self._readbacks.get(axis_id), self._readbacks.get(_TIMESTAMP_ID) # type: ignore + + def put(self, axis: str, val: float): + self._rest_put(params={axis: val}) + + def stop(self): + # There doesn't appear to be a stop endpoint on the server + # Best effort: set the target to the current position + with self._readback_lock: + targets = { + axis: self._readbacks[axis] + for axis in self._signal_registry + if axis in self._readbacks + } + self._rest_put(params=targets) + + +class Smargon(HttpOphydDevice): + USER_ACCESS: ClassVar[list[str]] = ["nudge_in_lab_frame"] + controller_class = SmargonController + + x = Cpt(HttpDeviceSignal, axis_identifier="SHX", tolerance=0.01) + y = Cpt(HttpDeviceSignal, axis_identifier="SHY", tolerance=0.01) + z = Cpt(HttpDeviceSignal, axis_identifier="SHZ", tolerance=0.01) + phi = Cpt(HttpDeviceSignal, axis_identifier="PHI", tolerance=0.01) + chi = Cpt(HttpDeviceSignal, axis_identifier="CHI", tolerance=0.01) + + def nudge_in_lab_frame( + self, x_mm: float, y_mm: float, z_mm: float = 0.0, omega_deg: float = 0.0 + ): + """Apply a relative move in the lab frame (adjusted for the rotation angle, assuming that + the frames are identical when omega = phi = chi = 0). `omega_deg` is the angle of the + rotation stage the smargon sits on (the Aerotech `u` axis), which the smargon does not + know itself.""" + x_mm, y_mm, z_mm = self._lab_frame_offset_to_smargon_nudge(x_mm, y_mm, z_mm, omega_deg) + return ( + self.x.set(self.x.get() + x_mm) + & self.y.set(self.y.get() + y_mm) + & self.z.set(self.z.get() + z_mm) + ) + + def _lab_frame_offset_to_smargon_nudge( + self, x_mm: float, y_mm: float, z_mm: float = 0.0, omega_deg: float = 0.0 + ): + """adjust a move for the rotation angle, assuming that the frames are identical when omega = phi = chi = 0""" + phi = np.radians(np.around(self.phi.get(), decimals=1)) + chi = np.radians(np.around(self.chi.get(), decimals=1)) + omega = np.radians(np.around(omega_deg, decimals=1)) + + co = np.cos(omega) + so = np.sin(omega) + cp = np.cos(phi) + sp = np.sin(phi) + cc = np.cos(chi) + sc = np.sin(chi) + + res_x = ( + -z_mm * co * sp + - y_mm * so * sp + + x_mm * cp * sc + - y_mm * co * cc * cp + + z_mm * so * cc * cp + ) + res_y = ( + -z_mm * co * cp + - y_mm * so * cp + - x_mm * sc * sp + + y_mm * co * cc * sp + - z_mm * so * cc * sp + ) + res_z = -x_mm * cc - y_mm * co * sc + z_mm * so * sc + return res_x, res_y, res_z diff --git a/mx_bec/endpoints.py b/mx_bec/endpoints.py new file mode 100644 index 0000000..d303ef2 --- /dev/null +++ b/mx_bec/endpoints.py @@ -0,0 +1,66 @@ +from bec_lib.endpoints import EndpointInfo, EndpointType, MessageOp +from bec_lib.messages import BoolConfigDefaultFalse + +from mx_bec.messages import MXMeasurementSequenceMessage, OpticalPredictionMessage + + +class StateEndpoints: + """Milestones of the MX measurement sequence, published by whoever completes the step.""" + + @staticmethod + def sample_mounted(): + return EndpointInfo( + endpoint=f"{EndpointType.INFO.value}/mx/sequence/mounted", + message_type=MXMeasurementSequenceMessage, + message_op=MessageOp.SET_PUBLISH, + ) + + @staticmethod + def optical_centering_done(): + return EndpointInfo( + endpoint=f"{EndpointType.INFO.value}/mx/sequence/optical_centering_done", + message_type=MXMeasurementSequenceMessage, + message_op=MessageOp.SET_PUBLISH, + ) + + @staticmethod + def xray_centering_done(): + return EndpointInfo( + endpoint=f"{EndpointType.INFO.value}/mx/sequence/xray_centering_done", + message_type=MXMeasurementSequenceMessage, + message_op=MessageOp.SET_PUBLISH, + ) + + @staticmethod + def rotation_done(): + return EndpointInfo( + endpoint=f"{EndpointType.INFO.value}/mx/sequence/rotation_done", + message_type=MXMeasurementSequenceMessage, + message_op=MessageOp.SET_PUBLISH, + ) + + +class ActorEndpoints: + """Per-actor configuration, keyed by the actor's `config_key`.""" + + @staticmethod + def enabled(actor_key: str): + """Managed bool: whether the AareActorManager should keep this actor running. + Same shape as MessageEndpoints.scan_interlock_enabled(), so it works with RedisConfigValue. + """ + return EndpointInfo( + endpoint=f"{EndpointType.USER.value}/actor/mx/{actor_key}/config/enabled", + message_type=BoolConfigDefaultFalse, + message_op=MessageOp.STREAM, + ) + + +class DataAnalysisEndpoints: + @staticmethod + def optical_prediction(): + """Stream for image analysis predictions (for optical centering, grid scan parameters...)""" + return EndpointInfo( + endpoint=f"{EndpointType.USER.value}/mx/analysis/optical_prediction", + message_type=OpticalPredictionMessage, + message_op=MessageOp.STREAM, + ) diff --git a/mx_bec/main.py b/mx_bec/main.py new file mode 100644 index 0000000..a34a81f --- /dev/null +++ b/mx_bec/main.py @@ -0,0 +1,32 @@ +# This file is the entry point for the AareBEC service. +# It is called either by the aare-bec-proto entry point or directly from the command line. +import threading + +from bec_lib.bec_service import parse_cmdline_args +from bec_lib.logger import bec_logger +from bec_lib.redis_connector import RedisConnector + +from mx_bec.service import AareBec + +logger = bec_logger.logger +bec_logger.level = bec_logger.LOGLEVEL.INFO + + +def main(): + """ + Launch the AareBEC service. + """ + _, _, config = parse_cmdline_args() + + service = AareBec(config, RedisConnector) + service.start() + try: + event = threading.Event() + logger.success("Started AareBec") + event.wait() + except KeyboardInterrupt: + service.shutdown() + + +if __name__ == "__main__": + main() diff --git a/mx_bec/messages.py b/mx_bec/messages.py new file mode 100644 index 0000000..9b6f514 --- /dev/null +++ b/mx_bec/messages.py @@ -0,0 +1,24 @@ +import time +from typing import ClassVar + +from aarelcinfer_client.models import LatestPredictionModel +from bec_lib.messages import BECMessage +from pydantic import Field + + +class MXMeasurementSequenceMessage(BECMessage): + """Published when a step of the MX measurement sequence finishes for a sample.""" + + msg_type: ClassVar[str] = "mx_measurement_sequence_message" + + sample_id: int + success: bool + + +class OpticalPredictionMessage(BECMessage): + """The latest optical image analysis prediction""" + + msg_type: ClassVar[str] = "mx_optical_prediction_message" + + timestamp: float = Field(default_factory=time.time) + prediction: LatestPredictionModel diff --git a/mx_bec/optical_centering.py b/mx_bec/optical_centering.py new file mode 100644 index 0000000..82edd61 --- /dev/null +++ b/mx_bec/optical_centering.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import numpy as np +from aarelcinfer_client import Client as AareLcClient +from aarelcinfer_client.models import LatestPredictionModel +from bec_lib.logger import bec_logger + +from mx_bec.endpoints import DataAnalysisEndpoints +from mx_bec.messages import OpticalPredictionMessage + +if TYPE_CHECKING: + from mx_bec.service import AareBec + +logger = bec_logger.logger + + +class OpticalPrediction: + def __init__(self, client: AareBec): + self._client = client + self._aarelc_client = AareLcClient(base_url=self._client.aare_config.aarelc_infer.host) + + def get_latest(self): + response = self._aarelc_client.request("GET", "/predictions/latest").json() + return LatestPredictionModel.model_validate(response) + + def get_target_point_px(self): + """Retry up to n times to get a target point""" + max_tries = self._client.aare_config.retries.aarelc_fetch_target_point + tries, latest = 0, self.get_latest() + while tries < max_tries: + if latest.target_point is not None: + return latest.target_point + latest = self.get_latest() + tries += 1 + logger.warning(f"Failed to get a target point from AareLC in {max_tries} tries.") + return None + + def get_target_point_offset_mm(self): + """Get the predicted target from the camera image and convert it to an x,y offset in mm""" + if (target_px := self.get_target_point_px()) is None: + return None + zoom = self._client.devices.zoom + a = self._client.config.camera.translation_factor_a + b = self._client.config.camera.translation_factor_b + base_pixel_in_mm = 1.0 / (b * np.exp(a * zoom)) + adjusted_pixel_in_mm = ( + base_pixel_in_mm * self._client.aare_config.camera.lens_magnification_multiplier + ) + return target_px.x * adjusted_pixel_in_mm, target_px.y * adjusted_pixel_in_mm + + def update_latest(self): + latest = self.get_latest() + logger.debug(f"Updating latest prediction to {latest}") + self._client.connector.xadd( + DataAnalysisEndpoints.optical_prediction(), + msg_dict={"data": OpticalPredictionMessage(prediction=latest)}, + max_size=1, + ) diff --git a/mx_bec/service.py b/mx_bec/service.py new file mode 100644 index 0000000..aadf19c --- /dev/null +++ b/mx_bec/service.py @@ -0,0 +1,98 @@ +from __future__ import annotations + +import os +from typing import TYPE_CHECKING + +from aare_config import AareConfigClient +from bec_lib import messages +from bec_lib.client import BECClient +from bec_lib.logger import bec_logger + +from mx_bec.actor_manager import AareActorManager +from mx_bec.constants import AareBecWorkflowState +from mx_bec.devices.smargopolo_smargon import Smargon +from mx_bec.endpoints import StateEndpoints +from mx_bec.messages import MXMeasurementSequenceMessage +from mx_bec.optical_centering import OpticalPrediction + +if TYPE_CHECKING: + from bec_lib.redis_connector import RedisConnector + from bec_lib.service_config import ServiceConfig + + +logger = bec_logger.logger + + +class AareBec(BECClient): + """Custom MX BEC client, managing automation tasks and data flow.""" + + def __init__( + self, config: ServiceConfig, connector_cls: type[RedisConnector], **kwargs + ) -> None: + if (config_redis_url := os.environ.get("CONFIG_REDIS_URL")) is None: + raise RuntimeError( + "No address for redis config client specified. " + "Set CONFIG_REDIS_URL to 'mx--queue-01'" + "if you want to create an AareBec client" + ) + super().__init__(config, connector_cls, name="AareBec", **kwargs) + self.aare_config = AareConfigClient(redis_url=config_redis_url, key_prefix="config") + self.workflow_state = AareBecWorkflowState.IDLE + self.actor_manager: AareActorManager | None = None + self.optical_prediction = OpticalPrediction(client=self) + self.tasks = MxTasks(self) + + def start(self): + super().start() + self._start_actor_manager() + self.status = messages.BECStatus.RUNNING + + @property + def devices(self): + if self.device_manager is None: + raise RuntimeError("You must start the client before trying to access devices") + return self.device_manager.devices + + def _start_actor_manager(self): + self.actor_manager = AareActorManager(self) + + def shutdown(self, per_thread_timeout_s: float | None = None) -> None: + """shutdown the service""" + if self.actor_manager is not None: + self.actor_manager.shutdown() + self.actor_manager = None + super().shutdown(per_thread_timeout_s) + + +class MxTasks: + """Holder for operations on mx beamlines. Probably needs to be reconsidered + or at least moved to its own module""" + + def __init__(self, client: AareBec): + self._client = client + + def run_optical_centering(self, sample_id: int): + """Rotate the Aerotech to each angle from the config, update the optical centering + prediction and tell the Smargon to move there. Publishes the `optical_centering_done` + milestone, as failed if no target can be obtained or a move fails.""" + smargon: Smargon = self._client.devices.smargon + aerotech = self._client.devices.aerotech + try: + for angle in self._client.aare_config.optical_centering.angles: + aerotech.u.set(angle).wait() + if (target := self._client.optical_prediction.get_target_point_offset_mm()) is None: + logger.warning("No target point obtained from AareLc") + self._publish_optical_centering_done(sample_id, success=False) + return + smargon.nudge_in_lab_frame(*target, omega_deg=angle).wait() + except Exception: + logger.exception(f"Optical centering of sample {sample_id} failed") + self._publish_optical_centering_done(sample_id, success=False) + raise + self._publish_optical_centering_done(sample_id, success=True) + + def _publish_optical_centering_done(self, sample_id: int, *, success: bool): + self._client.connector.set_and_publish( + StateEndpoints.optical_centering_done(), + MXMeasurementSequenceMessage(sample_id=sample_id, success=success), + ) diff --git a/mx_bec/states/__init__.py b/mx_bec/states/__init__.py new file mode 100644 index 0000000..67dc5a3 --- /dev/null +++ b/mx_bec/states/__init__.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from numbers import Real +from typing import Annotated, ClassVar, cast + +from bec_lib import messages +from bec_lib.bl_states import DeviceBeamlineState, DeviceStateConfig +from bec_lib.scan_args import ScanArgument + + +class DeviceEqualsStateConfig(DeviceStateConfig): + """Configuration for a state that is valid while a device signal equals a target value.""" + + state_type: ClassVar[str] = "DeviceEqualsState" + + target: Annotated[ + float, + ScanArgument(display_name="Target", description="Value the signal must have to be valid."), + ] + + +class DeviceEqualsState(DeviceBeamlineState[DeviceEqualsStateConfig]): + """Valid while the monitored signal equals `target`, invalid otherwise.""" + + CONFIG_CLASS = DeviceEqualsStateConfig + + def evaluate( + self, msg: messages.DeviceMessage, *args, **kwargs + ) -> messages.BeamlineStateMessage: + config = cast(DeviceEqualsStateConfig, self.config) + signal_name = cast(str, self.signal_name) + device = self.device_obj.dotted_name + val = msg.signals.get(signal_name, {}).get("value", None) + if not isinstance(val, Real): + return messages.BeamlineStateMessage( + name=config.name, + status="invalid", + label=f"Device {device}: {signal_name} is not a number", + ) + if val == config.target: + return messages.BeamlineStateMessage( + name=config.name, status="valid", label=f"Device {device} == {config.target}" + ) + return messages.BeamlineStateMessage( + name=config.name, + status="invalid", + label=f"Device {device} is {val}, expected {config.target}", + ) + + +__all__ = ["DeviceEqualsState", "DeviceEqualsStateConfig"] diff --git a/pyproject.toml b/pyproject.toml index c2d5587..1f9b9bf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,12 +12,23 @@ classifiers = [ "Programming Language :: Python :: 3", "Topic :: Scientific/Engineering", ] -dependencies = [] +dependencies = [ + "aarecommon", + "aare_config", + "aarelcinfer_client==0.1.1a8", + "bec_lib>=3.130.3", + "bec-server>=3.130.3", + "bec-ipython-client>=3.130.3", + "ophyd_devices>=1.46", + "pydantic>=2.11", +] [project.optional-dependencies] dev = [ "black", "copier", + "basedpyright", + "ruff>=0.15", "isort", "coverage", "pylint", @@ -25,6 +36,14 @@ dev = [ "pytest-random-order", "ophyd_devices", "bec_server", + "pytest", + "pytest-cov", + "pytest-mock", + "pytest-asyncio", + "pytest-timeout", + "fakeredis[lua]", + "fastapi", + "uvicorn", ] [tool.hatch.build.targets.wheel] diff --git a/tests/unit/mock_smargopolo.py b/tests/unit/mock_smargopolo.py new file mode 100644 index 0000000..41f1ca2 --- /dev/null +++ b/tests/unit/mock_smargopolo.py @@ -0,0 +1,160 @@ +"""A mock smargopolo REST interface with mock motors, for testing devices against. + +Adapted from pxii_bec/tests/tests_devices/mock_smargopolo.py. +Run it standalone with `python mock_smargopolo.py` or in-process via `run_in_thread()`. +""" + +import asyncio +import random +import socket +import time +from collections.abc import Iterable +from contextlib import asynccontextmanager +from threading import Thread +from typing import Annotated + +import uvicorn +from fastapi import FastAPI, HTTPException, Query, Request + +AxisQuery = Annotated[list[str] | None, Query()] + +AXES = ["SHX", "SHY", "SHZ", "PHI", "CHI"] + + +class Motor: + def __init__(self, velocity: float = 1.0, position: float = 0.0): + self.position = position + self.target = position + self.velocity = velocity + self.moving = False + self._last_update = time.monotonic() + + def update(self): + now = time.monotonic() + dt = now - self._last_update + self._last_update = now + + if not self.moving: + return + + jitter_factor = random.random() * 0.05 - 0.025 # +- 2.5% jitter in step + distance = self.target - self.position + direction = 1 if distance > 0 else -1 + step = direction * self.velocity * dt + + if abs(step) >= abs(distance): + self.position = self.target + (step * jitter_factor) + self.moving = False + else: + self.position += step * (1 + jitter_factor) + + +def make_motors() -> dict[str, Motor]: + return { + "SHX": Motor(velocity=3), + "SHY": Motor(velocity=2.5), + "SHZ": Motor(velocity=2), + "PHI": Motor(velocity=1.0), + "CHI": Motor(velocity=0.7), + } + + +motors: dict[str, Motor] = make_motors() + + +@asynccontextmanager +async def lifespan(app: FastAPI): + async def updater(): + while True: + for motor in motors.values(): + motor.update() + await asyncio.sleep(0.02) # 50 Hz update loop + + task = asyncio.create_task(updater()) + yield + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + + +app = FastAPI(lifespan=lifespan) + + +def validate_axes(axes: Iterable[str] | None) -> list[str]: + if axes is None: + return AXES + for a in axes: + if a not in AXES: + raise HTTPException(status_code=404, detail=f"Unknown axis: {a}") + return list(axes) + + +@app.get("/readbackSCS") +async def readback_scs(axis: AxisQuery = None): + selected_axes = validate_axes(axis) + return {ax: motors[ax].position for ax in selected_axes} + + +@app.get("/targetSCS") +async def get_target_scs(axis: AxisQuery = None): + selected_axes = validate_axes(axis) + return {ax: motors[ax].target for ax in selected_axes} + + +@app.put("/targetSCS") +async def target_scs(req: Request): + targets = {ax: float(t) for ax, t in req.query_params.items()} + selected_axes = validate_axes(targets.keys()) + + for a in selected_axes: + motor = motors[a] + motor.update() + motor.target = targets[a] + motor.moving = True + + return {"targets": targets, "message": "Move started"} + + +def free_port() -> int: + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +class MockSmargopolo: + """The mock server running in a background thread, for use in tests.""" + + def __init__(self, port: int | None = None): + self.port = port if port is not None else free_port() + self.url = f"http://127.0.0.1:{self.port}" + self._server = uvicorn.Server( + uvicorn.Config(app, host="127.0.0.1", port=self.port, log_level="warning") + ) + self._thread = Thread(target=self._server.run, daemon=True) + + def start(self, timeout: float = 5.0): + motors.clear() + motors.update(make_motors()) + self._thread.start() + deadline = time.monotonic() + timeout + while not self._server.started: + if time.monotonic() > deadline: + raise TimeoutError("Mock smargopolo did not start") + time.sleep(0.01) + return self + + def stop(self): + self._server.should_exit = True + self._thread.join(timeout=5) + + def __enter__(self): + return self.start() + + def __exit__(self, *exc): + self.stop() + + +if __name__ == "__main__": + uvicorn.run(app, host="0.0.0.0", port=8000, reload=False) diff --git a/tests/unit/test_actor_manager.py b/tests/unit/test_actor_manager.py new file mode 100644 index 0000000..fcc76e6 --- /dev/null +++ b/tests/unit/test_actor_manager.py @@ -0,0 +1,119 @@ +from unittest.mock import MagicMock, patch + +import pytest +from bec_lib.endpoints import EndpointInfo + +from aare_bec_proto.actor_manager import AareActorManager +from aare_bec_proto.actors import all_actor_classes +from aare_bec_proto.actors.core import MXAutomationActor +from aare_bec_proto.actors.mx_automation import ( + OnOpticalCenteringDoneRunXrayCentering, + OnSampleMountedRunOpticalCentering, +) +from aare_bec_proto.messages import MXMeasurementSequenceMessage + + +class FakeConfigValue: + """Stand-in for RedisConfigValue: a bool with subscribers, no Redis.""" + + initial = False # value "found in Redis" on construction + + def __init__(self, connector, endpoint, wait_for_writes=True): + self.endpoint = endpoint + self._value = self.initial + self._cbs = [] + self.unregistered = False + + @property + def value(self): + return self._value + + @value.setter + def value(self, value): + self._value = value + for cb in self._cbs: + cb(value) + + def subscribe(self, cb): + self._cbs.append(cb) + + def unregister_all(self): + self.unregistered = True + + +class DummyActor(MXAutomationActor): + config_key = "dummy" + + def default_monitor_endpoints(self) -> set[EndpointInfo[type[MXMeasurementSequenceMessage]]]: + return set() + + def condition(self, client) -> bool: + return True + + def action(self, client) -> None: + pass + + +@pytest.fixture +def manager(): + with patch("aare_bec_proto.actor_manager.RedisConfigValue", FakeConfigValue): + client = MagicMock() + mgr = AareActorManager(client, actor_classes=[DummyActor]) + yield mgr, client + mgr.shutdown() + + +def test_all_actor_classes_finds_concrete_subclasses(): + classes = all_actor_classes() + assert OnSampleMountedRunOpticalCentering in classes + assert OnOpticalCenteringDoneRunXrayCentering in classes + assert MXAutomationActor not in classes + assert len({c.config_key for c in classes}) == len(classes), "config keys must be unique" + + +def test_default_manager_manages_all_actors(): + with patch("aare_bec_proto.actor_manager.RedisConfigValue", FakeConfigValue): + mgr = AareActorManager(MagicMock()) + assert mgr.actor_classes == all_actor_classes() + assert mgr.running == [] + + +def test_disabled_actor_is_not_started(manager): + mgr, _ = manager + assert not mgr.is_enabled(DummyActor) + assert mgr.running == [] + + +def test_enabling_starts_and_disabling_stops_actor(manager): + mgr, client = manager + mgr.set_enabled(DummyActor, True) + assert mgr.running == [DummyActor] + actor, thread, _ = mgr._actors_threads_and_stops[DummyActor] + assert isinstance(actor, DummyActor) + assert thread.is_alive() + assert client.connector.send.called # clients were pinged + + mgr.set_enabled(DummyActor, False) + assert mgr.running == [] + assert not thread.is_alive() + + +def test_actor_enabled_at_startup_is_started(): + with ( + patch("aare_bec_proto.actor_manager.RedisConfigValue", FakeConfigValue), + patch.object(FakeConfigValue, "initial", True), + ): + mgr = AareActorManager(MagicMock(), actor_classes=[DummyActor]) + try: + assert mgr.running == [DummyActor] + finally: + mgr.shutdown() + assert mgr.running == [] + + +def test_shutdown_unregisters_flags(manager): + mgr, _ = manager + mgr.set_enabled(DummyActor, True) + mgr.shutdown() + assert mgr.running == [] + assert all(flag.unregistered for flag in mgr._enabled_flags.values()) diff --git a/tests/unit/test_actors.py b/tests/unit/test_actors.py new file mode 100644 index 0000000..5f9ebfd --- /dev/null +++ b/tests/unit/test_actors.py @@ -0,0 +1,85 @@ +from unittest.mock import MagicMock + +import pytest +from bec_lib.endpoints import MessageOp +from bec_lib.messages import BoolConfigDefaultFalse +from bec_lib.redis_connector import MessageObject + +from mx_bec.actors.mx_automation import ( + OnOpticalCenteringDoneRunXrayCentering, + OnSampleMountedRunOpticalCentering, +) +from mx_bec.endpoints import StateEndpoints +from mx_bec.messages import MXMeasurementSequenceMessage +from mx_bec.service import MxTasks + + +@pytest.fixture +def client(): + return MagicMock() + + +def _msg_obj( + endpoint, sample_id: int, success: bool +) -> MessageObject[MXMeasurementSequenceMessage]: + return MessageObject( + topic=endpoint.endpoint, + value=MXMeasurementSequenceMessage(sample_id=sample_id, success=success), + ) + + +def test_config_endpoint_is_a_managed_bool_stream(): + ep = OnSampleMountedRunOpticalCentering.config_endpoint() + assert ep.message_op == MessageOp.STREAM + assert ep.message_type is BoolConfigDefaultFalse + assert OnSampleMountedRunOpticalCentering.config_key in ep.endpoint + + +def test_actor_subscribes_to_its_milestone(client): + OnSampleMountedRunOpticalCentering(client, name="a", exec_id="a") + registered = {call.args[0].endpoint for call in client.connector.register.call_args_list} + assert StateEndpoints.sample_mounted().endpoint in registered + + +def test_successful_milestone_triggers_next_step(client): + actor = OnSampleMountedRunOpticalCentering(client, name="a", exec_id="a") + actor.evaluate(_msg_obj(StateEndpoints.sample_mounted(), sample_id=42, success=True)) + + client.tasks.run_optical_centering.assert_called_once_with(42) + assert actor.last_message is None + + +def test_failed_milestone_does_not_trigger(client): + actor = OnSampleMountedRunOpticalCentering(client, name="a", exec_id="a") + actor.evaluate(_msg_obj(StateEndpoints.sample_mounted(), sample_id=42, success=False)) + client.tasks.run_optical_centering.assert_not_called() + client.connector.set_and_publish.assert_not_called() + + +def test_unexpected_message_is_ignored(client): + actor = OnSampleMountedRunOpticalCentering(client, name="a", exec_id="a") + actor.evaluate(MessageObject(topic="x", value=BoolConfigDefaultFalse())) + client.tasks.run_optical_centering.assert_not_called() + client.connector.set_and_publish.assert_not_called() + + +def test_actors_chain(client): + """sample mounted -> optical centering -> xray centering: each actor consumes what the previous + step publishes. Uses the real MxTasks with a mocked prediction and smargon.""" + client.tasks = MxTasks(client) + client.config.optical_centering.angles = [0.0] + client.optical_prediction.get_target_point_offset_mm.return_value = (0.1, 0.2) + first = OnSampleMountedRunOpticalCentering(client, name="a", exec_id="a") + second = OnOpticalCenteringDoneRunXrayCentering(client, name="b", exec_id="b") + + first.evaluate(_msg_obj(StateEndpoints.sample_mounted(), sample_id=7, success=True)) + client.devices.aerotech.u.set.assert_called_once_with(0.0) + client.devices.smargon.nudge_in_lab_frame.assert_called_once_with(0.1, 0.2, omega_deg=0.0) + endpoint, msg = client.connector.set_and_publish.call_args.args + assert endpoint.endpoint == StateEndpoints.optical_centering_done().endpoint + assert msg == MXMeasurementSequenceMessage(sample_id=7, success=True) + second.evaluate(MessageObject(topic=endpoint.endpoint, value=msg)) + + endpoint, msg = client.connector.set_and_publish.call_args.args + assert endpoint.endpoint == StateEndpoints.xray_centering_done().endpoint + assert msg.sample_id == 7 diff --git a/tests/unit/test_demo_config.py b/tests/unit/test_demo_config.py new file mode 100644 index 0000000..6a3a5b2 --- /dev/null +++ b/tests/unit/test_demo_config.py @@ -0,0 +1,13 @@ +from ophyd_devices.utils.static_device_test import StaticDeviceTest + +from mx_bec.configs import MX_DEMO_CONFIG + + +def test_all_demo_devices_construct_and_connect(): + """Instantiate every device in the demo config the way the device server would.""" + results = StaticDeviceTest(config_file=str(MX_DEMO_CONFIG)).run_with_list_output( + connect=True, timeout_per_device=10 + ) + failed = {r.name: r.message for r in results if not r.success} + assert not failed, failed + assert {r.name for r in results} >= {"eiger", "aerotech", "gonio", "robot"} diff --git a/tests/unit/test_devices.py b/tests/unit/test_devices.py new file mode 100644 index 0000000..764d72d --- /dev/null +++ b/tests/unit/test_devices.py @@ -0,0 +1,71 @@ +import pytest +from bec_server.device_server.tests.utils import DMMock +from ophyd_devices.interfaces.base_classes.psi_device_base import DeviceStoppedError + +from mx_bec.devices import RobotState, SimAerotechStage, SimGoniometer, SimSampleChanger + + +@pytest.fixture +def robot(): + dev = SimSampleChanger(name="robot", mount_time=0.05, device_manager=DMMock()) + dev.on_connected() + yield dev + dev.destroy() + + +@pytest.mark.parametrize("cls", [SimAerotechStage, SimGoniometer]) +def test_stage_reads_all_axes(cls): + stage = cls(name="stage") + readings = stage.read() + for axis in cls.component_names: + assert f"stage_{axis}" in readings + stage.destroy() + + +def test_omega_is_unbounded(): + stage = SimAerotechStage(name="aerotech") + stage.omega.delay = 0 + stage.omega.move(720).wait(timeout=1) + assert stage.omega.position == pytest.approx(720, abs=stage.omega.tolerance.get()) + stage.destroy() + + +def test_robot_mount_and_unmount(robot): + assert robot.mount_time.get() == 0.05 + robot.mount(puck=2, position=7).wait(timeout=1) + assert robot.read()["robot_sample_mounted"]["value"] == 1 + assert robot.mounted_puck.get() == 2 + assert robot.mounted_position.get() == 7 + assert robot.state.get() == RobotState.IDLE + + robot.unmount().wait(timeout=1) + assert robot.sample_mounted.get() == 0 + assert robot.mounted_puck.get() == 0 + + +def test_robot_is_busy_while_mounting(robot): + status = robot.mount(puck=1, position=1) + assert robot.state.get() == RobotState.BUSY + with pytest.raises(RuntimeError, match="not idle"): + robot.mount(puck=1, position=2) + status.wait(timeout=1) + assert robot.mounted_position.get() == 1 + + +def test_robot_refuses_with_door_open(robot): + robot.door_closed.put(0) + with pytest.raises(RuntimeError, match="door"): + robot.mount(puck=1, position=1) + assert robot.state.get() == RobotState.ERROR + robot.reset() + assert robot.state.get() == RobotState.IDLE + + +def test_robot_stop_aborts_mount(robot): + robot.mount_time.put(5) + status = robot.mount(puck=1, position=1) + robot.stop() + with pytest.raises(DeviceStoppedError): + status.wait(timeout=1) + assert robot.sample_mounted.get() == 0 + assert robot.state.get() == RobotState.IDLE diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py new file mode 100644 index 0000000..1ec1fd6 --- /dev/null +++ b/tests/unit/test_service.py @@ -0,0 +1,109 @@ +from unittest.mock import MagicMock, call, patch + +import pytest +from bec_lib.client import BECClient +from bec_lib.service_config import ServiceConfig +from bec_lib.tests.utils import ConnectorMock + +from mx_bec.constants import AareBecWorkflowState +from mx_bec.endpoints import StateEndpoints +from mx_bec.messages import MXMeasurementSequenceMessage +from mx_bec.service import AareBec, MxTasks + + +@pytest.fixture +def service(): + BECClient._reset_singleton() + # the config client connects to the beamline redis on construction + with patch("mx_bec.service.AareConfigClient"): + svc = AareBec(ServiceConfig(redis={"host": "dummy", "port": 6379}), ConnectorMock) + yield svc + BECClient._reset_singleton() + + +def test_service_is_idle_before_start(service): + assert service.workflow_state == AareBecWorkflowState.IDLE + assert service.actor_manager is None + + +def test_start_creates_actor_manager(service): + with ( + patch.object(BECClient, "start") as base_start, + patch("mx_bec.service.AareActorManager") as manager_cls, + patch.object(AareBec, "status", create=True), + ): + service.start() + base_start.assert_called_once() + manager_cls.assert_called_once_with(service) + assert service.actor_manager is manager_cls.return_value + + +def test_shutdown_stops_actor_manager(service): + service.actor_manager = MagicMock() + manager = service.actor_manager + with patch.object(BECClient, "shutdown") as base_shutdown: + service.shutdown() + manager.shutdown.assert_called_once() + base_shutdown.assert_called_once() + assert service.actor_manager is None + + +@pytest.fixture +def mock_client(): + client = MagicMock() + client.config.optical_centering.angles = [0.0, 90.0] + return client + + +def _published(client) -> list[tuple[str, MXMeasurementSequenceMessage]]: + return [ + (call.args[0].endpoint, call.args[1]) + for call in client.connector.set_and_publish.call_args_list + ] + + +def _optical_centering_done(sample_id: int, success: bool): + return ( + StateEndpoints.optical_centering_done().endpoint, + MXMeasurementSequenceMessage(sample_id=sample_id, success=success), + ) + + +def test_optical_centering_without_target_publishes_failure(mock_client): + mock_client.optical_prediction.get_target_point_offset_mm.return_value = None + MxTasks(mock_client).run_optical_centering(sample_id=3) + mock_client.devices.smargon.nudge_in_lab_frame.assert_not_called() + assert _published(mock_client) == [_optical_centering_done(3, success=False)] + + +def test_optical_centering_centres_at_each_angle_then_publishes_success(mock_client): + smargon, aerotech = mock_client.devices.smargon, mock_client.devices.aerotech + mock_client.optical_prediction.get_target_point_offset_mm.return_value = (0.1, -0.2) + + MxTasks(mock_client).run_optical_centering(sample_id=3) + + assert [call.args for call in aerotech.u.set.call_args_list] == [(0.0,), (90.0,)] + assert aerotech.u.set.return_value.wait.call_count == 2 + assert smargon.nudge_in_lab_frame.call_args_list == [ + call(0.1, -0.2, omega_deg=0.0), + call(0.1, -0.2, omega_deg=90.0), + ] + assert smargon.nudge_in_lab_frame.return_value.wait.call_count == 2 + assert _published(mock_client) == [_optical_centering_done(3, success=True)] + + +def test_optical_centering_gives_up_when_a_later_angle_has_no_target(mock_client): + mock_client.optical_prediction.get_target_point_offset_mm.side_effect = [(0.1, -0.2), None] + MxTasks(mock_client).run_optical_centering(sample_id=3) + assert mock_client.devices.smargon.nudge_in_lab_frame.call_count == 1 + assert _published(mock_client) == [_optical_centering_done(3, success=False)] + + +def test_optical_centering_publishes_failure_when_move_fails(mock_client): + mock_client.optical_prediction.get_target_point_offset_mm.return_value = (0.1, -0.2) + move = mock_client.devices.smargon.nudge_in_lab_frame.return_value + move.wait.side_effect = TimeoutError("smargon did not reach target") + + with pytest.raises(TimeoutError): + MxTasks(mock_client).run_optical_centering(sample_id=3) + assert _published(mock_client) == [_optical_centering_done(3, success=False)] diff --git a/tests/unit/test_smargon.py b/tests/unit/test_smargon.py new file mode 100644 index 0000000..d6c4dac --- /dev/null +++ b/tests/unit/test_smargon.py @@ -0,0 +1,106 @@ +"""Tests of the smargopolo Smargon device against the in-process mock server.""" + +import numpy as np +import pytest +import requests +from mock_smargopolo import AXES, MockSmargopolo, motors + +from mx_bec.devices.smargopolo_smargon import Smargon + +TOL = 0.01 + + +@pytest.fixture(scope="module") +def server(): + with MockSmargopolo() as srv: + yield srv + + +@pytest.fixture +def smargon(server): + for motor in motors.values(): + motor.position = motor.target = 0.0 + motor.moving = False + dev = Smargon(name="smargon", prefix=server.url) + dev.wait_for_connection() + yield dev + dev.controller._stop_monitor_readback_event.set() + dev.destroy() + + +def reference_nudge(x, y, z, phi_deg, chi_deg, omega_deg): + """aarecommon.math.sample_geometry.SampleGeometry.smargon_nudge""" + phi, chi, omega = (np.radians(np.around(a, decimals=1)) for a in (phi_deg, chi_deg, omega_deg)) + co, so = np.cos(omega), np.sin(omega) + cp, sp = np.cos(phi), np.sin(phi) + cc, sc = np.cos(chi), np.sin(chi) + return ( + -z * co * sp - y * so * sp + x * cp * sc - y * co * cc * cp + z * so * cc * cp, + -z * co * cp - y * so * cp - x * sc * sp + y * co * cc * sp - z * so * cc * sp, + -x * cc - y * co * sc + z * so * sc, + ) + + +def test_read_all_axes(smargon): + motors["SHX"].position = 1.5 + motors["CHI"].position = 42.0 + smargon.controller.manual_update() + reading = smargon.read() + assert set(reading) == {f"smargon_{ax}" for ax in ("x", "y", "z", "phi", "chi")} + assert reading["smargon_x"]["value"] == 1.5 + assert reading["smargon_chi"]["value"] == 42.0 + + +def test_set_moves_and_completes(smargon): + smargon.x.set(0.5).wait(timeout=2) + assert smargon.x.get() == pytest.approx(0.5, abs=TOL) + assert motors["SHX"].target == 0.5 + + +def test_set_sends_only_that_axis(smargon): + before = {ax: motors[ax].target for ax in AXES} + smargon.phi.set(0.3).wait(timeout=2) + before["PHI"] = 0.3 + assert {ax: motors[ax].target for ax in AXES} == before + + +def test_nudge_in_lab_frame_at_zero_angles(smargon): + # With omega = phi = chi = 0 a lab-frame x offset is a smargon -z move, y -> -x, z -> -y + smargon.nudge_in_lab_frame(0.2, 0.0, 0.0).wait(timeout=2) + assert smargon.z.get() == pytest.approx(-0.2, abs=TOL) + assert smargon.x.get() == pytest.approx(0.0, abs=TOL) + assert smargon.y.get() == pytest.approx(0.0, abs=TOL) + smargon.nudge_in_lab_frame(0.0, 0.2, 0.0).wait(timeout=2) + assert smargon.x.get() == pytest.approx(-0.2, abs=TOL) + + +@pytest.mark.parametrize( + "phi_deg, chi_deg, omega_deg", [(90.0, 0.0, 0.0), (0.0, 20.0, 0.0), (30.0, 20.0, 45.0)] +) +def test_nudge_matches_reference(smargon, phi_deg, chi_deg, omega_deg): + for ax, val in (("PHI", phi_deg), ("CHI", chi_deg)): + motors[ax].position = motors[ax].target = val + smargon.controller.manual_update() + # omega is the Aerotech rotation, which the smargon does not know: it is passed in + assert smargon._lab_frame_offset_to_smargon_nudge(1.0, 0.5, 0.25, omega_deg) == pytest.approx( + reference_nudge(1.0, 0.5, 0.25, phi_deg, chi_deg, omega_deg) + ) + + +def test_stop_targets_current_position(smargon): + smargon.x.put(5.0) + assert motors["SHX"].moving + smargon.stop() + assert smargon.stopped + # the target was re-set to the (buffered) readback, not to 5.0, and nothing but axes was sent + assert motors["SHX"].target == pytest.approx(smargon.x.get(), abs=0.1) + assert motors["SHX"].target != 5.0 + + +def test_server_rejects_unknown_axis(server): + resp = requests.put(f"{server.url}/targetSCS", params={"__timestamp": 1.0}) + assert resp.status_code == 404 + + +def test_user_access_is_a_list(): + assert Smargon.USER_ACCESS == ["nudge_in_lab_frame"]