From 9c4d7566cf2407576bc288fb52e31e146e1fd120 Mon Sep 17 00:00:00 2001 From: x10sa Date: Wed, 11 Nov 2026 13:38:50 +0100 Subject: [PATCH] integrate stuff --- mx_bec/actors/mx_automation.py | 198 +++++++++++++++++++++- mx_bec/endpoints.py | 12 ++ mx_bec/sample_info.py | 12 +- mx_bec/tasks.py | 296 ++++++++++++++++++++------------- 4 files changed, 393 insertions(+), 125 deletions(-) diff --git a/mx_bec/actors/mx_automation.py b/mx_bec/actors/mx_automation.py index e5ef963..4465662 100644 --- a/mx_bec/actors/mx_automation.py +++ b/mx_bec/actors/mx_automation.py @@ -7,13 +7,24 @@ exercised end to end on the simulated beamline before the real procedures exist. import secrets from time import sleep +from typing import Any, ClassVar from bec_lib.endpoints import EndpointInfo from bec_lib.logger import bec_logger +from pxii_bec.macros.flux_macros import bpm2flux from mx_bec.actors.core import MXAutomationActor from mx_bec.endpoints import StateEndpoints from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskExecutionMessage +from mx_bec.self_driving import ( + Action, + SelfDrivingRecord, + StrategyConfig, + analyse_grid, + assess_collection, + decide_followup, + plan_rotation, +) from mx_bec.service import AareBec logger = bec_logger.logger @@ -60,19 +71,196 @@ class OnOpticalCenteringDoneRunXrayCentering(MXAutomationActor): sleep(2) logger.info("calculating...") sleep(2) + n_x = 10 + n_y = 10 + step_x_mm = 0.05 + step_y_mm = 0.05 strategy = { - "n_x": 10, - "n_y": 10, - "step_x_mm": 0.05, - "step_y_mm": 0.05, + "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, - } logger.info(f"calculated strategy: {strategy}") + client.add_task_to_queue( MXTaskExecutionMessage(name="xray_centering", args=(sample_id, strategy), kwargs={}) ) + + +class SelfDrivingActor(MXAutomationActor): + """Shared helpers. Abstract: subclasses set ``config_key`` and implement ``action``.""" + + strategy: ClassVar[StrategyConfig] = StrategyConfig() + + def condition(self, client: AareBec) -> bool: + 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 + + @staticmethod + def record(client: AareBec) -> SelfDrivingRecord: + info = client.sample_info + assert info is not None, "No sample loaded" + if info.self_driving is None: + info.self_driving = SelfDrivingRecord() + return info.self_driving + + @staticmethod + def queue(client: AareBec, name: str, *args: Any) -> None: + client.add_task_to_queue(MXTaskExecutionMessage(name=name, args=args, kwargs={})) + + @staticmethod + def finish(client: AareBec, sample_id: int, *, success: bool, reason: str) -> None: + logger.info(f"Self-driving: 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, + record: SelfDrivingRecord, + sample_id: int, + position_index: int, + *, + chi_values: list[float] | tuple[float, ...] = (0.0,), + dose_fraction: float = 1.0, + reason: str, + ) -> bool: + assert record.analysis is not None + prefix = f"S{sample_id}_{secrets.token_hex(3)}" + _, self.strategy.beam.flux_ph_s = bpm2flux() + try: + plan = plan_rotation( + record.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, sample_id, success=False, reason=f"cannot plan: {e}") + return False + if position_index not in record.positions_used: + record.positions_used.append(position_index) + logger.info(f"Self-driving: queue collection for sample {sample_id}: {plan}") + self.queue(client, "collect_dataset", sample_id, plan.model_dump()) + return True + + +class OnXrayCenteringDonePlanCollection(SelfDrivingActor): + """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 + + record = self.record(client) + record.raster_strategy = dict(raster.strategy) + record.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). + record.positions_used = [] + record.current_offset_mm = (0.0, 0.0) + + analysis = record.analysis + 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: + record.chi_sweeps_done += 1 + reason = "anomalous: low-dose multi-chi" + else: + chis, reason = (0.0,), "best spot from grid" + self.queue_collection(client, record, sample_id, 0, chi_values=chis, reason=reason) + + +class OnRotationDoneDecideFollowUp(SelfDrivingActor): + """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 + record = self.record(client) + if not record.collections: + self.finish(client, sample_id, success=False, reason="rotation_done without a record") + return + + latest = record.collections[-1] + latest.assessment = assess_collection(latest, self.strategy) + decision = decide_followup(latest.assessment, record, 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 record.collections) + self.finish(client, sample_id, success=usable, reason=decision.reason) + return + + record.followups += 1 + if decision.action is Action.RECENTRE: + if record.raster_strategy is None: + self.finish(client, sample_id, success=False, reason="no raster to repeat") + return + record.recentres += 1 + strategy = dict(record.raster_strategy) + strategy["file_prefix"] = ( + f"{strategy.get('file_prefix') or 'raster'}_rc{record.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: + record.chi_sweeps_done += 1 + self.queue_collection( + client, + record, + sample_id, + decision.position_index, + chi_values=decision.chi_values, + dose_fraction=decision.dose_fraction, + reason=decision.reason, + ) diff --git a/mx_bec/endpoints.py b/mx_bec/endpoints.py index ee9e607..5f3a1b0 100644 --- a/mx_bec/endpoints.py +++ b/mx_bec/endpoints.py @@ -44,6 +44,18 @@ class StateEndpoints: 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`.""" diff --git a/mx_bec/sample_info.py b/mx_bec/sample_info.py index 9a462ae..43eb21b 100644 --- a/mx_bec/sample_info.py +++ b/mx_bec/sample_info.py @@ -3,7 +3,9 @@ from __future__ import annotations import time from aarelcinfer_client.models import LatestPredictionModel -from pydantic import BaseModel, Field +from pydantic import BaseModel, ConfigDict, Field + +from mx_bec.self_driving import RasterRecord, SelfDrivingRecord class OpticalCenteringResults(BaseModel): @@ -14,8 +16,12 @@ class OpticalCenteringResults(BaseModel): class SampleInfo(BaseModel): - """Information about the currently mounted sample. Gradually filled out as - information from previous stages is obtained""" + """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 + self_driving: SelfDrivingRecord | None = None diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index 1702f9e..d858c5c 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -6,6 +6,7 @@ from threading import Event, RLock, Thread from typing import TYPE_CHECKING, Callable, Concatenate, ParamSpec, Self, TypeVar 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.config_values import RedisConfigValue @@ -20,6 +21,15 @@ from mx_bec.messages import ( MXTaskExecutionMessage, MXTaskQueueChangedMessage, ) +from mx_bec.self_driving import ( + CollectionRecord, + GridGeometry, + RasterRecord, + RotationPlan, + SelfDrivingRecord, + SweepRecord, + scan_images, +) if TYPE_CHECKING: from pxii_bec.macros.beamline_planner import StateChangePlanner @@ -130,7 +140,10 @@ class MxTasks: return self._optical_centering_done_update(sample_id, success=True) @task - def run_optical_centering(self, sample_id): + 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() return self._optical_centering_done_update(sample_id, success=True) @@ -163,44 +176,6 @@ class MxTasks: MXMeasurementSequenceMessage(sample_id=dbid, success=True), ) - @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: - """Have AareDAQ run an n_x by n_y raster scan from the current Smargon position - (`smargon_top_left` is left unset), optionally auto-centering afterwards.""" - smargon = self._client.devices.smargon - smargon_top_left = smargon_top_left or SmargonCoordinate( - sh_mm=Coordinate(x=smargon.x.get(), y=smargon.y.get(), z=smargon.z.get()), - chi_deg=smargon.chi.get(), - phi_deg=smargon.phi.get(), - ) - logger.info(f"smargon top left supplied to grid scan {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"AareDAQ raster scan done: {len(result.r)} grid(s) collected") - @task def multiple_rasters( self, @@ -217,7 +192,7 @@ class MxTasks: omegas = [float(ang.strip()) for ang in omegas_deg_list.split(",")] smargon = self._client.devices.smargon smargon_top_left = SmargonCoordinate( - sh_mm=Coordinate(x=smargon.x.get(), y=smargon.x.get(), z=smargon.x.get()), + sh_mm=Coordinate(x=smargon.x.get(), y=smargon.y.get(), z=smargon.z.get()), chi_deg=smargon.chi.get(), phi_deg=smargon.phi.get(), ) @@ -234,14 +209,6 @@ class MxTasks: ) logger.info(f"Raster {i + 1} out of {len(omegas)} done.") - @task - def xray_centering(self, dbid: int, strategy: dict): - self.aaredaq_raster_scan(**strategy) - return ( - StateEndpoints.xray_centering_done(), - MXMeasurementSequenceMessage(sample_id=dbid, success=True), - ) - @task def aaredaq_rotation_scan( self, @@ -271,76 +238,171 @@ class MxTasks: 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 -# @task -# def run_grid_scan( -# self, -# n_x: int, -# n_y: int, -# step_x_um: float, -# step_y_um: float, -# exp_time_s: float, -# file_prefix: str, -# detector_distance_mm: float, -# transmission: float, -# energy_keV: float, -# beam_center_x_pxl: float, -# beam_center_y_pxl: float, -# beam_size_x_mm: float, -# beam_size_y_mm: float, -# ring_current_mA: float, -# flux_ph_s: float, -# sample_temperature_K: float, -# pgroup: str = "p16371", -# sample_name: str = "unknown_sample", -# ) -> None: -# """Collect an n_x by n_y grid scan at the current position and omega: configure the -# Aerotech grid scan and check that AareScan accepts it, arm JFJoch, then trigger the -# Aerotech and wait for both to finish.""" -# expected_s = exp_time_s * n_x * n_y + n_y * 0.3 -# if expected_s > MAX_GRID_SCAN_S: -# raise ValueError(f"Grid scan is too long: {expected_s:.0f} s > {MAX_GRID_SCAN_S} s") -# -# aerotech = self._client.devices.aerotech -# config = aerotech.gridscan_config -# for signal, value in ( -# (config.grid_elem_count_x, n_x), -# (config.grid_elem_count_y, n_y), -# (config.grid_elem_size_x_um, step_x_um), -# (config.grid_elem_size_y_um, step_y_um), -# (config.time_per_element_sec, exp_time_s), -# ): -# signal.set(value).wait() -# if not config.valid.get(): -# raise ValueError(f"AareScan rejected the grid scan parameters: {config.message.get()}") -# -# jfjoch = self._client.jfjoch -# jfjoch.measure_raster( -# RasterScan( -# n_x=n_x, -# n_y=n_y, -# step_x_mm=step_x_um / 1000.0, -# step_y_mm=step_y_um / 1000.0, -# omega_deg=aerotech.u.get(), -# exp_time_s=exp_time_s, -# detector_distance_mm=detector_distance_mm, -# transmission=transmission, -# file_prefix=file_prefix, -# pgroup=pgroup, -# sample_name=sample_name, -# energy_keV=energy_keV, -# beam_center_pxl=(beam_center_x_pxl, beam_center_y_pxl), -# beam_size_mm=(beam_size_x_mm, beam_size_y_mm), -# ring_current_mA=ring_current_mA, -# flux_ph_s=flux_ph_s, -# sample_temperature_K=sample_temperature_K, -# ) -# ) -# jfjoch.wait_till_running(timeout_s=60) -# logger.info(f"Starting {n_x}x{n_y} grid scan, {exp_time_s} s per element") -# aerotech.trigger().wait() -# result = jfjoch.wait_till_done(timeout_s=60) -# logger.info(f"Grid scan finished: {result.file_prefix} with {len(result.images)} images") + smargon_top_left = SmargonCoordinate( + sh_mm=Coordinate( + x=smargon.x.get(), + y=smargon.y.get(), # + y_offset_mm, + z=smargon.z.get(), # + x_offset_mm, + ), + 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), + ) + + # c) New: moves relative to the raster start, and the rotation collection itself. + + def _self_driving_record(self) -> SelfDrivingRecord: + info = self._client.sample_info + assert info is not None, "No sample loaded" + if info.self_driving is None: + info.self_driving = SelfDrivingRecord() + return info.self_driving + + 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. + """ + record = self._self_driving_record() + info = self._client.sample_info + omega = info.raster.geometry.omega_deg if info and info.raster else 0.0 + dx = offset_x_mm - record.current_offset_mm[0] + dy = offset_y_mm - record.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) + record.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() + self._self_driving_record().collections.append(record) + return ( + StateEndpoints.rotation_done(), + MXMeasurementSequenceMessage(sample_id=dbid, success=True), + ) class MxTaskQueue: