diff --git a/csaxs_bec/bec_ipython_client/plugins/LamNI/AI_docs/FLOMNI_LAMNI_FEATURE_GAPS_2026-07.md b/csaxs_bec/bec_ipython_client/plugins/LamNI/AI_docs/FLOMNI_LAMNI_FEATURE_GAPS_2026-07.md
index 2ba01a01..63fba981 100644
--- a/csaxs_bec/bec_ipython_client/plugins/LamNI/AI_docs/FLOMNI_LAMNI_FEATURE_GAPS_2026-07.md
+++ b/csaxs_bec/bec_ipython_client/plugins/LamNI/AI_docs/FLOMNI_LAMNI_FEATURE_GAPS_2026-07.md
@@ -1,5 +1,53 @@
# flomni → lamni feature gaps still open (2026-07 sweep)
+> **Status update (2026-09-25 go-live audit).** The sections below are the
+> original July findings; several are done since. Current state:
+>
+> - **Done**: §1 timing log + `scilog_last_ptycho_scans()`, §2 account-change
+> reset, §4 `lfzp_in()` skip-if-in-position, §6 `tomo_alignment_scan()` (12
+> angles over 360°, `write_alignment_scan_numbers()`). §7 (OSA clearance in
+> `lfzp_info()`) is implemented but **inactive** until `loptz`'s
+> `collision_offset` userParameter is commissioned in `ptycho_lamni.yaml`.
+> - **Still open**: §3 `collect_empty_frames()` (needs a decision whether
+> lamni's reconstruction uses flat fields), §5 hard-stop button in the GUI
+> (see the caveat in the audit notes below), §9 status-page rows (zero-degree
+> reference toggle is now shown; golden damage-check shots already were).
+> - **Fixed by the September audit** (LamNI compared against the running
+> flomni; tests in `tests/tests_bec_ipython_client/test_lamni_golive_fixes.py`
+> and siblings): projections silently dropped on a TimeoutError alarm
+> (also in `tomo_alignment_scan`); `leye_out()` opened the shutter instead of
+> closing it; endless golden-ratio scan crashed on its first projection and
+> any GUI failure aborted the scan; scilog writes used the removed
+> `bec.logbook` API; `raise_window()` could hide the GUI; tomo_scan_projection
+> now reconstructs itself like flomni (custom hooks were never reconstructed);
+> PDF report ignored the tomo type; CLI range guards; special-angle
+> `UnboundLocalError` (also fixed in flomni); tomo-type-3 sub-tomogram
+> boundary float truncation; `lfzp_info()`/queue "move Energy" used the
+> legacy `mokev` device (now `ccm_energy`); webpage showed half the
+> type-1 projection count; GUI manual-shift unit label (mm, not µm) and a
+> bunch-size floor of 20; x-ray-eye `align()` cleanup on any failure;
+> `xrayeye_update_frame()` beam-state warning.
+> - **Open questions found by the audit** (need a hardware/design decision, not
+> changed): default `lopty.limits = [3.0, 3.6]` excludes the FZP-in position
+> 3.724 from `ptycho_lamni.yaml`; no OSA collision guard in `losa_in()` (needs
+> LamNI's own geometry constant); the hard-stop button must not blindly reuse
+> flomni's `hard_abort_and_restore_positioning_mode()` (it runs `XQ#POSMODE`,
+> a transfer routine LamNI's Galil program may not have; LamNI has one Galil,
+> a SmarAct controller for the OSA and the RT controller);
+> `_write_tomo_scan_number()` writes the literal `'lamni'` (flomni: sanitized
+> sample name, 0cadd85) and `.3f` angles (flomni `.5f`); `LamniFermatScan`
+> lacks flomni's `randomize_offset` switch and `MAX_CORRIDOR_SIZE` cap
+> (19cfee3, 53f246a); `tomo_alignment_scan()` always runs the full eye-out
+> sequence (flomni skips it when already out).
+> - **Behaviour to be aware of**: flomni's `tomo_alignment_scan()` queues its
+> projections for reconstruction (it goes through `tomo_scan_projection`);
+> LamNI's deliberately does not (`_reconstruct=False`).
+> - **Same latent issues remain in flomni** (running in production, not
+> touched here): tomo-type-3 sub-tomogram boundary float truncation
+> (`flomni.py` `_golden_equally_spaced`), and the queue "move Energy" device
+> name `mokev` (`_TOMO_QUEUE_MOVE_DEVICES`) which is only defined in
+> `device_configs/legacy/`.
+
Follow-up to `FLOMNI_TO_LAMNI_COMPARISON.md` (flomni's `AI_docs/`) and this
folder's `TOMO_QUEUE_PORT.md`/`TOMO_PARAMS_GUI_PORT.md` — those covered the
tomo-queue backend, the GUI, the webpage generator, and the angle-distribution
diff --git a/csaxs_bec/bec_ipython_client/plugins/LamNI/LamNI_webpage_generator.py b/csaxs_bec/bec_ipython_client/plugins/LamNI/LamNI_webpage_generator.py
index ead6fe36..ce758c5d 100644
--- a/csaxs_bec/bec_ipython_client/plugins/LamNI/LamNI_webpage_generator.py
+++ b/csaxs_bec/bec_ipython_client/plugins/LamNI/LamNI_webpage_generator.py
@@ -59,7 +59,11 @@ class LamniWebpageGenerator(WebpageGeneratorBase):
# FlomniWebpageGenerator's TOMO_TYPES -- confirmed against lamni.py's
# actual tomo_scan()/sub_tomo_scan() implementation, not a guess.
TOMO_TYPES = {
- 1: {"kind": "equally_spaced_grid", "n_subtomos": 8},
+ # base_angle 360: each lamni sub-tomogram sweeps the full circle
+ # (N = int(360 / step), LamNI._tomo_type1_actual_grid()), unlike
+ # flomni's 180-degree sub-tomograms -- without it the page showed
+ # half the real projection count (144 instead of 288 at 10 deg).
+ 1: {"kind": "equally_spaced_grid", "n_subtomos": 8, "base_angle": 360},
2: {"kind": "golden_capped"},
3: {"kind": "golden_capped"},
}
@@ -72,6 +76,11 @@ class LamniWebpageGenerator(WebpageGeneratorBase):
("tomo_type", "Type"),
("tomo_countingtime", "Exposure (s)"),
("tomo_circfov", "Circular FOV (µm)"),
+ # the piezo range is the FOV of each ptycho tile actually scanned
+ ("lamni_piezo_range_x", "Piezo range x (µm)"),
+ ("lamni_piezo_range_y", "Piezo range y (µm)"),
+ ("manual_shift_x", "Manual shift x (mm)"),
+ ("manual_shift_y", "Manual shift y (mm)"),
("tomo_angle_stepsize", "Angle step (°)"),
("tomo_shellstep", "Shell step (µm)"),
("lamni_stitch_x", "Stitch x"),
@@ -82,6 +91,7 @@ class LamniWebpageGenerator(WebpageGeneratorBase):
("golden_ratio_bunch_size", "Golden bunch size"),
("golden_max_number_of_projections", "Golden max projections"),
("golden_projections_at_0_deg_for_damage_estimation", "0° damage-check shots"),
+ ("zero_deg_reference_at_each_subtomo", "0° reference per sub-tomo"),
("ptycho_reconstruct_foldername", "Recon folder"),
]
diff --git a/csaxs_bec/bec_ipython_client/plugins/LamNI/extra_tomo.py b/csaxs_bec/bec_ipython_client/plugins/LamNI/extra_tomo.py
index fa325343..4ba826f7 100644
--- a/csaxs_bec/bec_ipython_client/plugins/LamNI/extra_tomo.py
+++ b/csaxs_bec/bec_ipython_client/plugins/LamNI/extra_tomo.py
@@ -61,8 +61,8 @@ class MagLamNI(LamNI):
lamni_at_each_angle(self, angle)
return
+ # tomo_scan_projection() adds the projection to the reconstruction queue
self.tomo_scan_projection(angle, _internal=True)
- self.tomo_reconstruct()
class DataDrivenLamNI(LamNI):
@@ -110,9 +110,7 @@ class DataDrivenLamNI(LamNI):
content = f"Loading tomo parameters from {fname}."
logger.warning(content)
- msg = bec.logbook.LogbookMessage()
- msg.add_text(content).add_tag(["Data_driven_file", "BEC"])
- self.client.logbook.send_logbook_message(msg)
+ self.write_to_scilog(content, ["Data_driven_file"])
self._update_tomo_data_from_file(fname)
self._current_special_angles = self.special_angles.copy()
@@ -176,6 +174,10 @@ class DataDrivenLamNI(LamNI):
error_caught = False
if 0 <= angle < 360.05:
print(f"Starting LamNI scan for angle {angle}")
+ # default for angles that aren't a special angle; without it
+ # num_repeats is unbound whenever special_angles is set but
+ # this angle isn't near the next one in the list
+ num_repeats = 1
while not successful:
self._start_beam_check()
if not self.special_angles:
diff --git a/csaxs_bec/bec_ipython_client/plugins/LamNI/gui_tools.py b/csaxs_bec/bec_ipython_client/plugins/LamNI/gui_tools.py
index 52d612e1..8e2113e5 100644
--- a/csaxs_bec/bec_ipython_client/plugins/LamNI/gui_tools.py
+++ b/csaxs_bec/bec_ipython_client/plugins/LamNI/gui_tools.py
@@ -4,6 +4,10 @@ import builtins
import datetime
import time
+from bec_lib import bec_logger
+
+logger = bec_logger.logger
+
if builtins.__dict__.get("bec") is not None:
bec = builtins.__dict__.get("bec")
dev = builtins.__dict__.get("dev")
@@ -41,13 +45,19 @@ class LamniGuiTools:
def lamnigui_show_gui(self):
if "lamni" in self.gui.windows:
self.lamni_window = self.gui.windows["lamni"]
- self.gui.lamni.raise_window()
+ # raise_window() is currently buggy (bec_widgets RPCServer "raise" handling can
+ # detach/hide the window instead of bringing it to front) - disabled so that
+ # calling a lamnigui_show_* macro again on an already-open GUI is a safe no-op
+ # instead of risking hiding the window. Same workaround as flomni's
+ # flomnigui_show_gui().
+ # self.gui.lamni.raise_window()
else:
self.lamni_window = self.gui.new("lamni", timeout=self.GUI_RPC_TIMEOUT)
time.sleep(1)
def lamnigui_raise(self):
- self.gui.lamni.raise_window()
+ # raise_window() disabled, see lamnigui_show_gui().
+ pass
def lamnigui_stop_gui(self):
self.gui.lamni.hide()
@@ -198,20 +208,27 @@ class LamniGuiTools:
# ------------------------------------------------------------------
def lamnigui_show_progress(self):
- self.lamnigui_show_gui()
- if self._lamnigui_is_missing("progressbar"):
- self.lamnigui_remove_all_docks()
- self.progressbar = self.gui.lamni.new(
- "RingProgressBar", timeout=self.GUI_RPC_TIMEOUT
- )
- # Outer ring: overall tomo progress (manual update)
- self.progressbar.add_ring().set_update("manual")
- # Middle ring: current sub-tomo progress (manual update)
- self.progressbar.add_ring().set_update("manual")
- # Inner ring: current scan progress (driven by BEC scan events)
- self.progressbar.add_ring().set_update("scan")
+ # The progress GUI is a display only: it must never be able to abort
+ # a tomogram (a closed GUI / RPC timeout raising out of here would
+ # propagate through @scan_repeat and fail the projection). Same
+ # safeguard as flomni's flomnigui_show_progress() (dea43ed).
+ try:
+ self.lamnigui_show_gui()
+ if self._lamnigui_is_missing("progressbar"):
+ self.lamnigui_remove_all_docks()
+ self.progressbar = self.gui.lamni.new(
+ "RingProgressBar", timeout=self.GUI_RPC_TIMEOUT
+ )
+ # Outer ring: overall tomo progress (manual update)
+ self.progressbar.add_ring().set_update("manual")
+ # Middle ring: current sub-tomo progress (manual update)
+ self.progressbar.add_ring().set_update("manual")
+ # Inner ring: current scan progress (driven by BEC scan events)
+ self.progressbar.add_ring().set_update("scan")
- self._lamnigui_update_progress()
+ self._lamnigui_update_progress()
+ except Exception as exc: # pylint: disable=broad-except
+ logger.warning(f"Error in lamnigui_show_progress: {exc}")
def _lamnigui_update_progress(self):
"""Update the progress ring bar and centre label from the current progress state.
@@ -220,18 +237,35 @@ class LamniGuiTools:
so this reflects the live state accessible from any BEC client session via::
client.get_global_var("tomo_progress")
+
+ Never raises: called from _print_progress() inside every projection, so a
+ GUI failure must not fail (and, via @scan_repeat, retry) the scan itself.
"""
+ try:
+ self._lamnigui_update_progress_impl()
+ except Exception as exc: # pylint: disable=broad-except
+ logger.warning(f"Error updating the LamNI progress GUI: {exc}")
+
+ @staticmethod
+ def _percent(numerator, denominator) -> float:
+ """numerator/denominator in percent; 0 when the denominator is not
+ positive -- e.g. the total of an "endless" golden-ratio scan
+ (golden_max_number_of_projections == 0), which has no meaningful
+ percentage."""
+ if not denominator or denominator <= 0:
+ return 0.0
+ return numerator / denominator * 100
+
+ def _lamnigui_update_progress_impl(self):
if self.progressbar is None:
return
main_progress_ring = self.progressbar.rings[0]
subtomo_progress_ring = self.progressbar.rings[1]
- progress = self.progress["projection"] / self.progress["total_projections"] * 100
- subtomo_progress = (
- self.progress["subtomo_projection"]
- / self.progress["subtomo_total_projections"]
- * 100
+ progress = self._percent(self.progress["projection"], self.progress["total_projections"])
+ subtomo_progress = self._percent(
+ self.progress["subtomo_projection"], self.progress["subtomo_total_projections"]
)
main_progress_ring.set_value(progress)
subtomo_progress_ring.set_value(subtomo_progress)
@@ -269,11 +303,14 @@ class LamniGuiTools:
else:
finish_display = "N/A"
+ total = self.progress["total_projections"]
+ total_display = f"{total:.0f}" if total and total > 0 else "endless"
+
text = (
f"Progress report:\n"
f" Tomo type: {self.progress['tomo_type']}\n"
f" Projection: {self.progress['projection']:.0f}\n"
- f" Total projections expected: {self.progress['total_projections']:.1f}\n"
+ f" Total projections expected: {total_display}\n"
f" Angle: {self.progress['angle']:.1f}\n"
f" Current subtomo: {self.progress['subtomo']}\n"
f" Current projection within subtomo: {self.progress['subtomo_projection']}\n"
diff --git a/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni.py b/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni.py
index df2e018d..83def288 100644
--- a/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni.py
+++ b/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni.py
@@ -130,6 +130,9 @@ class LamNIError(Exception):
class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools):
+ _TOMO_PARAMS_WINDOW_NAME = "lamni_tomo_params"
+ _TOMO_PARAMS_ERROR = LamNIError
+
# Ordered set of all global-var-backed tomo scan parameters snapshotted
# by tomo_queue_add()/restored by tomo_queue_execute(). Lamni's own
# names for overlapping flomni concepts (tomo_circfov instead of
@@ -160,10 +163,14 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
)
# Curated allow-list for the "move" queue action -- same beamline-wide
- # devices as flomni's (mokev, idgap). Lamni has no equivalent of
+ # devices as flomni's (energy, idgap). Lamni has no equivalent of
# flomni's ftray (sample-transfer tray) sim-testable bonus target.
+ # The energy device is "ccm_energy" (bl_optics_hutch.yaml; also what
+ # write_pdf_report()/lfzp_info() read) -- the legacy "mokev" only exists
+ # in device_configs/legacy/, so a queued "move Energy" job would have
+ # failed with a KeyError in dev["mokev"] and paused the queue.
_TOMO_QUEUE_MOVE_DEVICES = {
- "mokev": {"label": "Energy", "unit": "keV"},
+ "ccm_energy": {"label": "Energy", "unit": "keV"},
"idgap": {"label": "Undulator gap", "unit": "mm"},
}
@@ -210,9 +217,10 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
f"step={p.get('tomo_shellstep')}um ctime={p.get('tomo_countingtime')}s"
)
- def __init__(self, client):
+ def __init__(self, client, csaxs=None):
super().__init__()
self.client = client
+ self.csaxs = csaxs
self.set_client(client)
self.device_manager = client.device_manager
self.init = LaMNIInitStages(client)
@@ -473,6 +481,11 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
for line in timing_lines:
print(line)
timing_content = "\n".join(timing_lines)
+ hook_source = self._active_hook_source()
+ if hook_source:
+ timing_content += (
+ f"\n\nAt-each-angle hook source ('{self.at_each_angle_hook}'):\n{hook_source}"
+ )
self.write_to_scilog(timing_content, ["tomoscan"])
@property
@@ -567,9 +580,48 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
Args:
keep_shutter_open: If True the shutter is left open after the frame.
"""
+ all_valid, bad_states = self._check_beamline_states_valid()
+ if not all_valid:
+ print(
+ "Attention: not all beamline states are valid:\n "
+ + "\n ".join(bad_states)
+ + "\nThe beam may be down, so the frame could come back empty."
+ )
+ if not self.OMNYTools.yesno("Take a frame anyway?", "n"):
+ print("Stopping.")
+ return
aligner = XrayEyeAlignGUI(self.client, self)
aligner.update_frame(keep_shutter_open=keep_shutter_open)
+ def _check_beamline_states_valid(self):
+ """Return (all_valid, invalid_labels).
+
+ Reads every configured beamline state (bec.beamline_states) and
+ collects the ones whose status is not "valid" (i.e. "invalid",
+ "warning" or "unknown"). Used to warn before taking a manual X-ray
+ eye frame: if e.g. the beam is down, the frame would come back empty
+ and the user is left confused about why they see nothing. Ported from
+ Flomni._check_beamline_states_valid() (4fe8d02).
+
+ Returns all_valid=True (with an empty list) if the beamline-state
+ machinery isn't available at all, so this never blocks on a session
+ that doesn't use beamline states.
+ """
+ bec = builtins.__dict__.get("bec")
+ manager = getattr(bec, "beamline_states", None) if bec is not None else None
+ if manager is None:
+ return True, []
+
+ bad = []
+ for name in list(getattr(manager, "_states", {})):
+ try:
+ status = manager.get_status_by_name(name)
+ except Exception: # pylint: disable=broad-except
+ continue
+ if status is not None and status != "valid":
+ bad.append(f"{name}: {status}")
+ return (len(bad) == 0), bad
+
def xrayeye_rotation_center_calibration_isolated(self, keep_shutter_open: bool = False):
"""Determine new lsamx/lsamy rotation-center values for a sparse/isolated
particle, via the X-ray eye GUI.
@@ -733,6 +785,21 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
def lights_on(self):
self.device_manager.devices.lsamx.controller.lights_on()
+ def lamni_move_to_scan_center(self, shift_x: float, shift_y: float, angle: float):
+ """
+ LamNI scan to move the interferometer to the computed scan center based on the provided shift and angle.
+
+ Args:
+ shift_x (float): Shift x.
+ shift_y (float): Shift y.
+ angle (float): Angle.
+
+ Returns:
+ ScanReport
+ """
+ scans = builtins.__dict__.get("scans")
+ return scans.lamni_move_to_scan_center(shift_x=shift_x, shift_y=shift_y, angle=angle)
+
# ------------------------------------------------------------------
# Global parameters (backed by BEC global vars)
# ------------------------------------------------------------------
@@ -992,17 +1059,38 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
# Logging helpers
# ------------------------------------------------------------------
- def write_to_scilog(self, content, tags: list = None):
+ def _get_scilog(self):
+ """The enabled scilog messaging service, or None (with a warning) if
+ scilog is unavailable/disabled -- e.g. a dev/sim session."""
+ scilog = getattr(getattr(bec, "messaging", None), "scilog", None)
+ if scilog is None or not getattr(scilog, "_enabled", False):
+ logger.warning("scilog is not enabled; skipping scilog entry.")
+ return None
+ return scilog
+
+ def write_to_scilog(self, content, tags: list = None) -> bool:
+ """Write a text entry to scilog, tolerating scilog being disabled or
+ unreachable. This is documentation of a scan, not part of the scan
+ itself -- it must never fail a caller (in particular a tomo_queue
+ job, which would otherwise be marked "incomplete" and pause the whole
+ queue over a logging side effect). Uses the ``bec.messaging.scilog``
+ service like Flomni._scilog_write(); the old ``bec.logbook`` API this
+ used to call no longer exists in current bec_lib, so every entry was
+ silently dropped.
+
+ Returns True if the entry was sent, False if skipped/failed.
+ """
+ scilog = self._get_scilog()
+ if scilog is None:
+ return False
try:
- if tags is not None:
- tags.append("BEC")
- else:
- tags = ["BEC"]
- msg = bec.logbook.LogbookMessage()
- msg.add_text(content).add_tag(tags)
- self.client.logbook.send_logbook_message(msg)
- except Exception:
- logger.warning("Failed to write to scilog.")
+ tags = list(tags) if tags is not None else []
+ tags.append("BEC")
+ scilog.new().add_text(content.replace("\n", "
")).add_tags(tags).send()
+ return True
+ except Exception as exc: # pylint: disable=broad-except
+ logger.warning(f"Failed to write to scilog: {exc}")
+ return False
_TIMING_LOG_DIR = "~/data/raw/logs/timing_statistics"
_TIMING_SETUP = "lamni"
@@ -1231,8 +1319,18 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
# Scan projection
# ------------------------------------------------------------------
- def tomo_scan_projection(self, angle: float, _internal: bool = False):
- """Acquire one fermat-scan projection at `angle`.
+ def tomo_scan_projection(
+ self, angle: float, _internal: bool = False, _reconstruct: bool = True
+ ):
+ """Acquire one fermat-scan projection at `angle` and add it to the
+ reconstruction queue (tomo_reconstruct()), like
+ Flomni.tomo_scan_projection().
+
+ Reconstruction lives here, not in _at_each_angle(), so that custom
+ at_each_angle hooks -- which call ``setup.tomo_scan_projection(angle,
+ _internal=True)`` (see tomo_queue_mixin's hook example) -- and direct
+ calls also get their projection reconstructed; it used to be
+ skipped for them.
_internal=True is passed by callers that already sit inside an
already-checked flow (tomo_scan()'s/tomo_alignment_scan()'s own
@@ -1240,6 +1338,10 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
below only runs once per tomogram/alignment run instead of once per
projection. Direct/standalone calls (the default) are checked every
time, mirroring Flomni.tomo_scan_projection()'s _internal convention.
+
+ _reconstruct=False skips the reconstruction-queue entry; used by
+ tomo_alignment_scan(), whose quick projections were never queued for
+ reconstruction on lamni.
"""
scans = builtins.__dict__.get("scans")
@@ -1301,9 +1403,19 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
corridor_size=corridor_size,
)
- def write_alignment_scan_numbers(self, first_scan: int) -> None:
+ if _reconstruct:
+ self.tomo_reconstruct()
+
+ def write_alignment_scan_numbers(
+ self, first_scan: int, scans: list[int] | None = None
+ ) -> None:
"""Write the scan-number/angle/offset log consumed by BEC_ptycho_align.
+ ``scans`` (optional): the actual scan number of each alignment point,
+ used to rewrite the file after the scan when a retried angle consumed
+ extra scan numbers. Defaults to the contiguous ``first_scan + k``
+ prediction written before the scan starts.
+
Mirrors Flomni.write_alignment_scan_numbers() exactly (same 4-line
format), adapted to lamni's own alignment-scan angle set (12 points
across the full 360 degrees, see tomo_alignment_scan()) and its own
@@ -1313,7 +1425,8 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
version makes.
"""
angles = list(np.linspace(0, 360, num=12, endpoint=False))
- scans = [first_scan + k for k in range(len(angles))]
+ if scans is None:
+ scans = [first_scan + k for k in range(len(angles))]
x_vals = []
for angle in angles:
@@ -1378,29 +1491,38 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
)
self.lamnigui_show_alignment_progress()
+ first_scan_per_angle = []
+ max_attempts = 10
for idx, angle in enumerate(angles):
- successful = False
print(f"Starting LamNI scan for angle {angle}")
- while not successful:
+ for attempt in range(1, max_attempts + 1):
+ start_scan_number = bec.queue.next_scan_number
try:
- start_scan_number = bec.queue.next_scan_number
- self.tomo_scan_projection(angle, _internal=True)
+ self.tomo_scan_projection(angle, _internal=True, _reconstruct=False)
+ break
except AlarmBase as exc:
- if exc.alarm_type == "TimeoutError":
- bec.queue.request_queue_reset()
- time.sleep(2)
- else:
- raise exc
+ if exc.alarm_type != "TimeoutError" or attempt == max_attempts:
+ raise
+ # Re-acquire this angle after clearing the queue. This used
+ # to swallow the alarm and carry on, silently losing the
+ # angle while still logging the failed attempt's scan
+ # numbers as if it had succeeded.
+ print(f"Alignment angle {angle}: scan timed out, retrying ({attempt}).")
+ bec.queue.request_queue_reset()
+ time.sleep(2)
- end_scan_number = bec.queue.next_scan_number
- for scan_nr in range(start_scan_number, end_scan_number):
- alignment_scan_numbers.append(scan_nr)
-
- successful = True
+ end_scan_number = bec.queue.next_scan_number
+ first_scan_per_angle.append(start_scan_number)
+ alignment_scan_numbers.extend(range(start_scan_number, end_scan_number))
self.alignment_scan_progress.update(angle_index=idx + 1, angle=angle)
self._lamnigui_update_alignment_progress()
+ # The file written up front assumes first_scan + k per angle; a retried
+ # angle consumes extra scan numbers, so rewrite it with what was
+ # actually acquired.
+ self.write_alignment_scan_numbers(first_scan_per_angle[0], scans=first_scan_per_angle)
+
umv(dev.lsamrot, 0)
self.OMNYTools.printgreenbold(
"\n\nAlignment scan finished. Please run BEC_ptycho_align and load the new fit"
@@ -1421,12 +1543,26 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
self.write_to_scilog(scilog_content, ["alignmentscan"])
def tomo_reconstruct(self, base_path="~/data/raw/logs/reconstruction_queue"):
- """write the tomo reconstruct file for the reconstruction queue"""
+ """Write the tomo reconstruct file for the reconstruction queue.
+
+ Normally called automatically at the end of tomo_scan_projection(),
+ which keeps self._current_scan_list up to date with the scan
+ number(s) of the projection just acquired (possibly several, when
+ stitching). When called directly -- e.g. from the command line after
+ a plain scans.lamni_fermat_scan(), without going through
+ tomo_scan_projection() -- that cached list is either stale (left over
+ from an earlier tomo scan) or not set at all, so fall back to just
+ the most recently completed scan number.
+ """
bec = builtins.__dict__.get("bec")
+ next_scan_number = bec.queue.next_scan_number
+ last_scan_number = next_scan_number - 1
+ scan_list = getattr(self, "_current_scan_list", None)
+ if not scan_list or scan_list[-1] != last_scan_number:
+ scan_list = [last_scan_number]
+ self.reconstructor.folder_name = self.ptycho_reconstruct_foldername
self.reconstructor.write(
- scan_list=self._current_scan_list,
- next_scan_number=bec.queue.next_scan_number,
- base_path=base_path,
+ scan_list=scan_list, next_scan_number=next_scan_number, base_path=base_path
)
def _at_each_angle(self, angle: float) -> None:
@@ -1436,8 +1572,9 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
hook(self, angle)
return
+ # tomo_scan_projection() itself adds the projection to the
+ # reconstruction queue -- do not call tomo_reconstruct() again here.
self.tomo_scan_projection(angle, _internal=True)
- self.tomo_reconstruct()
# ------------------------------------------------------------------
# Progress reporting
@@ -1478,6 +1615,56 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
print(f"Estimated finish time: ........... {finish_str}\x1b[0m")
self._lamnigui_update_progress()
+ def _reset_progress_for_new_scan(self) -> None:
+ """Reset ``tomo_progress`` (and refresh the progress GUI) for a brand-new
+ tomogram, in one global-var round-trip.
+
+ Every field must be reset, not just the timing/ETA ones: a finished
+ previous scan leaves projection == total_projections (100 %), its last
+ subtomo and angle behind, and the new scan's very first
+ _print_progress() -- fired by the 0-degree reference shot, before the
+ grid loop has written a single field -- would otherwise show those
+ stale values (rings at 100 %, old subtomo/angle, and an ETA of "0 s"
+ computed from the old projection count against the NEW start time).
+
+ subtomo is set to 1 (not 0) so a scan interrupted during the 0-degree
+ shot is still resumable by tomo_scan_resume().
+ """
+ if self.tomo_type == 1:
+ tomo_type_name = "Equally spaced sub-tomograms"
+ subtomo_total, _, total = self._tomo_type1_actual_grid()
+ elif self.tomo_type == 2:
+ tomo_type_name = "Golden ratio tomography"
+ subtomo_total = self.golden_ratio_bunch_size
+ total = self.golden_max_number_of_projections
+ elif self.tomo_type == 3:
+ tomo_type_name = "Equally spaced, golden ratio starting angles"
+ subtomo_total = 360 / self.tomo_angle_stepsize
+ total = self.golden_max_number_of_projections
+ else:
+ raise ValueError(f"Unknown tomo_type: {self.tomo_type}.")
+
+ self.progress.update(
+ {
+ "tomo_type": tomo_type_name,
+ "subtomo": 1,
+ "subtomo_projection": 0,
+ # totals are used as divisors by the GUI rings -- never 0
+ "subtomo_total_projections": subtomo_total or 1,
+ "projection": 0,
+ "total_projections": total if total and total > 0 else 1,
+ "angle": 0,
+ "tomo_start_time": datetime.datetime.now().isoformat(),
+ # no leftover ETA from a previous scan until this one has
+ # accumulated enough projections to compute a fresh one
+ "estimated_remaining_time": None,
+ "estimated_finish_time": None,
+ "heartbeat": None,
+ "accumulated_idle_time": 0.0,
+ }
+ )
+ self._lamnigui_update_progress()
+
# ------------------------------------------------------------------
# Tomo scan orchestration
# ------------------------------------------------------------------
@@ -1511,35 +1698,64 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
(no tomo_angle_range/forward-reverse split -- lamni always scans
the full 360 degrees).
+ Args:
+ start_angle (float, optional): resume point -- the literal angle
+ (on this sub-tomogram's own grid) to continue from, NOT the
+ origin of a new sweep. The returned angles are then the
+ remaining tail of the normal sweep, beginning at (and
+ including) this angle. Raises ValueError if it isn't on
+ the grid. Mirrors Flomni._subtomo_angle_plan().
+
Returns:
- angles (np.ndarray): the N angles (degrees) for this sub-tomogram.
+ angles (np.ndarray): the N angles (degrees) for this sub-tomogram
+ (or, when resuming, the remaining ones from start_angle on).
+ subtomo_offset (int): index of angles[0] within the full
+ sub-tomogram sweep (0 unless resuming), for progress numbering.
N (int): number of projections in this (and every) sub-tomogram.
"""
N = int(360.0 / tomo_angle_stepsize)
achievable_step = 360.0 / N
- if start_angle is None:
- # Phase offset must be a fraction of the ACHIEVABLE step (after
- # int() truncation), not the raw configured tomo_angle_stepsize --
- # they only coincide when 360/tomo_angle_stepsize happens to
- # already be a whole number. Using the raw value here breaks the
- # interlacing scheme: sub-tomograms combined in pairs/quads/all-8
- # land on unevenly-spaced angles instead of the intended
- # progressively finer, evenly-spaced grid at every combination
- # level. Mirrors Flomni._subtomo_angle_plan() exactly.
- offsets = {1: 0, 2: 4, 3: 2, 4: 6, 5: 1, 6: 5, 7: 3, 8: 7}
- start_angle = achievable_step / 8.0 * offsets[subtomo_number]
+ # Phase offset must be a fraction of the ACHIEVABLE step (after
+ # int() truncation), not the raw configured tomo_angle_stepsize --
+ # they only coincide when 360/tomo_angle_stepsize happens to
+ # already be a whole number. Using the raw value here breaks the
+ # interlacing scheme: sub-tomograms combined in pairs/quads/all-8
+ # land on unevenly-spaced angles instead of the intended
+ # progressively finer, evenly-spaced grid at every combination
+ # level. Mirrors Flomni._subtomo_angle_plan() exactly.
+ offsets = {1: 0, 2: 4, 3: 2, 4: 6, 5: 1, 6: 5, 7: 3, 8: 7}
+ sweep_start = achievable_step / 8.0 * offsets[subtomo_number]
- angle_end = start_angle + 360
# endpoint=False: a full 360-degree sweep must NOT re-measure both
- # start_angle and start_angle+360 -- they're the same physical angle,
+ # sweep_start and sweep_start+360 -- they're the same physical angle,
# unlike a [0, 180) span's two distinct endpoints.
- angles = np.linspace(start_angle, angle_end, num=N, endpoint=False)
+ angles = np.linspace(sweep_start, sweep_start + 360, num=N, endpoint=False)
if not (subtomo_number % 2):
angles = np.flip(angles)
- return angles, N
+ if start_angle is None:
+ return angles, 0, N
+
+ # Resuming: locate start_angle on this sub-tomogram's own grid (with
+ # 360-degree wrap-around) and continue from there in the same
+ # direction. start_angle must NOT be used as the sweep origin -- that
+ # would generate angles past 360 (silently skipped by
+ # _tomo_scan_at_angle's range gate) and never reach the remaining
+ # part of the sweep.
+ diff = np.abs((angles - start_angle + 180.0) % 360.0 - 180.0)
+ subtomo_offset = int(np.argmin(diff))
+ # start_angle normally comes straight from progress["angle"] (taken
+ # from this same grid), so only float noise is tolerated here -- the
+ # nearest grid point is always within step/2, so a looser check
+ # would never catch a genuinely off-grid angle.
+ if diff[subtomo_offset] > 0.01:
+ raise ValueError(
+ f"start_angle {start_angle} is not on the angle grid of sub-tomogram "
+ f"{subtomo_number} (tomo_angle_stepsize={tomo_angle_stepsize})."
+ )
+ return angles[subtomo_offset:], subtomo_offset, N
def _resolve_type1_projection(self, projection_number: int) -> tuple[int, float]:
"""Map a flat 0-indexed tomo_type-1 projection number to
@@ -1551,7 +1767,7 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
tomography_scannumbers.txt log resolves to the same angle
sub_tomo_scan() would have produced at that position.
"""
- _, N = self._subtomo_angle_plan(1, self.tomo_angle_stepsize)
+ _, _, N = self._subtomo_angle_plan(1, self.tomo_angle_stepsize)
total = N * 8
if not 0 <= projection_number < total:
raise ValueError(
@@ -1559,20 +1775,20 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
f"(tomo_angle_stepsize={self.tomo_angle_stepsize})."
)
subtomo_number = projection_number // N + 1
- angles, _ = self._subtomo_angle_plan(subtomo_number, self.tomo_angle_stepsize)
+ angles, _, _ = self._subtomo_angle_plan(subtomo_number, self.tomo_angle_stepsize)
return subtomo_number, float(angles[projection_number % N])
def sub_tomo_scan(self, subtomo_number, start_angle=None):
"""Perform one sub-tomogram (tomo_type 1 only)."""
- angles, N = self._subtomo_angle_plan(
+ angles, subtomo_offset, N = self._subtomo_angle_plan(
subtomo_number, self.tomo_angle_stepsize, start_angle=start_angle
)
total_projections = N * 8
- for angle in angles:
+ for i, angle in enumerate(angles):
self.progress["tomo_type"] = "Equally spaced sub-tomograms"
self.progress["subtomo"] = subtomo_number
- self.progress["subtomo_projection"] = np.where(angles == angle)[0][0]
+ self.progress["subtomo_projection"] = subtomo_offset + i
self.progress["subtomo_total_projections"] = N
self.progress["projection"] = (subtomo_number - 1) * N + self.progress[
"subtomo_projection"
@@ -1610,8 +1826,6 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
@scan_repeat(max_repeats=10, default=True, exc_handler=_retry_unless_lamni_error)
def _tomo_scan_at_angle(self, angle, subtomo_number):
- successful = False
- error_caught = False
if 0 <= angle < 360.05:
now = datetime.datetime.now()
prev_heartbeat_str = self.progress.get("heartbeat")
@@ -1643,49 +1857,54 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
print(f"Starting LamNI scan for angle {angle} in subtomo {subtomo_number}")
self._print_progress()
- while not successful:
- if not self.special_angles:
- self._current_special_angles = []
- if self._current_special_angles:
- next_special_angle = self._current_special_angles[0]
- if np.isclose(angle, next_special_angle, atol=0.5):
- self._current_special_angles.pop(0)
- num_repeats = self.special_angle_repeats
- else:
- num_repeats = 1
- try:
- start_scan_number = bec.queue.next_scan_number
- projection_start = time.perf_counter()
- for i in range(num_repeats):
- self._at_each_angle(angle)
- projection_duration = time.perf_counter() - projection_start
- error_caught = False
- except AlarmBase as exc:
- if exc.alarm_type == "TimeoutError":
- bec.queue.request_queue_reset()
- time.sleep(2)
- error_caught = True
- else:
- raise exc
- end_scan_number = bec.queue.next_scan_number
- for scan_nr in range(start_scan_number, end_scan_number):
- self._write_tomo_scan_number(scan_nr, angle, subtomo_number)
+ if not self.special_angles:
+ self._current_special_angles = []
+ # num_repeats is decided without consuming the special-angle list,
+ # which is only popped once the projection succeeded: this method
+ # runs under @scan_repeat, so a failed attempt is retried and must
+ # see the same special angle (and repeat count) again.
+ num_repeats = 1
+ is_special_angle = bool(
+ self._current_special_angles
+ and np.isclose(angle, self._current_special_angles[0], atol=0.5)
+ )
+ if is_special_angle:
+ num_repeats = self.special_angle_repeats
- if not error_caught:
- # Only reached for a clean completion -- an
- # AlarmBase/TimeoutError attempt above has no reliable
- # duration measurement, so it's excluded from the
- # timing log rather than polluting it.
- self._log_projection_timing(
- angle=angle,
- subtomo_number=subtomo_number,
- duration_s=projection_duration,
- start_scan_number=start_scan_number,
- end_scan_number=end_scan_number,
- )
+ start_scan_number = bec.queue.next_scan_number
+ projection_start = time.perf_counter()
+ try:
+ for _ in range(num_repeats):
+ self._at_each_angle(angle)
+ except AlarmBase as exc:
+ if exc.alarm_type == "TimeoutError":
+ # Clear the stuck queue, then re-raise so @scan_repeat
+ # re-acquires this projection. Swallowing the alarm here
+ # (as this used to) silently dropped the projection: its
+ # failed scan numbers were logged as if it had succeeded
+ # and it never reached the reconstruction queue.
+ bec.queue.request_queue_reset()
+ time.sleep(2)
+ raise
+ projection_duration = time.perf_counter() - projection_start
- successful = True
+ if is_special_angle:
+ self._current_special_angles.pop(0)
+
+ end_scan_number = bec.queue.next_scan_number
+ for scan_nr in range(start_scan_number, end_scan_number):
+ self._write_tomo_scan_number(scan_nr, angle, subtomo_number)
+
+ # Only reached when the projection completed without @scan_repeat
+ # re-raising, so this is the final successful attempt's duration.
+ self._log_projection_timing(
+ angle=angle,
+ subtomo_number=subtomo_number,
+ duration_s=projection_duration,
+ start_scan_number=start_scan_number,
+ end_scan_number=end_scan_number,
+ )
def _golden(self, ii, howmany_sorted, maxangle=360, reverse=False):
"""Return the ii-th golden ratio angle within sorted bunches and its subtomo number."""
@@ -1707,7 +1926,13 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
):
"""Return angles for equally spaced tomography with golden ratio sub-tomogram starting angles."""
angular_step = maxangle / number_of_projections_per_subtomo
- subtomo_number = int((ii * angular_step) / maxangle) + 1
+ # Exact integer division. The equivalent float expression
+ # int((ii * angular_step) / maxangle) + 1 truncates just below an
+ # integer for ii == k * n for some n (e.g. n = 19, 33, 38, 39, 66,
+ # ...): the first projection of a sub-tomogram was then labelled with
+ # the previous sub-tomogram number and acquired as a duplicate of its
+ # closing angle, and the next sub-tomogram skipped its first angle.
+ subtomo_number = int(ii // number_of_projections_per_subtomo) + 1
start_angle = self._golden(subtomo_number - 1, 1, angular_step)[0]
projection_number_of_subtomo = ii - (subtomo_number - 1) * number_of_projections_per_subtomo
@@ -1828,14 +2053,7 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
"BEC",
)
self.write_pdf_report()
- self.progress["tomo_start_time"] = datetime.datetime.now().isoformat()
- # reset stale estimates from any previous scan, otherwise the GUI
- # would keep showing a leftover ETA from before this scan has
- # accumulated enough projections to compute a fresh one
- self.progress["estimated_remaining_time"] = None
- self.progress["estimated_finish_time"] = None
- self.progress["accumulated_idle_time"] = 0.0
- self.progress["heartbeat"] = None
+ self._reset_progress_for_new_scan()
# Unconditional single 0-degree reference projection at the very
# start of a new tomogram, independent of
# zero_deg_reference_at_each_subtomo /
@@ -1989,6 +2207,11 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
for line in timing_lines[3:]:
print(line)
timing_content = "\n".join(timing_lines)
+ hook_source = self._active_hook_source()
+ if hook_source:
+ timing_content += (
+ f"\n\nAt-each-angle hook source ('{self.at_each_angle_hook}'):\n{hook_source}"
+ )
self.write_to_scilog(timing_content, ["tomoscan"])
def tomo_scan_resume(self) -> None:
@@ -2085,8 +2308,9 @@ class LamNI(TomoQueueMixin, LamNIAlignmentMixin, LamNIOpticsMixin, LamniGuiTools
return LamniFermatScan.MIN_POSITIONS
- def tomo_parameters(self):
- """Print and interactively update the tomo parameters."""
+ def tomo_parameters_cli(self):
+ """Print and interactively update the tomo parameters on the command line.
+ tomo_parameters() opens the GUI version."""
print("Current settings:")
print(f"Counting time per frame
")).add_tag(
+ scilog.new().add_attachment(logo_path, width=200).add_text(
+ scilog_text.replace("\n", "
")
+ ).add_tags(
["BEC", "tomo_parameters", f"dataset_id_{dataset_id}", "LamNI", self.sample_name]
- )
- self.client.logbook.send_logbook_message(msg)
- except Exception:
- logger.warning("Failed to write PDF report to scilog.")
+ ).send()
+ except Exception as exc: # pylint: disable=broad-except
+ logger.warning(f"Failed to write PDF report to scilog: {exc}")
def get_calibration_of_capstops_left_and_right(self):
import time
diff --git a/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni_alignment_mixin.py b/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni_alignment_mixin.py
index e404710a..a60d914f 100644
--- a/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni_alignment_mixin.py
+++ b/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni_alignment_mixin.py
@@ -202,8 +202,10 @@ class LamNIAlignmentMixin:
.. important::
This method reads from the live GUI widget. If the XRayEye GUI
window has been closed since the alignment was performed the call
- will fail. In that case use :meth:`read_xray_eye_correction` to
- reload from the archived text files.
+ will fail. (The former file-based fallback
+ ``read_xray_eye_correction()`` is disabled -- see the commented-out
+ code above -- so re-open the X-ray eye GUI and let the fit converge
+ again, or re-run the alignment.)
"""
_dev = builtins.__dict__.get("dev")
tomo_fit_xray_eye = np.zeros((2, 3))
@@ -223,9 +225,8 @@ class LamNIAlignmentMixin:
f"{type(params).__name__ if not isinstance(params, dict) else 'a dict missing keys'}). "
"This means the fit hasn't converged / DAP forwarding hasn't produced "
"a result yet, not that the correction data is missing. Wait for the "
- "fit to converge in the XRayEye GUI's Fit tab, or use "
- "read_xray_eye_correction() to reload from the archived text files "
- "instead."
+ "fit to converge in the XRayEye GUI's Fit tab (keep the XRayEye "
+ "window open), or re-run the alignment."
)
tomo_fit_xray_eye[0][0] = params_x["SineModel_0_amplitude"]
@@ -314,7 +315,6 @@ class LamNIAlignmentMixin:
with open(correction_file, "r") as f:
num_elements = f.readline()
int_num_elements = int(num_elements.split(" ")[2])
- print(int_num_elements)
corr_pos_x = []
corr_pos_y = []
corr_angle = []
diff --git a/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni_optics_mixin.py b/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni_optics_mixin.py
index c04a4d24..10915a20 100644
--- a/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni_optics_mixin.py
+++ b/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni_optics_mixin.py
@@ -214,23 +214,122 @@ class LamNIOpticsMixin:
return None
return param.get(var)
+ @property
+ def _sl1xs_before_eye(self):
+ return self.client.get_global_var("lamni_sl1xs_before_eye")
+
+ @_sl1xs_before_eye.setter
+ def _sl1xs_before_eye(self, val):
+ self.client.set_global_var("lamni_sl1xs_before_eye", val)
+
+ @property
+ def _sl1ys_before_eye(self):
+ return self.client.get_global_var("lamni_sl1ys_before_eye")
+
+ @_sl1ys_before_eye.setter
+ def _sl1ys_before_eye(self, val):
+ self.client.set_global_var("lamni_sl1ys_before_eye", val)
+
def leye_out(self):
self.loptics_in()
- dev.fsh.fshopen()
+ # Close (not open) the shutter as the eye leaves the beam, like
+ # flomni's feye_out(). Was fshclose() originally; commit 4967474
+ # ("removed fsh commands") turned it into fshopen() by mistake.
+ dev.fsh.fshclose()
+
+ if self.csaxs is not None:
+ self.csaxs.fil_trans(1, print_only=False)
+
+ sl1xs_before = self._sl1xs_before_eye
+ sl1ys_before = self._sl1ys_before_eye
+ if sl1xs_before is not None and sl1ys_before is not None:
+ # if the slit was manually re-adjusted while the eye was in,
+ # offer to keep the current size instead of restoring the
+ # pre-eye value
+ current_sl1xs = dev.sl1xs.user_readback.get()
+ current_sl1ys = dev.sl1ys.user_readback.get()
+ expected_sl1xs = sl1xs_before + 0.3
+ expected_sl1ys = sl1ys_before + 0.3
+ tol = 0.01 # mm (10 microns)
+ manually_adjusted = not np.isclose(
+ current_sl1xs, expected_sl1xs, atol=tol
+ ) or not np.isclose(current_sl1ys, expected_sl1ys, atol=tol)
+
+ if manually_adjusted and self.OMNYTools.yesno(
+ "sl1xs/sl1ys appear to have been adjusted manually while the "
+ "eye was in. Keep the current slit size instead of "
+ "restoring the pre-eye value?"
+ ):
+ print("Keeping current slit size, not restoring pre-eye value.")
+ else:
+ umv(dev.sl1xs, sl1xs_before, dev.sl1ys, sl1ys_before)
+ self._sl1xs_before_eye = None
+ self._sl1ys_before_eye = None
+
leyey_out = self._get_user_param_safe("leyey", "out")
umv(dev.leyey, leyey_out)
umv(dev.lsamrot, 0)
#umv(dev.dttrz, 5854, dev.fttrz, 2395)
+ # DRAFT, disabled until the fttrz positions are known: move the flight tube
+ # in after the eye is out, like flomni's feye_out(). Needs the userParameters
+ # fttrz_in / fttrz_out on leyex (see ptycho_lamni.yaml).
+ # if "fttrz" not in dev:
+ # if not self.OMNYTools.yesno(
+ # "Device 'fttrz' does not exist in the current config, so it "
+ # "can't be moved into position. Continue anyway? WARNING: "
+ # "this could cause collisions when operating on the real "
+ # "beamline."
+ # ):
+ # print("Aborting leye_out(): fttrz not moved.")
+ # return
+ # else:
+ # fttrz_in = self._get_user_param_safe("leyex", "fttrz_in")
+ # umv(dev.fttrz, fttrz_in)
+
def leye_in(self):
bec.queue.next_dataset_number += 1
umv(dev.lsamrot, 0)
#umv(dev.dttrz, 6419.677, dev.fttrz, 2959.979)
+
+ # DRAFT, disabled until the fttrz positions are known: move the flight tube
+ # out before the eye goes in, like flomni's feye_in(). When enabled, this
+ # replaces the manual "Did the flight tube move out?" prompt below.
+ # if "fttrz" not in dev:
+ # if not self.OMNYTools.yesno(
+ # "Device 'fttrz' does not exist in the current config, so it "
+ # "can't be moved out of the way. Continue anyway? WARNING: "
+ # "this could cause collisions when operating on the real "
+ # "beamline."
+ # ):
+ # print("Aborting leye_in(): fttrz not moved.")
+ # return
+ # else:
+ # fttrz_out = self._get_user_param_safe("leyex", "fttrz_out")
+ # umv(dev.fttrz, fttrz_out)
+
if not self.OMNYTools.yesno("Did the flight tube move out?", "y"):
return
leyex_in = self._get_user_param_safe("leyex", "in")
leyey_in = self._get_user_param_safe("leyey", "in")
+
+ current_leyex = dev.leyex.readback.get()
+ current_leyey = dev.leyey.readback.get()
+
+ # check if both are close enough (within 0.01)
+ if np.isclose(current_leyex, leyex_in, atol=0.01) and np.isclose(current_leyey, leyey_in, atol=0.01):
+ # both already in position -> do nothing
+ pass
+ else:
+ if "sl1xs" in dev and "sl1ys" in dev:
+ self._sl1xs_before_eye = dev.sl1xs.user_readback.get()
+ self._sl1ys_before_eye = dev.sl1ys.user_readback.get()
+ scans.umv(dev.sl1xs, 0.3, dev.sl1ys, 0.3, relative=True)
+
+ if self.csaxs is not None:
+ self.csaxs.fil_trans(0.05, print_only=False)
+
umv(dev.leyex, leyex_in, dev.leyey, leyey_in)
self.xrayeye_update_frame()
@@ -423,11 +522,15 @@ class LamNIOpticsMixin:
def lfzp_info(self, mokev_val=-1):
if mokev_val == -1:
+ # The energy readback device is "ccm_energy" (same as flomni's
+ # ffzp_info() and LamNI.write_pdf_report()); the legacy "mokev"
+ # device is not in the current configs, so this always bailed out.
try:
- mokev_val = dev.mokev.readback.get()
+ mokev_val = dev.ccm_energy.read(cached=True)[dev.ccm_energy.name]["value"]
except Exception:
print(
- "Device mokev does not exist. You can specify the energy in keV as an argument instead."
+ "Could not read the photon energy from device ccm_energy. "
+ "You can specify the energy in keV as an argument instead."
)
return
loptz_val = dev.loptz.read()["loptz"]["value"]
diff --git a/csaxs_bec/bec_ipython_client/plugins/LamNI/x_ray_eye_align.py b/csaxs_bec/bec_ipython_client/plugins/LamNI/x_ray_eye_align.py
index 0cff8843..cc03dabd 100644
--- a/csaxs_bec/bec_ipython_client/plugins/LamNI/x_ray_eye_align.py
+++ b/csaxs_bec/bec_ipython_client/plugins/LamNI/x_ray_eye_align.py
@@ -273,6 +273,35 @@ class XrayEyeAlign:
return False
def align(self, keep_shutter_open: bool = False):
+ """Run the full LamNI X-ray eye alignment (see _align_impl() for the
+ procedure).
+
+ Whatever ends the run -- success, Ctrl-C or ANY other exception (a GUI
+ RPC error, a missing GUI output key, ...) -- the GUI is put back into
+ a clean state afterwards: DAP parameter forwarding off and the
+ alignment crosshair hidden. Previously only KeyboardInterrupt (handled
+ by the caller) did this, so any other failure left forwarding on and
+ the crosshair drawn. Mirrors flomni's XrayEyeAlign.align() try/finally
+ (LamNI has no skip button or ROI vertical lock to reset).
+ """
+ try:
+ self.gui.reset_zoom()
+ except Exception as exc: # pylint: disable=broad-except
+ logger.warning(f"Failed to reset the XRayEye zoom: {exc}")
+
+ try:
+ self._align_impl(keep_shutter_open)
+ finally:
+ try:
+ self.gui.set_dap_params_forwarding(False)
+ except Exception as exc: # pylint: disable=broad-except
+ logger.warning(f"Failed to disable XRayEye DAP parameter forwarding: {exc}")
+ try:
+ self.gui.hide_crosshair()
+ except Exception as exc: # pylint: disable=broad-except
+ logger.warning(f"Failed to hide XRayEye alignment crosshair: {exc}")
+
+ def _align_impl(self, keep_shutter_open: bool = False):
"""Run the full LamNI X-ray eye alignment.
Args:
@@ -556,7 +585,7 @@ class XrayEyeAlign:
self.tomo_rotate(0)
print(
"Done. You are ready to remove the X-ray eye and start ptychography scans.\n"
- "Fine alignment: lamni.tomo_parameters() with offset 0, then lamni.sub_tomo_scan(1,0)"
+ "Fine alignment: lamni.tomo_parameters(), then lamni.tomo_alignment_scan()"
)
# ------------------------------------------------------------------
diff --git a/csaxs_bec/bec_ipython_client/plugins/OMNY_shared/tomo_queue_mixin.py b/csaxs_bec/bec_ipython_client/plugins/OMNY_shared/tomo_queue_mixin.py
index f5af08ef..1b427dab 100644
--- a/csaxs_bec/bec_ipython_client/plugins/OMNY_shared/tomo_queue_mixin.py
+++ b/csaxs_bec/bec_ipython_client/plugins/OMNY_shared/tomo_queue_mixin.py
@@ -41,6 +41,7 @@ import inspect
import json
import os
import threading
+import time
import uuid
from typing import Callable
@@ -210,6 +211,12 @@ class TomoQueueMixin:
_TOMO_QUEUE_ACTIONS: dict = {}
_TOMO_QUEUE_MOVE_DEVICES: dict = {}
+ # tomo_parameters() GUI window: subclasses set a unique window name (a valid
+ # Python identifier, e.g. "lamni_tomo_params") and their own error class.
+ _TOMO_PARAMS_WINDOW_NAME: str = ""
+ _TOMO_PARAMS_ERROR: type[Exception] = RuntimeError
+ _TOMO_PARAMS_GUI_TIMEOUT = 20
+
# Name of a registered at_each_angle hook (see register_at_each_angle_hook()),
# or None for the default per-projection behaviour.
at_each_angle_hook = _GlobalVarParam(None)
@@ -237,6 +244,42 @@ class TomoQueueMixin:
# since-ended session must not linger and look registered.
self._publish_at_each_angle_hooks()
+ # ── tomo parameter GUI window ───────────────────────────────────────────
+
+ def tomo_parameters(self) -> None:
+ """Open the tomo parameter GUI (OMNY_TomoParams) in its own window.
+
+ Calling it again while the window is open does nothing. The widget
+ works on the same global variables as the command line version,
+ ``tomo_parameters_cli()``, which is not used as an automatic fallback:
+ if the GUI cannot be opened this raises, so the problem gets fixed.
+ """
+ name = self._TOMO_PARAMS_WINDOW_NAME
+ error = self._TOMO_PARAMS_ERROR
+ gui = getattr(self.client, "gui", None)
+ if gui is None:
+ raise error(
+ "No BEC GUI is available in this session, so the tomo parameter window cannot be"
+ " opened. Use tomo_parameters_cli() for the command line version."
+ )
+ timeout = self._TOMO_PARAMS_GUI_TIMEOUT
+ try:
+ if name in gui.windows:
+ window = getattr(gui, name)
+ if hasattr(window, "tomo_params"):
+ print("The tomo parameter window is already open.")
+ return
+ else:
+ gui.new(name, timeout=timeout)
+ time.sleep(1)
+ window = getattr(gui, name)
+ window.new("OMNY_TomoParams", object_name="tomo_params", timeout=timeout)
+ except Exception as exc: # pylint: disable=broad-except
+ raise error(
+ f"Could not open the tomo parameter window ({type(exc).__name__}: {exc}). Use"
+ " tomo_parameters_cli() for the command line version."
+ ) from exc
+
# ── at_each_angle hook registry ─────────────────────────────────────────
def register_at_each_angle_hook(self, name: str, func) -> None:
diff --git a/csaxs_bec/bec_ipython_client/plugins/OMNY_shared/webpage_generator_base.py b/csaxs_bec/bec_ipython_client/plugins/OMNY_shared/webpage_generator_base.py
index 0bdddcb1..38028410 100644
--- a/csaxs_bec/bec_ipython_client/plugins/OMNY_shared/webpage_generator_base.py
+++ b/csaxs_bec/bec_ipython_client/plugins/OMNY_shared/webpage_generator_base.py
@@ -404,14 +404,21 @@ class WebpageGeneratorBase:
takes. Used by the UI to compute total-projection
counts for queued jobs without hardcoding a
per-instrument formula in JS. Recognised "kind"s:
- "equally_spaced_grid" (params: n_subtomos)
- total = floor(180 / angle_stepsize) * n_subtomos
+ "equally_spaced_grid" (params: n_subtomos,
+ optional base_angle,
+ default 180)
+ total = floor(base_angle / angle_stepsize)
+ * n_subtomos
(independent of angle_range - see
Flomni._subtomo_angle_plan()'s docstring for
why: in 360-degree mode, angle_range only
splits the n_subtomos into complementary
low/high halves, it does not change the
- total count)
+ total count). base_angle is the angular span
+ ONE sub-tomogram covers: 180 for flomni, 360
+ for lamni (which always sweeps the full
+ circle per sub-tomogram -- see
+ LamNI._tomo_type1_actual_grid()).
"golden_capped"
total = golden_max_number_of_projections
TQ_PARAM_DISPLAY -- list of (global_var_key, display_label) pairs, in
@@ -2701,13 +2708,15 @@ function calcProjections(params){{
return (gmax!=null&&gmax>0)?gmax:null;
}}
if(def.kind==='equally_spaced_grid'){{
- // Always floor(180/step), never floor(angle_range/step): in 360-degree
- // mode angle_range only splits the sub-tomograms into complementary
- // low/high halves, it does not change the total projection count -
- // see Flomni._subtomo_angle_plan()'s docstring.
+ // Always floor(base_angle/step), never floor(angle_range/step): in
+ // 360-degree mode angle_range only splits the sub-tomograms into
+ // complementary low/high halves, it does not change the total
+ // projection count - see Flomni._subtomo_angle_plan()'s docstring.
+ // base_angle is the span of one sub-tomogram: 180 (default, flomni) or
+ // 360 (lamni, which sweeps the full circle in every sub-tomogram).
const step=params.tomo_angle_stepsize;
if(step>0){{
- const N=Math.floor(180/step);
+ const N=Math.floor((def.base_angle||180)/step);
return N*(def.n_subtomos||1);
}}
}}
diff --git a/csaxs_bec/bec_ipython_client/plugins/flomni/flomni.py b/csaxs_bec/bec_ipython_client/plugins/flomni/flomni.py
index 60205aed..5d83d2e7 100644
--- a/csaxs_bec/bec_ipython_client/plugins/flomni/flomni.py
+++ b/csaxs_bec/bec_ipython_client/plugins/flomni/flomni.py
@@ -1784,6 +1784,9 @@ class Flomni(
cSAXSBeamlineChecks,
flomniGuiTools,
):
+ _TOMO_PARAMS_WINDOW_NAME = "flomni_tomo_params"
+ _TOMO_PARAMS_ERROR = FlomniError
+
# Backed by a BEC global var (Redis) so the pre-open slit position
# survives a kernel restart while the eye is still in.
_sl1xs_before_eye = _GlobalVarParam(None)
@@ -2597,18 +2600,26 @@ class Flomni(
if not self.special_angles:
self._current_special_angles = []
- if self._current_special_angles:
- next_special_angle = self._current_special_angles[0]
- if np.isclose(angle, next_special_angle, atol=0.5):
- self._current_special_angles.pop(0)
- num_repeats = self.special_angle_repeats
- else:
- num_repeats = 1
+ # num_repeats is always defined (it used to be unbound whenever
+ # special_angles was set but this angle wasn't near the next one
+ # -> UnboundLocalError, retried 10x by @scan_repeat) and the
+ # special-angle list is consumed only after the projection
+ # succeeded, so a retried attempt still sees the same special
+ # angle and repeat count.
+ num_repeats = 1
+ is_special_angle = bool(
+ self._current_special_angles
+ and np.isclose(angle, self._current_special_angles[0], atol=0.5)
+ )
+ if is_special_angle:
+ num_repeats = self.special_angle_repeats
start_scan_number = bec.queue.next_scan_number
projection_start = time.perf_counter()
for i in range(num_repeats):
self._at_each_angle(angle)
projection_duration = time.perf_counter() - projection_start
+ if is_special_angle:
+ self._current_special_angles.pop(0)
end_scan_number = bec.queue.next_scan_number
for scan_nr in range(start_scan_number, end_scan_number):
@@ -3757,8 +3768,9 @@ class Flomni(
return FlomniFermatScan.MIN_POSITIONS
- def tomo_parameters(self):
- """print and update the tomo parameters"""
+ def tomo_parameters_cli(self):
+ """print and update the tomo parameters on the command line.
+ tomo_parameters() opens the GUI version."""
print("Current settings:")
print(f"Counting time per frame
line2"
+ assert scilog.sink["entry"]["tags"] == ["tomoscan", "BEC"]
+ assert tags == ["tomoscan"], "the caller's list must not be mutated"
+
+
+def test_write_to_scilog_disabled_is_a_noop(monkeypatch):
+ lamni = make_scilog_lamni(monkeypatch, FakeSciLog(enabled=False))
+ assert lamni.write_to_scilog("x", ["t"]) is False
+
+
+def test_write_to_scilog_never_raises(monkeypatch):
+ class Exploding(FakeSciLog):
+ def new(self):
+ raise RuntimeError("scilog unreachable")
+
+ lamni = make_scilog_lamni(monkeypatch, Exploding())
+ assert lamni.write_to_scilog("x", ["t"]) is False
+
+
+def test_write_to_scilog_without_messaging_service(monkeypatch):
+ obj = object.__new__(LamNI)
+ obj.client = FakeClient()
+ monkeypatch.setitem(builtins.__dict__, "bec", types.SimpleNamespace())
+ assert obj.write_to_scilog("x", ["t"]) is False
+
+
+# ── tomo_scan_projection adds the projection to the reconstruction queue ────
+#
+# Like flomni, reconstruction is done by tomo_scan_projection() itself, so
+# custom at_each_angle hooks (which call tomo_scan_projection(_internal=True))
+# and direct calls are reconstructed too. It used to live in _at_each_angle(),
+# so hooks silently produced no reconstruction entries.
+
+
+def make_lamni_for_projection(fake_bec):
+ obj = object.__new__(LamNI)
+ obj.client = FakeClient()
+ obj._progress_proxy = _ProgressProxy(obj.client)
+ obj.compute_additional_correction = lambda angle: (0, 0)
+ obj.compute_additional_correction_2 = lambda angle: (0, 0)
+ obj.lamni_compute_additional_correction_xeye_mu = lambda angle, verbose=True: (0, 0)
+ obj.reconstruct_calls = []
+ obj.tomo_reconstruct = lambda: obj.reconstruct_calls.append(1)
+ obj.fermat_calls = []
+ fake_scans = types.SimpleNamespace(
+ lamni_fermat_scan=lambda **kw: obj.fermat_calls.append(kw)
+ )
+ return obj, fake_scans
+
+
+@pytest.fixture
+def projection_env(monkeypatch, fake_bec):
+ obj, fake_scans = make_lamni_for_projection(fake_bec)
+ monkeypatch.setitem(builtins.__dict__, "scans", fake_scans)
+ return obj
+
+
+def test_tomo_scan_projection_reconstructs_exactly_once(projection_env):
+ projection_env.tomo_scan_projection(30.0, _internal=True)
+
+ assert len(projection_env.fermat_calls) == 1
+ assert projection_env.reconstruct_calls == [1]
+
+
+def test_tomo_scan_projection_reconstructs_once_per_projection_not_per_tile(projection_env):
+ """With stitching several Fermat scans make up one projection; the
+ reconstruction entry is written once, after all tiles."""
+ projection_env.lamni_stitch_x = 1 # 3 x 1 tiles
+ projection_env.tomo_scan_projection(30.0, _internal=True)
+
+ assert len(projection_env.fermat_calls) == 3
+ assert projection_env.reconstruct_calls == [1]
+
+
+def test_tomo_scan_projection_can_skip_reconstruction(projection_env):
+ projection_env.tomo_scan_projection(30.0, _internal=True, _reconstruct=False)
+
+ assert len(projection_env.fermat_calls) == 1
+ assert projection_env.reconstruct_calls == []
+
+
+def test_custom_hook_using_tomo_scan_projection_gets_reconstructed(projection_env):
+ """The documented hook pattern (tomo_queue_mixin's example) is just
+ setup.tomo_scan_projection(angle, _internal=True)."""
+
+ def hook(setup, angle):
+ setup.tomo_scan_projection(angle, _internal=True)
+
+ projection_env.at_each_angle_hook = "my_hook"
+ projection_env._resolve_at_each_angle_hook = lambda name, err: hook
+
+ projection_env._at_each_angle(45.0)
+
+ assert projection_env.reconstruct_calls == [1]
+
+
+def test_default_at_each_angle_reconstructs_only_once(projection_env):
+ projection_env.at_each_angle_hook = None
+
+ projection_env._at_each_angle(45.0)
+
+ assert projection_env.reconstruct_calls == [1], "must not be reconstructed twice"
+
+
+# ── tomo_type 3: sub-tomogram boundaries must be exact ──────────────────────
+
+
+@pytest.mark.parametrize("n_per_subtomo", range(1, 401))
+def test_type3_subtomo_numbering_is_exact(n_per_subtomo):
+ """subtomo_number was int((ii * step) / 360) + 1, which truncates one
+ below the integer for ii == k * n at ~35 values of n < 400 (e.g. 19, 33,
+ 38, 39, 66): the first projection of a sub-tomogram got the previous
+ sub-tomogram's number and a duplicate of its closing angle."""
+ lamni = object.__new__(LamNI)
+ for ii in range(0, 6 * n_per_subtomo + 1):
+ angle, subtomo = lamni._golden_equally_spaced(ii, n_per_subtomo, maxangle=360, reverse=True)
+ assert subtomo == ii // n_per_subtomo + 1, (n_per_subtomo, ii)
+ assert 0 <= angle < 720
+
+
+@pytest.mark.parametrize("n_per_subtomo", [19, 33, 38, 39, 66, 76, 78, 103, 161])
+def test_type3_each_subtomo_has_n_distinct_angles(n_per_subtomo):
+ lamni = object.__new__(LamNI)
+ for subtomo in range(1, 5):
+ angles = [
+ lamni._golden_equally_spaced(
+ (subtomo - 1) * n_per_subtomo + p, n_per_subtomo, maxangle=360, reverse=True
+ )[0]
+ % 360
+ for p in range(n_per_subtomo)
+ ]
+ assert len({round(a, 6) for a in angles}) == n_per_subtomo, (n_per_subtomo, subtomo)
+
+
+# ── xrayeye_update_frame warns when the beamline states are not valid ───────
+
+
+class _FakeStates:
+ def __init__(self, statuses):
+ self._states = dict(statuses)
+
+ def get_status_by_name(self, name):
+ status = self._states[name]
+ if isinstance(status, Exception):
+ raise status
+ return status
+
+
+def _update_frame_lamni(monkeypatch, states, answer_yes):
+ obj = object.__new__(LamNI)
+ obj.client = FakeClient()
+ fake_bec = (
+ types.SimpleNamespace(beamline_states=states)
+ if states is not None
+ else types.SimpleNamespace()
+ )
+ monkeypatch.setitem(builtins.__dict__, "bec", fake_bec)
+ asked = []
+ obj.OMNYTools = types.SimpleNamespace(
+ yesno=lambda question, default: asked.append((question, default)) or answer_yes
+ )
+ frames = []
+
+ class FakeAligner:
+ def __init__(self, client, lamni):
+ pass
+
+ def update_frame(self, keep_shutter_open=False):
+ frames.append(keep_shutter_open)
+
+ monkeypatch.setattr(lamni_module, "XrayEyeAlignGUI", FakeAligner)
+ return obj, frames, asked
+
+
+def test_update_frame_takes_a_frame_when_all_states_are_valid(monkeypatch):
+ lamni, frames, asked = _update_frame_lamni(
+ monkeypatch, _FakeStates({"beam": "valid", "shutter": "valid"}), answer_yes=False
+ )
+
+ lamni.xrayeye_update_frame(keep_shutter_open=True)
+
+ assert frames == [True]
+ assert asked == []
+
+
+def test_update_frame_warns_and_stops_when_a_state_is_invalid(monkeypatch, capsys):
+ lamni, frames, asked = _update_frame_lamni(
+ monkeypatch, _FakeStates({"beam": "invalid", "shutter": "valid"}), answer_yes=False
+ )
+
+ lamni.xrayeye_update_frame()
+
+ assert frames == []
+ assert asked == [("Take a frame anyway?", "n")]
+ out = capsys.readouterr().out
+ assert "beam: invalid" in out
+ assert "shutter" not in out.split("Attention")[1]
+
+
+def test_update_frame_proceeds_if_the_user_insists(monkeypatch):
+ lamni, frames, _ = _update_frame_lamni(
+ monkeypatch, _FakeStates({"beam": "warning"}), answer_yes=True
+ )
+
+ lamni.xrayeye_update_frame()
+
+ assert frames == [False]
+
+
+def test_update_frame_never_blocks_without_beamline_states(monkeypatch):
+ lamni, frames, asked = _update_frame_lamni(monkeypatch, None, answer_yes=False)
+
+ lamni.xrayeye_update_frame()
+
+ assert frames == [False]
+ assert asked == []
+
+
+def test_update_frame_ignores_states_that_cannot_be_read(monkeypatch):
+ lamni, frames, _ = _update_frame_lamni(
+ monkeypatch, _FakeStates({"flaky": RuntimeError("unreadable"), "beam": "valid"}), True
+ )
+
+ lamni.xrayeye_update_frame()
+
+ assert frames == [False]
diff --git a/tests/tests_bec_ipython_client/test_lamni_osa_collision_info.py b/tests/tests_bec_ipython_client/test_lamni_osa_collision_info.py
index 1a441213..88afbc8d 100644
--- a/tests/tests_bec_ipython_client/test_lamni_osa_collision_info.py
+++ b/tests/tests_bec_ipython_client/test_lamni_osa_collision_info.py
@@ -144,3 +144,37 @@ def test_lfzp_info_notes_parked_out(fake_dev, capsys):
out = capsys.readouterr().out
assert "likely parked OUT" in out
assert "Remaining space if OSA is moved to its IN position" in out
+
+
+class FakeCcmEnergy:
+ """ccm_energy is a PSISimplePositioner: read(cached=True) -> {name: {"value": ...}}."""
+
+ name = "ccm_energy"
+
+ def read(self, cached=False):
+ return {"ccm_energy": {"value": 6.2}}
+
+
+def test_lfzp_info_reads_the_energy_from_ccm_energy(fake_dev, capsys):
+ """It used to read dev.mokev, which only exists in device_configs/legacy/,
+ so lfzp_info() without an argument always bailed out."""
+ dev = fake_dev(collision_offset=113.0)
+ del dev.mokev # not in the current configs
+ dev.ccm_energy = FakeCcmEnergy()
+
+ make_optics().lfzp_info()
+
+ out = capsys.readouterr().out
+ assert "6.2000 keV" in out
+ assert "Could not read" not in out
+
+
+def test_lfzp_info_without_energy_device_explains_and_returns(fake_dev, capsys):
+ dev = fake_dev(collision_offset=113.0)
+ del dev.mokev
+
+ make_optics().lfzp_info() # no ccm_energy either: must not raise
+
+ out = capsys.readouterr().out
+ assert "ccm_energy" in out
+ assert "keV" in out # tells the user to pass the energy explicitly
diff --git a/tests/tests_bec_ipython_client/test_lamni_pdf_report.py b/tests/tests_bec_ipython_client/test_lamni_pdf_report.py
new file mode 100644
index 00000000..f790a818
--- /dev/null
+++ b/tests/tests_bec_ipython_client/test_lamni_pdf_report.py
@@ -0,0 +1,172 @@
+"""Tests for LamNI.write_pdf_report()'s report content.
+
+It always used the tomo_type-1 grid (int(360/tomo_angle_stepsize) * 8), so a
+golden-ratio tomogram (tomo_type 2/3) reported a stale type-1 projection count
+left over in the persistent tomo_angle_stepsize global var, and a hardcoded
+"8 sub-tomograms" -- fixed like flomni's 5a22651. It also read the
+e-account from client.username (flomni: bec.active_account, c1ad2fc), and a
+missing detector_distance userParameter crashed the report after the
+tomogram had already been registered.
+
+Drives the real method with a fake PDFWriter that captures the report text.
+"""
+
+import builtins
+import types
+
+import pytest
+
+import csaxs_bec.bec_ipython_client.plugins.LamNI.lamni as lamni_module
+from csaxs_bec.bec_ipython_client.plugins.LamNI.lamni import LamNI, _ProgressProxy
+
+
+class FakeClient:
+ def __init__(self):
+ self._vars = {}
+ self.queue = types.SimpleNamespace(next_dataset_number=7, next_scan_number=1000)
+ self.username = "unix_user"
+
+ def get_global_var(self, key):
+ return self._vars.get(key)
+
+ def set_global_var(self, key, value):
+ self._vars[key] = value
+
+
+class FakePDFWriter:
+ written: list[str] = []
+
+ def __init__(self, path):
+ self._pdf = types.SimpleNamespace(image=lambda *a, **k: None, ln=lambda *a, **k: None)
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ def write(self, text):
+ FakePDFWriter.written.append(text)
+
+
+@pytest.fixture
+def report_lamni(monkeypatch, tmp_path):
+ FakePDFWriter.written = []
+ monkeypatch.setattr(lamni_module, "PDFWriter", FakePDFWriter)
+ monkeypatch.setattr(
+ "os.path.expanduser",
+ lambda p: p.replace("~", str(tmp_path)) if p.startswith("~") else p,
+ )
+ monkeypatch.setitem(
+ builtins.__dict__,
+ "bec",
+ types.SimpleNamespace(active_account="e12345", messaging=types.SimpleNamespace()),
+ )
+ monkeypatch.setitem(builtins.__dict__, "dev", types.SimpleNamespace())
+
+ obj = object.__new__(LamNI)
+ obj.client = FakeClient()
+ obj._progress_proxy = _ProgressProxy(obj.client)
+ obj.tomo_id = 42
+ obj.sample_name = "sample1"
+ obj._add_psi_footer = lambda file: None
+ obj._upload_pdf_report_to_samples = lambda path: None
+ obj._describe_active_hook = lambda: ""
+ obj._active_hook_source = lambda: None
+ obj._get_user_param_safe = lambda device, var: {"detector_distance": 1500.0}.get(var, "x")
+ return obj
+
+
+def _report(lamni) -> str:
+ lamni.write_pdf_report()
+ assert FakePDFWriter.written, "no report was written"
+ return FakePDFWriter.written[0]
+
+
+def _line(report: str, label: str) -> str:
+ for line in report.splitlines():
+ if line.startswith(label):
+ return line[len(label) :].strip()
+ raise AssertionError(f"{label!r} not in report:\n{report}")
+
+
+def test_type1_report_uses_the_grid(report_lamni):
+ report_lamni.tomo_type = 1
+ report_lamni.tomo_angle_stepsize = 10.0
+
+ report = _report(report_lamni)
+
+ assert _line(report, "Number of projections:") == "288"
+ assert _line(report, "Number of individual sub-tomograms:") == "8"
+ assert _line(report, "Angular step within sub-tomogram:") == "10.00"
+ assert _line(report, "Last scan number approx.:") == "1298" # 1000 + 288 + 10
+
+
+def test_type1_report_shows_the_achievable_step_not_the_configured_one(report_lamni):
+ """7 deg does not divide 360: N = 51, achievable step 360/51 = 7.06."""
+ report_lamni.tomo_type = 1
+ report_lamni.tomo_angle_stepsize = 7.0
+
+ report = _report(report_lamni)
+
+ assert _line(report, "Number of projections:") == str(51 * 8)
+ assert _line(report, "Angular step within sub-tomogram:") == "7.06"
+
+
+def test_golden_ratio_report_does_not_use_the_stale_type1_grid(report_lamni):
+ report_lamni.tomo_type = 2
+ report_lamni.tomo_angle_stepsize = 10.0 # stale type-1 leftover: would give 288
+ report_lamni.golden_max_number_of_projections = 500
+ report_lamni.golden_ratio_bunch_size = 30
+
+ report = _report(report_lamni)
+
+ assert _line(report, "Number of projections:") == "500"
+ assert _line(report, "Sorted in bunches of:") == "30"
+ assert _line(report, "Angular step within sub-tomogram:") == "N/A (golden ratio)"
+ assert "Number of individual sub-tomograms" not in report
+ assert _line(report, "Last scan number approx.:") == "1510"
+
+
+def test_golden_ratio_endless_scan_reports_manual_stop(report_lamni):
+ report_lamni.tomo_type = 2
+ report_lamni.golden_max_number_of_projections = 0
+ report_lamni.golden_ratio_bunch_size = 20
+
+ report = _report(report_lamni)
+
+ assert _line(report, "Number of projections:") == "N/A (manual stop)"
+ assert _line(report, "Last scan number approx.:") == "N/A"
+
+
+def test_type3_report_uses_projections_per_full_circle_subtomo(report_lamni):
+ report_lamni.tomo_type = 3
+ report_lamni.tomo_angle_stepsize = 10.0
+ report_lamni.golden_max_number_of_projections = 400
+
+ report = _report(report_lamni)
+
+ assert _line(report, "Number of projections:") == "400"
+ # lamni sub-tomograms span 360 degrees (flomni: 180)
+ assert _line(report, "Number of projections per sub-tomogram:") == "36.0"
+ assert _line(report, "Angular step within sub-tomogram:") == "10.00"
+
+
+def test_report_uses_the_active_account(report_lamni):
+ report_lamni.tomo_type = 1
+ report = _report(report_lamni)
+ assert _line(report, "e-account:") == "e12345"
+
+
+def test_report_survives_a_missing_detector_distance(report_lamni):
+ def _get(device, var):
+ if var == "detector_distance":
+ raise ValueError("no user parameter definition")
+ return "x"
+
+ report_lamni._get_user_param_safe = _get
+ report_lamni.tomo_type = 1
+
+ report = _report(report_lamni)
+
+ assert _line(report, "Sample-to-detector distance:") == "N/A mm"
diff --git a/tests/tests_bec_ipython_client/test_lamni_tomo_alignment_scan.py b/tests/tests_bec_ipython_client/test_lamni_tomo_alignment_scan.py
index 4b6fa550..a3d45ab8 100644
--- a/tests/tests_bec_ipython_client/test_lamni_tomo_alignment_scan.py
+++ b/tests/tests_bec_ipython_client/test_lamni_tomo_alignment_scan.py
@@ -85,7 +85,7 @@ def test_tomo_alignment_scan_aborts_without_xray_eye_fit(monkeypatch):
lamni = make_lamni(monkeypatch, xray_eye_fit=None)
lamni._confirm_sequence_override = lambda *a, **k: False
calls = []
- lamni.tomo_scan_projection = lambda angle: calls.append(angle)
+ lamni.tomo_scan_projection = lambda angle, **kw: calls.append(angle)
lamni.tomo_alignment_scan()
@@ -97,7 +97,7 @@ def test_tomo_alignment_scan_runs_12_projections_across_360(monkeypatch):
lamni = make_lamni(monkeypatch, xray_eye_fit=[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
calls = []
- def _fake_projection(angle, _internal=False):
+ def _fake_projection(angle, _internal=False, **kw):
calls.append(angle)
builtins.__dict__["bec"].queue.next_scan_number += 1
@@ -115,7 +115,7 @@ def test_tomo_alignment_scan_runs_12_projections_across_360(monkeypatch):
def test_tomo_alignment_scan_rotates_back_to_zero(monkeypatch):
lamni = make_lamni(monkeypatch, xray_eye_fit=[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
- lamni.tomo_scan_projection = lambda angle, _internal=False: None
+ lamni.tomo_scan_projection = lambda angle, _internal=False, **kw: None
umv_calls = []
monkeypatch.setattr(lamni_module, "umv", lambda *a: umv_calls.append(a), raising=False)
@@ -142,3 +142,64 @@ def test_write_alignment_scan_numbers_format(tmp_path, monkeypatch):
assert angles == list(np.linspace(0, 360, num=12, endpoint=False))
assert len(lines[2].split()) == 12
assert len(lines[3].split()) == 12
+
+
+def _timeout_alarm():
+ from bec_lib.alarm_handler import AlarmBase
+
+ alarm = AlarmBase.__new__(AlarmBase)
+ alarm.alarm_type = "TimeoutError"
+ return alarm
+
+
+def test_tomo_alignment_scan_retries_timed_out_angle_and_records_real_scan_numbers(
+ tmp_path, monkeypatch
+):
+ """A TimeoutError alarm used to be swallowed: the angle was silently lost
+ while the failed attempt's scan numbers were logged as if it succeeded, and
+ the pre-written scan-number file (first_scan + k per angle) went stale."""
+ lamni = make_lamni(monkeypatch, xray_eye_fit=[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
+ monkeypatch.setattr(
+ "os.path.expanduser",
+ lambda p: p.replace("~", str(tmp_path)) if p.startswith("~") else p,
+ )
+ monkeypatch.setattr(lamni_module.time, "sleep", lambda s: None)
+ calls = []
+
+ def _projection(angle, _internal=False, **kw):
+ calls.append(angle)
+ builtins.__dict__["bec"].queue.next_scan_number += 1 # each attempt uses a scan number
+ if len(calls) == 3: # 3rd call = first attempt at the 3rd angle
+ raise _timeout_alarm()
+
+ lamni.tomo_scan_projection = _projection
+
+ lamni.tomo_alignment_scan()
+
+ expected_angles = list(np.linspace(0, 360, num=12, endpoint=False))
+ assert len(calls) == 13, "the timed-out angle must be re-acquired"
+ assert calls[2] == calls[3] == expected_angles[2]
+
+ log_file = tmp_path / "data/raw/logs/ptychotomoalign_scannum.txt"
+ lines = log_file.read_text().splitlines()
+ scans = [int(s) for s in lines[0].split()]
+ # scans 100, 101 = angles 0, 1; 102 = the failed attempt at angle 2 (must be
+ # skipped); 103.. = the retry and the remaining angles
+ assert scans == [100, 101] + list(range(103, 113))
+ assert [float(a) for a in lines[1].split()] == expected_angles
+ content, _tags = lamni._scilog_calls[0]
+ assert "Number of alignment scans: 12" in content
+
+
+def test_tomo_alignment_scan_projections_are_not_queued_for_reconstruction(monkeypatch):
+ """Alignment projections were never added to the reconstruction queue on
+ lamni; moving tomo_reconstruct() into tomo_scan_projection() must not
+ change that."""
+ lamni = make_lamni(monkeypatch, xray_eye_fit=[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
+ kwargs_seen = []
+ lamni.tomo_scan_projection = lambda angle, **kw: kwargs_seen.append(kw)
+
+ lamni.tomo_alignment_scan()
+
+ assert len(kwargs_seen) == 12
+ assert all(kw.get("_reconstruct") is False for kw in kwargs_seen)
diff --git a/tests/tests_bec_ipython_client/test_lamni_tomo_angles.py b/tests/tests_bec_ipython_client/test_lamni_tomo_angles.py
index 36e9e220..5363044b 100644
--- a/tests/tests_bec_ipython_client/test_lamni_tomo_angles.py
+++ b/tests/tests_bec_ipython_client/test_lamni_tomo_angles.py
@@ -129,6 +129,112 @@ def test_all_eight_subtomos_are_equally_spaced_when_combined(stepsize):
_assert_equally_spaced(combined, "full (all 8)")
+# ── progress reset at the start of a new scan ───────────────────────────────
+#
+# A finished scan leaves projection == total (100 %), its last subtomo and
+# angle in tomo_progress. The new scan's first _print_progress() (from the
+# 0-degree reference shot) used to render those stale values in the progress
+# GUI, because only the timing/ETA fields were reset.
+
+
+def test_new_scan_resets_stale_progress_before_first_projection(monkeypatch):
+ lamni = make_lamni_for_tomo_scan(monkeypatch, 10.0, active_account="")
+ lamni.progress.update(
+ {
+ "tomo_type": "Golden ratio tomography",
+ "subtomo": 8,
+ "subtomo_projection": 36,
+ "subtomo_total_projections": 36,
+ "projection": 288,
+ "total_projections": 288,
+ "angle": 355.0,
+ "estimated_remaining_time": 0.0,
+ "estimated_finish_time": "2020-01-01T00:00:00",
+ "accumulated_idle_time": 99.0,
+ "heartbeat": "2020-01-01T00:00:00",
+ }
+ )
+ lamni.add_sample_database = lambda *a, **k: 0
+ seen = []
+ lamni._tomo_scan_at_angle = lambda angle, subtomo_number: seen.append(
+ (angle, subtomo_number, dict(lamni.progress.as_dict()))
+ )
+
+ lamni.tomo_scan()
+
+ angle, subtomo_number, prog = seen[0]
+ assert (angle, subtomo_number) == (0, 1)
+ assert prog["tomo_type"] == "Equally spaced sub-tomograms"
+ assert prog["subtomo"] == 1
+ assert prog["projection"] == 0
+ assert prog["subtomo_projection"] == 0
+ assert prog["angle"] == 0
+ assert prog["total_projections"] == 36 * 8
+ assert prog["subtomo_total_projections"] == 36
+ assert prog["estimated_remaining_time"] is None
+ assert prog["estimated_finish_time"] is None
+ assert prog["accumulated_idle_time"] == 0.0
+ assert prog["heartbeat"] is None
+ assert prog["tomo_start_time"] is not None
+
+
+def test_resume_does_not_reset_progress(monkeypatch):
+ lamni = make_lamni_for_tomo_scan(monkeypatch, 10.0, active_account="")
+ resets = []
+ lamni._reset_progress_for_new_scan = lambda: resets.append(1)
+
+ lamni.tomo_scan(subtomo_start=2, start_angle=85.0)
+
+ assert resets == []
+
+
+# ── resuming mid-sub-tomogram (start_angle) ─────────────────────────────────
+#
+# start_angle used to be treated as the ORIGIN of a fresh 360-degree sweep,
+# so resuming e.g. subtomo 2 at 85 deg generated 435..85 (flipped): the >360
+# artifacts were silently skipped, the resume started at 355 deg instead of
+# 85, re-measured done angles and never reached the remaining ones.
+
+
+def _resume(stepsize: float, subtomo_number: int, start_angle: float):
+ lamni = make_lamni(stepsize)
+ recorded = []
+
+ def _record(angle, subtomo):
+ recorded.append((float(angle), int(lamni.progress["subtomo_projection"])))
+
+ lamni._tomo_scan_at_angle = _record
+ lamni.sub_tomo_scan(subtomo_number, start_angle=start_angle)
+ return recorded
+
+
+@pytest.mark.parametrize("stepsize", STEPSIZES)
+@pytest.mark.parametrize("subtomo_number", range(1, 9))
+def test_resume_yields_tail_of_normal_sweep(stepsize, subtomo_number):
+ full = make_lamni(stepsize)
+ full_recorded = []
+ full._tomo_scan_at_angle = lambda angle, subtomo: full_recorded.append(float(angle))
+ full.sub_tomo_scan(subtomo_number)
+
+ for k, start in enumerate(full_recorded):
+ resumed = _resume(stepsize, subtomo_number, start)
+ assert [a for a, _ in resumed] == pytest.approx(full_recorded[k:])
+ assert [i for _, i in resumed] == list(range(k, len(full_recorded)))
+ assert all(0 <= a < 360.05 for a, _ in resumed)
+
+
+def test_resume_reported_case_subtomo2_at_85_deg():
+ resumed = _resume(10.0, 2, 85.0)
+ assert resumed[0] == (pytest.approx(85.0), 27)
+ assert resumed[-1][0] == pytest.approx(5.0)
+ assert len(resumed) == 36 - 27
+
+
+def test_resume_off_grid_start_angle_raises():
+ with pytest.raises(ValueError):
+ _resume(10.0, 2, 80.0)
+
+
# ── tomo_scan()'s new-scan account handling ─────────────────────────────────
#
# bec.active_account used to be passed through .decode() (as if it were
@@ -171,7 +277,10 @@ def make_lamni_for_tomo_scan(
obj._print_progress = lambda: None
obj._format_duration = lambda seconds: "0s"
obj.lamnigui_show_progress = lambda: None
+ obj._lamnigui_update_progress = lambda: None
obj.at_each_angle_hook = None
+ # the real __init__ sets up the hook registry _active_hook_source() reads
+ obj._active_hook_source = lambda: None
obj.OMNYTools = types.SimpleNamespace(printgreenbold=lambda msg: None)
# These tests exercise tomo_scan()'s account-handling/heartbeat/progress-GUI
# logic, not the fine-alignment confirmation gate or the measurement-
diff --git a/tests/tests_bec_ipython_client/test_lamni_tomo_params_widget_math.py b/tests/tests_bec_ipython_client/test_lamni_tomo_params_widget_math.py
index 7b7b06f4..909c3abc 100644
--- a/tests/tests_bec_ipython_client/test_lamni_tomo_params_widget_math.py
+++ b/tests/tests_bec_ipython_client/test_lamni_tomo_params_widget_math.py
@@ -249,3 +249,76 @@ def test_compute_fermat_positions_lamni_zero_step_is_safe():
)
assert count == 0
assert min_positions == LamniFermatScan.MIN_POSITIONS
+
+
+# ── golden bunch-size floor + manual-shift units ────────────────────────────
+#
+# lamni's golden_ratio_bunch_size setter/CLI reject < 20, but the shared GUI
+# spinbox allowed 1..100: a GUI-queued job with a smaller value made
+# tomo_queue_execute()'s setattr() raise ValueError and pause the queue.
+# The manual-shift fields were labelled um (+-1000) but lamni's manual shift is
+# mm end to end (added to the mm scan centre, applied to lsamx/lsamy in mm).
+
+
+def _bare_widget_for(setup: str):
+ from qtpy.QtWidgets import QApplication
+
+ from csaxs_bec.bec_widgets.widgets.tomo_params.tomo_params import OMNY_TomoParams
+
+ QApplication.instance() or QApplication([])
+ widget = OMNY_TomoParams.__new__(OMNY_TomoParams)
+ widget._profile = SETUP_PROFILES[setup]
+ widget._pw = {}
+ return widget
+
+
+def test_lamni_bunch_size_spinbox_floor_is_20():
+ widget = _bare_widget_for("lamni")
+ box = widget._build_type23_section() # keep a reference: it owns the spinboxes
+ assert box is not None
+ assert widget._pw["golden_ratio_bunch_size"].minimum() == 20
+ assert widget._pw["golden_ratio_bunch_size"].maximum() == 100
+
+
+def test_flomni_bunch_size_spinbox_is_unchanged():
+ widget = _bare_widget_for("flomni")
+ box = widget._build_type23_section() # keep a reference: it owns the spinboxes
+ assert box is not None
+ assert widget._pw["golden_ratio_bunch_size"].minimum() == 1
+
+
+def test_lamni_gui_bunch_size_floor_matches_the_setter():
+ """Every value the GUI can produce must be accepted by lamni's setter."""
+
+ class FakeClient:
+ def __init__(self):
+ self._vars = {}
+
+ def get_global_var(self, key):
+ return self._vars.get(key)
+
+ def set_global_var(self, key, value):
+ self._vars[key] = value
+
+ lamni = object.__new__(LamNI)
+ lamni.client = FakeClient()
+ floor = SETUP_PROFILES["lamni"]["golden_bunch_size_min"]
+
+ lamni.golden_ratio_bunch_size = floor # must not raise
+ with pytest.raises(ValueError):
+ lamni.golden_ratio_bunch_size = floor - 1
+
+
+def test_lamni_manual_shift_fields_are_in_mm():
+ fields = SETUP_PROFILES["lamni"]["manual_shift_fields"]
+ assert [f[0] for f in fields] == ["manual_shift_x", "manual_shift_y"]
+ for _key, label, min_, max_, _decimals in fields:
+ assert "(mm)" in label and "µm" not in label
+ assert (min_, max_) == (-1.0, 1.0)
+
+
+def test_flomni_manual_shift_field_is_still_um():
+ """flomni's own field really is um -- must not be touched."""
+ (_key, label, min_, max_, _dec), = SETUP_PROFILES["flomni"]["manual_shift_fields"]
+ assert "µm" in label
+ assert (min_, max_) == (-50.0, 50.0)
diff --git a/tests/tests_bec_ipython_client/test_lamni_tomo_queue.py b/tests/tests_bec_ipython_client/test_lamni_tomo_queue.py
index a35f12e3..0397b2d8 100644
--- a/tests/tests_bec_ipython_client/test_lamni_tomo_queue.py
+++ b/tests/tests_bec_ipython_client/test_lamni_tomo_queue.py
@@ -166,17 +166,19 @@ def test_tomo_queue_execute_resumes_incomplete_job():
def test_tomo_queue_add_command_move_action(monkeypatch):
lamni = make_lamni()
- fake_dev = {"mokev": "mokev-device"}
+ # lamni's energy device is ccm_energy (the legacy "mokev" is not in the
+ # current configs)
+ fake_dev = {"ccm_energy": "ccm_energy-device"}
moved = []
monkeypatch.setattr(tomo_queue_mixin, "dev", fake_dev, raising=False)
monkeypatch.setattr(tomo_queue_mixin, "umv", lambda *a: moved.append(a), raising=False)
lamni.tomo_queue_add_command(
- {"action": "move", "kwargs": {"positions": {"mokev": 6.2}}}, label="reconfigure"
+ {"action": "move", "kwargs": {"positions": {"ccm_energy": 6.2}}}, label="reconfigure"
)
lamni.tomo_queue_execute()
- assert moved == [("mokev-device", 6.2)]
+ assert moved == [("ccm_energy-device", 6.2)]
job = lamni._tomo_queue_proxy.as_list()[0]
assert job["kind"] == "command"
assert job["status"] == "done"
@@ -204,16 +206,19 @@ def test_register_at_each_angle_hook_dispatches_from_at_each_angle():
def test_at_each_angle_default_path_unchanged_without_hook():
- """No hook registered -- must fall through to the exact same default
- behaviour lamni had before this port: tomo_scan_projection + tomo_reconstruct."""
+ """No hook registered -- falls through to tomo_scan_projection(), which
+ itself adds the projection to the reconstruction queue (like flomni), so
+ _at_each_angle() must NOT call tomo_reconstruct() a second time."""
lamni = make_lamni()
calls = []
- lamni.tomo_scan_projection = lambda angle, _internal=False: calls.append(("projection", angle))
+ lamni.tomo_scan_projection = lambda angle, _internal=False, **kw: calls.append(
+ ("projection", angle, _internal)
+ )
lamni.tomo_reconstruct = lambda: calls.append(("reconstruct",))
lamni._at_each_angle(30.0)
- assert calls == [("projection", 30.0), ("reconstruct",)]
+ assert calls == [("projection", 30.0, True)]
def test_at_each_angle_raises_for_unregistered_hook_name():
diff --git a/tests/tests_bec_ipython_client/test_lamni_tomo_reconstruct.py b/tests/tests_bec_ipython_client/test_lamni_tomo_reconstruct.py
new file mode 100644
index 00000000..163da14d
--- /dev/null
+++ b/tests/tests_bec_ipython_client/test_lamni_tomo_reconstruct.py
@@ -0,0 +1,56 @@
+"""tomo_reconstruct() must write the right scan list and queue folder, also when called
+directly (without tomo_scan_projection() having just set _current_scan_list)."""
+
+import builtins
+import types
+
+import pytest
+
+from csaxs_bec.bec_ipython_client.plugins.LamNI.lamni import LamNI
+
+
+class FakeReconstructor:
+ def __init__(self):
+ self.folder_name = "stale_folder"
+ self.calls = []
+
+ def write(self, **kwargs):
+ self.calls.append(dict(kwargs, folder_name=self.folder_name))
+
+
+class FakeClient:
+ def get_global_var(self, key):
+ return {"ptycho_reconstruct_foldername": "current_folder"}.get(key)
+
+
+@pytest.fixture
+def lamni(monkeypatch):
+ obj = object.__new__(LamNI)
+ obj.client = FakeClient()
+ obj.reconstructor = FakeReconstructor()
+ fake_bec = types.SimpleNamespace(queue=types.SimpleNamespace(next_scan_number=101))
+ monkeypatch.setitem(builtins.__dict__, "bec", fake_bec)
+ return obj
+
+
+def test_uses_cached_scan_list_when_current(lamni):
+ lamni._current_scan_list = [99, 100]
+ lamni.tomo_reconstruct()
+ assert lamni.reconstructor.calls[0]["scan_list"] == [99, 100]
+ assert lamni.reconstructor.calls[0]["next_scan_number"] == 101
+
+
+def test_falls_back_when_scan_list_stale(lamni):
+ lamni._current_scan_list = [40, 41]
+ lamni.tomo_reconstruct()
+ assert lamni.reconstructor.calls[0]["scan_list"] == [100]
+
+
+def test_falls_back_when_scan_list_missing(lamni):
+ lamni.tomo_reconstruct()
+ assert lamni.reconstructor.calls[0]["scan_list"] == [100]
+
+
+def test_folder_name_resynced_from_global_var(lamni):
+ lamni.tomo_reconstruct()
+ assert lamni.reconstructor.calls[0]["folder_name"] == "current_folder"
diff --git a/tests/tests_bec_ipython_client/test_tomo_parameters_gui.py b/tests/tests_bec_ipython_client/test_tomo_parameters_gui.py
new file mode 100644
index 00000000..18540b11
--- /dev/null
+++ b/tests/tests_bec_ipython_client/test_tomo_parameters_gui.py
@@ -0,0 +1,96 @@
+"""tomo_parameters() opens the OMNY_TomoParams widget in its own window (shared TomoQueueMixin
+implementation, used by LamNI and Flomni); tomo_parameters_cli() is the command line version."""
+
+import pytest
+
+import csaxs_bec.bec_ipython_client.plugins.OMNY_shared.tomo_queue_mixin as mixin_module
+from csaxs_bec.bec_ipython_client.plugins.flomni.flomni import Flomni, FlomniError
+from csaxs_bec.bec_ipython_client.plugins.LamNI.lamni import LamNI, LamNIError
+
+
+class FakeWindow:
+ def __init__(self):
+ self.new_calls = []
+
+ def new(self, widget, **kwargs):
+ self.new_calls.append((widget, kwargs))
+ self.tomo_params = object()
+
+
+class FakeGui:
+ def __init__(self, fail_new=False):
+ self.windows = {}
+ self.new_calls = []
+ self.fail_new = fail_new
+
+ def new(self, name, **kwargs):
+ if self.fail_new:
+ raise TimeoutError("GUI server did not answer")
+ self.new_calls.append((name, kwargs))
+ self.windows[name] = window = FakeWindow()
+ setattr(self, name, window)
+ return window
+
+
+class FakeClient:
+ def __init__(self, gui):
+ if gui is not None:
+ self.gui = gui
+
+
+@pytest.fixture(autouse=True)
+def no_sleep(monkeypatch):
+ monkeypatch.setattr(mixin_module.time, "sleep", lambda *_: None)
+
+
+def make(cls, gui):
+ obj = object.__new__(cls)
+ obj.client = FakeClient(gui)
+ return obj
+
+
+@pytest.mark.parametrize(
+ "cls, window_name, error",
+ [(LamNI, "lamni_tomo_params", LamNIError), (Flomni, "flomni_tomo_params", FlomniError)],
+)
+class TestTomoParametersWindow:
+ def test_opens_widget_in_own_window(self, cls, window_name, error):
+ gui = FakeGui()
+ make(cls, gui).tomo_parameters()
+ assert [name for name, _ in gui.new_calls] == [window_name]
+ widget, kwargs = gui.windows[window_name].new_calls[0]
+ assert widget == "OMNY_TomoParams"
+ assert kwargs["object_name"] == "tomo_params"
+
+ def test_second_call_does_not_open_another(self, cls, window_name, error, capsys):
+ gui = FakeGui()
+ obj = make(cls, gui)
+ obj.tomo_parameters()
+ obj.tomo_parameters()
+ assert len(gui.new_calls) == 1
+ assert len(gui.windows[window_name].new_calls) == 1
+ assert "already open" in capsys.readouterr().out
+
+ def test_window_without_widget_gets_the_widget(self, cls, window_name, error):
+ gui = FakeGui()
+ gui.new(window_name) # window exists, but holds no tomo_params widget
+ make(cls, gui).tomo_parameters()
+ assert len(gui.new_calls) == 1 # window reused, not created again
+ assert gui.windows[window_name].new_calls[0][0] == "OMNY_TomoParams"
+
+ def test_raises_without_gui_and_names_cli(self, cls, window_name, error):
+ with pytest.raises(error, match="tomo_parameters_cli"):
+ make(cls, None).tomo_parameters()
+
+ def test_raises_when_gui_fails_and_does_not_fall_back(self, cls, window_name, error):
+ obj = make(cls, FakeGui(fail_new=True))
+ obj.tomo_parameters_cli = lambda: pytest.fail("must not fall back to the CLI")
+ with pytest.raises(error, match="tomo_parameters_cli") as exc_info:
+ obj.tomo_parameters()
+ assert isinstance(exc_info.value.__cause__, TimeoutError)
+
+
+def test_cli_version_exists_and_gui_version_is_the_mixin_one():
+ for cls in (LamNI, Flomni):
+ assert "tomo_parameters_cli" in vars(cls)
+ assert "tomo_parameters" not in vars(cls)
diff --git a/tests/tests_bec_ipython_client/test_tomo_queue_reacquire.py b/tests/tests_bec_ipython_client/test_tomo_queue_reacquire.py
index 2d1bf83c..8d59dce1 100644
--- a/tests/tests_bec_ipython_client/test_tomo_queue_reacquire.py
+++ b/tests/tests_bec_ipython_client/test_tomo_queue_reacquire.py
@@ -191,7 +191,7 @@ def test_tomo_queue_reacquire_resets_later_jobs_to_pending_tomo_and_command():
i0 = lamni.tomo_queue_add(label="job0")
i1 = lamni.tomo_queue_add(label="job1")
- lamni.tomo_queue_add_command({"action": "move", "kwargs": {"positions": {"mokev": 6.2}}})
+ lamni.tomo_queue_add_command({"action": "move", "kwargs": {"positions": {"ccm_energy": 6.2}}})
i3 = lamni.tomo_queue_add(label="job3")
for i in (i0, i1, i3):
@@ -213,7 +213,7 @@ def test_tomo_queue_reacquire_rejects_out_of_range_job_index():
def test_tomo_queue_reacquire_rejects_command_job():
lamni = make_lamni()
- lamni.tomo_queue_add_command({"action": "move", "kwargs": {"positions": {"mokev": 6.2}}})
+ lamni.tomo_queue_add_command({"action": "move", "kwargs": {"positions": {"ccm_energy": 6.2}}})
with pytest.raises(TomoQueueError):
lamni.tomo_queue_reacquire(0, projection_number=0)
diff --git a/tests/tests_bec_ipython_client/test_webpage_projection_count.py b/tests/tests_bec_ipython_client/test_webpage_projection_count.py
new file mode 100644
index 00000000..c74dc307
--- /dev/null
+++ b/tests/tests_bec_ipython_client/test_webpage_projection_count.py
@@ -0,0 +1,108 @@
+"""The status webpage computes a job's total projection count in JS
+(calcProjections) from a per-setup TOMO_TYPES table.
+
+For lamni's equally-spaced tomo_type 1 it used to hardcode flomni's
+floor(180/step) * 8, so the page showed half of the real count (144 instead of
+288 at a 10 degree step): lamni sweeps the full 360 degrees in every
+sub-tomogram (N = int(360/step), see LamNI._tomo_type1_actual_grid()).
+
+There is no JS engine in the test environment, so this checks the data the JS
+consumes (the TOMO_TYPES JSON rendered into the page) and that the JS uses
+it, and cross-checks the formula against the real LamNI grid.
+"""
+
+import json
+import math
+import re
+
+import pytest
+
+from csaxs_bec.bec_ipython_client.plugins.flomni.flomni_webpage_generator import (
+ FlomniWebpageGenerator,
+)
+from csaxs_bec.bec_ipython_client.plugins.LamNI.lamni import LamNI, _ProgressProxy
+from csaxs_bec.bec_ipython_client.plugins.LamNI.LamNI_webpage_generator import (
+ LamniWebpageGenerator,
+)
+from csaxs_bec.bec_ipython_client.plugins.OMNY_shared.webpage_generator_base import _render_html
+
+
+class FakeClient:
+ """Minimal in-memory stand-in for BEC's global-var store."""
+
+ def __init__(self):
+ self._vars = {}
+
+ def get_global_var(self, key):
+ return self._vars.get(key)
+
+ def set_global_var(self, key, value):
+ self._vars[key] = value
+
+
+def _rendered_tomo_types(generator_cls) -> dict:
+ html = _render_html(
+ [], generator_cls.HAS_TOMO_QUEUE, generator_cls.TOMO_TYPES, generator_cls.TQ_PARAM_DISPLAY
+ )
+ match = re.search(r"const TOMO_TYPES = (\{.*?\});", html, re.S)
+ assert match, "TOMO_TYPES not found in the rendered page"
+ # JSON object keys are strings once serialized
+ return json.loads(match.group(1))
+
+
+def _js_expression_for_grid(generator_cls) -> str:
+ html = _render_html(
+ [], generator_cls.HAS_TOMO_QUEUE, generator_cls.TOMO_TYPES, generator_cls.TQ_PARAM_DISPLAY
+ )
+ match = re.search(r"const N=Math\.floor\((.*?)/step\);", html)
+ assert match, "grid projection formula not found in the rendered page"
+ return match.group(1)
+
+
+def test_page_js_uses_the_per_setup_base_angle():
+ assert _js_expression_for_grid(LamniWebpageGenerator) == "(def.base_angle||180)"
+
+
+def test_lamni_grid_type_declares_360_degree_sub_tomograms():
+ types = _rendered_tomo_types(LamniWebpageGenerator)
+ assert types["1"] == {"kind": "equally_spaced_grid", "n_subtomos": 8, "base_angle": 360}
+
+
+def test_flomni_grid_type_is_unchanged():
+ """flomni's page must keep computing floor(180/step) * 8."""
+ types = _rendered_tomo_types(FlomniWebpageGenerator)
+ assert types["1"] == {"kind": "equally_spaced_grid", "n_subtomos": 8}
+ assert "base_angle" not in types["1"]
+
+
+@pytest.mark.parametrize("stepsize", [10.0, 7.0, 25.0, 12.5, 5.0])
+def test_page_projection_count_matches_the_real_lamni_grid(stepsize):
+ grid = LamniWebpageGenerator.TOMO_TYPES[1]
+ page_total = math.floor(grid.get("base_angle", 180) / stepsize) * grid["n_subtomos"]
+
+ lamni = object.__new__(LamNI)
+ lamni.client = FakeClient()
+ lamni._progress_proxy = _ProgressProxy(lamni.client)
+ lamni.tomo_angle_stepsize = stepsize
+ _n, _step, real_total = lamni._tomo_type1_actual_grid()
+
+ assert page_total == real_total
+
+
+def test_lamni_10_degree_step_shows_288_not_144():
+ grid = LamniWebpageGenerator.TOMO_TYPES[1]
+ assert math.floor(grid["base_angle"] / 10.0) * grid["n_subtomos"] == 288
+
+
+def test_lamni_param_table_only_shows_real_lamni_parameters():
+ """Every row of the page's parameter table must be a parameter the
+ tomo queue actually stores for lamni (or the special hook row)."""
+ known = set(LamNI._TOMO_SCAN_PARAM_NAMES) | {"tomo_type"}
+ for key, _label in LamniWebpageGenerator.TQ_PARAM_DISPLAY:
+ assert key in known, f"{key!r} is not a lamni tomo-queue parameter"
+
+
+def test_lamni_param_table_shows_the_scan_fov_and_manual_shift():
+ keys = [key for key, _label in LamniWebpageGenerator.TQ_PARAM_DISPLAY]
+ for wanted in ("lamni_piezo_range_x", "lamni_piezo_range_y", "manual_shift_x", "manual_shift_y"):
+ assert wanted in keys
diff --git a/tests/tests_bec_ipython_client/test_x_ray_eye_align.py b/tests/tests_bec_ipython_client/test_x_ray_eye_align.py
index 9987ebe4..d8024347 100644
--- a/tests/tests_bec_ipython_client/test_x_ray_eye_align.py
+++ b/tests/tests_bec_ipython_client/test_x_ray_eye_align.py
@@ -586,4 +586,60 @@ def test_find_rotation_center_smear_experimental_saves_composites_and_clicks(bec
save_mock.assert_called_once()
_, kwargs = save_mock.call_args
assert kwargs["fzp_xy"] == (0.0, 0.0)
- assert kwargs["sweep_deg"] == 45.0
\ No newline at end of file
+ assert kwargs["sweep_deg"] == 45.0
+
+# ── align() must always leave the GUI clean ─────────────────────────────────
+#
+# Only KeyboardInterrupt (handled by the caller) used to reset the GUI; any
+# other exception (a GUI RPC error, a missing GUI output key, ...) left DAP
+# parameter forwarding on and the alignment crosshair drawn. Mirrors flomni's
+# XrayEyeAlign.align() try/finally.
+
+
+def _bare_aligner():
+ aligner = object.__new__(XrayEyeAlign)
+ # .gui is a read-only property returning self.lamni.xeyegui
+ aligner.lamni = mock.MagicMock()
+ return aligner
+
+
+def test_align_cleans_up_gui_after_success():
+ aligner = _bare_aligner()
+ aligner._align_impl = mock.MagicMock()
+
+ aligner.align(keep_shutter_open=True)
+
+ aligner._align_impl.assert_called_once_with(True)
+ aligner.lamni.xeyegui.set_dap_params_forwarding.assert_called_with(False)
+ aligner.lamni.xeyegui.hide_crosshair.assert_called_once()
+
+
+def test_align_cleans_up_gui_after_any_exception_and_reraises():
+ aligner = _bare_aligner()
+ aligner._align_impl = mock.MagicMock(side_effect=KeyError("gui output key missing"))
+
+ with pytest.raises(KeyError):
+ aligner.align()
+
+ aligner.lamni.xeyegui.set_dap_params_forwarding.assert_called_with(False)
+ aligner.lamni.xeyegui.hide_crosshair.assert_called_once()
+
+
+def test_align_cleanup_failures_do_not_mask_the_original_error():
+ aligner = _bare_aligner()
+ aligner._align_impl = mock.MagicMock(side_effect=ValueError("real problem"))
+ aligner.lamni.xeyegui.set_dap_params_forwarding.side_effect = RuntimeError("GUI gone")
+ aligner.lamni.xeyegui.hide_crosshair.side_effect = RuntimeError("GUI gone")
+
+ with pytest.raises(ValueError, match="real problem"):
+ aligner.align()
+
+
+def test_align_survives_a_gui_without_reset_zoom():
+ aligner = _bare_aligner()
+ aligner.lamni.xeyegui.reset_zoom.side_effect = AttributeError("no reset_zoom")
+ aligner._align_impl = mock.MagicMock()
+
+ aligner.align()
+
+ aligner._align_impl.assert_called_once_with(False)
diff --git a/tests/tests_devices/test_sim_lamni_feedback.py b/tests/tests_devices/test_sim_lamni_feedback.py
new file mode 100644
index 00000000..58222876
--- /dev/null
+++ b/tests/tests_devices/test_sim_lamni_feedback.py
@@ -0,0 +1,61 @@
+"""The simulated LamNI RT server must not run scans while the feedback loop is off."""
+
+import time
+
+import pytest
+
+from csaxs_bec.devices.sim.sim_lamni import SimRtLamniSocket, SimRtLamniState
+
+N_POSITIONS = 10
+
+
+@pytest.fixture
+def state():
+ state = SimRtLamniState()
+ state.point_dwell_s = 0.02
+ for ii in range(N_POSITIONS):
+ state.add_scan_position([float(ii), float(ii)])
+ yield state
+ state.clear_scan()
+
+
+def _wait_for_scan_end(state, timeout=5):
+ deadline = time.time() + timeout
+ while state.scan_mode != 0 and time.time() < deadline:
+ time.sleep(0.005)
+ assert state.scan_mode == 0
+
+
+def test_scan_not_started_without_feedback(state):
+ state.feedback_running = False
+ assert state.start_scan() == N_POSITIONS
+ assert state.scan_mode == 0
+ assert state.scan_current == 0
+ assert state._scan_thread is None
+
+
+def test_scan_runs_with_feedback(state):
+ state.feedback_running = True
+ state.start_scan()
+ _wait_for_scan_end(state)
+ assert state.scan_current == N_POSITIONS
+
+
+def test_scan_aborts_when_feedback_drops(state):
+ state.feedback_running = True
+ state.start_scan()
+ time.sleep(3.5 * state.point_dwell_s)
+ state.feedback_running = False
+ _wait_for_scan_end(state)
+ assert 0 < state.scan_current < N_POSITIONS
+
+
+def test_sd_command_reply_without_feedback(state):
+ socket = SimRtLamniSocket.__new__(SimRtLamniSocket)
+ socket.state = state
+ state.feedback_running = False
+ assert "not started" in socket.handle_command("sd")
+ assert state.scan_mode == 0
+ state.feedback_running = True
+ assert "Scan mode started" in socket.handle_command("sd")
+ _wait_for_scan_end(state)
diff --git a/tests/tests_scans/test_lamni_fermat_scan.py b/tests/tests_scans/test_lamni_fermat_scan.py
index d12595eb..f2da0c09 100644
--- a/tests/tests_scans/test_lamni_fermat_scan.py
+++ b/tests/tests_scans/test_lamni_fermat_scan.py
@@ -1,5 +1,7 @@
from unittest import mock
+import numpy as np
+
from csaxs_bec.scans.lamni_fermat_scan import LamniFermatScan
@@ -57,3 +59,39 @@ def test_lamni_fermat_spiral_reaches_elongated_fov_corners():
-fovx / 2, fovx / 2, -fovy / 2, fovy / 2, step=1, fovx=fovx, fovy=fovy
)
assert len(pos) >= 60
+
+
+def _spiral(**overrides):
+ kwargs = dict(
+ m1_start=-40.0,
+ m1_stop=40.0,
+ m2_start=-40.0,
+ m2_stop=40.0,
+ step=10.0,
+ angle=0.0,
+ fovx=80.0,
+ fovy=80.0,
+ seed=0,
+ )
+ kwargs.update(overrides)
+ return LamniFermatScan.get_lamni_fermat_spiral_pos(**kwargs)
+
+
+def test_shift_and_center_are_mm_and_positions_are_um():
+ """Unit contract of the LamNI scan: shift_x/shift_y (LamNI's manual shift)
+ and center_x/center_y (the FOV offsets) are in mm, the generated scan
+ positions handed to the RT controller are in um. A shift of 0.01 mm must
+ therefore move every position by exactly 10 um.
+
+ (The tomo-parameters GUI used to label the manual shift "um" with a
+ +-1000 range -- copied from flomni -- although it is mm end to end.)
+ """
+ base = _spiral()
+ shifted_x = _spiral(shift_x=0.01)
+ shifted_y = _spiral(shift_y=0.005)
+ centered_x = _spiral(center_x=0.01) # at angle 0, stitch 0: same physical shift
+
+ assert base.shape == shifted_x.shape == shifted_y.shape == centered_x.shape
+ np.testing.assert_allclose(shifted_x - base, [[10.0, 0.0]] * len(base), atol=1e-9)
+ np.testing.assert_allclose(shifted_y - base, [[0.0, 5.0]] * len(base), atol=1e-9)
+ np.testing.assert_allclose(centered_x - base, [[10.0, 0.0]] * len(base), atol=1e-9)