CI for mx_bec / e2e tests with pxi_bec (push) Failing after 1m4s
CI for mx_bec / e2e tests with pxii_bec (push) Failing after 1m17s
CI for mx_bec / e2e tests with pxiii_bec (push) Failing after 1m17s
CI for mx_bec / unit tests with pxiii_bec (push) Failing after 1m47s
CI for mx_bec / unit tests with pxii_bec (push) Failing after 1m55s
CI for mx_bec / unit tests with pxi_bec (push) Failing after 1m55s
# MX task architecture: AareBec service, tasks, queues and widgets Brings the AareBec task architecture into `mx_bec` ## Components - **AareBec service** (`service.py`, `main.py`): custom BEC client that owns the task queue, the actor manager and the external API clients. - **Task framework** (`tasks/core.py`): `@task` decorator and `TaskManager` with `Server` and `Client` roles. The server runs tasks one at a time and pauses the queue on failure; clients request tasks over Redis. `MxTaskQueue` works off the execution list. - **MX tasks** (`tasks/mx_tasks.py`): sample mount, optical centering, raster and multi-raster scans, X-ray centering, rotation data collection, beamline state change and cleanup. - **Automation actors** (`actors/`, `actor_manager.py`): actors that react to sequence milestones and queue the next task, each switchable through a Redis config value. - **External clients**: `AareDaq` REST client (Kerberos token, baton handling), `JFJoch` raster client, `OpticalPrediction` (AareLC). The `AareDaq` client is to be replaced with native BEC implementations. - **Devices** (`devices/`): Aerotech, Smargon (smargopolo), HTTP device base, simulated stages and sample changer, plus a demo config. - **Widgets** (`bec_widgets/widgets/aare_bec/`): actor config, task queue, task panel, sample queue and sample spreadsheet display - for development and admin use. - **Endpoints and messages** for task requests, the execution list, queue-change notifications and sequence state. ## Notes - BEC-driven optical centering was removed; it will be reimplemented from scratch. - The sample spreadsheet is copied between Redis instances by a hack in the service, to be replaced by the sample database connection module. - CI installs from the MX Gitea package index (`jfjoch_client` is pre-release only). --------- Co-authored-by: x10sa <x10sa@psi.ch> Reviewed-on: #2 Co-authored-by: David Perl <david.perl@psi.ch>
223 lines
7.6 KiB
Python
223 lines
7.6 KiB
Python
from types import SimpleNamespace
|
|
from unittest.mock import MagicMock
|
|
|
|
import pytest
|
|
import yaml
|
|
|
|
from mx_bec.configs import MX_SIMULATED_DEVICES, MX_SIMULATED_STATES, render_config
|
|
from mx_bec.device_planner import (
|
|
SIMULATED,
|
|
BeamlineState,
|
|
DefineStatesManager,
|
|
Environment,
|
|
GuardViolation,
|
|
PositionDevice,
|
|
StateChangePlanner,
|
|
TemperatureMode,
|
|
build_devices,
|
|
init_beamline_environment,
|
|
motor_resolver,
|
|
)
|
|
|
|
DEVICES = {
|
|
"bs_z": {"userParameter": {"safe": 50.0, "samp": 10.0}},
|
|
"cryo_pos": {"userParameter": {"in": 1.0, "out": 0.0, "move_method": "signal"}},
|
|
"aerotech": {"userParameter": {"tol": 0.01, "x": {"in": 0.0, "out": -20.0}}},
|
|
"not_positioned": {},
|
|
}
|
|
STATES = {
|
|
"states": {
|
|
"data_collection": {"allow_modifiers": True, "bs_z": "samp", "aerotech_x": "out"},
|
|
"maintenance": {"bs_z": "safe", "aerotech_x": "in"},
|
|
}
|
|
}
|
|
# aerotech_x has to be out before the beamstop moves to the sample
|
|
DEPS = {("bs_z", "samp"): [("aerotech_x", "out")]}
|
|
|
|
|
|
class FakeMotor:
|
|
def __init__(self, name: str, value: float = 0.0, user_parameter: dict | None = None):
|
|
self.name = name
|
|
self.value = value
|
|
self.user_parameter = user_parameter or {}
|
|
|
|
def read(self):
|
|
return {self.name: {"value": self.value}}
|
|
|
|
def put(self, value):
|
|
self.value = value
|
|
|
|
|
|
class FakeDevices(SimpleNamespace):
|
|
def __getitem__(self, name):
|
|
return getattr(self, name)
|
|
|
|
|
|
@pytest.fixture
|
|
def moves():
|
|
return []
|
|
|
|
|
|
@pytest.fixture
|
|
def scans(moves):
|
|
def mv(motor, position, relative=False):
|
|
assert relative is False
|
|
moves.append((motor.name, position))
|
|
motor.value = position
|
|
return MagicMock()
|
|
|
|
return SimpleNamespace(mv=mv)
|
|
|
|
|
|
@pytest.fixture
|
|
def dev():
|
|
return FakeDevices(
|
|
bs_z=FakeMotor("bs_z", 50.0, DEVICES["bs_z"]["userParameter"]),
|
|
cryo_pos=FakeMotor("cryo_pos", 0.0, DEVICES["cryo_pos"]["userParameter"]),
|
|
aerotech=SimpleNamespace(x=FakeMotor("aerotech_x", 0.0)),
|
|
bcu_shutter=FakeMotor("bcu_shutter", 1.0),
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
def planner(tmp_path, dev, scans):
|
|
devices_file, states_file = tmp_path / "devices.yaml", tmp_path / "states.yaml"
|
|
devices_file.write_text(yaml.safe_dump(DEVICES))
|
|
states_file.write_text(yaml.safe_dump(STATES))
|
|
devices = build_devices(devices_file, dev, scans)
|
|
states, allow_modifiers = DefineStatesManager.initialize_states(states_file)
|
|
return StateChangePlanner(dev, devices, states, allow_modifiers, DEPS)
|
|
|
|
|
|
def test_motor_resolver_finds_devices_and_components(dev):
|
|
assert motor_resolver(dev, "bs_z") is dev.bs_z
|
|
assert motor_resolver(dev, "aerotech_x") is dev.aerotech.x
|
|
with pytest.raises(ValueError):
|
|
motor_resolver(dev, "no_such_motor")
|
|
|
|
|
|
def test_devices_and_states_are_built_from_the_yaml_files(planner):
|
|
assert set(planner.devices) == {"bs_z", "cryo_pos", "aerotech_x"}
|
|
assert planner.available_states() == [BeamlineState.DATA_COLLECTION, BeamlineState.MAINTENANCE]
|
|
assert planner.state_devices() == ["aerotech_x", "bs_z"]
|
|
assert planner.get_positions() == {"aerotech_x": "in", "bs_z": "safe"}
|
|
assert planner.is_state(BeamlineState.MAINTENANCE)
|
|
assert not planner.is_state(BeamlineState.DATA_COLLECTION)
|
|
|
|
|
|
def test_move_to_closes_the_shutter_and_moves_in_dependency_order(planner, dev, moves):
|
|
planner.move_to("data_collection")
|
|
assert dev.bcu_shutter.value == 0
|
|
assert moves == [("aerotech_x", -20.0), ("bs_z", 10.0)]
|
|
assert planner.is_state(BeamlineState.DATA_COLLECTION)
|
|
|
|
moves.clear()
|
|
planner.move_to(BeamlineState.DATA_COLLECTION) # already there: nothing moves
|
|
assert moves == []
|
|
|
|
|
|
def test_modifier_is_applied_where_the_state_allows_it(planner, dev, moves):
|
|
planner.move_to(BeamlineState.DATA_COLLECTION, TemperatureMode.CRYO)
|
|
assert dev.cryo_pos.value == 1.0 # moved by put(), as its move_method is "signal"
|
|
assert ("cryo_pos", 1.0) not in moves
|
|
assert planner.is_state(BeamlineState.DATA_COLLECTION, TemperatureMode.CRYO)
|
|
|
|
planner.move_to(BeamlineState.MAINTENANCE, "room_temp") # no modifiers allowed there
|
|
assert dev.cryo_pos.value == 1.0
|
|
|
|
|
|
def test_unknown_state_is_rejected_before_anything_moves(planner, moves):
|
|
with pytest.raises(ValueError):
|
|
planner.move_to("no_such_state")
|
|
assert moves == []
|
|
|
|
|
|
def test_circular_dependencies_are_detected(planner):
|
|
planner.deps = {
|
|
("bs_z", "samp"): [("aerotech_x", "out")],
|
|
("aerotech_x", "out"): [("bs_z", "samp")],
|
|
}
|
|
with pytest.raises(RuntimeError, match="Circular"):
|
|
planner.move_to(BeamlineState.DATA_COLLECTION)
|
|
|
|
|
|
def test_guards_and_policies_stop_a_move(dev, scans, moves):
|
|
device = PositionDevice("bs_z", dev.bs_z, {"safe": 50.0, "samp": 10.0}, dev=dev, scans=scans)
|
|
|
|
def guard():
|
|
raise GuardViolation("not now")
|
|
|
|
device.guards.append(guard)
|
|
with pytest.raises(GuardViolation):
|
|
device.move("samp")
|
|
device.guards.clear()
|
|
|
|
def policy(target):
|
|
if target < 20:
|
|
raise GuardViolation("too close")
|
|
|
|
device.policy = policy
|
|
with pytest.raises(GuardViolation):
|
|
device.move("samp")
|
|
assert moves == []
|
|
with pytest.raises(ValueError):
|
|
device.move(30.0) # only named positions unless allow_arbitrary
|
|
|
|
|
|
# ---- the simulated beamline for development (BEAMLINE=SIMULATED) ----
|
|
|
|
|
|
def test_simulated_environment_uses_the_configs_of_mx_bec():
|
|
env = Environment(SIMULATED)
|
|
assert env.simulated and env.deployment == "simulated"
|
|
assert env.devices_file == MX_SIMULATED_DEVICES
|
|
assert env.states_file == MX_SIMULATED_STATES
|
|
assert env.daily_setup_dir.is_dir()
|
|
|
|
|
|
def test_unknown_beamline_is_rejected():
|
|
with pytest.raises(ValueError, match="Unknown beamline"):
|
|
Environment("simulated") # has to be set explicitly, in capitals
|
|
|
|
|
|
@pytest.fixture
|
|
def simulated_dev():
|
|
"""Fake BEC devices for everything in the simulated device config, at the values the
|
|
simulated devices start with (0 for the positioners)."""
|
|
config = yaml.safe_load(MX_SIMULATED_DEVICES.read_text())
|
|
dev = FakeDevices()
|
|
for name, cfg in config.items():
|
|
user = cfg.get("userParameter") or {}
|
|
if name in ("aerotech", "smargon"):
|
|
axes = {axis: FakeMotor(f"{name}_{axis}") for axis in user if axis != "tol"}
|
|
setattr(dev, name, SimpleNamespace(user_parameter=user, **axes))
|
|
else:
|
|
value = (cfg.get("deviceConfig") or {}).get("value", 0.0)
|
|
setattr(dev, name, FakeMotor(name, value, user))
|
|
return dev
|
|
|
|
|
|
def test_simulated_devices_are_valid_for_the_device_server():
|
|
from ophyd_devices.utils.static_device_test import StaticDeviceTest
|
|
|
|
results = StaticDeviceTest(
|
|
config_file=str(render_config(MX_SIMULATED_DEVICES))
|
|
).run_with_list_output(connect=True, timeout_per_device=10)
|
|
failed = {r.name: r.message for r in results if not r.success}
|
|
assert not failed, failed
|
|
|
|
|
|
def test_every_simulated_state_can_be_reached(monkeypatch, simulated_dev, scans):
|
|
"""From the initial positions of the simulated devices, go through every state and back:
|
|
the positions, dependencies, guards and policies have to be consistent with each other."""
|
|
monkeypatch.setenv("BEAMLINE", SIMULATED)
|
|
env, devices, planner = init_beamline_environment(simulated_dev, scans)
|
|
assert env.simulated
|
|
assert set(planner.state_devices()) <= set(devices)
|
|
states = planner.available_states()
|
|
assert set(states) == set(BeamlineState)
|
|
for state in [*states, *reversed(states)]:
|
|
for modifier in (None, TemperatureMode.CRYO, TemperatureMode.ROOM_TEMP):
|
|
planner.move_to(state, modifier)
|
|
assert planner.is_state(state), (state, modifier, planner.get_positions())
|