feat: add rotation scan task

This commit is contained in:
perl_d committed 2026-11-26 16:30:01 +01:00
1 parent 4ff87a3782
commit 9e70f063d4
6 files changed
+263 -72

No files matched your search

@@ -50,6 +50,13 @@ TASK_FORMS: dict[str, list[tuple[str, int | float | str | list[float]]]] = {
("omega_deg", 0.0),
("file_prefix", "AareBecTestGridScan"),
],
"rotation_scan": [
("exp_time_s", 0.05),
("incr_omega_deg", 0.1),
("steps", 100),
("start_omega_deg", 0.0),
("file_prefix", "AareBecTestRotationScan"),
],
"multiple_rasters": [
("omegas_deg_list", [0, 45, 60, 90, 120, 135]),
("n_x", 10),
+33 -10
View File
@@ -87,6 +87,7 @@ class AerotechController(HttpDeviceControllerWithConfigVelocity):
_readback_endpoint = "/status"
_target_endpoint = "/position"
_grid_scan_endpoint = "/grid_scan"
_rotation_scan_endpoint = "/rotation_scan"
_wait_till_done_endpoint = "/wait_till_done"
MAX_WAIT_TILL_DONE_S = 3600 # upper bound of the AareScan timeout parameter
@@ -108,6 +109,10 @@ class AerotechController(HttpDeviceControllerWithConfigVelocity):
"""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 start_rotation_scan(self, body: dict):
"""Start a rotation scan with the given (validated) request body, returning immediately."""
self._rest_post(body={**body, "run_async": True}, endpoint=self._rotation_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)
@@ -115,13 +120,17 @@ class AerotechController(HttpDeviceControllerWithConfigVelocity):
class Aerotech(HttpOphydDevice[AerotechController]):
"""Aerotech sample stage driven through the AareScan REST API. Triggering runs the grid scan
configured in `gridscan_config`."""
"""Aerotech sample stage driven through the AareScan REST API. Triggering runs the scan
selected by `scan_type`: the grid scan configured in `gridscan_config` (the default) or the
rotation scan configured in `rotation_config`."""
controller_class = AerotechController
# margin on top of the expected grid scan duration before giving up waiting for it
GRID_SCAN: ClassVar[str] = "grid_scan"
ROTATION_SCAN: ClassVar[str] = "rotation_scan"
# margin on top of the expected scan duration before giving up waiting for it
GRID_SCAN_TIMEOUT_MARGIN_S = 60.0
scan_type = Cpt(Signal, kind=Kind.config, dtype=str, value="grid_scan")
gridscan_config = Cpt(GridscanParameters)
screening_config = Cpt(ScreeningParameters)
rotation_config = Cpt(RotationScanParameters)
@@ -147,15 +156,24 @@ class Aerotech(HttpOphydDevice[AerotechController]):
########################################
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
"""Start the scan selected by `scan_type` from its config; the returned status finishes
once AareScan reports the scan done."""
scan_type = self.scan_type.get()
if scan_type == self.GRID_SCAN:
name, config, start = "Grid scan", self.gridscan_config, self.controller.start_grid_scan
timeout_s = self.grid_scan_timeout_s()
elif scan_type == self.ROTATION_SCAN:
name, config = "Rotation scan", self.rotation_config
start, timeout_s = self.controller.start_rotation_scan, self.rotation_scan_timeout_s()
else:
raise ValueError(
f"Unknown scan type {scan_type!r}: use {self.GRID_SCAN!r} or {self.ROTATION_SCAN!r}"
)
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)
raise ValueError(f"{name} parameters are not valid: {config.message.get()}")
start(config.request_body())
status = self.task_handler.submit_task(
self.controller.wait_till_done, task_kwargs={"timeout_s": self.grid_scan_timeout_s()}
self.controller.wait_till_done, task_kwargs={"timeout_s": timeout_s}
)
self.cancel_on_stop(status)
return status
@@ -173,6 +191,11 @@ class Aerotech(HttpOphydDevice[AerotechController]):
def grid_scan_timeout_s(self) -> float:
return self.expected_grid_scan_s() * 1.1 + self.GRID_SCAN_TIMEOUT_MARGIN_S
def rotation_scan_timeout_s(self) -> float:
"""As for the grid scan, on top of the configured duration of the rotation."""
expected_s = self.rotation_config.total_time_sec.get()
return expected_s * 1.1 + self.GRID_SCAN_TIMEOUT_MARGIN_S
def _test():
a = Aerotech(name="aerotech", prefix="http://mx-x10sa-queue-01:5234")
+59 -23
View File
@@ -21,20 +21,15 @@ P = ParamSpec("P")
R = TypeVar("R")
class RasterScan(BaseModel):
"""Everything JFJoch needs to collect one raster (grid) scan."""
class DataCollection(BaseModel):
"""What JFJoch needs for any data collection: the exposure, where the files go and the state
of the beamline."""
# grid: n_x columns by n_y rows, stepped by step_*_mm, at a fixed omega
n_x: int = Field(ge=1)
n_y: int = Field(ge=1)
step_x_mm: float = Field(gt=0)
step_y_mm: float = Field(gt=0)
omega_deg: float
# exposure
exp_time_s: float = Field(gt=0)
detector_distance_mm: float = Field(gt=0)
transmission: float = Field(ge=0, le=1)
# output: files go to <pgroup>/raw/raster/<file_prefix>
# output: files go to <pgroup>/raw/<kind of scan>/<file_prefix>
file_prefix: str
pgroup: str = "p16371"
sample_name: str = "unknown_sample"
@@ -51,6 +46,26 @@ class RasterScan(BaseModel):
smargon_chi_deg: float | None = None
class RasterScan(DataCollection):
"""Everything JFJoch needs to collect one raster (grid) scan: n_x columns by n_y rows,
stepped by step_*_mm, at a fixed omega."""
n_x: int = Field(ge=1)
n_y: int = Field(ge=1)
step_x_mm: float = Field(gt=0)
step_y_mm: float = Field(gt=0)
omega_deg: float
class RotationScan(DataCollection):
"""Everything JFJoch needs to collect one rotation scan: `steps` images of `incr_omega_deg`
each, from `start_omega_deg`."""
steps: int = Field(ge=1)
incr_omega_deg: float = Field(gt=0)
start_omega_deg: float
class JFJochError(RuntimeError):
"""A call to the JFJoch detector broker failed."""
@@ -67,7 +82,8 @@ def needs_connection(method: Callable[P, R]) -> Callable[P, R]:
class JFJoch:
"""Thin wrapper around the JFJoch detector broker REST API, for raster (grid) scans.
"""Thin wrapper around the JFJoch detector broker REST API, for raster (grid) and rotation
scans.
Adapted from aaredaq's `JFJochWrapper`: the client is created on first use and every API
call is wrapped so that failures raise `JFJochError`.
@@ -115,6 +131,12 @@ class JFJoch:
"""Start a raster scan data collection; wait with `wait_till_running` / `wait_till_done`."""
self._call("start_post", dataset_settings=self.dataset_settings(scan, async_start))
@needs_connection
def measure_rotation(self, scan: RotationScan, async_start: bool = True) -> None:
"""Start a rotation scan data collection; wait with `wait_till_running` /
`wait_till_done`."""
self._call("start_post", dataset_settings=self.dataset_settings(scan, async_start))
@needs_connection
def wait_till_running(self, timeout_s: float = 60) -> None:
"""Block until JFJoch reports the detector armed, or raise."""
@@ -140,11 +162,27 @@ class JFJoch:
return self._call("result_scan_get")
def dataset_settings(
self, scan: RasterScan, async_start: bool = True
self, scan: RasterScan | RotationScan, async_start: bool = True
) -> jfjoch_client.DatasetSettings:
"""Build the JFJoch dataset settings for a raster scan."""
# a single column is collected as one trigger with n_y images
ntrigger, images = (1, scan.n_y) if scan.n_x == 1 else (scan.n_y, scan.n_x)
"""Build the JFJoch dataset settings for a raster or rotation scan."""
if isinstance(scan, RasterScan):
kind = "raster"
# a single column is collected as one trigger with n_y images
ntrigger, images = (1, scan.n_y) if scan.n_x == 1 else (scan.n_y, scan.n_x)
omega_start, omega_step = scan.omega_deg, 0
grid_scan = jfjoch_client.GridScan(
n_fast=scan.n_x,
snake=True,
step_x_um=scan.step_x_mm * 1000.0,
step_y_um=scan.step_y_mm * 1000.0,
vertical=False,
)
else:
kind = "rotation"
# the whole rotation is one trigger
ntrigger, images = 1, scan.steps
omega_start, omega_step = scan.start_omega_deg, scan.incr_omega_deg
grid_scan = None
if scan.smargon_phi_deg is not None and scan.smargon_chi_deg is not None:
smargon = DatasetSettingsSmargon(
phi_deg=scan.smargon_phi_deg, chi_deg=max(scan.smargon_chi_deg, 0)
@@ -157,7 +195,7 @@ class JFJoch:
ntrigger=ntrigger,
images_per_trigger=images,
detector_distance_mm=scan.detector_distance_mm,
file_prefix=f"{scan.pgroup}/raw/raster/{scan.file_prefix}",
file_prefix=f"{scan.pgroup}/raw/{kind}/{scan.file_prefix}",
incident_energy_keV=scan.energy_keV,
sample_name=scan.sample_name,
image_time_us=round(scan.exp_time_s * 1e6),
@@ -177,13 +215,11 @@ class JFJoch:
polarization_factor=1.0,
images_per_file=self._client.aare_config.jfjoch.n_images_per_file or None,
goniometer=jfjoch_client.RotationAxis(
step=0, start=scan.omega_deg, name="omega", vector=[-1, 0, 0], screening_wedge_deg=0
),
grid_scan=jfjoch_client.GridScan(
n_fast=scan.n_x,
snake=True,
step_x_um=scan.step_x_mm * 1000.0,
step_y_um=scan.step_y_mm * 1000.0,
vertical=False,
step=omega_step,
start=omega_start,
name="omega",
vector=[-1, 0, 0],
screening_wedge_deg=0,
),
grid_scan=grid_scan,
)
+115 -38
View File
@@ -28,7 +28,7 @@ from mx_bec.decisions import (
)
from mx_bec.device_planner import BeamlineState, StateChangePlanner, init_beamline_environment
from mx_bec.endpoints import StateEndpoints
from mx_bec.jfjoch import RasterScan
from mx_bec.jfjoch import DataCollection, RasterScan, RotationScan
from mx_bec.messages import MXMeasurementSequenceMessage
from mx_bec.tasks.core import MxSequenceUpdate, RoleT, TaskManager, task
@@ -38,6 +38,7 @@ if TYPE_CHECKING:
logger = bec_logger.logger
MAX_GRID_SCAN_S = 1200.0 # refuse grid scans expected to take longer than 20 min
MAX_ROTATION_SCAN_S = 1200.0 # and rotation scans
JFJOCH_TIMEOUT_S = 60.0 # for JFJoch to arm the detector, and to finish once the scan is done
@@ -320,24 +321,81 @@ class MxTasks(TaskManager[RoleT]):
) -> None:
"""Rotate to the scan's omega, set the detector distance and transmission if given, and
configure the Aerotech grid scan, checking that AareScan accepts it."""
devices, scans = self._client.devices, self._client.scans
aerotech = devices.aerotech
aerotech = self._client.devices.aerotech
aerotech.u.set(omega_deg).wait()
self._set_detector_distance_and_transmission(dtz, transmission)
config = aerotech.gridscan_config
self._configure_aerotech_scan(
"grid_scan",
config,
{
config.grid_elem_count_x: n_x,
config.grid_elem_count_y: n_y,
config.grid_elem_size_x_um: step_x_mm * 1000.0,
config.grid_elem_size_y_um: step_y_mm * 1000.0,
config.time_per_element_sec: exp_time_s,
},
)
def _set_detector_distance_and_transmission(
self, dtz: float | None, transmission: float | None
) -> None:
"""Move the detector to `dtz` and set the transmission; what is None is left as it is."""
devices, scans = self._client.devices, self._client.scans
if dtz is not None:
scans.mv(devices.det_z, dtz, relative=False).wait()
if transmission is not None:
scans.mv(devices.transm, transmission, relative=False).wait()
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_mm * 1000.0),
(config.grid_elem_size_y_um, step_y_mm * 1000.0),
(config.time_per_element_sec, exp_time_s),
):
def _configure_aerotech_scan(self, scan_type: str, config, values: dict) -> None:
"""Make `scan_type` ("grid_scan" or "rotation_scan") the scan which triggering the
Aerotech runs, set the signals of its `config`, and check that AareScan accepts them."""
self._client.devices.aerotech.scan_type.set(scan_type).wait()
for signal, value in values.items():
signal.set(value).wait()
if not config.valid.get():
raise ValueError(f"AareScan rejected the grid scan parameters: {config.message.get()}")
raise ValueError(
f"AareScan rejected the {scan_type} parameters: {config.message.get()}"
)
def _data_collection_settings(self, file_prefix: str) -> dict:
"""The fields of a JFJoch `DataCollection` which describe the beamline as it is now."""
beam = self._beam_conditions()
smargon = self._client.devices.smargon
return dict(
detector_distance_mm=beam.detector_distance_mm,
transmission=beam.transmission,
file_prefix=file_prefix,
energy_keV=beam.energy_keV,
beam_center_pxl=beam.beam_center_pxl,
beam_size_mm=beam.beam_size_mm,
ring_current_mA=beam.ring_current_mA,
flux_ph_s=beam.full_flux_ph_s,
sample_temperature_K=beam.sample_temperature_K,
smargon_phi_deg=smargon.phi.get(),
smargon_chi_deg=smargon.chi.get(),
)
def _collect(self, scan: DataCollection, description: str) -> None:
"""Arm JFJoch for `scan`, trigger the Aerotech scan which was configured for it, and wait
for both to finish."""
jfjoch = self._client.jfjoch
if isinstance(scan, RasterScan):
jfjoch.measure_raster(scan)
elif isinstance(scan, RotationScan):
jfjoch.measure_rotation(scan)
else:
raise TypeError(f"Cannot collect a {type(scan).__name__}")
try:
jfjoch.wait_till_running(timeout_s=JFJOCH_TIMEOUT_S)
logger.info(f"Starting {description}")
self._client.devices.aerotech.trigger().wait()
result = jfjoch.wait_till_done(timeout_s=JFJOCH_TIMEOUT_S)
except Exception:
# do not leave the detector armed, waiting for triggers which will not come
jfjoch.cancel()
raise
logger.info(f"Finished {description}: {result.file_prefix}, {len(result.images)} images")
@task
def grid_scan(
@@ -363,13 +421,11 @@ class MxTasks(TaskManager[RoleT]):
n_x, n_y, step_x_mm, step_y_mm, exp_time_s, omega_deg, dtz, transmission
)
smargon = self._client.devices.smargon
x_offset_mm, y_offset_mm = n_x * step_x_mm * 0.5, n_y * step_y_mm * 0.5
logger.info(f"Nudging smargon to the top left of the grid: -{x_offset_mm=} -{y_offset_mm=}")
# smargopolo applies the nudge for its own reading of omega, which is now the scan's omega
smargon.nudge_in_lab_frame(-x_offset_mm, -y_offset_mm)
self._client.devices.smargon.nudge_in_lab_frame(-x_offset_mm, -y_offset_mm)
beam = self._beam_conditions()
scan = RasterScan(
n_x=n_x,
n_y=n_y,
@@ -377,30 +433,51 @@ class MxTasks(TaskManager[RoleT]):
step_y_mm=step_y_mm,
omega_deg=omega_deg,
exp_time_s=exp_time_s,
detector_distance_mm=beam.detector_distance_mm,
transmission=beam.transmission,
file_prefix=file_prefix or f"grid_{token_hex(3)}",
energy_keV=beam.energy_keV,
beam_center_pxl=beam.beam_center_pxl,
beam_size_mm=beam.beam_size_mm,
ring_current_mA=beam.ring_current_mA,
flux_ph_s=beam.full_flux_ph_s,
sample_temperature_K=beam.sample_temperature_K,
smargon_phi_deg=smargon.phi.get(),
smargon_chi_deg=smargon.chi.get(),
**self._data_collection_settings(file_prefix or f"grid_{token_hex(3)}"),
)
self._collect(scan, f"{n_x}x{n_y} grid scan, {exp_time_s} s per element")
@task
def rotation_scan(
self,
exp_time_s: float,
incr_omega_deg: float,
steps: int,
start_omega_deg: float = 0.0,
file_prefix: str | None = None,
dtz: float | None = None,
transmission: float | None = None,
) -> None:
"""Collect a rotation scan of `steps` images of `incr_omega_deg` each, from
`start_omega_deg`, at the current Smargon position and without AareDAQ: set the
prerequisites (the detector distance `dtz` and the transmission if given, the Aerotech
rotation scan), arm JFJoch, then trigger the Aerotech and wait for both to finish."""
total_time_s = exp_time_s * steps
if total_time_s > MAX_ROTATION_SCAN_S:
raise ValueError(
f"Rotation scan is too long: {total_time_s:.0f} s > {MAX_ROTATION_SCAN_S} s"
)
self._set_detector_distance_and_transmission(dtz, transmission)
config = self._client.devices.aerotech.rotation_config
self._configure_aerotech_scan(
"rotation_scan",
config,
{
config.rotation_deg: incr_omega_deg * steps,
config.total_time_sec: total_time_s,
config.start_pos_deg: start_omega_deg,
},
)
scan = RotationScan(
steps=steps,
incr_omega_deg=incr_omega_deg,
start_omega_deg=start_omega_deg,
exp_time_s=exp_time_s,
**self._data_collection_settings(file_prefix or f"rotation_{token_hex(3)}"),
)
self._collect(
scan, f"rotation scan, {steps} images of {incr_omega_deg} deg, {exp_time_s} s each"
)
jfjoch = self._client.jfjoch
jfjoch.measure_raster(scan)
try:
jfjoch.wait_till_running(timeout_s=JFJOCH_TIMEOUT_S)
logger.info(f"Starting {n_x}x{n_y} grid scan, {exp_time_s} s per element")
self._client.devices.aerotech.trigger().wait()
result = jfjoch.wait_till_done(timeout_s=JFJOCH_TIMEOUT_S)
except Exception:
# do not leave the detector armed, waiting for triggers which will not come
jfjoch.cancel()
raise
logger.info(f"Grid scan finished: {result.file_prefix} with {len(result.images)} images")
@task
def xray_centering(self, dbid: int, strategy: dict) -> MxSequenceUpdate:
+28
View File
@@ -86,6 +86,34 @@ def test_trigger_refuses_invalid_config(aerotech):
session.post.assert_not_called()
def test_trigger_starts_the_rotation_scan_if_selected(aerotech):
session = aerotech.controller._session
config = aerotech.rotation_config
config.rotation_deg.put(10.0)
config.total_time_sec.put(5.0)
config.start_pos_deg.put(30.0)
aerotech.scan_type.put(Aerotech.ROTATION_SCAN)
session.post.reset_mock()
aerotech.trigger().wait(timeout=5)
expected_timeout = round(5.0 * 1.1 + Aerotech.GRID_SCAN_TIMEOUT_MARGIN_S)
assert session.post.call_args_list == [
call(
f"{PREFIX}/rotation_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_refuses_an_unknown_scan_type(aerotech):
aerotech.scan_type.put("helical")
with pytest.raises(ValueError, match="Unknown scan type 'helical'"):
aerotech.trigger()
def test_wait_till_done_timeout_is_clamped(aerotech):
session = aerotech.controller._session
aerotech.controller.wait_till_done(timeout_s=1e6)
+21 -1
View File
@@ -3,7 +3,7 @@ from unittest.mock import MagicMock, patch
import pytest
from pydantic import ValidationError
from mx_bec.jfjoch import JFJoch, JFJochError, RasterScan
from mx_bec.jfjoch import JFJoch, JFJochError, RasterScan, RotationScan
@pytest.fixture
@@ -122,6 +122,26 @@ def test_measure_raster_builds_grid_dataset_settings(jfjoch):
)
def test_measure_rotation_builds_rotation_dataset_settings(jfjoch):
grid_fields = ("n_x", "n_y", "step_x_mm", "step_y_mm", "omega_deg")
common = {k: v for k, v in _scan().model_dump().items() if k not in grid_fields}
scan = RotationScan(steps=900, incr_omega_deg=0.2, start_omega_deg=30.0, **common)
with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client:
jfjoch.measure_rotation(scan)
settings = jfjoch_client.DatasetSettings.call_args.kwargs
# the whole rotation is one trigger, and there is no grid
assert settings["ntrigger"] == 1 and settings["images_per_trigger"] == 900
assert settings["file_prefix"] == "p16371/raw/rotation/test"
assert settings["grid_scan"] is None
jfjoch_client.GridScan.assert_not_called()
jfjoch_client.RotationAxis.assert_called_once_with(
step=0.2, start=30.0, name="omega", vector=[-1, 0, 0], screening_wedge_deg=0
)
jfjoch_client.DefaultApi.return_value.start_post.assert_called_once_with(
dataset_settings=jfjoch_client.DatasetSettings.return_value
)
def test_single_column_raster_is_one_trigger(jfjoch):
with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client:
jfjoch.dataset_settings(_scan(n_x=1, n_y=4))