fix: tidy math module
CI for mx_bec / test (push) Failing after 1m8s
CI for mx_bec / test (pull_request) Failing after 1m8s

This commit is contained in:
perl_d committed 2026-11-24 11:40:12 +01:00
1 parent 1640ef9657
commit f6271b06e8
7 files changed
+136 -901

No files matched your search

+75 -7
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import secrets
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, ClassVar
@@ -7,8 +8,9 @@ from bec_lib.endpoints import EndpointInfo
from bec_lib.logger import bec_logger
from bec_server.actors.actor import SubscriptionActor
from mx_bec.endpoints import ActorEndpoints
from mx_bec.messages import MXMeasurementSequenceMessage
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
@@ -23,14 +25,18 @@ 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 `condition` / `action`.
Whenever a successful milestone message arrives it is stored in `last_message` and the
action table is evaluated.
(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}
@@ -55,9 +61,17 @@ class MXAutomationActor(SubscriptionActor, ABC):
logger.info(f"{self.name}: step failed for sample {msg.sample_id}, not acting")
return super().evaluate()
@abstractmethod
def condition(self, client: AareBec) -> bool:
"""Whether `action` should run; evaluated after every successful milestone message."""
"""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:
@@ -67,3 +81,57 @@ class MXAutomationActor(SubscriptionActor, ABC):
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
+26 -105
View File
@@ -5,35 +5,31 @@ are stand-ins for now: they log and immediately publish the next milestone, so t
exercised end to end on the simulated beamline before the real procedures exist.
"""
import secrets
from datetime import date
from time import sleep
from typing import Any, ClassVar
from aarelcinfer_client.models import DetectionModel
from bec_lib.endpoints import EndpointInfo
from bec_lib.logger import bec_logger
from pxii_bec.macros.calculator import calc_scam_microns
from pxii_bec.macros.flux_macros import bpm2flux
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.math import gridscan_calculation, gridscan_strategy_from_optical, mock_grid_calculation
from mx_bec.messages import (
MXMeasurementSequenceMessage,
MXQueueChangedMessage,
MXSampleExecutionMessage,
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
@@ -155,76 +151,7 @@ class OnSampleDoneLoadNext(MXAutomationActor):
)
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):
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"
@@ -241,15 +168,12 @@ class OnXrayCenteringDonePlanCollection(SelfDrivingActor):
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)
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).
record.positions_used = []
record.current_offset_mm = (0.0, 0.0)
info.positions_used = []
info.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)"
@@ -262,14 +186,14 @@ class OnXrayCenteringDonePlanCollection(SelfDrivingActor):
if cfg.anomalous:
chis = cfg.anomalous_chi_deg
if len(chis) > 1:
record.chi_sweeps_done += 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, record, sample_id, 0, chi_values=chis, reason=reason)
self.queue_collection(client, 0, chi_values=chis, reason=reason)
class OnRotationDoneDecideFollowUp(SelfDrivingActor):
class OnRotationDoneDecideFollowUp(MXAutomationActor):
"""Assess the last dataset and queue a follow-up, or finish the sample."""
config_key = "self_driving_followup_after_rotation"
@@ -281,33 +205,32 @@ class OnRotationDoneDecideFollowUp(SelfDrivingActor):
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:
if not info.collections:
self.finish(client, sample_id, success=False, reason="rotation_done without a record")
return
latest = record.collections[-1]
latest = info.collections[-1]
latest.assessment = assess_collection(latest, self.strategy)
decision = decide_followup(latest.assessment, record, 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 record.collections)
usable = any(c.assessment and c.assessment.usable for c in info.collections)
self.finish(client, sample_id, success=usable, reason=decision.reason)
return
record.followups += 1
info.followups += 1
if decision.action is Action.RECENTRE:
if record.raster_strategy is None:
if info.raster is None:
self.finish(client, sample_id, success=False, reason="no raster to repeat")
return
record.recentres += 1
strategy = dict(record.raster_strategy)
info.recentres += 1
strategy = dict(info.raster.strategy)
strategy["file_prefix"] = (
f"{strategy.get('file_prefix') or 'raster'}_rc{record.recentres}"
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)
@@ -316,11 +239,9 @@ class OnRotationDoneDecideFollowUp(SelfDrivingActor):
assert decision.position_index is not None
if decision.action is Action.CHI_SWEEP:
record.chi_sweeps_done += 1
info.chi_sweeps_done += 1
self.queue_collection(
client,
record,
sample_id,
decision.position_index,
chi_values=decision.chi_values,
dose_fraction=decision.dose_fraction,
-130
View File
@@ -1,130 +0,0 @@
import secrets
import numpy as np
from aarecommon.math.coordinate import Coordinate
from bec_lib.logger import bec_logger
from pxii_bec.macros.calculator import calc_scam_microns
from mx_bec.sample_info import OpticalCenteringResults
logger = bec_logger.logger
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
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,
):
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,
)
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,
):
"""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 = calc_scam_microns(box_x_pixels, zoom=400)
box_y_microns = calc_scam_microns(box_y_pixels, zoom=400)
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_x_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,
}
+22 -2
View File
@@ -5,7 +5,7 @@ import time
from aarelcinfer_client.models import LatestPredictionModel
from pydantic import BaseModel, ConfigDict, Field
from mx_bec.self_driving import RasterRecord, SelfDrivingRecord
from mx_bec.decisions import CollectionRecord, GridAnalysis, RasterRecord
class OpticalCenteringResults(BaseModel):
@@ -24,4 +24,24 @@ class SampleInfo(BaseModel):
sample_id: int
optical_centering_results: OpticalCenteringResults | None = None
raster: RasterRecord | None = None
self_driving: SelfDrivingRecord | 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
-638
View File
@@ -1,638 +0,0 @@
"""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.self_driving`` 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.
"""
from __future__ import annotations
import math
import statistics
from collections.abc import Iterable, Sequence
from enum import Enum
from typing import Any
from aarecommon.models.raster_grid import CompletedRasterGridElem
from bec_lib.logger import bec_logger
from pydantic import BaseModel, ConfigDict, Field
HC_KEV_A = 12.398419843320026 # keV * Angstrom
logger = bec_logger.logger
# --------------------------------------------------------------------------------------------
# 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"
)
# --------------------------------------------------------------------------------------------
# Grid analysis
# --------------------------------------------------------------------------------------------
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 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),
)
# --------------------------------------------------------------------------------------------
# Rotation planning
# --------------------------------------------------------------------------------------------
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()]
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,
)
# --------------------------------------------------------------------------------------------
# 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
class SelfDrivingRecord(BaseModel):
"""Per-sample history; reset by ``reset_sample_info`` on mount."""
analysis: GridAnalysis | None = None
raster_strategy: dict[str, Any] | None = None
current_offset_mm: tuple[float, float] = (0.0, 0.0)
positions_used: list[int] = []
chi_sweeps_done: int = 0
recentres: int = 0
followups: int = 0
collections: list[CollectionRecord] = []
def next_free_position(self) -> int | None:
if self.analysis is None:
return None
for i in range(len(self.analysis.positions)):
if i not in self.positions_used:
return i
return 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__}")
# --------------------------------------------------------------------------------------------
# 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, record: SelfDrivingRecord, cfg: StrategyConfig
) -> Decision:
"""Priority: budget -> lost diffraction -> damage -> completeness (chi) -> weak -> finish."""
issues = set(assessment.issues)
if record.followups >= cfg.max_followups:
return Decision(action=Action.FINISH, reason="follow-up budget spent")
nxt = record.next_free_position()
if Issue.LOST_DIFFRACTION in issues:
if record.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 record.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 = record.positions_used[-1] if record.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")
+12 -18
View File
@@ -9,18 +9,17 @@ from aarecommon.models.raster_grid import RasterGridRequest
from aarecommon.models.rotation_scan import RotationScanRequest
from bec_lib.logger import bec_logger
from mx_bec.endpoints import StateEndpoints
from mx_bec.math import smargon_nudge
from mx_bec.messages import MXMeasurementSequenceMessage
from mx_bec.self_driving import (
from mx_bec.decisions import (
CollectionRecord,
GridGeometry,
RasterRecord,
RotationPlan,
SelfDrivingRecord,
SweepRecord,
scan_images,
smargon_nudge,
)
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:
@@ -266,13 +265,6 @@ class MxTasks(TaskManager[RoleT]):
MXMeasurementSequenceMessage(sample_id=dbid, success=True),
)
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.
@@ -280,16 +272,16 @@ class MxTasks(TaskManager[RoleT]):
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]
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)
record.current_offset_mm = (offset_x_mm, offset_y_mm)
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:
@@ -324,7 +316,9 @@ class MxTasks(TaskManager[RoleT]):
)
finally:
smargon.chi.set(0.0).wait()
self._self_driving_record().collections.append(record)
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),
+1 -1
View File
@@ -5,7 +5,7 @@ from aarecommon.math.coordinate import Coordinate, SmargonCoordinate
from aarecommon.models.raster_grid import RasterGridRequest
from aarecommon.models.rotation_scan import RotationScanRequest
from mx_bec.math import smargon_nudge
from mx_bec.decisions import smargon_nudge
from mx_bec.tasks import MxTasks, Server
# where the mock smargon sits