diff --git a/mx_bec/jfjoch.py b/mx_bec/jfjoch.py new file mode 100644 index 0000000..4536851 --- /dev/null +++ b/mx_bec/jfjoch.py @@ -0,0 +1,189 @@ +from __future__ import annotations + +import functools +import math +from typing import TYPE_CHECKING, Callable, ParamSpec, TypeVar + +import jfjoch_client +from aarecommon.config.beamline import get_jfjoch_url, mx_beamline +from bec_lib.logger import bec_logger +from jfjoch_client.models.dataset_settings_smargon import DatasetSettingsSmargon +from pydantic import BaseModel, Field + +if TYPE_CHECKING: + from jfjoch_client.models.scan_result import ScanResult + + from mx_bec.service import AareBec + +logger = bec_logger.logger + +P = ParamSpec("P") +R = TypeVar("R") + + +class RasterScan(BaseModel): + """Everything JFJoch needs to collect one raster (grid) scan.""" + + # 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 /raw/raster/ + file_prefix: str + pgroup: str = "p16371" + sample_name: str = "unknown_sample" + # beamline and diffraction geometry + energy_keV: float = Field(gt=0) + beam_center_pxl: tuple[float, float] + beam_size_mm: tuple[float, float] + poni_rot1_rad: float = 0.0 + poni_rot2_rad: float = 0.0 + ring_current_mA: float + flux_ph_s: float + sample_temperature_K: float + smargon_phi_deg: float | None = None + smargon_chi_deg: float | None = None + + +class JFJochError(RuntimeError): + """A call to the JFJoch detector broker failed.""" + + +def needs_connection(method: Callable[P, R]) -> Callable[P, R]: + """Connect to JFJoch before the decorated method touches the API.""" + + @functools.wraps(method) + def wrapper(self: JFJoch, *args, **kwargs): + self.connect() + return method(self, *args, **kwargs) + + return wrapper # type: ignore # self is part of P + + +class JFJoch: + """Thin wrapper around the JFJoch detector broker REST API, for raster (grid) scans. + + Adapted from aaredaq's `JFJochWrapper`: the client is created on first use and every API + call is wrapped so that failures raise `JFJochError`. + """ + + def __init__(self, client: AareBec, url: str | None = None) -> None: + self._client = client + self._url = url + self._api: jfjoch_client.DefaultApi | None = None + + @property + def url(self) -> str: + """The broker URL: as given, else resolved on first use from the aarecommon beamline + config, which picks the beamline from the BEAMLINE environment variable.""" + if self._url is None: + self._url = get_jfjoch_url(mx_beamline()) + return self._url + + def connect(self) -> None: + """Create the API client on first use and cancel anything JFJoch is still doing.""" + if self._api is not None: + return + api_client = jfjoch_client.ApiClient(jfjoch_client.Configuration(host=self.url)) + self._api = jfjoch_client.DefaultApi(api_client) + try: + self.cancel() + except JFJochError: + self._api = None + raise + + def _call(self, endpoint: str, *args, **kwargs): + """Call `endpoint` on the API, turning any failure into a JFJochError.""" + assert self._api is not None, "connect() must be called first" + try: + return getattr(self._api, endpoint)(*args, **kwargs) + except Exception as e: + raise JFJochError(f"JFJoch {endpoint} failed: {e}") from e + + @needs_connection + def cancel(self) -> None: + self._call("cancel_post") + + @needs_connection + def measure_raster(self, scan: RasterScan, async_start: bool = True) -> None: + """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 wait_till_running(self, timeout_s: float = 60) -> None: + """Block until JFJoch reports the detector armed, or raise.""" + logger.info("Waiting for JFJoch to report detector armed") + try: + self._call("wait_until_running_post_with_http_info", timeout=math.ceil(timeout_s)) + except JFJochError as e: + if "Output file already exists" in str(e): + raise JFJochError( + "JFJoch reports the output file already exists: change the file name or " + "increment the run number." + ) from e + raise + status = self._call("status_get") + logger.debug(status) + if status.message_severity == "error": + raise JFJochError(f"JFJoch reported an error after arming: {status.message}") + + @needs_connection + def wait_till_done(self, timeout_s: float) -> ScanResult: + """Block until the running data collection finished and return its result.""" + self._call("wait_till_done_post_with_http_info", timeout=math.ceil(timeout_s)) + return self._call("result_scan_get") + + def dataset_settings( + self, scan: RasterScan, 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) + 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) + ) + else: + smargon = None + return jfjoch_client.DatasetSettings( + beam_x_pxl=scan.beam_center_pxl[0], + beam_y_pxl=scan.beam_center_pxl[1], + ntrigger=ntrigger, + images_per_trigger=images, + detector_distance_mm=scan.detector_distance_mm, + file_prefix=f"{scan.pgroup}/raw/raster/{scan.file_prefix}", + incident_energy_keV=scan.energy_keV, + sample_name=scan.sample_name, + image_time_us=round(scan.exp_time_s * 1e6), + experiment_group=scan.pgroup, + transmission=scan.transmission, + ring_current_mA=scan.ring_current_mA, + sample_temperature_K=scan.sample_temperature_K, + total_flux=scan.flux_ph_s * scan.transmission, + poni_rot1_rad=scan.poni_rot1_rad, + poni_rot2_rad=scan.poni_rot2_rad, + max_spot_count=1000, + detect_ice_rings=True, + async_start=async_start, + smargon=smargon, + beam_size_x_um=scan.beam_size_mm[0] * 1000.0, + beam_size_y_um=scan.beam_size_mm[1] * 1000.0, + 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, + ), + ) diff --git a/mx_bec/service.py b/mx_bec/service.py index 6e4f7ba..6cfc0bb 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -11,6 +11,7 @@ from bec_lib.logger import bec_logger from mx_bec.actor_manager import AareActorManager from mx_bec.constants import AareBecWorkflowState from mx_bec.endpoints import TaskEndpoints +from mx_bec.jfjoch import JFJoch from mx_bec.messages import MXTaskQueueChangedMessage from mx_bec.optical_centering import OpticalPrediction from mx_bec.tasks import MxTaskQueue, MxTasks @@ -45,6 +46,7 @@ class AareBec(BECClient): self.workflow_state = AareBecWorkflowState.IDLE self.actor_manager: AareActorManager | None = None self.optical_prediction = OpticalPrediction(client=self) + self.jfjoch = JFJoch(client=self) # connects lazily on first use self.tasks = MxTasks(self) self.task_queue: MxTaskQueue | None = None diff --git a/tests/unit/test_jfjoch.py b/tests/unit/test_jfjoch.py new file mode 100644 index 0000000..4b3bd81 --- /dev/null +++ b/tests/unit/test_jfjoch.py @@ -0,0 +1,152 @@ +from unittest.mock import MagicMock, patch + +import pytest +from pydantic import ValidationError + +from mx_bec.jfjoch import JFJoch, JFJochError, RasterScan + + +@pytest.fixture +def api(): + with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client: + yield jfjoch_client.DefaultApi.return_value + + +@pytest.fixture +def client(): + client = MagicMock() + client.aare_config.jfjoch.n_images_per_file = 100 + return client + + +@pytest.fixture +def jfjoch(client, api): + return JFJoch(client, url="http://jfjoch:8080") + + +def _scan(**overrides) -> RasterScan: + params = dict( + n_x=3, + n_y=2, + 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="test", + 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, + smargon_phi_deg=10.0, + smargon_chi_deg=-5.0, + ) + return RasterScan(**{**params, **overrides}) + + +def test_url_is_resolved_from_beamline_config_on_first_use(client, monkeypatch): + monkeypatch.delenv("BEAMLINE", raising=False) + jfjoch = JFJoch(client) # must not need BEAMLINE yet + with ( + patch("mx_bec.jfjoch.mx_beamline", return_value="X10SA") as beamline, + patch("mx_bec.jfjoch.get_jfjoch_url", return_value="http://gpu:8080") as get_url, + ): + assert jfjoch.url == "http://gpu:8080" + assert jfjoch.url == "http://gpu:8080" + get_url.assert_called_once_with("X10SA") + beamline.assert_called_once() + + +def test_connects_lazily_and_cancels_once(jfjoch, api): + api.cancel_post.assert_not_called() + jfjoch.measure_raster(_scan()) + jfjoch.measure_raster(_scan()) + api.cancel_post.assert_called_once() + assert api.start_post.call_count == 2 + + +def test_failed_cancel_on_connect_leaves_it_disconnected(jfjoch, api): + api.cancel_post.side_effect = RuntimeError("down") + with pytest.raises(JFJochError, match="cancel_post failed: down"): + jfjoch.wait_till_done(timeout_s=1) + assert jfjoch._api is None + + +def test_wait_till_running_reports_existing_output_file(jfjoch, api): + api.wait_until_running_post_with_http_info.side_effect = RuntimeError( + "Output file already exists" + ) + with pytest.raises(JFJochError, match="output file already exists"): + jfjoch.wait_till_running(timeout_s=1.5) + api.wait_until_running_post_with_http_info.assert_called_once_with(timeout=2) + + +def test_wait_till_running_raises_on_error_status(jfjoch, api): + api.status_get.return_value.message_severity = "error" + api.status_get.return_value.message = "detector unhappy" + with pytest.raises(JFJochError, match="detector unhappy"): + jfjoch.wait_till_running() + + +def test_wait_till_done_returns_scan_result(jfjoch, api): + assert jfjoch.wait_till_done(timeout_s=10.2) is api.result_scan_get.return_value + api.wait_till_done_post_with_http_info.assert_called_once_with(timeout=11) + + +def test_measure_raster_builds_grid_dataset_settings(jfjoch): + # re-patch to capture the DatasetSettings constructor; connect() happens inside, so the + # API mock to check is this patch's, not the `api` fixture's + with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client: + jfjoch.measure_raster(_scan()) + settings = jfjoch_client.DatasetSettings.call_args.kwargs + assert settings["ntrigger"] == 2 and settings["images_per_trigger"] == 3 + assert settings["file_prefix"] == "p16371/raw/raster/test" + assert settings["experiment_group"] == "p16371" + assert settings["sample_name"] == "unknown_sample" + assert settings["image_time_us"] == 100_000 + assert settings["total_flux"] == 5e11 + assert settings["beam_x_pxl"] == 1000.0 and settings["beam_y_pxl"] == 1100.0 + assert settings["beam_size_x_um"] == 20.0 and settings["beam_size_y_um"] == 10.0 + assert settings["images_per_file"] == 100 + jfjoch_client.GridScan.assert_called_once_with( + n_fast=3, snake=True, step_x_um=50.0, step_y_um=40.0, vertical=False + ) + jfjoch_client.RotationAxis.assert_called_once_with( + step=0, start=12.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)) + settings = jfjoch_client.DatasetSettings.call_args.kwargs + assert settings["ntrigger"] == 1 and settings["images_per_trigger"] == 4 + + +def test_dataset_settings_clamps_negative_chi(jfjoch): + with patch("mx_bec.jfjoch.DatasetSettingsSmargon") as smargon: + jfjoch.dataset_settings(_scan()) + smargon.assert_called_once_with(phi_deg=10.0, chi_deg=0) + + +def test_dataset_settings_without_smargon_angles(jfjoch): + with ( + patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client, + patch("mx_bec.jfjoch.DatasetSettingsSmargon") as smargon, + ): + jfjoch.dataset_settings(_scan(smargon_phi_deg=None)) + smargon.assert_not_called() + assert jfjoch_client.DatasetSettings.call_args.kwargs["smargon"] is None + + +def test_raster_scan_validates_fields(): + with pytest.raises(ValidationError): + _scan(n_x=0) + with pytest.raises(ValidationError): + _scan(transmission=1.5)