progress 261104
CI for mx_bec / test (push) Failing after 47s

This commit is contained in:
x10sa committed 2026-11-04 14:57:14 +01:00
1 parent 6854f2d15f
commit 406a2ee2d8
9 files changed
+122 -52

No files matched your search

+2 -3
View File
@@ -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)
+34 -8
View File
@@ -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={})
)
@@ -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),
+9 -2
View File
@@ -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))
+1 -1
View File
@@ -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]
+23 -16
View File
@@ -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
)
+5 -5
View File
@@ -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):
+5 -1
View File
@@ -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
+41 -16
View File
@@ -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,