From 0717e1ebc359a8bf0c732969fb7e9ff6640d2672 Mon Sep 17 00:00:00 2001 From: Mirko Holler Date: Fri, 25 Sep 2026 14:42:56 +0200 Subject: [PATCH] feat(lamni,flomni): tomo_parameters() opens the GUI window, CLI is tomo_parameters_cli() - shared TomoQueueMixin.tomo_parameters() opens OMNY_TomoParams in its own window (lamni_tomo_params / flomni_tomo_params); repeat calls do not open a second one; a missing or failing GUI raises the setup's error and points to tomo_parameters_cli() instead of silently falling back - rename the prompt-based versions to tomo_parameters_cli() - docs: describe both, and use the CLI in the queue examples that rely on the command blocking until the values are entered - add tests with a fake GUI Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_016gUjUT2xCNpnBQkThn3CqP --- .../bec_ipython_client/plugins/LamNI/lamni.py | 8 +- .../plugins/OMNY_shared/tomo_queue_mixin.py | 43 +++++++++ .../plugins/flomni/flomni.py | 8 +- docs/user/ptychography/flomni.md | 12 ++- docs/user/ptychography/lamni.md | 12 ++- .../test_tomo_parameters_gui.py | 96 +++++++++++++++++++ 6 files changed, 165 insertions(+), 14 deletions(-) create mode 100644 tests/tests_bec_ipython_client/test_tomo_parameters_gui.py diff --git a/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni.py b/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni.py index edde4935..a1a090b7 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 @@ -2114,8 +2117,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 = {self.tomo_countingtime} s") print(f"Stepsize microns = {self.tomo_shellstep}") 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/flomni/flomni.py b/csaxs_bec/bec_ipython_client/plugins/flomni/flomni.py index b46837bf..a2ed2c7d 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) @@ -3757,8 +3760,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 = {self.tomo_countingtime} s") print(f"Stepsize microns = {self.tomo_shellstep}") diff --git a/docs/user/ptychography/flomni.md b/docs/user/ptychography/flomni.md index 65ebe493..0ae5a53f 100644 --- a/docs/user/ptychography/flomni.md +++ b/docs/user/ptychography/flomni.md @@ -76,7 +76,7 @@ _To bypass the fine alignment: `flomni.feye_out()`_ ### Tomographic Measurement Now that the sample is aligned, the tomographic measurement can be performed. -1. `flomni.tomo_parameters()` adjust the scan parameters for the tomographic scan. This includes the parameters for ptychographic scans of projections plus the strategy for angular sampling. The vertical shift adjusts the field of view, up (positive) or down (negative). After adjusting the numbers, type again `flomni.tomo_parameters()` and verify that they are correct. For the "8 sub-tomograms" mode, an optional 0-deg reference shot can be enabled at the start of every odd sub-tomogram and once more at the end, useful for tracking radiation damage over the course of a long measurement. +1. `flomni.tomo_parameters()` opens the tomo parameter window (GUI) to adjust the scan parameters for the tomographic scan (`flomni.tomo_parameters_cli()` is the command line version, which prompts for each value in the terminal). This includes the parameters for ptychographic scans of projections plus the strategy for angular sampling. The vertical shift adjusts the field of view, up (positive) or down (negative). After adjusting the numbers, type again `flomni.tomo_parameters()` and verify that they are correct. For the "8 sub-tomograms" mode, an optional 0-deg reference shot can be enabled at the start of every odd sub-tomogram and once more at the end, useful for tracking radiation damage over the course of a long measurement. 1. `flomni.tomo_scan_projection(angle)` perform a ptychographic scan at the rotation angle . Launch the tomographic measurement by `flomni.tomo_scan()`. During the scan a live progress report is printed, including an estimated time of completion. Unusually long gaps (e.g. a beamline interruption) are detected automatically and excluded from the estimate, and the total time lost to such gaps is reported once the scan finishes. 1. Before changing sample, verify that all subtomograms were completely acquired using the tomo_reconstruction matlab script. @@ -404,11 +404,13 @@ The queue is persisted (it survives a BEC client restart). Each job's status is If the process running the queue dies hard enough that it never gets to write a status update at all (a kernel restart, a Ctrl-C during a blocking prompt) a job can be left stuck showing `running` with nothing actually running. `flomni.tomo_queue_delete(index)` has no status guard and works on a stuck row regardless; you can also fix the status directly with `flomni._tomo_queue_proxy.update_by_id(job_id, status="incomplete")` (to make it resumable) or `status="done"` (to skip it). The GUI's Delete/Clear normally refuse to touch a `running` row, but detect a stale one (no recent scan heartbeat) and offer to proceed anyway with an explicit confirmation instead of blocking forever. +In the examples, `flomni.tomo_parameters_cli()` is used because it waits until the values are entered before the next command runs. With the GUI window, adjust the values there and add the job with its queue button, or with `flomni.tomo_queue_add()`. + Example: ``` -flomni.tomo_parameters() # set up parameter set #1 +flomni.tomo_parameters_cli() # set up parameter set #1 flomni.tomo_queue_add("fast overview") -flomni.tomo_parameters() # set up parameter set #2 +flomni.tomo_parameters_cli() # set up parameter set #2 flomni.tomo_queue_add("hires scan") flomni.tomo_queue_show() flomni.tomo_queue_execute() # runs both, in order, on this sample @@ -544,7 +546,7 @@ Example — queue a polarizer-modulated tomogram, then a normal one: ```python flomni.register_at_each_angle_hook("polarizer_mod", polarizer_modulation) -flomni.tomo_parameters() # set up the scan parameters as usual +flomni.tomo_parameters_cli() # set up the scan parameters as usual flomni.at_each_angle_hook = "polarizer_mod" # activate the hook flomni.tomo_queue_add("polarizer run") @@ -613,7 +615,7 @@ Load and use it: import my_hooks flomni.register_at_each_angle_hook("high_res_every_5th", my_hooks.high_res_every_5th) -flomni.tomo_parameters() # set up the scan parameters as usual +flomni.tomo_parameters_cli() # set up the scan parameters as usual flomni.at_each_angle_hook = "high_res_every_5th" # activate the hook flomni.tomo_queue_add("subtomo 2 high-res every 5th") diff --git a/docs/user/ptychography/lamni.md b/docs/user/ptychography/lamni.md index 4257352b..0c693c62 100644 --- a/docs/user/ptychography/lamni.md +++ b/docs/user/ptychography/lamni.md @@ -119,7 +119,7 @@ The alignment scan itself already uses the x-ray eye correction and any correcti Start the laminography scan by -1. `lamni.tomo_parameters()` adjust the parameters to the desired settings. +1. `lamni.tomo_parameters()` opens the tomo parameter window (GUI) to adjust the parameters to the desired settings. The command line version, which prompts for each value in the terminal, is `lamni.tomo_parameters_cli()`. 2. for test scans run `lamni.tomo_scan_projection(angle)` `lamni.tomo_reconstruct()` @@ -160,11 +160,13 @@ The queue is persisted (it survives a BEC client restart). Each job's status is If the process running the queue dies hard enough that it never gets to write a status update at all (a kernel restart, a Ctrl-C during a blocking prompt) a job can be left stuck showing `running` with nothing actually running. `lamni.tomo_queue_delete(index)` has no status guard and works on a stuck row regardless; you can also fix the status directly with `lamni._tomo_queue_proxy.update_by_id(job_id, status="incomplete")` (to make it resumable) or `status="done"` (to skip it). The GUI's Delete/Clear normally refuse to touch a `running` row, but detect a stale one (no recent scan heartbeat) and offer to proceed anyway with an explicit confirmation instead of blocking forever. +In the examples, `lamni.tomo_parameters_cli()` is used because it waits until the values are entered before the next command runs. With the GUI window, adjust the values there and add the job with its queue button, or with `lamni.tomo_queue_add()`. + Example: ``` -lamni.tomo_parameters() # set up parameter set #1 +lamni.tomo_parameters_cli() # set up parameter set #1 lamni.tomo_queue_add("fast overview") -lamni.tomo_parameters() # set up parameter set #2 +lamni.tomo_parameters_cli() # set up parameter set #2 lamni.tomo_queue_add("hires scan") lamni.tomo_queue_show() lamni.tomo_queue_execute() # runs both, in order, on this sample @@ -287,7 +289,7 @@ Example — queue a polarizer-modulated laminogram, then a normal one: ```python lamni.register_at_each_angle_hook("polarizer_mod", polarizer_modulation) -lamni.tomo_parameters() # set up the scan parameters as usual +lamni.tomo_parameters_cli() # set up the scan parameters as usual lamni.at_each_angle_hook = "polarizer_mod" # activate the hook lamni.tomo_queue_add("polarizer run") @@ -356,7 +358,7 @@ Load and use it: import my_hooks lamni.register_at_each_angle_hook("high_res_every_5th", my_hooks.high_res_every_5th) -lamni.tomo_parameters() # set up the scan parameters as usual +lamni.tomo_parameters_cli() # set up the scan parameters as usual lamni.at_each_angle_hook = "high_res_every_5th" # activate the hook lamni.tomo_queue_add("subtomo 2 high-res every 5th") 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)