apply smargon nudge math to gridscan
CI for mx_bec / test (push) Failing after 48s

This commit is contained in:
x10sa committed 2026-11-11 14:52:56 +01:00
1 parent 78fe7ae11a
commit 49b699434e
2 files changed
+653 -11

No files matched your search

+638
View File
@@ -0,0 +1,638 @@
"""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")
+15 -11
View File
@@ -16,6 +16,7 @@ from bec_lib.logger import bec_logger
from mx_bec.devices.smargopolo_smargon import Smargon
from mx_bec.endpoints import StateEndpoints, TaskEndpoints
from mx_bec.jfjoch import RasterScan
from mx_bec.math import smargon_nudge
from mx_bec.messages import (
MXMeasurementSequenceMessage,
MXTaskExecutionMessage,
@@ -253,19 +254,22 @@ class MxTasks:
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)"
# )
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_deg.get(),
smargon.chi_deg.get(),
aerotech.u.get(),
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(), # + y_offset_mm,
z=smargon.z.get(), # + x_offset_mm,
),
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(),
)