From d807f8219cf959ba9bb4a9641085e08b6a07d287 Mon Sep 17 00:00:00 2001 From: x10sa Date: Mon, 2 Nov 2026 11:36:28 +0100 Subject: [PATCH 01/46] 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"] -- 2.54.1 From ebb4e1f08ac697ce357e7bae70d0f361e95cc7dc Mon Sep 17 00:00:00 2001 From: x10sa Date: Mon, 2 Nov 2026 14:43:10 +0100 Subject: [PATCH 02/46] WIP continue integration --- mx_bec/actor_manager.py | 25 +++++++---- .../bec_widgets/widgets/aare_bec/__init__.py | 0 .../widgets/aare_bec/actors_config.py | 42 +++++++++++++++++++ mx_bec/endpoints.py | 11 ++++- mx_bec/service.py | 5 ++- pyproject.toml | 3 ++ 6 files changed, 76 insertions(+), 10 deletions(-) create mode 100644 mx_bec/bec_widgets/widgets/aare_bec/__init__.py create mode 100644 mx_bec/bec_widgets/widgets/aare_bec/actors_config.py diff --git a/mx_bec/actor_manager.py b/mx_bec/actor_manager.py index 73868b7..1ddf989 100644 --- a/mx_bec/actor_manager.py +++ b/mx_bec/actor_manager.py @@ -1,20 +1,22 @@ from __future__ import annotations import functools -from collections.abc import Callable, Iterable from threading import Event, Thread -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Callable, Iterable 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 bec_lib.messages import AvailableResourceMessage, BuiltinActorStateUpdatedNotification from mx_bec.actors import all_actor_classes from mx_bec.actors.core import MXAutomationActor +from mx_bec.endpoints import ActorEndpoints if TYPE_CHECKING: - from bec_lib.client import BECClient + from bec_lib.endpoints import EndpointInfo + + from mx_bec.service import AareBec logger = bec_logger.logger @@ -33,7 +35,7 @@ class AareActorManager: """ def __init__( - self, client: BECClient, actor_classes: Iterable[type[MXAutomationActor]] | None = None + self, client: AareBec, actor_classes: Iterable[type[MXAutomationActor]] | None = None ) -> None: self._client = client self._actor_classes = ( @@ -43,16 +45,23 @@ class AareActorManager: 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]] = {} - + enabled_endpoints: dict[str, EndpointInfo] = {} for actor_class in self._actor_classes: + ep = actor_class.config_endpoint() flag: RedisConfigValue[bool] = RedisConfigValue( - connector=self._client.connector, endpoint=actor_class.config_endpoint() + connector=self._client.connector, endpoint=ep ) + enabled_endpoints[actor_class.__name__] = ep callback = functools.partial(self._enabled_changed, actor_class) flag.subscribe(callback) self._enabled_flags[actor_class] = flag self._enabled_callbacks[actor_class] = callback - + available_actor_config_eps = AvailableResourceMessage( + resource={"endpoints": enabled_endpoints} + ) + self._client.connector.set_and_publish( + ActorEndpoints.available_actor_config_eps(), available_actor_config_eps + ) self._start_all() @property diff --git a/mx_bec/bec_widgets/widgets/aare_bec/__init__.py b/mx_bec/bec_widgets/widgets/aare_bec/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/mx_bec/bec_widgets/widgets/aare_bec/actors_config.py b/mx_bec/bec_widgets/widgets/aare_bec/actors_config.py new file mode 100644 index 0000000..0f8bf55 --- /dev/null +++ b/mx_bec/bec_widgets/widgets/aare_bec/actors_config.py @@ -0,0 +1,42 @@ +from bec_lib.logger import bec_logger +from bec_lib.messages import AvailableResourceMessage +from bec_widgets.utils.bec_connector import ConnectionConfig +from bec_widgets.utils.bec_widget import BECWidget +from bec_widgets.widgets.utility.toggle.toggle import ToggleSwitch +from qtpy.QtWidgets import QLabel, QVBoxLayout, QWidget + +from mx_bec.endpoints import ActorEndpoints + +logger = bec_logger.logger + + +class MxActorConfigWidget(BECWidget, QWidget): + """ + Widget displaying and managing MX actors - automation steps. + """ + + PLUGIN = True + ICON_NAME = "format_list_bulleted" + USER_ACCESS = ["refresh"] + + def __init__( + self, + parent: QWidget | None = None, + client=None, + config: ConnectionConfig | None = None, + gui_id: str | None = None, + **kwargs, + ) -> None: + super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs) + self.refresh() + + def refresh(self): + """Reset the layout for currently loaded actors""" + self._layout = QVBoxLayout(self) + available_actors = self.client.connector.get(ActorEndpoints.available_actor_config_eps()) + if not isinstance(available_actors, AvailableResourceMessage): + logger.warning("No available MX actors registered") + self._layout.addWidget(QLabel("No available MX actors registered")) + for name, ep in available_actors.resource["endpoints"].items(): + self._layout.addWidget(QLabel(name)) + self._layout.addWidget(ToggleSwitch()) diff --git a/mx_bec/endpoints.py b/mx_bec/endpoints.py index d303ef2..518413b 100644 --- a/mx_bec/endpoints.py +++ b/mx_bec/endpoints.py @@ -1,5 +1,5 @@ from bec_lib.endpoints import EndpointInfo, EndpointType, MessageOp -from bec_lib.messages import BoolConfigDefaultFalse +from bec_lib.messages import AvailableResourceMessage, BoolConfigDefaultFalse from mx_bec.messages import MXMeasurementSequenceMessage, OpticalPredictionMessage @@ -54,6 +54,15 @@ class ActorEndpoints: message_op=MessageOp.STREAM, ) + @staticmethod + def available_actor_config_eps(): + """Endpoint to broadcast which MX actors are available on the MX builtin actor manager""" + return EndpointInfo( + endpoint=f"{EndpointType.INFO}/actor/mx/available_config_eps", + message_type=AvailableResourceMessage, + message_op=MessageOp.SET_PUBLISH, + ) + class DataAnalysisEndpoints: @staticmethod diff --git a/mx_bec/service.py b/mx_bec/service.py index aadf19c..e8a1fc7 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -32,9 +32,12 @@ class AareBec(BECClient): 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'" + "Set CONFIG_REDIS_URL to 'redis://mx--queue-01:6379'" "if you want to create an AareBec client" ) + config.model.log_writer.base_path = "/tmp/mx_bec_logs" + config.config["log_writer"]["base_path"] = "/tmp/mx_bec_logs" + 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 diff --git a/pyproject.toml b/pyproject.toml index 1f9b9bf..fd9891d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -71,6 +71,9 @@ good-names-rgxs = [ ".*_1D.*", ] +[project.scripts] +mx-bec-service = "mx_bec.main:main" + [tool.ruff] line-length = 100 -- 2.54.1 From 8e44786bb6fa5fc03e02a2bc63b48ced37c7c6f9 Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 3 Nov 2026 07:48:32 +0100 Subject: [PATCH 03/46] feat: add actor config panel --- .../widgets/aare_bec/actors_config.py | 71 +++++++++++++++++-- 1 file changed, 65 insertions(+), 6 deletions(-) diff --git a/mx_bec/bec_widgets/widgets/aare_bec/actors_config.py b/mx_bec/bec_widgets/widgets/aare_bec/actors_config.py index 0f8bf55..ca443ce 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/actors_config.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/actors_config.py @@ -1,9 +1,17 @@ +from __future__ import annotations + +import functools +from typing import Callable + +from bec_lib.config_values import RedisConfigValue from bec_lib.logger import bec_logger from bec_lib.messages import AvailableResourceMessage from bec_widgets.utils.bec_connector import ConnectionConfig from bec_widgets.utils.bec_widget import BECWidget +from bec_widgets.utils.error_popups import SafeSlot from bec_widgets.widgets.utility.toggle.toggle import ToggleSwitch -from qtpy.QtWidgets import QLabel, QVBoxLayout, QWidget +from qtpy.QtCore import Signal +from qtpy.QtWidgets import QGridLayout, QLabel, QWidget from mx_bec.endpoints import ActorEndpoints @@ -13,12 +21,19 @@ logger = bec_logger.logger class MxActorConfigWidget(BECWidget, QWidget): """ Widget displaying and managing MX actors - automation steps. + + Each available actor gets a row with its name and a toggle bound to the actor's `enabled` + flag in Redis, so the toggle both writes the flag and follows changes made elsewhere. """ PLUGIN = True ICON_NAME = "format_list_bulleted" USER_ACCESS = ["refresh"] + # Redis callbacks arrive on the connector thread; re-emit so the toggle is updated on the GUI + # thread. + _config_value_changed = Signal(str, bool) + def __init__( self, parent: QWidget | None = None, @@ -28,15 +43,59 @@ class MxActorConfigWidget(BECWidget, QWidget): **kwargs, ) -> None: super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs) + self._layout = QGridLayout(self) + self._toggles: dict[str, ToggleSwitch] = {} + self._config_values: dict[str, RedisConfigValue[bool]] = {} + # RedisConfigValue only keeps weak references to subscribers, so hold the partials here. + self._config_callbacks: dict[str, Callable[[bool], None]] = {} + self._config_value_changed.connect(self._on_config_value_changed) self.refresh() + @SafeSlot() def refresh(self): """Reset the layout for currently loaded actors""" - self._layout = QVBoxLayout(self) + self._clear() available_actors = self.client.connector.get(ActorEndpoints.available_actor_config_eps()) if not isinstance(available_actors, AvailableResourceMessage): logger.warning("No available MX actors registered") - self._layout.addWidget(QLabel("No available MX actors registered")) - for name, ep in available_actors.resource["endpoints"].items(): - self._layout.addWidget(QLabel(name)) - self._layout.addWidget(ToggleSwitch()) + self._layout.addWidget(QLabel("No available MX actors registered"), 0, 0, 1, 2) + return + for row, (name, ep) in enumerate(available_actors.resource["endpoints"].items()): + config_value: RedisConfigValue[bool] = RedisConfigValue( + connector=self.client.connector, endpoint=ep, wait_for_writes=False + ) + toggle = ToggleSwitch(parent=self, checked=config_value.value) + toggle.stateChanged.connect(functools.partial(self._set_config_value, name)) + callback = functools.partial(self._config_value_changed.emit, name) + config_value.subscribe(callback) + self._toggles[name] = toggle + self._config_values[name] = config_value + self._config_callbacks[name] = callback + self._layout.addWidget(QLabel(name, parent=self), row, 0) + self._layout.addWidget(toggle, row, 1) + + def _set_config_value(self, name: str, enabled: bool): + self._config_values[name].value = enabled + + @SafeSlot(str, bool) + def _on_config_value_changed(self, name: str, enabled: bool): + if (toggle := self._toggles.get(name)) is None: + return + # Don't write the value we just received straight back to Redis. + toggle.blockSignals(True) + toggle.setChecked(enabled) + toggle.blockSignals(False) + + def _clear(self): + for config_value in self._config_values.values(): + config_value.unregister_all() + self._config_values.clear() + self._config_callbacks.clear() + self._toggles.clear() + while (item := self._layout.takeAt(0)) is not None: + if (widget := item.widget()) is not None: + widget.deleteLater() + + def cleanup(self): + self._clear() + super().cleanup() -- 2.54.1 From 32fe721b649f018e47028abc6c5c0dcf322cd0da Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 3 Nov 2026 08:30:08 +0100 Subject: [PATCH 04/46] feat: add tasks module --- mx_bec/configs/mx_demo_config.yaml | 9 ++-- mx_bec/messages.py | 10 +++++ mx_bec/service.py | 38 +---------------- mx_bec/tasks.py | 67 ++++++++++++++++++++++++++++++ tests/unit/test_actor_manager.py | 16 +++---- tests/unit/test_actors.py | 2 +- tests/unit/test_service.py | 5 ++- 7 files changed, 95 insertions(+), 52 deletions(-) create mode 100644 mx_bec/tasks.py diff --git a/mx_bec/configs/mx_demo_config.yaml b/mx_bec/configs/mx_demo_config.yaml index 80044c7..26107b2 100644 --- a/mx_bec/configs/mx_demo_config.yaml +++ b/mx_bec/configs/mx_demo_config.yaml @@ -2,7 +2,8 @@ # 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 +# mx_bec.devices (re-exported through the pxii_bec plugin, which is what the +# device server can load). Load it into a running BEC with # from mx_bec.configs import load_mx_demo_config # load_mx_demo_config(bec) ############################################################ @@ -29,7 +30,7 @@ eiger: # Aerotech rotation stage: x/y/z translation (mm) under the omega rotation axis (deg). aerotech: readoutPriority: baseline - deviceClass: mx_bec.devices.SimAerotechStage + deviceClass: pxii_bec.devices.SimAerotechStage deviceConfig: deviceTags: - sample stage @@ -40,7 +41,7 @@ aerotech: # 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 + deviceClass: pxii_bec.devices.SimGoniometer deviceConfig: deviceTags: - sample stage @@ -54,7 +55,7 @@ gonio: robot: readoutPriority: baseline - deviceClass: mx_bec.devices.SimSampleChanger + deviceClass: pxii_bec.devices.SimSampleChanger deviceConfig: mount_time: 2.0 deviceTags: diff --git a/mx_bec/messages.py b/mx_bec/messages.py index 9b6f514..c22d43b 100644 --- a/mx_bec/messages.py +++ b/mx_bec/messages.py @@ -15,6 +15,16 @@ class MXMeasurementSequenceMessage(BECMessage): success: bool +class MXTaskExecutionMessage(BECMessage): + """Used to send commands for custom tasks to the AareBec service.""" + + msg_type: ClassVar[str] = "mx_task_execution_message" + + name: str + args: tuple[int | bool | str | float | None] + kwargs: dict[str, int | bool | str | float | None] + + class OpticalPredictionMessage(BECMessage): """The latest optical image analysis prediction""" diff --git a/mx_bec/service.py b/mx_bec/service.py index e8a1fc7..ef91af0 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -10,10 +10,8 @@ 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 +from mx_bec.tasks import MxTasks if TYPE_CHECKING: from bec_lib.redis_connector import RedisConnector @@ -65,37 +63,3 @@ class AareBec(BECClient): 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/tasks.py b/mx_bec/tasks.py new file mode 100644 index 0000000..0605e5a --- /dev/null +++ b/mx_bec/tasks.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +import functools +from threading import RLock +from typing import TYPE_CHECKING, Callable, ParamSpec, TypeVar + +from bec_lib.logger import bec_logger + +from mx_bec.devices.smargopolo_smargon import Smargon +from mx_bec.endpoints import StateEndpoints +from mx_bec.messages import MXMeasurementSequenceMessage + +if TYPE_CHECKING: + from mx_bec.service import AareBec + +logger = bec_logger.logger + +P = ParamSpec("P") +R = TypeVar("R") + + +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 + self._busy_lock = RLock() + + @staticmethod + def with_lock(method: Callable[P, R]) -> Callable[P, R]: + """Run the decorated method while holding `self._busy_lock`, so that only one task + runs at a time.""" + + @functools.wraps(method) + def wrapper(self: MxTasks, *args, **kwargs): + with self._busy_lock: + return method(self, *args, **kwargs) + + return wrapper # type: ignore # self is part of P + + @with_lock + 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/tests/unit/test_actor_manager.py b/tests/unit/test_actor_manager.py index fcc76e6..65332e9 100644 --- a/tests/unit/test_actor_manager.py +++ b/tests/unit/test_actor_manager.py @@ -3,14 +3,14 @@ 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 ( +from mx_bec.actor_manager import AareActorManager +from mx_bec.actors import all_actor_classes +from mx_bec.actors.core import MXAutomationActor +from mx_bec.actors.mx_automation import ( OnOpticalCenteringDoneRunXrayCentering, OnSampleMountedRunOpticalCentering, ) -from aare_bec_proto.messages import MXMeasurementSequenceMessage +from mx_bec.messages import MXMeasurementSequenceMessage class FakeConfigValue: @@ -56,7 +56,7 @@ class DummyActor(MXAutomationActor): @pytest.fixture def manager(): - with patch("aare_bec_proto.actor_manager.RedisConfigValue", FakeConfigValue): + with patch("mx_bec.actor_manager.RedisConfigValue", FakeConfigValue): client = MagicMock() mgr = AareActorManager(client, actor_classes=[DummyActor]) yield mgr, client @@ -72,7 +72,7 @@ def test_all_actor_classes_finds_concrete_subclasses(): def test_default_manager_manages_all_actors(): - with patch("aare_bec_proto.actor_manager.RedisConfigValue", FakeConfigValue): + with patch("mx_bec.actor_manager.RedisConfigValue", FakeConfigValue): mgr = AareActorManager(MagicMock()) assert mgr.actor_classes == all_actor_classes() assert mgr.running == [] @@ -100,7 +100,7 @@ def test_enabling_starts_and_disabling_stops_actor(manager): def test_actor_enabled_at_startup_is_started(): with ( - patch("aare_bec_proto.actor_manager.RedisConfigValue", FakeConfigValue), + patch("mx_bec.actor_manager.RedisConfigValue", FakeConfigValue), patch.object(FakeConfigValue, "initial", True), ): mgr = AareActorManager(MagicMock(), actor_classes=[DummyActor]) diff --git a/tests/unit/test_actors.py b/tests/unit/test_actors.py index 5f9ebfd..70e9730 100644 --- a/tests/unit/test_actors.py +++ b/tests/unit/test_actors.py @@ -67,7 +67,7 @@ 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.aare_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") diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py index 1ec1fd6..2119a0d 100644 --- a/tests/unit/test_service.py +++ b/tests/unit/test_service.py @@ -12,8 +12,9 @@ from mx_bec.service import AareBec, MxTasks @pytest.fixture -def service(): +def service(monkeypatch): BECClient._reset_singleton() + monkeypatch.setenv("CONFIG_REDIS_URL", "redis://dummy:6379") # 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) @@ -51,7 +52,7 @@ def test_shutdown_stops_actor_manager(service): @pytest.fixture def mock_client(): client = MagicMock() - client.config.optical_centering.angles = [0.0, 90.0] + client.aare_config.optical_centering.angles = [0.0, 90.0] return client -- 2.54.1 From 7c6113042ce837d4ec18fb45eccdcc2d550ffe92 Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 3 Nov 2026 09:07:11 +0100 Subject: [PATCH 05/46] feat: add tasks list --- mx_bec/endpoints.py | 30 ++++++++++++++- mx_bec/messages.py | 2 +- mx_bec/service.py | 16 ++++++++ mx_bec/tasks.py | 14 +++++-- tests/unit/test_service.py | 76 +++++++++++++++++++++++++++++++++++++- 5 files changed, 131 insertions(+), 7 deletions(-) diff --git a/mx_bec/endpoints.py b/mx_bec/endpoints.py index 518413b..e4c28a7 100644 --- a/mx_bec/endpoints.py +++ b/mx_bec/endpoints.py @@ -1,7 +1,11 @@ from bec_lib.endpoints import EndpointInfo, EndpointType, MessageOp from bec_lib.messages import AvailableResourceMessage, BoolConfigDefaultFalse -from mx_bec.messages import MXMeasurementSequenceMessage, OpticalPredictionMessage +from mx_bec.messages import ( + MXMeasurementSequenceMessage, + MXTaskExecutionMessage, + OpticalPredictionMessage, +) class StateEndpoints: @@ -64,6 +68,30 @@ class ActorEndpoints: ) +class TaskEndpoints: + """Requests for the AareBec service to run one of its `MxTasks`.""" + + @staticmethod + def task_request(): + """Stream of task requests from clients. The AareBec service validates them and queues + the accepted ones on `task_execution`.""" + return EndpointInfo( + endpoint=f"{EndpointType.USER.value}/mx/tasks/request", + message_type=MXTaskExecutionMessage, + message_op=MessageOp.STREAM, + ) + + @staticmethod + def task_execution(): + """FIFO queue of validated tasks waiting to be executed by the AareBec service: new tasks + are appended on the right.""" + return EndpointInfo( + endpoint=f"{EndpointType.USER.value}/mx/tasks/execution", + message_type=MXTaskExecutionMessage, + message_op=MessageOp.LIST, + ) + + class DataAnalysisEndpoints: @staticmethod def optical_prediction(): diff --git a/mx_bec/messages.py b/mx_bec/messages.py index c22d43b..38f1e9c 100644 --- a/mx_bec/messages.py +++ b/mx_bec/messages.py @@ -21,7 +21,7 @@ class MXTaskExecutionMessage(BECMessage): msg_type: ClassVar[str] = "mx_task_execution_message" name: str - args: tuple[int | bool | str | float | None] + args: tuple[int | bool | str | float | None, ...] kwargs: dict[str, int | bool | str | float | None] diff --git a/mx_bec/service.py b/mx_bec/service.py index ef91af0..89e63bb 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -10,6 +10,7 @@ from bec_lib.logger import bec_logger from mx_bec.actor_manager import AareActorManager from mx_bec.constants import AareBecWorkflowState +from mx_bec.endpoints import TaskEndpoints from mx_bec.optical_centering import OpticalPrediction from mx_bec.tasks import MxTasks @@ -17,6 +18,8 @@ if TYPE_CHECKING: from bec_lib.redis_connector import RedisConnector from bec_lib.service_config import ServiceConfig + from mx_bec.messages import MXTaskExecutionMessage + logger = bec_logger.logger @@ -46,8 +49,19 @@ class AareBec(BECClient): def start(self): super().start() self._start_actor_manager() + self.connector.register(TaskEndpoints.task_request(), cb=self._on_task_request) self.status = messages.BECStatus.RUNNING + def _on_task_request(self, msg_dict: dict) -> None: + """Validate a task request and, if it names a public `MxTasks` method, append it to the + task execution queue.""" + msg: MXTaskExecutionMessage = msg_dict["data"] + if not MxTasks.is_task(msg.name): + logger.warning(f"Rejected task request: {msg.name!r} is not a public MxTasks method") + return + logger.info(f"Queueing task request: {msg}") + self.connector.rpush(TaskEndpoints.task_execution(), msg) + @property def devices(self): if self.device_manager is None: @@ -62,4 +76,6 @@ class AareBec(BECClient): if self.actor_manager is not None: self.actor_manager.shutdown() self.actor_manager = None + if self.started: # the connector only exists once the client has been started + self.connector.unregister(TaskEndpoints.task_request(), cb=self._on_task_request) super().shutdown(per_thread_timeout_s) diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index 0605e5a..a8e3811 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -1,6 +1,7 @@ from __future__ import annotations import functools +import inspect from threading import RLock from typing import TYPE_CHECKING, Callable, ParamSpec, TypeVar @@ -27,16 +28,23 @@ class MxTasks: self._client = client self._busy_lock = RLock() + @classmethod + def is_task(cls, name: str) -> bool: + """Whether `name` can be requested as a task, i.e. is a method decorated with + `with_lock`.""" + return getattr(inspect.getattr_static(cls, name, None), "is_mx_task", False) + @staticmethod def with_lock(method: Callable[P, R]) -> Callable[P, R]: - """Run the decorated method while holding `self._busy_lock`, so that only one task - runs at a time.""" + """Mark the decorated method as a task and run it while holding `self._busy_lock`, so + that only one task runs at a time.""" @functools.wraps(method) def wrapper(self: MxTasks, *args, **kwargs): - with self._busy_lock: + with self._busy_lock: # pylint: disable=protected-access return method(self, *args, **kwargs) + wrapper.is_mx_task = True return wrapper # type: ignore # self is part of P @with_lock diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py index 2119a0d..702126d 100644 --- a/tests/unit/test_service.py +++ b/tests/unit/test_service.py @@ -6,8 +6,8 @@ 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.endpoints import StateEndpoints, TaskEndpoints +from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskExecutionMessage from mx_bec.service import AareBec, MxTasks @@ -28,6 +28,7 @@ def test_service_is_idle_before_start(service): def test_start_creates_actor_manager(service): + service.connector = MagicMock() # normally created by the patched-out BECClient.start with ( patch.object(BECClient, "start") as base_start, patch("mx_bec.service.AareActorManager") as manager_cls, @@ -49,6 +50,77 @@ def test_shutdown_stops_actor_manager(service): assert service.actor_manager is None +def test_start_registers_task_execution_callback(service): + # BECClient.start (patched out) is what normally creates the connector + service.connector = MagicMock() + with ( + patch.object(BECClient, "start"), + patch("mx_bec.service.AareActorManager"), + patch.object(AareBec, "status", create=True), + ): + service.start() + service.connector.register.assert_called_once_with( + TaskEndpoints.task_request(), cb=service._on_task_request + ) + + +def test_shutdown_unregisters_task_request_callback(service): + service.started = True + service.connector = MagicMock() + with patch.object(BECClient, "shutdown"): + service.shutdown() + service.connector.unregister.assert_called_once_with( + TaskEndpoints.task_request(), cb=service._on_task_request + ) + + +def test_shutdown_before_start_does_not_touch_connector(service): + with patch.object(BECClient, "shutdown") as base_shutdown: + service.shutdown() + base_shutdown.assert_called_once() + + +def test_task_request_for_known_method_is_queued(service): + service.connector = MagicMock() + msg = MXTaskExecutionMessage(name="run_optical_centering", args=(3,), kwargs={}) + service._on_task_request({"data": msg}) + service.connector.rpush.assert_called_once_with(TaskEndpoints.task_execution(), msg) + + +NOT_TASKS = [ + "no_such_task", + "_publish_optical_centering_done", # private method + "_client", # private attribute + "_busy_lock", + "with_lock", # public, but a helper rather than a task + "is_task", +] + + +@pytest.mark.parametrize("name", NOT_TASKS) +def test_task_request_for_non_task_name_is_rejected(service, name): + service.connector = MagicMock() + msg = MXTaskExecutionMessage(name=name, args=(), kwargs={}) + with patch("mx_bec.service.logger") as logger: + service._on_task_request({"data": msg}) + service.connector.rpush.assert_not_called() + logger.warning.assert_called_once() + assert name in logger.warning.call_args.args[0] + + +def test_tasks_are_exactly_the_methods_decorated_with_with_lock(): + class Tasks(MxTasks): + @MxTasks.with_lock + def decorated(self): ... + + def plain(self): ... + + assert Tasks.is_task("decorated") + assert not Tasks.is_task("plain") + assert MxTasks.is_task("run_optical_centering") + assert all(not MxTasks.is_task(name) for name in NOT_TASKS) + + @pytest.fixture def mock_client(): client = MagicMock() -- 2.54.1 From fdd96c545fa1dcf8f8b5cb22f2c90581035339da Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 3 Nov 2026 09:12:50 +0100 Subject: [PATCH 06/46] feat: add vibed task queue --- mx_bec/endpoints.py | 12 +++- mx_bec/service.py | 8 ++- mx_bec/tasks.py | 71 +++++++++++++++++++- tests/unit/test_service.py | 35 ++++++---- tests/unit/test_tasks.py | 129 +++++++++++++++++++++++++++++++++++++ 5 files changed, 239 insertions(+), 16 deletions(-) create mode 100644 tests/unit/test_tasks.py diff --git a/mx_bec/endpoints.py b/mx_bec/endpoints.py index e4c28a7..2b17356 100644 --- a/mx_bec/endpoints.py +++ b/mx_bec/endpoints.py @@ -84,13 +84,23 @@ class TaskEndpoints: @staticmethod def task_execution(): """FIFO queue of validated tasks waiting to be executed by the AareBec service: new tasks - are appended on the right.""" + are appended on the right and executed from the left.""" return EndpointInfo( endpoint=f"{EndpointType.USER.value}/mx/tasks/execution", message_type=MXTaskExecutionMessage, message_op=MessageOp.LIST, ) + @staticmethod + def task_queue_paused(): + """Managed bool: whether the AareBec service should stop taking tasks from the execution + queue. Works with RedisConfigValue; defaults to running (not paused).""" + return EndpointInfo( + endpoint=f"{EndpointType.USER.value}/mx/tasks/queue_paused", + message_type=BoolConfigDefaultFalse, + message_op=MessageOp.STREAM, + ) + class DataAnalysisEndpoints: @staticmethod diff --git a/mx_bec/service.py b/mx_bec/service.py index 89e63bb..9a5dc63 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -12,7 +12,7 @@ from mx_bec.actor_manager import AareActorManager from mx_bec.constants import AareBecWorkflowState from mx_bec.endpoints import TaskEndpoints from mx_bec.optical_centering import OpticalPrediction -from mx_bec.tasks import MxTasks +from mx_bec.tasks import MxTaskQueue, MxTasks if TYPE_CHECKING: from bec_lib.redis_connector import RedisConnector @@ -45,10 +45,13 @@ class AareBec(BECClient): self.actor_manager: AareActorManager | None = None self.optical_prediction = OpticalPrediction(client=self) self.tasks = MxTasks(self) + self.task_queue: MxTaskQueue | None = None def start(self): super().start() self._start_actor_manager() + self.task_queue = MxTaskQueue(self, self.tasks) + self.task_queue.start() self.connector.register(TaskEndpoints.task_request(), cb=self._on_task_request) self.status = messages.BECStatus.RUNNING @@ -78,4 +81,7 @@ class AareBec(BECClient): self.actor_manager = None if self.started: # the connector only exists once the client has been started self.connector.unregister(TaskEndpoints.task_request(), cb=self._on_task_request) + if self.task_queue is not None: + self.task_queue.shutdown() + self.task_queue = None super().shutdown(per_thread_timeout_s) diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index a8e3811..ecee110 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -2,16 +2,18 @@ from __future__ import annotations import functools import inspect -from threading import RLock +from threading import Event, RLock, Thread from typing import TYPE_CHECKING, Callable, ParamSpec, TypeVar +from bec_lib.config_values import RedisConfigValue from bec_lib.logger import bec_logger from mx_bec.devices.smargopolo_smargon import Smargon -from mx_bec.endpoints import StateEndpoints +from mx_bec.endpoints import StateEndpoints, TaskEndpoints from mx_bec.messages import MXMeasurementSequenceMessage if TYPE_CHECKING: + from mx_bec.messages import MXTaskExecutionMessage from mx_bec.service import AareBec logger = bec_logger.logger @@ -73,3 +75,68 @@ class MxTasks: StateEndpoints.optical_centering_done(), MXMeasurementSequenceMessage(sample_id=sample_id, success=success), ) + + +class MxTaskQueue: + """Executes requested tasks one at a time, in order, on a background thread. + + Tasks are popped from the left of the `TaskEndpoints.task_execution()` list and run on the + given `MxTasks`. The queue can be paused through the `TaskEndpoints.task_queue_paused()` + config value (from any client): no new task is popped while paused, but a task which is + already running is left to finish. + """ + + def __init__(self, client: AareBec, tasks: MxTasks, poll_interval_s: float = 0.5) -> None: + self._client = client + self._tasks = tasks + self._poll_interval_s = poll_interval_s + self._stop_event = Event() + self._paused: RedisConfigValue[bool] = RedisConfigValue( + connector=client.connector, endpoint=TaskEndpoints.task_queue_paused() + ) + self._thread = Thread(target=self._run, name="MxTaskQueue", daemon=True) + + @property + def paused(self) -> bool: + return self._paused.value + + def pause(self) -> None: + """Stop taking new tasks from the queue; the current task finishes.""" + self._paused.value = True + + def resume(self) -> None: + """Start taking tasks from the queue again.""" + self._paused.value = False + + def start(self) -> None: + self._thread.start() + + def shutdown(self) -> None: + """Stop the queue thread, waiting for a running task to finish, and drop the Redis + subscription of the paused flag.""" + self._stop_event.set() + if self._thread.is_alive(): + self._thread.join() + self._paused.unregister_all() + + def _run(self) -> None: + while not self._stop_event.is_set(): + if self._paused.value: + self._stop_event.wait(self._poll_interval_s) + continue + msg = self._client.connector.blocking_list_pop( + TaskEndpoints.task_execution(), side="LEFT", timeout_s=self._poll_interval_s + ) + if msg is not None: + self.execute(msg) + + def execute(self, msg: MXTaskExecutionMessage) -> None: + """Run a single task on `MxTasks`. Failures are logged and do not stop the queue.""" + if not MxTasks.is_task(msg.name): + logger.warning(f"Skipping queued task: {msg.name!r} is not a public MxTasks method") + return + logger.info(f"Running task {msg.name} with args={msg.args}, kwargs={msg.kwargs}") + try: + getattr(self._tasks, msg.name)(*msg.args, **msg.kwargs) + except Exception: # pylint: disable=broad-except + logger.exception(f"Task {msg.name} failed") diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py index 702126d..fa62389 100644 --- a/tests/unit/test_service.py +++ b/tests/unit/test_service.py @@ -27,38 +27,49 @@ def test_service_is_idle_before_start(service): assert service.actor_manager is None -def test_start_creates_actor_manager(service): +@pytest.fixture +def started_service(service): + """Run `service.start()` with the BECClient internals and the actor/task machinery mocked.""" service.connector = MagicMock() # normally created by the patched-out BECClient.start with ( patch.object(BECClient, "start") as base_start, patch("mx_bec.service.AareActorManager") as manager_cls, + patch("mx_bec.service.MxTaskQueue") as queue_cls, patch.object(AareBec, "status", create=True), ): service.start() + yield service, base_start, manager_cls, queue_cls + + +def test_start_creates_actor_manager(started_service): + service, base_start, manager_cls, _ = started_service 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): +def test_start_creates_and_starts_task_queue(started_service): + service, _, _, queue_cls = started_service + queue_cls.assert_called_once_with(service, service.tasks) + queue_cls.return_value.start.assert_called_once() + assert service.task_queue is queue_cls.return_value + + +def test_shutdown_stops_actor_manager_and_task_queue(service): service.actor_manager = MagicMock() - manager = service.actor_manager + service.task_queue = MagicMock() + manager, queue = service.actor_manager, service.task_queue with patch.object(BECClient, "shutdown") as base_shutdown: service.shutdown() manager.shutdown.assert_called_once() + queue.shutdown.assert_called_once() base_shutdown.assert_called_once() assert service.actor_manager is None + assert service.task_queue is None -def test_start_registers_task_execution_callback(service): - # BECClient.start (patched out) is what normally creates the connector - service.connector = MagicMock() - with ( - patch.object(BECClient, "start"), - patch("mx_bec.service.AareActorManager"), - patch.object(AareBec, "status", create=True), - ): - service.start() +def test_start_registers_task_request_callback(started_service): + service, *_ = started_service service.connector.register.assert_called_once_with( TaskEndpoints.task_request(), cb=service._on_task_request ) diff --git a/tests/unit/test_tasks.py b/tests/unit/test_tasks.py new file mode 100644 index 0000000..60101cc --- /dev/null +++ b/tests/unit/test_tasks.py @@ -0,0 +1,129 @@ +import time +from threading import Event +from unittest.mock import MagicMock, call, patch + +import fakeredis +import pytest +from bec_lib.redis_connector import RedisConnector + +from mx_bec.endpoints import TaskEndpoints +from mx_bec.messages import MXTaskExecutionMessage +from mx_bec.tasks import MxTaskQueue, MxTasks + + +@pytest.fixture +def connector(): + conn = RedisConnector("localhost:1", redis_cls=lambda *_, **__: fakeredis.FakeRedis()) + conn._managed_connection.flushall() + yield conn + conn.shutdown() + + +@pytest.fixture +def client(connector): + client = MagicMock() + client.connector = connector + return client + + +@pytest.fixture +def tasks(): + return MagicMock(spec=MxTasks) + + +@pytest.fixture +def queue(client, tasks): + q = MxTaskQueue(client, tasks, poll_interval_s=0.05) + yield q + q.shutdown() + + +def _request(name="run_optical_centering", *args): + return MXTaskExecutionMessage(name=name, args=args, kwargs={}) + + +def _wait_for(predicate, timeout_s=3.0): + deadline = time.monotonic() + timeout_s + while time.monotonic() < deadline: + if predicate(): + return + time.sleep(0.01) + raise AssertionError("condition not met in time") + + +def test_queue_runs_tasks_in_order(connector, queue, tasks): + for sample_id in (1, 2, 3): + connector.rpush( + TaskEndpoints.task_execution(), _request("run_optical_centering", sample_id) + ) + queue.start() + _wait_for(lambda: tasks.run_optical_centering.call_count == 3) + assert tasks.run_optical_centering.call_args_list == [call(1), call(2), call(3)] + assert connector.llen(TaskEndpoints.task_execution()) == 0 + + +def test_queue_does_not_pop_while_paused(connector, queue, tasks): + queue.pause() + connector.rpush(TaskEndpoints.task_execution(), _request("run_optical_centering", 1)) + queue.start() + time.sleep(0.3) + tasks.run_optical_centering.assert_not_called() + assert connector.llen(TaskEndpoints.task_execution()) == 1 + + queue.resume() + _wait_for(lambda: tasks.run_optical_centering.call_count == 1) + assert connector.llen(TaskEndpoints.task_execution()) == 0 + + +def test_paused_flag_is_shared_through_redis(connector, queue): + # another client (here: a second config value on the same endpoint) can pause the queue + other = MagicMock() + other.connector = connector + other_queue = MxTaskQueue(other, MagicMock(spec=MxTasks)) + try: + assert not queue.paused + other_queue.pause() + _wait_for(lambda: queue.paused) + other_queue.resume() + _wait_for(lambda: not queue.paused) + finally: + other_queue.shutdown() + + +def test_queue_skips_non_task_names(connector, queue, tasks): + connector.rpush(TaskEndpoints.task_execution(), _request("_publish_optical_centering_done", 1)) + connector.rpush(TaskEndpoints.task_execution(), _request("run_optical_centering", 2)) + with patch("mx_bec.tasks.logger") as logger: + queue.start() + _wait_for(lambda: tasks.run_optical_centering.call_count == 1) + tasks.run_optical_centering.assert_called_once_with(2) + tasks._publish_optical_centering_done.assert_not_called() + logger.warning.assert_called_once() + + +def test_failed_task_is_logged_and_queue_continues(connector, queue, tasks): + tasks.run_optical_centering.side_effect = [RuntimeError("boom"), None] + connector.rpush(TaskEndpoints.task_execution(), _request("run_optical_centering", 1)) + connector.rpush(TaskEndpoints.task_execution(), _request("run_optical_centering", 2)) + with patch("mx_bec.tasks.logger") as logger: + queue.start() + _wait_for(lambda: tasks.run_optical_centering.call_count == 2) + logger.exception.assert_called_once() + assert tasks.run_optical_centering.call_args_list == [call(1), call(2)] + + +def test_shutdown_waits_for_running_task(connector, queue, tasks): + started, release = Event(), Event() + + def slow_task(*_): + started.set() + release.wait(timeout=3) + + tasks.run_optical_centering.side_effect = slow_task + connector.rpush(TaskEndpoints.task_execution(), _request("run_optical_centering", 1)) + queue.start() + assert started.wait(timeout=3) + assert queue._thread.is_alive() + release.set() + queue.shutdown() + assert not queue._thread.is_alive() -- 2.54.1 From bd445867ac23db117274809ea910e618ccbe8bd3 Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 3 Nov 2026 09:30:16 +0100 Subject: [PATCH 07/46] feat: add queue widget --- .../widgets/aare_bec/task_queue.py | 100 ++++++++++++++++++ mx_bec/endpoints.py | 11 ++ mx_bec/messages.py | 7 ++ mx_bec/service.py | 2 + mx_bec/tasks.py | 5 +- tests/unit/test_service.py | 12 ++- tests/unit/test_tasks.py | 18 +++- 7 files changed, 151 insertions(+), 4 deletions(-) create mode 100644 mx_bec/bec_widgets/widgets/aare_bec/task_queue.py diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py b/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py new file mode 100644 index 0000000..7212b87 --- /dev/null +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py @@ -0,0 +1,100 @@ +from __future__ import annotations + +from bec_lib.config_values import RedisConfigValue +from bec_lib.logger import bec_logger +from bec_widgets.utils.bec_connector import ConnectionConfig +from bec_widgets.utils.bec_widget import BECWidget +from bec_widgets.utils.error_popups import SafeSlot +from bec_widgets.widgets.utility.toggle.toggle import ToggleSwitch +from qtpy.QtCore import Signal +from qtpy.QtWidgets import QHBoxLayout, QLabel, QListWidget, QVBoxLayout, QWidget + +from mx_bec.endpoints import TaskEndpoints + +logger = bec_logger.logger + + +class MxTaskQueueWidget(BECWidget, QWidget): + """ + Widget to pause/resume the MX task queue and show the tasks waiting in it. + + The toggle is bound to the `task_queue_paused` flag in Redis (checked = running), the list + is re-read from the task execution queue whenever the service announces a change on + `task_queue_changed`. + """ + + PLUGIN = True + ICON_NAME = "pending_actions" + USER_ACCESS = ["refresh"] + + # Redis callbacks arrive on the connector thread; re-emit so the toggle is updated on the GUI + # thread. + _paused_changed = Signal(bool) + + def __init__( + self, + parent: QWidget | None = None, + client=None, + config: ConnectionConfig | None = None, + gui_id: str | None = None, + **kwargs, + ) -> None: + super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs) + self._paused: RedisConfigValue[bool] = RedisConfigValue( + connector=self.client.connector, + endpoint=TaskEndpoints.task_queue_paused(), + wait_for_writes=False, + ) + # RedisConfigValue keeps a weak ref to the subscriber, which must be a bound method + self._paused.subscribe(self._emit_paused_changed) + self._paused_changed.connect(self._on_paused_changed) + + self._toggle = ToggleSwitch(parent=self, checked=not self._paused.value) + self._toggle.stateChanged.connect(self._set_running) + self._list = QListWidget(parent=self) + + layout = QVBoxLayout(self) + header = QHBoxLayout() + header.addWidget(QLabel("Task queue running", parent=self)) + header.addWidget(self._toggle) + header.addStretch() + layout.addLayout(header) + layout.addWidget(QLabel("Queued tasks", parent=self)) + layout.addWidget(self._list) + + # released automatically by BECWidget.cleanup() (disconnect_owner) + self.bec_dispatcher.connect_slot(self._on_queue_changed, TaskEndpoints.task_queue_changed()) + self.refresh() + + @SafeSlot() + def refresh(self): + """Reload the queued tasks from Redis.""" + tasks = self.client.connector.lrange(TaskEndpoints.task_execution(), 0, -1) + self._list.clear() + for msg in tasks: + args = ", ".join( + [repr(a) for a in msg.args] + [f"{k}={v!r}" for k, v in msg.kwargs.items()] + ) + self._list.addItem(f"{msg.name}({args})") + + @SafeSlot(dict, dict) + def _on_queue_changed(self, _content: dict, _metadata: dict): + self.refresh() + + def _emit_paused_changed(self, paused: bool): + self._paused_changed.emit(paused) + + @SafeSlot(bool) + def _set_running(self, running: bool): + self._paused.value = not running + + @SafeSlot(bool) + def _on_paused_changed(self, paused: bool): + # Don't write the value we just received straight back to Redis. + self._toggle.blockSignals(True) + self._toggle.setChecked(not paused) + self._toggle.blockSignals(False) + + def cleanup(self): + self._paused.unregister_all() + super().cleanup() diff --git a/mx_bec/endpoints.py b/mx_bec/endpoints.py index 2b17356..ee9e607 100644 --- a/mx_bec/endpoints.py +++ b/mx_bec/endpoints.py @@ -4,6 +4,7 @@ from bec_lib.messages import AvailableResourceMessage, BoolConfigDefaultFalse from mx_bec.messages import ( MXMeasurementSequenceMessage, MXTaskExecutionMessage, + MXTaskQueueChangedMessage, OpticalPredictionMessage, ) @@ -91,6 +92,16 @@ class TaskEndpoints: message_op=MessageOp.LIST, ) + @staticmethod + def task_queue_changed(): + """Pub/sub channel on which the AareBec service announces changes to the execution + queue, so that clients know to re-read it.""" + return EndpointInfo( + endpoint=f"{EndpointType.USER.value}/mx/tasks/queue_changed", + message_type=MXTaskQueueChangedMessage, + message_op=MessageOp.SEND, + ) + @staticmethod def task_queue_paused(): """Managed bool: whether the AareBec service should stop taking tasks from the execution diff --git a/mx_bec/messages.py b/mx_bec/messages.py index 38f1e9c..1805280 100644 --- a/mx_bec/messages.py +++ b/mx_bec/messages.py @@ -25,6 +25,13 @@ class MXTaskExecutionMessage(BECMessage): kwargs: dict[str, int | bool | str | float | None] +class MXTaskQueueChangedMessage(BECMessage): + """Notification that the task execution queue changed; carries no data, subscribers + re-read the queue.""" + + msg_type: ClassVar[str] = "mx_task_queue_changed_message" + + class OpticalPredictionMessage(BECMessage): """The latest optical image analysis prediction""" diff --git a/mx_bec/service.py b/mx_bec/service.py index 9a5dc63..6e4f7ba 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -11,6 +11,7 @@ from bec_lib.logger import bec_logger from mx_bec.actor_manager import AareActorManager from mx_bec.constants import AareBecWorkflowState from mx_bec.endpoints import TaskEndpoints +from mx_bec.messages import MXTaskQueueChangedMessage from mx_bec.optical_centering import OpticalPrediction from mx_bec.tasks import MxTaskQueue, MxTasks @@ -64,6 +65,7 @@ class AareBec(BECClient): return logger.info(f"Queueing task request: {msg}") self.connector.rpush(TaskEndpoints.task_execution(), msg) + self.connector.send(TaskEndpoints.task_queue_changed(), MXTaskQueueChangedMessage()) @property def devices(self): diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index ecee110..3904df1 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -10,7 +10,7 @@ from bec_lib.logger import bec_logger from mx_bec.devices.smargopolo_smargon import Smargon from mx_bec.endpoints import StateEndpoints, TaskEndpoints -from mx_bec.messages import MXMeasurementSequenceMessage +from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskQueueChangedMessage if TYPE_CHECKING: from mx_bec.messages import MXTaskExecutionMessage @@ -128,6 +128,9 @@ class MxTaskQueue: TaskEndpoints.task_execution(), side="LEFT", timeout_s=self._poll_interval_s ) if msg is not None: + self._client.connector.send( + TaskEndpoints.task_queue_changed(), MXTaskQueueChangedMessage() + ) self.execute(msg) def execute(self, msg: MXTaskExecutionMessage) -> None: diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py index fa62389..9cb5c91 100644 --- a/tests/unit/test_service.py +++ b/tests/unit/test_service.py @@ -7,7 +7,11 @@ from bec_lib.tests.utils import ConnectorMock from mx_bec.constants import AareBecWorkflowState from mx_bec.endpoints import StateEndpoints, TaskEndpoints -from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskExecutionMessage +from mx_bec.messages import ( + MXMeasurementSequenceMessage, + MXTaskExecutionMessage, + MXTaskQueueChangedMessage, +) from mx_bec.service import AareBec, MxTasks @@ -91,11 +95,14 @@ def test_shutdown_before_start_does_not_touch_connector(service): base_shutdown.assert_called_once() -def test_task_request_for_known_method_is_queued(service): +def test_task_request_for_known_method_is_queued_and_announced(service): service.connector = MagicMock() msg = MXTaskExecutionMessage(name="run_optical_centering", args=(3,), kwargs={}) service._on_task_request({"data": msg}) service.connector.rpush.assert_called_once_with(TaskEndpoints.task_execution(), msg) + service.connector.send.assert_called_once_with( + TaskEndpoints.task_queue_changed(), MXTaskQueueChangedMessage() + ) NOT_TASKS = [ @@ -115,6 +122,7 @@ def test_task_request_for_non_task_name_is_rejected(service, name): with patch("mx_bec.service.logger") as logger: service._on_task_request({"data": msg}) service.connector.rpush.assert_not_called() + service.connector.send.assert_not_called() logger.warning.assert_called_once() assert name in logger.warning.call_args.args[0] diff --git a/tests/unit/test_tasks.py b/tests/unit/test_tasks.py index 60101cc..1c177fd 100644 --- a/tests/unit/test_tasks.py +++ b/tests/unit/test_tasks.py @@ -7,7 +7,7 @@ import pytest from bec_lib.redis_connector import RedisConnector from mx_bec.endpoints import TaskEndpoints -from mx_bec.messages import MXTaskExecutionMessage +from mx_bec.messages import MXTaskExecutionMessage, MXTaskQueueChangedMessage from mx_bec.tasks import MxTaskQueue, MxTasks @@ -62,6 +62,22 @@ def test_queue_runs_tasks_in_order(connector, queue, tasks): assert connector.llen(TaskEndpoints.task_execution()) == 0 +def test_queue_announces_each_pop(connector, queue): + notifications = [] + + def on_changed(msg): # the connector keeps a weak ref: must be a function, not list.append + notifications.append(msg) + + connector.register(TaskEndpoints.task_queue_changed(), cb=on_changed) + for sample_id in (1, 2): + connector.rpush( + TaskEndpoints.task_execution(), _request("run_optical_centering", sample_id) + ) + queue.start() + _wait_for(lambda: len(notifications) == 2) + assert all(n.value == MXTaskQueueChangedMessage() for n in notifications) + + def test_queue_does_not_pop_while_paused(connector, queue, tasks): queue.pause() connector.rpush(TaskEndpoints.task_execution(), _request("run_optical_centering", 1)) -- 2.54.1 From 797f29e1fc49064def34ae6637390a230f0cd03a Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 3 Nov 2026 09:38:15 +0100 Subject: [PATCH 08/46] feat: add task panel widget --- .../widgets/aare_bec/task_panel.py | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 mx_bec/bec_widgets/widgets/aare_bec/task_panel.py diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py new file mode 100644 index 0000000..7ab6309 --- /dev/null +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +from bec_lib.logger import bec_logger +from bec_widgets.utils.bec_connector import ConnectionConfig +from bec_widgets.utils.bec_widget import BECWidget +from bec_widgets.utils.error_popups import SafeSlot +from qtpy.QtWidgets import ( + QFormLayout, + QGroupBox, + QHBoxLayout, + QPushButton, + QSpinBox, + QVBoxLayout, + QWidget, +) + +from mx_bec.endpoints import TaskEndpoints +from mx_bec.messages import MXTaskExecutionMessage + +logger = bec_logger.logger + + +class MxTaskPanel(BECWidget, QWidget): + """ + Testing panel to submit tasks to the AareBec task request stream: one hard-coded form and + "Run" button per task. + """ + + PLUGIN = True + ICON_NAME = "play_arrow" + USER_ACCESS = ["request_task"] + + def __init__( + self, + parent: QWidget | None = None, + client=None, + config: ConnectionConfig | None = None, + gui_id: str | None = None, + **kwargs, + ) -> None: + super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs) + layout = QVBoxLayout(self) + layout.addWidget(self._optical_centering_box()) + layout.addStretch() + + def _optical_centering_box(self) -> QGroupBox: + box = QGroupBox("run_optical_centering", parent=self) + self._sample_id = QSpinBox(parent=box) + self._sample_id.setRange(0, 1_000_000) + run = QPushButton("Run", parent=box) + run.clicked.connect(self._run_optical_centering) + form = QFormLayout() + form.addRow("sample_id", self._sample_id) + layout = QHBoxLayout(box) + layout.addLayout(form) + layout.addWidget(run) + return box + + @SafeSlot() + def _run_optical_centering(self): + self.request_task("run_optical_centering", self._sample_id.value()) + + @SafeSlot(str) + def request_task(self, name: str, *args, **kwargs): + """Submit a task request to the AareBec service.""" + msg = MXTaskExecutionMessage(name=name, args=args, kwargs=kwargs) + logger.info(f"Requesting task: {msg}") + self.client.connector.xadd(TaskEndpoints.task_request(), {"data": msg}) -- 2.54.1 From f4fb2ff1080905395ec00ea0dca92543bce31a27 Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 3 Nov 2026 10:08:18 +0100 Subject: [PATCH 09/46] feat: add jfjoch raster --- mx_bec/jfjoch.py | 189 ++++++++++++++++++++++++++++++++++++++ mx_bec/service.py | 2 + tests/unit/test_jfjoch.py | 152 ++++++++++++++++++++++++++++++ 3 files changed, 343 insertions(+) create mode 100644 mx_bec/jfjoch.py create mode 100644 tests/unit/test_jfjoch.py diff --git a/mx_bec/jfjoch.py b/mx_bec/jfjoch.py new file mode 100644 index 0000000..4536851 --- /dev/null +++ b/mx_bec/jfjoch.py @@ -0,0 +1,189 @@ +from __future__ import annotations + +import functools +import math +from typing import TYPE_CHECKING, Callable, ParamSpec, TypeVar + +import jfjoch_client +from aarecommon.config.beamline import get_jfjoch_url, mx_beamline +from bec_lib.logger import bec_logger +from jfjoch_client.models.dataset_settings_smargon import DatasetSettingsSmargon +from pydantic import BaseModel, Field + +if TYPE_CHECKING: + from jfjoch_client.models.scan_result import ScanResult + + from mx_bec.service import AareBec + +logger = bec_logger.logger + +P = ParamSpec("P") +R = TypeVar("R") + + +class RasterScan(BaseModel): + """Everything JFJoch needs to collect one raster (grid) scan.""" + + # grid: n_x columns by n_y rows, stepped by step_*_mm, at a fixed omega + n_x: int = Field(ge=1) + n_y: int = Field(ge=1) + step_x_mm: float = Field(gt=0) + step_y_mm: float = Field(gt=0) + omega_deg: float + # exposure + exp_time_s: float = Field(gt=0) + detector_distance_mm: float = Field(gt=0) + transmission: float = Field(ge=0, le=1) + # output: files go to /raw/raster/ + file_prefix: str + pgroup: str = "p16371" + sample_name: str = "unknown_sample" + # beamline and diffraction geometry + energy_keV: float = Field(gt=0) + beam_center_pxl: tuple[float, float] + beam_size_mm: tuple[float, float] + poni_rot1_rad: float = 0.0 + poni_rot2_rad: float = 0.0 + ring_current_mA: float + flux_ph_s: float + sample_temperature_K: float + smargon_phi_deg: float | None = None + smargon_chi_deg: float | None = None + + +class JFJochError(RuntimeError): + """A call to the JFJoch detector broker failed.""" + + +def needs_connection(method: Callable[P, R]) -> Callable[P, R]: + """Connect to JFJoch before the decorated method touches the API.""" + + @functools.wraps(method) + def wrapper(self: JFJoch, *args, **kwargs): + self.connect() + return method(self, *args, **kwargs) + + return wrapper # type: ignore # self is part of P + + +class JFJoch: + """Thin wrapper around the JFJoch detector broker REST API, for raster (grid) scans. + + Adapted from aaredaq's `JFJochWrapper`: the client is created on first use and every API + call is wrapped so that failures raise `JFJochError`. + """ + + def __init__(self, client: AareBec, url: str | None = None) -> None: + self._client = client + self._url = url + self._api: jfjoch_client.DefaultApi | None = None + + @property + def url(self) -> str: + """The broker URL: as given, else resolved on first use from the aarecommon beamline + config, which picks the beamline from the BEAMLINE environment variable.""" + if self._url is None: + self._url = get_jfjoch_url(mx_beamline()) + return self._url + + def connect(self) -> None: + """Create the API client on first use and cancel anything JFJoch is still doing.""" + if self._api is not None: + return + api_client = jfjoch_client.ApiClient(jfjoch_client.Configuration(host=self.url)) + self._api = jfjoch_client.DefaultApi(api_client) + try: + self.cancel() + except JFJochError: + self._api = None + raise + + def _call(self, endpoint: str, *args, **kwargs): + """Call `endpoint` on the API, turning any failure into a JFJochError.""" + assert self._api is not None, "connect() must be called first" + try: + return getattr(self._api, endpoint)(*args, **kwargs) + except Exception as e: + raise JFJochError(f"JFJoch {endpoint} failed: {e}") from e + + @needs_connection + def cancel(self) -> None: + self._call("cancel_post") + + @needs_connection + def measure_raster(self, scan: RasterScan, async_start: bool = True) -> None: + """Start a raster scan data collection; wait with `wait_till_running` / `wait_till_done`.""" + self._call("start_post", dataset_settings=self.dataset_settings(scan, async_start)) + + @needs_connection + def wait_till_running(self, timeout_s: float = 60) -> None: + """Block until JFJoch reports the detector armed, or raise.""" + logger.info("Waiting for JFJoch to report detector armed") + try: + self._call("wait_until_running_post_with_http_info", timeout=math.ceil(timeout_s)) + except JFJochError as e: + if "Output file already exists" in str(e): + raise JFJochError( + "JFJoch reports the output file already exists: change the file name or " + "increment the run number." + ) from e + raise + status = self._call("status_get") + logger.debug(status) + if status.message_severity == "error": + raise JFJochError(f"JFJoch reported an error after arming: {status.message}") + + @needs_connection + def wait_till_done(self, timeout_s: float) -> ScanResult: + """Block until the running data collection finished and return its result.""" + self._call("wait_till_done_post_with_http_info", timeout=math.ceil(timeout_s)) + return self._call("result_scan_get") + + def dataset_settings( + self, scan: RasterScan, async_start: bool = True + ) -> jfjoch_client.DatasetSettings: + """Build the JFJoch dataset settings for a raster scan.""" + # a single column is collected as one trigger with n_y images + ntrigger, images = (1, scan.n_y) if scan.n_x == 1 else (scan.n_y, scan.n_x) + if scan.smargon_phi_deg is not None and scan.smargon_chi_deg is not None: + smargon = DatasetSettingsSmargon( + phi_deg=scan.smargon_phi_deg, chi_deg=max(scan.smargon_chi_deg, 0) + ) + else: + smargon = None + return jfjoch_client.DatasetSettings( + beam_x_pxl=scan.beam_center_pxl[0], + beam_y_pxl=scan.beam_center_pxl[1], + ntrigger=ntrigger, + images_per_trigger=images, + detector_distance_mm=scan.detector_distance_mm, + file_prefix=f"{scan.pgroup}/raw/raster/{scan.file_prefix}", + incident_energy_keV=scan.energy_keV, + sample_name=scan.sample_name, + image_time_us=round(scan.exp_time_s * 1e6), + experiment_group=scan.pgroup, + transmission=scan.transmission, + ring_current_mA=scan.ring_current_mA, + sample_temperature_K=scan.sample_temperature_K, + total_flux=scan.flux_ph_s * scan.transmission, + poni_rot1_rad=scan.poni_rot1_rad, + poni_rot2_rad=scan.poni_rot2_rad, + max_spot_count=1000, + detect_ice_rings=True, + async_start=async_start, + smargon=smargon, + beam_size_x_um=scan.beam_size_mm[0] * 1000.0, + beam_size_y_um=scan.beam_size_mm[1] * 1000.0, + polarization_factor=1.0, + images_per_file=self._client.aare_config.jfjoch.n_images_per_file or None, + goniometer=jfjoch_client.RotationAxis( + step=0, start=scan.omega_deg, name="omega", vector=[-1, 0, 0], screening_wedge_deg=0 + ), + grid_scan=jfjoch_client.GridScan( + n_fast=scan.n_x, + snake=True, + step_x_um=scan.step_x_mm * 1000.0, + step_y_um=scan.step_y_mm * 1000.0, + vertical=False, + ), + ) diff --git a/mx_bec/service.py b/mx_bec/service.py index 6e4f7ba..6cfc0bb 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -11,6 +11,7 @@ from bec_lib.logger import bec_logger from mx_bec.actor_manager import AareActorManager from mx_bec.constants import AareBecWorkflowState from mx_bec.endpoints import TaskEndpoints +from mx_bec.jfjoch import JFJoch from mx_bec.messages import MXTaskQueueChangedMessage from mx_bec.optical_centering import OpticalPrediction from mx_bec.tasks import MxTaskQueue, MxTasks @@ -45,6 +46,7 @@ class AareBec(BECClient): self.workflow_state = AareBecWorkflowState.IDLE self.actor_manager: AareActorManager | None = None self.optical_prediction = OpticalPrediction(client=self) + self.jfjoch = JFJoch(client=self) # connects lazily on first use self.tasks = MxTasks(self) self.task_queue: MxTaskQueue | None = None diff --git a/tests/unit/test_jfjoch.py b/tests/unit/test_jfjoch.py new file mode 100644 index 0000000..4b3bd81 --- /dev/null +++ b/tests/unit/test_jfjoch.py @@ -0,0 +1,152 @@ +from unittest.mock import MagicMock, patch + +import pytest +from pydantic import ValidationError + +from mx_bec.jfjoch import JFJoch, JFJochError, RasterScan + + +@pytest.fixture +def api(): + with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client: + yield jfjoch_client.DefaultApi.return_value + + +@pytest.fixture +def client(): + client = MagicMock() + client.aare_config.jfjoch.n_images_per_file = 100 + return client + + +@pytest.fixture +def jfjoch(client, api): + return JFJoch(client, url="http://jfjoch:8080") + + +def _scan(**overrides) -> RasterScan: + params = dict( + n_x=3, + n_y=2, + step_x_mm=0.05, + step_y_mm=0.04, + omega_deg=12.0, + exp_time_s=0.1, + detector_distance_mm=150.0, + transmission=0.5, + file_prefix="test", + energy_keV=12.658, + beam_center_pxl=(1000.0, 1100.0), + beam_size_mm=(0.02, 0.01), + ring_current_mA=400.0, + flux_ph_s=1e12, + sample_temperature_K=100.0, + smargon_phi_deg=10.0, + smargon_chi_deg=-5.0, + ) + return RasterScan(**{**params, **overrides}) + + +def test_url_is_resolved_from_beamline_config_on_first_use(client, monkeypatch): + monkeypatch.delenv("BEAMLINE", raising=False) + jfjoch = JFJoch(client) # must not need BEAMLINE yet + with ( + patch("mx_bec.jfjoch.mx_beamline", return_value="X10SA") as beamline, + patch("mx_bec.jfjoch.get_jfjoch_url", return_value="http://gpu:8080") as get_url, + ): + assert jfjoch.url == "http://gpu:8080" + assert jfjoch.url == "http://gpu:8080" + get_url.assert_called_once_with("X10SA") + beamline.assert_called_once() + + +def test_connects_lazily_and_cancels_once(jfjoch, api): + api.cancel_post.assert_not_called() + jfjoch.measure_raster(_scan()) + jfjoch.measure_raster(_scan()) + api.cancel_post.assert_called_once() + assert api.start_post.call_count == 2 + + +def test_failed_cancel_on_connect_leaves_it_disconnected(jfjoch, api): + api.cancel_post.side_effect = RuntimeError("down") + with pytest.raises(JFJochError, match="cancel_post failed: down"): + jfjoch.wait_till_done(timeout_s=1) + assert jfjoch._api is None + + +def test_wait_till_running_reports_existing_output_file(jfjoch, api): + api.wait_until_running_post_with_http_info.side_effect = RuntimeError( + "Output file already exists" + ) + with pytest.raises(JFJochError, match="output file already exists"): + jfjoch.wait_till_running(timeout_s=1.5) + api.wait_until_running_post_with_http_info.assert_called_once_with(timeout=2) + + +def test_wait_till_running_raises_on_error_status(jfjoch, api): + api.status_get.return_value.message_severity = "error" + api.status_get.return_value.message = "detector unhappy" + with pytest.raises(JFJochError, match="detector unhappy"): + jfjoch.wait_till_running() + + +def test_wait_till_done_returns_scan_result(jfjoch, api): + assert jfjoch.wait_till_done(timeout_s=10.2) is api.result_scan_get.return_value + api.wait_till_done_post_with_http_info.assert_called_once_with(timeout=11) + + +def test_measure_raster_builds_grid_dataset_settings(jfjoch): + # re-patch to capture the DatasetSettings constructor; connect() happens inside, so the + # API mock to check is this patch's, not the `api` fixture's + with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client: + jfjoch.measure_raster(_scan()) + settings = jfjoch_client.DatasetSettings.call_args.kwargs + assert settings["ntrigger"] == 2 and settings["images_per_trigger"] == 3 + assert settings["file_prefix"] == "p16371/raw/raster/test" + assert settings["experiment_group"] == "p16371" + assert settings["sample_name"] == "unknown_sample" + assert settings["image_time_us"] == 100_000 + assert settings["total_flux"] == 5e11 + assert settings["beam_x_pxl"] == 1000.0 and settings["beam_y_pxl"] == 1100.0 + assert settings["beam_size_x_um"] == 20.0 and settings["beam_size_y_um"] == 10.0 + assert settings["images_per_file"] == 100 + jfjoch_client.GridScan.assert_called_once_with( + n_fast=3, snake=True, step_x_um=50.0, step_y_um=40.0, vertical=False + ) + jfjoch_client.RotationAxis.assert_called_once_with( + step=0, start=12.0, name="omega", vector=[-1, 0, 0], screening_wedge_deg=0 + ) + jfjoch_client.DefaultApi.return_value.start_post.assert_called_once_with( + dataset_settings=jfjoch_client.DatasetSettings.return_value + ) + + +def test_single_column_raster_is_one_trigger(jfjoch): + with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client: + jfjoch.dataset_settings(_scan(n_x=1, n_y=4)) + settings = jfjoch_client.DatasetSettings.call_args.kwargs + assert settings["ntrigger"] == 1 and settings["images_per_trigger"] == 4 + + +def test_dataset_settings_clamps_negative_chi(jfjoch): + with patch("mx_bec.jfjoch.DatasetSettingsSmargon") as smargon: + jfjoch.dataset_settings(_scan()) + smargon.assert_called_once_with(phi_deg=10.0, chi_deg=0) + + +def test_dataset_settings_without_smargon_angles(jfjoch): + with ( + patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client, + patch("mx_bec.jfjoch.DatasetSettingsSmargon") as smargon, + ): + jfjoch.dataset_settings(_scan(smargon_phi_deg=None)) + smargon.assert_not_called() + assert jfjoch_client.DatasetSettings.call_args.kwargs["smargon"] is None + + +def test_raster_scan_validates_fields(): + with pytest.raises(ValidationError): + _scan(n_x=0) + with pytest.raises(ValidationError): + _scan(transmission=1.5) -- 2.54.1 From b7c82b65c17ef447cd97e3c75190fe2fbf890ba6 Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 3 Nov 2026 10:23:10 +0100 Subject: [PATCH 10/46] feat: vibe-copy raster task from aaredaq --- mx_bec/devices/aerotech.py | 49 +++++++++++++++ mx_bec/tasks.py | 73 ++++++++++++++++++++++ tests/unit/test_aerotech.py | 94 ++++++++++++++++++++++++++++ tests/unit/test_grid_scan_task.py | 100 ++++++++++++++++++++++++++++++ 4 files changed, 316 insertions(+) create mode 100644 tests/unit/test_aerotech.py create mode 100644 tests/unit/test_grid_scan_task.py diff --git a/mx_bec/devices/aerotech.py b/mx_bec/devices/aerotech.py index f51bb50..952a98e 100644 --- a/mx_bec/devices/aerotech.py +++ b/mx_bec/devices/aerotech.py @@ -5,6 +5,7 @@ from ophyd import Component as Cpt from ophyd import Kind from ophyd.device import Device from ophyd.signal import Signal +from ophyd_devices.utils.psi_device_base_utils import StatusBase from requests import RequestException from .http import ( @@ -85,6 +86,9 @@ class RotationScanParameters(ValidatedHttpParams): class AerotechController(HttpDeviceControllerWithConfigVelocity): _readback_endpoint = "/status" _target_endpoint = "/position" + _grid_scan_endpoint = "/grid_scan" + _wait_till_done_endpoint = "/wait_till_done" + MAX_WAIT_TILL_DONE_S = 3600 # upper bound of the AareScan timeout parameter def __init__(self, *, prefix, **kwargs): self._readbacks: dict[str, dict[str, float | bool]] = {} @@ -100,9 +104,23 @@ class AerotechController(HttpDeviceControllerWithConfigVelocity): return None return self._readbacks.get(axis_id)["pos"], self._readbacks.get(TIMESTAMP_ID) # type: ignore + def start_grid_scan(self, body: dict): + """Start a grid scan with the given (validated) request body, returning immediately.""" + self._rest_post(body={**body, "run_async": True}, endpoint=self._grid_scan_endpoint) + + def wait_till_done(self, timeout_s: float): + """Block until AareScan is idle again. Raises HttpRestError on timeout (504).""" + timeout = min(max(int(round(timeout_s)), 0), self.MAX_WAIT_TILL_DONE_S) + self._rest_post(params={"timeout": timeout}, endpoint=self._wait_till_done_endpoint) + class Aerotech(HttpOphydDevice): + """Aerotech sample stage driven through the AareScan REST API. Triggering runs the grid scan + configured in `gridscan_config`.""" + controller_class = AerotechController + # margin on top of the expected grid scan duration before giving up waiting for it + GRID_SCAN_TIMEOUT_MARGIN_S = 60.0 gridscan_config = Cpt(GridscanParameters) screening_config = Cpt(ScreeningParameters) @@ -124,6 +142,37 @@ class Aerotech(HttpOphydDevice): config.validate() return ret + ######################################## + # Beamline Specific Implementations # + ######################################## + + def on_trigger(self) -> StatusBase: + """Start the grid scan from `gridscan_config`; the returned status finishes once AareScan + reports the scan done.""" + config = self.gridscan_config + if not config.valid.get(): + raise ValueError(f"Grid scan parameters are not valid: {config.message.get()}") + body = config.request_body() + self.controller.start_grid_scan(body) + status = self.task_handler.submit_task( + self.controller.wait_till_done, task_kwargs={"timeout_s": self.grid_scan_timeout_s()} + ) + self.cancel_on_stop(status) + return status + + ######################################## + # Helper Methods # + ######################################## + + def expected_grid_scan_s(self) -> float: + """Expected duration of the configured grid scan (exposure plus ~0.3 s per line).""" + config = self.gridscan_config + n_x, n_y = config.grid_elem_count_x.get(), config.grid_elem_count_y.get() + return config.time_per_element_sec.get() * n_x * n_y + n_y * 0.3 + + def grid_scan_timeout_s(self) -> float: + return self.expected_grid_scan_s() * 1.1 + self.GRID_SCAN_TIMEOUT_MARGIN_S + def _test(): a = Aerotech(name="aerotech", prefix="http://mx-x10sa-queue-01:5234") diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index 3904df1..c27e7a5 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -10,6 +10,7 @@ from bec_lib.logger import bec_logger from mx_bec.devices.smargopolo_smargon import Smargon from mx_bec.endpoints import StateEndpoints, TaskEndpoints +from mx_bec.jfjoch import RasterScan from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskQueueChangedMessage if TYPE_CHECKING: @@ -21,6 +22,8 @@ logger = bec_logger.logger P = ParamSpec("P") R = TypeVar("R") +MAX_GRID_SCAN_S = 1200.0 # refuse grid scans expected to take longer than 20 min + class MxTasks: """Holder for operations on mx beamlines. Probably needs to be reconsidered @@ -76,6 +79,76 @@ class MxTasks: MXMeasurementSequenceMessage(sample_id=sample_id, success=success), ) + @with_lock + def run_grid_scan( + self, + n_x: int, + n_y: int, + step_x_um: float, + step_y_um: float, + exp_time_s: float, + file_prefix: str, + detector_distance_mm: float, + transmission: float, + energy_keV: float, + beam_center_x_pxl: float, + beam_center_y_pxl: float, + beam_size_x_mm: float, + beam_size_y_mm: float, + ring_current_mA: float, + flux_ph_s: float, + sample_temperature_K: float, + pgroup: str = "p16371", + sample_name: str = "unknown_sample", + ) -> None: + """Collect an n_x by n_y grid scan at the current position and omega: configure the + Aerotech grid scan and check that AareScan accepts it, arm JFJoch, then trigger the + Aerotech and wait for both to finish.""" + expected_s = exp_time_s * n_x * n_y + n_y * 0.3 + if expected_s > MAX_GRID_SCAN_S: + raise ValueError(f"Grid scan is too long: {expected_s:.0f} s > {MAX_GRID_SCAN_S} s") + + aerotech = self._client.devices.aerotech + config = aerotech.gridscan_config + for signal, value in ( + (config.grid_elem_count_x, n_x), + (config.grid_elem_count_y, n_y), + (config.grid_elem_size_x_um, step_x_um), + (config.grid_elem_size_y_um, step_y_um), + (config.time_per_element_sec, exp_time_s), + ): + signal.set(value).wait() + if not config.valid.get(): + raise ValueError(f"AareScan rejected the grid scan parameters: {config.message.get()}") + + jfjoch = self._client.jfjoch + jfjoch.measure_raster( + RasterScan( + n_x=n_x, + n_y=n_y, + step_x_mm=step_x_um / 1000.0, + step_y_mm=step_y_um / 1000.0, + omega_deg=aerotech.u.get(), + exp_time_s=exp_time_s, + detector_distance_mm=detector_distance_mm, + transmission=transmission, + file_prefix=file_prefix, + pgroup=pgroup, + sample_name=sample_name, + energy_keV=energy_keV, + beam_center_pxl=(beam_center_x_pxl, beam_center_y_pxl), + beam_size_mm=(beam_size_x_mm, beam_size_y_mm), + ring_current_mA=ring_current_mA, + flux_ph_s=flux_ph_s, + sample_temperature_K=sample_temperature_K, + ) + ) + jfjoch.wait_till_running(timeout_s=60) + logger.info(f"Starting {n_x}x{n_y} grid scan, {exp_time_s} s per element") + aerotech.trigger().wait() + result = jfjoch.wait_till_done(timeout_s=60) + logger.info(f"Grid scan finished: {result.file_prefix} with {len(result.images)} images") + class MxTaskQueue: """Executes requested tasks one at a time, in order, on a background thread. diff --git a/tests/unit/test_aerotech.py b/tests/unit/test_aerotech.py new file mode 100644 index 0000000..db5354f --- /dev/null +++ b/tests/unit/test_aerotech.py @@ -0,0 +1,94 @@ +from unittest.mock import MagicMock, call + +import pytest + +from mx_bec.devices.aerotech import Aerotech +from mx_bec.devices.http import HttpRestError + +PREFIX = "http://aarescan:5234" + + +def _response(ok=True, status_code=200, reason="OK", url=PREFIX, method="POST"): + resp = MagicMock(ok=ok, status_code=status_code, reason=reason) + resp.request.method, resp.request.url = method, url + return resp + + +@pytest.fixture +def aerotech(): + device = Aerotech(name="aerotech", prefix=PREFIX) + # every REST call goes through the controller's session; never touch the network + device.controller._session = MagicMock() + device.controller._session.post.return_value = _response() + yield device + device.destroy() + + +def _configure(aerotech, n_x=4, n_y=3, exp_time_s=0.1): + config = aerotech.gridscan_config + config.grid_elem_count_x.put(n_x) + config.grid_elem_count_y.put(n_y) + config.grid_elem_size_x_um.put(50.0) + config.grid_elem_size_y_um.put(40.0) + config.time_per_element_sec.put(exp_time_s) + return config + + +def test_config_change_validates_with_aarescan(aerotech): + session = aerotech.controller._session + config = _configure(aerotech) + assert session.post.call_args == call( + f"{PREFIX}/validate/grid_scan", json=config.request_body() + ) + assert config.valid.get() is True and config.message.get() == "" + + session.post.return_value = _response(ok=False, status_code=400, reason="Bad Request") + session.post.return_value.json.return_value = "grid too large" + config.grid_elem_count_x.put(1000) + assert config.valid.get() is False and config.message.get() == "grid too large" + + +def test_trigger_starts_grid_scan_and_waits_till_done(aerotech): + session = aerotech.controller._session + config = _configure(aerotech, n_x=4, n_y=3, exp_time_s=0.1) + session.post.reset_mock() + + status = aerotech.trigger() + status.wait(timeout=5) + + expected_timeout = round((0.1 * 4 * 3 + 3 * 0.3) * 1.1 + Aerotech.GRID_SCAN_TIMEOUT_MARGIN_S) + assert session.post.call_args_list == [ + call(f"{PREFIX}/grid_scan", params=None, json={**config.request_body(), "run_async": True}), + call(f"{PREFIX}/wait_till_done", params={"timeout": expected_timeout}, json=None), + ] + + +def test_trigger_status_fails_when_aarescan_times_out(aerotech): + session = aerotech.controller._session + _configure(aerotech) + session.post.side_effect = [ + _response(), # grid_scan accepted + _response(ok=False, status_code=504, reason="Gateway Timeout"), # wait_till_done + ] + status = aerotech.trigger() + with pytest.raises(HttpRestError, match="504"): + status.wait(timeout=5) + + +def test_trigger_refuses_invalid_config(aerotech): + session = aerotech.controller._session + session.post.return_value = _response(ok=False, status_code=400, reason="Bad Request") + session.post.return_value.json.return_value = "nope" + _configure(aerotech) + session.post.reset_mock() + with pytest.raises(ValueError, match="nope"): + aerotech.trigger() + session.post.assert_not_called() + + +def test_wait_till_done_timeout_is_clamped(aerotech): + session = aerotech.controller._session + aerotech.controller.wait_till_done(timeout_s=1e6) + assert session.post.call_args.kwargs["params"] == {"timeout": 3600} + aerotech.controller.wait_till_done(timeout_s=-5) + assert session.post.call_args.kwargs["params"] == {"timeout": 0} diff --git a/tests/unit/test_grid_scan_task.py b/tests/unit/test_grid_scan_task.py new file mode 100644 index 0000000..dbe27de --- /dev/null +++ b/tests/unit/test_grid_scan_task.py @@ -0,0 +1,100 @@ +from types import SimpleNamespace +from unittest.mock import MagicMock, call + +import pytest + +from mx_bec.jfjoch import RasterScan +from mx_bec.tasks import MAX_GRID_SCAN_S, MxTasks + +GRID = dict(n_x=4, n_y=3, step_x_um=50.0, step_y_um=40.0, exp_time_s=0.1, file_prefix="grid") +BEAMLINE = dict( + detector_distance_mm=150.0, + transmission=0.5, + energy_keV=12.658, + beam_center_x_pxl=1000.0, + beam_center_y_pxl=1100.0, + beam_size_x_mm=0.02, + beam_size_y_mm=0.01, + ring_current_mA=400.0, + flux_ph_s=1e12, + sample_temperature_K=100.0, +) + + +@pytest.fixture +def client(): + client = MagicMock() + aerotech = client.devices.aerotech + aerotech.gridscan_config.valid.get.return_value = True + aerotech.u.get.return_value = 12.0 + # a plain result so that logging it doesn't record extra mock calls + client.jfjoch.wait_till_done.return_value = SimpleNamespace( + file_prefix="p16371/raw/raster/grid", images=[1, 2, 3] + ) + return client + + +def test_run_grid_scan_sequence(client): + aerotech, jfjoch = client.devices.aerotech, client.jfjoch + config = aerotech.gridscan_config + # one mock to record the order across devices and jfjoch + sequence = MagicMock() + sequence.attach_mock(jfjoch, "jfjoch") + sequence.attach_mock(aerotech.trigger, "trigger") + + MxTasks(client).run_grid_scan(**GRID, **BEAMLINE) + + config.grid_elem_count_x.set.assert_called_once_with(4) + config.grid_elem_count_y.set.assert_called_once_with(3) + config.grid_elem_size_x_um.set.assert_called_once_with(50.0) + config.grid_elem_size_y_um.set.assert_called_once_with(40.0) + config.time_per_element_sec.set.assert_called_once_with(0.1) + assert config.time_per_element_sec.set.return_value.wait.called + + scan = jfjoch.measure_raster.call_args.args[0] + assert scan == RasterScan( + n_x=4, + n_y=3, + step_x_mm=0.05, + step_y_mm=0.04, + omega_deg=12.0, + exp_time_s=0.1, + detector_distance_mm=150.0, + transmission=0.5, + file_prefix="grid", + energy_keV=12.658, + beam_center_pxl=(1000.0, 1100.0), + beam_size_mm=(0.02, 0.01), + ring_current_mA=400.0, + flux_ph_s=1e12, + sample_temperature_K=100.0, + ) + # JFJoch is armed before the Aerotech moves, and the result is collected afterwards + assert sequence.mock_calls == [ + call.jfjoch.measure_raster(scan), + call.jfjoch.wait_till_running(timeout_s=60), + call.trigger(), + call.trigger().wait(), + call.jfjoch.wait_till_done(timeout_s=60), + ] + + +def test_run_grid_scan_refuses_invalid_parameters(client): + config = client.devices.aerotech.gridscan_config + config.valid.get.return_value = False + config.message.get.return_value = "too many elements" + with pytest.raises(ValueError, match="too many elements"): + MxTasks(client).run_grid_scan(**GRID, **BEAMLINE) + client.jfjoch.measure_raster.assert_not_called() + client.devices.aerotech.trigger.assert_not_called() + + +def test_run_grid_scan_refuses_too_long_scans(client): + too_long = {**GRID, "n_x": 100, "n_y": 100, "exp_time_s": MAX_GRID_SCAN_S / 100} + with pytest.raises(ValueError, match="too long"): + MxTasks(client).run_grid_scan(**too_long, **BEAMLINE) + client.devices.aerotech.gridscan_config.grid_elem_count_x.set.assert_not_called() + + +def test_run_grid_scan_is_a_task(): + assert MxTasks.is_task("run_grid_scan") -- 2.54.1 From f1be7d39ed2ac0de9dc09ab69116b60fae507547 Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 3 Nov 2026 10:25:24 +0100 Subject: [PATCH 11/46] feat: add raster to task table --- .gitea/workflows/ci.yml | 3 +- .../widgets/aare_bec/task_panel.py | 78 ++++++++++++++++--- pyproject.toml | 1 + 3 files changed, 69 insertions(+), 13 deletions(-) diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 0eb4dc1..908f0d2 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -95,7 +95,8 @@ jobs: uv pip install --system -e ./bec/bec_ipython_client uv pip install --system -e ./bec/bec_server[dev] uv pip install --system -e ./bec_widgets[dev,pyside6] - uv pip install --system -e ./mx_bec + # MX-internal dependencies (aarecommon, aare_config, jfjoch_client, ...) come from gitea + uv pip install --system --extra-index-url https://gitea.psi.ch/api/packages/mx/pypi/simple/ -e ./mx_bec - name: Run Pytest with Coverage id: coverage diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py index 7ab6309..139deee 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -5,9 +5,11 @@ from bec_widgets.utils.bec_connector import ConnectionConfig from bec_widgets.utils.bec_widget import BECWidget from bec_widgets.utils.error_popups import SafeSlot from qtpy.QtWidgets import ( + QDoubleSpinBox, QFormLayout, QGroupBox, QHBoxLayout, + QLineEdit, QPushButton, QSpinBox, QVBoxLayout, @@ -19,11 +21,36 @@ from mx_bec.messages import MXTaskExecutionMessage logger = bec_logger.logger +# Hard-coded forms: task name -> [(argument, default value)]; the widget type follows the default. +TASK_FORMS: dict[str, list[tuple[str, int | float | str]]] = { + "run_optical_centering": [("sample_id", 0)], + "run_grid_scan": [ + ("n_x", 4), + ("n_y", 3), + ("step_x_um", 50.0), + ("step_y_um", 50.0), + ("exp_time_s", 0.1), + ("file_prefix", "grid"), + ("detector_distance_mm", 150.0), + ("transmission", 0.1), + ("energy_keV", 12.4), + ("beam_center_x_pxl", 0.0), + ("beam_center_y_pxl", 0.0), + ("beam_size_x_mm", 0.02), + ("beam_size_y_mm", 0.01), + ("ring_current_mA", 400.0), + ("flux_ph_s", 1e12), + ("sample_temperature_K", 100.0), + ("pgroup", "p16371"), + ("sample_name", "unknown_sample"), + ], +} + class MxTaskPanel(BECWidget, QWidget): """ Testing panel to submit tasks to the AareBec task request stream: one hard-coded form and - "Run" button per task. + "Run" button per task (see `TASK_FORMS`). """ PLUGIN = True @@ -39,26 +66,53 @@ class MxTaskPanel(BECWidget, QWidget): **kwargs, ) -> None: super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs) + self._inputs: dict[str, dict[str, QSpinBox | QDoubleSpinBox | QLineEdit]] = {} layout = QVBoxLayout(self) - layout.addWidget(self._optical_centering_box()) + for task, fields in TASK_FORMS.items(): + layout.addWidget(self._task_box(task, fields)) layout.addStretch() - def _optical_centering_box(self) -> QGroupBox: - box = QGroupBox("run_optical_centering", parent=self) - self._sample_id = QSpinBox(parent=box) - self._sample_id.setRange(0, 1_000_000) - run = QPushButton("Run", parent=box) - run.clicked.connect(self._run_optical_centering) + def _task_box(self, task: str, fields: list[tuple[str, int | float | str]]) -> QGroupBox: + box = QGroupBox(task, parent=self) form = QFormLayout() - form.addRow("sample_id", self._sample_id) + self._inputs[task] = {} + for name, default in fields: + widget = self._input(box, default) + form.addRow(name, widget) + self._inputs[task][name] = widget + run = QPushButton("Run", parent=box) + run.clicked.connect(lambda *_, task=task: self._run(task)) layout = QHBoxLayout(box) layout.addLayout(form) layout.addWidget(run) return box - @SafeSlot() - def _run_optical_centering(self): - self.request_task("run_optical_centering", self._sample_id.value()) + @staticmethod + def _input( + parent: QWidget, default: int | float | str + ) -> QSpinBox | QDoubleSpinBox | QLineEdit: + if isinstance(default, bool) or isinstance(default, str): + return QLineEdit(str(default), parent=parent) + if isinstance(default, int): + box = QSpinBox(parent=parent) + box.setRange(0, 1_000_000) + box.setValue(default) + return box + box = QDoubleSpinBox(parent=parent) + box.setDecimals(6) + box.setRange(-1e15, 1e15) + box.setValue(default) + return box + + def _values(self, task: str) -> dict[str, int | float | str]: + return { + name: widget.text() if isinstance(widget, QLineEdit) else widget.value() + for name, widget in self._inputs[task].items() + } + + @SafeSlot(str) + def _run(self, task: str): + self.request_task(task, **self._values(task)) @SafeSlot(str) def request_task(self, name: str, *args, **kwargs): diff --git a/pyproject.toml b/pyproject.toml index fd9891d..0d88214 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,6 +16,7 @@ dependencies = [ "aarecommon", "aare_config", "aarelcinfer_client==0.1.1a8", + "jfjoch_client>=1.0.0rc166", # only pre-releases exist; the rc specifier lets pip pick them "bec_lib>=3.130.3", "bec-server>=3.130.3", "bec-ipython-client>=3.130.3", -- 2.54.1 From d0cfcac2491783dcc4fa54eb80ffbe99cfc38b5e Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 3 Nov 2026 13:34:35 +0100 Subject: [PATCH 12/46] feat: hack in state change --- .../widgets/aare_bec/task_panel.py | 19 ++++++ mx_bec/tasks.py | 59 ++++++++++++++++--- tests/unit/test_change_state_task.py | 43 ++++++++++++++ tests/unit/test_service.py | 44 +++++++++++++- 4 files changed, 153 insertions(+), 12 deletions(-) create mode 100644 tests/unit/test_change_state_task.py diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py index 139deee..72bf021 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -7,6 +7,7 @@ from bec_widgets.utils.error_popups import SafeSlot from qtpy.QtWidgets import ( QDoubleSpinBox, QFormLayout, + QGridLayout, QGroupBox, QHBoxLayout, QLineEdit, @@ -56,6 +57,7 @@ class MxTaskPanel(BECWidget, QWidget): PLUGIN = True ICON_NAME = "play_arrow" USER_ACCESS = ["request_task"] + STATE_BUTTONS_PER_ROW = 4 def __init__( self, @@ -70,8 +72,25 @@ class MxTaskPanel(BECWidget, QWidget): layout = QVBoxLayout(self) for task, fields in TASK_FORMS.items(): layout.addWidget(self._task_box(task, fields)) + layout.addWidget(self._change_state_box()) layout.addStretch() + def _change_state_box(self) -> QGroupBox: + """One button per beamline state, each requesting the `change_state` task.""" + from pxii_bec.macros.beamline_planner import ( # pyright: ignore[reportMissingImports] + BeamlineState, + ) + + box = QGroupBox("change_state", parent=self) + grid = QGridLayout(box) + for i, state in enumerate(BeamlineState): + button = QPushButton(state.value, parent=box) + button.clicked.connect( + lambda *_, state=state.value: self.request_task("change_state", state=state) + ) + grid.addWidget(button, i // self.STATE_BUTTONS_PER_ROW, i % self.STATE_BUTTONS_PER_ROW) + return box + def _task_box(self, task: str, fields: list[tuple[str, int | float | str]]) -> QGroupBox: box = QGroupBox(task, parent=self) form = QFormLayout() diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index c27e7a5..7e6bdbc 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -14,6 +14,8 @@ from mx_bec.jfjoch import RasterScan from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskQueueChangedMessage if TYPE_CHECKING: + from pxii_bec.macros.beamline_planner import StateChangePlanner + from mx_bec.messages import MXTaskExecutionMessage from mx_bec.service import AareBec @@ -32,27 +34,54 @@ class MxTasks: def __init__(self, client: AareBec): self._client = client self._busy_lock = RLock() + self._planner: StateChangePlanner | None = None + + @property + def planner(self) -> StateChangePlanner: + """The beamline state planner, built on first use: `init_beamline_environment` needs the + BEAMLINE environment variable and the beamline devices.""" + if self._planner is None: + # pyright: ignore[reportMissingImports, reportMissingModuleSource] + from pxii_bec.scripts.init_beamline import init_beamline_environment + + _, _, self._planner = init_beamline_environment() + return self._planner @classmethod def is_task(cls, name: str) -> bool: - """Whether `name` can be requested as a task, i.e. is a method decorated with - `with_lock`.""" + """Whether `name` can be requested as a task, i.e. is a method decorated with `task`.""" return getattr(inspect.getattr_static(cls, name, None), "is_mx_task", False) @staticmethod - def with_lock(method: Callable[P, R]) -> Callable[P, R]: - """Mark the decorated method as a task and run it while holding `self._busy_lock`, so - that only one task runs at a time.""" + def task(method: Callable[P, R]) -> Callable[P, R]: + """Mark the decorated method as a task. It runs while holding `self._busy_lock`, so that + only one task runs at a time, and if it raises, the task queue is paused before the + exception propagates, so that queued tasks don't carry on from a failed state.""" @functools.wraps(method) def wrapper(self: MxTasks, *args, **kwargs): - with self._busy_lock: # pylint: disable=protected-access - return method(self, *args, **kwargs) + # pylint: disable=protected-access + with self._busy_lock: + try: + return method(self, *args, **kwargs) + except Exception: + self._pause_queue_after_failure(method.__name__) + raise wrapper.is_mx_task = True return wrapper # type: ignore # self is part of P - @with_lock + def _pause_queue_after_failure(self, task_name: str) -> None: + if (queue := getattr(self._client, "task_queue", None)) is None: + return + logger.warning(f"Task {task_name} failed, pausing the task queue") + try: + queue.pause() + except Exception: # pylint: disable=broad-except + # the task's own exception is the one to surface + logger.exception("Failed to pause the task queue") + + @task 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` @@ -79,7 +108,19 @@ class MxTasks: MXMeasurementSequenceMessage(sample_id=sample_id, success=success), ) - @with_lock + @task + def change_state(self, state: str, modifier: str | None = None) -> None: + """Move the beamline devices to `state`, the value of a `BeamlineState` (e.g. + "sample_alignment"), optionally with a temperature `modifier` ("cryo" or "room_temp").""" + from pxii_bec.macros.beamline_planner import ( # pyright: ignore[reportMissingImports] + BeamlineState, + ) + + target = BeamlineState(state) # reject unknown states before anything moves + logger.info(f"Changing beamline state to {target.value}, modifier={modifier}") + self.planner.move_to(target, modifier) + + @task def run_grid_scan( self, n_x: int, diff --git a/tests/unit/test_change_state_task.py b/tests/unit/test_change_state_task.py new file mode 100644 index 0000000..c74de02 --- /dev/null +++ b/tests/unit/test_change_state_task.py @@ -0,0 +1,43 @@ +from unittest.mock import MagicMock, patch + +import pytest +from pxii_bec.macros.beamline_planner import BeamlineState + +from mx_bec.tasks import MxTasks + + +@pytest.fixture +def tasks(): + tasks = MxTasks(MagicMock()) + tasks._planner = MagicMock() + return tasks + + +def test_planner_is_built_lazily_from_the_beamline_environment(monkeypatch): + monkeypatch.delenv("BEAMLINE", raising=False) + tasks = MxTasks(MagicMock()) # must not need the beamline environment yet + env, devices, planner = MagicMock(), MagicMock(), MagicMock() + with patch( + "pxii_bec.scripts.init_beamline.init_beamline_environment", + return_value=(env, devices, planner), + ) as init: + assert tasks.planner is planner + assert tasks.planner is planner + init.assert_called_once() + + +@pytest.mark.parametrize("modifier", [None, "cryo"]) +def test_change_state_moves_to_the_state(tasks, modifier): + tasks.change_state("sample_alignment", modifier) + tasks.planner.move_to.assert_called_once_with(BeamlineState.SAMPLE_ALIGNMENT, modifier) + + +def test_change_state_rejects_unknown_states(tasks): + with pytest.raises(ValueError, match="no_such_state"): + tasks.change_state("no_such_state") + tasks.planner.move_to.assert_not_called() + + +def test_change_state_is_a_task_and_planner_is_not(): + assert MxTasks.is_task("change_state") + assert not MxTasks.is_task("planner") diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py index 9cb5c91..1bb3812 100644 --- a/tests/unit/test_service.py +++ b/tests/unit/test_service.py @@ -110,8 +110,9 @@ NOT_TASKS = [ "_publish_optical_centering_done", # private method "_client", # private attribute "_busy_lock", - "with_lock", # public, but a helper rather than a task + "task", # public, but the decorator rather than a task "is_task", + "planner", # property ] @@ -127,9 +128,9 @@ def test_task_request_for_non_task_name_is_rejected(service, name): assert name in logger.warning.call_args.args[0] -def test_tasks_are_exactly_the_methods_decorated_with_with_lock(): +def test_tasks_are_exactly_the_decorated_methods(): class Tasks(MxTasks): - @MxTasks.with_lock + @MxTasks.task def decorated(self): ... def plain(self): ... @@ -140,6 +141,43 @@ def test_tasks_are_exactly_the_methods_decorated_with_with_lock(): assert all(not MxTasks.is_task(name) for name in NOT_TASKS) +class _FailingTasks(MxTasks): + @MxTasks.task + def boom(self): + raise RuntimeError("boom") + + @MxTasks.task + def fine(self): + return "ok" + + +def test_failed_task_pauses_the_queue_and_reraises(): + client = MagicMock() + with pytest.raises(RuntimeError, match="boom"): + _FailingTasks(client).boom() + client.task_queue.pause.assert_called_once() + + +def test_successful_task_does_not_pause_the_queue(): + client = MagicMock() + assert _FailingTasks(client).fine() == "ok" + client.task_queue.pause.assert_not_called() + + +def test_failed_task_reraises_without_a_queue(): + client = MagicMock() + client.task_queue = None # the queue only exists once the service has started + with pytest.raises(RuntimeError, match="boom"): + _FailingTasks(client).boom() + + +def test_failed_task_reraises_even_if_pausing_fails(): + client = MagicMock() + client.task_queue.pause.side_effect = ConnectionError("redis gone") + with pytest.raises(RuntimeError, match="boom"): + _FailingTasks(client).boom() + + @pytest.fixture def mock_client(): client = MagicMock() -- 2.54.1 From 71cd3ac6b4d8a351ddc6ee8f91521b75af349236 Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 3 Nov 2026 15:17:06 +0100 Subject: [PATCH 13/46] feat: add sample info holder --- mx_bec/sample_info.py | 21 +++++++++++++++++++++ mx_bec/service.py | 5 +++++ 2 files changed, 26 insertions(+) create mode 100644 mx_bec/sample_info.py diff --git a/mx_bec/sample_info.py b/mx_bec/sample_info.py new file mode 100644 index 0000000..39d7e34 --- /dev/null +++ b/mx_bec/sample_info.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +from pydantic import BaseModel, Field + + +class OpticalCenteringResults: + """Outputs from the optical centering stage""" + + found: bool + smargon_coordinates: tuple[float, float, float] = Field( + description="x,y,z motor coords of the smargon where the crystal was centred" + ) + type_used: str = Field(description="Image analysis element used to determine the center") + + +class SampleInfo(BaseModel): + """Information about the currently mounted sample. Gradually filled out as + information from previous stages is obtained""" + + sample_id: int + optical_centering_results: OpticalCenteringResults | None = None diff --git a/mx_bec/service.py b/mx_bec/service.py index 6cfc0bb..51ab267 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -14,6 +14,7 @@ from mx_bec.endpoints import TaskEndpoints from mx_bec.jfjoch import JFJoch from mx_bec.messages import MXTaskQueueChangedMessage from mx_bec.optical_centering import OpticalPrediction +from mx_bec.sample_info import SampleInfo from mx_bec.tasks import MxTaskQueue, MxTasks if TYPE_CHECKING: @@ -49,6 +50,7 @@ class AareBec(BECClient): self.jfjoch = JFJoch(client=self) # connects lazily on first use self.tasks = MxTasks(self) self.task_queue: MxTaskQueue | None = None + self.sample_info: SampleInfo | None = None def start(self): super().start() @@ -78,6 +80,9 @@ class AareBec(BECClient): def _start_actor_manager(self): self.actor_manager = AareActorManager(self) + def reset_sample_info(self, sample_id: int): + self.sample_info = SampleInfo(sample_id=sample_id) + def shutdown(self, per_thread_timeout_s: float | None = None) -> None: """shutdown the service""" if self.actor_manager is not None: -- 2.54.1 From 75b51fc3140a3fcc1ba90addfc28a9db666ded3d Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 3 Nov 2026 15:48:51 +0100 Subject: [PATCH 14/46] feat: add aaredaq api client --- mx_bec/aaredaq.py | 167 +++++++++++++++++++++++++++++++++++++ mx_bec/sample_info.py | 2 +- mx_bec/service.py | 2 + tests/unit/test_aaredaq.py | 146 ++++++++++++++++++++++++++++++++ 4 files changed, 316 insertions(+), 1 deletion(-) create mode 100644 mx_bec/aaredaq.py create mode 100644 tests/unit/test_aaredaq.py diff --git a/mx_bec/aaredaq.py b/mx_bec/aaredaq.py new file mode 100644 index 0000000..c003093 --- /dev/null +++ b/mx_bec/aaredaq.py @@ -0,0 +1,167 @@ +from __future__ import annotations + +import json +import subprocess +from typing import TYPE_CHECKING, Any + +import requests +from aarecommon.config.beamline import cfg_get, mx_beamline +from aarecommon.models.beamline import MXBeamline +from aarecommon.models.raster_grid import CompletedRasterGrid, RasterGridRequest +from aarecommon.models.rotation_scan import CompletedRotationScan, RotationScanRequest +from bec_lib.logger import bec_logger + +if TYPE_CHECKING: + from mx_bec.service import AareBec + +logger = bec_logger.logger + +# same defaults as the AareDAQ GUI (aare/gui/gui.py) +DEFAULT_URLS = { + MXBeamline.X06DA: "https://mx-x06da-queue-01.psi.ch", + MXBeamline.X10SA: "https://mx-x10sa-queue-01.psi.ch", +} +DEFAULT_CERT_PATHS = { + MXBeamline.X06DA: "/sls/x06da/misc/.cert/6d.crt", + MXBeamline.X10SA: "/sls/x10sa/misc/.cert/10s.crt", +} +TOKEN_TIMEOUT_S = 120.0 +SCAN_TIMEOUT_S = 3600.0 # the scan endpoints block until the scan is done + + +class AareDaqError(RuntimeError): + """A call to the AareDAQ server failed.""" + + +class AareDaq: + """Client for the AareDAQ REST API (aaredaq `server.py`). + + Mirrors how the AareDAQ GUI talks to the server: a bearer token is obtained once, lazily, by + Kerberos (`curl --negotiate` against the Apache proxy in front of the server, exactly as + `aare.gui.auth.auth` does), and is renewed once if the server answers 401. The server URL and + its certificate come from the aarecommon beamline config unless given. + """ + + def __init__( + self, client: AareBec, url: str | None = None, cert_path: str | None = None + ) -> None: + self._client = client + self._url = url + self._cert_path = cert_path + self._token: str | None = None + self._session = requests.Session() + + @property + def url(self) -> str: + if self._url is None: + beamline = mx_beamline() + self._url = cfg_get("gui.daq.daq_url", DEFAULT_URLS.get(beamline)) + if self._url is None: + raise AareDaqError(f"No AareDAQ URL configured for beamline {beamline}") + return self._url + + @property + def cert_path(self) -> str: + if self._cert_path is None: + beamline = mx_beamline() + self._cert_path = cfg_get("gui.daq.cert_path", DEFAULT_CERT_PATHS.get(beamline)) + if self._cert_path is None: + raise AareDaqError(f"No AareDAQ certificate configured for beamline {beamline}") + return self._cert_path + + @property + def token(self) -> str: + if self._token is None: + self._token = self._request_token() + return self._token + + def _request_token(self) -> str: + """POST /token through the Kerberos (SPNEGO) proxy; needs a valid ticket (kinit).""" + cmd = ["curl", "-s", "--cacert", self.cert_path, "--negotiate", "-u", ":", "-XPOST"] + cmd.append(f"{self.url}/token") + try: + result = subprocess.run( + cmd, capture_output=True, text=True, timeout=TOKEN_TIMEOUT_S, check=False + ) + except (OSError, subprocess.TimeoutExpired) as e: + raise AareDaqError(f"AareDAQ token request failed: {e}") from e + if result.returncode != 0: + raise AareDaqError( + f"AareDAQ token request failed (curl exit {result.returncode}): " + f"{result.stderr[:500]}. Is the Kerberos ticket valid (kinit)?" + ) + try: + token = json.loads(result.stdout).get("access_token") + except json.JSONDecodeError as e: + raise AareDaqError(f"AareDAQ token response is not JSON: {result.stdout[:500]}") from e + if not isinstance(token, str) or not token: + raise AareDaqError(f"AareDAQ token response has no access_token: {result.stdout[:500]}") + return token + + def _post( + self, + endpoint: str, + *, + params: dict[str, Any] | None = None, + body: dict[str, Any] | None = None, + timeout_s: float = SCAN_TIMEOUT_S, + ) -> Any: + """POST to `endpoint` with the bearer token and return the decoded JSON response. A 401 is + retried once with a fresh token; any other error becomes an AareDaqError.""" + for attempt in range(2): + try: + resp = self._session.post( + f"{self.url}{endpoint}", + params=params, + json=body, + headers={"Authorization": f"Bearer {self.token}"}, + verify=self.cert_path, + timeout=timeout_s, + ) + except requests.RequestException as e: + raise AareDaqError(f"AareDAQ POST {endpoint} failed: {e}") from e + if resp.status_code == 401 and attempt == 0: + logger.info("AareDAQ rejected the token, requesting a new one") + self._token = None + continue + if not resp.ok: + raise AareDaqError( + f"AareDAQ POST {endpoint} failed with {resp.status_code}: {resp.text[:500]}" + ) + return resp.json() + raise AssertionError("unreachable") # pragma: no cover + + def mount_sample(self, dbid: int, reference: bool = False, timeout_s: float = 600.0) -> None: + """Mount the sample with database id `dbid` (from the reference tools if `reference`).""" + logger.info(f"AareDAQ: mounting sample {dbid}{' (reference tool)' if reference else ''}") + self._post( + "/sample/mount", params={"dbid": dbid, "reference": reference}, timeout_s=timeout_s + ) + + def raster_scan( + self, + request: RasterGridRequest, + auto_center: bool = False, + timeout_s: float = SCAN_TIMEOUT_S, + ) -> CompletedRasterGrid: + """Run a raster scan and return its result (blocks until the scan is done).""" + logger.info(f"AareDAQ: raster scan {request.n_x}x{request.n_y}, auto_center={auto_center}") + result = self._post( + "/scan/raster", + params={"auto_center": auto_center}, + body=request.model_dump(mode="json"), + timeout_s=timeout_s, + ) + return CompletedRasterGrid.model_validate(result) + + def rotation_scan( + self, request: RotationScanRequest, timeout_s: float = SCAN_TIMEOUT_S + ) -> CompletedRotationScan: + """Run a rotation (or screening) scan and return its result (blocks until done).""" + logger.info( + f"AareDAQ: rotation scan, {request.steps} steps of {request.incr_omega_deg} deg" + ) + result = self._post( + "/scan/rotation", body=request.model_dump(mode="json"), timeout_s=timeout_s + ) + return CompletedRotationScan.model_validate(result) diff --git a/mx_bec/sample_info.py b/mx_bec/sample_info.py index 39d7e34..3671f05 100644 --- a/mx_bec/sample_info.py +++ b/mx_bec/sample_info.py @@ -3,7 +3,7 @@ from __future__ import annotations from pydantic import BaseModel, Field -class OpticalCenteringResults: +class OpticalCenteringResults(BaseModel): """Outputs from the optical centering stage""" found: bool diff --git a/mx_bec/service.py b/mx_bec/service.py index 51ab267..bb22038 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -8,6 +8,7 @@ from bec_lib import messages from bec_lib.client import BECClient from bec_lib.logger import bec_logger +from mx_bec.aaredaq import AareDaq from mx_bec.actor_manager import AareActorManager from mx_bec.constants import AareBecWorkflowState from mx_bec.endpoints import TaskEndpoints @@ -48,6 +49,7 @@ class AareBec(BECClient): self.actor_manager: AareActorManager | None = None self.optical_prediction = OpticalPrediction(client=self) self.jfjoch = JFJoch(client=self) # connects lazily on first use + self.aaredaq = AareDaq(client=self) # authenticates lazily on first use self.tasks = MxTasks(self) self.task_queue: MxTaskQueue | None = None self.sample_info: SampleInfo | None = None diff --git a/tests/unit/test_aaredaq.py b/tests/unit/test_aaredaq.py new file mode 100644 index 0000000..f4ea730 --- /dev/null +++ b/tests/unit/test_aaredaq.py @@ -0,0 +1,146 @@ +import subprocess +from unittest.mock import MagicMock, call, patch + +import pytest +from aarecommon.math.coordinate import Coordinate, SmargonCoordinate +from aarecommon.models.raster_grid import CompletedRasterGrid, RasterGridRequest +from aarecommon.models.rotation_scan import CompletedRotationScan, RotationScanRequest + +from mx_bec.aaredaq import DEFAULT_URLS, AareDaq, AareDaqError + +URL, CERT, TOKEN = "https://daq.test", "/certs/daq.crt", "eyJ.abc.def" + + +def _curl_result(stdout='{"access_token": "' + TOKEN + '"}', returncode=0, stderr=""): + return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr=stderr) + + +def _response(status_code=200, json_data=None, text=""): + resp = MagicMock(status_code=status_code, ok=200 <= status_code < 300, text=text) + resp.json.return_value = json_data + return resp + + +@pytest.fixture +def curl(): + with patch("mx_bec.aaredaq.subprocess.run", return_value=_curl_result()) as run: + yield run + + +@pytest.fixture +def daq(curl): + daq = AareDaq(MagicMock(), url=URL, cert_path=CERT) + daq._session = MagicMock() + daq._session.post.return_value = _response(json_data="OK") + return daq + + +def _raster_request(): + return RasterGridRequest( + n_x=2, + n_y=1, + grid_size_mm=Coordinate(x=0.05, y=0.05), + file_prefix="t", + exp_time_s=0.1, + dtz=150, + transmission=1, + smargon_top_left=SmargonCoordinate(), + omega_deg=0.0, + ) + + +def test_url_and_cert_are_resolved_from_beamline_config_on_first_use(curl, monkeypatch): + monkeypatch.delenv("BEAMLINE", raising=False) + daq = AareDaq(MagicMock()) # must not need the beamline environment yet + with ( + patch("mx_bec.aaredaq.mx_beamline", return_value="X10SA"), + patch("mx_bec.aaredaq.cfg_get", side_effect=lambda key, default: default) as cfg_get, + ): + assert daq.url == DEFAULT_URLS["X10SA"] + assert daq.cert_path == "/sls/x10sa/misc/.cert/10s.crt" + assert cfg_get.call_args_list[0].args[0] == "gui.daq.daq_url" + + +def test_token_is_requested_lazily_by_kerberos_curl(daq, curl): + curl.assert_not_called() + assert daq.token == TOKEN + assert daq.token == TOKEN + curl.assert_called_once() + cmd = curl.call_args.args[0] + assert cmd[0] == "curl" and "--negotiate" in cmd and cmd[-1] == f"{URL}/token" + assert cmd[cmd.index("--cacert") + 1] == CERT + + +@pytest.mark.parametrize( + "result, match", + [ + (_curl_result(returncode=6, stderr="could not resolve"), "curl exit 6"), + (_curl_result(stdout=""), "not JSON"), + (_curl_result(stdout="{}"), "no access_token"), + ], +) +def test_token_request_failures(daq, curl, result, match): + curl.return_value = result + with pytest.raises(AareDaqError, match=match): + _ = daq.token + + +def test_token_request_timeout(daq, curl): + curl.side_effect = subprocess.TimeoutExpired(cmd="curl", timeout=120) + with pytest.raises(AareDaqError, match="token request failed"): + _ = daq.token + + +def test_mount_sample(daq): + daq.mount_sample(42) + daq._session.post.assert_called_once_with( + f"{URL}/sample/mount", + params={"dbid": 42, "reference": False}, + json=None, + headers={"Authorization": f"Bearer {TOKEN}"}, + verify=CERT, + timeout=600.0, + ) + + +def test_raster_scan(daq): + request = _raster_request() + completed = CompletedRasterGrid(r=[]) + daq._session.post.return_value = _response(json_data=completed.model_dump(mode="json")) + assert daq.raster_scan(request, auto_center=True) == completed + kwargs = daq._session.post.call_args.kwargs + assert daq._session.post.call_args.args == (f"{URL}/scan/raster",) + assert kwargs["params"] == {"auto_center": True} + assert kwargs["json"] == request.model_dump(mode="json") + assert kwargs["timeout"] == 3600.0 + + +def test_rotation_scan(daq): + request = RotationScanRequest(exp_time_s=0.05, incr_omega_deg=0.1, steps=100) + completed = CompletedRotationScan(request=request, result={"images": []}) + daq._session.post.return_value = _response(json_data=completed.model_dump(mode="json")) + assert daq.rotation_scan(request) == completed + assert daq._session.post.call_args.args == (f"{URL}/scan/rotation",) + assert daq._session.post.call_args.kwargs["json"] == request.model_dump(mode="json") + + +def test_expired_token_is_renewed_once(daq, curl): + curl.side_effect = [_curl_result(), _curl_result('{"access_token": "new"}')] + daq._session.post.side_effect = [_response(401), _response(json_data="OK")] + daq.mount_sample(1) + headers = [c.kwargs["headers"]["Authorization"] for c in daq._session.post.call_args_list] + assert headers == [f"Bearer {TOKEN}", "Bearer new"] + assert daq.token == "new" + + +def test_persistent_401_is_an_error(daq): + daq._session.post.return_value = _response(401, text="nope") + with pytest.raises(AareDaqError, match="401"): + daq.mount_sample(1) + assert daq._session.post.call_count == 2 + + +def test_http_error_reports_status_and_body(daq): + daq._session.post.return_value = _response(422, text='{"detail": "bad request"}') + with pytest.raises(AareDaqError, match="422.*bad request"): + daq.rotation_scan(RotationScanRequest(exp_time_s=0.05, incr_omega_deg=0.1, steps=1)) -- 2.54.1 From 02be72d885a84f02447529cede4b29be7fd114d1 Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 3 Nov 2026 15:51:09 +0100 Subject: [PATCH 15/46] feat: add tasks for aaredaq scans --- .../widgets/aare_bec/task_panel.py | 41 ++++++++-- mx_bec/tasks.py | 68 ++++++++++++++++ tests/unit/test_aaredaq_tasks.py | 79 +++++++++++++++++++ 3 files changed, 181 insertions(+), 7 deletions(-) create mode 100644 tests/unit/test_aaredaq_tasks.py diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py index 72bf021..6d8a509 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -12,6 +12,7 @@ from qtpy.QtWidgets import ( QHBoxLayout, QLineEdit, QPushButton, + QScrollArea, QSpinBox, QVBoxLayout, QWidget, @@ -45,6 +46,22 @@ TASK_FORMS: dict[str, list[tuple[str, int | float | str]]] = { ("pgroup", "p16371"), ("sample_name", "unknown_sample"), ], + # the AareDAQ-driven tasks; their bool/optional arguments keep their defaults here + "aaredaq_mount_sample": [("dbid", 0)], + "aaredaq_raster_scan": [ + ("n_x", 4), + ("n_y", 3), + ("step_x_mm", 0.05), + ("step_y_mm", 0.05), + ("exp_time_s", 0.1), + ("omega_deg", 0.0), + ], + "aaredaq_rotation_scan": [ + ("exp_time_s", 0.05), + ("incr_omega_deg", 0.1), + ("steps", 100), + ("start_omega_deg", 0.0), + ], } @@ -69,19 +86,27 @@ class MxTaskPanel(BECWidget, QWidget): ) -> None: super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs) self._inputs: dict[str, dict[str, QSpinBox | QDoubleSpinBox | QLineEdit]] = {} - layout = QVBoxLayout(self) + # all the forms live in a scrollable content widget + content = QWidget() + layout = QVBoxLayout(content) for task, fields in TASK_FORMS.items(): - layout.addWidget(self._task_box(task, fields)) - layout.addWidget(self._change_state_box()) + layout.addWidget(self._task_box(content, task, fields)) + layout.addWidget(self._change_state_box(content)) layout.addStretch() + scroll = QScrollArea(parent=self) + scroll.setWidgetResizable(True) + scroll.setWidget(content) + outer = QVBoxLayout(self) + outer.setContentsMargins(0, 0, 0, 0) + outer.addWidget(scroll) - def _change_state_box(self) -> QGroupBox: + def _change_state_box(self, parent: QWidget) -> QGroupBox: """One button per beamline state, each requesting the `change_state` task.""" from pxii_bec.macros.beamline_planner import ( # pyright: ignore[reportMissingImports] BeamlineState, ) - box = QGroupBox("change_state", parent=self) + box = QGroupBox("change_state", parent=parent) grid = QGridLayout(box) for i, state in enumerate(BeamlineState): button = QPushButton(state.value, parent=box) @@ -91,8 +116,10 @@ class MxTaskPanel(BECWidget, QWidget): grid.addWidget(button, i // self.STATE_BUTTONS_PER_ROW, i % self.STATE_BUTTONS_PER_ROW) return box - def _task_box(self, task: str, fields: list[tuple[str, int | float | str]]) -> QGroupBox: - box = QGroupBox(task, parent=self) + def _task_box( + self, parent: QWidget, task: str, fields: list[tuple[str, int | float | str]] + ) -> QGroupBox: + box = QGroupBox(task, parent=parent) form = QFormLayout() self._inputs[task] = {} for name, default in fields: diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index 7e6bdbc..887a2b5 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -5,6 +5,9 @@ import inspect from threading import Event, RLock, Thread from typing import TYPE_CHECKING, Callable, ParamSpec, TypeVar +from aarecommon.math.coordinate import Coordinate +from aarecommon.models.raster_grid import RasterGridRequest +from aarecommon.models.rotation_scan import RotationScanRequest from bec_lib.config_values import RedisConfigValue from bec_lib.logger import bec_logger @@ -120,6 +123,71 @@ class MxTasks: logger.info(f"Changing beamline state to {target.value}, modifier={modifier}") self.planner.move_to(target, modifier) + @task + def aaredaq_mount_sample(self, dbid: int, reference: bool = False) -> None: + """Have AareDAQ mount the sample with database id `dbid` (a reference tool if + `reference`).""" + self._client.aaredaq.mount_sample(dbid, reference=reference) + + @task + def aaredaq_raster_scan( + self, + n_x: int, + n_y: int, + step_x_mm: float, + step_y_mm: float, + exp_time_s: float, + omega_deg: float = 0.0, + file_prefix: str | None = None, + dtz: float | None = None, + transmission: float | None = None, + auto_center: bool = False, + ) -> None: + """Have AareDAQ run an n_x by n_y raster scan from the current Smargon position + (`smargon_top_left` is left unset), optionally auto-centering afterwards.""" + request = RasterGridRequest( + n_x=n_x, + n_y=n_y, + grid_size_mm=Coordinate(x=step_x_mm, y=step_y_mm), + exp_time_s=exp_time_s, + omega_deg=omega_deg, + file_prefix=file_prefix, + dtz=dtz, + transmission=transmission, + smargon_top_left=None, + ) + result = self._client.aaredaq.raster_scan(request, auto_center=auto_center) + logger.info(f"AareDAQ raster scan done: {len(result.r)} grid(s) collected") + + @task + def aaredaq_rotation_scan( + self, + exp_time_s: float, + incr_omega_deg: float, + steps: int, + start_omega_deg: float = 0.0, + file_prefix: str | None = None, + dtz: float | None = None, + transmission: float | None = None, + screening: bool = False, + wedge_omega_deg: float | None = None, + ) -> None: + """Have AareDAQ run a rotation (or screening) scan of `steps` images of `incr_omega_deg` + each, starting at the current Smargon position (`start`/`end` are left unset).""" + request = RotationScanRequest( + exp_time_s=exp_time_s, + incr_omega_deg=incr_omega_deg, + steps=steps, + start_omega_deg=start_omega_deg, + file_prefix=file_prefix, + dtz=dtz, + transmission=transmission, + screening=screening, + wedge_omega_deg=wedge_omega_deg, + ) + result = self._client.aaredaq.rotation_scan(request) + logger.info(f"AareDAQ rotation scan done: {len(result.result.images)} images") + @task def run_grid_scan( self, diff --git a/tests/unit/test_aaredaq_tasks.py b/tests/unit/test_aaredaq_tasks.py new file mode 100644 index 0000000..025cccc --- /dev/null +++ b/tests/unit/test_aaredaq_tasks.py @@ -0,0 +1,79 @@ +from unittest.mock import MagicMock + +import pytest +from aarecommon.math.coordinate import Coordinate +from aarecommon.models.raster_grid import RasterGridRequest +from aarecommon.models.rotation_scan import RotationScanRequest + +from mx_bec.tasks import MxTasks + + +@pytest.fixture +def client(): + return MagicMock() + + +@pytest.fixture +def tasks(client): + return MxTasks(client) + + +@pytest.mark.parametrize( + "name", ["aaredaq_mount_sample", "aaredaq_raster_scan", "aaredaq_rotation_scan"] +) +def test_aaredaq_methods_are_tasks(name): + assert MxTasks.is_task(name) + + +def test_mount_sample(tasks, client): + tasks.aaredaq_mount_sample(42) + client.aaredaq.mount_sample.assert_called_once_with(42, reference=False) + tasks.aaredaq_mount_sample(7, reference=True) + client.aaredaq.mount_sample.assert_called_with(7, reference=True) + + +def test_raster_scan_builds_request_from_flat_arguments(tasks, client): + tasks.aaredaq_raster_scan( + n_x=4, n_y=3, step_x_mm=0.05, step_y_mm=0.04, exp_time_s=0.1, omega_deg=12.0, dtz=150.0 + ) + request, kwargs = ( + client.aaredaq.raster_scan.call_args.args[0], + client.aaredaq.raster_scan.call_args.kwargs, + ) + assert request == RasterGridRequest( + n_x=4, + n_y=3, + grid_size_mm=Coordinate(x=0.05, y=0.04), + exp_time_s=0.1, + omega_deg=12.0, + dtz=150.0, + smargon_top_left=None, + ) + assert kwargs == {"auto_center": False} + + +def test_raster_scan_passes_auto_center(tasks, client): + tasks.aaredaq_raster_scan(1, 1, 0.05, 0.05, 0.1, auto_center=True) + assert client.aaredaq.raster_scan.call_args.kwargs == {"auto_center": True} + + +def test_rotation_scan_builds_request_from_flat_arguments(tasks, client): + tasks.aaredaq_rotation_scan( + exp_time_s=0.05, incr_omega_deg=0.1, steps=100, start_omega_deg=90.0, file_prefix="rot" + ) + assert client.aaredaq.rotation_scan.call_args.args[0] == RotationScanRequest( + exp_time_s=0.05, incr_omega_deg=0.1, steps=100, start_omega_deg=90.0, file_prefix="rot" + ) + + +def test_screening_scan(tasks, client): + tasks.aaredaq_rotation_scan(0.05, 1.0, 4, screening=True, wedge_omega_deg=90.0) + request = client.aaredaq.rotation_scan.call_args.args[0] + assert request.screening is True and request.wedge_omega_deg == 90.0 + + +def test_failed_aaredaq_call_pauses_queue_and_reraises(tasks, client): + client.aaredaq.mount_sample.side_effect = RuntimeError("sample not found") + with pytest.raises(RuntimeError, match="sample not found"): + tasks.aaredaq_mount_sample(1) + client.task_queue.pause.assert_called_once() -- 2.54.1 From 876f17edd14249fb055e7da2f84baa8aa966b3fb Mon Sep 17 00:00:00 2001 From: x10sa Date: Wed, 4 Nov 2026 10:34:02 +0100 Subject: [PATCH 16/46] wip --- mx_bec/optical_centering.py | 4 +++- mx_bec/tasks.py | 21 ++++++++++++--------- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/mx_bec/optical_centering.py b/mx_bec/optical_centering.py index 82edd61..8bf8db4 100644 --- a/mx_bec/optical_centering.py +++ b/mx_bec/optical_centering.py @@ -23,7 +23,9 @@ class OpticalPrediction: def get_latest(self): response = self._aarelc_client.request("GET", "/predictions/latest").json() - return LatestPredictionModel.model_validate(response) + prediction = LatestPredictionModel.model_validate(response) + logger.info(f"Got AareLc prediction: {prediction}") + return prediction def get_target_point_px(self): """Retry up to n times to get a target point""" diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index 887a2b5..0a3ba85 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -3,7 +3,7 @@ from __future__ import annotations import functools import inspect from threading import Event, RLock, Thread -from typing import TYPE_CHECKING, Callable, ParamSpec, TypeVar +from typing import TYPE_CHECKING, Callable, Concatenate, ParamSpec, Self, TypeVar from aarecommon.math.coordinate import Coordinate from aarecommon.models.raster_grid import RasterGridRequest @@ -56,7 +56,7 @@ class MxTasks: return getattr(inspect.getattr_static(cls, name, None), "is_mx_task", False) @staticmethod - def task(method: Callable[P, R]) -> Callable[P, R]: + def task(method: Callable[Concatenate[MxTasks, P], R]) -> Callable[P, R]: """Mark the decorated method as a task. It runs while holding `self._busy_lock`, so that only one task runs at a time, and if it raises, the task queue is paused before the exception propagates, so that queued tasks don't carry on from a failed state.""" @@ -66,18 +66,20 @@ class MxTasks: # pylint: disable=protected-access with self._busy_lock: try: - return method(self, *args, **kwargs) - except Exception: - self._pause_queue_after_failure(method.__name__) + result = method(self, *args, **kwargs) + except Exception as e: + self._pause_queue_after_failure(method.__name__, e) raise + logger.info(f"Task: {method.__name__} completed.") + return result - wrapper.is_mx_task = True - return wrapper # type: ignore # self is part of P + setattr(wrapper, "is_mx_task", True) + return wrapper - def _pause_queue_after_failure(self, task_name: str) -> None: + def _pause_queue_after_failure(self, task_name: str, e: Exception) -> None: if (queue := getattr(self._client, "task_queue", None)) is None: return - logger.warning(f"Task {task_name} failed, pausing the task queue") + logger.warning(f"Task {task_name} failed: {e}.\n Pausing the task queue.") try: queue.pause() except Exception: # pylint: disable=broad-except @@ -128,6 +130,7 @@ class MxTasks: """Have AareDAQ mount the sample with database id `dbid` (a reference tool if `reference`).""" self._client.aaredaq.mount_sample(dbid, reference=reference) + self._client.reset_sample_info(dbid) @task def aaredaq_raster_scan( -- 2.54.1 From 6854f2d15f19cd957707328e79bba68794b20eb5 Mon Sep 17 00:00:00 2001 From: David Perl Date: Wed, 4 Nov 2026 10:39:33 +0100 Subject: [PATCH 17/46] feat: aaredaq grabs baton --- mx_bec/aaredaq.py | 78 +++++++++++++++++++-- tests/unit/test_aaredaq.py | 137 +++++++++++++++++++++++++++++++------ 2 files changed, 189 insertions(+), 26 deletions(-) diff --git a/mx_bec/aaredaq.py b/mx_bec/aaredaq.py index c003093..a75eff8 100644 --- a/mx_bec/aaredaq.py +++ b/mx_bec/aaredaq.py @@ -2,10 +2,12 @@ from __future__ import annotations import json import subprocess +import time from typing import TYPE_CHECKING, Any import requests from aarecommon.config.beamline import cfg_get, mx_beamline +from aarecommon.models.auth import BatonStatus from aarecommon.models.beamline import MXBeamline from aarecommon.models.raster_grid import CompletedRasterGrid, RasterGridRequest from aarecommon.models.rotation_scan import CompletedRotationScan, RotationScanRequest @@ -26,7 +28,10 @@ DEFAULT_CERT_PATHS = { MXBeamline.X10SA: "/sls/x10sa/misc/.cert/10s.crt", } TOKEN_TIMEOUT_S = 120.0 +REQUEST_TIMEOUT_S = 30.0 # for quick calls such as the baton endpoints SCAN_TIMEOUT_S = 3600.0 # the scan endpoints block until the scan is done +BATON_WAIT_S = 60.0 # covers the server's 30 s for the current holder to answer a request +BATON_POLL_INTERVAL_S = 1.0 class AareDaqError(RuntimeError): @@ -39,7 +44,8 @@ class AareDaq: Mirrors how the AareDAQ GUI talks to the server: a bearer token is obtained once, lazily, by Kerberos (`curl --negotiate` against the Apache proxy in front of the server, exactly as `aare.gui.auth.auth` does), and is renewed once if the server answers 401. The server URL and - its certificate come from the aarecommon beamline config unless given. + its certificate come from the aarecommon beamline config unless given. Hardware operations + take the beamline baton first if this session does not hold it yet. """ def __init__( @@ -98,19 +104,21 @@ class AareDaq: raise AareDaqError(f"AareDAQ token response has no access_token: {result.stdout[:500]}") return token - def _post( + def _request( self, + method: str, endpoint: str, *, params: dict[str, Any] | None = None, body: dict[str, Any] | None = None, timeout_s: float = SCAN_TIMEOUT_S, ) -> Any: - """POST to `endpoint` with the bearer token and return the decoded JSON response. A 401 is + """Call `endpoint` with the bearer token and return the decoded JSON response. A 401 is retried once with a fresh token; any other error becomes an AareDaqError.""" for attempt in range(2): try: - resp = self._session.post( + resp = self._session.request( + method, f"{self.url}{endpoint}", params=params, json=body, @@ -119,20 +127,76 @@ class AareDaq: timeout=timeout_s, ) except requests.RequestException as e: - raise AareDaqError(f"AareDAQ POST {endpoint} failed: {e}") from e + raise AareDaqError(f"AareDAQ {method} {endpoint} failed: {e}") from e if resp.status_code == 401 and attempt == 0: logger.info("AareDAQ rejected the token, requesting a new one") self._token = None continue if not resp.ok: raise AareDaqError( - f"AareDAQ POST {endpoint} failed with {resp.status_code}: {resp.text[:500]}" + f"AareDAQ {method} {endpoint} failed with {resp.status_code}: " + f"{resp.text[:500]}" ) return resp.json() raise AssertionError("unreachable") # pragma: no cover + def _get(self, endpoint: str, timeout_s: float = REQUEST_TIMEOUT_S) -> Any: + return self._request("GET", endpoint, timeout_s=timeout_s) + + def _post( + self, + endpoint: str, + *, + params: dict[str, Any] | None = None, + body: dict[str, Any] | None = None, + timeout_s: float = SCAN_TIMEOUT_S, + ) -> Any: + return self._request("POST", endpoint, params=params, body=body, timeout_s=timeout_s) + + # ---- baton: AareDAQ only runs hardware operations for the session holding the baton ---- + + def baton_status(self) -> BatonStatus: + return BatonStatus.model_validate(self._get("/baton/status")) + + def take_baton( + self, wait_s: float = BATON_WAIT_S, poll_interval_s: float = BATON_POLL_INTERVAL_S + ) -> None: + """Take the baton. Granted at once if the beamline is vacant (or we are staff); otherwise + the current holder is asked, and we poll until they accept or their time to answer runs + out, for up to `wait_s`. Raises AareDaqError if refused or not granted in time.""" + result = self._post("/baton/request", timeout_s=REQUEST_TIMEOUT_S) + if result.get("granted") or result.get("already_holder"): + logger.info(f"AareDAQ baton: {result.get('message')}") + return + if not (result.get("pending") or result.get("queued")): + raise AareDaqError(f"AareDAQ refused the baton request: {result.get('message')}") + logger.info(f"AareDAQ baton: {result.get('message')}; waiting for it") + deadline = time.monotonic() + wait_s + while True: + time.sleep(poll_interval_s) + result = self._get("/baton/check_timeout") + if result.get("granted"): + logger.info("AareDAQ baton acquired") + return + if result.get("refused"): + raise AareDaqError("AareDAQ baton request was refused by the current holder") + if time.monotonic() > deadline: + raise AareDaqError(f"AareDAQ baton not granted within {wait_s} s: {result}") + + def release_baton(self) -> None: + """Release the baton, leaving the beamline vacant.""" + self._post("/baton/release", timeout_s=REQUEST_TIMEOUT_S) + + def ensure_baton(self) -> None: + """Take the baton unless this session already holds it.""" + if not self.baton_status().you_are_holder: + self.take_baton() + + # ---- hardware operations ---- + def mount_sample(self, dbid: int, reference: bool = False, timeout_s: float = 600.0) -> None: """Mount the sample with database id `dbid` (from the reference tools if `reference`).""" + self.ensure_baton() logger.info(f"AareDAQ: mounting sample {dbid}{' (reference tool)' if reference else ''}") self._post( "/sample/mount", params={"dbid": dbid, "reference": reference}, timeout_s=timeout_s @@ -145,6 +209,7 @@ class AareDaq: timeout_s: float = SCAN_TIMEOUT_S, ) -> CompletedRasterGrid: """Run a raster scan and return its result (blocks until the scan is done).""" + self.ensure_baton() logger.info(f"AareDAQ: raster scan {request.n_x}x{request.n_y}, auto_center={auto_center}") result = self._post( "/scan/raster", @@ -158,6 +223,7 @@ class AareDaq: self, request: RotationScanRequest, timeout_s: float = SCAN_TIMEOUT_S ) -> CompletedRotationScan: """Run a rotation (or screening) scan and return its result (blocks until done).""" + self.ensure_baton() logger.info( f"AareDAQ: rotation scan, {request.steps} steps of {request.incr_omega_deg} deg" ) diff --git a/tests/unit/test_aaredaq.py b/tests/unit/test_aaredaq.py index f4ea730..88ade01 100644 --- a/tests/unit/test_aaredaq.py +++ b/tests/unit/test_aaredaq.py @@ -3,6 +3,7 @@ from unittest.mock import MagicMock, call, patch import pytest from aarecommon.math.coordinate import Coordinate, SmargonCoordinate +from aarecommon.models.auth import BatonStatus from aarecommon.models.raster_grid import CompletedRasterGrid, RasterGridRequest from aarecommon.models.rotation_scan import CompletedRotationScan, RotationScanRequest @@ -27,14 +28,37 @@ def curl(): yield run +def _status(you_are_holder: bool) -> dict: + return BatonStatus(you_are_holder=you_are_holder).model_dump(mode="json") + + @pytest.fixture def daq(curl): + """Client with a mocked HTTP session: by default this session holds the baton and every + POST answers "OK".""" daq = AareDaq(MagicMock(), url=URL, cert_path=CERT) daq._session = MagicMock() - daq._session.post.return_value = _response(json_data="OK") + responses = {"GET": _response(json_data=_status(True)), "POST": _response(json_data="OK")} + daq._session.request.side_effect = lambda method, *a, **k: responses[method] + daq._responses = responses return daq +def _calls(daq, method): + """(url, kwargs) of the recorded requests of the given method, in order.""" + return [ + (c.args[1], c.kwargs) for c in daq._session.request.call_args_list if c.args[0] == method + ] + + +def _set_posts(daq, *responses): + """Make successive POSTs answer with the given responses (GETs keep the default).""" + posts = iter(responses) + daq._session.request.side_effect = lambda method, *a, **k: ( + next(posts) if method == "POST" else daq._responses["GET"] + ) + + def _raster_request(): return RasterGridRequest( n_x=2, @@ -93,23 +117,27 @@ def test_token_request_timeout(daq, curl): def test_mount_sample(daq): daq.mount_sample(42) - daq._session.post.assert_called_once_with( - f"{URL}/sample/mount", - params={"dbid": 42, "reference": False}, - json=None, - headers={"Authorization": f"Bearer {TOKEN}"}, - verify=CERT, - timeout=600.0, - ) + assert _calls(daq, "POST") == [ + ( + f"{URL}/sample/mount", + { + "params": {"dbid": 42, "reference": False}, + "json": None, + "headers": {"Authorization": f"Bearer {TOKEN}"}, + "verify": CERT, + "timeout": 600.0, + }, + ) + ] def test_raster_scan(daq): request = _raster_request() completed = CompletedRasterGrid(r=[]) - daq._session.post.return_value = _response(json_data=completed.model_dump(mode="json")) + _set_posts(daq, _response(json_data=completed.model_dump(mode="json"))) assert daq.raster_scan(request, auto_center=True) == completed - kwargs = daq._session.post.call_args.kwargs - assert daq._session.post.call_args.args == (f"{URL}/scan/raster",) + [(url, kwargs)] = _calls(daq, "POST") + assert url == f"{URL}/scan/raster" assert kwargs["params"] == {"auto_center": True} assert kwargs["json"] == request.model_dump(mode="json") assert kwargs["timeout"] == 3600.0 @@ -118,29 +146,98 @@ def test_raster_scan(daq): def test_rotation_scan(daq): request = RotationScanRequest(exp_time_s=0.05, incr_omega_deg=0.1, steps=100) completed = CompletedRotationScan(request=request, result={"images": []}) - daq._session.post.return_value = _response(json_data=completed.model_dump(mode="json")) + _set_posts(daq, _response(json_data=completed.model_dump(mode="json"))) assert daq.rotation_scan(request) == completed - assert daq._session.post.call_args.args == (f"{URL}/scan/rotation",) - assert daq._session.post.call_args.kwargs["json"] == request.model_dump(mode="json") + [(url, kwargs)] = _calls(daq, "POST") + assert url == f"{URL}/scan/rotation" + assert kwargs["json"] == request.model_dump(mode="json") def test_expired_token_is_renewed_once(daq, curl): curl.side_effect = [_curl_result(), _curl_result('{"access_token": "new"}')] - daq._session.post.side_effect = [_response(401), _response(json_data="OK")] + _set_posts(daq, _response(401), _response(json_data="OK")) daq.mount_sample(1) - headers = [c.kwargs["headers"]["Authorization"] for c in daq._session.post.call_args_list] + headers = [kwargs["headers"]["Authorization"] for _, kwargs in _calls(daq, "POST")] assert headers == [f"Bearer {TOKEN}", "Bearer new"] assert daq.token == "new" def test_persistent_401_is_an_error(daq): - daq._session.post.return_value = _response(401, text="nope") + _set_posts(daq, _response(401, text="nope"), _response(401, text="nope")) with pytest.raises(AareDaqError, match="401"): daq.mount_sample(1) - assert daq._session.post.call_count == 2 + assert len(_calls(daq, "POST")) == 2 def test_http_error_reports_status_and_body(daq): - daq._session.post.return_value = _response(422, text='{"detail": "bad request"}') + _set_posts(daq, _response(422, text='{"detail": "bad request"}')) with pytest.raises(AareDaqError, match="422.*bad request"): daq.rotation_scan(RotationScanRequest(exp_time_s=0.05, incr_omega_deg=0.1, steps=1)) + + +# ---- baton ---- + + +def test_baton_status(daq): + assert daq.baton_status() == BatonStatus(you_are_holder=True) + [(url, kwargs)] = _calls(daq, "GET") + assert url == f"{URL}/baton/status" and kwargs["timeout"] == 30.0 + + +def test_hardware_calls_skip_the_baton_request_when_already_holder(daq): + daq.mount_sample(1) + assert [url for url, _ in _calls(daq, "POST")] == [f"{URL}/sample/mount"] + + +def test_hardware_calls_take_the_baton_first(daq): + daq._responses["GET"] = _response(json_data=_status(False)) + _set_posts(daq, _response(json_data={"granted": True}), _response(json_data="OK")) + daq.mount_sample(1) + assert [url for url, _ in _calls(daq, "POST")] == [ + f"{URL}/baton/request", + f"{URL}/sample/mount", + ] + + +@pytest.mark.parametrize("result", [{"granted": True}, {"already_holder": True}]) +def test_take_baton_immediately(daq, result): + _set_posts(daq, _response(json_data=result)) + daq.take_baton() + assert [url for url, _ in _calls(daq, "POST")] == [f"{URL}/baton/request"] + + +def test_take_baton_refused_by_policy(daq): + _set_posts(daq, _response(json_data={"error": True, "message": "disabled by policy"})) + with pytest.raises(AareDaqError, match="disabled by policy"): + daq.take_baton() + + +def test_take_baton_waits_for_the_holder(daq): + _set_posts(daq, _response(json_data={"pending": True, "message": "asked"})) + checks = iter([{"pending": True, "remaining_seconds": 20}, {"granted": True}]) + daq._responses["GET"] = MagicMock() + daq._responses["GET"].ok, daq._responses["GET"].status_code = True, 200 + daq._responses["GET"].json.side_effect = lambda: next(checks) + with patch("mx_bec.aaredaq.time.sleep") as sleep: + daq.take_baton(poll_interval_s=0.5) + assert [url for url, _ in _calls(daq, "GET")] == [f"{URL}/baton/check_timeout"] * 2 + sleep.assert_called_with(0.5) + + +def test_take_baton_refused_by_holder(daq): + _set_posts(daq, _response(json_data={"pending": True})) + daq._responses["GET"] = _response(json_data={"refused": True}) + with patch("mx_bec.aaredaq.time.sleep"), pytest.raises(AareDaqError, match="refused"): + daq.take_baton() + + +def test_take_baton_gives_up_after_wait(daq): + _set_posts(daq, _response(json_data={"queued": True})) + daq._responses["GET"] = _response(json_data={"queued": True}) + with patch("mx_bec.aaredaq.time.sleep"), pytest.raises(AareDaqError, match="not granted"): + daq.take_baton(wait_s=0) + + +def test_release_baton(daq): + daq.release_baton() + assert [url for url, _ in _calls(daq, "POST")] == [f"{URL}/baton/release"] -- 2.54.1 From 406a2ee2d8cd9d8a46aec18773cb689fd012cbee Mon Sep 17 00:00:00 2001 From: x10sa Date: Wed, 4 Nov 2026 14:56:10 +0100 Subject: [PATCH 18/46] progress 261104 --- mx_bec/actors/core.py | 5 +- mx_bec/actors/mx_automation.py | 42 +++++++++++--- .../widgets/aare_bec/task_panel.py | 2 + mx_bec/devices/smargopolo_smargon.py | 11 +++- mx_bec/messages.py | 2 +- mx_bec/optical_centering.py | 39 +++++++------ mx_bec/sample_info.py | 10 ++-- mx_bec/service.py | 6 +- mx_bec/tasks.py | 57 +++++++++++++------ 9 files changed, 122 insertions(+), 52 deletions(-) diff --git a/mx_bec/actors/core.py b/mx_bec/actors/core.py index bc4bf58..a32e1a9 100644 --- a/mx_bec/actors/core.py +++ b/mx_bec/actors/core.py @@ -60,11 +60,10 @@ class MXAutomationActor(SubscriptionActor, ABC): """Whether `action` should run; evaluated after every successful milestone message.""" @abstractmethod - def action(self, client: AareBec, sample_id: int) -> None: + def action(self, client: AareBec) -> 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) + self.action(client) diff --git a/mx_bec/actors/mx_automation.py b/mx_bec/actors/mx_automation.py index 01784a4..e5ef963 100644 --- a/mx_bec/actors/mx_automation.py +++ b/mx_bec/actors/mx_automation.py @@ -5,12 +5,15 @@ are stand-ins for now: they log and immediately publish the next milestone, so t exercised end to end on the simulated beamline before the real procedures exist. """ +import secrets +from time import sleep + 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.messages import MXMeasurementSequenceMessage, MXTaskExecutionMessage from mx_bec.service import AareBec logger = bec_logger.logger @@ -27,9 +30,13 @@ class OnSampleMountedRunOpticalCentering(MXAutomationActor): 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: + def action(self, client: AareBec) -> None: + assert client.sample_info, "No sample loaded" + sample_id = client.sample_info.sample_id logger.info(f"{self.name}: running optical centering for sample {sample_id}") - client.tasks.run_optical_centering(sample_id) + client.add_task_to_queue( + MXTaskExecutionMessage(name="run_optical_centering", args=(sample_id,), kwargs={}) + ) class OnOpticalCenteringDoneRunXrayCentering(MXAutomationActor): @@ -43,10 +50,29 @@ class OnOpticalCenteringDoneRunXrayCentering(MXAutomationActor): def condition(self, client: AareBec) -> bool: return self.last_message is not None - def action(self, client: AareBec, sample_id: int) -> None: + def action(self, client: AareBec) -> None: + assert client.sample_info, "No sample loaded" + sample_id = client.sample_info.sample_id 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), + logger.info( + f"Calculating gridscan strategy given optical centering results of: {client.sample_info.optical_centering_results}" + ) + sleep(2) + logger.info("calculating...") + sleep(2) + strategy = { + "n_x": 10, + "n_y": 10, + "step_x_mm": 0.05, + "step_y_mm": 0.05, + "exp_time_s": 0.05, + "omega_deg": 0.0, + "file_prefix": f"AareBecTestGridScan_{secrets.token_hex(6)}", + "dtz": 250, + "transmission": 0.2, + + } + logger.info(f"calculated strategy: {strategy}") + client.add_task_to_queue( + MXTaskExecutionMessage(name="xray_centering", args=(sample_id, strategy), kwargs={}) ) diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py index 6d8a509..732ca50 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -55,6 +55,8 @@ TASK_FORMS: dict[str, list[tuple[str, int | float | str]]] = { ("step_y_mm", 0.05), ("exp_time_s", 0.1), ("omega_deg", 0.0), + ("dtz", 250), + ("file_prefix", "AareBecTestGridScan"), ], "aaredaq_rotation_scan": [ ("exp_time_s", 0.05), diff --git a/mx_bec/devices/smargopolo_smargon.py b/mx_bec/devices/smargopolo_smargon.py index 29e8b09..6360929 100644 --- a/mx_bec/devices/smargopolo_smargon.py +++ b/mx_bec/devices/smargopolo_smargon.py @@ -1,10 +1,13 @@ from typing import ClassVar import numpy as np +from bec_lib.logger import bec_logger from ophyd import Component as Cpt from .http import HttpDeviceController, HttpDeviceSignal, HttpOphydDevice +logger = bec_logger.logger + _TIMESTAMP_ID = "__timestamp" _POLL_INTERVAL_SLOW = 0.1 @@ -58,16 +61,20 @@ class Smargon(HttpOphydDevice): 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 ( + logger.info(f"Nudging smargon by {x_mm=},{y_mm=},{z_mm=}") + ( self.x.set(self.x.get() + x_mm) & self.y.set(self.y.get() + y_mm) & self.z.set(self.z.get() + z_mm) - ) + ).wait() 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""" + logger.info( + f"Calculating smargon motor nudge for camera offset: {x_mm=}, {y_mm=}, {z_mm=}, at {omega_deg=}" + ) 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)) diff --git a/mx_bec/messages.py b/mx_bec/messages.py index 1805280..084583a 100644 --- a/mx_bec/messages.py +++ b/mx_bec/messages.py @@ -21,7 +21,7 @@ class MXTaskExecutionMessage(BECMessage): msg_type: ClassVar[str] = "mx_task_execution_message" name: str - args: tuple[int | bool | str | float | None, ...] + args: tuple[int | bool | str | float | None | dict[str, int | bool | str | float | None], ...] kwargs: dict[str, int | bool | str | float | None] diff --git a/mx_bec/optical_centering.py b/mx_bec/optical_centering.py index 8bf8db4..8bfad18 100644 --- a/mx_bec/optical_centering.py +++ b/mx_bec/optical_centering.py @@ -7,8 +7,7 @@ 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 +from mx_bec.sample_info import OpticalCenteringResults if TYPE_CHECKING: from mx_bec.service import AareBec @@ -24,7 +23,9 @@ class OpticalPrediction: def get_latest(self): response = self._aarelc_client.request("GET", "/predictions/latest").json() prediction = LatestPredictionModel.model_validate(response) - logger.info(f"Got AareLc prediction: {prediction}") + logger.info( + f"Got AareLc prediction: {prediction.frame_id=}, {prediction.target_point=}, {prediction.image_height=}, {prediction.image_width=}" + ) return prediction def get_target_point_px(self): @@ -41,22 +42,28 @@ class OpticalPrediction: 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""" + zoom = self._client.devices.scam_zoom + zoom.set(1) 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 + logger.info(f"Target point prediction in px on camera image: {target_px}") + a = self._client.aare_config.camera.translation_factor_a + b = self._client.aare_config.camera.translation_factor_b + base_pixel_in_um = 1.0 / (b * np.exp(a * zoom.user_readback.get())) + adjusted_pixel_in_um = ( + base_pixel_in_um * self._client.aare_config.camera.lens_magnification_multiplier ) - return target_px.x * adjusted_pixel_in_mm, target_px.y * adjusted_pixel_in_mm + offset_predicted = ( + target_px.x * adjusted_pixel_in_um / 1000, + target_px.y * adjusted_pixel_in_um / 1000, + ) + logger.info(f"Target point offset in smargon coords predicted: {offset_predicted}") + return offset_predicted 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, - ) + logger.info("Updating latest prediction on sample info") + if self._client.sample_info: + self._client.sample_info.optical_centering_results = OpticalCenteringResults( + prediction=latest + ) diff --git a/mx_bec/sample_info.py b/mx_bec/sample_info.py index 3671f05..9a462ae 100644 --- a/mx_bec/sample_info.py +++ b/mx_bec/sample_info.py @@ -1,16 +1,16 @@ from __future__ import annotations +import time + +from aarelcinfer_client.models import LatestPredictionModel from pydantic import BaseModel, Field class OpticalCenteringResults(BaseModel): """Outputs from the optical centering stage""" - found: bool - smargon_coordinates: tuple[float, float, float] = Field( - description="x,y,z motor coords of the smargon where the crystal was centred" - ) - type_used: str = Field(description="Image analysis element used to determine the center") + prediction: LatestPredictionModel + timestamp: float = Field(default_factory=time.time) class SampleInfo(BaseModel): diff --git a/mx_bec/service.py b/mx_bec/service.py index bb22038..0984f64 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -70,7 +70,11 @@ class AareBec(BECClient): logger.warning(f"Rejected task request: {msg.name!r} is not a public MxTasks method") return logger.info(f"Queueing task request: {msg}") - self.connector.rpush(TaskEndpoints.task_execution(), msg) + self.add_task_to_queue(msg) + + def add_task_to_queue(self, task: MXTaskExecutionMessage): + """Add a task to the task queue. The task should be validated or guaranteed possible.""" + self.connector.rpush(TaskEndpoints.task_execution(), task) self.connector.send(TaskEndpoints.task_queue_changed(), MXTaskQueueChangedMessage()) @property diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index 0a3ba85..f096b63 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -5,10 +5,11 @@ import inspect from threading import Event, RLock, Thread from typing import TYPE_CHECKING, Callable, Concatenate, ParamSpec, Self, TypeVar -from aarecommon.math.coordinate import Coordinate +from aarecommon.math.coordinate import Coordinate, SmargonCoordinate from aarecommon.models.raster_grid import RasterGridRequest from aarecommon.models.rotation_scan import RotationScanRequest from bec_lib.config_values import RedisConfigValue +from bec_lib.endpoints import EndpointInfo from bec_lib.logger import bec_logger from mx_bec.devices.smargopolo_smargon import Smargon @@ -29,6 +30,8 @@ R = TypeVar("R") MAX_GRID_SCAN_S = 1200.0 # refuse grid scans expected to take longer than 20 min +MxSequenceUpdate = tuple[EndpointInfo, MXMeasurementSequenceMessage] | None + class MxTasks: """Holder for operations on mx beamlines. Probably needs to be reconsidered @@ -56,7 +59,9 @@ class MxTasks: return getattr(inspect.getattr_static(cls, name, None), "is_mx_task", False) @staticmethod - def task(method: Callable[Concatenate[MxTasks, P], R]) -> Callable[P, R]: + def task( + method: Callable[Concatenate[MxTasks, P], MxSequenceUpdate], + ) -> Callable[Concatenate[MxTasks, P], None]: """Mark the decorated method as a task. It runs while holding `self._busy_lock`, so that only one task runs at a time, and if it raises, the task queue is paused before the exception propagates, so that queued tasks don't carry on from a failed state.""" @@ -66,12 +71,13 @@ class MxTasks: # pylint: disable=protected-access with self._busy_lock: try: - result = method(self, *args, **kwargs) + state_update = method(self, *args, **kwargs) except Exception as e: self._pause_queue_after_failure(method.__name__, e) raise logger.info(f"Task: {method.__name__} completed.") - return result + if state_update: + self._client.connector.set_and_publish(*state_update) setattr(wrapper, "is_mx_task", True) return wrapper @@ -91,24 +97,28 @@ class MxTasks: """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 + logger.info(f"Optical centering started for sample {sample_id}") try: - for angle in self._client.aare_config.optical_centering.angles: + smargon: Smargon = self._client.devices.smargon + aerotech = self._client.devices.aerotech + angles = self._client.aare_config.optical_centering.angles + logger.info(f"Centring at angles: {angles}") + for angle in angles: + logger.info(f"Aerotech {aerotech} u move to {angle} starting") aerotech.u.set(angle).wait() + logger.info(f"Aerotech u move to {angle} done") 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() + return self._optical_centering_done_update(sample_id, success=False) + smargon.nudge_in_lab_frame(*target, omega_deg=angle) 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) + self._client.optical_prediction.update_latest() + return self._optical_centering_done_update(sample_id, success=True) - def _publish_optical_centering_done(self, sample_id: int, *, success: bool): - self._client.connector.set_and_publish( + def _optical_centering_done_update(self, sample_id: int, *, success: bool): + return ( StateEndpoints.optical_centering_done(), MXMeasurementSequenceMessage(sample_id=sample_id, success=success), ) @@ -126,11 +136,15 @@ class MxTasks: self.planner.move_to(target, modifier) @task - def aaredaq_mount_sample(self, dbid: int, reference: bool = False) -> None: + def aaredaq_mount_sample(self, dbid: int, reference: bool = False) -> MxSequenceUpdate: """Have AareDAQ mount the sample with database id `dbid` (a reference tool if `reference`).""" self._client.aaredaq.mount_sample(dbid, reference=reference) self._client.reset_sample_info(dbid) + return ( + StateEndpoints.sample_mounted(), + MXMeasurementSequenceMessage(sample_id=dbid, success=True), + ) @task def aaredaq_raster_scan( @@ -148,6 +162,7 @@ class MxTasks: ) -> None: """Have AareDAQ run an n_x by n_y raster scan from the current Smargon position (`smargon_top_left` is left unset), optionally auto-centering afterwards.""" + smargon = self._client.devices.smargon request = RasterGridRequest( n_x=n_x, n_y=n_y, @@ -157,11 +172,21 @@ class MxTasks: file_prefix=file_prefix, dtz=dtz, transmission=transmission, - smargon_top_left=None, + smargon_top_left=SmargonCoordinate( + sh_mm=Coordinate(x=smargon.x.get(), y=smargon.x.get(), z=smargon.x.get()) + ), ) result = self._client.aaredaq.raster_scan(request, auto_center=auto_center) logger.info(f"AareDAQ raster scan done: {len(result.r)} grid(s) collected") + @task + def xray_centering(self, dbid: int, strategy: dict): + self.aaredaq_raster_scan(**strategy) + return ( + StateEndpoints.xray_centering_done(), + MXMeasurementSequenceMessage(sample_id=dbid, success=True), + ) + @task def aaredaq_rotation_scan( self, -- 2.54.1 From f0ea2153f1a05dbd03672559d711a9f5446a9b29 Mon Sep 17 00:00:00 2001 From: David Perl Date: Wed, 4 Nov 2026 16:06:42 +0100 Subject: [PATCH 19/46] docs: add todo --- todo.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 todo.md diff --git a/todo.md b/todo.md new file mode 100644 index 0000000..59e50c0 --- /dev/null +++ b/todo.md @@ -0,0 +1,4 @@ +- smargon limits (move sticks forever out of range) +- 2 queues: sample + task queue, tasks can be l-added +- replace all tasks with wrapped aaredaq tasks to review calculations +- -- 2.54.1 From 66105af28559e5b3eefb66fb1246d80144b622f0 Mon Sep 17 00:00:00 2001 From: David Perl Date: Mon, 9 Nov 2026 11:36:02 +0100 Subject: [PATCH 20/46] feat: add aaredaq optical task --- mx_bec/aaredaq.py | 7 +- .../widgets/aare_bec/task_panel.py | 40 ++--- mx_bec/tasks.py | 157 ++++++++++-------- 3 files changed, 109 insertions(+), 95 deletions(-) diff --git a/mx_bec/aaredaq.py b/mx_bec/aaredaq.py index a75eff8..28f799b 100644 --- a/mx_bec/aaredaq.py +++ b/mx_bec/aaredaq.py @@ -134,8 +134,7 @@ class AareDaq: continue if not resp.ok: raise AareDaqError( - f"AareDAQ {method} {endpoint} failed with {resp.status_code}: " - f"{resp.text[:500]}" + f"AareDAQ {method} {endpoint} failed with {resp.status_code}: {resp.text[:500]}" ) return resp.json() raise AssertionError("unreachable") # pragma: no cover @@ -202,6 +201,10 @@ class AareDaq: "/sample/mount", params={"dbid": dbid, "reference": reference}, timeout_s=timeout_s ) + def auto_loop_center(self): + self.ensure_baton() + self._post("/alc/center_loop") + def raster_scan( self, request: RasterGridRequest, diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py index 732ca50..1293137 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -26,26 +26,26 @@ logger = bec_logger.logger # Hard-coded forms: task name -> [(argument, default value)]; the widget type follows the default. TASK_FORMS: dict[str, list[tuple[str, int | float | str]]] = { "run_optical_centering": [("sample_id", 0)], - "run_grid_scan": [ - ("n_x", 4), - ("n_y", 3), - ("step_x_um", 50.0), - ("step_y_um", 50.0), - ("exp_time_s", 0.1), - ("file_prefix", "grid"), - ("detector_distance_mm", 150.0), - ("transmission", 0.1), - ("energy_keV", 12.4), - ("beam_center_x_pxl", 0.0), - ("beam_center_y_pxl", 0.0), - ("beam_size_x_mm", 0.02), - ("beam_size_y_mm", 0.01), - ("ring_current_mA", 400.0), - ("flux_ph_s", 1e12), - ("sample_temperature_K", 100.0), - ("pgroup", "p16371"), - ("sample_name", "unknown_sample"), - ], + # "run_grid_scan": [ + # ("n_x", 4), + # ("n_y", 3), + # ("step_x_um", 50.0), + # ("step_y_um", 50.0), + # ("exp_time_s", 0.1), + # ("file_prefix", "grid"), + # ("detector_distance_mm", 150.0), + # ("transmission", 0.1), + # ("energy_keV", 12.4), + # ("beam_center_x_pxl", 0.0), + # ("beam_center_y_pxl", 0.0), + # ("beam_size_x_mm", 0.02), + # ("beam_size_y_mm", 0.01), + # ("ring_current_mA", 400.0), + # ("flux_ph_s", 1e12), + # ("sample_temperature_K", 100.0), + # ("pgroup", "p16371"), + # ("sample_name", "unknown_sample"), + # ], # the AareDAQ-driven tasks; their bool/optional arguments keep their defaults here "aaredaq_mount_sample": [("dbid", 0)], "aaredaq_raster_scan": [ diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index f096b63..b45b5cb 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -34,8 +34,11 @@ MxSequenceUpdate = tuple[EndpointInfo, MXMeasurementSequenceMessage] | None class MxTasks: - """Holder for operations on mx beamlines. Probably needs to be reconsidered - or at least moved to its own module""" + """Holder for operations on mx beamlines. Probably needs to be reconsidered. + TODO: + - categorise tasks, allow nesting with one lock + - add doc info to decorator, including placeholder for args, to show to GUI + """ def __init__(self, client: AareBec): self._client = client @@ -79,7 +82,7 @@ class MxTasks: if state_update: self._client.connector.set_and_publish(*state_update) - setattr(wrapper, "is_mx_task", True) + wrapper.is_mx_task = True return wrapper def _pause_queue_after_failure(self, task_name: str, e: Exception) -> None: @@ -93,7 +96,7 @@ class MxTasks: logger.exception("Failed to pause the task queue") @task - def run_optical_centering(self, sample_id: int): + def run_optical_centering_bec(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.""" @@ -117,6 +120,11 @@ class MxTasks: self._client.optical_prediction.update_latest() return self._optical_centering_done_update(sample_id, success=True) + @task + def run_optical_centering(self, sample_id): + self._client.aaredaq.auto_loop_center() + return self._optical_centering_done_update(sample_id, success=True) + def _optical_centering_done_update(self, sample_id: int, *, success: bool): return ( StateEndpoints.optical_centering_done(), @@ -173,7 +181,9 @@ class MxTasks: dtz=dtz, transmission=transmission, smargon_top_left=SmargonCoordinate( - sh_mm=Coordinate(x=smargon.x.get(), y=smargon.x.get(), z=smargon.x.get()) + sh_mm=Coordinate(x=smargon.x.get(), y=smargon.x.get(), z=smargon.x.get()), + chi_deg=smargon.chi.get(), + phi_deg=smargon.phi.get(), ), ) result = self._client.aaredaq.raster_scan(request, auto_center=auto_center) @@ -216,75 +226,76 @@ class MxTasks: result = self._client.aaredaq.rotation_scan(request) logger.info(f"AareDAQ rotation scan done: {len(result.result.images)} images") - @task - def run_grid_scan( - self, - n_x: int, - n_y: int, - step_x_um: float, - step_y_um: float, - exp_time_s: float, - file_prefix: str, - detector_distance_mm: float, - transmission: float, - energy_keV: float, - beam_center_x_pxl: float, - beam_center_y_pxl: float, - beam_size_x_mm: float, - beam_size_y_mm: float, - ring_current_mA: float, - flux_ph_s: float, - sample_temperature_K: float, - pgroup: str = "p16371", - sample_name: str = "unknown_sample", - ) -> None: - """Collect an n_x by n_y grid scan at the current position and omega: configure the - Aerotech grid scan and check that AareScan accepts it, arm JFJoch, then trigger the - Aerotech and wait for both to finish.""" - expected_s = exp_time_s * n_x * n_y + n_y * 0.3 - if expected_s > MAX_GRID_SCAN_S: - raise ValueError(f"Grid scan is too long: {expected_s:.0f} s > {MAX_GRID_SCAN_S} s") - aerotech = self._client.devices.aerotech - config = aerotech.gridscan_config - for signal, value in ( - (config.grid_elem_count_x, n_x), - (config.grid_elem_count_y, n_y), - (config.grid_elem_size_x_um, step_x_um), - (config.grid_elem_size_y_um, step_y_um), - (config.time_per_element_sec, exp_time_s), - ): - signal.set(value).wait() - if not config.valid.get(): - raise ValueError(f"AareScan rejected the grid scan parameters: {config.message.get()}") - - jfjoch = self._client.jfjoch - jfjoch.measure_raster( - RasterScan( - n_x=n_x, - n_y=n_y, - step_x_mm=step_x_um / 1000.0, - step_y_mm=step_y_um / 1000.0, - omega_deg=aerotech.u.get(), - exp_time_s=exp_time_s, - detector_distance_mm=detector_distance_mm, - transmission=transmission, - file_prefix=file_prefix, - pgroup=pgroup, - sample_name=sample_name, - energy_keV=energy_keV, - beam_center_pxl=(beam_center_x_pxl, beam_center_y_pxl), - beam_size_mm=(beam_size_x_mm, beam_size_y_mm), - ring_current_mA=ring_current_mA, - flux_ph_s=flux_ph_s, - sample_temperature_K=sample_temperature_K, - ) - ) - jfjoch.wait_till_running(timeout_s=60) - logger.info(f"Starting {n_x}x{n_y} grid scan, {exp_time_s} s per element") - aerotech.trigger().wait() - result = jfjoch.wait_till_done(timeout_s=60) - logger.info(f"Grid scan finished: {result.file_prefix} with {len(result.images)} images") +# @task +# def run_grid_scan( +# self, +# n_x: int, +# n_y: int, +# step_x_um: float, +# step_y_um: float, +# exp_time_s: float, +# file_prefix: str, +# detector_distance_mm: float, +# transmission: float, +# energy_keV: float, +# beam_center_x_pxl: float, +# beam_center_y_pxl: float, +# beam_size_x_mm: float, +# beam_size_y_mm: float, +# ring_current_mA: float, +# flux_ph_s: float, +# sample_temperature_K: float, +# pgroup: str = "p16371", +# sample_name: str = "unknown_sample", +# ) -> None: +# """Collect an n_x by n_y grid scan at the current position and omega: configure the +# Aerotech grid scan and check that AareScan accepts it, arm JFJoch, then trigger the +# Aerotech and wait for both to finish.""" +# expected_s = exp_time_s * n_x * n_y + n_y * 0.3 +# if expected_s > MAX_GRID_SCAN_S: +# raise ValueError(f"Grid scan is too long: {expected_s:.0f} s > {MAX_GRID_SCAN_S} s") +# +# aerotech = self._client.devices.aerotech +# config = aerotech.gridscan_config +# for signal, value in ( +# (config.grid_elem_count_x, n_x), +# (config.grid_elem_count_y, n_y), +# (config.grid_elem_size_x_um, step_x_um), +# (config.grid_elem_size_y_um, step_y_um), +# (config.time_per_element_sec, exp_time_s), +# ): +# signal.set(value).wait() +# if not config.valid.get(): +# raise ValueError(f"AareScan rejected the grid scan parameters: {config.message.get()}") +# +# jfjoch = self._client.jfjoch +# jfjoch.measure_raster( +# RasterScan( +# n_x=n_x, +# n_y=n_y, +# step_x_mm=step_x_um / 1000.0, +# step_y_mm=step_y_um / 1000.0, +# omega_deg=aerotech.u.get(), +# exp_time_s=exp_time_s, +# detector_distance_mm=detector_distance_mm, +# transmission=transmission, +# file_prefix=file_prefix, +# pgroup=pgroup, +# sample_name=sample_name, +# energy_keV=energy_keV, +# beam_center_pxl=(beam_center_x_pxl, beam_center_y_pxl), +# beam_size_mm=(beam_size_x_mm, beam_size_y_mm), +# ring_current_mA=ring_current_mA, +# flux_ph_s=flux_ph_s, +# sample_temperature_K=sample_temperature_K, +# ) +# ) +# jfjoch.wait_till_running(timeout_s=60) +# logger.info(f"Starting {n_x}x{n_y} grid scan, {exp_time_s} s per element") +# aerotech.trigger().wait() +# result = jfjoch.wait_till_done(timeout_s=60) +# logger.info(f"Grid scan finished: {result.file_prefix} with {len(result.images)} images") class MxTaskQueue: -- 2.54.1 From dc247745b26d773e5b292416a4a182e246fd8ffc Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 10 Nov 2026 09:11:09 +0100 Subject: [PATCH 21/46] feat: add multi-raster --- .../widgets/aare_bec/task_panel.py | 10 ++++ mx_bec/tasks.py | 58 ++++++++++++++++--- 2 files changed, 61 insertions(+), 7 deletions(-) diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py index 1293137..e26e329 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -58,6 +58,16 @@ TASK_FORMS: dict[str, list[tuple[str, int | float | str]]] = { ("dtz", 250), ("file_prefix", "AareBecTestGridScan"), ], + "multiple_rasters": [ + ("omegas_deg_list", "0, 30, 60, 90"), + ("n_x", 4), + ("n_y", 3), + ("step_x_mm", 0.05), + ("step_y_mm", 0.05), + ("exp_time_s", 0.1), + ("dtz", 250), + ("file_prefix", "AareBecTestGridScan"), + ], "aaredaq_rotation_scan": [ ("exp_time_s", 0.05), ("incr_omega_deg", 0.1), diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index b45b5cb..41ce346 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -15,12 +15,15 @@ from bec_lib.logger import bec_logger from mx_bec.devices.smargopolo_smargon import Smargon from mx_bec.endpoints import StateEndpoints, TaskEndpoints from mx_bec.jfjoch import RasterScan -from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskQueueChangedMessage +from mx_bec.messages import ( + MXMeasurementSequenceMessage, + MXTaskExecutionMessage, + MXTaskQueueChangedMessage, +) if TYPE_CHECKING: from pxii_bec.macros.beamline_planner import StateChangePlanner - from mx_bec.messages import MXTaskExecutionMessage from mx_bec.service import AareBec logger = bec_logger.logger @@ -45,6 +48,12 @@ class MxTasks: self._busy_lock = RLock() self._planner: StateChangePlanner | None = None + def _request_task(self, name: str, *args, **kwargs): + """Submit a task request to the AareBec service.""" + msg = MXTaskExecutionMessage(name=name, args=args, kwargs=kwargs) + logger.info(f"Requesting task: {msg}") + self._client.connector.xadd(TaskEndpoints.task_request(), {"data": msg}) + @property def planner(self) -> StateChangePlanner: """The beamline state planner, built on first use: `init_beamline_environment` needs the @@ -166,11 +175,17 @@ class MxTasks: file_prefix: str | None = None, dtz: float | None = None, transmission: float | None = None, + smargon_top_left: SmargonCoordinate | None = None, auto_center: bool = False, ) -> None: """Have AareDAQ run an n_x by n_y raster scan from the current Smargon position (`smargon_top_left` is left unset), optionally auto-centering afterwards.""" smargon = self._client.devices.smargon + smargon_top_left = smargon_top_left or SmargonCoordinate( + sh_mm=Coordinate(x=smargon.x.get(), y=smargon.x.get(), z=smargon.x.get()), + chi_deg=smargon.chi.get(), + phi_deg=smargon.phi.get(), + ) request = RasterGridRequest( n_x=n_x, n_y=n_y, @@ -180,15 +195,44 @@ class MxTasks: file_prefix=file_prefix, dtz=dtz, transmission=transmission, - smargon_top_left=SmargonCoordinate( - sh_mm=Coordinate(x=smargon.x.get(), y=smargon.x.get(), z=smargon.x.get()), - chi_deg=smargon.chi.get(), - phi_deg=smargon.phi.get(), - ), + smargon_top_left=smargon_top_left, ) result = self._client.aaredaq.raster_scan(request, auto_center=auto_center) logger.info(f"AareDAQ raster scan done: {len(result.r)} grid(s) collected") + @task + def multiple_rasters( + self, + omegas_deg_list: str, + n_x: int, + n_y: int, + step_x_mm: float, + step_y_mm: float, + exp_time_s: float, + file_prefix: str | None = None, + dtz: float | None = None, + ) -> None: + """Run multiple raster scans at different omega values""" + omegas = [float(ang) for ang in omegas_deg_list.split(",")] + smargon = self._client.devices.smargon + smargon_top_left = SmargonCoordinate( + sh_mm=Coordinate(x=smargon.x.get(), y=smargon.x.get(), z=smargon.x.get()), + chi_deg=smargon.chi.get(), + phi_deg=smargon.phi.get(), + ) + for i, omega in enumerate(omegas): + self.aaredaq_raster_scan( + n_x, + n_y, + step_x_mm, + step_y_mm, + exp_time_s, + file_prefix=f"{file_prefix}_{i}_{omega:%.2f}deg", + dtz=dtz, + smargon_top_left=smargon_top_left, + ) + logger.info(f"Raster {i + 1} out of {len(omegas)} done.") + @task def xray_centering(self, dbid: int, strategy: dict): self.aaredaq_raster_scan(**strategy) -- 2.54.1 From 04c76ac0f050c10ea97c5cd4141e9e24f03e841c Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 10 Nov 2026 09:25:58 +0100 Subject: [PATCH 22/46] feat: add spreadsheet display hax --- .../aare_bec/sample_spreadsheet_display.py | 42 +++++++++++++++++++ mx_bec/service.py | 9 ++++ 2 files changed, 51 insertions(+) create mode 100644 mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py diff --git a/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py b/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py new file mode 100644 index 0000000..9087158 --- /dev/null +++ b/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +import json +from typing import Any + +from bec_lib.logger import bec_logger +from bec_widgets.utils.bec_connector import ConnectionConfig +from bec_widgets.utils.bec_widget import BECWidget +from PySide6.QtWidgets import QVBoxLayout +from qtpy.QtWidgets import QLabel, QWidget + +logger = bec_logger.logger + + +class SampleSpreadsheetDisplay(BECWidget, QWidget): + """ + Display information from the sample spreadsheet + """ + + PLUGIN = True + ICON_NAME = "format_list_bulleted" + + def __init__( + self, + parent: QWidget | None = None, + client=None, + config: ConnectionConfig | None = None, + gui_id: str | None = None, + **kwargs, + ) -> None: + super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs) + self._data: dict[str, Any] + self._layout = QVBoxLayout(self) + self._layout.addWidget(QLabel(" Sample spreadhseet data: ")) + try: + data: str = self.client.connector._managed_connection.get("x10sa:sample_spreadsheet") + if data is not None: + dict_data = json.loads(data) + except Exception as e: + self._layout.addWidget(QLabel(f"Failed to load spreadsheet data: {e}")) + return + self._layout.addWidget(QLabel(json.dumps(dict_data, indent=2))) diff --git a/mx_bec/service.py b/mx_bec/service.py index 0984f64..fb4c868 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -7,6 +7,7 @@ from aare_config import AareConfigClient from bec_lib import messages from bec_lib.client import BECClient from bec_lib.logger import bec_logger +from redis.client import Redis from mx_bec.aaredaq import AareDaq from mx_bec.actor_manager import AareActorManager @@ -53,6 +54,12 @@ class AareBec(BECClient): self.tasks = MxTasks(self) self.task_queue: MxTaskQueue | None = None self.sample_info: SampleInfo | None = None + # HAX + _host, _port = config_redis_url.split(":") + _port = int(_port) + _hacky_redis = Redis(_host, _port) + self._spreadsheet = _hacky_redis.get("x10sa:sample_spreadsheet") + _hacky_redis.close() def start(self): super().start() @@ -61,6 +68,8 @@ class AareBec(BECClient): self.task_queue.start() self.connector.register(TaskEndpoints.task_request(), cb=self._on_task_request) self.status = messages.BECStatus.RUNNING + # HAX + self.connector._managed_connection.set("x10sa:sample_spreadsheet", self._spreadsheet) def _on_task_request(self, msg_dict: dict) -> None: """Validate a task request and, if it names a public `MxTasks` method, append it to the -- 2.54.1 From c8cab28dafe827c544d5df627fdd34172affb56b Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 10 Nov 2026 12:11:10 +0100 Subject: [PATCH 23/46] add html table --- .../aare_bec/sample_spreadsheet_display.py | 42 ++++++++++++++++--- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py b/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py index 9087158..5378a4f 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py @@ -4,14 +4,41 @@ import json from typing import Any from bec_lib.logger import bec_logger +from bec_lib.messages import RawMessage from bec_widgets.utils.bec_connector import ConnectionConfig from bec_widgets.utils.bec_widget import BECWidget -from PySide6.QtWidgets import QVBoxLayout +from PySide6.QtWidgets import QScrollArea, QVBoxLayout from qtpy.QtWidgets import QLabel, QWidget logger = bec_logger.logger +def dicts_to_html_table(data: list[dict]) -> str: + if not data: + return "

No data available

" + + # 1. Extract unique keys for the header + headers = list(set(k for item in data for k in item.keys())) + + # 2. Build the HTML Header Row + html = "\n \n \n" + for header in headers: + html += f" \n" + html += " \n \n \n" + + # 3. Build the Data Rows + for row in data: + html += " \n" + for header in headers: + # .get() handles missing keys safely + val = row.get(header, "") + html += f" \n" + html += " \n" + + html += " \n
{header}
{val}
" + return html + + class SampleSpreadsheetDisplay(BECWidget, QWidget): """ Display information from the sample spreadsheet @@ -32,11 +59,16 @@ class SampleSpreadsheetDisplay(BECWidget, QWidget): self._data: dict[str, Any] self._layout = QVBoxLayout(self) self._layout.addWidget(QLabel(" Sample spreadhseet data: ")) + dict_data = [{}] try: - data: str = self.client.connector._managed_connection.get("x10sa:sample_spreadsheet") - if data is not None: - dict_data = json.loads(data) + data = self.client.connector._managed_connection.get("x10sa:sample_spreadsheet") + if isinstance(data, RawMessage): + dict_data: list[dict[str, Any]] = data.data["s"] + else: + dict_data = [{"text": str(data)}] except Exception as e: self._layout.addWidget(QLabel(f"Failed to load spreadsheet data: {e}")) return - self._layout.addWidget(QLabel(json.dumps(dict_data, indent=2))) + self._layout_area = QScrollArea() + self._layout.addWidget(self._layout_area) + self._layout_area.setWidget(QLabel(dicts_to_html_table(dict_data))) -- 2.54.1 From 57738e98f8f15811eed4238771267882939eeeed Mon Sep 17 00:00:00 2001 From: x10sa Date: Wed, 11 Nov 2026 10:38:50 +0100 Subject: [PATCH 24/46] fix display --- .../widgets/aare_bec/sample_spreadsheet_display.py | 6 +++--- mx_bec/bec_widgets/widgets/aare_bec/task_panel.py | 5 +++++ mx_bec/service.py | 4 ++-- mx_bec/tasks.py | 7 ++++--- 4 files changed, 14 insertions(+), 8 deletions(-) diff --git a/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py b/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py index 5378a4f..76c3797 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py @@ -1,14 +1,12 @@ from __future__ import annotations -import json from typing import Any from bec_lib.logger import bec_logger from bec_lib.messages import RawMessage from bec_widgets.utils.bec_connector import ConnectionConfig from bec_widgets.utils.bec_widget import BECWidget -from PySide6.QtWidgets import QScrollArea, QVBoxLayout -from qtpy.QtWidgets import QLabel, QWidget +from qtpy.QtWidgets import QLabel, QScrollArea, QVBoxLayout, QWidget logger = bec_logger.logger @@ -19,6 +17,8 @@ def dicts_to_html_table(data: list[dict]) -> str: # 1. Extract unique keys for the header headers = list(set(k for item in data for k in item.keys())) + if "aaredb_params" in headers: + headers.remove("aaredb_params") # 2. Build the HTML Header Row html = "\n \n \n" diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py index e26e329..1cbf997 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -10,6 +10,7 @@ from qtpy.QtWidgets import ( QGridLayout, QGroupBox, QHBoxLayout, + QLabel, QLineEdit, QPushButton, QScrollArea, @@ -20,6 +21,7 @@ from qtpy.QtWidgets import ( from mx_bec.endpoints import TaskEndpoints from mx_bec.messages import MXTaskExecutionMessage +from mx_bec.tasks import MxTasks logger = bec_logger.logger @@ -133,6 +135,9 @@ class MxTaskPanel(BECWidget, QWidget): ) -> QGroupBox: box = QGroupBox(task, parent=parent) form = QFormLayout() + if (task_fn := getattr(MxTasks, task, None)) is not None: + if (doc := task_fn.__doc__) is not None: + form.addWidget(QLabel(doc)) self._inputs[task] = {} for name, default in fields: widget = self._input(box, default) diff --git a/mx_bec/service.py b/mx_bec/service.py index fb4c868..e15323d 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -55,9 +55,9 @@ class AareBec(BECClient): self.task_queue: MxTaskQueue | None = None self.sample_info: SampleInfo | None = None # HAX - _host, _port = config_redis_url.split(":") + _, _host, _port = config_redis_url.split(":") _port = int(_port) - _hacky_redis = Redis(_host, _port) + _hacky_redis = Redis(_host[2:], _port) self._spreadsheet = _hacky_redis.get("x10sa:sample_spreadsheet") _hacky_redis.close() diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index 41ce346..1702f9e 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -182,10 +182,11 @@ class MxTasks: (`smargon_top_left` is left unset), optionally auto-centering afterwards.""" smargon = self._client.devices.smargon smargon_top_left = smargon_top_left or SmargonCoordinate( - sh_mm=Coordinate(x=smargon.x.get(), y=smargon.x.get(), z=smargon.x.get()), + sh_mm=Coordinate(x=smargon.x.get(), y=smargon.y.get(), z=smargon.z.get()), chi_deg=smargon.chi.get(), phi_deg=smargon.phi.get(), ) + logger.info(f"smargon top left supplied to grid scan {smargon_top_left=}") request = RasterGridRequest( n_x=n_x, n_y=n_y, @@ -213,7 +214,7 @@ class MxTasks: dtz: float | None = None, ) -> None: """Run multiple raster scans at different omega values""" - omegas = [float(ang) for ang in omegas_deg_list.split(",")] + omegas = [float(ang.strip()) for ang in omegas_deg_list.split(",")] smargon = self._client.devices.smargon smargon_top_left = SmargonCoordinate( sh_mm=Coordinate(x=smargon.x.get(), y=smargon.x.get(), z=smargon.x.get()), @@ -227,7 +228,7 @@ class MxTasks: step_x_mm, step_y_mm, exp_time_s, - file_prefix=f"{file_prefix}_{i}_{omega:%.2f}deg", + file_prefix=f"{file_prefix}_{i}_{omega:.2f}deg", dtz=dtz, smargon_top_left=smargon_top_left, ) -- 2.54.1 From 9c4d7566cf2407576bc288fb52e31e146e1fd120 Mon Sep 17 00:00:00 2001 From: x10sa Date: Wed, 11 Nov 2026 13:38:50 +0100 Subject: [PATCH 25/46] integrate stuff --- mx_bec/actors/mx_automation.py | 198 +++++++++++++++++++++- mx_bec/endpoints.py | 12 ++ mx_bec/sample_info.py | 12 +- mx_bec/tasks.py | 296 ++++++++++++++++++++------------- 4 files changed, 393 insertions(+), 125 deletions(-) diff --git a/mx_bec/actors/mx_automation.py b/mx_bec/actors/mx_automation.py index e5ef963..4465662 100644 --- a/mx_bec/actors/mx_automation.py +++ b/mx_bec/actors/mx_automation.py @@ -7,13 +7,24 @@ exercised end to end on the simulated beamline before the real procedures exist. import secrets from time import sleep +from typing import Any, ClassVar from bec_lib.endpoints import EndpointInfo from bec_lib.logger import bec_logger +from pxii_bec.macros.flux_macros import bpm2flux from mx_bec.actors.core import MXAutomationActor from mx_bec.endpoints import StateEndpoints from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskExecutionMessage +from mx_bec.self_driving import ( + Action, + SelfDrivingRecord, + StrategyConfig, + analyse_grid, + assess_collection, + decide_followup, + plan_rotation, +) from mx_bec.service import AareBec logger = bec_logger.logger @@ -60,19 +71,196 @@ class OnOpticalCenteringDoneRunXrayCentering(MXAutomationActor): sleep(2) logger.info("calculating...") sleep(2) + n_x = 10 + n_y = 10 + step_x_mm = 0.05 + step_y_mm = 0.05 strategy = { - "n_x": 10, - "n_y": 10, - "step_x_mm": 0.05, - "step_y_mm": 0.05, + "n_x": n_x, + "n_y": n_y, + "step_x_mm": step_x_mm, + "step_y_mm": step_y_mm, "exp_time_s": 0.05, "omega_deg": 0.0, "file_prefix": f"AareBecTestGridScan_{secrets.token_hex(6)}", "dtz": 250, "transmission": 0.2, - } logger.info(f"calculated strategy: {strategy}") + client.add_task_to_queue( MXTaskExecutionMessage(name="xray_centering", args=(sample_id, strategy), kwargs={}) ) + + +class SelfDrivingActor(MXAutomationActor): + """Shared helpers. Abstract: subclasses set ``config_key`` and implement ``action``.""" + + strategy: ClassVar[StrategyConfig] = StrategyConfig() + + def condition(self, client: AareBec) -> bool: + msg = self.last_message + if msg is None or not msg.success: + return False + info = client.sample_info + if info is None or info.sample_id != msg.sample_id: + logger.warning(f"{type(self).__name__}: message for sample {msg.sample_id} is stale") + return False + return True + + @staticmethod + def record(client: AareBec) -> SelfDrivingRecord: + info = client.sample_info + assert info is not None, "No sample loaded" + if info.self_driving is None: + info.self_driving = SelfDrivingRecord() + return info.self_driving + + @staticmethod + def queue(client: AareBec, name: str, *args: Any) -> None: + client.add_task_to_queue(MXTaskExecutionMessage(name=name, args=args, kwargs={})) + + @staticmethod + def finish(client: AareBec, sample_id: int, *, success: bool, reason: str) -> None: + logger.info(f"Self-driving: sample {sample_id} finished (success={success}): {reason}") + client.connector.set_and_publish( + StateEndpoints.sample_done(), + MXMeasurementSequenceMessage(sample_id=sample_id, success=success), + ) + + def queue_collection( + self, + client: AareBec, + record: SelfDrivingRecord, + sample_id: int, + position_index: int, + *, + chi_values: list[float] | tuple[float, ...] = (0.0,), + dose_fraction: float = 1.0, + reason: str, + ) -> bool: + assert record.analysis is not None + prefix = f"S{sample_id}_{secrets.token_hex(3)}" + _, self.strategy.beam.flux_ph_s = bpm2flux() + try: + plan = plan_rotation( + record.analysis, + position_index, + self.strategy, + file_prefix=prefix, + chi_values=chi_values, + dose_fraction=dose_fraction, + reason=reason, + ) + except ValueError as e: + self.finish(client, sample_id, success=False, reason=f"cannot plan: {e}") + return False + if position_index not in record.positions_used: + record.positions_used.append(position_index) + logger.info(f"Self-driving: queue collection for sample {sample_id}: {plan}") + self.queue(client, "collect_dataset", sample_id, plan.model_dump()) + return True + + +class OnXrayCenteringDonePlanCollection(SelfDrivingActor): + """Analyse the grid with the Rugnux/Jungfraujoch per-cell results and queue the first dataset.""" + + config_key = "self_driving_collect_after_grid" + + def default_monitor_endpoints(self) -> set[EndpointInfo[type[MXMeasurementSequenceMessage]]]: + return {StateEndpoints.xray_centering_done()} + + def action(self, client: AareBec) -> None: + info = client.sample_info + assert info is not None, "No sample loaded" + sample_id = info.sample_id + raster = info.raster + if raster is None: + self.finish(client, sample_id, success=False, reason="no raster results stored") + return + + record = self.record(client) + record.raster_strategy = dict(raster.strategy) + record.analysis = analyse_grid(raster.images, raster.geometry, self.strategy) + # A new grid has new coordinates: spots from an earlier grid no longer apply. + # ASSUMPTION: the raster leaves the smargon at its start position (cell 0, 0). + record.positions_used = [] + record.current_offset_mm = (0.0, 0.0) + + analysis = record.analysis + logger.info( + f"Self-driving: grid for sample {sample_id}: {analysis.n_hits}/{analysis.n_images} " + f"hits, {len(analysis.regions)} crystal(s), {len(analysis.positions)} spot(s)" + ) + if not analysis.positions: + self.finish(client, sample_id, success=False, reason="no diffraction in grid") + return + + cfg = self.strategy + if cfg.anomalous: + chis = cfg.anomalous_chi_deg + if len(chis) > 1: + record.chi_sweeps_done += 1 + reason = "anomalous: low-dose multi-chi" + else: + chis, reason = (0.0,), "best spot from grid" + self.queue_collection(client, record, sample_id, 0, chi_values=chis, reason=reason) + + +class OnRotationDoneDecideFollowUp(SelfDrivingActor): + """Assess the last dataset and queue a follow-up, or finish the sample.""" + + config_key = "self_driving_followup_after_rotation" + + def default_monitor_endpoints(self) -> set[EndpointInfo[type[MXMeasurementSequenceMessage]]]: + return {StateEndpoints.rotation_done()} + + def action(self, client: AareBec) -> None: + info = client.sample_info + assert info is not None, "No sample loaded" + sample_id = info.sample_id + record = self.record(client) + if not record.collections: + self.finish(client, sample_id, success=False, reason="rotation_done without a record") + return + + latest = record.collections[-1] + latest.assessment = assess_collection(latest, self.strategy) + decision = decide_followup(latest.assessment, record, self.strategy) + logger.info( + f"Self-driving: sample {sample_id} issues={[i.value for i in latest.assessment.issues]}" + f" -> {decision.action.value}: {decision.reason}" + ) + + if decision.action is Action.FINISH: + usable = any(c.assessment and c.assessment.usable for c in record.collections) + self.finish(client, sample_id, success=usable, reason=decision.reason) + return + + record.followups += 1 + if decision.action is Action.RECENTRE: + if record.raster_strategy is None: + self.finish(client, sample_id, success=False, reason="no raster to repeat") + return + record.recentres += 1 + strategy = dict(record.raster_strategy) + strategy["file_prefix"] = ( + f"{strategy.get('file_prefix') or 'raster'}_rc{record.recentres}" + ) + # Back to the original raster start so the repeat grid covers the same area. + self.queue(client, "move_to_grid_offset", sample_id, 0.0, 0.0) + self.queue(client, "xray_centering", sample_id, strategy) + return + + assert decision.position_index is not None + if decision.action is Action.CHI_SWEEP: + record.chi_sweeps_done += 1 + self.queue_collection( + client, + record, + sample_id, + decision.position_index, + chi_values=decision.chi_values, + dose_fraction=decision.dose_fraction, + reason=decision.reason, + ) diff --git a/mx_bec/endpoints.py b/mx_bec/endpoints.py index ee9e607..5f3a1b0 100644 --- a/mx_bec/endpoints.py +++ b/mx_bec/endpoints.py @@ -44,6 +44,18 @@ class StateEndpoints: message_op=MessageOp.SET_PUBLISH, ) + @staticmethod + def sample_done() -> EndpointInfo[type[MXMeasurementSequenceMessage]]: + """The self-driving sequence has finished with the mounted sample. + + ``success`` is True when at least one dataset was usable. + """ + return EndpointInfo( + endpoint=f"{EndpointType.INFO.value}/mx/sequence/sample_done", + message_type=MXMeasurementSequenceMessage, + message_op=MessageOp.SET_PUBLISH, + ) + class ActorEndpoints: """Per-actor configuration, keyed by the actor's `config_key`.""" diff --git a/mx_bec/sample_info.py b/mx_bec/sample_info.py index 9a462ae..43eb21b 100644 --- a/mx_bec/sample_info.py +++ b/mx_bec/sample_info.py @@ -3,7 +3,9 @@ from __future__ import annotations import time from aarelcinfer_client.models import LatestPredictionModel -from pydantic import BaseModel, Field +from pydantic import BaseModel, ConfigDict, Field + +from mx_bec.self_driving import RasterRecord, SelfDrivingRecord class OpticalCenteringResults(BaseModel): @@ -14,8 +16,12 @@ class OpticalCenteringResults(BaseModel): class SampleInfo(BaseModel): - """Information about the currently mounted sample. Gradually filled out as - information from previous stages is obtained""" + """Information about the currently mounted sample. Gradually filled out as information from + previous stages is obtained""" + + model_config = ConfigDict(arbitrary_types_allowed=True) sample_id: int optical_centering_results: OpticalCenteringResults | None = None + raster: RasterRecord | None = None + self_driving: SelfDrivingRecord | None = None diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index 1702f9e..d858c5c 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -6,6 +6,7 @@ from threading import Event, RLock, Thread from typing import TYPE_CHECKING, Callable, Concatenate, ParamSpec, Self, TypeVar from aarecommon.math.coordinate import Coordinate, SmargonCoordinate +from aarecommon.models.raster_grid import CompletedRasterGrid # already imported in aaredaq.py from aarecommon.models.raster_grid import RasterGridRequest from aarecommon.models.rotation_scan import RotationScanRequest from bec_lib.config_values import RedisConfigValue @@ -20,6 +21,15 @@ from mx_bec.messages import ( MXTaskExecutionMessage, MXTaskQueueChangedMessage, ) +from mx_bec.self_driving import ( + CollectionRecord, + GridGeometry, + RasterRecord, + RotationPlan, + SelfDrivingRecord, + SweepRecord, + scan_images, +) if TYPE_CHECKING: from pxii_bec.macros.beamline_planner import StateChangePlanner @@ -130,7 +140,10 @@ class MxTasks: return self._optical_centering_done_update(sample_id, success=True) @task - def run_optical_centering(self, sample_id): + def run_optical_centering(self, sample_id: int): + """warning: Updates the sample id to whatever you enter even if it's not the real one!""" + if self._client.sample_info is None or self._client.sample_info.sample_id != sample_id: + self._client.reset_sample_info(sample_id) self._client.aaredaq.auto_loop_center() return self._optical_centering_done_update(sample_id, success=True) @@ -163,44 +176,6 @@ class MxTasks: MXMeasurementSequenceMessage(sample_id=dbid, success=True), ) - @task - def aaredaq_raster_scan( - self, - n_x: int, - n_y: int, - step_x_mm: float, - step_y_mm: float, - exp_time_s: float, - omega_deg: float = 0.0, - file_prefix: str | None = None, - dtz: float | None = None, - transmission: float | None = None, - smargon_top_left: SmargonCoordinate | None = None, - auto_center: bool = False, - ) -> None: - """Have AareDAQ run an n_x by n_y raster scan from the current Smargon position - (`smargon_top_left` is left unset), optionally auto-centering afterwards.""" - smargon = self._client.devices.smargon - smargon_top_left = smargon_top_left or SmargonCoordinate( - sh_mm=Coordinate(x=smargon.x.get(), y=smargon.y.get(), z=smargon.z.get()), - chi_deg=smargon.chi.get(), - phi_deg=smargon.phi.get(), - ) - logger.info(f"smargon top left supplied to grid scan {smargon_top_left=}") - request = RasterGridRequest( - n_x=n_x, - n_y=n_y, - grid_size_mm=Coordinate(x=step_x_mm, y=step_y_mm), - exp_time_s=exp_time_s, - omega_deg=omega_deg, - file_prefix=file_prefix, - dtz=dtz, - transmission=transmission, - smargon_top_left=smargon_top_left, - ) - result = self._client.aaredaq.raster_scan(request, auto_center=auto_center) - logger.info(f"AareDAQ raster scan done: {len(result.r)} grid(s) collected") - @task def multiple_rasters( self, @@ -217,7 +192,7 @@ class MxTasks: omegas = [float(ang.strip()) for ang in omegas_deg_list.split(",")] smargon = self._client.devices.smargon smargon_top_left = SmargonCoordinate( - sh_mm=Coordinate(x=smargon.x.get(), y=smargon.x.get(), z=smargon.x.get()), + sh_mm=Coordinate(x=smargon.x.get(), y=smargon.y.get(), z=smargon.z.get()), chi_deg=smargon.chi.get(), phi_deg=smargon.phi.get(), ) @@ -234,14 +209,6 @@ class MxTasks: ) logger.info(f"Raster {i + 1} out of {len(omegas)} done.") - @task - def xray_centering(self, dbid: int, strategy: dict): - self.aaredaq_raster_scan(**strategy) - return ( - StateEndpoints.xray_centering_done(), - MXMeasurementSequenceMessage(sample_id=dbid, success=True), - ) - @task def aaredaq_rotation_scan( self, @@ -271,76 +238,171 @@ class MxTasks: result = self._client.aaredaq.rotation_scan(request) logger.info(f"AareDAQ rotation scan done: {len(result.result.images)} images") + def _run_raster( + self, + n_x: int, + n_y: int, + step_x_mm: float, + step_y_mm: float, + exp_time_s: float, + omega_deg: float = 0.0, + file_prefix: str | None = None, + dtz: float | None = None, + transmission: float | None = None, + smargon_top_left: SmargonCoordinate | None = None, + auto_center: bool = False, + ) -> CompletedRasterGrid: + if not smargon_top_left: + # x_offset_mm = n_x * step_x_mm * 0.5 + # y_offset_mm = n_y * step_y_mm * 0.5 + # logger.info( + # f"offsetting smargon x,y by half of grid: {x_offset_mm=} {y_offset_mm=} (grid x to smargon z)" + # ) + smargon = self._client.devices.smargon -# @task -# def run_grid_scan( -# self, -# n_x: int, -# n_y: int, -# step_x_um: float, -# step_y_um: float, -# exp_time_s: float, -# file_prefix: str, -# detector_distance_mm: float, -# transmission: float, -# energy_keV: float, -# beam_center_x_pxl: float, -# beam_center_y_pxl: float, -# beam_size_x_mm: float, -# beam_size_y_mm: float, -# ring_current_mA: float, -# flux_ph_s: float, -# sample_temperature_K: float, -# pgroup: str = "p16371", -# sample_name: str = "unknown_sample", -# ) -> None: -# """Collect an n_x by n_y grid scan at the current position and omega: configure the -# Aerotech grid scan and check that AareScan accepts it, arm JFJoch, then trigger the -# Aerotech and wait for both to finish.""" -# expected_s = exp_time_s * n_x * n_y + n_y * 0.3 -# if expected_s > MAX_GRID_SCAN_S: -# raise ValueError(f"Grid scan is too long: {expected_s:.0f} s > {MAX_GRID_SCAN_S} s") -# -# aerotech = self._client.devices.aerotech -# config = aerotech.gridscan_config -# for signal, value in ( -# (config.grid_elem_count_x, n_x), -# (config.grid_elem_count_y, n_y), -# (config.grid_elem_size_x_um, step_x_um), -# (config.grid_elem_size_y_um, step_y_um), -# (config.time_per_element_sec, exp_time_s), -# ): -# signal.set(value).wait() -# if not config.valid.get(): -# raise ValueError(f"AareScan rejected the grid scan parameters: {config.message.get()}") -# -# jfjoch = self._client.jfjoch -# jfjoch.measure_raster( -# RasterScan( -# n_x=n_x, -# n_y=n_y, -# step_x_mm=step_x_um / 1000.0, -# step_y_mm=step_y_um / 1000.0, -# omega_deg=aerotech.u.get(), -# exp_time_s=exp_time_s, -# detector_distance_mm=detector_distance_mm, -# transmission=transmission, -# file_prefix=file_prefix, -# pgroup=pgroup, -# sample_name=sample_name, -# energy_keV=energy_keV, -# beam_center_pxl=(beam_center_x_pxl, beam_center_y_pxl), -# beam_size_mm=(beam_size_x_mm, beam_size_y_mm), -# ring_current_mA=ring_current_mA, -# flux_ph_s=flux_ph_s, -# sample_temperature_K=sample_temperature_K, -# ) -# ) -# jfjoch.wait_till_running(timeout_s=60) -# logger.info(f"Starting {n_x}x{n_y} grid scan, {exp_time_s} s per element") -# aerotech.trigger().wait() -# result = jfjoch.wait_till_done(timeout_s=60) -# logger.info(f"Grid scan finished: {result.file_prefix} with {len(result.images)} images") + smargon_top_left = SmargonCoordinate( + sh_mm=Coordinate( + x=smargon.x.get(), + y=smargon.y.get(), # + y_offset_mm, + z=smargon.z.get(), # + x_offset_mm, + ), + chi_deg=smargon.chi.get(), + phi_deg=smargon.phi.get(), + ) + logger.info(f"Smargon top left: {smargon_top_left}") + request = RasterGridRequest( + n_x=n_x, + n_y=n_y, + grid_size_mm=Coordinate(x=step_x_mm, y=step_y_mm), + exp_time_s=exp_time_s, + omega_deg=omega_deg, + file_prefix=file_prefix, + dtz=dtz, + transmission=transmission, + smargon_top_left=smargon_top_left, + ) + result = self._client.aaredaq.raster_scan(request, auto_center=auto_center) + logger.info(f"Raster scan finished with {len(scan_images(result))} images") + return result + + @task + def aaredaq_raster_scan( + self, + n_x: int, + n_y: int, + step_x_mm: float, + step_y_mm: float, + exp_time_s: float, + omega_deg: float = 0.0, + file_prefix: str | None = None, + dtz: float | None = None, + transmission: float | None = None, + smargon_top_left: SmargonCoordinate | None = None, + auto_center: bool = False, + ) -> None: + self._run_raster( + n_x, + n_y, + step_x_mm, + step_y_mm, + exp_time_s, + omega_deg, + file_prefix, + dtz, + transmission, + smargon_top_left, + auto_center, + ) + + @task + def xray_centering(self, dbid: int, strategy: dict) -> MxSequenceUpdate: + result = self._run_raster(**strategy) + info = self._client.sample_info + if info is None or info.sample_id != dbid: + self._client.reset_sample_info(dbid) + info = self._client.sample_info + info.raster = RasterRecord( + strategy=dict(strategy), + geometry=GridGeometry( + n_x=strategy["n_x"], + n_y=strategy["n_y"], + step_x_mm=strategy["step_x_mm"], + step_y_mm=strategy["step_y_mm"], + omega_deg=strategy.get("omega_deg", 0.0), + snake=True, # jfjoch.dataset_settings uses GridScan(snake=True) + ), + images=scan_images(result), + ) + return ( + StateEndpoints.xray_centering_done(), + MXMeasurementSequenceMessage(sample_id=dbid, success=True), + ) + + # c) New: moves relative to the raster start, and the rotation collection itself. + + def _self_driving_record(self) -> SelfDrivingRecord: + info = self._client.sample_info + assert info is not None, "No sample loaded" + if info.self_driving is None: + info.self_driving = SelfDrivingRecord() + return info.self_driving + + def _move_to_grid_offset(self, offset_x_mm: float, offset_y_mm: float) -> None: + """Move to a point given relative to the raster start, in the raster plane. + + Rotates omega back to the raster angle first, so the lab-frame nudge is in the plane the + grid was measured in. CHECK on the beamline: sign and axis mapping of grid x/y to + nudge_in_lab_frame x/y. + """ + record = self._self_driving_record() + info = self._client.sample_info + omega = info.raster.geometry.omega_deg if info and info.raster else 0.0 + dx = offset_x_mm - record.current_offset_mm[0] + dy = offset_y_mm - record.current_offset_mm[1] + if abs(dx) < 1e-4 and abs(dy) < 1e-4: + return + self._client.devices.aerotech.u.set(omega).wait() + self._client.devices.smargon.nudge_in_lab_frame(dx, dy, omega_deg=omega) + record.current_offset_mm = (offset_x_mm, offset_y_mm) + + @task + def move_to_grid_offset(self, dbid: int, offset_x_mm: float, offset_y_mm: float) -> None: + self._move_to_grid_offset(offset_x_mm, offset_y_mm) + + @task + def collect_dataset(self, dbid: int, plan: dict) -> MxSequenceUpdate: + """Rotation data at a planned grid spot, one sweep per chi value.""" + p = RotationPlan.model_validate(plan) + self._move_to_grid_offset(p.offset_x_mm, p.offset_y_mm) + smargon = self._client.devices.smargon + record = CollectionRecord(plan=p) + try: + for chi in p.chi_values(): + smargon.chi.set(chi).wait() + request = RotationScanRequest( + exp_time_s=p.exp_time_s, + incr_omega_deg=p.incr_omega_deg, + steps=p.steps, + start_omega_deg=p.start_omega_deg, + file_prefix=f"{p.file_prefix}_chi{chi:g}", + dtz=p.dtz, + transmission=p.transmission, + ) + result = self._client.aaredaq.rotation_scan(request) + record.sweeps.append( + SweepRecord( + chi_deg=chi, + images=scan_images(result), + bravais=getattr(result.result, "rotation_bravais", None), + ) + ) + finally: + smargon.chi.set(0.0).wait() + self._self_driving_record().collections.append(record) + return ( + StateEndpoints.rotation_done(), + MXMeasurementSequenceMessage(sample_id=dbid, success=True), + ) class MxTaskQueue: -- 2.54.1 From 78fe7ae11a89f6914b70756f4904c6b13da1d266 Mon Sep 17 00:00:00 2001 From: David Perl Date: Wed, 11 Nov 2026 14:08:13 +0100 Subject: [PATCH 26/46] add smargon math --- mx_bec/math.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 mx_bec/math.py diff --git a/mx_bec/math.py b/mx_bec/math.py new file mode 100644 index 0000000..5aefe43 --- /dev/null +++ b/mx_bec/math.py @@ -0,0 +1,37 @@ +import numpy as np +from aarecommon.math.coordinate import Coordinate + + +def smargon_nudge( + phi_deg: float, chi_deg: float, omega_deg: float, nudge_vector: Coordinate +) -> Coordinate: + """Translate a relative movement of the smargon from lab frame to smargon frame. + Add the result of this to the smargon's current position to get the new position.""" + phi = np.radians(np.around(phi_deg, decimals=1)) + chi = np.radians(np.around(chi_deg, decimals=1)) + omega = np.radians(np.around(omega_deg, decimals=1)) + + offset = Coordinate() + co = np.cos(omega) + so = np.sin(omega) + cp = np.cos(phi) + sp = np.sin(phi) + cc = np.cos(chi) + sc = np.sin(chi) + + offset.x = ( + -nudge_vector.z * co * sp + - nudge_vector.y * so * sp + + nudge_vector.x * cp * sc + - nudge_vector.y * co * cc * cp + + nudge_vector.z * so * cc * cp + ) + offset.y = ( + -nudge_vector.z * co * cp + - nudge_vector.y * so * cp + - nudge_vector.x * sc * sp + + nudge_vector.y * co * cc * sp + - nudge_vector.z * so * cc * sp + ) + offset.z = -nudge_vector.x * cc - nudge_vector.y * co * sc + nudge_vector.z * so * sc + return offset -- 2.54.1 From 49b699434e3d5b613282f3c835950fcf699f0f79 Mon Sep 17 00:00:00 2001 From: x10sa Date: Wed, 11 Nov 2026 14:52:56 +0100 Subject: [PATCH 27/46] apply smargon nudge math to gridscan --- mx_bec/self_driving.py | 638 +++++++++++++++++++++++++++++++++++++++++ mx_bec/tasks.py | 26 +- 2 files changed, 653 insertions(+), 11 deletions(-) create mode 100644 mx_bec/self_driving.py diff --git a/mx_bec/self_driving.py b/mx_bec/self_driving.py new file mode 100644 index 0000000..405c261 --- /dev/null +++ b/mx_bec/self_driving.py @@ -0,0 +1,638 @@ +"""Decision logic for the self-driving MX sequence. + + grid scan -> analyse_grid -> plan_rotation -> collect_dataset -> assess_collection + -> decide_followup -> (re-raster | new position | chi sweep | finish) + +Everything here is pure: pydantic models and functions, no BEC, Redis or device access. The +actors in ``mx_bec.actors.self_driving`` call these functions, and the same functions can be +replayed offline against archived Jungfraujoch results to tune thresholds. + +Per-image inputs are duck-typed against ``jfjoch_client.models.ScanResultImagesInner`` +(``number``, ``nx``, ``ny``, ``angle``, ``spots``, ``spots_indexed``, ``ice``, ``res``, +``latt_count``, ``spindle_blind``), so plain objects or the jfjoch models both work. +""" + +from __future__ import annotations + +import math +import statistics +from collections.abc import Iterable, Sequence +from enum import Enum +from typing import Any + +from aarecommon.models.raster_grid import CompletedRasterGridElem +from bec_lib.logger import bec_logger +from pydantic import BaseModel, ConfigDict, Field + +HC_KEV_A = 12.398419843320026 # keV * Angstrom + + +logger = bec_logger.logger + + +# -------------------------------------------------------------------------------------------- +# Configuration +# -------------------------------------------------------------------------------------------- + + +class BeamState(BaseModel): + """Beam at the sample. ``flux_ph_s`` is at transmission 1.""" + + energy_keV: float = Field(12.4, gt=0) + flux_ph_s: float | None = Field(None, gt=0, description="Must be set; no dose plan without it") + beam_size_um: tuple[float, float] = (25.0, 25.0) + + @property + def wavelength_A(self) -> float: + return HC_KEV_A / self.energy_keV + + +class StrategyConfig(BaseModel): + """Every threshold the actors use. Defaults are starting points for the replay study.""" + + # grid analysis + min_spots_hit: int = Field(10, description="Spots per image for a cell to count as a hit") + ice_threshold: float = Field(1.5, description="jfjoch 'ice' ratio above which a cell is icy") + ice_penalty: float = 0.5 + multi_lattice_penalty: float = 0.5 + reference_res_A: float = Field(2.0, description="Resolution at which the score factor is 1") + max_positions: int = 4 + min_spot_separation_mm: float = Field(0.04, description="Beam size plus dose halo") + min_position_score_fraction: float = Field(0.3, description="Relative to the best cell") + + # rotation plan + beam: BeamState = BeamState() + dose_MGy_per_A: float = Field(5.0, description="Dose budget = this x target resolution") + photons_per_um2_per_Gy_12p4keV: float = Field( + 2000.0, + description="Rule-of-thumb fluence per Gy at 12.4 keV, scaled by E^2; replace with " + "RADDOSE-3D when the crystal model is available", + ) + total_rotation_deg: float = 360.0 + oscillation_deg: float = 0.1 + exp_time_s: float = 0.005 + min_transmission: float = 0.001 + resolution_margin: float = Field(0.9, description="Aim this factor beyond the grid estimate") + default_res_A: float = 2.5 + best_res_limit_A: float = 0.8 + detector_radius_mm: float = Field(150.0, description="Beam centre to nearest detector edge") + min_distance_mm: float = 100.0 + max_distance_mm: float = 1000.0 + + # anomalous: low-dose multi-chi from the start + anomalous: bool = False + anomalous_chi_deg: tuple[float, ...] = (0.0, 15.0, 30.0) + + # assessment + n_wedges: int = 10 + lost_ratio: float = Field(0.3, description="Wedge spots below this x previous max = lost") + damage_res_increase: float = Field(0.15, description="Relative d_min loss first->last wedge") + min_indexed_spots: int = 10 + min_indexed_fraction: float = 0.5 + spindle_blind_threshold: float = Field(0.5, description="jfjoch: >= 0.5 engage recovery") + treat_unassessed_blind_as_blind: bool = Field( + True, description="jfjoch: an absent spindle_blind must be treated as above threshold" + ) + low_symmetry_bravais: frozenset[str] = frozenset({"aP", "mP", "mC"}) + + # follow-up policy + max_followups: int = 3 + max_recentres: int = 1 + max_chi_sweeps: int = 1 + chi_offset_deg: float = 30.0 + damage_dose_fraction: float = 0.5 + same_position_dose_fraction: float = Field( + 0.3, description="Extra dose allowed when a chi sweep must reuse a burnt position" + ) + + +# -------------------------------------------------------------------------------------------- +# Grid analysis +# -------------------------------------------------------------------------------------------- + + +class GridGeometry(BaseModel): + """Raster layout. Cell (0, 0) sits at the raster start position (``smargon_top_left``).""" + + n_x: int = Field(ge=1) + n_y: int = Field(ge=1) + step_x_mm: float + step_y_mm: float + omega_deg: float = 0.0 + snake: bool = True + + def offset_mm(self, ix: int, iy: int) -> tuple[float, float]: + return ix * self.step_x_mm, iy * self.step_y_mm + + +class Cell(BaseModel): + model_config = ConfigDict(frozen=True) + + ix: int + iy: int + spots: int + spots_indexed: int | None = None + res_A: float | None = None + ice: float | None = None + lattices: int | None = None + score: float = 0.0 + + +class CrystalRegion(BaseModel): + cells: list[Cell] + best: Cell + extent_x_mm: float + extent_y_mm: float + median_res_A: float | None + max_lattices: int + + +class GridAnalysis(BaseModel): + geometry: GridGeometry + n_images: int + n_hits: int + regions: list[CrystalRegion] + positions: list[Cell] = Field(description="Ranked collection spots, best first") + + def position_offset_mm(self, index: int) -> tuple[float, float]: + cell = self.positions[index] + return self.geometry.offset_mm(cell.ix, cell.iy) + + def position_res_A(self, index: int) -> float | None: + cell = self.positions[index] + if cell.res_A: + return cell.res_A + for region in self.regions: + if cell in region.cells: + return region.median_res_A + return None + + +def _cell_index(img: Any, geom: GridGeometry) -> tuple[int, int]: + nx, ny = getattr(img, "nx", None), getattr(img, "ny", None) + if nx is not None and ny is not None: + return int(nx), int(ny) + row, col = divmod(int(img.number), geom.n_x) + if geom.snake and row % 2: + col = geom.n_x - 1 - col + return col, row + + +def cell_score(img: Any, cfg: StrategyConfig) -> float: + """Indexed spots weighted for resolution, penalised for ice and extra lattices.""" + spots = img.spots or 0 + indexed = getattr(img, "spots_indexed", None) + base = float(spots) if indexed is None else indexed + 0.25 * max(spots - indexed, 0) + ice = getattr(img, "ice", None) + if ice is not None and ice > cfg.ice_threshold: + base *= cfg.ice_penalty + lattices = getattr(img, "latt_count", None) + if lattices is not None and lattices > 1: + base *= cfg.multi_lattice_penalty + res = getattr(img, "res", None) + if res: + base *= min(2.0, max(0.5, cfg.reference_res_A / res)) + return base + + +def _regions(cells: dict[tuple[int, int], Cell]) -> list[list[Cell]]: + """8-connected components of hit cells.""" + seen: set[tuple[int, int]] = set() + out: list[list[Cell]] = [] + for start in cells: + if start in seen: + continue + stack, comp = [start], [] + seen.add(start) + while stack: + ix, iy = stack.pop() + comp.append(cells[(ix, iy)]) + for dx in (-1, 0, 1): + for dy in (-1, 0, 1): + nb = (ix + dx, iy + dy) + if nb in cells and nb not in seen: + seen.add(nb) + stack.append(nb) + out.append(comp) + return out + + +def _distance_mm(a: Cell, b: Cell, geom: GridGeometry) -> float: + return math.hypot((a.ix - b.ix) * geom.step_x_mm, (a.iy - b.iy) * geom.step_y_mm) + + +def pick_positions( + regions: Sequence[CrystalRegion], geom: GridGeometry, cfg: StrategyConfig +) -> list[Cell]: + """Best cell of each crystal first, then further spots spaced beyond the dose halo.""" + if not regions: + return [] + top = max(r.best.score for r in regions) + floor = cfg.min_position_score_fraction * top + ordered = [r.best for r in regions] + sorted( + (c for r in regions for c in r.cells), key=lambda c: c.score, reverse=True + ) + chosen: list[Cell] = [] + for cell in ordered: + if len(chosen) >= cfg.max_positions: + break + if cell.score < floor or cell in chosen: + continue + if all(_distance_mm(cell, c, geom) >= cfg.min_spot_separation_mm for c in chosen): + chosen.append(cell) + return chosen + + +def analyse_grid( + results: Iterable[CompletedRasterGridElem], geom: GridGeometry, cfg: StrategyConfig +) -> GridAnalysis: + results = list(results) + logger.info(f"analyze_grid got {len(results)} results.") + images = results[0].result.images + hits: dict[tuple[int, int], Cell] = {} + for img in images: + if (img.spots or 0) < cfg.min_spots_hit: + continue + ix, iy = _cell_index(img, geom) + hits[(ix, iy)] = Cell( + ix=ix, + iy=iy, + spots=img.spots, + spots_indexed=getattr(img, "spots_indexed", None), + res_A=getattr(img, "res", None), + ice=getattr(img, "ice", None), + lattices=getattr(img, "latt_count", None), + score=cell_score(img, cfg), + ) + regions = [] + for comp in _regions(hits): + xs, ys = [c.ix for c in comp], [c.iy for c in comp] + res = [c.res_A for c in comp if c.res_A] + regions.append( + CrystalRegion( + cells=sorted(comp, key=lambda c: c.score, reverse=True), + best=max(comp, key=lambda c: (c.score, -(c.res_A or 99.0))), + extent_x_mm=(max(xs) - min(xs) + 1) * abs(geom.step_x_mm), + extent_y_mm=(max(ys) - min(ys) + 1) * abs(geom.step_y_mm), + median_res_A=statistics.median(res) if res else None, + max_lattices=max((c.lattices or 1) for c in comp), + ) + ) + regions.sort(key=lambda r: r.best.score, reverse=True) + return GridAnalysis( + geometry=geom, + n_images=len(images), + n_hits=len(hits), + regions=regions, + positions=pick_positions(regions, geom, cfg), + ) + + +# -------------------------------------------------------------------------------------------- +# Rotation planning +# -------------------------------------------------------------------------------------------- + + +class RotationPlan(BaseModel): + """Flat parameters for the ``collect_dataset`` task. + + ``MXTaskExecutionMessage`` only carries scalars, so chi values travel as a comma string, + like ``multiple_rasters`` does for omegas. + """ + + position_index: int + offset_x_mm: float + offset_y_mm: float + chi_deg_list: str = "0" + start_omega_deg: float = 0.0 + incr_omega_deg: float + steps: int + exp_time_s: float + transmission: float + dtz: float + file_prefix: str + dose_MGy: float + target_res_A: float + reason: str = "" + + def chi_values(self) -> list[float]: + return [float(v) for v in self.chi_deg_list.split(",") if v.strip()] + + +def detector_distance_mm(res_A: float, beam: BeamState, cfg: StrategyConfig) -> float: + """Distance that puts ``res_A`` at the nearest detector edge.""" + s = beam.wavelength_A / (2.0 * res_A) + if s >= 1.0: + return cfg.min_distance_mm + two_theta = 2.0 * math.asin(s) + distance = cfg.detector_radius_mm / math.tan(two_theta) + return min(cfg.max_distance_mm, max(cfg.min_distance_mm, distance)) + + +def dose_rate_MGy_s(beam: BeamState, cfg: StrategyConfig, transmission: float = 1.0) -> float: + if beam.flux_ph_s is None: + raise ValueError("BeamState.flux_ph_s is not set; refusing to plan a dose") + area_um2 = beam.beam_size_um[0] * beam.beam_size_um[1] + photons_per_um2_per_Gy = cfg.photons_per_um2_per_Gy_12p4keV * (beam.energy_keV / 12.4) ** 2 + return beam.flux_ph_s * transmission / area_um2 / photons_per_um2_per_Gy / 1e6 + + +def plan_rotation( + analysis: GridAnalysis, + position_index: int, + cfg: StrategyConfig, + *, + file_prefix: str, + chi_values: Sequence[float] = (0.0,), + dose_fraction: float = 1.0, + reason: str = "", +) -> RotationPlan: + """Rotation at one grid position under the ``dose_MGy_per_A`` rule. + + The budget (``dose_fraction`` of the full one) is shared over all chi sweeps, which gives the + low-dose multi-chi strategy for anomalous data. + """ + beam = cfg.beam + res_est = analysis.position_res_A(position_index) or cfg.default_res_A + target = max(cfg.best_res_limit_A, res_est * cfg.resolution_margin) + steps = max(1, round(cfg.total_rotation_deg / cfg.oscillation_deg)) + sweep_time_s = steps * cfg.exp_time_s + n_sweeps = max(1, len(chi_values)) + dose_per_sweep = cfg.dose_MGy_per_A * target * dose_fraction / n_sweeps + full_rate = dose_rate_MGy_s(beam, cfg) + transmission = dose_per_sweep / (full_rate * sweep_time_s) + transmission = min(1.0, max(cfg.min_transmission, transmission)) + x, y = analysis.position_offset_mm(position_index) + return RotationPlan( + position_index=position_index, + offset_x_mm=x, + offset_y_mm=y, + chi_deg_list=",".join(f"{c:g}" for c in chi_values), + incr_omega_deg=cfg.oscillation_deg, + steps=steps, + exp_time_s=cfg.exp_time_s, + transmission=round(transmission, 5), + dtz=round(detector_distance_mm(target, beam, cfg), 1), + file_prefix=f"{file_prefix}_p{position_index}", + dose_MGy=round(full_rate * transmission * sweep_time_s * n_sweeps, 3), + target_res_A=round(target, 2), + reason=reason, + ) + + +# -------------------------------------------------------------------------------------------- +# Records kept on SampleInfo between actors +# -------------------------------------------------------------------------------------------- + + +class RasterRecord(BaseModel): + model_config = ConfigDict(arbitrary_types_allowed=True) + + strategy: dict[str, Any] = Field(description="Kwargs of the raster, for a repeat") + geometry: GridGeometry + images: list[Any] + + +class SweepRecord(BaseModel): + model_config = ConfigDict(arbitrary_types_allowed=True) + + chi_deg: float + images: list[Any] + bravais: str | None = None + + +class Issue(str, Enum): + LOST_DIFFRACTION = "lost_diffraction" + RADIATION_DAMAGE = "radiation_damage" + BLIND_REGION = "blind_region" + LOW_SYMMETRY = "low_symmetry" + WEAK = "weak" + + +class Assessment(BaseModel): + issues: list[Issue] = [] + n_images: int = 0 + indexed_fraction: float = 0.0 + wedge_spots: list[float] = [] + wedge_res_A: list[float | None] = [] + onset_angle_deg: float | None = None + median_spindle_blind: float | None = None + bravais: str | None = None + + @property + def usable(self) -> bool: + return not {Issue.LOST_DIFFRACTION, Issue.WEAK} & set(self.issues) + + +class CollectionRecord(BaseModel): + plan: RotationPlan + sweeps: list[SweepRecord] = [] + assessment: Assessment | None = None + + +class SelfDrivingRecord(BaseModel): + """Per-sample history; reset by ``reset_sample_info`` on mount.""" + + analysis: GridAnalysis | None = None + raster_strategy: dict[str, Any] | None = None + current_offset_mm: tuple[float, float] = (0.0, 0.0) + positions_used: list[int] = [] + chi_sweeps_done: int = 0 + recentres: int = 0 + followups: int = 0 + collections: list[CollectionRecord] = [] + + def next_free_position(self) -> int | None: + if self.analysis is None: + return None + for i in range(len(self.analysis.positions)): + if i not in self.positions_used: + return i + return None + + +def scan_images(completed: Any) -> list[Any]: + """Per-image Jungfraujoch results from an aarecommon ``Completed*`` model. + + ``CompletedRotationScan`` carries a jfjoch ``ScanResult`` under ``.result``. Check which field + ``CompletedRasterGrid`` uses (``tasks.py`` logs ``len(result.r)``) and keep that path first. + """ + for path in (("result", "images"), ("r",), ("images",)): + obj = completed + for attr in path: + obj = getattr(obj, attr, None) + if obj is None: + break + if obj is not None: + return list(obj) + raise ValueError(f"No per-image results found on {type(completed).__name__}") + + +# -------------------------------------------------------------------------------------------- +# Assessment and follow-up decision +# -------------------------------------------------------------------------------------------- + + +def _wedges(items: Sequence[Any], n: int) -> list[Sequence[Any]]: + n = max(1, min(n, len(items))) + size = len(items) / n + return [items[round(i * size) : round((i + 1) * size)] for i in range(n)] + + +def assess_sweep(images: Sequence[Any], bravais: str | None, cfg: StrategyConfig) -> Assessment: + imgs = sorted( + images, + key=lambda im: (im.angle if getattr(im, "angle", None) is not None else 0.0, im.number), + ) + if not imgs: + return Assessment(issues=[Issue.LOST_DIFFRACTION, Issue.WEAK], bravais=bravais) + issues: list[Issue] = [] + wedges = _wedges(imgs, cfg.n_wedges) + wedge_spots = [float(statistics.median([(im.spots or 0) for im in w])) for w in wedges] + wedge_res: list[float | None] = [] + for w in wedges: + res = [im.res for im in w if getattr(im, "res", None)] + wedge_res.append(statistics.median(res) if res else None) + + # Lost diffraction: a drop below lost_ratio of the running max that never recovers + onset = None + running_max = wedge_spots[0] + for i in range(1, len(wedge_spots)): + if running_max >= cfg.min_spots_hit and all( + s < cfg.lost_ratio * running_max for s in wedge_spots[i:] + ): + onset = getattr(wedges[i][0], "angle", None) + issues.append(Issue.LOST_DIFFRACTION) + break + running_max = max(running_max, wedge_spots[i]) + + # Radiation damage: d_min of the last wedge worse than the first (same orientation for 360°) + first, last = wedge_res[0], wedge_res[-1] + if ( + Issue.LOST_DIFFRACTION not in issues + and first + and last + and (last - first) / first > cfg.damage_res_increase + ): + issues.append(Issue.RADIATION_DAMAGE) + + indexed = sum(1 for im in imgs if (im.spots_indexed or 0) >= cfg.min_indexed_spots) + indexed_fraction = indexed / len(imgs) + if indexed_fraction < cfg.min_indexed_fraction: + issues.append(Issue.WEAK) + + blind_values = [getattr(im, "spindle_blind", None) for im in imgs] + median_blind = None + if any(v is not None for v in blind_values): + median_blind = statistics.median([1.0 if v is None else v for v in blind_values]) + if median_blind >= cfg.spindle_blind_threshold: + issues.append(Issue.BLIND_REGION) + elif cfg.treat_unassessed_blind_as_blind: + issues.append(Issue.BLIND_REGION) + + if bravais and bravais in cfg.low_symmetry_bravais: + issues.append(Issue.LOW_SYMMETRY) + + return Assessment( + issues=issues, + n_images=len(imgs), + indexed_fraction=round(indexed_fraction, 3), + wedge_spots=wedge_spots, + wedge_res_A=wedge_res, + onset_angle_deg=onset, + median_spindle_blind=median_blind, + bravais=bravais, + ) + + +def assess_collection(record: CollectionRecord, cfg: StrategyConfig) -> Assessment: + """Assess each chi sweep separately, then merge. + + Blind region is a per-sweep property, so a multi-chi collection only keeps it if every sweep + reports it. Every other issue is kept if any sweep reports it. + """ + parts = [assess_sweep(s.images, s.bravais, cfg) for s in record.sweeps] + if not parts: + return Assessment(issues=[Issue.LOST_DIFFRACTION, Issue.WEAK]) + merged = parts[0].model_copy(deep=True) + issues: list[Issue] = [] + for issue in Issue: + flags = [issue in p.issues for p in parts] + keep = all(flags) if issue is Issue.BLIND_REGION else any(flags) + if keep: + issues.append(issue) + merged.issues = issues + merged.n_images = sum(p.n_images for p in parts) + merged.bravais = next((p.bravais for p in parts if p.bravais), None) + return merged + + +class Action(str, Enum): + FINISH = "finish" + RECENTRE = "recentre" + NEW_POSITION = "new_position" + CHI_SWEEP = "chi_sweep" + + +class Decision(BaseModel): + action: Action + reason: str + position_index: int | None = None + chi_values: list[float] = [0.0] + dose_fraction: float = 1.0 + + +def decide_followup( + assessment: Assessment, record: SelfDrivingRecord, cfg: StrategyConfig +) -> Decision: + """Priority: budget -> lost diffraction -> damage -> completeness (chi) -> weak -> finish.""" + issues = set(assessment.issues) + if record.followups >= cfg.max_followups: + return Decision(action=Action.FINISH, reason="follow-up budget spent") + nxt = record.next_free_position() + + if Issue.LOST_DIFFRACTION in issues: + if record.recentres < cfg.max_recentres: + return Decision( + action=Action.RECENTRE, + reason=f"diffraction lost at omega={assessment.onset_angle_deg}; re-raster", + ) + if nxt is not None: + return Decision( + action=Action.NEW_POSITION, position_index=nxt, reason="lost again; next spot" + ) + return Decision(action=Action.FINISH, reason="diffraction lost, no spot left") + + if Issue.RADIATION_DAMAGE in issues: + if nxt is not None: + return Decision( + action=Action.NEW_POSITION, + position_index=nxt, + dose_fraction=cfg.damage_dose_fraction, + reason="radiation damage; fresh spot at reduced dose", + ) + return Decision(action=Action.FINISH, reason="radiation damage, no fresh spot left") + + needs_chi = issues & {Issue.BLIND_REGION, Issue.LOW_SYMMETRY} + if needs_chi and record.chi_sweeps_done < cfg.max_chi_sweeps: + why = "+".join(sorted(i.value for i in needs_chi)) + if nxt is not None: + return Decision( + action=Action.CHI_SWEEP, + position_index=nxt, + chi_values=[cfg.chi_offset_deg], + reason=f"{why}; chi sweep on a fresh spot", + ) + last = record.positions_used[-1] if record.positions_used else 0 + return Decision( + action=Action.CHI_SWEEP, + position_index=last, + chi_values=[cfg.chi_offset_deg], + dose_fraction=cfg.same_position_dose_fraction, + reason=f"{why}; chi sweep on the same spot, extra dose", + ) + + if Issue.WEAK in issues and nxt is not None: + return Decision(action=Action.NEW_POSITION, position_index=nxt, reason="weak; next spot") + + return Decision(action=Action.FINISH, reason="no issue left to act on") diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index d858c5c..5758eab 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -16,6 +16,7 @@ from bec_lib.logger import bec_logger from mx_bec.devices.smargopolo_smargon import Smargon from mx_bec.endpoints import StateEndpoints, TaskEndpoints from mx_bec.jfjoch import RasterScan +from mx_bec.math import smargon_nudge from mx_bec.messages import ( MXMeasurementSequenceMessage, MXTaskExecutionMessage, @@ -253,19 +254,22 @@ class MxTasks: auto_center: bool = False, ) -> CompletedRasterGrid: if not smargon_top_left: - # x_offset_mm = n_x * step_x_mm * 0.5 - # y_offset_mm = n_y * step_y_mm * 0.5 - # logger.info( - # f"offsetting smargon x,y by half of grid: {x_offset_mm=} {y_offset_mm=} (grid x to smargon z)" - # ) + x_offset_mm = n_x * step_x_mm * 0.5 + y_offset_mm = n_y * step_y_mm * 0.5 + logger.info( + f"offsetting smargon x,y by half of grid: {x_offset_mm=} {y_offset_mm=} (grid x to smargon z)" + ) smargon = self._client.devices.smargon - + aerotech = self._client.devices.aerotech + adjustment = smargon_nudge( + smargon.phi_deg.get(), + smargon.chi_deg.get(), + aerotech.u.get(), + Coordinate(x=x_offset_mm, y=y_offset_mm, z=0), + ) smargon_top_left = SmargonCoordinate( - sh_mm=Coordinate( - x=smargon.x.get(), - y=smargon.y.get(), # + y_offset_mm, - z=smargon.z.get(), # + x_offset_mm, - ), + sh_mm=Coordinate(x=smargon.x.get(), y=smargon.y.get(), z=smargon.z.get()) + + adjustment, chi_deg=smargon.chi.get(), phi_deg=smargon.phi.get(), ) -- 2.54.1 From 54755032389eeb53c2024873322a5bf64db9e85e Mon Sep 17 00:00:00 2001 From: x10sa Date: Thu, 12 Nov 2026 08:27:46 +0100 Subject: [PATCH 28/46] fix multi grid scan and take args --- mx_bec/actors/mx_automation.py | 141 ++++++++++++++++++++++++++++----- mx_bec/tasks.py | 25 +++--- 2 files changed, 132 insertions(+), 34 deletions(-) diff --git a/mx_bec/actors/mx_automation.py b/mx_bec/actors/mx_automation.py index 4465662..6287897 100644 --- a/mx_bec/actors/mx_automation.py +++ b/mx_bec/actors/mx_automation.py @@ -9,8 +9,10 @@ import secrets from time import sleep from typing import Any, ClassVar +from aarelcinfer_client.models import DetectionModel from bec_lib.endpoints import EndpointInfo from bec_lib.logger import bec_logger +from pxii_bec.macros.calculator import calc_scam_microns from pxii_bec.macros.flux_macros import bpm2flux from mx_bec.actors.core import MXAutomationActor @@ -50,6 +52,28 @@ class OnSampleMountedRunOpticalCentering(MXAutomationActor): ) +def mock_grid_calculation(): + sleep(1) + logger.info("calculating mock grid given no optical results ...") + sleep(1) + n_x = 10 + n_y = 10 + step_x_mm = 0.05 + step_y_mm = 0.05 + strategy = { + "n_x": n_x, + "n_y": n_y, + "step_x_mm": step_x_mm, + "step_y_mm": step_y_mm, + "exp_time_s": 0.05, + "omega_deg": 0.0, + "file_prefix": f"AareBecTestGridScan_{secrets.token_hex(6)}", + "dtz": 250, + "transmission": 0.2, + } + return strategy + + class OnOpticalCenteringDoneRunXrayCentering(MXAutomationActor): """When optical centering finished, run X-ray centering. Runs regardless of success.""" @@ -66,33 +90,110 @@ class OnOpticalCenteringDoneRunXrayCentering(MXAutomationActor): sample_id = client.sample_info.sample_id logger.info(f"{self.name}: running X-ray centering for sample {sample_id}") logger.info( - f"Calculating gridscan strategy given optical centering results of: {client.sample_info.optical_centering_results}" + f"Calculating gridscan strategy given optical centering results available: {client.sample_info.optical_centering_results is not None}" ) - sleep(2) - logger.info("calculating...") - sleep(2) - n_x = 10 - n_y = 10 - step_x_mm = 0.05 - step_y_mm = 0.05 - strategy = { - "n_x": n_x, - "n_y": n_y, - "step_x_mm": step_x_mm, - "step_y_mm": step_y_mm, - "exp_time_s": 0.05, - "omega_deg": 0.0, - "file_prefix": f"AareBecTestGridScan_{secrets.token_hex(6)}", - "dtz": 250, - "transmission": 0.2, - } - logger.info(f"calculated strategy: {strategy}") + if (optical_results := client.sample_info.optical_centering_results) is None or len( + boxes := optical_results.prediction.boxes + ) == 0: + strategy = mock_grid_calculation() + else: + box_data = {box.label: ((box.x1, box.y1), (box.x2, box.y2)) for box in boxes} + logger.info(f"got detection boxes: {box_data}") + box_corners = None + for label_option in ["crystal", "loop_face", "loop_all"]: + if label_option in box_data: + box_corners = box_data[label_option] + if box_corners is None: + strategy = mock_grid_calculation() + else: + step_x_mm = 0.03 + step_y_mm = 0.02 + n_x = int( + calc_scam_microns(abs(box_corners[0][0] - box_corners[1][0])) / 1000 / step_x_mm + ) + n_y = int( + calc_scam_microns(abs(box_corners[0][1] - box_corners[1][1])) / 1000 / step_y_mm + ) + strategy = { + "n_x": n_x, + "n_y": n_y, + "step_x_mm": step_x_mm, + "step_y_mm": step_y_mm, + "exp_time_s": 0.05, + "omega_deg": 0.0, + "file_prefix": f"AareBecTestGridScan_{secrets.token_hex(6)}", + "dtz": 250, + "transmission": 0.2, + } + logger.info(f"calculated strategy: {strategy}") client.add_task_to_queue( MXTaskExecutionMessage(name="xray_centering", args=(sample_id, strategy), kwargs={}) ) +class OnOpticalCenteringDoneRunMultiGrid(MXAutomationActor): + """When optical centering finished, run X-ray centering. Runs regardless of success.""" + + config_key = "multigrid_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) -> None: + assert client.sample_info, "No sample loaded" + sample_id = client.sample_info.sample_id + logger.info(f"{self.name}: running X-ray centering for sample {sample_id}") + logger.info( + f"Calculating gridscan strategy given optical centering results available: {client.sample_info.optical_centering_results is not None}" + ) + if (optical_results := client.sample_info.optical_centering_results) is None or len( + boxes := optical_results.prediction.boxes + ) == 0: + strategy = mock_grid_calculation() + else: + box_data = {box.label: ((box.x1, box.y1), (box.x2, box.y2)) for box in boxes} + logger.info(f"got detection boxes: {box_data}") + box_corners = None + for label_option in ["crystal", "loop_face", "loop_all"]: + if label_option in box_data: + box_corners = box_data[label_option] + if box_corners is None: + strategy = mock_grid_calculation() + else: + step_x_mm = 0.03 + step_y_mm = 0.02 + n_x = int( + calc_scam_microns(abs(box_corners[0][0] - box_corners[1][0]), zoom=400) + / 1000 + / step_x_mm + * 1.5 + ) + n_y = int( + calc_scam_microns(abs(box_corners[0][1] - box_corners[1][1]), zoom=400) + / 1000 + / step_y_mm + * 1.5 + ) + strategy = { + "n_x": n_x, + "n_y": n_y, + "step_x_mm": step_x_mm, + "step_y_mm": step_y_mm, + "exp_time_s": 0.01, + "file_prefix": "AareBecTestGridScan", + "dtz": 200, + } + + logger.info(f"calculated strategy: {strategy}") + client.add_task_to_queue( + MXTaskExecutionMessage(name="multiple_rasters", args=("0,60,120",), kwargs=strategy) + ) + + class SelfDrivingActor(MXAutomationActor): """Shared helpers. Abstract: subclasses set ``config_key`` and implement ``action``.""" diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index 5758eab..4715e84 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -2,6 +2,7 @@ from __future__ import annotations import functools import inspect +from secrets import token_hex from threading import Event, RLock, Thread from typing import TYPE_CHECKING, Callable, Concatenate, ParamSpec, Self, TypeVar @@ -146,6 +147,8 @@ class MxTasks: if self._client.sample_info is None or self._client.sample_info.sample_id != sample_id: self._client.reset_sample_info(sample_id) self._client.aaredaq.auto_loop_center() + self._client.scans.mv(self._client.devices.scam_zoom, 400, relative=False).wait() + self._client.optical_prediction.update_latest() return self._optical_centering_done_update(sample_id, success=True) def _optical_centering_done_update(self, sample_id: int, *, success: bool): @@ -191,22 +194,16 @@ class MxTasks: ) -> None: """Run multiple raster scans at different omega values""" omegas = [float(ang.strip()) for ang in omegas_deg_list.split(",")] - smargon = self._client.devices.smargon - smargon_top_left = SmargonCoordinate( - sh_mm=Coordinate(x=smargon.x.get(), y=smargon.y.get(), z=smargon.z.get()), - chi_deg=smargon.chi.get(), - phi_deg=smargon.phi.get(), - ) for i, omega in enumerate(omegas): - self.aaredaq_raster_scan( + self._run_raster( n_x, n_y, step_x_mm, step_y_mm, exp_time_s, - file_prefix=f"{file_prefix}_{i}_{omega:.2f}deg", + file_prefix=f"{file_prefix}_{i}_{omega:.2f}deg_{token_hex(3)}", dtz=dtz, - smargon_top_left=smargon_top_left, + omega_deg=omega, ) logger.info(f"Raster {i + 1} out of {len(omegas)} done.") @@ -260,16 +257,16 @@ class MxTasks: f"offsetting smargon x,y by half of grid: {x_offset_mm=} {y_offset_mm=} (grid x to smargon z)" ) smargon = self._client.devices.smargon - aerotech = self._client.devices.aerotech + # aerotech = self._client.devices.aerotech adjustment = smargon_nudge( - smargon.phi_deg.get(), - smargon.chi_deg.get(), - aerotech.u.get(), + smargon.phi.get(), + smargon.chi.get(), + omega_deg, Coordinate(x=x_offset_mm, y=y_offset_mm, z=0), ) smargon_top_left = SmargonCoordinate( sh_mm=Coordinate(x=smargon.x.get(), y=smargon.y.get(), z=smargon.z.get()) - + adjustment, + - adjustment, chi_deg=smargon.chi.get(), phi_deg=smargon.phi.get(), ) -- 2.54.1 From 1e2d14c55edaa417e53ff703e93861707a84ef5d Mon Sep 17 00:00:00 2001 From: x10sa Date: Thu, 12 Nov 2026 11:22:12 +0100 Subject: [PATCH 29/46] move stuff to maths, factorise --- mx_bec/actors/mx_automation.py | 107 ++++----------------------------- mx_bec/math.py | 81 +++++++++++++++++++++++++ mx_bec/tasks.py | 2 - 3 files changed, 92 insertions(+), 98 deletions(-) diff --git a/mx_bec/actors/mx_automation.py b/mx_bec/actors/mx_automation.py index 6287897..1257fff 100644 --- a/mx_bec/actors/mx_automation.py +++ b/mx_bec/actors/mx_automation.py @@ -17,6 +17,7 @@ from pxii_bec.macros.flux_macros import bpm2flux from mx_bec.actors.core import MXAutomationActor from mx_bec.endpoints import StateEndpoints +from mx_bec.math import gridscan_calculation, gridscan_strategy_from_optical, mock_grid_calculation from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskExecutionMessage from mx_bec.self_driving import ( Action, @@ -32,6 +33,11 @@ from mx_bec.service import AareBec logger = bec_logger.logger +STEP_X_MM = 0.03 +STEP_Y_MM = 0.02 +MARGIN = 1.3 + + class OnSampleMountedRunOpticalCentering(MXAutomationActor): """When a sample is mounted, run optical centering. Only runs if mounting reported success.""" @@ -52,28 +58,6 @@ class OnSampleMountedRunOpticalCentering(MXAutomationActor): ) -def mock_grid_calculation(): - sleep(1) - logger.info("calculating mock grid given no optical results ...") - sleep(1) - n_x = 10 - n_y = 10 - step_x_mm = 0.05 - step_y_mm = 0.05 - strategy = { - "n_x": n_x, - "n_y": n_y, - "step_x_mm": step_x_mm, - "step_y_mm": step_y_mm, - "exp_time_s": 0.05, - "omega_deg": 0.0, - "file_prefix": f"AareBecTestGridScan_{secrets.token_hex(6)}", - "dtz": 250, - "transmission": 0.2, - } - return strategy - - class OnOpticalCenteringDoneRunXrayCentering(MXAutomationActor): """When optical centering finished, run X-ray centering. Runs regardless of success.""" @@ -88,44 +72,12 @@ class OnOpticalCenteringDoneRunXrayCentering(MXAutomationActor): def action(self, client: AareBec) -> None: assert client.sample_info, "No sample loaded" sample_id = client.sample_info.sample_id - logger.info(f"{self.name}: running X-ray centering for sample {sample_id}") + logger.info(f"{self.name}: running single-grid X-ray centering for sample {sample_id}") logger.info( f"Calculating gridscan strategy given optical centering results available: {client.sample_info.optical_centering_results is not None}" ) - if (optical_results := client.sample_info.optical_centering_results) is None or len( - boxes := optical_results.prediction.boxes - ) == 0: - strategy = mock_grid_calculation() - else: - box_data = {box.label: ((box.x1, box.y1), (box.x2, box.y2)) for box in boxes} - logger.info(f"got detection boxes: {box_data}") - box_corners = None - for label_option in ["crystal", "loop_face", "loop_all"]: - if label_option in box_data: - box_corners = box_data[label_option] - if box_corners is None: - strategy = mock_grid_calculation() - else: - step_x_mm = 0.03 - step_y_mm = 0.02 - n_x = int( - calc_scam_microns(abs(box_corners[0][0] - box_corners[1][0])) / 1000 / step_x_mm - ) - n_y = int( - calc_scam_microns(abs(box_corners[0][1] - box_corners[1][1])) / 1000 / step_y_mm - ) - strategy = { - "n_x": n_x, - "n_y": n_y, - "step_x_mm": step_x_mm, - "step_y_mm": step_y_mm, - "exp_time_s": 0.05, - "omega_deg": 0.0, - "file_prefix": f"AareBecTestGridScan_{secrets.token_hex(6)}", - "dtz": 250, - "transmission": 0.2, - } - + strategy = gridscan_strategy_from_optical(client.sample_info.optical_centering_results) + strategy["omega_deg"] = 0.0 logger.info(f"calculated strategy: {strategy}") client.add_task_to_queue( MXTaskExecutionMessage(name="xray_centering", args=(sample_id, strategy), kwargs={}) @@ -146,48 +98,11 @@ class OnOpticalCenteringDoneRunMultiGrid(MXAutomationActor): def action(self, client: AareBec) -> None: assert client.sample_info, "No sample loaded" sample_id = client.sample_info.sample_id - logger.info(f"{self.name}: running X-ray centering for sample {sample_id}") + logger.info(f"{self.name}: running multi-grid X-ray centering for sample {sample_id}") logger.info( f"Calculating gridscan strategy given optical centering results available: {client.sample_info.optical_centering_results is not None}" ) - if (optical_results := client.sample_info.optical_centering_results) is None or len( - boxes := optical_results.prediction.boxes - ) == 0: - strategy = mock_grid_calculation() - else: - box_data = {box.label: ((box.x1, box.y1), (box.x2, box.y2)) for box in boxes} - logger.info(f"got detection boxes: {box_data}") - box_corners = None - for label_option in ["crystal", "loop_face", "loop_all"]: - if label_option in box_data: - box_corners = box_data[label_option] - if box_corners is None: - strategy = mock_grid_calculation() - else: - step_x_mm = 0.03 - step_y_mm = 0.02 - n_x = int( - calc_scam_microns(abs(box_corners[0][0] - box_corners[1][0]), zoom=400) - / 1000 - / step_x_mm - * 1.5 - ) - n_y = int( - calc_scam_microns(abs(box_corners[0][1] - box_corners[1][1]), zoom=400) - / 1000 - / step_y_mm - * 1.5 - ) - strategy = { - "n_x": n_x, - "n_y": n_y, - "step_x_mm": step_x_mm, - "step_y_mm": step_y_mm, - "exp_time_s": 0.01, - "file_prefix": "AareBecTestGridScan", - "dtz": 200, - } - + strategy = gridscan_strategy_from_optical(client.sample_info.optical_centering_results) logger.info(f"calculated strategy: {strategy}") client.add_task_to_queue( MXTaskExecutionMessage(name="multiple_rasters", args=("0,60,120",), kwargs=strategy) diff --git a/mx_bec/math.py b/mx_bec/math.py index 5aefe43..bd0baf5 100644 --- a/mx_bec/math.py +++ b/mx_bec/math.py @@ -1,5 +1,18 @@ +import secrets + import numpy as np from aarecommon.math.coordinate import Coordinate +from bec_lib.logger import bec_logger +from pxii_bec.macros.calculator import calc_scam_microns + +from mx_bec.sample_info import OpticalCenteringResults + +logger = bec_logger.logger + + +STEP_X_MM = 0.03 +STEP_Y_MM = 0.02 +MARGIN = 1.3 def smargon_nudge( @@ -35,3 +48,71 @@ def smargon_nudge( ) offset.z = -nudge_vector.x * cc - nudge_vector.y * co * sc + nudge_vector.z * so * sc return offset + + +def mock_grid_calculation(): + logger.info("calculating mock grid given no optical results ...") + n_x = 10 + n_y = 10 + step_x_mm = 0.05 + step_y_mm = 0.05 + strategy = { + "n_x": n_x, + "n_y": n_y, + "step_x_mm": step_x_mm, + "step_y_mm": step_y_mm, + "exp_time_s": 0.05, + "omega_deg": 0.0, + "file_prefix": f"AareBecTestGridScan_{secrets.token_hex(6)}", + "dtz": 250, + "transmission": 0.2, + } + return strategy + + +def gridscan_strategy_from_optical(optical_results: OpticalCenteringResults | None): + if optical_results is None or len(boxes := optical_results.prediction.boxes) == 0: + return mock_grid_calculation() + else: + box_data = {box.label: ((box.x1, box.y1), (box.x2, box.y2)) for box in boxes} + logger.info(f"got detection boxes: {box_data}") + box_corners = None + for label_option in ["crystal", "loop_face", "loop_all"]: + if label_option in box_data: + box_corners = box_data[label_option] + if box_corners is None: + return mock_grid_calculation() + else: + file_prefix = f"AareBecTestGridScan_{secrets.token_hex(6)}" + return gridscan_calculation( + box_corners[0], box_corners[1], STEP_X_MM, STEP_Y_MM, MARGIN, file_prefix + ) + + +def gridscan_calculation( + x1_y1: tuple[float, float], + x2_y2: tuple[float, float], + size_x: float, + size_y: float, + margin: float, + file_prefix: str, +): + """calculate a gridscan from box coordinates and params. needs omega added later.""" + box_x_pixels = abs(x1_y1[0] - x1_y1[0]) + box_y_pixels = abs(x2_y2[1] - x2_y2[1]) + logger.info(f"{box_x_pixels=}, {box_y_pixels=}") + box_x_microns = calc_scam_microns(box_x_pixels, zoom=400) + box_y_microns = calc_scam_microns(box_y_pixels, zoom=400) + logger.info(f"{box_x_microns=}, {box_y_microns=}") + logger.info(f"adding margin to detection boxes of {margin}x") + n_x = int(box_x_microns / 1000 / size_x * margin) + n_y = int(box_x_microns / 1000 / size_y * margin) + return { + "n_x": n_x, + "n_y": n_y, + "step_x_mm": size_x, + "step_y_mm": size_y, + "exp_time_s": 0.01, + "file_prefix": file_prefix, + "dtz": 200, + } diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index 4715e84..8e3470b 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -339,8 +339,6 @@ class MxTasks: MXMeasurementSequenceMessage(sample_id=dbid, success=True), ) - # c) New: moves relative to the raster start, and the rotation collection itself. - def _self_driving_record(self) -> SelfDrivingRecord: info = self._client.sample_info assert info is not None, "No sample loaded" -- 2.54.1 From 48bf914a00bf7301786fef525fc9f040c5bcd3c6 Mon Sep 17 00:00:00 2001 From: David Perl Date: Thu, 12 Nov 2026 12:05:36 +0100 Subject: [PATCH 30/46] add refresh to spreadsheet --- .../aare_bec/sample_spreadsheet_display.py | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py b/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py index 76c3797..9948697 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py @@ -5,7 +5,8 @@ from typing import Any from bec_lib.logger import bec_logger from bec_lib.messages import RawMessage from bec_widgets.utils.bec_connector import ConnectionConfig -from bec_widgets.utils.bec_widget import BECWidget +from bec_widgets.utils.bec_widget import BECWidget, SafeSlot +from pyqtgraph.Qt.QtWidgets import QPushButton from qtpy.QtWidgets import QLabel, QScrollArea, QVBoxLayout, QWidget logger = bec_logger.logger @@ -59,6 +60,17 @@ class SampleSpreadsheetDisplay(BECWidget, QWidget): self._data: dict[str, Any] self._layout = QVBoxLayout(self) self._layout.addWidget(QLabel(" Sample spreadhseet data: ")) + self._refresh_button = QPushButton("refresh") + self._layout.addWidget(self._refresh_button) + self._display_label = QLabel("") + self._layout_area = QScrollArea() + self._layout.addWidget(self._layout_area) + self._layout_area.setWidget(self._display_label) + self.refresh() + self._refresh_button.clicked.connect(self.refresh) + + @SafeSlot() + def refresh(self): dict_data = [{}] try: data = self.client.connector._managed_connection.get("x10sa:sample_spreadsheet") @@ -67,8 +79,6 @@ class SampleSpreadsheetDisplay(BECWidget, QWidget): else: dict_data = [{"text": str(data)}] except Exception as e: - self._layout.addWidget(QLabel(f"Failed to load spreadsheet data: {e}")) + self._display_label.setText(f"Failed to load spreadsheet data: {e}") return - self._layout_area = QScrollArea() - self._layout.addWidget(self._layout_area) - self._layout_area.setWidget(QLabel(dicts_to_html_table(dict_data))) + self._display_label.setText(dicts_to_html_table(dict_data)) -- 2.54.1 From de57281d82fcd3751e83f97e2a599522ed650bf8 Mon Sep 17 00:00:00 2001 From: x10sa Date: Thu, 12 Nov 2026 14:19:32 +0100 Subject: [PATCH 31/46] use gridscan params from config --- mx_bec/actors/mx_automation.py | 18 +++++++++++++-- mx_bec/math.py | 41 +++++++++++++++++++++------------- 2 files changed, 42 insertions(+), 17 deletions(-) diff --git a/mx_bec/actors/mx_automation.py b/mx_bec/actors/mx_automation.py index 1257fff..f46daf8 100644 --- a/mx_bec/actors/mx_automation.py +++ b/mx_bec/actors/mx_automation.py @@ -76,7 +76,14 @@ class OnOpticalCenteringDoneRunXrayCentering(MXAutomationActor): logger.info( f"Calculating gridscan strategy given optical centering results available: {client.sample_info.optical_centering_results is not None}" ) - strategy = gridscan_strategy_from_optical(client.sample_info.optical_centering_results) + strategy = gridscan_strategy_from_optical( + client.sample_info.optical_centering_results, + client.aare_config.auto_grid_params.box_size_x_um, + client.aare_config.auto_grid_params.box_size_y_um, + client.aare_config.auto_grid_params.margin_multiplier, + client.aare_config.auto_grid_params.exp_time_s, + client.aare_config.auto_grid_params.detector_distance_mm, + ) strategy["omega_deg"] = 0.0 logger.info(f"calculated strategy: {strategy}") client.add_task_to_queue( @@ -102,7 +109,14 @@ class OnOpticalCenteringDoneRunMultiGrid(MXAutomationActor): logger.info( f"Calculating gridscan strategy given optical centering results available: {client.sample_info.optical_centering_results is not None}" ) - strategy = gridscan_strategy_from_optical(client.sample_info.optical_centering_results) + strategy = gridscan_strategy_from_optical( + client.sample_info.optical_centering_results, + client.aare_config.auto_grid_params.box_size_x_um, + client.aare_config.auto_grid_params.box_size_y_um, + client.aare_config.auto_grid_params.margin_multiplier, + client.aare_config.auto_grid_params.exp_time_s, + client.aare_config.auto_grid_params.detector_distance_mm, + ) logger.info(f"calculated strategy: {strategy}") client.add_task_to_queue( MXTaskExecutionMessage(name="multiple_rasters", args=("0,60,120",), kwargs=strategy) diff --git a/mx_bec/math.py b/mx_bec/math.py index bd0baf5..d066862 100644 --- a/mx_bec/math.py +++ b/mx_bec/math.py @@ -10,11 +10,6 @@ from mx_bec.sample_info import OpticalCenteringResults logger = bec_logger.logger -STEP_X_MM = 0.03 -STEP_Y_MM = 0.02 -MARGIN = 1.3 - - def smargon_nudge( phi_deg: float, chi_deg: float, omega_deg: float, nudge_vector: Coordinate ) -> Coordinate: @@ -70,7 +65,14 @@ def mock_grid_calculation(): return strategy -def gridscan_strategy_from_optical(optical_results: OpticalCenteringResults | None): +def gridscan_strategy_from_optical( + optical_results: OpticalCenteringResults | None, + step_x_um: float, + step_y_um: float, + margin: float, + exp_time_s: float, + dtz_mm: float, +): if optical_results is None or len(boxes := optical_results.prediction.boxes) == 0: return mock_grid_calculation() else: @@ -85,17 +87,26 @@ def gridscan_strategy_from_optical(optical_results: OpticalCenteringResults | No else: file_prefix = f"AareBecTestGridScan_{secrets.token_hex(6)}" return gridscan_calculation( - box_corners[0], box_corners[1], STEP_X_MM, STEP_Y_MM, MARGIN, file_prefix + box_corners[0], + box_corners[1], + step_x_um / 1000, + step_y_um / 1000, + margin, + file_prefix, + exp_time_s, + dtz_mm, ) def gridscan_calculation( x1_y1: tuple[float, float], x2_y2: tuple[float, float], - size_x: float, - size_y: float, + size_x_mm: float, + size_y_mm: float, margin: float, file_prefix: str, + exp_time_s: float, + dtz_mm: float, ): """calculate a gridscan from box coordinates and params. needs omega added later.""" box_x_pixels = abs(x1_y1[0] - x1_y1[0]) @@ -105,14 +116,14 @@ def gridscan_calculation( box_y_microns = calc_scam_microns(box_y_pixels, zoom=400) logger.info(f"{box_x_microns=}, {box_y_microns=}") logger.info(f"adding margin to detection boxes of {margin}x") - n_x = int(box_x_microns / 1000 / size_x * margin) - n_y = int(box_x_microns / 1000 / size_y * margin) + n_x = int(box_x_microns / 1000 / size_x_mm * margin) + n_y = int(box_x_microns / 1000 / size_y_mm * margin) return { "n_x": n_x, "n_y": n_y, - "step_x_mm": size_x, - "step_y_mm": size_y, - "exp_time_s": 0.01, + "step_x_mm": size_x_mm, + "step_y_mm": size_y_mm, + "exp_time_s": exp_time_s, "file_prefix": file_prefix, - "dtz": 200, + "dtz": dtz_mm, } -- 2.54.1 From 0ac00bd60d7b9cbc95dcd06edeca291c7f78996c Mon Sep 17 00:00:00 2001 From: x10sa Date: Thu, 12 Nov 2026 15:42:55 +0100 Subject: [PATCH 32/46] continue --- mx_bec/actors/mx_automation.py | 15 ++++---- .../aare_bec/sample_spreadsheet_display.py | 7 +++- .../widgets/aare_bec/task_panel.py | 36 ++++++++++++------- mx_bec/math.py | 6 ++-- mx_bec/messages.py | 14 ++++++-- mx_bec/tasks.py | 7 ++-- 6 files changed, 58 insertions(+), 27 deletions(-) diff --git a/mx_bec/actors/mx_automation.py b/mx_bec/actors/mx_automation.py index f46daf8..161dc1d 100644 --- a/mx_bec/actors/mx_automation.py +++ b/mx_bec/actors/mx_automation.py @@ -109,17 +109,20 @@ class OnOpticalCenteringDoneRunMultiGrid(MXAutomationActor): logger.info( f"Calculating gridscan strategy given optical centering results available: {client.sample_info.optical_centering_results is not None}" ) + params = client.aare_config.auto_grid_params strategy = gridscan_strategy_from_optical( client.sample_info.optical_centering_results, - client.aare_config.auto_grid_params.box_size_x_um, - client.aare_config.auto_grid_params.box_size_y_um, - client.aare_config.auto_grid_params.margin_multiplier, - client.aare_config.auto_grid_params.exp_time_s, - client.aare_config.auto_grid_params.detector_distance_mm, + params.box_size_x_um, + params.box_size_y_um, + params.margin_multiplier, + params.exp_time_s, + params.detector_distance_mm, ) logger.info(f"calculated strategy: {strategy}") client.add_task_to_queue( - MXTaskExecutionMessage(name="multiple_rasters", args=("0,60,120",), kwargs=strategy) + MXTaskExecutionMessage( + name="multiple_rasters", args=(params.omegas_for_multi_grid_degs,), kwargs=strategy + ) ) diff --git a/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py b/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py index 9948697..ca1b2ca 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py @@ -62,10 +62,13 @@ class SampleSpreadsheetDisplay(BECWidget, QWidget): self._layout.addWidget(QLabel(" Sample spreadhseet data: ")) self._refresh_button = QPushButton("refresh") self._layout.addWidget(self._refresh_button) - self._display_label = QLabel("") + self._layout_area = QScrollArea() self._layout.addWidget(self._layout_area) + + self._display_label = QLabel("") self._layout_area.setWidget(self._display_label) + self.refresh() self._refresh_button.clicked.connect(self.refresh) @@ -82,3 +85,5 @@ class SampleSpreadsheetDisplay(BECWidget, QWidget): self._display_label.setText(f"Failed to load spreadsheet data: {e}") return self._display_label.setText(dicts_to_html_table(dict_data)) + self._display_label.adjustSize() + logger.info(f"Successfully updated sample spreadsheet e.g. {dict_data[0]}...") diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py index 1cbf997..dbb187f 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -26,7 +26,7 @@ from mx_bec.tasks import MxTasks logger = bec_logger.logger # Hard-coded forms: task name -> [(argument, default value)]; the widget type follows the default. -TASK_FORMS: dict[str, list[tuple[str, int | float | str]]] = { +TASK_FORMS: dict[str, list[tuple[str, int | float | str | list[float]]]] = { "run_optical_centering": [("sample_id", 0)], # "run_grid_scan": [ # ("n_x", 4), @@ -61,13 +61,13 @@ TASK_FORMS: dict[str, list[tuple[str, int | float | str]]] = { ("file_prefix", "AareBecTestGridScan"), ], "multiple_rasters": [ - ("omegas_deg_list", "0, 30, 60, 90"), - ("n_x", 4), - ("n_y", 3), - ("step_x_mm", 0.05), - ("step_y_mm", 0.05), - ("exp_time_s", 0.1), - ("dtz", 250), + ("omegas_deg_list", [0, 45, 60, 90, 120, 135]), + ("n_x", 10), + ("n_y", 10), + ("step_x_mm", 0.02), + ("step_y_mm", 0.015), + ("exp_time_s", 0.01), + ("dtz", 200), ("file_prefix", "AareBecTestGridScan"), ], "aaredaq_rotation_scan": [ @@ -131,7 +131,7 @@ class MxTaskPanel(BECWidget, QWidget): return box def _task_box( - self, parent: QWidget, task: str, fields: list[tuple[str, int | float | str]] + self, parent: QWidget, task: str, fields: list[tuple[str, int | float | str | list[float]]] ) -> QGroupBox: box = QGroupBox(task, parent=parent) form = QFormLayout() @@ -152,10 +152,12 @@ class MxTaskPanel(BECWidget, QWidget): @staticmethod def _input( - parent: QWidget, default: int | float | str + parent: QWidget, default: int | float | str | list[float] ) -> QSpinBox | QDoubleSpinBox | QLineEdit: if isinstance(default, bool) or isinstance(default, str): return QLineEdit(str(default), parent=parent) + if isinstance(default, list): + return QLineEdit(str(default).strip("[]"), parent=parent) if isinstance(default, int): box = QSpinBox(parent=parent) box.setRange(0, 1_000_000) @@ -167,9 +169,19 @@ class MxTaskPanel(BECWidget, QWidget): box.setValue(default) return box - def _values(self, task: str) -> dict[str, int | float | str]: + def _parse_text(self, task: str, name: str, text: str): + inputs = {k: v for k, v in TASK_FORMS[task]} + if isinstance(inputs.get(name), list): + return [float(ang.strip()) for ang in text.split(",")] + return text + + def _values(self, task: str) -> dict[str, int | float | str | list[float]]: return { - name: widget.text() if isinstance(widget, QLineEdit) else widget.value() + name: ( + self._parse_text(task, name, widget.text()) + if isinstance(widget, QLineEdit) + else widget.value() + ) for name, widget in self._inputs[task].items() } diff --git a/mx_bec/math.py b/mx_bec/math.py index d066862..54166e2 100644 --- a/mx_bec/math.py +++ b/mx_bec/math.py @@ -82,6 +82,8 @@ def gridscan_strategy_from_optical( for label_option in ["crystal", "loop_face", "loop_all"]: if label_option in box_data: box_corners = box_data[label_option] + logger.info(f"using best available box: {label_option}") + break if box_corners is None: return mock_grid_calculation() else: @@ -109,8 +111,8 @@ def gridscan_calculation( dtz_mm: float, ): """calculate a gridscan from box coordinates and params. needs omega added later.""" - box_x_pixels = abs(x1_y1[0] - x1_y1[0]) - box_y_pixels = abs(x2_y2[1] - x2_y2[1]) + box_x_pixels = abs(x1_y1[0] - x2_y2[0]) + box_y_pixels = abs(x1_y1[1] - x2_y2[1]) logger.info(f"{box_x_pixels=}, {box_y_pixels=}") box_x_microns = calc_scam_microns(box_x_pixels, zoom=400) box_y_microns = calc_scam_microns(box_y_pixels, zoom=400) diff --git a/mx_bec/messages.py b/mx_bec/messages.py index 084583a..40b93a9 100644 --- a/mx_bec/messages.py +++ b/mx_bec/messages.py @@ -21,8 +21,18 @@ class MXTaskExecutionMessage(BECMessage): msg_type: ClassVar[str] = "mx_task_execution_message" name: str - args: tuple[int | bool | str | float | None | dict[str, int | bool | str | float | None], ...] - kwargs: dict[str, int | bool | str | float | None] + args: tuple[ + int + | bool + | str + | float + | None + | dict[str, int | bool | str | float | None] + | list[int] + | list[float], + ..., + ] + kwargs: dict[str, int | bool | str | float | None | list[int] | list[float]] class MXTaskQueueChangedMessage(BECMessage): diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index 8e3470b..b81735f 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -183,7 +183,7 @@ class MxTasks: @task def multiple_rasters( self, - omegas_deg_list: str, + omegas_deg_list: list[float], n_x: int, n_y: int, step_x_mm: float, @@ -193,8 +193,7 @@ class MxTasks: dtz: float | None = None, ) -> None: """Run multiple raster scans at different omega values""" - omegas = [float(ang.strip()) for ang in omegas_deg_list.split(",")] - for i, omega in enumerate(omegas): + for i, omega in enumerate(omegas_deg_list): self._run_raster( n_x, n_y, @@ -205,7 +204,7 @@ class MxTasks: dtz=dtz, omega_deg=omega, ) - logger.info(f"Raster {i + 1} out of {len(omegas)} done.") + logger.info(f"Raster {i + 1} out of {len(omegas_deg_list)} done.") @task def aaredaq_rotation_scan( -- 2.54.1 From 0870ac898aca72e6f812f98178aff7c0369cdd32 Mon Sep 17 00:00:00 2001 From: x10sa Date: Fri, 13 Nov 2026 09:28:01 +0100 Subject: [PATCH 33/46] ... --- mx_bec/math.py | 43 +++++++++++++++++++++---------------------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/mx_bec/math.py b/mx_bec/math.py index 54166e2..44bdb1b 100644 --- a/mx_bec/math.py +++ b/mx_bec/math.py @@ -75,29 +75,28 @@ def gridscan_strategy_from_optical( ): if optical_results is None or len(boxes := optical_results.prediction.boxes) == 0: return mock_grid_calculation() + box_data = {box.label: ((box.x1, box.y1), (box.x2, box.y2)) for box in boxes} + logger.info(f"got detection boxes: {box_data}") + box_corners = None + for label_option in ["crystal", "loop_face", "loop_all"]: + if label_option in box_data: + box_corners = box_data[label_option] + logger.info(f"using best available box: {label_option}") + break + if box_corners is None: + return mock_grid_calculation() else: - box_data = {box.label: ((box.x1, box.y1), (box.x2, box.y2)) for box in boxes} - logger.info(f"got detection boxes: {box_data}") - box_corners = None - for label_option in ["crystal", "loop_face", "loop_all"]: - if label_option in box_data: - box_corners = box_data[label_option] - logger.info(f"using best available box: {label_option}") - break - if box_corners is None: - return mock_grid_calculation() - else: - file_prefix = f"AareBecTestGridScan_{secrets.token_hex(6)}" - return gridscan_calculation( - box_corners[0], - box_corners[1], - step_x_um / 1000, - step_y_um / 1000, - margin, - file_prefix, - exp_time_s, - dtz_mm, - ) + file_prefix = f"AareBecTestGridScan_{secrets.token_hex(6)}" + return gridscan_calculation( + box_corners[0], + box_corners[1], + step_x_um / 1000, + step_y_um / 1000, + margin, + file_prefix, + exp_time_s, + dtz_mm, + ) def gridscan_calculation( -- 2.54.1 From b9709b2fd4d125b26acc5a9d41e4dae2e968383f Mon Sep 17 00:00:00 2001 From: David Perl Date: Fri, 13 Nov 2026 09:34:31 +0100 Subject: [PATCH 34/46] add clear task queue button --- mx_bec/bec_widgets/widgets/aare_bec/task_queue.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py b/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py index 7212b87..15f9436 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py @@ -7,7 +7,7 @@ from bec_widgets.utils.bec_widget import BECWidget from bec_widgets.utils.error_popups import SafeSlot from bec_widgets.widgets.utility.toggle.toggle import ToggleSwitch from qtpy.QtCore import Signal -from qtpy.QtWidgets import QHBoxLayout, QLabel, QListWidget, QVBoxLayout, QWidget +from qtpy.QtWidgets import QHBoxLayout, QLabel, QListWidget, QPushButton, QVBoxLayout, QWidget from mx_bec.endpoints import TaskEndpoints @@ -25,7 +25,7 @@ class MxTaskQueueWidget(BECWidget, QWidget): PLUGIN = True ICON_NAME = "pending_actions" - USER_ACCESS = ["refresh"] + USER_ACCESS = ["refresh", "clear_queue"] # Redis callbacks arrive on the connector thread; re-emit so the toggle is updated on the GUI # thread. @@ -51,12 +51,15 @@ class MxTaskQueueWidget(BECWidget, QWidget): self._toggle = ToggleSwitch(parent=self, checked=not self._paused.value) self._toggle.stateChanged.connect(self._set_running) + self._delete_button = QPushButton("Clear queue") + self._delete_button.clicked.connect(self.clear_queue) self._list = QListWidget(parent=self) layout = QVBoxLayout(self) header = QHBoxLayout() header.addWidget(QLabel("Task queue running", parent=self)) header.addWidget(self._toggle) + header.addWidget(self._delete_button) header.addStretch() layout.addLayout(header) layout.addWidget(QLabel("Queued tasks", parent=self)) @@ -75,7 +78,12 @@ class MxTaskQueueWidget(BECWidget, QWidget): args = ", ".join( [repr(a) for a in msg.args] + [f"{k}={v!r}" for k, v in msg.kwargs.items()] ) - self._list.addItem(f"{msg.name}({args})") + self._list.addItem(f"{msg.name}({args})") @ SafeSlot() + + @SafeSlot() + def clear_queue(self): + """Delete the queue contents""" + self.client.connector.delete(TaskEndpoints.task_execution()) @SafeSlot(dict, dict) def _on_queue_changed(self, _content: dict, _metadata: dict): -- 2.54.1 From 34693dff7c6e3636a21dcca99f0c4c4936ef7164 Mon Sep 17 00:00:00 2001 From: David Perl Date: Fri, 13 Nov 2026 10:13:08 +0100 Subject: [PATCH 35/46] add sample queue --- mx_bec/actors/mx_automation.py | 29 ++++- .../widgets/aare_bec/sample_queue.py | 109 ++++++++++++++++++ .../widgets/aare_bec/task_panel.py | 4 +- .../widgets/aare_bec/task_queue.py | 14 ++- mx_bec/endpoints.py | 40 ++++++- mx_bec/messages.py | 16 ++- mx_bec/service.py | 10 +- mx_bec/tasks.py | 22 ++-- tests/unit/test_service.py | 10 +- tests/unit/test_tasks.py | 26 ++--- 10 files changed, 231 insertions(+), 49 deletions(-) create mode 100644 mx_bec/bec_widgets/widgets/aare_bec/sample_queue.py diff --git a/mx_bec/actors/mx_automation.py b/mx_bec/actors/mx_automation.py index 161dc1d..38831f5 100644 --- a/mx_bec/actors/mx_automation.py +++ b/mx_bec/actors/mx_automation.py @@ -16,9 +16,13 @@ from pxii_bec.macros.calculator import calc_scam_microns from pxii_bec.macros.flux_macros import bpm2flux from mx_bec.actors.core import MXAutomationActor -from mx_bec.endpoints import StateEndpoints +from mx_bec.endpoints import QueueEndpoints, StateEndpoints from mx_bec.math import gridscan_calculation, gridscan_strategy_from_optical, mock_grid_calculation -from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskExecutionMessage +from mx_bec.messages import ( + MXMeasurementSequenceMessage, + MXSampleExecutionMessage, + MXTaskExecutionMessage, +) from mx_bec.self_driving import ( Action, SelfDrivingRecord, @@ -126,6 +130,27 @@ class OnOpticalCenteringDoneRunMultiGrid(MXAutomationActor): ) +class OnSampleDoneLoadNext(MXAutomationActor): + config_key = "on_sample_done_load_next" + + def default_monitor_endpoints(self) -> set[EndpointInfo[type[MXMeasurementSequenceMessage]]]: + return {StateEndpoints.sample_done()} + + def condition(self, client: AareBec) -> bool: + return self.last_message is not None + + def action(self, client: AareBec) -> None: + queue_len = client.connector.llen(QueueEndpoints.sample_execution()) + if not queue_len: + return # TODO: run some kind of cleanup e.g. unmount, gripper park and dry + next: MXSampleExecutionMessage = client.connector.blocking_list_pop( + QueueEndpoints.sample_execution() + ) + client.add_task_to_queue( + MXTaskExecutionMessage(name="aaredaq_mount_sample", args=(next.db_id,), kwargs={}) + ) + + class SelfDrivingActor(MXAutomationActor): """Shared helpers. Abstract: subclasses set ``config_key`` and implement ``action``.""" diff --git a/mx_bec/bec_widgets/widgets/aare_bec/sample_queue.py b/mx_bec/bec_widgets/widgets/aare_bec/sample_queue.py new file mode 100644 index 0000000..34371e3 --- /dev/null +++ b/mx_bec/bec_widgets/widgets/aare_bec/sample_queue.py @@ -0,0 +1,109 @@ +from __future__ import annotations + +from bec_lib.config_values import RedisConfigValue +from bec_lib.logger import bec_logger +from bec_widgets.utils.bec_connector import ConnectionConfig +from bec_widgets.utils.bec_widget import BECWidget +from bec_widgets.utils.error_popups import SafeSlot +from bec_widgets.widgets.utility.toggle.toggle import ToggleSwitch +from qtpy.QtCore import Signal +from qtpy.QtWidgets import QHBoxLayout, QLabel, QListWidget, QPushButton, QVBoxLayout, QWidget + +from mx_bec.endpoints import QueueEndpoints +from mx_bec.messages import MXSampleExecutionMessage + +logger = bec_logger.logger + + +class SampleQueueWidget(BECWidget, QWidget): + """ + Widget to pause/resume the MX sample queue and show the tasks waiting in it. + + The toggle is bound to the `sample_queue_paused` flag in Redis (checked = running), the list + is re-read from the task execution queue whenever the service announces a change on + `task_queue_changed`. + """ + + PLUGIN = True + ICON_NAME = "pending_actions" + USER_ACCESS = ["refresh", "clear_queue"] + + # Redis callbacks arrive on the connector thread; re-emit so the toggle is updated on the GUI + # thread. + _paused_changed = Signal(bool) + + def __init__( + self, + parent: QWidget | None = None, + client=None, + config: ConnectionConfig | None = None, + gui_id: str | None = None, + **kwargs, + ) -> None: + super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs) + self._paused: RedisConfigValue[bool] = RedisConfigValue( + connector=self.client.connector, + endpoint=QueueEndpoints.sample_queue_paused(), + wait_for_writes=False, + ) + # RedisConfigValue keeps a weak ref to the subscriber, which must be a bound method + self._paused.subscribe(self._emit_paused_changed) + self._paused_changed.connect(self._on_paused_changed) + + self._toggle = ToggleSwitch(parent=self, checked=not self._paused.value) + self._toggle.stateChanged.connect(self._set_running) + self._delete_button = QPushButton("Clear queue") + self._delete_button.clicked.connect(self.clear_queue) + self._list = QListWidget(parent=self) + + layout = QVBoxLayout(self) + header = QHBoxLayout() + header.addWidget(QLabel("Sample queue running", parent=self)) + header.addWidget(self._toggle) + header.addWidget(self._delete_button) + header.addStretch() + layout.addLayout(header) + layout.addWidget(QLabel("Queued sample", parent=self)) + layout.addWidget(self._list) + + # released automatically by BECWidget.cleanup() (disconnect_owner) + self.bec_dispatcher.connect_slot( + self._on_queue_changed, QueueEndpoints.sample_queue_changed() + ) + self.refresh() + + @SafeSlot() + def refresh(self): + """Reload the queued samples from Redis.""" + tasks = self.client.connector.lrange(QueueEndpoints.sample_execution(), 0, -1) + self._list.clear() + for msg in tasks: + msg: MXSampleExecutionMessage + self._list.addItem(f"{msg.sample_name} (db_id: {msg.db_id})") + + @SafeSlot() + def clear_queue(self): + """Delete the queue contents""" + self.client.connector.delete(QueueEndpoints.sample_execution()) + + @SafeSlot(dict, dict) + def _on_queue_changed(self, _content: dict, _metadata: dict): + self.refresh() + + def _emit_paused_changed(self, paused: bool): + self._paused_changed.emit(paused) + + @SafeSlot(bool) + def _set_running(self, running: bool): + self._paused.value = not running + + @SafeSlot(bool) + def _on_paused_changed(self, paused: bool): + # Don't write the value we just received straight back to Redis. + self._toggle.blockSignals(True) + self._toggle.setChecked(not paused) + self._toggle.blockSignals(False) + + def cleanup(self): + self._paused.unregister_all() + super().cleanup() diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py index dbb187f..0bd2788 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -19,7 +19,7 @@ from qtpy.QtWidgets import ( QWidget, ) -from mx_bec.endpoints import TaskEndpoints +from mx_bec.endpoints import QueueEndpoints from mx_bec.messages import MXTaskExecutionMessage from mx_bec.tasks import MxTasks @@ -194,4 +194,4 @@ class MxTaskPanel(BECWidget, QWidget): """Submit a task request to the AareBec service.""" msg = MXTaskExecutionMessage(name=name, args=args, kwargs=kwargs) logger.info(f"Requesting task: {msg}") - self.client.connector.xadd(TaskEndpoints.task_request(), {"data": msg}) + self.client.connector.xadd(QueueEndpoints.task_request(), {"data": msg}) diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py b/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py index 15f9436..80e2f71 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py @@ -9,7 +9,7 @@ from bec_widgets.widgets.utility.toggle.toggle import ToggleSwitch from qtpy.QtCore import Signal from qtpy.QtWidgets import QHBoxLayout, QLabel, QListWidget, QPushButton, QVBoxLayout, QWidget -from mx_bec.endpoints import TaskEndpoints +from mx_bec.endpoints import QueueEndpoints logger = bec_logger.logger @@ -42,7 +42,7 @@ class MxTaskQueueWidget(BECWidget, QWidget): super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs) self._paused: RedisConfigValue[bool] = RedisConfigValue( connector=self.client.connector, - endpoint=TaskEndpoints.task_queue_paused(), + endpoint=QueueEndpoints.task_queue_paused(), wait_for_writes=False, ) # RedisConfigValue keeps a weak ref to the subscriber, which must be a bound method @@ -66,24 +66,26 @@ class MxTaskQueueWidget(BECWidget, QWidget): layout.addWidget(self._list) # released automatically by BECWidget.cleanup() (disconnect_owner) - self.bec_dispatcher.connect_slot(self._on_queue_changed, TaskEndpoints.task_queue_changed()) + self.bec_dispatcher.connect_slot( + self._on_queue_changed, QueueEndpoints.task_queue_changed() + ) self.refresh() @SafeSlot() def refresh(self): """Reload the queued tasks from Redis.""" - tasks = self.client.connector.lrange(TaskEndpoints.task_execution(), 0, -1) + tasks = self.client.connector.lrange(QueueEndpoints.task_execution(), 0, -1) self._list.clear() for msg in tasks: args = ", ".join( [repr(a) for a in msg.args] + [f"{k}={v!r}" for k, v in msg.kwargs.items()] ) - self._list.addItem(f"{msg.name}({args})") @ SafeSlot() + self._list.addItem(f"{msg.name}({args})") @SafeSlot() def clear_queue(self): """Delete the queue contents""" - self.client.connector.delete(TaskEndpoints.task_execution()) + self.client.connector.delete(QueueEndpoints.task_execution()) @SafeSlot(dict, dict) def _on_queue_changed(self, _content: dict, _metadata: dict): diff --git a/mx_bec/endpoints.py b/mx_bec/endpoints.py index 5f3a1b0..92519e9 100644 --- a/mx_bec/endpoints.py +++ b/mx_bec/endpoints.py @@ -3,8 +3,8 @@ from bec_lib.messages import AvailableResourceMessage, BoolConfigDefaultFalse from mx_bec.messages import ( MXMeasurementSequenceMessage, + MXQueueChangedMessage, MXTaskExecutionMessage, - MXTaskQueueChangedMessage, OpticalPredictionMessage, ) @@ -81,8 +81,8 @@ class ActorEndpoints: ) -class TaskEndpoints: - """Requests for the AareBec service to run one of its `MxTasks`.""" +class QueueEndpoints: + """Endpoints for the sample and task queues.""" @staticmethod def task_request(): @@ -110,7 +110,7 @@ class TaskEndpoints: queue, so that clients know to re-read it.""" return EndpointInfo( endpoint=f"{EndpointType.USER.value}/mx/tasks/queue_changed", - message_type=MXTaskQueueChangedMessage, + message_type=MXQueueChangedMessage, message_op=MessageOp.SEND, ) @@ -124,6 +124,38 @@ class TaskEndpoints: message_op=MessageOp.STREAM, ) + @staticmethod + def sample_request(): + return EndpointInfo( + endpoint=f"{EndpointType.USER.value}/mx/sample_queue/request", + message_type=MXTaskExecutionMessage, + message_op=MessageOp.STREAM, + ) + + @staticmethod + def sample_execution(): + return EndpointInfo( + endpoint=f"{EndpointType.USER.value}/mx/sample_queue/execution", + message_type=MXTaskExecutionMessage, + message_op=MessageOp.LIST, + ) + + @staticmethod + def sample_queue_changed(): + return EndpointInfo( + endpoint=f"{EndpointType.USER.value}/mx/sample_queue/queue_changed", + message_type=MXQueueChangedMessage, + message_op=MessageOp.SEND, + ) + + @staticmethod + def sample_queue_paused(): + return EndpointInfo( + endpoint=f"{EndpointType.USER.value}/mx/sample_queue/queue_paused", + message_type=BoolConfigDefaultFalse, + message_op=MessageOp.STREAM, + ) + class DataAnalysisEndpoints: @staticmethod diff --git a/mx_bec/messages.py b/mx_bec/messages.py index 40b93a9..5b7d202 100644 --- a/mx_bec/messages.py +++ b/mx_bec/messages.py @@ -35,11 +35,21 @@ class MXTaskExecutionMessage(BECMessage): kwargs: dict[str, int | bool | str | float | None | list[int] | list[float]] -class MXTaskQueueChangedMessage(BECMessage): - """Notification that the task execution queue changed; carries no data, subscribers +class MXSampleExecutionMessage(BECMessage): + """An entry in the sample queue""" + + msg_type: ClassVar[str] = "mx_sample_execution_message" + + db_id: int + sample_name: str + # TODO: here add parameters for how to run the sample + + +class MXQueueChangedMessage(BECMessage): + """Notification that a queue has changed; carries no data, subscribers re-read the queue.""" - msg_type: ClassVar[str] = "mx_task_queue_changed_message" + msg_type: ClassVar[str] = "mx_queue_changed_message" class OpticalPredictionMessage(BECMessage): diff --git a/mx_bec/service.py b/mx_bec/service.py index e15323d..c120c65 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -12,7 +12,7 @@ from redis.client import Redis from mx_bec.aaredaq import AareDaq from mx_bec.actor_manager import AareActorManager from mx_bec.constants import AareBecWorkflowState -from mx_bec.endpoints import TaskEndpoints +from mx_bec.endpoints import QueueEndpoints from mx_bec.jfjoch import JFJoch from mx_bec.messages import MXTaskQueueChangedMessage from mx_bec.optical_centering import OpticalPrediction @@ -66,7 +66,7 @@ class AareBec(BECClient): self._start_actor_manager() self.task_queue = MxTaskQueue(self, self.tasks) self.task_queue.start() - self.connector.register(TaskEndpoints.task_request(), cb=self._on_task_request) + self.connector.register(QueueEndpoints.task_request(), cb=self._on_task_request) self.status = messages.BECStatus.RUNNING # HAX self.connector._managed_connection.set("x10sa:sample_spreadsheet", self._spreadsheet) @@ -83,8 +83,8 @@ class AareBec(BECClient): def add_task_to_queue(self, task: MXTaskExecutionMessage): """Add a task to the task queue. The task should be validated or guaranteed possible.""" - self.connector.rpush(TaskEndpoints.task_execution(), task) - self.connector.send(TaskEndpoints.task_queue_changed(), MXTaskQueueChangedMessage()) + self.connector.rpush(QueueEndpoints.task_execution(), task) + self.connector.send(QueueEndpoints.task_queue_changed(), MXTaskQueueChangedMessage()) @property def devices(self): @@ -104,7 +104,7 @@ class AareBec(BECClient): self.actor_manager.shutdown() self.actor_manager = None if self.started: # the connector only exists once the client has been started - self.connector.unregister(TaskEndpoints.task_request(), cb=self._on_task_request) + self.connector.unregister(QueueEndpoints.task_request(), cb=self._on_task_request) if self.task_queue is not None: self.task_queue.shutdown() self.task_queue = None diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index b81735f..9c96625 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -7,15 +7,17 @@ from threading import Event, RLock, Thread from typing import TYPE_CHECKING, Callable, Concatenate, ParamSpec, Self, TypeVar from aarecommon.math.coordinate import Coordinate, SmargonCoordinate -from aarecommon.models.raster_grid import CompletedRasterGrid # already imported in aaredaq.py -from aarecommon.models.raster_grid import RasterGridRequest +from aarecommon.models.raster_grid import ( + CompletedRasterGrid, # already imported in aaredaq.py + RasterGridRequest, +) from aarecommon.models.rotation_scan import RotationScanRequest from bec_lib.config_values import RedisConfigValue from bec_lib.endpoints import EndpointInfo from bec_lib.logger import bec_logger from mx_bec.devices.smargopolo_smargon import Smargon -from mx_bec.endpoints import StateEndpoints, TaskEndpoints +from mx_bec.endpoints import QueueEndpoints, StateEndpoints from mx_bec.jfjoch import RasterScan from mx_bec.math import smargon_nudge from mx_bec.messages import ( @@ -64,7 +66,7 @@ class MxTasks: """Submit a task request to the AareBec service.""" msg = MXTaskExecutionMessage(name=name, args=args, kwargs=kwargs) logger.info(f"Requesting task: {msg}") - self._client.connector.xadd(TaskEndpoints.task_request(), {"data": msg}) + self._client.connector.xadd(QueueEndpoints.task_request(), {"data": msg}) @property def planner(self) -> StateChangePlanner: @@ -90,6 +92,8 @@ class MxTasks: only one task runs at a time, and if it raises, the task queue is paused before the exception propagates, so that queued tasks don't carry on from a failed state.""" + # TODO: task becomes a callable class with methods to request, etc + @functools.wraps(method) def wrapper(self: MxTasks, *args, **kwargs): # pylint: disable=protected-access @@ -406,8 +410,8 @@ class MxTasks: class MxTaskQueue: """Executes requested tasks one at a time, in order, on a background thread. - Tasks are popped from the left of the `TaskEndpoints.task_execution()` list and run on the - given `MxTasks`. The queue can be paused through the `TaskEndpoints.task_queue_paused()` + Tasks are popped from the left of the `QueueEndpoints.task_execution()` list and run on the + given `MxTasks`. The queue can be paused through the `QueueEndpoints.task_queue_paused()` config value (from any client): no new task is popped while paused, but a task which is already running is left to finish. """ @@ -418,7 +422,7 @@ class MxTaskQueue: self._poll_interval_s = poll_interval_s self._stop_event = Event() self._paused: RedisConfigValue[bool] = RedisConfigValue( - connector=client.connector, endpoint=TaskEndpoints.task_queue_paused() + connector=client.connector, endpoint=QueueEndpoints.task_queue_paused() ) self._thread = Thread(target=self._run, name="MxTaskQueue", daemon=True) @@ -451,11 +455,11 @@ class MxTaskQueue: self._stop_event.wait(self._poll_interval_s) continue msg = self._client.connector.blocking_list_pop( - TaskEndpoints.task_execution(), side="LEFT", timeout_s=self._poll_interval_s + QueueEndpoints.task_execution(), side="LEFT", timeout_s=self._poll_interval_s ) if msg is not None: self._client.connector.send( - TaskEndpoints.task_queue_changed(), MXTaskQueueChangedMessage() + QueueEndpoints.task_queue_changed(), MXTaskQueueChangedMessage() ) self.execute(msg) diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py index 1bb3812..b8a0a6e 100644 --- a/tests/unit/test_service.py +++ b/tests/unit/test_service.py @@ -6,7 +6,7 @@ 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, TaskEndpoints +from mx_bec.endpoints import QueueEndpoints, StateEndpoints from mx_bec.messages import ( MXMeasurementSequenceMessage, MXTaskExecutionMessage, @@ -75,7 +75,7 @@ def test_shutdown_stops_actor_manager_and_task_queue(service): def test_start_registers_task_request_callback(started_service): service, *_ = started_service service.connector.register.assert_called_once_with( - TaskEndpoints.task_request(), cb=service._on_task_request + QueueEndpoints.task_request(), cb=service._on_task_request ) @@ -85,7 +85,7 @@ def test_shutdown_unregisters_task_request_callback(service): with patch.object(BECClient, "shutdown"): service.shutdown() service.connector.unregister.assert_called_once_with( - TaskEndpoints.task_request(), cb=service._on_task_request + QueueEndpoints.task_request(), cb=service._on_task_request ) @@ -99,9 +99,9 @@ def test_task_request_for_known_method_is_queued_and_announced(service): service.connector = MagicMock() msg = MXTaskExecutionMessage(name="run_optical_centering", args=(3,), kwargs={}) service._on_task_request({"data": msg}) - service.connector.rpush.assert_called_once_with(TaskEndpoints.task_execution(), msg) + service.connector.rpush.assert_called_once_with(QueueEndpoints.task_execution(), msg) service.connector.send.assert_called_once_with( - TaskEndpoints.task_queue_changed(), MXTaskQueueChangedMessage() + QueueEndpoints.task_queue_changed(), MXTaskQueueChangedMessage() ) diff --git a/tests/unit/test_tasks.py b/tests/unit/test_tasks.py index 1c177fd..b533549 100644 --- a/tests/unit/test_tasks.py +++ b/tests/unit/test_tasks.py @@ -6,7 +6,7 @@ import fakeredis import pytest from bec_lib.redis_connector import RedisConnector -from mx_bec.endpoints import TaskEndpoints +from mx_bec.endpoints import QueueEndpoints from mx_bec.messages import MXTaskExecutionMessage, MXTaskQueueChangedMessage from mx_bec.tasks import MxTaskQueue, MxTasks @@ -54,12 +54,12 @@ def _wait_for(predicate, timeout_s=3.0): def test_queue_runs_tasks_in_order(connector, queue, tasks): for sample_id in (1, 2, 3): connector.rpush( - TaskEndpoints.task_execution(), _request("run_optical_centering", sample_id) + QueueEndpoints.task_execution(), _request("run_optical_centering", sample_id) ) queue.start() _wait_for(lambda: tasks.run_optical_centering.call_count == 3) assert tasks.run_optical_centering.call_args_list == [call(1), call(2), call(3)] - assert connector.llen(TaskEndpoints.task_execution()) == 0 + assert connector.llen(QueueEndpoints.task_execution()) == 0 def test_queue_announces_each_pop(connector, queue): @@ -68,10 +68,10 @@ def test_queue_announces_each_pop(connector, queue): def on_changed(msg): # the connector keeps a weak ref: must be a function, not list.append notifications.append(msg) - connector.register(TaskEndpoints.task_queue_changed(), cb=on_changed) + connector.register(QueueEndpoints.task_queue_changed(), cb=on_changed) for sample_id in (1, 2): connector.rpush( - TaskEndpoints.task_execution(), _request("run_optical_centering", sample_id) + QueueEndpoints.task_execution(), _request("run_optical_centering", sample_id) ) queue.start() _wait_for(lambda: len(notifications) == 2) @@ -80,15 +80,15 @@ def test_queue_announces_each_pop(connector, queue): def test_queue_does_not_pop_while_paused(connector, queue, tasks): queue.pause() - connector.rpush(TaskEndpoints.task_execution(), _request("run_optical_centering", 1)) + connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 1)) queue.start() time.sleep(0.3) tasks.run_optical_centering.assert_not_called() - assert connector.llen(TaskEndpoints.task_execution()) == 1 + assert connector.llen(QueueEndpoints.task_execution()) == 1 queue.resume() _wait_for(lambda: tasks.run_optical_centering.call_count == 1) - assert connector.llen(TaskEndpoints.task_execution()) == 0 + assert connector.llen(QueueEndpoints.task_execution()) == 0 def test_paused_flag_is_shared_through_redis(connector, queue): @@ -107,8 +107,8 @@ def test_paused_flag_is_shared_through_redis(connector, queue): def test_queue_skips_non_task_names(connector, queue, tasks): - connector.rpush(TaskEndpoints.task_execution(), _request("_publish_optical_centering_done", 1)) - connector.rpush(TaskEndpoints.task_execution(), _request("run_optical_centering", 2)) + connector.rpush(QueueEndpoints.task_execution(), _request("_publish_optical_centering_done", 1)) + connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 2)) with patch("mx_bec.tasks.logger") as logger: queue.start() _wait_for(lambda: tasks.run_optical_centering.call_count == 1) @@ -119,8 +119,8 @@ def test_queue_skips_non_task_names(connector, queue, tasks): def test_failed_task_is_logged_and_queue_continues(connector, queue, tasks): tasks.run_optical_centering.side_effect = [RuntimeError("boom"), None] - connector.rpush(TaskEndpoints.task_execution(), _request("run_optical_centering", 1)) - connector.rpush(TaskEndpoints.task_execution(), _request("run_optical_centering", 2)) + connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 1)) + connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 2)) with patch("mx_bec.tasks.logger") as logger: queue.start() _wait_for(lambda: tasks.run_optical_centering.call_count == 2) @@ -136,7 +136,7 @@ def test_shutdown_waits_for_running_task(connector, queue, tasks): release.wait(timeout=3) tasks.run_optical_centering.side_effect = slow_task - connector.rpush(TaskEndpoints.task_execution(), _request("run_optical_centering", 1)) + connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 1)) queue.start() assert started.wait(timeout=3) assert queue._thread.is_alive() -- 2.54.1 From 173a710ffb8c0538846ac3a9d41172ed735296b9 Mon Sep 17 00:00:00 2001 From: x10sa Date: Fri, 13 Nov 2026 13:44:15 +0100 Subject: [PATCH 36/46] ... --- mx_bec/actors/mx_automation.py | 2 + .../bec_widgets/widgets/aare_bec/__init__.py | 13 +++ .../widgets/aare_bec/sample_queue.py | 14 ++- .../aare_bec/sample_spreadsheet_display.py | 104 ++++++++++-------- .../widgets/aare_bec/task_queue.py | 2 + mx_bec/endpoints.py | 17 +-- mx_bec/math.py | 2 +- mx_bec/service.py | 4 +- mx_bec/tasks.py | 18 +-- tests/unit/test_service.py | 4 +- tests/unit/test_tasks.py | 4 +- 11 files changed, 113 insertions(+), 71 deletions(-) diff --git a/mx_bec/actors/mx_automation.py b/mx_bec/actors/mx_automation.py index 38831f5..e3d98c9 100644 --- a/mx_bec/actors/mx_automation.py +++ b/mx_bec/actors/mx_automation.py @@ -6,6 +6,7 @@ exercised end to end on the simulated beamline before the real procedures exist. """ import secrets +from datetime import date from time import sleep from typing import Any, ClassVar @@ -123,6 +124,7 @@ class OnOpticalCenteringDoneRunMultiGrid(MXAutomationActor): params.detector_distance_mm, ) logger.info(f"calculated strategy: {strategy}") + strategy["file_prefix"] = date.today().strftime("%Y%m%d") + "/" + strategy["file_prefix"] client.add_task_to_queue( MXTaskExecutionMessage( name="multiple_rasters", args=(params.omegas_for_multi_grid_degs,), kwargs=strategy diff --git a/mx_bec/bec_widgets/widgets/aare_bec/__init__.py b/mx_bec/bec_widgets/widgets/aare_bec/__init__.py index e69de29..d624b39 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/__init__.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/__init__.py @@ -0,0 +1,13 @@ +from .actors_config import MxActorConfigWidget +from .sample_queue import SampleQueueWidget +from .sample_spreadsheet_display import SampleSpreadsheetDisplay +from .task_panel import MxTaskPanel +from .task_queue import MxTaskQueueWidget + +__all__ = [ + "MxActorConfigWidget", + "SampleQueueWidget", + "SampleSpreadsheetDisplay", + "MxTaskPanel", + "MxTaskQueueWidget", +] diff --git a/mx_bec/bec_widgets/widgets/aare_bec/sample_queue.py b/mx_bec/bec_widgets/widgets/aare_bec/sample_queue.py index 34371e3..d3a7f11 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/sample_queue.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/sample_queue.py @@ -2,6 +2,7 @@ from __future__ import annotations from bec_lib.config_values import RedisConfigValue from bec_lib.logger import bec_logger +from bec_lib.serialization import MsgpackSerialization from bec_widgets.utils.bec_connector import ConnectionConfig from bec_widgets.utils.bec_widget import BECWidget from bec_widgets.utils.error_popups import SafeSlot @@ -10,7 +11,7 @@ from qtpy.QtCore import Signal from qtpy.QtWidgets import QHBoxLayout, QLabel, QListWidget, QPushButton, QVBoxLayout, QWidget from mx_bec.endpoints import QueueEndpoints -from mx_bec.messages import MXSampleExecutionMessage +from mx_bec.messages import MXQueueChangedMessage, MXSampleExecutionMessage logger = bec_logger.logger @@ -78,13 +79,20 @@ class SampleQueueWidget(BECWidget, QWidget): tasks = self.client.connector.lrange(QueueEndpoints.sample_execution(), 0, -1) self._list.clear() for msg in tasks: - msg: MXSampleExecutionMessage - self._list.addItem(f"{msg.sample_name} (db_id: {msg.db_id})") + try: + msg = MsgpackSerialization.loads(msg) + except Exception as e: + logger.exception(f"failed to decode: {e}") + if isinstance(msg, MXSampleExecutionMessage): + self._list.addItem(f"{msg.sample_name} (db_id: {msg.db_id})") + else: + self._list.addItem(str(msg)) @SafeSlot() def clear_queue(self): """Delete the queue contents""" self.client.connector.delete(QueueEndpoints.sample_execution()) + self.client.connector.send(QueueEndpoints.sample_queue_changed(), MXQueueChangedMessage()) @SafeSlot(dict, dict) def _on_queue_changed(self, _content: dict, _metadata: dict): diff --git a/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py b/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py index ca1b2ca..5078191 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py @@ -7,39 +7,15 @@ from bec_lib.messages import RawMessage from bec_widgets.utils.bec_connector import ConnectionConfig from bec_widgets.utils.bec_widget import BECWidget, SafeSlot from pyqtgraph.Qt.QtWidgets import QPushButton -from qtpy.QtWidgets import QLabel, QScrollArea, QVBoxLayout, QWidget +from qtpy.QtWidgets import QLabel, QScrollArea, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget +from redis import RedisError + +from mx_bec.endpoints import QueueEndpoints +from mx_bec.messages import MXQueueChangedMessage, MXSampleExecutionMessage logger = bec_logger.logger -def dicts_to_html_table(data: list[dict]) -> str: - if not data: - return "

No data available

" - - # 1. Extract unique keys for the header - headers = list(set(k for item in data for k in item.keys())) - if "aaredb_params" in headers: - headers.remove("aaredb_params") - - # 2. Build the HTML Header Row - html = "
\n \n \n" - for header in headers: - html += f" \n" - html += " \n \n \n" - - # 3. Build the Data Rows - for row in data: - html += " \n" - for header in headers: - # .get() handles missing keys safely - val = row.get(header, "") - html += f" \n" - html += " \n" - - html += " \n
{header}
{val}
" - return html - - class SampleSpreadsheetDisplay(BECWidget, QWidget): """ Display information from the sample spreadsheet @@ -60,20 +36,10 @@ class SampleSpreadsheetDisplay(BECWidget, QWidget): self._data: dict[str, Any] self._layout = QVBoxLayout(self) self._layout.addWidget(QLabel(" Sample spreadhseet data: ")) - self._refresh_button = QPushButton("refresh") - self._layout.addWidget(self._refresh_button) - self._layout_area = QScrollArea() - self._layout.addWidget(self._layout_area) + # self._layout_area = QScrollArea() + # self._layout.addWidget(self._layout_area) - self._display_label = QLabel("") - self._layout_area.setWidget(self._display_label) - - self.refresh() - self._refresh_button.clicked.connect(self.refresh) - - @SafeSlot() - def refresh(self): dict_data = [{}] try: data = self.client.connector._managed_connection.get("x10sa:sample_spreadsheet") @@ -81,9 +47,55 @@ class SampleSpreadsheetDisplay(BECWidget, QWidget): dict_data: list[dict[str, Any]] = data.data["s"] else: dict_data = [{"text": str(data)}] - except Exception as e: - self._display_label.setText(f"Failed to load spreadsheet data: {e}") - return - self._display_label.setText(dicts_to_html_table(dict_data)) - self._display_label.adjustSize() + except RedisError: + logger.exception("No data obtained") + dict_data = [{"data": "none"}] + self._table = self._dicts_to_table_widget(dict_data) + # self._layout_area.setWidget(self._table) + # self._layout_area.adjustSize() + self._layout.addWidget(self._table) + self._table.adjustSize() logger.info(f"Successfully updated sample spreadsheet e.g. {dict_data[0]}...") + + @SafeSlot() + def _request(self, db_id, name): + self.client.connector.lpush( + QueueEndpoints.sample_execution(), + MXSampleExecutionMessage(db_id=db_id, sample_name=name), + ) + self.client.connector.send(QueueEndpoints.sample_queue_changed(), MXQueueChangedMessage()) + + def _req_button(self, db_id, name): + if not isinstance(db_id, int): + return "No id!" + button = QPushButton("Add to queue") + button.clicked.connect(lambda: self._request(db_id, name)) + return button + + def _dicts_to_table_widget(self, data: list[dict]) -> QTableWidget: + if not data: + return QTableWidget(1, 1) + + headers = ["Add to queue", *set(k for item in data for k in item.keys())] + if "aaredb_params" in headers: + headers.remove("aaredb_params") + + rows = [ + [ + self._req_button(row.get("db_id"), row.get("sample_name", "")), + *(row.get(h, "") for h in headers), + ] + for row in data + ] + n_rows = len(rows) + n_cols = len(headers) + table = QTableWidget(len(rows), len(headers)) + for i in range(n_rows): + for j in range(n_cols): + item = rows[i][j] + if isinstance(item, QWidget): + table.setCellWidget(i, j, item) + else: + table.setItem(i, j, QTableWidgetItem(str(item))) + + return table diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py b/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py index 80e2f71..33628a1 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py @@ -10,6 +10,7 @@ from qtpy.QtCore import Signal from qtpy.QtWidgets import QHBoxLayout, QLabel, QListWidget, QPushButton, QVBoxLayout, QWidget from mx_bec.endpoints import QueueEndpoints +from mx_bec.messages import MXQueueChangedMessage logger = bec_logger.logger @@ -86,6 +87,7 @@ class MxTaskQueueWidget(BECWidget, QWidget): def clear_queue(self): """Delete the queue contents""" self.client.connector.delete(QueueEndpoints.task_execution()) + self.client.connector.send(QueueEndpoints.sample_queue_changed(), MXQueueChangedMessage()) @SafeSlot(dict, dict) def _on_queue_changed(self, _content: dict, _metadata: dict): diff --git a/mx_bec/endpoints.py b/mx_bec/endpoints.py index 92519e9..38565e1 100644 --- a/mx_bec/endpoints.py +++ b/mx_bec/endpoints.py @@ -4,6 +4,7 @@ from bec_lib.messages import AvailableResourceMessage, BoolConfigDefaultFalse from mx_bec.messages import ( MXMeasurementSequenceMessage, MXQueueChangedMessage, + MXSampleExecutionMessage, MXTaskExecutionMessage, OpticalPredictionMessage, ) @@ -124,19 +125,19 @@ class QueueEndpoints: message_op=MessageOp.STREAM, ) - @staticmethod - def sample_request(): - return EndpointInfo( - endpoint=f"{EndpointType.USER.value}/mx/sample_queue/request", - message_type=MXTaskExecutionMessage, - message_op=MessageOp.STREAM, - ) + # @staticmethod + # def sample_request(): + # return EndpointInfo( + # endpoint=f"{EndpointType.USER.value}/mx/sample_queue/request", + # message_type=MXTaskExecutionMessage, + # message_op=MessageOp.STREAM, + # ) @staticmethod def sample_execution(): return EndpointInfo( endpoint=f"{EndpointType.USER.value}/mx/sample_queue/execution", - message_type=MXTaskExecutionMessage, + message_type=MXSampleExecutionMessage, message_op=MessageOp.LIST, ) diff --git a/mx_bec/math.py b/mx_bec/math.py index 44bdb1b..db76ac7 100644 --- a/mx_bec/math.py +++ b/mx_bec/math.py @@ -78,7 +78,7 @@ def gridscan_strategy_from_optical( box_data = {box.label: ((box.x1, box.y1), (box.x2, box.y2)) for box in boxes} logger.info(f"got detection boxes: {box_data}") box_corners = None - for label_option in ["crystal", "loop_face", "loop_all"]: + for label_option in ["loop_face", "loop_all"]: if label_option in box_data: box_corners = box_data[label_option] logger.info(f"using best available box: {label_option}") diff --git a/mx_bec/service.py b/mx_bec/service.py index c120c65..283f204 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -14,7 +14,7 @@ from mx_bec.actor_manager import AareActorManager from mx_bec.constants import AareBecWorkflowState from mx_bec.endpoints import QueueEndpoints from mx_bec.jfjoch import JFJoch -from mx_bec.messages import MXTaskQueueChangedMessage +from mx_bec.messages import MXQueueChangedMessage from mx_bec.optical_centering import OpticalPrediction from mx_bec.sample_info import SampleInfo from mx_bec.tasks import MxTaskQueue, MxTasks @@ -84,7 +84,7 @@ class AareBec(BECClient): def add_task_to_queue(self, task: MXTaskExecutionMessage): """Add a task to the task queue. The task should be validated or guaranteed possible.""" self.connector.rpush(QueueEndpoints.task_execution(), task) - self.connector.send(QueueEndpoints.task_queue_changed(), MXTaskQueueChangedMessage()) + self.connector.send(QueueEndpoints.task_queue_changed(), MXQueueChangedMessage()) @property def devices(self): diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index 9c96625..913b3aa 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -7,10 +7,8 @@ from threading import Event, RLock, Thread from typing import TYPE_CHECKING, Callable, Concatenate, ParamSpec, Self, TypeVar from aarecommon.math.coordinate import Coordinate, SmargonCoordinate -from aarecommon.models.raster_grid import ( - CompletedRasterGrid, # already imported in aaredaq.py - RasterGridRequest, -) +from aarecommon.models.raster_grid import CompletedRasterGrid # already imported in aaredaq.py +from aarecommon.models.raster_grid import RasterGridRequest from aarecommon.models.rotation_scan import RotationScanRequest from bec_lib.config_values import RedisConfigValue from bec_lib.endpoints import EndpointInfo @@ -22,8 +20,8 @@ from mx_bec.jfjoch import RasterScan from mx_bec.math import smargon_nudge from mx_bec.messages import ( MXMeasurementSequenceMessage, + MXQueueChangedMessage, MXTaskExecutionMessage, - MXTaskQueueChangedMessage, ) from mx_bec.self_driving import ( CollectionRecord, @@ -195,7 +193,7 @@ class MxTasks: exp_time_s: float, file_prefix: str | None = None, dtz: float | None = None, - ) -> None: + ) -> MxSequenceUpdate: """Run multiple raster scans at different omega values""" for i, omega in enumerate(omegas_deg_list): self._run_raster( @@ -209,6 +207,12 @@ class MxTasks: omega_deg=omega, ) logger.info(f"Raster {i + 1} out of {len(omegas_deg_list)} done.") + return ( + StateEndpoints.sample_done(), + MXMeasurementSequenceMessage( + sample_id=self._client.sample_info.sample_id, success=True + ), + ) @task def aaredaq_rotation_scan( @@ -459,7 +463,7 @@ class MxTaskQueue: ) if msg is not None: self._client.connector.send( - QueueEndpoints.task_queue_changed(), MXTaskQueueChangedMessage() + QueueEndpoints.task_queue_changed(), MXQueueChangedMessage() ) self.execute(msg) diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py index b8a0a6e..ba2c6f0 100644 --- a/tests/unit/test_service.py +++ b/tests/unit/test_service.py @@ -9,8 +9,8 @@ from mx_bec.constants import AareBecWorkflowState from mx_bec.endpoints import QueueEndpoints, StateEndpoints from mx_bec.messages import ( MXMeasurementSequenceMessage, + MXQueueChangedMessage, MXTaskExecutionMessage, - MXTaskQueueChangedMessage, ) from mx_bec.service import AareBec, MxTasks @@ -101,7 +101,7 @@ def test_task_request_for_known_method_is_queued_and_announced(service): service._on_task_request({"data": msg}) service.connector.rpush.assert_called_once_with(QueueEndpoints.task_execution(), msg) service.connector.send.assert_called_once_with( - QueueEndpoints.task_queue_changed(), MXTaskQueueChangedMessage() + QueueEndpoints.task_queue_changed(), MXQueueChangedMessage() ) diff --git a/tests/unit/test_tasks.py b/tests/unit/test_tasks.py index b533549..34eab6a 100644 --- a/tests/unit/test_tasks.py +++ b/tests/unit/test_tasks.py @@ -7,7 +7,7 @@ import pytest from bec_lib.redis_connector import RedisConnector from mx_bec.endpoints import QueueEndpoints -from mx_bec.messages import MXTaskExecutionMessage, MXTaskQueueChangedMessage +from mx_bec.messages import MXQueueChangedMessage, MXTaskExecutionMessage from mx_bec.tasks import MxTaskQueue, MxTasks @@ -75,7 +75,7 @@ def test_queue_announces_each_pop(connector, queue): ) queue.start() _wait_for(lambda: len(notifications) == 2) - assert all(n.value == MXTaskQueueChangedMessage() for n in notifications) + assert all(n.value == MXQueueChangedMessage() for n in notifications) def test_queue_does_not_pop_while_paused(connector, queue, tasks): -- 2.54.1 From 745e73fa90054e7435cca2466eb65343bba55497 Mon Sep 17 00:00:00 2001 From: David Perl Date: Fri, 13 Nov 2026 14:00:29 +0100 Subject: [PATCH 37/46] qol of queue usage --- mx_bec/aaredaq.py | 6 +++++ mx_bec/actors/mx_automation.py | 2 ++ .../widgets/aare_bec/task_panel.py | 3 ++- .../widgets/aare_bec/task_queue.py | 25 +++++++++++++++++-- mx_bec/tasks.py | 11 ++++++-- 5 files changed, 42 insertions(+), 5 deletions(-) diff --git a/mx_bec/aaredaq.py b/mx_bec/aaredaq.py index 28f799b..257143d 100644 --- a/mx_bec/aaredaq.py +++ b/mx_bec/aaredaq.py @@ -201,6 +201,12 @@ class AareDaq: "/sample/mount", params={"dbid": dbid, "reference": reference}, timeout_s=timeout_s ) + def unmount_sample_then_park(self, timeout_s: float = 600.0) -> None: + """unmount the current sample.""" + self.ensure_baton() + logger.info("AareDAQ: unmounting sample, then putting the robot to a safe place") + self._post("/sample/unmount_then_park_and_dry", timeout_s=timeout_s) + def auto_loop_center(self): self.ensure_baton() self._post("/alc/center_loop") diff --git a/mx_bec/actors/mx_automation.py b/mx_bec/actors/mx_automation.py index e3d98c9..fc74089 100644 --- a/mx_bec/actors/mx_automation.py +++ b/mx_bec/actors/mx_automation.py @@ -21,6 +21,7 @@ from mx_bec.endpoints import QueueEndpoints, StateEndpoints from mx_bec.math import gridscan_calculation, gridscan_strategy_from_optical, mock_grid_calculation from mx_bec.messages import ( MXMeasurementSequenceMessage, + MXQueueChangedMessage, MXSampleExecutionMessage, MXTaskExecutionMessage, ) @@ -148,6 +149,7 @@ class OnSampleDoneLoadNext(MXAutomationActor): next: MXSampleExecutionMessage = client.connector.blocking_list_pop( QueueEndpoints.sample_execution() ) + client.connector.send(QueueEndpoints.sample_queue_changed(), MXQueueChangedMessage()) client.add_task_to_queue( MXTaskExecutionMessage(name="aaredaq_mount_sample", args=(next.db_id,), kwargs={}) ) diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py index 0bd2788..edf9a31 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -27,7 +27,9 @@ logger = bec_logger.logger # Hard-coded forms: task name -> [(argument, default value)]; the widget type follows the default. TASK_FORMS: dict[str, list[tuple[str, int | float | str | list[float]]]] = { + "aaredaq_mount_sample": [("dbid", 0)], "run_optical_centering": [("sample_id", 0)], + "cleanup_beamline": [], # "run_grid_scan": [ # ("n_x", 4), # ("n_y", 3), @@ -49,7 +51,6 @@ TASK_FORMS: dict[str, list[tuple[str, int | float | str | list[float]]]] = { # ("sample_name", "unknown_sample"), # ], # the AareDAQ-driven tasks; their bool/optional arguments keep their defaults here - "aaredaq_mount_sample": [("dbid", 0)], "aaredaq_raster_scan": [ ("n_x", 4), ("n_y", 3), diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py b/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py index 33628a1..6a51a13 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py @@ -10,7 +10,7 @@ from qtpy.QtCore import Signal from qtpy.QtWidgets import QHBoxLayout, QLabel, QListWidget, QPushButton, QVBoxLayout, QWidget from mx_bec.endpoints import QueueEndpoints -from mx_bec.messages import MXQueueChangedMessage +from mx_bec.messages import MXQueueChangedMessage, MXSampleExecutionMessage, MXTaskExecutionMessage logger = bec_logger.logger @@ -26,7 +26,7 @@ class MxTaskQueueWidget(BECWidget, QWidget): PLUGIN = True ICON_NAME = "pending_actions" - USER_ACCESS = ["refresh", "clear_queue"] + USER_ACCESS = ["refresh", "clear_queue", "start_queue"] # Redis callbacks arrive on the connector thread; re-emit so the toggle is updated on the GUI # thread. @@ -54,6 +54,8 @@ class MxTaskQueueWidget(BECWidget, QWidget): self._toggle.stateChanged.connect(self._set_running) self._delete_button = QPushButton("Clear queue") self._delete_button.clicked.connect(self.clear_queue) + self._start_button = QPushButton("Start queue") + self._start_button.clicked.connect(self.start_queue) self._list = QListWidget(parent=self) layout = QVBoxLayout(self) @@ -89,6 +91,25 @@ class MxTaskQueueWidget(BECWidget, QWidget): self.client.connector.delete(QueueEndpoints.task_execution()) self.client.connector.send(QueueEndpoints.sample_queue_changed(), MXQueueChangedMessage()) + @SafeSlot() + def start_queue(self): + """Try to start the queue""" + queue_len = self.client.connector.llen(QueueEndpoints.sample_execution()) + if not queue_len: + return # TODO: run some kind of cleanup e.g. unmount, gripper park and dry + next: MXSampleExecutionMessage = self.client.connector.blocking_list_pop( + QueueEndpoints.sample_execution() + ) + self.client.connector.send(QueueEndpoints.sample_queue_changed(), MXQueueChangedMessage()) + self.client.connector.xadd( + QueueEndpoints.task_request(), + { + "data": MXTaskExecutionMessage( + name="aaredaq_mount_sample", args=(next.db_id,), kwargs={} + ) + }, + ) + @SafeSlot(dict, dict) def _on_queue_changed(self, _content: dict, _metadata: dict): self.refresh() diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index 913b3aa..7b6c37a 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -7,8 +7,10 @@ from threading import Event, RLock, Thread from typing import TYPE_CHECKING, Callable, Concatenate, ParamSpec, Self, TypeVar from aarecommon.math.coordinate import Coordinate, SmargonCoordinate -from aarecommon.models.raster_grid import CompletedRasterGrid # already imported in aaredaq.py -from aarecommon.models.raster_grid import RasterGridRequest +from aarecommon.models.raster_grid import ( + CompletedRasterGrid, # already imported in aaredaq.py + RasterGridRequest, +) from aarecommon.models.rotation_scan import RotationScanRequest from bec_lib.config_values import RedisConfigValue from bec_lib.endpoints import EndpointInfo @@ -182,6 +184,11 @@ class MxTasks: MXMeasurementSequenceMessage(sample_id=dbid, success=True), ) + @task + def cleanup_beamline(self): + """Unmount the current sample and send the gripper to dry""" + self._client.aaredaq.unmount_sample_then_park() + @task def multiple_rasters( self, -- 2.54.1 From 5a02d9d8fb73b233adc0740277fcb461ff158963 Mon Sep 17 00:00:00 2001 From: David Perl Date: Fri, 13 Nov 2026 14:14:25 +0100 Subject: [PATCH 38/46] add many to queue --- .../aare_bec/sample_spreadsheet_display.py | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py b/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py index 5078191..8abb2d0 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py @@ -37,6 +37,9 @@ class SampleSpreadsheetDisplay(BECWidget, QWidget): self._layout = QVBoxLayout(self) self._layout.addWidget(QLabel(" Sample spreadhseet data: ")) + self._add_selected_button = QPushButton("Add selected to queue") + self._layout.addWidget(self._add_selected_button) + self._add_selected_button.clicked.connect(self._add_selected) # self._layout_area = QScrollArea() # self._layout.addWidget(self._layout_area) @@ -50,6 +53,7 @@ class SampleSpreadsheetDisplay(BECWidget, QWidget): except RedisError: logger.exception("No data obtained") dict_data = [{"data": "none"}] + self.data = dict_data self._table = self._dicts_to_table_widget(dict_data) # self._layout_area.setWidget(self._table) # self._layout_area.adjustSize() @@ -57,7 +61,7 @@ class SampleSpreadsheetDisplay(BECWidget, QWidget): self._table.adjustSize() logger.info(f"Successfully updated sample spreadsheet e.g. {dict_data[0]}...") - @SafeSlot() + @SafeSlot(int, str) def _request(self, db_id, name): self.client.connector.lpush( QueueEndpoints.sample_execution(), @@ -65,6 +69,22 @@ class SampleSpreadsheetDisplay(BECWidget, QWidget): ) self.client.connector.send(QueueEndpoints.sample_queue_changed(), MXQueueChangedMessage()) + @SafeSlot() + def _add_selected(self): + selection = self._table.selectionModel() + rows = [id.row() for id in selection.selectedRows()] + logger.info(f"Adding selected rows: {rows} to queue") + ids: list[tuple[int, str]] = [ + (self.data[row].get("db_id"), self.data[row].get("sample_name")) for row in rows + ] + logger.info(f"Adding samples: {ids} to queue") + for id in ids: + self.client.connector.lpush( + QueueEndpoints.sample_execution(), + MXSampleExecutionMessage(db_id=id[0], sample_name=id[1]), + ) + self.client.connector.send(QueueEndpoints.sample_queue_changed(), MXQueueChangedMessage()) + def _req_button(self, db_id, name): if not isinstance(db_id, int): return "No id!" @@ -90,6 +110,7 @@ class SampleSpreadsheetDisplay(BECWidget, QWidget): n_rows = len(rows) n_cols = len(headers) table = QTableWidget(len(rows), len(headers)) + table.setHorizontalHeaderLabels(headers) for i in range(n_rows): for j in range(n_cols): item = rows[i][j] -- 2.54.1 From 48a5efa56bd37ffe937bfbc30e38ef38a1de9b6e Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 24 Nov 2026 10:49:44 +0100 Subject: [PATCH 39/46] task architecture with requesting client --- .../widgets/aare_bec/task_panel.py | 9 +- mx_bec/service.py | 22 +- mx_bec/tasks/__init__.py | 29 ++ mx_bec/tasks/core.py | 378 ++++++++++++++++++ mx_bec/{tasks.py => tasks/mx_tasks.py} | 151 +------ tests/unit/test_aaredaq_tasks.py | 4 +- tests/unit/test_actors.py | 4 +- tests/unit/test_change_state_task.py | 6 +- tests/unit/test_grid_scan_task.py | 8 +- tests/unit/test_service.py | 39 +- tests/unit/test_tasks.py | 28 +- tests/unit/test_tasks_core.py | 198 +++++++++ 12 files changed, 687 insertions(+), 189 deletions(-) create mode 100644 mx_bec/tasks/__init__.py create mode 100644 mx_bec/tasks/core.py rename mx_bec/{tasks.py => tasks/mx_tasks.py} (69%) create mode 100644 tests/unit/test_tasks_core.py diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py index edf9a31..ae42bfb 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -19,9 +19,7 @@ from qtpy.QtWidgets import ( QWidget, ) -from mx_bec.endpoints import QueueEndpoints -from mx_bec.messages import MXTaskExecutionMessage -from mx_bec.tasks import MxTasks +from mx_bec.tasks import Client, MxTasks logger = bec_logger.logger @@ -100,6 +98,7 @@ class MxTaskPanel(BECWidget, QWidget): **kwargs, ) -> None: super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs) + self._tasks = MxTasks[Client](self.client) self._inputs: dict[str, dict[str, QSpinBox | QDoubleSpinBox | QLineEdit]] = {} # all the forms live in a scrollable content widget content = QWidget() @@ -193,6 +192,4 @@ class MxTaskPanel(BECWidget, QWidget): @SafeSlot(str) def request_task(self, name: str, *args, **kwargs): """Submit a task request to the AareBec service.""" - msg = MXTaskExecutionMessage(name=name, args=args, kwargs=kwargs) - logger.info(f"Requesting task: {msg}") - self.client.connector.xadd(QueueEndpoints.task_request(), {"data": msg}) + self._tasks.request(name, *args, **kwargs) diff --git a/mx_bec/service.py b/mx_bec/service.py index 283f204..a46485e 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -17,7 +17,7 @@ from mx_bec.jfjoch import JFJoch from mx_bec.messages import MXQueueChangedMessage from mx_bec.optical_centering import OpticalPrediction from mx_bec.sample_info import SampleInfo -from mx_bec.tasks import MxTaskQueue, MxTasks +from mx_bec.tasks import MxTaskQueue, MxTasks, Server, UnknownTask if TYPE_CHECKING: from bec_lib.redis_connector import RedisConnector @@ -51,10 +51,11 @@ class AareBec(BECClient): self.optical_prediction = OpticalPrediction(client=self) self.jfjoch = JFJoch(client=self) # connects lazily on first use self.aaredaq = AareDaq(client=self) # authenticates lazily on first use - self.tasks = MxTasks(self) + self.tasks = MxTasks[Server](self) self.task_queue: MxTaskQueue | None = None self.sample_info: SampleInfo | None = None - # HAX + # HAX: copy the sample spreadsheet from the beamline redis, to put it into the BEC redis in + # start(). To be replaced by the eventual sample database connection module. _, _host, _port = config_redis_url.split(":") _port = int(_port) _hacky_redis = Redis(_host[2:], _port) @@ -68,18 +69,17 @@ class AareBec(BECClient): self.task_queue.start() self.connector.register(QueueEndpoints.task_request(), cb=self._on_task_request) self.status = messages.BECStatus.RUNNING - # HAX + # HAX: see __init__; to be replaced by the eventual sample database connection module self.connector._managed_connection.set("x10sa:sample_spreadsheet", self._spreadsheet) def _on_task_request(self, msg_dict: dict) -> None: - """Validate a task request and, if it names a public `MxTasks` method, append it to the - task execution queue.""" + """Append a requested task to the task execution queue, unless it does not name a task + of `MxTasks`.""" msg: MXTaskExecutionMessage = msg_dict["data"] - if not MxTasks.is_task(msg.name): - logger.warning(f"Rejected task request: {msg.name!r} is not a public MxTasks method") - return - logger.info(f"Queueing task request: {msg}") - self.add_task_to_queue(msg) + try: + self.tasks.request(msg.name, *msg.args, **msg.kwargs) + except UnknownTask as e: + logger.warning(f"Rejected task request: {e}") def add_task_to_queue(self, task: MXTaskExecutionMessage): """Add a task to the task queue. The task should be validated or guaranteed possible.""" diff --git a/mx_bec/tasks/__init__.py b/mx_bec/tasks/__init__.py new file mode 100644 index 0000000..619e363 --- /dev/null +++ b/mx_bec/tasks/__init__.py @@ -0,0 +1,29 @@ +"""Tasks which can be requested from the AareBec service: `core` has the machinery (the `task` +decorator, the Server/Client roles, the task queue), `mx_tasks` the tasks themselves.""" + +from mx_bec.tasks.core import ( + BoundTask, + Client, + MxSequenceUpdate, + MxTaskQueue, + RoleT, + Server, + TaskManager, + UnknownTask, + task, +) +from mx_bec.tasks.mx_tasks import MAX_GRID_SCAN_S, MxTasks + +__all__ = [ + "MAX_GRID_SCAN_S", + "BoundTask", + "Client", + "MxSequenceUpdate", + "MxTaskQueue", + "MxTasks", + "RoleT", + "Server", + "TaskManager", + "UnknownTask", + "task", +] diff --git a/mx_bec/tasks/core.py b/mx_bec/tasks/core.py new file mode 100644 index 0000000..ec2a0d7 --- /dev/null +++ b/mx_bec/tasks/core.py @@ -0,0 +1,378 @@ +""" +Role-generic task manager, communicating through the MX task endpoints in Redis. + + class MxTasks(TaskManager[RoleT]): + @task + def mount(self, dbid: int) -> MxSequenceUpdate: ... + + server = MxTasks[Server](aare_bec) # in the AareBec service: tasks run here + client = MxTasks[Client](bec_client) # anywhere else: tasks are requested from the service + + server.mount(3) # runs here, blocking, holding the task lock + server.mount.request(3) # appends it to the task execution queue + server.request("mount", 3) # the same, looked up by name + server.execute(msg) # runs the task named by an MXTaskExecutionMessage + + client.mount(3) # sends a request to the service's task request stream + client.mount.request(3) # the same + client.request("mount", 3) # the same, looked up by name + +Nothing travels back to the requester: a task reports its outcome by returning a state update +(endpoint, message), which the server publishes once the task is done. +""" + +from __future__ import annotations + +import functools +from collections.abc import Callable +from threading import Event, RLock, Thread +from typing import TYPE_CHECKING, Any, ClassVar, Concatenate, Generic, ParamSpec, TypeVar, overload + +from bec_lib.config_values import RedisConfigValue +from bec_lib.endpoints import EndpointInfo +from bec_lib.logger import bec_logger + +from mx_bec.endpoints import QueueEndpoints +from mx_bec.messages import ( + MXMeasurementSequenceMessage, + MXQueueChangedMessage, + MXTaskExecutionMessage, +) +from mx_bec.service import AareBec + +if TYPE_CHECKING: + from bec_lib.client import BECClient + +logger = bec_logger.logger + +# What a task returns: a state to set and publish once it is done, or nothing. +MxSequenceUpdate = tuple[EndpointInfo[Any], MXMeasurementSequenceMessage] | None + +P = ParamSpec("P") +S = TypeVar("S", bound="TaskManager[Any]") + +Args = tuple[Any, ...] +Kwargs = dict[str, Any] + + +class UnknownTask(LookupError): + """The requested name is not a task of the task manager.""" + + +# --------------------------------------------------------------------------- # +# The decorator / descriptor +# --------------------------------------------------------------------------- # + + +class task(Generic[S, P]): # pylint: disable=invalid-name + """Turns a method into a task. What calling it does depends on the instance's role.""" + + def __init__(self, func: Callable[Concatenate[S, P], MxSequenceUpdate]) -> None: + self.func = func + self.name: str = func.__name__ + functools.update_wrapper(self, func) + + def __set_name__(self, owner: type, name: str) -> None: + self.name = name + + def __call__(self, obj: S, /, *args: P.args, **kwargs: P.kwargs) -> None: + """Calling through the class, `MyTasks.some_task(instance, ...)`.""" + obj._call_task(self, args, kwargs) # pylint: disable=protected-access + + @overload + def __get__(self, obj: None, objtype: type | None = None) -> task[S, P]: ... + @overload + def __get__(self, obj: S, objtype: type | None = None) -> BoundTask[P]: ... + def __get__(self, obj: S | None, objtype: type | None = None) -> task[S, P] | BoundTask[P]: + if obj is None: + return self + return BoundTask(self, obj) + + def __repr__(self) -> str: + return f"" + + +AnyTask = task[Any, ...] + + +class BoundTask(Generic[P]): + """A task attached to an instance. Calling it delegates to the instance's role.""" + + __slots__ = ("owner", "spec") + + def __init__(self, spec: task[Any, P], owner: TaskManager[Any]) -> None: + self.spec = spec + self.owner = owner + + def __call__(self, *args: P.args, **kwargs: P.kwargs) -> None: + self.owner._call_task(self.spec, args, kwargs) # pylint: disable=protected-access + + def request(self, *args: P.args, **kwargs: P.kwargs) -> None: + self.owner._request_task(self.spec, args, kwargs) # pylint: disable=protected-access + + @property + def __name__(self) -> str: + return self.spec.name + + @property + def __doc__(self) -> str | None: # pyright: ignore[reportIncompatibleVariableOverride] + return self.spec.__doc__ + + def __repr__(self) -> str: + return f"" + + +# --------------------------------------------------------------------------- # +# Roles +# --------------------------------------------------------------------------- # + + +class Role: + """Base for the 'fundamental type' a TaskManager is parameterised over. A role is mixed in + in front of the TaskManager subclass, so `self` is the task manager instance.""" + + # set by TaskManager.__init__ + _client: BECClient # pyright: ignore[reportUninitializedInstanceVariable] + + def _init_role(self) -> None: + """Set up what the role needs; called at the end of TaskManager.__init__.""" + + def _call_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None: + raise NotImplementedError + + def _request_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None: + raise NotImplementedError + + +class Server(Role): + """Tasks execute here, one at a time. For the AareBec service: `client` is the service.""" + + _busy_lock: RLock # pyright: ignore[reportUninitializedInstanceVariable] + + def _init_role(self) -> None: + self._busy_lock = RLock() # reentrant, so that a task can call other tasks + + def _call_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None: + """Run the task while holding the lock. If it raises, the task queue is paused before + the exception propagates, so that queued tasks don't carry on from a failed state. + Otherwise the state update it returned, if any, is published.""" + with self._busy_lock: + try: + state_update = spec.func(self, *args, **kwargs) + except Exception as e: + self._pause_queue_after_failure(spec.name, e) + raise + logger.info(f"Task: {spec.name} completed.") + if state_update: + self._client.connector.set_and_publish(*state_update) + + def _request_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None: + """Append the task to the execution queue, which the service's MxTaskQueue works off.""" + msg = MXTaskExecutionMessage(name=spec.name, args=args, kwargs=kwargs) + logger.info(f"Queueing task: {msg}") + self._client.connector.rpush(QueueEndpoints.task_execution(), msg) + self._client.connector.send(QueueEndpoints.task_queue_changed(), MXQueueChangedMessage()) + + def _pause_queue_after_failure(self, task_name: str, e: Exception) -> None: + # the queue only exists once the service has started + if (queue := getattr(self._client, "task_queue", None)) is None: + return + logger.warning(f"Task {task_name} failed: {e}.\n Pausing the task queue.") + try: + queue.pause() + except Exception: # pylint: disable=broad-except + # the task's own exception is the one to surface + logger.exception("Failed to pause the task queue") + + +class Client(Role): + """Tasks are forwarded to the service through the task request stream. There is no reply, + so calling a task and requesting it are the same thing.""" + + def _call_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None: + self._request_task(spec, args, kwargs) + + def _request_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None: + msg = MXTaskExecutionMessage(name=spec.name, args=args, kwargs=kwargs) + logger.info(f"Requesting task: {msg}") + self._client.connector.xadd(QueueEndpoints.task_request(), {"data": msg}) + + +RoleT = TypeVar("RoleT", bound=Role) + + +# --------------------------------------------------------------------------- # +# The generic base +# --------------------------------------------------------------------------- # + + +class TaskManager(Generic[RoleT]): + """ + Subclass this as `class MyTasks(TaskManager[RoleT])` and decorate methods with @task. + Instantiate as MyTasks[Server](service) or MyTasks[Client](bec_client). + + MyTasks[Role] builds (and caches) a real class whose MRO is + (MyTasks[Role], Role, MyTasks, TaskManager, ...), so the role's hooks + take effect and isinstance(obj, MyTasks) still holds. + """ + + _tasks: ClassVar[dict[str, AnyTask]] = {} + _role_classes: ClassVar[dict[type, type]] + + def __init__(self, client: AareBec) -> None: + self._client = client + self._init_role() + + def __init_subclass__(cls, **kwargs: Any) -> None: + super().__init_subclass__(**kwargs) + cls._tasks = { + name: attr + for klass in reversed(cls.__mro__) + for name, attr in vars(klass).items() + if isinstance(attr, task) + } + cls._role_classes = {} + + def __class_getitem__(cls, role): + if not (isinstance(role, type) and issubclass(role, Role)): + # TypeVars etc.: normal generic behaviour + return super().__class_getitem__(role) # pyright: ignore[reportAttributeAccessIssue] + if issubclass(cls, Role): + raise TypeError(f"{cls.__name__} already has a role") + if role not in cls._role_classes: + cls._role_classes[role] = type( + f"{cls.__name__}[{role.__name__}]", + (role, cls), + { + "__module__": cls.__module__, + "__qualname__": f"{cls.__qualname__}[{role.__name__}]", + }, + ) + return cls._role_classes[role] + + def __new__(cls, *args: Any, **kwargs: Any): + if not issubclass(cls, Role): + raise TypeError( + f"Instantiate {cls.__name__}[Server](...) or {cls.__name__}[Client](...), " + f"not {cls.__name__}(...)" + ) + return super().__new__(cls) + + # Fallbacks so type checkers know every TaskManager has these hooks; the role overrides them. + def _init_role(self) -> None: + raise NotImplementedError + + def _call_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None: + raise NotImplementedError + + def _request_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None: + raise NotImplementedError + + # --- public API, the same for every role --------------------------------- + + @classmethod + def task_names(cls) -> list[str]: + return list(cls._tasks) + + @classmethod + def is_task(cls, name: str) -> bool: + """Whether `name` can be requested as a task, i.e. is a method decorated with `task`.""" + return name in cls._tasks + + @classmethod + def get_task(cls, name: str) -> AnyTask: + try: + return cls._tasks[name] + except KeyError: + raise UnknownTask(f"{name!r} is not a task of {cls.__name__}") from None + + def request(self, task_: str | BoundTask[...] | AnyTask, /, *args: Any, **kwargs: Any) -> None: + """Request a task by name or by reference: a server queues it for itself, a client asks + the server. Raises UnknownTask for a name which is not a task.""" + if isinstance(task_, BoundTask): + spec = task_.spec + elif isinstance(task_, task): + spec = task_ + else: + spec = self.get_task(task_) + self._request_task(spec, args, kwargs) + + def execute(self, msg: MXTaskExecutionMessage) -> None: + """Call the task named by `msg` with its arguments, as if it had been called directly. + Raises UnknownTask for a name which is not a task.""" + self._call_task(self.get_task(msg.name), msg.args, msg.kwargs) + + +# --------------------------------------------------------------------------- # +# The queue the server works off +# --------------------------------------------------------------------------- # + + +class MxTaskQueue: + """Executes requested tasks one at a time, in order, on a background thread. + + Tasks are popped from the left of the `QueueEndpoints.task_execution()` list and run on the + given task manager. The queue can be paused through the `QueueEndpoints.task_queue_paused()` + config value (from any client): no new task is popped while paused, but a task which is + already running is left to finish. + """ + + def __init__( + self, client: BECClient, tasks: TaskManager[Server], poll_interval_s: float = 0.5 + ) -> None: + self._client = client + self._tasks = tasks + self._poll_interval_s = poll_interval_s + self._stop_event = Event() + self._paused: RedisConfigValue[bool] = RedisConfigValue( + connector=client.connector, endpoint=QueueEndpoints.task_queue_paused() + ) + self._thread = Thread(target=self._run, name="MxTaskQueue", daemon=True) + + @property + def paused(self) -> bool: + return self._paused.value + + def pause(self) -> None: + """Stop taking new tasks from the queue; the current task finishes.""" + self._paused.value = True + + def resume(self) -> None: + """Start taking tasks from the queue again.""" + self._paused.value = False + + def start(self) -> None: + self._thread.start() + + def shutdown(self) -> None: + """Stop the queue thread, waiting for a running task to finish, and drop the Redis + subscription of the paused flag.""" + self._stop_event.set() + if self._thread.is_alive(): + self._thread.join() + self._paused.unregister_all() + + def _run(self) -> None: + while not self._stop_event.is_set(): + if self._paused.value: + self._stop_event.wait(self._poll_interval_s) + continue + msg = self._client.connector.blocking_list_pop( + QueueEndpoints.task_execution(), side="LEFT", timeout_s=self._poll_interval_s + ) + if msg is not None: + self._client.connector.send( + QueueEndpoints.task_queue_changed(), MXQueueChangedMessage() + ) + self.execute(msg) + + def execute(self, msg: MXTaskExecutionMessage) -> None: + """Run a single task. Failures are logged and do not stop the queue thread (a task + manager with the Server role pauses the queue when one of its tasks fails).""" + logger.info(f"Running task {msg.name} with args={msg.args}, kwargs={msg.kwargs}") + try: + self._tasks.execute(msg) + except UnknownTask as e: + logger.warning(f"Skipping queued task: {e}") + except Exception: # pylint: disable=broad-except + logger.exception(f"Task {msg.name} failed") diff --git a/mx_bec/tasks.py b/mx_bec/tasks/mx_tasks.py similarity index 69% rename from mx_bec/tasks.py rename to mx_bec/tasks/mx_tasks.py index 7b6c37a..0029f1b 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks/mx_tasks.py @@ -1,10 +1,7 @@ from __future__ import annotations -import functools -import inspect from secrets import token_hex -from threading import Event, RLock, Thread -from typing import TYPE_CHECKING, Callable, Concatenate, ParamSpec, Self, TypeVar +from typing import TYPE_CHECKING from aarecommon.math.coordinate import Coordinate, SmargonCoordinate from aarecommon.models.raster_grid import ( @@ -12,19 +9,12 @@ from aarecommon.models.raster_grid import ( RasterGridRequest, ) from aarecommon.models.rotation_scan import RotationScanRequest -from bec_lib.config_values import RedisConfigValue -from bec_lib.endpoints import EndpointInfo from bec_lib.logger import bec_logger from mx_bec.devices.smargopolo_smargon import Smargon -from mx_bec.endpoints import QueueEndpoints, StateEndpoints -from mx_bec.jfjoch import RasterScan +from mx_bec.endpoints import StateEndpoints from mx_bec.math import smargon_nudge -from mx_bec.messages import ( - MXMeasurementSequenceMessage, - MXQueueChangedMessage, - MXTaskExecutionMessage, -) +from mx_bec.messages import MXMeasurementSequenceMessage from mx_bec.self_driving import ( CollectionRecord, GridGeometry, @@ -34,6 +24,7 @@ from mx_bec.self_driving import ( SweepRecord, scan_images, ) +from mx_bec.tasks.core import MxSequenceUpdate, RoleT, TaskManager, task if TYPE_CHECKING: from pxii_bec.macros.beamline_planner import StateChangePlanner @@ -42,31 +33,24 @@ if TYPE_CHECKING: logger = bec_logger.logger -P = ParamSpec("P") -R = TypeVar("R") - MAX_GRID_SCAN_S = 1200.0 # refuse grid scans expected to take longer than 20 min -MxSequenceUpdate = tuple[EndpointInfo, MXMeasurementSequenceMessage] | None +class MxTasks(TaskManager[RoleT]): + """The operations on mx beamlines which can be requested as tasks. Instantiate as + `MxTasks[Server](aare_bec)` in the AareBec service, where the tasks run, or as + `MxTasks[Client](bec_client)` anywhere else, to request them from the service. -class MxTasks: - """Holder for operations on mx beamlines. Probably needs to be reconsidered. TODO: - - categorise tasks, allow nesting with one lock + - categorise tasks - add doc info to decorator, including placeholder for args, to show to GUI """ - def __init__(self, client: AareBec): - self._client = client - self._busy_lock = RLock() - self._planner: StateChangePlanner | None = None + if TYPE_CHECKING: + # the tasks only run in the service + _client: AareBec # pyright: ignore[reportIncompatibleVariableOverride] - def _request_task(self, name: str, *args, **kwargs): - """Submit a task request to the AareBec service.""" - msg = MXTaskExecutionMessage(name=name, args=args, kwargs=kwargs) - logger.info(f"Requesting task: {msg}") - self._client.connector.xadd(QueueEndpoints.task_request(), {"data": msg}) + _planner: StateChangePlanner | None = None @property def planner(self) -> StateChangePlanner: @@ -79,47 +63,6 @@ class MxTasks: _, _, self._planner = init_beamline_environment() return self._planner - @classmethod - def is_task(cls, name: str) -> bool: - """Whether `name` can be requested as a task, i.e. is a method decorated with `task`.""" - return getattr(inspect.getattr_static(cls, name, None), "is_mx_task", False) - - @staticmethod - def task( - method: Callable[Concatenate[MxTasks, P], MxSequenceUpdate], - ) -> Callable[Concatenate[MxTasks, P], None]: - """Mark the decorated method as a task. It runs while holding `self._busy_lock`, so that - only one task runs at a time, and if it raises, the task queue is paused before the - exception propagates, so that queued tasks don't carry on from a failed state.""" - - # TODO: task becomes a callable class with methods to request, etc - - @functools.wraps(method) - def wrapper(self: MxTasks, *args, **kwargs): - # pylint: disable=protected-access - with self._busy_lock: - try: - state_update = method(self, *args, **kwargs) - except Exception as e: - self._pause_queue_after_failure(method.__name__, e) - raise - logger.info(f"Task: {method.__name__} completed.") - if state_update: - self._client.connector.set_and_publish(*state_update) - - wrapper.is_mx_task = True - return wrapper - - def _pause_queue_after_failure(self, task_name: str, e: Exception) -> None: - if (queue := getattr(self._client, "task_queue", None)) is None: - return - logger.warning(f"Task {task_name} failed: {e}.\n Pausing the task queue.") - try: - queue.pause() - except Exception: # pylint: disable=broad-except - # the task's own exception is the one to surface - logger.exception("Failed to pause the task queue") - @task def run_optical_centering_bec(self, sample_id: int): """Rotate the Aerotech to each angle from the config, update the optical centering @@ -416,71 +359,3 @@ class MxTasks: StateEndpoints.rotation_done(), MXMeasurementSequenceMessage(sample_id=dbid, success=True), ) - - -class MxTaskQueue: - """Executes requested tasks one at a time, in order, on a background thread. - - Tasks are popped from the left of the `QueueEndpoints.task_execution()` list and run on the - given `MxTasks`. The queue can be paused through the `QueueEndpoints.task_queue_paused()` - config value (from any client): no new task is popped while paused, but a task which is - already running is left to finish. - """ - - def __init__(self, client: AareBec, tasks: MxTasks, poll_interval_s: float = 0.5) -> None: - self._client = client - self._tasks = tasks - self._poll_interval_s = poll_interval_s - self._stop_event = Event() - self._paused: RedisConfigValue[bool] = RedisConfigValue( - connector=client.connector, endpoint=QueueEndpoints.task_queue_paused() - ) - self._thread = Thread(target=self._run, name="MxTaskQueue", daemon=True) - - @property - def paused(self) -> bool: - return self._paused.value - - def pause(self) -> None: - """Stop taking new tasks from the queue; the current task finishes.""" - self._paused.value = True - - def resume(self) -> None: - """Start taking tasks from the queue again.""" - self._paused.value = False - - def start(self) -> None: - self._thread.start() - - def shutdown(self) -> None: - """Stop the queue thread, waiting for a running task to finish, and drop the Redis - subscription of the paused flag.""" - self._stop_event.set() - if self._thread.is_alive(): - self._thread.join() - self._paused.unregister_all() - - def _run(self) -> None: - while not self._stop_event.is_set(): - if self._paused.value: - self._stop_event.wait(self._poll_interval_s) - continue - msg = self._client.connector.blocking_list_pop( - QueueEndpoints.task_execution(), side="LEFT", timeout_s=self._poll_interval_s - ) - if msg is not None: - self._client.connector.send( - QueueEndpoints.task_queue_changed(), MXQueueChangedMessage() - ) - self.execute(msg) - - def execute(self, msg: MXTaskExecutionMessage) -> None: - """Run a single task on `MxTasks`. Failures are logged and do not stop the queue.""" - if not MxTasks.is_task(msg.name): - logger.warning(f"Skipping queued task: {msg.name!r} is not a public MxTasks method") - return - logger.info(f"Running task {msg.name} with args={msg.args}, kwargs={msg.kwargs}") - try: - getattr(self._tasks, msg.name)(*msg.args, **msg.kwargs) - except Exception: # pylint: disable=broad-except - logger.exception(f"Task {msg.name} failed") diff --git a/tests/unit/test_aaredaq_tasks.py b/tests/unit/test_aaredaq_tasks.py index 025cccc..74c5b38 100644 --- a/tests/unit/test_aaredaq_tasks.py +++ b/tests/unit/test_aaredaq_tasks.py @@ -5,7 +5,7 @@ from aarecommon.math.coordinate import Coordinate from aarecommon.models.raster_grid import RasterGridRequest from aarecommon.models.rotation_scan import RotationScanRequest -from mx_bec.tasks import MxTasks +from mx_bec.tasks import MxTasks, Server @pytest.fixture @@ -15,7 +15,7 @@ def client(): @pytest.fixture def tasks(client): - return MxTasks(client) + return MxTasks[Server](client) @pytest.mark.parametrize( diff --git a/tests/unit/test_actors.py b/tests/unit/test_actors.py index 70e9730..23b7333 100644 --- a/tests/unit/test_actors.py +++ b/tests/unit/test_actors.py @@ -11,7 +11,7 @@ from mx_bec.actors.mx_automation import ( ) from mx_bec.endpoints import StateEndpoints from mx_bec.messages import MXMeasurementSequenceMessage -from mx_bec.service import MxTasks +from mx_bec.tasks import MxTasks, Server @pytest.fixture @@ -66,7 +66,7 @@ def test_unexpected_message_is_ignored(client): 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.tasks = MxTasks[Server](client) client.aare_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") diff --git a/tests/unit/test_change_state_task.py b/tests/unit/test_change_state_task.py index c74de02..2f3a5ea 100644 --- a/tests/unit/test_change_state_task.py +++ b/tests/unit/test_change_state_task.py @@ -3,19 +3,19 @@ from unittest.mock import MagicMock, patch import pytest from pxii_bec.macros.beamline_planner import BeamlineState -from mx_bec.tasks import MxTasks +from mx_bec.tasks import MxTasks, Server @pytest.fixture def tasks(): - tasks = MxTasks(MagicMock()) + tasks = MxTasks[Server](MagicMock()) tasks._planner = MagicMock() return tasks def test_planner_is_built_lazily_from_the_beamline_environment(monkeypatch): monkeypatch.delenv("BEAMLINE", raising=False) - tasks = MxTasks(MagicMock()) # must not need the beamline environment yet + tasks = MxTasks[Server](MagicMock()) # must not need the beamline environment yet env, devices, planner = MagicMock(), MagicMock(), MagicMock() with patch( "pxii_bec.scripts.init_beamline.init_beamline_environment", diff --git a/tests/unit/test_grid_scan_task.py b/tests/unit/test_grid_scan_task.py index dbe27de..77fe441 100644 --- a/tests/unit/test_grid_scan_task.py +++ b/tests/unit/test_grid_scan_task.py @@ -4,7 +4,7 @@ from unittest.mock import MagicMock, call import pytest from mx_bec.jfjoch import RasterScan -from mx_bec.tasks import MAX_GRID_SCAN_S, MxTasks +from mx_bec.tasks import MAX_GRID_SCAN_S, MxTasks, Server GRID = dict(n_x=4, n_y=3, step_x_um=50.0, step_y_um=40.0, exp_time_s=0.1, file_prefix="grid") BEAMLINE = dict( @@ -42,7 +42,7 @@ def test_run_grid_scan_sequence(client): sequence.attach_mock(jfjoch, "jfjoch") sequence.attach_mock(aerotech.trigger, "trigger") - MxTasks(client).run_grid_scan(**GRID, **BEAMLINE) + MxTasks[Server](client).run_grid_scan(**GRID, **BEAMLINE) config.grid_elem_count_x.set.assert_called_once_with(4) config.grid_elem_count_y.set.assert_called_once_with(3) @@ -84,7 +84,7 @@ def test_run_grid_scan_refuses_invalid_parameters(client): config.valid.get.return_value = False config.message.get.return_value = "too many elements" with pytest.raises(ValueError, match="too many elements"): - MxTasks(client).run_grid_scan(**GRID, **BEAMLINE) + MxTasks[Server](client).run_grid_scan(**GRID, **BEAMLINE) client.jfjoch.measure_raster.assert_not_called() client.devices.aerotech.trigger.assert_not_called() @@ -92,7 +92,7 @@ def test_run_grid_scan_refuses_invalid_parameters(client): def test_run_grid_scan_refuses_too_long_scans(client): too_long = {**GRID, "n_x": 100, "n_y": 100, "exp_time_s": MAX_GRID_SCAN_S / 100} with pytest.raises(ValueError, match="too long"): - MxTasks(client).run_grid_scan(**too_long, **BEAMLINE) + MxTasks[Server](client).run_grid_scan(**too_long, **BEAMLINE) client.devices.aerotech.gridscan_config.grid_elem_count_x.set.assert_not_called() diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py index ba2c6f0..4a65043 100644 --- a/tests/unit/test_service.py +++ b/tests/unit/test_service.py @@ -12,7 +12,8 @@ from mx_bec.messages import ( MXQueueChangedMessage, MXTaskExecutionMessage, ) -from mx_bec.service import AareBec, MxTasks +from mx_bec.service import AareBec +from mx_bec.tasks import MxTasks, RoleT, Server, task @pytest.fixture @@ -20,7 +21,10 @@ def service(monkeypatch): BECClient._reset_singleton() monkeypatch.setenv("CONFIG_REDIS_URL", "redis://dummy:6379") # the config client connects to the beamline redis on construction - with patch("mx_bec.service.AareConfigClient"): + # HAX: the service reads the sample spreadsheet straight from the beamline redis on + # construction (mx_bec/service.py lines 57-63), so that connection is patched out too. Remove + # this patch together with that hack. + with patch("mx_bec.service.AareConfigClient"), patch("mx_bec.service.Redis"): svc = AareBec(ServiceConfig(redis={"host": "dummy", "port": 6379}), ConnectorMock) yield svc BECClient._reset_singleton() @@ -110,7 +114,8 @@ NOT_TASKS = [ "_publish_optical_centering_done", # private method "_client", # private attribute "_busy_lock", - "task", # public, but the decorator rather than a task + "request", # public, but not a task + "execute", "is_task", "planner", # property ] @@ -129,8 +134,8 @@ def test_task_request_for_non_task_name_is_rejected(service, name): def test_tasks_are_exactly_the_decorated_methods(): - class Tasks(MxTasks): - @MxTasks.task + class Tasks(MxTasks[RoleT]): + @task def decorated(self): ... def plain(self): ... @@ -141,26 +146,26 @@ def test_tasks_are_exactly_the_decorated_methods(): assert all(not MxTasks.is_task(name) for name in NOT_TASKS) -class _FailingTasks(MxTasks): - @MxTasks.task +class _FailingTasks(MxTasks[RoleT]): + @task def boom(self): raise RuntimeError("boom") - @MxTasks.task + @task def fine(self): - return "ok" + return None def test_failed_task_pauses_the_queue_and_reraises(): client = MagicMock() with pytest.raises(RuntimeError, match="boom"): - _FailingTasks(client).boom() + _FailingTasks[Server](client).boom() client.task_queue.pause.assert_called_once() def test_successful_task_does_not_pause_the_queue(): client = MagicMock() - assert _FailingTasks(client).fine() == "ok" + assert _FailingTasks[Server](client).fine() is None client.task_queue.pause.assert_not_called() @@ -168,14 +173,14 @@ def test_failed_task_reraises_without_a_queue(): client = MagicMock() client.task_queue = None # the queue only exists once the service has started with pytest.raises(RuntimeError, match="boom"): - _FailingTasks(client).boom() + _FailingTasks[Server](client).boom() def test_failed_task_reraises_even_if_pausing_fails(): client = MagicMock() client.task_queue.pause.side_effect = ConnectionError("redis gone") with pytest.raises(RuntimeError, match="boom"): - _FailingTasks(client).boom() + _FailingTasks[Server](client).boom() @pytest.fixture @@ -201,7 +206,7 @@ def _optical_centering_done(sample_id: int, success: bool): 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) + MxTasks[Server](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)] @@ -210,7 +215,7 @@ def test_optical_centering_centres_at_each_angle_then_publishes_success(mock_cli 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) + MxTasks[Server](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 @@ -224,7 +229,7 @@ def test_optical_centering_centres_at_each_angle_then_publishes_success(mock_cli 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) + MxTasks[Server](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)] @@ -235,5 +240,5 @@ def test_optical_centering_publishes_failure_when_move_fails(mock_client): move.wait.side_effect = TimeoutError("smargon did not reach target") with pytest.raises(TimeoutError): - MxTasks(mock_client).run_optical_centering(sample_id=3) + MxTasks[Server](mock_client).run_optical_centering(sample_id=3) assert _published(mock_client) == [_optical_centering_done(3, success=False)] diff --git a/tests/unit/test_tasks.py b/tests/unit/test_tasks.py index 34eab6a..5021f52 100644 --- a/tests/unit/test_tasks.py +++ b/tests/unit/test_tasks.py @@ -8,7 +8,7 @@ from bec_lib.redis_connector import RedisConnector from mx_bec.endpoints import QueueEndpoints from mx_bec.messages import MXQueueChangedMessage, MXTaskExecutionMessage -from mx_bec.tasks import MxTaskQueue, MxTasks +from mx_bec.tasks import MxTaskQueue, RoleT, Server, TaskManager, task @pytest.fixture @@ -26,14 +26,30 @@ def client(connector): return client +class _Tasks(TaskManager[RoleT]): + """Records the calls of its one task on `calls`.""" + + calls: MagicMock + + @task + def run_optical_centering(self, sample_id: int) -> None: + self.calls.run_optical_centering(sample_id) + + def _publish_optical_centering_done(self, sample_id: int) -> None: + self.calls._publish_optical_centering_done(sample_id) + + @pytest.fixture def tasks(): - return MagicMock(spec=MxTasks) + """The recorder of the calls made to the tasks.""" + return MagicMock() @pytest.fixture def queue(client, tasks): - q = MxTaskQueue(client, tasks, poll_interval_s=0.05) + manager = _Tasks[Server](client) + manager.calls = tasks + q = MxTaskQueue(client, manager, poll_interval_s=0.05) yield q q.shutdown() @@ -95,7 +111,7 @@ def test_paused_flag_is_shared_through_redis(connector, queue): # another client (here: a second config value on the same endpoint) can pause the queue other = MagicMock() other.connector = connector - other_queue = MxTaskQueue(other, MagicMock(spec=MxTasks)) + other_queue = MxTaskQueue(other, _Tasks[Server](other)) try: assert not queue.paused other_queue.pause() @@ -109,7 +125,7 @@ def test_paused_flag_is_shared_through_redis(connector, queue): def test_queue_skips_non_task_names(connector, queue, tasks): connector.rpush(QueueEndpoints.task_execution(), _request("_publish_optical_centering_done", 1)) connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 2)) - with patch("mx_bec.tasks.logger") as logger: + with patch("mx_bec.tasks.core.logger") as logger: queue.start() _wait_for(lambda: tasks.run_optical_centering.call_count == 1) tasks.run_optical_centering.assert_called_once_with(2) @@ -121,7 +137,7 @@ def test_failed_task_is_logged_and_queue_continues(connector, queue, tasks): tasks.run_optical_centering.side_effect = [RuntimeError("boom"), None] connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 1)) connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 2)) - with patch("mx_bec.tasks.logger") as logger: + with patch("mx_bec.tasks.core.logger") as logger: queue.start() _wait_for(lambda: tasks.run_optical_centering.call_count == 2) logger.exception.assert_called_once() diff --git a/tests/unit/test_tasks_core.py b/tests/unit/test_tasks_core.py new file mode 100644 index 0000000..5789da4 --- /dev/null +++ b/tests/unit/test_tasks_core.py @@ -0,0 +1,198 @@ +from unittest.mock import MagicMock + +import pytest + +from mx_bec.endpoints import QueueEndpoints, StateEndpoints +from mx_bec.messages import ( + MXMeasurementSequenceMessage, + MXQueueChangedMessage, + MXTaskExecutionMessage, +) +from mx_bec.tasks.core import ( + BoundTask, + Client, + MxSequenceUpdate, + RoleT, + Server, + TaskManager, + UnknownTask, + task, +) + + +class Tasks(TaskManager[RoleT]): + """Shaped like MxTasks: tasks use `self._client` and may return a state update.""" + + @task + def mount(self, dbid: int, reference: bool = False) -> MxSequenceUpdate: + """Mount a sample""" + self._client.aaredaq.mount_sample(dbid, reference=reference) + return ( + StateEndpoints.sample_mounted(), + MXMeasurementSequenceMessage(sample_id=dbid, success=True), + ) + + @task + def quiet(self) -> None: + self._client.aaredaq.quiet() + + @task + def nested(self, dbid: int) -> None: + self.mount(dbid) + + @task + def boom(self) -> None: + raise RuntimeError("boom") + + def plain(self): ... + + def _private(self): ... + + +@pytest.fixture +def client(): + return MagicMock() + + +@pytest.fixture +def server(client): + return Tasks[Server](client) + + +@pytest.fixture +def remote(client): + return Tasks[Client](client) + + +def test_role_classes(server, remote): + assert Tasks[Server] is Tasks[Server] + assert isinstance(server, Tasks) and isinstance(server, Server) + assert isinstance(remote, Tasks) and isinstance(remote, Client) + assert type(server).__name__ == "Tasks[Server]" + with pytest.raises(TypeError, match=r"Tasks\[Server\]"): + Tasks(MagicMock()) + with pytest.raises(TypeError, match="already has a role"): + Tasks[Server][Client] + + +def test_tasks_are_exactly_the_decorated_methods(): + assert Tasks.task_names() == ["mount", "quiet", "nested", "boom"] + assert Tasks[Server].task_names() == Tasks.task_names() + assert Tasks.is_task("mount") + assert not any(Tasks.is_task(name) for name in ("plain", "_private", "request", "nope")) + + class MoreTasks(Tasks[RoleT]): + @task + def extra(self) -> None: ... + + assert MoreTasks.is_task("extra") and MoreTasks.is_task("mount") + assert not Tasks.is_task("extra") + + +def test_task_metadata(server): + assert Tasks.mount.__doc__ == "Mount a sample" + assert isinstance(server.mount, BoundTask) + assert server.mount.__name__ == "mount" + assert server.mount.__doc__ == "Mount a sample" + + +def test_server_call_runs_the_task_and_publishes_its_state_update(server, client): + assert server.mount(3, reference=True) is None + client.aaredaq.mount_sample.assert_called_once_with(3, reference=True) + endpoint, msg = client.connector.set_and_publish.call_args.args + assert endpoint.endpoint == StateEndpoints.sample_mounted().endpoint + assert msg == MXMeasurementSequenceMessage(sample_id=3, success=True) + client.task_queue.pause.assert_not_called() + + +def test_server_call_without_state_update_publishes_nothing(server, client): + server.quiet() + client.aaredaq.quiet.assert_called_once_with() + client.connector.set_and_publish.assert_not_called() + + +def test_server_task_can_call_another_task(server, client): + server.nested(5) # must not deadlock on the task lock + client.aaredaq.mount_sample.assert_called_once_with(5, reference=False) + client.connector.set_and_publish.assert_called_once() + + +def test_server_call_through_the_class(server, client): + Tasks.mount(server, 4) + client.aaredaq.mount_sample.assert_called_once_with(4, reference=False) + + +def test_failed_task_pauses_the_queue_and_reraises(server, client): + with pytest.raises(RuntimeError, match="boom"): + server.boom() + client.task_queue.pause.assert_called_once() + client.connector.set_and_publish.assert_not_called() + + +def test_failed_task_reraises_without_a_queue(server, client): + client.task_queue = None # the queue only exists once the service has started + with pytest.raises(RuntimeError, match="boom"): + server.boom() + + +def test_failed_task_reraises_even_if_pausing_fails(server, client): + client.task_queue.pause.side_effect = ConnectionError("redis gone") + with pytest.raises(RuntimeError, match="boom"): + server.boom() + + +def test_server_execute_runs_the_task_of_a_message(server, client): + server.execute(MXTaskExecutionMessage(name="mount", args=(7,), kwargs={"reference": True})) + client.aaredaq.mount_sample.assert_called_once_with(7, reference=True) + with pytest.raises(UnknownTask, match="plain"): + server.execute(MXTaskExecutionMessage(name="plain", args=(), kwargs={})) + + +@pytest.mark.parametrize( + "request_task", + [ + lambda tasks: tasks.mount.request(3, reference=True), + lambda tasks: tasks.request("mount", 3, reference=True), + lambda tasks: tasks.request(tasks.mount, 3, reference=True), + lambda tasks: tasks.request(Tasks.mount, 3, reference=True), + ], +) +def test_server_request_queues_the_task(server, client, request_task): + request_task(server) + client.aaredaq.mount_sample.assert_not_called() + endpoint, msg = client.connector.rpush.call_args.args + assert endpoint.endpoint == QueueEndpoints.task_execution().endpoint + assert msg == MXTaskExecutionMessage(name="mount", args=(3,), kwargs={"reference": True}) + endpoint, msg = client.connector.send.call_args.args + assert endpoint.endpoint == QueueEndpoints.task_queue_changed().endpoint + assert isinstance(msg, MXQueueChangedMessage) + + +def test_request_of_unknown_task_is_rejected(server, remote, client): + for tasks in (server, remote): + with pytest.raises(UnknownTask): + tasks.request("plain") + client.connector.rpush.assert_not_called() + client.connector.xadd.assert_not_called() + + +@pytest.mark.parametrize( + "call", + [ + lambda tasks: tasks.mount(3, reference=True), + lambda tasks: tasks.mount.request(3, reference=True), + lambda tasks: tasks.request("mount", 3, reference=True), + lambda tasks: tasks.execute( + MXTaskExecutionMessage(name="mount", args=(3,), kwargs={"reference": True}) + ), + ], +) +def test_client_sends_a_task_request(remote, client, call): + call(remote) + client.aaredaq.mount_sample.assert_not_called() + client.connector.rpush.assert_not_called() + endpoint, payload = client.connector.xadd.call_args.args + assert endpoint.endpoint == QueueEndpoints.task_request().endpoint + assert payload == { + "data": MXTaskExecutionMessage(name="mount", args=(3,), kwargs={"reference": True}) + } -- 2.54.1 From 7656b45dcb654b372b2d38a47381d8e040122a77 Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 24 Nov 2026 11:09:39 +0100 Subject: [PATCH 40/46] fix: clean up stuff --- .../widgets/aare_bec/task_panel.py | 20 ---- mx_bec/optical_centering.py | 33 ------ mx_bec/tasks/__init__.py | 3 +- mx_bec/tasks/core.py | 5 +- mx_bec/tasks/mx_tasks.py | 34 +----- tests/unit/test_aaredaq_tasks.py | 24 ++++- tests/unit/test_actors.py | 39 ++----- tests/unit/test_grid_scan_task.py | 100 ------------------ tests/unit/test_service.py | 71 +------------ 9 files changed, 38 insertions(+), 291 deletions(-) delete mode 100644 tests/unit/test_grid_scan_task.py diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py index ae42bfb..74950fd 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -28,26 +28,6 @@ TASK_FORMS: dict[str, list[tuple[str, int | float | str | list[float]]]] = { "aaredaq_mount_sample": [("dbid", 0)], "run_optical_centering": [("sample_id", 0)], "cleanup_beamline": [], - # "run_grid_scan": [ - # ("n_x", 4), - # ("n_y", 3), - # ("step_x_um", 50.0), - # ("step_y_um", 50.0), - # ("exp_time_s", 0.1), - # ("file_prefix", "grid"), - # ("detector_distance_mm", 150.0), - # ("transmission", 0.1), - # ("energy_keV", 12.4), - # ("beam_center_x_pxl", 0.0), - # ("beam_center_y_pxl", 0.0), - # ("beam_size_x_mm", 0.02), - # ("beam_size_y_mm", 0.01), - # ("ring_current_mA", 400.0), - # ("flux_ph_s", 1e12), - # ("sample_temperature_K", 100.0), - # ("pgroup", "p16371"), - # ("sample_name", "unknown_sample"), - # ], # the AareDAQ-driven tasks; their bool/optional arguments keep their defaults here "aaredaq_raster_scan": [ ("n_x", 4), diff --git a/mx_bec/optical_centering.py b/mx_bec/optical_centering.py index 8bfad18..2cae007 100644 --- a/mx_bec/optical_centering.py +++ b/mx_bec/optical_centering.py @@ -2,7 +2,6 @@ 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 @@ -28,38 +27,6 @@ class OpticalPrediction: ) return prediction - 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""" - zoom = self._client.devices.scam_zoom - zoom.set(1) - if (target_px := self.get_target_point_px()) is None: - return None - logger.info(f"Target point prediction in px on camera image: {target_px}") - a = self._client.aare_config.camera.translation_factor_a - b = self._client.aare_config.camera.translation_factor_b - base_pixel_in_um = 1.0 / (b * np.exp(a * zoom.user_readback.get())) - adjusted_pixel_in_um = ( - base_pixel_in_um * self._client.aare_config.camera.lens_magnification_multiplier - ) - offset_predicted = ( - target_px.x * adjusted_pixel_in_um / 1000, - target_px.y * adjusted_pixel_in_um / 1000, - ) - logger.info(f"Target point offset in smargon coords predicted: {offset_predicted}") - return offset_predicted - def update_latest(self): latest = self.get_latest() logger.info("Updating latest prediction on sample info") diff --git a/mx_bec/tasks/__init__.py b/mx_bec/tasks/__init__.py index 619e363..e433b2f 100644 --- a/mx_bec/tasks/__init__.py +++ b/mx_bec/tasks/__init__.py @@ -12,10 +12,9 @@ from mx_bec.tasks.core import ( UnknownTask, task, ) -from mx_bec.tasks.mx_tasks import MAX_GRID_SCAN_S, MxTasks +from mx_bec.tasks.mx_tasks import MxTasks __all__ = [ - "MAX_GRID_SCAN_S", "BoundTask", "Client", "MxSequenceUpdate", diff --git a/mx_bec/tasks/core.py b/mx_bec/tasks/core.py index ec2a0d7..097377c 100644 --- a/mx_bec/tasks/core.py +++ b/mx_bec/tasks/core.py @@ -38,11 +38,12 @@ from mx_bec.messages import ( MXQueueChangedMessage, MXTaskExecutionMessage, ) -from mx_bec.service import AareBec if TYPE_CHECKING: from bec_lib.client import BECClient + from mx_bec.service import AareBec + logger = bec_logger.logger # What a task returns: a state to set and publish once it is done, or nothing. @@ -209,7 +210,7 @@ RoleT = TypeVar("RoleT", bound=Role) class TaskManager(Generic[RoleT]): """ Subclass this as `class MyTasks(TaskManager[RoleT])` and decorate methods with @task. - Instantiate as MyTasks[Server](service) or MyTasks[Client](bec_client). + Instantiate as MyTasks[Server](aare_bec_service) or MyTasks[Client](aare_bec_client). MyTasks[Role] builds (and caches) a real class whose MRO is (MyTasks[Role], Role, MyTasks, TaskManager, ...), so the role's hooks diff --git a/mx_bec/tasks/mx_tasks.py b/mx_bec/tasks/mx_tasks.py index 0029f1b..d72851a 100644 --- a/mx_bec/tasks/mx_tasks.py +++ b/mx_bec/tasks/mx_tasks.py @@ -4,14 +4,11 @@ from secrets import token_hex from typing import TYPE_CHECKING from aarecommon.math.coordinate import Coordinate, SmargonCoordinate -from aarecommon.models.raster_grid import ( - CompletedRasterGrid, # already imported in aaredaq.py - RasterGridRequest, -) +from aarecommon.models.raster_grid import CompletedRasterGrid # already imported in aaredaq.py +from aarecommon.models.raster_grid import RasterGridRequest from aarecommon.models.rotation_scan import RotationScanRequest from bec_lib.logger import bec_logger -from mx_bec.devices.smargopolo_smargon import Smargon from mx_bec.endpoints import StateEndpoints from mx_bec.math import smargon_nudge from mx_bec.messages import MXMeasurementSequenceMessage @@ -33,8 +30,6 @@ if TYPE_CHECKING: logger = bec_logger.logger -MAX_GRID_SCAN_S = 1200.0 # refuse grid scans expected to take longer than 20 min - class MxTasks(TaskManager[RoleT]): """The operations on mx beamlines which can be requested as tasks. Instantiate as @@ -63,31 +58,6 @@ class MxTasks(TaskManager[RoleT]): _, _, self._planner = init_beamline_environment() return self._planner - @task - def run_optical_centering_bec(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.""" - logger.info(f"Optical centering started for sample {sample_id}") - try: - smargon: Smargon = self._client.devices.smargon - aerotech = self._client.devices.aerotech - angles = self._client.aare_config.optical_centering.angles - logger.info(f"Centring at angles: {angles}") - for angle in angles: - logger.info(f"Aerotech {aerotech} u move to {angle} starting") - aerotech.u.set(angle).wait() - logger.info(f"Aerotech u move to {angle} done") - if (target := self._client.optical_prediction.get_target_point_offset_mm()) is None: - logger.warning("No target point obtained from AareLc") - return self._optical_centering_done_update(sample_id, success=False) - smargon.nudge_in_lab_frame(*target, omega_deg=angle) - except Exception: - logger.exception(f"Optical centering of sample {sample_id} failed") - raise - self._client.optical_prediction.update_latest() - return self._optical_centering_done_update(sample_id, success=True) - @task def run_optical_centering(self, sample_id: int): """warning: Updates the sample id to whatever you enter even if it's not the real one!""" diff --git a/tests/unit/test_aaredaq_tasks.py b/tests/unit/test_aaredaq_tasks.py index 74c5b38..5637ebf 100644 --- a/tests/unit/test_aaredaq_tasks.py +++ b/tests/unit/test_aaredaq_tasks.py @@ -1,16 +1,23 @@ from unittest.mock import MagicMock import pytest -from aarecommon.math.coordinate import Coordinate +from aarecommon.math.coordinate import Coordinate, SmargonCoordinate from aarecommon.models.raster_grid import RasterGridRequest from aarecommon.models.rotation_scan import RotationScanRequest +from mx_bec.math import smargon_nudge from mx_bec.tasks import MxTasks, Server +# where the mock smargon sits +SMARGON_POSITION = {"x": 1.0, "y": 2.0, "z": 3.0, "phi": 0.0, "chi": 0.0} + @pytest.fixture def client(): - return MagicMock() + client = MagicMock() + for axis, position in SMARGON_POSITION.items(): + getattr(client.devices.smargon, axis).get.return_value = position + return client @pytest.fixture @@ -40,6 +47,10 @@ def test_raster_scan_builds_request_from_flat_arguments(tasks, client): client.aaredaq.raster_scan.call_args.args[0], client.aaredaq.raster_scan.call_args.kwargs, ) + # without a top left corner, the grid is centred on the current smargon position: the corner + # is half the grid away, in the lab frame at the scan's omega + half_grid = Coordinate(x=4 * 0.05 / 2, y=3 * 0.04 / 2, z=0) + top_left = Coordinate(x=1.0, y=2.0, z=3.0) - smargon_nudge(0.0, 0.0, 12.0, half_grid) assert request == RasterGridRequest( n_x=4, n_y=3, @@ -47,11 +58,18 @@ def test_raster_scan_builds_request_from_flat_arguments(tasks, client): exp_time_s=0.1, omega_deg=12.0, dtz=150.0, - smargon_top_left=None, + smargon_top_left=SmargonCoordinate(sh_mm=top_left, chi_deg=0.0, phi_deg=0.0), ) assert kwargs == {"auto_center": False} +def test_raster_scan_uses_a_given_top_left_corner(tasks, client): + top_left = SmargonCoordinate(sh_mm=Coordinate(x=0.1, y=0.2, z=0.3), chi_deg=10.0, phi_deg=20.0) + tasks.aaredaq_raster_scan(1, 1, 0.05, 0.05, 0.1, smargon_top_left=top_left) + assert client.aaredaq.raster_scan.call_args.args[0].smargon_top_left == top_left + client.devices.smargon.x.get.assert_not_called() + + def test_raster_scan_passes_auto_center(tasks, client): tasks.aaredaq_raster_scan(1, 1, 0.05, 0.05, 0.1, auto_center=True) assert client.aaredaq.raster_scan.call_args.kwargs == {"auto_center": True} diff --git a/tests/unit/test_actors.py b/tests/unit/test_actors.py index 23b7333..3defbde 100644 --- a/tests/unit/test_actors.py +++ b/tests/unit/test_actors.py @@ -5,13 +5,9 @@ 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.actors.mx_automation import OnSampleMountedRunOpticalCentering from mx_bec.endpoints import StateEndpoints -from mx_bec.messages import MXMeasurementSequenceMessage -from mx_bec.tasks import MxTasks, Server +from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskExecutionMessage @pytest.fixture @@ -42,44 +38,25 @@ def test_actor_subscribes_to_its_milestone(client): def test_successful_milestone_triggers_next_step(client): + client.sample_info.sample_id = 42 # the actor takes the sample from the service 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) + client.add_task_to_queue.assert_called_once_with( + MXTaskExecutionMessage(name="run_optical_centering", args=(42,), kwargs={}) + ) 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.add_task_to_queue.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.add_task_to_queue.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[Server](client) - client.aare_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_grid_scan_task.py b/tests/unit/test_grid_scan_task.py deleted file mode 100644 index 77fe441..0000000 --- a/tests/unit/test_grid_scan_task.py +++ /dev/null @@ -1,100 +0,0 @@ -from types import SimpleNamespace -from unittest.mock import MagicMock, call - -import pytest - -from mx_bec.jfjoch import RasterScan -from mx_bec.tasks import MAX_GRID_SCAN_S, MxTasks, Server - -GRID = dict(n_x=4, n_y=3, step_x_um=50.0, step_y_um=40.0, exp_time_s=0.1, file_prefix="grid") -BEAMLINE = dict( - detector_distance_mm=150.0, - transmission=0.5, - energy_keV=12.658, - beam_center_x_pxl=1000.0, - beam_center_y_pxl=1100.0, - beam_size_x_mm=0.02, - beam_size_y_mm=0.01, - ring_current_mA=400.0, - flux_ph_s=1e12, - sample_temperature_K=100.0, -) - - -@pytest.fixture -def client(): - client = MagicMock() - aerotech = client.devices.aerotech - aerotech.gridscan_config.valid.get.return_value = True - aerotech.u.get.return_value = 12.0 - # a plain result so that logging it doesn't record extra mock calls - client.jfjoch.wait_till_done.return_value = SimpleNamespace( - file_prefix="p16371/raw/raster/grid", images=[1, 2, 3] - ) - return client - - -def test_run_grid_scan_sequence(client): - aerotech, jfjoch = client.devices.aerotech, client.jfjoch - config = aerotech.gridscan_config - # one mock to record the order across devices and jfjoch - sequence = MagicMock() - sequence.attach_mock(jfjoch, "jfjoch") - sequence.attach_mock(aerotech.trigger, "trigger") - - MxTasks[Server](client).run_grid_scan(**GRID, **BEAMLINE) - - config.grid_elem_count_x.set.assert_called_once_with(4) - config.grid_elem_count_y.set.assert_called_once_with(3) - config.grid_elem_size_x_um.set.assert_called_once_with(50.0) - config.grid_elem_size_y_um.set.assert_called_once_with(40.0) - config.time_per_element_sec.set.assert_called_once_with(0.1) - assert config.time_per_element_sec.set.return_value.wait.called - - scan = jfjoch.measure_raster.call_args.args[0] - assert scan == RasterScan( - n_x=4, - n_y=3, - step_x_mm=0.05, - step_y_mm=0.04, - omega_deg=12.0, - exp_time_s=0.1, - detector_distance_mm=150.0, - transmission=0.5, - file_prefix="grid", - energy_keV=12.658, - beam_center_pxl=(1000.0, 1100.0), - beam_size_mm=(0.02, 0.01), - ring_current_mA=400.0, - flux_ph_s=1e12, - sample_temperature_K=100.0, - ) - # JFJoch is armed before the Aerotech moves, and the result is collected afterwards - assert sequence.mock_calls == [ - call.jfjoch.measure_raster(scan), - call.jfjoch.wait_till_running(timeout_s=60), - call.trigger(), - call.trigger().wait(), - call.jfjoch.wait_till_done(timeout_s=60), - ] - - -def test_run_grid_scan_refuses_invalid_parameters(client): - config = client.devices.aerotech.gridscan_config - config.valid.get.return_value = False - config.message.get.return_value = "too many elements" - with pytest.raises(ValueError, match="too many elements"): - MxTasks[Server](client).run_grid_scan(**GRID, **BEAMLINE) - client.jfjoch.measure_raster.assert_not_called() - client.devices.aerotech.trigger.assert_not_called() - - -def test_run_grid_scan_refuses_too_long_scans(client): - too_long = {**GRID, "n_x": 100, "n_y": 100, "exp_time_s": MAX_GRID_SCAN_S / 100} - with pytest.raises(ValueError, match="too long"): - MxTasks[Server](client).run_grid_scan(**too_long, **BEAMLINE) - client.devices.aerotech.gridscan_config.grid_elem_count_x.set.assert_not_called() - - -def test_run_grid_scan_is_a_task(): - assert MxTasks.is_task("run_grid_scan") diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py index 4a65043..864ed10 100644 --- a/tests/unit/test_service.py +++ b/tests/unit/test_service.py @@ -1,4 +1,4 @@ -from unittest.mock import MagicMock, call, patch +from unittest.mock import MagicMock, patch import pytest from bec_lib.client import BECClient @@ -6,12 +6,8 @@ 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 QueueEndpoints, StateEndpoints -from mx_bec.messages import ( - MXMeasurementSequenceMessage, - MXQueueChangedMessage, - MXTaskExecutionMessage, -) +from mx_bec.endpoints import QueueEndpoints +from mx_bec.messages import MXQueueChangedMessage, MXTaskExecutionMessage from mx_bec.service import AareBec from mx_bec.tasks import MxTasks, RoleT, Server, task @@ -181,64 +177,3 @@ def test_failed_task_reraises_even_if_pausing_fails(): client.task_queue.pause.side_effect = ConnectionError("redis gone") with pytest.raises(RuntimeError, match="boom"): _FailingTasks[Server](client).boom() - - -@pytest.fixture -def mock_client(): - client = MagicMock() - client.aare_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[Server](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[Server](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[Server](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[Server](mock_client).run_optical_centering(sample_id=3) - assert _published(mock_client) == [_optical_centering_done(3, success=False)] -- 2.54.1 From 1640ef96571642c098c13d467c25f7b0fa7cfbec Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 24 Nov 2026 11:14:06 +0100 Subject: [PATCH 41/46] fix: use coverage rather than pytest-cov --- .gitea/workflows/ci.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 908f0d2..27ffb58 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -100,4 +100,9 @@ jobs: - name: Run Pytest with Coverage id: coverage - run: pytest --random-order --cov=./mx_bec --cov-config=./mx_bec/pyproject.toml --cov-branch --cov-report=xml --no-cov-on-fail ./mx_bec/tests/ || test $? -eq 5 + run: | + if coverage run --rcfile=./mx_bec/pyproject.toml --branch --source=./mx_bec -m pytest --random-order ./mx_bec/tests/; then + coverage xml --rcfile=./mx_bec/pyproject.toml + else + test $? -eq 5 + fi -- 2.54.1 From f6271b06e80d552789f6a3a44c4cbe9a7bc46eac Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 24 Nov 2026 11:40:12 +0100 Subject: [PATCH 42/46] fix: tidy math module --- mx_bec/actors/core.py | 82 +++- mx_bec/actors/mx_automation.py | 131 ++----- mx_bec/math.py | 130 ------- mx_bec/sample_info.py | 24 +- mx_bec/self_driving.py | 638 ------------------------------- mx_bec/tasks/mx_tasks.py | 30 +- tests/unit/test_aaredaq_tasks.py | 2 +- 7 files changed, 136 insertions(+), 901 deletions(-) delete mode 100644 mx_bec/math.py delete mode 100644 mx_bec/self_driving.py diff --git a/mx_bec/actors/core.py b/mx_bec/actors/core.py index a32e1a9..9f3407e 100644 --- a/mx_bec/actors/core.py +++ b/mx_bec/actors/core.py @@ -1,5 +1,6 @@ from __future__ import annotations +import secrets from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Any, ClassVar @@ -7,8 +8,9 @@ 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 +from mx_bec.decisions import StrategyConfig, plan_rotation +from mx_bec.endpoints import ActorEndpoints, StateEndpoints +from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskExecutionMessage if TYPE_CHECKING: from bec_lib.messages import BoolConfigDefaultFalse @@ -23,14 +25,18 @@ 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. + (which must carry `MXMeasurementSequenceMessage`s), and implement `action`. Whenever a + milestone message arrives it is stored in `last_message` and the action table is evaluated. + By default the action runs if the step succeeded for the sample which is currently loaded; + override `condition` to change that. """ config_key: ClassVar[str] """Unique key used to build this actor's config endpoints, e.g. "optical_centering".""" + strategy: ClassVar[StrategyConfig] = StrategyConfig() + """Thresholds and limits for planning data collections.""" + 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} @@ -55,9 +61,17 @@ class MXAutomationActor(SubscriptionActor, ABC): 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.""" + """Whether `action` should run; evaluated after every milestone message. By default: the + step succeeded, and for the sample which is currently loaded.""" + msg = self.last_message + if msg is None or not msg.success: + return False + info = client.sample_info + if info is None or info.sample_id != msg.sample_id: + logger.warning(f"{type(self).__name__}: message for sample {msg.sample_id} is stale") + return False + return True @abstractmethod def action(self, client: AareBec) -> None: @@ -67,3 +81,57 @@ class MXAutomationActor(SubscriptionActor, ABC): assert self.last_message is not None self.last_message = None self.action(client) + + # ---- helpers for the actions ---- + + @staticmethod + def queue(client: AareBec, name: str, *args: Any) -> None: + """Append a task to the task queue.""" + client.add_task_to_queue(MXTaskExecutionMessage(name=name, args=args, kwargs={})) + + @staticmethod + def finish(client: AareBec, sample_id: int, *, success: bool, reason: str) -> None: + """Publish the `sample_done` milestone: nothing more will be done with this sample.""" + logger.info(f"Sample {sample_id} finished (success={success}): {reason}") + client.connector.set_and_publish( + StateEndpoints.sample_done(), + MXMeasurementSequenceMessage(sample_id=sample_id, success=success), + ) + + def queue_collection( + self, + client: AareBec, + position_index: int, + *, + chi_values: list[float] | tuple[float, ...] = (0.0,), + dose_fraction: float = 1.0, + reason: str, + ) -> bool: + """Plan a rotation dataset at a spot of the sample's grid analysis and queue it. Finishes + the sample as failed, and returns False, if no dataset can be planned there.""" + # pyright: ignore[reportMissingImports] + from pxii_bec.macros.flux_macros import bpm2flux + + info = client.sample_info + assert info is not None, "No sample loaded" + assert info.grid_analysis is not None, "No grid analysed" + prefix = f"S{info.sample_id}_{secrets.token_hex(3)}" + _, self.strategy.beam.flux_ph_s = bpm2flux() + try: + plan = plan_rotation( + info.grid_analysis, + position_index, + self.strategy, + file_prefix=prefix, + chi_values=chi_values, + dose_fraction=dose_fraction, + reason=reason, + ) + except ValueError as e: + self.finish(client, info.sample_id, success=False, reason=f"cannot plan: {e}") + return False + if position_index not in info.positions_used: + info.positions_used.append(position_index) + logger.info(f"Queue collection for sample {info.sample_id}: {plan}") + self.queue(client, "collect_dataset", info.sample_id, plan.model_dump()) + return True diff --git a/mx_bec/actors/mx_automation.py b/mx_bec/actors/mx_automation.py index fc74089..490d3b2 100644 --- a/mx_bec/actors/mx_automation.py +++ b/mx_bec/actors/mx_automation.py @@ -5,35 +5,31 @@ are stand-ins for now: they log and immediately publish the next milestone, so t exercised end to end on the simulated beamline before the real procedures exist. """ -import secrets from datetime import date from time import sleep -from typing import Any, ClassVar from aarelcinfer_client.models import DetectionModel from bec_lib.endpoints import EndpointInfo from bec_lib.logger import bec_logger from pxii_bec.macros.calculator import calc_scam_microns -from pxii_bec.macros.flux_macros import bpm2flux from mx_bec.actors.core import MXAutomationActor +from mx_bec.decisions import ( + Action, + analyse_grid, + assess_collection, + decide_followup, + gridscan_calculation, + gridscan_strategy_from_optical, + mock_grid_calculation, +) from mx_bec.endpoints import QueueEndpoints, StateEndpoints -from mx_bec.math import gridscan_calculation, gridscan_strategy_from_optical, mock_grid_calculation from mx_bec.messages import ( MXMeasurementSequenceMessage, MXQueueChangedMessage, MXSampleExecutionMessage, MXTaskExecutionMessage, ) -from mx_bec.self_driving import ( - Action, - SelfDrivingRecord, - StrategyConfig, - analyse_grid, - assess_collection, - decide_followup, - plan_rotation, -) from mx_bec.service import AareBec logger = bec_logger.logger @@ -155,76 +151,7 @@ class OnSampleDoneLoadNext(MXAutomationActor): ) -class SelfDrivingActor(MXAutomationActor): - """Shared helpers. Abstract: subclasses set ``config_key`` and implement ``action``.""" - - strategy: ClassVar[StrategyConfig] = StrategyConfig() - - def condition(self, client: AareBec) -> bool: - msg = self.last_message - if msg is None or not msg.success: - return False - info = client.sample_info - if info is None or info.sample_id != msg.sample_id: - logger.warning(f"{type(self).__name__}: message for sample {msg.sample_id} is stale") - return False - return True - - @staticmethod - def record(client: AareBec) -> SelfDrivingRecord: - info = client.sample_info - assert info is not None, "No sample loaded" - if info.self_driving is None: - info.self_driving = SelfDrivingRecord() - return info.self_driving - - @staticmethod - def queue(client: AareBec, name: str, *args: Any) -> None: - client.add_task_to_queue(MXTaskExecutionMessage(name=name, args=args, kwargs={})) - - @staticmethod - def finish(client: AareBec, sample_id: int, *, success: bool, reason: str) -> None: - logger.info(f"Self-driving: sample {sample_id} finished (success={success}): {reason}") - client.connector.set_and_publish( - StateEndpoints.sample_done(), - MXMeasurementSequenceMessage(sample_id=sample_id, success=success), - ) - - def queue_collection( - self, - client: AareBec, - record: SelfDrivingRecord, - sample_id: int, - position_index: int, - *, - chi_values: list[float] | tuple[float, ...] = (0.0,), - dose_fraction: float = 1.0, - reason: str, - ) -> bool: - assert record.analysis is not None - prefix = f"S{sample_id}_{secrets.token_hex(3)}" - _, self.strategy.beam.flux_ph_s = bpm2flux() - try: - plan = plan_rotation( - record.analysis, - position_index, - self.strategy, - file_prefix=prefix, - chi_values=chi_values, - dose_fraction=dose_fraction, - reason=reason, - ) - except ValueError as e: - self.finish(client, sample_id, success=False, reason=f"cannot plan: {e}") - return False - if position_index not in record.positions_used: - record.positions_used.append(position_index) - logger.info(f"Self-driving: queue collection for sample {sample_id}: {plan}") - self.queue(client, "collect_dataset", sample_id, plan.model_dump()) - return True - - -class OnXrayCenteringDonePlanCollection(SelfDrivingActor): +class OnXrayCenteringDonePlanCollection(MXAutomationActor): """Analyse the grid with the Rugnux/Jungfraujoch per-cell results and queue the first dataset.""" config_key = "self_driving_collect_after_grid" @@ -241,15 +168,12 @@ class OnXrayCenteringDonePlanCollection(SelfDrivingActor): self.finish(client, sample_id, success=False, reason="no raster results stored") return - record = self.record(client) - record.raster_strategy = dict(raster.strategy) - record.analysis = analyse_grid(raster.images, raster.geometry, self.strategy) + analysis = info.grid_analysis = analyse_grid(raster.images, raster.geometry, self.strategy) # A new grid has new coordinates: spots from an earlier grid no longer apply. # ASSUMPTION: the raster leaves the smargon at its start position (cell 0, 0). - record.positions_used = [] - record.current_offset_mm = (0.0, 0.0) + info.positions_used = [] + info.current_offset_mm = (0.0, 0.0) - analysis = record.analysis logger.info( f"Self-driving: grid for sample {sample_id}: {analysis.n_hits}/{analysis.n_images} " f"hits, {len(analysis.regions)} crystal(s), {len(analysis.positions)} spot(s)" @@ -262,14 +186,14 @@ class OnXrayCenteringDonePlanCollection(SelfDrivingActor): if cfg.anomalous: chis = cfg.anomalous_chi_deg if len(chis) > 1: - record.chi_sweeps_done += 1 + info.chi_sweeps_done += 1 reason = "anomalous: low-dose multi-chi" else: chis, reason = (0.0,), "best spot from grid" - self.queue_collection(client, record, sample_id, 0, chi_values=chis, reason=reason) + self.queue_collection(client, 0, chi_values=chis, reason=reason) -class OnRotationDoneDecideFollowUp(SelfDrivingActor): +class OnRotationDoneDecideFollowUp(MXAutomationActor): """Assess the last dataset and queue a follow-up, or finish the sample.""" config_key = "self_driving_followup_after_rotation" @@ -281,33 +205,32 @@ class OnRotationDoneDecideFollowUp(SelfDrivingActor): info = client.sample_info assert info is not None, "No sample loaded" sample_id = info.sample_id - record = self.record(client) - if not record.collections: + if not info.collections: self.finish(client, sample_id, success=False, reason="rotation_done without a record") return - latest = record.collections[-1] + latest = info.collections[-1] latest.assessment = assess_collection(latest, self.strategy) - decision = decide_followup(latest.assessment, record, self.strategy) + decision = decide_followup(latest.assessment, info, self.strategy) logger.info( f"Self-driving: sample {sample_id} issues={[i.value for i in latest.assessment.issues]}" f" -> {decision.action.value}: {decision.reason}" ) if decision.action is Action.FINISH: - usable = any(c.assessment and c.assessment.usable for c in record.collections) + usable = any(c.assessment and c.assessment.usable for c in info.collections) self.finish(client, sample_id, success=usable, reason=decision.reason) return - record.followups += 1 + info.followups += 1 if decision.action is Action.RECENTRE: - if record.raster_strategy is None: + if info.raster is None: self.finish(client, sample_id, success=False, reason="no raster to repeat") return - record.recentres += 1 - strategy = dict(record.raster_strategy) + info.recentres += 1 + strategy = dict(info.raster.strategy) strategy["file_prefix"] = ( - f"{strategy.get('file_prefix') or 'raster'}_rc{record.recentres}" + f"{strategy.get('file_prefix') or 'raster'}_rc{info.recentres}" ) # Back to the original raster start so the repeat grid covers the same area. self.queue(client, "move_to_grid_offset", sample_id, 0.0, 0.0) @@ -316,11 +239,9 @@ class OnRotationDoneDecideFollowUp(SelfDrivingActor): assert decision.position_index is not None if decision.action is Action.CHI_SWEEP: - record.chi_sweeps_done += 1 + info.chi_sweeps_done += 1 self.queue_collection( client, - record, - sample_id, decision.position_index, chi_values=decision.chi_values, dose_fraction=decision.dose_fraction, diff --git a/mx_bec/math.py b/mx_bec/math.py deleted file mode 100644 index db76ac7..0000000 --- a/mx_bec/math.py +++ /dev/null @@ -1,130 +0,0 @@ -import secrets - -import numpy as np -from aarecommon.math.coordinate import Coordinate -from bec_lib.logger import bec_logger -from pxii_bec.macros.calculator import calc_scam_microns - -from mx_bec.sample_info import OpticalCenteringResults - -logger = bec_logger.logger - - -def smargon_nudge( - phi_deg: float, chi_deg: float, omega_deg: float, nudge_vector: Coordinate -) -> Coordinate: - """Translate a relative movement of the smargon from lab frame to smargon frame. - Add the result of this to the smargon's current position to get the new position.""" - phi = np.radians(np.around(phi_deg, decimals=1)) - chi = np.radians(np.around(chi_deg, decimals=1)) - omega = np.radians(np.around(omega_deg, decimals=1)) - - offset = Coordinate() - co = np.cos(omega) - so = np.sin(omega) - cp = np.cos(phi) - sp = np.sin(phi) - cc = np.cos(chi) - sc = np.sin(chi) - - offset.x = ( - -nudge_vector.z * co * sp - - nudge_vector.y * so * sp - + nudge_vector.x * cp * sc - - nudge_vector.y * co * cc * cp - + nudge_vector.z * so * cc * cp - ) - offset.y = ( - -nudge_vector.z * co * cp - - nudge_vector.y * so * cp - - nudge_vector.x * sc * sp - + nudge_vector.y * co * cc * sp - - nudge_vector.z * so * cc * sp - ) - offset.z = -nudge_vector.x * cc - nudge_vector.y * co * sc + nudge_vector.z * so * sc - return offset - - -def mock_grid_calculation(): - logger.info("calculating mock grid given no optical results ...") - n_x = 10 - n_y = 10 - step_x_mm = 0.05 - step_y_mm = 0.05 - strategy = { - "n_x": n_x, - "n_y": n_y, - "step_x_mm": step_x_mm, - "step_y_mm": step_y_mm, - "exp_time_s": 0.05, - "omega_deg": 0.0, - "file_prefix": f"AareBecTestGridScan_{secrets.token_hex(6)}", - "dtz": 250, - "transmission": 0.2, - } - return strategy - - -def gridscan_strategy_from_optical( - optical_results: OpticalCenteringResults | None, - step_x_um: float, - step_y_um: float, - margin: float, - exp_time_s: float, - dtz_mm: float, -): - if optical_results is None or len(boxes := optical_results.prediction.boxes) == 0: - return mock_grid_calculation() - box_data = {box.label: ((box.x1, box.y1), (box.x2, box.y2)) for box in boxes} - logger.info(f"got detection boxes: {box_data}") - box_corners = None - for label_option in ["loop_face", "loop_all"]: - if label_option in box_data: - box_corners = box_data[label_option] - logger.info(f"using best available box: {label_option}") - break - if box_corners is None: - return mock_grid_calculation() - else: - file_prefix = f"AareBecTestGridScan_{secrets.token_hex(6)}" - return gridscan_calculation( - box_corners[0], - box_corners[1], - step_x_um / 1000, - step_y_um / 1000, - margin, - file_prefix, - exp_time_s, - dtz_mm, - ) - - -def gridscan_calculation( - x1_y1: tuple[float, float], - x2_y2: tuple[float, float], - size_x_mm: float, - size_y_mm: float, - margin: float, - file_prefix: str, - exp_time_s: float, - dtz_mm: float, -): - """calculate a gridscan from box coordinates and params. needs omega added later.""" - box_x_pixels = abs(x1_y1[0] - x2_y2[0]) - box_y_pixels = abs(x1_y1[1] - x2_y2[1]) - logger.info(f"{box_x_pixels=}, {box_y_pixels=}") - box_x_microns = calc_scam_microns(box_x_pixels, zoom=400) - box_y_microns = calc_scam_microns(box_y_pixels, zoom=400) - logger.info(f"{box_x_microns=}, {box_y_microns=}") - logger.info(f"adding margin to detection boxes of {margin}x") - n_x = int(box_x_microns / 1000 / size_x_mm * margin) - n_y = int(box_x_microns / 1000 / size_y_mm * margin) - return { - "n_x": n_x, - "n_y": n_y, - "step_x_mm": size_x_mm, - "step_y_mm": size_y_mm, - "exp_time_s": exp_time_s, - "file_prefix": file_prefix, - "dtz": dtz_mm, - } diff --git a/mx_bec/sample_info.py b/mx_bec/sample_info.py index 43eb21b..ecd5912 100644 --- a/mx_bec/sample_info.py +++ b/mx_bec/sample_info.py @@ -5,7 +5,7 @@ import time from aarelcinfer_client.models import LatestPredictionModel from pydantic import BaseModel, ConfigDict, Field -from mx_bec.self_driving import RasterRecord, SelfDrivingRecord +from mx_bec.decisions import CollectionRecord, GridAnalysis, RasterRecord class OpticalCenteringResults(BaseModel): @@ -24,4 +24,24 @@ class SampleInfo(BaseModel): sample_id: int optical_centering_results: OpticalCenteringResults | None = None raster: RasterRecord | None = None - self_driving: SelfDrivingRecord | None = None + """The latest raster scan: its parameters (for a repeat), geometry and per-image results.""" + grid_analysis: GridAnalysis | None = None + """Crystals and collection spots found in `raster`.""" + current_offset_mm: tuple[float, float] = (0.0, 0.0) + """Where the sample sits relative to the raster start, in the raster plane.""" + positions_used: list[int] = [] + """Indices of the `grid_analysis` spots which data has been collected at.""" + collections: list[CollectionRecord] = [] + """Every rotation dataset collected so far, with its plan and assessment.""" + chi_sweeps_done: int = 0 + recentres: int = 0 + followups: int = 0 + + def next_free_position(self) -> int | None: + """Index of the best `grid_analysis` spot not collected at yet, if any is left.""" + if self.grid_analysis is None: + return None + for i in range(len(self.grid_analysis.positions)): + if i not in self.positions_used: + return i + return None diff --git a/mx_bec/self_driving.py b/mx_bec/self_driving.py deleted file mode 100644 index 405c261..0000000 --- a/mx_bec/self_driving.py +++ /dev/null @@ -1,638 +0,0 @@ -"""Decision logic for the self-driving MX sequence. - - grid scan -> analyse_grid -> plan_rotation -> collect_dataset -> assess_collection - -> decide_followup -> (re-raster | new position | chi sweep | finish) - -Everything here is pure: pydantic models and functions, no BEC, Redis or device access. The -actors in ``mx_bec.actors.self_driving`` call these functions, and the same functions can be -replayed offline against archived Jungfraujoch results to tune thresholds. - -Per-image inputs are duck-typed against ``jfjoch_client.models.ScanResultImagesInner`` -(``number``, ``nx``, ``ny``, ``angle``, ``spots``, ``spots_indexed``, ``ice``, ``res``, -``latt_count``, ``spindle_blind``), so plain objects or the jfjoch models both work. -""" - -from __future__ import annotations - -import math -import statistics -from collections.abc import Iterable, Sequence -from enum import Enum -from typing import Any - -from aarecommon.models.raster_grid import CompletedRasterGridElem -from bec_lib.logger import bec_logger -from pydantic import BaseModel, ConfigDict, Field - -HC_KEV_A = 12.398419843320026 # keV * Angstrom - - -logger = bec_logger.logger - - -# -------------------------------------------------------------------------------------------- -# Configuration -# -------------------------------------------------------------------------------------------- - - -class BeamState(BaseModel): - """Beam at the sample. ``flux_ph_s`` is at transmission 1.""" - - energy_keV: float = Field(12.4, gt=0) - flux_ph_s: float | None = Field(None, gt=0, description="Must be set; no dose plan without it") - beam_size_um: tuple[float, float] = (25.0, 25.0) - - @property - def wavelength_A(self) -> float: - return HC_KEV_A / self.energy_keV - - -class StrategyConfig(BaseModel): - """Every threshold the actors use. Defaults are starting points for the replay study.""" - - # grid analysis - min_spots_hit: int = Field(10, description="Spots per image for a cell to count as a hit") - ice_threshold: float = Field(1.5, description="jfjoch 'ice' ratio above which a cell is icy") - ice_penalty: float = 0.5 - multi_lattice_penalty: float = 0.5 - reference_res_A: float = Field(2.0, description="Resolution at which the score factor is 1") - max_positions: int = 4 - min_spot_separation_mm: float = Field(0.04, description="Beam size plus dose halo") - min_position_score_fraction: float = Field(0.3, description="Relative to the best cell") - - # rotation plan - beam: BeamState = BeamState() - dose_MGy_per_A: float = Field(5.0, description="Dose budget = this x target resolution") - photons_per_um2_per_Gy_12p4keV: float = Field( - 2000.0, - description="Rule-of-thumb fluence per Gy at 12.4 keV, scaled by E^2; replace with " - "RADDOSE-3D when the crystal model is available", - ) - total_rotation_deg: float = 360.0 - oscillation_deg: float = 0.1 - exp_time_s: float = 0.005 - min_transmission: float = 0.001 - resolution_margin: float = Field(0.9, description="Aim this factor beyond the grid estimate") - default_res_A: float = 2.5 - best_res_limit_A: float = 0.8 - detector_radius_mm: float = Field(150.0, description="Beam centre to nearest detector edge") - min_distance_mm: float = 100.0 - max_distance_mm: float = 1000.0 - - # anomalous: low-dose multi-chi from the start - anomalous: bool = False - anomalous_chi_deg: tuple[float, ...] = (0.0, 15.0, 30.0) - - # assessment - n_wedges: int = 10 - lost_ratio: float = Field(0.3, description="Wedge spots below this x previous max = lost") - damage_res_increase: float = Field(0.15, description="Relative d_min loss first->last wedge") - min_indexed_spots: int = 10 - min_indexed_fraction: float = 0.5 - spindle_blind_threshold: float = Field(0.5, description="jfjoch: >= 0.5 engage recovery") - treat_unassessed_blind_as_blind: bool = Field( - True, description="jfjoch: an absent spindle_blind must be treated as above threshold" - ) - low_symmetry_bravais: frozenset[str] = frozenset({"aP", "mP", "mC"}) - - # follow-up policy - max_followups: int = 3 - max_recentres: int = 1 - max_chi_sweeps: int = 1 - chi_offset_deg: float = 30.0 - damage_dose_fraction: float = 0.5 - same_position_dose_fraction: float = Field( - 0.3, description="Extra dose allowed when a chi sweep must reuse a burnt position" - ) - - -# -------------------------------------------------------------------------------------------- -# Grid analysis -# -------------------------------------------------------------------------------------------- - - -class GridGeometry(BaseModel): - """Raster layout. Cell (0, 0) sits at the raster start position (``smargon_top_left``).""" - - n_x: int = Field(ge=1) - n_y: int = Field(ge=1) - step_x_mm: float - step_y_mm: float - omega_deg: float = 0.0 - snake: bool = True - - def offset_mm(self, ix: int, iy: int) -> tuple[float, float]: - return ix * self.step_x_mm, iy * self.step_y_mm - - -class Cell(BaseModel): - model_config = ConfigDict(frozen=True) - - ix: int - iy: int - spots: int - spots_indexed: int | None = None - res_A: float | None = None - ice: float | None = None - lattices: int | None = None - score: float = 0.0 - - -class CrystalRegion(BaseModel): - cells: list[Cell] - best: Cell - extent_x_mm: float - extent_y_mm: float - median_res_A: float | None - max_lattices: int - - -class GridAnalysis(BaseModel): - geometry: GridGeometry - n_images: int - n_hits: int - regions: list[CrystalRegion] - positions: list[Cell] = Field(description="Ranked collection spots, best first") - - def position_offset_mm(self, index: int) -> tuple[float, float]: - cell = self.positions[index] - return self.geometry.offset_mm(cell.ix, cell.iy) - - def position_res_A(self, index: int) -> float | None: - cell = self.positions[index] - if cell.res_A: - return cell.res_A - for region in self.regions: - if cell in region.cells: - return region.median_res_A - return None - - -def _cell_index(img: Any, geom: GridGeometry) -> tuple[int, int]: - nx, ny = getattr(img, "nx", None), getattr(img, "ny", None) - if nx is not None and ny is not None: - return int(nx), int(ny) - row, col = divmod(int(img.number), geom.n_x) - if geom.snake and row % 2: - col = geom.n_x - 1 - col - return col, row - - -def cell_score(img: Any, cfg: StrategyConfig) -> float: - """Indexed spots weighted for resolution, penalised for ice and extra lattices.""" - spots = img.spots or 0 - indexed = getattr(img, "spots_indexed", None) - base = float(spots) if indexed is None else indexed + 0.25 * max(spots - indexed, 0) - ice = getattr(img, "ice", None) - if ice is not None and ice > cfg.ice_threshold: - base *= cfg.ice_penalty - lattices = getattr(img, "latt_count", None) - if lattices is not None and lattices > 1: - base *= cfg.multi_lattice_penalty - res = getattr(img, "res", None) - if res: - base *= min(2.0, max(0.5, cfg.reference_res_A / res)) - return base - - -def _regions(cells: dict[tuple[int, int], Cell]) -> list[list[Cell]]: - """8-connected components of hit cells.""" - seen: set[tuple[int, int]] = set() - out: list[list[Cell]] = [] - for start in cells: - if start in seen: - continue - stack, comp = [start], [] - seen.add(start) - while stack: - ix, iy = stack.pop() - comp.append(cells[(ix, iy)]) - for dx in (-1, 0, 1): - for dy in (-1, 0, 1): - nb = (ix + dx, iy + dy) - if nb in cells and nb not in seen: - seen.add(nb) - stack.append(nb) - out.append(comp) - return out - - -def _distance_mm(a: Cell, b: Cell, geom: GridGeometry) -> float: - return math.hypot((a.ix - b.ix) * geom.step_x_mm, (a.iy - b.iy) * geom.step_y_mm) - - -def pick_positions( - regions: Sequence[CrystalRegion], geom: GridGeometry, cfg: StrategyConfig -) -> list[Cell]: - """Best cell of each crystal first, then further spots spaced beyond the dose halo.""" - if not regions: - return [] - top = max(r.best.score for r in regions) - floor = cfg.min_position_score_fraction * top - ordered = [r.best for r in regions] + sorted( - (c for r in regions for c in r.cells), key=lambda c: c.score, reverse=True - ) - chosen: list[Cell] = [] - for cell in ordered: - if len(chosen) >= cfg.max_positions: - break - if cell.score < floor or cell in chosen: - continue - if all(_distance_mm(cell, c, geom) >= cfg.min_spot_separation_mm for c in chosen): - chosen.append(cell) - return chosen - - -def analyse_grid( - results: Iterable[CompletedRasterGridElem], geom: GridGeometry, cfg: StrategyConfig -) -> GridAnalysis: - results = list(results) - logger.info(f"analyze_grid got {len(results)} results.") - images = results[0].result.images - hits: dict[tuple[int, int], Cell] = {} - for img in images: - if (img.spots or 0) < cfg.min_spots_hit: - continue - ix, iy = _cell_index(img, geom) - hits[(ix, iy)] = Cell( - ix=ix, - iy=iy, - spots=img.spots, - spots_indexed=getattr(img, "spots_indexed", None), - res_A=getattr(img, "res", None), - ice=getattr(img, "ice", None), - lattices=getattr(img, "latt_count", None), - score=cell_score(img, cfg), - ) - regions = [] - for comp in _regions(hits): - xs, ys = [c.ix for c in comp], [c.iy for c in comp] - res = [c.res_A for c in comp if c.res_A] - regions.append( - CrystalRegion( - cells=sorted(comp, key=lambda c: c.score, reverse=True), - best=max(comp, key=lambda c: (c.score, -(c.res_A or 99.0))), - extent_x_mm=(max(xs) - min(xs) + 1) * abs(geom.step_x_mm), - extent_y_mm=(max(ys) - min(ys) + 1) * abs(geom.step_y_mm), - median_res_A=statistics.median(res) if res else None, - max_lattices=max((c.lattices or 1) for c in comp), - ) - ) - regions.sort(key=lambda r: r.best.score, reverse=True) - return GridAnalysis( - geometry=geom, - n_images=len(images), - n_hits=len(hits), - regions=regions, - positions=pick_positions(regions, geom, cfg), - ) - - -# -------------------------------------------------------------------------------------------- -# Rotation planning -# -------------------------------------------------------------------------------------------- - - -class RotationPlan(BaseModel): - """Flat parameters for the ``collect_dataset`` task. - - ``MXTaskExecutionMessage`` only carries scalars, so chi values travel as a comma string, - like ``multiple_rasters`` does for omegas. - """ - - position_index: int - offset_x_mm: float - offset_y_mm: float - chi_deg_list: str = "0" - start_omega_deg: float = 0.0 - incr_omega_deg: float - steps: int - exp_time_s: float - transmission: float - dtz: float - file_prefix: str - dose_MGy: float - target_res_A: float - reason: str = "" - - def chi_values(self) -> list[float]: - return [float(v) for v in self.chi_deg_list.split(",") if v.strip()] - - -def detector_distance_mm(res_A: float, beam: BeamState, cfg: StrategyConfig) -> float: - """Distance that puts ``res_A`` at the nearest detector edge.""" - s = beam.wavelength_A / (2.0 * res_A) - if s >= 1.0: - return cfg.min_distance_mm - two_theta = 2.0 * math.asin(s) - distance = cfg.detector_radius_mm / math.tan(two_theta) - return min(cfg.max_distance_mm, max(cfg.min_distance_mm, distance)) - - -def dose_rate_MGy_s(beam: BeamState, cfg: StrategyConfig, transmission: float = 1.0) -> float: - if beam.flux_ph_s is None: - raise ValueError("BeamState.flux_ph_s is not set; refusing to plan a dose") - area_um2 = beam.beam_size_um[0] * beam.beam_size_um[1] - photons_per_um2_per_Gy = cfg.photons_per_um2_per_Gy_12p4keV * (beam.energy_keV / 12.4) ** 2 - return beam.flux_ph_s * transmission / area_um2 / photons_per_um2_per_Gy / 1e6 - - -def plan_rotation( - analysis: GridAnalysis, - position_index: int, - cfg: StrategyConfig, - *, - file_prefix: str, - chi_values: Sequence[float] = (0.0,), - dose_fraction: float = 1.0, - reason: str = "", -) -> RotationPlan: - """Rotation at one grid position under the ``dose_MGy_per_A`` rule. - - The budget (``dose_fraction`` of the full one) is shared over all chi sweeps, which gives the - low-dose multi-chi strategy for anomalous data. - """ - beam = cfg.beam - res_est = analysis.position_res_A(position_index) or cfg.default_res_A - target = max(cfg.best_res_limit_A, res_est * cfg.resolution_margin) - steps = max(1, round(cfg.total_rotation_deg / cfg.oscillation_deg)) - sweep_time_s = steps * cfg.exp_time_s - n_sweeps = max(1, len(chi_values)) - dose_per_sweep = cfg.dose_MGy_per_A * target * dose_fraction / n_sweeps - full_rate = dose_rate_MGy_s(beam, cfg) - transmission = dose_per_sweep / (full_rate * sweep_time_s) - transmission = min(1.0, max(cfg.min_transmission, transmission)) - x, y = analysis.position_offset_mm(position_index) - return RotationPlan( - position_index=position_index, - offset_x_mm=x, - offset_y_mm=y, - chi_deg_list=",".join(f"{c:g}" for c in chi_values), - incr_omega_deg=cfg.oscillation_deg, - steps=steps, - exp_time_s=cfg.exp_time_s, - transmission=round(transmission, 5), - dtz=round(detector_distance_mm(target, beam, cfg), 1), - file_prefix=f"{file_prefix}_p{position_index}", - dose_MGy=round(full_rate * transmission * sweep_time_s * n_sweeps, 3), - target_res_A=round(target, 2), - reason=reason, - ) - - -# -------------------------------------------------------------------------------------------- -# Records kept on SampleInfo between actors -# -------------------------------------------------------------------------------------------- - - -class RasterRecord(BaseModel): - model_config = ConfigDict(arbitrary_types_allowed=True) - - strategy: dict[str, Any] = Field(description="Kwargs of the raster, for a repeat") - geometry: GridGeometry - images: list[Any] - - -class SweepRecord(BaseModel): - model_config = ConfigDict(arbitrary_types_allowed=True) - - chi_deg: float - images: list[Any] - bravais: str | None = None - - -class Issue(str, Enum): - LOST_DIFFRACTION = "lost_diffraction" - RADIATION_DAMAGE = "radiation_damage" - BLIND_REGION = "blind_region" - LOW_SYMMETRY = "low_symmetry" - WEAK = "weak" - - -class Assessment(BaseModel): - issues: list[Issue] = [] - n_images: int = 0 - indexed_fraction: float = 0.0 - wedge_spots: list[float] = [] - wedge_res_A: list[float | None] = [] - onset_angle_deg: float | None = None - median_spindle_blind: float | None = None - bravais: str | None = None - - @property - def usable(self) -> bool: - return not {Issue.LOST_DIFFRACTION, Issue.WEAK} & set(self.issues) - - -class CollectionRecord(BaseModel): - plan: RotationPlan - sweeps: list[SweepRecord] = [] - assessment: Assessment | None = None - - -class SelfDrivingRecord(BaseModel): - """Per-sample history; reset by ``reset_sample_info`` on mount.""" - - analysis: GridAnalysis | None = None - raster_strategy: dict[str, Any] | None = None - current_offset_mm: tuple[float, float] = (0.0, 0.0) - positions_used: list[int] = [] - chi_sweeps_done: int = 0 - recentres: int = 0 - followups: int = 0 - collections: list[CollectionRecord] = [] - - def next_free_position(self) -> int | None: - if self.analysis is None: - return None - for i in range(len(self.analysis.positions)): - if i not in self.positions_used: - return i - return None - - -def scan_images(completed: Any) -> list[Any]: - """Per-image Jungfraujoch results from an aarecommon ``Completed*`` model. - - ``CompletedRotationScan`` carries a jfjoch ``ScanResult`` under ``.result``. Check which field - ``CompletedRasterGrid`` uses (``tasks.py`` logs ``len(result.r)``) and keep that path first. - """ - for path in (("result", "images"), ("r",), ("images",)): - obj = completed - for attr in path: - obj = getattr(obj, attr, None) - if obj is None: - break - if obj is not None: - return list(obj) - raise ValueError(f"No per-image results found on {type(completed).__name__}") - - -# -------------------------------------------------------------------------------------------- -# Assessment and follow-up decision -# -------------------------------------------------------------------------------------------- - - -def _wedges(items: Sequence[Any], n: int) -> list[Sequence[Any]]: - n = max(1, min(n, len(items))) - size = len(items) / n - return [items[round(i * size) : round((i + 1) * size)] for i in range(n)] - - -def assess_sweep(images: Sequence[Any], bravais: str | None, cfg: StrategyConfig) -> Assessment: - imgs = sorted( - images, - key=lambda im: (im.angle if getattr(im, "angle", None) is not None else 0.0, im.number), - ) - if not imgs: - return Assessment(issues=[Issue.LOST_DIFFRACTION, Issue.WEAK], bravais=bravais) - issues: list[Issue] = [] - wedges = _wedges(imgs, cfg.n_wedges) - wedge_spots = [float(statistics.median([(im.spots or 0) for im in w])) for w in wedges] - wedge_res: list[float | None] = [] - for w in wedges: - res = [im.res for im in w if getattr(im, "res", None)] - wedge_res.append(statistics.median(res) if res else None) - - # Lost diffraction: a drop below lost_ratio of the running max that never recovers - onset = None - running_max = wedge_spots[0] - for i in range(1, len(wedge_spots)): - if running_max >= cfg.min_spots_hit and all( - s < cfg.lost_ratio * running_max for s in wedge_spots[i:] - ): - onset = getattr(wedges[i][0], "angle", None) - issues.append(Issue.LOST_DIFFRACTION) - break - running_max = max(running_max, wedge_spots[i]) - - # Radiation damage: d_min of the last wedge worse than the first (same orientation for 360°) - first, last = wedge_res[0], wedge_res[-1] - if ( - Issue.LOST_DIFFRACTION not in issues - and first - and last - and (last - first) / first > cfg.damage_res_increase - ): - issues.append(Issue.RADIATION_DAMAGE) - - indexed = sum(1 for im in imgs if (im.spots_indexed or 0) >= cfg.min_indexed_spots) - indexed_fraction = indexed / len(imgs) - if indexed_fraction < cfg.min_indexed_fraction: - issues.append(Issue.WEAK) - - blind_values = [getattr(im, "spindle_blind", None) for im in imgs] - median_blind = None - if any(v is not None for v in blind_values): - median_blind = statistics.median([1.0 if v is None else v for v in blind_values]) - if median_blind >= cfg.spindle_blind_threshold: - issues.append(Issue.BLIND_REGION) - elif cfg.treat_unassessed_blind_as_blind: - issues.append(Issue.BLIND_REGION) - - if bravais and bravais in cfg.low_symmetry_bravais: - issues.append(Issue.LOW_SYMMETRY) - - return Assessment( - issues=issues, - n_images=len(imgs), - indexed_fraction=round(indexed_fraction, 3), - wedge_spots=wedge_spots, - wedge_res_A=wedge_res, - onset_angle_deg=onset, - median_spindle_blind=median_blind, - bravais=bravais, - ) - - -def assess_collection(record: CollectionRecord, cfg: StrategyConfig) -> Assessment: - """Assess each chi sweep separately, then merge. - - Blind region is a per-sweep property, so a multi-chi collection only keeps it if every sweep - reports it. Every other issue is kept if any sweep reports it. - """ - parts = [assess_sweep(s.images, s.bravais, cfg) for s in record.sweeps] - if not parts: - return Assessment(issues=[Issue.LOST_DIFFRACTION, Issue.WEAK]) - merged = parts[0].model_copy(deep=True) - issues: list[Issue] = [] - for issue in Issue: - flags = [issue in p.issues for p in parts] - keep = all(flags) if issue is Issue.BLIND_REGION else any(flags) - if keep: - issues.append(issue) - merged.issues = issues - merged.n_images = sum(p.n_images for p in parts) - merged.bravais = next((p.bravais for p in parts if p.bravais), None) - return merged - - -class Action(str, Enum): - FINISH = "finish" - RECENTRE = "recentre" - NEW_POSITION = "new_position" - CHI_SWEEP = "chi_sweep" - - -class Decision(BaseModel): - action: Action - reason: str - position_index: int | None = None - chi_values: list[float] = [0.0] - dose_fraction: float = 1.0 - - -def decide_followup( - assessment: Assessment, record: SelfDrivingRecord, cfg: StrategyConfig -) -> Decision: - """Priority: budget -> lost diffraction -> damage -> completeness (chi) -> weak -> finish.""" - issues = set(assessment.issues) - if record.followups >= cfg.max_followups: - return Decision(action=Action.FINISH, reason="follow-up budget spent") - nxt = record.next_free_position() - - if Issue.LOST_DIFFRACTION in issues: - if record.recentres < cfg.max_recentres: - return Decision( - action=Action.RECENTRE, - reason=f"diffraction lost at omega={assessment.onset_angle_deg}; re-raster", - ) - if nxt is not None: - return Decision( - action=Action.NEW_POSITION, position_index=nxt, reason="lost again; next spot" - ) - return Decision(action=Action.FINISH, reason="diffraction lost, no spot left") - - if Issue.RADIATION_DAMAGE in issues: - if nxt is not None: - return Decision( - action=Action.NEW_POSITION, - position_index=nxt, - dose_fraction=cfg.damage_dose_fraction, - reason="radiation damage; fresh spot at reduced dose", - ) - return Decision(action=Action.FINISH, reason="radiation damage, no fresh spot left") - - needs_chi = issues & {Issue.BLIND_REGION, Issue.LOW_SYMMETRY} - if needs_chi and record.chi_sweeps_done < cfg.max_chi_sweeps: - why = "+".join(sorted(i.value for i in needs_chi)) - if nxt is not None: - return Decision( - action=Action.CHI_SWEEP, - position_index=nxt, - chi_values=[cfg.chi_offset_deg], - reason=f"{why}; chi sweep on a fresh spot", - ) - last = record.positions_used[-1] if record.positions_used else 0 - return Decision( - action=Action.CHI_SWEEP, - position_index=last, - chi_values=[cfg.chi_offset_deg], - dose_fraction=cfg.same_position_dose_fraction, - reason=f"{why}; chi sweep on the same spot, extra dose", - ) - - if Issue.WEAK in issues and nxt is not None: - return Decision(action=Action.NEW_POSITION, position_index=nxt, reason="weak; next spot") - - return Decision(action=Action.FINISH, reason="no issue left to act on") diff --git a/mx_bec/tasks/mx_tasks.py b/mx_bec/tasks/mx_tasks.py index d72851a..fafa8b3 100644 --- a/mx_bec/tasks/mx_tasks.py +++ b/mx_bec/tasks/mx_tasks.py @@ -9,18 +9,17 @@ from aarecommon.models.raster_grid import RasterGridRequest from aarecommon.models.rotation_scan import RotationScanRequest from bec_lib.logger import bec_logger -from mx_bec.endpoints import StateEndpoints -from mx_bec.math import smargon_nudge -from mx_bec.messages import MXMeasurementSequenceMessage -from mx_bec.self_driving import ( +from mx_bec.decisions import ( CollectionRecord, GridGeometry, RasterRecord, RotationPlan, - SelfDrivingRecord, SweepRecord, scan_images, + smargon_nudge, ) +from mx_bec.endpoints import StateEndpoints +from mx_bec.messages import MXMeasurementSequenceMessage from mx_bec.tasks.core import MxSequenceUpdate, RoleT, TaskManager, task if TYPE_CHECKING: @@ -266,13 +265,6 @@ class MxTasks(TaskManager[RoleT]): MXMeasurementSequenceMessage(sample_id=dbid, success=True), ) - def _self_driving_record(self) -> SelfDrivingRecord: - info = self._client.sample_info - assert info is not None, "No sample loaded" - if info.self_driving is None: - info.self_driving = SelfDrivingRecord() - return info.self_driving - def _move_to_grid_offset(self, offset_x_mm: float, offset_y_mm: float) -> None: """Move to a point given relative to the raster start, in the raster plane. @@ -280,16 +272,16 @@ class MxTasks(TaskManager[RoleT]): grid was measured in. CHECK on the beamline: sign and axis mapping of grid x/y to nudge_in_lab_frame x/y. """ - record = self._self_driving_record() info = self._client.sample_info - omega = info.raster.geometry.omega_deg if info and info.raster else 0.0 - dx = offset_x_mm - record.current_offset_mm[0] - dy = offset_y_mm - record.current_offset_mm[1] + assert info is not None, "No sample loaded" + omega = info.raster.geometry.omega_deg if info.raster else 0.0 + dx = offset_x_mm - info.current_offset_mm[0] + dy = offset_y_mm - info.current_offset_mm[1] if abs(dx) < 1e-4 and abs(dy) < 1e-4: return self._client.devices.aerotech.u.set(omega).wait() self._client.devices.smargon.nudge_in_lab_frame(dx, dy, omega_deg=omega) - record.current_offset_mm = (offset_x_mm, offset_y_mm) + info.current_offset_mm = (offset_x_mm, offset_y_mm) @task def move_to_grid_offset(self, dbid: int, offset_x_mm: float, offset_y_mm: float) -> None: @@ -324,7 +316,9 @@ class MxTasks(TaskManager[RoleT]): ) finally: smargon.chi.set(0.0).wait() - self._self_driving_record().collections.append(record) + info = self._client.sample_info + assert info is not None, "No sample loaded" + info.collections.append(record) return ( StateEndpoints.rotation_done(), MXMeasurementSequenceMessage(sample_id=dbid, success=True), diff --git a/tests/unit/test_aaredaq_tasks.py b/tests/unit/test_aaredaq_tasks.py index 5637ebf..86edf63 100644 --- a/tests/unit/test_aaredaq_tasks.py +++ b/tests/unit/test_aaredaq_tasks.py @@ -5,7 +5,7 @@ from aarecommon.math.coordinate import Coordinate, SmargonCoordinate from aarecommon.models.raster_grid import RasterGridRequest from aarecommon.models.rotation_scan import RotationScanRequest -from mx_bec.math import smargon_nudge +from mx_bec.decisions import smargon_nudge from mx_bec.tasks import MxTasks, Server # where the mock smargon sits -- 2.54.1 From 3b8fe994032763ba02a834b18c710201afcddfbe Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 24 Nov 2026 12:32:53 +0100 Subject: [PATCH 43/46] fix: actually add decisions module --- mx_bec/decisions/__init__.py | 85 ++++++++++ mx_bec/decisions/core.py | 241 ++++++++++++++++++++++++++++ mx_bec/decisions/grid_scans.py | 283 +++++++++++++++++++++++++++++++++ mx_bec/decisions/rotations.py | 259 ++++++++++++++++++++++++++++++ 4 files changed, 868 insertions(+) create mode 100644 mx_bec/decisions/__init__.py create mode 100644 mx_bec/decisions/core.py create mode 100644 mx_bec/decisions/grid_scans.py create mode 100644 mx_bec/decisions/rotations.py diff --git a/mx_bec/decisions/__init__.py b/mx_bec/decisions/__init__.py new file mode 100644 index 0000000..f989983 --- /dev/null +++ b/mx_bec/decisions/__init__.py @@ -0,0 +1,85 @@ +"""Decision logic for the self-driving MX sequence. + + grid scan -> analyse_grid -> plan_rotation -> collect_dataset -> assess_collection + -> decide_followup -> (re-raster | new position | chi sweep | finish) + +Everything here is pure: pydantic models and functions, no BEC, Redis or device access (only +``gridscan_calculation`` uses a pxii calibration macro, imported when it is called). The +actors in ``mx_bec.actors.mx_automation`` call these functions, and the same functions can be +replayed offline against archived Jungfraujoch results to tune thresholds. + +Per-image inputs are duck-typed against ``jfjoch_client.models.ScanResultImagesInner`` +(``number``, ``nx``, ``ny``, ``angle``, ``spots``, ``spots_indexed``, ``ice``, ``res``, +``latt_count``, ``spindle_blind``), so plain objects or the jfjoch models both work. + +`core` has the configuration and the records, `grid_scans` the analysis of a raster, `rotations` +the planning, assessment and follow-up of rotation datasets. +""" + +from mx_bec.decisions.core import ( + HC_KEV_A, + Assessment, + BeamState, + CollectionRecord, + GridGeometry, + Issue, + RasterRecord, + RotationPlan, + StrategyConfig, + SweepRecord, + scan_images, + smargon_nudge, +) +from mx_bec.decisions.grid_scans import ( + Cell, + CrystalRegion, + GridAnalysis, + analyse_grid, + cell_score, + gridscan_calculation, + gridscan_strategy_from_optical, + mock_grid_calculation, + pick_positions, +) +from mx_bec.decisions.rotations import ( + Action, + Decision, + assess_collection, + assess_sweep, + decide_followup, + detector_distance_mm, + dose_rate_MGy_s, + plan_rotation, +) + +__all__ = [ + "HC_KEV_A", + "Action", + "Assessment", + "BeamState", + "Cell", + "CollectionRecord", + "CrystalRegion", + "Decision", + "GridAnalysis", + "GridGeometry", + "Issue", + "RasterRecord", + "RotationPlan", + "StrategyConfig", + "SweepRecord", + "analyse_grid", + "assess_collection", + "assess_sweep", + "cell_score", + "decide_followup", + "detector_distance_mm", + "gridscan_calculation", + "gridscan_strategy_from_optical", + "mock_grid_calculation", + "dose_rate_MGy_s", + "pick_positions", + "plan_rotation", + "scan_images", + "smargon_nudge", +] diff --git a/mx_bec/decisions/core.py b/mx_bec/decisions/core.py new file mode 100644 index 0000000..12c0b45 --- /dev/null +++ b/mx_bec/decisions/core.py @@ -0,0 +1,241 @@ +"""Shared by the decisions: constants, the strategy configuration, the records of what was +measured, which are kept on `SampleInfo` between the actors, and the smargon geometry.""" + +from __future__ import annotations + +from enum import Enum +from typing import Any + +import numpy as np +from aarecommon.math.coordinate import Coordinate +from pydantic import BaseModel, ConfigDict, Field + +HC_KEV_A = 12.398419843320026 # keV * Angstrom + + +# -------------------------------------------------------------------------------------------- +# Configuration +# -------------------------------------------------------------------------------------------- + + +class BeamState(BaseModel): + """Beam at the sample. ``flux_ph_s`` is at transmission 1.""" + + energy_keV: float = Field(12.4, gt=0) + flux_ph_s: float | None = Field(None, gt=0, description="Must be set; no dose plan without it") + beam_size_um: tuple[float, float] = (25.0, 25.0) + + @property + def wavelength_A(self) -> float: + return HC_KEV_A / self.energy_keV + + +class StrategyConfig(BaseModel): + """Every threshold the actors use. Defaults are starting points for the replay study.""" + + # grid analysis + min_spots_hit: int = Field(10, description="Spots per image for a cell to count as a hit") + ice_threshold: float = Field(1.5, description="jfjoch 'ice' ratio above which a cell is icy") + ice_penalty: float = 0.5 + multi_lattice_penalty: float = 0.5 + reference_res_A: float = Field(2.0, description="Resolution at which the score factor is 1") + max_positions: int = 4 + min_spot_separation_mm: float = Field(0.04, description="Beam size plus dose halo") + min_position_score_fraction: float = Field(0.3, description="Relative to the best cell") + + # rotation plan + beam: BeamState = BeamState() + dose_MGy_per_A: float = Field(5.0, description="Dose budget = this x target resolution") + photons_per_um2_per_Gy_12p4keV: float = Field( + 2000.0, + description="Rule-of-thumb fluence per Gy at 12.4 keV, scaled by E^2; replace with " + "RADDOSE-3D when the crystal model is available", + ) + total_rotation_deg: float = 360.0 + oscillation_deg: float = 0.1 + exp_time_s: float = 0.005 + min_transmission: float = 0.001 + resolution_margin: float = Field(0.9, description="Aim this factor beyond the grid estimate") + default_res_A: float = 2.5 + best_res_limit_A: float = 0.8 + detector_radius_mm: float = Field(150.0, description="Beam centre to nearest detector edge") + min_distance_mm: float = 100.0 + max_distance_mm: float = 1000.0 + + # anomalous: low-dose multi-chi from the start + anomalous: bool = False + anomalous_chi_deg: tuple[float, ...] = (0.0, 15.0, 30.0) + + # assessment + n_wedges: int = 10 + lost_ratio: float = Field(0.3, description="Wedge spots below this x previous max = lost") + damage_res_increase: float = Field(0.15, description="Relative d_min loss first->last wedge") + min_indexed_spots: int = 10 + min_indexed_fraction: float = 0.5 + spindle_blind_threshold: float = Field(0.5, description="jfjoch: >= 0.5 engage recovery") + treat_unassessed_blind_as_blind: bool = Field( + True, description="jfjoch: an absent spindle_blind must be treated as above threshold" + ) + low_symmetry_bravais: frozenset[str] = frozenset({"aP", "mP", "mC"}) + + # follow-up policy + max_followups: int = 3 + max_recentres: int = 1 + max_chi_sweeps: int = 1 + chi_offset_deg: float = 30.0 + damage_dose_fraction: float = 0.5 + same_position_dose_fraction: float = Field( + 0.3, description="Extra dose allowed when a chi sweep must reuse a burnt position" + ) + + +# -------------------------------------------------------------------------------------------- +# Parameters of the measurements +# -------------------------------------------------------------------------------------------- + + +class GridGeometry(BaseModel): + """Raster layout. Cell (0, 0) sits at the raster start position (``smargon_top_left``).""" + + n_x: int = Field(ge=1) + n_y: int = Field(ge=1) + step_x_mm: float + step_y_mm: float + omega_deg: float = 0.0 + snake: bool = True + + def offset_mm(self, ix: int, iy: int) -> tuple[float, float]: + return ix * self.step_x_mm, iy * self.step_y_mm + + +class RotationPlan(BaseModel): + """Flat parameters for the ``collect_dataset`` task. + + ``MXTaskExecutionMessage`` only carries scalars, so chi values travel as a comma string, + like ``multiple_rasters`` does for omegas. + """ + + position_index: int + offset_x_mm: float + offset_y_mm: float + chi_deg_list: str = "0" + start_omega_deg: float = 0.0 + incr_omega_deg: float + steps: int + exp_time_s: float + transmission: float + dtz: float + file_prefix: str + dose_MGy: float + target_res_A: float + reason: str = "" + + def chi_values(self) -> list[float]: + return [float(v) for v in self.chi_deg_list.split(",") if v.strip()] + + +# -------------------------------------------------------------------------------------------- +# Records kept on SampleInfo between actors +# -------------------------------------------------------------------------------------------- + + +class RasterRecord(BaseModel): + model_config = ConfigDict(arbitrary_types_allowed=True) + + strategy: dict[str, Any] = Field(description="Kwargs of the raster, for a repeat") + geometry: GridGeometry + images: list[Any] + + +class SweepRecord(BaseModel): + model_config = ConfigDict(arbitrary_types_allowed=True) + + chi_deg: float + images: list[Any] + bravais: str | None = None + + +class Issue(str, Enum): + LOST_DIFFRACTION = "lost_diffraction" + RADIATION_DAMAGE = "radiation_damage" + BLIND_REGION = "blind_region" + LOW_SYMMETRY = "low_symmetry" + WEAK = "weak" + + +class Assessment(BaseModel): + issues: list[Issue] = [] + n_images: int = 0 + indexed_fraction: float = 0.0 + wedge_spots: list[float] = [] + wedge_res_A: list[float | None] = [] + onset_angle_deg: float | None = None + median_spindle_blind: float | None = None + bravais: str | None = None + + @property + def usable(self) -> bool: + return not {Issue.LOST_DIFFRACTION, Issue.WEAK} & set(self.issues) + + +class CollectionRecord(BaseModel): + plan: RotationPlan + sweeps: list[SweepRecord] = [] + assessment: Assessment | None = None + + +def scan_images(completed: Any) -> list[Any]: + """Per-image Jungfraujoch results from an aarecommon ``Completed*`` model. + + ``CompletedRotationScan`` carries a jfjoch ``ScanResult`` under ``.result``. Check which field + ``CompletedRasterGrid`` uses (``tasks.py`` logs ``len(result.r)``) and keep that path first. + """ + for path in (("result", "images"), ("r",), ("images",)): + obj = completed + for attr in path: + obj = getattr(obj, attr, None) + if obj is None: + break + if obj is not None: + return list(obj) + raise ValueError(f"No per-image results found on {type(completed).__name__}") + + +# -------------------------------------------------------------------------------------------- +# Geometry +# -------------------------------------------------------------------------------------------- + + +def smargon_nudge( + phi_deg: float, chi_deg: float, omega_deg: float, nudge_vector: Coordinate +) -> Coordinate: + """Translate a relative movement of the smargon from lab frame to smargon frame. + Add the result of this to the smargon's current position to get the new position.""" + phi = np.radians(np.around(phi_deg, decimals=1)) + chi = np.radians(np.around(chi_deg, decimals=1)) + omega = np.radians(np.around(omega_deg, decimals=1)) + + offset = Coordinate() + co = np.cos(omega) + so = np.sin(omega) + cp = np.cos(phi) + sp = np.sin(phi) + cc = np.cos(chi) + sc = np.sin(chi) + + offset.x = ( + -nudge_vector.z * co * sp + - nudge_vector.y * so * sp + + nudge_vector.x * cp * sc + - nudge_vector.y * co * cc * cp + + nudge_vector.z * so * cc * cp + ) + offset.y = ( + -nudge_vector.z * co * cp + - nudge_vector.y * so * cp + - nudge_vector.x * sc * sp + + nudge_vector.y * co * cc * sp + - nudge_vector.z * so * cc * sp + ) + offset.z = -nudge_vector.x * cc - nudge_vector.y * co * sc + nudge_vector.z * so * sc + return offset diff --git a/mx_bec/decisions/grid_scans.py b/mx_bec/decisions/grid_scans.py new file mode 100644 index 0000000..0b2be1c --- /dev/null +++ b/mx_bec/decisions/grid_scans.py @@ -0,0 +1,283 @@ +"""Grid scans: work out the grid to scan from the optical centering results, find the crystals +in the per-cell results of a raster and pick the spots to collect data at.""" + +from __future__ import annotations + +import math +import secrets +import statistics +from collections.abc import Iterable, Sequence +from typing import TYPE_CHECKING, Any + +from aarecommon.models.raster_grid import CompletedRasterGridElem +from bec_lib.logger import bec_logger +from pydantic import BaseModel, ConfigDict, Field + +from mx_bec.decisions.core import GridGeometry, StrategyConfig + +if TYPE_CHECKING: + from mx_bec.sample_info import OpticalCenteringResults + +logger = bec_logger.logger + + +# -------------------------------------------------------------------------------------------- +# Strategy: which grid to scan +# -------------------------------------------------------------------------------------------- + + +def mock_grid_calculation(): + logger.info("calculating mock grid given no optical results ...") + n_x = 10 + n_y = 10 + step_x_mm = 0.05 + step_y_mm = 0.05 + strategy = { + "n_x": n_x, + "n_y": n_y, + "step_x_mm": step_x_mm, + "step_y_mm": step_y_mm, + "exp_time_s": 0.05, + "omega_deg": 0.0, + "file_prefix": f"AareBecTestGridScan_{secrets.token_hex(6)}", + "dtz": 250, + "transmission": 0.2, + } + return strategy + + +def gridscan_strategy_from_optical( + optical_results: OpticalCenteringResults | None, + step_x_um: float, + step_y_um: float, + margin: float, + exp_time_s: float, + dtz_mm: float, +): + if optical_results is None or len(boxes := optical_results.prediction.boxes) == 0: + return mock_grid_calculation() + box_data = {box.label: ((box.x1, box.y1), (box.x2, box.y2)) for box in boxes} + logger.info(f"got detection boxes: {box_data}") + box_corners = None + for label_option in ["loop_face", "loop_all"]: + if label_option in box_data: + box_corners = box_data[label_option] + logger.info(f"using best available box: {label_option}") + break + if box_corners is None: + return mock_grid_calculation() + else: + file_prefix = f"AareBecTestGridScan_{secrets.token_hex(6)}" + return gridscan_calculation( + box_corners[0], + box_corners[1], + step_x_um / 1000, + step_y_um / 1000, + margin, + file_prefix, + exp_time_s, + dtz_mm, + ) + + +def gridscan_calculation( + x1_y1: tuple[float, float], + x2_y2: tuple[float, float], + size_x_mm: float, + size_y_mm: float, + margin: float, + file_prefix: str, + exp_time_s: float, + dtz_mm: float, +): + """calculate a gridscan from box coordinates and params. needs omega added later.""" + # pyright: ignore[reportMissingImports] + from pxii_bec.macros.calculator import calc_scam_microns + # TODO: migrate utils from plugins to mx_bec + + box_x_pixels = abs(x1_y1[0] - x2_y2[0]) + box_y_pixels = abs(x1_y1[1] - x2_y2[1]) + logger.info(f"{box_x_pixels=}, {box_y_pixels=}") + box_x_microns = calc_scam_microns(box_x_pixels, zoom=400) + box_y_microns = calc_scam_microns(box_y_pixels, zoom=400) + logger.info(f"{box_x_microns=}, {box_y_microns=}") + logger.info(f"adding margin to detection boxes of {margin}x") + n_x = int(box_x_microns / 1000 / size_x_mm * margin) + n_y = int(box_y_microns / 1000 / size_y_mm * margin) + return { + "n_x": n_x, + "n_y": n_y, + "step_x_mm": size_x_mm, + "step_y_mm": size_y_mm, + "exp_time_s": exp_time_s, + "file_prefix": file_prefix, + "dtz": dtz_mm, + } + + +# -------------------------------------------------------------------------------------------- +# Analysis: what the grid found +# -------------------------------------------------------------------------------------------- + + +class Cell(BaseModel): + model_config = ConfigDict(frozen=True) + + ix: int + iy: int + spots: int + spots_indexed: int | None = None + res_A: float | None = None + ice: float | None = None + lattices: int | None = None + score: float = 0.0 + + +class CrystalRegion(BaseModel): + cells: list[Cell] + best: Cell + extent_x_mm: float + extent_y_mm: float + median_res_A: float | None + max_lattices: int + + +class GridAnalysis(BaseModel): + geometry: GridGeometry + n_images: int + n_hits: int + regions: list[CrystalRegion] + positions: list[Cell] = Field(description="Ranked collection spots, best first") + + def position_offset_mm(self, index: int) -> tuple[float, float]: + cell = self.positions[index] + return self.geometry.offset_mm(cell.ix, cell.iy) + + def position_res_A(self, index: int) -> float | None: + cell = self.positions[index] + if cell.res_A: + return cell.res_A + for region in self.regions: + if cell in region.cells: + return region.median_res_A + return None + + +def _cell_index(img: Any, geom: GridGeometry) -> tuple[int, int]: + nx, ny = getattr(img, "nx", None), getattr(img, "ny", None) + if nx is not None and ny is not None: + return int(nx), int(ny) + row, col = divmod(int(img.number), geom.n_x) + if geom.snake and row % 2: + col = geom.n_x - 1 - col + return col, row + + +def cell_score(img: Any, cfg: StrategyConfig) -> float: + """Indexed spots weighted for resolution, penalised for ice and extra lattices.""" + spots = img.spots or 0 + indexed = getattr(img, "spots_indexed", None) + base = float(spots) if indexed is None else indexed + 0.25 * max(spots - indexed, 0) + ice = getattr(img, "ice", None) + if ice is not None and ice > cfg.ice_threshold: + base *= cfg.ice_penalty + lattices = getattr(img, "latt_count", None) + if lattices is not None and lattices > 1: + base *= cfg.multi_lattice_penalty + res = getattr(img, "res", None) + if res: + base *= min(2.0, max(0.5, cfg.reference_res_A / res)) + return base + + +def _regions(cells: dict[tuple[int, int], Cell]) -> list[list[Cell]]: + """8-connected components of hit cells.""" + seen: set[tuple[int, int]] = set() + out: list[list[Cell]] = [] + for start in cells: + if start in seen: + continue + stack, comp = [start], [] + seen.add(start) + while stack: + ix, iy = stack.pop() + comp.append(cells[(ix, iy)]) + for dx in (-1, 0, 1): + for dy in (-1, 0, 1): + nb = (ix + dx, iy + dy) + if nb in cells and nb not in seen: + seen.add(nb) + stack.append(nb) + out.append(comp) + return out + + +def _distance_mm(a: Cell, b: Cell, geom: GridGeometry) -> float: + return math.hypot((a.ix - b.ix) * geom.step_x_mm, (a.iy - b.iy) * geom.step_y_mm) + + +def pick_positions( + regions: Sequence[CrystalRegion], geom: GridGeometry, cfg: StrategyConfig +) -> list[Cell]: + """Best cell of each crystal first, then further spots spaced beyond the dose halo.""" + if not regions: + return [] + top = max(r.best.score for r in regions) + floor = cfg.min_position_score_fraction * top + ordered = [r.best for r in regions] + sorted( + (c for r in regions for c in r.cells), key=lambda c: c.score, reverse=True + ) + chosen: list[Cell] = [] + for cell in ordered: + if len(chosen) >= cfg.max_positions: + break + if cell.score < floor or cell in chosen: + continue + if all(_distance_mm(cell, c, geom) >= cfg.min_spot_separation_mm for c in chosen): + chosen.append(cell) + return chosen + + +def analyse_grid( + results: Iterable[CompletedRasterGridElem], geom: GridGeometry, cfg: StrategyConfig +) -> GridAnalysis: + results = list(results) + logger.info(f"analyze_grid got {len(results)} results.") + images = results[0].result.images + hits: dict[tuple[int, int], Cell] = {} + for img in images: + if (img.spots or 0) < cfg.min_spots_hit: + continue + ix, iy = _cell_index(img, geom) + hits[(ix, iy)] = Cell( + ix=ix, + iy=iy, + spots=img.spots, + spots_indexed=getattr(img, "spots_indexed", None), + res_A=getattr(img, "res", None), + ice=getattr(img, "ice", None), + lattices=getattr(img, "latt_count", None), + score=cell_score(img, cfg), + ) + regions = [] + for comp in _regions(hits): + xs, ys = [c.ix for c in comp], [c.iy for c in comp] + res = [c.res_A for c in comp if c.res_A] + regions.append( + CrystalRegion( + cells=sorted(comp, key=lambda c: c.score, reverse=True), + best=max(comp, key=lambda c: (c.score, -(c.res_A or 99.0))), + extent_x_mm=(max(xs) - min(xs) + 1) * abs(geom.step_x_mm), + extent_y_mm=(max(ys) - min(ys) + 1) * abs(geom.step_y_mm), + median_res_A=statistics.median(res) if res else None, + max_lattices=max((c.lattices or 1) for c in comp), + ) + ) + regions.sort(key=lambda r: r.best.score, reverse=True) + return GridAnalysis( + geometry=geom, + n_images=len(images), + n_hits=len(hits), + regions=regions, + positions=pick_positions(regions, geom, cfg), + ) diff --git a/mx_bec/decisions/rotations.py b/mx_bec/decisions/rotations.py new file mode 100644 index 0000000..e596444 --- /dev/null +++ b/mx_bec/decisions/rotations.py @@ -0,0 +1,259 @@ +"""Rotations: plan a rotation dataset at a spot of the grid, assess what was collected and +decide how to follow it up.""" + +from __future__ import annotations + +import math +import statistics +from collections.abc import Sequence +from enum import Enum +from typing import TYPE_CHECKING, Any + +from pydantic import BaseModel + +from mx_bec.decisions.core import ( + Assessment, + BeamState, + CollectionRecord, + Issue, + RotationPlan, + StrategyConfig, +) +from mx_bec.decisions.grid_scans import GridAnalysis + +if TYPE_CHECKING: + from mx_bec.sample_info import SampleInfo + + +# -------------------------------------------------------------------------------------------- +# Planning +# -------------------------------------------------------------------------------------------- + + +def detector_distance_mm(res_A: float, beam: BeamState, cfg: StrategyConfig) -> float: + """Distance that puts ``res_A`` at the nearest detector edge.""" + s = beam.wavelength_A / (2.0 * res_A) + if s >= 1.0: + return cfg.min_distance_mm + two_theta = 2.0 * math.asin(s) + distance = cfg.detector_radius_mm / math.tan(two_theta) + return min(cfg.max_distance_mm, max(cfg.min_distance_mm, distance)) + + +def dose_rate_MGy_s(beam: BeamState, cfg: StrategyConfig, transmission: float = 1.0) -> float: + if beam.flux_ph_s is None: + raise ValueError("BeamState.flux_ph_s is not set; refusing to plan a dose") + area_um2 = beam.beam_size_um[0] * beam.beam_size_um[1] + photons_per_um2_per_Gy = cfg.photons_per_um2_per_Gy_12p4keV * (beam.energy_keV / 12.4) ** 2 + return beam.flux_ph_s * transmission / area_um2 / photons_per_um2_per_Gy / 1e6 + + +def plan_rotation( + analysis: GridAnalysis, + position_index: int, + cfg: StrategyConfig, + *, + file_prefix: str, + chi_values: Sequence[float] = (0.0,), + dose_fraction: float = 1.0, + reason: str = "", +) -> RotationPlan: + """Rotation at one grid position under the ``dose_MGy_per_A`` rule. + + The budget (``dose_fraction`` of the full one) is shared over all chi sweeps, which gives the + low-dose multi-chi strategy for anomalous data. + """ + beam = cfg.beam + res_est = analysis.position_res_A(position_index) or cfg.default_res_A + target = max(cfg.best_res_limit_A, res_est * cfg.resolution_margin) + steps = max(1, round(cfg.total_rotation_deg / cfg.oscillation_deg)) + sweep_time_s = steps * cfg.exp_time_s + n_sweeps = max(1, len(chi_values)) + dose_per_sweep = cfg.dose_MGy_per_A * target * dose_fraction / n_sweeps + full_rate = dose_rate_MGy_s(beam, cfg) + transmission = dose_per_sweep / (full_rate * sweep_time_s) + transmission = min(1.0, max(cfg.min_transmission, transmission)) + x, y = analysis.position_offset_mm(position_index) + return RotationPlan( + position_index=position_index, + offset_x_mm=x, + offset_y_mm=y, + chi_deg_list=",".join(f"{c:g}" for c in chi_values), + incr_omega_deg=cfg.oscillation_deg, + steps=steps, + exp_time_s=cfg.exp_time_s, + transmission=round(transmission, 5), + dtz=round(detector_distance_mm(target, beam, cfg), 1), + file_prefix=f"{file_prefix}_p{position_index}", + dose_MGy=round(full_rate * transmission * sweep_time_s * n_sweeps, 3), + target_res_A=round(target, 2), + reason=reason, + ) + + +# -------------------------------------------------------------------------------------------- +# Assessment and follow-up decision +# -------------------------------------------------------------------------------------------- + + +def _wedges(items: Sequence[Any], n: int) -> list[Sequence[Any]]: + n = max(1, min(n, len(items))) + size = len(items) / n + return [items[round(i * size) : round((i + 1) * size)] for i in range(n)] + + +def assess_sweep(images: Sequence[Any], bravais: str | None, cfg: StrategyConfig) -> Assessment: + imgs = sorted( + images, + key=lambda im: (im.angle if getattr(im, "angle", None) is not None else 0.0, im.number), + ) + if not imgs: + return Assessment(issues=[Issue.LOST_DIFFRACTION, Issue.WEAK], bravais=bravais) + issues: list[Issue] = [] + wedges = _wedges(imgs, cfg.n_wedges) + wedge_spots = [float(statistics.median([(im.spots or 0) for im in w])) for w in wedges] + wedge_res: list[float | None] = [] + for w in wedges: + res = [im.res for im in w if getattr(im, "res", None)] + wedge_res.append(statistics.median(res) if res else None) + + # Lost diffraction: a drop below lost_ratio of the running max that never recovers + onset = None + running_max = wedge_spots[0] + for i in range(1, len(wedge_spots)): + if running_max >= cfg.min_spots_hit and all( + s < cfg.lost_ratio * running_max for s in wedge_spots[i:] + ): + onset = getattr(wedges[i][0], "angle", None) + issues.append(Issue.LOST_DIFFRACTION) + break + running_max = max(running_max, wedge_spots[i]) + + # Radiation damage: d_min of the last wedge worse than the first (same orientation for 360°) + first, last = wedge_res[0], wedge_res[-1] + if ( + Issue.LOST_DIFFRACTION not in issues + and first + and last + and (last - first) / first > cfg.damage_res_increase + ): + issues.append(Issue.RADIATION_DAMAGE) + + indexed = sum(1 for im in imgs if (im.spots_indexed or 0) >= cfg.min_indexed_spots) + indexed_fraction = indexed / len(imgs) + if indexed_fraction < cfg.min_indexed_fraction: + issues.append(Issue.WEAK) + + blind_values = [getattr(im, "spindle_blind", None) for im in imgs] + median_blind = None + if any(v is not None for v in blind_values): + median_blind = statistics.median([1.0 if v is None else v for v in blind_values]) + if median_blind >= cfg.spindle_blind_threshold: + issues.append(Issue.BLIND_REGION) + elif cfg.treat_unassessed_blind_as_blind: + issues.append(Issue.BLIND_REGION) + + if bravais and bravais in cfg.low_symmetry_bravais: + issues.append(Issue.LOW_SYMMETRY) + + return Assessment( + issues=issues, + n_images=len(imgs), + indexed_fraction=round(indexed_fraction, 3), + wedge_spots=wedge_spots, + wedge_res_A=wedge_res, + onset_angle_deg=onset, + median_spindle_blind=median_blind, + bravais=bravais, + ) + + +def assess_collection(record: CollectionRecord, cfg: StrategyConfig) -> Assessment: + """Assess each chi sweep separately, then merge. + + Blind region is a per-sweep property, so a multi-chi collection only keeps it if every sweep + reports it. Every other issue is kept if any sweep reports it. + """ + parts = [assess_sweep(s.images, s.bravais, cfg) for s in record.sweeps] + if not parts: + return Assessment(issues=[Issue.LOST_DIFFRACTION, Issue.WEAK]) + merged = parts[0].model_copy(deep=True) + issues: list[Issue] = [] + for issue in Issue: + flags = [issue in p.issues for p in parts] + keep = all(flags) if issue is Issue.BLIND_REGION else any(flags) + if keep: + issues.append(issue) + merged.issues = issues + merged.n_images = sum(p.n_images for p in parts) + merged.bravais = next((p.bravais for p in parts if p.bravais), None) + return merged + + +class Action(str, Enum): + FINISH = "finish" + RECENTRE = "recentre" + NEW_POSITION = "new_position" + CHI_SWEEP = "chi_sweep" + + +class Decision(BaseModel): + action: Action + reason: str + position_index: int | None = None + chi_values: list[float] = [0.0] + dose_fraction: float = 1.0 + + +def decide_followup(assessment: Assessment, info: SampleInfo, cfg: StrategyConfig) -> Decision: + """Priority: budget -> lost diffraction -> damage -> completeness (chi) -> weak -> finish.""" + issues = set(assessment.issues) + if info.followups >= cfg.max_followups: + return Decision(action=Action.FINISH, reason="follow-up budget spent") + nxt = info.next_free_position() + + if Issue.LOST_DIFFRACTION in issues: + if info.recentres < cfg.max_recentres: + return Decision( + action=Action.RECENTRE, + reason=f"diffraction lost at omega={assessment.onset_angle_deg}; re-raster", + ) + if nxt is not None: + return Decision( + action=Action.NEW_POSITION, position_index=nxt, reason="lost again; next spot" + ) + return Decision(action=Action.FINISH, reason="diffraction lost, no spot left") + + if Issue.RADIATION_DAMAGE in issues: + if nxt is not None: + return Decision( + action=Action.NEW_POSITION, + position_index=nxt, + dose_fraction=cfg.damage_dose_fraction, + reason="radiation damage; fresh spot at reduced dose", + ) + return Decision(action=Action.FINISH, reason="radiation damage, no fresh spot left") + + needs_chi = issues & {Issue.BLIND_REGION, Issue.LOW_SYMMETRY} + if needs_chi and info.chi_sweeps_done < cfg.max_chi_sweeps: + why = "+".join(sorted(i.value for i in needs_chi)) + if nxt is not None: + return Decision( + action=Action.CHI_SWEEP, + position_index=nxt, + chi_values=[cfg.chi_offset_deg], + reason=f"{why}; chi sweep on a fresh spot", + ) + last = info.positions_used[-1] if info.positions_used else 0 + return Decision( + action=Action.CHI_SWEEP, + position_index=last, + chi_values=[cfg.chi_offset_deg], + dose_fraction=cfg.same_position_dose_fraction, + reason=f"{why}; chi sweep on the same spot, extra dose", + ) + + if Issue.WEAK in issues and nxt is not None: + return Decision(action=Action.NEW_POSITION, position_index=nxt, reason="weak; next spot") + + return Decision(action=Action.FINISH, reason="no issue left to act on") -- 2.54.1 From bfc56b81b990a175b4ee8b85d1f42da6e6854123 Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 24 Nov 2026 13:16:58 +0100 Subject: [PATCH 44/46] feat: add samcam conversion --- .gitea/workflows/ci.yml | 4 +- mx_bec/actors/mx_automation.py | 1 - mx_bec/calc.py | 6 + mx_bec/decisions/__init__.py | 3 +- mx_bec/decisions/grid_scans.py | 11 +- mx_bec/device_planner/__init__.py | 45 +++++ mx_bec/device_planner/build.py | 125 +++++++++++++ mx_bec/device_planner/environment.py | 116 ++++++++++++ mx_bec/device_planner/guards.py | 93 ++++++++++ mx_bec/device_planner/planner.py | 226 +++++++++++++++++++++++ mx_bec/device_planner/policies.py | 78 ++++++++ mx_bec/device_planner/position_device.py | 134 ++++++++++++++ mx_bec/optical_centering.py | 14 +- mx_bec/sample_info.py | 4 + pyproject.toml | 4 +- tests/unit/test_device_planner.py | 160 ++++++++++++++++ 16 files changed, 1009 insertions(+), 15 deletions(-) create mode 100644 mx_bec/calc.py create mode 100644 mx_bec/device_planner/__init__.py create mode 100644 mx_bec/device_planner/build.py create mode 100644 mx_bec/device_planner/environment.py create mode 100644 mx_bec/device_planner/guards.py create mode 100644 mx_bec/device_planner/planner.py create mode 100644 mx_bec/device_planner/policies.py create mode 100644 mx_bec/device_planner/position_device.py create mode 100644 tests/unit/test_device_planner.py diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 27ffb58..64e75bb 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -94,9 +94,9 @@ jobs: uv pip install --system -e ./bec/bec_lib[dev] uv pip install --system -e ./bec/bec_ipython_client uv pip install --system -e ./bec/bec_server[dev] - uv pip install --system -e ./bec_widgets[dev,pyside6] + uv pip install --system -e ./bec_widgets[dev] # MX-internal dependencies (aarecommon, aare_config, jfjoch_client, ...) come from gitea - uv pip install --system --extra-index-url https://gitea.psi.ch/api/packages/mx/pypi/simple/ -e ./mx_bec + uv pip install --system --extra-index-url https://gitea.psi.ch/api/packages/mx/pypi/simple/ -e ./mx_bec[dev] - name: Run Pytest with Coverage id: coverage diff --git a/mx_bec/actors/mx_automation.py b/mx_bec/actors/mx_automation.py index 490d3b2..de04cda 100644 --- a/mx_bec/actors/mx_automation.py +++ b/mx_bec/actors/mx_automation.py @@ -11,7 +11,6 @@ from time import sleep from aarelcinfer_client.models import DetectionModel from bec_lib.endpoints import EndpointInfo from bec_lib.logger import bec_logger -from pxii_bec.macros.calculator import calc_scam_microns from mx_bec.actors.core import MXAutomationActor from mx_bec.decisions import ( diff --git a/mx_bec/calc.py b/mx_bec/calc.py new file mode 100644 index 0000000..a223586 --- /dev/null +++ b/mx_bec/calc.py @@ -0,0 +1,6 @@ +import numpy as np + + +def samcam_pixels_to_microns(pixels: int, zoom: float, multiplier: float, exponent: float): + """Convert pixels to microns for the sample camera""" + return float(pixels / (multiplier * np.exp(exponent * zoom))) diff --git a/mx_bec/decisions/__init__.py b/mx_bec/decisions/__init__.py index f989983..bcbbd36 100644 --- a/mx_bec/decisions/__init__.py +++ b/mx_bec/decisions/__init__.py @@ -3,8 +3,7 @@ grid scan -> analyse_grid -> plan_rotation -> collect_dataset -> assess_collection -> decide_followup -> (re-raster | new position | chi sweep | finish) -Everything here is pure: pydantic models and functions, no BEC, Redis or device access (only -``gridscan_calculation`` uses a pxii calibration macro, imported when it is called). The +Everything here is pure: pydantic models and functions, no BEC, Redis or device access. The actors in ``mx_bec.actors.mx_automation`` call these functions, and the same functions can be replayed offline against archived Jungfraujoch results to tune thresholds. diff --git a/mx_bec/decisions/grid_scans.py b/mx_bec/decisions/grid_scans.py index 0b2be1c..5fe2386 100644 --- a/mx_bec/decisions/grid_scans.py +++ b/mx_bec/decisions/grid_scans.py @@ -54,6 +54,7 @@ def gridscan_strategy_from_optical( exp_time_s: float, dtz_mm: float, ): + """Work out the grid to scan from the loop detected by the optical centering.""" if optical_results is None or len(boxes := optical_results.prediction.boxes) == 0: return mock_grid_calculation() box_data = {box.label: ((box.x1, box.y1), (box.x2, box.y2)) for box in boxes} @@ -77,6 +78,7 @@ def gridscan_strategy_from_optical( file_prefix, exp_time_s, dtz_mm, + optical_results.microns_per_pixel, ) @@ -89,17 +91,14 @@ def gridscan_calculation( file_prefix: str, exp_time_s: float, dtz_mm: float, + microns_per_pixel: float, ): """calculate a gridscan from box coordinates and params. needs omega added later.""" - # pyright: ignore[reportMissingImports] - from pxii_bec.macros.calculator import calc_scam_microns - # TODO: migrate utils from plugins to mx_bec - box_x_pixels = abs(x1_y1[0] - x2_y2[0]) box_y_pixels = abs(x1_y1[1] - x2_y2[1]) logger.info(f"{box_x_pixels=}, {box_y_pixels=}") - box_x_microns = calc_scam_microns(box_x_pixels, zoom=400) - box_y_microns = calc_scam_microns(box_y_pixels, zoom=400) + box_x_microns = box_x_pixels * microns_per_pixel + box_y_microns = box_y_pixels * microns_per_pixel logger.info(f"{box_x_microns=}, {box_y_microns=}") logger.info(f"adding margin to detection boxes of {margin}x") n_x = int(box_x_microns / 1000 / size_x_mm * margin) diff --git a/mx_bec/device_planner/__init__.py b/mx_bec/device_planner/__init__.py new file mode 100644 index 0000000..d53bc16 --- /dev/null +++ b/mx_bec/device_planner/__init__.py @@ -0,0 +1,45 @@ +"""Planner to move the beamline devices between beamline states. + +Copied from the pxii_bec macros (`macros/beamline_planner.py` and what it is built from: +`position_device`, `build_devices`, `devices_manager`, `beamline_state_manager`, `dependencies`, +`guards`, `policies`, and `scripts/init_beamline.py`). The macros rely on `dev` and `scans` being +globals of the BEC IPython client; here they are passed in, so that this also works in a service. +""" + +from mx_bec.device_planner.build import ( + DefineStatesManager, + DeviceManager, + build_devices, + planner_deps, +) +from mx_bec.device_planner.environment import Environment, init_beamline_environment +from mx_bec.device_planner.guards import ( + AtPositionGuard, + GuardViolation, + MinMaxGuard, + attach_guards, + guards_setup, +) +from mx_bec.device_planner.planner import BeamlineState, StateChangePlanner, TemperatureMode +from mx_bec.device_planner.policies import attach_policies +from mx_bec.device_planner.position_device import PositionDevice, motor_resolver + +__all__ = [ + "AtPositionGuard", + "BeamlineState", + "DefineStatesManager", + "DeviceManager", + "Environment", + "GuardViolation", + "MinMaxGuard", + "PositionDevice", + "StateChangePlanner", + "TemperatureMode", + "attach_guards", + "attach_policies", + "build_devices", + "guards_setup", + "init_beamline_environment", + "motor_resolver", + "planner_deps", +] diff --git a/mx_bec/device_planner/build.py b/mx_bec/device_planner/build.py new file mode 100644 index 0000000..d7deda6 --- /dev/null +++ b/mx_bec/device_planner/build.py @@ -0,0 +1,125 @@ +"""Build what the planner works with: the position devices with their guards and policies, the +beamline states and the dependencies between positions.""" + +import yaml + +from mx_bec.device_planner.guards import attach_guards +from mx_bec.device_planner.planner import BeamlineState +from mx_bec.device_planner.policies import attach_policies +from mx_bec.device_planner.position_device import PositionDevice, motor_resolver + + +def build_devices(yaml_file, dev, scans): + """Build the position devices from the device config yaml, for the BEC devices `dev`, moved + with the BEC scans `scans`.""" + + state_devices = {} + + with open(yaml_file, encoding="utf-8") as f: + data = yaml.safe_load(f) + + for bec_name, cfg in data.items(): + user = cfg.get("userParameter") + + # Skip devices without user parameters + if not user: + continue + + if bec_name in ("aerotech", "smargon"): + tol = user.get("tol", 0.01) + + for axis in ["x", "y", "z", "u", "chi", "phi"]: + positions = user.get(axis) + + if positions is None: + continue + + component_name = f"{bec_name}_{axis}" + + pos_dev = PositionDevice( + bec_name=component_name, + mot_device=motor_resolver(dev, component_name), + dev=dev, + scans=scans, + positions=positions, + tol=tol, + allow_arbitrary=True, + ) + + state_devices[component_name] = pos_dev + + else: + tol = user.get("tol", 0.1) + allow_arbitrary = user.get("type") == "continuous" + move_method = user.get("move_method", "motor") + + positions = {k: v for k, v in user.items() if k not in ("type", "tol", "move_method")} + + pos_dev = PositionDevice( + bec_name=bec_name, + mot_device=motor_resolver(dev, bec_name), + dev=dev, + scans=scans, + positions=positions, + tol=tol, + allow_arbitrary=allow_arbitrary, + move_method=move_method, + ) + + state_devices[bec_name] = pos_dev + + return state_devices + + +class DeviceManager: + """Class for building devices and attaching safety guards and policies.""" + + @staticmethod + def initialize_devices(devices_file, dev, scans): + """ + Initializes sample environment devices from the specified file. + """ + devices = build_devices(devices_file, dev, scans) + attach_guards(devices) + attach_policies(devices) + return devices + + +class DefineStatesManager: + """Reads the beamline states from their yaml file.""" + + @staticmethod + def initialize_states(states_file): + """ + Returns the states and modifiers defined in the specified states file. + """ + with open(states_file, "r", encoding="utf-8") as f: + cfg = yaml.safe_load(f) + states = {} + allow_modifiers = {} + + for name, config in cfg["states"].items(): + state = BeamlineState(name) + allow_modifiers[state] = config.pop("allow_modifiers", False) + states[state] = config + + return states, allow_modifiers + + +def planner_deps(): + """Define the dependencies between beamline positions""" + return { + ("bs_z", "samp"): [("aerotech_x", "out"), ("diag_y", "out"), ("coll_y", "out")], + ("aerotech_x", "in"): [("diag_y", "out"), ("bs_z", "safe")], + ("aerotech_x", "out"): [("diag_y", "out"), ("bs_z", "safe")], + ("diag_y", "scint"): [("aerotech_x", "out"), ("bs_z", "safe"), ("cryo_pos", "out")], + ("diag_y", "i1"): [("aerotech_x", "out"), ("bs_z", "safe"), ("cryo_pos", "out")], + ("bs_pos", "out"): [("bs_z", "safe")], + ("bs_pos", "in"): [("bs_z", "safe")], + ("diag_y", "out"): [("bs_z", "safe")], + ("diag_y", "park"): [("bs_z", "safe")], + ("coll_y", "out"): [("bs_z", "safe")], + ("coll_y", "park"): [("bs_z", "safe")], + ("coll_y", "in"): [("bs_z", "safe")], + ("coll_y", "intermediate"): [("bs_z", "safe")], + } diff --git a/mx_bec/device_planner/environment.py b/mx_bec/device_planner/environment.py new file mode 100644 index 0000000..210bfac --- /dev/null +++ b/mx_bec/device_planner/environment.py @@ -0,0 +1,116 @@ +"""Initialise sample environment devices and beamline states.""" + +import importlib +import os +from dataclasses import dataclass +from pathlib import Path + +from mx_bec.device_planner.build import DefineStatesManager, DeviceManager, planner_deps +from mx_bec.device_planner.planner import StateChangePlanner + + +@dataclass +class Environment: + """Define configuration files for a beamline and BEC deployment.""" + + beamline: str + + beamline_configs = { + "x06sa": { + "name": "PXI", + "package": "pxi_bec", + "devices": "pxi-devices.yaml", + "states": "pxi-beamline-states.yaml", + }, + "x10sa": { + "name": "PXII", + "package": "pxii_bec", + "devices": "pxii-devices.yaml", + "states": "pxii-beamline-states.yaml", + }, + "x06da": { + "name": "PXIII", + "package": "pxiii_bec", + "devices": "pxiii-devices.yaml", + "states": "pxiii-beamline-states.yaml", + }, + } + + valid_deployments = ("test", "production") + + def __post_init__(self): + + if self.beamline not in self.beamline_configs: + raise ValueError( + f"Unknown beamline '{self.beamline}'. Choose from {list(self.beamline_configs)}" + ) + + cfg = self.beamline_configs[self.beamline] + self.beamline_name = cfg["name"] + + # Import whichever deployment BEC has already made available + package = importlib.import_module(cfg["package"]) + + self.bec_dir = Path(package.__file__).resolve().parent + + self.device_config_dir = self.bec_dir / "device_configs" + self.lut_dir = self.bec_dir / "macros" / "luts" + + # Runtime files generated by daily setup + self.daily_setup_dir = self.bec_dir / "daily_setup_files" + self.daily_setup_dir.mkdir(exist_ok=True) + + self.devices_file = self.device_config_dir / cfg["devices"] + self.states_file = self.device_config_dir / cfg["states"] + + # Determine which deployment is being used + self.deployment = self._get_deployment() + + if not self.devices_file.exists(): + raise FileNotFoundError(f"Device configuration not found: {self.devices_file}") + + if not self.states_file.exists(): + raise FileNotFoundError(f"State configuration not found: {self.states_file}") + + def _get_deployment(self): + """Determine deployment from the loaded package path.""" + + for deployment in ("test", "production"): + if deployment in self.bec_dir.parts: + return deployment + + raise RuntimeError(f"Could not determine BEC deployment from {self.bec_dir}") + + +def init_beamline_environment(dev, scans): + """ + Initialise beamline positioned devices and state planner, for the BEC devices `dev` (e.g. + `client.device_manager.devices`) and the BEC scans `scans` (e.g. `client.scans`). + """ + + beamline = os.environ["BEAMLINE"] + + env = Environment(beamline=beamline) + + print("=" * 60) + print(f"Beamline : {beamline}") + print(f"BEC deployment : {env.deployment.upper()}") + print(f"Devices file : {env.devices_file}") + print(f"States file : {env.states_file}") + print("=" * 60) + + # Initialise positioned devices + device_manager = DeviceManager() + devices = device_manager.initialize_devices(env.devices_file, dev, scans) + + # Initialise beamline states + state_manager = DefineStatesManager() + states, allow_modifiers = state_manager.initialize_states(env.states_file) + + # Set up dependencies + deps = planner_deps() + + # Set up planner + planner = StateChangePlanner(dev, devices, states, allow_modifiers, deps) + + return env, devices, planner diff --git a/mx_bec/device_planner/guards.py b/mx_bec/device_planner/guards.py new file mode 100644 index 0000000..1306af9 --- /dev/null +++ b/mx_bec/device_planner/guards.py @@ -0,0 +1,93 @@ +"""Setup guards for devices.""" + + +class GuardViolation(Exception): + """Raised when a guarded move is not allowed.""" + + +class AtPositionGuard: + """Guard that checks if a device is in a specific position.""" + + def __init__(self, device, position): + self.device = device + self.pos = position + + def check(self): + """Check if the device is in the specified position.""" + if self.device.pos != self.pos: + raise GuardViolation(f"{self.device.bec_name} must be in the '{self.pos}' position") + # print("move allowed") + return True + + def requirement(self): + """Return the requirement for the guard.""" + return (self.device.bec_name, self.pos) + + +class MinMaxGuard: + """Guard that checks if a device is within a specific range.""" + + def __init__(self, device, limit_value, direction): + self.device = device + self.limit_value = limit_value + self.direction = direction # direction: 'max' or 'min' + + def check(self): + """Check if the device is within the specified range.""" + if self.direction == "less_than": + if not (self.device.actual - self.device.tol) <= self.limit_value: + raise GuardViolation( + f"{self.device.bec_name} must be less than or equal to {self.limit_value} mm" + ) + elif self.direction == "more_than": + if not (self.device.actual + self.device.tol) >= self.limit_value: + raise GuardViolation( + f"{self.device.bec_name} must be greater than or equal to {self.limit_value} mm" + ) + else: + raise ValueError( + f"Invalid direction '{self.direction}'. Use 'less_than' or 'more_than'." + ) + + # print("move allowed") + return True + + def requirement(self): + """Return the requirement for the guard.""" + # planner cannot handle numeric constraints directly + # return None -> planner ignores + return None + + +def guards_setup(d): + """Define guards for devices.""" + guards = {} + guards["bs_safe"] = AtPositionGuard(d["bs_z"], position="safe") + guards["bs_max_blin"] = MinMaxGuard( + d["bs_z"], direction="less_than", limit_value=d["bs_z"].positions["max_blin"] + ) + guards["bs_work_min"] = MinMaxGuard( + d["bs_z"], direction="more_than", limit_value=d["bs_z"].positions["work_min"] + ) + guards["bs_pos_in"] = AtPositionGuard(d["bs_pos"], position="in") + guards["gonx_out"] = MinMaxGuard( + d["aerotech_x"], direction="less_than", limit_value=d["aerotech_x"].positions["out"] + ) + guards["gonx_safe"] = AtPositionGuard(d["aerotech_x"], position="safe") + guards["diag_y_out"] = MinMaxGuard( + d["diag_y"], direction="less_than", limit_value=d["diag_y"].positions["out"] + ) + guards["coll_y_out"] = MinMaxGuard( + d["coll_y"], direction="less_than", limit_value=d["coll_y"].positions["out"] + ) + return guards + + +def attach_guards(d): + """Attach guards to devices.""" + g = guards_setup(d) + d["diag_y"].guards.append(g["bs_work_min"].check) + d["bl_pos"].guards.append(g["bs_max_blin"].check) + d["bs_pos"].guards.append(g["bs_safe"].check) + d["bs_z"].guards.append(g["bs_pos_in"].check) + d["coll_y"].guards.append(g["bs_work_min"].check) diff --git a/mx_bec/device_planner/planner.py b/mx_bec/device_planner/planner.py new file mode 100644 index 0000000..b6e4609 --- /dev/null +++ b/mx_bec/device_planner/planner.py @@ -0,0 +1,226 @@ +"""Planner to move between beamline states""" + +from collections import defaultdict, deque +from enum import Enum + + +class BeamlineState(str, Enum): + """List of beamline states""" + + ROBOT_SAMPLE_EXCHANGE = "robot_sample_exchange" + SAMPLE_ALIGNMENT = "sample_alignment" + DATA_COLLECTION = "data_collection" + DC_XRF = "DC_XRF" + MANUAL_SAMPLE_EXCHANGE = "manual_sample_exchange" + BEAM_VISUALISATION = "beam_visualisation" + FLUX_MEASUREMENT = "flux_measurement" + BEAMSTOP_ALIGNMENT = "beamstop_alignment" + MAINTENANCE = "maintenance" + XTAL_SNAPSHOT = "xtal_snapshot" + DET_DIODE = "det_diode" + + +class TemperatureMode(str, Enum): + """List of temperature modes""" + + CRYO = "cryo" + ROOM_TEMP = "room_temp" + + +class StateChangePlanner: + """Moves devices to the correct positions to achieve a given state""" + + def __init__( + self, + dev, + devices, + states: dict[BeamlineState, dict[str, str]], + allow_modifiers=None, + deps=None, + debug=False, + ): + self.dev = dev # the BEC devices, e.g. `client.device_manager.devices` + self.devices = devices # the position devices, by name + self.states = states + self.allow_modifiers = allow_modifiers or {} + self.deps = deps + self.debug = debug + + self.modifiers = { + TemperatureMode.CRYO: {"cryo_pos": "in"}, + TemperatureMode.ROOM_TEMP: {"cryo_pos": "out"}, + } + + def _merged_state(self, state, modifier): + target = dict(self.states[state]) + + if modifier: + if isinstance(modifier, str): + modifier = TemperatureMode(modifier) + + if self.allow_modifiers.get(state, False): + target.update(self.modifiers[modifier]) + return target + + def move_to(self, state_name, modifier=None): + """Move devices to the correct positions to achieve a given state""" + + # Close the fast shutter before moving anything + self.dev.bcu_shutter.put(0) + + if isinstance(state_name, str): + state_name = BeamlineState(state_name) + target = self._merged_state(state_name, modifier) + + plan = self._plan(target) + + print("PLAN:") + for i, stage in enumerate(plan): + print(f"Stage {i + 1}: {stage}") + + for stage in plan: + for pd_devs, pos in stage: + d = self.devices[pd_devs] + if not d.is_at(pos): + + if self.debug: + print(f"→ Moving {pd_devs} -> {pos}") + # print(" Before:", self.get_states()) + + try: + d.move(pos) + + except Exception as e: + print(f"Exception occurred: {e}") + print(f"\nFAILED MOVE: {pd_devs} -> {pos}") + print("States at failure:", self.get_positions()) + raise + + def available_states(self): + """Return a list of available states""" + return list(self.states.keys()) + + def state_devices(self): + """Return the set of devices that participate in + beamline state definitions""" + + devices = set() + + for state in self.states.values(): + devices.update(state.keys()) + + return sorted(devices) + + def get_positions(self): + """Return current positions of devices that are used + in state transitions""" + return {name: self.devices[name].pos for name in self.state_devices()} + + def print_positions(self): + """Return current state of all devices""" + for name in self.state_devices(): + device = self.devices[name] + + print(f"{name:10s} : {device.pos:10s} value: {device.actual:.5g}") + + def diff_states(self, before): + """Return a dict of {device: (before, after)} pairs for devices that changed state""" + after = self.get_positions() + return {k: (before[k], after[k]) for k in before if before[k] != after[k]} + + def __get_closest_states(self): + """ + Return states ordered by number of mismatches. + """ + + results = [] + + for state in self.states: + + config = self._merged_state(state, None) + + mismatches = [] + + for dev, expected in config.items(): + + if not self.devices[dev].is_at(expected): + mismatches.append((dev, self.devices[dev].pos, expected)) + + results.append((state.name, len(mismatches), mismatches)) + + return sorted(results, key=lambda x: x[1]) + + def closest_states(self, n=5): + + for state, count, mismatches in self.__get_closest_states()[:n]: + + print(f"\n{state}: {count} mismatch(es)") + + for dev, actual, expected in mismatches: + print(f" {dev:15s} " f"{actual:10s} -> {expected}") + + def current_state(self): + """Return all current matching BeamlineState and TemperatureMode combinations, + prioritizing non-None modifiers first.""" + matches = [] # Store all matching (state, modifier) pairs + ignore_keys = {"bl_bright", "fl_bright"} + + for state in self.states: + # Start with prioritized modifiers: Non-None first, then None. + modifiers = list(self.modifiers.keys()) + modifiers.append(None) # Add `None` as a fallback after real modifiers. + + for modifier in modifiers: + # Combine state and modifier to get full configuration + config = self._merged_state(state, modifier) + + # Check if all devices match their expected positions + if all(self.devices[d].is_at(p) for d, p in config.items() if d not in ignore_keys): + matches.append((state.name, modifier.name if modifier else "None")) + + return matches if matches else None + + def is_state(self, state, modifier=None): + """Check if the current state matches the given state and modifier.""" + actual = self.current_state() + if not actual: + return False + + if modifier is None: + # match any modifier + return any(s == state.name for s, _ in actual) + + return (state.name, modifier.name) in actual + + def _plan(self, target): + + graph = defaultdict(set) + indeg = defaultdict(int) + nodes = set() + + for dev, pos in target.items(): + node = (dev, pos) + nodes.add(node) + + for dep in self.deps.get(node, []): + graph[dep].add(node) + indeg[node] += 1 + nodes.add(dep) + + q = deque(n for n in nodes if indeg[n] == 0) + stages = [] + + while q: + stage = list(q) + stages.append(stage) + q.clear() + + for n in stage: + for m in graph[n]: + indeg[m] -= 1 + if indeg[m] == 0: + q.append(m) + + if sum(len(s) for s in stages) != len(nodes): + raise RuntimeError("Circular dependency in state dependencies") + return stages diff --git a/mx_bec/device_planner/policies.py b/mx_bec/device_planner/policies.py new file mode 100644 index 0000000..580b7b0 --- /dev/null +++ b/mx_bec/device_planner/policies.py @@ -0,0 +1,78 @@ +"""Define guard policies for devices in the beamline.""" + +from mx_bec.device_planner.guards import GuardViolation, guards_setup + + +def is_sample_area_clear_for_beamstop(d): + """Check if the sample area is clear of diag_y, coll_y, and gonx""" + g = guards_setup(d) + if g["diag_y_out"].check() and g["coll_y_out"].check() and g["gonx_out"].check(): + return True + return False + + +def is_sample_area_clear_for_gonx(d): + """Check if the sample area is clear of diag_y and bs_z""" + g = guards_setup(d) + if g["diag_y_out"].check() and g["bs_work_min"].check(): + return True + return False + + +def make_aerotech_x_policy(d): + """Create the policy for aerotech_x""" + + def aerotech_x_policy(target): + cfg = d["aerotech_x"].positions + if target >= cfg["out"] and not is_sample_area_clear_for_gonx(d): + raise GuardViolation("Sample area is not clear") + + return aerotech_x_policy + + +def make_bs_z_policy(d): + """Create the policy for bs_z""" + + def bs_z_policy(target): + """Checks that the target position is within limits""" + cfg = d["bs_z"].positions + # Lower bound + if target < cfg["work_min"] and not is_sample_area_clear_for_beamstop(d): + raise GuardViolation("Sample area is not clear") + if target < cfg["min"]: + raise GuardViolation( + f"Requested beamstop Z {target} is below recommended minimum {cfg['min']}" + ) + # Upper bound + if d["bl_pos"].pos == "in" and target > cfg["max_blin"]: + raise GuardViolation( + f"Beamstop Z cannot move beyond {cfg['max_blin']} when backlight is IN" + ) + + return bs_z_policy + + +def make_diag_y_policy(d): + """Create the policy for diag_y""" + + def diag_y_policy(target): + cfg = d["diag_y"].positions + # Don't move in if the goniometer is in + if d["aerotech_x"].actual >= d["aerotech_x"].positions["in"] and target > cfg["out"]: + raise GuardViolation( + f"Diagnostic device cannot move beyond {cfg['out']} mm when goniometer is not OUT" + ) + # Don't move if cryocooler is in + if d["cryo_pos"].pos == "in" and target > cfg["out"]: + raise GuardViolation( + f"Diagnostic device cannot move beyond {cfg['out']} mm when cryocooler is IN" + ) + + return diag_y_policy + + +def attach_policies(d): + """Attach the policies to the devices""" + d["bs_z"].policy = make_bs_z_policy(d) + d["aerotech_x"].policy = make_aerotech_x_policy(d) + d["diag_y"].policy = make_diag_y_policy(d) diff --git a/mx_bec/device_planner/position_device.py b/mx_bec/device_planner/position_device.py new file mode 100644 index 0000000..48c8cde --- /dev/null +++ b/mx_bec/device_planner/position_device.py @@ -0,0 +1,134 @@ +"""Set up the positioned devices for mock or real motors""" + +from dataclasses import dataclass, field +from typing import Any, Callable, Union + +from bec_lib.device import Device +from bec_lib.logger import bec_logger + + +def motor_resolver(dev, bec_name): + """Used to handle aerotech and smargon motors: find the motor called `bec_name`, or the + component it names (e.g. "aerotech_x" -> aerotech.x), in the BEC devices `dev`.""" + + candidates = [bec_name, bec_name.replace("_", ".")] + + for path in candidates: + try: + obj = dev + + for part in path.split("."): + obj = getattr(obj, part) + + return obj + + except Exception: # noqa: BLE001, S110 + pass + + raise ValueError(f"Cannot resolve motor for '{bec_name}'") + + +@dataclass +class PositionDevice: + """Generic device that moves between named or numeric positions""" + + bec_name: str + mot_device: Any = None + positions: dict[str, float] = field(default_factory=dict) + tol: float = 0.1 + # device_timeout = 3 + guards: list[Callable[[], None]] = field(default_factory=list) + policy: Callable[[float], None] | None = None + allow_arbitrary: bool = False + move_method: str = "motor" + dev: Any = None # the BEC devices, e.g. `client.device_manager.devices` + scans: Any = None # the BEC scans, e.g. `client.scans` + + def __post_init__(self): + # Normalize position names + self.positions = {k.lower(): v for k, v in self.positions.items()} + + def _check_guards(self): + """Check if guards exist""" + for g in self.guards: + g() + + def _resolve_target(self, target: str | float) -> float: + """Convert target into a motor position""" + + if isinstance(target, str): + name = target.lower() + try: + bec_logger.logger.info( + f"attempting to find position {name} from bec device {self.bec_name} userParameter." + ) + bec_device: Device = self.dev[self.bec_name] + position = bec_device.user_parameter[target] + + bec_logger.logger.info( + f"obtained position {position} - compare to cached value {self.positions.get(target)}" + ) + return position + except Exception as e: + bec_logger.logger.debug( + f"Failed to fetch user parameter for device {self.bec_name} and target {target} from bec, falling back to cached position {e}" + ) + + if name not in self.positions: + raise ValueError(f"Unknown position '{target}'") + + return self.positions[name] + + if isinstance(target, (float, int)): + if not self.allow_arbitrary: + raise ValueError(f"{self.bec_name} only accepts named positions") + return float(target) + + raise TypeError("Target must be str or float") + + def move(self, target: str | float): + """Move the device and wait until it is there""" + pos = self._resolve_target(target) + + self._check_guards() + + if self.policy: + self.policy(pos) + + if self.move_method == "signal": + self.mot_device.put(pos) + else: + self.scans.mv(self.mot_device, pos, relative=False).wait() + + def mv(self, target: str | float): + """Start moving the device and return the scan report, to wait on (with a timeout)""" + + pos = self._resolve_target(target) + + self._check_guards() + + if self.policy: + self.policy(pos) + + return self.scans.mv(self.mot_device, pos, relative=False) + + @property + def actual(self) -> float: + """Return the actual position of the device.""" + return self.mot_device.read()[self.bec_name]["value"] + + @property + def pos(self) -> str: + """Return the closest matching position""" + + for name, pos in self.positions.items(): + if abs(self.actual - pos) <= self.tol: + return name + + return "unknown" + + def is_at(self, target: str | float) -> bool: + """Return True if the device is at the given position.""" + + pos = self._resolve_target(target) + return abs(self.actual - pos) <= self.tol diff --git a/mx_bec/optical_centering.py b/mx_bec/optical_centering.py index 2cae007..a8748c2 100644 --- a/mx_bec/optical_centering.py +++ b/mx_bec/optical_centering.py @@ -6,6 +6,7 @@ from aarelcinfer_client import Client as AareLcClient from aarelcinfer_client.models import LatestPredictionModel from bec_lib.logger import bec_logger +from mx_bec.calc import samcam_pixels_to_microns from mx_bec.sample_info import OpticalCenteringResults if TYPE_CHECKING: @@ -32,5 +33,16 @@ class OpticalPrediction: logger.info("Updating latest prediction on sample info") if self._client.sample_info: self._client.sample_info.optical_centering_results = OpticalCenteringResults( - prediction=latest + prediction=latest, microns_per_pixel=self.microns_per_pixel() ) + + def microns_per_pixel(self) -> float: + """Size of a sample camera pixel on the sample, at the current zoom.""" + camera = self._client.aare_config.camera + zoom = self._client.devices.scam_zoom.user_readback.get() + return samcam_pixels_to_microns( + 1, + zoom, + multiplier=camera.translation_factor_b / 1000, + exponent=camera.translation_factor_a, + ) diff --git a/mx_bec/sample_info.py b/mx_bec/sample_info.py index ecd5912..7525550 100644 --- a/mx_bec/sample_info.py +++ b/mx_bec/sample_info.py @@ -12,6 +12,10 @@ class OpticalCenteringResults(BaseModel): """Outputs from the optical centering stage""" prediction: LatestPredictionModel + microns_per_pixel: float = Field( + description="Size of a pixel of the prediction's image on the sample, from the sample " + "camera calibration at the zoom the image was taken with" + ) timestamp: float = Field(default_factory=time.time) diff --git a/pyproject.toml b/pyproject.toml index 0d88214..71ac8fb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,7 +16,7 @@ dependencies = [ "aarecommon", "aare_config", "aarelcinfer_client==0.1.1a8", - "jfjoch_client>=1.0.0rc166", # only pre-releases exist; the rc specifier lets pip pick them + "jfjoch_client>=1.0.0rc166", # only pre-releases exist; the rc specifier lets pip pick them "bec_lib>=3.130.3", "bec-server>=3.130.3", "bec-ipython-client>=3.130.3", @@ -38,7 +38,6 @@ dev = [ "ophyd_devices", "bec_server", "pytest", - "pytest-cov", "pytest-mock", "pytest-asyncio", "pytest-timeout", @@ -80,4 +79,3 @@ line-length = 100 [tool.ruff.format] skip-magic-trailing-comma = true - diff --git a/tests/unit/test_device_planner.py b/tests/unit/test_device_planner.py new file mode 100644 index 0000000..e6ef782 --- /dev/null +++ b/tests/unit/test_device_planner.py @@ -0,0 +1,160 @@ +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest +import yaml + +from mx_bec.device_planner import ( + BeamlineState, + DefineStatesManager, + GuardViolation, + PositionDevice, + StateChangePlanner, + TemperatureMode, + build_devices, + motor_resolver, +) + +DEVICES = { + "bs_z": {"userParameter": {"safe": 50.0, "samp": 10.0}}, + "cryo_pos": {"userParameter": {"in": 1.0, "out": 0.0, "move_method": "signal"}}, + "aerotech": {"userParameter": {"tol": 0.01, "x": {"in": 0.0, "out": -20.0}}}, + "not_positioned": {}, +} +STATES = { + "states": { + "data_collection": {"allow_modifiers": True, "bs_z": "samp", "aerotech_x": "out"}, + "maintenance": {"bs_z": "safe", "aerotech_x": "in"}, + } +} +# aerotech_x has to be out before the beamstop moves to the sample +DEPS = {("bs_z", "samp"): [("aerotech_x", "out")]} + + +class FakeMotor: + def __init__(self, name: str, value: float = 0.0, user_parameter: dict | None = None): + self.name = name + self.value = value + self.user_parameter = user_parameter or {} + + def read(self): + return {self.name: {"value": self.value}} + + def put(self, value): + self.value = value + + +class FakeDevices(SimpleNamespace): + def __getitem__(self, name): + return getattr(self, name) + + +@pytest.fixture +def moves(): + return [] + + +@pytest.fixture +def scans(moves): + def mv(motor, position, relative=False): + assert relative is False + moves.append((motor.name, position)) + motor.value = position + return MagicMock() + + return SimpleNamespace(mv=mv) + + +@pytest.fixture +def dev(): + return FakeDevices( + bs_z=FakeMotor("bs_z", 50.0, DEVICES["bs_z"]["userParameter"]), + cryo_pos=FakeMotor("cryo_pos", 0.0, DEVICES["cryo_pos"]["userParameter"]), + aerotech=SimpleNamespace(x=FakeMotor("aerotech_x", 0.0)), + bcu_shutter=FakeMotor("bcu_shutter", 1.0), + ) + + +@pytest.fixture +def planner(tmp_path, dev, scans): + devices_file, states_file = tmp_path / "devices.yaml", tmp_path / "states.yaml" + devices_file.write_text(yaml.safe_dump(DEVICES)) + states_file.write_text(yaml.safe_dump(STATES)) + devices = build_devices(devices_file, dev, scans) + states, allow_modifiers = DefineStatesManager.initialize_states(states_file) + return StateChangePlanner(dev, devices, states, allow_modifiers, DEPS) + + +def test_motor_resolver_finds_devices_and_components(dev): + assert motor_resolver(dev, "bs_z") is dev.bs_z + assert motor_resolver(dev, "aerotech_x") is dev.aerotech.x + with pytest.raises(ValueError): + motor_resolver(dev, "no_such_motor") + + +def test_devices_and_states_are_built_from_the_yaml_files(planner): + assert set(planner.devices) == {"bs_z", "cryo_pos", "aerotech_x"} + assert planner.available_states() == [BeamlineState.DATA_COLLECTION, BeamlineState.MAINTENANCE] + assert planner.state_devices() == ["aerotech_x", "bs_z"] + assert planner.get_positions() == {"aerotech_x": "in", "bs_z": "safe"} + assert planner.is_state(BeamlineState.MAINTENANCE) + assert not planner.is_state(BeamlineState.DATA_COLLECTION) + + +def test_move_to_closes_the_shutter_and_moves_in_dependency_order(planner, dev, moves): + planner.move_to("data_collection") + assert dev.bcu_shutter.value == 0 + assert moves == [("aerotech_x", -20.0), ("bs_z", 10.0)] + assert planner.is_state(BeamlineState.DATA_COLLECTION) + + moves.clear() + planner.move_to(BeamlineState.DATA_COLLECTION) # already there: nothing moves + assert moves == [] + + +def test_modifier_is_applied_where_the_state_allows_it(planner, dev, moves): + planner.move_to(BeamlineState.DATA_COLLECTION, TemperatureMode.CRYO) + assert dev.cryo_pos.value == 1.0 # moved by put(), as its move_method is "signal" + assert ("cryo_pos", 1.0) not in moves + assert planner.is_state(BeamlineState.DATA_COLLECTION, TemperatureMode.CRYO) + + planner.move_to(BeamlineState.MAINTENANCE, "room_temp") # no modifiers allowed there + assert dev.cryo_pos.value == 1.0 + + +def test_unknown_state_is_rejected_before_anything_moves(planner, moves): + with pytest.raises(ValueError): + planner.move_to("no_such_state") + assert moves == [] + + +def test_circular_dependencies_are_detected(planner): + planner.deps = { + ("bs_z", "samp"): [("aerotech_x", "out")], + ("aerotech_x", "out"): [("bs_z", "samp")], + } + with pytest.raises(RuntimeError, match="Circular"): + planner.move_to(BeamlineState.DATA_COLLECTION) + + +def test_guards_and_policies_stop_a_move(dev, scans, moves): + device = PositionDevice("bs_z", dev.bs_z, {"safe": 50.0, "samp": 10.0}, dev=dev, scans=scans) + + def guard(): + raise GuardViolation("not now") + + device.guards.append(guard) + with pytest.raises(GuardViolation): + device.move("samp") + device.guards.clear() + + def policy(target): + if target < 20: + raise GuardViolation("too close") + + device.policy = policy + with pytest.raises(GuardViolation): + device.move("samp") + assert moves == [] + with pytest.raises(ValueError): + device.move(30.0) # only named positions unless allow_arbitrary -- 2.54.1 From 7eb785416599ba54243dd58a9be3e31d51d6bd30 Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 24 Nov 2026 14:04:11 +0100 Subject: [PATCH 45/46] feat: use mx_bec planner --- .../widgets/aare_bec/task_panel.py | 5 +- mx_bec/configs/__init__.py | 11 + mx_bec/configs/mx_demo_config.yaml | 2 +- mx_bec/configs/simulated_devices.yaml | 365 ++++++++++++++++++ mx_bec/configs/simulated_states.yaml | 196 ++++++++++ mx_bec/device_planner/__init__.py | 3 +- mx_bec/device_planner/environment.py | 45 ++- mx_bec/device_planner/guards.py | 1 - mx_bec/devices/sim_stages.py | 32 +- mx_bec/tasks/mx_tasks.py | 14 +- tests/unit/test_change_state_task.py | 10 +- tests/unit/test_device_planner.py | 62 +++ tests/unit/test_devices.py | 8 +- 13 files changed, 708 insertions(+), 46 deletions(-) create mode 100644 mx_bec/configs/simulated_devices.yaml create mode 100644 mx_bec/configs/simulated_states.yaml diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py index 74950fd..23e5ce4 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -19,6 +19,7 @@ from qtpy.QtWidgets import ( QWidget, ) +from mx_bec.device_planner import BeamlineState from mx_bec.tasks import Client, MxTasks logger = bec_logger.logger @@ -96,10 +97,6 @@ class MxTaskPanel(BECWidget, QWidget): def _change_state_box(self, parent: QWidget) -> QGroupBox: """One button per beamline state, each requesting the `change_state` task.""" - from pxii_bec.macros.beamline_planner import ( # pyright: ignore[reportMissingImports] - BeamlineState, - ) - box = QGroupBox("change_state", parent=parent) grid = QGridLayout(box) for i, state in enumerate(BeamlineState): diff --git a/mx_bec/configs/__init__.py b/mx_bec/configs/__init__.py index 15f35b0..ce8c08c 100644 --- a/mx_bec/configs/__init__.py +++ b/mx_bec/configs/__init__.py @@ -7,6 +7,9 @@ if TYPE_CHECKING: from bec_lib.client import BECClient MX_DEMO_CONFIG = Path(__file__).parent / "mx_demo_config.yaml" +# the simulated beamline which the device planner uses if BEAMLINE=SIMULATED +MX_SIMULATED_DEVICES = Path(__file__).parent / "simulated_devices.yaml" +MX_SIMULATED_STATES = Path(__file__).parent / "simulated_states.yaml" def load_mx_demo_config(client: BECClient, force: bool = False) -> None: @@ -14,3 +17,11 @@ def load_mx_demo_config(client: BECClient, force: bool = False) -> None: if client.config is None: raise RuntimeError("BEC client is not started") client.config.update_session_with_file(str(MX_DEMO_CONFIG), force=force) + + +def load_mx_simulated_config(client: BECClient, force: bool = False) -> None: + """Replace the current BEC session's device config with the simulated beamline for + development, which has the devices the beamline states are made of (BEAMLINE=SIMULATED).""" + if client.config is None: + raise RuntimeError("BEC client is not started") + client.config.update_session_with_file(str(MX_SIMULATED_DEVICES), force=force) diff --git a/mx_bec/configs/mx_demo_config.yaml b/mx_bec/configs/mx_demo_config.yaml index 26107b2..725e280 100644 --- a/mx_bec/configs/mx_demo_config.yaml +++ b/mx_bec/configs/mx_demo_config.yaml @@ -27,7 +27,7 @@ eiger: ##################### Sample stages ######################## ############################################################ -# Aerotech rotation stage: x/y/z translation (mm) under the omega rotation axis (deg). +# Aerotech rotation stage: x/y/z translation (mm) under the omega rotation axis u (deg). aerotech: readoutPriority: baseline deviceClass: pxii_bec.devices.SimAerotechStage diff --git a/mx_bec/configs/simulated_devices.yaml b/mx_bec/configs/simulated_devices.yaml new file mode 100644 index 0000000..a6d2073 --- /dev/null +++ b/mx_bec/configs/simulated_devices.yaml @@ -0,0 +1,365 @@ +############################################################ +# Simulated MX beamline for development. +# +# Used when the BEAMLINE environment variable is set to SIMULATED: the device planner +# (mx_bec.device_planner) then takes the positions of the sample environment devices from the +# userParameter entries in this file, and the beamline states from simulated_states.yaml. +# +# Every device here is a simulation: either from ophyd_devices.sim or from mx_bec.devices +# (re-exported through the pxii_bec plugin, which is what the device server can load). The +# names and the named positions follow the PXII device config; the positions of the simulated +# stages are scaled down to fit their travel. Load it into a running BEC with +# from mx_bec.configs import load_mx_simulated_config +# load_mx_simulated_config(bec) +############################################################ + +############################################################ +####################### Detector ########################### +############################################################ + +eiger: + readoutPriority: async + deviceClass: ophyd_devices.SimCamera + deviceConfig: + device_access: true + deviceTags: + - detector + enabled: true + readOnly: false + softwareTrigger: true + +det_z: + description: Detector distance + readoutPriority: baseline + deviceClass: ophyd_devices.SimPositioner + deviceConfig: + delay: 1 + limits: + - 100 + - 1000 + tolerance: 0.01 + update_frequency: 400 + deviceTags: + - sample environment + enabled: true + readOnly: false + userParameter: + mse: 800 + vis: 800 + +det_cov: + description: Detector cover + readoutPriority: baseline + deviceClass: ophyd_devices.sim.sim_signals.SetableSignal + deviceConfig: + value: 1 + deviceTags: + - sample environment + enabled: true + readOnly: false + userParameter: + close: 1 + open: 2 + type: discrete + move_method: signal + +############################################################ +##################### Sample stages ######################## +############################################################ + +# Aerotech rotation stage: x/y/z translation (mm) under the omega rotation axis u (deg). +aerotech: + readoutPriority: baseline + deviceClass: pxii_bec.devices.SimAerotechStage + deviceConfig: + deviceTags: + - sample stage + - aerotech + enabled: true + readOnly: false + userParameter: + tol: 0.01 + x: + in: 0.0 + out: -2.0 + safe: -4.0 + y: + mount: 0.0 + work: -0.03 + z: + mount: 0.0 + work: -0.01 + u: + mount: 0.0 + work: 0.0 + +# Smargon mini-kappa goniometer head on top of the aerotech: x/y/z (mm), phi/chi (deg). +smargon: + readoutPriority: baseline + deviceClass: pxii_bec.devices.SimGoniometer + deviceConfig: + deviceTags: + - sample stage + - goniometer + enabled: true + readOnly: false + userParameter: + tol: 0.01 + x: + mount: 0.0 + y: + mount: 0.0 + z: + mount: 1.8 + chi: + mount: 0.0 + phi: + mount: 0.0 + +############################################################ +#################### Sample changer ######################## +############################################################ + +robot: + readoutPriority: baseline + deviceClass: pxii_bec.devices.SimSampleChanger + deviceConfig: + mount_time: 2.0 + deviceTags: + - sample changer + enabled: true + readOnly: false + +############################################################ +################## Sample environment ###################### +############################################################ + +# The devices the beamline states are made of. The signals are moved by writing to them +# (move_method: signal), the positioners with a scan. + +bs_z: + description: Beamstop distance from the sample + readoutPriority: baseline + deviceClass: ophyd_devices.SimPositioner + deviceConfig: + delay: 1 + limits: + - 0 + - 80 + tolerance: 0.01 + update_frequency: 400 + deviceTags: + - sample environment + enabled: true + readOnly: false + userParameter: + max_blin: 45.4 + max_blout: 70 + min: 13 + safe: 45.1 + samp: 16.8 + work_min: 20 + type: continuous + +bs_pos: + description: Beamstop in/out + readoutPriority: baseline + deviceClass: ophyd_devices.sim.sim_signals.SetableSignal + deviceConfig: + value: 1 + deviceTags: + - sample environment + enabled: true + readOnly: false + userParameter: + in: 1 + out: 0 + type: discrete + move_method: signal + +coll_y: + description: Collimator + readoutPriority: baseline + deviceClass: ophyd_devices.SimPositioner + deviceConfig: + delay: 1 + limits: + - 0 + - 50 + tolerance: 0.01 + update_frequency: 400 + deviceTags: + - sample environment + enabled: true + readOnly: false + userParameter: + in: 39.0 + intermediate: 32 + out: 20.0 + park: 1 + tol: 0.05 + type: continuous + +diag_y: + description: Diagnostics stage with scintillator and diode + readoutPriority: baseline + deviceClass: ophyd_devices.SimPositioner + deviceConfig: + delay: 1 + limits: + - 0 + - 50 + tolerance: 0.01 + update_frequency: 400 + deviceTags: + - sample environment + enabled: true + readOnly: false + userParameter: + i1: 40.7 + out: 20.0 + park: 1 + scint: 35.74 + tol: 0.3 + type: continuous + +bl_pos: + description: Backlight in/out + readoutPriority: baseline + deviceClass: ophyd_devices.sim.sim_signals.SetableSignal + deviceConfig: + value: 0 + deviceTags: + - sample environment + enabled: true + readOnly: false + userParameter: + in: 1 + out: 0 + type: discrete + move_method: signal + +bl_bright: + description: Backlight brightness + readoutPriority: baseline + deviceClass: ophyd_devices.sim.sim_signals.SetableSignal + deviceConfig: + value: 0.0 + deviceTags: + - sample environment + enabled: true + readOnly: false + userParameter: + "off": 0.0 + "on": 1.3 + tol: 0.01 + type: continuous + move_method: signal + +fl_bright: + description: Front light brightness + readoutPriority: baseline + deviceClass: ophyd_devices.sim.sim_signals.SetableSignal + deviceConfig: + value: 0.0 + deviceTags: + - sample environment + enabled: true + readOnly: false + userParameter: + "off": 0.0 + "on": 3.0 + tol: 0.01 + type: continuous + move_method: signal + +cryo_pos: + description: Cryojet in/out + readoutPriority: baseline + deviceClass: ophyd_devices.sim.sim_signals.SetableSignal + deviceConfig: + value: 1 + deviceTags: + - sample environment + enabled: true + readOnly: false + userParameter: + in: 1 + out: 0 + type: discrete + move_method: signal + +xrf_pos: + description: Fluorescence detector in/out + readoutPriority: baseline + deviceClass: ophyd_devices.sim.sim_signals.SetableSignal + deviceConfig: + value: 0 + deviceTags: + - sample environment + enabled: true + readOnly: false + userParameter: + in: 1 + out: 0 + type: discrete + move_method: signal + +############################################################ +################## Beamline conditions ##################### +############################################################ + +# The fast shutter, which the planner closes before it moves anything. +bcu_shutter: + readoutPriority: baseline + deviceClass: ophyd_devices.sim.sim_signals.SetableSignal + deviceConfig: + value: 0 + deviceTags: + - beamline + enabled: true + readOnly: false + +# The sample camera zoom, which the optical centering sets and reads back. +scam_zoom: + readoutPriority: baseline + deviceClass: ophyd_devices.SimPositioner + deviceConfig: + delay: 1 + limits: + - 1 + - 1000 + tolerance: 0.5 + update_frequency: 400 + deviceTags: + - beamline + enabled: true + readOnly: false + +# 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 + +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/configs/simulated_states.yaml b/mx_bec/configs/simulated_states.yaml new file mode 100644 index 0000000..41d75d4 --- /dev/null +++ b/mx_bec/configs/simulated_states.yaml @@ -0,0 +1,196 @@ +############################################################ +# Beamline states of the simulated MX beamline (BEAMLINE=SIMULATED): for every state, the named +# position of each sample environment device. The positions themselves are the userParameter +# entries in simulated_devices.yaml. +# +# Follows the PXII beamline states. +############################################################ + +states: + robot_sample_exchange: + allow_modifiers: true + bl_pos: in + bl_bright: 'off' + bs_pos: in + bs_z: safe + coll_y: out + cryo_pos: in + det_cov: close + diag_y: out + fl_bright: 'off' + aerotech_x: in + aerotech_y: mount + aerotech_z: mount + aerotech_u: mount + smargon_x: mount + smargon_y: mount + smargon_z: mount + smargon_chi: mount + smargon_phi: mount + xrf_pos: out + + sample_alignment: + allow_modifiers: true + bl_pos: in + bl_bright: 'on' + bs_pos: in + bs_z: safe + coll_y: out + cryo_pos: in + det_cov: close + diag_y: out + fl_bright: 'on' + aerotech_x: in + xrf_pos: out + + data_collection: + allow_modifiers: true + bl_pos: out + bl_bright: 'off' + bs_pos: in + bs_z: safe + coll_y: in + cryo_pos: in + det_cov: open + diag_y: out + fl_bright: 'on' + aerotech_x: in + xrf_pos: out + + DC_XRF: + allow_modifiers: true + bl_bright: 'off' + bs_pos: in + bs_z: safe + coll_y: in + cryo_pos: in + det_cov: close + diag_y: out + fl_bright: 'on' + aerotech_x: in + aerotech_y: work + aerotech_z: work + aerotech_u: mount + xrf_pos: out + + manual_sample_exchange: + allow_modifiers: true + bl_pos: out + bl_bright: 'off' + bs_pos: out + bs_z: safe + coll_y: park + cryo_pos: in + det_cov: close + det_z: mse + diag_y: park + fl_bright: 'off' + aerotech_x: in + aerotech_y: mount + aerotech_z: mount + aerotech_u: mount + smargon_x: mount + smargon_y: mount + smargon_chi: mount + smargon_phi: mount + xrf_pos: out + + beam_visualisation: + bl_pos: out + bl_bright: 'off' + bs_pos: in + bs_z: safe + coll_y: out + cryo_pos: out + det_cov: close + diag_y: scint + fl_bright: 'off' + aerotech_x: out + smargon_x: mount + smargon_y: mount + smargon_chi: mount + smargon_phi: mount + xrf_pos: out + + flux_measurement: + bl_pos: in + bl_bright: 'off' + bs_pos: in + bs_z: safe + coll_y: out + cryo_pos: out + det_cov: close + diag_y: i1 + fl_bright: 'off' + aerotech_x: out + smargon_x: mount + smargon_y: mount + smargon_chi: mount + smargon_phi: mount + xrf_pos: out + + beamstop_alignment: + bl_pos: out + bl_bright: 'off' + bs_pos: in + bs_z: samp + coll_y: out + cryo_pos: out + det_cov: close + diag_y: out + fl_bright: 'on' + aerotech_x: out + aerotech_u: mount + smargon_x: mount + smargon_y: mount + smargon_chi: mount + smargon_phi: mount + xrf_pos: out + + maintenance: + allow_modifiers: true + bl_pos: out + bl_bright: 'off' + bs_pos: out + bs_z: safe + coll_y: park + cryo_pos: in + det_cov: close + diag_y: park + fl_bright: 'off' + aerotech_x: out + aerotech_y: mount + aerotech_z: mount + aerotech_u: mount + smargon_x: mount + smargon_y: mount + smargon_chi: mount + smargon_phi: mount + xrf_pos: out + + xtal_snapshot: + allow_modifiers: true + bl_pos: in + bl_bright: 'on' + bs_pos: in + bs_z: safe + coll_y: intermediate + cryo_pos: in + det_cov: close + diag_y: out + fl_bright: 'on' + xrf_pos: out + + det_diode: + allow_modifiers: true + bl_pos: out + bl_bright: 'off' + bs_pos: in + bs_z: safe + coll_y: out + cryo_pos: in + det_cov: close + diag_y: out + fl_bright: 'off' + aerotech_x: in + xrf_pos: out diff --git a/mx_bec/device_planner/__init__.py b/mx_bec/device_planner/__init__.py index d53bc16..00fe78f 100644 --- a/mx_bec/device_planner/__init__.py +++ b/mx_bec/device_planner/__init__.py @@ -12,7 +12,7 @@ from mx_bec.device_planner.build import ( build_devices, planner_deps, ) -from mx_bec.device_planner.environment import Environment, init_beamline_environment +from mx_bec.device_planner.environment import SIMULATED, Environment, init_beamline_environment from mx_bec.device_planner.guards import ( AtPositionGuard, GuardViolation, @@ -25,6 +25,7 @@ from mx_bec.device_planner.policies import attach_policies from mx_bec.device_planner.position_device import PositionDevice, motor_resolver __all__ = [ + "SIMULATED", "AtPositionGuard", "BeamlineState", "DefineStatesManager", diff --git a/mx_bec/device_planner/environment.py b/mx_bec/device_planner/environment.py index 210bfac..1c93cc5 100644 --- a/mx_bec/device_planner/environment.py +++ b/mx_bec/device_planner/environment.py @@ -2,12 +2,21 @@ import importlib import os +import tempfile from dataclasses import dataclass from pathlib import Path +from bec_lib.logger import bec_logger + from mx_bec.device_planner.build import DefineStatesManager, DeviceManager, planner_deps from mx_bec.device_planner.planner import StateChangePlanner +logger = bec_logger.logger + +SIMULATED = "SIMULATED" +"""Value of the BEAMLINE environment variable which selects the simulated beamline in +`mx_bec/configs`, for development.""" + @dataclass class Environment: @@ -34,6 +43,13 @@ class Environment: "devices": "pxiii-devices.yaml", "states": "pxiii-beamline-states.yaml", }, + SIMULATED: { + "name": "Simulated", + "package": "mx_bec", + "config_dir": "configs", + "devices": "simulated_devices.yaml", + "states": "simulated_states.yaml", + }, } valid_deployments = ("test", "production") @@ -53,11 +69,15 @@ class Environment: self.bec_dir = Path(package.__file__).resolve().parent - self.device_config_dir = self.bec_dir / "device_configs" + self.device_config_dir = self.bec_dir / cfg.get("config_dir", "device_configs") self.lut_dir = self.bec_dir / "macros" / "luts" # Runtime files generated by daily setup - self.daily_setup_dir = self.bec_dir / "daily_setup_files" + if self.simulated: + # nothing to keep, and the package directory may not be writable + self.daily_setup_dir = Path(tempfile.gettempdir()) / "mx_bec_daily_setup_files" + else: + self.daily_setup_dir = self.bec_dir / "daily_setup_files" self.daily_setup_dir.mkdir(exist_ok=True) self.devices_file = self.device_config_dir / cfg["devices"] @@ -72,9 +92,17 @@ class Environment: if not self.states_file.exists(): raise FileNotFoundError(f"State configuration not found: {self.states_file}") + @property + def simulated(self) -> bool: + """Whether this is the simulated beamline for development.""" + return self.beamline == SIMULATED + def _get_deployment(self): """Determine deployment from the loaded package path.""" + if self.simulated: + return "simulated" + for deployment in ("test", "production"): if deployment in self.bec_dir.parts: return deployment @@ -92,12 +120,13 @@ def init_beamline_environment(dev, scans): env = Environment(beamline=beamline) - print("=" * 60) - print(f"Beamline : {beamline}") - print(f"BEC deployment : {env.deployment.upper()}") - print(f"Devices file : {env.devices_file}") - print(f"States file : {env.states_file}") - print("=" * 60) + logger.success( + "Initialised the beamline environment:\n" + f" Beamline : {beamline}\n" + f" BEC deployment : {env.deployment.upper()}\n" + f" Devices file : {env.devices_file}\n" + f" States file : {env.states_file}" + ) # Initialise positioned devices device_manager = DeviceManager() diff --git a/mx_bec/device_planner/guards.py b/mx_bec/device_planner/guards.py index 1306af9..7fdf1a9 100644 --- a/mx_bec/device_planner/guards.py +++ b/mx_bec/device_planner/guards.py @@ -16,7 +16,6 @@ class AtPositionGuard: """Check if the device is in the specified position.""" if self.device.pos != self.pos: raise GuardViolation(f"{self.device.bec_name} must be in the '{self.pos}' position") - # print("move allowed") return True def requirement(self): diff --git a/mx_bec/devices/sim_stages.py b/mx_bec/devices/sim_stages.py index 6c62431..3cad611 100644 --- a/mx_bec/devices/sim_stages.py +++ b/mx_bec/devices/sim_stages.py @@ -1,28 +1,36 @@ """Simulated MX sample stages, built from ophyd_devices SimPositioners.""" from ophyd import Component as Cpt -from ophyd import Device +from ophyd import Device, Kind from ophyd_devices.sim.sim_positioner import SimPositioner +from ophyd_devices.sim.sim_signals import SetableSignal + + +class SimStageAxis(SimPositioner): + """A SimPositioner with a more sensible tolerance.""" + + tolerance = Cpt(SetableSignal, value=0.01, kind=Kind.config) class SimAerotechStage(Device): - """Simulated Aerotech rotation stage: a 3-axis translation under an omega rotation axis. + """Simulated Aerotech rotation stage: a 3-axis translation under the omega rotation axis, `u` + (as on the real Aerotech). - omega is unbounded (low == high limit disables the SimPositioner limit check) so that + u 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]) + x = Cpt(SimStageAxis, name="x", limits=[-5, 5]) + y = Cpt(SimStageAxis, name="y", limits=[-5, 5]) + z = Cpt(SimStageAxis, name="z", limits=[-5, 5]) + u = Cpt(SimStageAxis, name="u", 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]) + x = Cpt(SimStageAxis, name="x", limits=[-5, 5]) + y = Cpt(SimStageAxis, name="y", limits=[-5, 5]) + z = Cpt(SimStageAxis, name="z", limits=[-5, 5]) + phi = Cpt(SimStageAxis, name="phi", limits=[0, 0]) + chi = Cpt(SimStageAxis, name="chi", limits=[0, 45]) diff --git a/mx_bec/tasks/mx_tasks.py b/mx_bec/tasks/mx_tasks.py index fafa8b3..00b7834 100644 --- a/mx_bec/tasks/mx_tasks.py +++ b/mx_bec/tasks/mx_tasks.py @@ -18,13 +18,12 @@ from mx_bec.decisions import ( scan_images, smargon_nudge, ) +from mx_bec.device_planner import BeamlineState, StateChangePlanner, init_beamline_environment from mx_bec.endpoints import StateEndpoints from mx_bec.messages import MXMeasurementSequenceMessage from mx_bec.tasks.core import MxSequenceUpdate, RoleT, TaskManager, task if TYPE_CHECKING: - from pxii_bec.macros.beamline_planner import StateChangePlanner - from mx_bec.service import AareBec logger = bec_logger.logger @@ -51,10 +50,9 @@ class MxTasks(TaskManager[RoleT]): """The beamline state planner, built on first use: `init_beamline_environment` needs the BEAMLINE environment variable and the beamline devices.""" if self._planner is None: - # pyright: ignore[reportMissingImports, reportMissingModuleSource] - from pxii_bec.scripts.init_beamline import init_beamline_environment - - _, _, self._planner = init_beamline_environment() + _, _, self._planner = init_beamline_environment( + self._client.devices, self._client.scans + ) return self._planner @task @@ -77,10 +75,6 @@ class MxTasks(TaskManager[RoleT]): def change_state(self, state: str, modifier: str | None = None) -> None: """Move the beamline devices to `state`, the value of a `BeamlineState` (e.g. "sample_alignment"), optionally with a temperature `modifier` ("cryo" or "room_temp").""" - from pxii_bec.macros.beamline_planner import ( # pyright: ignore[reportMissingImports] - BeamlineState, - ) - target = BeamlineState(state) # reject unknown states before anything moves logger.info(f"Changing beamline state to {target.value}, modifier={modifier}") self.planner.move_to(target, modifier) diff --git a/tests/unit/test_change_state_task.py b/tests/unit/test_change_state_task.py index 2f3a5ea..3959808 100644 --- a/tests/unit/test_change_state_task.py +++ b/tests/unit/test_change_state_task.py @@ -1,8 +1,8 @@ from unittest.mock import MagicMock, patch import pytest -from pxii_bec.macros.beamline_planner import BeamlineState +from mx_bec.device_planner import BeamlineState from mx_bec.tasks import MxTasks, Server @@ -15,15 +15,15 @@ def tasks(): def test_planner_is_built_lazily_from_the_beamline_environment(monkeypatch): monkeypatch.delenv("BEAMLINE", raising=False) - tasks = MxTasks[Server](MagicMock()) # must not need the beamline environment yet + client = MagicMock() + tasks = MxTasks[Server](client) # must not need the beamline environment yet env, devices, planner = MagicMock(), MagicMock(), MagicMock() with patch( - "pxii_bec.scripts.init_beamline.init_beamline_environment", - return_value=(env, devices, planner), + "mx_bec.tasks.mx_tasks.init_beamline_environment", return_value=(env, devices, planner) ) as init: assert tasks.planner is planner assert tasks.planner is planner - init.assert_called_once() + init.assert_called_once_with(client.devices, client.scans) @pytest.mark.parametrize("modifier", [None, "cryo"]) diff --git a/tests/unit/test_device_planner.py b/tests/unit/test_device_planner.py index e6ef782..b22c470 100644 --- a/tests/unit/test_device_planner.py +++ b/tests/unit/test_device_planner.py @@ -4,14 +4,18 @@ from unittest.mock import MagicMock import pytest import yaml +from mx_bec.configs import MX_SIMULATED_DEVICES, MX_SIMULATED_STATES from mx_bec.device_planner import ( + SIMULATED, BeamlineState, DefineStatesManager, + Environment, GuardViolation, PositionDevice, StateChangePlanner, TemperatureMode, build_devices, + init_beamline_environment, motor_resolver, ) @@ -158,3 +162,61 @@ def test_guards_and_policies_stop_a_move(dev, scans, moves): assert moves == [] with pytest.raises(ValueError): device.move(30.0) # only named positions unless allow_arbitrary + + +# ---- the simulated beamline for development (BEAMLINE=SIMULATED) ---- + + +def test_simulated_environment_uses_the_configs_of_mx_bec(): + env = Environment(SIMULATED) + assert env.simulated and env.deployment == "simulated" + assert env.devices_file == MX_SIMULATED_DEVICES + assert env.states_file == MX_SIMULATED_STATES + assert env.daily_setup_dir.is_dir() + + +def test_unknown_beamline_is_rejected(): + with pytest.raises(ValueError, match="Unknown beamline"): + Environment("simulated") # has to be set explicitly, in capitals + + +@pytest.fixture +def simulated_dev(): + """Fake BEC devices for everything in the simulated device config, at the values the + simulated devices start with (0 for the positioners).""" + config = yaml.safe_load(MX_SIMULATED_DEVICES.read_text()) + dev = FakeDevices() + for name, cfg in config.items(): + user = cfg.get("userParameter") or {} + if name in ("aerotech", "smargon"): + axes = {axis: FakeMotor(f"{name}_{axis}") for axis in user if axis != "tol"} + setattr(dev, name, SimpleNamespace(user_parameter=user, **axes)) + else: + value = (cfg.get("deviceConfig") or {}).get("value", 0.0) + setattr(dev, name, FakeMotor(name, value, user)) + return dev + + +def test_simulated_devices_are_valid_for_the_device_server(): + from ophyd_devices.utils.static_device_test import StaticDeviceTest + + results = StaticDeviceTest(config_file=str(MX_SIMULATED_DEVICES)).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 + + +def test_every_simulated_state_can_be_reached(monkeypatch, simulated_dev, scans): + """From the initial positions of the simulated devices, go through every state and back: + the positions, dependencies, guards and policies have to be consistent with each other.""" + monkeypatch.setenv("BEAMLINE", SIMULATED) + env, devices, planner = init_beamline_environment(simulated_dev, scans) + assert env.simulated + assert set(planner.state_devices()) <= set(devices) + states = planner.available_states() + assert set(states) == set(BeamlineState) + for state in [*states, *reversed(states)]: + for modifier in (None, TemperatureMode.CRYO, TemperatureMode.ROOM_TEMP): + planner.move_to(state, modifier) + assert planner.is_state(state), (state, modifier, planner.get_positions()) diff --git a/tests/unit/test_devices.py b/tests/unit/test_devices.py index 764d72d..49965ca 100644 --- a/tests/unit/test_devices.py +++ b/tests/unit/test_devices.py @@ -22,11 +22,11 @@ def test_stage_reads_all_axes(cls): stage.destroy() -def test_omega_is_unbounded(): +def test_rotation_axis_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.u.delay = 0 + stage.u.move(720).wait(timeout=1) + assert stage.u.position == pytest.approx(720, abs=stage.u.tolerance.get()) stage.destroy() -- 2.54.1 From c237f0b730f4d58bb8b9600f6ff0f9b71db718bd Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 24 Nov 2026 14:32:23 +0100 Subject: [PATCH 46/46] feat: run tests against all beamlines --- .gitea/workflows/ci.yml | 63 ++++++++++++++++++++++- mx_bec/configs/__init__.py | 35 ++++++++++--- mx_bec/configs/mx_demo_config.yaml | 12 +++-- mx_bec/configs/simulated_devices.yaml | 12 +++-- pyproject.toml | 1 + tests/e2e/conftest.py | 56 ++++++++++++++++++++ tests/e2e/test_simulated_beamline.py | 74 +++++++++++++++++++++++++++ tests/unit/test_demo_config.py | 11 +++- tests/unit/test_device_planner.py | 8 +-- 9 files changed, 249 insertions(+), 23 deletions(-) create mode 100644 tests/e2e/conftest.py create mode 100644 tests/e2e/test_simulated_beamline.py diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 64e75bb..5e0231f 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -24,6 +24,11 @@ on: required: false type: string default: "main" + BEAMLINE_PLUGIN_BRANCH: + description: "Branch of the beamline plugins (pxi_bec, pxii_bec, pxiii_bec) to install" + required: false + type: string + default: "main" PYTHON_VERSION: description: "Python version to use" required: false @@ -36,6 +41,15 @@ permissions: jobs: test: runs-on: ubuntu-latest + name: "${{ matrix.suite }} tests with ${{ matrix.plugin }}" + strategy: + fail-fast: false + matrix: + # unit: tests/unit; e2e: tests/e2e, against BEC servers running the simulated beamline + suite: [unit, e2e] + # BEC works with exactly one beamline plugin installed, which is what the device server + # loads the mx_bec devices through: run against each of them individually + plugin: [pxi_bec, pxii_bec, pxiii_bec] env: QTWEBENGINE_DISABLE_SANDBOX: 1 QT_QPA_PLATFORM: "offscreen" @@ -58,6 +72,29 @@ jobs: # Find all Copier conflicts except this line run: '! grep -r "<<<<<<< before updating" | grep -v "grep -r \"<<<<<<< before updating"' + # Use the same-named branch of the beamline plugin if it exists (e.g. a feature developed in both repos), otherwise main. + - name: Resolve beamline plugin branch + id: plugin + shell: bash + run: | + ref="${{ inputs.BEAMLINE_PLUGIN_BRANCH || github.head_ref || github.ref_name }}" + auth="$(printf 'x-access-token:%s' '${{ github.token }}' | base64 -w0)" + if git -c "http.extraheader=Authorization: Basic ${auth}" ls-remote --exit-code --heads \ + "${{ github.server_url }}/bec/${{ matrix.plugin }}.git" "refs/heads/${ref}" >/dev/null; then + echo "Using ${{ matrix.plugin }} branch '${ref}'" + else + echo "${{ matrix.plugin }} has no branch '${ref}', using main" + ref=main + fi + echo "ref=${ref}" >> "$GITHUB_OUTPUT" + + - name: Checkout beamline plugin + uses: actions/checkout@v4 + with: + repository: "bec/${{ matrix.plugin }}" + ref: "${{ steps.plugin.outputs.ref }}" + path: "./${{ matrix.plugin }}" + - name: Checkout BEC Core uses: actions/checkout@v4 with: @@ -85,6 +122,8 @@ jobs: sudo apt-get update sudo apt-get install -y libgl1 libegl1 x11-utils libxkbcommon-x11-0 libdbus-1-3 xvfb sudo apt-get -y install libnss3 libxdamage1 libasound2t64 libatomic1 libxcursor1 + # the end-to-end tests start their own redis server + sudo apt-get -y install redis-server - name: Install Python dependencies shell: bash @@ -94,15 +133,37 @@ jobs: uv pip install --system -e ./bec/bec_lib[dev] uv pip install --system -e ./bec/bec_ipython_client uv pip install --system -e ./bec/bec_server[dev] + uv pip install --system -e ./bec/pytest_bec_e2e uv pip install --system -e ./bec_widgets[dev] # MX-internal dependencies (aarecommon, aare_config, jfjoch_client, ...) come from gitea uv pip install --system --extra-index-url https://gitea.psi.ch/api/packages/mx/pypi/simple/ -e ./mx_bec[dev] + uv pip install --system --extra-index-url https://gitea.psi.ch/api/packages/mx/pypi/simple/ -e ./${{ matrix.plugin }} - name: Run Pytest with Coverage + if: matrix.suite == 'unit' id: coverage run: | - if coverage run --rcfile=./mx_bec/pyproject.toml --branch --source=./mx_bec -m pytest --random-order ./mx_bec/tests/; then + if coverage run --rcfile=./mx_bec/pyproject.toml --branch --source=./mx_bec -m pytest --random-order ./mx_bec/tests/unit; then coverage xml --rcfile=./mx_bec/pyproject.toml else test $? -eq 5 fi + + - name: Run end-to-end tests + if: matrix.suite == 'e2e' + shell: bash + run: | + mkdir -p ./e2e_files + pytest -v --start-servers --files-path ./e2e_files ./mx_bec/tests/e2e + + - name: Show server logs if the end-to-end tests fail + if: failure() && matrix.suite == 'e2e' + shell: bash + run: | + shopt -s nullglob + # the BEC services write their logs next to the bec checkout + for log in ./e2e_files/*.log ./bec/logs/*.log; do + echo "::group::${log}" + tail -n 200 "${log}" + echo "::endgroup::" + done diff --git a/mx_bec/configs/__init__.py b/mx_bec/configs/__init__.py index ce8c08c..c1fd95c 100644 --- a/mx_bec/configs/__init__.py +++ b/mx_bec/configs/__init__.py @@ -1,8 +1,11 @@ from __future__ import annotations +import tempfile from pathlib import Path from typing import TYPE_CHECKING +from bec_lib import plugin_helper + if TYPE_CHECKING: from bec_lib.client import BECClient @@ -11,17 +14,37 @@ MX_DEMO_CONFIG = Path(__file__).parent / "mx_demo_config.yaml" MX_SIMULATED_DEVICES = Path(__file__).parent / "simulated_devices.yaml" MX_SIMULATED_STATES = Path(__file__).parent / "simulated_states.yaml" +PLUGIN_PLACEHOLDER = "${BEC_PLUGIN}" + + +def render_config(config: Path, plugin: str | None = None) -> Path: + """Write a copy of a device config in which `${BEC_PLUGIN}` is replaced by the package name + of the beamline plugin (by default the one which is installed), and return its path. + + The device server can only load device classes from ophyd_devices or from the installed + beamline plugin, so the simulated devices of mx_bec are named in the configs as + `${BEC_PLUGIN}.devices.`: the plugin has to re-export them from its `devices` module. + """ + if plugin is None: + # raises ValueError unless exactly one beamline plugin is installed + plugin = plugin_helper.plugin_package_name() + rendered = Path(tempfile.mkdtemp(prefix="mx_bec_config_")) / config.name + rendered.write_text(config.read_text().replace(PLUGIN_PLACEHOLDER, plugin)) + return rendered + + +def _load(client: BECClient, config: Path, force: bool) -> None: + if client.config is None: + raise RuntimeError("BEC client is not started") + client.config.update_session_with_file(str(render_config(config)), force=force) + 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) + _load(client, MX_DEMO_CONFIG, force) def load_mx_simulated_config(client: BECClient, force: bool = False) -> None: """Replace the current BEC session's device config with the simulated beamline for development, which has the devices the beamline states are made of (BEAMLINE=SIMULATED).""" - if client.config is None: - raise RuntimeError("BEC client is not started") - client.config.update_session_with_file(str(MX_SIMULATED_DEVICES), force=force) + _load(client, MX_SIMULATED_DEVICES, force) diff --git a/mx_bec/configs/mx_demo_config.yaml b/mx_bec/configs/mx_demo_config.yaml index 725e280..0323632 100644 --- a/mx_bec/configs/mx_demo_config.yaml +++ b/mx_bec/configs/mx_demo_config.yaml @@ -2,8 +2,10 @@ # Simulated MX beamline for the AareBEC prototype. # # Every device here is a simulation: either from ophyd_devices.sim or from -# mx_bec.devices (re-exported through the pxii_bec plugin, which is what the -# device server can load). Load it into a running BEC with +# mx_bec.devices. The device server can only load the latter through the beamline +# plugin which is installed (pxi_bec, pxii_bec, pxiii_bec), which has to re-export +# them from its `devices` module: ${BEC_PLUGIN} stands for that plugin and is filled +# in when the config is loaded. Load it into a running BEC with # from mx_bec.configs import load_mx_demo_config # load_mx_demo_config(bec) ############################################################ @@ -30,7 +32,7 @@ eiger: # Aerotech rotation stage: x/y/z translation (mm) under the omega rotation axis u (deg). aerotech: readoutPriority: baseline - deviceClass: pxii_bec.devices.SimAerotechStage + deviceClass: ${BEC_PLUGIN}.devices.SimAerotechStage deviceConfig: deviceTags: - sample stage @@ -41,7 +43,7 @@ aerotech: # Smargon mini-kappa goniometer head on top of the aerotech: x/y/z (mm), phi/chi (deg). gonio: readoutPriority: baseline - deviceClass: pxii_bec.devices.SimGoniometer + deviceClass: ${BEC_PLUGIN}.devices.SimGoniometer deviceConfig: deviceTags: - sample stage @@ -55,7 +57,7 @@ gonio: robot: readoutPriority: baseline - deviceClass: pxii_bec.devices.SimSampleChanger + deviceClass: ${BEC_PLUGIN}.devices.SimSampleChanger deviceConfig: mount_time: 2.0 deviceTags: diff --git a/mx_bec/configs/simulated_devices.yaml b/mx_bec/configs/simulated_devices.yaml index a6d2073..172d934 100644 --- a/mx_bec/configs/simulated_devices.yaml +++ b/mx_bec/configs/simulated_devices.yaml @@ -5,8 +5,10 @@ # (mx_bec.device_planner) then takes the positions of the sample environment devices from the # userParameter entries in this file, and the beamline states from simulated_states.yaml. # -# Every device here is a simulation: either from ophyd_devices.sim or from mx_bec.devices -# (re-exported through the pxii_bec plugin, which is what the device server can load). The +# Every device here is a simulation: either from ophyd_devices.sim or from mx_bec.devices. The +# device server can only load the latter through the beamline plugin which is installed +# (pxi_bec, pxii_bec, pxiii_bec), which has to re-export them from its `devices` module: +# ${BEC_PLUGIN} stands for that plugin and is filled in when the config is loaded. The # names and the named positions follow the PXII device config; the positions of the simulated # stages are scaled down to fit their travel. Load it into a running BEC with # from mx_bec.configs import load_mx_simulated_config @@ -70,7 +72,7 @@ det_cov: # Aerotech rotation stage: x/y/z translation (mm) under the omega rotation axis u (deg). aerotech: readoutPriority: baseline - deviceClass: pxii_bec.devices.SimAerotechStage + deviceClass: ${BEC_PLUGIN}.devices.SimAerotechStage deviceConfig: deviceTags: - sample stage @@ -96,7 +98,7 @@ aerotech: # Smargon mini-kappa goniometer head on top of the aerotech: x/y/z (mm), phi/chi (deg). smargon: readoutPriority: baseline - deviceClass: pxii_bec.devices.SimGoniometer + deviceClass: ${BEC_PLUGIN}.devices.SimGoniometer deviceConfig: deviceTags: - sample stage @@ -122,7 +124,7 @@ smargon: robot: readoutPriority: baseline - deviceClass: pxii_bec.devices.SimSampleChanger + deviceClass: ${BEC_PLUGIN}.devices.SimSampleChanger deviceConfig: mount_time: 2.0 deviceTags: diff --git a/pyproject.toml b/pyproject.toml index 71ac8fb..e0f792d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,6 +41,7 @@ dev = [ "pytest-mock", "pytest-asyncio", "pytest-timeout", + "pytest-bec-e2e", # fixtures which start BEC servers for the end-to-end tests "fakeredis[lua]", "fastapi", "uvicorn", diff --git a/tests/e2e/conftest.py b/tests/e2e/conftest.py new file mode 100644 index 0000000..337825c --- /dev/null +++ b/tests/e2e/conftest.py @@ -0,0 +1,56 @@ +"""Fixtures for the end-to-end tests, which run against real BEC servers with the simulated MX +beamline loaded. They build on the `pytest_bec_e2e` plugin; run them with + + pytest --start-servers --files-path tests/e2e + +which starts a Redis server and the BEC servers for the test session (without `--start-servers` +they have to be running already). +""" + +import pytest +from bec_lib.client import BECClient +from bec_lib.redis_connector import RedisConnector +from bec_lib.service_config import ServiceConfig +from bec_lib.tests.utils import wait_for_empty_queue + +from mx_bec.configs import MX_SIMULATED_DEVICES, load_mx_simulated_config, render_config +from mx_bec.device_planner import SIMULATED + +CLIENT_SHUTDOWN_TIMEOUT_S = 10 + + +@pytest.fixture(scope="session") +def test_config_yaml_file_path(): + """The device config which `bec_servers` (pytest_bec_e2e) copies next to the service config.""" + return render_config(MX_SIMULATED_DEVICES) + + +@pytest.fixture(scope="session") +def simulated_bec_session(bec_redis_fixture, bec_services_config_file_path, bec_servers): + """A BEC client connected to the test servers, with the simulated beamline loaded once for + the whole session.""" + config = ServiceConfig(bec_services_config_file_path) + bec = BECClient(config, RedisConnector, forced=True, wait_for_server=True) + bec.start() + load_mx_simulated_config(bec, force=True) + try: + yield bec + finally: + bec.shutdown(per_thread_timeout_s=CLIENT_SHUTDOWN_TIMEOUT_S) + bec._client._reset_singleton() + + +@pytest.fixture +def bec(simulated_bec_session): + """The client on the simulated beamline, with an empty, running scan queue.""" + bec = simulated_bec_session + bec.queue.request_queue_reset() + bec.queue.request_scan_continuation() + wait_for_empty_queue(bec) + return bec + + +@pytest.fixture +def simulated_beamline(monkeypatch): + """Select the simulated beamline for the device planner.""" + monkeypatch.setenv("BEAMLINE", SIMULATED) diff --git a/tests/e2e/test_simulated_beamline.py b/tests/e2e/test_simulated_beamline.py new file mode 100644 index 0000000..563f877 --- /dev/null +++ b/tests/e2e/test_simulated_beamline.py @@ -0,0 +1,74 @@ +"""The simulated beamline for development (BEAMLINE=SIMULATED), on real BEC servers.""" + +import pytest +import yaml + +from mx_bec.configs import MX_SIMULATED_DEVICES +from mx_bec.device_planner import BeamlineState, TemperatureMode, init_beamline_environment + +MOVE_TIMEOUT_S = 30 + + +def _value(device) -> float: + return next(iter(device.read(cached=False).values()))["value"] + + +def test_all_simulated_devices_are_loaded(bec): + config = yaml.safe_load(MX_SIMULATED_DEVICES.read_text()) + assert set(config) <= set(bec.device_manager.devices.keys()) + + +@pytest.mark.parametrize( + "name, target", + [("bl_pos", 1), ("bl_pos", 0), ("det_cov", 2), ("cryo_pos", 0), ("bl_bright", 1.3)], +) +def test_simulated_signals_can_be_moved_with_a_scan(bec, name, target): + device = bec.device_manager.devices[name] + bec.scans.mv(device, target, relative=False).wait(timeout=MOVE_TIMEOUT_S) + assert _value(device) == pytest.approx(target) + + +def test_simulated_signals_can_be_written_directly(bec): + """What the device planner does for a device with `move_method: signal`.""" + shutter = bec.device_manager.devices.bcu_shutter + for target in (1, 0): + shutter.put(target) + assert _value(shutter) == target + + +@pytest.mark.parametrize( + "path, target, tolerance", + [ + ("bs_z", 45.1, 0.1), + ("aerotech.x", -2.0, 0.01), + ("aerotech.u", 90.0, 0.01), + ("smargon.z", 1.8, 0.01), + ("smargon.chi", 10.0, 0.01), + ], +) +def test_simulated_positioners_reach_their_target(bec, path, target, tolerance): + """The stages have to get as close to a named position as the device planner checks it.""" + device = bec.device_manager.devices + for part in path.split("."): + device = getattr(device, part) + bec.scans.mv(device, target, relative=False).wait(timeout=MOVE_TIMEOUT_S) + assert _value(device) == pytest.approx(target, abs=tolerance) + + +def test_device_planner_moves_between_beamline_states(bec, simulated_beamline): + env, devices, planner = init_beamline_environment(bec.device_manager.devices, bec.scans) + assert env.simulated + assert set(planner.available_states()) == set(BeamlineState) + + for state, modifier in [ + (BeamlineState.ROBOT_SAMPLE_EXCHANGE, TemperatureMode.CRYO), + (BeamlineState.DATA_COLLECTION, TemperatureMode.CRYO), + (BeamlineState.BEAM_VISUALISATION, None), + (BeamlineState.MANUAL_SAMPLE_EXCHANGE, TemperatureMode.ROOM_TEMP), + (BeamlineState.SAMPLE_ALIGNMENT, TemperatureMode.CRYO), + ]: + planner.move_to(state, modifier) + assert planner.is_state(state), (state, planner.get_positions()) + target = planner._merged_state(state, modifier) + assert all(devices[name].is_at(position) for name, position in target.items()) + assert _value(bec.device_manager.devices.bcu_shutter) == 0 # closed before anything moves diff --git a/tests/unit/test_demo_config.py b/tests/unit/test_demo_config.py index 6a3a5b2..2258351 100644 --- a/tests/unit/test_demo_config.py +++ b/tests/unit/test_demo_config.py @@ -1,13 +1,20 @@ from ophyd_devices.utils.static_device_test import StaticDeviceTest -from mx_bec.configs import MX_DEMO_CONFIG +from mx_bec.configs import MX_DEMO_CONFIG, render_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( + results = StaticDeviceTest(config_file=str(render_config(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"} + + +def test_render_config_fills_in_the_plugin(tmp_path): + assert "${BEC_PLUGIN}" in MX_DEMO_CONFIG.read_text() + rendered = render_config(MX_DEMO_CONFIG, plugin="some_bec").read_text() + assert "${BEC_PLUGIN}" not in rendered + assert "deviceClass: some_bec.devices.SimAerotechStage" in rendered diff --git a/tests/unit/test_device_planner.py b/tests/unit/test_device_planner.py index b22c470..c0c87f5 100644 --- a/tests/unit/test_device_planner.py +++ b/tests/unit/test_device_planner.py @@ -4,7 +4,7 @@ from unittest.mock import MagicMock import pytest import yaml -from mx_bec.configs import MX_SIMULATED_DEVICES, MX_SIMULATED_STATES +from mx_bec.configs import MX_SIMULATED_DEVICES, MX_SIMULATED_STATES, render_config from mx_bec.device_planner import ( SIMULATED, BeamlineState, @@ -200,9 +200,9 @@ def simulated_dev(): def test_simulated_devices_are_valid_for_the_device_server(): from ophyd_devices.utils.static_device_test import StaticDeviceTest - results = StaticDeviceTest(config_file=str(MX_SIMULATED_DEVICES)).run_with_list_output( - connect=True, timeout_per_device=10 - ) + results = StaticDeviceTest( + config_file=str(render_config(MX_SIMULATED_DEVICES)) + ).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 -- 2.54.1