refactor: remove now unused aaredaq stuff

This commit is contained in:
perl_d committed 2026-12-02 13:07:29 +01:00
1 parent f9b03b6354
commit 80e06c2f24
6 files changed
+145 -353

No files matched your search

@@ -28,19 +28,7 @@ logger = bec_logger.logger
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": [],
# the AareDAQ-driven tasks; their bool/optional arguments keep their defaults here
"aaredaq_raster_scan": [
("n_x", 4),
("n_y", 3),
("step_x_mm", 0.05),
("step_y_mm", 0.05),
("exp_time_s", 0.1),
("omega_deg", 0.0),
("dtz", 250),
("file_prefix", "AareBecTestGridScan"),
],
# the same scan run by BEC itself (Smargon, JFJoch and Aerotech), without AareDAQ
# run by BEC itself: Smargon, JFJoch and Aerotech
"grid_scan": [
("n_x", 4),
("n_y", 3),
@@ -67,12 +55,6 @@ TASK_FORMS: dict[str, list[tuple[str, int | float | str | list[float]]]] = {
("dtz", 200),
("file_prefix", "AareBecTestGridScan"),
],
"aaredaq_rotation_scan": [
("exp_time_s", 0.05),
("incr_omega_deg", 0.1),
("steps", 100),
("start_omega_deg", 0.0),
],
}
+10 -53
View File
@@ -9,8 +9,6 @@ import requests
from aarecommon.config.beamline import cfg_get, mx_beamline
from aarecommon.models.auth import BatonStatus
from aarecommon.models.beamline import MXBeamline
from aarecommon.models.raster_grid import CompletedRasterGrid, RasterGridRequest
from aarecommon.models.rotation_scan import CompletedRotationScan, RotationScanRequest
from bec_lib.logger import bec_logger
if TYPE_CHECKING:
@@ -29,7 +27,7 @@ DEFAULT_CERT_PATHS = {
}
TOKEN_TIMEOUT_S = 120.0
REQUEST_TIMEOUT_S = 30.0 # for quick calls such as the baton endpoints
SCAN_TIMEOUT_S = 3600.0 # the scan endpoints block until the scan is done
MOUNT_TIMEOUT_S = 600.0 # the mount endpoint blocks until the sample is mounted
BATON_WAIT_S = 60.0 # covers the server's 30 s for the current holder to answer a request
BATON_POLL_INTERVAL_S = 1.0
@@ -39,13 +37,14 @@ class AareDaqError(RuntimeError):
class AareDaq:
"""Client for the AareDAQ REST API (aaredaq `server.py`).
"""Client for the part of the AareDAQ REST API (aaredaq `server.py`) which AareBec still uses:
mounting a sample.
Mirrors how the AareDAQ GUI talks to the server: a bearer token is obtained once, lazily, by
Kerberos (`curl --negotiate` against the Apache proxy in front of the server, exactly as
`aare.gui.auth.auth` does), and is renewed once if the server answers 401. The server URL and
its certificate come from the aarecommon beamline config unless given. Hardware operations
take the beamline baton first if this session does not hold it yet.
its certificate come from the aarecommon beamline config unless given. AareDAQ only mounts
for the session holding the beamline baton, so it is taken first if not held yet.
"""
def __init__(
@@ -111,7 +110,7 @@ class AareDaq:
*,
params: dict[str, Any] | None = None,
body: dict[str, Any] | None = None,
timeout_s: float = SCAN_TIMEOUT_S,
timeout_s: float = REQUEST_TIMEOUT_S,
) -> Any:
"""Call `endpoint` with the bearer token and return the decoded JSON response. A 401 is
retried once with a fresh token; any other error becomes an AareDaqError."""
@@ -148,7 +147,7 @@ class AareDaq:
*,
params: dict[str, Any] | None = None,
body: dict[str, Any] | None = None,
timeout_s: float = SCAN_TIMEOUT_S,
timeout_s: float = REQUEST_TIMEOUT_S,
) -> Any:
return self._request("POST", endpoint, params=params, body=body, timeout_s=timeout_s)
@@ -182,10 +181,6 @@ class AareDaq:
if time.monotonic() > deadline:
raise AareDaqError(f"AareDAQ baton not granted within {wait_s} s: {result}")
def release_baton(self) -> None:
"""Release the baton, leaving the beamline vacant."""
self._post("/baton/release", timeout_s=REQUEST_TIMEOUT_S)
def ensure_baton(self) -> None:
"""Take the baton unless this session already holds it."""
if not self.baton_status().you_are_holder:
@@ -193,50 +188,12 @@ class AareDaq:
# ---- hardware operations ----
def mount_sample(self, dbid: int, reference: bool = False, timeout_s: float = 600.0) -> None:
def mount_sample(
self, dbid: int, reference: bool = False, timeout_s: float = MOUNT_TIMEOUT_S
) -> None:
"""Mount the sample with database id `dbid` (from the reference tools if `reference`)."""
self.ensure_baton()
logger.info(f"AareDAQ: mounting sample {dbid}{' (reference tool)' if reference else ''}")
self._post(
"/sample/mount", params={"dbid": dbid, "reference": reference}, timeout_s=timeout_s
)
def unmount_sample_then_park(self, timeout_s: float = 600.0) -> None:
"""unmount the current sample."""
self.ensure_baton()
logger.info("AareDAQ: unmounting sample, then putting the robot to a safe place")
self._post("/sample/unmount_then_park_and_dry", timeout_s=timeout_s)
def auto_loop_center(self):
self.ensure_baton()
self._post("/alc/center_loop")
def raster_scan(
self,
request: RasterGridRequest,
auto_center: bool = False,
timeout_s: float = SCAN_TIMEOUT_S,
) -> CompletedRasterGrid:
"""Run a raster scan and return its result (blocks until the scan is done)."""
self.ensure_baton()
logger.info(f"AareDAQ: raster scan {request.n_x}x{request.n_y}, auto_center={auto_center}")
result = self._post(
"/scan/raster",
params={"auto_center": auto_center},
body=request.model_dump(mode="json"),
timeout_s=timeout_s,
)
return CompletedRasterGrid.model_validate(result)
def rotation_scan(
self, request: RotationScanRequest, timeout_s: float = SCAN_TIMEOUT_S
) -> CompletedRotationScan:
"""Run a rotation (or screening) scan and return its result (blocks until done)."""
self.ensure_baton()
logger.info(
f"AareDAQ: rotation scan, {request.steps} steps of {request.incr_omega_deg} deg"
)
result = self._post(
"/scan/rotation", body=request.model_dump(mode="json"), timeout_s=timeout_s
)
return CompletedRotationScan.model_validate(result)
@@ -15,6 +15,23 @@ if TYPE_CHECKING:
logger = bec_logger.logger
def target_offset_mm(results: OpticalCenteringResults) -> tuple[float, float] | None:
"""Where the prediction's target point is relative to the beam, as (x, y) in mm in the image
plane (x to the right, y down), or None if no target point was found. The beam is where the
prediction's geometry puts it, or else at the centre of the image."""
prediction = results.prediction
if (target := prediction.target_point) is None:
return None
geometry = prediction.geometry
if geometry is not None and geometry.beam_x is not None and geometry.beam_y is not None:
beam_x, beam_y = geometry.beam_x, geometry.beam_y
else:
logger.warning("The prediction has no beam position, assuming the centre of the image")
beam_x, beam_y = prediction.image_width / 2, prediction.image_height / 2
mm_per_pixel = results.microns_per_pixel / 1000.0
return (target.x - beam_x) * mm_per_pixel, (target.y - beam_y) * mm_per_pixel
class OpticalPrediction:
def __init__(self, client: AareBec):
self._client = client
+108 -171
View File
@@ -7,13 +7,7 @@ from secrets import token_hex
from typing import TYPE_CHECKING
from aarecommon.config.beamline import mx_beamline
from aarecommon.math.coordinate import Coordinate, SmargonCoordinate
from aarecommon.models.beam_centre import BeamCentre
from aarecommon.models.raster_grid import (
CompletedRasterGrid, # already imported in aaredaq.py
RasterGridRequest,
)
from aarecommon.models.rotation_scan import RotationScanRequest
from bec_lib.logger import bec_logger
from mx_bec.decisions import (
@@ -23,16 +17,17 @@ from mx_bec.decisions import (
RasterRecord,
RotationPlan,
SweepRecord,
scan_images,
smargon_nudge,
)
from mx_bec.device_planner import BeamlineState, StateChangePlanner, init_beamline_environment
from mx_bec.endpoints import StateEndpoints
from mx_bec.external_services.jfjoch import DataCollection, RasterScan, RotationScan
from mx_bec.external_services.optical_centering import target_offset_mm
from mx_bec.messages import MXMeasurementSequenceMessage
from mx_bec.tasks.core import MxSequenceUpdate, RoleT, TaskManager, task
if TYPE_CHECKING:
from jfjoch_client.models.scan_result import ScanResult
from mx_bec.service import AareBec
logger = bec_logger.logger
@@ -83,12 +78,24 @@ class MxTasks(TaskManager[RoleT]):
@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!"""
"""Naive optical centering: take the loop prediction for the sample camera image and
nudge the Smargon so that the prediction's target point sits in the beam. One view only,
so the sample is not centred along the beam. Fails if the prediction has no target point.
warning: Updates the sample id to whatever you enter even if it's not the real one!"""
if self._client.sample_info is None or self._client.sample_info.sample_id != sample_id:
self._client.reset_sample_info(sample_id)
self._client.aaredaq.auto_loop_center()
self._client.scans.mv(self._client.devices.scam_zoom, 400, relative=False).wait()
self._client.optical_prediction.update_latest()
prediction = self._client.optical_prediction
prediction.update_latest()
results = self._client.sample_info.optical_centering_results
offset_mm = target_offset_mm(results) if results is not None else None
if offset_mm is None:
logger.warning("Optical centering: no target point predicted, not moving the sample")
return self._optical_centering_done_update(sample_id, success=False)
logger.info(f"Optical centering: nudging the target point to the beam, {offset_mm=}")
# same convention as the grid scans: a nudge by v brings the point at v into the beam
self._client.devices.smargon.nudge_in_lab_frame(*offset_mm)
prediction.update_latest() # the results for the grid strategy describe the centred loop
return self._optical_centering_done_update(sample_id, success=True)
def _optical_centering_done_update(self, sample_id: int, *, success: bool):
@@ -116,11 +123,6 @@ class MxTasks(TaskManager[RoleT]):
MXMeasurementSequenceMessage(sample_id=dbid, success=True),
)
@task
def cleanup_beamline(self):
"""Unmount the current sample and send the gripper to dry"""
self._client.aaredaq.unmount_sample_then_park()
@task
def multiple_rasters(
self,
@@ -133,17 +135,19 @@ class MxTasks(TaskManager[RoleT]):
file_prefix: str | None = None,
dtz: float | None = None,
) -> MxSequenceUpdate:
"""Run multiple raster scans at different omega values"""
"""Run multiple raster scans at different omega values, each centred on the position
the Smargon is at now."""
for i, omega in enumerate(omegas_deg_list):
self._run_raster(
self._grid_scan(
n_x,
n_y,
step_x_mm,
step_y_mm,
exp_time_s,
file_prefix=f"{file_prefix}_{i}_{omega:.2f}deg_{token_hex(3)}",
dtz=dtz,
omega_deg=omega,
file_prefix=f"{file_prefix or 'grid'}_{i}_{omega:.2f}deg_{token_hex(3)}",
dtz=dtz,
return_to_centre=True,
)
logger.info(f"Raster {i + 1} out of {len(omegas_deg_list)} done.")
return (
@@ -153,114 +157,6 @@ class MxTasks(TaskManager[RoleT]):
),
)
@task
def aaredaq_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,
screening: bool = False,
wedge_omega_deg: float | None = None,
) -> None:
"""Have AareDAQ run a rotation (or screening) scan of `steps` images of `incr_omega_deg`
each, starting at the current Smargon position (`start`/`end` are left unset)."""
request = RotationScanRequest(
exp_time_s=exp_time_s,
incr_omega_deg=incr_omega_deg,
steps=steps,
start_omega_deg=start_omega_deg,
file_prefix=file_prefix,
dtz=dtz,
transmission=transmission,
screening=screening,
wedge_omega_deg=wedge_omega_deg,
)
result = self._client.aaredaq.rotation_scan(request)
logger.info(f"AareDAQ rotation scan done: {len(result.result.images)} images")
def _run_raster(
self,
n_x: int,
n_y: int,
step_x_mm: float,
step_y_mm: float,
exp_time_s: float,
omega_deg: float = 0.0,
file_prefix: str | None = None,
dtz: float | None = None,
transmission: float | None = None,
smargon_top_left: SmargonCoordinate | None = None,
auto_center: bool = False,
) -> CompletedRasterGrid:
if not smargon_top_left:
x_offset_mm = n_x * step_x_mm * 0.5
y_offset_mm = n_y * step_y_mm * 0.5
logger.info(
f"offsetting smargon x,y by half of grid: {x_offset_mm=} {y_offset_mm=} (grid x to smargon z)"
)
smargon = self._client.devices.smargon
# aerotech = self._client.devices.aerotech
adjustment = smargon_nudge(
smargon.phi.get(),
smargon.chi.get(),
omega_deg,
Coordinate(x=x_offset_mm, y=y_offset_mm, z=0),
)
smargon_top_left = SmargonCoordinate(
sh_mm=Coordinate(x=smargon.x.get(), y=smargon.y.get(), z=smargon.z.get())
- adjustment,
chi_deg=smargon.chi.get(),
phi_deg=smargon.phi.get(),
)
logger.info(f"Smargon top left: {smargon_top_left}")
request = RasterGridRequest(
n_x=n_x,
n_y=n_y,
grid_size_mm=Coordinate(x=step_x_mm, y=step_y_mm),
exp_time_s=exp_time_s,
omega_deg=omega_deg,
file_prefix=file_prefix,
dtz=dtz,
transmission=transmission,
smargon_top_left=smargon_top_left,
)
result = self._client.aaredaq.raster_scan(request, auto_center=auto_center)
logger.info(f"Raster scan finished with {len(scan_images(result))} images")
return result
@task
def aaredaq_raster_scan(
self,
n_x: int,
n_y: int,
step_x_mm: float,
step_y_mm: float,
exp_time_s: float,
omega_deg: float = 0.0,
file_prefix: str | None = None,
dtz: float | None = None,
transmission: float | None = None,
smargon_top_left: SmargonCoordinate | None = None,
auto_center: bool = False,
) -> None:
self._run_raster(
n_x,
n_y,
step_x_mm,
step_y_mm,
exp_time_s,
omega_deg,
file_prefix,
dtz,
transmission,
smargon_top_left,
auto_center,
)
def _read(self, device: str) -> float:
"""The current value of the device (or signal) with this name."""
return self._client.devices[device].read()[device]["value"]
@@ -376,9 +272,9 @@ class MxTasks(TaskManager[RoleT]):
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."""
def _collect(self, scan: DataCollection, description: str) -> ScanResult:
"""Arm JFJoch for `scan`, trigger the Aerotech scan which was configured for it, wait for
both to finish, and return the JFJoch result."""
jfjoch = self._client.jfjoch
if isinstance(scan, RasterScan):
jfjoch.measure_raster(scan)
@@ -396,6 +292,51 @@ class MxTasks(TaskManager[RoleT]):
jfjoch.cancel()
raise
logger.info(f"Finished {description}: {result.file_prefix}, {len(result.images)} images")
return result
def _grid_scan(
self,
n_x: int,
n_y: int,
step_x_mm: float,
step_y_mm: float,
exp_time_s: float,
omega_deg: float = 0.0,
file_prefix: str | None = None,
dtz: float | None = None,
transmission: float | None = None,
return_to_centre: bool = False,
) -> ScanResult:
"""Collect a grid scan as the `grid_scan` task describes and return the JFJoch result.
The Smargon stays at the top left corner of the grid, unless `return_to_centre` undoes
the nudge to the corner once the scan is done."""
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")
self._set_grid_scan_prerequisites(
n_x, n_y, step_x_mm, step_y_mm, exp_time_s, omega_deg, dtz, transmission
)
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 = self._client.devices.smargon
smargon.nudge_in_lab_frame(-x_offset_mm, -y_offset_mm)
try:
scan = RasterScan(
n_x=n_x,
n_y=n_y,
step_x_mm=step_x_mm,
step_y_mm=step_y_mm,
omega_deg=omega_deg,
exp_time_s=exp_time_s,
**self._data_collection_settings(file_prefix or f"grid_{token_hex(3)}"),
)
return self._collect(scan, f"{n_x}x{n_y} grid scan, {exp_time_s} s per element")
finally:
if return_to_centre:
self._client.devices.aerotech.u.set(omega_deg).wait()
smargon.nudge_in_lab_frame(x_offset_mm, y_offset_mm)
@task
def grid_scan(
@@ -410,35 +351,15 @@ class MxTasks(TaskManager[RoleT]):
dtz: float | None = None,
transmission: float | None = None,
) -> None:
"""Collect an n_x by n_y grid scan centred on the current position, without AareDAQ: set
the prerequisites (omega, the detector distance `dtz` and the transmission if given, the
Aerotech grid scan), nudge the Smargon to the top left corner of the grid, arm JFJoch,
then trigger the Aerotech and wait for both to finish. The Smargon stays at the corner."""
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")
self._set_grid_scan_prerequisites(
n_x, n_y, step_x_mm, step_y_mm, exp_time_s, omega_deg, dtz, transmission
"""Collect an n_x by n_y grid scan centred on the current position: set the prerequisites
(omega, the detector distance `dtz` and the transmission if given, the Aerotech grid
scan), nudge the Smargon to the top left corner of the grid, arm JFJoch, then trigger the
Aerotech and wait for both to finish. The Smargon stays at the corner."""
self._grid_scan(
n_x, n_y, step_x_mm, step_y_mm, exp_time_s, omega_deg, file_prefix, dtz, transmission
)
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
self._client.devices.smargon.nudge_in_lab_frame(-x_offset_mm, -y_offset_mm)
scan = RasterScan(
n_x=n_x,
n_y=n_y,
step_x_mm=step_x_mm,
step_y_mm=step_y_mm,
omega_deg=omega_deg,
exp_time_s=exp_time_s,
**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(
def _rotation_scan(
self,
exp_time_s: float,
incr_omega_deg: float,
@@ -447,11 +368,9 @@ class MxTasks(TaskManager[RoleT]):
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."""
) -> ScanResult:
"""Collect a rotation scan as the `rotation_scan` task describes and return the JFJoch
result."""
total_time_s = exp_time_s * steps
if total_time_s > MAX_ROTATION_SCAN_S:
raise ValueError(
@@ -475,13 +394,34 @@ class MxTasks(TaskManager[RoleT]):
exp_time_s=exp_time_s,
**self._data_collection_settings(file_prefix or f"rotation_{token_hex(3)}"),
)
self._collect(
return self._collect(
scan, f"rotation scan, {steps} images of {incr_omega_deg} deg, {exp_time_s} s each"
)
@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: 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."""
self._rotation_scan(
exp_time_s, incr_omega_deg, steps, start_omega_deg, file_prefix, dtz, transmission
)
@task
def xray_centering(self, dbid: int, strategy: dict) -> MxSequenceUpdate:
result = self._run_raster(**strategy)
"""Collect the grid scan described by `strategy` (the arguments of `grid_scan`) and
record its per-image results for the sample. The Smargon stays at the raster start."""
result = self._grid_scan(**strategy)
info = self._client.sample_info
if info is None or info.sample_id != dbid:
self._client.reset_sample_info(dbid)
@@ -496,7 +436,7 @@ class MxTasks(TaskManager[RoleT]):
omega_deg=strategy.get("omega_deg", 0.0),
snake=True, # jfjoch.dataset_settings uses GridScan(snake=True)
),
images=scan_images(result),
images=list(result.images),
)
return (
StateEndpoints.xray_centering_done(),
@@ -536,7 +476,7 @@ class MxTasks(TaskManager[RoleT]):
try:
for chi in p.chi_values():
smargon.chi.set(chi).wait()
request = RotationScanRequest(
result = self._rotation_scan(
exp_time_s=p.exp_time_s,
incr_omega_deg=p.incr_omega_deg,
steps=p.steps,
@@ -545,12 +485,9 @@ class MxTasks(TaskManager[RoleT]):
dtz=p.dtz,
transmission=p.transmission,
)
result = self._client.aaredaq.rotation_scan(request)
record.sweeps.append(
SweepRecord(
chi_deg=chi,
images=scan_images(result),
bravais=getattr(result.result, "rotation_bravais", None),
chi_deg=chi, images=list(result.images), bravais=result.rotation_bravais
)
)
finally:
+1 -45
View File
@@ -2,10 +2,7 @@ import subprocess
from unittest.mock import MagicMock, call, patch
import pytest
from aarecommon.math.coordinate import Coordinate, SmargonCoordinate
from aarecommon.models.auth import BatonStatus
from aarecommon.models.raster_grid import CompletedRasterGrid, RasterGridRequest
from aarecommon.models.rotation_scan import CompletedRotationScan, RotationScanRequest
from mx_bec.external_services.aaredaq import DEFAULT_URLS, AareDaq, AareDaqError
@@ -61,20 +58,6 @@ def _set_posts(daq, *responses):
)
def _raster_request():
return RasterGridRequest(
n_x=2,
n_y=1,
grid_size_mm=Coordinate(x=0.05, y=0.05),
file_prefix="t",
exp_time_s=0.1,
dtz=150,
transmission=1,
smargon_top_left=SmargonCoordinate(),
omega_deg=0.0,
)
def test_url_and_cert_are_resolved_from_beamline_config_on_first_use(curl, monkeypatch):
monkeypatch.delenv("BEAMLINE", raising=False)
daq = AareDaq(MagicMock()) # must not need the beamline environment yet
@@ -135,28 +118,6 @@ def test_mount_sample(daq):
]
def test_raster_scan(daq):
request = _raster_request()
completed = CompletedRasterGrid(r=[])
_set_posts(daq, _response(json_data=completed.model_dump(mode="json")))
assert daq.raster_scan(request, auto_center=True) == completed
[(url, kwargs)] = _calls(daq, "POST")
assert url == f"{URL}/scan/raster"
assert kwargs["params"] == {"auto_center": True}
assert kwargs["json"] == request.model_dump(mode="json")
assert kwargs["timeout"] == 3600.0
def test_rotation_scan(daq):
request = RotationScanRequest(exp_time_s=0.05, incr_omega_deg=0.1, steps=100)
completed = CompletedRotationScan(request=request, result={"images": []})
_set_posts(daq, _response(json_data=completed.model_dump(mode="json")))
assert daq.rotation_scan(request) == completed
[(url, kwargs)] = _calls(daq, "POST")
assert url == f"{URL}/scan/rotation"
assert kwargs["json"] == request.model_dump(mode="json")
def test_expired_token_is_renewed_once(daq, curl):
curl.side_effect = [_curl_result(), _curl_result('{"access_token": "new"}')]
_set_posts(daq, _response(401), _response(json_data="OK"))
@@ -176,7 +137,7 @@ def test_persistent_401_is_an_error(daq):
def test_http_error_reports_status_and_body(daq):
_set_posts(daq, _response(422, text='{"detail": "bad request"}'))
with pytest.raises(AareDaqError, match="422.*bad request"):
daq.rotation_scan(RotationScanRequest(exp_time_s=0.05, incr_omega_deg=0.1, steps=1))
daq.mount_sample(1)
# ---- baton ----
@@ -246,8 +207,3 @@ def test_take_baton_gives_up_after_wait(daq):
pytest.raises(AareDaqError, match="not granted"),
):
daq.take_baton(wait_s=0)
def test_release_baton(daq):
daq.release_baton()
assert [url for url, _ in _calls(daq, "POST")] == [f"{URL}/baton/release"]
+8 -65
View File
@@ -1,23 +1,13 @@
from unittest.mock import MagicMock
import pytest
from aarecommon.math.coordinate import Coordinate, SmargonCoordinate
from aarecommon.models.raster_grid import RasterGridRequest
from aarecommon.models.rotation_scan import RotationScanRequest
from mx_bec.decisions 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():
client = MagicMock()
for axis, position in SMARGON_POSITION.items():
getattr(client.devices.smargon, axis).get.return_value = position
return client
return MagicMock()
@pytest.fixture
@@ -25,11 +15,15 @@ def tasks(client):
return MxTasks[Server](client)
def test_mount_sample_is_a_task():
assert MxTasks.is_task("aaredaq_mount_sample")
@pytest.mark.parametrize(
"name", ["aaredaq_mount_sample", "aaredaq_raster_scan", "aaredaq_rotation_scan"]
"name", ["aaredaq_raster_scan", "aaredaq_rotation_scan", "cleanup_beamline"]
)
def test_aaredaq_methods_are_tasks(name):
assert MxTasks.is_task(name)
def test_other_aaredaq_tasks_are_gone(name):
assert not MxTasks.is_task(name)
def test_mount_sample(tasks, client):
@@ -39,57 +33,6 @@ def test_mount_sample(tasks, client):
client.aaredaq.mount_sample.assert_called_with(7, reference=True)
def test_raster_scan_builds_request_from_flat_arguments(tasks, client):
tasks.aaredaq_raster_scan(
n_x=4, n_y=3, step_x_mm=0.05, step_y_mm=0.04, exp_time_s=0.1, omega_deg=12.0, dtz=150.0
)
request, kwargs = (
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,
grid_size_mm=Coordinate(x=0.05, y=0.04),
exp_time_s=0.1,
omega_deg=12.0,
dtz=150.0,
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}
def test_rotation_scan_builds_request_from_flat_arguments(tasks, client):
tasks.aaredaq_rotation_scan(
exp_time_s=0.05, incr_omega_deg=0.1, steps=100, start_omega_deg=90.0, file_prefix="rot"
)
assert client.aaredaq.rotation_scan.call_args.args[0] == RotationScanRequest(
exp_time_s=0.05, incr_omega_deg=0.1, steps=100, start_omega_deg=90.0, file_prefix="rot"
)
def test_screening_scan(tasks, client):
tasks.aaredaq_rotation_scan(0.05, 1.0, 4, screening=True, wedge_omega_deg=90.0)
request = client.aaredaq.rotation_scan.call_args.args[0]
assert request.screening is True and request.wedge_omega_deg == 90.0
def test_failed_aaredaq_call_pauses_queue_and_reraises(tasks, client):
client.aaredaq.mount_sample.side_effect = RuntimeError("sample not found")
with pytest.raises(RuntimeError, match="sample not found"):