feat: vibe-copy raster task from aaredaq
This commit is contained in:
1 parent
f4fb2ff108
commit
b7c82b65c1
4 files changed
+316
No files matched your search
@@ -5,6 +5,7 @@ from ophyd import Component as Cpt
|
||||
from ophyd import Kind
|
||||
from ophyd.device import Device
|
||||
from ophyd.signal import Signal
|
||||
from ophyd_devices.utils.psi_device_base_utils import StatusBase
|
||||
from requests import RequestException
|
||||
|
||||
from .http import (
|
||||
@@ -85,6 +86,9 @@ class RotationScanParameters(ValidatedHttpParams):
|
||||
class AerotechController(HttpDeviceControllerWithConfigVelocity):
|
||||
_readback_endpoint = "/status"
|
||||
_target_endpoint = "/position"
|
||||
_grid_scan_endpoint = "/grid_scan"
|
||||
_wait_till_done_endpoint = "/wait_till_done"
|
||||
MAX_WAIT_TILL_DONE_S = 3600 # upper bound of the AareScan timeout parameter
|
||||
|
||||
def __init__(self, *, prefix, **kwargs):
|
||||
self._readbacks: dict[str, dict[str, float | bool]] = {}
|
||||
@@ -100,9 +104,23 @@ class AerotechController(HttpDeviceControllerWithConfigVelocity):
|
||||
return None
|
||||
return self._readbacks.get(axis_id)["pos"], self._readbacks.get(TIMESTAMP_ID) # type: ignore
|
||||
|
||||
def start_grid_scan(self, body: dict):
|
||||
"""Start a grid scan with the given (validated) request body, returning immediately."""
|
||||
self._rest_post(body={**body, "run_async": True}, endpoint=self._grid_scan_endpoint)
|
||||
|
||||
def wait_till_done(self, timeout_s: float):
|
||||
"""Block until AareScan is idle again. Raises HttpRestError on timeout (504)."""
|
||||
timeout = min(max(int(round(timeout_s)), 0), self.MAX_WAIT_TILL_DONE_S)
|
||||
self._rest_post(params={"timeout": timeout}, endpoint=self._wait_till_done_endpoint)
|
||||
|
||||
|
||||
class Aerotech(HttpOphydDevice):
|
||||
"""Aerotech sample stage driven through the AareScan REST API. Triggering runs the grid scan
|
||||
configured in `gridscan_config`."""
|
||||
|
||||
controller_class = AerotechController
|
||||
# margin on top of the expected grid scan duration before giving up waiting for it
|
||||
GRID_SCAN_TIMEOUT_MARGIN_S = 60.0
|
||||
|
||||
gridscan_config = Cpt(GridscanParameters)
|
||||
screening_config = Cpt(ScreeningParameters)
|
||||
@@ -124,6 +142,37 @@ class Aerotech(HttpOphydDevice):
|
||||
config.validate()
|
||||
return ret
|
||||
|
||||
########################################
|
||||
# Beamline Specific Implementations #
|
||||
########################################
|
||||
|
||||
def on_trigger(self) -> StatusBase:
|
||||
"""Start the grid scan from `gridscan_config`; the returned status finishes once AareScan
|
||||
reports the scan done."""
|
||||
config = self.gridscan_config
|
||||
if not config.valid.get():
|
||||
raise ValueError(f"Grid scan parameters are not valid: {config.message.get()}")
|
||||
body = config.request_body()
|
||||
self.controller.start_grid_scan(body)
|
||||
status = self.task_handler.submit_task(
|
||||
self.controller.wait_till_done, task_kwargs={"timeout_s": self.grid_scan_timeout_s()}
|
||||
)
|
||||
self.cancel_on_stop(status)
|
||||
return status
|
||||
|
||||
########################################
|
||||
# Helper Methods #
|
||||
########################################
|
||||
|
||||
def expected_grid_scan_s(self) -> float:
|
||||
"""Expected duration of the configured grid scan (exposure plus ~0.3 s per line)."""
|
||||
config = self.gridscan_config
|
||||
n_x, n_y = config.grid_elem_count_x.get(), config.grid_elem_count_y.get()
|
||||
return config.time_per_element_sec.get() * n_x * n_y + n_y * 0.3
|
||||
|
||||
def grid_scan_timeout_s(self) -> float:
|
||||
return self.expected_grid_scan_s() * 1.1 + self.GRID_SCAN_TIMEOUT_MARGIN_S
|
||||
|
||||
|
||||
def _test():
|
||||
a = Aerotech(name="aerotech", prefix="http://mx-x10sa-queue-01:5234")
|
||||
|
||||
@@ -10,6 +10,7 @@ from bec_lib.logger import bec_logger
|
||||
|
||||
from mx_bec.devices.smargopolo_smargon import Smargon
|
||||
from mx_bec.endpoints import StateEndpoints, TaskEndpoints
|
||||
from mx_bec.jfjoch import RasterScan
|
||||
from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskQueueChangedMessage
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -21,6 +22,8 @@ logger = bec_logger.logger
|
||||
P = ParamSpec("P")
|
||||
R = TypeVar("R")
|
||||
|
||||
MAX_GRID_SCAN_S = 1200.0 # refuse grid scans expected to take longer than 20 min
|
||||
|
||||
|
||||
class MxTasks:
|
||||
"""Holder for operations on mx beamlines. Probably needs to be reconsidered
|
||||
@@ -76,6 +79,76 @@ class MxTasks:
|
||||
MXMeasurementSequenceMessage(sample_id=sample_id, success=success),
|
||||
)
|
||||
|
||||
@with_lock
|
||||
def run_grid_scan(
|
||||
self,
|
||||
n_x: int,
|
||||
n_y: int,
|
||||
step_x_um: float,
|
||||
step_y_um: float,
|
||||
exp_time_s: float,
|
||||
file_prefix: str,
|
||||
detector_distance_mm: float,
|
||||
transmission: float,
|
||||
energy_keV: float,
|
||||
beam_center_x_pxl: float,
|
||||
beam_center_y_pxl: float,
|
||||
beam_size_x_mm: float,
|
||||
beam_size_y_mm: float,
|
||||
ring_current_mA: float,
|
||||
flux_ph_s: float,
|
||||
sample_temperature_K: float,
|
||||
pgroup: str = "p16371",
|
||||
sample_name: str = "unknown_sample",
|
||||
) -> None:
|
||||
"""Collect an n_x by n_y grid scan at the current position and omega: configure the
|
||||
Aerotech grid scan and check that AareScan accepts it, arm JFJoch, then trigger the
|
||||
Aerotech and wait for both to finish."""
|
||||
expected_s = exp_time_s * n_x * n_y + n_y * 0.3
|
||||
if expected_s > MAX_GRID_SCAN_S:
|
||||
raise ValueError(f"Grid scan is too long: {expected_s:.0f} s > {MAX_GRID_SCAN_S} s")
|
||||
|
||||
aerotech = self._client.devices.aerotech
|
||||
config = aerotech.gridscan_config
|
||||
for signal, value in (
|
||||
(config.grid_elem_count_x, n_x),
|
||||
(config.grid_elem_count_y, n_y),
|
||||
(config.grid_elem_size_x_um, step_x_um),
|
||||
(config.grid_elem_size_y_um, step_y_um),
|
||||
(config.time_per_element_sec, exp_time_s),
|
||||
):
|
||||
signal.set(value).wait()
|
||||
if not config.valid.get():
|
||||
raise ValueError(f"AareScan rejected the grid scan parameters: {config.message.get()}")
|
||||
|
||||
jfjoch = self._client.jfjoch
|
||||
jfjoch.measure_raster(
|
||||
RasterScan(
|
||||
n_x=n_x,
|
||||
n_y=n_y,
|
||||
step_x_mm=step_x_um / 1000.0,
|
||||
step_y_mm=step_y_um / 1000.0,
|
||||
omega_deg=aerotech.u.get(),
|
||||
exp_time_s=exp_time_s,
|
||||
detector_distance_mm=detector_distance_mm,
|
||||
transmission=transmission,
|
||||
file_prefix=file_prefix,
|
||||
pgroup=pgroup,
|
||||
sample_name=sample_name,
|
||||
energy_keV=energy_keV,
|
||||
beam_center_pxl=(beam_center_x_pxl, beam_center_y_pxl),
|
||||
beam_size_mm=(beam_size_x_mm, beam_size_y_mm),
|
||||
ring_current_mA=ring_current_mA,
|
||||
flux_ph_s=flux_ph_s,
|
||||
sample_temperature_K=sample_temperature_K,
|
||||
)
|
||||
)
|
||||
jfjoch.wait_till_running(timeout_s=60)
|
||||
logger.info(f"Starting {n_x}x{n_y} grid scan, {exp_time_s} s per element")
|
||||
aerotech.trigger().wait()
|
||||
result = jfjoch.wait_till_done(timeout_s=60)
|
||||
logger.info(f"Grid scan finished: {result.file_prefix} with {len(result.images)} images")
|
||||
|
||||
|
||||
class MxTaskQueue:
|
||||
"""Executes requested tasks one at a time, in order, on a background thread.
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
from unittest.mock import MagicMock, call
|
||||
|
||||
import pytest
|
||||
|
||||
from mx_bec.devices.aerotech import Aerotech
|
||||
from mx_bec.devices.http import HttpRestError
|
||||
|
||||
PREFIX = "http://aarescan:5234"
|
||||
|
||||
|
||||
def _response(ok=True, status_code=200, reason="OK", url=PREFIX, method="POST"):
|
||||
resp = MagicMock(ok=ok, status_code=status_code, reason=reason)
|
||||
resp.request.method, resp.request.url = method, url
|
||||
return resp
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def aerotech():
|
||||
device = Aerotech(name="aerotech", prefix=PREFIX)
|
||||
# every REST call goes through the controller's session; never touch the network
|
||||
device.controller._session = MagicMock()
|
||||
device.controller._session.post.return_value = _response()
|
||||
yield device
|
||||
device.destroy()
|
||||
|
||||
|
||||
def _configure(aerotech, n_x=4, n_y=3, exp_time_s=0.1):
|
||||
config = aerotech.gridscan_config
|
||||
config.grid_elem_count_x.put(n_x)
|
||||
config.grid_elem_count_y.put(n_y)
|
||||
config.grid_elem_size_x_um.put(50.0)
|
||||
config.grid_elem_size_y_um.put(40.0)
|
||||
config.time_per_element_sec.put(exp_time_s)
|
||||
return config
|
||||
|
||||
|
||||
def test_config_change_validates_with_aarescan(aerotech):
|
||||
session = aerotech.controller._session
|
||||
config = _configure(aerotech)
|
||||
assert session.post.call_args == call(
|
||||
f"{PREFIX}/validate/grid_scan", json=config.request_body()
|
||||
)
|
||||
assert config.valid.get() is True and config.message.get() == ""
|
||||
|
||||
session.post.return_value = _response(ok=False, status_code=400, reason="Bad Request")
|
||||
session.post.return_value.json.return_value = "grid too large"
|
||||
config.grid_elem_count_x.put(1000)
|
||||
assert config.valid.get() is False and config.message.get() == "grid too large"
|
||||
|
||||
|
||||
def test_trigger_starts_grid_scan_and_waits_till_done(aerotech):
|
||||
session = aerotech.controller._session
|
||||
config = _configure(aerotech, n_x=4, n_y=3, exp_time_s=0.1)
|
||||
session.post.reset_mock()
|
||||
|
||||
status = aerotech.trigger()
|
||||
status.wait(timeout=5)
|
||||
|
||||
expected_timeout = round((0.1 * 4 * 3 + 3 * 0.3) * 1.1 + Aerotech.GRID_SCAN_TIMEOUT_MARGIN_S)
|
||||
assert session.post.call_args_list == [
|
||||
call(f"{PREFIX}/grid_scan", params=None, json={**config.request_body(), "run_async": True}),
|
||||
call(f"{PREFIX}/wait_till_done", params={"timeout": expected_timeout}, json=None),
|
||||
]
|
||||
|
||||
|
||||
def test_trigger_status_fails_when_aarescan_times_out(aerotech):
|
||||
session = aerotech.controller._session
|
||||
_configure(aerotech)
|
||||
session.post.side_effect = [
|
||||
_response(), # grid_scan accepted
|
||||
_response(ok=False, status_code=504, reason="Gateway Timeout"), # wait_till_done
|
||||
]
|
||||
status = aerotech.trigger()
|
||||
with pytest.raises(HttpRestError, match="504"):
|
||||
status.wait(timeout=5)
|
||||
|
||||
|
||||
def test_trigger_refuses_invalid_config(aerotech):
|
||||
session = aerotech.controller._session
|
||||
session.post.return_value = _response(ok=False, status_code=400, reason="Bad Request")
|
||||
session.post.return_value.json.return_value = "nope"
|
||||
_configure(aerotech)
|
||||
session.post.reset_mock()
|
||||
with pytest.raises(ValueError, match="nope"):
|
||||
aerotech.trigger()
|
||||
session.post.assert_not_called()
|
||||
|
||||
|
||||
def test_wait_till_done_timeout_is_clamped(aerotech):
|
||||
session = aerotech.controller._session
|
||||
aerotech.controller.wait_till_done(timeout_s=1e6)
|
||||
assert session.post.call_args.kwargs["params"] == {"timeout": 3600}
|
||||
aerotech.controller.wait_till_done(timeout_s=-5)
|
||||
assert session.post.call_args.kwargs["params"] == {"timeout": 0}
|
||||
@@ -0,0 +1,100 @@
|
||||
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
|
||||
|
||||
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(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(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(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")
|
||||
Reference in new issue
Block a user