refactor: move external services to module
This commit is contained in:
1 parent
9e70f063d4
commit
f82680c569
12 files changed
+492
-21
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
Whitespace-only changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+3
-3
@@ -9,13 +9,13 @@ from bec_lib.client import BECClient
|
||||
from bec_lib.logger import bec_logger
|
||||
from redis.client import Redis
|
||||
|
||||
from mx_bec.aaredaq import AareDaq
|
||||
from mx_bec.actor_manager import AareActorManager
|
||||
from mx_bec.constants import AareBecWorkflowState
|
||||
from mx_bec.endpoints import QueueEndpoints
|
||||
from mx_bec.jfjoch import JFJoch
|
||||
from mx_bec.external_services.aaredaq import AareDaq
|
||||
from mx_bec.external_services.jfjoch import JFJoch
|
||||
from mx_bec.external_services.optical_centering import OpticalPrediction
|
||||
from mx_bec.messages import MXQueueChangedMessage
|
||||
from mx_bec.optical_centering import OpticalPrediction
|
||||
from mx_bec.sample_info import SampleInfo
|
||||
from mx_bec.tasks import MxTaskQueue, MxTasks, Server, UnknownTask
|
||||
|
||||
|
||||
@@ -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 DataCollection, RasterScan, RotationScan
|
||||
from mx_bec.external_services.jfjoch import DataCollection, RasterScan, RotationScan
|
||||
from mx_bec.messages import MXMeasurementSequenceMessage
|
||||
from mx_bec.tasks.core import MxSequenceUpdate, RoleT, TaskManager, task
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ 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.aaredaq import DEFAULT_URLS, AareDaq, AareDaqError
|
||||
from mx_bec.external_services.aaredaq import DEFAULT_URLS, AareDaq, AareDaqError
|
||||
|
||||
URL, CERT, TOKEN = "https://daq.test", "/certs/daq.crt", "eyJ.abc.def"
|
||||
|
||||
@@ -24,7 +24,9 @@ def _response(status_code=200, json_data=None, text=""):
|
||||
|
||||
@pytest.fixture
|
||||
def curl():
|
||||
with patch("mx_bec.aaredaq.subprocess.run", return_value=_curl_result()) as run:
|
||||
with patch(
|
||||
"mx_bec.external_services.aaredaq.subprocess.run", return_value=_curl_result()
|
||||
) as run:
|
||||
yield run
|
||||
|
||||
|
||||
@@ -77,8 +79,10 @@ def test_url_and_cert_are_resolved_from_beamline_config_on_first_use(curl, monke
|
||||
monkeypatch.delenv("BEAMLINE", raising=False)
|
||||
daq = AareDaq(MagicMock()) # must not need the beamline environment yet
|
||||
with (
|
||||
patch("mx_bec.aaredaq.mx_beamline", return_value="X10SA"),
|
||||
patch("mx_bec.aaredaq.cfg_get", side_effect=lambda key, default: default) as cfg_get,
|
||||
patch("mx_bec.external_services.aaredaq.mx_beamline", return_value="X10SA"),
|
||||
patch(
|
||||
"mx_bec.external_services.aaredaq.cfg_get", side_effect=lambda key, default: default
|
||||
) as cfg_get,
|
||||
):
|
||||
assert daq.url == DEFAULT_URLS["X10SA"]
|
||||
assert daq.cert_path == "/sls/x10sa/misc/.cert/10s.crt"
|
||||
@@ -218,7 +222,7 @@ def test_take_baton_waits_for_the_holder(daq):
|
||||
daq._responses["GET"] = MagicMock()
|
||||
daq._responses["GET"].ok, daq._responses["GET"].status_code = True, 200
|
||||
daq._responses["GET"].json.side_effect = lambda: next(checks)
|
||||
with patch("mx_bec.aaredaq.time.sleep") as sleep:
|
||||
with patch("mx_bec.external_services.aaredaq.time.sleep") as sleep:
|
||||
daq.take_baton(poll_interval_s=0.5)
|
||||
assert [url for url, _ in _calls(daq, "GET")] == [f"{URL}/baton/check_timeout"] * 2
|
||||
sleep.assert_called_with(0.5)
|
||||
@@ -227,14 +231,20 @@ def test_take_baton_waits_for_the_holder(daq):
|
||||
def test_take_baton_refused_by_holder(daq):
|
||||
_set_posts(daq, _response(json_data={"pending": True}))
|
||||
daq._responses["GET"] = _response(json_data={"refused": True})
|
||||
with patch("mx_bec.aaredaq.time.sleep"), pytest.raises(AareDaqError, match="refused"):
|
||||
with (
|
||||
patch("mx_bec.external_services.aaredaq.time.sleep"),
|
||||
pytest.raises(AareDaqError, match="refused"),
|
||||
):
|
||||
daq.take_baton()
|
||||
|
||||
|
||||
def test_take_baton_gives_up_after_wait(daq):
|
||||
_set_posts(daq, _response(json_data={"queued": True}))
|
||||
daq._responses["GET"] = _response(json_data={"queued": True})
|
||||
with patch("mx_bec.aaredaq.time.sleep"), pytest.raises(AareDaqError, match="not granted"):
|
||||
with (
|
||||
patch("mx_bec.external_services.aaredaq.time.sleep"),
|
||||
pytest.raises(AareDaqError, match="not granted"),
|
||||
):
|
||||
daq.take_baton(wait_s=0)
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
+12
-10
@@ -3,12 +3,12 @@ from unittest.mock import MagicMock, patch
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from mx_bec.jfjoch import JFJoch, JFJochError, RasterScan, RotationScan
|
||||
from mx_bec.external_services.jfjoch import JFJoch, JFJochError, RasterScan, RotationScan
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def api():
|
||||
with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client:
|
||||
with patch("mx_bec.external_services.jfjoch.jfjoch_client") as jfjoch_client:
|
||||
yield jfjoch_client.DefaultApi.return_value
|
||||
|
||||
|
||||
@@ -51,8 +51,10 @@ 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,
|
||||
patch("mx_bec.external_services.jfjoch.mx_beamline", return_value="X10SA") as beamline,
|
||||
patch(
|
||||
"mx_bec.external_services.jfjoch.get_jfjoch_url", return_value="http://gpu:8080"
|
||||
) as get_url,
|
||||
):
|
||||
assert jfjoch.url == "http://gpu:8080"
|
||||
assert jfjoch.url == "http://gpu:8080"
|
||||
@@ -99,7 +101,7 @@ def test_wait_till_done_returns_scan_result(jfjoch, api):
|
||||
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:
|
||||
with patch("mx_bec.external_services.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
|
||||
@@ -126,7 +128,7 @@ 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:
|
||||
with patch("mx_bec.external_services.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
|
||||
@@ -143,22 +145,22 @@ def test_measure_rotation_builds_rotation_dataset_settings(jfjoch):
|
||||
|
||||
|
||||
def test_single_column_raster_is_one_trigger(jfjoch):
|
||||
with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client:
|
||||
with patch("mx_bec.external_services.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:
|
||||
with patch("mx_bec.external_services.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,
|
||||
patch("mx_bec.external_services.jfjoch.jfjoch_client") as jfjoch_client,
|
||||
patch("mx_bec.external_services.jfjoch.DatasetSettingsSmargon") as smargon,
|
||||
):
|
||||
jfjoch.dataset_settings(_scan(smargon_phi_deg=None))
|
||||
smargon.assert_not_called()
|
||||
|
||||
Reference in new issue
Block a user