From 4adfa7c174c03cb295a4c104541c6c9fddcf609e Mon Sep 17 00:00:00 2001 From: David Perl Date: Wed, 2 Dec 2026 13:07:39 +0100 Subject: [PATCH] f --- .../systemd/mx-bec-service-restart.path | 9 + .../systemd/mx-bec-service-restart.service | 7 + deployment/systemd/mx-bec-service.service | 19 + mx_bec/external_services/__init__.py | 0 tests/unit/test_grid_scan_task.py | 424 ++++++++++++++++++ 5 files changed, 459 insertions(+) create mode 100644 deployment/systemd/mx-bec-service-restart.path create mode 100644 deployment/systemd/mx-bec-service-restart.service create mode 100644 deployment/systemd/mx-bec-service.service create mode 100644 mx_bec/external_services/__init__.py create mode 100644 tests/unit/test_grid_scan_task.py diff --git a/deployment/systemd/mx-bec-service-restart.path b/deployment/systemd/mx-bec-service-restart.path new file mode 100644 index 0000000..ff16773 --- /dev/null +++ b/deployment/systemd/mx-bec-service-restart.path @@ -0,0 +1,9 @@ +[Unit] +Description=Watch the deployed mx_bec pyproject.toml, to restart the MX BEC service on a new deployment + +[Path] +PathChanged=/sls/x10sa/config/bec/test/mx_bec/pyproject.toml +Unit=mx-bec-service-restart.service + +[Install] +WantedBy=multi-user.target diff --git a/deployment/systemd/mx-bec-service-restart.service b/deployment/systemd/mx-bec-service-restart.service new file mode 100644 index 0000000..dc41ac7 --- /dev/null +++ b/deployment/systemd/mx-bec-service-restart.service @@ -0,0 +1,7 @@ +[Unit] +Description=Restart the MX BEC service after a new deployment + +[Service] +Type=oneshot +# try-restart: leave the service stopped if it was stopped on purpose +ExecStart=/usr/bin/systemctl try-restart mx-bec-service.service diff --git a/deployment/systemd/mx-bec-service.service b/deployment/systemd/mx-bec-service.service new file mode 100644 index 0000000..ee7b219 --- /dev/null +++ b/deployment/systemd/mx-bec-service.service @@ -0,0 +1,19 @@ +[Unit] +Description=MX BEC service (AareBec) +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +Environment=BEAMLINE=x10sa +Environment=CONFIG_REDIS_URL=redis://mx-x10sa-queue-01:6379 +# Started through bash: SELinux does not let systemd (init_t) execute files on NFS (nfs_t) directly +ExecStart=/bin/bash -c 'exec /sls/x10sa/config/bec/test/bec_venv/bin/mx-bec-service' +# the service shuts down cleanly on a keyboard interrupt +KillSignal=SIGINT +TimeoutStopSec=30 +Restart=on-failure +RestartSec=5 + +[Install] +WantedBy=multi-user.target diff --git a/mx_bec/external_services/__init__.py b/mx_bec/external_services/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/unit/test_grid_scan_task.py b/tests/unit/test_grid_scan_task.py new file mode 100644 index 0000000..81992f0 --- /dev/null +++ b/tests/unit/test_grid_scan_task.py @@ -0,0 +1,424 @@ +from types import SimpleNamespace +from unittest.mock import MagicMock, call + +import pytest +from aarelcinfer_client.models import LatestPredictionModel + +from mx_bec.decisions import RotationPlan +from mx_bec.endpoints import StateEndpoints +from mx_bec.external_services.jfjoch import RasterScan, RotationScan +from mx_bec.sample_info import OpticalCenteringResults, SampleInfo +from mx_bec.tasks import MxTasks, Server +from mx_bec.tasks.mx_tasks import MAX_GRID_SCAN_S, MAX_ROTATION_SCAN_S, BeamConditions + +GRID = dict(n_x=4, n_y=3, step_x_mm=0.05, step_y_mm=0.04, exp_time_s=0.1) +BEAM = BeamConditions( + energy_keV=12.658, + full_flux_ph_s=1e12, + transmission=0.5, + detector_distance_mm=150.0, + beam_center_pxl=(1000.0, 1100.0), + beam_size_mm=(0.02, 0.01), + ring_current_mA=400.0, + sample_temperature_K=100.0, +) +# what the devices read, by name +READINGS = {"transm": 0.5, "det_z": 200.0, "det_y": 62.0, "sls_current": 400.0, "cryo_temp": 100.0} + + +@pytest.fixture +def client(): + client = MagicMock() + client.devices.aerotech.gridscan_config.valid.get.return_value = True + client.devices.aerotech.rotation_config.valid.get.return_value = True + client.devices.smargon.phi.get.return_value = 30.0 + client.devices.smargon.chi.get.return_value = 20.0 + client.devices.__getitem__.side_effect = lambda name: SimpleNamespace( + read=lambda: {name: {"value": READINGS[name]}} + ) + # 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], rotation_bravais="tP" + ) + return client + + +@pytest.fixture +def tasks(client, monkeypatch): + tasks = MxTasks[Server](client) + monkeypatch.setattr(tasks, "_beam_conditions", lambda: BEAM) + return tasks + + +def test_grid_scan_is_a_task(): + assert MxTasks.is_task("grid_scan") + + +def test_grid_scan_sequence(tasks, client): + devices, jfjoch = client.devices, client.jfjoch + # one mock to record the order across the devices and jfjoch + sequence = MagicMock() + sequence.attach_mock(devices.aerotech.u.set, "rotate") + sequence.attach_mock(devices.aerotech.scan_type.set, "scan_type") + sequence.attach_mock(devices.aerotech.gridscan_config.valid.get, "validate") + sequence.attach_mock(devices.smargon.nudge_in_lab_frame, "nudge") + sequence.attach_mock(jfjoch, "jfjoch") + sequence.attach_mock(devices.aerotech.trigger, "trigger") + + tasks.grid_scan(**GRID, omega_deg=12.0, file_prefix="grid") + + 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, + smargon_phi_deg=30.0, + smargon_chi_deg=20.0, + ) + # prerequisites, then the smargon goes to the top left corner (half the grid away), then + # JFJoch is armed before the Aerotech moves, and the result is collected afterwards + assert sequence.mock_calls == [ + call.rotate(12.0), + call.rotate().wait(), + call.scan_type("grid_scan"), + call.scan_type().wait(), + call.validate(), + call.nudge(pytest.approx(-0.1), pytest.approx(-0.06)), + call.jfjoch.measure_raster(scan), + call.jfjoch.wait_till_running(timeout_s=60.0), + call.trigger(), + call.trigger().wait(), + call.jfjoch.wait_till_done(timeout_s=60.0), + ] + + +def test_grid_scan_configures_the_aerotech_in_microns(tasks, client): + tasks.grid_scan(**GRID) + config = client.devices.aerotech.gridscan_config + 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(pytest.approx(50.0)) + config.grid_elem_size_y_um.set.assert_called_once_with(pytest.approx(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 + + +def test_grid_scan_leaves_detector_distance_and_transmission_unless_given(tasks, client): + tasks.grid_scan(**GRID) + client.scans.mv.assert_not_called() + tasks.grid_scan(**GRID, dtz=180.0, transmission=0.2) + assert client.scans.mv.call_args_list == [ + call(client.devices.det_z, 180.0, relative=False), + call(client.devices.transm, 0.2, relative=False), + ] + + +def test_grid_scan_names_the_files_itself_if_no_prefix_is_given(tasks, client): + tasks.grid_scan(**GRID) + tasks.grid_scan(**GRID) + first, second = (c.args[0].file_prefix for c in client.jfjoch.measure_raster.call_args_list) + assert first.startswith("grid_") and second.startswith("grid_") and first != second + + +def test_grid_scan_refuses_invalid_parameters(tasks, 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"): + tasks.grid_scan(**GRID) + client.devices.smargon.nudge_in_lab_frame.assert_not_called() + client.jfjoch.measure_raster.assert_not_called() + client.devices.aerotech.trigger.assert_not_called() + + +def test_grid_scan_refuses_too_long_scans(tasks, 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"): + tasks.grid_scan(**too_long) + client.devices.aerotech.u.set.assert_not_called() + + +def test_grid_scan_cancels_jfjoch_if_the_aerotech_scan_fails(tasks, client): + client.devices.aerotech.trigger.return_value.wait.side_effect = RuntimeError("stage fault") + with pytest.raises(RuntimeError, match="stage fault"): + tasks.grid_scan(**GRID) + client.jfjoch.cancel.assert_called_once_with() + client.jfjoch.wait_till_done.assert_not_called() + + +ROTATION = dict(exp_time_s=0.05, incr_omega_deg=0.1, steps=100) + + +def test_rotation_scan_is_a_task(): + assert MxTasks.is_task("rotation_scan") + + +def test_rotation_scan_sequence(tasks, client): + devices, jfjoch = client.devices, client.jfjoch + sequence = MagicMock() + sequence.attach_mock(devices.aerotech.scan_type.set, "scan_type") + sequence.attach_mock(devices.aerotech.rotation_config.valid.get, "validate") + sequence.attach_mock(jfjoch, "jfjoch") + sequence.attach_mock(devices.aerotech.trigger, "trigger") + + tasks.rotation_scan(**ROTATION, start_omega_deg=30.0, file_prefix="rot") + + scan = jfjoch.measure_rotation.call_args.args[0] + assert scan == RotationScan( + steps=100, + incr_omega_deg=0.1, + start_omega_deg=30.0, + exp_time_s=0.05, + detector_distance_mm=150.0, + transmission=0.5, + file_prefix="rot", + 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=30.0, + smargon_chi_deg=20.0, + ) + # the Aerotech is set to run its rotation scan, then JFJoch is armed before it is triggered + assert sequence.mock_calls == [ + call.scan_type("rotation_scan"), + call.scan_type().wait(), + call.validate(), + call.jfjoch.measure_rotation(scan), + call.jfjoch.wait_till_running(timeout_s=60.0), + call.trigger(), + call.trigger().wait(), + call.jfjoch.wait_till_done(timeout_s=60.0), + ] + # the sample stays where it is + devices.smargon.nudge_in_lab_frame.assert_not_called() + jfjoch.measure_raster.assert_not_called() + + +def test_rotation_scan_configures_the_aerotech_with_totals(tasks, client): + tasks.rotation_scan(**ROTATION, start_omega_deg=30.0) + config = client.devices.aerotech.rotation_config + config.rotation_deg.set.assert_called_once_with(pytest.approx(10.0)) + config.total_time_sec.set.assert_called_once_with(pytest.approx(5.0)) + config.start_pos_deg.set.assert_called_once_with(30.0) + + +def test_rotation_scan_sets_detector_distance_and_transmission_if_given(tasks, client): + tasks.rotation_scan(**ROTATION) + client.scans.mv.assert_not_called() + tasks.rotation_scan(**ROTATION, dtz=180.0, transmission=0.2) + assert client.scans.mv.call_args_list == [ + call(client.devices.det_z, 180.0, relative=False), + call(client.devices.transm, 0.2, relative=False), + ] + + +def test_rotation_scan_refuses_invalid_parameters(tasks, client): + config = client.devices.aerotech.rotation_config + config.valid.get.return_value = False + config.message.get.return_value = "too fast" + with pytest.raises(ValueError, match="too fast"): + tasks.rotation_scan(**ROTATION) + client.jfjoch.measure_rotation.assert_not_called() + client.devices.aerotech.trigger.assert_not_called() + + +def test_rotation_scan_refuses_too_long_scans(tasks, client): + with pytest.raises(ValueError, match="too long"): + tasks.rotation_scan(exp_time_s=1.0, incr_omega_deg=0.1, steps=int(MAX_ROTATION_SCAN_S) + 1) + client.devices.aerotech.scan_type.set.assert_not_called() + + +def test_rotation_scan_cancels_jfjoch_if_the_aerotech_scan_fails(tasks, client): + client.devices.aerotech.trigger.return_value.wait.side_effect = RuntimeError("stage fault") + with pytest.raises(RuntimeError, match="stage fault"): + tasks.rotation_scan(**ROTATION) + client.jfjoch.cancel.assert_called_once_with() + + +def test_beam_conditions_are_read_from_the_devices(client, monkeypatch): + monkeypatch.setenv("BEAMLINE", "X10SA") + tasks = MxTasks[Server](client) + # energy and flux come from beamline plugin calibrations + energy_and_flux = MagicMock(return_value=(12658.0, 2e12)) + monkeypatch.setattr(tasks, "_energy_eV_and_full_flux_ph_s", energy_and_flux) + + beam = tasks._beam_conditions() + + energy_and_flux.assert_called_once_with(0.5) + assert beam.energy_keV == pytest.approx(12.658) + assert (beam.full_flux_ph_s, beam.transmission) == (2e12, 0.5) + assert (beam.detector_distance_mm, beam.ring_current_mA) == (200.0, 400.0) + assert beam.sample_temperature_K == 100.0 + # from aarecommon's measurements for X10SA, which lie around (2080, 2230) at this position + assert beam.beam_center_pxl == pytest.approx((2080, 2230), abs=30) + assert beam.beam_size_mm == pytest.approx((0.025, 0.025)) + + +def test_beam_center_needs_measurements_for_the_beamline(client, monkeypatch): + monkeypatch.setenv("BEAMLINE", "SIMULATED") + with pytest.raises(ValueError, match="no beam centre measurements"): + MxTasks[Server](client)._beam_center_pxl(200.0, 62.0) + + +# ---- the tasks built on the grid and rotation scans; none of them may go through AareDAQ ---- + + +def test_multiple_rasters_scans_at_each_omega_and_returns_to_the_centre(tasks, client): + client.sample_info = SampleInfo(sample_id=5) + tasks.multiple_rasters([0.0, 90.0], **GRID, file_prefix="multi") + endpoint, msg = client.connector.set_and_publish.call_args.args + + scans = [c.args[0] for c in client.jfjoch.measure_raster.call_args_list] + assert [scan.omega_deg for scan in scans] == [0.0, 90.0] + assert scans[0].file_prefix.startswith("multi_0_0.00deg_") + assert scans[1].file_prefix.startswith("multi_1_90.00deg_") + # to the corner and back for each grid, so every grid is centred on the same point + to_corner = call(pytest.approx(-0.1), pytest.approx(-0.06)) + back = call(pytest.approx(0.1), pytest.approx(0.06)) + assert client.devices.smargon.nudge_in_lab_frame.call_args_list == [ + to_corner, + back, + to_corner, + back, + ] + assert endpoint == StateEndpoints.sample_done() + assert (msg.sample_id, msg.success) == (5, True) + assert client.aaredaq.mock_calls == [] + + +def test_multiple_rasters_returns_to_the_centre_if_a_scan_fails(tasks, client): + client.devices.aerotech.trigger.return_value.wait.side_effect = RuntimeError("stage fault") + with pytest.raises(RuntimeError, match="stage fault"): + tasks.multiple_rasters([0.0, 90.0], **GRID) + assert client.devices.smargon.nudge_in_lab_frame.call_count == 2 + + +def test_xray_centering_records_the_raster_and_stays_at_its_start(tasks, client): + client.sample_info = SampleInfo(sample_id=5) + strategy = dict(GRID, omega_deg=30.0, file_prefix="xc", dtz=200.0) + + tasks.xray_centering(5, strategy) + endpoint, msg = client.connector.set_and_publish.call_args.args + + client.jfjoch.measure_raster.assert_called_once() + client.devices.smargon.nudge_in_lab_frame.assert_called_once() + raster = client.sample_info.raster + assert raster.strategy == strategy + assert raster.images == [1, 2, 3] + assert (raster.geometry.n_x, raster.geometry.n_y) == (4, 3) + assert raster.geometry.omega_deg == 30.0 + assert endpoint == StateEndpoints.xray_centering_done() + assert (msg.sample_id, msg.success) == (5, True) + assert client.aaredaq.mock_calls == [] + + +def test_collect_dataset_runs_a_rotation_scan_per_chi(tasks, client): + client.sample_info = SampleInfo(sample_id=5) + plan = RotationPlan( + position_index=0, + offset_x_mm=0.0, + offset_y_mm=0.0, + chi_deg_list="0,20", + incr_omega_deg=0.1, + steps=100, + exp_time_s=0.05, + transmission=0.2, + dtz=180.0, + file_prefix="data", + dose_MGy=1.0, + target_res_A=2.0, + ) + + tasks.collect_dataset(5, plan.model_dump()) + endpoint, msg = client.connector.set_and_publish.call_args.args + + scans = [c.args[0] for c in client.jfjoch.measure_rotation.call_args_list] + assert [scan.file_prefix for scan in scans] == ["data_chi0", "data_chi20"] + assert [scan.steps for scan in scans] == [100, 100] + chi = client.devices.smargon.chi.set + assert chi.call_args_list == [call(0.0), call(20.0), call(0.0)] # and back to 0 at the end + [record] = client.sample_info.collections + assert [(s.chi_deg, s.images, s.bravais) for s in record.sweeps] == [ + (0.0, [1, 2, 3], "tP"), + (20.0, [1, 2, 3], "tP"), + ] + assert endpoint == StateEndpoints.rotation_done() + assert (msg.sample_id, msg.success) == (5, True) + assert client.aaredaq.mock_calls == [] + + +def _prediction(target_point, geometry=None): + return LatestPredictionModel( + frame_id=1, + time=0.0, + image_width=1000, + image_height=800, + target_point=target_point, + geometry=geometry, + conf=0.5, + infer_scale=1.0, + skip=0, + max_fps=10.0, + tracker="none", + worker_shard_index=0, + worker_shard_count=1, + pixel_format="BGR", + ) + + +def _optical_centering(tasks, client, prediction): + """Run the task with `prediction` as what the optical prediction service returns.""" + client.sample_info = SampleInfo(sample_id=5) + + def update_latest(): + client.sample_info.optical_centering_results = OpticalCenteringResults( + prediction=prediction, microns_per_pixel=2.0 + ) + + client.optical_prediction.update_latest.side_effect = update_latest + tasks.run_optical_centering(5) + return client.connector.set_and_publish.call_args.args + + +def test_optical_centering_nudges_the_target_point_to_the_beam(tasks, client): + geometry = dict(zoom=400.0, um_per_px=2.0, beam_x=600.0, beam_y=300.0, source="test") + target = dict(x=650, y=250, source="test") + endpoint, msg = _optical_centering(tasks, client, _prediction(target, geometry)) + # 50 px right of and 50 px above the beam, at 2 um per pixel + client.devices.smargon.nudge_in_lab_frame.assert_called_once_with( + pytest.approx(0.1), pytest.approx(-0.1) + ) + # the prediction is taken again once the sample has moved + assert client.optical_prediction.update_latest.call_count == 2 + assert endpoint == StateEndpoints.optical_centering_done() + assert (msg.sample_id, msg.success) == (5, True) + assert client.aaredaq.mock_calls == [] + + +def test_optical_centering_assumes_the_beam_at_the_image_centre_without_geometry(tasks, client): + _optical_centering(tasks, client, _prediction(dict(x=400, y=500, source="test"))) + client.devices.smargon.nudge_in_lab_frame.assert_called_once_with( + pytest.approx(-0.2), pytest.approx(0.2) + ) + + +def test_optical_centering_fails_without_a_target_point(tasks, client): + endpoint, msg = _optical_centering(tasks, client, _prediction(None)) + client.devices.smargon.nudge_in_lab_frame.assert_not_called() + assert endpoint == StateEndpoints.optical_centering_done() + assert (msg.sample_id, msg.success) == (5, False)