From bfc56b81b990a175b4ee8b85d1f42da6e6854123 Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 24 Nov 2026 13:16:58 +0100 Subject: [PATCH] feat: add samcam conversion --- .gitea/workflows/ci.yml | 4 +- mx_bec/actors/mx_automation.py | 1 - mx_bec/calc.py | 6 + mx_bec/decisions/__init__.py | 3 +- mx_bec/decisions/grid_scans.py | 11 +- mx_bec/device_planner/__init__.py | 45 +++++ mx_bec/device_planner/build.py | 125 +++++++++++++ mx_bec/device_planner/environment.py | 116 ++++++++++++ mx_bec/device_planner/guards.py | 93 ++++++++++ mx_bec/device_planner/planner.py | 226 +++++++++++++++++++++++ mx_bec/device_planner/policies.py | 78 ++++++++ mx_bec/device_planner/position_device.py | 134 ++++++++++++++ mx_bec/optical_centering.py | 14 +- mx_bec/sample_info.py | 4 + pyproject.toml | 4 +- tests/unit/test_device_planner.py | 160 ++++++++++++++++ 16 files changed, 1009 insertions(+), 15 deletions(-) create mode 100644 mx_bec/calc.py create mode 100644 mx_bec/device_planner/__init__.py create mode 100644 mx_bec/device_planner/build.py create mode 100644 mx_bec/device_planner/environment.py create mode 100644 mx_bec/device_planner/guards.py create mode 100644 mx_bec/device_planner/planner.py create mode 100644 mx_bec/device_planner/policies.py create mode 100644 mx_bec/device_planner/position_device.py create mode 100644 tests/unit/test_device_planner.py diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 27ffb58..64e75bb 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -94,9 +94,9 @@ jobs: uv pip install --system -e ./bec/bec_lib[dev] uv pip install --system -e ./bec/bec_ipython_client uv pip install --system -e ./bec/bec_server[dev] - uv pip install --system -e ./bec_widgets[dev,pyside6] + uv pip install --system -e ./bec_widgets[dev] # MX-internal dependencies (aarecommon, aare_config, jfjoch_client, ...) come from gitea - uv pip install --system --extra-index-url https://gitea.psi.ch/api/packages/mx/pypi/simple/ -e ./mx_bec + uv pip install --system --extra-index-url https://gitea.psi.ch/api/packages/mx/pypi/simple/ -e ./mx_bec[dev] - name: Run Pytest with Coverage id: coverage diff --git a/mx_bec/actors/mx_automation.py b/mx_bec/actors/mx_automation.py index 490d3b2..de04cda 100644 --- a/mx_bec/actors/mx_automation.py +++ b/mx_bec/actors/mx_automation.py @@ -11,7 +11,6 @@ from time import sleep from aarelcinfer_client.models import DetectionModel from bec_lib.endpoints import EndpointInfo from bec_lib.logger import bec_logger -from pxii_bec.macros.calculator import calc_scam_microns from mx_bec.actors.core import MXAutomationActor from mx_bec.decisions import ( diff --git a/mx_bec/calc.py b/mx_bec/calc.py new file mode 100644 index 0000000..a223586 --- /dev/null +++ b/mx_bec/calc.py @@ -0,0 +1,6 @@ +import numpy as np + + +def samcam_pixels_to_microns(pixels: int, zoom: float, multiplier: float, exponent: float): + """Convert pixels to microns for the sample camera""" + return float(pixels / (multiplier * np.exp(exponent * zoom))) diff --git a/mx_bec/decisions/__init__.py b/mx_bec/decisions/__init__.py index f989983..bcbbd36 100644 --- a/mx_bec/decisions/__init__.py +++ b/mx_bec/decisions/__init__.py @@ -3,8 +3,7 @@ grid scan -> analyse_grid -> plan_rotation -> collect_dataset -> assess_collection -> decide_followup -> (re-raster | new position | chi sweep | finish) -Everything here is pure: pydantic models and functions, no BEC, Redis or device access (only -``gridscan_calculation`` uses a pxii calibration macro, imported when it is called). The +Everything here is pure: pydantic models and functions, no BEC, Redis or device access. The actors in ``mx_bec.actors.mx_automation`` call these functions, and the same functions can be replayed offline against archived Jungfraujoch results to tune thresholds. diff --git a/mx_bec/decisions/grid_scans.py b/mx_bec/decisions/grid_scans.py index 0b2be1c..5fe2386 100644 --- a/mx_bec/decisions/grid_scans.py +++ b/mx_bec/decisions/grid_scans.py @@ -54,6 +54,7 @@ def gridscan_strategy_from_optical( exp_time_s: float, dtz_mm: float, ): + """Work out the grid to scan from the loop detected by the optical centering.""" if optical_results is None or len(boxes := optical_results.prediction.boxes) == 0: return mock_grid_calculation() box_data = {box.label: ((box.x1, box.y1), (box.x2, box.y2)) for box in boxes} @@ -77,6 +78,7 @@ def gridscan_strategy_from_optical( file_prefix, exp_time_s, dtz_mm, + optical_results.microns_per_pixel, ) @@ -89,17 +91,14 @@ def gridscan_calculation( file_prefix: str, exp_time_s: float, dtz_mm: float, + microns_per_pixel: float, ): """calculate a gridscan from box coordinates and params. needs omega added later.""" - # pyright: ignore[reportMissingImports] - from pxii_bec.macros.calculator import calc_scam_microns - # TODO: migrate utils from plugins to mx_bec - box_x_pixels = abs(x1_y1[0] - x2_y2[0]) box_y_pixels = abs(x1_y1[1] - x2_y2[1]) logger.info(f"{box_x_pixels=}, {box_y_pixels=}") - box_x_microns = calc_scam_microns(box_x_pixels, zoom=400) - box_y_microns = calc_scam_microns(box_y_pixels, zoom=400) + box_x_microns = box_x_pixels * microns_per_pixel + box_y_microns = box_y_pixels * microns_per_pixel logger.info(f"{box_x_microns=}, {box_y_microns=}") logger.info(f"adding margin to detection boxes of {margin}x") n_x = int(box_x_microns / 1000 / size_x_mm * margin) diff --git a/mx_bec/device_planner/__init__.py b/mx_bec/device_planner/__init__.py new file mode 100644 index 0000000..d53bc16 --- /dev/null +++ b/mx_bec/device_planner/__init__.py @@ -0,0 +1,45 @@ +"""Planner to move the beamline devices between beamline states. + +Copied from the pxii_bec macros (`macros/beamline_planner.py` and what it is built from: +`position_device`, `build_devices`, `devices_manager`, `beamline_state_manager`, `dependencies`, +`guards`, `policies`, and `scripts/init_beamline.py`). The macros rely on `dev` and `scans` being +globals of the BEC IPython client; here they are passed in, so that this also works in a service. +""" + +from mx_bec.device_planner.build import ( + DefineStatesManager, + DeviceManager, + build_devices, + planner_deps, +) +from mx_bec.device_planner.environment import Environment, init_beamline_environment +from mx_bec.device_planner.guards import ( + AtPositionGuard, + GuardViolation, + MinMaxGuard, + attach_guards, + guards_setup, +) +from mx_bec.device_planner.planner import BeamlineState, StateChangePlanner, TemperatureMode +from mx_bec.device_planner.policies import attach_policies +from mx_bec.device_planner.position_device import PositionDevice, motor_resolver + +__all__ = [ + "AtPositionGuard", + "BeamlineState", + "DefineStatesManager", + "DeviceManager", + "Environment", + "GuardViolation", + "MinMaxGuard", + "PositionDevice", + "StateChangePlanner", + "TemperatureMode", + "attach_guards", + "attach_policies", + "build_devices", + "guards_setup", + "init_beamline_environment", + "motor_resolver", + "planner_deps", +] diff --git a/mx_bec/device_planner/build.py b/mx_bec/device_planner/build.py new file mode 100644 index 0000000..d7deda6 --- /dev/null +++ b/mx_bec/device_planner/build.py @@ -0,0 +1,125 @@ +"""Build what the planner works with: the position devices with their guards and policies, the +beamline states and the dependencies between positions.""" + +import yaml + +from mx_bec.device_planner.guards import attach_guards +from mx_bec.device_planner.planner import BeamlineState +from mx_bec.device_planner.policies import attach_policies +from mx_bec.device_planner.position_device import PositionDevice, motor_resolver + + +def build_devices(yaml_file, dev, scans): + """Build the position devices from the device config yaml, for the BEC devices `dev`, moved + with the BEC scans `scans`.""" + + state_devices = {} + + with open(yaml_file, encoding="utf-8") as f: + data = yaml.safe_load(f) + + for bec_name, cfg in data.items(): + user = cfg.get("userParameter") + + # Skip devices without user parameters + if not user: + continue + + if bec_name in ("aerotech", "smargon"): + tol = user.get("tol", 0.01) + + for axis in ["x", "y", "z", "u", "chi", "phi"]: + positions = user.get(axis) + + if positions is None: + continue + + component_name = f"{bec_name}_{axis}" + + pos_dev = PositionDevice( + bec_name=component_name, + mot_device=motor_resolver(dev, component_name), + dev=dev, + scans=scans, + positions=positions, + tol=tol, + allow_arbitrary=True, + ) + + state_devices[component_name] = pos_dev + + else: + tol = user.get("tol", 0.1) + allow_arbitrary = user.get("type") == "continuous" + move_method = user.get("move_method", "motor") + + positions = {k: v for k, v in user.items() if k not in ("type", "tol", "move_method")} + + pos_dev = PositionDevice( + bec_name=bec_name, + mot_device=motor_resolver(dev, bec_name), + dev=dev, + scans=scans, + positions=positions, + tol=tol, + allow_arbitrary=allow_arbitrary, + move_method=move_method, + ) + + state_devices[bec_name] = pos_dev + + return state_devices + + +class DeviceManager: + """Class for building devices and attaching safety guards and policies.""" + + @staticmethod + def initialize_devices(devices_file, dev, scans): + """ + Initializes sample environment devices from the specified file. + """ + devices = build_devices(devices_file, dev, scans) + attach_guards(devices) + attach_policies(devices) + return devices + + +class DefineStatesManager: + """Reads the beamline states from their yaml file.""" + + @staticmethod + def initialize_states(states_file): + """ + Returns the states and modifiers defined in the specified states file. + """ + with open(states_file, "r", encoding="utf-8") as f: + cfg = yaml.safe_load(f) + states = {} + allow_modifiers = {} + + for name, config in cfg["states"].items(): + state = BeamlineState(name) + allow_modifiers[state] = config.pop("allow_modifiers", False) + states[state] = config + + return states, allow_modifiers + + +def planner_deps(): + """Define the dependencies between beamline positions""" + return { + ("bs_z", "samp"): [("aerotech_x", "out"), ("diag_y", "out"), ("coll_y", "out")], + ("aerotech_x", "in"): [("diag_y", "out"), ("bs_z", "safe")], + ("aerotech_x", "out"): [("diag_y", "out"), ("bs_z", "safe")], + ("diag_y", "scint"): [("aerotech_x", "out"), ("bs_z", "safe"), ("cryo_pos", "out")], + ("diag_y", "i1"): [("aerotech_x", "out"), ("bs_z", "safe"), ("cryo_pos", "out")], + ("bs_pos", "out"): [("bs_z", "safe")], + ("bs_pos", "in"): [("bs_z", "safe")], + ("diag_y", "out"): [("bs_z", "safe")], + ("diag_y", "park"): [("bs_z", "safe")], + ("coll_y", "out"): [("bs_z", "safe")], + ("coll_y", "park"): [("bs_z", "safe")], + ("coll_y", "in"): [("bs_z", "safe")], + ("coll_y", "intermediate"): [("bs_z", "safe")], + } diff --git a/mx_bec/device_planner/environment.py b/mx_bec/device_planner/environment.py new file mode 100644 index 0000000..210bfac --- /dev/null +++ b/mx_bec/device_planner/environment.py @@ -0,0 +1,116 @@ +"""Initialise sample environment devices and beamline states.""" + +import importlib +import os +from dataclasses import dataclass +from pathlib import Path + +from mx_bec.device_planner.build import DefineStatesManager, DeviceManager, planner_deps +from mx_bec.device_planner.planner import StateChangePlanner + + +@dataclass +class Environment: + """Define configuration files for a beamline and BEC deployment.""" + + beamline: str + + beamline_configs = { + "x06sa": { + "name": "PXI", + "package": "pxi_bec", + "devices": "pxi-devices.yaml", + "states": "pxi-beamline-states.yaml", + }, + "x10sa": { + "name": "PXII", + "package": "pxii_bec", + "devices": "pxii-devices.yaml", + "states": "pxii-beamline-states.yaml", + }, + "x06da": { + "name": "PXIII", + "package": "pxiii_bec", + "devices": "pxiii-devices.yaml", + "states": "pxiii-beamline-states.yaml", + }, + } + + valid_deployments = ("test", "production") + + def __post_init__(self): + + if self.beamline not in self.beamline_configs: + raise ValueError( + f"Unknown beamline '{self.beamline}'. Choose from {list(self.beamline_configs)}" + ) + + cfg = self.beamline_configs[self.beamline] + self.beamline_name = cfg["name"] + + # Import whichever deployment BEC has already made available + package = importlib.import_module(cfg["package"]) + + self.bec_dir = Path(package.__file__).resolve().parent + + self.device_config_dir = self.bec_dir / "device_configs" + self.lut_dir = self.bec_dir / "macros" / "luts" + + # Runtime files generated by daily setup + self.daily_setup_dir = self.bec_dir / "daily_setup_files" + self.daily_setup_dir.mkdir(exist_ok=True) + + self.devices_file = self.device_config_dir / cfg["devices"] + self.states_file = self.device_config_dir / cfg["states"] + + # Determine which deployment is being used + self.deployment = self._get_deployment() + + if not self.devices_file.exists(): + raise FileNotFoundError(f"Device configuration not found: {self.devices_file}") + + if not self.states_file.exists(): + raise FileNotFoundError(f"State configuration not found: {self.states_file}") + + def _get_deployment(self): + """Determine deployment from the loaded package path.""" + + for deployment in ("test", "production"): + if deployment in self.bec_dir.parts: + return deployment + + raise RuntimeError(f"Could not determine BEC deployment from {self.bec_dir}") + + +def init_beamline_environment(dev, scans): + """ + Initialise beamline positioned devices and state planner, for the BEC devices `dev` (e.g. + `client.device_manager.devices`) and the BEC scans `scans` (e.g. `client.scans`). + """ + + beamline = os.environ["BEAMLINE"] + + env = Environment(beamline=beamline) + + print("=" * 60) + print(f"Beamline : {beamline}") + print(f"BEC deployment : {env.deployment.upper()}") + print(f"Devices file : {env.devices_file}") + print(f"States file : {env.states_file}") + print("=" * 60) + + # Initialise positioned devices + device_manager = DeviceManager() + devices = device_manager.initialize_devices(env.devices_file, dev, scans) + + # Initialise beamline states + state_manager = DefineStatesManager() + states, allow_modifiers = state_manager.initialize_states(env.states_file) + + # Set up dependencies + deps = planner_deps() + + # Set up planner + planner = StateChangePlanner(dev, devices, states, allow_modifiers, deps) + + return env, devices, planner diff --git a/mx_bec/device_planner/guards.py b/mx_bec/device_planner/guards.py new file mode 100644 index 0000000..1306af9 --- /dev/null +++ b/mx_bec/device_planner/guards.py @@ -0,0 +1,93 @@ +"""Setup guards for devices.""" + + +class GuardViolation(Exception): + """Raised when a guarded move is not allowed.""" + + +class AtPositionGuard: + """Guard that checks if a device is in a specific position.""" + + def __init__(self, device, position): + self.device = device + self.pos = position + + def check(self): + """Check if the device is in the specified position.""" + if self.device.pos != self.pos: + raise GuardViolation(f"{self.device.bec_name} must be in the '{self.pos}' position") + # print("move allowed") + return True + + def requirement(self): + """Return the requirement for the guard.""" + return (self.device.bec_name, self.pos) + + +class MinMaxGuard: + """Guard that checks if a device is within a specific range.""" + + def __init__(self, device, limit_value, direction): + self.device = device + self.limit_value = limit_value + self.direction = direction # direction: 'max' or 'min' + + def check(self): + """Check if the device is within the specified range.""" + if self.direction == "less_than": + if not (self.device.actual - self.device.tol) <= self.limit_value: + raise GuardViolation( + f"{self.device.bec_name} must be less than or equal to {self.limit_value} mm" + ) + elif self.direction == "more_than": + if not (self.device.actual + self.device.tol) >= self.limit_value: + raise GuardViolation( + f"{self.device.bec_name} must be greater than or equal to {self.limit_value} mm" + ) + else: + raise ValueError( + f"Invalid direction '{self.direction}'. Use 'less_than' or 'more_than'." + ) + + # print("move allowed") + return True + + def requirement(self): + """Return the requirement for the guard.""" + # planner cannot handle numeric constraints directly + # return None -> planner ignores + return None + + +def guards_setup(d): + """Define guards for devices.""" + guards = {} + guards["bs_safe"] = AtPositionGuard(d["bs_z"], position="safe") + guards["bs_max_blin"] = MinMaxGuard( + d["bs_z"], direction="less_than", limit_value=d["bs_z"].positions["max_blin"] + ) + guards["bs_work_min"] = MinMaxGuard( + d["bs_z"], direction="more_than", limit_value=d["bs_z"].positions["work_min"] + ) + guards["bs_pos_in"] = AtPositionGuard(d["bs_pos"], position="in") + guards["gonx_out"] = MinMaxGuard( + d["aerotech_x"], direction="less_than", limit_value=d["aerotech_x"].positions["out"] + ) + guards["gonx_safe"] = AtPositionGuard(d["aerotech_x"], position="safe") + guards["diag_y_out"] = MinMaxGuard( + d["diag_y"], direction="less_than", limit_value=d["diag_y"].positions["out"] + ) + guards["coll_y_out"] = MinMaxGuard( + d["coll_y"], direction="less_than", limit_value=d["coll_y"].positions["out"] + ) + return guards + + +def attach_guards(d): + """Attach guards to devices.""" + g = guards_setup(d) + d["diag_y"].guards.append(g["bs_work_min"].check) + d["bl_pos"].guards.append(g["bs_max_blin"].check) + d["bs_pos"].guards.append(g["bs_safe"].check) + d["bs_z"].guards.append(g["bs_pos_in"].check) + d["coll_y"].guards.append(g["bs_work_min"].check) diff --git a/mx_bec/device_planner/planner.py b/mx_bec/device_planner/planner.py new file mode 100644 index 0000000..b6e4609 --- /dev/null +++ b/mx_bec/device_planner/planner.py @@ -0,0 +1,226 @@ +"""Planner to move between beamline states""" + +from collections import defaultdict, deque +from enum import Enum + + +class BeamlineState(str, Enum): + """List of beamline states""" + + ROBOT_SAMPLE_EXCHANGE = "robot_sample_exchange" + SAMPLE_ALIGNMENT = "sample_alignment" + DATA_COLLECTION = "data_collection" + DC_XRF = "DC_XRF" + MANUAL_SAMPLE_EXCHANGE = "manual_sample_exchange" + BEAM_VISUALISATION = "beam_visualisation" + FLUX_MEASUREMENT = "flux_measurement" + BEAMSTOP_ALIGNMENT = "beamstop_alignment" + MAINTENANCE = "maintenance" + XTAL_SNAPSHOT = "xtal_snapshot" + DET_DIODE = "det_diode" + + +class TemperatureMode(str, Enum): + """List of temperature modes""" + + CRYO = "cryo" + ROOM_TEMP = "room_temp" + + +class StateChangePlanner: + """Moves devices to the correct positions to achieve a given state""" + + def __init__( + self, + dev, + devices, + states: dict[BeamlineState, dict[str, str]], + allow_modifiers=None, + deps=None, + debug=False, + ): + self.dev = dev # the BEC devices, e.g. `client.device_manager.devices` + self.devices = devices # the position devices, by name + self.states = states + self.allow_modifiers = allow_modifiers or {} + self.deps = deps + self.debug = debug + + self.modifiers = { + TemperatureMode.CRYO: {"cryo_pos": "in"}, + TemperatureMode.ROOM_TEMP: {"cryo_pos": "out"}, + } + + def _merged_state(self, state, modifier): + target = dict(self.states[state]) + + if modifier: + if isinstance(modifier, str): + modifier = TemperatureMode(modifier) + + if self.allow_modifiers.get(state, False): + target.update(self.modifiers[modifier]) + return target + + def move_to(self, state_name, modifier=None): + """Move devices to the correct positions to achieve a given state""" + + # Close the fast shutter before moving anything + self.dev.bcu_shutter.put(0) + + if isinstance(state_name, str): + state_name = BeamlineState(state_name) + target = self._merged_state(state_name, modifier) + + plan = self._plan(target) + + print("PLAN:") + for i, stage in enumerate(plan): + print(f"Stage {i + 1}: {stage}") + + for stage in plan: + for pd_devs, pos in stage: + d = self.devices[pd_devs] + if not d.is_at(pos): + + if self.debug: + print(f"→ Moving {pd_devs} -> {pos}") + # print(" Before:", self.get_states()) + + try: + d.move(pos) + + except Exception as e: + print(f"Exception occurred: {e}") + print(f"\nFAILED MOVE: {pd_devs} -> {pos}") + print("States at failure:", self.get_positions()) + raise + + def available_states(self): + """Return a list of available states""" + return list(self.states.keys()) + + def state_devices(self): + """Return the set of devices that participate in + beamline state definitions""" + + devices = set() + + for state in self.states.values(): + devices.update(state.keys()) + + return sorted(devices) + + def get_positions(self): + """Return current positions of devices that are used + in state transitions""" + return {name: self.devices[name].pos for name in self.state_devices()} + + def print_positions(self): + """Return current state of all devices""" + for name in self.state_devices(): + device = self.devices[name] + + print(f"{name:10s} : {device.pos:10s} value: {device.actual:.5g}") + + def diff_states(self, before): + """Return a dict of {device: (before, after)} pairs for devices that changed state""" + after = self.get_positions() + return {k: (before[k], after[k]) for k in before if before[k] != after[k]} + + def __get_closest_states(self): + """ + Return states ordered by number of mismatches. + """ + + results = [] + + for state in self.states: + + config = self._merged_state(state, None) + + mismatches = [] + + for dev, expected in config.items(): + + if not self.devices[dev].is_at(expected): + mismatches.append((dev, self.devices[dev].pos, expected)) + + results.append((state.name, len(mismatches), mismatches)) + + return sorted(results, key=lambda x: x[1]) + + def closest_states(self, n=5): + + for state, count, mismatches in self.__get_closest_states()[:n]: + + print(f"\n{state}: {count} mismatch(es)") + + for dev, actual, expected in mismatches: + print(f" {dev:15s} " f"{actual:10s} -> {expected}") + + def current_state(self): + """Return all current matching BeamlineState and TemperatureMode combinations, + prioritizing non-None modifiers first.""" + matches = [] # Store all matching (state, modifier) pairs + ignore_keys = {"bl_bright", "fl_bright"} + + for state in self.states: + # Start with prioritized modifiers: Non-None first, then None. + modifiers = list(self.modifiers.keys()) + modifiers.append(None) # Add `None` as a fallback after real modifiers. + + for modifier in modifiers: + # Combine state and modifier to get full configuration + config = self._merged_state(state, modifier) + + # Check if all devices match their expected positions + if all(self.devices[d].is_at(p) for d, p in config.items() if d not in ignore_keys): + matches.append((state.name, modifier.name if modifier else "None")) + + return matches if matches else None + + def is_state(self, state, modifier=None): + """Check if the current state matches the given state and modifier.""" + actual = self.current_state() + if not actual: + return False + + if modifier is None: + # match any modifier + return any(s == state.name for s, _ in actual) + + return (state.name, modifier.name) in actual + + def _plan(self, target): + + graph = defaultdict(set) + indeg = defaultdict(int) + nodes = set() + + for dev, pos in target.items(): + node = (dev, pos) + nodes.add(node) + + for dep in self.deps.get(node, []): + graph[dep].add(node) + indeg[node] += 1 + nodes.add(dep) + + q = deque(n for n in nodes if indeg[n] == 0) + stages = [] + + while q: + stage = list(q) + stages.append(stage) + q.clear() + + for n in stage: + for m in graph[n]: + indeg[m] -= 1 + if indeg[m] == 0: + q.append(m) + + if sum(len(s) for s in stages) != len(nodes): + raise RuntimeError("Circular dependency in state dependencies") + return stages diff --git a/mx_bec/device_planner/policies.py b/mx_bec/device_planner/policies.py new file mode 100644 index 0000000..580b7b0 --- /dev/null +++ b/mx_bec/device_planner/policies.py @@ -0,0 +1,78 @@ +"""Define guard policies for devices in the beamline.""" + +from mx_bec.device_planner.guards import GuardViolation, guards_setup + + +def is_sample_area_clear_for_beamstop(d): + """Check if the sample area is clear of diag_y, coll_y, and gonx""" + g = guards_setup(d) + if g["diag_y_out"].check() and g["coll_y_out"].check() and g["gonx_out"].check(): + return True + return False + + +def is_sample_area_clear_for_gonx(d): + """Check if the sample area is clear of diag_y and bs_z""" + g = guards_setup(d) + if g["diag_y_out"].check() and g["bs_work_min"].check(): + return True + return False + + +def make_aerotech_x_policy(d): + """Create the policy for aerotech_x""" + + def aerotech_x_policy(target): + cfg = d["aerotech_x"].positions + if target >= cfg["out"] and not is_sample_area_clear_for_gonx(d): + raise GuardViolation("Sample area is not clear") + + return aerotech_x_policy + + +def make_bs_z_policy(d): + """Create the policy for bs_z""" + + def bs_z_policy(target): + """Checks that the target position is within limits""" + cfg = d["bs_z"].positions + # Lower bound + if target < cfg["work_min"] and not is_sample_area_clear_for_beamstop(d): + raise GuardViolation("Sample area is not clear") + if target < cfg["min"]: + raise GuardViolation( + f"Requested beamstop Z {target} is below recommended minimum {cfg['min']}" + ) + # Upper bound + if d["bl_pos"].pos == "in" and target > cfg["max_blin"]: + raise GuardViolation( + f"Beamstop Z cannot move beyond {cfg['max_blin']} when backlight is IN" + ) + + return bs_z_policy + + +def make_diag_y_policy(d): + """Create the policy for diag_y""" + + def diag_y_policy(target): + cfg = d["diag_y"].positions + # Don't move in if the goniometer is in + if d["aerotech_x"].actual >= d["aerotech_x"].positions["in"] and target > cfg["out"]: + raise GuardViolation( + f"Diagnostic device cannot move beyond {cfg['out']} mm when goniometer is not OUT" + ) + # Don't move if cryocooler is in + if d["cryo_pos"].pos == "in" and target > cfg["out"]: + raise GuardViolation( + f"Diagnostic device cannot move beyond {cfg['out']} mm when cryocooler is IN" + ) + + return diag_y_policy + + +def attach_policies(d): + """Attach the policies to the devices""" + d["bs_z"].policy = make_bs_z_policy(d) + d["aerotech_x"].policy = make_aerotech_x_policy(d) + d["diag_y"].policy = make_diag_y_policy(d) diff --git a/mx_bec/device_planner/position_device.py b/mx_bec/device_planner/position_device.py new file mode 100644 index 0000000..48c8cde --- /dev/null +++ b/mx_bec/device_planner/position_device.py @@ -0,0 +1,134 @@ +"""Set up the positioned devices for mock or real motors""" + +from dataclasses import dataclass, field +from typing import Any, Callable, Union + +from bec_lib.device import Device +from bec_lib.logger import bec_logger + + +def motor_resolver(dev, bec_name): + """Used to handle aerotech and smargon motors: find the motor called `bec_name`, or the + component it names (e.g. "aerotech_x" -> aerotech.x), in the BEC devices `dev`.""" + + candidates = [bec_name, bec_name.replace("_", ".")] + + for path in candidates: + try: + obj = dev + + for part in path.split("."): + obj = getattr(obj, part) + + return obj + + except Exception: # noqa: BLE001, S110 + pass + + raise ValueError(f"Cannot resolve motor for '{bec_name}'") + + +@dataclass +class PositionDevice: + """Generic device that moves between named or numeric positions""" + + bec_name: str + mot_device: Any = None + positions: dict[str, float] = field(default_factory=dict) + tol: float = 0.1 + # device_timeout = 3 + guards: list[Callable[[], None]] = field(default_factory=list) + policy: Callable[[float], None] | None = None + allow_arbitrary: bool = False + move_method: str = "motor" + dev: Any = None # the BEC devices, e.g. `client.device_manager.devices` + scans: Any = None # the BEC scans, e.g. `client.scans` + + def __post_init__(self): + # Normalize position names + self.positions = {k.lower(): v for k, v in self.positions.items()} + + def _check_guards(self): + """Check if guards exist""" + for g in self.guards: + g() + + def _resolve_target(self, target: str | float) -> float: + """Convert target into a motor position""" + + if isinstance(target, str): + name = target.lower() + try: + bec_logger.logger.info( + f"attempting to find position {name} from bec device {self.bec_name} userParameter." + ) + bec_device: Device = self.dev[self.bec_name] + position = bec_device.user_parameter[target] + + bec_logger.logger.info( + f"obtained position {position} - compare to cached value {self.positions.get(target)}" + ) + return position + except Exception as e: + bec_logger.logger.debug( + f"Failed to fetch user parameter for device {self.bec_name} and target {target} from bec, falling back to cached position {e}" + ) + + if name not in self.positions: + raise ValueError(f"Unknown position '{target}'") + + return self.positions[name] + + if isinstance(target, (float, int)): + if not self.allow_arbitrary: + raise ValueError(f"{self.bec_name} only accepts named positions") + return float(target) + + raise TypeError("Target must be str or float") + + def move(self, target: str | float): + """Move the device and wait until it is there""" + pos = self._resolve_target(target) + + self._check_guards() + + if self.policy: + self.policy(pos) + + if self.move_method == "signal": + self.mot_device.put(pos) + else: + self.scans.mv(self.mot_device, pos, relative=False).wait() + + def mv(self, target: str | float): + """Start moving the device and return the scan report, to wait on (with a timeout)""" + + pos = self._resolve_target(target) + + self._check_guards() + + if self.policy: + self.policy(pos) + + return self.scans.mv(self.mot_device, pos, relative=False) + + @property + def actual(self) -> float: + """Return the actual position of the device.""" + return self.mot_device.read()[self.bec_name]["value"] + + @property + def pos(self) -> str: + """Return the closest matching position""" + + for name, pos in self.positions.items(): + if abs(self.actual - pos) <= self.tol: + return name + + return "unknown" + + def is_at(self, target: str | float) -> bool: + """Return True if the device is at the given position.""" + + pos = self._resolve_target(target) + return abs(self.actual - pos) <= self.tol diff --git a/mx_bec/optical_centering.py b/mx_bec/optical_centering.py index 2cae007..a8748c2 100644 --- a/mx_bec/optical_centering.py +++ b/mx_bec/optical_centering.py @@ -6,6 +6,7 @@ from aarelcinfer_client import Client as AareLcClient from aarelcinfer_client.models import LatestPredictionModel from bec_lib.logger import bec_logger +from mx_bec.calc import samcam_pixels_to_microns from mx_bec.sample_info import OpticalCenteringResults if TYPE_CHECKING: @@ -32,5 +33,16 @@ class OpticalPrediction: logger.info("Updating latest prediction on sample info") if self._client.sample_info: self._client.sample_info.optical_centering_results = OpticalCenteringResults( - prediction=latest + prediction=latest, microns_per_pixel=self.microns_per_pixel() ) + + def microns_per_pixel(self) -> float: + """Size of a sample camera pixel on the sample, at the current zoom.""" + camera = self._client.aare_config.camera + zoom = self._client.devices.scam_zoom.user_readback.get() + return samcam_pixels_to_microns( + 1, + zoom, + multiplier=camera.translation_factor_b / 1000, + exponent=camera.translation_factor_a, + ) diff --git a/mx_bec/sample_info.py b/mx_bec/sample_info.py index ecd5912..7525550 100644 --- a/mx_bec/sample_info.py +++ b/mx_bec/sample_info.py @@ -12,6 +12,10 @@ class OpticalCenteringResults(BaseModel): """Outputs from the optical centering stage""" prediction: LatestPredictionModel + microns_per_pixel: float = Field( + description="Size of a pixel of the prediction's image on the sample, from the sample " + "camera calibration at the zoom the image was taken with" + ) timestamp: float = Field(default_factory=time.time) diff --git a/pyproject.toml b/pyproject.toml index 0d88214..71ac8fb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,7 +16,7 @@ dependencies = [ "aarecommon", "aare_config", "aarelcinfer_client==0.1.1a8", - "jfjoch_client>=1.0.0rc166", # only pre-releases exist; the rc specifier lets pip pick them + "jfjoch_client>=1.0.0rc166", # only pre-releases exist; the rc specifier lets pip pick them "bec_lib>=3.130.3", "bec-server>=3.130.3", "bec-ipython-client>=3.130.3", @@ -38,7 +38,6 @@ dev = [ "ophyd_devices", "bec_server", "pytest", - "pytest-cov", "pytest-mock", "pytest-asyncio", "pytest-timeout", @@ -80,4 +79,3 @@ line-length = 100 [tool.ruff.format] skip-magic-trailing-comma = true - diff --git a/tests/unit/test_device_planner.py b/tests/unit/test_device_planner.py new file mode 100644 index 0000000..e6ef782 --- /dev/null +++ b/tests/unit/test_device_planner.py @@ -0,0 +1,160 @@ +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest +import yaml + +from mx_bec.device_planner import ( + BeamlineState, + DefineStatesManager, + GuardViolation, + PositionDevice, + StateChangePlanner, + TemperatureMode, + build_devices, + 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