fix: actually add decisions module
This commit is contained in:
1 parent
f6271b06e8
commit
3b8fe99403
4 files changed
+868
No files matched your search
@@ -0,0 +1,85 @@
|
||||
"""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 (only
|
||||
``gridscan_calculation`` uses a pxii calibration macro, imported when it is called). 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",
|
||||
]
|
||||
@@ -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
|
||||
@@ -0,0 +1,283 @@
|
||||
"""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,
|
||||
):
|
||||
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."""
|
||||
# pyright: ignore[reportMissingImports]
|
||||
from pxii_bec.macros.calculator import calc_scam_microns
|
||||
# TODO: migrate utils from plugins to mx_bec
|
||||
|
||||
box_x_pixels = abs(x1_y1[0] - x2_y2[0])
|
||||
box_y_pixels = abs(x1_y1[1] - x2_y2[1])
|
||||
logger.info(f"{box_x_pixels=}, {box_y_pixels=}")
|
||||
box_x_microns = calc_scam_microns(box_x_pixels, zoom=400)
|
||||
box_y_microns = calc_scam_microns(box_y_pixels, zoom=400)
|
||||
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),
|
||||
)
|
||||
@@ -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")
|
||||
Reference in new issue
Block a user