From 7656b45dcb654b372b2d38a47381d8e040122a77 Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 24 Nov 2026 11:09:39 +0100 Subject: [PATCH] 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)]