From f7cc9d8e327de60b8d3d42adf22dbe2a10399bd3 Mon Sep 17 00:00:00 2001 From: David Perl Date: Thu, 26 Nov 2026 15:39:59 +0100 Subject: [PATCH] feat: use smargopolo nudge directly --- mx_bec/devices/aerotech.py | 2 +- mx_bec/devices/http.py | 21 ++++-- mx_bec/devices/smargopolo_smargon.py | 97 +++++++++++++--------------- mx_bec/tasks/mx_tasks.py | 3 +- tests/unit/mock_smargopolo.py | 32 +++++++++ tests/unit/test_smargon.py | 62 ++++++++++-------- 6 files changed, 132 insertions(+), 85 deletions(-) diff --git a/mx_bec/devices/aerotech.py b/mx_bec/devices/aerotech.py index 952a98e..6dfdc3d 100644 --- a/mx_bec/devices/aerotech.py +++ b/mx_bec/devices/aerotech.py @@ -114,7 +114,7 @@ class AerotechController(HttpDeviceControllerWithConfigVelocity): self._rest_post(params={"timeout": timeout}, endpoint=self._wait_till_done_endpoint) -class Aerotech(HttpOphydDevice): +class Aerotech(HttpOphydDevice[AerotechController]): """Aerotech sample stage driven through the AareScan REST API. Triggering runs the grid scan configured in `gridscan_config`.""" diff --git a/mx_bec/devices/http.py b/mx_bec/devices/http.py index 0e69acd..7fad29c 100644 --- a/mx_bec/devices/http.py +++ b/mx_bec/devices/http.py @@ -1,7 +1,7 @@ import time from abc import ABC, abstractmethod from threading import Event, RLock, Thread -from typing import Any +from typing import Any, Generic, TypeVar from bec_lib.logger import bec_logger from ophyd import Kind, OphydObject, Signal @@ -99,8 +99,11 @@ class HttpDeviceController(OphydObject, ABC): 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) + def _rest_put( + 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.put(self._prefix + endpoint, params=params, json=body) if not resp.ok: raise HttpRestError(resp, value=params) @@ -232,8 +235,16 @@ class HttpVelocitySignal(Signal): self._controller.register_velocity(axis_id=self._axis_id, signal=self) -class HttpOphydDevice(PSIDeviceBase): - controller_class: type[HttpDeviceController] +ControllerT = TypeVar("ControllerT", bound=HttpDeviceController) + + +class HttpOphydDevice(PSIDeviceBase, Generic[ControllerT]): + """Device whose signals talk to a REST interface through a controller. Subclasses give the + controller type twice: as the type parameter, for type checkers, and as `controller_class`, + which is what gets instantiated.""" + + controller_class: type[ControllerT] + controller: ControllerT def __init__( self, *, name: str, prefix: str = "", scan_info=None, device_manager=None, **kwargs diff --git a/mx_bec/devices/smargopolo_smargon.py b/mx_bec/devices/smargopolo_smargon.py index 5772a02..64eba87 100644 --- a/mx_bec/devices/smargopolo_smargon.py +++ b/mx_bec/devices/smargopolo_smargon.py @@ -1,6 +1,6 @@ +import time from typing import ClassVar -import numpy as np from bec_lib.logger import bec_logger from ophyd import Component as Cpt @@ -10,6 +10,7 @@ logger = bec_logger.logger _TIMESTAMP_ID = "__timestamp" _POLL_INTERVAL_SLOW = 0.1 +_TARGET_CHANGE_MM = 1e-9 # targets further apart than this are different targets class SmargonController(HttpDeviceController): @@ -17,6 +18,7 @@ class SmargonController(HttpDeviceController): _readback_endpoint = "/readbackSCS" _target_endpoint = "/targetSCS" + _nudge_endpoint = "/nudgeBCS" def __init__(self, *, prefix, **kwargs): self._readbacks: dict[str, float] = {} @@ -31,6 +33,14 @@ class SmargonController(HttpDeviceController): def put(self, axis: str, val: float): self._rest_put(params={axis: val}) + def get_targets(self) -> dict[str, float]: + """The current target position of every axis.""" + return self._rest_get(self._target_endpoint) + + def nudge(self, x_mm: float, y_mm: float, z_mm: float): + """Request a move relative to the current target, given in the beamline (lab) frame.""" + self._rest_put(params={"BX": x_mm, "BY": y_mm, "BZ": z_mm}, endpoint=self._nudge_endpoint) + def stop(self): # There doesn't appear to be a stop endpoint on the server # Best effort: set the target to the current position @@ -43,7 +53,7 @@ class SmargonController(HttpDeviceController): self._rest_put(params=targets) -class Smargon(HttpOphydDevice): +class Smargon(HttpOphydDevice[SmargonController]): USER_ACCESS: ClassVar[list[str]] = ["nudge_in_lab_frame"] controller_class = SmargonController @@ -54,56 +64,39 @@ class Smargon(HttpOphydDevice): 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, - timeout_s: float | None = 2.0, + self, x_mm: float, y_mm: float, z_mm: float = 0.0, timeout_s: float | None = 2.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) - 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(timeout=timeout_s) + """Apply a relative move in the lab frame (the beamline coordinate system of smargopolo) + and wait for it to finish, for at most `timeout_s` (forever if None). - 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)) + The smargopolo server does the conversion to a move of its own axes (`/nudgeBCS`, see + `nudge.cpp` there), for its current phi and chi targets and its own reading of the omega + rotation stage the smargon sits on.""" + if x_mm == 0 and y_mm == 0 and z_mm == 0: + return + logger.info(f"Nudging smargon in the lab frame by {x_mm=}, {y_mm=}, {z_mm=}") + targets_before = self.controller.get_targets() + self.controller.nudge(x_mm, y_mm, z_mm) + self._wait_for_nudge(targets_before, timeout_s) - 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 + def _wait_for_nudge(self, targets_before: dict[str, float], timeout_s: float | None): + """The nudge request only places the move: wait for the server to set the new targets, + which differ from `targets_before`, and then for the axes to reach them.""" + axes: list[HttpDeviceSignal] = [self.x, self.y, self.z] + deadline = None if timeout_s is None else time.monotonic() + timeout_s + while True: + targets = self.controller.get_targets() + target_set = any( + abs(targets[axis._axis_id] - targets_before[axis._axis_id]) > _TARGET_CHANGE_MM + for axis in axes + ) + if target_set and all( + abs(axis.get() - targets[axis._axis_id]) <= axis.tolerance for axis in axes + ): + return + if deadline is not None and time.monotonic() > deadline: + raise TimeoutError( + f"Smargon nudge did not finish within {timeout_s} s " + f"({'targets ' + str(targets) if target_set else 'no new targets were set'})" + ) + time.sleep(_POLL_INTERVAL_SLOW) diff --git a/mx_bec/tasks/mx_tasks.py b/mx_bec/tasks/mx_tasks.py index 00b7834..a707a7d 100644 --- a/mx_bec/tasks/mx_tasks.py +++ b/mx_bec/tasks/mx_tasks.py @@ -274,7 +274,8 @@ class MxTasks(TaskManager[RoleT]): 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) + # smargopolo applies the nudge for its own reading of omega, which is now the raster angle + self._client.devices.smargon.nudge_in_lab_frame(dx, dy) info.current_offset_mm = (offset_x_mm, offset_y_mm) @task diff --git a/tests/unit/mock_smargopolo.py b/tests/unit/mock_smargopolo.py index 41f1ca2..8473bf2 100644 --- a/tests/unit/mock_smargopolo.py +++ b/tests/unit/mock_smargopolo.py @@ -5,6 +5,7 @@ Run it standalone with `python mock_smargopolo.py` or in-process via `run_in_thr """ import asyncio +import math import random import socket import time @@ -61,6 +62,10 @@ def make_motors() -> dict[str, Motor]: motors: dict[str, Motor] = make_motors() +# What the server reads for the omega rotation stage which the smargon sits on, in degrees (the +# `omega` key of a dict so that tests can set it). +rotation_stage: dict[str, float] = {"omega": 0.0} + @asynccontextmanager async def lifespan(app: FastAPI): @@ -117,6 +122,33 @@ async def target_scs(req: Request): return {"targets": targets, "message": "Move started"} +def nudge_bcs_to_scs(nx: float, ny: float, nz: float) -> tuple[float, float, float]: + """The beamline-frame nudge as a move of SHX, SHY, SHZ: `calculateSH` of smargopolo's + nudge.cpp, with its orientation tweak parameters (offsetOMEGA, FPRX, FPRY, FPRZ) at zero.""" + omega = math.radians(rotation_stage["omega"]) + phi = math.radians(motors["PHI"].target) + chi = math.radians(motors["CHI"].target) + co, so = math.cos(omega), math.sin(omega) + cp, sp = math.cos(phi), math.sin(phi) + cc, sc = math.cos(chi), math.sin(chi) + return ( + -nz * co * sp - ny * so * sp + nx * cp * sc - ny * co * cc * cp + nz * so * cc * cp, + -nz * co * cp - ny * so * cp - nx * sc * sp + ny * co * cc * sp - nz * so * cc * sp, + -nx * cc - ny * co * sc + nz * so * sc, + ) + + +@app.put("/nudgeBCS") +async def nudge_bcs(BX: float = 0.0, BY: float = 0.0, BZ: float = 0.0): + """Move relative to the current targets (not the readbacks), as smargopolo does.""" + for axis, nudge in zip(("SHX", "SHY", "SHZ"), nudge_bcs_to_scs(BX, BY, BZ)): + motor = motors[axis] + motor.update() + motor.target += nudge + motor.moving = True + return [BX, BY, BZ] + + def free_port() -> int: with socket.socket() as sock: sock.bind(("127.0.0.1", 0)) diff --git a/tests/unit/test_smargon.py b/tests/unit/test_smargon.py index 1157d7b..554d2b7 100644 --- a/tests/unit/test_smargon.py +++ b/tests/unit/test_smargon.py @@ -1,9 +1,10 @@ """Tests of the smargopolo Smargon device against the in-process mock server.""" -import numpy as np +from unittest import mock + import pytest import requests -from mock_smargopolo import AXES, MockSmargopolo, motors +from mock_smargopolo import AXES, MockSmargopolo, motors, rotation_stage from mx_bec.devices.smargopolo_smargon import Smargon @@ -21,6 +22,7 @@ def smargon(server): for motor in motors.values(): motor.position = motor.target = 0.0 motor.moving = False + rotation_stage["omega"] = 0.0 dev = Smargon(name="smargon", prefix=server.url) dev.wait_for_connection() yield dev @@ -28,19 +30,6 @@ def smargon(server): 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 @@ -74,17 +63,38 @@ def test_nudge_in_lab_frame_at_zero_angles(smargon): 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_nudge_is_converted_by_the_server_for_its_angles(smargon): + # at chi = 90 a lab-frame x offset is a smargon x move instead of a -z move; at omega = 90 a + # lab-frame y offset is a smargon -y move instead of a -x move + motors["CHI"].position = motors["CHI"].target = 90.0 + smargon.nudge_in_lab_frame(0.2, 0.0) + assert motors["SHX"].target == pytest.approx(0.2) + assert motors["SHZ"].target == pytest.approx(0.0) + assert smargon.x.get() == pytest.approx(0.2, abs=TOL) + + motors["CHI"].position = motors["CHI"].target = 0.0 + rotation_stage["omega"] = 90.0 + smargon.nudge_in_lab_frame(0.0, 0.2) + assert motors["SHY"].target == pytest.approx(-0.2) + assert motors["SHX"].target == pytest.approx(0.2) + + +def test_nudge_sends_the_lab_frame_offset_to_the_server(smargon): + with mock.patch.object(smargon.controller, "_rest_put") as rest_put: + with pytest.raises(TimeoutError, match="no new targets were set"): + smargon.nudge_in_lab_frame(0.1, 0.2, 0.3, timeout_s=0.2) + rest_put.assert_called_once_with(params={"BX": 0.1, "BY": 0.2, "BZ": 0.3}, endpoint="/nudgeBCS") + + +def test_nudge_of_nothing_sends_nothing(smargon): + with mock.patch.object(smargon.controller, "_rest_put") as rest_put: + smargon.nudge_in_lab_frame(0.0, 0.0) + rest_put.assert_not_called() + + +def test_nudge_times_out_if_the_move_takes_too_long(smargon): + with pytest.raises(TimeoutError, match="targets"): + smargon.nudge_in_lab_frame(50.0, 0.0, timeout_s=0.3) def test_stop_targets_current_position(smargon):