From e55ef1e080978fdb586da1e6eeea5a8c6d5807d8 Mon Sep 17 00:00:00 2001 From: David Perl Date: Thu, 29 Oct 2026 14:53:04 +0100 Subject: [PATCH] WIP feat: add optical centering stuff --- big_todo_list.md | 2 + pyproject.toml | 9 ++- src/aare_bec_proto/actors/core.py | 9 +-- src/aare_bec_proto/actors/mx_automation.py | 15 ++--- src/aare_bec_proto/devices/aerotech.py | 2 +- src/aare_bec_proto/devices/http.py | 2 +- .../devices/optical_centring.py | 39 ------------ .../devices/smargopolo_smargon.py | 40 +++++++++++++ src/aare_bec_proto/endpoints.py | 13 +++- src/aare_bec_proto/messages.py | 12 ++++ src/aare_bec_proto/service.py | 37 ++++++++++-- src/aare_bec_proto/states/optical_centring.py | 60 +++++++++++++++++++ 12 files changed, 174 insertions(+), 66 deletions(-) create mode 100644 big_todo_list.md delete mode 100644 src/aare_bec_proto/devices/optical_centring.py create mode 100644 src/aare_bec_proto/states/optical_centring.py diff --git a/big_todo_list.md b/big_todo_list.md new file mode 100644 index 0000000..b2007b2 --- /dev/null +++ b/big_todo_list.md @@ -0,0 +1,2 @@ +- on updates to the workflow, send sample events to DB +- diff --git a/pyproject.toml b/pyproject.toml index 37bbda6..c92c4bb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,6 +5,7 @@ description = "Prototype of a BEC-integrated replacement for AareDAQ" readme = "README.md" requires-python = ">=3.11" dependencies = [ + "aarecommon", "bec_lib>=3.130.3", "bec-server>=3.130.3", # bec_server imports bec_ipython_client at package import time but does not @@ -24,7 +25,7 @@ test = [ "pytest-timeout", "fakeredis[lua]", "diff-cover", - "ruff>=0.15" + "ruff>=0.15", ] [project.scripts] @@ -49,9 +50,7 @@ python_files = ["test_*.py"] norecursedirs = ["scripts", ".venv", "logs", "docs"] asyncio_mode = "auto" asyncio_default_fixture_loop_scope = "function" -markers = [ - "integration: tests that require external systems or secrets", -] +markers = ["integration: tests that require external systems or secrets"] [build-system] requires = ["setuptools>=75.6.0"] @@ -73,7 +72,7 @@ multi_line_output = 3 line-length = 100 [tool.ruff.lint] -isort.split-on-trailing-comma=false +isort.split-on-trailing-comma = false [tool.ruff.format] skip-magic-trailing-comma = true diff --git a/src/aare_bec_proto/actors/core.py b/src/aare_bec_proto/actors/core.py index 64e8dfd..73b6cda 100644 --- a/src/aare_bec_proto/actors/core.py +++ b/src/aare_bec_proto/actors/core.py @@ -3,13 +3,13 @@ from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Any, ClassVar -from bec_lib.client import BECClient from bec_lib.endpoints import EndpointInfo from bec_lib.logger import bec_logger from bec_server.actors.actor import SubscriptionActor from aare_bec_proto.endpoints import ActorEndpoints from aare_bec_proto.messages import MXMeasurementSequenceMessage +from aare_bec_proto.service import AareBec if TYPE_CHECKING: from bec_lib.messages import BoolConfigDefaultFalse @@ -30,7 +30,8 @@ class MXAutomationActor(SubscriptionActor, ABC): config_key: ClassVar[str] """Unique key used to build this actor's config endpoints, e.g. "optical_centring".""" - def __init__(self, client: BECClient, name: str, exec_id: str): + 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) @@ -55,9 +56,9 @@ class MXAutomationActor(SubscriptionActor, ABC): return super().evaluate() @abstractmethod - def condition(self, client: BECClient) -> bool: + def condition(self, client: AareBec) -> bool: """Whether `action` should run; evaluated after every successful milestone message.""" @abstractmethod - def action(self, client: BECClient) -> None: + def action(self, client: AareBec) -> None: """What to do when `.condition()` evaluates `True`.""" diff --git a/src/aare_bec_proto/actors/mx_automation.py b/src/aare_bec_proto/actors/mx_automation.py index 5060804..38be512 100644 --- a/src/aare_bec_proto/actors/mx_automation.py +++ b/src/aare_bec_proto/actors/mx_automation.py @@ -12,6 +12,7 @@ from bec_lib.logger import bec_logger from aare_bec_proto.actors.core import MXAutomationActor from aare_bec_proto.endpoints import StateEndpoints from aare_bec_proto.messages import MXMeasurementSequenceMessage +from aare_bec_proto.service import AareBec logger = bec_logger.logger @@ -24,18 +25,14 @@ class OnSampleMountedRunOpticalCentring(MXAutomationActor): def default_monitor_endpoints(self) -> set[EndpointInfo[type[MXMeasurementSequenceMessage]]]: return {StateEndpoints.sample_mounted()} - def condition(self, client: BECClient) -> bool: + def condition(self, client: AareBec) -> bool: return self.last_message is not None - def action(self, client: BECClient) -> None: + def action(self, client: AareBec) -> None: assert self.last_message is not None sample_id = self.last_message.sample_id logger.info(f"{self.name}: running optical centring for sample {sample_id}") - # TODO: replace with the real centring procedure; publish the milestone from there. - client.connector.set_and_publish( - StateEndpoints.optical_centring_done(), - MXMeasurementSequenceMessage(sample_id=sample_id, success=True), - ) + client.tasks.run_optical_centring() class OnOpticalCentringDoneRunXrayCentring(MXAutomationActor): @@ -46,10 +43,10 @@ class OnOpticalCentringDoneRunXrayCentring(MXAutomationActor): def default_monitor_endpoints(self) -> set[EndpointInfo[type[MXMeasurementSequenceMessage]]]: return {StateEndpoints.optical_centring_done()} - def condition(self, client: BECClient) -> bool: + def condition(self, client: AareBec) -> bool: return self.last_message is not None - def action(self, client: BECClient) -> None: + def action(self, client: AareBec) -> None: assert self.last_message is not None sample_id = self.last_message.sample_id logger.info(f"{self.name}: running X-ray centring for sample {sample_id}") diff --git a/src/aare_bec_proto/devices/aerotech.py b/src/aare_bec_proto/devices/aerotech.py index 6839f6b..f51bb50 100644 --- a/src/aare_bec_proto/devices/aerotech.py +++ b/src/aare_bec_proto/devices/aerotech.py @@ -92,7 +92,7 @@ class AerotechController(HttpDeviceControllerWithConfigVelocity): 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(self.params_for_move(axis, val, velocity)) + 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: diff --git a/src/aare_bec_proto/devices/http.py b/src/aare_bec_proto/devices/http.py index 66d12a1..0e69acd 100644 --- a/src/aare_bec_proto/devices/http.py +++ b/src/aare_bec_proto/devices/http.py @@ -200,7 +200,7 @@ class HttpDeviceSignal(HttpDeviceSignalBase): def _socket_set(self, val: float): self._controller.put(self._axis_id, val) - def get(self, **kwargs): + def get(self, **kwargs) -> float: if self._controller.monitor_stopped(): self._controller.start_monitor() return super().get(**kwargs) diff --git a/src/aare_bec_proto/devices/optical_centring.py b/src/aare_bec_proto/devices/optical_centring.py deleted file mode 100644 index f280c48..0000000 --- a/src/aare_bec_proto/devices/optical_centring.py +++ /dev/null @@ -1,39 +0,0 @@ -from __future__ import annotations - -import os -from typing import TYPE_CHECKING - -from aare_config import AareConfigClient -from aarelcinfer_client import AuthenticatedClient -from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase - -if TYPE_CHECKING: - from bec_lib.devicemanager import DeviceManagerBase, ScanInfo - -AARELC_KEY = os.environ["AARELC_INFER_API_KEY"] - - -class OpticalCentring(PSIDeviceBase): - def get_target(self): - # TODO: fetch target from inference server - # TODO: in smargon, use this method and go there - ... - - def __init__( - self, - prefix: str = "", - *, - name: str, - scan_info: ScanInfo | None = None, - device_manager: DeviceManagerBase | None = None, - **kwargs, - ): - self._config = AareConfigClient(redis_url="", key_prefix="config") - super().__init__( - prefix=prefix, name=name, scan_info=scan_info, device_manager=device_manager, **kwargs - ) - self._aarelc_client = AuthenticatedClient( - base_url=self._config.aarelc_infer.host, - token=AARELC_KEY, - headers={"X-API-KEY": AARELC_KEY}, - ) diff --git a/src/aare_bec_proto/devices/smargopolo_smargon.py b/src/aare_bec_proto/devices/smargopolo_smargon.py index a7c4618..994a3fb 100644 --- a/src/aare_bec_proto/devices/smargopolo_smargon.py +++ b/src/aare_bec_proto/devices/smargopolo_smargon.py @@ -1,3 +1,5 @@ +import numpy as np +from aarecommon.math.coordinate import Coordinate from ophyd import Component as Cpt from ophyd_devices import PSIDeviceBase @@ -33,6 +35,7 @@ class SmargonController(HttpDeviceController): class Smargon(HttpOphydDevice): + USER_ACCESS = "nudge_in_lab_frame" controller_class = SmargonController x = Cpt(HttpDeviceSignal, axis_identifier="SHX", tolerance=0.01) @@ -40,3 +43,40 @@ class Smargon(HttpOphydDevice): 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) + omega = Cpt(HttpDeviceSignal, axis_identifier="OMEGA", tolerance=0.01) + + def nudge_in_lab_frame(self, x_mm: float, y_mm: float, z_mm: 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)""" + x_mm, y_mm, z_mm = self._lab_frame_offset_to_smargon_nudge(x_mm, y_mm, z_mm) + self.x.set(self.x.get() + x_mm) + + def _lab_frame_offset_to_smargon_nudge(self, x_mm: float, y_mm: float, z_mm: 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.chi.get(), decimals=1)) + chi = np.radians(np.around(self.phi.get(), decimals=1)) + omega = np.radians(np.around(self.omega.get(), 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/src/aare_bec_proto/endpoints.py b/src/aare_bec_proto/endpoints.py index ee020ae..ed5a75e 100644 --- a/src/aare_bec_proto/endpoints.py +++ b/src/aare_bec_proto/endpoints.py @@ -1,7 +1,7 @@ from bec_lib.endpoints import EndpointInfo, EndpointType, MessageOp from bec_lib.messages import BoolConfigDefaultFalse -from aare_bec_proto.messages import MXMeasurementSequenceMessage +from aare_bec_proto.messages import MXMeasurementSequenceMessage, OpticalPredictionMessage class StateEndpoints: @@ -52,3 +52,14 @@ class ActorEndpoints: message_type=BoolConfigDefaultFalse, message_op=MessageOp.STREAM, ) + + +class DataAnalysisEndpoints: + @staticmethod + def optical_prediction(): + """Stream for image analysis predictions (for optical centring, grid scan parameters...)""" + return EndpointInfo( + endpoint=f"{EndpointType.USER.value}/mx/analysis/optical_prediction", + message_type=OpticalPredictionMessage, + message_op=MessageOp.STREAM, + ) diff --git a/src/aare_bec_proto/messages.py b/src/aare_bec_proto/messages.py index ae9d1db..9b6f514 100644 --- a/src/aare_bec_proto/messages.py +++ b/src/aare_bec_proto/messages.py @@ -1,6 +1,9 @@ +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): @@ -10,3 +13,12 @@ class MXMeasurementSequenceMessage(BECMessage): 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/src/aare_bec_proto/service.py b/src/aare_bec_proto/service.py index 4eeadfd..131fda7 100644 --- a/src/aare_bec_proto/service.py +++ b/src/aare_bec_proto/service.py @@ -1,41 +1,50 @@ 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 aare_bec_proto.actor_manager import AareActorManager from aare_bec_proto.constants import AareBecWorkflowState +from aare_bec_proto.endpoints import StateEndpoints +from aare_bec_proto.messages import MXMeasurementSequenceMessage +from aare_bec_proto.states.optical_centring import OpticalPrediction if TYPE_CHECKING: from bec_lib.redis_connector import RedisConnector from bec_lib.service_config import ServiceConfig +CONFIG_REDIS_URL = os.environ.get("CONFIG_REDIS_URL", "redis://mx-x10sa-queue-01") logger = bec_logger.logger class AareBec(BECClient): - """Prototype BEC service standing in for AareDAQ. - - A BECClient (so the actors get device access, the scan queue and beamline states for free) - which additionally owns the MX automation actors. Like any BECClient it only connects to - Redis in `start()`. - """ + """Custom MX BEC client, managing automation tasks and data flow.""" def __init__( self, config: ServiceConfig, connector_cls: type[RedisConnector], **kwargs ) -> None: super().__init__(config, connector_cls, name="AareBec", **kwargs) + self.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) 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) @@ -45,3 +54,19 @@ class AareBec(BECClient): self.actor_manager.shutdown() self.actor_manager = None super().shutdown(per_thread_timeout_s) + + +class MxTasks: + def __init__(self, client: AareBec): + self._client = client + + def run_optical_centring(self, sample_id: int): + """Update optical centring prediction, then tell Smargon to move there.""" + if (target := self._client.optical_prediction.get_target_point_offset_mm()) is not None: + self._client.devices(target) + else: + logger.warning("No target point obtained from AareLc") + self._client.connector.set_and_publish( + StateEndpoints.optical_centring_done(), + MXMeasurementSequenceMessage(sample_id=sample_id, success=True), + ) diff --git a/src/aare_bec_proto/states/optical_centring.py b/src/aare_bec_proto/states/optical_centring.py new file mode 100644 index 0000000..3c669fb --- /dev/null +++ b/src/aare_bec_proto/states/optical_centring.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 aare_bec_proto.endpoints import DataAnalysisEndpoints +from aare_bec_proto.messages import OpticalPredictionMessage + +if TYPE_CHECKING: + from aare_bec_proto.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.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.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.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, + )