feat: add tasks module
This commit is contained in:
1 parent
8e44786bb6
commit
32fe721b64
7 files changed
+95
-52
No files matched your search
@@ -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:
|
||||
|
||||
@@ -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"""
|
||||
|
||||
|
||||
+1
-37
@@ -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),
|
||||
)
|
||||
@@ -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),
|
||||
)
|
||||
@@ -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])
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user