diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml
index 0eb4dc1..5e0231f 100644
--- a/.gitea/workflows/ci.yml
+++ b/.gitea/workflows/ci.yml
@@ -24,6 +24,11 @@ on:
required: false
type: string
default: "main"
+ BEAMLINE_PLUGIN_BRANCH:
+ description: "Branch of the beamline plugins (pxi_bec, pxii_bec, pxiii_bec) to install"
+ required: false
+ type: string
+ default: "main"
PYTHON_VERSION:
description: "Python version to use"
required: false
@@ -36,6 +41,15 @@ permissions:
jobs:
test:
runs-on: ubuntu-latest
+ name: "${{ matrix.suite }} tests with ${{ matrix.plugin }}"
+ strategy:
+ fail-fast: false
+ matrix:
+ # unit: tests/unit; e2e: tests/e2e, against BEC servers running the simulated beamline
+ suite: [unit, e2e]
+ # BEC works with exactly one beamline plugin installed, which is what the device server
+ # loads the mx_bec devices through: run against each of them individually
+ plugin: [pxi_bec, pxii_bec, pxiii_bec]
env:
QTWEBENGINE_DISABLE_SANDBOX: 1
QT_QPA_PLATFORM: "offscreen"
@@ -58,6 +72,29 @@ jobs:
# Find all Copier conflicts except this line
run: '! grep -r "<<<<<<< before updating" | grep -v "grep -r \"<<<<<<< before updating"'
+ # Use the same-named branch of the beamline plugin if it exists (e.g. a feature developed in both repos), otherwise main.
+ - name: Resolve beamline plugin branch
+ id: plugin
+ shell: bash
+ run: |
+ ref="${{ inputs.BEAMLINE_PLUGIN_BRANCH || github.head_ref || github.ref_name }}"
+ auth="$(printf 'x-access-token:%s' '${{ github.token }}' | base64 -w0)"
+ if git -c "http.extraheader=Authorization: Basic ${auth}" ls-remote --exit-code --heads \
+ "${{ github.server_url }}/bec/${{ matrix.plugin }}.git" "refs/heads/${ref}" >/dev/null; then
+ echo "Using ${{ matrix.plugin }} branch '${ref}'"
+ else
+ echo "${{ matrix.plugin }} has no branch '${ref}', using main"
+ ref=main
+ fi
+ echo "ref=${ref}" >> "$GITHUB_OUTPUT"
+
+ - name: Checkout beamline plugin
+ uses: actions/checkout@v4
+ with:
+ repository: "bec/${{ matrix.plugin }}"
+ ref: "${{ steps.plugin.outputs.ref }}"
+ path: "./${{ matrix.plugin }}"
+
- name: Checkout BEC Core
uses: actions/checkout@v4
with:
@@ -85,6 +122,8 @@ jobs:
sudo apt-get update
sudo apt-get install -y libgl1 libegl1 x11-utils libxkbcommon-x11-0 libdbus-1-3 xvfb
sudo apt-get -y install libnss3 libxdamage1 libasound2t64 libatomic1 libxcursor1
+ # the end-to-end tests start their own redis server
+ sudo apt-get -y install redis-server
- name: Install Python dependencies
shell: bash
@@ -94,9 +133,37 @@ 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 ./mx_bec
+ uv pip install --system -e ./bec/pytest_bec_e2e
+ 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[dev]
+ uv pip install --system --extra-index-url https://gitea.psi.ch/api/packages/mx/pypi/simple/ -e ./${{ matrix.plugin }}
- name: Run Pytest with Coverage
+ if: matrix.suite == 'unit'
id: coverage
- run: pytest --random-order --cov=./mx_bec --cov-config=./mx_bec/pyproject.toml --cov-branch --cov-report=xml --no-cov-on-fail ./mx_bec/tests/ || test $? -eq 5
+ run: |
+ if coverage run --rcfile=./mx_bec/pyproject.toml --branch --source=./mx_bec -m pytest --random-order ./mx_bec/tests/unit; then
+ coverage xml --rcfile=./mx_bec/pyproject.toml
+ else
+ test $? -eq 5
+ fi
+
+ - name: Run end-to-end tests
+ if: matrix.suite == 'e2e'
+ shell: bash
+ run: |
+ mkdir -p ./e2e_files
+ pytest -v --start-servers --files-path ./e2e_files ./mx_bec/tests/e2e
+
+ - name: Show server logs if the end-to-end tests fail
+ if: failure() && matrix.suite == 'e2e'
+ shell: bash
+ run: |
+ shopt -s nullglob
+ # the BEC services write their logs next to the bec checkout
+ for log in ./e2e_files/*.log ./bec/logs/*.log; do
+ echo "::group::${log}"
+ tail -n 200 "${log}"
+ echo "::endgroup::"
+ done
diff --git a/mx_bec/__init__.py b/mx_bec/__init__.py
index e69de29..4a6e830 100644
--- a/mx_bec/__init__.py
+++ b/mx_bec/__init__.py
@@ -0,0 +1,3 @@
+from .service import AareBec
+
+__all__ = ["AareBec"]
diff --git a/mx_bec/aaredaq.py b/mx_bec/aaredaq.py
new file mode 100644
index 0000000..257143d
--- /dev/null
+++ b/mx_bec/aaredaq.py
@@ -0,0 +1,242 @@
+from __future__ import annotations
+
+import json
+import subprocess
+import time
+from typing import TYPE_CHECKING, Any
+
+import requests
+from aarecommon.config.beamline import cfg_get, mx_beamline
+from aarecommon.models.auth import BatonStatus
+from aarecommon.models.beamline import MXBeamline
+from aarecommon.models.raster_grid import CompletedRasterGrid, RasterGridRequest
+from aarecommon.models.rotation_scan import CompletedRotationScan, RotationScanRequest
+from bec_lib.logger import bec_logger
+
+if TYPE_CHECKING:
+ from mx_bec.service import AareBec
+
+logger = bec_logger.logger
+
+# same defaults as the AareDAQ GUI (aare/gui/gui.py)
+DEFAULT_URLS = {
+ MXBeamline.X06DA: "https://mx-x06da-queue-01.psi.ch",
+ MXBeamline.X10SA: "https://mx-x10sa-queue-01.psi.ch",
+}
+DEFAULT_CERT_PATHS = {
+ MXBeamline.X06DA: "/sls/x06da/misc/.cert/6d.crt",
+ MXBeamline.X10SA: "/sls/x10sa/misc/.cert/10s.crt",
+}
+TOKEN_TIMEOUT_S = 120.0
+REQUEST_TIMEOUT_S = 30.0 # for quick calls such as the baton endpoints
+SCAN_TIMEOUT_S = 3600.0 # the scan endpoints block until the scan is done
+BATON_WAIT_S = 60.0 # covers the server's 30 s for the current holder to answer a request
+BATON_POLL_INTERVAL_S = 1.0
+
+
+class AareDaqError(RuntimeError):
+ """A call to the AareDAQ server failed."""
+
+
+class AareDaq:
+ """Client for the AareDAQ REST API (aaredaq `server.py`).
+
+ Mirrors how the AareDAQ GUI talks to the server: a bearer token is obtained once, lazily, by
+ Kerberos (`curl --negotiate` against the Apache proxy in front of the server, exactly as
+ `aare.gui.auth.auth` does), and is renewed once if the server answers 401. The server URL and
+ its certificate come from the aarecommon beamline config unless given. Hardware operations
+ take the beamline baton first if this session does not hold it yet.
+ """
+
+ def __init__(
+ self, client: AareBec, url: str | None = None, cert_path: str | None = None
+ ) -> None:
+ self._client = client
+ self._url = url
+ self._cert_path = cert_path
+ self._token: str | None = None
+ self._session = requests.Session()
+
+ @property
+ def url(self) -> str:
+ if self._url is None:
+ beamline = mx_beamline()
+ self._url = cfg_get("gui.daq.daq_url", DEFAULT_URLS.get(beamline))
+ if self._url is None:
+ raise AareDaqError(f"No AareDAQ URL configured for beamline {beamline}")
+ return self._url
+
+ @property
+ def cert_path(self) -> str:
+ if self._cert_path is None:
+ beamline = mx_beamline()
+ self._cert_path = cfg_get("gui.daq.cert_path", DEFAULT_CERT_PATHS.get(beamline))
+ if self._cert_path is None:
+ raise AareDaqError(f"No AareDAQ certificate configured for beamline {beamline}")
+ return self._cert_path
+
+ @property
+ def token(self) -> str:
+ if self._token is None:
+ self._token = self._request_token()
+ return self._token
+
+ def _request_token(self) -> str:
+ """POST /token through the Kerberos (SPNEGO) proxy; needs a valid ticket (kinit)."""
+ cmd = ["curl", "-s", "--cacert", self.cert_path, "--negotiate", "-u", ":", "-XPOST"]
+ cmd.append(f"{self.url}/token")
+ try:
+ result = subprocess.run(
+ cmd, capture_output=True, text=True, timeout=TOKEN_TIMEOUT_S, check=False
+ )
+ except (OSError, subprocess.TimeoutExpired) as e:
+ raise AareDaqError(f"AareDAQ token request failed: {e}") from e
+ if result.returncode != 0:
+ raise AareDaqError(
+ f"AareDAQ token request failed (curl exit {result.returncode}): "
+ f"{result.stderr[:500]}. Is the Kerberos ticket valid (kinit)?"
+ )
+ try:
+ token = json.loads(result.stdout).get("access_token")
+ except json.JSONDecodeError as e:
+ raise AareDaqError(f"AareDAQ token response is not JSON: {result.stdout[:500]}") from e
+ if not isinstance(token, str) or not token:
+ raise AareDaqError(f"AareDAQ token response has no access_token: {result.stdout[:500]}")
+ return token
+
+ def _request(
+ self,
+ method: str,
+ endpoint: str,
+ *,
+ params: dict[str, Any] | None = None,
+ body: dict[str, Any] | None = None,
+ timeout_s: float = SCAN_TIMEOUT_S,
+ ) -> Any:
+ """Call `endpoint` with the bearer token and return the decoded JSON response. A 401 is
+ retried once with a fresh token; any other error becomes an AareDaqError."""
+ for attempt in range(2):
+ try:
+ resp = self._session.request(
+ method,
+ f"{self.url}{endpoint}",
+ params=params,
+ json=body,
+ headers={"Authorization": f"Bearer {self.token}"},
+ verify=self.cert_path,
+ timeout=timeout_s,
+ )
+ except requests.RequestException as e:
+ raise AareDaqError(f"AareDAQ {method} {endpoint} failed: {e}") from e
+ if resp.status_code == 401 and attempt == 0:
+ logger.info("AareDAQ rejected the token, requesting a new one")
+ self._token = None
+ continue
+ if not resp.ok:
+ raise AareDaqError(
+ f"AareDAQ {method} {endpoint} failed with {resp.status_code}: {resp.text[:500]}"
+ )
+ return resp.json()
+ raise AssertionError("unreachable") # pragma: no cover
+
+ def _get(self, endpoint: str, timeout_s: float = REQUEST_TIMEOUT_S) -> Any:
+ return self._request("GET", endpoint, timeout_s=timeout_s)
+
+ def _post(
+ self,
+ endpoint: str,
+ *,
+ params: dict[str, Any] | None = None,
+ body: dict[str, Any] | None = None,
+ timeout_s: float = SCAN_TIMEOUT_S,
+ ) -> Any:
+ return self._request("POST", endpoint, params=params, body=body, timeout_s=timeout_s)
+
+ # ---- baton: AareDAQ only runs hardware operations for the session holding the baton ----
+
+ def baton_status(self) -> BatonStatus:
+ return BatonStatus.model_validate(self._get("/baton/status"))
+
+ def take_baton(
+ self, wait_s: float = BATON_WAIT_S, poll_interval_s: float = BATON_POLL_INTERVAL_S
+ ) -> None:
+ """Take the baton. Granted at once if the beamline is vacant (or we are staff); otherwise
+ the current holder is asked, and we poll until they accept or their time to answer runs
+ out, for up to `wait_s`. Raises AareDaqError if refused or not granted in time."""
+ result = self._post("/baton/request", timeout_s=REQUEST_TIMEOUT_S)
+ if result.get("granted") or result.get("already_holder"):
+ logger.info(f"AareDAQ baton: {result.get('message')}")
+ return
+ if not (result.get("pending") or result.get("queued")):
+ raise AareDaqError(f"AareDAQ refused the baton request: {result.get('message')}")
+ logger.info(f"AareDAQ baton: {result.get('message')}; waiting for it")
+ deadline = time.monotonic() + wait_s
+ while True:
+ time.sleep(poll_interval_s)
+ result = self._get("/baton/check_timeout")
+ if result.get("granted"):
+ logger.info("AareDAQ baton acquired")
+ return
+ if result.get("refused"):
+ raise AareDaqError("AareDAQ baton request was refused by the current holder")
+ if time.monotonic() > deadline:
+ raise AareDaqError(f"AareDAQ baton not granted within {wait_s} s: {result}")
+
+ def release_baton(self) -> None:
+ """Release the baton, leaving the beamline vacant."""
+ self._post("/baton/release", timeout_s=REQUEST_TIMEOUT_S)
+
+ def ensure_baton(self) -> None:
+ """Take the baton unless this session already holds it."""
+ if not self.baton_status().you_are_holder:
+ self.take_baton()
+
+ # ---- hardware operations ----
+
+ def mount_sample(self, dbid: int, reference: bool = False, timeout_s: float = 600.0) -> None:
+ """Mount the sample with database id `dbid` (from the reference tools if `reference`)."""
+ self.ensure_baton()
+ logger.info(f"AareDAQ: mounting sample {dbid}{' (reference tool)' if reference else ''}")
+ self._post(
+ "/sample/mount", params={"dbid": dbid, "reference": reference}, timeout_s=timeout_s
+ )
+
+ def unmount_sample_then_park(self, timeout_s: float = 600.0) -> None:
+ """unmount the current sample."""
+ self.ensure_baton()
+ logger.info("AareDAQ: unmounting sample, then putting the robot to a safe place")
+ self._post("/sample/unmount_then_park_and_dry", timeout_s=timeout_s)
+
+ def auto_loop_center(self):
+ self.ensure_baton()
+ self._post("/alc/center_loop")
+
+ def raster_scan(
+ self,
+ request: RasterGridRequest,
+ auto_center: bool = False,
+ timeout_s: float = SCAN_TIMEOUT_S,
+ ) -> CompletedRasterGrid:
+ """Run a raster scan and return its result (blocks until the scan is done)."""
+ self.ensure_baton()
+ logger.info(f"AareDAQ: raster scan {request.n_x}x{request.n_y}, auto_center={auto_center}")
+ result = self._post(
+ "/scan/raster",
+ params={"auto_center": auto_center},
+ body=request.model_dump(mode="json"),
+ timeout_s=timeout_s,
+ )
+ return CompletedRasterGrid.model_validate(result)
+
+ def rotation_scan(
+ self, request: RotationScanRequest, timeout_s: float = SCAN_TIMEOUT_S
+ ) -> CompletedRotationScan:
+ """Run a rotation (or screening) scan and return its result (blocks until done)."""
+ self.ensure_baton()
+ logger.info(
+ f"AareDAQ: rotation scan, {request.steps} steps of {request.incr_omega_deg} deg"
+ )
+ result = self._post(
+ "/scan/rotation", body=request.model_dump(mode="json"), timeout_s=timeout_s
+ )
+ return CompletedRotationScan.model_validate(result)
diff --git a/mx_bec/actor_manager.py b/mx_bec/actor_manager.py
new file mode 100644
index 0000000..1ddf989
--- /dev/null
+++ b/mx_bec/actor_manager.py
@@ -0,0 +1,123 @@
+from __future__ import annotations
+
+import functools
+from threading import Event, Thread
+from typing import TYPE_CHECKING, Callable, Iterable
+
+from bec_lib.config_values import RedisConfigValue
+from bec_lib.endpoints import MessageEndpoints
+from bec_lib.logger import bec_logger
+from bec_lib.messages import AvailableResourceMessage, BuiltinActorStateUpdatedNotification
+
+from mx_bec.actors import all_actor_classes
+from mx_bec.actors.core import MXAutomationActor
+from mx_bec.endpoints import ActorEndpoints
+
+if TYPE_CHECKING:
+ from bec_lib.endpoints import EndpointInfo
+
+ from mx_bec.service import AareBec
+
+logger = bec_logger.logger
+
+
+ActorClass = type[MXAutomationActor]
+RunningActor = tuple[MXAutomationActor, Thread, Event]
+
+
+class AareActorManager:
+ """Runs the MX automation actors on behalf of the AareBec service.
+
+ Every actor class has an `enabled` flag in Redis (see `MXAutomationActor.config_endpoint`);
+ the manager starts an actor thread when its flag becomes true and stops it when it becomes
+ false. By default all actors in `mx_bec.actors` are managed; pass `actor_classes`
+ to override.
+ """
+
+ def __init__(
+ self, client: AareBec, actor_classes: Iterable[type[MXAutomationActor]] | None = None
+ ) -> None:
+ self._client = client
+ self._actor_classes = (
+ list(actor_classes) if actor_classes is not None else all_actor_classes()
+ )
+ self._actors_threads_and_stops: dict[ActorClass, RunningActor] = {}
+ self._enabled_flags: dict[ActorClass, RedisConfigValue[bool]] = {}
+ # RedisConfigValue only keeps weak references to subscribers, so hold the partials here.
+ self._enabled_callbacks: dict[ActorClass, Callable[[bool], None]] = {}
+ enabled_endpoints: dict[str, EndpointInfo] = {}
+ for actor_class in self._actor_classes:
+ ep = actor_class.config_endpoint()
+ flag: RedisConfigValue[bool] = RedisConfigValue(
+ connector=self._client.connector, endpoint=ep
+ )
+ enabled_endpoints[actor_class.__name__] = ep
+ callback = functools.partial(self._enabled_changed, actor_class)
+ flag.subscribe(callback)
+ self._enabled_flags[actor_class] = flag
+ self._enabled_callbacks[actor_class] = callback
+ available_actor_config_eps = AvailableResourceMessage(
+ resource={"endpoints": enabled_endpoints}
+ )
+ self._client.connector.set_and_publish(
+ ActorEndpoints.available_actor_config_eps(), available_actor_config_eps
+ )
+ self._start_all()
+
+ @property
+ def actor_classes(self) -> list[type[MXAutomationActor]]:
+ return list(self._actor_classes)
+
+ @property
+ def running(self) -> list[type[MXAutomationActor]]:
+ return list(self._actors_threads_and_stops)
+
+ def is_enabled(self, actor_class: type[MXAutomationActor]) -> bool:
+ return self._enabled_flags[actor_class].value
+
+ def set_enabled(self, actor_class: type[MXAutomationActor], enabled: bool) -> None:
+ """Write the actor's enabled flag; the actor is started/stopped via the Redis callback."""
+ self._enabled_flags[actor_class].value = enabled
+
+ def _ping_clients(self, actor_name: str):
+ self._client.connector.send(
+ MessageEndpoints.builtin_actor_update_notif(actor_name),
+ BuiltinActorStateUpdatedNotification(actor_name=actor_name),
+ )
+
+ def _enabled_changed(self, actor_class: type[MXAutomationActor], enabled: bool):
+ (self._start_actor(actor_class) if enabled else self._stop_actor(actor_class))
+ self._ping_clients(actor_class.__name__)
+
+ def _start_all(self):
+ for actor_class in self._actor_classes:
+ if self._enabled_flags[actor_class].value:
+ self._start_actor(actor_class)
+
+ def _start_actor(self, actor_class: type[MXAutomationActor]):
+ name = actor_class.__name__
+ logger.info(f"Starting {name}")
+ if actor_class in self._actors_threads_and_stops:
+ logger.warning(f"Actor {name} is already active!")
+ return
+ actor = actor_class(self._client, name=name, exec_id=name)
+ t = Thread(target=actor.run, name=name)
+ self._actors_threads_and_stops[actor_class] = (actor, t, actor.stop_event)
+ t.start()
+
+ def _stop_actor(self, actor_class: type[MXAutomationActor]):
+ logger.info(f"Stopping {actor_class.__name__}")
+ if (entry := self._actors_threads_and_stops.get(actor_class)) is None:
+ logger.warning(f"Actor {actor_class.__name__} is not active!")
+ return
+ actor, t, event = entry
+ event.set()
+ t.join()
+ del self._actors_threads_and_stops[actor_class]
+ del actor
+
+ def shutdown(self):
+ for flag in self._enabled_flags.values():
+ flag.unregister_all()
+ for actor_class in list(self._actors_threads_and_stops):
+ self._stop_actor(actor_class)
diff --git a/mx_bec/actors/__init__.py b/mx_bec/actors/__init__.py
new file mode 100644
index 0000000..c8122db
--- /dev/null
+++ b/mx_bec/actors/__init__.py
@@ -0,0 +1,21 @@
+import inspect
+
+from .core import MXAutomationActor
+
+
+def all_actor_classes() -> list[type[MXAutomationActor]]:
+ """Every concrete MXAutomationActor subclass defined in this package, in definition order."""
+ # Importing the module is what registers its classes as subclasses.
+ from . import mx_automation # noqa: F401
+
+ found: list[type[MXAutomationActor]] = []
+ pending = list(MXAutomationActor.__subclasses__())
+ while pending:
+ cls = pending.pop(0)
+ pending.extend(cls.__subclasses__())
+ if not inspect.isabstract(cls) and cls not in found:
+ found.append(cls)
+ return found
+
+
+__all__ = ["MXAutomationActor", "all_actor_classes"]
diff --git a/mx_bec/actors/core.py b/mx_bec/actors/core.py
new file mode 100644
index 0000000..9f3407e
--- /dev/null
+++ b/mx_bec/actors/core.py
@@ -0,0 +1,137 @@
+from __future__ import annotations
+
+import secrets
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, Any, ClassVar
+
+from bec_lib.endpoints import EndpointInfo
+from bec_lib.logger import bec_logger
+from bec_server.actors.actor import SubscriptionActor
+
+from mx_bec.decisions import StrategyConfig, plan_rotation
+from mx_bec.endpoints import ActorEndpoints, StateEndpoints
+from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskExecutionMessage
+
+if TYPE_CHECKING:
+ from bec_lib.messages import BoolConfigDefaultFalse
+ from bec_lib.redis_connector import MessageObject
+
+ from mx_bec.service import AareBec
+
+logger = bec_logger.logger
+
+
+class MXAutomationActor(SubscriptionActor, ABC):
+ """Base for MX automation actors.
+
+ Subclasses pick the sequence milestones they react to via `default_monitor_endpoints()`
+ (which must carry `MXMeasurementSequenceMessage`s), and implement `action`. Whenever a
+ milestone message arrives it is stored in `last_message` and the action table is evaluated.
+ By default the action runs if the step succeeded for the sample which is currently loaded;
+ override `condition` to change that.
+ """
+
+ config_key: ClassVar[str]
+ """Unique key used to build this actor's config endpoints, e.g. "optical_centering"."""
+
+ strategy: ClassVar[StrategyConfig] = StrategyConfig()
+ """Thresholds and limits for planning data collections."""
+
+ def __init__(self, client: AareBec, name: str, exec_id: str):
+ # TODO aare protocols for aare actors which take only the aare client
+ self.action_table = {self.condition: self._action}
+ self.last_message: MXMeasurementSequenceMessage | None = None
+ super().__init__(client, name, exec_id)
+
+ @classmethod
+ def config_endpoint(cls) -> EndpointInfo[type[BoolConfigDefaultFalse]]:
+ """Managed bool controlling whether the actor manager runs this actor."""
+ return ActorEndpoints.enabled(cls.config_key)
+
+ def evaluate(self, msg_obj: MessageObject[Any] | None = None, **_):
+ """Callback for the monitored endpoints. Called with a MessageObject whose value is the
+ milestone message; evaluates the action table if the step succeeded."""
+ if msg_obj is not None:
+ msg = msg_obj.value
+ if not isinstance(msg, MXMeasurementSequenceMessage):
+ logger.warning(f"{self.name} ignoring unexpected message on {msg_obj.topic}: {msg}")
+ return
+ self.last_message = msg
+ if not msg.success:
+ logger.info(f"{self.name}: step failed for sample {msg.sample_id}, not acting")
+ return super().evaluate()
+
+ def condition(self, client: AareBec) -> bool:
+ """Whether `action` should run; evaluated after every milestone message. By default: the
+ step succeeded, and for the sample which is currently loaded."""
+ msg = self.last_message
+ if msg is None or not msg.success:
+ return False
+ info = client.sample_info
+ if info is None or info.sample_id != msg.sample_id:
+ logger.warning(f"{type(self).__name__}: message for sample {msg.sample_id} is stale")
+ return False
+ return True
+
+ @abstractmethod
+ def action(self, client: AareBec) -> None:
+ """What to do when `.condition()` evaluates `True`."""
+
+ def _action(self, client: AareBec) -> None:
+ assert self.last_message is not None
+ self.last_message = None
+ self.action(client)
+
+ # ---- helpers for the actions ----
+
+ @staticmethod
+ def queue(client: AareBec, name: str, *args: Any) -> None:
+ """Append a task to the task queue."""
+ client.add_task_to_queue(MXTaskExecutionMessage(name=name, args=args, kwargs={}))
+
+ @staticmethod
+ def finish(client: AareBec, sample_id: int, *, success: bool, reason: str) -> None:
+ """Publish the `sample_done` milestone: nothing more will be done with this sample."""
+ logger.info(f"Sample {sample_id} finished (success={success}): {reason}")
+ client.connector.set_and_publish(
+ StateEndpoints.sample_done(),
+ MXMeasurementSequenceMessage(sample_id=sample_id, success=success),
+ )
+
+ def queue_collection(
+ self,
+ client: AareBec,
+ position_index: int,
+ *,
+ chi_values: list[float] | tuple[float, ...] = (0.0,),
+ dose_fraction: float = 1.0,
+ reason: str,
+ ) -> bool:
+ """Plan a rotation dataset at a spot of the sample's grid analysis and queue it. Finishes
+ the sample as failed, and returns False, if no dataset can be planned there."""
+ # pyright: ignore[reportMissingImports]
+ from pxii_bec.macros.flux_macros import bpm2flux
+
+ info = client.sample_info
+ assert info is not None, "No sample loaded"
+ assert info.grid_analysis is not None, "No grid analysed"
+ prefix = f"S{info.sample_id}_{secrets.token_hex(3)}"
+ _, self.strategy.beam.flux_ph_s = bpm2flux()
+ try:
+ plan = plan_rotation(
+ info.grid_analysis,
+ position_index,
+ self.strategy,
+ file_prefix=prefix,
+ chi_values=chi_values,
+ dose_fraction=dose_fraction,
+ reason=reason,
+ )
+ except ValueError as e:
+ self.finish(client, info.sample_id, success=False, reason=f"cannot plan: {e}")
+ return False
+ if position_index not in info.positions_used:
+ info.positions_used.append(position_index)
+ logger.info(f"Queue collection for sample {info.sample_id}: {plan}")
+ self.queue(client, "collect_dataset", info.sample_id, plan.model_dump())
+ return True
diff --git a/mx_bec/actors/mx_automation.py b/mx_bec/actors/mx_automation.py
new file mode 100644
index 0000000..de04cda
--- /dev/null
+++ b/mx_bec/actors/mx_automation.py
@@ -0,0 +1,248 @@
+"""Actors chaining the steps of an automated MX measurement.
+
+Each actor listens to one milestone of the sequence and kicks off the next step. The actions
+are stand-ins for now: they log and immediately publish the next milestone, so the chain can be
+exercised end to end on the simulated beamline before the real procedures exist.
+"""
+
+from datetime import date
+from time import sleep
+
+from aarelcinfer_client.models import DetectionModel
+from bec_lib.endpoints import EndpointInfo
+from bec_lib.logger import bec_logger
+
+from mx_bec.actors.core import MXAutomationActor
+from mx_bec.decisions import (
+ Action,
+ analyse_grid,
+ assess_collection,
+ decide_followup,
+ gridscan_calculation,
+ gridscan_strategy_from_optical,
+ mock_grid_calculation,
+)
+from mx_bec.endpoints import QueueEndpoints, StateEndpoints
+from mx_bec.messages import (
+ MXMeasurementSequenceMessage,
+ MXQueueChangedMessage,
+ MXSampleExecutionMessage,
+ MXTaskExecutionMessage,
+)
+from mx_bec.service import AareBec
+
+logger = bec_logger.logger
+
+
+STEP_X_MM = 0.03
+STEP_Y_MM = 0.02
+MARGIN = 1.3
+
+
+class OnSampleMountedRunOpticalCentering(MXAutomationActor):
+ """When a sample is mounted, run optical centering. Only runs if mounting reported success."""
+
+ config_key = "optical_centering_on_mount"
+
+ def default_monitor_endpoints(self) -> set[EndpointInfo[type[MXMeasurementSequenceMessage]]]:
+ return {StateEndpoints.sample_mounted()}
+
+ def condition(self, client: AareBec) -> bool:
+ return self.last_message is not None and self.last_message.success
+
+ def action(self, client: AareBec) -> None:
+ assert client.sample_info, "No sample loaded"
+ sample_id = client.sample_info.sample_id
+ logger.info(f"{self.name}: running optical centering for sample {sample_id}")
+ client.add_task_to_queue(
+ MXTaskExecutionMessage(name="run_optical_centering", args=(sample_id,), kwargs={})
+ )
+
+
+class OnOpticalCenteringDoneRunXrayCentering(MXAutomationActor):
+ """When optical centering finished, run X-ray centering. Runs regardless of success."""
+
+ config_key = "xray_centering_after_optical"
+
+ def default_monitor_endpoints(self) -> set[EndpointInfo[type[MXMeasurementSequenceMessage]]]:
+ return {StateEndpoints.optical_centering_done()}
+
+ def condition(self, client: AareBec) -> bool:
+ return self.last_message is not None
+
+ def action(self, client: AareBec) -> None:
+ assert client.sample_info, "No sample loaded"
+ sample_id = client.sample_info.sample_id
+ logger.info(f"{self.name}: running single-grid X-ray centering for sample {sample_id}")
+ logger.info(
+ f"Calculating gridscan strategy given optical centering results available: {client.sample_info.optical_centering_results is not None}"
+ )
+ strategy = gridscan_strategy_from_optical(
+ client.sample_info.optical_centering_results,
+ client.aare_config.auto_grid_params.box_size_x_um,
+ client.aare_config.auto_grid_params.box_size_y_um,
+ client.aare_config.auto_grid_params.margin_multiplier,
+ client.aare_config.auto_grid_params.exp_time_s,
+ client.aare_config.auto_grid_params.detector_distance_mm,
+ )
+ strategy["omega_deg"] = 0.0
+ logger.info(f"calculated strategy: {strategy}")
+ client.add_task_to_queue(
+ MXTaskExecutionMessage(name="xray_centering", args=(sample_id, strategy), kwargs={})
+ )
+
+
+class OnOpticalCenteringDoneRunMultiGrid(MXAutomationActor):
+ """When optical centering finished, run X-ray centering. Runs regardless of success."""
+
+ config_key = "multigrid_after_optical"
+
+ def default_monitor_endpoints(self) -> set[EndpointInfo[type[MXMeasurementSequenceMessage]]]:
+ return {StateEndpoints.optical_centering_done()}
+
+ def condition(self, client: AareBec) -> bool:
+ return self.last_message is not None
+
+ def action(self, client: AareBec) -> None:
+ assert client.sample_info, "No sample loaded"
+ sample_id = client.sample_info.sample_id
+ logger.info(f"{self.name}: running multi-grid X-ray centering for sample {sample_id}")
+ logger.info(
+ f"Calculating gridscan strategy given optical centering results available: {client.sample_info.optical_centering_results is not None}"
+ )
+ params = client.aare_config.auto_grid_params
+ strategy = gridscan_strategy_from_optical(
+ client.sample_info.optical_centering_results,
+ params.box_size_x_um,
+ params.box_size_y_um,
+ params.margin_multiplier,
+ params.exp_time_s,
+ params.detector_distance_mm,
+ )
+ logger.info(f"calculated strategy: {strategy}")
+ strategy["file_prefix"] = date.today().strftime("%Y%m%d") + "/" + strategy["file_prefix"]
+ client.add_task_to_queue(
+ MXTaskExecutionMessage(
+ name="multiple_rasters", args=(params.omegas_for_multi_grid_degs,), kwargs=strategy
+ )
+ )
+
+
+class OnSampleDoneLoadNext(MXAutomationActor):
+ config_key = "on_sample_done_load_next"
+
+ def default_monitor_endpoints(self) -> set[EndpointInfo[type[MXMeasurementSequenceMessage]]]:
+ return {StateEndpoints.sample_done()}
+
+ def condition(self, client: AareBec) -> bool:
+ return self.last_message is not None
+
+ def action(self, client: AareBec) -> None:
+ queue_len = client.connector.llen(QueueEndpoints.sample_execution())
+ if not queue_len:
+ return # TODO: run some kind of cleanup e.g. unmount, gripper park and dry
+ next: MXSampleExecutionMessage = client.connector.blocking_list_pop(
+ QueueEndpoints.sample_execution()
+ )
+ client.connector.send(QueueEndpoints.sample_queue_changed(), MXQueueChangedMessage())
+ client.add_task_to_queue(
+ MXTaskExecutionMessage(name="aaredaq_mount_sample", args=(next.db_id,), kwargs={})
+ )
+
+
+class OnXrayCenteringDonePlanCollection(MXAutomationActor):
+ """Analyse the grid with the Rugnux/Jungfraujoch per-cell results and queue the first dataset."""
+
+ config_key = "self_driving_collect_after_grid"
+
+ def default_monitor_endpoints(self) -> set[EndpointInfo[type[MXMeasurementSequenceMessage]]]:
+ return {StateEndpoints.xray_centering_done()}
+
+ def action(self, client: AareBec) -> None:
+ info = client.sample_info
+ assert info is not None, "No sample loaded"
+ sample_id = info.sample_id
+ raster = info.raster
+ if raster is None:
+ self.finish(client, sample_id, success=False, reason="no raster results stored")
+ return
+
+ analysis = info.grid_analysis = analyse_grid(raster.images, raster.geometry, self.strategy)
+ # A new grid has new coordinates: spots from an earlier grid no longer apply.
+ # ASSUMPTION: the raster leaves the smargon at its start position (cell 0, 0).
+ info.positions_used = []
+ info.current_offset_mm = (0.0, 0.0)
+
+ logger.info(
+ f"Self-driving: grid for sample {sample_id}: {analysis.n_hits}/{analysis.n_images} "
+ f"hits, {len(analysis.regions)} crystal(s), {len(analysis.positions)} spot(s)"
+ )
+ if not analysis.positions:
+ self.finish(client, sample_id, success=False, reason="no diffraction in grid")
+ return
+
+ cfg = self.strategy
+ if cfg.anomalous:
+ chis = cfg.anomalous_chi_deg
+ if len(chis) > 1:
+ info.chi_sweeps_done += 1
+ reason = "anomalous: low-dose multi-chi"
+ else:
+ chis, reason = (0.0,), "best spot from grid"
+ self.queue_collection(client, 0, chi_values=chis, reason=reason)
+
+
+class OnRotationDoneDecideFollowUp(MXAutomationActor):
+ """Assess the last dataset and queue a follow-up, or finish the sample."""
+
+ config_key = "self_driving_followup_after_rotation"
+
+ def default_monitor_endpoints(self) -> set[EndpointInfo[type[MXMeasurementSequenceMessage]]]:
+ return {StateEndpoints.rotation_done()}
+
+ def action(self, client: AareBec) -> None:
+ info = client.sample_info
+ assert info is not None, "No sample loaded"
+ sample_id = info.sample_id
+ if not info.collections:
+ self.finish(client, sample_id, success=False, reason="rotation_done without a record")
+ return
+
+ latest = info.collections[-1]
+ latest.assessment = assess_collection(latest, self.strategy)
+ decision = decide_followup(latest.assessment, info, self.strategy)
+ logger.info(
+ f"Self-driving: sample {sample_id} issues={[i.value for i in latest.assessment.issues]}"
+ f" -> {decision.action.value}: {decision.reason}"
+ )
+
+ if decision.action is Action.FINISH:
+ usable = any(c.assessment and c.assessment.usable for c in info.collections)
+ self.finish(client, sample_id, success=usable, reason=decision.reason)
+ return
+
+ info.followups += 1
+ if decision.action is Action.RECENTRE:
+ if info.raster is None:
+ self.finish(client, sample_id, success=False, reason="no raster to repeat")
+ return
+ info.recentres += 1
+ strategy = dict(info.raster.strategy)
+ strategy["file_prefix"] = (
+ f"{strategy.get('file_prefix') or 'raster'}_rc{info.recentres}"
+ )
+ # Back to the original raster start so the repeat grid covers the same area.
+ self.queue(client, "move_to_grid_offset", sample_id, 0.0, 0.0)
+ self.queue(client, "xray_centering", sample_id, strategy)
+ return
+
+ assert decision.position_index is not None
+ if decision.action is Action.CHI_SWEEP:
+ info.chi_sweeps_done += 1
+ self.queue_collection(
+ client,
+ decision.position_index,
+ chi_values=decision.chi_values,
+ dose_fraction=decision.dose_fraction,
+ reason=decision.reason,
+ )
diff --git a/mx_bec/bec_widgets/widgets/aare_bec/__init__.py b/mx_bec/bec_widgets/widgets/aare_bec/__init__.py
new file mode 100644
index 0000000..d624b39
--- /dev/null
+++ b/mx_bec/bec_widgets/widgets/aare_bec/__init__.py
@@ -0,0 +1,13 @@
+from .actors_config import MxActorConfigWidget
+from .sample_queue import SampleQueueWidget
+from .sample_spreadsheet_display import SampleSpreadsheetDisplay
+from .task_panel import MxTaskPanel
+from .task_queue import MxTaskQueueWidget
+
+__all__ = [
+ "MxActorConfigWidget",
+ "SampleQueueWidget",
+ "SampleSpreadsheetDisplay",
+ "MxTaskPanel",
+ "MxTaskQueueWidget",
+]
diff --git a/mx_bec/bec_widgets/widgets/aare_bec/actors_config.py b/mx_bec/bec_widgets/widgets/aare_bec/actors_config.py
new file mode 100644
index 0000000..ca443ce
--- /dev/null
+++ b/mx_bec/bec_widgets/widgets/aare_bec/actors_config.py
@@ -0,0 +1,101 @@
+from __future__ import annotations
+
+import functools
+from typing import Callable
+
+from bec_lib.config_values import RedisConfigValue
+from bec_lib.logger import bec_logger
+from bec_lib.messages import AvailableResourceMessage
+from bec_widgets.utils.bec_connector import ConnectionConfig
+from bec_widgets.utils.bec_widget import BECWidget
+from bec_widgets.utils.error_popups import SafeSlot
+from bec_widgets.widgets.utility.toggle.toggle import ToggleSwitch
+from qtpy.QtCore import Signal
+from qtpy.QtWidgets import QGridLayout, QLabel, QWidget
+
+from mx_bec.endpoints import ActorEndpoints
+
+logger = bec_logger.logger
+
+
+class MxActorConfigWidget(BECWidget, QWidget):
+ """
+ Widget displaying and managing MX actors - automation steps.
+
+ Each available actor gets a row with its name and a toggle bound to the actor's `enabled`
+ flag in Redis, so the toggle both writes the flag and follows changes made elsewhere.
+ """
+
+ PLUGIN = True
+ ICON_NAME = "format_list_bulleted"
+ USER_ACCESS = ["refresh"]
+
+ # Redis callbacks arrive on the connector thread; re-emit so the toggle is updated on the GUI
+ # thread.
+ _config_value_changed = Signal(str, bool)
+
+ def __init__(
+ self,
+ parent: QWidget | None = None,
+ client=None,
+ config: ConnectionConfig | None = None,
+ gui_id: str | None = None,
+ **kwargs,
+ ) -> None:
+ super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs)
+ self._layout = QGridLayout(self)
+ self._toggles: dict[str, ToggleSwitch] = {}
+ self._config_values: dict[str, RedisConfigValue[bool]] = {}
+ # RedisConfigValue only keeps weak references to subscribers, so hold the partials here.
+ self._config_callbacks: dict[str, Callable[[bool], None]] = {}
+ self._config_value_changed.connect(self._on_config_value_changed)
+ self.refresh()
+
+ @SafeSlot()
+ def refresh(self):
+ """Reset the layout for currently loaded actors"""
+ self._clear()
+ available_actors = self.client.connector.get(ActorEndpoints.available_actor_config_eps())
+ if not isinstance(available_actors, AvailableResourceMessage):
+ logger.warning("No available MX actors registered")
+ self._layout.addWidget(QLabel("No available MX actors registered"), 0, 0, 1, 2)
+ return
+ for row, (name, ep) in enumerate(available_actors.resource["endpoints"].items()):
+ config_value: RedisConfigValue[bool] = RedisConfigValue(
+ connector=self.client.connector, endpoint=ep, wait_for_writes=False
+ )
+ toggle = ToggleSwitch(parent=self, checked=config_value.value)
+ toggle.stateChanged.connect(functools.partial(self._set_config_value, name))
+ callback = functools.partial(self._config_value_changed.emit, name)
+ config_value.subscribe(callback)
+ self._toggles[name] = toggle
+ self._config_values[name] = config_value
+ self._config_callbacks[name] = callback
+ self._layout.addWidget(QLabel(name, parent=self), row, 0)
+ self._layout.addWidget(toggle, row, 1)
+
+ def _set_config_value(self, name: str, enabled: bool):
+ self._config_values[name].value = enabled
+
+ @SafeSlot(str, bool)
+ def _on_config_value_changed(self, name: str, enabled: bool):
+ if (toggle := self._toggles.get(name)) is None:
+ return
+ # Don't write the value we just received straight back to Redis.
+ toggle.blockSignals(True)
+ toggle.setChecked(enabled)
+ toggle.blockSignals(False)
+
+ def _clear(self):
+ for config_value in self._config_values.values():
+ config_value.unregister_all()
+ self._config_values.clear()
+ self._config_callbacks.clear()
+ self._toggles.clear()
+ while (item := self._layout.takeAt(0)) is not None:
+ if (widget := item.widget()) is not None:
+ widget.deleteLater()
+
+ def cleanup(self):
+ self._clear()
+ super().cleanup()
diff --git a/mx_bec/bec_widgets/widgets/aare_bec/sample_queue.py b/mx_bec/bec_widgets/widgets/aare_bec/sample_queue.py
new file mode 100644
index 0000000..d3a7f11
--- /dev/null
+++ b/mx_bec/bec_widgets/widgets/aare_bec/sample_queue.py
@@ -0,0 +1,117 @@
+from __future__ import annotations
+
+from bec_lib.config_values import RedisConfigValue
+from bec_lib.logger import bec_logger
+from bec_lib.serialization import MsgpackSerialization
+from bec_widgets.utils.bec_connector import ConnectionConfig
+from bec_widgets.utils.bec_widget import BECWidget
+from bec_widgets.utils.error_popups import SafeSlot
+from bec_widgets.widgets.utility.toggle.toggle import ToggleSwitch
+from qtpy.QtCore import Signal
+from qtpy.QtWidgets import QHBoxLayout, QLabel, QListWidget, QPushButton, QVBoxLayout, QWidget
+
+from mx_bec.endpoints import QueueEndpoints
+from mx_bec.messages import MXQueueChangedMessage, MXSampleExecutionMessage
+
+logger = bec_logger.logger
+
+
+class SampleQueueWidget(BECWidget, QWidget):
+ """
+ Widget to pause/resume the MX sample queue and show the tasks waiting in it.
+
+ The toggle is bound to the `sample_queue_paused` flag in Redis (checked = running), the list
+ is re-read from the task execution queue whenever the service announces a change on
+ `task_queue_changed`.
+ """
+
+ PLUGIN = True
+ ICON_NAME = "pending_actions"
+ USER_ACCESS = ["refresh", "clear_queue"]
+
+ # Redis callbacks arrive on the connector thread; re-emit so the toggle is updated on the GUI
+ # thread.
+ _paused_changed = Signal(bool)
+
+ def __init__(
+ self,
+ parent: QWidget | None = None,
+ client=None,
+ config: ConnectionConfig | None = None,
+ gui_id: str | None = None,
+ **kwargs,
+ ) -> None:
+ super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs)
+ self._paused: RedisConfigValue[bool] = RedisConfigValue(
+ connector=self.client.connector,
+ endpoint=QueueEndpoints.sample_queue_paused(),
+ wait_for_writes=False,
+ )
+ # RedisConfigValue keeps a weak ref to the subscriber, which must be a bound method
+ self._paused.subscribe(self._emit_paused_changed)
+ self._paused_changed.connect(self._on_paused_changed)
+
+ self._toggle = ToggleSwitch(parent=self, checked=not self._paused.value)
+ self._toggle.stateChanged.connect(self._set_running)
+ self._delete_button = QPushButton("Clear queue")
+ self._delete_button.clicked.connect(self.clear_queue)
+ self._list = QListWidget(parent=self)
+
+ layout = QVBoxLayout(self)
+ header = QHBoxLayout()
+ header.addWidget(QLabel("Sample queue running", parent=self))
+ header.addWidget(self._toggle)
+ header.addWidget(self._delete_button)
+ header.addStretch()
+ layout.addLayout(header)
+ layout.addWidget(QLabel("Queued sample", parent=self))
+ layout.addWidget(self._list)
+
+ # released automatically by BECWidget.cleanup() (disconnect_owner)
+ self.bec_dispatcher.connect_slot(
+ self._on_queue_changed, QueueEndpoints.sample_queue_changed()
+ )
+ self.refresh()
+
+ @SafeSlot()
+ def refresh(self):
+ """Reload the queued samples from Redis."""
+ tasks = self.client.connector.lrange(QueueEndpoints.sample_execution(), 0, -1)
+ self._list.clear()
+ for msg in tasks:
+ try:
+ msg = MsgpackSerialization.loads(msg)
+ except Exception as e:
+ logger.exception(f"failed to decode: {e}")
+ if isinstance(msg, MXSampleExecutionMessage):
+ self._list.addItem(f"{msg.sample_name} (db_id: {msg.db_id})")
+ else:
+ self._list.addItem(str(msg))
+
+ @SafeSlot()
+ def clear_queue(self):
+ """Delete the queue contents"""
+ self.client.connector.delete(QueueEndpoints.sample_execution())
+ self.client.connector.send(QueueEndpoints.sample_queue_changed(), MXQueueChangedMessage())
+
+ @SafeSlot(dict, dict)
+ def _on_queue_changed(self, _content: dict, _metadata: dict):
+ self.refresh()
+
+ def _emit_paused_changed(self, paused: bool):
+ self._paused_changed.emit(paused)
+
+ @SafeSlot(bool)
+ def _set_running(self, running: bool):
+ self._paused.value = not running
+
+ @SafeSlot(bool)
+ def _on_paused_changed(self, paused: bool):
+ # Don't write the value we just received straight back to Redis.
+ self._toggle.blockSignals(True)
+ self._toggle.setChecked(not paused)
+ self._toggle.blockSignals(False)
+
+ def cleanup(self):
+ self._paused.unregister_all()
+ super().cleanup()
diff --git a/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py b/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py
new file mode 100644
index 0000000..8abb2d0
--- /dev/null
+++ b/mx_bec/bec_widgets/widgets/aare_bec/sample_spreadsheet_display.py
@@ -0,0 +1,122 @@
+from __future__ import annotations
+
+from typing import Any
+
+from bec_lib.logger import bec_logger
+from bec_lib.messages import RawMessage
+from bec_widgets.utils.bec_connector import ConnectionConfig
+from bec_widgets.utils.bec_widget import BECWidget, SafeSlot
+from pyqtgraph.Qt.QtWidgets import QPushButton
+from qtpy.QtWidgets import QLabel, QScrollArea, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget
+from redis import RedisError
+
+from mx_bec.endpoints import QueueEndpoints
+from mx_bec.messages import MXQueueChangedMessage, MXSampleExecutionMessage
+
+logger = bec_logger.logger
+
+
+class SampleSpreadsheetDisplay(BECWidget, QWidget):
+ """
+ Display information from the sample spreadsheet
+ """
+
+ PLUGIN = True
+ ICON_NAME = "format_list_bulleted"
+
+ def __init__(
+ self,
+ parent: QWidget | None = None,
+ client=None,
+ config: ConnectionConfig | None = None,
+ gui_id: str | None = None,
+ **kwargs,
+ ) -> None:
+ super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs)
+ self._data: dict[str, Any]
+ self._layout = QVBoxLayout(self)
+ self._layout.addWidget(QLabel(" Sample spreadhseet data: "))
+
+ self._add_selected_button = QPushButton("Add selected to queue")
+ self._layout.addWidget(self._add_selected_button)
+ self._add_selected_button.clicked.connect(self._add_selected)
+ # self._layout_area = QScrollArea()
+ # self._layout.addWidget(self._layout_area)
+
+ dict_data = [{}]
+ try:
+ data = self.client.connector._managed_connection.get("x10sa:sample_spreadsheet")
+ if isinstance(data, RawMessage):
+ dict_data: list[dict[str, Any]] = data.data["s"]
+ else:
+ dict_data = [{"text": str(data)}]
+ except RedisError:
+ logger.exception("No data obtained")
+ dict_data = [{"data": "none"}]
+ self.data = dict_data
+ self._table = self._dicts_to_table_widget(dict_data)
+ # self._layout_area.setWidget(self._table)
+ # self._layout_area.adjustSize()
+ self._layout.addWidget(self._table)
+ self._table.adjustSize()
+ logger.info(f"Successfully updated sample spreadsheet e.g. {dict_data[0]}...")
+
+ @SafeSlot(int, str)
+ def _request(self, db_id, name):
+ self.client.connector.lpush(
+ QueueEndpoints.sample_execution(),
+ MXSampleExecutionMessage(db_id=db_id, sample_name=name),
+ )
+ self.client.connector.send(QueueEndpoints.sample_queue_changed(), MXQueueChangedMessage())
+
+ @SafeSlot()
+ def _add_selected(self):
+ selection = self._table.selectionModel()
+ rows = [id.row() for id in selection.selectedRows()]
+ logger.info(f"Adding selected rows: {rows} to queue")
+ ids: list[tuple[int, str]] = [
+ (self.data[row].get("db_id"), self.data[row].get("sample_name")) for row in rows
+ ]
+ logger.info(f"Adding samples: {ids} to queue")
+ for id in ids:
+ self.client.connector.lpush(
+ QueueEndpoints.sample_execution(),
+ MXSampleExecutionMessage(db_id=id[0], sample_name=id[1]),
+ )
+ self.client.connector.send(QueueEndpoints.sample_queue_changed(), MXQueueChangedMessage())
+
+ def _req_button(self, db_id, name):
+ if not isinstance(db_id, int):
+ return "No id!"
+ button = QPushButton("Add to queue")
+ button.clicked.connect(lambda: self._request(db_id, name))
+ return button
+
+ def _dicts_to_table_widget(self, data: list[dict]) -> QTableWidget:
+ if not data:
+ return QTableWidget(1, 1)
+
+ headers = ["Add to queue", *set(k for item in data for k in item.keys())]
+ if "aaredb_params" in headers:
+ headers.remove("aaredb_params")
+
+ rows = [
+ [
+ self._req_button(row.get("db_id"), row.get("sample_name", "")),
+ *(row.get(h, "") for h in headers),
+ ]
+ for row in data
+ ]
+ n_rows = len(rows)
+ n_cols = len(headers)
+ table = QTableWidget(len(rows), len(headers))
+ table.setHorizontalHeaderLabels(headers)
+ for i in range(n_rows):
+ for j in range(n_cols):
+ item = rows[i][j]
+ if isinstance(item, QWidget):
+ table.setCellWidget(i, j, item)
+ else:
+ table.setItem(i, j, QTableWidgetItem(str(item)))
+
+ return table
diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py
new file mode 100644
index 0000000..23e5ce4
--- /dev/null
+++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py
@@ -0,0 +1,172 @@
+from __future__ import annotations
+
+from bec_lib.logger import bec_logger
+from bec_widgets.utils.bec_connector import ConnectionConfig
+from bec_widgets.utils.bec_widget import BECWidget
+from bec_widgets.utils.error_popups import SafeSlot
+from qtpy.QtWidgets import (
+ QDoubleSpinBox,
+ QFormLayout,
+ QGridLayout,
+ QGroupBox,
+ QHBoxLayout,
+ QLabel,
+ QLineEdit,
+ QPushButton,
+ QScrollArea,
+ QSpinBox,
+ QVBoxLayout,
+ QWidget,
+)
+
+from mx_bec.device_planner import BeamlineState
+from mx_bec.tasks import Client, MxTasks
+
+logger = bec_logger.logger
+
+# Hard-coded forms: task name -> [(argument, default value)]; the widget type follows the default.
+TASK_FORMS: dict[str, list[tuple[str, int | float | str | list[float]]]] = {
+ "aaredaq_mount_sample": [("dbid", 0)],
+ "run_optical_centering": [("sample_id", 0)],
+ "cleanup_beamline": [],
+ # the AareDAQ-driven tasks; their bool/optional arguments keep their defaults here
+ "aaredaq_raster_scan": [
+ ("n_x", 4),
+ ("n_y", 3),
+ ("step_x_mm", 0.05),
+ ("step_y_mm", 0.05),
+ ("exp_time_s", 0.1),
+ ("omega_deg", 0.0),
+ ("dtz", 250),
+ ("file_prefix", "AareBecTestGridScan"),
+ ],
+ "multiple_rasters": [
+ ("omegas_deg_list", [0, 45, 60, 90, 120, 135]),
+ ("n_x", 10),
+ ("n_y", 10),
+ ("step_x_mm", 0.02),
+ ("step_y_mm", 0.015),
+ ("exp_time_s", 0.01),
+ ("dtz", 200),
+ ("file_prefix", "AareBecTestGridScan"),
+ ],
+ "aaredaq_rotation_scan": [
+ ("exp_time_s", 0.05),
+ ("incr_omega_deg", 0.1),
+ ("steps", 100),
+ ("start_omega_deg", 0.0),
+ ],
+}
+
+
+class MxTaskPanel(BECWidget, QWidget):
+ """
+ Testing panel to submit tasks to the AareBec task request stream: one hard-coded form and
+ "Run" button per task (see `TASK_FORMS`).
+ """
+
+ PLUGIN = True
+ ICON_NAME = "play_arrow"
+ USER_ACCESS = ["request_task"]
+ STATE_BUTTONS_PER_ROW = 4
+
+ def __init__(
+ self,
+ parent: QWidget | None = None,
+ client=None,
+ config: ConnectionConfig | None = None,
+ gui_id: str | None = None,
+ **kwargs,
+ ) -> None:
+ super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs)
+ self._tasks = MxTasks[Client](self.client)
+ self._inputs: dict[str, dict[str, QSpinBox | QDoubleSpinBox | QLineEdit]] = {}
+ # all the forms live in a scrollable content widget
+ content = QWidget()
+ layout = QVBoxLayout(content)
+ for task, fields in TASK_FORMS.items():
+ layout.addWidget(self._task_box(content, task, fields))
+ layout.addWidget(self._change_state_box(content))
+ layout.addStretch()
+ scroll = QScrollArea(parent=self)
+ scroll.setWidgetResizable(True)
+ scroll.setWidget(content)
+ outer = QVBoxLayout(self)
+ outer.setContentsMargins(0, 0, 0, 0)
+ outer.addWidget(scroll)
+
+ def _change_state_box(self, parent: QWidget) -> QGroupBox:
+ """One button per beamline state, each requesting the `change_state` task."""
+ box = QGroupBox("change_state", parent=parent)
+ grid = QGridLayout(box)
+ for i, state in enumerate(BeamlineState):
+ button = QPushButton(state.value, parent=box)
+ button.clicked.connect(
+ lambda *_, state=state.value: self.request_task("change_state", state=state)
+ )
+ grid.addWidget(button, i // self.STATE_BUTTONS_PER_ROW, i % self.STATE_BUTTONS_PER_ROW)
+ return box
+
+ def _task_box(
+ self, parent: QWidget, task: str, fields: list[tuple[str, int | float | str | list[float]]]
+ ) -> QGroupBox:
+ box = QGroupBox(task, parent=parent)
+ form = QFormLayout()
+ if (task_fn := getattr(MxTasks, task, None)) is not None:
+ if (doc := task_fn.__doc__) is not None:
+ form.addWidget(QLabel(doc))
+ self._inputs[task] = {}
+ for name, default in fields:
+ widget = self._input(box, default)
+ form.addRow(name, widget)
+ self._inputs[task][name] = widget
+ run = QPushButton("Run", parent=box)
+ run.clicked.connect(lambda *_, task=task: self._run(task))
+ layout = QHBoxLayout(box)
+ layout.addLayout(form)
+ layout.addWidget(run)
+ return box
+
+ @staticmethod
+ def _input(
+ parent: QWidget, default: int | float | str | list[float]
+ ) -> QSpinBox | QDoubleSpinBox | QLineEdit:
+ if isinstance(default, bool) or isinstance(default, str):
+ return QLineEdit(str(default), parent=parent)
+ if isinstance(default, list):
+ return QLineEdit(str(default).strip("[]"), parent=parent)
+ if isinstance(default, int):
+ box = QSpinBox(parent=parent)
+ box.setRange(0, 1_000_000)
+ box.setValue(default)
+ return box
+ box = QDoubleSpinBox(parent=parent)
+ box.setDecimals(6)
+ box.setRange(-1e15, 1e15)
+ box.setValue(default)
+ return box
+
+ def _parse_text(self, task: str, name: str, text: str):
+ inputs = {k: v for k, v in TASK_FORMS[task]}
+ if isinstance(inputs.get(name), list):
+ return [float(ang.strip()) for ang in text.split(",")]
+ return text
+
+ def _values(self, task: str) -> dict[str, int | float | str | list[float]]:
+ return {
+ name: (
+ self._parse_text(task, name, widget.text())
+ if isinstance(widget, QLineEdit)
+ else widget.value()
+ )
+ for name, widget in self._inputs[task].items()
+ }
+
+ @SafeSlot(str)
+ def _run(self, task: str):
+ self.request_task(task, **self._values(task))
+
+ @SafeSlot(str)
+ def request_task(self, name: str, *args, **kwargs):
+ """Submit a task request to the AareBec service."""
+ self._tasks.request(name, *args, **kwargs)
diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py b/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py
new file mode 100644
index 0000000..6a51a13
--- /dev/null
+++ b/mx_bec/bec_widgets/widgets/aare_bec/task_queue.py
@@ -0,0 +1,133 @@
+from __future__ import annotations
+
+from bec_lib.config_values import RedisConfigValue
+from bec_lib.logger import bec_logger
+from bec_widgets.utils.bec_connector import ConnectionConfig
+from bec_widgets.utils.bec_widget import BECWidget
+from bec_widgets.utils.error_popups import SafeSlot
+from bec_widgets.widgets.utility.toggle.toggle import ToggleSwitch
+from qtpy.QtCore import Signal
+from qtpy.QtWidgets import QHBoxLayout, QLabel, QListWidget, QPushButton, QVBoxLayout, QWidget
+
+from mx_bec.endpoints import QueueEndpoints
+from mx_bec.messages import MXQueueChangedMessage, MXSampleExecutionMessage, MXTaskExecutionMessage
+
+logger = bec_logger.logger
+
+
+class MxTaskQueueWidget(BECWidget, QWidget):
+ """
+ Widget to pause/resume the MX task queue and show the tasks waiting in it.
+
+ The toggle is bound to the `task_queue_paused` flag in Redis (checked = running), the list
+ is re-read from the task execution queue whenever the service announces a change on
+ `task_queue_changed`.
+ """
+
+ PLUGIN = True
+ ICON_NAME = "pending_actions"
+ USER_ACCESS = ["refresh", "clear_queue", "start_queue"]
+
+ # Redis callbacks arrive on the connector thread; re-emit so the toggle is updated on the GUI
+ # thread.
+ _paused_changed = Signal(bool)
+
+ def __init__(
+ self,
+ parent: QWidget | None = None,
+ client=None,
+ config: ConnectionConfig | None = None,
+ gui_id: str | None = None,
+ **kwargs,
+ ) -> None:
+ super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs)
+ self._paused: RedisConfigValue[bool] = RedisConfigValue(
+ connector=self.client.connector,
+ endpoint=QueueEndpoints.task_queue_paused(),
+ wait_for_writes=False,
+ )
+ # RedisConfigValue keeps a weak ref to the subscriber, which must be a bound method
+ self._paused.subscribe(self._emit_paused_changed)
+ self._paused_changed.connect(self._on_paused_changed)
+
+ self._toggle = ToggleSwitch(parent=self, checked=not self._paused.value)
+ self._toggle.stateChanged.connect(self._set_running)
+ self._delete_button = QPushButton("Clear queue")
+ self._delete_button.clicked.connect(self.clear_queue)
+ self._start_button = QPushButton("Start queue")
+ self._start_button.clicked.connect(self.start_queue)
+ self._list = QListWidget(parent=self)
+
+ layout = QVBoxLayout(self)
+ header = QHBoxLayout()
+ header.addWidget(QLabel("Task queue running", parent=self))
+ header.addWidget(self._toggle)
+ header.addWidget(self._delete_button)
+ header.addStretch()
+ layout.addLayout(header)
+ layout.addWidget(QLabel("Queued tasks", parent=self))
+ layout.addWidget(self._list)
+
+ # released automatically by BECWidget.cleanup() (disconnect_owner)
+ self.bec_dispatcher.connect_slot(
+ self._on_queue_changed, QueueEndpoints.task_queue_changed()
+ )
+ self.refresh()
+
+ @SafeSlot()
+ def refresh(self):
+ """Reload the queued tasks from Redis."""
+ tasks = self.client.connector.lrange(QueueEndpoints.task_execution(), 0, -1)
+ self._list.clear()
+ for msg in tasks:
+ args = ", ".join(
+ [repr(a) for a in msg.args] + [f"{k}={v!r}" for k, v in msg.kwargs.items()]
+ )
+ self._list.addItem(f"{msg.name}({args})")
+
+ @SafeSlot()
+ def clear_queue(self):
+ """Delete the queue contents"""
+ self.client.connector.delete(QueueEndpoints.task_execution())
+ self.client.connector.send(QueueEndpoints.sample_queue_changed(), MXQueueChangedMessage())
+
+ @SafeSlot()
+ def start_queue(self):
+ """Try to start the queue"""
+ queue_len = self.client.connector.llen(QueueEndpoints.sample_execution())
+ if not queue_len:
+ return # TODO: run some kind of cleanup e.g. unmount, gripper park and dry
+ next: MXSampleExecutionMessage = self.client.connector.blocking_list_pop(
+ QueueEndpoints.sample_execution()
+ )
+ self.client.connector.send(QueueEndpoints.sample_queue_changed(), MXQueueChangedMessage())
+ self.client.connector.xadd(
+ QueueEndpoints.task_request(),
+ {
+ "data": MXTaskExecutionMessage(
+ name="aaredaq_mount_sample", args=(next.db_id,), kwargs={}
+ )
+ },
+ )
+
+ @SafeSlot(dict, dict)
+ def _on_queue_changed(self, _content: dict, _metadata: dict):
+ self.refresh()
+
+ def _emit_paused_changed(self, paused: bool):
+ self._paused_changed.emit(paused)
+
+ @SafeSlot(bool)
+ def _set_running(self, running: bool):
+ self._paused.value = not running
+
+ @SafeSlot(bool)
+ def _on_paused_changed(self, paused: bool):
+ # Don't write the value we just received straight back to Redis.
+ self._toggle.blockSignals(True)
+ self._toggle.setChecked(not paused)
+ self._toggle.blockSignals(False)
+
+ def cleanup(self):
+ self._paused.unregister_all()
+ super().cleanup()
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/configs/__init__.py b/mx_bec/configs/__init__.py
new file mode 100644
index 0000000..c1fd95c
--- /dev/null
+++ b/mx_bec/configs/__init__.py
@@ -0,0 +1,50 @@
+from __future__ import annotations
+
+import tempfile
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from bec_lib import plugin_helper
+
+if TYPE_CHECKING:
+ from bec_lib.client import BECClient
+
+MX_DEMO_CONFIG = Path(__file__).parent / "mx_demo_config.yaml"
+# the simulated beamline which the device planner uses if BEAMLINE=SIMULATED
+MX_SIMULATED_DEVICES = Path(__file__).parent / "simulated_devices.yaml"
+MX_SIMULATED_STATES = Path(__file__).parent / "simulated_states.yaml"
+
+PLUGIN_PLACEHOLDER = "${BEC_PLUGIN}"
+
+
+def render_config(config: Path, plugin: str | None = None) -> Path:
+ """Write a copy of a device config in which `${BEC_PLUGIN}` is replaced by the package name
+ of the beamline plugin (by default the one which is installed), and return its path.
+
+ The device server can only load device classes from ophyd_devices or from the installed
+ beamline plugin, so the simulated devices of mx_bec are named in the configs as
+ `${BEC_PLUGIN}.devices.`: the plugin has to re-export them from its `devices` module.
+ """
+ if plugin is None:
+ # raises ValueError unless exactly one beamline plugin is installed
+ plugin = plugin_helper.plugin_package_name()
+ rendered = Path(tempfile.mkdtemp(prefix="mx_bec_config_")) / config.name
+ rendered.write_text(config.read_text().replace(PLUGIN_PLACEHOLDER, plugin))
+ return rendered
+
+
+def _load(client: BECClient, config: Path, force: bool) -> None:
+ if client.config is None:
+ raise RuntimeError("BEC client is not started")
+ client.config.update_session_with_file(str(render_config(config)), force=force)
+
+
+def load_mx_demo_config(client: BECClient, force: bool = False) -> None:
+ """Replace the current BEC session's device config with the simulated MX beamline."""
+ _load(client, MX_DEMO_CONFIG, force)
+
+
+def load_mx_simulated_config(client: BECClient, force: bool = False) -> None:
+ """Replace the current BEC session's device config with the simulated beamline for
+ development, which has the devices the beamline states are made of (BEAMLINE=SIMULATED)."""
+ _load(client, MX_SIMULATED_DEVICES, force)
diff --git a/mx_bec/configs/mx_demo_config.yaml b/mx_bec/configs/mx_demo_config.yaml
new file mode 100644
index 0000000..0323632
--- /dev/null
+++ b/mx_bec/configs/mx_demo_config.yaml
@@ -0,0 +1,108 @@
+############################################################
+# Simulated MX beamline for the AareBEC prototype.
+#
+# Every device here is a simulation: either from ophyd_devices.sim or from
+# mx_bec.devices. The device server can only load the latter through the beamline
+# plugin which is installed (pxi_bec, pxii_bec, pxiii_bec), which has to re-export
+# them from its `devices` module: ${BEC_PLUGIN} stands for that plugin and is filled
+# in when the config is loaded. Load it into a running BEC with
+# from mx_bec.configs import load_mx_demo_config
+# load_mx_demo_config(bec)
+############################################################
+
+############################################################
+####################### Detector ###########################
+############################################################
+
+eiger:
+ readoutPriority: async
+ deviceClass: ophyd_devices.SimCamera
+ deviceConfig:
+ device_access: true
+ deviceTags:
+ - detector
+ enabled: true
+ readOnly: false
+ softwareTrigger: true
+
+############################################################
+##################### Sample stages ########################
+############################################################
+
+# Aerotech rotation stage: x/y/z translation (mm) under the omega rotation axis u (deg).
+aerotech:
+ readoutPriority: baseline
+ deviceClass: ${BEC_PLUGIN}.devices.SimAerotechStage
+ deviceConfig:
+ deviceTags:
+ - sample stage
+ - aerotech
+ enabled: true
+ readOnly: false
+
+# Smargon mini-kappa goniometer head on top of the aerotech: x/y/z (mm), phi/chi (deg).
+gonio:
+ readoutPriority: baseline
+ deviceClass: ${BEC_PLUGIN}.devices.SimGoniometer
+ deviceConfig:
+ deviceTags:
+ - sample stage
+ - goniometer
+ enabled: true
+ readOnly: false
+
+############################################################
+#################### Sample changer ########################
+############################################################
+
+robot:
+ readoutPriority: baseline
+ deviceClass: ${BEC_PLUGIN}.devices.SimSampleChanger
+ deviceConfig:
+ mount_time: 2.0
+ deviceTags:
+ - sample changer
+ enabled: true
+ readOnly: false
+
+############################################################
+################## Beamline conditions #####################
+############################################################
+
+# Settable scalars so that beamline states / actors can be exercised by writing
+# to them from the client, e.g. `dev.ring_current.set(0)` to simulate a beam dump.
+
+ring_current:
+ readoutPriority: monitored
+ deviceClass: ophyd_devices.sim.sim_signals.SetableSignal
+ deviceConfig:
+ value: 400.0
+ deviceTags:
+ - beamline
+ enabled: true
+ readOnly: false
+
+fast_shutter:
+ readoutPriority: baseline
+ deviceClass: ophyd_devices.sim.sim_signals.SetableSignal
+ deviceConfig:
+ value: 0
+ deviceTags:
+ - beamline
+ enabled: true
+ readOnly: false
+
+energy:
+ readoutPriority: baseline
+ deviceClass: ophyd_devices.SimPositioner
+ deviceConfig:
+ delay: 1
+ limits:
+ - 5.0
+ - 20.0
+ tolerance: 0.001
+ update_frequency: 400
+ deviceTags:
+ - beamline
+ enabled: true
+ readOnly: false
diff --git a/mx_bec/configs/simulated_devices.yaml b/mx_bec/configs/simulated_devices.yaml
new file mode 100644
index 0000000..172d934
--- /dev/null
+++ b/mx_bec/configs/simulated_devices.yaml
@@ -0,0 +1,367 @@
+############################################################
+# Simulated MX beamline for development.
+#
+# Used when the BEAMLINE environment variable is set to SIMULATED: the device planner
+# (mx_bec.device_planner) then takes the positions of the sample environment devices from the
+# userParameter entries in this file, and the beamline states from simulated_states.yaml.
+#
+# Every device here is a simulation: either from ophyd_devices.sim or from mx_bec.devices. The
+# device server can only load the latter through the beamline plugin which is installed
+# (pxi_bec, pxii_bec, pxiii_bec), which has to re-export them from its `devices` module:
+# ${BEC_PLUGIN} stands for that plugin and is filled in when the config is loaded. The
+# names and the named positions follow the PXII device config; the positions of the simulated
+# stages are scaled down to fit their travel. Load it into a running BEC with
+# from mx_bec.configs import load_mx_simulated_config
+# load_mx_simulated_config(bec)
+############################################################
+
+############################################################
+####################### Detector ###########################
+############################################################
+
+eiger:
+ readoutPriority: async
+ deviceClass: ophyd_devices.SimCamera
+ deviceConfig:
+ device_access: true
+ deviceTags:
+ - detector
+ enabled: true
+ readOnly: false
+ softwareTrigger: true
+
+det_z:
+ description: Detector distance
+ readoutPriority: baseline
+ deviceClass: ophyd_devices.SimPositioner
+ deviceConfig:
+ delay: 1
+ limits:
+ - 100
+ - 1000
+ tolerance: 0.01
+ update_frequency: 400
+ deviceTags:
+ - sample environment
+ enabled: true
+ readOnly: false
+ userParameter:
+ mse: 800
+ vis: 800
+
+det_cov:
+ description: Detector cover
+ readoutPriority: baseline
+ deviceClass: ophyd_devices.sim.sim_signals.SetableSignal
+ deviceConfig:
+ value: 1
+ deviceTags:
+ - sample environment
+ enabled: true
+ readOnly: false
+ userParameter:
+ close: 1
+ open: 2
+ type: discrete
+ move_method: signal
+
+############################################################
+##################### Sample stages ########################
+############################################################
+
+# Aerotech rotation stage: x/y/z translation (mm) under the omega rotation axis u (deg).
+aerotech:
+ readoutPriority: baseline
+ deviceClass: ${BEC_PLUGIN}.devices.SimAerotechStage
+ deviceConfig:
+ deviceTags:
+ - sample stage
+ - aerotech
+ enabled: true
+ readOnly: false
+ userParameter:
+ tol: 0.01
+ x:
+ in: 0.0
+ out: -2.0
+ safe: -4.0
+ y:
+ mount: 0.0
+ work: -0.03
+ z:
+ mount: 0.0
+ work: -0.01
+ u:
+ mount: 0.0
+ work: 0.0
+
+# Smargon mini-kappa goniometer head on top of the aerotech: x/y/z (mm), phi/chi (deg).
+smargon:
+ readoutPriority: baseline
+ deviceClass: ${BEC_PLUGIN}.devices.SimGoniometer
+ deviceConfig:
+ deviceTags:
+ - sample stage
+ - goniometer
+ enabled: true
+ readOnly: false
+ userParameter:
+ tol: 0.01
+ x:
+ mount: 0.0
+ y:
+ mount: 0.0
+ z:
+ mount: 1.8
+ chi:
+ mount: 0.0
+ phi:
+ mount: 0.0
+
+############################################################
+#################### Sample changer ########################
+############################################################
+
+robot:
+ readoutPriority: baseline
+ deviceClass: ${BEC_PLUGIN}.devices.SimSampleChanger
+ deviceConfig:
+ mount_time: 2.0
+ deviceTags:
+ - sample changer
+ enabled: true
+ readOnly: false
+
+############################################################
+################## Sample environment ######################
+############################################################
+
+# The devices the beamline states are made of. The signals are moved by writing to them
+# (move_method: signal), the positioners with a scan.
+
+bs_z:
+ description: Beamstop distance from the sample
+ readoutPriority: baseline
+ deviceClass: ophyd_devices.SimPositioner
+ deviceConfig:
+ delay: 1
+ limits:
+ - 0
+ - 80
+ tolerance: 0.01
+ update_frequency: 400
+ deviceTags:
+ - sample environment
+ enabled: true
+ readOnly: false
+ userParameter:
+ max_blin: 45.4
+ max_blout: 70
+ min: 13
+ safe: 45.1
+ samp: 16.8
+ work_min: 20
+ type: continuous
+
+bs_pos:
+ description: Beamstop in/out
+ readoutPriority: baseline
+ deviceClass: ophyd_devices.sim.sim_signals.SetableSignal
+ deviceConfig:
+ value: 1
+ deviceTags:
+ - sample environment
+ enabled: true
+ readOnly: false
+ userParameter:
+ in: 1
+ out: 0
+ type: discrete
+ move_method: signal
+
+coll_y:
+ description: Collimator
+ readoutPriority: baseline
+ deviceClass: ophyd_devices.SimPositioner
+ deviceConfig:
+ delay: 1
+ limits:
+ - 0
+ - 50
+ tolerance: 0.01
+ update_frequency: 400
+ deviceTags:
+ - sample environment
+ enabled: true
+ readOnly: false
+ userParameter:
+ in: 39.0
+ intermediate: 32
+ out: 20.0
+ park: 1
+ tol: 0.05
+ type: continuous
+
+diag_y:
+ description: Diagnostics stage with scintillator and diode
+ readoutPriority: baseline
+ deviceClass: ophyd_devices.SimPositioner
+ deviceConfig:
+ delay: 1
+ limits:
+ - 0
+ - 50
+ tolerance: 0.01
+ update_frequency: 400
+ deviceTags:
+ - sample environment
+ enabled: true
+ readOnly: false
+ userParameter:
+ i1: 40.7
+ out: 20.0
+ park: 1
+ scint: 35.74
+ tol: 0.3
+ type: continuous
+
+bl_pos:
+ description: Backlight in/out
+ readoutPriority: baseline
+ deviceClass: ophyd_devices.sim.sim_signals.SetableSignal
+ deviceConfig:
+ value: 0
+ deviceTags:
+ - sample environment
+ enabled: true
+ readOnly: false
+ userParameter:
+ in: 1
+ out: 0
+ type: discrete
+ move_method: signal
+
+bl_bright:
+ description: Backlight brightness
+ readoutPriority: baseline
+ deviceClass: ophyd_devices.sim.sim_signals.SetableSignal
+ deviceConfig:
+ value: 0.0
+ deviceTags:
+ - sample environment
+ enabled: true
+ readOnly: false
+ userParameter:
+ "off": 0.0
+ "on": 1.3
+ tol: 0.01
+ type: continuous
+ move_method: signal
+
+fl_bright:
+ description: Front light brightness
+ readoutPriority: baseline
+ deviceClass: ophyd_devices.sim.sim_signals.SetableSignal
+ deviceConfig:
+ value: 0.0
+ deviceTags:
+ - sample environment
+ enabled: true
+ readOnly: false
+ userParameter:
+ "off": 0.0
+ "on": 3.0
+ tol: 0.01
+ type: continuous
+ move_method: signal
+
+cryo_pos:
+ description: Cryojet in/out
+ readoutPriority: baseline
+ deviceClass: ophyd_devices.sim.sim_signals.SetableSignal
+ deviceConfig:
+ value: 1
+ deviceTags:
+ - sample environment
+ enabled: true
+ readOnly: false
+ userParameter:
+ in: 1
+ out: 0
+ type: discrete
+ move_method: signal
+
+xrf_pos:
+ description: Fluorescence detector in/out
+ readoutPriority: baseline
+ deviceClass: ophyd_devices.sim.sim_signals.SetableSignal
+ deviceConfig:
+ value: 0
+ deviceTags:
+ - sample environment
+ enabled: true
+ readOnly: false
+ userParameter:
+ in: 1
+ out: 0
+ type: discrete
+ move_method: signal
+
+############################################################
+################## Beamline conditions #####################
+############################################################
+
+# The fast shutter, which the planner closes before it moves anything.
+bcu_shutter:
+ readoutPriority: baseline
+ deviceClass: ophyd_devices.sim.sim_signals.SetableSignal
+ deviceConfig:
+ value: 0
+ deviceTags:
+ - beamline
+ enabled: true
+ readOnly: false
+
+# The sample camera zoom, which the optical centering sets and reads back.
+scam_zoom:
+ readoutPriority: baseline
+ deviceClass: ophyd_devices.SimPositioner
+ deviceConfig:
+ delay: 1
+ limits:
+ - 1
+ - 1000
+ tolerance: 0.5
+ update_frequency: 400
+ deviceTags:
+ - beamline
+ enabled: true
+ readOnly: false
+
+# Settable scalars so that beamline states / actors can be exercised by writing
+# to them from the client, e.g. `dev.ring_current.set(0)` to simulate a beam dump.
+
+ring_current:
+ readoutPriority: monitored
+ deviceClass: ophyd_devices.sim.sim_signals.SetableSignal
+ deviceConfig:
+ value: 400.0
+ deviceTags:
+ - beamline
+ enabled: true
+ readOnly: false
+
+energy:
+ readoutPriority: baseline
+ deviceClass: ophyd_devices.SimPositioner
+ deviceConfig:
+ delay: 1
+ limits:
+ - 5.0
+ - 20.0
+ tolerance: 0.001
+ update_frequency: 400
+ deviceTags:
+ - beamline
+ enabled: true
+ readOnly: false
diff --git a/mx_bec/configs/simulated_states.yaml b/mx_bec/configs/simulated_states.yaml
new file mode 100644
index 0000000..41d75d4
--- /dev/null
+++ b/mx_bec/configs/simulated_states.yaml
@@ -0,0 +1,196 @@
+############################################################
+# Beamline states of the simulated MX beamline (BEAMLINE=SIMULATED): for every state, the named
+# position of each sample environment device. The positions themselves are the userParameter
+# entries in simulated_devices.yaml.
+#
+# Follows the PXII beamline states.
+############################################################
+
+states:
+ robot_sample_exchange:
+ allow_modifiers: true
+ bl_pos: in
+ bl_bright: 'off'
+ bs_pos: in
+ bs_z: safe
+ coll_y: out
+ cryo_pos: in
+ det_cov: close
+ diag_y: out
+ fl_bright: 'off'
+ aerotech_x: in
+ aerotech_y: mount
+ aerotech_z: mount
+ aerotech_u: mount
+ smargon_x: mount
+ smargon_y: mount
+ smargon_z: mount
+ smargon_chi: mount
+ smargon_phi: mount
+ xrf_pos: out
+
+ sample_alignment:
+ allow_modifiers: true
+ bl_pos: in
+ bl_bright: 'on'
+ bs_pos: in
+ bs_z: safe
+ coll_y: out
+ cryo_pos: in
+ det_cov: close
+ diag_y: out
+ fl_bright: 'on'
+ aerotech_x: in
+ xrf_pos: out
+
+ data_collection:
+ allow_modifiers: true
+ bl_pos: out
+ bl_bright: 'off'
+ bs_pos: in
+ bs_z: safe
+ coll_y: in
+ cryo_pos: in
+ det_cov: open
+ diag_y: out
+ fl_bright: 'on'
+ aerotech_x: in
+ xrf_pos: out
+
+ DC_XRF:
+ allow_modifiers: true
+ bl_bright: 'off'
+ bs_pos: in
+ bs_z: safe
+ coll_y: in
+ cryo_pos: in
+ det_cov: close
+ diag_y: out
+ fl_bright: 'on'
+ aerotech_x: in
+ aerotech_y: work
+ aerotech_z: work
+ aerotech_u: mount
+ xrf_pos: out
+
+ manual_sample_exchange:
+ allow_modifiers: true
+ bl_pos: out
+ bl_bright: 'off'
+ bs_pos: out
+ bs_z: safe
+ coll_y: park
+ cryo_pos: in
+ det_cov: close
+ det_z: mse
+ diag_y: park
+ fl_bright: 'off'
+ aerotech_x: in
+ aerotech_y: mount
+ aerotech_z: mount
+ aerotech_u: mount
+ smargon_x: mount
+ smargon_y: mount
+ smargon_chi: mount
+ smargon_phi: mount
+ xrf_pos: out
+
+ beam_visualisation:
+ bl_pos: out
+ bl_bright: 'off'
+ bs_pos: in
+ bs_z: safe
+ coll_y: out
+ cryo_pos: out
+ det_cov: close
+ diag_y: scint
+ fl_bright: 'off'
+ aerotech_x: out
+ smargon_x: mount
+ smargon_y: mount
+ smargon_chi: mount
+ smargon_phi: mount
+ xrf_pos: out
+
+ flux_measurement:
+ bl_pos: in
+ bl_bright: 'off'
+ bs_pos: in
+ bs_z: safe
+ coll_y: out
+ cryo_pos: out
+ det_cov: close
+ diag_y: i1
+ fl_bright: 'off'
+ aerotech_x: out
+ smargon_x: mount
+ smargon_y: mount
+ smargon_chi: mount
+ smargon_phi: mount
+ xrf_pos: out
+
+ beamstop_alignment:
+ bl_pos: out
+ bl_bright: 'off'
+ bs_pos: in
+ bs_z: samp
+ coll_y: out
+ cryo_pos: out
+ det_cov: close
+ diag_y: out
+ fl_bright: 'on'
+ aerotech_x: out
+ aerotech_u: mount
+ smargon_x: mount
+ smargon_y: mount
+ smargon_chi: mount
+ smargon_phi: mount
+ xrf_pos: out
+
+ maintenance:
+ allow_modifiers: true
+ bl_pos: out
+ bl_bright: 'off'
+ bs_pos: out
+ bs_z: safe
+ coll_y: park
+ cryo_pos: in
+ det_cov: close
+ diag_y: park
+ fl_bright: 'off'
+ aerotech_x: out
+ aerotech_y: mount
+ aerotech_z: mount
+ aerotech_u: mount
+ smargon_x: mount
+ smargon_y: mount
+ smargon_chi: mount
+ smargon_phi: mount
+ xrf_pos: out
+
+ xtal_snapshot:
+ allow_modifiers: true
+ bl_pos: in
+ bl_bright: 'on'
+ bs_pos: in
+ bs_z: safe
+ coll_y: intermediate
+ cryo_pos: in
+ det_cov: close
+ diag_y: out
+ fl_bright: 'on'
+ xrf_pos: out
+
+ det_diode:
+ allow_modifiers: true
+ bl_pos: out
+ bl_bright: 'off'
+ bs_pos: in
+ bs_z: safe
+ coll_y: out
+ cryo_pos: in
+ det_cov: close
+ diag_y: out
+ fl_bright: 'off'
+ aerotech_x: in
+ xrf_pos: out
diff --git a/mx_bec/constants.py b/mx_bec/constants.py
new file mode 100644
index 0000000..3e88485
--- /dev/null
+++ b/mx_bec/constants.py
@@ -0,0 +1,6 @@
+from enum import StrEnum
+
+
+class AareBecWorkflowState(StrEnum):
+ IDLE = "IDLE"
+ SAMPLE_MOUNTED = "SAMPLE_MOUNTED"
diff --git a/mx_bec/decisions/__init__.py b/mx_bec/decisions/__init__.py
new file mode 100644
index 0000000..bcbbd36
--- /dev/null
+++ b/mx_bec/decisions/__init__.py
@@ -0,0 +1,84 @@
+"""Decision logic for the self-driving MX sequence.
+
+ 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. 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.
+
+Per-image inputs are duck-typed against ``jfjoch_client.models.ScanResultImagesInner``
+(``number``, ``nx``, ``ny``, ``angle``, ``spots``, ``spots_indexed``, ``ice``, ``res``,
+``latt_count``, ``spindle_blind``), so plain objects or the jfjoch models both work.
+
+`core` has the configuration and the records, `grid_scans` the analysis of a raster, `rotations`
+the planning, assessment and follow-up of rotation datasets.
+"""
+
+from mx_bec.decisions.core import (
+ HC_KEV_A,
+ Assessment,
+ BeamState,
+ CollectionRecord,
+ GridGeometry,
+ Issue,
+ RasterRecord,
+ RotationPlan,
+ StrategyConfig,
+ SweepRecord,
+ scan_images,
+ smargon_nudge,
+)
+from mx_bec.decisions.grid_scans import (
+ Cell,
+ CrystalRegion,
+ GridAnalysis,
+ analyse_grid,
+ cell_score,
+ gridscan_calculation,
+ gridscan_strategy_from_optical,
+ mock_grid_calculation,
+ pick_positions,
+)
+from mx_bec.decisions.rotations import (
+ Action,
+ Decision,
+ assess_collection,
+ assess_sweep,
+ decide_followup,
+ detector_distance_mm,
+ dose_rate_MGy_s,
+ plan_rotation,
+)
+
+__all__ = [
+ "HC_KEV_A",
+ "Action",
+ "Assessment",
+ "BeamState",
+ "Cell",
+ "CollectionRecord",
+ "CrystalRegion",
+ "Decision",
+ "GridAnalysis",
+ "GridGeometry",
+ "Issue",
+ "RasterRecord",
+ "RotationPlan",
+ "StrategyConfig",
+ "SweepRecord",
+ "analyse_grid",
+ "assess_collection",
+ "assess_sweep",
+ "cell_score",
+ "decide_followup",
+ "detector_distance_mm",
+ "gridscan_calculation",
+ "gridscan_strategy_from_optical",
+ "mock_grid_calculation",
+ "dose_rate_MGy_s",
+ "pick_positions",
+ "plan_rotation",
+ "scan_images",
+ "smargon_nudge",
+]
diff --git a/mx_bec/decisions/core.py b/mx_bec/decisions/core.py
new file mode 100644
index 0000000..12c0b45
--- /dev/null
+++ b/mx_bec/decisions/core.py
@@ -0,0 +1,241 @@
+"""Shared by the decisions: constants, the strategy configuration, the records of what was
+measured, which are kept on `SampleInfo` between the actors, and the smargon geometry."""
+
+from __future__ import annotations
+
+from enum import Enum
+from typing import Any
+
+import numpy as np
+from aarecommon.math.coordinate import Coordinate
+from pydantic import BaseModel, ConfigDict, Field
+
+HC_KEV_A = 12.398419843320026 # keV * Angstrom
+
+
+# --------------------------------------------------------------------------------------------
+# Configuration
+# --------------------------------------------------------------------------------------------
+
+
+class BeamState(BaseModel):
+ """Beam at the sample. ``flux_ph_s`` is at transmission 1."""
+
+ energy_keV: float = Field(12.4, gt=0)
+ flux_ph_s: float | None = Field(None, gt=0, description="Must be set; no dose plan without it")
+ beam_size_um: tuple[float, float] = (25.0, 25.0)
+
+ @property
+ def wavelength_A(self) -> float:
+ return HC_KEV_A / self.energy_keV
+
+
+class StrategyConfig(BaseModel):
+ """Every threshold the actors use. Defaults are starting points for the replay study."""
+
+ # grid analysis
+ min_spots_hit: int = Field(10, description="Spots per image for a cell to count as a hit")
+ ice_threshold: float = Field(1.5, description="jfjoch 'ice' ratio above which a cell is icy")
+ ice_penalty: float = 0.5
+ multi_lattice_penalty: float = 0.5
+ reference_res_A: float = Field(2.0, description="Resolution at which the score factor is 1")
+ max_positions: int = 4
+ min_spot_separation_mm: float = Field(0.04, description="Beam size plus dose halo")
+ min_position_score_fraction: float = Field(0.3, description="Relative to the best cell")
+
+ # rotation plan
+ beam: BeamState = BeamState()
+ dose_MGy_per_A: float = Field(5.0, description="Dose budget = this x target resolution")
+ photons_per_um2_per_Gy_12p4keV: float = Field(
+ 2000.0,
+ description="Rule-of-thumb fluence per Gy at 12.4 keV, scaled by E^2; replace with "
+ "RADDOSE-3D when the crystal model is available",
+ )
+ total_rotation_deg: float = 360.0
+ oscillation_deg: float = 0.1
+ exp_time_s: float = 0.005
+ min_transmission: float = 0.001
+ resolution_margin: float = Field(0.9, description="Aim this factor beyond the grid estimate")
+ default_res_A: float = 2.5
+ best_res_limit_A: float = 0.8
+ detector_radius_mm: float = Field(150.0, description="Beam centre to nearest detector edge")
+ min_distance_mm: float = 100.0
+ max_distance_mm: float = 1000.0
+
+ # anomalous: low-dose multi-chi from the start
+ anomalous: bool = False
+ anomalous_chi_deg: tuple[float, ...] = (0.0, 15.0, 30.0)
+
+ # assessment
+ n_wedges: int = 10
+ lost_ratio: float = Field(0.3, description="Wedge spots below this x previous max = lost")
+ damage_res_increase: float = Field(0.15, description="Relative d_min loss first->last wedge")
+ min_indexed_spots: int = 10
+ min_indexed_fraction: float = 0.5
+ spindle_blind_threshold: float = Field(0.5, description="jfjoch: >= 0.5 engage recovery")
+ treat_unassessed_blind_as_blind: bool = Field(
+ True, description="jfjoch: an absent spindle_blind must be treated as above threshold"
+ )
+ low_symmetry_bravais: frozenset[str] = frozenset({"aP", "mP", "mC"})
+
+ # follow-up policy
+ max_followups: int = 3
+ max_recentres: int = 1
+ max_chi_sweeps: int = 1
+ chi_offset_deg: float = 30.0
+ damage_dose_fraction: float = 0.5
+ same_position_dose_fraction: float = Field(
+ 0.3, description="Extra dose allowed when a chi sweep must reuse a burnt position"
+ )
+
+
+# --------------------------------------------------------------------------------------------
+# Parameters of the measurements
+# --------------------------------------------------------------------------------------------
+
+
+class GridGeometry(BaseModel):
+ """Raster layout. Cell (0, 0) sits at the raster start position (``smargon_top_left``)."""
+
+ n_x: int = Field(ge=1)
+ n_y: int = Field(ge=1)
+ step_x_mm: float
+ step_y_mm: float
+ omega_deg: float = 0.0
+ snake: bool = True
+
+ def offset_mm(self, ix: int, iy: int) -> tuple[float, float]:
+ return ix * self.step_x_mm, iy * self.step_y_mm
+
+
+class RotationPlan(BaseModel):
+ """Flat parameters for the ``collect_dataset`` task.
+
+ ``MXTaskExecutionMessage`` only carries scalars, so chi values travel as a comma string,
+ like ``multiple_rasters`` does for omegas.
+ """
+
+ position_index: int
+ offset_x_mm: float
+ offset_y_mm: float
+ chi_deg_list: str = "0"
+ start_omega_deg: float = 0.0
+ incr_omega_deg: float
+ steps: int
+ exp_time_s: float
+ transmission: float
+ dtz: float
+ file_prefix: str
+ dose_MGy: float
+ target_res_A: float
+ reason: str = ""
+
+ def chi_values(self) -> list[float]:
+ return [float(v) for v in self.chi_deg_list.split(",") if v.strip()]
+
+
+# --------------------------------------------------------------------------------------------
+# Records kept on SampleInfo between actors
+# --------------------------------------------------------------------------------------------
+
+
+class RasterRecord(BaseModel):
+ model_config = ConfigDict(arbitrary_types_allowed=True)
+
+ strategy: dict[str, Any] = Field(description="Kwargs of the raster, for a repeat")
+ geometry: GridGeometry
+ images: list[Any]
+
+
+class SweepRecord(BaseModel):
+ model_config = ConfigDict(arbitrary_types_allowed=True)
+
+ chi_deg: float
+ images: list[Any]
+ bravais: str | None = None
+
+
+class Issue(str, Enum):
+ LOST_DIFFRACTION = "lost_diffraction"
+ RADIATION_DAMAGE = "radiation_damage"
+ BLIND_REGION = "blind_region"
+ LOW_SYMMETRY = "low_symmetry"
+ WEAK = "weak"
+
+
+class Assessment(BaseModel):
+ issues: list[Issue] = []
+ n_images: int = 0
+ indexed_fraction: float = 0.0
+ wedge_spots: list[float] = []
+ wedge_res_A: list[float | None] = []
+ onset_angle_deg: float | None = None
+ median_spindle_blind: float | None = None
+ bravais: str | None = None
+
+ @property
+ def usable(self) -> bool:
+ return not {Issue.LOST_DIFFRACTION, Issue.WEAK} & set(self.issues)
+
+
+class CollectionRecord(BaseModel):
+ plan: RotationPlan
+ sweeps: list[SweepRecord] = []
+ assessment: Assessment | None = None
+
+
+def scan_images(completed: Any) -> list[Any]:
+ """Per-image Jungfraujoch results from an aarecommon ``Completed*`` model.
+
+ ``CompletedRotationScan`` carries a jfjoch ``ScanResult`` under ``.result``. Check which field
+ ``CompletedRasterGrid`` uses (``tasks.py`` logs ``len(result.r)``) and keep that path first.
+ """
+ for path in (("result", "images"), ("r",), ("images",)):
+ obj = completed
+ for attr in path:
+ obj = getattr(obj, attr, None)
+ if obj is None:
+ break
+ if obj is not None:
+ return list(obj)
+ raise ValueError(f"No per-image results found on {type(completed).__name__}")
+
+
+# --------------------------------------------------------------------------------------------
+# Geometry
+# --------------------------------------------------------------------------------------------
+
+
+def smargon_nudge(
+ phi_deg: float, chi_deg: float, omega_deg: float, nudge_vector: Coordinate
+) -> Coordinate:
+ """Translate a relative movement of the smargon from lab frame to smargon frame.
+ Add the result of this to the smargon's current position to get the new position."""
+ phi = np.radians(np.around(phi_deg, decimals=1))
+ chi = np.radians(np.around(chi_deg, decimals=1))
+ omega = np.radians(np.around(omega_deg, decimals=1))
+
+ offset = Coordinate()
+ co = np.cos(omega)
+ so = np.sin(omega)
+ cp = np.cos(phi)
+ sp = np.sin(phi)
+ cc = np.cos(chi)
+ sc = np.sin(chi)
+
+ offset.x = (
+ -nudge_vector.z * co * sp
+ - nudge_vector.y * so * sp
+ + nudge_vector.x * cp * sc
+ - nudge_vector.y * co * cc * cp
+ + nudge_vector.z * so * cc * cp
+ )
+ offset.y = (
+ -nudge_vector.z * co * cp
+ - nudge_vector.y * so * cp
+ - nudge_vector.x * sc * sp
+ + nudge_vector.y * co * cc * sp
+ - nudge_vector.z * so * cc * sp
+ )
+ offset.z = -nudge_vector.x * cc - nudge_vector.y * co * sc + nudge_vector.z * so * sc
+ return offset
diff --git a/mx_bec/decisions/grid_scans.py b/mx_bec/decisions/grid_scans.py
new file mode 100644
index 0000000..5fe2386
--- /dev/null
+++ b/mx_bec/decisions/grid_scans.py
@@ -0,0 +1,282 @@
+"""Grid scans: work out the grid to scan from the optical centering results, find the crystals
+in the per-cell results of a raster and pick the spots to collect data at."""
+
+from __future__ import annotations
+
+import math
+import secrets
+import statistics
+from collections.abc import Iterable, Sequence
+from typing import TYPE_CHECKING, Any
+
+from aarecommon.models.raster_grid import CompletedRasterGridElem
+from bec_lib.logger import bec_logger
+from pydantic import BaseModel, ConfigDict, Field
+
+from mx_bec.decisions.core import GridGeometry, StrategyConfig
+
+if TYPE_CHECKING:
+ from mx_bec.sample_info import OpticalCenteringResults
+
+logger = bec_logger.logger
+
+
+# --------------------------------------------------------------------------------------------
+# Strategy: which grid to scan
+# --------------------------------------------------------------------------------------------
+
+
+def mock_grid_calculation():
+ logger.info("calculating mock grid given no optical results ...")
+ n_x = 10
+ n_y = 10
+ step_x_mm = 0.05
+ step_y_mm = 0.05
+ strategy = {
+ "n_x": n_x,
+ "n_y": n_y,
+ "step_x_mm": step_x_mm,
+ "step_y_mm": step_y_mm,
+ "exp_time_s": 0.05,
+ "omega_deg": 0.0,
+ "file_prefix": f"AareBecTestGridScan_{secrets.token_hex(6)}",
+ "dtz": 250,
+ "transmission": 0.2,
+ }
+ return strategy
+
+
+def gridscan_strategy_from_optical(
+ optical_results: OpticalCenteringResults | None,
+ step_x_um: float,
+ step_y_um: float,
+ margin: float,
+ 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}
+ logger.info(f"got detection boxes: {box_data}")
+ box_corners = None
+ for label_option in ["loop_face", "loop_all"]:
+ if label_option in box_data:
+ box_corners = box_data[label_option]
+ logger.info(f"using best available box: {label_option}")
+ break
+ if box_corners is None:
+ return mock_grid_calculation()
+ else:
+ file_prefix = f"AareBecTestGridScan_{secrets.token_hex(6)}"
+ return gridscan_calculation(
+ box_corners[0],
+ box_corners[1],
+ step_x_um / 1000,
+ step_y_um / 1000,
+ margin,
+ file_prefix,
+ exp_time_s,
+ dtz_mm,
+ optical_results.microns_per_pixel,
+ )
+
+
+def gridscan_calculation(
+ x1_y1: tuple[float, float],
+ x2_y2: tuple[float, float],
+ size_x_mm: float,
+ size_y_mm: float,
+ margin: float,
+ 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."""
+ 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 = 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)
+ n_y = int(box_y_microns / 1000 / size_y_mm * margin)
+ return {
+ "n_x": n_x,
+ "n_y": n_y,
+ "step_x_mm": size_x_mm,
+ "step_y_mm": size_y_mm,
+ "exp_time_s": exp_time_s,
+ "file_prefix": file_prefix,
+ "dtz": dtz_mm,
+ }
+
+
+# --------------------------------------------------------------------------------------------
+# Analysis: what the grid found
+# --------------------------------------------------------------------------------------------
+
+
+class Cell(BaseModel):
+ model_config = ConfigDict(frozen=True)
+
+ ix: int
+ iy: int
+ spots: int
+ spots_indexed: int | None = None
+ res_A: float | None = None
+ ice: float | None = None
+ lattices: int | None = None
+ score: float = 0.0
+
+
+class CrystalRegion(BaseModel):
+ cells: list[Cell]
+ best: Cell
+ extent_x_mm: float
+ extent_y_mm: float
+ median_res_A: float | None
+ max_lattices: int
+
+
+class GridAnalysis(BaseModel):
+ geometry: GridGeometry
+ n_images: int
+ n_hits: int
+ regions: list[CrystalRegion]
+ positions: list[Cell] = Field(description="Ranked collection spots, best first")
+
+ def position_offset_mm(self, index: int) -> tuple[float, float]:
+ cell = self.positions[index]
+ return self.geometry.offset_mm(cell.ix, cell.iy)
+
+ def position_res_A(self, index: int) -> float | None:
+ cell = self.positions[index]
+ if cell.res_A:
+ return cell.res_A
+ for region in self.regions:
+ if cell in region.cells:
+ return region.median_res_A
+ return None
+
+
+def _cell_index(img: Any, geom: GridGeometry) -> tuple[int, int]:
+ nx, ny = getattr(img, "nx", None), getattr(img, "ny", None)
+ if nx is not None and ny is not None:
+ return int(nx), int(ny)
+ row, col = divmod(int(img.number), geom.n_x)
+ if geom.snake and row % 2:
+ col = geom.n_x - 1 - col
+ return col, row
+
+
+def cell_score(img: Any, cfg: StrategyConfig) -> float:
+ """Indexed spots weighted for resolution, penalised for ice and extra lattices."""
+ spots = img.spots or 0
+ indexed = getattr(img, "spots_indexed", None)
+ base = float(spots) if indexed is None else indexed + 0.25 * max(spots - indexed, 0)
+ ice = getattr(img, "ice", None)
+ if ice is not None and ice > cfg.ice_threshold:
+ base *= cfg.ice_penalty
+ lattices = getattr(img, "latt_count", None)
+ if lattices is not None and lattices > 1:
+ base *= cfg.multi_lattice_penalty
+ res = getattr(img, "res", None)
+ if res:
+ base *= min(2.0, max(0.5, cfg.reference_res_A / res))
+ return base
+
+
+def _regions(cells: dict[tuple[int, int], Cell]) -> list[list[Cell]]:
+ """8-connected components of hit cells."""
+ seen: set[tuple[int, int]] = set()
+ out: list[list[Cell]] = []
+ for start in cells:
+ if start in seen:
+ continue
+ stack, comp = [start], []
+ seen.add(start)
+ while stack:
+ ix, iy = stack.pop()
+ comp.append(cells[(ix, iy)])
+ for dx in (-1, 0, 1):
+ for dy in (-1, 0, 1):
+ nb = (ix + dx, iy + dy)
+ if nb in cells and nb not in seen:
+ seen.add(nb)
+ stack.append(nb)
+ out.append(comp)
+ return out
+
+
+def _distance_mm(a: Cell, b: Cell, geom: GridGeometry) -> float:
+ return math.hypot((a.ix - b.ix) * geom.step_x_mm, (a.iy - b.iy) * geom.step_y_mm)
+
+
+def pick_positions(
+ regions: Sequence[CrystalRegion], geom: GridGeometry, cfg: StrategyConfig
+) -> list[Cell]:
+ """Best cell of each crystal first, then further spots spaced beyond the dose halo."""
+ if not regions:
+ return []
+ top = max(r.best.score for r in regions)
+ floor = cfg.min_position_score_fraction * top
+ ordered = [r.best for r in regions] + sorted(
+ (c for r in regions for c in r.cells), key=lambda c: c.score, reverse=True
+ )
+ chosen: list[Cell] = []
+ for cell in ordered:
+ if len(chosen) >= cfg.max_positions:
+ break
+ if cell.score < floor or cell in chosen:
+ continue
+ if all(_distance_mm(cell, c, geom) >= cfg.min_spot_separation_mm for c in chosen):
+ chosen.append(cell)
+ return chosen
+
+
+def analyse_grid(
+ results: Iterable[CompletedRasterGridElem], geom: GridGeometry, cfg: StrategyConfig
+) -> GridAnalysis:
+ results = list(results)
+ logger.info(f"analyze_grid got {len(results)} results.")
+ images = results[0].result.images
+ hits: dict[tuple[int, int], Cell] = {}
+ for img in images:
+ if (img.spots or 0) < cfg.min_spots_hit:
+ continue
+ ix, iy = _cell_index(img, geom)
+ hits[(ix, iy)] = Cell(
+ ix=ix,
+ iy=iy,
+ spots=img.spots,
+ spots_indexed=getattr(img, "spots_indexed", None),
+ res_A=getattr(img, "res", None),
+ ice=getattr(img, "ice", None),
+ lattices=getattr(img, "latt_count", None),
+ score=cell_score(img, cfg),
+ )
+ regions = []
+ for comp in _regions(hits):
+ xs, ys = [c.ix for c in comp], [c.iy for c in comp]
+ res = [c.res_A for c in comp if c.res_A]
+ regions.append(
+ CrystalRegion(
+ cells=sorted(comp, key=lambda c: c.score, reverse=True),
+ best=max(comp, key=lambda c: (c.score, -(c.res_A or 99.0))),
+ extent_x_mm=(max(xs) - min(xs) + 1) * abs(geom.step_x_mm),
+ extent_y_mm=(max(ys) - min(ys) + 1) * abs(geom.step_y_mm),
+ median_res_A=statistics.median(res) if res else None,
+ max_lattices=max((c.lattices or 1) for c in comp),
+ )
+ )
+ regions.sort(key=lambda r: r.best.score, reverse=True)
+ return GridAnalysis(
+ geometry=geom,
+ n_images=len(images),
+ n_hits=len(hits),
+ regions=regions,
+ positions=pick_positions(regions, geom, cfg),
+ )
diff --git a/mx_bec/decisions/rotations.py b/mx_bec/decisions/rotations.py
new file mode 100644
index 0000000..e596444
--- /dev/null
+++ b/mx_bec/decisions/rotations.py
@@ -0,0 +1,259 @@
+"""Rotations: plan a rotation dataset at a spot of the grid, assess what was collected and
+decide how to follow it up."""
+
+from __future__ import annotations
+
+import math
+import statistics
+from collections.abc import Sequence
+from enum import Enum
+from typing import TYPE_CHECKING, Any
+
+from pydantic import BaseModel
+
+from mx_bec.decisions.core import (
+ Assessment,
+ BeamState,
+ CollectionRecord,
+ Issue,
+ RotationPlan,
+ StrategyConfig,
+)
+from mx_bec.decisions.grid_scans import GridAnalysis
+
+if TYPE_CHECKING:
+ from mx_bec.sample_info import SampleInfo
+
+
+# --------------------------------------------------------------------------------------------
+# Planning
+# --------------------------------------------------------------------------------------------
+
+
+def detector_distance_mm(res_A: float, beam: BeamState, cfg: StrategyConfig) -> float:
+ """Distance that puts ``res_A`` at the nearest detector edge."""
+ s = beam.wavelength_A / (2.0 * res_A)
+ if s >= 1.0:
+ return cfg.min_distance_mm
+ two_theta = 2.0 * math.asin(s)
+ distance = cfg.detector_radius_mm / math.tan(two_theta)
+ return min(cfg.max_distance_mm, max(cfg.min_distance_mm, distance))
+
+
+def dose_rate_MGy_s(beam: BeamState, cfg: StrategyConfig, transmission: float = 1.0) -> float:
+ if beam.flux_ph_s is None:
+ raise ValueError("BeamState.flux_ph_s is not set; refusing to plan a dose")
+ area_um2 = beam.beam_size_um[0] * beam.beam_size_um[1]
+ photons_per_um2_per_Gy = cfg.photons_per_um2_per_Gy_12p4keV * (beam.energy_keV / 12.4) ** 2
+ return beam.flux_ph_s * transmission / area_um2 / photons_per_um2_per_Gy / 1e6
+
+
+def plan_rotation(
+ analysis: GridAnalysis,
+ position_index: int,
+ cfg: StrategyConfig,
+ *,
+ file_prefix: str,
+ chi_values: Sequence[float] = (0.0,),
+ dose_fraction: float = 1.0,
+ reason: str = "",
+) -> RotationPlan:
+ """Rotation at one grid position under the ``dose_MGy_per_A`` rule.
+
+ The budget (``dose_fraction`` of the full one) is shared over all chi sweeps, which gives the
+ low-dose multi-chi strategy for anomalous data.
+ """
+ beam = cfg.beam
+ res_est = analysis.position_res_A(position_index) or cfg.default_res_A
+ target = max(cfg.best_res_limit_A, res_est * cfg.resolution_margin)
+ steps = max(1, round(cfg.total_rotation_deg / cfg.oscillation_deg))
+ sweep_time_s = steps * cfg.exp_time_s
+ n_sweeps = max(1, len(chi_values))
+ dose_per_sweep = cfg.dose_MGy_per_A * target * dose_fraction / n_sweeps
+ full_rate = dose_rate_MGy_s(beam, cfg)
+ transmission = dose_per_sweep / (full_rate * sweep_time_s)
+ transmission = min(1.0, max(cfg.min_transmission, transmission))
+ x, y = analysis.position_offset_mm(position_index)
+ return RotationPlan(
+ position_index=position_index,
+ offset_x_mm=x,
+ offset_y_mm=y,
+ chi_deg_list=",".join(f"{c:g}" for c in chi_values),
+ incr_omega_deg=cfg.oscillation_deg,
+ steps=steps,
+ exp_time_s=cfg.exp_time_s,
+ transmission=round(transmission, 5),
+ dtz=round(detector_distance_mm(target, beam, cfg), 1),
+ file_prefix=f"{file_prefix}_p{position_index}",
+ dose_MGy=round(full_rate * transmission * sweep_time_s * n_sweeps, 3),
+ target_res_A=round(target, 2),
+ reason=reason,
+ )
+
+
+# --------------------------------------------------------------------------------------------
+# Assessment and follow-up decision
+# --------------------------------------------------------------------------------------------
+
+
+def _wedges(items: Sequence[Any], n: int) -> list[Sequence[Any]]:
+ n = max(1, min(n, len(items)))
+ size = len(items) / n
+ return [items[round(i * size) : round((i + 1) * size)] for i in range(n)]
+
+
+def assess_sweep(images: Sequence[Any], bravais: str | None, cfg: StrategyConfig) -> Assessment:
+ imgs = sorted(
+ images,
+ key=lambda im: (im.angle if getattr(im, "angle", None) is not None else 0.0, im.number),
+ )
+ if not imgs:
+ return Assessment(issues=[Issue.LOST_DIFFRACTION, Issue.WEAK], bravais=bravais)
+ issues: list[Issue] = []
+ wedges = _wedges(imgs, cfg.n_wedges)
+ wedge_spots = [float(statistics.median([(im.spots or 0) for im in w])) for w in wedges]
+ wedge_res: list[float | None] = []
+ for w in wedges:
+ res = [im.res for im in w if getattr(im, "res", None)]
+ wedge_res.append(statistics.median(res) if res else None)
+
+ # Lost diffraction: a drop below lost_ratio of the running max that never recovers
+ onset = None
+ running_max = wedge_spots[0]
+ for i in range(1, len(wedge_spots)):
+ if running_max >= cfg.min_spots_hit and all(
+ s < cfg.lost_ratio * running_max for s in wedge_spots[i:]
+ ):
+ onset = getattr(wedges[i][0], "angle", None)
+ issues.append(Issue.LOST_DIFFRACTION)
+ break
+ running_max = max(running_max, wedge_spots[i])
+
+ # Radiation damage: d_min of the last wedge worse than the first (same orientation for 360°)
+ first, last = wedge_res[0], wedge_res[-1]
+ if (
+ Issue.LOST_DIFFRACTION not in issues
+ and first
+ and last
+ and (last - first) / first > cfg.damage_res_increase
+ ):
+ issues.append(Issue.RADIATION_DAMAGE)
+
+ indexed = sum(1 for im in imgs if (im.spots_indexed or 0) >= cfg.min_indexed_spots)
+ indexed_fraction = indexed / len(imgs)
+ if indexed_fraction < cfg.min_indexed_fraction:
+ issues.append(Issue.WEAK)
+
+ blind_values = [getattr(im, "spindle_blind", None) for im in imgs]
+ median_blind = None
+ if any(v is not None for v in blind_values):
+ median_blind = statistics.median([1.0 if v is None else v for v in blind_values])
+ if median_blind >= cfg.spindle_blind_threshold:
+ issues.append(Issue.BLIND_REGION)
+ elif cfg.treat_unassessed_blind_as_blind:
+ issues.append(Issue.BLIND_REGION)
+
+ if bravais and bravais in cfg.low_symmetry_bravais:
+ issues.append(Issue.LOW_SYMMETRY)
+
+ return Assessment(
+ issues=issues,
+ n_images=len(imgs),
+ indexed_fraction=round(indexed_fraction, 3),
+ wedge_spots=wedge_spots,
+ wedge_res_A=wedge_res,
+ onset_angle_deg=onset,
+ median_spindle_blind=median_blind,
+ bravais=bravais,
+ )
+
+
+def assess_collection(record: CollectionRecord, cfg: StrategyConfig) -> Assessment:
+ """Assess each chi sweep separately, then merge.
+
+ Blind region is a per-sweep property, so a multi-chi collection only keeps it if every sweep
+ reports it. Every other issue is kept if any sweep reports it.
+ """
+ parts = [assess_sweep(s.images, s.bravais, cfg) for s in record.sweeps]
+ if not parts:
+ return Assessment(issues=[Issue.LOST_DIFFRACTION, Issue.WEAK])
+ merged = parts[0].model_copy(deep=True)
+ issues: list[Issue] = []
+ for issue in Issue:
+ flags = [issue in p.issues for p in parts]
+ keep = all(flags) if issue is Issue.BLIND_REGION else any(flags)
+ if keep:
+ issues.append(issue)
+ merged.issues = issues
+ merged.n_images = sum(p.n_images for p in parts)
+ merged.bravais = next((p.bravais for p in parts if p.bravais), None)
+ return merged
+
+
+class Action(str, Enum):
+ FINISH = "finish"
+ RECENTRE = "recentre"
+ NEW_POSITION = "new_position"
+ CHI_SWEEP = "chi_sweep"
+
+
+class Decision(BaseModel):
+ action: Action
+ reason: str
+ position_index: int | None = None
+ chi_values: list[float] = [0.0]
+ dose_fraction: float = 1.0
+
+
+def decide_followup(assessment: Assessment, info: SampleInfo, cfg: StrategyConfig) -> Decision:
+ """Priority: budget -> lost diffraction -> damage -> completeness (chi) -> weak -> finish."""
+ issues = set(assessment.issues)
+ if info.followups >= cfg.max_followups:
+ return Decision(action=Action.FINISH, reason="follow-up budget spent")
+ nxt = info.next_free_position()
+
+ if Issue.LOST_DIFFRACTION in issues:
+ if info.recentres < cfg.max_recentres:
+ return Decision(
+ action=Action.RECENTRE,
+ reason=f"diffraction lost at omega={assessment.onset_angle_deg}; re-raster",
+ )
+ if nxt is not None:
+ return Decision(
+ action=Action.NEW_POSITION, position_index=nxt, reason="lost again; next spot"
+ )
+ return Decision(action=Action.FINISH, reason="diffraction lost, no spot left")
+
+ if Issue.RADIATION_DAMAGE in issues:
+ if nxt is not None:
+ return Decision(
+ action=Action.NEW_POSITION,
+ position_index=nxt,
+ dose_fraction=cfg.damage_dose_fraction,
+ reason="radiation damage; fresh spot at reduced dose",
+ )
+ return Decision(action=Action.FINISH, reason="radiation damage, no fresh spot left")
+
+ needs_chi = issues & {Issue.BLIND_REGION, Issue.LOW_SYMMETRY}
+ if needs_chi and info.chi_sweeps_done < cfg.max_chi_sweeps:
+ why = "+".join(sorted(i.value for i in needs_chi))
+ if nxt is not None:
+ return Decision(
+ action=Action.CHI_SWEEP,
+ position_index=nxt,
+ chi_values=[cfg.chi_offset_deg],
+ reason=f"{why}; chi sweep on a fresh spot",
+ )
+ last = info.positions_used[-1] if info.positions_used else 0
+ return Decision(
+ action=Action.CHI_SWEEP,
+ position_index=last,
+ chi_values=[cfg.chi_offset_deg],
+ dose_fraction=cfg.same_position_dose_fraction,
+ reason=f"{why}; chi sweep on the same spot, extra dose",
+ )
+
+ if Issue.WEAK in issues and nxt is not None:
+ return Decision(action=Action.NEW_POSITION, position_index=nxt, reason="weak; next spot")
+
+ return Decision(action=Action.FINISH, reason="no issue left to act on")
diff --git a/mx_bec/device_planner/__init__.py b/mx_bec/device_planner/__init__.py
new file mode 100644
index 0000000..00fe78f
--- /dev/null
+++ b/mx_bec/device_planner/__init__.py
@@ -0,0 +1,46 @@
+"""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 SIMULATED, 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__ = [
+ "SIMULATED",
+ "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..1c93cc5
--- /dev/null
+++ b/mx_bec/device_planner/environment.py
@@ -0,0 +1,145 @@
+"""Initialise sample environment devices and beamline states."""
+
+import importlib
+import os
+import tempfile
+from dataclasses import dataclass
+from pathlib import Path
+
+from bec_lib.logger import bec_logger
+
+from mx_bec.device_planner.build import DefineStatesManager, DeviceManager, planner_deps
+from mx_bec.device_planner.planner import StateChangePlanner
+
+logger = bec_logger.logger
+
+SIMULATED = "SIMULATED"
+"""Value of the BEAMLINE environment variable which selects the simulated beamline in
+`mx_bec/configs`, for development."""
+
+
+@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",
+ },
+ SIMULATED: {
+ "name": "Simulated",
+ "package": "mx_bec",
+ "config_dir": "configs",
+ "devices": "simulated_devices.yaml",
+ "states": "simulated_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 / cfg.get("config_dir", "device_configs")
+ self.lut_dir = self.bec_dir / "macros" / "luts"
+
+ # Runtime files generated by daily setup
+ if self.simulated:
+ # nothing to keep, and the package directory may not be writable
+ self.daily_setup_dir = Path(tempfile.gettempdir()) / "mx_bec_daily_setup_files"
+ else:
+ 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}")
+
+ @property
+ def simulated(self) -> bool:
+ """Whether this is the simulated beamline for development."""
+ return self.beamline == SIMULATED
+
+ def _get_deployment(self):
+ """Determine deployment from the loaded package path."""
+
+ if self.simulated:
+ return "simulated"
+
+ 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)
+
+ logger.success(
+ "Initialised the beamline environment:\n"
+ f" Beamline : {beamline}\n"
+ f" BEC deployment : {env.deployment.upper()}\n"
+ f" Devices file : {env.devices_file}\n"
+ f" States file : {env.states_file}"
+ )
+
+ # 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..7fdf1a9
--- /dev/null
+++ b/mx_bec/device_planner/guards.py
@@ -0,0 +1,92 @@
+"""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")
+ 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/devices/__init__.py b/mx_bec/devices/__init__.py
index e69de29..5c17ef7 100644
--- a/mx_bec/devices/__init__.py
+++ b/mx_bec/devices/__init__.py
@@ -0,0 +1,4 @@
+from .sim_sample_changer import RobotState, SimSampleChanger
+from .sim_stages import SimAerotechStage, SimGoniometer
+
+__all__ = ["RobotState", "SimAerotechStage", "SimGoniometer", "SimSampleChanger"]
diff --git a/mx_bec/devices/aerotech.py b/mx_bec/devices/aerotech.py
new file mode 100644
index 0000000..952a98e
--- /dev/null
+++ b/mx_bec/devices/aerotech.py
@@ -0,0 +1,186 @@
+from typing import ClassVar
+
+from bec_lib.logger import bec_logger
+from ophyd import Component as Cpt
+from ophyd import Kind
+from ophyd.device import Device
+from ophyd.signal import Signal
+from ophyd_devices.utils.psi_device_base_utils import StatusBase
+from requests import RequestException
+
+from .http import (
+ TIMESTAMP_ID,
+ HttpDeviceControllerWithConfigVelocity,
+ HttpDeviceSignal,
+ HttpOphydDevice,
+ HttpVelocitySignal,
+ get_controller,
+)
+
+logger = bec_logger.logger
+
+
+class ValidatedHttpParams(Device):
+ """Group of config signals making up one AareScan request body. Whenever a config signal
+ changes, the body is validated by the server at `validate_endpoint` and the result is
+ published on the `valid` and `message` signals."""
+
+ validate_endpoint: ClassVar[str]
+
+ valid = Cpt(Signal, kind=Kind.normal, value=False)
+ message = Cpt(Signal, kind=Kind.normal, value="")
+
+ def __init__(self, prefix="", *, name, **kwargs):
+ super().__init__(prefix, name=name, **kwargs)
+ self._controller = get_controller(self)
+ for attr in self.configuration_attrs:
+ getattr(self, attr).subscribe(self._on_config_change, run=False)
+
+ def request_body(self) -> dict:
+ return {attr: getattr(self, attr).get() for attr in self.configuration_attrs}
+
+ def validate(self) -> tuple[bool, str]:
+ """Validate the current configuration, update `valid`/`message` and return them."""
+ try:
+ result = self._controller.validate(self.validate_endpoint, self.request_body())
+ except RequestException as exc:
+ result = False, f"Could not reach {self.validate_endpoint}: {exc}"
+ valid, message = result
+ if not valid:
+ logger.warning(f"{self.name} is invalid: {message}")
+ self.valid.put(valid)
+ self.message.put(message)
+ return result
+
+ def _on_config_change(self, **kwargs):
+ self.validate()
+
+
+class GridscanParameters(ValidatedHttpParams):
+ validate_endpoint = "/validate/grid_scan"
+
+ grid_elem_count_y = Cpt(Signal, kind=Kind.config, dtype=int, value=0)
+ grid_elem_size_y_um = Cpt(Signal, kind=Kind.config, dtype=float, value=0.0)
+ grid_elem_size_x_um = Cpt(Signal, kind=Kind.config, dtype=float, value=0.0)
+ grid_elem_count_x = Cpt(Signal, kind=Kind.config, dtype=int, value=0)
+ time_per_element_sec = Cpt(Signal, kind=Kind.config, dtype=float, value=0.0)
+
+
+class ScreeningParameters(ValidatedHttpParams):
+ validate_endpoint = "/validate/screening"
+
+ rotation_deg = Cpt(Signal, kind=Kind.config, dtype=float, value=0.0)
+ wedge_deg = Cpt(Signal, kind=Kind.config, dtype=float, value=0.0)
+ time_per_element_sec = Cpt(Signal, kind=Kind.config, dtype=float, value=0.0)
+ steps = Cpt(Signal, kind=Kind.config, dtype=int, value=0)
+
+
+class RotationScanParameters(ValidatedHttpParams):
+ validate_endpoint = "/validate/rotation_scan"
+
+ rotation_deg = Cpt(Signal, kind=Kind.config, dtype=float, value=0.0)
+ total_time_sec = Cpt(Signal, kind=Kind.config, dtype=float, value=0.0)
+ start_pos_deg = Cpt(Signal, kind=Kind.config, dtype=float, value=0.0)
+
+
+class AerotechController(HttpDeviceControllerWithConfigVelocity):
+ _readback_endpoint = "/status"
+ _target_endpoint = "/position"
+ _grid_scan_endpoint = "/grid_scan"
+ _wait_till_done_endpoint = "/wait_till_done"
+ MAX_WAIT_TILL_DONE_S = 3600 # upper bound of the AareScan timeout parameter
+
+ def __init__(self, *, prefix, **kwargs):
+ self._readbacks: dict[str, dict[str, float | bool]] = {}
+ super().__init__(prefix=prefix, **kwargs)
+
+ def put(self, axis: str, val: float, velocity: float | None = None):
+ """Move the axis. If no velocity is given, the axis' velocity signal (if any) is used."""
+ self._rest_post(body=self.params_for_move(axis, val, velocity))
+
+ def get_readback(self, axis_id: str) -> tuple[float, float] | None:
+ with self._readback_lock:
+ if axis_id not in self._readbacks or TIMESTAMP_ID not in self._readbacks:
+ return None
+ return self._readbacks.get(axis_id)["pos"], self._readbacks.get(TIMESTAMP_ID) # type: ignore
+
+ def start_grid_scan(self, body: dict):
+ """Start a grid scan with the given (validated) request body, returning immediately."""
+ self._rest_post(body={**body, "run_async": True}, endpoint=self._grid_scan_endpoint)
+
+ def wait_till_done(self, timeout_s: float):
+ """Block until AareScan is idle again. Raises HttpRestError on timeout (504)."""
+ timeout = min(max(int(round(timeout_s)), 0), self.MAX_WAIT_TILL_DONE_S)
+ self._rest_post(params={"timeout": timeout}, endpoint=self._wait_till_done_endpoint)
+
+
+class Aerotech(HttpOphydDevice):
+ """Aerotech sample stage driven through the AareScan REST API. Triggering runs the grid scan
+ configured in `gridscan_config`."""
+
+ controller_class = AerotechController
+ # margin on top of the expected grid scan duration before giving up waiting for it
+ GRID_SCAN_TIMEOUT_MARGIN_S = 60.0
+
+ gridscan_config = Cpt(GridscanParameters)
+ screening_config = Cpt(ScreeningParameters)
+ rotation_config = Cpt(RotationScanParameters)
+
+ x = Cpt(HttpDeviceSignal, axis_identifier="x", tolerance=0.01)
+ y = Cpt(HttpDeviceSignal, axis_identifier="y", tolerance=0.01)
+ z = Cpt(HttpDeviceSignal, axis_identifier="z", tolerance=0.01)
+ u = Cpt(HttpDeviceSignal, axis_identifier="u", tolerance=0.01)
+ vel_x_mm_s = Cpt(HttpVelocitySignal, axis_identifier="x", param_name="vel_x_mm_s")
+ vel_y_mm_s = Cpt(HttpVelocitySignal, axis_identifier="y", param_name="vel_y_mm_s")
+ vel_z_mm_s = Cpt(HttpVelocitySignal, axis_identifier="z", param_name="vel_z_mm_s")
+ vel_u_deg_s = Cpt(HttpVelocitySignal, axis_identifier="u", param_name="vel_u_deg_s")
+
+ def wait_for_connection(self, **kwargs): # type: ignore
+ ret = super().wait_for_connection(**kwargs)
+ # Config signals only validate on change; publish the state of the initial values too.
+ for config in (self.gridscan_config, self.screening_config, self.rotation_config):
+ config.validate()
+ return ret
+
+ ########################################
+ # Beamline Specific Implementations #
+ ########################################
+
+ def on_trigger(self) -> StatusBase:
+ """Start the grid scan from `gridscan_config`; the returned status finishes once AareScan
+ reports the scan done."""
+ config = self.gridscan_config
+ if not config.valid.get():
+ raise ValueError(f"Grid scan parameters are not valid: {config.message.get()}")
+ body = config.request_body()
+ self.controller.start_grid_scan(body)
+ status = self.task_handler.submit_task(
+ self.controller.wait_till_done, task_kwargs={"timeout_s": self.grid_scan_timeout_s()}
+ )
+ self.cancel_on_stop(status)
+ return status
+
+ ########################################
+ # Helper Methods #
+ ########################################
+
+ def expected_grid_scan_s(self) -> float:
+ """Expected duration of the configured grid scan (exposure plus ~0.3 s per line)."""
+ config = self.gridscan_config
+ n_x, n_y = config.grid_elem_count_x.get(), config.grid_elem_count_y.get()
+ return config.time_per_element_sec.get() * n_x * n_y + n_y * 0.3
+
+ def grid_scan_timeout_s(self) -> float:
+ return self.expected_grid_scan_s() * 1.1 + self.GRID_SCAN_TIMEOUT_MARGIN_S
+
+
+def _test():
+ a = Aerotech(name="aerotech", prefix="http://mx-x10sa-queue-01:5234")
+ a.wait_for_connection()
+ return a
+
+
+if __name__ == "__main__":
+ aerotech = _test()
+ print(aerotech.read())
+ aerotech.stop()
diff --git a/mx_bec/devices/http.py b/mx_bec/devices/http.py
new file mode 100644
index 0000000..0e69acd
--- /dev/null
+++ b/mx_bec/devices/http.py
@@ -0,0 +1,253 @@
+import time
+from abc import ABC, abstractmethod
+from threading import Event, RLock, Thread
+from typing import Any
+
+from bec_lib.logger import bec_logger
+from ophyd import Kind, OphydObject, Signal
+from ophyd_devices import PSIDeviceBase
+from ophyd_devices.utils.socket import SocketSignal
+from requests import Response, Session
+
+logger = bec_logger.logger
+
+TIMESTAMP_ID = "__timestamp"
+_POLL_INTERVAL_SLOW = 0.1
+
+
+def get_controller(obj: OphydObject) -> "HttpDeviceController":
+ """Return the HttpDeviceController of the root device of `obj`."""
+ controller: HttpDeviceController | None = getattr(obj.root, "controller", None)
+ if controller is None:
+ raise TypeError(
+ f"{type(obj).__name__} must be used in a device with a HttpDeviceController"
+ )
+ return controller
+
+
+class HttpRestError(Exception):
+ """Error for rest calls from a HttpRestSignal."""
+
+ def __init__(self, resp: Response, *args: object, value: Any | None = None) -> None:
+ method, url = resp.request.method, resp.request.url
+ data = f"{value!s} to " if value is not None else ""
+ super().__init__(
+ f"Could not {method} {data}{url}. Code: {resp.status_code}. Reason: {resp.reason}.",
+ *args,
+ )
+
+
+class HttpDeviceController(OphydObject, ABC):
+ """Controller to consolidate polling loops and other REST calls for devices which communicate
+ with HTTP REST interfaces"""
+
+ _readback_endpoint: str
+ _target_endpoint: str
+
+ def __init__(self, *, prefix, **kwargs):
+ self._readbacks: dict
+ self._session = Session()
+ self._prefix = prefix
+ self._targets = {}
+ self._signal_registry: set[str] = set()
+ self._readback_poll_interval: float = _POLL_INTERVAL_SLOW
+
+ super().__init__(**kwargs)
+ self._setup_readback()
+
+ def _setup_readback(self):
+ self._stop_monitor_readback_event = Event()
+ self._readback_lock = RLock()
+ self._monitor_readback_thread = Thread(
+ target=self._monitor,
+ args=[
+ self._readback_endpoint,
+ self._stop_monitor_readback_event,
+ self._readback_lock,
+ self._readbacks,
+ ],
+ )
+
+ def manual_update(self):
+ self._update_reading(self._readback_endpoint, self._readback_lock, self._readbacks)
+
+ def _update_reading(self, endpoint: str, lock: RLock, buffer: dict):
+ data = self._rest_get(endpoint)
+ timestamp = time.monotonic()
+ with lock:
+ buffer.update(data)
+ buffer["__timestamp"] = timestamp
+
+ def _monitor(self, endpoint: str, event: Event, lock: RLock, buffer: dict):
+ while not event.is_set():
+ self._update_reading(endpoint, lock, buffer)
+ time.sleep(self._readback_poll_interval)
+
+ def _clean_monitor(self):
+ if self._monitor_readback_thread.is_alive():
+ self._stop_monitor_readback_event.set()
+ self._monitor_readback_thread.join(timeout=2)
+ if self._monitor_readback_thread.is_alive():
+ raise RuntimeError("Failed to clean up Aerotech monitor thread.")
+
+ def register(self, axis_id: str):
+ self._signal_registry.add(axis_id)
+
+ def _rest_get(self, endpoint):
+ resp = self._session.get(self._prefix + endpoint)
+ if not resp.ok:
+ raise HttpRestError(resp)
+ return resp.json()
+
+ def _rest_put(self, params: dict | None = None, body: dict | None = None):
+ resp = self._session.put(self._prefix + self._target_endpoint, params=params, json=body)
+ if not resp.ok:
+ raise HttpRestError(resp, value=params)
+
+ def _rest_post(
+ self, params: dict | None = None, body: dict | None = None, endpoint: str | None = None
+ ):
+ endpoint = self._target_endpoint if endpoint is None else endpoint
+ resp = self._session.post(self._prefix + endpoint, params=params, json=body)
+ if not resp.ok:
+ raise HttpRestError(resp, value=params)
+
+ def validate(self, endpoint: str, body: dict) -> tuple[bool, str]:
+ """POST `body` to a validation endpoint. Returns (valid, message); the message is the
+ server's error text for an invalid request and empty otherwise."""
+ resp = self._session.post(self._prefix + endpoint, json=body)
+ if resp.ok:
+ return True, ""
+ try:
+ message = resp.json()
+ except ValueError:
+ message = resp.text
+ return False, str(message)
+
+ def start_monitor(self):
+ """Start or restart the automonitor thread."""
+ self._clean_monitor()
+ self._setup_readback()
+ self._monitor_readback_thread.start()
+
+ def monitor_stopped(self):
+ return not self._monitor_readback_thread.is_alive()
+
+ def put(self, axis: str, val: float):
+ self._rest_put({axis: val})
+
+ @abstractmethod
+ def get_readback(self, axis_id: str) -> tuple[float, float] | None:
+ """Return a tuple (reading, timestamp) if the axis_id exists"""
+
+ def stop(self):
+ # There doesn't appear to be a stop endpoint on the server
+ # Best effort: set the target to the current position
+ pass
+ # TODO: self._rest_put(self._readbacks)
+
+
+class HttpDeviceControllerWithConfigVelocity(HttpDeviceController):
+ """Controller for devices whose move request accepts a per-axis velocity parameter. The velocity
+ for each axis is held in a registered HttpVelocitySignal and sent along with every move."""
+
+ def __init__(self, *, prefix, **kwargs):
+ super().__init__(prefix=prefix, **kwargs)
+ self._velocity_signal_registry: dict[str, HttpVelocitySignal] = {}
+
+ def register_velocity(self, axis_id: str, signal: "HttpVelocitySignal"):
+ self._velocity_signal_registry[axis_id] = signal
+
+ def get_velocity(self, axis_id: str) -> float | None:
+ """Return the configured velocity for the axis, or None if it has no velocity signal."""
+ if (signal := self._velocity_signal_registry.get(axis_id)) is None:
+ return None
+ return signal.get()
+
+ def params_for_move(self, axis: str, val: float, velocity: float | None = None):
+ """Build the request params for a move. If no explicit velocity is given, the registered
+ velocity signal for the axis is used if one exists."""
+ if (signal := self._velocity_signal_registry.get(axis)) is None:
+ if velocity is not None:
+ raise ValueError(f"Axis {axis} has no registered velocity signal")
+ return {axis: val}
+ if velocity is None:
+ velocity = signal.get()
+ return {axis: val, signal.param_name: velocity}
+
+
+class HttpDeviceSignalBase(SocketSignal):
+ """Ophyd signal which gets and puts to a REST API rather than EPICS PVs, mediated through the Aerotech
+ Controller"""
+
+ def __init__(self, *args, axis_identifier: str, **kwargs):
+ super().__init__(*args, **kwargs)
+ self._controller = get_controller(self)
+ self._axis_id = axis_identifier
+
+
+class HttpDeviceSignal(HttpDeviceSignalBase):
+ def __init__(self, *args, axis_identifier: str, **kwargs):
+ super().__init__(*args, axis_identifier=axis_identifier, **kwargs)
+ self._controller.register(self._axis_id)
+
+ def _socket_get(self): # type: ignore
+ self._readback, self.metadata["timestamp"] = self._controller.get_readback(
+ self._axis_id
+ ) or (0.0, 0.0)
+ return self._readback
+
+ def _socket_set(self, val: float):
+ self._controller.put(self._axis_id, val)
+
+ def get(self, **kwargs) -> float:
+ if self._controller.monitor_stopped():
+ self._controller.start_monitor()
+ return super().get(**kwargs)
+
+
+class HttpVelocitySignal(Signal):
+ """Config signal holding the velocity used for moves of one axis. Putting to it does not talk to
+ the controller; the value is sent as `param_name` with the next move of the axis."""
+
+ def __init__(
+ self,
+ *args,
+ axis_identifier: str,
+ param_name: str,
+ kind=Kind.config,
+ dtype=float,
+ value=1.0,
+ **kwargs,
+ ):
+ super().__init__(*args, kind=kind, dtype=dtype, value=value, **kwargs)
+ controller = get_controller(self)
+ if not isinstance(controller, HttpDeviceControllerWithConfigVelocity):
+ raise TypeError(
+ "HttpVelocitySignal must be used in a device with a HttpDeviceControllerWithConfigVelocity"
+ )
+ self._controller = controller
+ self._axis_id = axis_identifier
+ self.param_name = param_name
+ self._controller.register_velocity(axis_id=self._axis_id, signal=self)
+
+
+class HttpOphydDevice(PSIDeviceBase):
+ controller_class: type[HttpDeviceController]
+
+ def __init__(
+ self, *, name: str, prefix: str = "", scan_info=None, device_manager=None, **kwargs
+ ):
+ self.controller = self.controller_class(prefix=prefix)
+ super().__init__(
+ name=name, prefix=prefix, scan_info=scan_info, device_manager=device_manager, **kwargs
+ )
+
+ def wait_for_connection(self, **kwargs): # type: ignore
+ self.controller.start_monitor()
+ self.controller.manual_update()
+ return super().wait_for_connection(**kwargs)
+
+ def stop(self, *, success: bool = False) -> None:
+ self.controller.stop()
+ return super().stop(success=success)
diff --git a/mx_bec/devices/sim_sample_changer.py b/mx_bec/devices/sim_sample_changer.py
new file mode 100644
index 0000000..b44bb68
--- /dev/null
+++ b/mx_bec/devices/sim_sample_changer.py
@@ -0,0 +1,108 @@
+"""Simulated MX sample changer robot (TELL-like)."""
+
+from __future__ import annotations
+
+import enum
+import threading
+from typing import ClassVar
+
+from bec_lib.logger import bec_logger
+from ophyd import Component as Cpt
+from ophyd import DeviceStatus, Kind
+from ophyd_devices.interfaces.base_classes.psi_device_base import DeviceStoppedError, PSIDeviceBase
+from ophyd_devices.sim.sim_signals import SetableSignal
+
+logger = bec_logger.logger
+
+
+class RobotState(enum.IntEnum):
+ IDLE = 0
+ BUSY = 1
+ ERROR = 2
+
+
+class SimSampleChanger(PSIDeviceBase):
+ """A minimal sample changer: mounts and unmounts a (puck, position) with a configurable delay.
+
+ All signals are integers so that they can be used directly in BEC beamline states
+ (e.g. `DeviceWithinLimitsState` on `state` or `sample_mounted`).
+
+ >>> robot = SimSampleChanger(name="robot")
+ >>> robot.mount(puck=1, position=3).wait()
+ """
+
+ USER_ACCESS: ClassVar[list[str]] = ["mount", "unmount", "reset"]
+
+ state = Cpt(SetableSignal, value=int(RobotState.IDLE), kind=Kind.hinted)
+ sample_mounted = Cpt(SetableSignal, value=0, kind=Kind.normal)
+ mounted_puck = Cpt(SetableSignal, value=0, kind=Kind.normal)
+ mounted_position = Cpt(SetableSignal, value=0, kind=Kind.normal)
+ door_closed = Cpt(SetableSignal, value=1, kind=Kind.normal)
+
+ mount_time = Cpt(SetableSignal, value=1.0, kind=Kind.config, doc="Mount/unmount time in s")
+
+ def __init__(self, name: str, *, mount_time: float | None = None, **kwargs):
+ super().__init__(name=name, **kwargs)
+ self._mount_time_init = mount_time
+ self._stop_event = threading.Event()
+ self._worker: threading.Thread | None = None
+
+ def on_connected(self) -> None:
+ if self._mount_time_init is not None:
+ self.mount_time.put(self._mount_time_init)
+
+ def mount(self, puck: int, position: int) -> DeviceStatus:
+ """Mount the sample at `position` of `puck`. Returns a status that finishes once mounted."""
+ return self._run_motion(lambda: self._set_mounted(puck, position))
+
+ def unmount(self) -> DeviceStatus:
+ """Unmount the current sample. Returns a status that finishes once the sample is back."""
+ return self._run_motion(lambda: self._set_mounted(0, 0))
+
+ def _set_mounted(self, puck: int, position: int) -> None:
+ self.mounted_puck.put(puck)
+ self.mounted_position.put(position)
+ self.sample_mounted.put(int(puck > 0))
+
+ def _run_motion(self, on_done) -> DeviceStatus:
+ # Precondition failures raise instead of returning a failed status: a failed
+ # DeviceStatus calls device.stop(), which would abort a motion already in flight.
+ if self.state.get() != RobotState.IDLE:
+ raise RuntimeError(f"{self.name} is not idle")
+ if not self.door_closed.get():
+ self.state.put(int(RobotState.ERROR))
+ raise RuntimeError(f"{self.name}: hutch door is open")
+
+ self.stopped = False
+ self._stop_event.clear()
+ self.state.put(int(RobotState.BUSY))
+ status = DeviceStatus(self)
+
+ def worker():
+ try:
+ if self._stop_event.wait(timeout=self.mount_time.get()):
+ raise DeviceStoppedError(f"{self.name} was stopped")
+ on_done()
+ except DeviceStoppedError as exc:
+ logger.warning(f"{self.name} motion aborted: {exc}")
+ status.set_exception(exc)
+ else:
+ status.set_finished()
+ finally:
+ self.state.put(int(RobotState.IDLE))
+
+ self._worker = threading.Thread(target=worker, daemon=True)
+ self._worker.start()
+ return status
+
+ def reset(self) -> None:
+ """Clear an error state."""
+ if self.state.get() == RobotState.ERROR:
+ self.state.put(int(RobotState.IDLE))
+
+ def on_stop(self) -> None:
+ self._stop_event.set()
+ worker = self._worker
+ # A failed status calls device.stop() from the worker itself; don't join ourselves.
+ if worker is not None and worker.is_alive() and worker is not threading.current_thread():
+ worker.join(timeout=1.0)
diff --git a/mx_bec/devices/sim_stages.py b/mx_bec/devices/sim_stages.py
new file mode 100644
index 0000000..3cad611
--- /dev/null
+++ b/mx_bec/devices/sim_stages.py
@@ -0,0 +1,36 @@
+"""Simulated MX sample stages, built from ophyd_devices SimPositioners."""
+
+from ophyd import Component as Cpt
+from ophyd import Device, Kind
+from ophyd_devices.sim.sim_positioner import SimPositioner
+from ophyd_devices.sim.sim_signals import SetableSignal
+
+
+class SimStageAxis(SimPositioner):
+ """A SimPositioner with a more sensible tolerance."""
+
+ tolerance = Cpt(SetableSignal, value=0.01, kind=Kind.config)
+
+
+class SimAerotechStage(Device):
+ """Simulated Aerotech rotation stage: a 3-axis translation under the omega rotation axis, `u`
+ (as on the real Aerotech).
+
+ u is unbounded (low == high limit disables the SimPositioner limit check) so that
+ multi-turn rotation scans are possible; the translations are limited to a few mm.
+ """
+
+ x = Cpt(SimStageAxis, name="x", limits=[-5, 5])
+ y = Cpt(SimStageAxis, name="y", limits=[-5, 5])
+ z = Cpt(SimStageAxis, name="z", limits=[-5, 5])
+ u = Cpt(SimStageAxis, name="u", limits=[0, 0])
+
+
+class SimGoniometer(Device):
+ """Simulated Smargon-style goniometer head mounted on top of the Aerotech stage."""
+
+ x = Cpt(SimStageAxis, name="x", limits=[-5, 5])
+ y = Cpt(SimStageAxis, name="y", limits=[-5, 5])
+ z = Cpt(SimStageAxis, name="z", limits=[-5, 5])
+ phi = Cpt(SimStageAxis, name="phi", limits=[0, 0])
+ chi = Cpt(SimStageAxis, name="chi", limits=[0, 45])
diff --git a/mx_bec/devices/smargopolo_smargon.py b/mx_bec/devices/smargopolo_smargon.py
new file mode 100644
index 0000000..6360929
--- /dev/null
+++ b/mx_bec/devices/smargopolo_smargon.py
@@ -0,0 +1,104 @@
+from typing import ClassVar
+
+import numpy as np
+from bec_lib.logger import bec_logger
+from ophyd import Component as Cpt
+
+from .http import HttpDeviceController, HttpDeviceSignal, HttpOphydDevice
+
+logger = bec_logger.logger
+
+_TIMESTAMP_ID = "__timestamp"
+_POLL_INTERVAL_SLOW = 0.1
+
+
+class SmargonController(HttpDeviceController):
+ """Controller to consolidate polling loops and other REST calls for the smargon"""
+
+ _readback_endpoint = "/readbackSCS"
+ _target_endpoint = "/targetSCS"
+
+ def __init__(self, *, prefix, **kwargs):
+ self._readbacks: dict[str, float] = {}
+ super().__init__(prefix=prefix, **kwargs)
+
+ def get_readback(self, axis_id: str) -> tuple[float, float] | None:
+ with self._readback_lock:
+ if axis_id not in self._readbacks or _TIMESTAMP_ID not in self._readbacks:
+ return None
+ return self._readbacks.get(axis_id), self._readbacks.get(_TIMESTAMP_ID) # type: ignore
+
+ def put(self, axis: str, val: float):
+ self._rest_put(params={axis: val})
+
+ def stop(self):
+ # There doesn't appear to be a stop endpoint on the server
+ # Best effort: set the target to the current position
+ with self._readback_lock:
+ targets = {
+ axis: self._readbacks[axis]
+ for axis in self._signal_registry
+ if axis in self._readbacks
+ }
+ self._rest_put(params=targets)
+
+
+class Smargon(HttpOphydDevice):
+ USER_ACCESS: ClassVar[list[str]] = ["nudge_in_lab_frame"]
+ controller_class = SmargonController
+
+ x = Cpt(HttpDeviceSignal, axis_identifier="SHX", tolerance=0.01)
+ y = Cpt(HttpDeviceSignal, axis_identifier="SHY", tolerance=0.01)
+ z = Cpt(HttpDeviceSignal, axis_identifier="SHZ", tolerance=0.01)
+ phi = Cpt(HttpDeviceSignal, axis_identifier="PHI", tolerance=0.01)
+ chi = Cpt(HttpDeviceSignal, axis_identifier="CHI", tolerance=0.01)
+
+ def nudge_in_lab_frame(
+ self, x_mm: float, y_mm: float, z_mm: float = 0.0, omega_deg: float = 0.0
+ ):
+ """Apply a relative move in the lab frame (adjusted for the rotation angle, assuming that
+ the frames are identical when omega = phi = chi = 0). `omega_deg` is the angle of the
+ rotation stage the smargon sits on (the Aerotech `u` axis), which the smargon does not
+ know itself."""
+ x_mm, y_mm, z_mm = self._lab_frame_offset_to_smargon_nudge(x_mm, y_mm, z_mm, omega_deg)
+ logger.info(f"Nudging smargon by {x_mm=},{y_mm=},{z_mm=}")
+ (
+ self.x.set(self.x.get() + x_mm)
+ & self.y.set(self.y.get() + y_mm)
+ & self.z.set(self.z.get() + z_mm)
+ ).wait()
+
+ def _lab_frame_offset_to_smargon_nudge(
+ self, x_mm: float, y_mm: float, z_mm: float = 0.0, omega_deg: float = 0.0
+ ):
+ """adjust a move for the rotation angle, assuming that the frames are identical when omega = phi = chi = 0"""
+ logger.info(
+ f"Calculating smargon motor nudge for camera offset: {x_mm=}, {y_mm=}, {z_mm=}, at {omega_deg=}"
+ )
+ phi = np.radians(np.around(self.phi.get(), decimals=1))
+ chi = np.radians(np.around(self.chi.get(), decimals=1))
+ omega = np.radians(np.around(omega_deg, decimals=1))
+
+ co = np.cos(omega)
+ so = np.sin(omega)
+ cp = np.cos(phi)
+ sp = np.sin(phi)
+ cc = np.cos(chi)
+ sc = np.sin(chi)
+
+ res_x = (
+ -z_mm * co * sp
+ - y_mm * so * sp
+ + x_mm * cp * sc
+ - y_mm * co * cc * cp
+ + z_mm * so * cc * cp
+ )
+ res_y = (
+ -z_mm * co * cp
+ - y_mm * so * cp
+ - x_mm * sc * sp
+ + y_mm * co * cc * sp
+ - z_mm * so * cc * sp
+ )
+ res_z = -x_mm * cc - y_mm * co * sc + z_mm * so * sc
+ return res_x, res_y, res_z
diff --git a/mx_bec/endpoints.py b/mx_bec/endpoints.py
new file mode 100644
index 0000000..38565e1
--- /dev/null
+++ b/mx_bec/endpoints.py
@@ -0,0 +1,169 @@
+from bec_lib.endpoints import EndpointInfo, EndpointType, MessageOp
+from bec_lib.messages import AvailableResourceMessage, BoolConfigDefaultFalse
+
+from mx_bec.messages import (
+ MXMeasurementSequenceMessage,
+ MXQueueChangedMessage,
+ MXSampleExecutionMessage,
+ MXTaskExecutionMessage,
+ OpticalPredictionMessage,
+)
+
+
+class StateEndpoints:
+ """Milestones of the MX measurement sequence, published by whoever completes the step."""
+
+ @staticmethod
+ def sample_mounted():
+ return EndpointInfo(
+ endpoint=f"{EndpointType.INFO.value}/mx/sequence/mounted",
+ message_type=MXMeasurementSequenceMessage,
+ message_op=MessageOp.SET_PUBLISH,
+ )
+
+ @staticmethod
+ def optical_centering_done():
+ return EndpointInfo(
+ endpoint=f"{EndpointType.INFO.value}/mx/sequence/optical_centering_done",
+ message_type=MXMeasurementSequenceMessage,
+ message_op=MessageOp.SET_PUBLISH,
+ )
+
+ @staticmethod
+ def xray_centering_done():
+ return EndpointInfo(
+ endpoint=f"{EndpointType.INFO.value}/mx/sequence/xray_centering_done",
+ message_type=MXMeasurementSequenceMessage,
+ message_op=MessageOp.SET_PUBLISH,
+ )
+
+ @staticmethod
+ def rotation_done():
+ return EndpointInfo(
+ endpoint=f"{EndpointType.INFO.value}/mx/sequence/rotation_done",
+ message_type=MXMeasurementSequenceMessage,
+ message_op=MessageOp.SET_PUBLISH,
+ )
+
+ @staticmethod
+ def sample_done() -> EndpointInfo[type[MXMeasurementSequenceMessage]]:
+ """The self-driving sequence has finished with the mounted sample.
+
+ ``success`` is True when at least one dataset was usable.
+ """
+ return EndpointInfo(
+ endpoint=f"{EndpointType.INFO.value}/mx/sequence/sample_done",
+ message_type=MXMeasurementSequenceMessage,
+ message_op=MessageOp.SET_PUBLISH,
+ )
+
+
+class ActorEndpoints:
+ """Per-actor configuration, keyed by the actor's `config_key`."""
+
+ @staticmethod
+ def enabled(actor_key: str):
+ """Managed bool: whether the AareActorManager should keep this actor running.
+ Same shape as MessageEndpoints.scan_interlock_enabled(), so it works with RedisConfigValue.
+ """
+ return EndpointInfo(
+ endpoint=f"{EndpointType.USER.value}/actor/mx/{actor_key}/config/enabled",
+ message_type=BoolConfigDefaultFalse,
+ message_op=MessageOp.STREAM,
+ )
+
+ @staticmethod
+ def available_actor_config_eps():
+ """Endpoint to broadcast which MX actors are available on the MX builtin actor manager"""
+ return EndpointInfo(
+ endpoint=f"{EndpointType.INFO}/actor/mx/available_config_eps",
+ message_type=AvailableResourceMessage,
+ message_op=MessageOp.SET_PUBLISH,
+ )
+
+
+class QueueEndpoints:
+ """Endpoints for the sample and task queues."""
+
+ @staticmethod
+ def task_request():
+ """Stream of task requests from clients. The AareBec service validates them and queues
+ the accepted ones on `task_execution`."""
+ return EndpointInfo(
+ endpoint=f"{EndpointType.USER.value}/mx/tasks/request",
+ message_type=MXTaskExecutionMessage,
+ message_op=MessageOp.STREAM,
+ )
+
+ @staticmethod
+ def task_execution():
+ """FIFO queue of validated tasks waiting to be executed by the AareBec service: new tasks
+ are appended on the right and executed from the left."""
+ return EndpointInfo(
+ endpoint=f"{EndpointType.USER.value}/mx/tasks/execution",
+ message_type=MXTaskExecutionMessage,
+ message_op=MessageOp.LIST,
+ )
+
+ @staticmethod
+ def task_queue_changed():
+ """Pub/sub channel on which the AareBec service announces changes to the execution
+ queue, so that clients know to re-read it."""
+ return EndpointInfo(
+ endpoint=f"{EndpointType.USER.value}/mx/tasks/queue_changed",
+ message_type=MXQueueChangedMessage,
+ message_op=MessageOp.SEND,
+ )
+
+ @staticmethod
+ def task_queue_paused():
+ """Managed bool: whether the AareBec service should stop taking tasks from the execution
+ queue. Works with RedisConfigValue; defaults to running (not paused)."""
+ return EndpointInfo(
+ endpoint=f"{EndpointType.USER.value}/mx/tasks/queue_paused",
+ message_type=BoolConfigDefaultFalse,
+ message_op=MessageOp.STREAM,
+ )
+
+ # @staticmethod
+ # def sample_request():
+ # return EndpointInfo(
+ # endpoint=f"{EndpointType.USER.value}/mx/sample_queue/request",
+ # message_type=MXTaskExecutionMessage,
+ # message_op=MessageOp.STREAM,
+ # )
+
+ @staticmethod
+ def sample_execution():
+ return EndpointInfo(
+ endpoint=f"{EndpointType.USER.value}/mx/sample_queue/execution",
+ message_type=MXSampleExecutionMessage,
+ message_op=MessageOp.LIST,
+ )
+
+ @staticmethod
+ def sample_queue_changed():
+ return EndpointInfo(
+ endpoint=f"{EndpointType.USER.value}/mx/sample_queue/queue_changed",
+ message_type=MXQueueChangedMessage,
+ message_op=MessageOp.SEND,
+ )
+
+ @staticmethod
+ def sample_queue_paused():
+ return EndpointInfo(
+ endpoint=f"{EndpointType.USER.value}/mx/sample_queue/queue_paused",
+ message_type=BoolConfigDefaultFalse,
+ message_op=MessageOp.STREAM,
+ )
+
+
+class DataAnalysisEndpoints:
+ @staticmethod
+ def optical_prediction():
+ """Stream for image analysis predictions (for optical centering, grid scan parameters...)"""
+ return EndpointInfo(
+ endpoint=f"{EndpointType.USER.value}/mx/analysis/optical_prediction",
+ message_type=OpticalPredictionMessage,
+ message_op=MessageOp.STREAM,
+ )
diff --git a/mx_bec/jfjoch.py b/mx_bec/jfjoch.py
new file mode 100644
index 0000000..4536851
--- /dev/null
+++ b/mx_bec/jfjoch.py
@@ -0,0 +1,189 @@
+from __future__ import annotations
+
+import functools
+import math
+from typing import TYPE_CHECKING, Callable, ParamSpec, TypeVar
+
+import jfjoch_client
+from aarecommon.config.beamline import get_jfjoch_url, mx_beamline
+from bec_lib.logger import bec_logger
+from jfjoch_client.models.dataset_settings_smargon import DatasetSettingsSmargon
+from pydantic import BaseModel, Field
+
+if TYPE_CHECKING:
+ from jfjoch_client.models.scan_result import ScanResult
+
+ from mx_bec.service import AareBec
+
+logger = bec_logger.logger
+
+P = ParamSpec("P")
+R = TypeVar("R")
+
+
+class RasterScan(BaseModel):
+ """Everything JFJoch needs to collect one raster (grid) scan."""
+
+ # grid: n_x columns by n_y rows, stepped by step_*_mm, at a fixed omega
+ n_x: int = Field(ge=1)
+ n_y: int = Field(ge=1)
+ step_x_mm: float = Field(gt=0)
+ step_y_mm: float = Field(gt=0)
+ omega_deg: float
+ # exposure
+ exp_time_s: float = Field(gt=0)
+ detector_distance_mm: float = Field(gt=0)
+ transmission: float = Field(ge=0, le=1)
+ # output: files go to /raw/raster/
+ file_prefix: str
+ pgroup: str = "p16371"
+ sample_name: str = "unknown_sample"
+ # beamline and diffraction geometry
+ energy_keV: float = Field(gt=0)
+ beam_center_pxl: tuple[float, float]
+ beam_size_mm: tuple[float, float]
+ poni_rot1_rad: float = 0.0
+ poni_rot2_rad: float = 0.0
+ ring_current_mA: float
+ flux_ph_s: float
+ sample_temperature_K: float
+ smargon_phi_deg: float | None = None
+ smargon_chi_deg: float | None = None
+
+
+class JFJochError(RuntimeError):
+ """A call to the JFJoch detector broker failed."""
+
+
+def needs_connection(method: Callable[P, R]) -> Callable[P, R]:
+ """Connect to JFJoch before the decorated method touches the API."""
+
+ @functools.wraps(method)
+ def wrapper(self: JFJoch, *args, **kwargs):
+ self.connect()
+ return method(self, *args, **kwargs)
+
+ return wrapper # type: ignore # self is part of P
+
+
+class JFJoch:
+ """Thin wrapper around the JFJoch detector broker REST API, for raster (grid) scans.
+
+ Adapted from aaredaq's `JFJochWrapper`: the client is created on first use and every API
+ call is wrapped so that failures raise `JFJochError`.
+ """
+
+ def __init__(self, client: AareBec, url: str | None = None) -> None:
+ self._client = client
+ self._url = url
+ self._api: jfjoch_client.DefaultApi | None = None
+
+ @property
+ def url(self) -> str:
+ """The broker URL: as given, else resolved on first use from the aarecommon beamline
+ config, which picks the beamline from the BEAMLINE environment variable."""
+ if self._url is None:
+ self._url = get_jfjoch_url(mx_beamline())
+ return self._url
+
+ def connect(self) -> None:
+ """Create the API client on first use and cancel anything JFJoch is still doing."""
+ if self._api is not None:
+ return
+ api_client = jfjoch_client.ApiClient(jfjoch_client.Configuration(host=self.url))
+ self._api = jfjoch_client.DefaultApi(api_client)
+ try:
+ self.cancel()
+ except JFJochError:
+ self._api = None
+ raise
+
+ def _call(self, endpoint: str, *args, **kwargs):
+ """Call `endpoint` on the API, turning any failure into a JFJochError."""
+ assert self._api is not None, "connect() must be called first"
+ try:
+ return getattr(self._api, endpoint)(*args, **kwargs)
+ except Exception as e:
+ raise JFJochError(f"JFJoch {endpoint} failed: {e}") from e
+
+ @needs_connection
+ def cancel(self) -> None:
+ self._call("cancel_post")
+
+ @needs_connection
+ def measure_raster(self, scan: RasterScan, async_start: bool = True) -> None:
+ """Start a raster scan data collection; wait with `wait_till_running` / `wait_till_done`."""
+ self._call("start_post", dataset_settings=self.dataset_settings(scan, async_start))
+
+ @needs_connection
+ def wait_till_running(self, timeout_s: float = 60) -> None:
+ """Block until JFJoch reports the detector armed, or raise."""
+ logger.info("Waiting for JFJoch to report detector armed")
+ try:
+ self._call("wait_until_running_post_with_http_info", timeout=math.ceil(timeout_s))
+ except JFJochError as e:
+ if "Output file already exists" in str(e):
+ raise JFJochError(
+ "JFJoch reports the output file already exists: change the file name or "
+ "increment the run number."
+ ) from e
+ raise
+ status = self._call("status_get")
+ logger.debug(status)
+ if status.message_severity == "error":
+ raise JFJochError(f"JFJoch reported an error after arming: {status.message}")
+
+ @needs_connection
+ def wait_till_done(self, timeout_s: float) -> ScanResult:
+ """Block until the running data collection finished and return its result."""
+ self._call("wait_till_done_post_with_http_info", timeout=math.ceil(timeout_s))
+ return self._call("result_scan_get")
+
+ def dataset_settings(
+ self, scan: RasterScan, async_start: bool = True
+ ) -> jfjoch_client.DatasetSettings:
+ """Build the JFJoch dataset settings for a raster scan."""
+ # a single column is collected as one trigger with n_y images
+ ntrigger, images = (1, scan.n_y) if scan.n_x == 1 else (scan.n_y, scan.n_x)
+ if scan.smargon_phi_deg is not None and scan.smargon_chi_deg is not None:
+ smargon = DatasetSettingsSmargon(
+ phi_deg=scan.smargon_phi_deg, chi_deg=max(scan.smargon_chi_deg, 0)
+ )
+ else:
+ smargon = None
+ return jfjoch_client.DatasetSettings(
+ beam_x_pxl=scan.beam_center_pxl[0],
+ beam_y_pxl=scan.beam_center_pxl[1],
+ ntrigger=ntrigger,
+ images_per_trigger=images,
+ detector_distance_mm=scan.detector_distance_mm,
+ file_prefix=f"{scan.pgroup}/raw/raster/{scan.file_prefix}",
+ incident_energy_keV=scan.energy_keV,
+ sample_name=scan.sample_name,
+ image_time_us=round(scan.exp_time_s * 1e6),
+ experiment_group=scan.pgroup,
+ transmission=scan.transmission,
+ ring_current_mA=scan.ring_current_mA,
+ sample_temperature_K=scan.sample_temperature_K,
+ total_flux=scan.flux_ph_s * scan.transmission,
+ poni_rot1_rad=scan.poni_rot1_rad,
+ poni_rot2_rad=scan.poni_rot2_rad,
+ max_spot_count=1000,
+ detect_ice_rings=True,
+ async_start=async_start,
+ smargon=smargon,
+ beam_size_x_um=scan.beam_size_mm[0] * 1000.0,
+ beam_size_y_um=scan.beam_size_mm[1] * 1000.0,
+ polarization_factor=1.0,
+ images_per_file=self._client.aare_config.jfjoch.n_images_per_file or None,
+ goniometer=jfjoch_client.RotationAxis(
+ step=0, start=scan.omega_deg, name="omega", vector=[-1, 0, 0], screening_wedge_deg=0
+ ),
+ grid_scan=jfjoch_client.GridScan(
+ n_fast=scan.n_x,
+ snake=True,
+ step_x_um=scan.step_x_mm * 1000.0,
+ step_y_um=scan.step_y_mm * 1000.0,
+ vertical=False,
+ ),
+ )
diff --git a/mx_bec/main.py b/mx_bec/main.py
new file mode 100644
index 0000000..a34a81f
--- /dev/null
+++ b/mx_bec/main.py
@@ -0,0 +1,32 @@
+# This file is the entry point for the AareBEC service.
+# It is called either by the aare-bec-proto entry point or directly from the command line.
+import threading
+
+from bec_lib.bec_service import parse_cmdline_args
+from bec_lib.logger import bec_logger
+from bec_lib.redis_connector import RedisConnector
+
+from mx_bec.service import AareBec
+
+logger = bec_logger.logger
+bec_logger.level = bec_logger.LOGLEVEL.INFO
+
+
+def main():
+ """
+ Launch the AareBEC service.
+ """
+ _, _, config = parse_cmdline_args()
+
+ service = AareBec(config, RedisConnector)
+ service.start()
+ try:
+ event = threading.Event()
+ logger.success("Started AareBec")
+ event.wait()
+ except KeyboardInterrupt:
+ service.shutdown()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/mx_bec/messages.py b/mx_bec/messages.py
new file mode 100644
index 0000000..5b7d202
--- /dev/null
+++ b/mx_bec/messages.py
@@ -0,0 +1,61 @@
+import time
+from typing import ClassVar
+
+from aarelcinfer_client.models import LatestPredictionModel
+from bec_lib.messages import BECMessage
+from pydantic import Field
+
+
+class MXMeasurementSequenceMessage(BECMessage):
+ """Published when a step of the MX measurement sequence finishes for a sample."""
+
+ msg_type: ClassVar[str] = "mx_measurement_sequence_message"
+
+ sample_id: int
+ success: bool
+
+
+class MXTaskExecutionMessage(BECMessage):
+ """Used to send commands for custom tasks to the AareBec service."""
+
+ msg_type: ClassVar[str] = "mx_task_execution_message"
+
+ name: str
+ args: tuple[
+ int
+ | bool
+ | str
+ | float
+ | None
+ | dict[str, int | bool | str | float | None]
+ | list[int]
+ | list[float],
+ ...,
+ ]
+ kwargs: dict[str, int | bool | str | float | None | list[int] | list[float]]
+
+
+class MXSampleExecutionMessage(BECMessage):
+ """An entry in the sample queue"""
+
+ msg_type: ClassVar[str] = "mx_sample_execution_message"
+
+ db_id: int
+ sample_name: str
+ # TODO: here add parameters for how to run the sample
+
+
+class MXQueueChangedMessage(BECMessage):
+ """Notification that a queue has changed; carries no data, subscribers
+ re-read the queue."""
+
+ msg_type: ClassVar[str] = "mx_queue_changed_message"
+
+
+class OpticalPredictionMessage(BECMessage):
+ """The latest optical image analysis prediction"""
+
+ msg_type: ClassVar[str] = "mx_optical_prediction_message"
+
+ timestamp: float = Field(default_factory=time.time)
+ prediction: LatestPredictionModel
diff --git a/mx_bec/optical_centering.py b/mx_bec/optical_centering.py
new file mode 100644
index 0000000..a8748c2
--- /dev/null
+++ b/mx_bec/optical_centering.py
@@ -0,0 +1,48 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+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:
+ from mx_bec.service import AareBec
+
+logger = bec_logger.logger
+
+
+class OpticalPrediction:
+ def __init__(self, client: AareBec):
+ self._client = client
+ self._aarelc_client = AareLcClient(base_url=self._client.aare_config.aarelc_infer.host)
+
+ def get_latest(self):
+ response = self._aarelc_client.request("GET", "/predictions/latest").json()
+ prediction = LatestPredictionModel.model_validate(response)
+ logger.info(
+ f"Got AareLc prediction: {prediction.frame_id=}, {prediction.target_point=}, {prediction.image_height=}, {prediction.image_width=}"
+ )
+ return prediction
+
+ def update_latest(self):
+ latest = self.get_latest()
+ logger.info("Updating latest prediction on sample info")
+ if self._client.sample_info:
+ self._client.sample_info.optical_centering_results = OpticalCenteringResults(
+ 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
new file mode 100644
index 0000000..7525550
--- /dev/null
+++ b/mx_bec/sample_info.py
@@ -0,0 +1,51 @@
+from __future__ import annotations
+
+import time
+
+from aarelcinfer_client.models import LatestPredictionModel
+from pydantic import BaseModel, ConfigDict, Field
+
+from mx_bec.decisions import CollectionRecord, GridAnalysis, RasterRecord
+
+
+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)
+
+
+class SampleInfo(BaseModel):
+ """Information about the currently mounted sample. Gradually filled out as information from
+ previous stages is obtained"""
+
+ model_config = ConfigDict(arbitrary_types_allowed=True)
+
+ sample_id: int
+ optical_centering_results: OpticalCenteringResults | None = None
+ raster: RasterRecord | None = None
+ """The latest raster scan: its parameters (for a repeat), geometry and per-image results."""
+ grid_analysis: GridAnalysis | None = None
+ """Crystals and collection spots found in `raster`."""
+ current_offset_mm: tuple[float, float] = (0.0, 0.0)
+ """Where the sample sits relative to the raster start, in the raster plane."""
+ positions_used: list[int] = []
+ """Indices of the `grid_analysis` spots which data has been collected at."""
+ collections: list[CollectionRecord] = []
+ """Every rotation dataset collected so far, with its plan and assessment."""
+ chi_sweeps_done: int = 0
+ recentres: int = 0
+ followups: int = 0
+
+ def next_free_position(self) -> int | None:
+ """Index of the best `grid_analysis` spot not collected at yet, if any is left."""
+ if self.grid_analysis is None:
+ return None
+ for i in range(len(self.grid_analysis.positions)):
+ if i not in self.positions_used:
+ return i
+ return None
diff --git a/mx_bec/service.py b/mx_bec/service.py
new file mode 100644
index 0000000..a46485e
--- /dev/null
+++ b/mx_bec/service.py
@@ -0,0 +1,111 @@
+from __future__ import annotations
+
+import os
+from typing import TYPE_CHECKING
+
+from aare_config import AareConfigClient
+from bec_lib import messages
+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.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
+
+if TYPE_CHECKING:
+ from bec_lib.redis_connector import RedisConnector
+ from bec_lib.service_config import ServiceConfig
+
+ from mx_bec.messages import MXTaskExecutionMessage
+
+
+logger = bec_logger.logger
+
+
+class AareBec(BECClient):
+ """Custom MX BEC client, managing automation tasks and data flow."""
+
+ def __init__(
+ self, config: ServiceConfig, connector_cls: type[RedisConnector], **kwargs
+ ) -> None:
+ if (config_redis_url := os.environ.get("CONFIG_REDIS_URL")) is None:
+ raise RuntimeError(
+ "No address for redis config client specified. "
+ "Set CONFIG_REDIS_URL to 'redis://mx--queue-01:6379'"
+ "if you want to create an AareBec client"
+ )
+ config.model.log_writer.base_path = "/tmp/mx_bec_logs"
+ config.config["log_writer"]["base_path"] = "/tmp/mx_bec_logs"
+
+ super().__init__(config, connector_cls, name="AareBec", **kwargs)
+ self.aare_config = AareConfigClient(redis_url=config_redis_url, key_prefix="config")
+ self.workflow_state = AareBecWorkflowState.IDLE
+ self.actor_manager: AareActorManager | None = None
+ self.optical_prediction = OpticalPrediction(client=self)
+ self.jfjoch = JFJoch(client=self) # connects lazily on first use
+ self.aaredaq = AareDaq(client=self) # authenticates lazily on first use
+ self.tasks = MxTasks[Server](self)
+ self.task_queue: MxTaskQueue | None = None
+ self.sample_info: SampleInfo | None = None
+ # HAX: copy the sample spreadsheet from the beamline redis, to put it into the BEC redis in
+ # start(). To be replaced by the eventual sample database connection module.
+ _, _host, _port = config_redis_url.split(":")
+ _port = int(_port)
+ _hacky_redis = Redis(_host[2:], _port)
+ self._spreadsheet = _hacky_redis.get("x10sa:sample_spreadsheet")
+ _hacky_redis.close()
+
+ def start(self):
+ super().start()
+ self._start_actor_manager()
+ self.task_queue = MxTaskQueue(self, self.tasks)
+ self.task_queue.start()
+ self.connector.register(QueueEndpoints.task_request(), cb=self._on_task_request)
+ self.status = messages.BECStatus.RUNNING
+ # HAX: see __init__; to be replaced by the eventual sample database connection module
+ self.connector._managed_connection.set("x10sa:sample_spreadsheet", self._spreadsheet)
+
+ def _on_task_request(self, msg_dict: dict) -> None:
+ """Append a requested task to the task execution queue, unless it does not name a task
+ of `MxTasks`."""
+ msg: MXTaskExecutionMessage = msg_dict["data"]
+ try:
+ self.tasks.request(msg.name, *msg.args, **msg.kwargs)
+ except UnknownTask as e:
+ logger.warning(f"Rejected task request: {e}")
+
+ def add_task_to_queue(self, task: MXTaskExecutionMessage):
+ """Add a task to the task queue. The task should be validated or guaranteed possible."""
+ self.connector.rpush(QueueEndpoints.task_execution(), task)
+ self.connector.send(QueueEndpoints.task_queue_changed(), MXQueueChangedMessage())
+
+ @property
+ def devices(self):
+ if self.device_manager is None:
+ raise RuntimeError("You must start the client before trying to access devices")
+ return self.device_manager.devices
+
+ def _start_actor_manager(self):
+ self.actor_manager = AareActorManager(self)
+
+ def reset_sample_info(self, sample_id: int):
+ self.sample_info = SampleInfo(sample_id=sample_id)
+
+ def shutdown(self, per_thread_timeout_s: float | None = None) -> None:
+ """shutdown the service"""
+ if self.actor_manager is not None:
+ self.actor_manager.shutdown()
+ self.actor_manager = None
+ if self.started: # the connector only exists once the client has been started
+ self.connector.unregister(QueueEndpoints.task_request(), cb=self._on_task_request)
+ if self.task_queue is not None:
+ self.task_queue.shutdown()
+ self.task_queue = None
+ super().shutdown(per_thread_timeout_s)
diff --git a/mx_bec/states/__init__.py b/mx_bec/states/__init__.py
new file mode 100644
index 0000000..67dc5a3
--- /dev/null
+++ b/mx_bec/states/__init__.py
@@ -0,0 +1,51 @@
+from __future__ import annotations
+
+from numbers import Real
+from typing import Annotated, ClassVar, cast
+
+from bec_lib import messages
+from bec_lib.bl_states import DeviceBeamlineState, DeviceStateConfig
+from bec_lib.scan_args import ScanArgument
+
+
+class DeviceEqualsStateConfig(DeviceStateConfig):
+ """Configuration for a state that is valid while a device signal equals a target value."""
+
+ state_type: ClassVar[str] = "DeviceEqualsState"
+
+ target: Annotated[
+ float,
+ ScanArgument(display_name="Target", description="Value the signal must have to be valid."),
+ ]
+
+
+class DeviceEqualsState(DeviceBeamlineState[DeviceEqualsStateConfig]):
+ """Valid while the monitored signal equals `target`, invalid otherwise."""
+
+ CONFIG_CLASS = DeviceEqualsStateConfig
+
+ def evaluate(
+ self, msg: messages.DeviceMessage, *args, **kwargs
+ ) -> messages.BeamlineStateMessage:
+ config = cast(DeviceEqualsStateConfig, self.config)
+ signal_name = cast(str, self.signal_name)
+ device = self.device_obj.dotted_name
+ val = msg.signals.get(signal_name, {}).get("value", None)
+ if not isinstance(val, Real):
+ return messages.BeamlineStateMessage(
+ name=config.name,
+ status="invalid",
+ label=f"Device {device}: {signal_name} is not a number",
+ )
+ if val == config.target:
+ return messages.BeamlineStateMessage(
+ name=config.name, status="valid", label=f"Device {device} == {config.target}"
+ )
+ return messages.BeamlineStateMessage(
+ name=config.name,
+ status="invalid",
+ label=f"Device {device} is {val}, expected {config.target}",
+ )
+
+
+__all__ = ["DeviceEqualsState", "DeviceEqualsStateConfig"]
diff --git a/mx_bec/tasks/__init__.py b/mx_bec/tasks/__init__.py
new file mode 100644
index 0000000..e433b2f
--- /dev/null
+++ b/mx_bec/tasks/__init__.py
@@ -0,0 +1,28 @@
+"""Tasks which can be requested from the AareBec service: `core` has the machinery (the `task`
+decorator, the Server/Client roles, the task queue), `mx_tasks` the tasks themselves."""
+
+from mx_bec.tasks.core import (
+ BoundTask,
+ Client,
+ MxSequenceUpdate,
+ MxTaskQueue,
+ RoleT,
+ Server,
+ TaskManager,
+ UnknownTask,
+ task,
+)
+from mx_bec.tasks.mx_tasks import MxTasks
+
+__all__ = [
+ "BoundTask",
+ "Client",
+ "MxSequenceUpdate",
+ "MxTaskQueue",
+ "MxTasks",
+ "RoleT",
+ "Server",
+ "TaskManager",
+ "UnknownTask",
+ "task",
+]
diff --git a/mx_bec/tasks/core.py b/mx_bec/tasks/core.py
new file mode 100644
index 0000000..097377c
--- /dev/null
+++ b/mx_bec/tasks/core.py
@@ -0,0 +1,379 @@
+"""
+Role-generic task manager, communicating through the MX task endpoints in Redis.
+
+ class MxTasks(TaskManager[RoleT]):
+ @task
+ def mount(self, dbid: int) -> MxSequenceUpdate: ...
+
+ server = MxTasks[Server](aare_bec) # in the AareBec service: tasks run here
+ client = MxTasks[Client](bec_client) # anywhere else: tasks are requested from the service
+
+ server.mount(3) # runs here, blocking, holding the task lock
+ server.mount.request(3) # appends it to the task execution queue
+ server.request("mount", 3) # the same, looked up by name
+ server.execute(msg) # runs the task named by an MXTaskExecutionMessage
+
+ client.mount(3) # sends a request to the service's task request stream
+ client.mount.request(3) # the same
+ client.request("mount", 3) # the same, looked up by name
+
+Nothing travels back to the requester: a task reports its outcome by returning a state update
+(endpoint, message), which the server publishes once the task is done.
+"""
+
+from __future__ import annotations
+
+import functools
+from collections.abc import Callable
+from threading import Event, RLock, Thread
+from typing import TYPE_CHECKING, Any, ClassVar, Concatenate, Generic, ParamSpec, TypeVar, overload
+
+from bec_lib.config_values import RedisConfigValue
+from bec_lib.endpoints import EndpointInfo
+from bec_lib.logger import bec_logger
+
+from mx_bec.endpoints import QueueEndpoints
+from mx_bec.messages import (
+ MXMeasurementSequenceMessage,
+ MXQueueChangedMessage,
+ MXTaskExecutionMessage,
+)
+
+if TYPE_CHECKING:
+ from bec_lib.client import BECClient
+
+ from mx_bec.service import AareBec
+
+logger = bec_logger.logger
+
+# What a task returns: a state to set and publish once it is done, or nothing.
+MxSequenceUpdate = tuple[EndpointInfo[Any], MXMeasurementSequenceMessage] | None
+
+P = ParamSpec("P")
+S = TypeVar("S", bound="TaskManager[Any]")
+
+Args = tuple[Any, ...]
+Kwargs = dict[str, Any]
+
+
+class UnknownTask(LookupError):
+ """The requested name is not a task of the task manager."""
+
+
+# --------------------------------------------------------------------------- #
+# The decorator / descriptor
+# --------------------------------------------------------------------------- #
+
+
+class task(Generic[S, P]): # pylint: disable=invalid-name
+ """Turns a method into a task. What calling it does depends on the instance's role."""
+
+ def __init__(self, func: Callable[Concatenate[S, P], MxSequenceUpdate]) -> None:
+ self.func = func
+ self.name: str = func.__name__
+ functools.update_wrapper(self, func)
+
+ def __set_name__(self, owner: type, name: str) -> None:
+ self.name = name
+
+ def __call__(self, obj: S, /, *args: P.args, **kwargs: P.kwargs) -> None:
+ """Calling through the class, `MyTasks.some_task(instance, ...)`."""
+ obj._call_task(self, args, kwargs) # pylint: disable=protected-access
+
+ @overload
+ def __get__(self, obj: None, objtype: type | None = None) -> task[S, P]: ...
+ @overload
+ def __get__(self, obj: S, objtype: type | None = None) -> BoundTask[P]: ...
+ def __get__(self, obj: S | None, objtype: type | None = None) -> task[S, P] | BoundTask[P]:
+ if obj is None:
+ return self
+ return BoundTask(self, obj)
+
+ def __repr__(self) -> str:
+ return f""
+
+
+AnyTask = task[Any, ...]
+
+
+class BoundTask(Generic[P]):
+ """A task attached to an instance. Calling it delegates to the instance's role."""
+
+ __slots__ = ("owner", "spec")
+
+ def __init__(self, spec: task[Any, P], owner: TaskManager[Any]) -> None:
+ self.spec = spec
+ self.owner = owner
+
+ def __call__(self, *args: P.args, **kwargs: P.kwargs) -> None:
+ self.owner._call_task(self.spec, args, kwargs) # pylint: disable=protected-access
+
+ def request(self, *args: P.args, **kwargs: P.kwargs) -> None:
+ self.owner._request_task(self.spec, args, kwargs) # pylint: disable=protected-access
+
+ @property
+ def __name__(self) -> str:
+ return self.spec.name
+
+ @property
+ def __doc__(self) -> str | None: # pyright: ignore[reportIncompatibleVariableOverride]
+ return self.spec.__doc__
+
+ def __repr__(self) -> str:
+ return f""
+
+
+# --------------------------------------------------------------------------- #
+# Roles
+# --------------------------------------------------------------------------- #
+
+
+class Role:
+ """Base for the 'fundamental type' a TaskManager is parameterised over. A role is mixed in
+ in front of the TaskManager subclass, so `self` is the task manager instance."""
+
+ # set by TaskManager.__init__
+ _client: BECClient # pyright: ignore[reportUninitializedInstanceVariable]
+
+ def _init_role(self) -> None:
+ """Set up what the role needs; called at the end of TaskManager.__init__."""
+
+ def _call_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None:
+ raise NotImplementedError
+
+ def _request_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None:
+ raise NotImplementedError
+
+
+class Server(Role):
+ """Tasks execute here, one at a time. For the AareBec service: `client` is the service."""
+
+ _busy_lock: RLock # pyright: ignore[reportUninitializedInstanceVariable]
+
+ def _init_role(self) -> None:
+ self._busy_lock = RLock() # reentrant, so that a task can call other tasks
+
+ def _call_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None:
+ """Run the task while holding the lock. If it raises, the task queue is paused before
+ the exception propagates, so that queued tasks don't carry on from a failed state.
+ Otherwise the state update it returned, if any, is published."""
+ with self._busy_lock:
+ try:
+ state_update = spec.func(self, *args, **kwargs)
+ except Exception as e:
+ self._pause_queue_after_failure(spec.name, e)
+ raise
+ logger.info(f"Task: {spec.name} completed.")
+ if state_update:
+ self._client.connector.set_and_publish(*state_update)
+
+ def _request_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None:
+ """Append the task to the execution queue, which the service's MxTaskQueue works off."""
+ msg = MXTaskExecutionMessage(name=spec.name, args=args, kwargs=kwargs)
+ logger.info(f"Queueing task: {msg}")
+ self._client.connector.rpush(QueueEndpoints.task_execution(), msg)
+ self._client.connector.send(QueueEndpoints.task_queue_changed(), MXQueueChangedMessage())
+
+ def _pause_queue_after_failure(self, task_name: str, e: Exception) -> None:
+ # the queue only exists once the service has started
+ if (queue := getattr(self._client, "task_queue", None)) is None:
+ return
+ logger.warning(f"Task {task_name} failed: {e}.\n Pausing the task queue.")
+ try:
+ queue.pause()
+ except Exception: # pylint: disable=broad-except
+ # the task's own exception is the one to surface
+ logger.exception("Failed to pause the task queue")
+
+
+class Client(Role):
+ """Tasks are forwarded to the service through the task request stream. There is no reply,
+ so calling a task and requesting it are the same thing."""
+
+ def _call_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None:
+ self._request_task(spec, args, kwargs)
+
+ def _request_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None:
+ msg = MXTaskExecutionMessage(name=spec.name, args=args, kwargs=kwargs)
+ logger.info(f"Requesting task: {msg}")
+ self._client.connector.xadd(QueueEndpoints.task_request(), {"data": msg})
+
+
+RoleT = TypeVar("RoleT", bound=Role)
+
+
+# --------------------------------------------------------------------------- #
+# The generic base
+# --------------------------------------------------------------------------- #
+
+
+class TaskManager(Generic[RoleT]):
+ """
+ Subclass this as `class MyTasks(TaskManager[RoleT])` and decorate methods with @task.
+ Instantiate as MyTasks[Server](aare_bec_service) or MyTasks[Client](aare_bec_client).
+
+ MyTasks[Role] builds (and caches) a real class whose MRO is
+ (MyTasks[Role], Role, MyTasks, TaskManager, ...), so the role's hooks
+ take effect and isinstance(obj, MyTasks) still holds.
+ """
+
+ _tasks: ClassVar[dict[str, AnyTask]] = {}
+ _role_classes: ClassVar[dict[type, type]]
+
+ def __init__(self, client: AareBec) -> None:
+ self._client = client
+ self._init_role()
+
+ def __init_subclass__(cls, **kwargs: Any) -> None:
+ super().__init_subclass__(**kwargs)
+ cls._tasks = {
+ name: attr
+ for klass in reversed(cls.__mro__)
+ for name, attr in vars(klass).items()
+ if isinstance(attr, task)
+ }
+ cls._role_classes = {}
+
+ def __class_getitem__(cls, role):
+ if not (isinstance(role, type) and issubclass(role, Role)):
+ # TypeVars etc.: normal generic behaviour
+ return super().__class_getitem__(role) # pyright: ignore[reportAttributeAccessIssue]
+ if issubclass(cls, Role):
+ raise TypeError(f"{cls.__name__} already has a role")
+ if role not in cls._role_classes:
+ cls._role_classes[role] = type(
+ f"{cls.__name__}[{role.__name__}]",
+ (role, cls),
+ {
+ "__module__": cls.__module__,
+ "__qualname__": f"{cls.__qualname__}[{role.__name__}]",
+ },
+ )
+ return cls._role_classes[role]
+
+ def __new__(cls, *args: Any, **kwargs: Any):
+ if not issubclass(cls, Role):
+ raise TypeError(
+ f"Instantiate {cls.__name__}[Server](...) or {cls.__name__}[Client](...), "
+ f"not {cls.__name__}(...)"
+ )
+ return super().__new__(cls)
+
+ # Fallbacks so type checkers know every TaskManager has these hooks; the role overrides them.
+ def _init_role(self) -> None:
+ raise NotImplementedError
+
+ def _call_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None:
+ raise NotImplementedError
+
+ def _request_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None:
+ raise NotImplementedError
+
+ # --- public API, the same for every role ---------------------------------
+
+ @classmethod
+ def task_names(cls) -> list[str]:
+ return list(cls._tasks)
+
+ @classmethod
+ def is_task(cls, name: str) -> bool:
+ """Whether `name` can be requested as a task, i.e. is a method decorated with `task`."""
+ return name in cls._tasks
+
+ @classmethod
+ def get_task(cls, name: str) -> AnyTask:
+ try:
+ return cls._tasks[name]
+ except KeyError:
+ raise UnknownTask(f"{name!r} is not a task of {cls.__name__}") from None
+
+ def request(self, task_: str | BoundTask[...] | AnyTask, /, *args: Any, **kwargs: Any) -> None:
+ """Request a task by name or by reference: a server queues it for itself, a client asks
+ the server. Raises UnknownTask for a name which is not a task."""
+ if isinstance(task_, BoundTask):
+ spec = task_.spec
+ elif isinstance(task_, task):
+ spec = task_
+ else:
+ spec = self.get_task(task_)
+ self._request_task(spec, args, kwargs)
+
+ def execute(self, msg: MXTaskExecutionMessage) -> None:
+ """Call the task named by `msg` with its arguments, as if it had been called directly.
+ Raises UnknownTask for a name which is not a task."""
+ self._call_task(self.get_task(msg.name), msg.args, msg.kwargs)
+
+
+# --------------------------------------------------------------------------- #
+# The queue the server works off
+# --------------------------------------------------------------------------- #
+
+
+class MxTaskQueue:
+ """Executes requested tasks one at a time, in order, on a background thread.
+
+ Tasks are popped from the left of the `QueueEndpoints.task_execution()` list and run on the
+ given task manager. The queue can be paused through the `QueueEndpoints.task_queue_paused()`
+ config value (from any client): no new task is popped while paused, but a task which is
+ already running is left to finish.
+ """
+
+ def __init__(
+ self, client: BECClient, tasks: TaskManager[Server], poll_interval_s: float = 0.5
+ ) -> None:
+ self._client = client
+ self._tasks = tasks
+ self._poll_interval_s = poll_interval_s
+ self._stop_event = Event()
+ self._paused: RedisConfigValue[bool] = RedisConfigValue(
+ connector=client.connector, endpoint=QueueEndpoints.task_queue_paused()
+ )
+ self._thread = Thread(target=self._run, name="MxTaskQueue", daemon=True)
+
+ @property
+ def paused(self) -> bool:
+ return self._paused.value
+
+ def pause(self) -> None:
+ """Stop taking new tasks from the queue; the current task finishes."""
+ self._paused.value = True
+
+ def resume(self) -> None:
+ """Start taking tasks from the queue again."""
+ self._paused.value = False
+
+ def start(self) -> None:
+ self._thread.start()
+
+ def shutdown(self) -> None:
+ """Stop the queue thread, waiting for a running task to finish, and drop the Redis
+ subscription of the paused flag."""
+ self._stop_event.set()
+ if self._thread.is_alive():
+ self._thread.join()
+ self._paused.unregister_all()
+
+ def _run(self) -> None:
+ while not self._stop_event.is_set():
+ if self._paused.value:
+ self._stop_event.wait(self._poll_interval_s)
+ continue
+ msg = self._client.connector.blocking_list_pop(
+ QueueEndpoints.task_execution(), side="LEFT", timeout_s=self._poll_interval_s
+ )
+ if msg is not None:
+ self._client.connector.send(
+ QueueEndpoints.task_queue_changed(), MXQueueChangedMessage()
+ )
+ self.execute(msg)
+
+ def execute(self, msg: MXTaskExecutionMessage) -> None:
+ """Run a single task. Failures are logged and do not stop the queue thread (a task
+ manager with the Server role pauses the queue when one of its tasks fails)."""
+ logger.info(f"Running task {msg.name} with args={msg.args}, kwargs={msg.kwargs}")
+ try:
+ self._tasks.execute(msg)
+ except UnknownTask as e:
+ logger.warning(f"Skipping queued task: {e}")
+ except Exception: # pylint: disable=broad-except
+ logger.exception(f"Task {msg.name} failed")
diff --git a/mx_bec/tasks/mx_tasks.py b/mx_bec/tasks/mx_tasks.py
new file mode 100644
index 0000000..00b7834
--- /dev/null
+++ b/mx_bec/tasks/mx_tasks.py
@@ -0,0 +1,319 @@
+from __future__ import annotations
+
+from secrets import token_hex
+from typing import TYPE_CHECKING
+
+from aarecommon.math.coordinate import Coordinate, SmargonCoordinate
+from aarecommon.models.raster_grid import CompletedRasterGrid # already imported in aaredaq.py
+from aarecommon.models.raster_grid import RasterGridRequest
+from aarecommon.models.rotation_scan import RotationScanRequest
+from bec_lib.logger import bec_logger
+
+from mx_bec.decisions import (
+ CollectionRecord,
+ GridGeometry,
+ RasterRecord,
+ RotationPlan,
+ SweepRecord,
+ scan_images,
+ smargon_nudge,
+)
+from mx_bec.device_planner import BeamlineState, StateChangePlanner, init_beamline_environment
+from mx_bec.endpoints import StateEndpoints
+from mx_bec.messages import MXMeasurementSequenceMessage
+from mx_bec.tasks.core import MxSequenceUpdate, RoleT, TaskManager, task
+
+if TYPE_CHECKING:
+ from mx_bec.service import AareBec
+
+logger = bec_logger.logger
+
+
+class MxTasks(TaskManager[RoleT]):
+ """The operations on mx beamlines which can be requested as tasks. Instantiate as
+ `MxTasks[Server](aare_bec)` in the AareBec service, where the tasks run, or as
+ `MxTasks[Client](bec_client)` anywhere else, to request them from the service.
+
+ TODO:
+ - categorise tasks
+ - add doc info to decorator, including placeholder for args, to show to GUI
+ """
+
+ if TYPE_CHECKING:
+ # the tasks only run in the service
+ _client: AareBec # pyright: ignore[reportIncompatibleVariableOverride]
+
+ _planner: StateChangePlanner | None = None
+
+ @property
+ def planner(self) -> StateChangePlanner:
+ """The beamline state planner, built on first use: `init_beamline_environment` needs the
+ BEAMLINE environment variable and the beamline devices."""
+ if self._planner is None:
+ _, _, self._planner = init_beamline_environment(
+ self._client.devices, self._client.scans
+ )
+ return self._planner
+
+ @task
+ def run_optical_centering(self, sample_id: int):
+ """warning: Updates the sample id to whatever you enter even if it's not the real one!"""
+ if self._client.sample_info is None or self._client.sample_info.sample_id != sample_id:
+ self._client.reset_sample_info(sample_id)
+ self._client.aaredaq.auto_loop_center()
+ self._client.scans.mv(self._client.devices.scam_zoom, 400, relative=False).wait()
+ self._client.optical_prediction.update_latest()
+ return self._optical_centering_done_update(sample_id, success=True)
+
+ def _optical_centering_done_update(self, sample_id: int, *, success: bool):
+ return (
+ StateEndpoints.optical_centering_done(),
+ MXMeasurementSequenceMessage(sample_id=sample_id, success=success),
+ )
+
+ @task
+ def change_state(self, state: str, modifier: str | None = None) -> None:
+ """Move the beamline devices to `state`, the value of a `BeamlineState` (e.g.
+ "sample_alignment"), optionally with a temperature `modifier` ("cryo" or "room_temp")."""
+ target = BeamlineState(state) # reject unknown states before anything moves
+ logger.info(f"Changing beamline state to {target.value}, modifier={modifier}")
+ self.planner.move_to(target, modifier)
+
+ @task
+ def aaredaq_mount_sample(self, dbid: int, reference: bool = False) -> MxSequenceUpdate:
+ """Have AareDAQ mount the sample with database id `dbid` (a reference tool if
+ `reference`)."""
+ self._client.aaredaq.mount_sample(dbid, reference=reference)
+ self._client.reset_sample_info(dbid)
+ return (
+ StateEndpoints.sample_mounted(),
+ MXMeasurementSequenceMessage(sample_id=dbid, success=True),
+ )
+
+ @task
+ def cleanup_beamline(self):
+ """Unmount the current sample and send the gripper to dry"""
+ self._client.aaredaq.unmount_sample_then_park()
+
+ @task
+ def multiple_rasters(
+ self,
+ omegas_deg_list: list[float],
+ n_x: int,
+ n_y: int,
+ step_x_mm: float,
+ step_y_mm: float,
+ exp_time_s: float,
+ file_prefix: str | None = None,
+ dtz: float | None = None,
+ ) -> MxSequenceUpdate:
+ """Run multiple raster scans at different omega values"""
+ for i, omega in enumerate(omegas_deg_list):
+ self._run_raster(
+ n_x,
+ n_y,
+ step_x_mm,
+ step_y_mm,
+ exp_time_s,
+ file_prefix=f"{file_prefix}_{i}_{omega:.2f}deg_{token_hex(3)}",
+ dtz=dtz,
+ omega_deg=omega,
+ )
+ logger.info(f"Raster {i + 1} out of {len(omegas_deg_list)} done.")
+ return (
+ StateEndpoints.sample_done(),
+ MXMeasurementSequenceMessage(
+ sample_id=self._client.sample_info.sample_id, success=True
+ ),
+ )
+
+ @task
+ def aaredaq_rotation_scan(
+ self,
+ exp_time_s: float,
+ incr_omega_deg: float,
+ steps: int,
+ start_omega_deg: float = 0.0,
+ file_prefix: str | None = None,
+ dtz: float | None = None,
+ transmission: float | None = None,
+ screening: bool = False,
+ wedge_omega_deg: float | None = None,
+ ) -> None:
+ """Have AareDAQ run a rotation (or screening) scan of `steps` images of `incr_omega_deg`
+ each, starting at the current Smargon position (`start`/`end` are left unset)."""
+ request = RotationScanRequest(
+ exp_time_s=exp_time_s,
+ incr_omega_deg=incr_omega_deg,
+ steps=steps,
+ start_omega_deg=start_omega_deg,
+ file_prefix=file_prefix,
+ dtz=dtz,
+ transmission=transmission,
+ screening=screening,
+ wedge_omega_deg=wedge_omega_deg,
+ )
+ result = self._client.aaredaq.rotation_scan(request)
+ logger.info(f"AareDAQ rotation scan done: {len(result.result.images)} images")
+
+ def _run_raster(
+ self,
+ n_x: int,
+ n_y: int,
+ step_x_mm: float,
+ step_y_mm: float,
+ exp_time_s: float,
+ omega_deg: float = 0.0,
+ file_prefix: str | None = None,
+ dtz: float | None = None,
+ transmission: float | None = None,
+ smargon_top_left: SmargonCoordinate | None = None,
+ auto_center: bool = False,
+ ) -> CompletedRasterGrid:
+ if not smargon_top_left:
+ x_offset_mm = n_x * step_x_mm * 0.5
+ y_offset_mm = n_y * step_y_mm * 0.5
+ logger.info(
+ f"offsetting smargon x,y by half of grid: {x_offset_mm=} {y_offset_mm=} (grid x to smargon z)"
+ )
+ smargon = self._client.devices.smargon
+ # aerotech = self._client.devices.aerotech
+ adjustment = smargon_nudge(
+ smargon.phi.get(),
+ smargon.chi.get(),
+ omega_deg,
+ Coordinate(x=x_offset_mm, y=y_offset_mm, z=0),
+ )
+ smargon_top_left = SmargonCoordinate(
+ sh_mm=Coordinate(x=smargon.x.get(), y=smargon.y.get(), z=smargon.z.get())
+ - adjustment,
+ chi_deg=smargon.chi.get(),
+ phi_deg=smargon.phi.get(),
+ )
+ logger.info(f"Smargon top left: {smargon_top_left}")
+ request = RasterGridRequest(
+ n_x=n_x,
+ n_y=n_y,
+ grid_size_mm=Coordinate(x=step_x_mm, y=step_y_mm),
+ exp_time_s=exp_time_s,
+ omega_deg=omega_deg,
+ file_prefix=file_prefix,
+ dtz=dtz,
+ transmission=transmission,
+ smargon_top_left=smargon_top_left,
+ )
+ result = self._client.aaredaq.raster_scan(request, auto_center=auto_center)
+ logger.info(f"Raster scan finished with {len(scan_images(result))} images")
+ return result
+
+ @task
+ def aaredaq_raster_scan(
+ self,
+ n_x: int,
+ n_y: int,
+ step_x_mm: float,
+ step_y_mm: float,
+ exp_time_s: float,
+ omega_deg: float = 0.0,
+ file_prefix: str | None = None,
+ dtz: float | None = None,
+ transmission: float | None = None,
+ smargon_top_left: SmargonCoordinate | None = None,
+ auto_center: bool = False,
+ ) -> None:
+ self._run_raster(
+ n_x,
+ n_y,
+ step_x_mm,
+ step_y_mm,
+ exp_time_s,
+ omega_deg,
+ file_prefix,
+ dtz,
+ transmission,
+ smargon_top_left,
+ auto_center,
+ )
+
+ @task
+ def xray_centering(self, dbid: int, strategy: dict) -> MxSequenceUpdate:
+ result = self._run_raster(**strategy)
+ info = self._client.sample_info
+ if info is None or info.sample_id != dbid:
+ self._client.reset_sample_info(dbid)
+ info = self._client.sample_info
+ info.raster = RasterRecord(
+ strategy=dict(strategy),
+ geometry=GridGeometry(
+ n_x=strategy["n_x"],
+ n_y=strategy["n_y"],
+ step_x_mm=strategy["step_x_mm"],
+ step_y_mm=strategy["step_y_mm"],
+ omega_deg=strategy.get("omega_deg", 0.0),
+ snake=True, # jfjoch.dataset_settings uses GridScan(snake=True)
+ ),
+ images=scan_images(result),
+ )
+ return (
+ StateEndpoints.xray_centering_done(),
+ MXMeasurementSequenceMessage(sample_id=dbid, success=True),
+ )
+
+ def _move_to_grid_offset(self, offset_x_mm: float, offset_y_mm: float) -> None:
+ """Move to a point given relative to the raster start, in the raster plane.
+
+ Rotates omega back to the raster angle first, so the lab-frame nudge is in the plane the
+ grid was measured in. CHECK on the beamline: sign and axis mapping of grid x/y to
+ nudge_in_lab_frame x/y.
+ """
+ info = self._client.sample_info
+ assert info is not None, "No sample loaded"
+ omega = info.raster.geometry.omega_deg if info.raster else 0.0
+ dx = offset_x_mm - info.current_offset_mm[0]
+ dy = offset_y_mm - info.current_offset_mm[1]
+ if abs(dx) < 1e-4 and abs(dy) < 1e-4:
+ return
+ self._client.devices.aerotech.u.set(omega).wait()
+ self._client.devices.smargon.nudge_in_lab_frame(dx, dy, omega_deg=omega)
+ info.current_offset_mm = (offset_x_mm, offset_y_mm)
+
+ @task
+ def move_to_grid_offset(self, dbid: int, offset_x_mm: float, offset_y_mm: float) -> None:
+ self._move_to_grid_offset(offset_x_mm, offset_y_mm)
+
+ @task
+ def collect_dataset(self, dbid: int, plan: dict) -> MxSequenceUpdate:
+ """Rotation data at a planned grid spot, one sweep per chi value."""
+ p = RotationPlan.model_validate(plan)
+ self._move_to_grid_offset(p.offset_x_mm, p.offset_y_mm)
+ smargon = self._client.devices.smargon
+ record = CollectionRecord(plan=p)
+ try:
+ for chi in p.chi_values():
+ smargon.chi.set(chi).wait()
+ request = RotationScanRequest(
+ exp_time_s=p.exp_time_s,
+ incr_omega_deg=p.incr_omega_deg,
+ steps=p.steps,
+ start_omega_deg=p.start_omega_deg,
+ file_prefix=f"{p.file_prefix}_chi{chi:g}",
+ dtz=p.dtz,
+ transmission=p.transmission,
+ )
+ result = self._client.aaredaq.rotation_scan(request)
+ record.sweeps.append(
+ SweepRecord(
+ chi_deg=chi,
+ images=scan_images(result),
+ bravais=getattr(result.result, "rotation_bravais", None),
+ )
+ )
+ finally:
+ smargon.chi.set(0.0).wait()
+ info = self._client.sample_info
+ assert info is not None, "No sample loaded"
+ info.collections.append(record)
+ return (
+ StateEndpoints.rotation_done(),
+ MXMeasurementSequenceMessage(sample_id=dbid, success=True),
+ )
diff --git a/pyproject.toml b/pyproject.toml
index c2d5587..e0f792d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -12,12 +12,24 @@ classifiers = [
"Programming Language :: Python :: 3",
"Topic :: Scientific/Engineering",
]
-dependencies = []
+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
+ "bec_lib>=3.130.3",
+ "bec-server>=3.130.3",
+ "bec-ipython-client>=3.130.3",
+ "ophyd_devices>=1.46",
+ "pydantic>=2.11",
+]
[project.optional-dependencies]
dev = [
"black",
"copier",
+ "basedpyright",
+ "ruff>=0.15",
"isort",
"coverage",
"pylint",
@@ -25,6 +37,14 @@ dev = [
"pytest-random-order",
"ophyd_devices",
"bec_server",
+ "pytest",
+ "pytest-mock",
+ "pytest-asyncio",
+ "pytest-timeout",
+ "pytest-bec-e2e", # fixtures which start BEC servers for the end-to-end tests
+ "fakeredis[lua]",
+ "fastapi",
+ "uvicorn",
]
[tool.hatch.build.targets.wheel]
@@ -52,9 +72,11 @@ good-names-rgxs = [
".*_1D.*",
]
+[project.scripts]
+mx-bec-service = "mx_bec.main:main"
+
[tool.ruff]
line-length = 100
[tool.ruff.format]
skip-magic-trailing-comma = true
-
diff --git a/tests/e2e/conftest.py b/tests/e2e/conftest.py
new file mode 100644
index 0000000..337825c
--- /dev/null
+++ b/tests/e2e/conftest.py
@@ -0,0 +1,56 @@
+"""Fixtures for the end-to-end tests, which run against real BEC servers with the simulated MX
+beamline loaded. They build on the `pytest_bec_e2e` plugin; run them with
+
+ pytest --start-servers --files-path tests/e2e
+
+which starts a Redis server and the BEC servers for the test session (without `--start-servers`
+they have to be running already).
+"""
+
+import pytest
+from bec_lib.client import BECClient
+from bec_lib.redis_connector import RedisConnector
+from bec_lib.service_config import ServiceConfig
+from bec_lib.tests.utils import wait_for_empty_queue
+
+from mx_bec.configs import MX_SIMULATED_DEVICES, load_mx_simulated_config, render_config
+from mx_bec.device_planner import SIMULATED
+
+CLIENT_SHUTDOWN_TIMEOUT_S = 10
+
+
+@pytest.fixture(scope="session")
+def test_config_yaml_file_path():
+ """The device config which `bec_servers` (pytest_bec_e2e) copies next to the service config."""
+ return render_config(MX_SIMULATED_DEVICES)
+
+
+@pytest.fixture(scope="session")
+def simulated_bec_session(bec_redis_fixture, bec_services_config_file_path, bec_servers):
+ """A BEC client connected to the test servers, with the simulated beamline loaded once for
+ the whole session."""
+ config = ServiceConfig(bec_services_config_file_path)
+ bec = BECClient(config, RedisConnector, forced=True, wait_for_server=True)
+ bec.start()
+ load_mx_simulated_config(bec, force=True)
+ try:
+ yield bec
+ finally:
+ bec.shutdown(per_thread_timeout_s=CLIENT_SHUTDOWN_TIMEOUT_S)
+ bec._client._reset_singleton()
+
+
+@pytest.fixture
+def bec(simulated_bec_session):
+ """The client on the simulated beamline, with an empty, running scan queue."""
+ bec = simulated_bec_session
+ bec.queue.request_queue_reset()
+ bec.queue.request_scan_continuation()
+ wait_for_empty_queue(bec)
+ return bec
+
+
+@pytest.fixture
+def simulated_beamline(monkeypatch):
+ """Select the simulated beamline for the device planner."""
+ monkeypatch.setenv("BEAMLINE", SIMULATED)
diff --git a/tests/e2e/test_simulated_beamline.py b/tests/e2e/test_simulated_beamline.py
new file mode 100644
index 0000000..563f877
--- /dev/null
+++ b/tests/e2e/test_simulated_beamline.py
@@ -0,0 +1,74 @@
+"""The simulated beamline for development (BEAMLINE=SIMULATED), on real BEC servers."""
+
+import pytest
+import yaml
+
+from mx_bec.configs import MX_SIMULATED_DEVICES
+from mx_bec.device_planner import BeamlineState, TemperatureMode, init_beamline_environment
+
+MOVE_TIMEOUT_S = 30
+
+
+def _value(device) -> float:
+ return next(iter(device.read(cached=False).values()))["value"]
+
+
+def test_all_simulated_devices_are_loaded(bec):
+ config = yaml.safe_load(MX_SIMULATED_DEVICES.read_text())
+ assert set(config) <= set(bec.device_manager.devices.keys())
+
+
+@pytest.mark.parametrize(
+ "name, target",
+ [("bl_pos", 1), ("bl_pos", 0), ("det_cov", 2), ("cryo_pos", 0), ("bl_bright", 1.3)],
+)
+def test_simulated_signals_can_be_moved_with_a_scan(bec, name, target):
+ device = bec.device_manager.devices[name]
+ bec.scans.mv(device, target, relative=False).wait(timeout=MOVE_TIMEOUT_S)
+ assert _value(device) == pytest.approx(target)
+
+
+def test_simulated_signals_can_be_written_directly(bec):
+ """What the device planner does for a device with `move_method: signal`."""
+ shutter = bec.device_manager.devices.bcu_shutter
+ for target in (1, 0):
+ shutter.put(target)
+ assert _value(shutter) == target
+
+
+@pytest.mark.parametrize(
+ "path, target, tolerance",
+ [
+ ("bs_z", 45.1, 0.1),
+ ("aerotech.x", -2.0, 0.01),
+ ("aerotech.u", 90.0, 0.01),
+ ("smargon.z", 1.8, 0.01),
+ ("smargon.chi", 10.0, 0.01),
+ ],
+)
+def test_simulated_positioners_reach_their_target(bec, path, target, tolerance):
+ """The stages have to get as close to a named position as the device planner checks it."""
+ device = bec.device_manager.devices
+ for part in path.split("."):
+ device = getattr(device, part)
+ bec.scans.mv(device, target, relative=False).wait(timeout=MOVE_TIMEOUT_S)
+ assert _value(device) == pytest.approx(target, abs=tolerance)
+
+
+def test_device_planner_moves_between_beamline_states(bec, simulated_beamline):
+ env, devices, planner = init_beamline_environment(bec.device_manager.devices, bec.scans)
+ assert env.simulated
+ assert set(planner.available_states()) == set(BeamlineState)
+
+ for state, modifier in [
+ (BeamlineState.ROBOT_SAMPLE_EXCHANGE, TemperatureMode.CRYO),
+ (BeamlineState.DATA_COLLECTION, TemperatureMode.CRYO),
+ (BeamlineState.BEAM_VISUALISATION, None),
+ (BeamlineState.MANUAL_SAMPLE_EXCHANGE, TemperatureMode.ROOM_TEMP),
+ (BeamlineState.SAMPLE_ALIGNMENT, TemperatureMode.CRYO),
+ ]:
+ planner.move_to(state, modifier)
+ assert planner.is_state(state), (state, planner.get_positions())
+ target = planner._merged_state(state, modifier)
+ assert all(devices[name].is_at(position) for name, position in target.items())
+ assert _value(bec.device_manager.devices.bcu_shutter) == 0 # closed before anything moves
diff --git a/tests/unit/mock_smargopolo.py b/tests/unit/mock_smargopolo.py
new file mode 100644
index 0000000..41f1ca2
--- /dev/null
+++ b/tests/unit/mock_smargopolo.py
@@ -0,0 +1,160 @@
+"""A mock smargopolo REST interface with mock motors, for testing devices against.
+
+Adapted from pxii_bec/tests/tests_devices/mock_smargopolo.py.
+Run it standalone with `python mock_smargopolo.py` or in-process via `run_in_thread()`.
+"""
+
+import asyncio
+import random
+import socket
+import time
+from collections.abc import Iterable
+from contextlib import asynccontextmanager
+from threading import Thread
+from typing import Annotated
+
+import uvicorn
+from fastapi import FastAPI, HTTPException, Query, Request
+
+AxisQuery = Annotated[list[str] | None, Query()]
+
+AXES = ["SHX", "SHY", "SHZ", "PHI", "CHI"]
+
+
+class Motor:
+ def __init__(self, velocity: float = 1.0, position: float = 0.0):
+ self.position = position
+ self.target = position
+ self.velocity = velocity
+ self.moving = False
+ self._last_update = time.monotonic()
+
+ def update(self):
+ now = time.monotonic()
+ dt = now - self._last_update
+ self._last_update = now
+
+ if not self.moving:
+ return
+
+ jitter_factor = random.random() * 0.05 - 0.025 # +- 2.5% jitter in step
+ distance = self.target - self.position
+ direction = 1 if distance > 0 else -1
+ step = direction * self.velocity * dt
+
+ if abs(step) >= abs(distance):
+ self.position = self.target + (step * jitter_factor)
+ self.moving = False
+ else:
+ self.position += step * (1 + jitter_factor)
+
+
+def make_motors() -> dict[str, Motor]:
+ return {
+ "SHX": Motor(velocity=3),
+ "SHY": Motor(velocity=2.5),
+ "SHZ": Motor(velocity=2),
+ "PHI": Motor(velocity=1.0),
+ "CHI": Motor(velocity=0.7),
+ }
+
+
+motors: dict[str, Motor] = make_motors()
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+ async def updater():
+ while True:
+ for motor in motors.values():
+ motor.update()
+ await asyncio.sleep(0.02) # 50 Hz update loop
+
+ task = asyncio.create_task(updater())
+ yield
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+
+
+app = FastAPI(lifespan=lifespan)
+
+
+def validate_axes(axes: Iterable[str] | None) -> list[str]:
+ if axes is None:
+ return AXES
+ for a in axes:
+ if a not in AXES:
+ raise HTTPException(status_code=404, detail=f"Unknown axis: {a}")
+ return list(axes)
+
+
+@app.get("/readbackSCS")
+async def readback_scs(axis: AxisQuery = None):
+ selected_axes = validate_axes(axis)
+ return {ax: motors[ax].position for ax in selected_axes}
+
+
+@app.get("/targetSCS")
+async def get_target_scs(axis: AxisQuery = None):
+ selected_axes = validate_axes(axis)
+ return {ax: motors[ax].target for ax in selected_axes}
+
+
+@app.put("/targetSCS")
+async def target_scs(req: Request):
+ targets = {ax: float(t) for ax, t in req.query_params.items()}
+ selected_axes = validate_axes(targets.keys())
+
+ for a in selected_axes:
+ motor = motors[a]
+ motor.update()
+ motor.target = targets[a]
+ motor.moving = True
+
+ return {"targets": targets, "message": "Move started"}
+
+
+def free_port() -> int:
+ with socket.socket() as sock:
+ sock.bind(("127.0.0.1", 0))
+ return sock.getsockname()[1]
+
+
+class MockSmargopolo:
+ """The mock server running in a background thread, for use in tests."""
+
+ def __init__(self, port: int | None = None):
+ self.port = port if port is not None else free_port()
+ self.url = f"http://127.0.0.1:{self.port}"
+ self._server = uvicorn.Server(
+ uvicorn.Config(app, host="127.0.0.1", port=self.port, log_level="warning")
+ )
+ self._thread = Thread(target=self._server.run, daemon=True)
+
+ def start(self, timeout: float = 5.0):
+ motors.clear()
+ motors.update(make_motors())
+ self._thread.start()
+ deadline = time.monotonic() + timeout
+ while not self._server.started:
+ if time.monotonic() > deadline:
+ raise TimeoutError("Mock smargopolo did not start")
+ time.sleep(0.01)
+ return self
+
+ def stop(self):
+ self._server.should_exit = True
+ self._thread.join(timeout=5)
+
+ def __enter__(self):
+ return self.start()
+
+ def __exit__(self, *exc):
+ self.stop()
+
+
+if __name__ == "__main__":
+ uvicorn.run(app, host="0.0.0.0", port=8000, reload=False)
diff --git a/tests/unit/test_aaredaq.py b/tests/unit/test_aaredaq.py
new file mode 100644
index 0000000..88ade01
--- /dev/null
+++ b/tests/unit/test_aaredaq.py
@@ -0,0 +1,243 @@
+import subprocess
+from unittest.mock import MagicMock, call, patch
+
+import pytest
+from aarecommon.math.coordinate import Coordinate, SmargonCoordinate
+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
+
+URL, CERT, TOKEN = "https://daq.test", "/certs/daq.crt", "eyJ.abc.def"
+
+
+def _curl_result(stdout='{"access_token": "' + TOKEN + '"}', returncode=0, stderr=""):
+ return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr=stderr)
+
+
+def _response(status_code=200, json_data=None, text=""):
+ resp = MagicMock(status_code=status_code, ok=200 <= status_code < 300, text=text)
+ resp.json.return_value = json_data
+ return resp
+
+
+@pytest.fixture
+def curl():
+ with patch("mx_bec.aaredaq.subprocess.run", return_value=_curl_result()) as run:
+ yield run
+
+
+def _status(you_are_holder: bool) -> dict:
+ return BatonStatus(you_are_holder=you_are_holder).model_dump(mode="json")
+
+
+@pytest.fixture
+def daq(curl):
+ """Client with a mocked HTTP session: by default this session holds the baton and every
+ POST answers "OK"."""
+ daq = AareDaq(MagicMock(), url=URL, cert_path=CERT)
+ daq._session = MagicMock()
+ responses = {"GET": _response(json_data=_status(True)), "POST": _response(json_data="OK")}
+ daq._session.request.side_effect = lambda method, *a, **k: responses[method]
+ daq._responses = responses
+ return daq
+
+
+def _calls(daq, method):
+ """(url, kwargs) of the recorded requests of the given method, in order."""
+ return [
+ (c.args[1], c.kwargs) for c in daq._session.request.call_args_list if c.args[0] == method
+ ]
+
+
+def _set_posts(daq, *responses):
+ """Make successive POSTs answer with the given responses (GETs keep the default)."""
+ posts = iter(responses)
+ daq._session.request.side_effect = lambda method, *a, **k: (
+ next(posts) if method == "POST" else daq._responses["GET"]
+ )
+
+
+def _raster_request():
+ return RasterGridRequest(
+ n_x=2,
+ n_y=1,
+ grid_size_mm=Coordinate(x=0.05, y=0.05),
+ file_prefix="t",
+ exp_time_s=0.1,
+ dtz=150,
+ transmission=1,
+ smargon_top_left=SmargonCoordinate(),
+ omega_deg=0.0,
+ )
+
+
+def test_url_and_cert_are_resolved_from_beamline_config_on_first_use(curl, monkeypatch):
+ 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,
+ ):
+ assert daq.url == DEFAULT_URLS["X10SA"]
+ assert daq.cert_path == "/sls/x10sa/misc/.cert/10s.crt"
+ assert cfg_get.call_args_list[0].args[0] == "gui.daq.daq_url"
+
+
+def test_token_is_requested_lazily_by_kerberos_curl(daq, curl):
+ curl.assert_not_called()
+ assert daq.token == TOKEN
+ assert daq.token == TOKEN
+ curl.assert_called_once()
+ cmd = curl.call_args.args[0]
+ assert cmd[0] == "curl" and "--negotiate" in cmd and cmd[-1] == f"{URL}/token"
+ assert cmd[cmd.index("--cacert") + 1] == CERT
+
+
+@pytest.mark.parametrize(
+ "result, match",
+ [
+ (_curl_result(returncode=6, stderr="could not resolve"), "curl exit 6"),
+ (_curl_result(stdout=""), "not JSON"),
+ (_curl_result(stdout="{}"), "no access_token"),
+ ],
+)
+def test_token_request_failures(daq, curl, result, match):
+ curl.return_value = result
+ with pytest.raises(AareDaqError, match=match):
+ _ = daq.token
+
+
+def test_token_request_timeout(daq, curl):
+ curl.side_effect = subprocess.TimeoutExpired(cmd="curl", timeout=120)
+ with pytest.raises(AareDaqError, match="token request failed"):
+ _ = daq.token
+
+
+def test_mount_sample(daq):
+ daq.mount_sample(42)
+ assert _calls(daq, "POST") == [
+ (
+ f"{URL}/sample/mount",
+ {
+ "params": {"dbid": 42, "reference": False},
+ "json": None,
+ "headers": {"Authorization": f"Bearer {TOKEN}"},
+ "verify": CERT,
+ "timeout": 600.0,
+ },
+ )
+ ]
+
+
+def test_raster_scan(daq):
+ request = _raster_request()
+ completed = CompletedRasterGrid(r=[])
+ _set_posts(daq, _response(json_data=completed.model_dump(mode="json")))
+ assert daq.raster_scan(request, auto_center=True) == completed
+ [(url, kwargs)] = _calls(daq, "POST")
+ assert url == f"{URL}/scan/raster"
+ assert kwargs["params"] == {"auto_center": True}
+ assert kwargs["json"] == request.model_dump(mode="json")
+ assert kwargs["timeout"] == 3600.0
+
+
+def test_rotation_scan(daq):
+ request = RotationScanRequest(exp_time_s=0.05, incr_omega_deg=0.1, steps=100)
+ completed = CompletedRotationScan(request=request, result={"images": []})
+ _set_posts(daq, _response(json_data=completed.model_dump(mode="json")))
+ assert daq.rotation_scan(request) == completed
+ [(url, kwargs)] = _calls(daq, "POST")
+ assert url == f"{URL}/scan/rotation"
+ assert kwargs["json"] == request.model_dump(mode="json")
+
+
+def test_expired_token_is_renewed_once(daq, curl):
+ curl.side_effect = [_curl_result(), _curl_result('{"access_token": "new"}')]
+ _set_posts(daq, _response(401), _response(json_data="OK"))
+ daq.mount_sample(1)
+ headers = [kwargs["headers"]["Authorization"] for _, kwargs in _calls(daq, "POST")]
+ assert headers == [f"Bearer {TOKEN}", "Bearer new"]
+ assert daq.token == "new"
+
+
+def test_persistent_401_is_an_error(daq):
+ _set_posts(daq, _response(401, text="nope"), _response(401, text="nope"))
+ with pytest.raises(AareDaqError, match="401"):
+ daq.mount_sample(1)
+ assert len(_calls(daq, "POST")) == 2
+
+
+def test_http_error_reports_status_and_body(daq):
+ _set_posts(daq, _response(422, text='{"detail": "bad request"}'))
+ with pytest.raises(AareDaqError, match="422.*bad request"):
+ daq.rotation_scan(RotationScanRequest(exp_time_s=0.05, incr_omega_deg=0.1, steps=1))
+
+
+# ---- baton ----
+
+
+def test_baton_status(daq):
+ assert daq.baton_status() == BatonStatus(you_are_holder=True)
+ [(url, kwargs)] = _calls(daq, "GET")
+ assert url == f"{URL}/baton/status" and kwargs["timeout"] == 30.0
+
+
+def test_hardware_calls_skip_the_baton_request_when_already_holder(daq):
+ daq.mount_sample(1)
+ assert [url for url, _ in _calls(daq, "POST")] == [f"{URL}/sample/mount"]
+
+
+def test_hardware_calls_take_the_baton_first(daq):
+ daq._responses["GET"] = _response(json_data=_status(False))
+ _set_posts(daq, _response(json_data={"granted": True}), _response(json_data="OK"))
+ daq.mount_sample(1)
+ assert [url for url, _ in _calls(daq, "POST")] == [
+ f"{URL}/baton/request",
+ f"{URL}/sample/mount",
+ ]
+
+
+@pytest.mark.parametrize("result", [{"granted": True}, {"already_holder": True}])
+def test_take_baton_immediately(daq, result):
+ _set_posts(daq, _response(json_data=result))
+ daq.take_baton()
+ assert [url for url, _ in _calls(daq, "POST")] == [f"{URL}/baton/request"]
+
+
+def test_take_baton_refused_by_policy(daq):
+ _set_posts(daq, _response(json_data={"error": True, "message": "disabled by policy"}))
+ with pytest.raises(AareDaqError, match="disabled by policy"):
+ daq.take_baton()
+
+
+def test_take_baton_waits_for_the_holder(daq):
+ _set_posts(daq, _response(json_data={"pending": True, "message": "asked"}))
+ checks = iter([{"pending": True, "remaining_seconds": 20}, {"granted": True}])
+ 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:
+ 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)
+
+
+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"):
+ 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"):
+ daq.take_baton(wait_s=0)
+
+
+def test_release_baton(daq):
+ daq.release_baton()
+ assert [url for url, _ in _calls(daq, "POST")] == [f"{URL}/baton/release"]
diff --git a/tests/unit/test_aaredaq_tasks.py b/tests/unit/test_aaredaq_tasks.py
new file mode 100644
index 0000000..86edf63
--- /dev/null
+++ b/tests/unit/test_aaredaq_tasks.py
@@ -0,0 +1,97 @@
+from unittest.mock import MagicMock
+
+import pytest
+from aarecommon.math.coordinate import Coordinate, SmargonCoordinate
+from aarecommon.models.raster_grid import RasterGridRequest
+from aarecommon.models.rotation_scan import RotationScanRequest
+
+from mx_bec.decisions import smargon_nudge
+from mx_bec.tasks import MxTasks, Server
+
+# where the mock smargon sits
+SMARGON_POSITION = {"x": 1.0, "y": 2.0, "z": 3.0, "phi": 0.0, "chi": 0.0}
+
+
+@pytest.fixture
+def client():
+ client = MagicMock()
+ for axis, position in SMARGON_POSITION.items():
+ getattr(client.devices.smargon, axis).get.return_value = position
+ return client
+
+
+@pytest.fixture
+def tasks(client):
+ return MxTasks[Server](client)
+
+
+@pytest.mark.parametrize(
+ "name", ["aaredaq_mount_sample", "aaredaq_raster_scan", "aaredaq_rotation_scan"]
+)
+def test_aaredaq_methods_are_tasks(name):
+ assert MxTasks.is_task(name)
+
+
+def test_mount_sample(tasks, client):
+ tasks.aaredaq_mount_sample(42)
+ client.aaredaq.mount_sample.assert_called_once_with(42, reference=False)
+ tasks.aaredaq_mount_sample(7, reference=True)
+ client.aaredaq.mount_sample.assert_called_with(7, reference=True)
+
+
+def test_raster_scan_builds_request_from_flat_arguments(tasks, client):
+ tasks.aaredaq_raster_scan(
+ n_x=4, n_y=3, step_x_mm=0.05, step_y_mm=0.04, exp_time_s=0.1, omega_deg=12.0, dtz=150.0
+ )
+ request, kwargs = (
+ client.aaredaq.raster_scan.call_args.args[0],
+ client.aaredaq.raster_scan.call_args.kwargs,
+ )
+ # without a top left corner, the grid is centred on the current smargon position: the corner
+ # is half the grid away, in the lab frame at the scan's omega
+ half_grid = Coordinate(x=4 * 0.05 / 2, y=3 * 0.04 / 2, z=0)
+ top_left = Coordinate(x=1.0, y=2.0, z=3.0) - smargon_nudge(0.0, 0.0, 12.0, half_grid)
+ assert request == RasterGridRequest(
+ n_x=4,
+ n_y=3,
+ grid_size_mm=Coordinate(x=0.05, y=0.04),
+ exp_time_s=0.1,
+ omega_deg=12.0,
+ dtz=150.0,
+ smargon_top_left=SmargonCoordinate(sh_mm=top_left, chi_deg=0.0, phi_deg=0.0),
+ )
+ assert kwargs == {"auto_center": False}
+
+
+def test_raster_scan_uses_a_given_top_left_corner(tasks, client):
+ top_left = SmargonCoordinate(sh_mm=Coordinate(x=0.1, y=0.2, z=0.3), chi_deg=10.0, phi_deg=20.0)
+ tasks.aaredaq_raster_scan(1, 1, 0.05, 0.05, 0.1, smargon_top_left=top_left)
+ assert client.aaredaq.raster_scan.call_args.args[0].smargon_top_left == top_left
+ client.devices.smargon.x.get.assert_not_called()
+
+
+def test_raster_scan_passes_auto_center(tasks, client):
+ tasks.aaredaq_raster_scan(1, 1, 0.05, 0.05, 0.1, auto_center=True)
+ assert client.aaredaq.raster_scan.call_args.kwargs == {"auto_center": True}
+
+
+def test_rotation_scan_builds_request_from_flat_arguments(tasks, client):
+ tasks.aaredaq_rotation_scan(
+ exp_time_s=0.05, incr_omega_deg=0.1, steps=100, start_omega_deg=90.0, file_prefix="rot"
+ )
+ assert client.aaredaq.rotation_scan.call_args.args[0] == RotationScanRequest(
+ exp_time_s=0.05, incr_omega_deg=0.1, steps=100, start_omega_deg=90.0, file_prefix="rot"
+ )
+
+
+def test_screening_scan(tasks, client):
+ tasks.aaredaq_rotation_scan(0.05, 1.0, 4, screening=True, wedge_omega_deg=90.0)
+ request = client.aaredaq.rotation_scan.call_args.args[0]
+ assert request.screening is True and request.wedge_omega_deg == 90.0
+
+
+def test_failed_aaredaq_call_pauses_queue_and_reraises(tasks, client):
+ client.aaredaq.mount_sample.side_effect = RuntimeError("sample not found")
+ with pytest.raises(RuntimeError, match="sample not found"):
+ tasks.aaredaq_mount_sample(1)
+ client.task_queue.pause.assert_called_once()
diff --git a/tests/unit/test_actor_manager.py b/tests/unit/test_actor_manager.py
new file mode 100644
index 0000000..65332e9
--- /dev/null
+++ b/tests/unit/test_actor_manager.py
@@ -0,0 +1,119 @@
+from unittest.mock import MagicMock, patch
+
+import pytest
+from bec_lib.endpoints import EndpointInfo
+
+from mx_bec.actor_manager import AareActorManager
+from mx_bec.actors import all_actor_classes
+from mx_bec.actors.core import MXAutomationActor
+from mx_bec.actors.mx_automation import (
+ OnOpticalCenteringDoneRunXrayCentering,
+ OnSampleMountedRunOpticalCentering,
+)
+from mx_bec.messages import MXMeasurementSequenceMessage
+
+
+class FakeConfigValue:
+ """Stand-in for RedisConfigValue: a bool with subscribers, no Redis."""
+
+ initial = False # value "found in Redis" on construction
+
+ def __init__(self, connector, endpoint, wait_for_writes=True):
+ self.endpoint = endpoint
+ self._value = self.initial
+ self._cbs = []
+ self.unregistered = False
+
+ @property
+ def value(self):
+ return self._value
+
+ @value.setter
+ def value(self, value):
+ self._value = value
+ for cb in self._cbs:
+ cb(value)
+
+ def subscribe(self, cb):
+ self._cbs.append(cb)
+
+ def unregister_all(self):
+ self.unregistered = True
+
+
+class DummyActor(MXAutomationActor):
+ config_key = "dummy"
+
+ def default_monitor_endpoints(self) -> set[EndpointInfo[type[MXMeasurementSequenceMessage]]]:
+ return set()
+
+ def condition(self, client) -> bool:
+ return True
+
+ def action(self, client) -> None:
+ pass
+
+
+@pytest.fixture
+def manager():
+ with patch("mx_bec.actor_manager.RedisConfigValue", FakeConfigValue):
+ client = MagicMock()
+ mgr = AareActorManager(client, actor_classes=[DummyActor])
+ yield mgr, client
+ mgr.shutdown()
+
+
+def test_all_actor_classes_finds_concrete_subclasses():
+ classes = all_actor_classes()
+ assert OnSampleMountedRunOpticalCentering in classes
+ assert OnOpticalCenteringDoneRunXrayCentering in classes
+ assert MXAutomationActor not in classes
+ assert len({c.config_key for c in classes}) == len(classes), "config keys must be unique"
+
+
+def test_default_manager_manages_all_actors():
+ with patch("mx_bec.actor_manager.RedisConfigValue", FakeConfigValue):
+ mgr = AareActorManager(MagicMock())
+ assert mgr.actor_classes == all_actor_classes()
+ assert mgr.running == []
+
+
+def test_disabled_actor_is_not_started(manager):
+ mgr, _ = manager
+ assert not mgr.is_enabled(DummyActor)
+ assert mgr.running == []
+
+
+def test_enabling_starts_and_disabling_stops_actor(manager):
+ mgr, client = manager
+ mgr.set_enabled(DummyActor, True)
+ assert mgr.running == [DummyActor]
+ actor, thread, _ = mgr._actors_threads_and_stops[DummyActor]
+ assert isinstance(actor, DummyActor)
+ assert thread.is_alive()
+ assert client.connector.send.called # clients were pinged
+
+ mgr.set_enabled(DummyActor, False)
+ assert mgr.running == []
+ assert not thread.is_alive()
+
+
+def test_actor_enabled_at_startup_is_started():
+ with (
+ patch("mx_bec.actor_manager.RedisConfigValue", FakeConfigValue),
+ patch.object(FakeConfigValue, "initial", True),
+ ):
+ mgr = AareActorManager(MagicMock(), actor_classes=[DummyActor])
+ try:
+ assert mgr.running == [DummyActor]
+ finally:
+ mgr.shutdown()
+ assert mgr.running == []
+
+
+def test_shutdown_unregisters_flags(manager):
+ mgr, _ = manager
+ mgr.set_enabled(DummyActor, True)
+ mgr.shutdown()
+ assert mgr.running == []
+ assert all(flag.unregistered for flag in mgr._enabled_flags.values())
diff --git a/tests/unit/test_actors.py b/tests/unit/test_actors.py
new file mode 100644
index 0000000..3defbde
--- /dev/null
+++ b/tests/unit/test_actors.py
@@ -0,0 +1,62 @@
+from unittest.mock import MagicMock
+
+import pytest
+from bec_lib.endpoints import MessageOp
+from bec_lib.messages import BoolConfigDefaultFalse
+from bec_lib.redis_connector import MessageObject
+
+from mx_bec.actors.mx_automation import OnSampleMountedRunOpticalCentering
+from mx_bec.endpoints import StateEndpoints
+from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskExecutionMessage
+
+
+@pytest.fixture
+def client():
+ return MagicMock()
+
+
+def _msg_obj(
+ endpoint, sample_id: int, success: bool
+) -> MessageObject[MXMeasurementSequenceMessage]:
+ return MessageObject(
+ topic=endpoint.endpoint,
+ value=MXMeasurementSequenceMessage(sample_id=sample_id, success=success),
+ )
+
+
+def test_config_endpoint_is_a_managed_bool_stream():
+ ep = OnSampleMountedRunOpticalCentering.config_endpoint()
+ assert ep.message_op == MessageOp.STREAM
+ assert ep.message_type is BoolConfigDefaultFalse
+ assert OnSampleMountedRunOpticalCentering.config_key in ep.endpoint
+
+
+def test_actor_subscribes_to_its_milestone(client):
+ OnSampleMountedRunOpticalCentering(client, name="a", exec_id="a")
+ registered = {call.args[0].endpoint for call in client.connector.register.call_args_list}
+ assert StateEndpoints.sample_mounted().endpoint in registered
+
+
+def test_successful_milestone_triggers_next_step(client):
+ client.sample_info.sample_id = 42 # the actor takes the sample from the service
+ actor = OnSampleMountedRunOpticalCentering(client, name="a", exec_id="a")
+ actor.evaluate(_msg_obj(StateEndpoints.sample_mounted(), sample_id=42, success=True))
+
+ client.add_task_to_queue.assert_called_once_with(
+ MXTaskExecutionMessage(name="run_optical_centering", args=(42,), kwargs={})
+ )
+ assert actor.last_message is None
+
+
+def test_failed_milestone_does_not_trigger(client):
+ actor = OnSampleMountedRunOpticalCentering(client, name="a", exec_id="a")
+ actor.evaluate(_msg_obj(StateEndpoints.sample_mounted(), sample_id=42, success=False))
+ client.add_task_to_queue.assert_not_called()
+ client.connector.set_and_publish.assert_not_called()
+
+
+def test_unexpected_message_is_ignored(client):
+ actor = OnSampleMountedRunOpticalCentering(client, name="a", exec_id="a")
+ actor.evaluate(MessageObject(topic="x", value=BoolConfigDefaultFalse()))
+ client.add_task_to_queue.assert_not_called()
+ client.connector.set_and_publish.assert_not_called()
diff --git a/tests/unit/test_aerotech.py b/tests/unit/test_aerotech.py
new file mode 100644
index 0000000..db5354f
--- /dev/null
+++ b/tests/unit/test_aerotech.py
@@ -0,0 +1,94 @@
+from unittest.mock import MagicMock, call
+
+import pytest
+
+from mx_bec.devices.aerotech import Aerotech
+from mx_bec.devices.http import HttpRestError
+
+PREFIX = "http://aarescan:5234"
+
+
+def _response(ok=True, status_code=200, reason="OK", url=PREFIX, method="POST"):
+ resp = MagicMock(ok=ok, status_code=status_code, reason=reason)
+ resp.request.method, resp.request.url = method, url
+ return resp
+
+
+@pytest.fixture
+def aerotech():
+ device = Aerotech(name="aerotech", prefix=PREFIX)
+ # every REST call goes through the controller's session; never touch the network
+ device.controller._session = MagicMock()
+ device.controller._session.post.return_value = _response()
+ yield device
+ device.destroy()
+
+
+def _configure(aerotech, n_x=4, n_y=3, exp_time_s=0.1):
+ config = aerotech.gridscan_config
+ config.grid_elem_count_x.put(n_x)
+ config.grid_elem_count_y.put(n_y)
+ config.grid_elem_size_x_um.put(50.0)
+ config.grid_elem_size_y_um.put(40.0)
+ config.time_per_element_sec.put(exp_time_s)
+ return config
+
+
+def test_config_change_validates_with_aarescan(aerotech):
+ session = aerotech.controller._session
+ config = _configure(aerotech)
+ assert session.post.call_args == call(
+ f"{PREFIX}/validate/grid_scan", json=config.request_body()
+ )
+ assert config.valid.get() is True and config.message.get() == ""
+
+ session.post.return_value = _response(ok=False, status_code=400, reason="Bad Request")
+ session.post.return_value.json.return_value = "grid too large"
+ config.grid_elem_count_x.put(1000)
+ assert config.valid.get() is False and config.message.get() == "grid too large"
+
+
+def test_trigger_starts_grid_scan_and_waits_till_done(aerotech):
+ session = aerotech.controller._session
+ config = _configure(aerotech, n_x=4, n_y=3, exp_time_s=0.1)
+ session.post.reset_mock()
+
+ status = aerotech.trigger()
+ status.wait(timeout=5)
+
+ expected_timeout = round((0.1 * 4 * 3 + 3 * 0.3) * 1.1 + Aerotech.GRID_SCAN_TIMEOUT_MARGIN_S)
+ assert session.post.call_args_list == [
+ call(f"{PREFIX}/grid_scan", params=None, json={**config.request_body(), "run_async": True}),
+ call(f"{PREFIX}/wait_till_done", params={"timeout": expected_timeout}, json=None),
+ ]
+
+
+def test_trigger_status_fails_when_aarescan_times_out(aerotech):
+ session = aerotech.controller._session
+ _configure(aerotech)
+ session.post.side_effect = [
+ _response(), # grid_scan accepted
+ _response(ok=False, status_code=504, reason="Gateway Timeout"), # wait_till_done
+ ]
+ status = aerotech.trigger()
+ with pytest.raises(HttpRestError, match="504"):
+ status.wait(timeout=5)
+
+
+def test_trigger_refuses_invalid_config(aerotech):
+ session = aerotech.controller._session
+ session.post.return_value = _response(ok=False, status_code=400, reason="Bad Request")
+ session.post.return_value.json.return_value = "nope"
+ _configure(aerotech)
+ session.post.reset_mock()
+ with pytest.raises(ValueError, match="nope"):
+ aerotech.trigger()
+ session.post.assert_not_called()
+
+
+def test_wait_till_done_timeout_is_clamped(aerotech):
+ session = aerotech.controller._session
+ aerotech.controller.wait_till_done(timeout_s=1e6)
+ assert session.post.call_args.kwargs["params"] == {"timeout": 3600}
+ aerotech.controller.wait_till_done(timeout_s=-5)
+ assert session.post.call_args.kwargs["params"] == {"timeout": 0}
diff --git a/tests/unit/test_change_state_task.py b/tests/unit/test_change_state_task.py
new file mode 100644
index 0000000..3959808
--- /dev/null
+++ b/tests/unit/test_change_state_task.py
@@ -0,0 +1,43 @@
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from mx_bec.device_planner import BeamlineState
+from mx_bec.tasks import MxTasks, Server
+
+
+@pytest.fixture
+def tasks():
+ tasks = MxTasks[Server](MagicMock())
+ tasks._planner = MagicMock()
+ return tasks
+
+
+def test_planner_is_built_lazily_from_the_beamline_environment(monkeypatch):
+ monkeypatch.delenv("BEAMLINE", raising=False)
+ client = MagicMock()
+ tasks = MxTasks[Server](client) # must not need the beamline environment yet
+ env, devices, planner = MagicMock(), MagicMock(), MagicMock()
+ with patch(
+ "mx_bec.tasks.mx_tasks.init_beamline_environment", return_value=(env, devices, planner)
+ ) as init:
+ assert tasks.planner is planner
+ assert tasks.planner is planner
+ init.assert_called_once_with(client.devices, client.scans)
+
+
+@pytest.mark.parametrize("modifier", [None, "cryo"])
+def test_change_state_moves_to_the_state(tasks, modifier):
+ tasks.change_state("sample_alignment", modifier)
+ tasks.planner.move_to.assert_called_once_with(BeamlineState.SAMPLE_ALIGNMENT, modifier)
+
+
+def test_change_state_rejects_unknown_states(tasks):
+ with pytest.raises(ValueError, match="no_such_state"):
+ tasks.change_state("no_such_state")
+ tasks.planner.move_to.assert_not_called()
+
+
+def test_change_state_is_a_task_and_planner_is_not():
+ assert MxTasks.is_task("change_state")
+ assert not MxTasks.is_task("planner")
diff --git a/tests/unit/test_demo_config.py b/tests/unit/test_demo_config.py
new file mode 100644
index 0000000..2258351
--- /dev/null
+++ b/tests/unit/test_demo_config.py
@@ -0,0 +1,20 @@
+from ophyd_devices.utils.static_device_test import StaticDeviceTest
+
+from mx_bec.configs import MX_DEMO_CONFIG, render_config
+
+
+def test_all_demo_devices_construct_and_connect():
+ """Instantiate every device in the demo config the way the device server would."""
+ results = StaticDeviceTest(config_file=str(render_config(MX_DEMO_CONFIG))).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
+ assert {r.name for r in results} >= {"eiger", "aerotech", "gonio", "robot"}
+
+
+def test_render_config_fills_in_the_plugin(tmp_path):
+ assert "${BEC_PLUGIN}" in MX_DEMO_CONFIG.read_text()
+ rendered = render_config(MX_DEMO_CONFIG, plugin="some_bec").read_text()
+ assert "${BEC_PLUGIN}" not in rendered
+ assert "deviceClass: some_bec.devices.SimAerotechStage" in rendered
diff --git a/tests/unit/test_device_planner.py b/tests/unit/test_device_planner.py
new file mode 100644
index 0000000..c0c87f5
--- /dev/null
+++ b/tests/unit/test_device_planner.py
@@ -0,0 +1,222 @@
+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())
diff --git a/tests/unit/test_devices.py b/tests/unit/test_devices.py
new file mode 100644
index 0000000..49965ca
--- /dev/null
+++ b/tests/unit/test_devices.py
@@ -0,0 +1,71 @@
+import pytest
+from bec_server.device_server.tests.utils import DMMock
+from ophyd_devices.interfaces.base_classes.psi_device_base import DeviceStoppedError
+
+from mx_bec.devices import RobotState, SimAerotechStage, SimGoniometer, SimSampleChanger
+
+
+@pytest.fixture
+def robot():
+ dev = SimSampleChanger(name="robot", mount_time=0.05, device_manager=DMMock())
+ dev.on_connected()
+ yield dev
+ dev.destroy()
+
+
+@pytest.mark.parametrize("cls", [SimAerotechStage, SimGoniometer])
+def test_stage_reads_all_axes(cls):
+ stage = cls(name="stage")
+ readings = stage.read()
+ for axis in cls.component_names:
+ assert f"stage_{axis}" in readings
+ stage.destroy()
+
+
+def test_rotation_axis_is_unbounded():
+ stage = SimAerotechStage(name="aerotech")
+ stage.u.delay = 0
+ stage.u.move(720).wait(timeout=1)
+ assert stage.u.position == pytest.approx(720, abs=stage.u.tolerance.get())
+ stage.destroy()
+
+
+def test_robot_mount_and_unmount(robot):
+ assert robot.mount_time.get() == 0.05
+ robot.mount(puck=2, position=7).wait(timeout=1)
+ assert robot.read()["robot_sample_mounted"]["value"] == 1
+ assert robot.mounted_puck.get() == 2
+ assert robot.mounted_position.get() == 7
+ assert robot.state.get() == RobotState.IDLE
+
+ robot.unmount().wait(timeout=1)
+ assert robot.sample_mounted.get() == 0
+ assert robot.mounted_puck.get() == 0
+
+
+def test_robot_is_busy_while_mounting(robot):
+ status = robot.mount(puck=1, position=1)
+ assert robot.state.get() == RobotState.BUSY
+ with pytest.raises(RuntimeError, match="not idle"):
+ robot.mount(puck=1, position=2)
+ status.wait(timeout=1)
+ assert robot.mounted_position.get() == 1
+
+
+def test_robot_refuses_with_door_open(robot):
+ robot.door_closed.put(0)
+ with pytest.raises(RuntimeError, match="door"):
+ robot.mount(puck=1, position=1)
+ assert robot.state.get() == RobotState.ERROR
+ robot.reset()
+ assert robot.state.get() == RobotState.IDLE
+
+
+def test_robot_stop_aborts_mount(robot):
+ robot.mount_time.put(5)
+ status = robot.mount(puck=1, position=1)
+ robot.stop()
+ with pytest.raises(DeviceStoppedError):
+ status.wait(timeout=1)
+ assert robot.sample_mounted.get() == 0
+ assert robot.state.get() == RobotState.IDLE
diff --git a/tests/unit/test_jfjoch.py b/tests/unit/test_jfjoch.py
new file mode 100644
index 0000000..4b3bd81
--- /dev/null
+++ b/tests/unit/test_jfjoch.py
@@ -0,0 +1,152 @@
+from unittest.mock import MagicMock, patch
+
+import pytest
+from pydantic import ValidationError
+
+from mx_bec.jfjoch import JFJoch, JFJochError, RasterScan
+
+
+@pytest.fixture
+def api():
+ with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client:
+ yield jfjoch_client.DefaultApi.return_value
+
+
+@pytest.fixture
+def client():
+ client = MagicMock()
+ client.aare_config.jfjoch.n_images_per_file = 100
+ return client
+
+
+@pytest.fixture
+def jfjoch(client, api):
+ return JFJoch(client, url="http://jfjoch:8080")
+
+
+def _scan(**overrides) -> RasterScan:
+ params = dict(
+ n_x=3,
+ n_y=2,
+ step_x_mm=0.05,
+ step_y_mm=0.04,
+ omega_deg=12.0,
+ exp_time_s=0.1,
+ detector_distance_mm=150.0,
+ transmission=0.5,
+ file_prefix="test",
+ energy_keV=12.658,
+ beam_center_pxl=(1000.0, 1100.0),
+ beam_size_mm=(0.02, 0.01),
+ ring_current_mA=400.0,
+ flux_ph_s=1e12,
+ sample_temperature_K=100.0,
+ smargon_phi_deg=10.0,
+ smargon_chi_deg=-5.0,
+ )
+ return RasterScan(**{**params, **overrides})
+
+
+def test_url_is_resolved_from_beamline_config_on_first_use(client, monkeypatch):
+ monkeypatch.delenv("BEAMLINE", raising=False)
+ jfjoch = JFJoch(client) # must not need BEAMLINE yet
+ with (
+ patch("mx_bec.jfjoch.mx_beamline", return_value="X10SA") as beamline,
+ patch("mx_bec.jfjoch.get_jfjoch_url", return_value="http://gpu:8080") as get_url,
+ ):
+ assert jfjoch.url == "http://gpu:8080"
+ assert jfjoch.url == "http://gpu:8080"
+ get_url.assert_called_once_with("X10SA")
+ beamline.assert_called_once()
+
+
+def test_connects_lazily_and_cancels_once(jfjoch, api):
+ api.cancel_post.assert_not_called()
+ jfjoch.measure_raster(_scan())
+ jfjoch.measure_raster(_scan())
+ api.cancel_post.assert_called_once()
+ assert api.start_post.call_count == 2
+
+
+def test_failed_cancel_on_connect_leaves_it_disconnected(jfjoch, api):
+ api.cancel_post.side_effect = RuntimeError("down")
+ with pytest.raises(JFJochError, match="cancel_post failed: down"):
+ jfjoch.wait_till_done(timeout_s=1)
+ assert jfjoch._api is None
+
+
+def test_wait_till_running_reports_existing_output_file(jfjoch, api):
+ api.wait_until_running_post_with_http_info.side_effect = RuntimeError(
+ "Output file already exists"
+ )
+ with pytest.raises(JFJochError, match="output file already exists"):
+ jfjoch.wait_till_running(timeout_s=1.5)
+ api.wait_until_running_post_with_http_info.assert_called_once_with(timeout=2)
+
+
+def test_wait_till_running_raises_on_error_status(jfjoch, api):
+ api.status_get.return_value.message_severity = "error"
+ api.status_get.return_value.message = "detector unhappy"
+ with pytest.raises(JFJochError, match="detector unhappy"):
+ jfjoch.wait_till_running()
+
+
+def test_wait_till_done_returns_scan_result(jfjoch, api):
+ assert jfjoch.wait_till_done(timeout_s=10.2) is api.result_scan_get.return_value
+ api.wait_till_done_post_with_http_info.assert_called_once_with(timeout=11)
+
+
+def test_measure_raster_builds_grid_dataset_settings(jfjoch):
+ # re-patch to capture the DatasetSettings constructor; connect() happens inside, so the
+ # API mock to check is this patch's, not the `api` fixture's
+ with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client:
+ jfjoch.measure_raster(_scan())
+ settings = jfjoch_client.DatasetSettings.call_args.kwargs
+ assert settings["ntrigger"] == 2 and settings["images_per_trigger"] == 3
+ assert settings["file_prefix"] == "p16371/raw/raster/test"
+ assert settings["experiment_group"] == "p16371"
+ assert settings["sample_name"] == "unknown_sample"
+ assert settings["image_time_us"] == 100_000
+ assert settings["total_flux"] == 5e11
+ assert settings["beam_x_pxl"] == 1000.0 and settings["beam_y_pxl"] == 1100.0
+ assert settings["beam_size_x_um"] == 20.0 and settings["beam_size_y_um"] == 10.0
+ assert settings["images_per_file"] == 100
+ jfjoch_client.GridScan.assert_called_once_with(
+ n_fast=3, snake=True, step_x_um=50.0, step_y_um=40.0, vertical=False
+ )
+ jfjoch_client.RotationAxis.assert_called_once_with(
+ step=0, start=12.0, name="omega", vector=[-1, 0, 0], screening_wedge_deg=0
+ )
+ jfjoch_client.DefaultApi.return_value.start_post.assert_called_once_with(
+ dataset_settings=jfjoch_client.DatasetSettings.return_value
+ )
+
+
+def test_single_column_raster_is_one_trigger(jfjoch):
+ with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client:
+ jfjoch.dataset_settings(_scan(n_x=1, n_y=4))
+ settings = jfjoch_client.DatasetSettings.call_args.kwargs
+ assert settings["ntrigger"] == 1 and settings["images_per_trigger"] == 4
+
+
+def test_dataset_settings_clamps_negative_chi(jfjoch):
+ with patch("mx_bec.jfjoch.DatasetSettingsSmargon") as smargon:
+ jfjoch.dataset_settings(_scan())
+ smargon.assert_called_once_with(phi_deg=10.0, chi_deg=0)
+
+
+def test_dataset_settings_without_smargon_angles(jfjoch):
+ with (
+ patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client,
+ patch("mx_bec.jfjoch.DatasetSettingsSmargon") as smargon,
+ ):
+ jfjoch.dataset_settings(_scan(smargon_phi_deg=None))
+ smargon.assert_not_called()
+ assert jfjoch_client.DatasetSettings.call_args.kwargs["smargon"] is None
+
+
+def test_raster_scan_validates_fields():
+ with pytest.raises(ValidationError):
+ _scan(n_x=0)
+ with pytest.raises(ValidationError):
+ _scan(transmission=1.5)
diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py
new file mode 100644
index 0000000..864ed10
--- /dev/null
+++ b/tests/unit/test_service.py
@@ -0,0 +1,179 @@
+from unittest.mock import MagicMock, patch
+
+import pytest
+from bec_lib.client import BECClient
+from bec_lib.service_config import ServiceConfig
+from bec_lib.tests.utils import ConnectorMock
+
+from mx_bec.constants import AareBecWorkflowState
+from mx_bec.endpoints import QueueEndpoints
+from mx_bec.messages import MXQueueChangedMessage, MXTaskExecutionMessage
+from mx_bec.service import AareBec
+from mx_bec.tasks import MxTasks, RoleT, Server, task
+
+
+@pytest.fixture
+def service(monkeypatch):
+ BECClient._reset_singleton()
+ monkeypatch.setenv("CONFIG_REDIS_URL", "redis://dummy:6379")
+ # the config client connects to the beamline redis on construction
+ # HAX: the service reads the sample spreadsheet straight from the beamline redis on
+ # construction (mx_bec/service.py lines 57-63), so that connection is patched out too. Remove
+ # this patch together with that hack.
+ with patch("mx_bec.service.AareConfigClient"), patch("mx_bec.service.Redis"):
+ svc = AareBec(ServiceConfig(redis={"host": "dummy", "port": 6379}), ConnectorMock)
+ yield svc
+ BECClient._reset_singleton()
+
+
+def test_service_is_idle_before_start(service):
+ assert service.workflow_state == AareBecWorkflowState.IDLE
+ assert service.actor_manager is None
+
+
+@pytest.fixture
+def started_service(service):
+ """Run `service.start()` with the BECClient internals and the actor/task machinery mocked."""
+ service.connector = MagicMock() # normally created by the patched-out BECClient.start
+ with (
+ patch.object(BECClient, "start") as base_start,
+ patch("mx_bec.service.AareActorManager") as manager_cls,
+ patch("mx_bec.service.MxTaskQueue") as queue_cls,
+ patch.object(AareBec, "status", create=True),
+ ):
+ service.start()
+ yield service, base_start, manager_cls, queue_cls
+
+
+def test_start_creates_actor_manager(started_service):
+ service, base_start, manager_cls, _ = started_service
+ base_start.assert_called_once()
+ manager_cls.assert_called_once_with(service)
+ assert service.actor_manager is manager_cls.return_value
+
+
+def test_start_creates_and_starts_task_queue(started_service):
+ service, _, _, queue_cls = started_service
+ queue_cls.assert_called_once_with(service, service.tasks)
+ queue_cls.return_value.start.assert_called_once()
+ assert service.task_queue is queue_cls.return_value
+
+
+def test_shutdown_stops_actor_manager_and_task_queue(service):
+ service.actor_manager = MagicMock()
+ service.task_queue = MagicMock()
+ manager, queue = service.actor_manager, service.task_queue
+ with patch.object(BECClient, "shutdown") as base_shutdown:
+ service.shutdown()
+ manager.shutdown.assert_called_once()
+ queue.shutdown.assert_called_once()
+ base_shutdown.assert_called_once()
+ assert service.actor_manager is None
+ assert service.task_queue is None
+
+
+def test_start_registers_task_request_callback(started_service):
+ service, *_ = started_service
+ service.connector.register.assert_called_once_with(
+ QueueEndpoints.task_request(), cb=service._on_task_request
+ )
+
+
+def test_shutdown_unregisters_task_request_callback(service):
+ service.started = True
+ service.connector = MagicMock()
+ with patch.object(BECClient, "shutdown"):
+ service.shutdown()
+ service.connector.unregister.assert_called_once_with(
+ QueueEndpoints.task_request(), cb=service._on_task_request
+ )
+
+
+def test_shutdown_before_start_does_not_touch_connector(service):
+ with patch.object(BECClient, "shutdown") as base_shutdown:
+ service.shutdown()
+ base_shutdown.assert_called_once()
+
+
+def test_task_request_for_known_method_is_queued_and_announced(service):
+ service.connector = MagicMock()
+ msg = MXTaskExecutionMessage(name="run_optical_centering", args=(3,), kwargs={})
+ service._on_task_request({"data": msg})
+ service.connector.rpush.assert_called_once_with(QueueEndpoints.task_execution(), msg)
+ service.connector.send.assert_called_once_with(
+ QueueEndpoints.task_queue_changed(), MXQueueChangedMessage()
+ )
+
+
+NOT_TASKS = [
+ "no_such_task",
+ "_publish_optical_centering_done", # private method
+ "_client", # private attribute
+ "_busy_lock",
+ "request", # public, but not a task
+ "execute",
+ "is_task",
+ "planner", # property
+]
+
+
+@pytest.mark.parametrize("name", NOT_TASKS)
+def test_task_request_for_non_task_name_is_rejected(service, name):
+ service.connector = MagicMock()
+ msg = MXTaskExecutionMessage(name=name, args=(), kwargs={})
+ with patch("mx_bec.service.logger") as logger:
+ service._on_task_request({"data": msg})
+ service.connector.rpush.assert_not_called()
+ service.connector.send.assert_not_called()
+ logger.warning.assert_called_once()
+ assert name in logger.warning.call_args.args[0]
+
+
+def test_tasks_are_exactly_the_decorated_methods():
+ class Tasks(MxTasks[RoleT]):
+ @task
+ def decorated(self): ...
+
+ def plain(self): ...
+
+ assert Tasks.is_task("decorated")
+ assert not Tasks.is_task("plain")
+ assert MxTasks.is_task("run_optical_centering")
+ assert all(not MxTasks.is_task(name) for name in NOT_TASKS)
+
+
+class _FailingTasks(MxTasks[RoleT]):
+ @task
+ def boom(self):
+ raise RuntimeError("boom")
+
+ @task
+ def fine(self):
+ return None
+
+
+def test_failed_task_pauses_the_queue_and_reraises():
+ client = MagicMock()
+ with pytest.raises(RuntimeError, match="boom"):
+ _FailingTasks[Server](client).boom()
+ client.task_queue.pause.assert_called_once()
+
+
+def test_successful_task_does_not_pause_the_queue():
+ client = MagicMock()
+ assert _FailingTasks[Server](client).fine() is None
+ client.task_queue.pause.assert_not_called()
+
+
+def test_failed_task_reraises_without_a_queue():
+ client = MagicMock()
+ client.task_queue = None # the queue only exists once the service has started
+ with pytest.raises(RuntimeError, match="boom"):
+ _FailingTasks[Server](client).boom()
+
+
+def test_failed_task_reraises_even_if_pausing_fails():
+ client = MagicMock()
+ client.task_queue.pause.side_effect = ConnectionError("redis gone")
+ with pytest.raises(RuntimeError, match="boom"):
+ _FailingTasks[Server](client).boom()
diff --git a/tests/unit/test_smargon.py b/tests/unit/test_smargon.py
new file mode 100644
index 0000000..d6c4dac
--- /dev/null
+++ b/tests/unit/test_smargon.py
@@ -0,0 +1,106 @@
+"""Tests of the smargopolo Smargon device against the in-process mock server."""
+
+import numpy as np
+import pytest
+import requests
+from mock_smargopolo import AXES, MockSmargopolo, motors
+
+from mx_bec.devices.smargopolo_smargon import Smargon
+
+TOL = 0.01
+
+
+@pytest.fixture(scope="module")
+def server():
+ with MockSmargopolo() as srv:
+ yield srv
+
+
+@pytest.fixture
+def smargon(server):
+ for motor in motors.values():
+ motor.position = motor.target = 0.0
+ motor.moving = False
+ dev = Smargon(name="smargon", prefix=server.url)
+ dev.wait_for_connection()
+ yield dev
+ dev.controller._stop_monitor_readback_event.set()
+ dev.destroy()
+
+
+def reference_nudge(x, y, z, phi_deg, chi_deg, omega_deg):
+ """aarecommon.math.sample_geometry.SampleGeometry.smargon_nudge"""
+ phi, chi, omega = (np.radians(np.around(a, decimals=1)) for a in (phi_deg, chi_deg, omega_deg))
+ co, so = np.cos(omega), np.sin(omega)
+ cp, sp = np.cos(phi), np.sin(phi)
+ cc, sc = np.cos(chi), np.sin(chi)
+ return (
+ -z * co * sp - y * so * sp + x * cp * sc - y * co * cc * cp + z * so * cc * cp,
+ -z * co * cp - y * so * cp - x * sc * sp + y * co * cc * sp - z * so * cc * sp,
+ -x * cc - y * co * sc + z * so * sc,
+ )
+
+
+def test_read_all_axes(smargon):
+ motors["SHX"].position = 1.5
+ motors["CHI"].position = 42.0
+ smargon.controller.manual_update()
+ reading = smargon.read()
+ assert set(reading) == {f"smargon_{ax}" for ax in ("x", "y", "z", "phi", "chi")}
+ assert reading["smargon_x"]["value"] == 1.5
+ assert reading["smargon_chi"]["value"] == 42.0
+
+
+def test_set_moves_and_completes(smargon):
+ smargon.x.set(0.5).wait(timeout=2)
+ assert smargon.x.get() == pytest.approx(0.5, abs=TOL)
+ assert motors["SHX"].target == 0.5
+
+
+def test_set_sends_only_that_axis(smargon):
+ before = {ax: motors[ax].target for ax in AXES}
+ smargon.phi.set(0.3).wait(timeout=2)
+ before["PHI"] = 0.3
+ assert {ax: motors[ax].target for ax in AXES} == before
+
+
+def test_nudge_in_lab_frame_at_zero_angles(smargon):
+ # With omega = phi = chi = 0 a lab-frame x offset is a smargon -z move, y -> -x, z -> -y
+ smargon.nudge_in_lab_frame(0.2, 0.0, 0.0).wait(timeout=2)
+ assert smargon.z.get() == pytest.approx(-0.2, abs=TOL)
+ assert smargon.x.get() == pytest.approx(0.0, abs=TOL)
+ assert smargon.y.get() == pytest.approx(0.0, abs=TOL)
+ smargon.nudge_in_lab_frame(0.0, 0.2, 0.0).wait(timeout=2)
+ assert smargon.x.get() == pytest.approx(-0.2, abs=TOL)
+
+
+@pytest.mark.parametrize(
+ "phi_deg, chi_deg, omega_deg", [(90.0, 0.0, 0.0), (0.0, 20.0, 0.0), (30.0, 20.0, 45.0)]
+)
+def test_nudge_matches_reference(smargon, phi_deg, chi_deg, omega_deg):
+ for ax, val in (("PHI", phi_deg), ("CHI", chi_deg)):
+ motors[ax].position = motors[ax].target = val
+ smargon.controller.manual_update()
+ # omega is the Aerotech rotation, which the smargon does not know: it is passed in
+ assert smargon._lab_frame_offset_to_smargon_nudge(1.0, 0.5, 0.25, omega_deg) == pytest.approx(
+ reference_nudge(1.0, 0.5, 0.25, phi_deg, chi_deg, omega_deg)
+ )
+
+
+def test_stop_targets_current_position(smargon):
+ smargon.x.put(5.0)
+ assert motors["SHX"].moving
+ smargon.stop()
+ assert smargon.stopped
+ # the target was re-set to the (buffered) readback, not to 5.0, and nothing but axes was sent
+ assert motors["SHX"].target == pytest.approx(smargon.x.get(), abs=0.1)
+ assert motors["SHX"].target != 5.0
+
+
+def test_server_rejects_unknown_axis(server):
+ resp = requests.put(f"{server.url}/targetSCS", params={"__timestamp": 1.0})
+ assert resp.status_code == 404
+
+
+def test_user_access_is_a_list():
+ assert Smargon.USER_ACCESS == ["nudge_in_lab_frame"]
diff --git a/tests/unit/test_tasks.py b/tests/unit/test_tasks.py
new file mode 100644
index 0000000..5021f52
--- /dev/null
+++ b/tests/unit/test_tasks.py
@@ -0,0 +1,161 @@
+import time
+from threading import Event
+from unittest.mock import MagicMock, call, patch
+
+import fakeredis
+import pytest
+from bec_lib.redis_connector import RedisConnector
+
+from mx_bec.endpoints import QueueEndpoints
+from mx_bec.messages import MXQueueChangedMessage, MXTaskExecutionMessage
+from mx_bec.tasks import MxTaskQueue, RoleT, Server, TaskManager, task
+
+
+@pytest.fixture
+def connector():
+ conn = RedisConnector("localhost:1", redis_cls=lambda *_, **__: fakeredis.FakeRedis())
+ conn._managed_connection.flushall()
+ yield conn
+ conn.shutdown()
+
+
+@pytest.fixture
+def client(connector):
+ client = MagicMock()
+ client.connector = connector
+ return client
+
+
+class _Tasks(TaskManager[RoleT]):
+ """Records the calls of its one task on `calls`."""
+
+ calls: MagicMock
+
+ @task
+ def run_optical_centering(self, sample_id: int) -> None:
+ self.calls.run_optical_centering(sample_id)
+
+ def _publish_optical_centering_done(self, sample_id: int) -> None:
+ self.calls._publish_optical_centering_done(sample_id)
+
+
+@pytest.fixture
+def tasks():
+ """The recorder of the calls made to the tasks."""
+ return MagicMock()
+
+
+@pytest.fixture
+def queue(client, tasks):
+ manager = _Tasks[Server](client)
+ manager.calls = tasks
+ q = MxTaskQueue(client, manager, poll_interval_s=0.05)
+ yield q
+ q.shutdown()
+
+
+def _request(name="run_optical_centering", *args):
+ return MXTaskExecutionMessage(name=name, args=args, kwargs={})
+
+
+def _wait_for(predicate, timeout_s=3.0):
+ deadline = time.monotonic() + timeout_s
+ while time.monotonic() < deadline:
+ if predicate():
+ return
+ time.sleep(0.01)
+ raise AssertionError("condition not met in time")
+
+
+def test_queue_runs_tasks_in_order(connector, queue, tasks):
+ for sample_id in (1, 2, 3):
+ connector.rpush(
+ QueueEndpoints.task_execution(), _request("run_optical_centering", sample_id)
+ )
+ queue.start()
+ _wait_for(lambda: tasks.run_optical_centering.call_count == 3)
+ assert tasks.run_optical_centering.call_args_list == [call(1), call(2), call(3)]
+ assert connector.llen(QueueEndpoints.task_execution()) == 0
+
+
+def test_queue_announces_each_pop(connector, queue):
+ notifications = []
+
+ def on_changed(msg): # the connector keeps a weak ref: must be a function, not list.append
+ notifications.append(msg)
+
+ connector.register(QueueEndpoints.task_queue_changed(), cb=on_changed)
+ for sample_id in (1, 2):
+ connector.rpush(
+ QueueEndpoints.task_execution(), _request("run_optical_centering", sample_id)
+ )
+ queue.start()
+ _wait_for(lambda: len(notifications) == 2)
+ assert all(n.value == MXQueueChangedMessage() for n in notifications)
+
+
+def test_queue_does_not_pop_while_paused(connector, queue, tasks):
+ queue.pause()
+ connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 1))
+ queue.start()
+ time.sleep(0.3)
+ tasks.run_optical_centering.assert_not_called()
+ assert connector.llen(QueueEndpoints.task_execution()) == 1
+
+ queue.resume()
+ _wait_for(lambda: tasks.run_optical_centering.call_count == 1)
+ assert connector.llen(QueueEndpoints.task_execution()) == 0
+
+
+def test_paused_flag_is_shared_through_redis(connector, queue):
+ # another client (here: a second config value on the same endpoint) can pause the queue
+ other = MagicMock()
+ other.connector = connector
+ other_queue = MxTaskQueue(other, _Tasks[Server](other))
+ try:
+ assert not queue.paused
+ other_queue.pause()
+ _wait_for(lambda: queue.paused)
+ other_queue.resume()
+ _wait_for(lambda: not queue.paused)
+ finally:
+ other_queue.shutdown()
+
+
+def test_queue_skips_non_task_names(connector, queue, tasks):
+ connector.rpush(QueueEndpoints.task_execution(), _request("_publish_optical_centering_done", 1))
+ connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 2))
+ with patch("mx_bec.tasks.core.logger") as logger:
+ queue.start()
+ _wait_for(lambda: tasks.run_optical_centering.call_count == 1)
+ tasks.run_optical_centering.assert_called_once_with(2)
+ tasks._publish_optical_centering_done.assert_not_called()
+ logger.warning.assert_called_once()
+
+
+def test_failed_task_is_logged_and_queue_continues(connector, queue, tasks):
+ tasks.run_optical_centering.side_effect = [RuntimeError("boom"), None]
+ connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 1))
+ connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 2))
+ with patch("mx_bec.tasks.core.logger") as logger:
+ queue.start()
+ _wait_for(lambda: tasks.run_optical_centering.call_count == 2)
+ logger.exception.assert_called_once()
+ assert tasks.run_optical_centering.call_args_list == [call(1), call(2)]
+
+
+def test_shutdown_waits_for_running_task(connector, queue, tasks):
+ started, release = Event(), Event()
+
+ def slow_task(*_):
+ started.set()
+ release.wait(timeout=3)
+
+ tasks.run_optical_centering.side_effect = slow_task
+ connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 1))
+ queue.start()
+ assert started.wait(timeout=3)
+ assert queue._thread.is_alive()
+ release.set()
+ queue.shutdown()
+ assert not queue._thread.is_alive()
diff --git a/tests/unit/test_tasks_core.py b/tests/unit/test_tasks_core.py
new file mode 100644
index 0000000..5789da4
--- /dev/null
+++ b/tests/unit/test_tasks_core.py
@@ -0,0 +1,198 @@
+from unittest.mock import MagicMock
+
+import pytest
+
+from mx_bec.endpoints import QueueEndpoints, StateEndpoints
+from mx_bec.messages import (
+ MXMeasurementSequenceMessage,
+ MXQueueChangedMessage,
+ MXTaskExecutionMessage,
+)
+from mx_bec.tasks.core import (
+ BoundTask,
+ Client,
+ MxSequenceUpdate,
+ RoleT,
+ Server,
+ TaskManager,
+ UnknownTask,
+ task,
+)
+
+
+class Tasks(TaskManager[RoleT]):
+ """Shaped like MxTasks: tasks use `self._client` and may return a state update."""
+
+ @task
+ def mount(self, dbid: int, reference: bool = False) -> MxSequenceUpdate:
+ """Mount a sample"""
+ self._client.aaredaq.mount_sample(dbid, reference=reference)
+ return (
+ StateEndpoints.sample_mounted(),
+ MXMeasurementSequenceMessage(sample_id=dbid, success=True),
+ )
+
+ @task
+ def quiet(self) -> None:
+ self._client.aaredaq.quiet()
+
+ @task
+ def nested(self, dbid: int) -> None:
+ self.mount(dbid)
+
+ @task
+ def boom(self) -> None:
+ raise RuntimeError("boom")
+
+ def plain(self): ...
+
+ def _private(self): ...
+
+
+@pytest.fixture
+def client():
+ return MagicMock()
+
+
+@pytest.fixture
+def server(client):
+ return Tasks[Server](client)
+
+
+@pytest.fixture
+def remote(client):
+ return Tasks[Client](client)
+
+
+def test_role_classes(server, remote):
+ assert Tasks[Server] is Tasks[Server]
+ assert isinstance(server, Tasks) and isinstance(server, Server)
+ assert isinstance(remote, Tasks) and isinstance(remote, Client)
+ assert type(server).__name__ == "Tasks[Server]"
+ with pytest.raises(TypeError, match=r"Tasks\[Server\]"):
+ Tasks(MagicMock())
+ with pytest.raises(TypeError, match="already has a role"):
+ Tasks[Server][Client]
+
+
+def test_tasks_are_exactly_the_decorated_methods():
+ assert Tasks.task_names() == ["mount", "quiet", "nested", "boom"]
+ assert Tasks[Server].task_names() == Tasks.task_names()
+ assert Tasks.is_task("mount")
+ assert not any(Tasks.is_task(name) for name in ("plain", "_private", "request", "nope"))
+
+ class MoreTasks(Tasks[RoleT]):
+ @task
+ def extra(self) -> None: ...
+
+ assert MoreTasks.is_task("extra") and MoreTasks.is_task("mount")
+ assert not Tasks.is_task("extra")
+
+
+def test_task_metadata(server):
+ assert Tasks.mount.__doc__ == "Mount a sample"
+ assert isinstance(server.mount, BoundTask)
+ assert server.mount.__name__ == "mount"
+ assert server.mount.__doc__ == "Mount a sample"
+
+
+def test_server_call_runs_the_task_and_publishes_its_state_update(server, client):
+ assert server.mount(3, reference=True) is None
+ client.aaredaq.mount_sample.assert_called_once_with(3, reference=True)
+ endpoint, msg = client.connector.set_and_publish.call_args.args
+ assert endpoint.endpoint == StateEndpoints.sample_mounted().endpoint
+ assert msg == MXMeasurementSequenceMessage(sample_id=3, success=True)
+ client.task_queue.pause.assert_not_called()
+
+
+def test_server_call_without_state_update_publishes_nothing(server, client):
+ server.quiet()
+ client.aaredaq.quiet.assert_called_once_with()
+ client.connector.set_and_publish.assert_not_called()
+
+
+def test_server_task_can_call_another_task(server, client):
+ server.nested(5) # must not deadlock on the task lock
+ client.aaredaq.mount_sample.assert_called_once_with(5, reference=False)
+ client.connector.set_and_publish.assert_called_once()
+
+
+def test_server_call_through_the_class(server, client):
+ Tasks.mount(server, 4)
+ client.aaredaq.mount_sample.assert_called_once_with(4, reference=False)
+
+
+def test_failed_task_pauses_the_queue_and_reraises(server, client):
+ with pytest.raises(RuntimeError, match="boom"):
+ server.boom()
+ client.task_queue.pause.assert_called_once()
+ client.connector.set_and_publish.assert_not_called()
+
+
+def test_failed_task_reraises_without_a_queue(server, client):
+ client.task_queue = None # the queue only exists once the service has started
+ with pytest.raises(RuntimeError, match="boom"):
+ server.boom()
+
+
+def test_failed_task_reraises_even_if_pausing_fails(server, client):
+ client.task_queue.pause.side_effect = ConnectionError("redis gone")
+ with pytest.raises(RuntimeError, match="boom"):
+ server.boom()
+
+
+def test_server_execute_runs_the_task_of_a_message(server, client):
+ server.execute(MXTaskExecutionMessage(name="mount", args=(7,), kwargs={"reference": True}))
+ client.aaredaq.mount_sample.assert_called_once_with(7, reference=True)
+ with pytest.raises(UnknownTask, match="plain"):
+ server.execute(MXTaskExecutionMessage(name="plain", args=(), kwargs={}))
+
+
+@pytest.mark.parametrize(
+ "request_task",
+ [
+ lambda tasks: tasks.mount.request(3, reference=True),
+ lambda tasks: tasks.request("mount", 3, reference=True),
+ lambda tasks: tasks.request(tasks.mount, 3, reference=True),
+ lambda tasks: tasks.request(Tasks.mount, 3, reference=True),
+ ],
+)
+def test_server_request_queues_the_task(server, client, request_task):
+ request_task(server)
+ client.aaredaq.mount_sample.assert_not_called()
+ endpoint, msg = client.connector.rpush.call_args.args
+ assert endpoint.endpoint == QueueEndpoints.task_execution().endpoint
+ assert msg == MXTaskExecutionMessage(name="mount", args=(3,), kwargs={"reference": True})
+ endpoint, msg = client.connector.send.call_args.args
+ assert endpoint.endpoint == QueueEndpoints.task_queue_changed().endpoint
+ assert isinstance(msg, MXQueueChangedMessage)
+
+
+def test_request_of_unknown_task_is_rejected(server, remote, client):
+ for tasks in (server, remote):
+ with pytest.raises(UnknownTask):
+ tasks.request("plain")
+ client.connector.rpush.assert_not_called()
+ client.connector.xadd.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "call",
+ [
+ lambda tasks: tasks.mount(3, reference=True),
+ lambda tasks: tasks.mount.request(3, reference=True),
+ lambda tasks: tasks.request("mount", 3, reference=True),
+ lambda tasks: tasks.execute(
+ MXTaskExecutionMessage(name="mount", args=(3,), kwargs={"reference": True})
+ ),
+ ],
+)
+def test_client_sends_a_task_request(remote, client, call):
+ call(remote)
+ client.aaredaq.mount_sample.assert_not_called()
+ client.connector.rpush.assert_not_called()
+ endpoint, payload = client.connector.xadd.call_args.args
+ assert endpoint.endpoint == QueueEndpoints.task_request().endpoint
+ assert payload == {
+ "data": MXTaskExecutionMessage(name="mount", args=(3,), kwargs={"reference": True})
+ }
diff --git a/todo.md b/todo.md
new file mode 100644
index 0000000..59e50c0
--- /dev/null
+++ b/todo.md
@@ -0,0 +1,4 @@
+- smargon limits (move sticks forever out of range)
+- 2 queues: sample + task queue, tasks can be l-added
+- replace all tasks with wrapped aaredaq tasks to review calculations
+-