From 4ff87a37827846d761881f64948af33d85fa93ee Mon Sep 17 00:00:00 2001 From: David Perl Date: Thu, 26 Nov 2026 16:11:41 +0100 Subject: [PATCH] feat: add grid scan task --- .../widgets/aare_bec/task_panel.py | 10 + mx_bec/tasks/mx_tasks.py | 173 +++++++++++++++++- 2 files changed, 180 insertions(+), 3 deletions(-) diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py index 23e5ce4..4be983e 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -40,6 +40,16 @@ TASK_FORMS: dict[str, list[tuple[str, int | float | str | list[float]]]] = { ("dtz", 250), ("file_prefix", "AareBecTestGridScan"), ], + # the same scan run by BEC itself (Smargon, JFJoch and Aerotech), without AareDAQ + "grid_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), + ("file_prefix", "AareBecTestGridScan"), + ], "multiple_rasters": [ ("omegas_deg_list", [0, 45, 60, 90, 120, 135]), ("n_x", 10), diff --git a/mx_bec/tasks/mx_tasks.py b/mx_bec/tasks/mx_tasks.py index a707a7d..a425a89 100644 --- a/mx_bec/tasks/mx_tasks.py +++ b/mx_bec/tasks/mx_tasks.py @@ -1,15 +1,23 @@ from __future__ import annotations +import json +from dataclasses import dataclass +from importlib.resources import files 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.raster_grid import CompletedRasterGrid # already imported in aaredaq.py -from aarecommon.models.raster_grid import RasterGridRequest +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 ( + BeamState, CollectionRecord, GridGeometry, RasterRecord, @@ -20,6 +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.messages import MXMeasurementSequenceMessage from mx_bec.tasks.core import MxSequenceUpdate, RoleT, TaskManager, task @@ -28,6 +37,23 @@ if TYPE_CHECKING: logger = bec_logger.logger +MAX_GRID_SCAN_S = 1200.0 # refuse grid scans expected to take longer than 20 min +JFJOCH_TIMEOUT_S = 60.0 # for JFJoch to arm the detector, and to finish once the scan is done + + +@dataclass +class BeamConditions: + """The state of the beamline which JFJoch records with a data collection.""" + + energy_keV: float + full_flux_ph_s: float # at transmission 1 + transmission: float + detector_distance_mm: float + beam_center_pxl: tuple[float, float] + beam_size_mm: tuple[float, float] + ring_current_mA: float + sample_temperature_K: float + class MxTasks(TaskManager[RoleT]): """The operations on mx beamlines which can be requested as tasks. Instantiate as @@ -36,7 +62,6 @@ class MxTasks(TaskManager[RoleT]): TODO: - categorise tasks - - add doc info to decorator, including placeholder for args, to show to GUI """ if TYPE_CHECKING: @@ -235,6 +260,148 @@ class MxTasks(TaskManager[RoleT]): 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"] + + def _energy_eV_and_full_flux_ph_s(self, transmission: float) -> tuple[float, float]: + """The photon energy, from the monochromator angle, and the flux at the sample at + transmission 1, from the beam position monitor. Both come from PXII calibrations.""" + # pylint: disable=import-outside-toplevel + from pxii_bec.macros.calculator import ( # pyright: ignore[reportMissingImports] + convert_from_bragg, + ) + from pxii_bec.macros.flux_macros import bpm2flux # pyright: ignore[reportMissingImports] + + energy_eV = convert_from_bragg(self._read("dcm_bragg"))["energy_ev"] + _, full_flux = bpm2flux( + energy=energy_eV, bpmsum=self._read("bcu_bpmsum"), transm=transmission + ) + return energy_eV, full_flux + + def _beam_center_pxl(self, det_z_mm: float, det_y_mm: float) -> tuple[float, float]: + """Where the beam hits the detector at this detector position, from the beam centres + which aarecommon has measured for the beamline.""" + beamline = mx_beamline().value.lower() + measured = json.loads( + files("aarecommon.config").joinpath("beamline_configs/beam_centres.json").read_text() + ) + if beamline not in measured: + raise ValueError(f"aarecommon has no beam centre measurements for {beamline}") + x, y = BeamCentre.model_validate(measured[beamline]).model.predict(det_z_mm, det_y_mm) + return float(x[0]), float(y[0]) + + def _beam_conditions(self) -> BeamConditions: + transmission = self._read("transm") + energy_eV, full_flux = self._energy_eV_and_full_flux_ph_s(transmission) + det_z_mm = self._read("det_z") + beam_size_um = BeamState().beam_size_um # not measured: the strategy's default + return BeamConditions( + energy_keV=energy_eV / 1000.0, + full_flux_ph_s=full_flux, + transmission=transmission, + detector_distance_mm=det_z_mm, + beam_center_pxl=self._beam_center_pxl(det_z_mm, self._read("det_y")), + beam_size_mm=(beam_size_um[0] / 1000.0, beam_size_um[1] / 1000.0), + ring_current_mA=self._read("sls_current"), + sample_temperature_K=self._read("cryo_temp"), + ) + + def _set_grid_scan_prerequisites( + self, + n_x: int, + n_y: int, + step_x_mm: float, + step_y_mm: float, + exp_time_s: float, + omega_deg: float, + dtz: float | None, + transmission: float | None, + ) -> 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.u.set(omega_deg).wait() + 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), + ): + signal.set(value).wait() + if not config.valid.get(): + raise ValueError(f"AareScan rejected the grid scan parameters: {config.message.get()}") + + @task + 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, + ) -> 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 + ) + + 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) + + beam = self._beam_conditions() + 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, + 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(), + ) + 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: result = self._run_raster(**strategy)