From 81522d1ac562011eb84fc32e98d2b0ee48dbe122 Mon Sep 17 00:00:00 2001 From: x01da Date: Tue, 1 Sep 2026 07:57:07 +0200 Subject: [PATCH 01/56] wip scheduler --- debye_bec/bec_widgets/widgets/client.py | 101 +- .../bec_widgets/widgets/scheduler/__init__.py | 0 .../widgets/scheduler/endpoints.py | 61 ++ .../bec_widgets/widgets/scheduler/guard.py | 160 +++ .../widgets/scheduler/guard_dialog.py | 94 ++ .../widgets/scheduler/item_dialog.py | 238 +++++ .../widgets/scheduler/notification_dialog.py | 59 ++ .../widgets/scheduler/notifications.py | 94 ++ .../widgets/scheduler/register_scheduler.py | 15 + .../widgets/scheduler/scan_form.py | 16 + .../widgets/scheduler/schedule_item.py | 76 ++ .../widgets/scheduler/schedule_logic.py | 60 ++ .../widgets/scheduler/scheduler.py | 995 ++++++++++++++++++ .../widgets/scheduler/scheduler.pyproject | 1 + .../widgets/scheduler/scheduler_plugin.py | 57 + 15 files changed, 2026 insertions(+), 1 deletion(-) create mode 100644 debye_bec/bec_widgets/widgets/scheduler/__init__.py create mode 100644 debye_bec/bec_widgets/widgets/scheduler/endpoints.py create mode 100644 debye_bec/bec_widgets/widgets/scheduler/guard.py create mode 100644 debye_bec/bec_widgets/widgets/scheduler/guard_dialog.py create mode 100644 debye_bec/bec_widgets/widgets/scheduler/item_dialog.py create mode 100644 debye_bec/bec_widgets/widgets/scheduler/notification_dialog.py create mode 100644 debye_bec/bec_widgets/widgets/scheduler/notifications.py create mode 100644 debye_bec/bec_widgets/widgets/scheduler/register_scheduler.py create mode 100644 debye_bec/bec_widgets/widgets/scheduler/scan_form.py create mode 100644 debye_bec/bec_widgets/widgets/scheduler/schedule_item.py create mode 100644 debye_bec/bec_widgets/widgets/scheduler/schedule_logic.py create mode 100644 debye_bec/bec_widgets/widgets/scheduler/scheduler.py create mode 100644 debye_bec/bec_widgets/widgets/scheduler/scheduler.pyproject create mode 100644 debye_bec/bec_widgets/widgets/scheduler/scheduler_plugin.py diff --git a/debye_bec/bec_widgets/widgets/client.py b/debye_bec/bec_widgets/widgets/client.py index c974339..0fc46e6 100644 --- a/debye_bec/bec_widgets/widgets/client.py +++ b/debye_bec/bec_widgets/widgets/client.py @@ -69,7 +69,7 @@ class DigitalTwin(RPCBase): class RestartServer(RPCBase): - """Main widget of server restart widget""" + """Main widget of server restart widget.""" _IMPORT_MODULE = "debye_bec.bec_widgets.widgets.restart_server.restart_server" @@ -115,3 +115,102 @@ class ScanControlXAS(RPCBase): """ Take a screenshot of the dock area and save it to a file. """ + + +class Scheduler(RPCBase): + """Schedule, persist and execute a sequence of BEC scan/device commands.""" + + _IMPORT_MODULE = "debye_bec.bec_widgets.widgets.scheduler.scheduler" + + @rpc_call + def run_schedule(self): + """ + Run the schedule, continuing from wherever it last left off. + """ + + @rpc_call + def abort_schedule(self): + """ + Request that the schedule stop after the current item. + """ + + @rpc_call + def reset_schedule(self): + """ + Clear all execution state and start the schedule over from item 1. + """ + + @rpc_call + def get_status(self) -> "dict": + """ + RPC-exposed: current schedule state, e.g. for another widget or a script. + """ + + @rpc_call + def add_item( + self, + command: "str", + index: "int | None" = None, + kind: "str" = "custom", + form_state: "dict | None" = None, + ) -> "str": + """ + RPC-exposed: insert a new, PENDING command into the schedule. + Safe to call while the schedule is running. + + Args: + command: command text, evaluated the same way as the existing + items (against `scans`/`dev`) once the schedule runs. + index: position to insert at (0 = first). Clamped so the item + can never land before something already running or + finished. Defaults to appending at the end. + kind/form_state: optional structured description of how + `command` was built (see `schedule_item.ScheduleItem`), + used to reopen the Edit dialog pre-filled. Leave as + defaults for a plain, hand-typed command. + + Returns: + The new item's item_id. + """ + + @rpc_call + def edit_item( + self, + item_id: "str", + command: "str", + kind: "str" = "custom", + form_state: "dict | None" = None, + ): + """ + RPC-exposed: change the command of an item that has not started + yet. Raises `RuntimeError` for an item that is already + running/finished. + """ + + @rpc_call + def delete_item(self, item_id: "str"): + """ + RPC-exposed: remove an item that has not started yet. Raises + `RuntimeError` for an item that is already running/finished. + """ + + @rpc_call + def move_item(self, item_id: "str", new_index: "int"): + """ + RPC-exposed: move an item that has not started yet to a new + position (0 = first, but never before something already + running/finished). Raises `RuntimeError` for an item that is + already running/finished. + """ + + @rpc_call + def move_item_up(self, item_id: "str"): + """ + RPC-exposed: swap an item with the one directly before it. + """ + + @rpc_call + def move_item_down(self, item_id: "str"): + """ + RPC-exposed: swap an item with the one directly after it. + """ diff --git a/debye_bec/bec_widgets/widgets/scheduler/__init__.py b/debye_bec/bec_widgets/widgets/scheduler/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/debye_bec/bec_widgets/widgets/scheduler/endpoints.py b/debye_bec/bec_widgets/widgets/scheduler/endpoints.py new file mode 100644 index 0000000..06fb111 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/endpoints.py @@ -0,0 +1,61 @@ +""" +Redis endpoint(s) for the schedule widget plugin. + +Design notes (why this looks the way it does) +----------------------------------------------- +BEC never touches Redis with raw keys/commands. Every channel is described +by an `EndpointInfo` (endpoint string + message type + allowed operations, +see `bec_lib.endpoints`), and `RedisConnector` enforces both: calling an +operation that isn't in the endpoint's `MessageOp` raises +`IncompatibleRedisOperation`, and passing a message that isn't an instance +of the endpoint's declared `message_type` raises +`IncompatibleMessageForEndpoint`. Plain string topics still work but are +deprecated. So a "conforming" custom endpoint means building a real +`EndpointInfo`, exactly like `bec_lib.endpoints.MessageEndpoints` does +internally. + +Namespace: we use `EndpointType.USER` ("user/...”), the same prefix BEC's +own `MessageEndpoints.scan_queue_schedule()` uses for user-writable, +persisted data (as opposed to `internal/`, `public/`, etc.). + +Message type: we deliberately do NOT declare our own `BECMessage` +subclass. BEC's msgpack codec (`bec_lib.codecs.BECMessageEncoder.decode`) +resolves an incoming message's class by name via +`getattr(bec_lib.messages, type_name)` - i.e. only classes physically +defined inside `bec_lib.messages` are resolvable this way. A message class +declared in plugin code would fail to deserialize unless you monkey-patch +it into that module, which is exactly the kind of side-door this plugin +is meant to avoid. Instead we reuse `bec_lib.messages.VariableMessage`, +a first-class, exported message type built for carrying an arbitrary +(msgpack-serializable) payload under `.value`. +`bec_lib.script_executor.upload_script` persists a script's text in Redis +the same way, for the same reason - it's the established BEC pattern for +"a plugin needs to stash its own structured data in Redis". +""" + +from __future__ import annotations + +from bec_lib.endpoints import EndpointInfo, EndpointType, MessageOp +from bec_lib.messages import VariableMessage + + +def schedule(schedule_name: str) -> EndpointInfo: + """ + Endpoint for one named widget schedule (an ordered list of commands + plus their execution status). The whole schedule is stored as a single + `VariableMessage` document that gets overwritten and republished on + every change (`MessageOp.SET_PUBLISH`), so any other subscriber - + another instance of this widget, a monitoring script, ... - stays in + sync live. + + Args: + schedule_name: a stable, user-chosen name for the schedule. Unlike + a widget's `gui_id` (regenerated every time the widget is + constructed), this name is what lets a widget that was closed + and reopened find its own previously persisted schedule again. + """ + return EndpointInfo( + endpoint=f"{EndpointType.USER.value}/schedule_widget/schedule/{schedule_name}", + message_type=VariableMessage, + message_op=MessageOp.SET_PUBLISH, + ) diff --git a/debye_bec/bec_widgets/widgets/scheduler/guard.py b/debye_bec/bec_widgets/widgets/scheduler/guard.py new file mode 100644 index 0000000..5fd69d5 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/guard.py @@ -0,0 +1,160 @@ +""" +A small, self-contained utility for "if signal X drops below A, pause; once +it's back above B, resume" (hysteresis) behavior - e.g. auto-pausing scans +while the beam current is too low. + +This module knows nothing about schedules, scans, or the rest of this +plugin. It only monitors one BEC device's live readback value +(`MessageEndpoints.device_readback`, the same endpoint the device server +publishes for every monitored device) and emits Qt signals when the value +crosses one of the two configured thresholds. `schedule_widget.py` is the +only place that connects those signals to schedule-specific behavior +(aborting/deferring a scan item) - see its module docstring for how. +""" + +from __future__ import annotations + +import threading + +from bec_lib.endpoints import MessageEndpoints +from bec_lib.logger import bec_logger +from pydantic import BaseModel +from qtpy.QtCore import QObject, Signal + +logger = bec_logger.logger + + +class GuardSettings(BaseModel): + """Persisted configuration for one `SignalGuard`.""" + + enabled: bool = False + device_name: str | None = None + pause_below: float | None = None + resume_above: float | None = None + + +class SignalGuard(QObject): + """ + Monitors one device's readback value and reports hysteresis-based + pause/resume crossings. + + - `paused` fires the first time the value drops below `pause_below` + (not again while it stays low). + - `resumed` fires the first time it then climbs back above + `resume_above` (not again while it stays high). + A value sitting between the two thresholds never re-triggers either + signal - that gap is the point of using two thresholds instead of one, + so a value oscillating right at a single cutoff wouldn't cause rapid + pause/resume flapping. + + Callbacks from `RedisConnector.register()` run on a background + (Redis-listener) thread, not the Qt GUI thread; `paused`/`resumed` are + Qt signals, so connecting to them with the default (auto) connection + type safely marshals delivery onto whatever thread the receiver lives + on - no extra locking needed on the receiving end. + """ + + paused = Signal(float) + resumed = Signal(float) + + def __init__(self, connector, parent=None): + super().__init__(parent) + self._connector = connector + self._lock = threading.Lock() + self._clear_event = threading.Event() + self._clear_event.set() # not blocking until configured/proven otherwise + + self.enabled = False + self.device_name: str | None = None + self.pause_below: float | None = None + self.resume_above: float | None = None + self.current_value: float | None = None + + self._subscribed_endpoint = None + + def configure(self, settings: GuardSettings): + """(Re)configure and (re)subscribe. Safe to call repeatedly, e.g. after editing settings.""" + self._unsubscribe() + + self.enabled = settings.enabled + self.device_name = settings.device_name + self.pause_below = settings.pause_below + self.resume_above = settings.resume_above + self.current_value = None + self._clear_event.set() + + if self.enabled and self.device_name and self.pause_below is not None and self.resume_above is not None: + self._subscribed_endpoint = MessageEndpoints.device_readback(self.device_name) + self._connector.register(topics=self._subscribed_endpoint, cb=self._on_readback) + + def _unsubscribe(self): + if self._subscribed_endpoint is not None: + try: + self._connector.unregister(topics=self._subscribed_endpoint, cb=self._on_readback) + except Exception: # pylint: disable=broad-except + logger.exception("Failed to unsubscribe SignalGuard from %s", self._subscribed_endpoint) + self._subscribed_endpoint = None + + def _on_readback(self, msg): + device_msg = getattr(msg, "value", None) + if device_msg is None: + return + value = _extract_value(device_msg, self.device_name) + if value is None: + return + + crossed_pause = crossed_resume = False + with self._lock: + self.current_value = value + if self._clear_event.is_set(): + if value < self.pause_below: + self._clear_event.clear() + crossed_pause = True + elif value > self.resume_above: + self._clear_event.set() + crossed_resume = True + + if crossed_pause: + logger.info("SignalGuard: %s dropped to %s (below %s) - pausing.", self.device_name, value, self.pause_below) + self.paused.emit(value) + elif crossed_resume: + logger.info("SignalGuard: %s recovered to %s (above %s) - resuming.", self.device_name, value, self.resume_above) + self.resumed.emit(value) + + def is_clear(self) -> bool: + """True if not currently blocking (disabled, or value above the resume threshold).""" + return (not self.enabled) or self._clear_event.is_set() + + def wait_until_clear(self, should_abort, poll_interval: float = 0.5) -> bool: + """ + Blocks the calling (non-GUI) thread until `is_clear()` becomes + True, checking `should_abort()` between polls so an operator abort + can still interrupt the wait. Returns True if it cleared, False if + `should_abort()` returned True first. + """ + if self.is_clear(): + return True + while not should_abort(): + if self._clear_event.wait(timeout=poll_interval): + return True + return False + + def cleanup(self): + self._unsubscribe() + + +def _extract_value(device_msg, device_name: str | None): + """ + `DeviceMessage.signals` is keyed by signal name, e.g. {"beam_current": + {"value": ..., "timestamp": ...}, ...}. For a simple scalar device the + primary signal is usually named after the device itself; fall back to + the first signal found if not (e.g. a differently-named primary signal + on a compound device). + """ + signals = getattr(device_msg, "signals", None) or {} + if device_name in signals: + return signals[device_name].get("value") + for signal in signals.values(): + if "value" in signal: + return signal["value"] + return None diff --git a/debye_bec/bec_widgets/widgets/scheduler/guard_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/guard_dialog.py new file mode 100644 index 0000000..3a7654f --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/guard_dialog.py @@ -0,0 +1,94 @@ +"""Small settings dialog for `guard.GuardSettings` - kept separate from the guard logic itself.""" + +from __future__ import annotations + +from qtpy.QtWidgets import ( + QCheckBox, + QComboBox, + QDialog, + QDialogButtonBox, + QDoubleSpinBox, + QFormLayout, + QLabel, + QMessageBox, + QVBoxLayout, +) + +from .guard import GuardSettings + +_DSPIN_RANGE = (-1e12, 1e12) + + +class GuardSettingsDialog(QDialog): + """Configure (or disable) the auto-pause/resume guard for scan items.""" + + def __init__(self, settings: GuardSettings, device_names: list[str], parent=None): + super().__init__(parent) + self.setWindowTitle("Auto-pause on signal") + + layout = QVBoxLayout(self) + info_label = QLabel( + "If enabled, the currently running scan is aborted as soon as the chosen " + "signal drops below the pause value, and automatically restarted once it " + "rises back above the resume value. Only scan items are affected - device " + "moves and custom/RPC commands are never interrupted by this." + ) + info_label.setWordWrap(True) + layout.addWidget(info_label) + + form = QFormLayout() + layout.addLayout(form) + + self.enabled_check = QCheckBox("Enable auto-pause") + self.enabled_check.setChecked(settings.enabled) + form.addRow("", self.enabled_check) + + self.device_combo = QComboBox() + self.device_combo.addItems(device_names) + if settings.device_name: + idx = self.device_combo.findText(settings.device_name) + if idx >= 0: + self.device_combo.setCurrentIndex(idx) + form.addRow("Signal (device)", self.device_combo) + + self.pause_below_spin = QDoubleSpinBox() + self.pause_below_spin.setDecimals(4) + self.pause_below_spin.setRange(*_DSPIN_RANGE) + if settings.pause_below is not None: + self.pause_below_spin.setValue(settings.pause_below) + form.addRow("Pause below", self.pause_below_spin) + + self.resume_above_spin = QDoubleSpinBox() + self.resume_above_spin.setDecimals(4) + self.resume_above_spin.setRange(*_DSPIN_RANGE) + if settings.resume_above is not None: + self.resume_above_spin.setValue(settings.resume_above) + form.addRow("Resume above", self.resume_above_spin) + + buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) + buttons.accepted.connect(self._on_accept) + buttons.rejected.connect(self.reject) + layout.addWidget(buttons) + + def _on_accept(self): + if self.enabled_check.isChecked(): + if not self.device_combo.currentText(): + QMessageBox.warning(self, "Missing input", "Select a device to monitor.") + return + if self.resume_above_spin.value() <= self.pause_below_spin.value(): + QMessageBox.warning( + self, + "Invalid thresholds", + "'Resume above' must be greater than 'Pause below' (hysteresis gap).", + ) + return + self.accept() + + def result_settings(self) -> GuardSettings: + """Valid after `exec_()` returns `QDialog.Accepted`.""" + return GuardSettings( + enabled=self.enabled_check.isChecked(), + device_name=self.device_combo.currentText() or None, + pause_below=self.pause_below_spin.value(), + resume_above=self.resume_above_spin.value(), + ) diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py new file mode 100644 index 0000000..001f541 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -0,0 +1,238 @@ +""" +The dialog behind the schedule widget's "Add..."/"Edit..." buttons. + +Rather than asking the operator to remember and type +`scans.xas_simple_scan(12000, 14000, 2, 10)`-style commands, this presents: + +- a "Scan" tab: BEC's own `bec_widgets` `ScanControl` widget, embedded + as-is - scan selection, its live-generated per-scan argument form, + docs tooltips, metadata, "recall last scan parameters", all of it. + Reusing it instead of a plugin-owned reimplementation means this stays + in sync with BEC's scan capabilities for free, and looks/behaves exactly + like the scan controls an operator already knows from elsewhere in the + GUI. `ScanControl.button_run_scan` ("Start") is hidden here: this dialog + only ever wants the configured scan name/args/kwargs, never an + immediate submission - see `_collect_scan_result`. +- a "Move" tab: pick a device and a target value/relative flag; +- a "Custom" tab: a free-text field, for anything else (including RPC + calls to other widgets), evaluated the same way as the other tabs. + +Whichever tab is used, the dialog's only output is the same kind of plain +command string the executor already knows how to run - this dialog adds a +friendlier way to *build* that string, it doesn't change what happens with +it afterwards. `kind`/`form_state` are carried along purely so "Edit..." +can reopen the dialog pre-filled instead of asking the user to start over. +""" + +from __future__ import annotations + +from bec_widgets.widgets.control.scan_control.scan_control import ScanControl, ScanParameterConfig +from qtpy.QtWidgets import ( + QCheckBox, + QComboBox, + QDialog, + QDialogButtonBox, + QDoubleSpinBox, + QFormLayout, + QLabel, + QLineEdit, + QMessageBox, + QTabWidget, + QVBoxLayout, + QWidget, +) + +from .scan_form import list_movable_device_names + +_DSPIN_RANGE = (-1e12, 1e12) + + +class ScheduleItemDialog(QDialog): + """Add or edit one schedule item, via ScanControl, a move form, or free text.""" + + def __init__(self, scans, dev, parent=None, initial: dict | None = None, client=None): + super().__init__(parent) + self.setWindowTitle("Schedule item") + self.setMinimumSize(520, 480) + + self._scans = scans + self._dev = dev + self._client = client + + layout = QVBoxLayout(self) + self.tabs = QTabWidget() + layout.addWidget(self.tabs) + + self._build_scan_tab() + self._build_move_tab() + self._build_custom_tab() + + buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) + buttons.accepted.connect(self._on_accept) + buttons.rejected.connect(self.reject) + layout.addWidget(buttons) + + self._apply_initial(initial or {}) + + # ------------------------------------------------------------------ # + # Scan tab - embeds BEC's own ScanControl widget + # ------------------------------------------------------------------ # + def _build_scan_tab(self): + tab = QWidget() + layout = QVBoxLayout(tab) + + # client=None resolves to the same process-wide BEC client + # (bec_dispatcher.client) our own widget uses - no second Redis + # connection is opened. + self.scan_control = ScanControl(parent=tab, client=self._client) + self.scan_control.button_run_scan.hide() + layout.addWidget(self.scan_control) + + hint = QLabel( + "Configure the scan above, then confirm with OK below - it will be " + "added to the schedule, not started immediately." + ) + hint.setWordWrap(True) + hint.setStyleSheet("color: gray;") + layout.addWidget(hint) + + self.tabs.addTab(tab, "Scan") + + def _collect_scan_result(self) -> dict: + # Same call ScanControl.run_scan() makes before actually + # submitting, to resolve a typed-but-unconfirmed scan name. + self.scan_control.validate_scan_selection() + scan_name = self.scan_control.current_scan + if not scan_name: + raise ValueError("No scan selected.") + + # bec_object=False: plain, repr-able values (e.g. a device name + # string rather than the live DeviceBase instance) - needed since + # the result has to survive a round-trip through Redis as text and + # be re-evaluated later, not just used in-process immediately. + args, kwargs = self.scan_control.get_scan_parameters(bec_object=False) + command = _format_scan_call(scan_name, args, kwargs) + return { + "command": command, + "kind": "scan", + "form_state": {"scan_name": scan_name, "args": args, "kwargs": kwargs}, + } + + def _prefill_scan_tab(self, scan_name: str, args: list, kwargs: dict): + # ScanControl restores parameters for a scan from its own config + # cache (see `ScanControl.restore_scan_parameters`); pre-loading + # that cache before switching to the scan reuses that mechanism + # instead of poking at its internal argument widgets directly. + self.scan_control.config.scans[scan_name] = ScanParameterConfig( + name=scan_name, args=args, kwargs=kwargs + ) + self.scan_control.current_scan = scan_name + + # ------------------------------------------------------------------ # + # Move tab + # ------------------------------------------------------------------ # + def _build_move_tab(self): + tab = QWidget() + form = QFormLayout(tab) + + self.move_device_combo = QComboBox() + self.move_device_combo.addItems(list_movable_device_names(self._dev)) + form.addRow("Device", self.move_device_combo) + + self.move_value_spin = QDoubleSpinBox() + self.move_value_spin.setDecimals(6) + self.move_value_spin.setRange(*_DSPIN_RANGE) + form.addRow("Target value", self.move_value_spin) + + self.move_relative_check = QCheckBox("Relative move") + form.addRow("", self.move_relative_check) + + self.tabs.addTab(tab, "Move") + + def _collect_move_result(self) -> dict: + device_name = self.move_device_combo.currentText() + if not device_name: + raise ValueError("No movable device available/selected.") + value = self.move_value_spin.value() + relative = self.move_relative_check.isChecked() + return { + "command": f"dev.{device_name}.move({value!r}, relative={relative!r})", + "kind": "move", + "form_state": {"device_name": device_name, "value": value, "relative": relative}, + } + + # ------------------------------------------------------------------ # + # Custom tab + # ------------------------------------------------------------------ # + def _build_custom_tab(self): + tab = QWidget() + layout = QVBoxLayout(tab) + layout.addWidget( + QLabel( + "Free-form command, evaluated against `scans` and `dev` - use this for " + "anything the Scan/Move tabs don't cover, e.g. an RPC call to another widget." + ) + ) + self.custom_edit = QLineEdit() + self.custom_edit.setPlaceholderText("scans.xas_simple_scan(12000, 14000, 2, 10)") + layout.addWidget(self.custom_edit) + layout.addStretch(1) + self.tabs.addTab(tab, "Custom") + + def _collect_custom_result(self) -> dict: + text = self.custom_edit.text().strip() + if not text: + raise ValueError("Command must not be empty.") + return {"command": text, "kind": "custom", "form_state": {"text": text}} + + # ------------------------------------------------------------------ # + # pre-fill (edit mode) / result extraction + # ------------------------------------------------------------------ # + def _apply_initial(self, initial: dict): + kind = initial.get("kind") + state = initial.get("form_state") or {} + + if kind == "scan" and state.get("scan_name"): + self._prefill_scan_tab( + state["scan_name"], state.get("args") or [], state.get("kwargs") or {} + ) + self.tabs.setCurrentIndex(0) + elif kind == "move" and state.get("device_name"): + idx = self.move_device_combo.findText(state["device_name"]) + if idx >= 0: + self.move_device_combo.setCurrentIndex(idx) + self.move_value_spin.setValue(float(state.get("value", 0.0))) + self.move_relative_check.setChecked(bool(state.get("relative", False))) + self.tabs.setCurrentIndex(1) + elif initial.get("command"): + # "custom" kind, or a legacy/unrecognized item - fall back to + # showing the raw command text as-is. + self.custom_edit.setText(state.get("text", initial["command"])) + self.tabs.setCurrentIndex(2) + + def _on_accept(self): + try: + result = self._collect_result() + except ValueError as exc: + QMessageBox.warning(self, "Missing input", str(exc)) + return + self._result = result + self.accept() + + def _collect_result(self) -> dict: + current = self.tabs.currentIndex() + if current == 0: + return self._collect_scan_result() + if current == 1: + return self._collect_move_result() + return self._collect_custom_result() + + def result(self) -> dict: + """Valid after `exec_()` returns `QDialog.Accepted`.""" + return self._result + + +def _format_scan_call(scan_name: str, args: list, kwargs: dict) -> str: + parts = [repr(a) for a in args] + parts += [f"{name}={value!r}" for name, value in kwargs.items()] + return f"scans.{scan_name}({', '.join(parts)})" diff --git a/debye_bec/bec_widgets/widgets/scheduler/notification_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/notification_dialog.py new file mode 100644 index 0000000..0397c58 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/notification_dialog.py @@ -0,0 +1,59 @@ +"""Small settings dialog for `notifications.NotificationSettings` - kept separate from the send logic itself.""" + +from __future__ import annotations + +from qtpy.QtWidgets import QCheckBox, QDialog, QDialogButtonBox, QLabel, QVBoxLayout + +from .notifications import NotificationSettings + + +class NotificationSettingsDialog(QDialog): + """Choose whether, and for which item types, finish/fail notifications are sent.""" + + def __init__(self, settings: NotificationSettings, parent=None): + super().__init__(parent) + self.setWindowTitle("Notifications") + + layout = QVBoxLayout(self) + info_label = QLabel( + "Sends a BEC notification (see MessageEndpoints.notification) whenever a " + "schedule item finishes or fails. Whether it reaches you as a message depends " + "on your facility's notification routing (SciHub + Signal/Teams/SciLog) being " + "configured for these events - ask your beamline admin if you're not sure." + ) + info_label.setWordWrap(True) + layout.addWidget(info_label) + + self.enabled_check = QCheckBox("Send notifications") + self.enabled_check.setChecked(settings.enabled) + layout.addWidget(self.enabled_check) + + self.scan_check = QCheckBox("Scans") + self.scan_check.setChecked(settings.notify_scan) + layout.addWidget(self.scan_check) + + self.move_check = QCheckBox("Movements") + self.move_check.setChecked(settings.notify_move) + layout.addWidget(self.move_check) + + self.rpc_check = QCheckBox("RPC / custom commands") + self.rpc_check.setChecked(settings.notify_rpc) + layout.addWidget(self.rpc_check) + + for check in (self.scan_check, self.move_check, self.rpc_check): + self.enabled_check.toggled.connect(check.setEnabled) + check.setEnabled(settings.enabled) + + buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) + buttons.accepted.connect(self.accept) + buttons.rejected.connect(self.reject) + layout.addWidget(buttons) + + def result_settings(self) -> NotificationSettings: + """Valid after `exec_()` returns `QDialog.Accepted`.""" + return NotificationSettings( + enabled=self.enabled_check.isChecked(), + notify_scan=self.scan_check.isChecked(), + notify_move=self.move_check.isChecked(), + notify_rpc=self.rpc_check.isChecked(), + ) diff --git a/debye_bec/bec_widgets/widgets/scheduler/notifications.py b/debye_bec/bec_widgets/widgets/scheduler/notifications.py new file mode 100644 index 0000000..b7542e2 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/notifications.py @@ -0,0 +1,94 @@ +""" +A small, self-contained "tell the user when something finished/failed" +feature, independent of scheduling/execution logic. + +Sends via BEC's own notification transport: `MessageEndpoints.notification` +carries a `messages.NotificationMessage`, the same message type/endpoint +BEC's own scan lifecycle events (e.g. "scan_completed") use. Reusing it +means schedule-item notifications are just more entries in the same +mechanism, not a plugin-invented side channel - and if your facility runs +SciHub with messaging-service routing configured (Signal/Teams/SciLog), +they can be forwarded out the same way any other BEC notification would +be, by adding a route for the event names below in that routing config. + +Nothing here is scheduling/BECWidget-specific: `notify_item_finished` only +needs a connector, a settings object and a few plain values, so it can be +called from `schedule_widget.py` without either module depending on the +other's internals. +""" + +from __future__ import annotations + +from bec_lib.endpoints import MessageEndpoints +from bec_lib.logger import bec_logger +from bec_lib.messages import MessagingServiceTextContent, NotificationMessage +from pydantic import BaseModel + +logger = bec_logger.logger + +# Namespaced so they can't collide with BEC's own built-in event names +# (e.g. "scan_completed"); an admin who wants these routed to Signal/Teams/ +# SciLog can add a route for exactly these names in their notification +# routing config (`MessageEndpoints.notification_config()`). +_EVENT_NAMES = { + ("scan", True): "schedule_scan_completed", + ("scan", False): "schedule_scan_failed", + ("move", True): "schedule_move_completed", + ("move", False): "schedule_move_failed", + ("custom", True): "schedule_rpc_completed", + ("custom", False): "schedule_rpc_failed", +} + + +class NotificationSettings(BaseModel): + """Persisted per-schedule notification preferences.""" + + enabled: bool = False + notify_scan: bool = True + notify_move: bool = True + # "custom" is what this plugin calls the free-text tab (see + # item_dialog.py) - it covers RPC calls to other widgets as well as + # any hand-typed command, so it's exposed to the user as "RPC". + notify_rpc: bool = True + + +def _enabled_for_kind(settings: NotificationSettings, kind: str) -> bool: + if not settings.enabled: + return False + return { + "scan": settings.notify_scan, + "move": settings.notify_move, + "custom": settings.notify_rpc, + }.get(kind, False) + + +def notify_item_finished( + connector, + schedule_name: str, + kind: str, + command: str, + success: bool, + settings: NotificationSettings, + error: str | None = None, +): + """ + Sends a `NotificationMessage` if notifications are enabled for `kind`. + Never raises - a notification failing to send should not affect + schedule execution. + """ + if not _enabled_for_kind(settings, kind): + return + + event = _EVENT_NAMES.get((kind, success), "schedule_item_finished") + status_word = "completed" if success else "failed" + text = f"[{schedule_name}] {kind} {status_word}: {command}" + if error: + text += f"\n{error.strip().splitlines()[-1]}" + + try: + connector.send( + MessageEndpoints.notification(event), + NotificationMessage(event=event, message=[MessagingServiceTextContent(content=text)]), + ) + except Exception: # pylint: disable=broad-except + logger.exception("Failed to send schedule notification for event '%s'", event) diff --git a/debye_bec/bec_widgets/widgets/scheduler/register_scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/register_scheduler.py new file mode 100644 index 0000000..6b6f1a1 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/register_scheduler.py @@ -0,0 +1,15 @@ +def main(): # pragma: no cover + from qtpy import PYSIDE6 + + if not PYSIDE6: + print("PYSIDE6 is not available in the environment. Cannot patch designer.") + return + from PySide6.QtDesigner import QPyDesignerCustomWidgetCollection + + from .scheduler_plugin import SchedulerPlugin + + QPyDesignerCustomWidgetCollection.addCustomWidget(SchedulerPlugin()) + + +if __name__ == "__main__": # pragma: no cover + main() diff --git a/debye_bec/bec_widgets/widgets/scheduler/scan_form.py b/debye_bec/bec_widgets/widgets/scheduler/scan_form.py new file mode 100644 index 0000000..3c77272 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/scan_form.py @@ -0,0 +1,16 @@ +""" +Small device-listing helper for the "Move" tab of `item_dialog.py`. + +Scan parameter introspection/forms used to live in this module too, but +that's now handled by embedding BEC's own `bec_widgets` `ScanControl` +widget directly (see `item_dialog.py`) instead of a plugin-owned +reimplementation - one less UI to keep in sync with BEC's scan +capabilities. +""" + +from __future__ import annotations + + +def list_movable_device_names(dev) -> list[str]: + """Device names that expose `.move(...)` (i.e. positioner-like devices).""" + return sorted(name for name, device in dev.items() if hasattr(device, "move")) diff --git a/debye_bec/bec_widgets/widgets/scheduler/schedule_item.py b/debye_bec/bec_widgets/widgets/scheduler/schedule_item.py new file mode 100644 index 0000000..872b2a5 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/schedule_item.py @@ -0,0 +1,76 @@ +""" +Plain (non-BECMessage) data model for one schedule entry and the schedule +as a whole. + +These are ordinary pydantic models used only client-side, for validation +and convenience. They are never sent over Redis as their own type - only +ever as the `.value` payload of a `bec_lib.messages.VariableMessage` (see +`endpoints.schedule` for why). +""" + +from __future__ import annotations + +from enum import Enum +from typing import Literal + +from pydantic import BaseModel, Field + +from .guard import GuardSettings +from .notifications import NotificationSettings + + +class ScheduleItemStatus(str, Enum): + PENDING = "pending" + RUNNING = "running" + COMPLETED = "completed" + FAILED = "failed" + ABORTED = "aborted" + + +# Which tab of the Add/Edit dialog built `command`, and therefore how to +# re-open that dialog pre-filled with the same values for editing. "custom" +# covers hand-typed text (including RPC calls to other widgets), which has +# no structured `form_state` to restore beyond the raw text itself. +ScheduleItemKind = Literal["scan", "move", "custom"] + + +class ScheduleItem(BaseModel): + """A single command in the schedule, plus its execution bookkeeping.""" + + item_id: str + command: str + status: ScheduleItemStatus = ScheduleItemStatus.PENDING + + # How `command` was produced, and (for "scan"/"move") the structured + # inputs behind it, so the Add/Edit dialog can be reopened pre-filled + # instead of asking the user to re-type everything. `command` itself + # remains the single source of truth actually evaluated at execution + # time - `kind`/`form_state` only drive the UI. + kind: ScheduleItemKind = "custom" + form_state: dict | None = None + + # Bookkeeping used to reconnect to a submission that is still (or was) + # in flight on the BEC scan/device server, after this widget has been + # closed and reopened. + request_id: str | None = None + scan_id: str | None = None + scan_number: int | None = None + + error: str | None = None + started_at: float | None = None + finished_at: float | None = None + + +class Schedule(BaseModel): + """The full, persisted state of one schedule-widget instance.""" + + schedule_name: str + items: list[ScheduleItem] = Field(default_factory=list) + is_running: bool = False + + # Settings for two independent, optional features (see notifications.py + # and guard.py) - persisted here alongside the schedule itself so they + # survive a widget restart too, but their *logic* lives entirely in + # those separate modules; this is just where their settings are stored. + notifications: NotificationSettings = Field(default_factory=NotificationSettings) + guard: GuardSettings = Field(default_factory=GuardSettings) diff --git a/debye_bec/bec_widgets/widgets/scheduler/schedule_logic.py b/debye_bec/bec_widgets/widgets/scheduler/schedule_logic.py new file mode 100644 index 0000000..29553d9 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/schedule_logic.py @@ -0,0 +1,60 @@ +""" +Pure bookkeeping over a list of `ScheduleItem`s - no Qt, no locking, no I/O. +Kept separate from `schedule_widget.py` for the same reason `guard.py` and +`notifications.py` are: it's testable on its own, and the widget should +only be responsible for Qt/orchestration, not figuring out which item runs +next. + +The one invariant everything here assumes and preserves: at any moment, a +schedule's items form a (possibly empty) prefix that is no longer PENDING +(RUNNING - at most one, the one currently executing - COMPLETED, FAILED or +ABORTED), followed by a suffix that is entirely PENDING. `ScheduleWidget` +is responsible for only ever mutating the PENDING suffix (see its module +docstring) and for calling these functions while holding its lock; nothing +here does its own locking. +""" + +from __future__ import annotations + +from typing import Literal + +from .schedule_item import ScheduleItem, ScheduleItemStatus + + +def protected_prefix_length(items: list[ScheduleItem]) -> int: + """How many items, from the start, are no longer PENDING.""" + count = 0 + for item in items: + if item.status != ScheduleItemStatus.PENDING: + count += 1 + else: + break + return count + + +def index_of(items: list[ScheduleItem], item_id: str | None) -> int | None: + if item_id is None: + return None + for i, item in enumerate(items): + if item.item_id == item_id: + return i + return None + + +def pick_next_runnable(items: list[ScheduleItem]) -> ScheduleItem | Literal["stop"] | None: + """ + What the execution loop should do next: always re-derived from scratch + (never a remembered index/object) so edits made to the PENDING suffix + between calls are picked up correctly. + + Returns the next item to run/attach to, the string `"stop"` if an + earlier item failed/was aborted (execution stays parked there until the + operator intervenes), or `None` if every item is COMPLETED. + """ + for item in items: + if item.status == ScheduleItemStatus.COMPLETED: + continue + if item.status in (ScheduleItemStatus.FAILED, ScheduleItemStatus.ABORTED): + return "stop" + return item # PENDING, or RUNNING (reconciled as still active) + return None diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py new file mode 100644 index 0000000..84a04f1 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -0,0 +1,995 @@ +""" +ScheduleWidget - persists an ordered schedule of BEC commands (scans, +device moves, ...) to Redis, executes them one by one, and survives being +closed and reopened - including while an item is still running +server-side. Items that have not started yet can be added, reordered or +deleted while the schedule is executing; items that have already started +or finished cannot. + +Persistence +----------- +The whole schedule (list of items + status) is stored as one +`VariableMessage` document under a stable, named endpoint +(`endpoints.schedule(schedule_name)`), re-written and republished on every +change. See `endpoints.py` for the reasoning behind that design. + +Building a command +------------------- +The "Add..."/"Edit..." buttons open `item_dialog.ScheduleItemDialog`, +which lets the operator pick a registered scan through BEC's own +`bec_widgets` `ScanControl` widget (embedded as-is, with its "Start" +button hidden so it only ever configures a scan instead of submitting +one) or a device move from a small form, instead of typing a command by +hand - while still allowing every parameter value to be changed. A +"Custom" tab keeps a free-text command for anything else (e.g. an RPC +call to another widget). Whichever tab is used, the result is the same +kind of plain command string described below - the dialog only changes +how that string gets built. + +Execution model +---------------- +Each command (e.g. "scans.xas_simple_scan(12000, 14000, 2, 10)" or +"dev.samx.move(12.3, relative=True)") is evaluated against a small, +fixed namespace of `{"scans": self.scans, "dev": self.dev}`. This mirrors +how `bec_lib.script_executor` runs persisted script text: it does not +invent a second way to talk to devices/scans, it drives the exact same +client objects an operator would use interactively. + +Both `scans.xxx(...)` and `dev..move(...)` (which internally calls +`scans.mv(...)`) submit *asynchronously* to BEC's scan queue and return a +`ScanReport` immediately, with `.request.requestID`, `.wait()` and +`.cancel()`. Submission already happened server-side by the time `.wait()` +returns - closing this widget (or even the whole GUI process) does not +stop a scan or move that has already been submitted; it keeps running on +the scan/device server. + +Reconciliation after being closed and reopened +------------------------------------------------ +If this widget is closed while an item is RUNNING and reopened later, we +must not blindly resume from "pending" (which could re-submit a scan that +is still running) nor blindly trust our last persisted status forever +(the scan may have long since finished). Instead, on load we ask BEC's +*own*, live queue state: `client.queue.queue_storage`, freshly seeded from +`MessageEndpoints.scan_queue_status()`, can look up any earlier +`request_id` via `find_queue_item_by_requestID()`. If it's still +pending/running there, we re-attach and wait; if it's no longer in the +queue, it has left the system (finished, successfully or not) while we +were disconnected, and we mark it completed and move on. + +Editing while running - the "protected prefix" invariant +------------------------------------------------------------ +`run_schedule()` walks the items strictly in order in a background task +(`BECConnector.submit_task`). To let the operator add/reorder/delete +items that haven't started yet *while that task is running*, without +racing it, every mutation goes through `self._lock` and respects one +invariant: at any moment, the schedule's items form a (possibly empty) +prefix of items that are no longer PENDING (RUNNING - at most one, the +one currently executing - COMPLETED/FAILED/ABORTED), followed by a suffix +of items that are all still PENDING. The pure bookkeeping over that +invariant (`protected_prefix_length`, `index_of`, `pick_next_runnable`) +lives in `schedule_logic.py`, kept separate the same way `guard.py` and +`notifications.py` are - no Qt, no locking, independently testable; this +widget only calls it while holding `self._lock`. Edits are only ever +allowed to touch the PENDING suffix: + - `add_item(..., index=...)` clamps `index` up to at least the prefix + length, so a new item can never be inserted before something already + running or finished. + - `move_item`/`delete_item` refuse (raise `RuntimeError`) if the target + item's status isn't PENDING. +The execution task itself never keeps a stale index across its +(potentially long) `report.wait()` calls - each time it needs the next +item, it re-scans `self.schedule.items` from the start under the lock, so +edits made to the PENDING suffix while an earlier item is executing are +picked up correctly. + +Multi-instance note: `_on_remote_update` (another widget instance, or a +script, publishing a new version of this schedule) replaces +`self.schedule` wholesale. If *this* instance is currently running its +own execution task, applying a wholesale replacement here would orphan +the `ScheduleItem` object that task is watching, so incoming remote +updates are ignored while `self.schedule.is_running` locally - this +instance's own state wins until it finishes running, at which point its +next `_persist()` call re-publishes the authoritative state anyway. This +is a simplification: true multi-writer merging (e.g. concurrently editing +the PENDING suffix from two open widgets while a third is executing it) +is out of scope here. + +Notes / things to adapt for your BEC version and deployment +------------------------------------------------------------- +- `eval()` is used deliberately for the "Custom" tab and to actually run + every item, with an empty `__builtins__` and a namespace restricted to + `scans`/`dev`, matching BEC's own trust model for script text (see + `bec_lib.script_executor`). The Scan/Move tabs never eval user text - + values come from typed Qt widgets and are placed into the generated + command with `repr()`. +- `QueueItem.status` is a plain string on the installed bec_lib version + this was written against; the exact set of literal values was not + fully pinned down against a live scan server, so + `_is_queue_item_active()` treats anything containing "PENDING" or + "RUNNING" as still active and everything else as finished. + +Two independent, optional features +------------------------------------- +Both are implemented in their own modules with no dependency on +scheduling/execution internals - `schedule_widget.py` only wires their +signals/functions into the execution loop: + +- **Notifications** (`notifications.py`/`notification_dialog.py`): sends a + BEC `NotificationMessage` whenever an item finishes or fails, if enabled + for that item's kind (scan/move/rpc, independently toggleable). Fires + from `_execute_item()` after an item's final status is known. +- **Auto-pause guard** (`guard.py`/`guard_dialog.py`): a `SignalGuard` + monitors one device's live readback and, on hysteresis-based + pause/resume crossings, emits Qt signals `schedule_widget.py` reacts to. + Applies to scan items only - see "Guard interaction" below. + +Guard interaction with execution +----------------------------------- +When the guard is enabled and about to start a `kind == "scan"` item, +`_execute_item` first calls `self._guard.wait_until_clear(...)`, blocking +(without marking the item RUNNING, so it stays PENDING and visibly +unaffected by the "protected prefix" invariant) until the signal is back +above the resume threshold or the operator aborts. If the guard trips +*while* a scan item is RUNNING, `_on_guard_paused` cancels its +`ScanReport` (the same mechanism `abort_schedule()` uses) and sets +`self._guard_interrupt_requested`; `_execute_item`'s exception handler +checks that flag and, if set, resets the item back to PENDING (clearing +its request/scan bookkeeping) instead of marking it ABORTED - so the +normal execution loop simply picks it up again once the guard clears, +with no special "resume" code path needed. Device moves and custom/RPC +items are never touched by the guard (checked via `item.kind == "scan"` +in both places) - note this means a scan typed into the free-text +"Custom" tab is *not* guard-protected, since we can't tell hand-typed +text apart from a scan call; use the "Scan" tab if you need that. One +more limitation: a scan reconciled as "still running from a previous +session" (see "Reconciliation" above) is only *waited on* via +`_await_running_item`, not submitted through `_execute_item`, so there is +no live `ScanReport` for the guard to cancel if it trips during that +narrow window - it will simply be picked up again once that scan finishes +on its own. +""" + +from __future__ import annotations + +import threading +import time +import traceback +import uuid + +from bec_lib.endpoints import MessageEndpoints +from bec_lib.logger import bec_logger +from bec_lib.messages import VariableMessage +from bec_widgets.utils.bec_connector import ConnectionConfig +from bec_widgets.utils.bec_widget import BECWidget +from bec_widgets.utils.error_popups import SafeSlot +from qtpy.QtCore import Qt, Signal +from qtpy.QtWidgets import ( + QDialog, + QHBoxLayout, + QLabel, + QListWidget, + QListWidgetItem, + QMessageBox, + QPushButton, + QVBoxLayout, + QWidget, +) + +from .endpoints import schedule as schedule_endpoint +from .guard import GuardSettings, SignalGuard +from .guard_dialog import GuardSettingsDialog +from .item_dialog import ScheduleItemDialog +from .notification_dialog import NotificationSettingsDialog +from .notifications import NotificationSettings, notify_item_finished +from .schedule_item import Schedule, ScheduleItem, ScheduleItemStatus +from .schedule_logic import index_of, pick_next_runnable, protected_prefix_length + +logger = bec_logger.logger + +# The static, hard-coded example schedule requested for this plugin. A +# real deployment would more likely let the user build this list purely +# through the UI - the persistence/execution/reconciliation logic below +# does not care where the commands came from. +DEFAULT_COMMANDS = [ + "scans.xas_simple_scan(12000, 14000, 2, 10)", + "dev.samx.move(12.3, relative=True)", + "scans.xas_simple_scan(13000, 17000, 1, 60)", +] + +_ACTIVE_QUEUE_STATES = ("PENDING", "RUNNING") +_ITEM_ID_ROLE = Qt.UserRole + 1 # QListWidgetItem data role used to map a row back to an item_id + +_STATUS_ICON = { + ScheduleItemStatus.PENDING: "\u23f3", # hourglass + ScheduleItemStatus.RUNNING: "\u25b6", # play + ScheduleItemStatus.COMPLETED: "\u2705", # check mark + ScheduleItemStatus.FAILED: "\u274c", # cross mark + ScheduleItemStatus.ABORTED: "\u23f9", # stop +} + + +class ScheduleWidgetConfig(ConnectionConfig): + """ + Per-instance identity/settings for `ScheduleWidget`, following the same + pattern `bec_widgets` itself uses (e.g. `ScanControlConfig`): a + `ConnectionConfig` subclass constructed in `__init__` when none is + passed, carrying whatever small settings distinguish one instance from + another. + + `schedule_name` lives here rather than as a bare constructor kwarg for + that consistency - but note this is *not* where the schedule's actual + contents (items, guard/notification settings) live: `self.config` is + used for RPC identity and optional explicit GUI-layout save/restore, + not auto-persisted across an ordinary widget close/reopen the way this + plugin's Redis-backed `Schedule` document is. Conflating the two would + quietly reintroduce the "closed widget loses its schedule" problem this + plugin exists to solve. + """ + + schedule_name: str = "default_schedule" + + +class Scheduler(BECWidget, QWidget): + """Schedule, persist and execute a sequence of BEC scan/device commands.""" + + ICON_NAME = "assignment_add" + USER_ACCESS = [ + "run_schedule", + "abort_schedule", + "reset_schedule", + "get_status", + "add_item", + "edit_item", + "delete_item", + "move_item", + "move_item_up", + "move_item_down", + ] + + # emitted (thread-safe, may come from the background execution task) + # whenever the schedule state changes and the UI should redraw + schedule_changed = Signal() + + def __init__( + self, + parent=None, + client=None, + config: ScheduleWidgetConfig | dict | None = None, + gui_id: str | None = None, + schedule_name: str | None = None, + **kwargs, + ): + if config is None: + config = ScheduleWidgetConfig( + widget_class=self.__class__.__name__, + schedule_name=schedule_name or "default_schedule", + ) + elif schedule_name is not None: + # Allow overriding even when a config object/dict was supplied, + # mirroring how ScanControl treats its own optional constructor + # args as overrides onto whatever config ends up in self.config. + if isinstance(config, dict): + config = dict(config, schedule_name=schedule_name) + else: + config.schedule_name = schedule_name + super().__init__(parent=parent, client=client, gui_id=gui_id, config=config, **kwargs) + + # A stable name, NOT self.gui_id: gui_id is regenerated every time + # the widget is constructed, so it could never be used to find a + # previously persisted schedule again after the widget is reopened. + self.schedule_name = self.config.schedule_name + + self.get_bec_shortcuts() # -> self.client, self.dev, self.scans, self.queue + self.connector = self.client.connector + + self._endpoint = schedule_endpoint(self.schedule_name) + self._lock = threading.Lock() # guards self.schedule (see module docstring) + self._abort_requested = False + self._guard_interrupt_requested = False # see "Guard interaction" in module docstring + self._current_report = None # ScanReport of the item currently executing, if any + self._current_item_kind: str | None = None # kind of the item _current_report belongs to + self._selected_item_id: str | None = None # survives list repopulation on refresh + + self.schedule_changed.connect(self._refresh_ui) + + self.schedule: Schedule = self._load_or_seed_schedule() + self._reconcile_with_live_state() + + self._guard = SignalGuard(self.connector, parent=self) + self._guard.paused.connect(self._on_guard_paused) + self._guard.resumed.connect(self._on_guard_resumed) + self._guard.configure(self.schedule.guard) + + self._build_ui() + self._refresh_ui() + + # Stay in sync with any other subscriber touching the same + # schedule (another instance of this widget, a script, ...). + self.bec_dispatcher.connect_slot(self._on_remote_update, self._endpoint) + + # ------------------------------------------------------------------ # + # persistence + # ------------------------------------------------------------------ # + def _load_or_seed_schedule(self) -> Schedule: + logger.info("load or seed schedule") + msg: VariableMessage | None = self.connector.get(self._endpoint) + if msg is not None: + logger.info(f"Got msg from endpoint: {msg}") + return Schedule.model_validate(msg.value) + + schedule = Schedule( + schedule_name=self.schedule_name, + items=[ + ScheduleItem(item_id=str(uuid.uuid4()), command=cmd) for cmd in DEFAULT_COMMANDS + ], + ) + self.connector.set_and_publish( + self._endpoint, VariableMessage(value=schedule.model_dump(mode="json")) + ) + return schedule + + def _persist_locked(self): + """Write `self.schedule` to Redis. Caller must hold `self._lock`.""" + self.connector.set_and_publish( + self._endpoint, VariableMessage(value=self.schedule.model_dump(mode="json")) + ) + + def _persist(self): + with self._lock: + self._persist_locked() + + @SafeSlot(dict, dict) + def _on_remote_update(self, msg_content: dict, metadata: dict): + value = msg_content.get("value") if msg_content else None + if not value or value.get("schedule_name") != self.schedule_name: + return + with self._lock: + if self.schedule.is_running: + # This instance's own execution task owns the current + # ScheduleItem objects (and will re-persist its own state + # again shortly); accepting a wholesale replacement here + # would orphan those objects. See module docstring. + logger.info( + "Ignoring remote schedule update for '%s' while a local run is in progress.", + self.schedule_name, + ) + return + self.schedule = Schedule.model_validate(value) + self._apply_guard_settings() + self._refresh_ui() + + # ------------------------------------------------------------------ # + # reconciliation: figure out real state after being closed/reopened + # ------------------------------------------------------------------ # + def _reconcile_with_live_state(self): + """ + For any item last seen as RUNNING, ask BEC's own queue state - + not our local memory, which may be stale or from a previous + process - what actually happened to it while we were gone. + """ + queue_storage = self.client.queue.queue_storage + + # Force a fresh pull of the current queue snapshot from Redis + # rather than relying on pubsub messages we may have missed while + # this widget instance did not exist. + status_msg = self.connector.get(MessageEndpoints.scan_queue_status()) + if status_msg is not None: + queue_storage.update_with_status(status_msg) + + with self._lock: + changed = False + for item in self.schedule.items: + if item.status != ScheduleItemStatus.RUNNING or not item.request_id: + continue + queue_item = queue_storage.find_queue_item_by_requestID(item.request_id) + if queue_item is not None and self._is_queue_item_active(queue_item): + # genuinely still in flight server-side; leave it + # RUNNING - run_schedule() will re-attach to it + # instead of resubmitting. + continue + item.status = ScheduleItemStatus.COMPLETED + item.finished_at = time.time() + changed = True + if changed: + self._persist_locked() + + @staticmethod + def _is_queue_item_active(queue_item) -> bool: + return str(getattr(queue_item, "status", "")).upper() in _ACTIVE_QUEUE_STATES + + # ------------------------------------------------------------------ # + # the "protected prefix" invariant (see module docstring) - the actual + # logic lives in schedule_logic.py, pure and independently testable; + # these thin wrappers just apply it to the current, lock-held state. + # ------------------------------------------------------------------ # + def _protected_prefix_length_locked(self) -> int: + return protected_prefix_length(self.schedule.items) + + def _index_of_locked(self, item_id: str | None) -> int | None: + return index_of(self.schedule.items, item_id) + + # ------------------------------------------------------------------ # + # UI + # ------------------------------------------------------------------ # + def _build_ui(self): + layout = QVBoxLayout(self) + layout.addWidget(QLabel(f"Schedule: {self.schedule_name}")) + + self.list_widget = QListWidget() + self.list_widget.currentRowChanged.connect(self._on_selection_changed) + layout.addWidget(self.list_widget) + + edit_row = QHBoxLayout() + self.add_btn = QPushButton("Add...") + self.edit_btn = QPushButton("Edit...") + self.delete_btn = QPushButton("Delete") + self.move_up_btn = QPushButton("Move Up") + self.move_down_btn = QPushButton("Move Down") + for button in ( + self.add_btn, + self.edit_btn, + self.delete_btn, + self.move_up_btn, + self.move_down_btn, + ): + edit_row.addWidget(button) + layout.addLayout(edit_row) + + self.add_btn.clicked.connect(self._on_add_clicked) + self.edit_btn.clicked.connect(self._on_edit_clicked) + self.delete_btn.clicked.connect(self._on_delete_clicked) + self.move_up_btn.clicked.connect(self._on_move_up_clicked) + self.move_down_btn.clicked.connect(self._on_move_down_clicked) + + run_row = QHBoxLayout() + self.run_btn = QPushButton("Run / Continue") + self.abort_btn = QPushButton("Abort") + self.reset_btn = QPushButton("Reset") + for button in (self.run_btn, self.abort_btn, self.reset_btn): + run_row.addWidget(button) + layout.addLayout(run_row) + + self.run_btn.clicked.connect(self.run_schedule) + self.abort_btn.clicked.connect(self.abort_schedule) + self.reset_btn.clicked.connect(self.reset_schedule) + + settings_row = QHBoxLayout() + self.notifications_btn = QPushButton("Notifications...") + self.guard_btn = QPushButton("Auto-pause...") + settings_row.addWidget(self.notifications_btn) + settings_row.addWidget(self.guard_btn) + layout.addLayout(settings_row) + + self.notifications_btn.clicked.connect(self._on_notifications_clicked) + self.guard_btn.clicked.connect(self._on_guard_clicked) + + self.guard_status_label = QLabel() + self.guard_status_label.setStyleSheet("color: gray;") + layout.addWidget(self.guard_status_label) + + @SafeSlot() + def _refresh_ui(self): + with self._lock: + items = list(self.schedule.items) + is_running = self.schedule.is_running + + self.list_widget.blockSignals(True) + self.list_widget.clear() + selected_row = None + for row, item in enumerate(items): + text = f"{_STATUS_ICON.get(item.status, '?')} {item.command}" + if item.error: + text += f" ({item.error.strip().splitlines()[-1]})" + list_item = QListWidgetItem(text, self.list_widget) + list_item.setData(_ITEM_ID_ROLE, item.item_id) + if item.item_id == self._selected_item_id: + selected_row = row + if selected_row is not None: + self.list_widget.setCurrentRow(selected_row) + else: + self._selected_item_id = None + self.list_widget.blockSignals(False) + + idx = None + selected_item = None + if self._selected_item_id is not None: + for i, item in enumerate(items): + if item.item_id == self._selected_item_id: + idx, selected_item = i, item + break + + # Editable = the selected item hasn't started yet. Thanks to the + # protected-prefix invariant, everything after the first PENDING + # item is guaranteed PENDING too, so a plain index/status check is + # enough here - see module docstring. + can_edit_selected = ( + selected_item is not None and selected_item.status == ScheduleItemStatus.PENDING + ) + + self.run_btn.setEnabled(not is_running) + # Adding is always safe: new items are clamped into the PENDING + # suffix regardless of what's selected (see add_item()). + self.add_btn.setEnabled(True) + self.edit_btn.setEnabled(can_edit_selected) + self.delete_btn.setEnabled(can_edit_selected) + self.move_up_btn.setEnabled(can_edit_selected and idx not in (None, 0)) + self.move_down_btn.setEnabled( + can_edit_selected and idx is not None and idx < len(items) - 1 + ) + + if self._guard.enabled: + state = "OK" if self._guard.is_clear() else "PAUSED - waiting to resume" + value = self._guard.current_value + value_text = f"{value:g}" if value is not None else "?" + self.guard_status_label.setText( + f"Auto-pause: {self._guard.device_name} = {value_text} " + f"(pause < {self._guard.pause_below:g}, resume > {self._guard.resume_above:g}) [{state}]" + ) + self.guard_status_label.show() + else: + self.guard_status_label.hide() + + def _on_selection_changed(self, row: int): + item = self.list_widget.item(row) if row >= 0 else None + self._selected_item_id = item.data(_ITEM_ID_ROLE) if item is not None else None + self._refresh_ui() + + # ---- notifications / auto-pause settings ---- # + @SafeSlot() + def _on_notifications_clicked(self): + dialog = NotificationSettingsDialog(self.schedule.notifications, parent=self) + if dialog.exec_() != QDialog.Accepted: + return + with self._lock: + self.schedule.notifications = dialog.result_settings() + self._persist_locked() + self._refresh_ui() + + @SafeSlot() + def _on_guard_clicked(self): + device_names = sorted(self.dev.keys()) + dialog = GuardSettingsDialog(self.schedule.guard, device_names, parent=self) + if dialog.exec_() != QDialog.Accepted: + return + with self._lock: + self.schedule.guard = dialog.result_settings() + self._persist_locked() + self._guard.configure(self.schedule.guard) + self._refresh_ui() + + def _apply_guard_settings(self): + """Re-subscribe the guard after `self.schedule.guard` changes (e.g. from a remote update).""" + self._guard.configure(self.schedule.guard) + + @SafeSlot(float) + def _on_guard_paused(self, value: float): + logger.info( + "Auto-pause guard tripped for schedule '%s' (value=%s); interrupting the running scan, if any.", + self.schedule_name, + value, + ) + if self._current_report is not None and self._current_item_kind == "scan": + self._guard_interrupt_requested = True + try: + self._current_report.cancel() + except Exception: # pylint: disable=broad-except + logger.exception("Failed to cancel the running scan for the auto-pause guard") + self.schedule_changed.emit() + + @SafeSlot(float) + def _on_guard_resumed(self, value: float): + logger.info( + "Auto-pause guard cleared for schedule '%s' (value=%s); the execution loop will " + "resume the next scan item automatically.", + self.schedule_name, + value, + ) + self.schedule_changed.emit() + + # ---- UI-triggered edit actions ---- # + @SafeSlot() + def _on_add_clicked(self): + dialog = ScheduleItemDialog(self.scans, self.dev, parent=self, client=self.client) + if dialog.exec_() != QDialog.Accepted: + return + result = dialog.result() + with self._lock: + idx = self._index_of_locked(self._selected_item_id) + insert_at = None if idx is None else idx + 1 + new_id = self.add_item( + result["command"], index=insert_at, kind=result["kind"], form_state=result["form_state"] + ) + self._selected_item_id = new_id + self._refresh_ui() + + @SafeSlot() + def _on_edit_clicked(self): + if self._selected_item_id is None: + return + with self._lock: + idx = self._index_of_locked(self._selected_item_id) + item = self.schedule.items[idx] if idx is not None else None + initial = ( + {"kind": item.kind, "command": item.command, "form_state": item.form_state} + if item is not None + else None + ) + if initial is None: + return + + dialog = ScheduleItemDialog( + self.scans, self.dev, parent=self, initial=initial, client=self.client + ) + if dialog.exec_() != QDialog.Accepted: + return + result = dialog.result() + try: + self.edit_item( + self._selected_item_id, + result["command"], + kind=result["kind"], + form_state=result["form_state"], + ) + except RuntimeError as exc: + QMessageBox.warning(self, "Cannot edit item", str(exc)) + return + self._refresh_ui() + + @SafeSlot() + def _on_delete_clicked(self): + if self._selected_item_id is None: + return + confirm = QMessageBox.question( + self, "Delete schedule item", "Remove the selected item from the schedule?" + ) + if confirm != QMessageBox.Yes: + return + try: + self.delete_item(self._selected_item_id) + except RuntimeError as exc: + QMessageBox.warning(self, "Cannot delete item", str(exc)) + return + self._selected_item_id = None + self._refresh_ui() + + @SafeSlot() + def _on_move_up_clicked(self): + if self._selected_item_id is None: + return + try: + self.move_item_up(self._selected_item_id) + except RuntimeError as exc: + QMessageBox.warning(self, "Cannot move item", str(exc)) + + @SafeSlot() + def _on_move_down_clicked(self): + if self._selected_item_id is None: + return + try: + self.move_item_down(self._selected_item_id) + except RuntimeError as exc: + QMessageBox.warning(self, "Cannot move item", str(exc)) + + # ------------------------------------------------------------------ # + # RPC-exposed actions (USER_ACCESS) + # ------------------------------------------------------------------ # + @SafeSlot() + def run_schedule(self): + """Run the schedule, continuing from wherever it last left off.""" + with self._lock: + if self.schedule.is_running: + return + self._abort_requested = False + self.schedule.is_running = True + self._persist_locked() + self.schedule_changed.emit() + self.submit_task( + self._run_all, on_complete=self._on_run_finished, on_failed=self._on_run_failed + ) + + @SafeSlot() + def abort_schedule(self): + """Request that the schedule stop after the current item.""" + self._abort_requested = True + if self._current_report is not None: + try: + self._current_report.cancel() + except Exception: # pylint: disable=broad-except + logger.exception("Failed to cancel the currently running schedule item") + + @SafeSlot() + def reset_schedule(self): + """Clear all execution state and start the schedule over from item 1.""" + with self._lock: + if self.schedule.is_running: + logger.info("Cannot reset schedule, as schedule is running!") + return + for item in self.schedule.items: + logger.info(f"Reset schedule item {item}") + item.status = ScheduleItemStatus.PENDING + item.request_id = None + item.scan_id = None + item.scan_number = None + item.error = None + item.started_at = None + item.finished_at = None + self._persist_locked() + self.schedule_changed.emit() + + def get_status(self) -> dict: + """RPC-exposed: current schedule state, e.g. for another widget or a script.""" + with self._lock: + return self.schedule.model_dump(mode="json") + + # ------------------------------------------------------------------ # + # RPC-exposed schedule editing (add / edit / move / delete) + # + # All of these only ever touch the PENDING suffix of the schedule - + # see the "protected prefix" section of the module docstring. They can + # be called at any time, including while the schedule is running. + # ------------------------------------------------------------------ # + def add_item( + self, + command: str, + index: int | None = None, + kind: str = "custom", + form_state: dict | None = None, + ) -> str: + """ + RPC-exposed: insert a new, PENDING command into the schedule. + Safe to call while the schedule is running. + + Args: + command: command text, evaluated the same way as the existing + items (against `scans`/`dev`) once the schedule runs. + index: position to insert at (0 = first). Clamped so the item + can never land before something already running or + finished. Defaults to appending at the end. + kind/form_state: optional structured description of how + `command` was built (see `schedule_item.ScheduleItem`), + used to reopen the Edit dialog pre-filled. Leave as + defaults for a plain, hand-typed command. + + Returns: + The new item's item_id. + """ + command = command.strip() + if not command: + raise ValueError("command must not be empty") + + with self._lock: + protected = self._protected_prefix_length_locked() + item = ScheduleItem( + item_id=str(uuid.uuid4()), command=command, kind=kind, form_state=form_state + ) + if index is None or index >= len(self.schedule.items): + self.schedule.items.append(item) + else: + self.schedule.items.insert(max(index, protected), item) + self._persist_locked() + self.schedule_changed.emit() + return item.item_id + + def edit_item( + self, item_id: str, command: str, kind: str = "custom", form_state: dict | None = None + ): + """ + RPC-exposed: change the command of an item that has not started + yet. Raises `RuntimeError` for an item that is already + running/finished. + """ + command = command.strip() + if not command: + raise ValueError("command must not be empty") + + with self._lock: + idx = self._index_of_locked(item_id) + if idx is None: + return + item = self.schedule.items[idx] + if item.status != ScheduleItemStatus.PENDING: + raise RuntimeError("Only items that have not started yet (PENDING) can be edited.") + item.command = command + item.kind = kind + item.form_state = form_state + self._persist_locked() + self.schedule_changed.emit() + + def delete_item(self, item_id: str): + """ + RPC-exposed: remove an item that has not started yet. Raises + `RuntimeError` for an item that is already running/finished. + """ + with self._lock: + idx = self._index_of_locked(item_id) + if idx is None: + return + if self.schedule.items[idx].status != ScheduleItemStatus.PENDING: + raise RuntimeError("Only items that have not started yet (PENDING) can be deleted.") + del self.schedule.items[idx] + self._persist_locked() + self.schedule_changed.emit() + + def move_item(self, item_id: str, new_index: int): + """ + RPC-exposed: move an item that has not started yet to a new + position (0 = first, but never before something already + running/finished). Raises `RuntimeError` for an item that is + already running/finished. + """ + with self._lock: + idx = self._index_of_locked(item_id) + if idx is None: + return + if self.schedule.items[idx].status != ScheduleItemStatus.PENDING: + raise RuntimeError("Only items that have not started yet (PENDING) can be moved.") + protected = self._protected_prefix_length_locked() + item = self.schedule.items.pop(idx) + new_index = max(protected, min(new_index, len(self.schedule.items))) + self.schedule.items.insert(new_index, item) + self._persist_locked() + self.schedule_changed.emit() + + def move_item_up(self, item_id: str): + """RPC-exposed: swap an item with the one directly before it.""" + with self._lock: + idx = self._index_of_locked(item_id) + target = idx - 1 if idx is not None and idx > 0 else None + if target is not None: + self.move_item(item_id, target) + + def move_item_down(self, item_id: str): + """RPC-exposed: swap an item with the one directly after it.""" + with self._lock: + idx = self._index_of_locked(item_id) + n = len(self.schedule.items) + target = idx + 1 if idx is not None and idx < n - 1 else None + if target is not None: + self.move_item(item_id, target) + + # ------------------------------------------------------------------ # + # execution - runs in a background task (BECConnector.submit_task, + # backed by a QThreadPool worker thread; UI updates below go through + # the `schedule_changed` Qt signal so they are marshalled back onto + # the GUI thread instead of touching widgets directly) + # ------------------------------------------------------------------ # + def _pick_next_runnable_locked(self): + """Must be called while holding `self._lock`; see `schedule_logic.pick_next_runnable`.""" + return pick_next_runnable(self.schedule.items) + + def _run_all(self): + namespace = {"scans": self.scans, "dev": self.dev} + while not self._abort_requested: + with self._lock: + next_item = self._pick_next_runnable_locked() + if next_item is None or next_item == "stop": + break + if next_item.status == ScheduleItemStatus.RUNNING: + self._await_running_item(next_item) + else: + self._execute_item(next_item, namespace) + + with self._lock: + self.schedule.is_running = False + self._persist_locked() + self.schedule_changed.emit() + + def _execute_item(self, item: ScheduleItem, namespace: dict): + if item.kind == "scan": + # Block here (item stays PENDING - nothing "started" yet) until + # the guard is clear or the operator aborts. See "Guard + # interaction" in the module docstring. + cleared = self._guard.wait_until_clear(should_abort=lambda: self._abort_requested) + self.schedule_changed.emit() + if not cleared: + return + + with self._lock: + item.status = ScheduleItemStatus.RUNNING + item.error = None + item.started_at = time.time() + self._persist_locked() + self.schedule_changed.emit() + + try: + report = eval( + item.command, {"__builtins__": {}}, namespace + ) # noqa: S307 pylint: disable=eval-used + self._current_report = report + self._current_item_kind = item.kind + + request = getattr(report, "request", None) + with self._lock: + item.request_id = getattr(request, "requestID", None) + # persist the request_id right away, before the + # (potentially long) wait below, so a reconnect can find + # it even if this process disappears mid-scan. + self._persist_locked() + + report.wait() + + scan = getattr(report, "scan", None) + with self._lock: + item.scan_id = getattr(scan, "scan_id", None) if scan else None + item.scan_number = getattr(scan, "scan_number", None) if scan else None + item.status = ( + ScheduleItemStatus.ABORTED + if self._abort_requested + else ScheduleItemStatus.COMPLETED + ) + except Exception: # pylint: disable=broad-except + with self._lock: + if self._guard_interrupt_requested: + # Interrupted by the auto-pause guard, not a real + # failure/operator abort - reset to PENDING so the + # normal execution loop retries it once the guard + # clears, instead of leaving it in a terminal state. + item.status = ScheduleItemStatus.PENDING + item.request_id = None + item.scan_id = None + item.scan_number = None + item.error = None + item.started_at = None + self._guard_interrupt_requested = False + elif self._abort_requested: + item.status = ScheduleItemStatus.ABORTED + else: + item.status = ScheduleItemStatus.FAILED + item.error = traceback.format_exc() + logger.error(f"Schedule item failed: {item.command}\n{item.error}") + finally: + with self._lock: + if item.status != ScheduleItemStatus.PENDING: + item.finished_at = time.time() + self._persist_locked() + final_status = item.status + self._current_report = None + self._current_item_kind = None + self.schedule_changed.emit() + + if final_status in (ScheduleItemStatus.COMPLETED, ScheduleItemStatus.FAILED): + notify_item_finished( + self.connector, + self.schedule_name, + item.kind, + item.command, + success=(final_status == ScheduleItemStatus.COMPLETED), + settings=self.schedule.notifications, + error=item.error, + ) + + def _await_running_item(self, item: ScheduleItem): + queue_storage = self.client.queue.queue_storage + while not self._abort_requested: + queue_item = queue_storage.find_queue_item_by_requestID(item.request_id) + if queue_item is None or not self._is_queue_item_active(queue_item): + with self._lock: + item.status = ScheduleItemStatus.COMPLETED + item.finished_at = time.time() + self._persist_locked() + self.schedule_changed.emit() + return + time.sleep(0.5) + + @SafeSlot() + def _on_run_finished(self): + self._refresh_ui() + + @SafeSlot(str) + def _on_run_failed(self, error: str): + logger.error(f"Schedule execution task failed unexpectedly: {error}") + with self._lock: + self.schedule.is_running = False + self._persist_locked() + self._refresh_ui() + + # ------------------------------------------------------------------ # + # cleanup + # ------------------------------------------------------------------ # + def cleanup(self): + # Note: we deliberately do NOT abort a running schedule here. The + # whole point of the Redis-backed design is that closing this + # widget must not interrupt anything already submitted to the + # scan/device server - see the module docstring. + self._guard.cleanup() + super().cleanup() # also disconnects all bec_dispatcher subscriptions for us diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.pyproject b/debye_bec/bec_widgets/widgets/scheduler/scheduler.pyproject new file mode 100644 index 0000000..0b99313 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.pyproject @@ -0,0 +1 @@ +{'files': ['scheduler.py']} \ No newline at end of file diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler_plugin.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler_plugin.py new file mode 100644 index 0000000..50ce14a --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler_plugin.py @@ -0,0 +1,57 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +from bec_widgets.utils.bec_designer import designer_material_icon +from qtpy.QtDesigner import QDesignerCustomWidgetInterface +from qtpy.QtWidgets import QWidget + +from .scheduler import Scheduler + +DOM_XML = """ + + + + +""" + + +class SchedulerPlugin(QDesignerCustomWidgetInterface): # pragma: no cover + def __init__(self): + super().__init__() + self._form_editor = None + + def createWidget(self, parent): + if parent is None: + return QWidget() + t = Scheduler(parent) + return t + + def domXml(self): + return DOM_XML + + def group(self): + return "" + + def icon(self): + return designer_material_icon(Scheduler.ICON_NAME) + + def includeFile(self): + return "scheduler" + + def initialize(self, form_editor): + self._form_editor = form_editor + + def isContainer(self): + return False + + def isInitialized(self): + return self._form_editor is not None + + def name(self): + return "Scheduler" + + def toolTip(self): + return "Scheduler" + + def whatsThis(self): + return self.toolTip() From 1150d1395b9c0ae7f66280f55e9fee9612db9025 Mon Sep 17 00:00:00 2001 From: x01da Date: Tue, 1 Sep 2026 12:42:27 +0200 Subject: [PATCH 02/56] wip --- .../widgets/scheduler/scheduler.py | 392 ++++++++---------- 1 file changed, 179 insertions(+), 213 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 84a04f1..efb2e1d 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -5,148 +5,6 @@ closed and reopened - including while an item is still running server-side. Items that have not started yet can be added, reordered or deleted while the schedule is executing; items that have already started or finished cannot. - -Persistence ------------ -The whole schedule (list of items + status) is stored as one -`VariableMessage` document under a stable, named endpoint -(`endpoints.schedule(schedule_name)`), re-written and republished on every -change. See `endpoints.py` for the reasoning behind that design. - -Building a command -------------------- -The "Add..."/"Edit..." buttons open `item_dialog.ScheduleItemDialog`, -which lets the operator pick a registered scan through BEC's own -`bec_widgets` `ScanControl` widget (embedded as-is, with its "Start" -button hidden so it only ever configures a scan instead of submitting -one) or a device move from a small form, instead of typing a command by -hand - while still allowing every parameter value to be changed. A -"Custom" tab keeps a free-text command for anything else (e.g. an RPC -call to another widget). Whichever tab is used, the result is the same -kind of plain command string described below - the dialog only changes -how that string gets built. - -Execution model ----------------- -Each command (e.g. "scans.xas_simple_scan(12000, 14000, 2, 10)" or -"dev.samx.move(12.3, relative=True)") is evaluated against a small, -fixed namespace of `{"scans": self.scans, "dev": self.dev}`. This mirrors -how `bec_lib.script_executor` runs persisted script text: it does not -invent a second way to talk to devices/scans, it drives the exact same -client objects an operator would use interactively. - -Both `scans.xxx(...)` and `dev..move(...)` (which internally calls -`scans.mv(...)`) submit *asynchronously* to BEC's scan queue and return a -`ScanReport` immediately, with `.request.requestID`, `.wait()` and -`.cancel()`. Submission already happened server-side by the time `.wait()` -returns - closing this widget (or even the whole GUI process) does not -stop a scan or move that has already been submitted; it keeps running on -the scan/device server. - -Reconciliation after being closed and reopened ------------------------------------------------- -If this widget is closed while an item is RUNNING and reopened later, we -must not blindly resume from "pending" (which could re-submit a scan that -is still running) nor blindly trust our last persisted status forever -(the scan may have long since finished). Instead, on load we ask BEC's -*own*, live queue state: `client.queue.queue_storage`, freshly seeded from -`MessageEndpoints.scan_queue_status()`, can look up any earlier -`request_id` via `find_queue_item_by_requestID()`. If it's still -pending/running there, we re-attach and wait; if it's no longer in the -queue, it has left the system (finished, successfully or not) while we -were disconnected, and we mark it completed and move on. - -Editing while running - the "protected prefix" invariant ------------------------------------------------------------- -`run_schedule()` walks the items strictly in order in a background task -(`BECConnector.submit_task`). To let the operator add/reorder/delete -items that haven't started yet *while that task is running*, without -racing it, every mutation goes through `self._lock` and respects one -invariant: at any moment, the schedule's items form a (possibly empty) -prefix of items that are no longer PENDING (RUNNING - at most one, the -one currently executing - COMPLETED/FAILED/ABORTED), followed by a suffix -of items that are all still PENDING. The pure bookkeeping over that -invariant (`protected_prefix_length`, `index_of`, `pick_next_runnable`) -lives in `schedule_logic.py`, kept separate the same way `guard.py` and -`notifications.py` are - no Qt, no locking, independently testable; this -widget only calls it while holding `self._lock`. Edits are only ever -allowed to touch the PENDING suffix: - - `add_item(..., index=...)` clamps `index` up to at least the prefix - length, so a new item can never be inserted before something already - running or finished. - - `move_item`/`delete_item` refuse (raise `RuntimeError`) if the target - item's status isn't PENDING. -The execution task itself never keeps a stale index across its -(potentially long) `report.wait()` calls - each time it needs the next -item, it re-scans `self.schedule.items` from the start under the lock, so -edits made to the PENDING suffix while an earlier item is executing are -picked up correctly. - -Multi-instance note: `_on_remote_update` (another widget instance, or a -script, publishing a new version of this schedule) replaces -`self.schedule` wholesale. If *this* instance is currently running its -own execution task, applying a wholesale replacement here would orphan -the `ScheduleItem` object that task is watching, so incoming remote -updates are ignored while `self.schedule.is_running` locally - this -instance's own state wins until it finishes running, at which point its -next `_persist()` call re-publishes the authoritative state anyway. This -is a simplification: true multi-writer merging (e.g. concurrently editing -the PENDING suffix from two open widgets while a third is executing it) -is out of scope here. - -Notes / things to adapt for your BEC version and deployment -------------------------------------------------------------- -- `eval()` is used deliberately for the "Custom" tab and to actually run - every item, with an empty `__builtins__` and a namespace restricted to - `scans`/`dev`, matching BEC's own trust model for script text (see - `bec_lib.script_executor`). The Scan/Move tabs never eval user text - - values come from typed Qt widgets and are placed into the generated - command with `repr()`. -- `QueueItem.status` is a plain string on the installed bec_lib version - this was written against; the exact set of literal values was not - fully pinned down against a live scan server, so - `_is_queue_item_active()` treats anything containing "PENDING" or - "RUNNING" as still active and everything else as finished. - -Two independent, optional features -------------------------------------- -Both are implemented in their own modules with no dependency on -scheduling/execution internals - `schedule_widget.py` only wires their -signals/functions into the execution loop: - -- **Notifications** (`notifications.py`/`notification_dialog.py`): sends a - BEC `NotificationMessage` whenever an item finishes or fails, if enabled - for that item's kind (scan/move/rpc, independently toggleable). Fires - from `_execute_item()` after an item's final status is known. -- **Auto-pause guard** (`guard.py`/`guard_dialog.py`): a `SignalGuard` - monitors one device's live readback and, on hysteresis-based - pause/resume crossings, emits Qt signals `schedule_widget.py` reacts to. - Applies to scan items only - see "Guard interaction" below. - -Guard interaction with execution ------------------------------------ -When the guard is enabled and about to start a `kind == "scan"` item, -`_execute_item` first calls `self._guard.wait_until_clear(...)`, blocking -(without marking the item RUNNING, so it stays PENDING and visibly -unaffected by the "protected prefix" invariant) until the signal is back -above the resume threshold or the operator aborts. If the guard trips -*while* a scan item is RUNNING, `_on_guard_paused` cancels its -`ScanReport` (the same mechanism `abort_schedule()` uses) and sets -`self._guard_interrupt_requested`; `_execute_item`'s exception handler -checks that flag and, if set, resets the item back to PENDING (clearing -its request/scan bookkeeping) instead of marking it ABORTED - so the -normal execution loop simply picks it up again once the guard clears, -with no special "resume" code path needed. Device moves and custom/RPC -items are never touched by the guard (checked via `item.kind == "scan"` -in both places) - note this means a scan typed into the free-text -"Custom" tab is *not* guard-protected, since we can't tell hand-typed -text apart from a scan call; use the "Scan" tab if you need that. One -more limitation: a scan reconciled as "still running from a previous -session" (see "Reconciliation" above) is only *waited on* via -`_await_running_item`, not submitted through `_execute_item`, so there is -no live `ScanReport` for the guard to cancel if it trips during that -narrow window - it will simply be picked up again once that scan finishes -on its own. """ from __future__ import annotations @@ -155,16 +13,22 @@ import threading import time import traceback import uuid +from typing import Literal, Optional from bec_lib.endpoints import MessageEndpoints from bec_lib.logger import bec_logger from bec_lib.messages import VariableMessage +from bec_qthemes._theme import AccentColors from bec_widgets.utils.bec_connector import ConnectionConfig from bec_widgets.utils.bec_widget import BECWidget +from bec_widgets.utils.colors import get_accent_colors from bec_widgets.utils.error_popups import SafeSlot from qtpy.QtCore import Qt, Signal +from qtpy.QtGui import QKeySequence, QShortcut from qtpy.QtWidgets import ( + QApplication, QDialog, + QGroupBox, QHBoxLayout, QLabel, QListWidget, @@ -229,9 +93,52 @@ class ScheduleWidgetConfig(ConnectionConfig): schedule_name: str = "default_schedule" +class MyListWidget(QListWidget): + deletePressed = Signal() + emptySpaceClicked = Signal() + + def keyPressEvent(self, event): + if event.key() == Qt.Key_Delete and self.currentItem() is not None: + self.deletePressed.emit() + event.accept() + return + + super().keyPressEvent(event) + + def mousePressEvent(self, event): + if event.button() == Qt.LeftButton and self.itemAt(event.position().toPoint()) is None: + self.clearSelection() + self.setCurrentRow(-1) + self.emptySpaceClicked.emit() + return + + super().mousePressEvent(event) + + +class MyButton(QPushButton): + def __init__(self, text="", color="default", parent=None): + self.color = color + super().__init__(text, parent) + + def apply_theme(self): + if self.isEnabled(): + colors = get_accent_colors() + color = getattr(colors, self.color).name() + self.setStyleSheet(f"QPushButton {{ background-color: {color}; color: white; }}") + else: + self.setStyleSheet( + "QPushButton {{background-color: rgb(120, 120, 120); color: white;}}" + ) + + def setEnabled(self, enable: bool = True): + super().setEnabled(enable) + self.apply_theme() + + class Scheduler(BECWidget, QWidget): """Schedule, persist and execute a sequence of BEC scan/device commands.""" + # BUG: Icon is not recognized, also no entry is created in designer_plugins.py ICON_NAME = "assignment_add" USER_ACCESS = [ "run_schedule", @@ -307,6 +214,118 @@ class Scheduler(BECWidget, QWidget): # schedule (another instance of this widget, a script, ...). self.bec_dispatcher.connect_slot(self._on_remote_update, self._endpoint) + # ------------------------------------------------------------------ # + # UI + # ------------------------------------------------------------------ # + def _build_ui(self): + layout = QVBoxLayout(self) + + schedule_group = QGroupBox("Schedule") + schedule_layout = QVBoxLayout(schedule_group) + + edit_row = QHBoxLayout() + self.add_btn = MyButton("Add", "default") + self.edit_btn = MyButton("Edit", "default") + self.delete_btn = MyButton("Delete", "default") + self.move_up_btn = MyButton("Move Up", "default") + self.move_down_btn = MyButton("Move Down", "default") + for button in ( + self.add_btn, + self.edit_btn, + self.delete_btn, + self.move_up_btn, + self.move_down_btn, + ): + edit_row.addWidget(button) + edit_row.addStretch() + schedule_layout.addLayout(edit_row) + # layout.addLayout(edit_row) + + # layout.addWidget(QLabel(f"Schedule: {self.schedule_name}")) + schedule_layout.addWidget(QLabel(f"Schedule: {self.schedule_name}")) + + self.list_widget = MyListWidget() + self.list_widget.currentRowChanged.connect(self._on_selection_changed) + self.list_widget.deletePressed.connect(self._on_delete_clicked) + self.list_widget.emptySpaceClicked.connect(self._on_empty_space_clicked) + # layout.ada(scheduldWidget(self.list_widget) + schedule_layout.addWidget(self.list_widget) + + self.add_btn.clicked.connect(self._on_add_clicked) + self.edit_btn.clicked.connect(self._on_edit_clicked) + self.delete_btn.clicked.connect(self._on_delete_clicked) + self.move_up_btn.clicked.connect(self._on_move_up_clicked) + self.move_down_btn.clicked.connect(self._on_move_down_clicked) + + layout.addWidget(schedule_group) + + control_group = QGroupBox("Control") + control_layout = QVBoxLayout(control_group) + + run_row = QHBoxLayout() + self.run_btn = MyButton("Run / Continue", "success") + self.abort_btn = MyButton("Abort", "emergency") + self.reset_btn = MyButton("Reset", "warning") + for button in (self.run_btn, self.abort_btn, self.reset_btn): + run_row.addWidget(button) + run_row.addStretch() + control_layout.addLayout(run_row) + # layout.addLayout(run_row) + + self.run_btn.clicked.connect(self.run_schedule) + self.abort_btn.clicked.connect(self.abort_schedule) + self.reset_btn.clicked.connect(self.reset_schedule) + + layout.addWidget(control_group) + + settings_group = QGroupBox("Settings") + settings_layout = QVBoxLayout(settings_group) + + settings_row = QHBoxLayout() + self.notifications_btn = MyButton("Notifications", "default") + self.guard_btn = MyButton("Auto-pause", "default") + settings_row.addWidget(self.notifications_btn) + settings_row.addWidget(self.guard_btn) + settings_row.addStretch() + settings_layout.addLayout(settings_row) + # layout.addLayout(settings_row) + + self.notifications_btn.clicked.connect(self._on_notifications_clicked) + self.guard_btn.clicked.connect(self._on_guard_clicked) + + layout.addWidget(settings_group) + + self.guard_status_label = QLabel() + self.guard_status_label.setStyleSheet("color: gray;") + layout.addWidget(self.guard_status_label) + + self.apply_theme() + + def apply_theme(self, theme: Optional[Literal["dark", "light"]] = None): + """ + Apply the theme + + Args: + theme (Optional[str]): Theme, either "dark", "light", or None. Defaults to None. + """ + if theme is None: + app = QApplication.instance() + theme = app.theme.theme # type: ignore + + for button in [ + self.add_btn, + self.edit_btn, + self.delete_btn, + self.move_down_btn, + self.move_up_btn, + self.run_btn, + self.abort_btn, + self.reset_btn, + self.notifications_btn, + self.guard_btn, + ]: + button.apply_theme() + # ------------------------------------------------------------------ # # persistence # ------------------------------------------------------------------ # @@ -314,9 +333,10 @@ class Scheduler(BECWidget, QWidget): logger.info("load or seed schedule") msg: VariableMessage | None = self.connector.get(self._endpoint) if msg is not None: - logger.info(f"Got msg from endpoint: {msg}") + logger.info(f"Got msg from endpoint: {msg.value}") return Schedule.model_validate(msg.value) + logger.info("No schedule found, create one now") schedule = Schedule( schedule_name=self.schedule_name, items=[ @@ -344,7 +364,8 @@ class Scheduler(BECWidget, QWidget): if not value or value.get("schedule_name") != self.schedule_name: return with self._lock: - if self.schedule.is_running: + new_schedule = Schedule.model_validate(value) + if new_schedule.is_running: # This instance's own execution task owns the current # ScheduleItem objects (and will re-persist its own state # again shortly); accepting a wholesale replacement here @@ -354,7 +375,7 @@ class Scheduler(BECWidget, QWidget): self.schedule_name, ) return - self.schedule = Schedule.model_validate(value) + self.schedule = new_schedule self._apply_guard_settings() self._refresh_ui() @@ -377,7 +398,7 @@ class Scheduler(BECWidget, QWidget): queue_storage.update_with_status(status_msg) with self._lock: - changed = False + self.schedule.is_running = False for item in self.schedule.items: if item.status != ScheduleItemStatus.RUNNING or not item.request_id: continue @@ -389,9 +410,7 @@ class Scheduler(BECWidget, QWidget): continue item.status = ScheduleItemStatus.COMPLETED item.finished_at = time.time() - changed = True - if changed: - self._persist_locked() + self._persist_locked() @staticmethod def _is_queue_item_active(queue_item) -> bool: @@ -408,65 +427,6 @@ class Scheduler(BECWidget, QWidget): def _index_of_locked(self, item_id: str | None) -> int | None: return index_of(self.schedule.items, item_id) - # ------------------------------------------------------------------ # - # UI - # ------------------------------------------------------------------ # - def _build_ui(self): - layout = QVBoxLayout(self) - layout.addWidget(QLabel(f"Schedule: {self.schedule_name}")) - - self.list_widget = QListWidget() - self.list_widget.currentRowChanged.connect(self._on_selection_changed) - layout.addWidget(self.list_widget) - - edit_row = QHBoxLayout() - self.add_btn = QPushButton("Add...") - self.edit_btn = QPushButton("Edit...") - self.delete_btn = QPushButton("Delete") - self.move_up_btn = QPushButton("Move Up") - self.move_down_btn = QPushButton("Move Down") - for button in ( - self.add_btn, - self.edit_btn, - self.delete_btn, - self.move_up_btn, - self.move_down_btn, - ): - edit_row.addWidget(button) - layout.addLayout(edit_row) - - self.add_btn.clicked.connect(self._on_add_clicked) - self.edit_btn.clicked.connect(self._on_edit_clicked) - self.delete_btn.clicked.connect(self._on_delete_clicked) - self.move_up_btn.clicked.connect(self._on_move_up_clicked) - self.move_down_btn.clicked.connect(self._on_move_down_clicked) - - run_row = QHBoxLayout() - self.run_btn = QPushButton("Run / Continue") - self.abort_btn = QPushButton("Abort") - self.reset_btn = QPushButton("Reset") - for button in (self.run_btn, self.abort_btn, self.reset_btn): - run_row.addWidget(button) - layout.addLayout(run_row) - - self.run_btn.clicked.connect(self.run_schedule) - self.abort_btn.clicked.connect(self.abort_schedule) - self.reset_btn.clicked.connect(self.reset_schedule) - - settings_row = QHBoxLayout() - self.notifications_btn = QPushButton("Notifications...") - self.guard_btn = QPushButton("Auto-pause...") - settings_row.addWidget(self.notifications_btn) - settings_row.addWidget(self.guard_btn) - layout.addLayout(settings_row) - - self.notifications_btn.clicked.connect(self._on_notifications_clicked) - self.guard_btn.clicked.connect(self._on_guard_clicked) - - self.guard_status_label = QLabel() - self.guard_status_label.setStyleSheet("color: gray;") - layout.addWidget(self.guard_status_label) - @SafeSlot() def _refresh_ui(self): with self._lock: @@ -529,11 +489,17 @@ class Scheduler(BECWidget, QWidget): else: self.guard_status_label.hide() + @SafeSlot() def _on_selection_changed(self, row: int): item = self.list_widget.item(row) if row >= 0 else None self._selected_item_id = item.data(_ITEM_ID_ROLE) if item is not None else None self._refresh_ui() + @SafeSlot() + def _on_empty_space_clicked(self): + self.list_widget.setCurrentRow(-1) + self._refresh_ui() + # ---- notifications / auto-pause settings ---- # @SafeSlot() def _on_notifications_clicked(self): @@ -639,17 +605,14 @@ class Scheduler(BECWidget, QWidget): def _on_delete_clicked(self): if self._selected_item_id is None: return - confirm = QMessageBox.question( - self, "Delete schedule item", "Remove the selected item from the schedule?" - ) - if confirm != QMessageBox.Yes: - return + row = self.list_widget.currentRow() try: self.delete_item(self._selected_item_id) except RuntimeError as exc: QMessageBox.warning(self, "Cannot delete item", str(exc)) return self._selected_item_id = None + self._on_selection_changed(max(0, row - 1)) self._refresh_ui() @SafeSlot() @@ -858,11 +821,13 @@ class Scheduler(BECWidget, QWidget): return pick_next_runnable(self.schedule.items) def _run_all(self): + logger.info("_run_all was called") namespace = {"scans": self.scans, "dev": self.dev} while not self._abort_requested: with self._lock: next_item = self._pick_next_runnable_locked() if next_item is None or next_item == "stop": + logger.info("Next item is None or stop") break if next_item.status == ScheduleItemStatus.RUNNING: self._await_running_item(next_item) @@ -870,6 +835,7 @@ class Scheduler(BECWidget, QWidget): self._execute_item(next_item, namespace) with self._lock: + logger.info("in _run_all, set is_running to false") self.schedule.is_running = False self._persist_locked() self.schedule_changed.emit() From 7c5bd4ce679775e35d8654cf7ac2daa881c2a9c5 Mon Sep 17 00:00:00 2001 From: x01da Date: Tue, 1 Sep 2026 14:28:25 +0200 Subject: [PATCH 03/56] wip --- .../widgets/scheduler/item_dialog.py | 45 ++++--- .../widgets/scheduler/scan_form.py | 16 --- .../widgets/scheduler/scheduler.py | 117 +++++++++++++----- 3 files changed, 116 insertions(+), 62 deletions(-) delete mode 100644 debye_bec/bec_widgets/widgets/scheduler/scan_form.py diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index 001f541..7aaf895 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -26,6 +26,11 @@ can reopen the dialog pre-filled instead of asking the user to start over. from __future__ import annotations +from bec_lib.logger import bec_logger +from bec_widgets.widgets.control.device_input.device_combobox.device_combobox import ( + BECDeviceFilter, + DeviceComboBox, +) from bec_widgets.widgets.control.scan_control.scan_control import ScanControl, ScanParameterConfig from qtpy.QtWidgets import ( QCheckBox, @@ -42,7 +47,9 @@ from qtpy.QtWidgets import ( QWidget, ) -from .scan_form import list_movable_device_names +from ..scan_control_xas.scan_control_xas import ScanControlXAS + +logger = bec_logger.logger _DSPIN_RANGE = (-1e12, 1e12) @@ -68,6 +75,8 @@ class ScheduleItemDialog(QDialog): self._build_custom_tab() buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) + buttons.button(QDialogButtonBox.Ok).setText("Add") + buttons.setStyleSheet("QPushButton {qproperty-icon: none;}") buttons.accepted.connect(self._on_accept) buttons.rejected.connect(self.reject) layout.addWidget(buttons) @@ -84,17 +93,17 @@ class ScheduleItemDialog(QDialog): # client=None resolves to the same process-wide BEC client # (bec_dispatcher.client) our own widget uses - no second Redis # connection is opened. - self.scan_control = ScanControl(parent=tab, client=self._client) + self.scan_control = ScanControlXAS(parent=tab, client=self._client) self.scan_control.button_run_scan.hide() layout.addWidget(self.scan_control) - hint = QLabel( - "Configure the scan above, then confirm with OK below - it will be " - "added to the schedule, not started immediately." - ) - hint.setWordWrap(True) - hint.setStyleSheet("color: gray;") - layout.addWidget(hint) + # hint = QLabel( + # "Configure the scan above, then confirm with OK below - it will be " + # "added to the schedule, not started immediately." + # ) + # hint.setWordWrap(True) + # hint.setStyleSheet("color: gray;") + # layout.addWidget(hint) self.tabs.addTab(tab, "Scan") @@ -127,6 +136,7 @@ class ScheduleItemDialog(QDialog): name=scan_name, args=args, kwargs=kwargs ) self.scan_control.current_scan = scan_name + self.scan_control.restore_scan_parameters(scan_name) # ------------------------------------------------------------------ # # Move tab @@ -134,18 +144,23 @@ class ScheduleItemDialog(QDialog): def _build_move_tab(self): tab = QWidget() form = QFormLayout(tab) + form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) + + # self.move_device_combo = QComboBox() + # self.move_device_combo.addItems(list_movable_device_names(self._dev)) + # self.move_device_combo.setMaxVisibleItems(12) + + self.move_device_combo = DeviceComboBox(self, device_filter=[BECDeviceFilter.POSITIONER]) - self.move_device_combo = QComboBox() - self.move_device_combo.addItems(list_movable_device_names(self._dev)) form.addRow("Device", self.move_device_combo) self.move_value_spin = QDoubleSpinBox() self.move_value_spin.setDecimals(6) self.move_value_spin.setRange(*_DSPIN_RANGE) - form.addRow("Target value", self.move_value_spin) + form.addRow("Value", self.move_value_spin) - self.move_relative_check = QCheckBox("Relative move") - form.addRow("", self.move_relative_check) + self.move_relative_check = QCheckBox("") + form.addRow("Relative move", self.move_relative_check) self.tabs.addTab(tab, "Move") @@ -209,6 +224,8 @@ class ScheduleItemDialog(QDialog): # showing the raw command text as-is. self.custom_edit.setText(state.get("text", initial["command"])) self.tabs.setCurrentIndex(2) + else: + logger.warning(f"Unknown kind: {kind}") def _on_accept(self): try: diff --git a/debye_bec/bec_widgets/widgets/scheduler/scan_form.py b/debye_bec/bec_widgets/widgets/scheduler/scan_form.py deleted file mode 100644 index 3c77272..0000000 --- a/debye_bec/bec_widgets/widgets/scheduler/scan_form.py +++ /dev/null @@ -1,16 +0,0 @@ -""" -Small device-listing helper for the "Move" tab of `item_dialog.py`. - -Scan parameter introspection/forms used to live in this module too, but -that's now handled by embedding BEC's own `bec_widgets` `ScanControl` -widget directly (see `item_dialog.py`) instead of a plugin-owned -reimplementation - one less UI to keep in sync with BEC's scan -capabilities. -""" - -from __future__ import annotations - - -def list_movable_device_names(dev) -> list[str]: - """Device names that expose `.move(...)` (i.e. positioner-like devices).""" - return sorted(name for name, device in dev.items() if hasattr(device, "move")) diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index efb2e1d..d7fdbe2 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -18,6 +18,7 @@ from typing import Literal, Optional from bec_lib.endpoints import MessageEndpoints from bec_lib.logger import bec_logger from bec_lib.messages import VariableMessage +from bec_qthemes import material_icon from bec_qthemes._theme import AccentColors from bec_widgets.utils.bec_connector import ConnectionConfig from bec_widgets.utils.bec_widget import BECWidget @@ -71,6 +72,15 @@ _STATUS_ICON = { ScheduleItemStatus.ABORTED: "\u23f9", # stop } +ICON_SIZE = 20 +_ICON_MAP = { + ScheduleItemStatus.PENDING: ("hourglass", "#919090"), + ScheduleItemStatus.RUNNING: ("cycle", "#2980b9"), + ScheduleItemStatus.COMPLETED: ("check", "#27ae60"), + ScheduleItemStatus.FAILED: ("warning", "#e74c3c"), + ScheduleItemStatus.ABORTED: ("cancel", "#e74c3c"), +} + class ScheduleWidgetConfig(ConnectionConfig): """ @@ -239,16 +249,15 @@ class Scheduler(BECWidget, QWidget): edit_row.addWidget(button) edit_row.addStretch() schedule_layout.addLayout(edit_row) - # layout.addLayout(edit_row) - # layout.addWidget(QLabel(f"Schedule: {self.schedule_name}")) schedule_layout.addWidget(QLabel(f"Schedule: {self.schedule_name}")) self.list_widget = MyListWidget() self.list_widget.currentRowChanged.connect(self._on_selection_changed) self.list_widget.deletePressed.connect(self._on_delete_clicked) self.list_widget.emptySpaceClicked.connect(self._on_empty_space_clicked) - # layout.ada(scheduldWidget(self.list_widget) + self.list_widget.itemDoubleClicked.connect(self._on_edit_clicked) + schedule_layout.addWidget(self.list_widget) self.add_btn.clicked.connect(self._on_add_clicked) @@ -270,7 +279,6 @@ class Scheduler(BECWidget, QWidget): run_row.addWidget(button) run_row.addStretch() control_layout.addLayout(run_row) - # layout.addLayout(run_row) self.run_btn.clicked.connect(self.run_schedule) self.abort_btn.clicked.connect(self.abort_schedule) @@ -288,7 +296,6 @@ class Scheduler(BECWidget, QWidget): settings_row.addWidget(self.guard_btn) settings_row.addStretch() settings_layout.addLayout(settings_row) - # layout.addLayout(settings_row) self.notifications_btn.clicked.connect(self._on_notifications_clicked) self.guard_btn.clicked.connect(self._on_guard_clicked) @@ -437,11 +444,26 @@ class Scheduler(BECWidget, QWidget): self.list_widget.clear() selected_row = None for row, item in enumerate(items): - text = f"{_STATUS_ICON.get(item.status, '?')} {item.command}" + + # text = f"{_STATUS_ICON.get(item.status, '?')} {item.command}" + + text = f"{item.command}" + + icon_name, color = _ICON_MAP[item.status] + icon = material_icon( + icon_name, size=(ICON_SIZE, ICON_SIZE), color=color, convert_to_pixmap=True + ) + # if item.status == ScheduleItemStatus.RUNNING: + # self._spin_anim.start() + # else: + # self._spin_anim.stop() + # self._label.setPixmap(icon) + if item.error: text += f" ({item.error.strip().splitlines()[-1]})" list_item = QListWidgetItem(text, self.list_widget) list_item.setData(_ITEM_ID_ROLE, item.item_id) + list_item.setIcon(icon) if item.item_id == self._selected_item_id: selected_row = row if selected_row is not None: @@ -450,32 +472,32 @@ class Scheduler(BECWidget, QWidget): self._selected_item_id = None self.list_widget.blockSignals(False) - idx = None - selected_item = None - if self._selected_item_id is not None: - for i, item in enumerate(items): - if item.item_id == self._selected_item_id: - idx, selected_item = i, item - break + # idx = None + # selected_item = None + # if self._selected_item_id is not None: + # for i, item in enumerate(items): + # if item.item_id == self._selected_item_id: + # idx, selected_item = i, item + # break - # Editable = the selected item hasn't started yet. Thanks to the - # protected-prefix invariant, everything after the first PENDING - # item is guaranteed PENDING too, so a plain index/status check is - # enough here - see module docstring. - can_edit_selected = ( - selected_item is not None and selected_item.status == ScheduleItemStatus.PENDING - ) + # # Editable = the selected item hasn't started yet. Thanks to the + # # protected-prefix invariant, everything after the first PENDING + # # item is guaranteed PENDING too, so a plain index/status check is + # # enough here - see module docstring. + # can_edit_selected = ( + # selected_item is not None and selected_item.status == ScheduleItemStatus.PENDING + # ) - self.run_btn.setEnabled(not is_running) - # Adding is always safe: new items are clamped into the PENDING - # suffix regardless of what's selected (see add_item()). - self.add_btn.setEnabled(True) - self.edit_btn.setEnabled(can_edit_selected) - self.delete_btn.setEnabled(can_edit_selected) - self.move_up_btn.setEnabled(can_edit_selected and idx not in (None, 0)) - self.move_down_btn.setEnabled( - can_edit_selected and idx is not None and idx < len(items) - 1 - ) + # self.run_btn.setEnabled(not is_running) + # # Adding is always safe: new items are clamped into the PENDING + # # suffix regardless of what's selected (see add_item()). + # self.add_btn.setEnabled(True) + # self.edit_btn.setEnabled(can_edit_selected) + # self.delete_btn.setEnabled(can_edit_selected) + # self.move_up_btn.setEnabled(can_edit_selected and idx not in (None, 0)) + # self.move_down_btn.setEnabled( + # can_edit_selected and idx is not None and idx < len(items) - 1 + # ) if self._guard.enabled: state = "OK" if self._guard.is_clear() else "PAUSED - waiting to resume" @@ -489,11 +511,39 @@ class Scheduler(BECWidget, QWidget): else: self.guard_status_label.hide() + def _update_buttons(self): + with self._lock: + items = list(self.schedule.items) + is_running = self.schedule.is_running + + idx = None + selected_item = None + + if self._selected_item_id is not None: + for i, item in enumerate(items): + if item.item_id == self._selected_item_id: + idx, selected_item = i, item + break + + can_edit_selected = ( + selected_item is not None and selected_item.status == ScheduleItemStatus.PENDING + ) + + self.run_btn.setEnabled(not is_running) + self.add_btn.setEnabled(True) + self.edit_btn.setEnabled(can_edit_selected) + self.delete_btn.setEnabled(can_edit_selected) + self.move_up_btn.setEnabled(can_edit_selected and idx not in (None, 0)) + self.move_down_btn.setEnabled( + can_edit_selected and idx is not None and idx < len(items) - 1 + ) + @SafeSlot() def _on_selection_changed(self, row: int): + logger.info("On selection changed") item = self.list_widget.item(row) if row >= 0 else None self._selected_item_id = item.data(_ITEM_ID_ROLE) if item is not None else None - self._refresh_ui() + self._update_buttons() @SafeSlot() def _on_empty_space_clicked(self): @@ -567,9 +617,10 @@ class Scheduler(BECWidget, QWidget): ) self._selected_item_id = new_id self._refresh_ui() + self._update_buttons() @SafeSlot() - def _on_edit_clicked(self): + def _on_edit_clicked(self, row=None): if self._selected_item_id is None: return with self._lock: @@ -583,6 +634,8 @@ class Scheduler(BECWidget, QWidget): if initial is None: return + logger.info(f"Initial: {initial}") + dialog = ScheduleItemDialog( self.scans, self.dev, parent=self, initial=initial, client=self.client ) From ac6b58197e99bf03374147248dab18ad64f6ebf1 Mon Sep 17 00:00:00 2001 From: x01da Date: Tue, 1 Sep 2026 15:37:36 +0200 Subject: [PATCH 04/56] wip --- .../widgets/scheduler/schedule_logic.py | 17 ++- .../widgets/scheduler/scheduler.py | 107 +++++++----------- 2 files changed, 54 insertions(+), 70 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/scheduler/schedule_logic.py b/debye_bec/bec_widgets/widgets/scheduler/schedule_logic.py index 29553d9..4073793 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/schedule_logic.py +++ b/debye_bec/bec_widgets/widgets/scheduler/schedule_logic.py @@ -18,8 +18,12 @@ from __future__ import annotations from typing import Literal +from bec_lib.logger import bec_logger + from .schedule_item import ScheduleItem, ScheduleItemStatus +logger = bec_logger.logger + def protected_prefix_length(items: list[ScheduleItem]) -> int: """How many items, from the start, are no longer PENDING.""" @@ -41,7 +45,9 @@ def index_of(items: list[ScheduleItem], item_id: str | None) -> int | None: return None -def pick_next_runnable(items: list[ScheduleItem]) -> ScheduleItem | Literal["stop"] | None: +def pick_next_runnable( + items: list[ScheduleItem], repeat_aborted_item +) -> ScheduleItem | Literal["stop"] | None: """ What the execution loop should do next: always re-derived from scratch (never a remembered index/object) so edits made to the PENDING suffix @@ -51,10 +57,15 @@ def pick_next_runnable(items: list[ScheduleItem]) -> ScheduleItem | Literal["sto earlier item failed/was aborted (execution stays parked there until the operator intervenes), or `None` if every item is COMPLETED. """ + logger.info(f"pick next runnable, repeat abort item is {repeat_aborted_item}") for item in items: + logger.info(f"item: {item}") if item.status == ScheduleItemStatus.COMPLETED: continue - if item.status in (ScheduleItemStatus.FAILED, ScheduleItemStatus.ABORTED): + if item.status == ScheduleItemStatus.ABORTED: + if not repeat_aborted_item: + continue + if item.status == ScheduleItemStatus.FAILED: return "stop" - return item # PENDING, or RUNNING (reconciled as still active) + return item # PENDING, RUNNING or ABORTED if repeat_aborted_item is set (reconciled as still active) return None diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index d7fdbe2..8caf677 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -64,21 +64,15 @@ DEFAULT_COMMANDS = [ _ACTIVE_QUEUE_STATES = ("PENDING", "RUNNING") _ITEM_ID_ROLE = Qt.UserRole + 1 # QListWidgetItem data role used to map a row back to an item_id -_STATUS_ICON = { - ScheduleItemStatus.PENDING: "\u23f3", # hourglass - ScheduleItemStatus.RUNNING: "\u25b6", # play - ScheduleItemStatus.COMPLETED: "\u2705", # check mark - ScheduleItemStatus.FAILED: "\u274c", # cross mark - ScheduleItemStatus.ABORTED: "\u23f9", # stop -} +# TODO: Colors should change when the item is selected, otherwise won't be readable ICON_SIZE = 20 _ICON_MAP = { ScheduleItemStatus.PENDING: ("hourglass", "#919090"), ScheduleItemStatus.RUNNING: ("cycle", "#2980b9"), ScheduleItemStatus.COMPLETED: ("check", "#27ae60"), ScheduleItemStatus.FAILED: ("warning", "#e74c3c"), - ScheduleItemStatus.ABORTED: ("cancel", "#e74c3c"), + ScheduleItemStatus.ABORTED: ("cancel", "#e6d922"), } @@ -224,6 +218,8 @@ class Scheduler(BECWidget, QWidget): # schedule (another instance of this widget, a script, ...). self.bec_dispatcher.connect_slot(self._on_remote_update, self._endpoint) + self._closing = threading.Event() + # ------------------------------------------------------------------ # # UI # ------------------------------------------------------------------ # @@ -378,8 +374,7 @@ class Scheduler(BECWidget, QWidget): # again shortly); accepting a wholesale replacement here # would orphan those objects. See module docstring. logger.info( - "Ignoring remote schedule update for '%s' while a local run is in progress.", - self.schedule_name, + f"Ignoring remote schedule update for {self.schedule_name} while a local run is in progress." ) return self.schedule = new_schedule @@ -438,27 +433,16 @@ class Scheduler(BECWidget, QWidget): def _refresh_ui(self): with self._lock: items = list(self.schedule.items) - is_running = self.schedule.is_running self.list_widget.blockSignals(True) self.list_widget.clear() selected_row = None for row, item in enumerate(items): - - # text = f"{_STATUS_ICON.get(item.status, '?')} {item.command}" - text = f"{item.command}" - icon_name, color = _ICON_MAP[item.status] icon = material_icon( icon_name, size=(ICON_SIZE, ICON_SIZE), color=color, convert_to_pixmap=True ) - # if item.status == ScheduleItemStatus.RUNNING: - # self._spin_anim.start() - # else: - # self._spin_anim.stop() - # self._label.setPixmap(icon) - if item.error: text += f" ({item.error.strip().splitlines()[-1]})" list_item = QListWidgetItem(text, self.list_widget) @@ -472,33 +456,6 @@ class Scheduler(BECWidget, QWidget): self._selected_item_id = None self.list_widget.blockSignals(False) - # idx = None - # selected_item = None - # if self._selected_item_id is not None: - # for i, item in enumerate(items): - # if item.item_id == self._selected_item_id: - # idx, selected_item = i, item - # break - - # # Editable = the selected item hasn't started yet. Thanks to the - # # protected-prefix invariant, everything after the first PENDING - # # item is guaranteed PENDING too, so a plain index/status check is - # # enough here - see module docstring. - # can_edit_selected = ( - # selected_item is not None and selected_item.status == ScheduleItemStatus.PENDING - # ) - - # self.run_btn.setEnabled(not is_running) - # # Adding is always safe: new items are clamped into the PENDING - # # suffix regardless of what's selected (see add_item()). - # self.add_btn.setEnabled(True) - # self.edit_btn.setEnabled(can_edit_selected) - # self.delete_btn.setEnabled(can_edit_selected) - # self.move_up_btn.setEnabled(can_edit_selected and idx not in (None, 0)) - # self.move_down_btn.setEnabled( - # can_edit_selected and idx is not None and idx < len(items) - 1 - # ) - if self._guard.enabled: state = "OK" if self._guard.is_clear() else "PAUSED - waiting to resume" value = self._guard.current_value @@ -540,7 +497,6 @@ class Scheduler(BECWidget, QWidget): @SafeSlot() def _on_selection_changed(self, row: int): - logger.info("On selection changed") item = self.list_widget.item(row) if row >= 0 else None self._selected_item_id = item.data(_ITEM_ID_ROLE) if item is not None else None self._update_buttons() @@ -695,12 +651,26 @@ class Scheduler(BECWidget, QWidget): with self._lock: if self.schedule.is_running: return + repeat_aborted_item = False + if any(item.status == ScheduleItemStatus.ABORTED for item in self.schedule.items): + repeat_aborted_item = ( + QMessageBox.question( + self, + "Repeat aborted scan", + "Would you like to repeat the aborted scan?", + QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, + ) + == QMessageBox.StandardButton.Yes + ) self._abort_requested = False self.schedule.is_running = True self._persist_locked() self.schedule_changed.emit() self.submit_task( - self._run_all, on_complete=self._on_run_finished, on_failed=self._on_run_failed + self._run_all, + repeat_aborted_item, + on_complete=self._on_run_finished, + on_failed=self._on_run_failed, ) @SafeSlot() @@ -869,16 +839,16 @@ class Scheduler(BECWidget, QWidget): # the `schedule_changed` Qt signal so they are marshalled back onto # the GUI thread instead of touching widgets directly) # ------------------------------------------------------------------ # - def _pick_next_runnable_locked(self): + def _pick_next_runnable_locked(self, repeat_aborted_item): """Must be called while holding `self._lock`; see `schedule_logic.pick_next_runnable`.""" - return pick_next_runnable(self.schedule.items) + return pick_next_runnable(self.schedule.items, repeat_aborted_item) - def _run_all(self): + def _run_all(self, repeat_aborted_item): logger.info("_run_all was called") namespace = {"scans": self.scans, "dev": self.dev} while not self._abort_requested: with self._lock: - next_item = self._pick_next_runnable_locked() + next_item = self._pick_next_runnable_locked(repeat_aborted_item) if next_item is None or next_item == "stop": logger.info("Next item is None or stop") break @@ -891,7 +861,7 @@ class Scheduler(BECWidget, QWidget): logger.info("in _run_all, set is_running to false") self.schedule.is_running = False self._persist_locked() - self.schedule_changed.emit() + self._emit_schedule_changed() def _execute_item(self, item: ScheduleItem, namespace: dict): if item.kind == "scan": @@ -899,7 +869,7 @@ class Scheduler(BECWidget, QWidget): # the guard is clear or the operator aborts. See "Guard # interaction" in the module docstring. cleared = self._guard.wait_until_clear(should_abort=lambda: self._abort_requested) - self.schedule_changed.emit() + self._emit_schedule_changed() if not cleared: return @@ -908,7 +878,7 @@ class Scheduler(BECWidget, QWidget): item.error = None item.started_at = time.time() self._persist_locked() - self.schedule_changed.emit() + self._emit_schedule_changed() try: report = eval( @@ -964,7 +934,7 @@ class Scheduler(BECWidget, QWidget): final_status = item.status self._current_report = None self._current_item_kind = None - self.schedule_changed.emit() + self._emit_schedule_changed() if final_status in (ScheduleItemStatus.COMPLETED, ScheduleItemStatus.FAILED): notify_item_finished( @@ -986,7 +956,7 @@ class Scheduler(BECWidget, QWidget): item.status = ScheduleItemStatus.COMPLETED item.finished_at = time.time() self._persist_locked() - self.schedule_changed.emit() + self._emit_schedule_changed() return time.sleep(0.5) @@ -1002,13 +972,16 @@ class Scheduler(BECWidget, QWidget): self._persist_locked() self._refresh_ui() - # ------------------------------------------------------------------ # - # cleanup - # ------------------------------------------------------------------ # + def _emit_schedule_changed(self): + if self._closing.is_set(): + return + + self.schedule_changed.emit() + def cleanup(self): - # Note: we deliberately do NOT abort a running schedule here. The - # whole point of the Redis-backed design is that closing this - # widget must not interrupt anything already submitted to the - # scan/device server - see the module docstring. + # The schedule itself must continue running after the widget is closed. + # We only tell the worker that the UI/Qt object is no longer available. + self._closing.set() + self._guard.cleanup() - super().cleanup() # also disconnects all bec_dispatcher subscriptions for us + super().cleanup() From 851ec945cee3cdceef795de241ad79a1b57a2562 Mon Sep 17 00:00:00 2001 From: x01da Date: Tue, 1 Sep 2026 15:39:48 +0200 Subject: [PATCH 05/56] wip --- .../widgets/scheduler/scheduler.py | 121 +++++++++++------- 1 file changed, 72 insertions(+), 49 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 8caf677..6a247bc 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -843,10 +843,42 @@ class Scheduler(BECWidget, QWidget): """Must be called while holding `self._lock`; see `schedule_logic.pick_next_runnable`.""" return pick_next_runnable(self.schedule.items, repeat_aborted_item) + @SafeSlot() + def _on_run_finished(self): + self._refresh_ui() + + @SafeSlot(str) + def _on_run_failed(self, error: str): + logger.error(f"Schedule execution task failed unexpectedly: {error}") + with self._lock: + self.schedule.is_running = False + self._persist_locked() + self._refresh_ui() + + def _emit_schedule_changed(self): + if self._closing.is_set(): + return + + self.schedule_changed.emit() + + def closeEvent(self, event): + """Ensure cleanup is invoked when the widget is closed via the window system.""" + self.cleanup() + super().closeEvent(event) + + def cleanup(self): + """Stop background execution loops without cancelling server-side scans.""" + self._closing.set() + + # Interrupt guard wait loops if any thread is blocked in self._guard.wait_until_clear() + self._guard.cleanup() + + super().cleanup() + def _run_all(self, repeat_aborted_item): logger.info("_run_all was called") namespace = {"scans": self.scans, "dev": self.dev} - while not self._abort_requested: + while not self._abort_requested and not self._closing.is_set(): with self._lock: next_item = self._pick_next_runnable_locked(repeat_aborted_item) if next_item is None or next_item == "stop": @@ -865,12 +897,12 @@ class Scheduler(BECWidget, QWidget): def _execute_item(self, item: ScheduleItem, namespace: dict): if item.kind == "scan": - # Block here (item stays PENDING - nothing "started" yet) until - # the guard is clear or the operator aborts. See "Guard - # interaction" in the module docstring. - cleared = self._guard.wait_until_clear(should_abort=lambda: self._abort_requested) + # Block here until the guard is clear, operator aborts, or widget closes + cleared = self._guard.wait_until_clear( + should_abort=lambda: self._abort_requested or self._closing.is_set() + ) self._emit_schedule_changed() - if not cleared: + if not cleared or self._closing.is_set(): return with self._lock: @@ -890,12 +922,15 @@ class Scheduler(BECWidget, QWidget): request = getattr(report, "request", None) with self._lock: item.request_id = getattr(request, "requestID", None) - # persist the request_id right away, before the - # (potentially long) wait below, so a reconnect can find - # it even if this process disappears mid-scan. self._persist_locked() - report.wait() + # Wait for completion without blocking the thread indefinitely + self._wait_for_report(report) + + if self._closing.is_set(): + # The widget was closed mid-item; exit without changing status in Redis. + # Reconciliation logic will handle state on reopen. + return scan = getattr(report, "scan", None) with self._lock: @@ -907,12 +942,10 @@ class Scheduler(BECWidget, QWidget): else ScheduleItemStatus.COMPLETED ) except Exception: # pylint: disable=broad-except + if self._closing.is_set(): + return with self._lock: if self._guard_interrupt_requested: - # Interrupted by the auto-pause guard, not a real - # failure/operator abort - reset to PENDING so the - # normal execution loop retries it once the guard - # clears, instead of leaving it in a terminal state. item.status = ScheduleItemStatus.PENDING item.request_id = None item.scan_id = None @@ -927,14 +960,17 @@ class Scheduler(BECWidget, QWidget): item.error = traceback.format_exc() logger.error(f"Schedule item failed: {item.command}\n{item.error}") finally: - with self._lock: - if item.status != ScheduleItemStatus.PENDING: - item.finished_at = time.time() - self._persist_locked() - final_status = item.status - self._current_report = None - self._current_item_kind = None - self._emit_schedule_changed() + if not self._closing.is_set(): + with self._lock: + if item.status != ScheduleItemStatus.PENDING: + item.finished_at = time.time() + self._persist_locked() + final_status = item.status + self._current_report = None + self._current_item_kind = None + self._emit_schedule_changed() + else: + final_status = None if final_status in (ScheduleItemStatus.COMPLETED, ScheduleItemStatus.FAILED): notify_item_finished( @@ -947,9 +983,22 @@ class Scheduler(BECWidget, QWidget): error=item.error, ) + def _wait_for_report(self, report, timeout: float = 0.5): + """Poll report status to allow thread exit if the widget closes.""" + while not self._closing.is_set() and not self._abort_requested: + # Check if scan report has finished via its internal event or status + if ( + getattr(report, "status", None) == "completed" + or getattr(report, "event", None) + and report.event.is_set() + ): + break + # Non-blocking poll interval + time.sleep(timeout) + def _await_running_item(self, item: ScheduleItem): queue_storage = self.client.queue.queue_storage - while not self._abort_requested: + while not self._abort_requested and not self._closing.is_set(): queue_item = queue_storage.find_queue_item_by_requestID(item.request_id) if queue_item is None or not self._is_queue_item_active(queue_item): with self._lock: @@ -959,29 +1008,3 @@ class Scheduler(BECWidget, QWidget): self._emit_schedule_changed() return time.sleep(0.5) - - @SafeSlot() - def _on_run_finished(self): - self._refresh_ui() - - @SafeSlot(str) - def _on_run_failed(self, error: str): - logger.error(f"Schedule execution task failed unexpectedly: {error}") - with self._lock: - self.schedule.is_running = False - self._persist_locked() - self._refresh_ui() - - def _emit_schedule_changed(self): - if self._closing.is_set(): - return - - self.schedule_changed.emit() - - def cleanup(self): - # The schedule itself must continue running after the widget is closed. - # We only tell the worker that the UI/Qt object is no longer available. - self._closing.set() - - self._guard.cleanup() - super().cleanup() From 02205b43c55dcbb5f103abc961cd412cacf0fe4f Mon Sep 17 00:00:00 2001 From: x01da Date: Wed, 2 Sep 2026 08:10:16 +0200 Subject: [PATCH 06/56] wip --- .../widgets/scheduler/item_dialog.py | 27 +- .../widgets/scheduler/schedule_item.py | 1 + .../widgets/scheduler/scheduler.py | 246 +++++++++++++++++- 3 files changed, 267 insertions(+), 7 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index 7aaf895..69c4942 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -26,6 +26,8 @@ can reopen the dialog pre-filled instead of asking the user to start over. from __future__ import annotations +import math + from bec_lib.logger import bec_logger from bec_widgets.widgets.control.device_input.device_combobox.device_combobox import ( BECDeviceFilter, @@ -146,24 +148,37 @@ class ScheduleItemDialog(QDialog): form = QFormLayout(tab) form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) - # self.move_device_combo = QComboBox() - # self.move_device_combo.addItems(list_movable_device_names(self._dev)) - # self.move_device_combo.setMaxVisibleItems(12) - self.move_device_combo = DeviceComboBox(self, device_filter=[BECDeviceFilter.POSITIONER]) form.addRow("Device", self.move_device_combo) self.move_value_spin = QDoubleSpinBox() - self.move_value_spin.setDecimals(6) - self.move_value_spin.setRange(*_DSPIN_RANGE) form.addRow("Value", self.move_value_spin) self.move_relative_check = QCheckBox("") form.addRow("Relative move", self.move_relative_check) + self.move_device_combo.currentIndexChanged.connect(self._adjust_spinbox) + self.tabs.addTab(tab, "Move") + def _adjust_spinbox(self, _) -> None: + prec = self._dev[self.move_device_combo.currentText()].precision + units = self._dev[self.move_device_combo.currentText()].egu() + ll = self._dev[self.move_device_combo.currentText()].low_limit + hl = self._dev[self.move_device_combo.currentText()].high_limit + + self.move_value_spin.setDecimals(prec) + self.move_value_spin.setSuffix(f" {units}") + if (hl - ll) > 0: + self.move_value_spin.setMinimum(ll) + self.move_value_spin.setMaximum(hl) + self.move_value_spin.setSingleStep(10 ** round(math.log10((hl - ll) / 100))) + else: + self.move_value_spin.setMinimum(1e6) + self.move_value_spin.setMaximum(-1e6) + self.move_value_spin.setSingleStep(1) + def _collect_move_result(self) -> dict: device_name = self.move_device_combo.currentText() if not device_name: diff --git a/debye_bec/bec_widgets/widgets/scheduler/schedule_item.py b/debye_bec/bec_widgets/widgets/scheduler/schedule_item.py index 872b2a5..74cb2e0 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/schedule_item.py +++ b/debye_bec/bec_widgets/widgets/scheduler/schedule_item.py @@ -67,6 +67,7 @@ class Schedule(BaseModel): schedule_name: str items: list[ScheduleItem] = Field(default_factory=list) is_running: bool = False + notes: str = "" # Settings for two independent, optional features (see notifications.py # and guard.py) - persisted here alongside the schedule itself so they diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 6a247bc..cf7385c 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -9,6 +9,7 @@ or finished cannot. from __future__ import annotations +import json import threading import time import traceback @@ -24,17 +25,20 @@ from bec_widgets.utils.bec_connector import ConnectionConfig from bec_widgets.utils.bec_widget import BECWidget from bec_widgets.utils.colors import get_accent_colors from bec_widgets.utils.error_popups import SafeSlot -from qtpy.QtCore import Qt, Signal +from pydantic import ValidationError +from qtpy.QtCore import Qt, QTimer, Signal from qtpy.QtGui import QKeySequence, QShortcut from qtpy.QtWidgets import ( QApplication, QDialog, + QFileDialog, QGroupBox, QHBoxLayout, QLabel, QListWidget, QListWidgetItem, QMessageBox, + QPlainTextEdit, QPushButton, QVBoxLayout, QWidget, @@ -100,6 +104,8 @@ class ScheduleWidgetConfig(ConnectionConfig): class MyListWidget(QListWidget): deletePressed = Signal() emptySpaceClicked = Signal() + copyPressed = Signal() + pastePressed = Signal() def keyPressEvent(self, event): if event.key() == Qt.Key_Delete and self.currentItem() is not None: @@ -107,6 +113,16 @@ class MyListWidget(QListWidget): event.accept() return + if event.matches(QKeySequence.StandardKey.Copy) and self.currentItem() is not None: + self.copyPressed.emit() + event.accept() + return + + if event.matches(QKeySequence.StandardKey.Paste): + self.pastePressed.emit() + event.accept() + return + super().keyPressEvent(event) def mousePressEvent(self, event): @@ -200,6 +216,14 @@ class Scheduler(BECWidget, QWidget): self._current_report = None # ScanReport of the item currently executing, if any self._current_item_kind: str | None = None # kind of the item _current_report belongs to self._selected_item_id: str | None = None # survives list repopulation on refresh + self._clipboard_item: dict | None = None # copy/paste buffer, see _on_copy_clicked + + # Notes are auto-saved on a debounce timer rather than on every + # keystroke - see _on_notes_changed/_persist_notes. + self._notes_save_timer = QTimer(self) + self._notes_save_timer.setSingleShot(True) + self._notes_save_timer.setInterval(600) + self._notes_save_timer.timeout.connect(self._persist_notes) self.schedule_changed.connect(self._refresh_ui) @@ -235,12 +259,16 @@ class Scheduler(BECWidget, QWidget): self.delete_btn = MyButton("Delete", "default") self.move_up_btn = MyButton("Move Up", "default") self.move_down_btn = MyButton("Move Down", "default") + self.copy_btn = MyButton("Copy", "default") + self.paste_btn = MyButton("Paste", "default") for button in ( self.add_btn, self.edit_btn, self.delete_btn, self.move_up_btn, self.move_down_btn, + self.copy_btn, + self.paste_btn, ): edit_row.addWidget(button) edit_row.addStretch() @@ -253,14 +281,26 @@ class Scheduler(BECWidget, QWidget): self.list_widget.deletePressed.connect(self._on_delete_clicked) self.list_widget.emptySpaceClicked.connect(self._on_empty_space_clicked) self.list_widget.itemDoubleClicked.connect(self._on_edit_clicked) + self.list_widget.copyPressed.connect(self._on_copy_clicked) + self.list_widget.pastePressed.connect(self._on_paste_clicked) schedule_layout.addWidget(self.list_widget) + schedule_layout.addWidget(QLabel("Notes")) + self.notes_edit = QPlainTextEdit() + self.notes_edit.setPlaceholderText("Notes about this schedule...") + self.notes_edit.setPlainText(self.schedule.notes) + self.notes_edit.setMaximumHeight(100) + self.notes_edit.textChanged.connect(self._on_notes_changed) + schedule_layout.addWidget(self.notes_edit) + self.add_btn.clicked.connect(self._on_add_clicked) self.edit_btn.clicked.connect(self._on_edit_clicked) self.delete_btn.clicked.connect(self._on_delete_clicked) self.move_up_btn.clicked.connect(self._on_move_up_clicked) self.move_down_btn.clicked.connect(self._on_move_down_clicked) + self.copy_btn.clicked.connect(self._on_copy_clicked) + self.paste_btn.clicked.connect(self._on_paste_clicked) layout.addWidget(schedule_group) @@ -298,6 +338,19 @@ class Scheduler(BECWidget, QWidget): layout.addWidget(settings_group) + file_group = QGroupBox("File") + file_layout = QHBoxLayout(file_group) + self.save_file_btn = MyButton("Save to file", "default") + self.load_file_btn = MyButton("Load from file", "default") + file_layout.addWidget(self.save_file_btn) + file_layout.addWidget(self.load_file_btn) + file_layout.addStretch() + + self.save_file_btn.clicked.connect(self._on_save_to_file_clicked) + self.load_file_btn.clicked.connect(self._on_load_from_file_clicked) + + layout.addWidget(file_group) + self.guard_status_label = QLabel() self.guard_status_label.setStyleSheet("color: gray;") layout.addWidget(self.guard_status_label) @@ -321,11 +374,15 @@ class Scheduler(BECWidget, QWidget): self.delete_btn, self.move_down_btn, self.move_up_btn, + self.copy_btn, + self.paste_btn, self.run_btn, self.abort_btn, self.reset_btn, self.notifications_btn, self.guard_btn, + self.save_file_btn, + self.load_file_btn, ]: button.apply_theme() @@ -433,6 +490,7 @@ class Scheduler(BECWidget, QWidget): def _refresh_ui(self): with self._lock: items = list(self.schedule.items) + notes = self.schedule.notes self.list_widget.blockSignals(True) self.list_widget.clear() @@ -456,6 +514,15 @@ class Scheduler(BECWidget, QWidget): self._selected_item_id = None self.list_widget.blockSignals(False) + # Don't stomp on notes the operator is actively typing (e.g. a + # remote update, or our own debounce timer firing right after + # local edits) - only resync when the field isn't focused and the + # text actually differs from what we already have. + if not self.notes_edit.hasFocus() and self.notes_edit.toPlainText() != notes: + self.notes_edit.blockSignals(True) + self.notes_edit.setPlainText(notes) + self.notes_edit.blockSignals(False) + if self._guard.enabled: state = "OK" if self._guard.is_clear() else "PAUSED - waiting to resume" value = self._guard.current_value @@ -494,6 +561,12 @@ class Scheduler(BECWidget, QWidget): self.move_down_btn.setEnabled( can_edit_selected and idx is not None and idx < len(items) - 1 ) + # Copy just captures the command text, so it's fine on any item + # (e.g. copying a COMPLETED item's command to reuse it later). + # Paste always goes through add_item(), which already clamps the + # insert position past the protected prefix - see _on_paste_clicked. + self.copy_btn.setEnabled(selected_item is not None) + self.paste_btn.setEnabled(self._clipboard_item is not None) @SafeSlot() def _on_selection_changed(self, row: int): @@ -506,6 +579,122 @@ class Scheduler(BECWidget, QWidget): self.list_widget.setCurrentRow(-1) self._refresh_ui() + # ---- notes ---- # + def _on_notes_changed(self): + # Debounced: restart the timer on every keystroke, only persist + # once typing pauses, so we're not writing to Redis on every + # character. + self._notes_save_timer.start() + + def _persist_notes(self): + text = self.notes_edit.toPlainText() + with self._lock: + if self.schedule.notes == text: + return + self.schedule.notes = text + self._persist_locked() + + # ---- save / restore to file ---- # + @SafeSlot() + def _on_save_to_file_clicked(self): + with self._lock: + data = self.schedule.model_dump(mode="json") + default_name = f"{self.schedule_name}.json" + path, _ = QFileDialog.getSaveFileName( + self, "Save schedule to file", default_name, "JSON files (*.json);;All files (*)" + ) + if not path: + return + try: + with open(path, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2) + except OSError as exc: + QMessageBox.critical(self, "Save failed", f"Could not write to {path}:\n{exc}") + return + logger.info(f"Saved schedule '{self.schedule_name}' to {path}") + + @SafeSlot() + def _on_load_from_file_clicked(self): + with self._lock: + if self.schedule.is_running: + QMessageBox.warning( + self, + "Cannot load", + "Stop the running schedule (Abort) before loading a new one from file.", + ) + return + + path, _ = QFileDialog.getOpenFileName( + self, "Load schedule from file", "", "JSON files (*.json);;All files (*)" + ) + if not path: + return + + try: + with open(path, encoding="utf-8") as f: + data = json.load(f) + loaded = Schedule.model_validate(data) + except (OSError, json.JSONDecodeError, ValidationError) as exc: + QMessageBox.critical( + self, "Load failed", f"Could not load a schedule from {path}:\n{exc}" + ) + return + + with self._lock: + current_count = len(self.schedule.items) + confirm = QMessageBox.question( + self, + "Load schedule", + f"Replace the current {current_count} item(s) with {len(loaded.items)} " + f"item(s) from the file?\n\nAll items will be loaded as PENDING, regardless " + f"of their status when the file was saved.", + ) + if confirm != QMessageBox.StandardButton.Yes: + return + + # Loading a file restores a *definition* (what to run), not a past + # execution: every item comes back PENDING with a fresh item_id and + # its execution bookkeeping cleared, and is_running is always + # forced False here - regardless of what the file says - so we + # never end up "reconciling" against request/scan ids from a + # different session. schedule_name is deliberately left as this + # widget's own name, not overwritten by the file's. + new_items = [ + item.model_copy( + update={ + "item_id": str(uuid.uuid4()), + "status": ScheduleItemStatus.PENDING, + "request_id": None, + "scan_id": None, + "scan_number": None, + "error": None, + "started_at": None, + "finished_at": None, + } + ) + for item in loaded.items + ] + + with self._lock: + if self.schedule.is_running: + QMessageBox.warning( + self, "Cannot load", "The schedule started running while the dialog was open." + ) + return + self.schedule.items = new_items + self.schedule.notes = loaded.notes + self.schedule.guard = loaded.guard + self.schedule.notifications = loaded.notifications + self._persist_locked() + + self._guard.configure(self.schedule.guard) + self._selected_item_id = None + logger.info( + f"Loaded schedule from {path} ({len(new_items)} item(s)) into '{self.schedule_name}'" + ) + self._refresh_ui() + self._update_buttons() + # ---- notifications / auto-pause settings ---- # @SafeSlot() def _on_notifications_clicked(self): @@ -642,6 +831,55 @@ class Scheduler(BECWidget, QWidget): except RuntimeError as exc: QMessageBox.warning(self, "Cannot move item", str(exc)) + @SafeSlot() + def _on_copy_clicked(self): + """ + Copy the selected item's command onto an internal clipboard. Only + the command/kind/form_state are captured (not status, timestamps, + request/scan ids, ...) since pasting always creates a fresh, + PENDING item - this is "copy the command", not "duplicate the + history". + """ + if self._selected_item_id is None: + return + with self._lock: + idx = self._index_of_locked(self._selected_item_id) + if idx is None: + return + item = self.schedule.items[idx] + self._clipboard_item = { + "command": item.command, + "kind": item.kind, + "form_state": dict(item.form_state) if item.form_state else None, + } + logger.info(f"Copied schedule item: {self._clipboard_item['command']}") + self._update_buttons() + + @SafeSlot() + def _on_paste_clicked(self): + """ + Paste the copied command as a new item, right after whatever is + currently selected (or at the end, if nothing is selected) - same + placement `_on_add_clicked` uses. This goes through `add_item()` + unchanged, so the existing protected-prefix clamping applies here + too: pasting can never land before an item that's already + running or finished. + """ + if self._clipboard_item is None: + return + with self._lock: + idx = self._index_of_locked(self._selected_item_id) + insert_at = None if idx is None else idx + 1 + new_id = self.add_item( + self._clipboard_item["command"], + index=insert_at, + kind=self._clipboard_item["kind"], + form_state=self._clipboard_item["form_state"], + ) + self._selected_item_id = new_id + self._refresh_ui() + self._update_buttons() + # ------------------------------------------------------------------ # # RPC-exposed actions (USER_ACCESS) # ------------------------------------------------------------------ # @@ -870,6 +1108,12 @@ class Scheduler(BECWidget, QWidget): """Stop background execution loops without cancelling server-side scans.""" self._closing.set() + # Flush any not-yet-saved notes edit instead of losing it - the + # debounce timer won't get a chance to fire once we're closing. + if self._notes_save_timer.isActive(): + self._notes_save_timer.stop() + self._persist_notes() + # Interrupt guard wait loops if any thread is blocked in self._guard.wait_until_clear() self._guard.cleanup() From ed181938095e1d2e5db21c825c0a79cec2a05de2 Mon Sep 17 00:00:00 2001 From: x01da Date: Wed, 2 Sep 2026 09:40:20 +0200 Subject: [PATCH 07/56] wip --- debye_bec/bec_widgets/widgets/client.py | 1 + .../bec_widgets/widgets/designer_plugins.py | 2 + .../bec_widgets/widgets/scheduler/guard.py | 38 +++++- .../widgets/scheduler/scheduler.py | 114 ++++++++---------- 4 files changed, 83 insertions(+), 72 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/client.py b/debye_bec/bec_widgets/widgets/client.py index 0fc46e6..94aa2c0 100644 --- a/debye_bec/bec_widgets/widgets/client.py +++ b/debye_bec/bec_widgets/widgets/client.py @@ -17,6 +17,7 @@ _Widgets = { "DigitalTwin": "DigitalTwin", "RestartServer": "RestartServer", "ScanControlXAS": "ScanControlXAS", + "Scheduler": "Scheduler", } diff --git a/debye_bec/bec_widgets/widgets/designer_plugins.py b/debye_bec/bec_widgets/widgets/designer_plugins.py index 77ddd10..aaf7251 100644 --- a/debye_bec/bec_widgets/widgets/designer_plugins.py +++ b/debye_bec/bec_widgets/widgets/designer_plugins.py @@ -15,6 +15,7 @@ designer_plugins = { "debye_bec.bec_widgets.widgets.scan_control_xas.scan_control_xas", "ScanControlXAS", ), + "Scheduler": ("debye_bec.bec_widgets.widgets.scheduler.scheduler", "Scheduler"), } widget_icons = { @@ -22,4 +23,5 @@ widget_icons = { "DigitalTwin": "lightbulb", "RestartServer": "restart_alt", "ScanControlXAS": "tune", + "Scheduler": "assignment_add", } diff --git a/debye_bec/bec_widgets/widgets/scheduler/guard.py b/debye_bec/bec_widgets/widgets/scheduler/guard.py index 5fd69d5..2f0dd11 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/guard.py +++ b/debye_bec/bec_widgets/widgets/scheduler/guard.py @@ -15,6 +15,7 @@ only place that connects those signals to schedule-specific behavior from __future__ import annotations import threading +import time from bec_lib.endpoints import MessageEndpoints from bec_lib.logger import bec_logger @@ -23,6 +24,8 @@ from qtpy.QtCore import QObject, Signal logger = bec_logger.logger +MIN_UPDATE_INTERVAL = 1 + class GuardSettings(BaseModel): """Persisted configuration for one `SignalGuard`.""" @@ -54,11 +57,13 @@ class SignalGuard(QObject): on - no extra locking needed on the receiving end. """ + value_update = Signal(float) paused = Signal(float) resumed = Signal(float) - def __init__(self, connector, parent=None): + def __init__(self, connector, parent=None, dev=None): super().__init__(parent) + self.dev = dev self._connector = connector self._lock = threading.Lock() self._clear_event = threading.Event() @@ -69,9 +74,13 @@ class SignalGuard(QObject): self.pause_below: float | None = None self.resume_above: float | None = None self.current_value: float | None = None + self.units: str = "" + self.prec: int = 3 self._subscribed_endpoint = None + self.last_val_update = time.time() + def configure(self, settings: GuardSettings): """(Re)configure and (re)subscribe. Safe to call repeatedly, e.g. after editing settings.""" self._unsubscribe() @@ -83,16 +92,26 @@ class SignalGuard(QObject): self.current_value = None self._clear_event.set() - if self.enabled and self.device_name and self.pause_below is not None and self.resume_above is not None: + if ( + self.enabled + and self.device_name + and self.pause_below is not None + and self.resume_above is not None + ): self._subscribed_endpoint = MessageEndpoints.device_readback(self.device_name) self._connector.register(topics=self._subscribed_endpoint, cb=self._on_readback) + description = self.dev[self.device_name].describe()[self.device_name] + self.units = description["units"] + self.prec = description["precision"] def _unsubscribe(self): if self._subscribed_endpoint is not None: try: self._connector.unregister(topics=self._subscribed_endpoint, cb=self._on_readback) except Exception: # pylint: disable=broad-except - logger.exception("Failed to unsubscribe SignalGuard from %s", self._subscribed_endpoint) + logger.exception( + f"Failed to unsubscribe SignalGuard from {self._subscribed_endpoint}" + ) self._subscribed_endpoint = None def _on_readback(self, msg): @@ -115,12 +134,21 @@ class SignalGuard(QObject): crossed_resume = True if crossed_pause: - logger.info("SignalGuard: %s dropped to %s (below %s) - pausing.", self.device_name, value, self.pause_below) + logger.info( + f"SignalGuard: {self.device_name} dropped to {value} (below {self.pause_below}) - pausing." + ) self.paused.emit(value) elif crossed_resume: - logger.info("SignalGuard: %s recovered to %s (above %s) - resuming.", self.device_name, value, self.resume_above) + logger.info( + f"SignalGuard: {self.device_name} recovered to {value} (above {self.resume_above}) - resuming." + ) self.resumed.emit(value) + current_time = time.time() + if current_time - self.last_val_update > MIN_UPDATE_INTERVAL: + self.last_val_update = current_time + self.value_update.emit(value) + def is_clear(self) -> bool: """True if not currently blocking (disabled, or value above the resume threshold).""" return (not self.enabled) or self._clear_event.is_set() diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index cf7385c..0b44652 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -20,14 +20,15 @@ from bec_lib.endpoints import MessageEndpoints from bec_lib.logger import bec_logger from bec_lib.messages import VariableMessage from bec_qthemes import material_icon -from bec_qthemes._theme import AccentColors from bec_widgets.utils.bec_connector import ConnectionConfig from bec_widgets.utils.bec_widget import BECWidget from bec_widgets.utils.colors import get_accent_colors from bec_widgets.utils.error_popups import SafeSlot from pydantic import ValidationError + +# pylint: disable=E0611 from qtpy.QtCore import Qt, QTimer, Signal -from qtpy.QtGui import QKeySequence, QShortcut +from qtpy.QtGui import QKeySequence from qtpy.QtWidgets import ( QApplication, QDialog, @@ -45,7 +46,7 @@ from qtpy.QtWidgets import ( ) from .endpoints import schedule as schedule_endpoint -from .guard import GuardSettings, SignalGuard +from .guard import SignalGuard from .guard_dialog import GuardSettingsDialog from .item_dialog import ScheduleItemDialog from .notification_dialog import NotificationSettingsDialog @@ -55,21 +56,9 @@ from .schedule_logic import index_of, pick_next_runnable, protected_prefix_lengt logger = bec_logger.logger -# The static, hard-coded example schedule requested for this plugin. A -# real deployment would more likely let the user build this list purely -# through the UI - the persistence/execution/reconciliation logic below -# does not care where the commands came from. -DEFAULT_COMMANDS = [ - "scans.xas_simple_scan(12000, 14000, 2, 10)", - "dev.samx.move(12.3, relative=True)", - "scans.xas_simple_scan(13000, 17000, 1, 60)", -] - _ACTIVE_QUEUE_STATES = ("PENDING", "RUNNING") _ITEM_ID_ROLE = Qt.UserRole + 1 # QListWidgetItem data role used to map a row back to an item_id - -# TODO: Colors should change when the item is selected, otherwise won't be readable ICON_SIZE = 20 _ICON_MAP = { ScheduleItemStatus.PENDING: ("hourglass", "#919090"), @@ -158,7 +147,7 @@ class MyButton(QPushButton): class Scheduler(BECWidget, QWidget): """Schedule, persist and execute a sequence of BEC scan/device commands.""" - # BUG: Icon is not recognized, also no entry is created in designer_plugins.py + PLUGIN = True ICON_NAME = "assignment_add" USER_ACCESS = [ "run_schedule", @@ -222,7 +211,7 @@ class Scheduler(BECWidget, QWidget): # keystroke - see _on_notes_changed/_persist_notes. self._notes_save_timer = QTimer(self) self._notes_save_timer.setSingleShot(True) - self._notes_save_timer.setInterval(600) + self._notes_save_timer.setInterval(200) self._notes_save_timer.timeout.connect(self._persist_notes) self.schedule_changed.connect(self._refresh_ui) @@ -230,9 +219,10 @@ class Scheduler(BECWidget, QWidget): self.schedule: Schedule = self._load_or_seed_schedule() self._reconcile_with_live_state() - self._guard = SignalGuard(self.connector, parent=self) + self._guard = SignalGuard(self.connector, parent=self, dev=self.dev) self._guard.paused.connect(self._on_guard_paused) self._guard.resumed.connect(self._on_guard_resumed) + self._guard.value_update.connect(self._update_guard_label) self._guard.configure(self.schedule.guard) self._build_ui() @@ -325,13 +315,18 @@ class Scheduler(BECWidget, QWidget): settings_group = QGroupBox("Settings") settings_layout = QVBoxLayout(settings_group) - settings_row = QHBoxLayout() - self.notifications_btn = MyButton("Notifications", "default") + guard_row = QHBoxLayout() self.guard_btn = MyButton("Auto-pause", "default") - settings_row.addWidget(self.notifications_btn) - settings_row.addWidget(self.guard_btn) - settings_row.addStretch() - settings_layout.addLayout(settings_row) + self.guard_status_label = QLabel() + guard_row.addWidget(self.guard_btn) + guard_row.addWidget(self.guard_status_label) + guard_row.addStretch() + notifications_row = QHBoxLayout() + self.notifications_btn = MyButton("Notifications", "default") + notifications_row.addWidget(self.notifications_btn) + notifications_row.addStretch() + settings_layout.addLayout(guard_row) + settings_layout.addLayout(notifications_row) self.notifications_btn.clicked.connect(self._on_notifications_clicked) self.guard_btn.clicked.connect(self._on_guard_clicked) @@ -351,10 +346,6 @@ class Scheduler(BECWidget, QWidget): layout.addWidget(file_group) - self.guard_status_label = QLabel() - self.guard_status_label.setStyleSheet("color: gray;") - layout.addWidget(self.guard_status_label) - self.apply_theme() def apply_theme(self, theme: Optional[Literal["dark", "light"]] = None): @@ -397,12 +388,7 @@ class Scheduler(BECWidget, QWidget): return Schedule.model_validate(msg.value) logger.info("No schedule found, create one now") - schedule = Schedule( - schedule_name=self.schedule_name, - items=[ - ScheduleItem(item_id=str(uuid.uuid4()), command=cmd) for cmd in DEFAULT_COMMANDS - ], - ) + schedule = Schedule(schedule_name=self.schedule_name, items=[]) self.connector.set_and_publish( self._endpoint, VariableMessage(value=schedule.model_dump(mode="json")) ) @@ -419,7 +405,7 @@ class Scheduler(BECWidget, QWidget): self._persist_locked() @SafeSlot(dict, dict) - def _on_remote_update(self, msg_content: dict, metadata: dict): + def _on_remote_update(self, msg_content: dict, _): value = msg_content.get("value") if msg_content else None if not value or value.get("schedule_name") != self.schedule_name: return @@ -497,17 +483,13 @@ class Scheduler(BECWidget, QWidget): selected_row = None for row, item in enumerate(items): text = f"{item.command}" - icon_name, color = _ICON_MAP[item.status] - icon = material_icon( - icon_name, size=(ICON_SIZE, ICON_SIZE), color=color, convert_to_pixmap=True - ) if item.error: text += f" ({item.error.strip().splitlines()[-1]})" list_item = QListWidgetItem(text, self.list_widget) list_item.setData(_ITEM_ID_ROLE, item.item_id) - list_item.setIcon(icon) if item.item_id == self._selected_item_id: selected_row = row + self._update_icons() if selected_row is not None: self.list_widget.setCurrentRow(selected_row) else: @@ -523,17 +505,18 @@ class Scheduler(BECWidget, QWidget): self.notes_edit.setPlainText(notes) self.notes_edit.blockSignals(False) + def _update_guard_label(self, *_): if self._guard.enabled: state = "OK" if self._guard.is_clear() else "PAUSED - waiting to resume" value = self._guard.current_value - value_text = f"{value:g}" if value is not None else "?" + units = self._guard.units + value_text = f"{value:.{self._guard.prec}f}" if value is not None else "?" self.guard_status_label.setText( - f"Auto-pause: {self._guard.device_name} = {value_text} " + f"Enabled: {self._guard.device_name} = {value_text} {units} " f"(pause < {self._guard.pause_below:g}, resume > {self._guard.resume_above:g}) [{state}]" ) - self.guard_status_label.show() else: - self.guard_status_label.hide() + self.guard_status_label.setText("Disabled") def _update_buttons(self): with self._lock: @@ -568,10 +551,23 @@ class Scheduler(BECWidget, QWidget): self.copy_btn.setEnabled(selected_item is not None) self.paste_btn.setEnabled(self._clipboard_item is not None) + def _update_icons(self): + items = list(self.schedule.items) + for row, item in enumerate(items): + icon_name, color = _ICON_MAP[item.status] + if self._selected_item_id == item.item_id: + color = "#FFFFFF" + icon = material_icon( + icon_name, size=(ICON_SIZE, ICON_SIZE), color=color, convert_to_pixmap=True + ) + list_item = self.list_widget.item(row) + list_item.setIcon(icon) + @SafeSlot() def _on_selection_changed(self, row: int): item = self.list_widget.item(row) if row >= 0 else None self._selected_item_id = item.data(_ITEM_ID_ROLE) if item is not None else None + self._update_icons() self._update_buttons() @SafeSlot() @@ -717,17 +713,17 @@ class Scheduler(BECWidget, QWidget): self._persist_locked() self._guard.configure(self.schedule.guard) self._refresh_ui() + self._update_guard_label() def _apply_guard_settings(self): """Re-subscribe the guard after `self.schedule.guard` changes (e.g. from a remote update).""" self._guard.configure(self.schedule.guard) + self._update_guard_label() @SafeSlot(float) def _on_guard_paused(self, value: float): logger.info( - "Auto-pause guard tripped for schedule '%s' (value=%s); interrupting the running scan, if any.", - self.schedule_name, - value, + f"Auto-pause guard tripped for schedule {self.schedule_name} (value = {value}); interrupting the running scan, if any." ) if self._current_report is not None and self._current_item_kind == "scan": self._guard_interrupt_requested = True @@ -740,10 +736,8 @@ class Scheduler(BECWidget, QWidget): @SafeSlot(float) def _on_guard_resumed(self, value: float): logger.info( - "Auto-pause guard cleared for schedule '%s' (value=%s); the execution loop will " - "resume the next scan item automatically.", - self.schedule_name, - value, + f"Auto-pause guard cleared for schedule {self.schedule_name} (value = {value}); the execution loop will " + "resume the next scan item automatically." ) self.schedule_changed.emit() @@ -765,7 +759,7 @@ class Scheduler(BECWidget, QWidget): self._update_buttons() @SafeSlot() - def _on_edit_clicked(self, row=None): + def _on_edit_clicked(self, _): if self._selected_item_id is None: return with self._lock: @@ -1168,8 +1162,7 @@ class Scheduler(BECWidget, QWidget): item.request_id = getattr(request, "requestID", None) self._persist_locked() - # Wait for completion without blocking the thread indefinitely - self._wait_for_report(report) + report.wait() if self._closing.is_set(): # The widget was closed mid-item; exit without changing status in Redis. @@ -1227,19 +1220,6 @@ class Scheduler(BECWidget, QWidget): error=item.error, ) - def _wait_for_report(self, report, timeout: float = 0.5): - """Poll report status to allow thread exit if the widget closes.""" - while not self._closing.is_set() and not self._abort_requested: - # Check if scan report has finished via its internal event or status - if ( - getattr(report, "status", None) == "completed" - or getattr(report, "event", None) - and report.event.is_set() - ): - break - # Non-blocking poll interval - time.sleep(timeout) - def _await_running_item(self, item: ScheduleItem): queue_storage = self.client.queue.queue_storage while not self._abort_requested and not self._closing.is_set(): From d54f247007e65cd6bff73f6b13ea3085601a37ad Mon Sep 17 00:00:00 2001 From: x01da Date: Wed, 2 Sep 2026 15:27:01 +0200 Subject: [PATCH 08/56] wip --- .../bec_widgets/widgets/scheduler/enums.py | 11 + .../widgets/scheduler/notification_dialog.py | 210 ++++++++++++++++-- .../widgets/scheduler/notifications.py | 145 ++++++++---- .../widgets/scheduler/schedule_item.py | 10 +- .../widgets/scheduler/scheduler.py | 72 +++++- 5 files changed, 371 insertions(+), 77 deletions(-) create mode 100644 debye_bec/bec_widgets/widgets/scheduler/enums.py diff --git a/debye_bec/bec_widgets/widgets/scheduler/enums.py b/debye_bec/bec_widgets/widgets/scheduler/enums.py new file mode 100644 index 0000000..71bc706 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/enums.py @@ -0,0 +1,11 @@ +from __future__ import annotations + +from enum import Enum + + +class ScheduleItemStatus(str, Enum): + PENDING = "pending" + RUNNING = "running" + COMPLETED = "completed" + FAILED = "failed" + ABORTED = "aborted" diff --git a/debye_bec/bec_widgets/widgets/scheduler/notification_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/notification_dialog.py index 0397c58..cc7dd81 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/notification_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/notification_dialog.py @@ -1,25 +1,56 @@ -"""Small settings dialog for `notifications.NotificationSettings` - kept separate from the send logic itself.""" +""" +Settings dialog for `notifications.NotificationSettings` - kept separate +from the send logic itself (`notifications.py`). +""" from __future__ import annotations -from qtpy.QtWidgets import QCheckBox, QDialog, QDialogButtonBox, QLabel, QVBoxLayout +from bec_lib.logger import bec_logger +from qtpy.QtWidgets import ( + QCheckBox, + QComboBox, + QDialog, + QDialogButtonBox, + QGroupBox, + QLabel, + QMessageBox, + QPushButton, + QVBoxLayout, +) -from .notifications import NotificationSettings +from .enums import ScheduleItemStatus +from .notifications import NotificationSettings, NotificationTarget, send_notification + +logger = bec_logger.logger + + +def _service_state(client, name: str) -> tuple[bool, list[str]]: + """ + Best-effort read of a messaging service's enabled/scopes state (see + the module docstring in notifications.py for why this is the only + introspection available). Never raises - a client without `messaging` + set up yet just looks like "not enabled, no scopes". + """ + messaging = getattr(client, "messaging", None) + service = getattr(messaging, name, None) if messaging is not None else None + if service is None: + return False, [] + return bool(getattr(service, "_enabled", False)), sorted(getattr(service, "_scopes", set())) class NotificationSettingsDialog(QDialog): - """Choose whether, and for which item types, finish/fail notifications are sent.""" + """Choose whether/where/for-which-item-types finish/fail notifications are sent.""" - def __init__(self, settings: NotificationSettings, parent=None): + def __init__(self, settings: NotificationSettings, client, parent=None): super().__init__(parent) + self._client = client self.setWindowTitle("Notifications") + self.setMinimumWidth(380) layout = QVBoxLayout(self) info_label = QLabel( - "Sends a BEC notification (see MessageEndpoints.notification) whenever a " - "schedule item finishes or fails. Whether it reaches you as a message depends " - "on your facility's notification routing (SciHub + Signal/Teams/SciLog) being " - "configured for these events - ask your beamline admin if you're not sure." + "Sends a message through the selected BEC messaging service whenever a " + "schedule item finishes or fails." ) info_label.setWordWrap(True) layout.addWidget(info_label) @@ -28,32 +59,173 @@ class NotificationSettingsDialog(QDialog): self.enabled_check.setChecked(settings.enabled) layout.addWidget(self.enabled_check) + kind_box = QGroupBox("Notify for") + kind_layout = QVBoxLayout(kind_box) self.scan_check = QCheckBox("Scans") self.scan_check.setChecked(settings.notify_scan) - layout.addWidget(self.scan_check) - self.move_check = QCheckBox("Movements") self.move_check.setChecked(settings.notify_move) - layout.addWidget(self.move_check) - self.rpc_check = QCheckBox("RPC / custom commands") self.rpc_check.setChecked(settings.notify_rpc) - layout.addWidget(self.rpc_check) - for check in (self.scan_check, self.move_check, self.rpc_check): - self.enabled_check.toggled.connect(check.setEnabled) - check.setEnabled(settings.enabled) + kind_layout.addWidget(check) + layout.addWidget(kind_box) + + target_box = QGroupBox("Send via") + target_layout = QVBoxLayout(target_box) + self.scilog_check = QCheckBox("SciLog") + self.teams_check = QCheckBox("Microsoft Teams") + self.signal_check = QCheckBox("Signal Messenger") + for check in (self.scilog_check, self.teams_check, self.signal_check): + target_layout.addWidget(check) + layout.addWidget(target_box) + + event_box = QGroupBox("Send on") + event_layout = QVBoxLayout(event_box) + self.completed_check = QCheckBox("Completed") + self.aborted_check = QCheckBox("Aborted") + self.failed_check = QCheckBox("Failed") + for check in (self.completed_check, self.aborted_check, self.failed_check): + event_layout.addWidget(check) + layout.addWidget(event_box) + + # Teams: contact/channel can only be a scope an admin has already + # registered for the deployment - there's no way to address an + # arbitrary Teams user from the client, so this is a dropdown, not + # free text (see notifications.py's module docstring). + self.teams_box = QGroupBox("Teams settings") + teams_layout = QVBoxLayout(self.teams_box) + teams_enabled, teams_scopes = _service_state(client, "teams") + self.teams_combo = QComboBox() + self.teams_combo.addItems(teams_scopes) + self.teams_combo.setEnabled(teams_enabled) + teams_layout.addWidget(QLabel("Contact or channel")) + teams_layout.addWidget(self.teams_combo) + if not teams_enabled: + teams_layout.addWidget(_dim_label("Teams messaging is not enabled for this session.")) + elif not teams_scopes: + teams_layout.addWidget(_dim_label("No Teams contacts/channels are registered.")) + layout.addWidget(self.teams_box) + + # Signal: a raw phone number works directly (BEC normalizes it - + # see the docs), so this is an editable combo box: type a number, + # or pick a pre-registered scope if any exist. + self.signal_box = QGroupBox("Signal settings") + signal_layout = QVBoxLayout(self.signal_box) + signal_enabled, signal_scopes = _service_state(client, "signal") + self.signal_combo = QComboBox() + self.signal_combo.setEditable(True) + self.signal_combo.addItems(signal_scopes) + self.signal_combo.setEnabled(signal_enabled) + signal_layout.addWidget(QLabel("Phone number or contact")) + self.signal_combo.setEditText("") + self.signal_combo.lineEdit().setPlaceholderText("e.g. +41791234567") + signal_layout.addWidget(self.signal_combo) + if not signal_enabled: + signal_layout.addWidget(_dim_label("Signal messaging is not enabled for this session.")) + layout.addWidget(self.signal_box) + + # pre-fill from the persisted settings + { + NotificationTarget.SCILOG: self.scilog_check, + NotificationTarget.TEAMS: self.teams_check, + NotificationTarget.SIGNAL: self.signal_check, + }.get(settings.target, self.scilog_check).setChecked(True) + for event in settings.events: + { + ScheduleItemStatus.COMPLETED: self.completed_check, + ScheduleItemStatus.ABORTED: self.aborted_check, + ScheduleItemStatus.FAILED: self.failed_check, + }.get(event).setChecked(True) + if settings.teams_scope: + idx = self.teams_combo.findText(settings.teams_scope) + if idx >= 0: + self.teams_combo.setCurrentIndex(idx) + if settings.signal_number: + self.signal_combo.setEditText(settings.signal_number) + + self.scilog_check.toggled.connect(lambda *_: self._sync_target_widgets(self.scilog_check)) + self.teams_check.toggled.connect(lambda *_: self._sync_target_widgets(self.teams_check)) + self.signal_check.toggled.connect(lambda *_: self._sync_target_widgets(self.signal_check)) + + self.test_btn = QPushButton("Send test message") + self.test_btn.clicked.connect(self._on_test_clicked) + layout.addWidget(self.test_btn) buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) layout.addWidget(buttons) - def result_settings(self) -> NotificationSettings: - """Valid after `exec_()` returns `QDialog.Accepted`.""" + self._sync_target_widgets() + + def _sync_target_widgets(self, current_button: QCheckBox = None): + if current_button is None: + for button in [self.scilog_check, self.teams_check, self.signal_check]: + if button.isChecked(): + current_button = button + break + if current_button.isChecked(): + for button in [self.scilog_check, self.teams_check, self.signal_check]: + if button != current_button: + button.setChecked(False) + if current_button == self.teams_check: + self.teams_box.setVisible(True) + self.signal_box.setVisible(False) + elif current_button == self.signal_check: + self.teams_box.setVisible(False) + self.signal_box.setVisible(True) + else: + self.teams_box.setVisible(False) + self.signal_box.setVisible(False) + self.layout().activate() + self.adjustSize() + + def _current_settings(self) -> NotificationSettings: + if self.scilog_check.isChecked(): + target = NotificationTarget.SCILOG + elif self.teams_check.isChecked(): + target = NotificationTarget.TEAMS + elif self.signal_check.isChecked(): + target = NotificationTarget.SIGNAL + else: + raise ValueError(f"Target {target} not supported") + + events = [] + if self.completed_check.isChecked(): + events.append(ScheduleItemStatus.COMPLETED) + if self.aborted_check.isChecked(): + events.append(ScheduleItemStatus.ABORTED) + if self.failed_check.isChecked(): + events.append(ScheduleItemStatus.FAILED) + return NotificationSettings( enabled=self.enabled_check.isChecked(), notify_scan=self.scan_check.isChecked(), notify_move=self.move_check.isChecked(), notify_rpc=self.rpc_check.isChecked(), + target=target, + events=events, + teams_scope=self.teams_combo.currentText().strip() or None, + signal_number=self.signal_combo.currentText().strip() or None, ) + + def _on_test_clicked(self): + settings = self._current_settings() + try: + send_notification(self._client, settings, "Test message from the BEC schedule widget.") + except Exception as exc: # pylint: disable=broad-except + QMessageBox.critical(self, "Test message failed", str(exc)) + return + QMessageBox.information(self, "Test message sent", "The test message was sent.") + + def result_settings(self) -> NotificationSettings: + """Valid after `exec_()` returns `QDialog.Accepted`.""" + return self._current_settings() + + +def _dim_label(text: str) -> QLabel: + label = QLabel(text) + label.setStyleSheet("color: gray;") + label.setWordWrap(True) + return label diff --git a/debye_bec/bec_widgets/widgets/scheduler/notifications.py b/debye_bec/bec_widgets/widgets/scheduler/notifications.py index b7542e2..16b9f34 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/notifications.py +++ b/debye_bec/bec_widgets/widgets/scheduler/notifications.py @@ -2,42 +2,55 @@ A small, self-contained "tell the user when something finished/failed" feature, independent of scheduling/execution logic. -Sends via BEC's own notification transport: `MessageEndpoints.notification` -carries a `messages.NotificationMessage`, the same message type/endpoint -BEC's own scan lifecycle events (e.g. "scan_completed") use. Reusing it -means schedule-item notifications are just more entries in the same -mechanism, not a plugin-invented side channel - and if your facility runs -SciHub with messaging-service routing configured (Signal/Teams/SciLog), -they can be forwarded out the same way any other BEC notification would -be, by adding a route for the event names below in that routing config. +Sends through BEC's own `client.messaging` container +(`bec_lib.messaging_services.MessagingContainer`, exposed as `bec.messaging` +in the IPython client) - the same mechanism documented at +https://bec.readthedocs.io/latest/how-to/general/send-messages-to-signal.html +and +https://bec.readthedocs.io/latest/how-to/general/send-messages-to-scilog.html: -Nothing here is scheduling/BECWidget-specific: `notify_item_finished` only -needs a connector, a settings object and a few plain values, so it can be -called from `schedule_widget.py` without either module depending on the -other's internals. + bec.messaging.signal.new("Beamline checks completed.").send(scope="+41791234567") + bec.messaging.scilog.new("Beamline checks completed.").send() + bec.messaging.teams.new("Beamline checks completed.").send(scope=) + +Notes on each service, read directly from `bec_lib.messaging_services` +rather than assumed: + +- **SciLog** needs no `scope` - it posts to the logbook of the currently + active pgroup automatically. +- **Signal** accepts a raw phone number as `scope` (BEC normalizes it, + defaulting to the Swiss country code for numbers without one - see the + docs above) *or* a pre-registered scope name for a group. +- **Teams** is a plain `MessagingService` with no Teams-specific methods: + a contact/channel can only be addressed by a `scope` an admin has + already registered for the deployment (`service._scopes`) - there is no + way to address an arbitrary Teams user/email directly from the client. + This is why the Teams UI in `notification_dialog.py` is a dropdown of + known scopes rather than free text, while Signal's is free text (with + any registered scopes offered as suggestions). + +`client.messaging.._enabled` / `._scopes` are the only +introspection available (no public accessor exists at the time of +writing) - used here and in the dialog to grey out a target that isn't +configured for the current session instead of only failing at send time. """ from __future__ import annotations -from bec_lib.endpoints import MessageEndpoints +from enum import Enum + from bec_lib.logger import bec_logger -from bec_lib.messages import MessagingServiceTextContent, NotificationMessage from pydantic import BaseModel +from .enums import ScheduleItemStatus + logger = bec_logger.logger -# Namespaced so they can't collide with BEC's own built-in event names -# (e.g. "scan_completed"); an admin who wants these routed to Signal/Teams/ -# SciLog can add a route for exactly these names in their notification -# routing config (`MessageEndpoints.notification_config()`). -_EVENT_NAMES = { - ("scan", True): "schedule_scan_completed", - ("scan", False): "schedule_scan_failed", - ("move", True): "schedule_move_completed", - ("move", False): "schedule_move_failed", - ("custom", True): "schedule_rpc_completed", - ("custom", False): "schedule_rpc_failed", -} + +class NotificationTarget(str, Enum): + SCILOG = "scilog" + TEAMS = "teams" + SIGNAL = "signal" class NotificationSettings(BaseModel): @@ -51,6 +64,11 @@ class NotificationSettings(BaseModel): # any hand-typed command, so it's exposed to the user as "RPC". notify_rpc: bool = True + target: NotificationTarget = NotificationTarget.SCILOG + events: list[ScheduleItemStatus] = [] + teams_scope: str | None = None # a pre-registered Teams scope (channel/contact) + signal_number: str | None = None # a phone number, or a pre-registered Signal scope + def _enabled_for_kind(settings: NotificationSettings, kind: str) -> bool: if not settings.enabled: @@ -62,33 +80,80 @@ def _enabled_for_kind(settings: NotificationSettings, kind: str) -> bool: }.get(kind, False) +def send_notification(client, settings: NotificationSettings, text: str) -> None: + """ + Send `text` through whichever service `settings.target` selects. + + Raises on failure (no target selected, missing Teams scope/Signal + number, the target service not enabled for this session, ...) - + callers that want a fire-and-forget send should catch around this. + `notify_item_finished` does; the dialog's "Send test message" button + deliberately does not, so the operator sees exactly what went wrong. + """ + if settings.target == NotificationTarget.SCILOG: + client.messaging.scilog.new(text).send() + elif settings.target == NotificationTarget.TEAMS: + if not settings.teams_scope: + raise ValueError("No Teams contact/channel selected.") + client.messaging.teams.new(text).send(scope=settings.teams_scope) + elif settings.target == NotificationTarget.SIGNAL: + if not settings.signal_number: + raise ValueError("No Signal phone number/contact set.") + client.messaging.signal.new(text).send(scope=settings.signal_number) + else: + raise ValueError("No notification target selected.") + + def notify_item_finished( - connector, - schedule_name: str, + client, kind: str, command: str, - success: bool, + scan_number: str, + final_status: ScheduleItemStatus, settings: NotificationSettings, error: str | None = None, ): """ - Sends a `NotificationMessage` if notifications are enabled for `kind`. - Never raises - a notification failing to send should not affect - schedule execution. + Sends a message if notifications are enabled for `kind` and a target + is configured. Never raises - a notification failing to send should + not affect schedule execution. """ if not _enabled_for_kind(settings, kind): return + if final_status not in settings.events: + return - event = _EVENT_NAMES.get((kind, success), "schedule_item_finished") - status_word = "completed" if success else "failed" - text = f"[{schedule_name}] {kind} {status_word}: {command}" + status_word = final_status.name + text = f"**BEC Scheduler Widget**\nStatus: {kind} {status_word}" + if scan_number is not None: + text = text + f"\nScan number: {scan_number}" + text = text + f"\n\nCommand: {command}" if error: text += f"\n{error.strip().splitlines()[-1]}" try: - connector.send( - MessageEndpoints.notification(event), - NotificationMessage(event=event, message=[MessagingServiceTextContent(content=text)]), - ) + send_notification(client, settings, text) except Exception: # pylint: disable=broad-except - logger.exception("Failed to send schedule notification for event '%s'", event) + logger.exception(f"Failed to send schedule notification via {settings.target.value}") + + +def notify_schedule_state(client, settings, schedule_name, state): + """ + Sends a message if notifications are enabled and a schedule is started or stopped. + Never raises - a notification failing to send should not affect schedule execution. + """ + text = f'**BEC Scheduler Widget**\nSchedule "{schedule_name}" ' + if state == "started": + text = text + "has started" + elif state == "aborted": + text = text + "was aborted" + elif state == "widget_closed": + text = text + "has finished prematurely because widget was closed" + elif state == "finished": + text = text + "has finished" + else: + logger.warning(f"Unknown schedule state {state}") + try: + send_notification(client, settings, text) + except Exception: # pylint: disable=broad-except + logger.exception(f"Failed to send schedule notification via {settings.target.value}") diff --git a/debye_bec/bec_widgets/widgets/scheduler/schedule_item.py b/debye_bec/bec_widgets/widgets/scheduler/schedule_item.py index 74cb2e0..b675094 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/schedule_item.py +++ b/debye_bec/bec_widgets/widgets/scheduler/schedule_item.py @@ -15,18 +15,10 @@ from typing import Literal from pydantic import BaseModel, Field +from .enums import ScheduleItemStatus from .guard import GuardSettings from .notifications import NotificationSettings - -class ScheduleItemStatus(str, Enum): - PENDING = "pending" - RUNNING = "running" - COMPLETED = "completed" - FAILED = "failed" - ABORTED = "aborted" - - # Which tab of the Add/Edit dialog built `command`, and therefore how to # re-open that dialog pre-filled with the same values for editing. "custom" # covers hand-typed text (including RPC calls to other widgets), which has diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 0b44652..bc4d826 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -46,12 +46,18 @@ from qtpy.QtWidgets import ( ) from .endpoints import schedule as schedule_endpoint +from .enums import ScheduleItemStatus from .guard import SignalGuard from .guard_dialog import GuardSettingsDialog from .item_dialog import ScheduleItemDialog from .notification_dialog import NotificationSettingsDialog -from .notifications import NotificationSettings, notify_item_finished -from .schedule_item import Schedule, ScheduleItem, ScheduleItemStatus +from .notifications import ( + NotificationSettings, + NotificationTarget, + notify_item_finished, + notify_schedule_state, +) +from .schedule_item import Schedule, ScheduleItem from .schedule_logic import index_of, pick_next_runnable, protected_prefix_length logger = bec_logger.logger @@ -323,7 +329,9 @@ class Scheduler(BECWidget, QWidget): guard_row.addStretch() notifications_row = QHBoxLayout() self.notifications_btn = MyButton("Notifications", "default") + self.notification_status_label = QLabel() notifications_row.addWidget(self.notifications_btn) + notifications_row.addWidget(self.notification_status_label) notifications_row.addStretch() settings_layout.addLayout(guard_row) settings_layout.addLayout(notifications_row) @@ -346,6 +354,9 @@ class Scheduler(BECWidget, QWidget): layout.addWidget(file_group) + self._update_guard_label() + self._update_notifications_label() + self.apply_theme() def apply_theme(self, theme: Optional[Literal["dark", "light"]] = None): @@ -694,14 +705,39 @@ class Scheduler(BECWidget, QWidget): # ---- notifications / auto-pause settings ---- # @SafeSlot() def _on_notifications_clicked(self): - dialog = NotificationSettingsDialog(self.schedule.notifications, parent=self) + dialog = NotificationSettingsDialog(self.schedule.notifications, self.client, parent=self) if dialog.exec_() != QDialog.Accepted: return with self._lock: self.schedule.notifications = dialog.result_settings() + self._update_notifications_label() self._persist_locked() self._refresh_ui() + def _update_notifications_label(self): + if self.schedule.notifications.enabled: + types = [] + if self.schedule.notifications.notify_scan: + types.append("scan") + if self.schedule.notifications.notify_move: + types.append("move") + if self.schedule.notifications.notify_rpc: + types.append("rpc") + match self.schedule.notifications.target: + case NotificationTarget.SIGNAL: + target = "Signal Messenger" + case NotificationTarget.TEAMS: + target = "Microsoft Teams" + case NotificationTarget.SCILOG: + target = "Scilog" + events = [] + for event in self.schedule.notifications.events: + events.append(event.value) + text = f"Enabled: Notify through {target}, for item type {types}, and events {events}" + else: + text = "Disabled" + self.notification_status_label.setText(text) + @SafeSlot() def _on_guard_clicked(self): device_names = sorted(self.dev.keys()) @@ -732,6 +768,7 @@ class Scheduler(BECWidget, QWidget): except Exception: # pylint: disable=broad-except logger.exception("Failed to cancel the running scan for the auto-pause guard") self.schedule_changed.emit() + self._update_guard_label() @SafeSlot(float) def _on_guard_resumed(self, value: float): @@ -1114,7 +1151,9 @@ class Scheduler(BECWidget, QWidget): super().cleanup() def _run_all(self, repeat_aborted_item): - logger.info("_run_all was called") + notify_schedule_state( + self.client, self.schedule.notifications, self.schedule_name, "started" + ) namespace = {"scans": self.scans, "dev": self.dev} while not self._abort_requested and not self._closing.is_set(): with self._lock: @@ -1126,7 +1165,18 @@ class Scheduler(BECWidget, QWidget): self._await_running_item(next_item) else: self._execute_item(next_item, namespace) - + if self._abort_requested: + notify_schedule_state( + self.client, self.schedule.notifications, self.schedule_name, "aborted" + ) + elif self._closing.is_set(): + notify_schedule_state( + self.client, self.schedule.notifications, self.schedule_name, "widget_closed" + ) + else: + notify_schedule_state( + self.client, self.schedule.notifications, self.schedule_name, "finished" + ) with self._lock: logger.info("in _run_all, set is_running to false") self.schedule.is_running = False @@ -1209,13 +1259,17 @@ class Scheduler(BECWidget, QWidget): else: final_status = None - if final_status in (ScheduleItemStatus.COMPLETED, ScheduleItemStatus.FAILED): + if final_status in ( + ScheduleItemStatus.COMPLETED, + ScheduleItemStatus.FAILED, + ScheduleItemStatus.ABORTED, + ): notify_item_finished( - self.connector, - self.schedule_name, + self.client, item.kind, item.command, - success=(final_status == ScheduleItemStatus.COMPLETED), + item.scan_number, + final_status=final_status, settings=self.schedule.notifications, error=item.error, ) From bc89079048d011ab564cb5b7ceb3b2693c7315b1 Mon Sep 17 00:00:00 2001 From: x01da Date: Wed, 2 Sep 2026 16:14:35 +0200 Subject: [PATCH 09/56] wip --- .../widgets/scheduler/scheduler.py | 44 +++++++++++++++++-- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index bc4d826..f89926f 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -36,6 +36,7 @@ from qtpy.QtWidgets import ( QGroupBox, QHBoxLayout, QLabel, + QLineEdit, QListWidget, QListWidgetItem, QMessageBox, @@ -249,6 +250,16 @@ class Scheduler(BECWidget, QWidget): schedule_group = QGroupBox("Schedule") schedule_layout = QVBoxLayout(schedule_group) + schedule_name_layout = QHBoxLayout() + name_label = QLabel("Name") + self.schedule_name_input = QLineEdit() + schedule_name_layout.addWidget(name_label) + schedule_name_layout.addWidget(self.schedule_name_input) + schedule_name_layout.addStretch() + schedule_layout.addLayout(schedule_name_layout) + + self.schedule_name_input.editingFinished.connect(self._on_schedule_name_change) + edit_row = QHBoxLayout() self.add_btn = MyButton("Add", "default") self.edit_btn = MyButton("Edit", "default") @@ -270,8 +281,6 @@ class Scheduler(BECWidget, QWidget): edit_row.addStretch() schedule_layout.addLayout(edit_row) - schedule_layout.addWidget(QLabel(f"Schedule: {self.schedule_name}")) - self.list_widget = MyListWidget() self.list_widget.currentRowChanged.connect(self._on_selection_changed) self.list_widget.deletePressed.connect(self._on_delete_clicked) @@ -486,9 +495,12 @@ class Scheduler(BECWidget, QWidget): @SafeSlot() def _refresh_ui(self): with self._lock: + schedule_name = self.schedule.schedule_name items = list(self.schedule.items) notes = self.schedule.notes + self.schedule_name_input.setText(schedule_name) + self.list_widget.blockSignals(True) self.list_widget.clear() selected_row = None @@ -574,6 +586,13 @@ class Scheduler(BECWidget, QWidget): list_item = self.list_widget.item(row) list_item.setIcon(icon) + @SafeSlot() + def _on_schedule_name_change(self): + name = self.schedule_name_input.text() + with self._lock: + self.schedule.schedule_name = name + self._persist_locked() + @SafeSlot() def _on_selection_changed(self, row: int): item = self.list_widget.item(row) if row >= 0 else None @@ -606,7 +625,15 @@ class Scheduler(BECWidget, QWidget): def _on_save_to_file_clicked(self): with self._lock: data = self.schedule.model_dump(mode="json") - default_name = f"{self.schedule_name}.json" + default_name = "schedule.json" + + hostname = self.client._hostname + start = hostname.find("x") + if start != -1: + beamline = hostname[start : start + 5] + active_account = self.client.active_account + default_name = f"/sls/{beamline}/data/{active_account}/raw/{default_name}" + path, _ = QFileDialog.getSaveFileName( self, "Save schedule to file", default_name, "JSON files (*.json);;All files (*)" ) @@ -631,8 +658,16 @@ class Scheduler(BECWidget, QWidget): ) return + start_folder = "" + hostname = self.client._hostname + start = hostname.find("x") + if start != -1: + beamline = hostname[start : start + 5] + active_account = self.client.active_account + start_folder = f"/sls/{beamline}/data/{active_account}/raw" + path, _ = QFileDialog.getOpenFileName( - self, "Load schedule from file", "", "JSON files (*.json);;All files (*)" + self, "Load schedule from file", start_folder, "JSON files (*.json);;All files (*)" ) if not path: return @@ -688,6 +723,7 @@ class Scheduler(BECWidget, QWidget): self, "Cannot load", "The schedule started running while the dialog was open." ) return + self.schedule.schedule_name = loaded.schedule_name self.schedule.items = new_items self.schedule.notes = loaded.notes self.schedule.guard = loaded.guard From f365ec595a0c29670eeafa9a8a9f4abadc11aabe Mon Sep 17 00:00:00 2001 From: x01da Date: Wed, 2 Sep 2026 16:17:44 +0200 Subject: [PATCH 10/56] wip --- debye_bec/bec_widgets/widgets/scheduler/scheduler.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index f89926f..78cd84c 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -1128,6 +1128,8 @@ class Scheduler(BECWidget, QWidget): target = idx - 1 if idx is not None and idx > 0 else None if target is not None: self.move_item(item_id, target) + self._refresh_ui() + self._update_buttons() def move_item_down(self, item_id: str): """RPC-exposed: swap an item with the one directly after it.""" @@ -1137,6 +1139,8 @@ class Scheduler(BECWidget, QWidget): target = idx + 1 if idx is not None and idx < n - 1 else None if target is not None: self.move_item(item_id, target) + self._refresh_ui() + self._update_buttons() # ------------------------------------------------------------------ # # execution - runs in a background task (BECConnector.submit_task, From 18a5d0d5eb8bac3f712eafbdc6b95978772f2831 Mon Sep 17 00:00:00 2001 From: x01da Date: Thu, 3 Sep 2026 08:23:46 +0200 Subject: [PATCH 11/56] feat(reffoilchanger): Added function to get all foils by name --- debye_bec/devices/reffoilchanger.py | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/debye_bec/devices/reffoilchanger.py b/debye_bec/devices/reffoilchanger.py index b59970d..9bd5a9c 100644 --- a/debye_bec/devices/reffoilchanger.py +++ b/debye_bec/devices/reffoilchanger.py @@ -37,7 +37,7 @@ class OpMode(int, enum.Enum): class Reffoilchanger(PSIDeviceBase): """Class for the ES2 Reference Foil Changer""" - USER_ACCESS = ["insert"] + USER_ACCESS = ["get_all_foils", "insert"] inserted = Cpt( EpicsSignalRO, suffix="ES2-REF:TRY-FilterInserted", kind="config", doc="Inserted indicator" @@ -53,13 +53,21 @@ class Reffoilchanger(PSIDeviceBase): EpicsSignal, suffix="ES2-REF:SELN-FilterState-ENUM_RBV", kind="config", doc="Status" ) status_string = Cpt( - EpicsSignal, suffix="ES2-REF:SELN-FilterState-ENUM_RBV", kind="config", doc="Status", string=True + EpicsSignal, + suffix="ES2-REF:SELN-FilterState-ENUM_RBV", + kind="config", + doc="Status", + string=True, ) op_mode = Cpt( EpicsSignalWithRBV, suffix="ES2-REF:SELN-OpMode-ENUM", kind="config", doc="Status" ) op_mode_string = Cpt( - EpicsSignalWithRBV, suffix="ES2-REF:SELN-OpMode-ENUM", kind="config", doc="Status", string=True + EpicsSignalWithRBV, + suffix="ES2-REF:SELN-OpMode-ENUM", + kind="config", + doc="Status", + string=True, ) ref_set = Cpt(EpicsSignal, suffix="ES2-REF:SELN-SET", kind="config", doc="Requested reference") ref_rb = Cpt( @@ -149,6 +157,13 @@ class Reffoilchanger(PSIDeviceBase): self.foil38, ] + def get_all_foils(self) -> list[str]: + """Returns a list of strings of all available foils""" + foils_list = [] + for foil in self.foils: + foils_list.append(foil.get()) + return foils_list + def insert(self, ref: str, wait: bool = False) -> DeviceStatus: """Insert a reference From 1bf4bd98d28f10d1844f1963cf6f6683a7b0f4e1 Mon Sep 17 00:00:00 2001 From: x01da Date: Thu, 3 Sep 2026 08:24:21 +0200 Subject: [PATCH 12/56] fix(ionization chamber): Fix TransisitonStatus call --- debye_bec/devices/ionization_chambers/ionization_chamber.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/debye_bec/devices/ionization_chambers/ionization_chamber.py b/debye_bec/devices/ionization_chambers/ionization_chamber.py index 25b81d8..9d2bd2c 100644 --- a/debye_bec/devices/ionization_chambers/ionization_chamber.py +++ b/debye_bec/devices/ionization_chambers/ionization_chamber.py @@ -263,7 +263,7 @@ class IonizationChamber0(PSIDeviceBase): self.gmes.gas2_req.set(gas2).wait(timeout=3) self.gmes.conc2_req.set(conc2).wait(timeout=3) - status = TransitionStatus(self.gmes.status.get(), [0, 1]) + status = TransitionStatus(self.gmes.status, [0, 1]) self.cancel_on_stop(status) self.gmes.fill.put(1) if wait: @@ -373,6 +373,7 @@ class IonizationChamber2(IonizationChamber0): } hv_en = Dcpt(hv_en_signals) + class Pips(IonizationChamber0): """Pips, prefix should be 'X01DA-'.""" From 96e2f45c506328db9bbd1d20669065aa220a953d Mon Sep 17 00:00:00 2001 From: x01da Date: Thu, 3 Sep 2026 08:24:29 +0200 Subject: [PATCH 13/56] wip --- .../widgets/scheduler/item_dialog.py | 115 +++++++++++++++++- .../widgets/scheduler/notifications.py | 2 +- .../widgets/scheduler/qt_widgets.py | 61 ++++++++++ .../widgets/scheduler/scheduler.py | 74 ++--------- 4 files changed, 187 insertions(+), 65 deletions(-) create mode 100644 debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index 69c4942..3f5bf6d 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -41,15 +41,19 @@ from qtpy.QtWidgets import ( QDialogButtonBox, QDoubleSpinBox, QFormLayout, + QGroupBox, + QHBoxLayout, QLabel, QLineEdit, QMessageBox, + QPushButton, QTabWidget, QVBoxLayout, QWidget, ) from ..scan_control_xas.scan_control_xas import ScanControlXAS +from .qt_widgets import MyButton logger = bec_logger.logger @@ -204,10 +208,119 @@ class ScheduleItemDialog(QDialog): ) ) self.custom_edit = QLineEdit() + # TODO Change to a different placeholder text self.custom_edit.setPlaceholderText("scans.xas_simple_scan(12000, 14000, 2, 10)") layout.addWidget(self.custom_edit) + + ic_form = self._create_ionization_chamber_form() + if ic_form is not None: + layout.addWidget(ic_form) + + reffoil_form = self._create_reffoil_form() + if reffoil_form is not None: + layout.addWidget(reffoil_form) + layout.addStretch(1) - self.tabs.addTab(tab, "Custom") + self.tabs.addTab(tab, "Other") + + def _create_ionization_chamber_form(self): + if all(key in self._dev for key in ("ic0", "ic1", "ic2")): + ic_group = QGroupBox("Ionization chamber filling") + layout = QVBoxLayout(ic_group) + form = QFormLayout() + layout.addLayout(form) + form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) + self.ic_selector = QComboBox() + self.ic_selector.addItems(["IC0", "IC1", "IC2"]) + gases = ["He", "N2", "Ar", "Kr"] + self.gas1 = QComboBox() + self.gas2 = QComboBox() + self.gas1.addItems(gases) + self.gas2.addItems(gases) + self.conc1 = QDoubleSpinBox() + self.conc2 = QDoubleSpinBox() + for conc in [self.conc1, self.conc2]: + conc.setDecimals(0) + conc.setSuffix(" %") + conc.setMinimum(0) + conc.setMaximum(100) + conc.setSingleStep(1) + self.pressure = QDoubleSpinBox() + self.pressure.setDecimals(3) + self.pressure.setSuffix(" bar abs") + self.pressure.setMinimum(1) + self.pressure.setMaximum(3) + self.pressure.setSingleStep(0.1) + + form.addRow("Ionization chamber", self.ic_selector) + form.addRow("Gas 1", self.gas1) + form.addRow("Concentration 1", self.conc1) + form.addRow("Gas 2", self.gas2) + form.addRow("Concentration 2", self.conc2) + form.addRow("Pressure", self.pressure) + + button_layout = QHBoxLayout() + generate_cmd = MyButton("Generate command", "default") + button_layout.addWidget(generate_cmd) + button_layout.addStretch(1) + layout.addLayout(button_layout) + + self.conc1.valueChanged.connect(self._equalize_ic_conc) + self.conc2.valueChanged.connect(self._equalize_ic_conc) + generate_cmd.clicked.connect(self._generate_ic_command) + + return ic_group + return None + + def _equalize_ic_conc(self, new_val): + if self.conc1.value() == new_val: # conc1 was changed + self.conc2.setValue(100 - new_val) + else: + self.conc1.setValue(100 - new_val) + + def _generate_ic_command(self): + match self.ic_selector.currentText(): + case "IC0": + ic = "ic0" + case "IC1": + ic = "ic1" + case "IC2": + ic = "ic2" + cmd = ( + f"dev.{ic}.fill(" + + f"gas1='{self.gas1.currentText()}', conc1={self.conc1.value()}, " + + f"gas2='{self.gas2.currentText()}', conc2={self.conc2.value()}, " + + f"pressure={self.pressure.value()}, wait=True)" + ) + self.custom_edit.setText(cmd) + + def _create_reffoil_form(self): + if "reffoilchanger" in self._dev: + reffoil_group = QGroupBox("Reference foil changer") + layout = QVBoxLayout(reffoil_group) + form = QFormLayout() + layout.addLayout(form) + form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) + self.reffoil_selector = QComboBox() + available_foils = self._dev.reffoilchanger.get_all_foils() + self.reffoil_selector.addItems(available_foils) + + form.addRow("Reference foil", self.reffoil_selector) + + button_layout = QHBoxLayout() + generate_cmd = MyButton("Generate command", "default") + button_layout.addWidget(generate_cmd) + button_layout.addStretch(1) + layout.addLayout(button_layout) + + generate_cmd.clicked.connect(self._generate_reffoil_command) + + return reffoil_group + return None + + def _generate_reffoil_command(self): + cmd = f"dev.reffoilchanger.insert(ref='{self.reffoil_selector.currentText()}', wait=True)" + self.custom_edit.setText(cmd) def _collect_custom_result(self) -> dict: text = self.custom_edit.text().strip() diff --git a/debye_bec/bec_widgets/widgets/scheduler/notifications.py b/debye_bec/bec_widgets/widgets/scheduler/notifications.py index 16b9f34..bd8fbf3 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/notifications.py +++ b/debye_bec/bec_widgets/widgets/scheduler/notifications.py @@ -129,7 +129,7 @@ def notify_item_finished( text = text + f"\nScan number: {scan_number}" text = text + f"\n\nCommand: {command}" if error: - text += f"\n{error.strip().splitlines()[-1]}" + text += f"\n\n{error.strip().splitlines()[-1]}" try: send_notification(client, settings, text) diff --git a/debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py b/debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py new file mode 100644 index 0000000..4f47e49 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py @@ -0,0 +1,61 @@ +from bec_widgets.utils.colors import get_accent_colors +from qtpy.QtCore import Qt, Signal + +# pylint: disable=E0611 +from qtpy.QtGui import QKeySequence +from qtpy.QtWidgets import QListWidget, QPushButton + + +class MyListWidget(QListWidget): + deletePressed = Signal() + emptySpaceClicked = Signal() + copyPressed = Signal() + pastePressed = Signal() + + def keyPressEvent(self, event): + if event.key() == Qt.Key_Delete and self.currentItem() is not None: + self.deletePressed.emit() + event.accept() + return + + if event.matches(QKeySequence.StandardKey.Copy) and self.currentItem() is not None: + self.copyPressed.emit() + event.accept() + return + + if event.matches(QKeySequence.StandardKey.Paste): + self.pastePressed.emit() + event.accept() + return + + super().keyPressEvent(event) + + def mousePressEvent(self, event): + if event.button() == Qt.LeftButton and self.itemAt(event.position().toPoint()) is None: + self.clearSelection() + self.setCurrentRow(-1) + self.emptySpaceClicked.emit() + return + + super().mousePressEvent(event) + + +class MyButton(QPushButton): + def __init__(self, text="", color="default", parent=None): + self.color = color + super().__init__(text, parent) + self.apply_theme() + + def apply_theme(self): + if self.isEnabled(): + colors = get_accent_colors() + color = getattr(colors, self.color).name() + self.setStyleSheet(f"QPushButton {{ background-color: {color}; color: white; }}") + else: + self.setStyleSheet( + "QPushButton {{background-color: rgb(120, 120, 120); color: white;}}" + ) + + def setEnabled(self, enable: bool = True): + super().setEnabled(enable) + self.apply_theme() diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 78cd84c..1a42bbe 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -22,13 +22,11 @@ from bec_lib.messages import VariableMessage from bec_qthemes import material_icon from bec_widgets.utils.bec_connector import ConnectionConfig from bec_widgets.utils.bec_widget import BECWidget -from bec_widgets.utils.colors import get_accent_colors from bec_widgets.utils.error_popups import SafeSlot from pydantic import ValidationError # pylint: disable=E0611 from qtpy.QtCore import Qt, QTimer, Signal -from qtpy.QtGui import QKeySequence from qtpy.QtWidgets import ( QApplication, QDialog, @@ -37,11 +35,9 @@ from qtpy.QtWidgets import ( QHBoxLayout, QLabel, QLineEdit, - QListWidget, QListWidgetItem, QMessageBox, QPlainTextEdit, - QPushButton, QVBoxLayout, QWidget, ) @@ -58,6 +54,7 @@ from .notifications import ( notify_item_finished, notify_schedule_state, ) +from .qt_widgets import MyButton, MyListWidget from .schedule_item import Schedule, ScheduleItem from .schedule_logic import index_of, pick_next_runnable, protected_prefix_length @@ -97,60 +94,6 @@ class ScheduleWidgetConfig(ConnectionConfig): schedule_name: str = "default_schedule" -class MyListWidget(QListWidget): - deletePressed = Signal() - emptySpaceClicked = Signal() - copyPressed = Signal() - pastePressed = Signal() - - def keyPressEvent(self, event): - if event.key() == Qt.Key_Delete and self.currentItem() is not None: - self.deletePressed.emit() - event.accept() - return - - if event.matches(QKeySequence.StandardKey.Copy) and self.currentItem() is not None: - self.copyPressed.emit() - event.accept() - return - - if event.matches(QKeySequence.StandardKey.Paste): - self.pastePressed.emit() - event.accept() - return - - super().keyPressEvent(event) - - def mousePressEvent(self, event): - if event.button() == Qt.LeftButton and self.itemAt(event.position().toPoint()) is None: - self.clearSelection() - self.setCurrentRow(-1) - self.emptySpaceClicked.emit() - return - - super().mousePressEvent(event) - - -class MyButton(QPushButton): - def __init__(self, text="", color="default", parent=None): - self.color = color - super().__init__(text, parent) - - def apply_theme(self): - if self.isEnabled(): - colors = get_accent_colors() - color = getattr(colors, self.color).name() - self.setStyleSheet(f"QPushButton {{ background-color: {color}; color: white; }}") - else: - self.setStyleSheet( - "QPushButton {{background-color: rgb(120, 120, 120); color: white;}}" - ) - - def setEnabled(self, enable: bool = True): - super().setEnabled(enable) - self.apply_theme() - - class Scheduler(BECWidget, QWidget): """Schedule, persist and execute a sequence of BEC scan/device commands.""" @@ -1192,7 +1135,7 @@ class Scheduler(BECWidget, QWidget): def _run_all(self, repeat_aborted_item): notify_schedule_state( - self.client, self.schedule.notifications, self.schedule_name, "started" + self.client, self.schedule.notifications, self.schedule.schedule_name, "started" ) namespace = {"scans": self.scans, "dev": self.dev} while not self._abort_requested and not self._closing.is_set(): @@ -1207,15 +1150,18 @@ class Scheduler(BECWidget, QWidget): self._execute_item(next_item, namespace) if self._abort_requested: notify_schedule_state( - self.client, self.schedule.notifications, self.schedule_name, "aborted" + self.client, self.schedule.notifications, self.schedule.schedule_name, "aborted" ) elif self._closing.is_set(): notify_schedule_state( - self.client, self.schedule.notifications, self.schedule_name, "widget_closed" + self.client, + self.schedule.notifications, + self.schedule.schedule_name, + "widget_closed", ) else: notify_schedule_state( - self.client, self.schedule.notifications, self.schedule_name, "finished" + self.client, self.schedule.notifications, self.schedule.schedule_name, "finished" ) with self._lock: logger.info("in _run_all, set is_running to false") @@ -1252,7 +1198,9 @@ class Scheduler(BECWidget, QWidget): item.request_id = getattr(request, "requestID", None) self._persist_locked() - report.wait() + # RPC commands may not return a status, thus have no wait() + if item.kind != "custom": + report.wait() if self._closing.is_set(): # The widget was closed mid-item; exit without changing status in Redis. From abcebea6c5b06631010c20b5f9825ac1b276e804 Mon Sep 17 00:00:00 2001 From: x01da Date: Thu, 3 Sep 2026 14:55:30 +0200 Subject: [PATCH 14/56] wip --- .../widgets/scheduler/item_dialog.py | 137 +++++++++++++++--- .../widgets/scheduler/scheduler.py | 21 ++- 2 files changed, 139 insertions(+), 19 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index 3f5bf6d..74f2d57 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -14,14 +14,34 @@ Rather than asking the operator to remember and type only ever wants the configured scan name/args/kwargs, never an immediate submission - see `_collect_scan_result`. - a "Move" tab: pick a device and a target value/relative flag; -- a "Custom" tab: a free-text field, for anything else (including RPC - calls to other widgets), evaluated the same way as the other tabs. +- a "Digital Twin" tab: the beamline-alignment `DigitalTwin` widget, + embedded the same way as ScanControl. Instead of submitting anything + itself, OK captures a *snapshot* of `DigitalTwin.get_assistant_config()` + and stores it - execution later calls `move_all_axes(...)` with that + frozen config, so editing the (possibly separately open) Digital Twin + widget afterwards never affects an already-added schedule item, exactly + like a Scan item's captured args/kwargs aren't affected by reopening + ScanControl elsewhere. See `_collect_digital_twin_result`. +- an "Other" tab: a free-text field for anything else (including RPC + calls to other widgets), plus a couple of beamline-specific quick-fill + forms (ionization chamber gas mix, reference foil). Whichever tab is used, the dialog's only output is the same kind of plain command string the executor already knows how to run - this dialog adds a friendlier way to *build* that string, it doesn't change what happens with it afterwards. `kind`/`form_state` are carried along purely so "Edit..." -can reopen the dialog pre-filled instead of asking the user to start over. +can reopen the dialog pre-filled instead of asking the user to start over +- except for the Digital Twin tab, where "Edit..." currently falls back to +showing the generated command as read/write text on the "Other" tab rather +than reloading the captured config back into DigitalTwin's input fields; +see the note on `_apply_initial`. + +The Digital Twin item reuses `kind="move"` (not a new kind): it submits +through `scans.mv(...)`, exactly like the plain Move tab, so it should be +treated the same way everywhere else in the plugin that branches on kind - +not guard-protected, and counted under the "Movements" notification +toggle. A `form_state["source"] = "digital_twin"` marker is only used +locally, by this dialog, to tell the two apart when reopening for Edit. """ from __future__ import annotations @@ -47,11 +67,16 @@ from qtpy.QtWidgets import ( QLineEdit, QMessageBox, QPushButton, + QScrollArea, QTabWidget, QVBoxLayout, QWidget, ) +from ....bec_ipython_client.plugins.digital_twin.digital_twin import DigitalTwinCore +from ..digital_twin.calculations.calc_positions import calc_positions +from ..digital_twin.digital_twin import DigitalTwin +from ..digital_twin.offsets import Offsets from ..scan_control_xas.scan_control_xas import ScanControlXAS from .qt_widgets import MyButton @@ -59,9 +84,16 @@ logger = bec_logger.logger _DSPIN_RANGE = (-1e12, 1e12) +# Tab indices, named instead of magic numbers now that there are four - +# see _collect_result()/_apply_initial(). +_TAB_SCAN = 0 +_TAB_MOVE = 1 +_TAB_DIGITAL_TWIN = 2 +_TAB_OTHER = 3 + class ScheduleItemDialog(QDialog): - """Add or edit one schedule item, via ScanControl, a move form, or free text.""" + """Add or edit one schedule item, via ScanControl, a move form, Digital Twin, or free text.""" def __init__(self, scans, dev, parent=None, initial: dict | None = None, client=None): super().__init__(parent) @@ -78,6 +110,7 @@ class ScheduleItemDialog(QDialog): self._build_scan_tab() self._build_move_tab() + self._build_digital_twin_tab() self._build_custom_tab() buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) @@ -87,6 +120,12 @@ class ScheduleItemDialog(QDialog): buttons.rejected.connect(self.reject) layout.addWidget(buttons) + # The embedded DigitalTwin instance runs a 1s polling timer and a + # bec_dispatcher subscription for its whole lifetime - stop both + # when this dialog closes, however it closes (OK, Cancel, or the + # window's own close button), not just on accept. + self.finished.connect(self._cleanup_digital_twin) + self._apply_initial(initial or {}) # ------------------------------------------------------------------ # @@ -103,14 +142,6 @@ class ScheduleItemDialog(QDialog): self.scan_control.button_run_scan.hide() layout.addWidget(self.scan_control) - # hint = QLabel( - # "Configure the scan above, then confirm with OK below - it will be " - # "added to the schedule, not started immediately." - # ) - # hint.setWordWrap(True) - # hint.setStyleSheet("color: gray;") - # layout.addWidget(hint) - self.tabs.addTab(tab, "Scan") def _collect_scan_result(self) -> dict: @@ -195,6 +226,64 @@ class ScheduleItemDialog(QDialog): "form_state": {"device_name": device_name, "value": value, "relative": relative}, } + # ------------------------------------------------------------------ # + # Digital Twin tab - embeds the beamline-alignment DigitalTwin widget + # ------------------------------------------------------------------ # + def _build_digital_twin_tab(self): + tab = QWidget() + outer = QVBoxLayout(tab) + + # DigitalTwin defaults to a large fixed size (it's normally its + # own top-level window) - wrap it in a scroll area so this dialog + # doesn't have to grow to match it. + scroll = QScrollArea() + scroll.setWidgetResizable(True) + self.digital_twin = DigitalTwin(parent=scroll, client=self._client) + # Hide move and abs open buttons + for mover in self.digital_twin.mover.mover_widgets: + mover.btn_action.hide() + self.digital_twin.mover.abs.btn_action.hide() + + scroll.setWidget(self.digital_twin) + outer.addWidget(scroll) + + hint = QLabel( + "Configure the beamline alignment above, then confirm with Add below - the " + "computed motor targets are captured now and moved together (in one combined " + "move) when this schedule item runs, not immediately." + ) + hint.setWordWrap(True) + hint.setStyleSheet("color: gray;") + outer.addWidget(hint) + + self.tabs.addTab(tab, "Digital Twin") + + def _collect_digital_twin_result(self) -> dict: + config = self.digital_twin.get_assistant_config() + # beamline = self.digital_twin.beamline + + # # Init the class when the scheduler is opened + # digital_twin = DigitalTwinCore() + # # The command below would then execute the movement + # digital_twin.move_with_config(config) + + cmd = f"digital_twin.move_with_config({config})" + + return {"command": f"{cmd}", "kind": "custom", "form_state": {"text": cmd}} + + def _cleanup_digital_twin(self, *_): + digital_twin = getattr(self, "digital_twin", None) + if digital_twin is None: + return + try: + digital_twin._timer.stop() # pylint: disable=protected-access + except Exception: # pylint: disable=broad-except + logger.exception("Failed to stop the Digital Twin's reality-update timer.") + try: + digital_twin.cleanup() + except Exception: # pylint: disable=broad-except + logger.exception("Failed to clean up the embedded Digital Twin widget.") + # ------------------------------------------------------------------ # # Custom tab # ------------------------------------------------------------------ # @@ -204,7 +293,7 @@ class ScheduleItemDialog(QDialog): layout.addWidget( QLabel( "Free-form command, evaluated against `scans` and `dev` - use this for " - "anything the Scan/Move tabs don't cover, e.g. an RPC call to another widget." + "anything the other tabs don't cover, e.g. an RPC call to another widget." ) ) self.custom_edit = QLineEdit() @@ -339,19 +428,29 @@ class ScheduleItemDialog(QDialog): self._prefill_scan_tab( state["scan_name"], state.get("args") or [], state.get("kwargs") or {} ) - self.tabs.setCurrentIndex(0) + self.tabs.setCurrentIndex(_TAB_SCAN) + elif kind == "move" and state.get("source") == "digital_twin": + # Reloading a captured config back into DigitalTwin's own input + # fields would need inverting get_assistant_config()'s unit + # conversions and mode branching (fm_focus, mo1_mode, ...) + # field-by-field - not implemented yet. Fall back to showing + # the generated command as read/write text instead of silently + # dropping the captured config; the "Add" (=Ok) button below + # will just resubmit that text unchanged unless it's edited. + self.custom_edit.setText(initial.get("command", "")) + self.tabs.setCurrentIndex(_TAB_OTHER) elif kind == "move" and state.get("device_name"): idx = self.move_device_combo.findText(state["device_name"]) if idx >= 0: self.move_device_combo.setCurrentIndex(idx) self.move_value_spin.setValue(float(state.get("value", 0.0))) self.move_relative_check.setChecked(bool(state.get("relative", False))) - self.tabs.setCurrentIndex(1) + self.tabs.setCurrentIndex(_TAB_MOVE) elif initial.get("command"): # "custom" kind, or a legacy/unrecognized item - fall back to # showing the raw command text as-is. self.custom_edit.setText(state.get("text", initial["command"])) - self.tabs.setCurrentIndex(2) + self.tabs.setCurrentIndex(_TAB_OTHER) else: logger.warning(f"Unknown kind: {kind}") @@ -366,10 +465,12 @@ class ScheduleItemDialog(QDialog): def _collect_result(self) -> dict: current = self.tabs.currentIndex() - if current == 0: + if current == _TAB_SCAN: return self._collect_scan_result() - if current == 1: + if current == _TAB_MOVE: return self._collect_move_result() + if current == _TAB_DIGITAL_TWIN: + return self._collect_digital_twin_result() return self._collect_custom_result() def result(self) -> dict: diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 1a42bbe..a9139cd 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -10,17 +10,20 @@ or finished cannot. from __future__ import annotations import json +import sys import threading import time import traceback import uuid from typing import Literal, Optional +import numpy as np from bec_lib.endpoints import MessageEndpoints from bec_lib.logger import bec_logger from bec_lib.messages import VariableMessage from bec_qthemes import material_icon from bec_widgets.utils.bec_connector import ConnectionConfig +from bec_widgets.utils.bec_dispatcher import BECDispatcher from bec_widgets.utils.bec_widget import BECWidget from bec_widgets.utils.error_popups import SafeSlot from pydantic import ValidationError @@ -42,6 +45,7 @@ from qtpy.QtWidgets import ( QWidget, ) +from ....bec_ipython_client.plugins.digital_twin.digital_twin import DigitalTwinCore from .endpoints import schedule as schedule_endpoint from .enums import ScheduleItemStatus from .guard import SignalGuard @@ -148,6 +152,8 @@ class Scheduler(BECWidget, QWidget): self.get_bec_shortcuts() # -> self.client, self.dev, self.scans, self.queue self.connector = self.client.connector + self.digital_twin = DigitalTwinCore() + self._endpoint = schedule_endpoint(self.schedule_name) self._lock = threading.Lock() # guards self.schedule (see module docstring) self._abort_requested = False @@ -1137,7 +1143,12 @@ class Scheduler(BECWidget, QWidget): notify_schedule_state( self.client, self.schedule.notifications, self.schedule.schedule_name, "started" ) - namespace = {"scans": self.scans, "dev": self.dev} + namespace = { + "scans": self.scans, + "dev": self.dev, + "digital_twin": self.digital_twin, + "np": np, + } while not self._abort_requested and not self._closing.is_set(): with self._lock: next_item = self._pick_next_runnable_locked(repeat_aborted_item) @@ -1274,3 +1285,11 @@ class Scheduler(BECWidget, QWidget): self._emit_schedule_changed() return time.sleep(0.5) + + +if __name__ == "__main__": + app = QApplication(sys.argv) + dispatcher = BECDispatcher(gui_id="digital_twin") + win = Scheduler() + win.show() + sys.exit(app.exec_()) From d96c48be7af7f5cd1ff6d1dd007e0dd2aee9f3e1 Mon Sep 17 00:00:00 2001 From: x01da Date: Thu, 3 Sep 2026 14:56:31 +0200 Subject: [PATCH 15/56] wip(digital_twin): Move core logic to ipython client --- .../plugins/digital_twin/__init__.py | 3 + .../plugins/digital_twin/beamline.py | 51 +++ .../plugins/digital_twin/digital_twin.py | 389 ++++++++++++++++++ .../plugins/digital_twin/types.py | 83 ++++ .../plugins/digital_twin/x01da_offsets.yaml | 50 +++ .../plugins/digital_twin/x01da_parameters.py | 323 +++++++++++++++ .../plugins/digital_twin/x10da_offsets.yaml | 59 +++ .../plugins/digital_twin/x10da_parameters.py | 296 +++++++++++++ .../startup/post_startup.py | 11 + .../calculations/calc_positions.py | 297 ------------- .../widgets/digital_twin/digital_twin.py | 80 +--- .../widgets/digital_twin/offsets.py | 83 ++++ 12 files changed, 1368 insertions(+), 357 deletions(-) create mode 100644 debye_bec/bec_ipython_client/plugins/digital_twin/__init__.py create mode 100644 debye_bec/bec_ipython_client/plugins/digital_twin/beamline.py create mode 100644 debye_bec/bec_ipython_client/plugins/digital_twin/digital_twin.py create mode 100644 debye_bec/bec_ipython_client/plugins/digital_twin/types.py create mode 100644 debye_bec/bec_ipython_client/plugins/digital_twin/x01da_offsets.yaml create mode 100644 debye_bec/bec_ipython_client/plugins/digital_twin/x01da_parameters.py create mode 100644 debye_bec/bec_ipython_client/plugins/digital_twin/x10da_offsets.yaml create mode 100644 debye_bec/bec_ipython_client/plugins/digital_twin/x10da_parameters.py delete mode 100644 debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_positions.py create mode 100644 debye_bec/bec_widgets/widgets/digital_twin/offsets.py diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin/__init__.py b/debye_bec/bec_ipython_client/plugins/digital_twin/__init__.py new file mode 100644 index 0000000..a42cb09 --- /dev/null +++ b/debye_bec/bec_ipython_client/plugins/digital_twin/__init__.py @@ -0,0 +1,3 @@ +from .beamline import get_parameters + +parameters = get_parameters() diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin/beamline.py b/debye_bec/bec_ipython_client/plugins/digital_twin/beamline.py new file mode 100644 index 0000000..3653284 --- /dev/null +++ b/debye_bec/bec_ipython_client/plugins/digital_twin/beamline.py @@ -0,0 +1,51 @@ +import socket + +from bec_lib import bec_logger + +from .types import BeamlineId + +logger = bec_logger.logger + + +def get_beamline_id() -> BeamlineId: + """ + Based on the bec servers hostname, tries to extract the beamline + identifier (e.g. x01da, x10da, etc). + + Raises: + ValueError if beamline cannot be extracted from hostname or beamline not implemented. + """ + bec_hostname = socket.gethostname() + start = bec_hostname.find("x") + if start != -1: + beamline = bec_hostname[start : start + 5] + match beamline: + case "x01da": + return BeamlineId.X01DA + case "x10da": + return BeamlineId.X10DA + case _: + raise ValueError(f"Not implemented beamline {beamline}") + else: + logger.warning(f"Failed to extract beamline from bec server hostname {bec_hostname}") + choice = input("Do you want to manually select a beamline? (yes/no): ").strip().lower() + if choice in ["yes", "y"]: + bl = input(f"Choose from: {[bl.value for bl in BeamlineId]}") + if bl in BeamlineId: + logger.info(f"Manually selected beamline {bl}") + return BeamlineId(bl) + else: + raise ValueError(f"Wrong selection {bl}") + else: + raise ValueError("Cannot open digital twin without a beamline") + + +def get_parameters(): + beamline = get_beamline_id() + if beamline == "x01da": + from . import x01da_parameters as parameters + elif beamline == "x10da": + from . import x10da_parameters as parameters + else: + raise ValueError(f"Unknown beamline: {beamline}") + return parameters diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin/digital_twin.py b/debye_bec/bec_ipython_client/plugins/digital_twin/digital_twin.py new file mode 100644 index 0000000..28019d2 --- /dev/null +++ b/debye_bec/bec_ipython_client/plugins/digital_twin/digital_twin.py @@ -0,0 +1,389 @@ +from pathlib import Path + +import numpy as np +import yaml +from bec_lib import bec_logger +from bec_lib.logger import bec_logger + +from . import parameters as bl +from .beamline import get_beamline_id +from .types import BeamlineId, ConfigDict + +OFFSET_FILE_X01DA = Path(__file__).with_name("x01da_offsets.yaml") +OFFSET_FILE_X10DA = Path(__file__).with_name("x10da_offsets.yaml") + +logger = bec_logger.logger + +""" +The idea is to move the core logic of digital_twin to this file. Only keep the gui elements in the widget. +This way, the scheduler widget can access digital twin without loading the GUI (GUI is still needed for the item creation, but not the item execution) + Scheduler will extract assistant inputs (get_assistant_config) during item creation + Scheduler will use digital_twin.calculate_positons to calculate positions and digital_twin.move_all to move the motors +""" + + +class DigitalTwinCore: + + def __init__(self): + logger.info("This is the digital twin from the ipython client!") + self.beamline = get_beamline_id() + self.offset_file = Path() + match self.beamline: + case "x01da": + self.offset_file = OFFSET_FILE_X01DA + case "x10da": + self.offset_file = OFFSET_FILE_X10DA + self.offsets = {} + self.load_offsets() + + def move_with_config(self, config): + positions = self.calc_positions(self.beamline, config) + positions = self.apply_offsets(positions, nested_config=True) + logger.info(f"Would now move to these positions: {positions}") + + def load_offsets(self): + if self.offsets == {}: + logger.info("Load beamline offsets") + if not self.offset_file.exists(): + raise FileNotFoundError(f"Offset file not found: {self.offset_file}") + + with self.offset_file.open("r", encoding="utf-8") as f: + data = yaml.safe_load(f) + + if not isinstance(data, dict): + raise ValueError(f"Expected a YAML mapping, got {type(data).__name__}") + + self.offsets = data + else: + logger.info("Unload beamline offsets") + self.offsets = {} + + def apply_offsets(self, config, nested_config=False): + for axis, axis_data in config.items(): + if axis in self.offsets: + axis_offsets = self.offsets[axis] + if "modifier" in axis_offsets and "offset" in axis_offsets: + for idx, rng in enumerate(axis_offsets["modifier"]["range"]): + modifier_axis = axis_offsets["modifier"]["axis"] + modifier_value = ( + config[modifier_axis]["value"] + if nested_config + else config[modifier_axis] + ) + if rng[0] < modifier_value < rng[1]: + if nested_config: + axis_data["value"] += axis_offsets["offset"][idx] + else: + config[axis] += axis_offsets["offset"][idx] + break + elif "offset" in axis_offsets: + if nested_config: + axis_data["value"] += axis_offsets["offset"] + else: + config[axis] += axis_offsets["offset"] + return config + + def remove_offsets(self, config): + for axis, _ in config.items(): + if axis in self.offsets: + axis_offsets = self.offsets[axis] + if "modifier" in axis_offsets and "offset" in axis_offsets: + for idx, rng in enumerate(axis_offsets["modifier"]["range"]): + if rng[0] < config[axis_offsets["modifier"]["axis"]] < rng[1]: + config[axis] -= axis_offsets["offset"][idx] + break + elif "offset" in axis_offsets: + config[axis] -= axis_offsets["offset"] + return config + + @staticmethod + def calc_positions(beamline: BeamlineId, cfg: ConfigDict) -> dict[str, dict[str, float]]: + """ + Calculates the positions of axes based on a beamline config. + + Args: + cfg(ConfigDict): Dictionary with beamline config + + Returns: + dict[str, dict[str, float]]: Dictionary mapping device names to dictionaries + containing a "value" key with the corresponding float value (position). + """ + + pos = {} + + ## FE slits + trxr = -np.arctan(cfg["h_acc"]) * bl.feSlits.center1[1] + trxw = ( + (np.arctan(cfg["h_acc"]) * bl.feSlits.center1[1]) + / bl.feSlits.center1[1] + * bl.feSlits.center2[1] + ) + tryb = -np.arctan(cfg["v_acc"]) * bl.feSlits.center1[1] + tryt = ( + (np.arctan(cfg["v_acc"]) * bl.feSlits.center1[1]) + / bl.feSlits.center1[1] + * bl.feSlits.center2[1] + ) + + xgap = trxw - trxr + ygap = tryt - tryb + + pos["sldi_gapx"] = {"value": xgap} + pos["sldi_gapy"] = {"value": ygap} + + ## Collimating Mirror + obj_dist = bl.cm.center[1] # object distance + beam_vs = 2 * obj_dist * np.tan(cfg["v_acc"]) # vertical size of beam after CM + + # TRX + if cfg["cm_stripe"] in bl.cm.surface: + index = bl.cm.surface.index(cfg["cm_stripe"]) + else: + raise ValueError(f"Requested stripe {cfg['cm_stripe']} not found in parameters!") + cm_trx = -(bl.cm.limOptX[0][index] + bl.cm.limOptX[1][index]) / 2 + pos["cm_trx"] = {"value": cm_trx} + + # TRY + height = obj_dist * np.tan(cfg["v_acc"]) ** 2 * 1 / np.tan(cfg["cm_pitch"]) + pos["cm_try"] = {"value": height} + + # Pitch + pos["cm_rotx"] = { + "value": -cfg["cm_pitch"] * 1e3 + } # invert and convert to mrad (same as EGU of rotx axis) + + # Bending Radius + radius = ( + 2.0 * obj_dist / np.sin(cfg["cm_pitch"]) + ) # Elements of modern X-ray Physics, page 108 ff. + pos["cm_bnd_radius"] = {"value": radius * 1e-6} # Convert to km + + ## Monochromator + if cfg["mo1_mode"] == "Monochromatic": + # Add 2x CM pitch to the bragg angle + bragg = cfg["mo1_bragg"] + elif cfg["mo1_mode"] == "Pinkbeam": + # Align xtal surfaces parallel to beam + bragg = 0 + else: + raise ValueError("Monochromator mode not supported") + pos["mo1_bragg_angle"] = {"value": bragg / np.pi * 180} # Bragg angle in deg + + # TRY, Height + l = bl.mo1.xtalGap[0] / np.sin(cfg["mo1_bragg"]) + yhor = l * np.cos(2.0 * (cfg["mo1_bragg"] + cfg["cm_pitch"])) + yver = yhor * np.tan(2.0 * cfg["cm_pitch"]) + + if cfg["mo1_mode"] == "Monochromatic": + beam_offset_mo1 = ( + l * np.sin(2.0 * (cfg["mo1_bragg"] + cfg["cm_pitch"])) - yver + ) # Resultat ist korrekt! + elif cfg["mo1_mode"] == "Pinkbeam": + beam_offset_mo1 = 0 + else: + raise ValueError("Monochromator mode not supported") + + def csc(a): + return 1 / np.sin(a) + + def cot(a): + return 1 / np.tan(a) + + # calculate height of center of first crystal surface + f = bl.mo1.rotOffset # rotation offset, mm + d = bl.mo1.heightOffset # xtal height offset, mm + c = d * csc(cfg["mo1_bragg"]) - f * cot(cfg["mo1_bragg"]) + + # Calculate height of center of rotation + b = np.sqrt( + d**2 * csc(cfg["mo1_bragg"]) ** 2 + - 2 * d * f * cot(cfg["mo1_bragg"]) * csc(cfg["mo1_bragg"]) + + f**2 * cot(cfg["mo1_bragg"]) ** 2 + + f**2 + ) + h = np.cos(np.pi / 2 - np.arctan(f / c) - cfg["mo1_bragg"] - 2 * cfg["cm_pitch"]) * b + h2 = ((bl.mo1.center[1] - bl.cm.center[1]) - np.sqrt(b**2 - h**2)) * np.tan( + 2 * cfg["cm_pitch"] + ) + height_mo1_real = ( + h + h2 + ) # per design, the height should not change if the pitch of the CM is not changed! + if cfg["mo1_mode"] == "Monochromatic": + pass + elif cfg["mo1_mode"] == "Pinkbeam": + height_mo1_real = ( + height_mo1_real - 13 + ) # Move down to let beam pass between both crystal without touching copper cooler + else: + raise ValueError("Monochromator mode not supported") + pos["mo1_try"] = {"value": height_mo1_real} + + # TRX, Crystal selection + if cfg["mo1_mode"] == "Monochromatic": + xtal = cfg["mo1_xtal"].translate( + str.maketrans("", "", "()") + ) # Remove brackets from xtal name to conform with parameters + if xtal in bl.mo1.xtal: + index = bl.mo1.xtal.index(xtal) + else: + raise ValueError(f"Requested xtal {xtal} not found in parameters!") + pos["mo1_trx"] = {"value": bl.mo1.xtalOffsetX[index]} + else: + pos["mo1_trx"] = {"value": 0} + + diag = bl.mo1.xtalGap[0] / np.sin(cfg["mo1_bragg"]) # Calculations for Mono + dz = diag * np.cos(2 * (cfg["cm_pitch"] + cfg["mo1_bragg"])) + + ## Slits 1 + d = bl.opSlits1.center[1] - bl.cm.center[1] - dz + sl1_beam_height = d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1 + pos["sl1_centery"] = {"value": sl1_beam_height} + pos["sl1_gapy"] = {"value": beam_vs} + + ## Beam Monitor 1 + d = bl.opBM1.center[1] - bl.cm.center[1] - dz + bm1_beam_height = d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1 + pos["bm1_try"] = {"value": bm1_beam_height} + + ## Focusing Mirror + p = bl.fm.center[1] + q = cfg["smpl"] - bl.fm.center[1] + f = (p * q) / (p + q) # focal length + + # Bender radius + if cfg["fm_qy"] is None: + radius = 2 * q / np.sin(cfg["fm_rotx"]) # ideal bending radius for focused beam + else: + radius = ( + 2 * cfg["fm_qy"] / np.sin(cfg["fm_rotx"]) + ) # ideal bending radius for unfocused beam + pos["fm_bnd_radius"] = {"value": radius * 1e-6} # Convert to km + + # Pitch + d = bl.fm.center[1] - bl.cm.center[1] - dz + fm_rotx = ( + 2 * cfg["cm_pitch"] - cfg["fm_rotx"] + ) # calculate pitch in absolute values (according to horizontal plane) + pos["fm_rotx"] = { + "value": -fm_rotx * 1e3 + } # invert and convert to mrad (same as EGU of rotx axis) + + if cfg["fm_stripe"] in ("Rh (toroid)", "Pt (toroid)"): + + # TRY + if cfg["fm_stripe"] == "Rh (toroid)": + r = bl.fm.r[0] + h_cyl = bl.fm.hToroid[0] + else: # PT toroid + r = bl.fm.r[1] + h_cyl = bl.fm.hToroid[1] + width_beam = 2 * bl.fm.center[1] * np.tan(cfg["h_acc"] * 1e-3) + alpha = np.arccos(1 - width_beam**2 / (2 * r**2)) + h = r - (r * np.cos(alpha / 2)) + fm_beam_height = (d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1) * cfg[ + "fm_gain_height" + ] + fm_height = (d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1 - h_cyl + h / 2) * cfg[ + "fm_gain_height" + ] + pos["fm_try"] = {"value": fm_height} + + # TRX + if cfg["fm_stripe"] == "Rh (toroid)": + x_cyl = -bl.fm.xToroid[0] + else: + x_cyl = -bl.fm.xToroid[1] + pos["fm_trx"] = {"value": x_cyl} + + elif cfg["fm_stripe"] in ("Rh (flat)", "Pt (flat)"): + + # TRY + fm_height = (d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1) * cfg["fm_gain_height"] + fm_beam_height = fm_height + pos["fm_try"] = {"value": fm_height} + + # TRX + if cfg["fm_stripe"] == "Rh (flat)": + x_flat = -bl.fm.xFlat[0] + else: + x_flat = -bl.fm.xFlat[1] + pos["fm_trx"] = {"value": x_flat} + + else: + raise ValueError("FM Stripe selection not valid") + + pos["fm_roty"] = {"value": 0} + pos["fm_rotz"] = {"value": 0} + + ## Slits 2 + if hasattr(bl, "opSlits2"): + d = bl.opSlits2.center[1] - bl.fm.center[1] + sl2_beam_height = fm_beam_height - d * np.tan( + -(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"]) + ) + pos["sl2_centery"] = {"value": sl2_beam_height} + pos["sl2_gapy"] = {"value": beam_vs} + + ## Beam Monitor 2 + d = bl.opBM2.center[1] - bl.fm.center[1] + bm2_beam_height = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) + pos["bm2_try"] = {"value": bm2_beam_height} + + ## Optical Table + + if beamline == "x01da": + # TRY + d = bl.ehWindow.center[1] - bl.fm.center[1] + ot_height = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) + pos["ot_try"] = {"value": ot_height} + + # Pitch + ot_pitch = -(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"]) + pos["ot_rotx"] = {"value": ot_pitch * 1e3} + + # TRZ ES1 + ot_es1_trz = cfg["smpl"] + pos["ot_es1_trz"] = {"value": ot_es1_trz} + + # ES0 exit window + pos["es0wi_try"] = { + "value": 5 + } # At 5mm, the middle of the window is 500 mm from the table (neutral position) + else: + # Exit window height + d = bl.ehWindow.center[1] - bl.fm.center[1] + es0wi_try = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) + pos["es0wi_try"] = {"value": es0wi_try} + + # ES1 table height + d = bl.es1.center[1] - bl.fm.center[1] + es1_try = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) + pos["es1_try"] = {"value": es1_try} + + # IC0 height + d = bl.es1ic0.center[1] - bl.fm.center[1] + es1ic0_try = ( + fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - es1_try + ) + pos["es1ic0_try"] = {"value": es1ic0_try} + + # IC1 height + d = bl.es1ic1.center[1] - bl.fm.center[1] + es1ic1_try = ( + fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - es1_try + ) + pos["es1ic1_try"] = {"value": es1ic1_try} + + # IC2 height + d = bl.es1ic2.center[1] - bl.fm.center[1] + es1ic2_try = ( + fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - es1_try + ) + pos["es1ic2_try"] = {"value": es1ic2_try} + + # ES2 table height + d = bl.es2.center[1] - bl.fm.center[1] + es2_try = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) + pos["es2_try"] = {"value": es2_try} + + return pos diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin/types.py b/debye_bec/bec_ipython_client/plugins/digital_twin/types.py new file mode 100644 index 0000000..d5c0393 --- /dev/null +++ b/debye_bec/bec_ipython_client/plugins/digital_twin/types.py @@ -0,0 +1,83 @@ +"""Types used for the beamline config and for plotting data""" + +from enum import Enum +from typing import TypedDict + + +class BeamlineId(str, Enum): + """ + Identifier for supported beamlines. + """ + + X01DA = "x01da" + X10DA = "x10da" + + +class ConfigDict(TypedDict): + """ + Typed dictionary representing the beamline configuration. + + Attributes: + energy (float): Beam energy. + h_acc (float): Horizontal acceptance. + v_acc (float): Vertical acceptance. + cm_pitch (float): CM pitch angle. + cm_stripe (str): CM stripe name. + cm_trx (float): CM translation x. + mo1_mode (str): MO1 mode. + mo1_xtal (str): MO1 crystal. + mo1_bragg (float): MO1 Bragg angle. + fm_rotx (float): FM rotation x. + fm_stripe (str): FM stripe name. + fm_trx (float): FM translation x. + fm_qy (float): FM qy value. + fm_gain_height (int): FM gain height. + smpl (float): Sample value. + """ + + energy: float + h_acc: float + v_acc: float + cm_pitch: float + cm_stripe: str + cm_trx: float + mo1_mode: str + mo1_xtal: str + mo1_bragg: float + fm_rotx: float + fm_stripe: str + fm_trx: float + fm_qy: None | float + fm_gain_height: int + smpl: float + + +class DataDict(TypedDict): + """ + Typed dictionary representing plot data. + + Attributes: + x (list[float]): List of x-axis values. + y (list[float]): List of y-axis values. + """ + + x: list + y: list + + +class SurfaceDict(TypedDict): + """ + Typed dictionary representing the surfaces of a scene, + grouping plot data by surface type. + + Attributes: + cm (DataDict): Data for the cm surface. + mo1_1 (DataDict): Data for the mo1_1 surface. + mo1_2 (DataDict): Data for the mo1_2 surface. + fm (DataDict): Data for the fm surface. + """ + + cm: DataDict + mo1_1: DataDict + mo1_2: DataDict + fm: DataDict diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin/x01da_offsets.yaml b/debye_bec/bec_ipython_client/plugins/digital_twin/x01da_offsets.yaml new file mode 100644 index 0000000..f475d96 --- /dev/null +++ b/debye_bec/bec_ipython_client/plugins/digital_twin/x01da_offsets.yaml @@ -0,0 +1,50 @@ +cm_try: + offset: 0.15 + +mo1_trx: + modifier: + axis: mo1_trx + range: [[-30, -0.1], [0.1, 30]] + offset: [-2.3, 1.31] + +mo1_try: + modifier: + axis: mo1_trx + range: [[-30, -0.1], [0.1, 30]] + offset: [-1.78, -1.78] + +sl1_centery: + offset: -1.2 + +fm_trx: + modifier: + axis: fm_trx + range: [[-66, -31], [-24, 7], [11, 31], [38, 66]] + offset: [-0.61, 0, 0, -0.16] + +fm_try: + modifier: + axis: fm_trx + range: [[-66, -31], [-24, 7], [11, 31], [38, 66]] + offset: [0.028, 0, 0, -0.45] + +fm_rotx: + modifier: + axis: fm_trx + range: [[-66, -31], [-24, 7], [11, 31], [38, 66]] + offset: [0.027, 0, 0, 0.045] + +fm_roty: + modifier: + axis: fm_trx + range: [[-66, -31], [-24, 7], [11, 31], [38, 66]] + offset: [-0.038, 0, 0, -0.053] + +sl2_centery: + offset: -0.7 + +ot_try: + offset: -0.49 + +ot_rotx: + offset: 0 \ No newline at end of file diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin/x01da_parameters.py b/debye_bec/bec_ipython_client/plugins/digital_twin/x01da_parameters.py new file mode 100644 index 0000000..214cb7d --- /dev/null +++ b/debye_bec/bec_ipython_client/plugins/digital_twin/x01da_parameters.py @@ -0,0 +1,323 @@ +""" +X01DA / Debye Beamline Parameters. +This file describes the parameter of each component of the Debye beamline +to be used for raytracing and geometrical calculations. +""" + +from collections import namedtuple + +import numpy as np +import xrt.backends.raycing.materials as rm + +# XRT definitions +filterBeryl = rm.Material("Be", rho=1.85, kind="plate") # pyright: ignore[reportArgumentType] +filterDiamond = rm.Material("C", rho=3.52, kind="plate") # pyright: ignore[reportArgumentType] +filterGraphite = rm.Material("C", rho=2.266, kind="plate") # pyright: ignore[reportArgumentType] + +stripeSi = rm.Material("Si", rho=2.33) # pyright: ignore[reportArgumentType] +stripePt = rm.Material("Pt", rho=21.45) # pyright: ignore[reportArgumentType] +stripeRh = rm.Material("Rh", rho=12.41) # pyright: ignore[reportArgumentType] +stripeCr = rm.Material("Cr", rho=7.14) # pyright: ignore[reportArgumentType] +stripePyrex = rm.Material( + "Si", rho=2.20 +) # Use Si as bare element and the density of SiO2 # pyright: ignore[reportArgumentType] + +si111_1 = rm.CrystalSi(hkl=(1, 1, 1), tK=77) # first xtal surface +si311_1 = rm.CrystalSi(hkl=(3, 1, 1), tK=77) # first xtal surface +si333_1 = rm.CrystalSi(hkl=(3, 3, 3), tK=77) # first xtal surface +si511_1 = rm.CrystalSi(hkl=(5, 1, 1), tK=77) # first xtal surface +si111_2 = rm.CrystalSi(hkl=(1, 1, 1), tK=77) # second xtal surface +si311_2 = rm.CrystalSi(hkl=(3, 1, 1), tK=77) # second xtal surface +si333_2 = rm.CrystalSi(hkl=(3, 3, 3), tK=77) # second xtal surface +si511_2 = rm.CrystalSi(hkl=(5, 1, 1), tK=77) # second xtal surface + +filterDiamond = rm.Material("C", rho=3.52, kind="plate") # pyright: ignore[reportArgumentType] +filterBe = rm.Material("Be", rho=1.85, kind="plate") # pyright: ignore[reportArgumentType] +filterSi3N4 = rm.Material( + ["Si", "N"], quantities=[3, 4], rho=3.44, kind="plate" +) # pyright: ignore[reportArgumentType] +filterAl = rm.Material("Al", rho=2.69, kind="plate") # pyright: ignore[reportArgumentType] +filterGraphite = rm.Material("C", rho=2.266, kind="plate") # pyright: ignore[reportArgumentType] + +# General parameters +sourceHeight = 0 + +# Synchrotron +synchrotron = namedtuple( + "synchrotron", ["eE", "eI", "eEspread", "eEpsilonX", "eEpsilonZ", "betaX", "betaZ"] +) + +sls1 = synchrotron( + eE=2.4, eI=0.4, eEspread=0.878e-3, eEpsilonX=5.63, eEpsilonZ=0.007, betaX=0.45, betaZ=14.4 +) + +sls2 = synchrotron( + eE=2.7, eI=0.4, eEspread=1.147e-3, eEpsilonX=0.156, eEpsilonZ=0.01, betaX=0.18, betaZ=4.6 +) + +# Source +bendingMagnet = namedtuple("bendingMagnet", ["name", "center", "sync", "B0"]) + +sls1_14t = bendingMagnet(name="FE-BM-SLS1-1.4T", center=(0, 0, 0), sync=sls1, B0=1.4) + +sls2_21t = bendingMagnet(name="FE-BM-SLS2-2.1T", center=(0, 0, 0), sync=sls2, B0=2.1) + +sls2_35t = bendingMagnet(name="FE-BM-SLS2-3.5T", center=(0, 0, 0), sync=sls2, B0=3.5) + +sls2_50t = bendingMagnet(name="FE-BM-SLS2-5.0T", center=(0, 0, 0), sync=sls2, B0=5.0) + +# FE slits +fe_slits = namedtuple("slits", ["name", "center", "center1", "center2", "maxDivH", "maxDivV"]) + +feSlits = fe_slits( + name="FE-SLITS", + center=(0, 6117, sourceHeight), + center1=(0, 5045, sourceHeight), + center2=(0, 5289.5, sourceHeight), + maxDivH=1.8e-3, + maxDivV=0.8e-3, +) + +# FE Window +filt = namedtuple( + "filt", ["name", "center", "pitch", "limPhysX", "limPhysY", "surface", "material", "thickness"] +) + +feWindow = filt( + name="FE-WINDOW", + center=(0.0, 7020, sourceHeight), + pitch=np.pi / 2, + limPhysX=(-6, 6), + limPhysY=(-3.0, 3.0), + surface="None", + material=filterDiamond, + thickness=0.1, +) +feWindow = feWindow._replace(surface=f"CVD Diamond window {feWindow.thickness*1e3:0.0f} $\\mu$m") + +# Collimating mirror +collimatingMirror = namedtuple( + "collimatingMirror", + [ + "name", + "center", + "surface", + "material", + "limPhysX", + "limPhysY", + "limOptX", + "limOptY", + "R", + "pitch", + "jack1", + "jack2", + "jack3", + "tx1", + "tx2", + ], +) + +cm = collimatingMirror( + name="FE-CM", + center=[0, 6890, sourceHeight], + surface=("Si", "Pt", "Rh"), + material=(stripeSi, stripePt, stripeRh), + limPhysX=(-34, 34), + limPhysY=(-600, 600), + limOptX=((-21, -7, 14), (-11, 11, 23)), + limOptY=((-500, -500, -500), (500, 500, 500)), + R=[3e6, 15e6], + pitch=[-5.0e-3, -0.0e-3], + jack1=[0.0, 7210.0, 0.0], # Tripod X, Y, Z (global) + jack2=[-210.0, 8310.0, 0.0], + jack3=[210.0, 8310.0, 0.0], + tx1=[0.0, -575.5], # X-Stage 1 [x, y] (local) + tx2=[0.0, 575], +) # X-Stage 2 + +apertures = namedtuple("apertures", ["name", "center", "opening"]) + +fePS = apertures( + name="FE-PS", center=[0, 8815, sourceHeight], opening=[-20.0, 20.0, -20.0 + 12.5, 20.0 + 12.5] +) # left, right, bottom, top + +opWbBsBlock = apertures( + name="OP-WB-BS-BLOCK", center=[0.0, 13860, sourceHeight], opening=[-18.0, 18.0, 25, 85.5] +) # left, right, bottom, top +# opening=[-18., 18., 42, 76], # X10DA + +# Monochromator +monochromator = namedtuple( + "monochromator", + [ + "name", + "center", + "xtal", + "material1", + "material2", + "xtalWidth", + "xtalOffsetX", + "xtalLength1", + "xtalLength2", + "xtalGap", + "rotOffset", + "heightOffset", + "braggLim", + "jack1", + "jack2", + "jack3", + "tx", + ], +) + +mo1 = monochromator( + name="OP-MO1", + center=[0.0, 11750, sourceHeight], + xtal=("Si311", "Si111"), + material1=(si311_1, si111_1), + material2=(si311_2, si111_2), + xtalWidth=(24, 24), + xtalOffsetX=(-21.2, 21.2), + xtalLength1=(55, 55), + xtalLength2=(105, 105), + xtalGap=(8, 8), + rotOffset=6, + heightOffset=8.5, + braggLim=[3.6, 33], + jack1=[0.0, 11350.0, 0.0], # Tripod maybe not available! + jack2=[-400.0, 12350.0, 0.0], + jack3=[400.0, 12350.0, 0.0], + tx=0.0, +) # X-Stage [x] + +mo2 = monochromator( + name="OP-CCM2", + center=[0.0, 13250, sourceHeight], + xtal=("Si311", "Si111"), + material1=(si311_1, si111_1), + material2=(si311_2, si111_2), + xtalWidth=(24, 24), + xtalOffsetX=(-21, 21), + xtalLength1=(55, 55), + xtalLength2=(105, 105), + xtalGap=(8, 8), + rotOffset=6, + heightOffset=8.5, + braggLim=[3.6, 33], + jack1=[0.0, 13350.0, 0.0], # Tripod maybe not available! + jack2=[-400.0, 14350.0, 0.0], + jack3=[400.0, 14350.0, 0.0], + tx=0.0, +) # X-Stage [x] + +# OP Slits +op_slits = namedtuple("op_slits", ["name", "center"]) + +opSlits1 = op_slits(name="OP-SLITS 1", center=(0, 14349.6, sourceHeight)) + +opSlits2 = op_slits(name="OP-SLITS 2", center=(0, 18134.8, sourceHeight)) + +# OP Beam Monitors +op_bm = namedtuple("op_bm", ["name", "center"]) + +opBM1 = op_bm(name="OP Beam Monitor 1", center=(0, 14599.6, sourceHeight)) + +opBM2 = op_bm(name="OP Beam Monitor 2", center=(0, 18384.8, sourceHeight)) + +# Focusing mirror +focusingMirror = namedtuple( + "focusingMirror", + [ + "name", + "center", + "surfaceToroid", + "materialToroid", + "surfaceFlat", + "materialFlat", + "limPhysXToroid", + "limPhysYToroid", + "limPhysXFlat", + "limPhysYFlat", + "limOptXToroid", + "limOptYToroid", + "limOptXFlat", + "limOptYFlat", + "R", + "pitch", + "r", + "xToroid", + "xFlat", + "hToroid", + "jack1", + "jack2", + "jack3", + "tx1", + "tx2", + ], +) + +fm = focusingMirror( + name="OP-FM", + center=[0.0, 15670, sourceHeight], # nominal height 58 mm above ring, SLS1! + surfaceToroid=("Rh", "Pt"), + materialToroid=(stripeRh, stripePt), + surfaceFlat=("Rh", "Pt"), + materialFlat=(stripeRh, stripePt), + limPhysXToroid=(-79.0, 79.0), + limPhysYToroid=(-575.0, 575.0), + limPhysXFlat=(-79.0, 79.0), + limPhysYFlat=(-575.0, 575.0), + limOptXToroid=((-38, 66), (-66, 31)), + limOptYToroid=((-500.0, -500.0), (500.0, 500.0)), + limOptXFlat=((-11.45, 23.55), (-30.45, -6.45)), + limOptYFlat=((-500.0, -500.0), (500.0, 500.0)), + R=[3e6, 15e6], + pitch=[-5.0e-3, 0e-3], + r=[35.510, 24.986], + xToroid=[-52, 48.5], # offset in local x + xFlat=[-20.95, 8.55], + hToroid=[2.88, 7.15], # depth of the cylinder at x = xCylinder1 and x = xCylinder2. + jack1=[-130.0, 15535 - 538.0, 0.0], + jack2=[130.0, 15535 + 538.0, 0.0], + jack3=[0.0, 15535 + 538.0, 0.0], + tx1=[0.0, -575.0], # X-Stage 1 [x, y] + tx2=[0.0, 575.0], +) # X-Stage 2 [x, y] + +# EH Window +ehWindow = filt( + name="EH-WINDOW", + center=(0.0, 19998.3, sourceHeight), + pitch=np.pi / 2, + limPhysX=(-20.0, 20.0), + limPhysY=(-4, 4), + surface="None", + material=filterSi3N4, + thickness=0.002, +) +ehWindow = ehWindow._replace(surface=f"Beryllium window {ehWindow.thickness*1e3:0.0f} $\\mu$m") + +# Sample +sample = namedtuple("sample", ["name", "center"]) + +smpl = sample(name="EH-SMPL", center=[0, 23365, sourceHeight]) + +smpl2 = sample(name="EH-SMPL2", center=[0, 27500, sourceHeight]) + +tables = {} + +# Vacuum pipes +# DN40CF ID = 35 mm oder 37 mm +# DN50CF ID = 47.5 mm +# DN63CF ID = 60.2 mm oder 66 mm +# DN100CF ID = 97.4 mm oder 104 mm +pipe = namedtuple("pipes", ["center", "diameter", "start", "end"]) +vacuum_pipes = pipe( + center=[27.5, (37.5 + 27.5) / 2, 37.5, 62.5, 72.5], + diameter=[97.4, 97.4, 97.4, 97.4, 97.4], + start=[10952.88, 11750 + 250, mo2.center[1] + 250, 14000, fm.center[1]], + end=[11750 - 250, mo2.center[1] - 250, 14000, fm.center[1], ehWindow.center[1]], +) + +Walls = namedtuple("walls", ["start", "end", "height"]) +walls = Walls(start=[13999.30], end=[13999 + 75.5 + 30], height=[[-20, 25]]) diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin/x10da_offsets.yaml b/debye_bec/bec_ipython_client/plugins/digital_twin/x10da_offsets.yaml new file mode 100644 index 0000000..f0fe9a8 --- /dev/null +++ b/debye_bec/bec_ipython_client/plugins/digital_twin/x10da_offsets.yaml @@ -0,0 +1,59 @@ + +cm_try: + offset: -0.7 + +mo1_try: + offset: -31.42 + +mo1_trx: + modifier: + axis: mo1_trx + range: [[-30, -0.1], [0.1, 30]] + offset: [-4.3, 0] + +sl1_centery: + offset: -55.54 + +bm1_try: + offset: 52.22 + +fm_trx: + modifier: + axis: fm_trx + range: [[-100, -48], [-47, 0]] + offset: [-0.3, 0.52] + +fm_try: + modifier: + axis: fm_trx + range: [[-100, -48], [-47, 0]] + offset: [-42.56, -41.49] + +# pitch +fm_rotx: + modifier: + axis: fm_trx + range: [[-100, -48], [-47, 0]] + offset: [1.30, 1.049] + +# yaw +fm_roty: + modifier: + axis: fm_trx + range: [[-100, -48], [-47, 0]] + offset: [1.754, 1.924] + +bm2_try: + offset: -19 + +es0wi_try: + offset: -71.98 + +es1_try: + offset: -113.26 + +es1ic1_try: + offset: 10.39 + +es1ic2_try: + offset: 3.55 diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin/x10da_parameters.py b/debye_bec/bec_ipython_client/plugins/digital_twin/x10da_parameters.py new file mode 100644 index 0000000..b7b40a5 --- /dev/null +++ b/debye_bec/bec_ipython_client/plugins/digital_twin/x10da_parameters.py @@ -0,0 +1,296 @@ +""" +X10DA / SuperXAS Beamline Parameters. +This file describes the parameter of each component of the SuperXAS beamline +to be used for raytracing and geometrical calculations. +""" + +from collections import namedtuple + +import numpy as np +import xrt.backends.raycing.materials as rm + +# XRT definitions +filterBeryl = rm.Material("Be", rho=1.85, kind="plate") # pyright: ignore[reportArgumentType] +filterDiamond = rm.Material("C", rho=3.52, kind="plate") # pyright: ignore[reportArgumentType] +filterGraphite = rm.Material("C", rho=2.266, kind="plate") # pyright: ignore[reportArgumentType] + +stripeSi = rm.Material("Si", rho=2.33) # pyright: ignore[reportArgumentType] +stripePt = rm.Material("Pt", rho=21.45) # pyright: ignore[reportArgumentType] +stripeRh = rm.Material("Rh", rho=12.41) # pyright: ignore[reportArgumentType] +stripeCr = rm.Material("Cr", rho=7.14) # pyright: ignore[reportArgumentType] +stripePyrex = rm.Material( + "Si", rho=2.20 +) # Use Si as bare element and the density of SiO2 # pyright: ignore[reportArgumentType] + +si111_1 = rm.CrystalSi(hkl=(1, 1, 1), tK=77) # first xtal surface +si311_1 = rm.CrystalSi(hkl=(3, 1, 1), tK=77) # first xtal surface +si333_1 = rm.CrystalSi(hkl=(3, 3, 3), tK=77) # first xtal surface +si511_1 = rm.CrystalSi(hkl=(5, 1, 1), tK=77) # first xtal surface +si111_2 = rm.CrystalSi(hkl=(1, 1, 1), tK=77) # second xtal surface +si311_2 = rm.CrystalSi(hkl=(3, 1, 1), tK=77) # second xtal surface +si333_2 = rm.CrystalSi(hkl=(3, 3, 3), tK=77) # second xtal surface +si511_2 = rm.CrystalSi(hkl=(5, 1, 1), tK=77) # second xtal surface + +filterDiamond = rm.Material("C", rho=3.52, kind="plate") # pyright: ignore[reportArgumentType] +filterBe = rm.Material("Be", rho=1.85, kind="plate") # pyright: ignore[reportArgumentType] +filterSi3N4 = rm.Material( + ["Si", "N"], quantities=[3, 4], rho=3.44, kind="plate" +) # pyright: ignore[reportArgumentType] +filterAl = rm.Material("Al", rho=2.69, kind="plate") # pyright: ignore[reportArgumentType] +filterGraphite = rm.Material("C", rho=2.266, kind="plate") # pyright: ignore[reportArgumentType] + +# General parameters +sourceHeight = 0 + +# Synchrotron +synchrotron = namedtuple( + "synchrotron", ["eE", "eI", "eEspread", "eEpsilonX", "eEpsilonZ", "betaX", "betaZ"] +) + +sls1 = synchrotron( + eE=2.4, eI=0.4, eEspread=0.878e-3, eEpsilonX=5.63, eEpsilonZ=0.007, betaX=0.45, betaZ=14.4 +) + +sls2 = synchrotron( + eE=2.7, eI=0.4, eEspread=1.147e-3, eEpsilonX=0.156, eEpsilonZ=0.01, betaX=0.18, betaZ=4.6 +) + +# Source +bendingMagnet = namedtuple("bendingMagnet", ["name", "center", "sync", "B0"]) + +sls1_14t = bendingMagnet(name="FE-BM-SLS1-1.4T", center=(0, 0, 0), sync=sls1, B0=1.4) + +sls2_21t = bendingMagnet(name="FE-BM-SLS2-2.1T", center=(0, 0, 0), sync=sls2, B0=2.1) + +sls2_35t = bendingMagnet(name="FE-BM-SLS2-3.5T", center=(0, 0, 0), sync=sls2, B0=3.5) + +sls2_50t = bendingMagnet(name="FE-BM-SLS2-5.0T", center=(0, 0, 0), sync=sls2, B0=5.0) + +# FE slits +fe_slits = namedtuple("slits", ["name", "center", "center1", "center2", "maxDivH", "maxDivV"]) + +feSlits = fe_slits( + name="FE-SLITS", + center=(0, 6117, sourceHeight), + center1=(0, 5038.4, sourceHeight), + center2=(0, 5282.9, sourceHeight), + maxDivH=1.8e-3, + maxDivV=0.8e-3, +) + +# Filters +filt = namedtuple( + "filt", ["name", "center", "pitch", "limPhysX", "limPhysY", "surface", "material", "thickness"] +) + +feWindow = filt( + name="FE-WINDOW", + center=(0.0, 6158, sourceHeight), + pitch=np.pi / 2, + limPhysX=(-6, 6), + limPhysY=(-3.0, 3.0), + surface="None", + material=filterDiamond, + thickness=0.1, +) +feWindow = feWindow._replace( + surface="CVD Diamond window {0:0.0f} $\\mu$m".format(feWindow.thickness * 1e3) +) + +feFilt = filt( + name="FE-FI", + center=(0.0, 6590, sourceHeight), + pitch=np.pi / 2, + limPhysX=(-15, 15), + limPhysY=(-10, 10), + surface="None", + material=filterGraphite, + thickness=0.25, +) +feFilt = feFilt._replace(surface="Graphite filter {0:0.0f} $\\mu$m".format(feFilt.thickness * 1e3)) + +# Collimating mirror +collimatingMirror = namedtuple( + "collimatingMirror", + [ + "name", + "center", + "surface", + "material", + "limPhysX", + "limPhysY", + "limOptX", + "limOptY", + "R", + "pitch", + "jack1", + "jack2", + "jack3", + "tx1", + "tx2", + ], +) + +cm = collimatingMirror( + name="FE-CM", + center=[0, 7560.8, sourceHeight], + surface=("Pt", "Si", "Rh"), + material=(stripePt, stripeSi, stripeRh), + limPhysX=(-30, 30), + limPhysY=(-600, 600), + limOptX=((-21, -0.5, 11), (-4, 9.5, 23)), + limOptY=((-500, -500, -500), (500, 500, 500)), + R=[3e6, 15e6], + pitch=[1.4e-3, 4.5e-3], + jack1=[0.0, 7210.0, 0.0], # Tripod X, Y, Z (global) + jack2=[-210.0, 8310.0, 0.0], + jack3=[210.0, 8310.0, 0.0], + tx1=[0.0, -575.5], # X-Stage 1 [x, y] (local) + tx2=[0.0, 575], +) # X-Stage 2 + +apertures = namedtuple("apertures", ["name", "center", "opening"]) + +fePS = apertures( + name="FE-PS", center=[0, 8760, sourceHeight], opening=[-39 / 2, 39 / 2, -10, 29] +) # left, right, bottom, top + +opWbBsBlock = apertures( + name="OP-WB-BS-BLOCK", center=[0.0, 13606 - 135, sourceHeight], opening=[-18.0, 18.0, 42, 76] +) # left, right, bottom, top + +opSlits1 = apertures( + name="OP-SLITS 1", center=[0, 14145 - 135, sourceHeight], opening=[-35 / 2, 35 / 2, 47.5, 82.5] +) + +# OP Beam Monitors +op_bm = namedtuple("op_bm", ["name", "center"]) + +opBM1 = op_bm(name="OP Beam Monitor 1", center=(0, 14525 - 135, sourceHeight)) + +opBM2 = op_bm(name="OP Beam Monitor 2", center=(0, 17161.6 - 135, sourceHeight)) + +# Monochromator +monochromator = namedtuple( + "monochromator", + [ + "name", + "center", + "xtal", + "material1", + "material2", + "xtalWidth", + "xtalOffsetX", + "xtalLength1", + "xtalLength2", + "xtalGap", + "rotOffset", + "heightOffset", + "braggLim", + "jack1", + "jack2", + "jack3", + "tx", + ], +) + +mo1 = monochromator( + name="OP-CCM1", + center=[0.0, 11670 - 135, sourceHeight], + xtal=("Si311", "Si111"), + material1=(si311_1, si111_1), + material2=(si311_2, si111_2), + xtalWidth=(20, 20), + xtalOffsetX=(19.2, -19.2), + xtalLength1=(60, 60), + xtalLength2=(60, 60), + xtalGap=(8, 8), + rotOffset=6, # not sure what it is + heightOffset=8.5, # not sure what it is + braggLim=[4, 35], + jack1=[0.0, 11350.0, 0.0], # Tripod not available! + jack2=[-400.0, 12350.0, 0.0], + jack3=[400.0, 12350.0, 0.0], + tx=0.0, +) # X-Stage [x] + +# Focusing mirror +focusingMirror = namedtuple( + "focusingMirror", + [ + "name", + "center", + "surfaceToroid", + "materialToroid", + "limPhysXToroid", + "limPhysYToroid", + "limOptXToroid", + "limOptYToroid", + "R", + "pitch", + "r", + "xToroid", + "hToroid", + "jack1", + "jack2", + "jack3", + "tx1", + "tx2", + ], +) + +OFFSET_TRX = 46.8735 + +fm = focusingMirror( + name="OP-FM", + center=[0.0, 15580 - 135, sourceHeight], + surfaceToroid=("Rh", "Pt"), + materialToroid=(stripeRh, stripePt), + limPhysXToroid=(-54.0, 54.0), + limPhysYToroid=(-565.0, 565.0), + limOptXToroid=( + (43.388 + OFFSET_TRX, -4.865 + OFFSET_TRX), + (4.865 + OFFSET_TRX, -40.882 + OFFSET_TRX), + ), + limOptYToroid=((-500.0, -500.0), (500.0, 500.0)), + R=[3e6, 15e6], + pitch=[1.4e-3, 4.5e-3], + r=[30, 20], + xToroid=[24.126 + OFFSET_TRX, -22 + OFFSET_TRX], # offset in local x + hToroid=[7.0, 11.3], # depth of the cylinder at x = xCylinder1 and x = xCylinder2. + jack1=[0.0, 14980.0, 0.0], + jack2=[-75.0, 16180.0, 0.0], + jack3=[75.0, 16180.0, 0.0], + tx1=[0.0, -575.0], # X-Stage 1 [x, y] + tx2=[0.0, 575.0], +) # X-Stage 2 [x, y] + +# Entry wall experimental hutch: 21593 mm from source (SLS2) + +# Exit window +ehWindow = filt( + name="EH-WINDOW", + center=(0.0, 22063, sourceHeight), + pitch=np.pi / 2, + limPhysX=(-10.0, 10.0), + limPhysY=(17.5, 92.5), + surface="None", + material=filterBe, + thickness=0.25, +) +ehWindow = ehWindow._replace( + surface="Beryllium window {0:0.0f} $\\mu$m".format(ehWindow.thickness * 1e3) +) + +# Sample +sample = namedtuple("sample", ["name", "center"]) + +es1 = sample(name="ES1", center=[0, 23823, sourceHeight]) +es2 = sample(name="ES2", center=[0, 25843, sourceHeight]) + +# Ionization chambers +ic = namedtuple("sample", ["name", "center"]) + +es1ic0 = ic(name="ES1 IC0", center=[0, 23633, sourceHeight]) +es1ic1 = ic(name="ES1 IC1", center=[0, 24383, sourceHeight]) +es1ic2 = ic(name="ES1 IC2", center=[0, 24723, sourceHeight]) diff --git a/debye_bec/bec_ipython_client/startup/post_startup.py b/debye_bec/bec_ipython_client/startup/post_startup.py index 07d6da4..a85498d 100644 --- a/debye_bec/bec_ipython_client/startup/post_startup.py +++ b/debye_bec/bec_ipython_client/startup/post_startup.py @@ -34,3 +34,14 @@ to setup the prompts. """ # pylint: disable=invalid-name, unused-import, import-error, undefined-variable, unused-variable, unused-argument, no-name-in-module + +from bec_lib import bec_logger + +logger = bec_logger.logger + +logger.info("Using the Debye startup script.") + +from debye_bec.bec_ipython_client.plugins.digital_twin.digital_twin import DigitalTwinCore + +digital_twin = DigitalTwinCore() +logger.success("Digital Twin Core loaded. Use 'digital_twin' to access it.") diff --git a/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_positions.py b/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_positions.py deleted file mode 100644 index 3047bdf..0000000 --- a/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_positions.py +++ /dev/null @@ -1,297 +0,0 @@ -""" -Calculates the positions of axes based on a beamline config -""" - -import numpy as np -from bec_lib import bec_logger - -from .. import parameters as bl -from ..types import BeamlineId, ConfigDict - -logger = bec_logger.logger - - -def calc_positions(beamline: BeamlineId, cfg: ConfigDict) -> dict[str, dict[str, float]]: - """ - Calculates the positions of axes based on a beamline config. - - Args: - cfg(ConfigDict): Dictionary with beamline config - - Returns: - dict[str, dict[str, float]]: Dictionary mapping device names to dictionaries - containing a "value" key with the corresponding float value (position). - """ - - pos = {} - - ## FE slits - trxr = -np.arctan(cfg["h_acc"]) * bl.feSlits.center1[1] - trxw = ( - (np.arctan(cfg["h_acc"]) * bl.feSlits.center1[1]) - / bl.feSlits.center1[1] - * bl.feSlits.center2[1] - ) - tryb = -np.arctan(cfg["v_acc"]) * bl.feSlits.center1[1] - tryt = ( - (np.arctan(cfg["v_acc"]) * bl.feSlits.center1[1]) - / bl.feSlits.center1[1] - * bl.feSlits.center2[1] - ) - - xgap = trxw - trxr - ygap = tryt - tryb - - pos["sldi_gapx"] = {"value": xgap} - pos["sldi_gapy"] = {"value": ygap} - - ## Collimating Mirror - obj_dist = bl.cm.center[1] # object distance - beam_vs = 2 * obj_dist * np.tan(cfg["v_acc"]) # vertical size of beam after CM - - # TRX - if cfg["cm_stripe"] in bl.cm.surface: - index = bl.cm.surface.index(cfg["cm_stripe"]) - else: - raise ValueError(f"Requested stripe {cfg['cm_stripe']} not found in parameters!") - cm_trx = -(bl.cm.limOptX[0][index] + bl.cm.limOptX[1][index]) / 2 - pos["cm_trx"] = {"value": cm_trx} - - # TRY - height = obj_dist * np.tan(cfg["v_acc"]) ** 2 * 1 / np.tan(cfg["cm_pitch"]) - pos["cm_try"] = {"value": height} - - # Pitch - pos["cm_rotx"] = { - "value": -cfg["cm_pitch"] * 1e3 - } # invert and convert to mrad (same as EGU of rotx axis) - - # Bending Radius - radius = ( - 2.0 * obj_dist / np.sin(cfg["cm_pitch"]) - ) # Elements of modern X-ray Physics, page 108 ff. - pos["cm_bnd_radius"] = {"value": radius * 1e-6} # Convert to km - - ## Monochromator - if cfg["mo1_mode"] == "Monochromatic": - # Add 2x CM pitch to the bragg angle - bragg = cfg["mo1_bragg"] - elif cfg["mo1_mode"] == "Pinkbeam": - # Align xtal surfaces parallel to beam - bragg = 0 - else: - raise ValueError("Monochromator mode not supported") - pos["mo1_bragg_angle"] = {"value": bragg / np.pi * 180} # Bragg angle in deg - - # TRY, Height - l = bl.mo1.xtalGap[0] / np.sin(cfg["mo1_bragg"]) - yhor = l * np.cos(2.0 * (cfg["mo1_bragg"] + cfg["cm_pitch"])) - yver = yhor * np.tan(2.0 * cfg["cm_pitch"]) - - if cfg["mo1_mode"] == "Monochromatic": - beam_offset_mo1 = ( - l * np.sin(2.0 * (cfg["mo1_bragg"] + cfg["cm_pitch"])) - yver - ) # Resultat ist korrekt! - elif cfg["mo1_mode"] == "Pinkbeam": - beam_offset_mo1 = 0 - else: - raise ValueError("Monochromator mode not supported") - - def csc(a): - return 1 / np.sin(a) - - def cot(a): - return 1 / np.tan(a) - - # calculate height of center of first crystal surface - f = bl.mo1.rotOffset # rotation offset, mm - d = bl.mo1.heightOffset # xtal height offset, mm - c = d * csc(cfg["mo1_bragg"]) - f * cot(cfg["mo1_bragg"]) - - # Calculate height of center of rotation - b = np.sqrt( - d**2 * csc(cfg["mo1_bragg"]) ** 2 - - 2 * d * f * cot(cfg["mo1_bragg"]) * csc(cfg["mo1_bragg"]) - + f**2 * cot(cfg["mo1_bragg"]) ** 2 - + f**2 - ) - h = np.cos(np.pi / 2 - np.arctan(f / c) - cfg["mo1_bragg"] - 2 * cfg["cm_pitch"]) * b - h2 = ((bl.mo1.center[1] - bl.cm.center[1]) - np.sqrt(b**2 - h**2)) * np.tan(2 * cfg["cm_pitch"]) - height_mo1_real = ( - h + h2 - ) # per design, the height should not change if the pitch of the CM is not changed! - if cfg["mo1_mode"] == "Monochromatic": - pass - elif cfg["mo1_mode"] == "Pinkbeam": - height_mo1_real = ( - height_mo1_real - 13 - ) # Move down to let beam pass between both crystal without touching copper cooler - else: - raise ValueError("Monochromator mode not supported") - pos["mo1_try"] = {"value": height_mo1_real} - - # TRX, Crystal selection - if cfg["mo1_mode"] == "Monochromatic": - xtal = cfg["mo1_xtal"].translate( - str.maketrans("", "", "()") - ) # Remove brackets from xtal name to conform with parameters - if xtal in bl.mo1.xtal: - index = bl.mo1.xtal.index(xtal) - else: - raise ValueError(f"Requested xtal {xtal} not found in parameters!") - pos["mo1_trx"] = {"value": bl.mo1.xtalOffsetX[index]} - else: - pos["mo1_trx"] = {"value": 0} - - diag = bl.mo1.xtalGap[0] / np.sin(cfg["mo1_bragg"]) # Calculations for Mono - dz = diag * np.cos(2 * (cfg["cm_pitch"] + cfg["mo1_bragg"])) - - ## Slits 1 - d = bl.opSlits1.center[1] - bl.cm.center[1] - dz - sl1_beam_height = d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1 - pos["sl1_centery"] = {"value": sl1_beam_height} - pos["sl1_gapy"] = {"value": beam_vs} - - ## Beam Monitor 1 - d = bl.opBM1.center[1] - bl.cm.center[1] - dz - bm1_beam_height = d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1 - pos["bm1_try"] = {"value": bm1_beam_height} - - ## Focusing Mirror - p = bl.fm.center[1] - q = cfg["smpl"] - bl.fm.center[1] - f = (p * q) / (p + q) # focal length - - # Bender radius - if cfg["fm_qy"] is None: - radius = 2 * q / np.sin(cfg["fm_rotx"]) # ideal bending radius for focused beam - else: - radius = ( - 2 * cfg["fm_qy"] / np.sin(cfg["fm_rotx"]) - ) # ideal bending radius for unfocused beam - pos["fm_bnd_radius"] = {"value": radius * 1e-6} # Convert to km - - # Pitch - d = bl.fm.center[1] - bl.cm.center[1] - dz - fm_rotx = ( - 2 * cfg["cm_pitch"] - cfg["fm_rotx"] - ) # calculate pitch in absolute values (according to horizontal plane) - pos["fm_rotx"] = { - "value": -fm_rotx * 1e3 - } # invert and convert to mrad (same as EGU of rotx axis) - - if cfg["fm_stripe"] in ("Rh (toroid)", "Pt (toroid)"): - - # TRY - if cfg["fm_stripe"] == "Rh (toroid)": - r = bl.fm.r[0] - h_cyl = bl.fm.hToroid[0] - else: # PT toroid - r = bl.fm.r[1] - h_cyl = bl.fm.hToroid[1] - width_beam = 2 * bl.fm.center[1] * np.tan(cfg["h_acc"] * 1e-3) - alpha = np.arccos(1 - width_beam**2 / (2 * r**2)) - h = r - (r * np.cos(alpha / 2)) - fm_beam_height = (d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1) * cfg["fm_gain_height"] - fm_height = (d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1 - h_cyl + h / 2) * cfg[ - "fm_gain_height" - ] - pos["fm_try"] = {"value": fm_height} - - # TRX - if cfg["fm_stripe"] == "Rh (toroid)": - x_cyl = -bl.fm.xToroid[0] - else: - x_cyl = -bl.fm.xToroid[1] - pos["fm_trx"] = {"value": x_cyl} - - elif cfg["fm_stripe"] in ("Rh (flat)", "Pt (flat)"): - - # TRY - fm_height = (d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1) * cfg["fm_gain_height"] - fm_beam_height = fm_height - pos["fm_try"] = {"value": fm_height} - - # TRX - if cfg["fm_stripe"] == "Rh (flat)": - x_flat = -bl.fm.xFlat[0] - else: - x_flat = -bl.fm.xFlat[1] - pos["fm_trx"] = {"value": x_flat} - - else: - raise ValueError("FM Stripe selection not valid") - - pos["fm_roty"] = {"value": 0} - pos["fm_rotz"] = {"value": 0} - - ## Slits 2 - if hasattr(bl, "opSlits2"): - d = bl.opSlits2.center[1] - bl.fm.center[1] - sl2_beam_height = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - pos["sl2_centery"] = {"value": sl2_beam_height} - pos["sl2_gapy"] = {"value": beam_vs} - - ## Beam Monitor 2 - d = bl.opBM2.center[1] - bl.fm.center[1] - bm2_beam_height = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - pos["bm2_try"] = {"value": bm2_beam_height} - - ## Optical Table - - if beamline == "x01da": - # TRY - d = bl.ehWindow.center[1] - bl.fm.center[1] - ot_height = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - pos["ot_try"] = {"value": ot_height} - - # Pitch - ot_pitch = -(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"]) - pos["ot_rotx"] = {"value": ot_pitch * 1e3} - - # TRZ ES1 - ot_es1_trz = cfg["smpl"] - pos["ot_es1_trz"] = {"value": ot_es1_trz} - - # ES0 exit window - pos["es0wi_try"] = { - "value": 5 - } # At 5mm, the middle of the window is 500 mm from the table (neutral position) - else: - # Exit window height - d = bl.ehWindow.center[1] - bl.fm.center[1] - es0wi_try = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - pos["es0wi_try"] = {"value": es0wi_try} - - # ES1 table height - d = bl.es1.center[1] - bl.fm.center[1] - es1_try = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - pos["es1_try"] = {"value": es1_try} - - # IC0 height - d = bl.es1ic0.center[1] - bl.fm.center[1] - es1ic0_try = ( - fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - es1_try - ) - pos["es1ic0_try"] = {"value": es1ic0_try} - - # IC1 height - d = bl.es1ic1.center[1] - bl.fm.center[1] - es1ic1_try = ( - fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - es1_try - ) - pos["es1ic1_try"] = {"value": es1ic1_try} - - # IC2 height - d = bl.es1ic2.center[1] - bl.fm.center[1] - es1ic2_try = ( - fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - es1_try - ) - pos["es1ic2_try"] = {"value": es1ic2_try} - - # ES2 table height - d = bl.es2.center[1] - bl.fm.center[1] - es2_try = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - pos["es2_try"] = {"value": es2_try} - - return pos diff --git a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py index f5fcbfe..3850e45 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py @@ -3,7 +3,6 @@ Digital Twin: Custom BEC widget to support the beamline alignment. """ import sys -from pathlib import Path from typing import Literal, cast import numpy as np @@ -35,9 +34,9 @@ from qtpy.QtWidgets import ( QWidget, ) +from ....bec_ipython_client.plugins.digital_twin.digital_twin import DigitalTwinCore from ..edge_selector import EdgeSelector from .beamline import get_beamline_id -from .calculations.calc_positions import calc_positions from .calculations.calc_sideview import calc_sideview from .calculations.calc_surfaces import calc_surfaces from .calculations.calc_varia import ( @@ -55,6 +54,7 @@ from .calculations.calc_varia import ( sldi_gap_to_acc, table_to_smpl_pos, ) +from .offsets import Offsets from .panels.input_panel import InputPanel from .panels.mover_panel import MoverPanel from .panels.plots import SideviewPlot, SurfacePlots @@ -64,9 +64,6 @@ from .widgets.qt_widgets import ComboBox, InputNumberField logger = bec_logger.logger -OFFSET_FILE_X01DA = Path(__file__).with_name("x01da_offsets.yaml") -OFFSET_FILE_X10DA = Path(__file__).with_name("x10da_offsets.yaml") - X01DA_E_MIN = 4500 X01DA_E_MAX = 60000 X10DA_E_MIN = 4500 @@ -85,16 +82,13 @@ class DigitalTwin(BECWidget, QWidget): super().__init__(parent=parent, *arg, **kwargs) self.get_bec_shortcuts() + self.core = DigitalTwinCore() + self.beamline = get_beamline_id() # Debugging, override beamline! # self.beamline = BeamlineId.X10DA - self.offset_file = Path() - match self.beamline: - case "x01da": - self.offset_file = OFFSET_FILE_X01DA - case "x10da": - self.offset_file = OFFSET_FILE_X10DA + self.offsets = Offsets() # Check if devices are all in config self.check_bec_config() @@ -172,7 +166,6 @@ class DigitalTwin(BECWidget, QWidget): self.edge_selector_energy = 0.0 self.bragg_angle = 0.0 self.qy = 0.0 - self.offsets = {} # Initialize all values self.load_offsets(recalculate=False) @@ -434,16 +427,7 @@ class DigitalTwin(BECWidget, QWidget): # Apply offsets if apply_offset: - for axis, _ in config.items(): - if axis in self.offsets: - axis_offsets = self.offsets[axis] - if "modifier" in axis_offsets and "offset" in axis_offsets: - for idx, rng in enumerate(axis_offsets["modifier"]["range"]): - if rng[0] < config[axis_offsets["modifier"]["axis"]] < rng[1]: - config[axis] += axis_offsets["offset"][idx] - break - elif "offset" in axis_offsets: - config[axis] += axis_offsets["offset"] + config = self.offsets.apply_offsets(config, nested_config=False) # Convert to SI units! config["h_acc"] *= 1e-3 @@ -592,16 +576,7 @@ class DigitalTwin(BECWidget, QWidget): pos["ot_es1_trz"] = self.dev.ot_es1_trz.read(cached=True)["ot_es1_trz"]["value"] # Removing offsets - for axis, _ in pos.items(): - if axis in self.offsets: - axis_offsets = self.offsets[axis] - if "modifier" in axis_offsets and "offset" in axis_offsets: - for idx, rng in enumerate(axis_offsets["modifier"]["range"]): - if rng[0] < pos[axis_offsets["modifier"]["axis"]] < rng[1]: - pos[axis] -= axis_offsets["offset"][idx] - break - elif "offset" in axis_offsets: - pos[axis] -= axis_offsets["offset"] + pos = self.offsets.remove_offsets(pos) self.input.energy.set_number(self.dev.mo1_bragg.read(cached=True)["mo1_bragg"]["value"]) h_acc, v_acc = sldi_gap_to_acc(pos["sldi_gapx"], pos["sldi_gapy"]) @@ -690,19 +665,9 @@ class DigitalTwin(BECWidget, QWidget): Defaults to True """ - if self.offsets == {}: - # Load offsets - if not self.offset_file.exists(): - raise FileNotFoundError(f"Offset file not found: {self.offset_file}") - - with self.offset_file.open("r", encoding="utf-8") as f: - data = yaml.safe_load(f) - - if not isinstance(data, dict): - raise ValueError(f"Expected a YAML mapping, got {type(data).__name__}") - - self.offsets = data - + self.offsets.load_offsets() + if self.offsets.offsets != {}: + # Offsets were loaded if recalculate: self.calc_assistant(identifier="init") @@ -711,8 +676,7 @@ class DigitalTwin(BECWidget, QWidget): self.settings.offsets_status.setColor(get_accent_colors().success.name()) self.settings.show_offsets.enable_button(True) else: - # Unload offsets - self.offsets = {} + # Offsets were unloaded self.calc_assistant(identifier="init") self.settings.load_offsets.setText("Load") @@ -736,7 +700,7 @@ class DigitalTwin(BECWidget, QWidget): intro_label.setWordWrap(True) layout.addWidget(intro_label) - file = QLabel(str(self.offset_file)) + file = QLabel(str(self.offsets.offset_file)) file.setWordWrap(True) font = QFont() font.setItalic(True) @@ -753,7 +717,9 @@ class DigitalTwin(BECWidget, QWidget): def represent_sequence(self, tag, sequence, *_): return super().represent_sequence(tag, sequence, flow_style=True) - text_edit.setPlainText(yaml.dump(self.offsets, Dumper=InlineListDumper, sort_keys=False)) + text_edit.setPlainText( + yaml.dump(self.offsets.offsets, Dumper=InlineListDumper, sort_keys=False) + ) layout.addWidget(text_edit) buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) @@ -886,19 +852,13 @@ class DigitalTwin(BECWidget, QWidget): """ Calculates the positions for the axes based on the assistant values """ - out = calc_positions(self.beamline, self.get_assistant_config()) + config = self.get_assistant_config() + out = self.core.calc_positions(self.beamline, config) + out = self.core.apply_offsets(out, nested_config=True) + # out = calc_positions(self.beamline, self.get_assistant_config()) # Apply offsets - for axis, axis_data in out.items(): - if axis in self.offsets: - axis_offsets = self.offsets[axis] - if "modifier" in axis_offsets and "offset" in axis_offsets: - for idx, rng in enumerate(axis_offsets["modifier"]["range"]): - if rng[0] < out[axis_offsets["modifier"]["axis"]]["value"] < rng[1]: - axis_data["value"] += axis_offsets["offset"][idx] - break - elif "offset" in axis_offsets: - axis_data["value"] += axis_offsets["offset"] + # out = self.offsets.apply_offsets(out, nested_config=True) self.mover.sldi_gapx.set_target(out["sldi_gapx"]["value"]) self.mover.sldi_gapy.set_target(out["sldi_gapy"]["value"]) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/offsets.py b/debye_bec/bec_widgets/widgets/digital_twin/offsets.py new file mode 100644 index 0000000..e905afc --- /dev/null +++ b/debye_bec/bec_widgets/widgets/digital_twin/offsets.py @@ -0,0 +1,83 @@ +""" +Offset class to load or unload offsets from a file +""" + +from pathlib import Path + +import yaml +from bec_lib import bec_logger + +from .beamline import get_beamline_id + +OFFSET_FILE_X01DA = Path(__file__).with_name("x01da_offsets.yaml") +OFFSET_FILE_X10DA = Path(__file__).with_name("x10da_offsets.yaml") + +logger = bec_logger.logger + + +class Offsets: + + def __init__(self, *arg, **kwargs): + self.beamline = get_beamline_id() + self.offset_file = Path() + match self.beamline: + case "x01da": + self.offset_file = OFFSET_FILE_X01DA + case "x10da": + self.offset_file = OFFSET_FILE_X10DA + self.offsets = {} + + def load_offsets(self): + if self.offsets == {}: + logger.info("Load beamline offsets") + if not self.offset_file.exists(): + raise FileNotFoundError(f"Offset file not found: {self.offset_file}") + + with self.offset_file.open("r", encoding="utf-8") as f: + data = yaml.safe_load(f) + + if not isinstance(data, dict): + raise ValueError(f"Expected a YAML mapping, got {type(data).__name__}") + + self.offsets = data + else: + logger.info("Unload beamline offsets") + self.offsets = {} + + def apply_offsets(self, config, nested_config=False): + for axis, axis_data in config.items(): + if axis in self.offsets: + axis_offsets = self.offsets[axis] + if "modifier" in axis_offsets and "offset" in axis_offsets: + for idx, rng in enumerate(axis_offsets["modifier"]["range"]): + modifier_axis = axis_offsets["modifier"]["axis"] + modifier_value = ( + config[modifier_axis]["value"] + if nested_config + else config[modifier_axis] + ) + if rng[0] < modifier_value < rng[1]: + if nested_config: + axis_data["value"] += axis_offsets["offset"][idx] + else: + config[axis] += axis_offsets["offset"][idx] + break + elif "offset" in axis_offsets: + if nested_config: + axis_data["value"] += axis_offsets["offset"] + else: + config[axis] += axis_offsets["offset"] + return config + + def remove_offsets(self, config): + for axis, _ in config.items(): + if axis in self.offsets: + axis_offsets = self.offsets[axis] + if "modifier" in axis_offsets and "offset" in axis_offsets: + for idx, rng in enumerate(axis_offsets["modifier"]["range"]): + if rng[0] < config[axis_offsets["modifier"]["axis"]] < rng[1]: + config[axis] -= axis_offsets["offset"][idx] + break + elif "offset" in axis_offsets: + config[axis] -= axis_offsets["offset"] + return config From 70aa0993139cc76a73c37a36b581ee8b1b1ada73 Mon Sep 17 00:00:00 2001 From: hitzst Date: Sat, 5 Sep 2026 20:35:58 +0200 Subject: [PATCH 16/56] wip --- debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py index 3850e45..3fb7ca7 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py @@ -855,10 +855,6 @@ class DigitalTwin(BECWidget, QWidget): config = self.get_assistant_config() out = self.core.calc_positions(self.beamline, config) out = self.core.apply_offsets(out, nested_config=True) - # out = calc_positions(self.beamline, self.get_assistant_config()) - - # Apply offsets - # out = self.offsets.apply_offsets(out, nested_config=True) self.mover.sldi_gapx.set_target(out["sldi_gapx"]["value"]) self.mover.sldi_gapy.set_target(out["sldi_gapy"]["value"]) From a95b586256ba2a658dcce77163b4fde4be3c5265 Mon Sep 17 00:00:00 2001 From: hitzst Date: Mon, 7 Sep 2026 09:09:20 +0200 Subject: [PATCH 17/56] wip --- .../bec_ipython_client/plugins/auto_gain.py | 211 ++++++++++++++++++ .../plugins/move_to_label.py | 82 ------- .../x01da_experimental_hutch.yaml | 15 ++ debye_bec/device_configs/x01da_frontend.yaml | 2 +- debye_bec/device_configs/x01da_machine.yaml | 14 ++ debye_bec/device_configs/x01da_optics.yaml | 16 +- debye_bec/devices/absorber.py | 34 ++- debye_bec/devices/eh_shutter.py | 75 +++++++ debye_bec/devices/op_shutter.py | 94 ++++++++ debye_bec/devices/utils/bl_status_enum.py | 8 + 10 files changed, 461 insertions(+), 90 deletions(-) create mode 100644 debye_bec/bec_ipython_client/plugins/auto_gain.py delete mode 100644 debye_bec/bec_ipython_client/plugins/move_to_label.py create mode 100644 debye_bec/devices/eh_shutter.py create mode 100644 debye_bec/devices/op_shutter.py create mode 100644 debye_bec/devices/utils/bl_status_enum.py diff --git a/debye_bec/bec_ipython_client/plugins/auto_gain.py b/debye_bec/bec_ipython_client/plugins/auto_gain.py new file mode 100644 index 0000000..ab4bbaa --- /dev/null +++ b/debye_bec/bec_ipython_client/plugins/auto_gain.py @@ -0,0 +1,211 @@ + +import xraydb +from bisect import bisect_right +import time +import builtins +import numpy as np +from bec_lib import bec_logger + +from ...devices.nidaq.nidaq_enums import NidaqState +from ...devices.absorber import STATUS as ABS_STATUS +from ...devices.op_shutter import STATUS as OP_PH_STATUS +from ...devices.eh_shutter import STATUS as EH_PH_STATUS +from ...devices.ionization_chambers.ionization_chamber_enums import AmplifierEnable + +if builtins.__dict__.get("bec") is not None: + bec = builtins.__dict__.get("bec") + dev = builtins.__dict__.get("dev") + scans = builtins.__dict__.get("scans") + +logger = bec_logger.logger + +EMIN = -100 +EMAX = 200 + +MIN_RING_CURRENT = 5 +NOMINAL_RING_CURRENT = 400 + +MONO_VELOCITY = 20 +TIMEOUT_MONO_PV = 5 +TIMEOUT_MONO_MOVE = 60 + +AVAILABLE_GAINS = [1e6, 1e7, 5e7, 1e8, 1e9] # ascending order +MIN_SIGNAL = 0.05 # Minimum signal to count as valid signal +FULL_SCALE_V = 10.0 # NIDAQ AI full-scale range +SAFETY_MARGIN = 0.9 # keep max signal under 90% of full scale + +class AutoGainError(Exception): + """AutoGain specific error""" + +class AutoGain(): + def __init__(self): + pass + + def start(self, element:str, edge:str, amplifier:list[str] | None=None, comp_ring_current:bool=True): + + if amplifier is None: + amplifier = ['ic0', 'ic1', 'ic2', 'pips'] + + # Make sure NIDAQ is in standby mode + if dev.nidaq.state.get() is not NidaqState.STANDBY: + raise AutoGainError('NIDAQ was not in Standby mode, cannot proceed.') + + # Check for beam availability + if self._get_ring_current() < MIN_RING_CURRENT: + raise AutoGainError(f'Ring current is below {MIN_RING_CURRENT} mA') + if dev.abs.status.get() != ABS_STATUS.OPEN: + raise AutoGainError('Absorber is closed, no beam') + if dev.op_shutter.status.get() != OP_PH_STATUS.NOT_CLOSED: + raise AutoGainError('OP Photon Shutter is closed, no beam') + if dev.eh_shutter.status.get() != EH_PH_STATUS.NOT_CLOSED: + raise AutoGainError('EH Photon Shutter is closed, no beam') + + # Check if no scan is running + scan_id = bec.queue.scan_storage.current_scan_id + if len(scan_id) > 0: + raise AutoGainError(f"Scan with ID {scan_id} is currently running, cannot continue") + + # Get edge energy + energy = xraydb.xray_edge(element, edge, True) + if energy is None: + raise ValueError(f'Could not find edge energy for element/edge {element}/{edge}') + emin = energy + EMIN + emax = energy + EMAX + + # Check range of mono + low_limit, high_limit = dev.mo1_bragg.limits() + if emin < low_limit or emax > high_limit: + raise ValueError( + f'Chosen element/edge {element}/{edge} with edge energy of {energy}' + + ' is outside of accessible range of monochromator ' + + f'{low_limit:.1f} eV - {high_limit:.1f} eV' + ) + + # Map amplifier names to their NIDAQ channels + channel_map = { + 'ic0': {'signal': dev.nidaq.ai0, 'dev': dev.ic0}, + 'ic1': {'signal': dev.nidaq.ai2, 'dev': dev.ic1}, + 'ic2': {'signal': dev.nidaq.ai4, 'dev': dev.ic2}, + 'pips': {'signal': dev.nidaq.ai6, 'dev': dev.pips}, + } + active_channels = {name: ch for name, ch in channel_map.items() if name in amplifier} + + # Check if amplifieres are switched on + for name, ch in active_channels.items(): + if ch['dev'].amp.cOnOff.get() != AmplifierEnable.ON: + raise AutoGainError(f"Amplifier of device {name} is not enabled") + + # Check high voltage on ionization chambers + for name, ch in active_channels.items(): + if name != 'pips': + if ch['dev'].hv_en.ena.get() is not True: + raise AutoGainError(f"High voltage of ionization chamber {name} is not enabled") + if ch['dev'].hv.v.get() < 1000: + raise AutoGainError(f"HV voltage of ionization chamber {name} is < 1000") + if ch['dev'].hv.grid_v.get() < 1000: + raise AutoGainError(f"Grid voltage of ionization chamber {name} is < 1000") + + # Check gas filling of ionization chambers + for name, ch in active_channels.items(): + if name != 'pips': + if ch['dev'].gmes.status.get() != True: + raise AutoGainError(f'Gas filling of ionization chamber {name} is not OK') + + logger.info('All checks done, start preparing for measurement') + + # Get initial monochromator position and velocity + init_pos = dev.mo1_bragg.position.get() + init_vel = dev.mo1_bragg.velocity.get() + + logger.info(f'Move mono to start of {emin} eV') + status = dev.mo1_bragg.move(emin) + status.wait(TIMEOUT_MONO_MOVE) + + # Set NIDAQ to max mode + # TODO implement + + # Set gains to lowest gain + for name, ch in active_channels.items(): + lowest_gain = AVAILABLE_GAINS[0] + ch['dev'].set_gain(lowest_gain) + ch['gain'] = lowest_gain + + remeasure = True + logger.info(f'Start measurement from {emin} eV to {emax} eV') + while(remeasure): + # Create temporary storage for max signal per channel + data = {name: 0 for name in active_channels} + + # Measure current ring current + ring_current_1 = self._get_ring_current() + logger.info(f'Ring current right before measurement: {ring_current_1} mA') + if ring_current_1 == 0: + raise AutoGainError('Ring current dropped to 0 mA right before measurement') + + # Scan range, recording the peak NIDAQ signal per channel + status = dev.mo1_bragg.velocity.put(MONO_VELOCITY) + status.wait(TIMEOUT_MONO_PV) + dev.mo1_bragg.move(emax).wait(timeout=TIMEOUT_MONO_MOVE) + status.wait(TIMEOUT_MONO_MOVE) + for name, ch in active_channels.items(): + data[name] = max(data[name], ch['signal'].get()) + + # Rest max values of NIDAQ signals + # TODO implement + + # Measure current ring current again + ring_current_2 = self._get_ring_current() + logger.info(f'Ring current right after measurement: {ring_current_2} mA') + if ring_current_2 == 0: + raise AutoGainError('Ring current dropped to 0 mA during measurement') + ring_current = (ring_current_1 + ring_current_2) / 2 + + # Move back to first monochromator position + status = dev.mo1_bragg.move(emin) + + # Choose gain per channel based on the max signal recorded during the scan + remeasure = False + for name, ch in active_channels.items(): + raw_signal = data[name] + logger.info(f'Raw signal for device {name} is {raw_signal} V') + if comp_ring_current: + raw_signal = raw_signal * NOMINAL_RING_CURRENT / ring_current + logger.info(f'Compensate for ring current, new raw signal is {raw_signal} V') + if raw_signal < MIN_SIGNAL: + logger.info(f'Raw signal for device {name} is below {MIN_SIGNAL}') + # Choose next gain to be 100x the current gain, or if this gain does not exist, choose the next smaller one + if ch['gain'] == AVAILABLE_GAINS[-1]: + logger.warning(f"Amplifier of {name} at highest gain {ch['gain']} and still not measured signal above {MIN_SIGNAL}") + else: + next_gain = AVAILABLE_GAINS[bisect_right(AVAILABLE_GAINS, ch['gain'] * 100) - 1] + ch['dev'].set_gain(next_gain) + logger.info(f'Setting gain of device {name} to {next_gain:.0e} and remeasure') + remeasure = True + else: + gain = max( + (g for g in AVAILABLE_GAINS if raw_signal / ch['gain'] * g <= FULL_SCALE_V * SAFETY_MARGIN), + default=min(AVAILABLE_GAINS), + ) + ch['dev'].set_gain(gain) + logger.info(f'Calculated final gain for {name} of {gain:.0e}') + + # Wait for mono to return to start position + status.wait(TIMEOUT_MONO_MOVE) + + # Reset NIDAQ to mean mode + # TODO implement + + # Wait for mono to move to initial position and reset velocity + status = dev.mo1_bragg.move(init_pos) + status.wait(TIMEOUT_MONO_MOVE) + dev.mo1_bragg.velocity.put(init_vel) + + @staticmethod + def _get_ring_current() -> float: + ring_current = 0 + retries = 0 + while ring_current == 0 and retries < 10: + ring_current = dev.curr.get() + retries += 1 + time.sleep(0.01) + return ring_current diff --git a/debye_bec/bec_ipython_client/plugins/move_to_label.py b/debye_bec/bec_ipython_client/plugins/move_to_label.py deleted file mode 100644 index dd14970..0000000 --- a/debye_bec/bec_ipython_client/plugins/move_to_label.py +++ /dev/null @@ -1,82 +0,0 @@ -from __future__ import annotations - -import builtins -from typing import TYPE_CHECKING - -from bec_lib import bec_logger -from debye_bec.devices.absorber import STATUS as ABS_STATUS - -logger = bec_logger.logger -# import builtins to avoid linter errors -dev = builtins.__dict__.get("dev") - -class MoveToLabelError(Exception): - """Exception for the MoveToLabel function""" - -def move_to_label(): - """ - Function to move several motors to a specific position defined in the label dict. - """ - - label = get_device_conditions(label="digitalTwin") - - # Get absorber status and close if open - logger.info("Check Frontend Absorber Status") - abs_was_open = dev.abs.status.get() == ABS_STATUS.OPEN - if abs_was_open: - logger.info(" Close Frontend Absorber") - status = dev.abs.close() - status.wait() - - # Move Frontend Slits - logger.info("Move Frontend Slits into position") - devices = ["sldi_centerx", "sldi_centery", "sldi_gapx", "sldi_gapy"] - matches = {key: label[key] for key in devices if key in label} - statuses = [] - for device in matches.values(): - statuses.append(device['device'].move(device['value'])) - for status in statuses: - status.wait(timeout=30) - - # Move Collimating mirror - logger.info("Move Collimating Mirror into position") - if "cm_rotx" in label: # pitch - logger.info(" Move pitch into position") - surveyed_movement( - axis=label['cm_rotx'], - surveyed_axes= [ - {'device': dev.cm_rotz, 'abs_tol': 0.1}, - ] - ) - - # Restore absorber position - logger.info("Restore Frontend Absorber Status") - if abs_was_open: - status = dev.abs.open() - status.wait() - - -def surveyed_movement(axis, surveyed_axes): - """ - Moves an axis while surverying a set of axes. - - Args: - axis (DeviceCondition): Device condition - surveyed_axes (list): List of dicts (same format as DeviceCondition) - - Raises: - If during movement of axis, one of the surveyed axes moves out of tolerance. - """ - - for surv_ax in surveyed_axes: - surv_ax['old_value'] = surv_ax['device'].read() - status = axis['device'].move(axis['value']) - while status.status == 'RUNNING': - for surv_ax in surveyed_axes: - if abs(surv_ax['device'].read() - surv_ax['old_value']) > surv_ax['abs_tol']: - axis['device'].stop() - raise MoveToLabelError( - f"During movement of {axis['device'].name}, {surv_ax['device'].name} " + - f"started to move unexpectedly (old pos: {surv_ax['old_value']}, " + - f"current pos: {surv_ax['device'].read()})" - ) diff --git a/debye_bec/device_configs/x01da_experimental_hutch.yaml b/debye_bec/device_configs/x01da_experimental_hutch.yaml index f2c241e..219e0d0 100644 --- a/debye_bec/device_configs/x01da_experimental_hutch.yaml +++ b/debye_bec/device_configs/x01da_experimental_hutch.yaml @@ -1,3 +1,18 @@ + +####################################### +## Experimental Hutch Photon Shutter ## +####################################### + +eh-sh: + readoutPriority: baseline + description: Experimental Hutch Photon Shutter + deviceClass: debye_bec.devices.eh_shutter.EHPhotonShutter + deviceConfig: + prefix: "X01DA-" + onFailure: retry + enabled: true + softwareTrigger: false + ################################### ## Optical Table ## ################################### diff --git a/debye_bec/device_configs/x01da_frontend.yaml b/debye_bec/device_configs/x01da_frontend.yaml index 3a9edb7..77a4236 100644 --- a/debye_bec/device_configs/x01da_frontend.yaml +++ b/debye_bec/device_configs/x01da_frontend.yaml @@ -240,4 +240,4 @@ cm_xstripe: prefix: X01DA-FE-CM:XSTRIPE onFailure: retry enabled: true - softwareTrigger: false \ No newline at end of file + softwareTrigger: false diff --git a/debye_bec/device_configs/x01da_machine.yaml b/debye_bec/device_configs/x01da_machine.yaml index cd957dd..cbade1e 100644 --- a/debye_bec/device_configs/x01da_machine.yaml +++ b/debye_bec/device_configs/x01da_machine.yaml @@ -15,4 +15,18 @@ curr: onFailure: buffer enabled: true readOnly: true + softwareTrigger: false + +bl_status: + readoutPriority: baseline + description: BL status for machine + deviceClass: ophyd.EpicsSignal + deviceConfig: + auto_monitor: false + read_pv: AGEOP-BL:STATUS-X01DA + deviceTags: + - machine + onFailure: buffer + enabled: true + readOnly: false softwareTrigger: false \ No newline at end of file diff --git a/debye_bec/device_configs/x01da_optics.yaml b/debye_bec/device_configs/x01da_optics.yaml index a168e92..ea61ae9 100644 --- a/debye_bec/device_configs/x01da_optics.yaml +++ b/debye_bec/device_configs/x01da_optics.yaml @@ -1,4 +1,18 @@ +################################### +## Optics Photon Shutter ## +################################### + +op-sh: + readoutPriority: baseline + description: Optics Hutch Photon Shutter + deviceClass: debye_bec.devices.op_shutter.OPPhotonShutter + deviceConfig: + prefix: "X01DA-" + onFailure: retry + enabled: true + softwareTrigger: false + ################################### ## Monochromator ## ################################### @@ -408,4 +422,4 @@ sl2_gapy: softwareTrigger: false deviceTags: - optics - - slits \ No newline at end of file + - slits diff --git a/debye_bec/devices/absorber.py b/debye_bec/devices/absorber.py index 73da60a..fa719db 100644 --- a/debye_bec/devices/absorber.py +++ b/debye_bec/devices/absorber.py @@ -10,9 +10,12 @@ from ophyd import EpicsSignal, EpicsSignalRO from ophyd_devices import CompareStatus, DeviceStatus from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase +from .utils.bl_status_enum import BlStatus + if TYPE_CHECKING: from bec_lib.devicemanager import ScanInfo +TIMEOUT_FOR_PV = 5 class AbsorberError(Exception): """Absorber specific exception""" @@ -37,6 +40,12 @@ class STATUS(int, enum.Enum): MAN_OPEN = 13 UNDEFINED = 14 +class BL_ENABLE(int, enum.Enum): + """Beamline enable""" + + DISABLE = 0 + ENABLE = 1 + class Absorber(PSIDeviceBase): """Class for the Frontend Absorber""" @@ -55,6 +64,7 @@ class Absorber(PSIDeviceBase): string=True, doc="Absorber Status", ) + close4bl = Cpt(EpicsSignal, suffix='CLOSE4BL', kind='config', doc='Beamline enable') def __init__(self, *, name: str, prefix: str = "", scan_info: ScanInfo | None = None, **kwargs): super().__init__(name=name, prefix=prefix, scan_info=scan_info, **kwargs) @@ -63,12 +73,25 @@ class Absorber(PSIDeviceBase): # Wait for connection on all components, ensure IOC is connected self.wait_for_connection(all_signals=True, timeout=5) - def open(self) -> DeviceStatus | None: - """Open the Absorber""" + def open(self, force:bool=False) -> DeviceStatus | None: + """Open the Absorber + + Args: + force(bool): If needed, set bl status to enable and bl enable to ENABLE, defaults to False + + """ + if force and self.device_manager.devices.get('bl_status', None) is None: + raise AbsorberError('bl_status is not in device config, thus cannot use force = True') if self.status.get() == STATUS.CLOSED: + if force: + if self.device_manager.bl_status.get() == BlStatus.OFFLINE: + status = self.device_manager.bl_status.put(BlStatus.ATTENDED) + status.wait(timeout=TIMEOUT_FOR_PV) + if self.close4bl.get() == BL_ENABLE.DISABLE: + status = self.close4bl.set(BL_ENABLE.ENABLE) + status.wait(timeout=TIMEOUT_FOR_PV) self.request.put(1) - status_open = CompareStatus(self.status, STATUS.OPEN, timeout=self.timeout_for_move) - status = status_open + status = CompareStatus(self.status, STATUS.OPEN, timeout=self.timeout_for_move) return status else: return None @@ -77,8 +100,7 @@ class Absorber(PSIDeviceBase): """Close the Absorber""" if self.status.get() == STATUS.OPEN: self.request.put(1) - status_close = CompareStatus(self.status, STATUS.CLOSED, timeout=self.timeout_for_move) - status = status_close + status = CompareStatus(self.status, STATUS.CLOSED, timeout=self.timeout_for_move) return status else: return None diff --git a/debye_bec/devices/eh_shutter.py b/debye_bec/devices/eh_shutter.py new file mode 100644 index 0000000..52d06e3 --- /dev/null +++ b/debye_bec/devices/eh_shutter.py @@ -0,0 +1,75 @@ +"""Experimental Hutch Photon Shutter""" + +from __future__ import annotations + +import enum +from typing import TYPE_CHECKING + +from ophyd import Component as Cpt +from ophyd import EpicsSignal, EpicsSignalRO +from ophyd_devices import CompareStatus, DeviceStatus +from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase + +from .utils.bl_status_enum import BlStatus + +if TYPE_CHECKING: + from bec_lib.devicemanager import ScanInfo + +TIMEOUT_FOR_PV = 5 + +class STATUS(int, enum.Enum): + """Shutter States""" + + NOT_CLOSED = 0 + CLOSED = 1 + +class BL_ENABLE(int, enum.Enum): + """Beamline enable""" + + DISABLE = 0 + ENABLE = 1 + + +class OPPhotonShutter(PSIDeviceBase): + """Class for the Experimental Hutch Photon Shutter""" + + USER_ACCESS = ["open", "close"] + + request_open = Cpt(EpicsSignal, suffix="EH1-PSYS:SH-A-OPEN-SET", kind="config", doc="Open Shutter") + request_close = Cpt(EpicsSignal, suffix="EH1-PSYS:SH-A-CLOSE-SET", kind="config", doc="Close Shutter") + status = Cpt( + EpicsSignalRO, suffix="EH1", kind="normal", auto_monitor=True, doc="Shutter Status" + ) + status_string = Cpt( + EpicsSignalRO, + suffix="EH1-PSYS:SH-A-CLOSE", + kind="normal", + auto_monitor=True, + string=True, + doc="Shutter Status", + ) + + def __init__(self, *, name: str, prefix: str = "", scan_info: ScanInfo | None = None, **kwargs): + super().__init__(name=name, prefix=prefix, scan_info=scan_info, **kwargs) + + self.timeout_for_move = 10 + # Wait for connection on all components, ensure IOC is connected + self.wait_for_connection(all_signals=True, timeout=5) + + def open(self) -> DeviceStatus | None: + """Open the Shutter""" + if self.status.get() == STATUS.CLOSED: + self.request_open.put(1) + status = CompareStatus(self.status, STATUS.NOT_CLOSED, timeout=self.timeout_for_move) + return status + else: + return None + + def close(self) -> DeviceStatus | None: + """Close the Shutter""" + if self.status.get() == STATUS.NOT_CLOSED: + self.request_close.put(1) + status = CompareStatus(self.status, STATUS.CLOSED, timeout=self.timeout_for_move) + return status + else: + return None diff --git a/debye_bec/devices/op_shutter.py b/debye_bec/devices/op_shutter.py new file mode 100644 index 0000000..99b8ba1 --- /dev/null +++ b/debye_bec/devices/op_shutter.py @@ -0,0 +1,94 @@ +"""Optics Photon Shutter""" + +from __future__ import annotations + +import enum +from typing import TYPE_CHECKING + +from ophyd import Component as Cpt +from ophyd import EpicsSignal, EpicsSignalRO +from ophyd_devices import CompareStatus, DeviceStatus +from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase + +from .utils.bl_status_enum import BlStatus + +if TYPE_CHECKING: + from bec_lib.devicemanager import ScanInfo + +TIMEOUT_FOR_PV = 5 + +class OPPhotonShutterError(Exception): + """Shutter specific exception""" + + +class STATUS(int, enum.Enum): + """Shutter States""" + + NOT_CLOSED = 0 + CLOSED = 1 + +class BL_ENABLE(int, enum.Enum): + """Beamline enable""" + + DISABLE = 0 + ENABLE = 1 + + +class OPPhotonShutter(PSIDeviceBase): + """Class for the Optics Photon Shutter""" + + USER_ACCESS = ["open", "close"] + + request_open = Cpt(EpicsSignal, suffix="OP-PSYS:SH-A-OPEN-SET", kind="config", doc="Open Shutter") + request_close = Cpt(EpicsSignal, suffix="OP-PSYS:SH-A-CLOSE-SET", kind="config", doc="Close Shutter") + status = Cpt( + EpicsSignalRO, suffix="OP-PSYS:SH-A-CLOSE", kind="normal", auto_monitor=True, doc="Shutter Status" + ) + status_string = Cpt( + EpicsSignalRO, + suffix="OP-PSYS:SH-A-CLOSE", + kind="normal", + auto_monitor=True, + string=True, + doc="Shutter Status", + ) + close4bl = Cpt(EpicsSignal, suffix='FE-BST1:CLOSE4BL', kind='config', doc='Beamline enable') + + def __init__(self, *, name: str, prefix: str = "", scan_info: ScanInfo | None = None, **kwargs): + super().__init__(name=name, prefix=prefix, scan_info=scan_info, **kwargs) + + self.timeout_for_move = 10 + # Wait for connection on all components, ensure IOC is connected + self.wait_for_connection(all_signals=True, timeout=5) + + def open(self, force:bool=False) -> DeviceStatus | None: + """Open the Shutter + + Args: + force(bool): If needed, set bl status to enable and bl enable to ENABLE, defaults to False + + """ + if force and self.device_manager.devices.get('bl_status', None) is None: + raise OPPhotonShutterError('bl_status is not in device config, thus cannot use force = True') + if self.status.get() == STATUS.CLOSED: + if force: + if self.device_manager.bl_status.get() == BlStatus.OFFLINE: + status = self.device_manager.bl_status.put(BlStatus.ATTENDED) + status.wait(timeout=TIMEOUT_FOR_PV) + if self.close4bl.get() == BL_ENABLE.DISABLE: + status = self.close4bl.set(BL_ENABLE.ENABLE) + status.wait(timeout=TIMEOUT_FOR_PV) + self.request_open.put(1) + status = CompareStatus(self.status, STATUS.NOT_CLOSED, timeout=self.timeout_for_move) + return status + else: + return None + + def close(self) -> DeviceStatus | None: + """Close the Shutter""" + if self.status.get() == STATUS.NOT_CLOSED: + self.request_close.put(1) + status = CompareStatus(self.status, STATUS.CLOSED, timeout=self.timeout_for_move) + return status + else: + return None diff --git a/debye_bec/devices/utils/bl_status_enum.py b/debye_bec/devices/utils/bl_status_enum.py new file mode 100644 index 0000000..2913745 --- /dev/null +++ b/debye_bec/devices/utils/bl_status_enum.py @@ -0,0 +1,8 @@ +import enum + +class BlStatus(str, enum.Enum): + """Beamline status enum""" + + OFFLINE = 0 + ATTENDED = 1 + REMOTE = 2 From d0eb5d9c941bd937f65e6e0c21fe03d733c75787 Mon Sep 17 00:00:00 2001 From: hitzst Date: Mon, 7 Sep 2026 15:52:37 +0200 Subject: [PATCH 18/56] wip --- .../bec_ipython_client/plugins/auto_gain.py | 142 +++++++++++------- .../startup/post_startup.py | 4 + debye_bec/devices/nidaq/nidaq.py | 3 + debye_bec/devices/nidaq/nidaq_enums.py | 6 + 4 files changed, 104 insertions(+), 51 deletions(-) diff --git a/debye_bec/bec_ipython_client/plugins/auto_gain.py b/debye_bec/bec_ipython_client/plugins/auto_gain.py index ab4bbaa..846e785 100644 --- a/debye_bec/bec_ipython_client/plugins/auto_gain.py +++ b/debye_bec/bec_ipython_client/plugins/auto_gain.py @@ -1,9 +1,10 @@ +""" Module to automatically set the gains for the selected amplifiers""" -import xraydb from bisect import bisect_right import time import builtins -import numpy as np + +import xraydb from bec_lib import bec_logger from ...devices.nidaq.nidaq_enums import NidaqState @@ -12,22 +13,17 @@ from ...devices.op_shutter import STATUS as OP_PH_STATUS from ...devices.eh_shutter import STATUS as EH_PH_STATUS from ...devices.ionization_chambers.ionization_chamber_enums import AmplifierEnable -if builtins.__dict__.get("bec") is not None: - bec = builtins.__dict__.get("bec") - dev = builtins.__dict__.get("dev") - scans = builtins.__dict__.get("scans") - logger = bec_logger.logger EMIN = -100 EMAX = 200 -MIN_RING_CURRENT = 5 -NOMINAL_RING_CURRENT = 400 +MIN_RING_CURRENT = 5 # Minimum ring current to use auto-gain +NOMINAL_RING_CURRENT = 400 # Nominal ring current of SLS2 -MONO_VELOCITY = 20 -TIMEOUT_MONO_PV = 5 -TIMEOUT_MONO_MOVE = 60 +MONO_VELOCITY = 20 # Move velocity in deg/s +TIMEOUT_MONO_PV = 5 # Timeout to set a PV on the mono +TIMEOUT_MONO_MOVE = 30 # Timeout to finish a movement on the mono AVAILABLE_GAINS = [1e6, 1e7, 5e7, 1e8, 1e9] # ascending order MIN_SIGNAL = 0.05 # Minimum signal to count as valid signal @@ -38,30 +34,67 @@ class AutoGainError(Exception): """AutoGain specific error""" class AutoGain(): + """ Module to automatically set the gains for the selected amplifiers""" def __init__(self): - pass + dev = builtins.__dict__.get("dev") + bec = builtins.__dict__.get("bec") + if dev is None: + raise AutoGainError('Did not get dev') + if bec is None: + raise AutoGainError('Did not get bec') + self.dev = dev + self.bec = bec - def start(self, element:str, edge:str, amplifier:list[str] | None=None, comp_ring_current:bool=True): + def start( + self, + element:str, + edge:str, + amplifier:list[str] | None=None, + comp_ring_current:bool=True + ) -> None: + """ Start the auto-gain sequence. Measure the signals of the specified + amplifiers and set the gains accordingly. Makes sure there is actually beam available. + + Args: + element(str): Element which defines the energy at which the gain will be set, e.g. 'Cu' + edge(str): Corresponding edge, e.g. 'L1' + amplifier(list[str]): Amplifiers where auto-gain should be applied to + Defaults to all amplifiers -> ['ic0', 'ic1', 'ic2', 'pips'] + comp_ring_current(bool): Respects the current ring current and calculates the gain(s) + for a nominal ring current of 400 mA. Defaults to True + + Raises: + If NIDAQ is not in measurement mode + If Ring current is below 5 mA + If Absorber, OP Photon Shutter or EH Photon Shutter is closed + If a bec scan is running + If the energy for the supplied element/edge cannot be found + If the energy is outside the movement range of the monochromator + If a selected amplifier is switched off + If the high voltage of a selected ionization chamber is not enabled or < 1000 V + If the gas filling of a selected ionization chamber is not OK + If the ring current drops to 0 mA during the measurement (beamdump) + """ if amplifier is None: amplifier = ['ic0', 'ic1', 'ic2', 'pips'] # Make sure NIDAQ is in standby mode - if dev.nidaq.state.get() is not NidaqState.STANDBY: + if self.dev.nidaq.state.get() is not NidaqState.STANDBY: raise AutoGainError('NIDAQ was not in Standby mode, cannot proceed.') # Check for beam availability if self._get_ring_current() < MIN_RING_CURRENT: raise AutoGainError(f'Ring current is below {MIN_RING_CURRENT} mA') - if dev.abs.status.get() != ABS_STATUS.OPEN: + if self.dev.abs.status.get() != ABS_STATUS.OPEN: raise AutoGainError('Absorber is closed, no beam') - if dev.op_shutter.status.get() != OP_PH_STATUS.NOT_CLOSED: + if self.dev.op_shutter.status.get() != OP_PH_STATUS.NOT_CLOSED: raise AutoGainError('OP Photon Shutter is closed, no beam') - if dev.eh_shutter.status.get() != EH_PH_STATUS.NOT_CLOSED: + if self.dev.eh_shutter.status.get() != EH_PH_STATUS.NOT_CLOSED: raise AutoGainError('EH Photon Shutter is closed, no beam') # Check if no scan is running - scan_id = bec.queue.scan_storage.current_scan_id + scan_id = self.bec.queue.scan_storage.current_scan_id if len(scan_id) > 0: raise AutoGainError(f"Scan with ID {scan_id} is currently running, cannot continue") @@ -73,7 +106,7 @@ class AutoGain(): emax = energy + EMAX # Check range of mono - low_limit, high_limit = dev.mo1_bragg.limits() + low_limit, high_limit = self.dev.mo1_bragg.limits() if emin < low_limit or emax > high_limit: raise ValueError( f'Chosen element/edge {element}/{edge} with edge energy of {energy}' + @@ -83,42 +116,42 @@ class AutoGain(): # Map amplifier names to their NIDAQ channels channel_map = { - 'ic0': {'signal': dev.nidaq.ai0, 'dev': dev.ic0}, - 'ic1': {'signal': dev.nidaq.ai2, 'dev': dev.ic1}, - 'ic2': {'signal': dev.nidaq.ai4, 'dev': dev.ic2}, - 'pips': {'signal': dev.nidaq.ai6, 'dev': dev.pips}, + 'ic0': {'signal': self.dev.nidaq.ai0, 'self.dev': self.dev.ic0}, + 'ic1': {'signal': self.dev.nidaq.ai2, 'self.dev': self.dev.ic1}, + 'ic2': {'signal': self.dev.nidaq.ai4, 'self.dev': self.dev.ic2}, + 'pips': {'signal': self.dev.nidaq.ai6, 'self.dev': self.dev.pips}, } active_channels = {name: ch for name, ch in channel_map.items() if name in amplifier} # Check if amplifieres are switched on for name, ch in active_channels.items(): - if ch['dev'].amp.cOnOff.get() != AmplifierEnable.ON: - raise AutoGainError(f"Amplifier of device {name} is not enabled") + if ch['self.dev'].amp.cOnOff.get() != AmplifierEnable.ON: + raise AutoGainError(f"Amplifier of self.device {name} is not enabled") # Check high voltage on ionization chambers for name, ch in active_channels.items(): if name != 'pips': - if ch['dev'].hv_en.ena.get() is not True: + if ch['self.dev'].hv_en.ena.get() is not True: raise AutoGainError(f"High voltage of ionization chamber {name} is not enabled") - if ch['dev'].hv.v.get() < 1000: + if ch['self.dev'].hv.v.get() < 1000: raise AutoGainError(f"HV voltage of ionization chamber {name} is < 1000") - if ch['dev'].hv.grid_v.get() < 1000: + if ch['self.dev'].hv.grid_v.get() < 1000: raise AutoGainError(f"Grid voltage of ionization chamber {name} is < 1000") # Check gas filling of ionization chambers for name, ch in active_channels.items(): if name != 'pips': - if ch['dev'].gmes.status.get() != True: + if ch['self.dev'].gmes.status.get() is not True: raise AutoGainError(f'Gas filling of ionization chamber {name} is not OK') logger.info('All checks done, start preparing for measurement') # Get initial monochromator position and velocity - init_pos = dev.mo1_bragg.position.get() - init_vel = dev.mo1_bragg.velocity.get() + init_pos = self.dev.mo1_bragg.position.get() + init_vel = self.dev.mo1_bragg.velocity.get() logger.info(f'Move mono to start of {emin} eV') - status = dev.mo1_bragg.move(emin) + status = self.dev.mo1_bragg.move(emin) status.wait(TIMEOUT_MONO_MOVE) # Set NIDAQ to max mode @@ -127,12 +160,12 @@ class AutoGain(): # Set gains to lowest gain for name, ch in active_channels.items(): lowest_gain = AVAILABLE_GAINS[0] - ch['dev'].set_gain(lowest_gain) + ch['self.dev'].set_gain(lowest_gain) ch['gain'] = lowest_gain remeasure = True logger.info(f'Start measurement from {emin} eV to {emax} eV') - while(remeasure): + while remeasure: # Create temporary storage for max signal per channel data = {name: 0 for name in active_channels} @@ -143,9 +176,9 @@ class AutoGain(): raise AutoGainError('Ring current dropped to 0 mA right before measurement') # Scan range, recording the peak NIDAQ signal per channel - status = dev.mo1_bragg.velocity.put(MONO_VELOCITY) + status = self.dev.mo1_bragg.velocity.put(MONO_VELOCITY) status.wait(TIMEOUT_MONO_PV) - dev.mo1_bragg.move(emax).wait(timeout=TIMEOUT_MONO_MOVE) + self.dev.mo1_bragg.move(emax).wait(timeout=TIMEOUT_MONO_MOVE) status.wait(TIMEOUT_MONO_MOVE) for name, ch in active_channels.items(): data[name] = max(data[name], ch['signal'].get()) @@ -161,32 +194,40 @@ class AutoGain(): ring_current = (ring_current_1 + ring_current_2) / 2 # Move back to first monochromator position - status = dev.mo1_bragg.move(emin) + status = self.dev.mo1_bragg.move(emin) # Choose gain per channel based on the max signal recorded during the scan remeasure = False for name, ch in active_channels.items(): raw_signal = data[name] - logger.info(f'Raw signal for device {name} is {raw_signal} V') + logger.info(f'Raw signal for self.device {name} is {raw_signal} V') if comp_ring_current: raw_signal = raw_signal * NOMINAL_RING_CURRENT / ring_current logger.info(f'Compensate for ring current, new raw signal is {raw_signal} V') if raw_signal < MIN_SIGNAL: - logger.info(f'Raw signal for device {name} is below {MIN_SIGNAL}') - # Choose next gain to be 100x the current gain, or if this gain does not exist, choose the next smaller one + logger.info(f'Raw signal for self.device {name} is below {MIN_SIGNAL}') + # Choose next gain to be 100x the current gain, or if this gain does not exist, + # choose the next smaller one if ch['gain'] == AVAILABLE_GAINS[-1]: - logger.warning(f"Amplifier of {name} at highest gain {ch['gain']} and still not measured signal above {MIN_SIGNAL}") + logger.warning( + f"Amplifier of {name} at highest gain {ch['gain']} and still not" + + f" measured signal above {MIN_SIGNAL}" + ) else: - next_gain = AVAILABLE_GAINS[bisect_right(AVAILABLE_GAINS, ch['gain'] * 100) - 1] - ch['dev'].set_gain(next_gain) - logger.info(f'Setting gain of device {name} to {next_gain:.0e} and remeasure') + next_gain = AVAILABLE_GAINS[ + bisect_right(AVAILABLE_GAINS, ch['gain'] * 100) - 1 + ] + ch['self.dev'].set_gain(next_gain) + logger.info( + f'Setting gain of self.device {name} to {next_gain:.0e} and remeasure' + ) remeasure = True else: gain = max( (g for g in AVAILABLE_GAINS if raw_signal / ch['gain'] * g <= FULL_SCALE_V * SAFETY_MARGIN), default=min(AVAILABLE_GAINS), ) - ch['dev'].set_gain(gain) + ch['self.dev'].set_gain(gain) logger.info(f'Calculated final gain for {name} of {gain:.0e}') # Wait for mono to return to start position @@ -196,16 +237,15 @@ class AutoGain(): # TODO implement # Wait for mono to move to initial position and reset velocity - status = dev.mo1_bragg.move(init_pos) + status = self.dev.mo1_bragg.move(init_pos) status.wait(TIMEOUT_MONO_MOVE) - dev.mo1_bragg.velocity.put(init_vel) + self.dev.mo1_bragg.velocity.put(init_vel) - @staticmethod - def _get_ring_current() -> float: + def _get_ring_current(self) -> float: ring_current = 0 retries = 0 while ring_current == 0 and retries < 10: - ring_current = dev.curr.get() + ring_current = self.dev.curr.get() retries += 1 time.sleep(0.01) return ring_current diff --git a/debye_bec/bec_ipython_client/startup/post_startup.py b/debye_bec/bec_ipython_client/startup/post_startup.py index a85498d..d1778bb 100644 --- a/debye_bec/bec_ipython_client/startup/post_startup.py +++ b/debye_bec/bec_ipython_client/startup/post_startup.py @@ -42,6 +42,10 @@ logger = bec_logger.logger logger.info("Using the Debye startup script.") from debye_bec.bec_ipython_client.plugins.digital_twin.digital_twin import DigitalTwinCore +from debye_bec.bec_ipython_client.plugins.auto_gain import AutoGain digital_twin = DigitalTwinCore() logger.success("Digital Twin Core loaded. Use 'digital_twin' to access it.") + +auto_gain = AutoGain() +logger.success("Auto-Gain module loaded. Use 'auto_gain' to access it.") diff --git a/debye_bec/devices/nidaq/nidaq.py b/debye_bec/devices/nidaq/nidaq.py index be52d92..d3543bc 100644 --- a/debye_bec/devices/nidaq/nidaq.py +++ b/debye_bec/devices/nidaq/nidaq.py @@ -178,6 +178,9 @@ class NidaqControl(Device): heartbeat = Cpt(EpicsSignal, suffix="NIDAQ-Heartbeat", kind=Kind.config, auto_monitor=True) time_left = Cpt(EpicsSignalRO, suffix="NIDAQ-TimeLeft", kind=Kind.config, auto_monitor=True) + epics_mode = Cpt(EpicsSignal, suffix="NIDAQ-EpicsMode", kind=Kind.config, auto_monitor=True) + epics_max_reset = Cpt(EpicsSignal, suffix="NIDAQ-EpicsMaxReset", kind=Kind.config, auto_monitor=True) + ai_chans = Cpt(EpicsSignal, suffix="NIDAQ-AIChans", kind=Kind.config, auto_monitor=True) ci_chans = Cpt(EpicsSignal, suffix="NIDAQ-CIChans", kind=Kind.config, auto_monitor=True) di_chans = Cpt(EpicsSignal, suffix="NIDAQ-DIChans", kind=Kind.config, auto_monitor=True) diff --git a/debye_bec/devices/nidaq/nidaq_enums.py b/debye_bec/devices/nidaq/nidaq_enums.py index 14e4e5c..9b659ee 100644 --- a/debye_bec/devices/nidaq/nidaq_enums.py +++ b/debye_bec/devices/nidaq/nidaq_enums.py @@ -58,3 +58,9 @@ class EncoderFactors(int, enum.Enum): X1 = 4 X2 = 5 X4 = 6 + +class EpicsMode(int, enum.Enum): + """Mode when sending through EPICS""" + + MEAN = 0 + MAX = 0 From 700b584c40f936c8d5b88cb636e00b8f177eb16d Mon Sep 17 00:00:00 2001 From: hitzst Date: Mon, 7 Sep 2026 21:20:19 +0200 Subject: [PATCH 19/56] wip --- .../widgets/scheduler/item_dialog.py | 146 +++++++++++++++--- .../widgets/scheduler/scheduler.py | 42 +++-- 2 files changed, 154 insertions(+), 34 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index 74f2d57..522aab1 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -66,24 +66,15 @@ from qtpy.QtWidgets import ( QLabel, QLineEdit, QMessageBox, - QPushButton, QScrollArea, QTabWidget, QVBoxLayout, QWidget, ) - -from ....bec_ipython_client.plugins.digital_twin.digital_twin import DigitalTwinCore -from ..digital_twin.calculations.calc_positions import calc_positions -from ..digital_twin.digital_twin import DigitalTwin -from ..digital_twin.offsets import Offsets -from ..scan_control_xas.scan_control_xas import ScanControlXAS from .qt_widgets import MyButton logger = bec_logger.logger -_DSPIN_RANGE = (-1e12, 1e12) - # Tab indices, named instead of magic numbers now that there are four - # see _collect_result()/_apply_initial(). _TAB_SCAN = 0 @@ -95,7 +86,7 @@ _TAB_OTHER = 3 class ScheduleItemDialog(QDialog): """Add or edit one schedule item, via ScanControl, a move form, Digital Twin, or free text.""" - def __init__(self, scans, dev, parent=None, initial: dict | None = None, client=None): + def __init__(self, scans, dev, parent=None, initial: dict | None = None, client=None, beamline:str|None=None): super().__init__(parent) self.setWindowTitle("Schedule item") self.setMinimumSize(520, 480) @@ -104,13 +95,21 @@ class ScheduleItemDialog(QDialog): self._dev = dev self._client = client + self.beamline = beamline + if self.beamline in ['x01da', 'x10da']: + from ....bec_ipython_client.plugins.digital_twin.digital_twin import DigitalTwinCore + from ..digital_twin.digital_twin import DigitalTwin + from ..scan_control_xas.scan_control_xas import ScanControlXAS + from ..edge_selector import EdgeSelector + layout = QVBoxLayout(self) self.tabs = QTabWidget() layout.addWidget(self.tabs) self._build_scan_tab() self._build_move_tab() - self._build_digital_twin_tab() + if self.beamline in ['x01da', 'x10da']: + self._build_digital_twin_tab() self._build_custom_tab() buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) @@ -138,7 +137,10 @@ class ScheduleItemDialog(QDialog): # client=None resolves to the same process-wide BEC client # (bec_dispatcher.client) our own widget uses - no second Redis # connection is opened. - self.scan_control = ScanControlXAS(parent=tab, client=self._client) + if self.beamline in ['x01da', 'x10da']: + self.scan_control = ScanControlXAS(parent=tab, client=self._client) + else: + self.scan_control = ScanControl(parent=tab, client=self._client) self.scan_control.button_run_scan.hide() layout.addWidget(self.scan_control) @@ -301,17 +303,58 @@ class ScheduleItemDialog(QDialog): self.custom_edit.setPlaceholderText("scans.xas_simple_scan(12000, 14000, 2, 10)") layout.addWidget(self.custom_edit) - ic_form = self._create_ionization_chamber_form() - if ic_form is not None: - layout.addWidget(ic_form) + if self.beamline in ['x01da', 'x10da']: + abs_form = self._create_abs_form() + if abs_form is not None: + layout.addWidget(abs_form) - reffoil_form = self._create_reffoil_form() - if reffoil_form is not None: - layout.addWidget(reffoil_form) + ic_form = self._create_ionization_chamber_form() + if ic_form is not None: + layout.addWidget(ic_form) + + reffoil_form = self._create_reffoil_form() + if reffoil_form is not None: + layout.addWidget(reffoil_form) + + auto_gain_form = self._create_auto_gain_form() + if auto_gain_form is not None: + layout.addWidget(auto_gain_form) layout.addStretch(1) self.tabs.addTab(tab, "Other") + def _create_abs_form(self): + if "abs" in self._dev: + abs_group = QGroupBox("Frontend Absorber") + layout = QVBoxLayout(abs_group) + form = QFormLayout() + layout.addLayout(form) + form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) + self.abs_selector = QComboBox() + self.abs_selector.addItems(["Open", "Force open", "Close"]) + + button_layout = QHBoxLayout() + generate_cmd = MyButton("Generate command", "default") + button_layout.addWidget(generate_cmd) + button_layout.addStretch(1) + layout.addLayout(button_layout) + + generate_cmd.clicked.connect(self._generate_abs_command) + + return abs_group + return None + + def _generate_abs_command(self): + match self.abs_selector.currentText(): + case 'Open': + suffix = 'open()' + case 'Force open': + suffix = 'open(force=True)' + case 'Close': + suffix = 'close()' + cmd = f"dev.abs.{suffix}" + self.custom_edit.setText(cmd) + def _create_ionization_chamber_form(self): if all(key in self._dev for key in ("ic0", "ic1", "ic2")): ic_group = QGroupBox("Ionization chamber filling") @@ -411,6 +454,73 @@ class ScheduleItemDialog(QDialog): cmd = f"dev.reffoilchanger.insert(ref='{self.reffoil_selector.currentText()}', wait=True)" self.custom_edit.setText(cmd) + def _create_auto_gain_form(self): + auto_gain_group = QGroupBox("Auto Gain") + layout = QVBoxLayout(auto_gain_group) + + edge_selector_layout = QHBoxLayout() + edge_selector_label = QLabel("Absorption edge:") + self.edge_selector_button = MyButton("Choose", "default") + self.edge_label = QLabel("No edge selected") + edge_selector_layout.addWidget(edge_selector_label) + edge_selector_layout.addWidget(self.edge_selector_button) + edge_selector_layout.addWidget(self.edge_label) + self.edge_element = None + self.edge_edge = None + + layout.addLayout(edge_selector_layout) + + form = QFormLayout() + form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) + + self.ic0_check = QCheckBox("") + form.addRow("Auto gain on IC0", self.ic0_check) + self.ic1_check = QCheckBox("") + form.addRow(" on IC1", self.ic1_check) + self.ic2_check = QCheckBox("") + form.addRow(" on IC2", self.ic2_check) + self.pips_check = QCheckBox("") + form.addRow(" on PIPS", self.pips_check) + + button_layout = QHBoxLayout() + generate_cmd = MyButton("Generate command", "default") + button_layout.addWidget(generate_cmd) + button_layout.addStretch(1) + layout.addLayout(button_layout) + + self.edge_selector_button.clicked.connect(self._update_edge) + generate_cmd.clicked.connect(self._generate_auto_gain_command) + + return auto_gain_group + + def _update_edge(self, *_): + match self.beamline: + case "x01da": + dlg = EdgeSelector(self) + case "x10da": + dlg = EdgeSelector(self) + case _: + dlg = EdgeSelector(self) + if dlg.exec_(): + self.edge_energy = dlg.selected_energy + self.edge_label.setText( + f"{dlg.selected_element}, {dlg.selected_edge}-edge, {dlg.selected_energy:0.1f} eV" + ) + self.edge_element = dlg.selected_element + self.edge_edge = dlg.selected_edge + + def _generate_auto_gain_command(self): + if self.edge_edge is None or self.edge_element is None: + return + amplifiers = [] + for amp, name in [(self.ic0_check, 'ic0'), (self.ic1_check, 'ic1'), (self.ic2_check, 'ic2'), (self.pips_check, 'pips')]: + if amp.isChecked(): + amplifiers.append(name) + if amplifiers == []: + return + cmd = f"auto_gain.start(element={self.edge_element}, edge={self.edge_edge}, {amplifiers}, comp_ring_current=True)" + self.custom_edit.setText(cmd) + def _collect_custom_result(self) -> dict: text = self.custom_edit.text().strip() if not text: diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index a9139cd..b398d16 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -45,7 +45,6 @@ from qtpy.QtWidgets import ( QWidget, ) -from ....bec_ipython_client.plugins.digital_twin.digital_twin import DigitalTwinCore from .endpoints import schedule as schedule_endpoint from .enums import ScheduleItemStatus from .guard import SignalGuard @@ -150,9 +149,20 @@ class Scheduler(BECWidget, QWidget): self.schedule_name = self.config.schedule_name self.get_bec_shortcuts() # -> self.client, self.dev, self.scans, self.queue + self.beamline = self.get_beamline() self.connector = self.client.connector - self.digital_twin = DigitalTwinCore() + if self.beamline in ['x01da', 'x10da']: + logger.info( + 'Scheduler running at X01DA or X10DA, import and load digital twin and auto-gain' + ) + from ....bec_ipython_client.plugins.digital_twin.digital_twin import DigitalTwinCore + from ....bec_ipython_client.plugins.auto_gain import AutoGain + self.digital_twin = DigitalTwinCore() + self.auto_gain = AutoGain() + else: + self.digital_twin = None + self.auto_gain = None self._endpoint = schedule_endpoint(self.schedule_name) self._lock = threading.Lock() # guards self.schedule (see module docstring) @@ -190,6 +200,12 @@ class Scheduler(BECWidget, QWidget): self._closing = threading.Event() + def get_beamline(self): + hostname = self.client._hostname + start = hostname.find("x") + if start != -1: + return hostname[start : start + 5] + # ------------------------------------------------------------------ # # UI # ------------------------------------------------------------------ # @@ -576,12 +592,8 @@ class Scheduler(BECWidget, QWidget): data = self.schedule.model_dump(mode="json") default_name = "schedule.json" - hostname = self.client._hostname - start = hostname.find("x") - if start != -1: - beamline = hostname[start : start + 5] - active_account = self.client.active_account - default_name = f"/sls/{beamline}/data/{active_account}/raw/{default_name}" + active_account = self.client.active_account + default_name = f"/sls/{self.beamline}/data/{active_account}/raw/{default_name}" path, _ = QFileDialog.getSaveFileName( self, "Save schedule to file", default_name, "JSON files (*.json);;All files (*)" @@ -608,12 +620,9 @@ class Scheduler(BECWidget, QWidget): return start_folder = "" - hostname = self.client._hostname - start = hostname.find("x") - if start != -1: - beamline = hostname[start : start + 5] - active_account = self.client.active_account - start_folder = f"/sls/{beamline}/data/{active_account}/raw" + + active_account = self.client.active_account + start_folder = f"/sls/{self.beamline}/data/{active_account}/raw" path, _ = QFileDialog.getOpenFileName( self, "Load schedule from file", start_folder, "JSON files (*.json);;All files (*)" @@ -766,7 +775,7 @@ class Scheduler(BECWidget, QWidget): # ---- UI-triggered edit actions ---- # @SafeSlot() def _on_add_clicked(self): - dialog = ScheduleItemDialog(self.scans, self.dev, parent=self, client=self.client) + dialog = ScheduleItemDialog(self.scans, self.dev, parent=self, client=self.client, beamline=self.beamline) if dialog.exec_() != QDialog.Accepted: return result = dialog.result() @@ -1147,6 +1156,7 @@ class Scheduler(BECWidget, QWidget): "scans": self.scans, "dev": self.dev, "digital_twin": self.digital_twin, + "auto_gain": self.auto_gain, "np": np, } while not self._abort_requested and not self._closing.is_set(): @@ -1289,7 +1299,7 @@ class Scheduler(BECWidget, QWidget): if __name__ == "__main__": app = QApplication(sys.argv) - dispatcher = BECDispatcher(gui_id="digital_twin") + dispatcher = BECDispatcher(gui_id="Scheduler") win = Scheduler() win.show() sys.exit(app.exec_()) From 6c2400a4393bfea695c3a6772969b7e3f5c4fbd3 Mon Sep 17 00:00:00 2001 From: x01da Date: Tue, 8 Sep 2026 09:37:33 +0200 Subject: [PATCH 20/56] wip --- .../bec_ipython_client/plugins/auto_gain.py | 152 +++++++++--------- .../digital_twin/widgets/move_widget.py | 7 +- .../widgets/scheduler/item_dialog.py | 73 ++++++--- .../x01da_experimental_hutch.yaml | 2 +- debye_bec/device_configs/x01da_optics.yaml | 2 +- debye_bec/devices/absorber.py | 12 +- debye_bec/devices/eh_shutter.py | 18 ++- debye_bec/devices/op_shutter.py | 28 +++- 8 files changed, 177 insertions(+), 117 deletions(-) diff --git a/debye_bec/bec_ipython_client/plugins/auto_gain.py b/debye_bec/bec_ipython_client/plugins/auto_gain.py index 846e785..a5ccd5c 100644 --- a/debye_bec/bec_ipython_client/plugins/auto_gain.py +++ b/debye_bec/bec_ipython_client/plugins/auto_gain.py @@ -1,60 +1,63 @@ -""" Module to automatically set the gains for the selected amplifiers""" +"""Module to automatically set the gains for the selected amplifiers""" -from bisect import bisect_right -import time import builtins +import time +from bisect import bisect_right import xraydb from bec_lib import bec_logger -from ...devices.nidaq.nidaq_enums import NidaqState from ...devices.absorber import STATUS as ABS_STATUS -from ...devices.op_shutter import STATUS as OP_PH_STATUS from ...devices.eh_shutter import STATUS as EH_PH_STATUS from ...devices.ionization_chambers.ionization_chamber_enums import AmplifierEnable +from ...devices.nidaq.nidaq_enums import NidaqState +from ...devices.op_shutter import STATUS as OP_PH_STATUS logger = bec_logger.logger EMIN = -100 EMAX = 200 -MIN_RING_CURRENT = 5 # Minimum ring current to use auto-gain -NOMINAL_RING_CURRENT = 400 # Nominal ring current of SLS2 +MIN_RING_CURRENT = 5 # Minimum ring current to use auto-gain +NOMINAL_RING_CURRENT = 400 # Nominal ring current of SLS2 -MONO_VELOCITY = 20 # Move velocity in deg/s -TIMEOUT_MONO_PV = 5 # Timeout to set a PV on the mono -TIMEOUT_MONO_MOVE = 30 # Timeout to finish a movement on the mono +MONO_VELOCITY = 20 # Move velocity in deg/s +TIMEOUT_MONO_PV = 5 # Timeout to set a PV on the mono +TIMEOUT_MONO_MOVE = 30 # Timeout to finish a movement on the mono AVAILABLE_GAINS = [1e6, 1e7, 5e7, 1e8, 1e9] # ascending order -MIN_SIGNAL = 0.05 # Minimum signal to count as valid signal +MIN_SIGNAL = 0.05 # Minimum signal to count as valid signal FULL_SCALE_V = 10.0 # NIDAQ AI full-scale range SAFETY_MARGIN = 0.9 # keep max signal under 90% of full scale + class AutoGainError(Exception): """AutoGain specific error""" -class AutoGain(): - """ Module to automatically set the gains for the selected amplifiers""" + +class AutoGain: + """Module to automatically set the gains for the selected amplifiers""" + def __init__(self): dev = builtins.__dict__.get("dev") bec = builtins.__dict__.get("bec") if dev is None: - raise AutoGainError('Did not get dev') + raise AutoGainError("Did not get dev") if bec is None: - raise AutoGainError('Did not get bec') + raise AutoGainError("Did not get bec") self.dev = dev self.bec = bec def start( - self, - element:str, - edge:str, - amplifier:list[str] | None=None, - comp_ring_current:bool=True - ) -> None: - """ Start the auto-gain sequence. Measure the signals of the specified + self, + element: str, + edge: str, + amplifier: list[str] | None = None, + comp_ring_current: bool = True, + ) -> None: + """Start the auto-gain sequence. Measure the signals of the specified amplifiers and set the gains accordingly. Makes sure there is actually beam available. - + Args: element(str): Element which defines the energy at which the gain will be set, e.g. 'Cu' edge(str): Corresponding edge, e.g. 'L1' @@ -73,25 +76,25 @@ class AutoGain(): If a selected amplifier is switched off If the high voltage of a selected ionization chamber is not enabled or < 1000 V If the gas filling of a selected ionization chamber is not OK - If the ring current drops to 0 mA during the measurement (beamdump) + If the ring current drops to 0 mA during the measurement (beamdump) """ if amplifier is None: - amplifier = ['ic0', 'ic1', 'ic2', 'pips'] + amplifier = ["ic0", "ic1", "ic2", "pips"] # Make sure NIDAQ is in standby mode - if self.dev.nidaq.state.get() is not NidaqState.STANDBY: - raise AutoGainError('NIDAQ was not in Standby mode, cannot proceed.') + if self.dev.nidaq.state.get() != NidaqState.STANDBY: + raise AutoGainError("NIDAQ was not in Standby mode, cannot proceed.") # Check for beam availability if self._get_ring_current() < MIN_RING_CURRENT: - raise AutoGainError(f'Ring current is below {MIN_RING_CURRENT} mA') + raise AutoGainError(f"Ring current is below {MIN_RING_CURRENT} mA") if self.dev.abs.status.get() != ABS_STATUS.OPEN: - raise AutoGainError('Absorber is closed, no beam') - if self.dev.op_shutter.status.get() != OP_PH_STATUS.NOT_CLOSED: - raise AutoGainError('OP Photon Shutter is closed, no beam') - if self.dev.eh_shutter.status.get() != EH_PH_STATUS.NOT_CLOSED: - raise AutoGainError('EH Photon Shutter is closed, no beam') + raise AutoGainError("Absorber is closed, no beam") + if self.dev.op_sh.status.get() != OP_PH_STATUS.NOT_CLOSED: + raise AutoGainError("OP Photon Shutter is closed, no beam") + if self.dev.eh_sh.status.get() != EH_PH_STATUS.NOT_CLOSED: + raise AutoGainError("EH Photon Shutter is closed, no beam") # Check if no scan is running scan_id = self.bec.queue.scan_storage.current_scan_id @@ -101,56 +104,57 @@ class AutoGain(): # Get edge energy energy = xraydb.xray_edge(element, edge, True) if energy is None: - raise ValueError(f'Could not find edge energy for element/edge {element}/{edge}') + raise ValueError(f"Could not find edge energy for element/edge {element}/{edge}") emin = energy + EMIN emax = energy + EMAX # Check range of mono - low_limit, high_limit = self.dev.mo1_bragg.limits() + low_limit = self.dev.mo1_bragg.low_lim.get() + high_limit = self.dev.mo1_bragg.high_lim.get() if emin < low_limit or emax > high_limit: raise ValueError( - f'Chosen element/edge {element}/{edge} with edge energy of {energy}' + - ' is outside of accessible range of monochromator ' + - f'{low_limit:.1f} eV - {high_limit:.1f} eV' + f"Chosen element/edge {element}/{edge} with edge energy of {energy}" + + " is outside of accessible range of monochromator " + + f"{low_limit:.1f} eV - {high_limit:.1f} eV" ) # Map amplifier names to their NIDAQ channels channel_map = { - 'ic0': {'signal': self.dev.nidaq.ai0, 'self.dev': self.dev.ic0}, - 'ic1': {'signal': self.dev.nidaq.ai2, 'self.dev': self.dev.ic1}, - 'ic2': {'signal': self.dev.nidaq.ai4, 'self.dev': self.dev.ic2}, - 'pips': {'signal': self.dev.nidaq.ai6, 'self.dev': self.dev.pips}, + "ic0": {"signal": self.dev.nidaq.ai0, "self.dev": self.dev.ic0}, + "ic1": {"signal": self.dev.nidaq.ai2, "self.dev": self.dev.ic1}, + "ic2": {"signal": self.dev.nidaq.ai4, "self.dev": self.dev.ic2}, + "pips": {"signal": self.dev.nidaq.ai6, "self.dev": self.dev.pips}, } active_channels = {name: ch for name, ch in channel_map.items() if name in amplifier} # Check if amplifieres are switched on for name, ch in active_channels.items(): - if ch['self.dev'].amp.cOnOff.get() != AmplifierEnable.ON: + if ch["self.dev"].amp.cOnOff.get() != AmplifierEnable.ON: raise AutoGainError(f"Amplifier of self.device {name} is not enabled") # Check high voltage on ionization chambers for name, ch in active_channels.items(): - if name != 'pips': - if ch['self.dev'].hv_en.ena.get() is not True: + if name != "pips": + if ch["self.dev"].hv_en.ena.get() != 1: raise AutoGainError(f"High voltage of ionization chamber {name} is not enabled") - if ch['self.dev'].hv.v.get() < 1000: + if ch["self.dev"].hv.hv_v.get() < 1000: raise AutoGainError(f"HV voltage of ionization chamber {name} is < 1000") - if ch['self.dev'].hv.grid_v.get() < 1000: + if ch["self.dev"].hv.grid_v.get() < 1000: raise AutoGainError(f"Grid voltage of ionization chamber {name} is < 1000") # Check gas filling of ionization chambers for name, ch in active_channels.items(): - if name != 'pips': - if ch['self.dev'].gmes.status.get() is not True: - raise AutoGainError(f'Gas filling of ionization chamber {name} is not OK') + if name != "pips": + if ch["self.dev"].gmes.status.get() != 1: + raise AutoGainError(f"Gas filling of ionization chamber {name} is not OK") - logger.info('All checks done, start preparing for measurement') + logger.info("All checks done, start preparing for measurement") # Get initial monochromator position and velocity init_pos = self.dev.mo1_bragg.position.get() init_vel = self.dev.mo1_bragg.velocity.get() - logger.info(f'Move mono to start of {emin} eV') + logger.info(f"Move mono to start of {emin} eV") status = self.dev.mo1_bragg.move(emin) status.wait(TIMEOUT_MONO_MOVE) @@ -160,20 +164,20 @@ class AutoGain(): # Set gains to lowest gain for name, ch in active_channels.items(): lowest_gain = AVAILABLE_GAINS[0] - ch['self.dev'].set_gain(lowest_gain) - ch['gain'] = lowest_gain + ch["self.dev"].set_gain(lowest_gain) + ch["gain"] = lowest_gain remeasure = True - logger.info(f'Start measurement from {emin} eV to {emax} eV') + logger.info(f"Start measurement from {emin} eV to {emax} eV") while remeasure: # Create temporary storage for max signal per channel data = {name: 0 for name in active_channels} # Measure current ring current ring_current_1 = self._get_ring_current() - logger.info(f'Ring current right before measurement: {ring_current_1} mA') + logger.info(f"Ring current right before measurement: {ring_current_1} mA") if ring_current_1 == 0: - raise AutoGainError('Ring current dropped to 0 mA right before measurement') + raise AutoGainError("Ring current dropped to 0 mA right before measurement") # Scan range, recording the peak NIDAQ signal per channel status = self.dev.mo1_bragg.velocity.put(MONO_VELOCITY) @@ -181,16 +185,16 @@ class AutoGain(): self.dev.mo1_bragg.move(emax).wait(timeout=TIMEOUT_MONO_MOVE) status.wait(TIMEOUT_MONO_MOVE) for name, ch in active_channels.items(): - data[name] = max(data[name], ch['signal'].get()) + data[name] = max(data[name], ch["signal"].get()) # Rest max values of NIDAQ signals # TODO implement # Measure current ring current again ring_current_2 = self._get_ring_current() - logger.info(f'Ring current right after measurement: {ring_current_2} mA') + logger.info(f"Ring current right after measurement: {ring_current_2} mA") if ring_current_2 == 0: - raise AutoGainError('Ring current dropped to 0 mA during measurement') + raise AutoGainError("Ring current dropped to 0 mA during measurement") ring_current = (ring_current_1 + ring_current_2) / 2 # Move back to first monochromator position @@ -200,35 +204,39 @@ class AutoGain(): remeasure = False for name, ch in active_channels.items(): raw_signal = data[name] - logger.info(f'Raw signal for self.device {name} is {raw_signal} V') + logger.info(f"Raw signal for self.device {name} is {raw_signal} V") if comp_ring_current: raw_signal = raw_signal * NOMINAL_RING_CURRENT / ring_current - logger.info(f'Compensate for ring current, new raw signal is {raw_signal} V') + logger.info(f"Compensate for ring current, new raw signal is {raw_signal} V") if raw_signal < MIN_SIGNAL: - logger.info(f'Raw signal for self.device {name} is below {MIN_SIGNAL}') + logger.info(f"Raw signal for self.device {name} is below {MIN_SIGNAL}") # Choose next gain to be 100x the current gain, or if this gain does not exist, # choose the next smaller one - if ch['gain'] == AVAILABLE_GAINS[-1]: + if ch["gain"] == AVAILABLE_GAINS[-1]: logger.warning( - f"Amplifier of {name} at highest gain {ch['gain']} and still not" + - f" measured signal above {MIN_SIGNAL}" + f"Amplifier of {name} at highest gain {ch['gain']} and still not" + + f" measured signal above {MIN_SIGNAL}" ) else: next_gain = AVAILABLE_GAINS[ - bisect_right(AVAILABLE_GAINS, ch['gain'] * 100) - 1 + bisect_right(AVAILABLE_GAINS, ch["gain"] * 100) - 1 ] - ch['self.dev'].set_gain(next_gain) + ch["self.dev"].set_gain(next_gain) logger.info( - f'Setting gain of self.device {name} to {next_gain:.0e} and remeasure' + f"Setting gain of self.device {name} to {next_gain:.0e} and remeasure" ) remeasure = True else: gain = max( - (g for g in AVAILABLE_GAINS if raw_signal / ch['gain'] * g <= FULL_SCALE_V * SAFETY_MARGIN), + ( + g + for g in AVAILABLE_GAINS + if raw_signal / ch["gain"] * g <= FULL_SCALE_V * SAFETY_MARGIN + ), default=min(AVAILABLE_GAINS), ) - ch['self.dev'].set_gain(gain) - logger.info(f'Calculated final gain for {name} of {gain:.0e}') + ch["self.dev"].set_gain(gain) + logger.info(f"Calculated final gain for {name} of {gain:.0e}") # Wait for mono to return to start position status.wait(TIMEOUT_MONO_MOVE) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py b/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py index aa57582..0aa6f24 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py @@ -292,15 +292,13 @@ class MotionWorker(QObject): Args: surveyed_axes (list): List of dictionaries of devices """ + logger.info(f"Move axis {self.motor} to target {self._target}, move_relative={relative}") try: if alias: self.motor = alias if abs_closed: if self.dev.abs.status.get() == ABS_STATUS.OPEN: status = self.dev.abs.close() - # TODO Set timeout to 0.001 and check if it actually raises - # (it should not start motion). - # Check of behavior of digital twin afterwards. status.wait(timeout=5) if surveyed_axes is not None: for surv_ax in surveyed_axes: @@ -336,7 +334,8 @@ class MotionWorker(QObject): self.finished.emit() break self.finished.emit() - except: + except Exception as e: + logger.error(f"Error during movement of {self.motor}: {e}") self.error.emit() self.finished.emit() diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index 522aab1..79d6bc3 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -54,6 +54,8 @@ from bec_widgets.widgets.control.device_input.device_combobox.device_combobox im DeviceComboBox, ) from bec_widgets.widgets.control.scan_control.scan_control import ScanControl, ScanParameterConfig + +# pylint: disable=E0611 from qtpy.QtWidgets import ( QCheckBox, QComboBox, @@ -71,6 +73,7 @@ from qtpy.QtWidgets import ( QVBoxLayout, QWidget, ) + from .qt_widgets import MyButton logger = bec_logger.logger @@ -86,7 +89,15 @@ _TAB_OTHER = 3 class ScheduleItemDialog(QDialog): """Add or edit one schedule item, via ScanControl, a move form, Digital Twin, or free text.""" - def __init__(self, scans, dev, parent=None, initial: dict | None = None, client=None, beamline:str|None=None): + def __init__( + self, + scans, + dev, + parent=None, + initial: dict | None = None, + client=None, + beamline: str | None = None, + ): super().__init__(parent) self.setWindowTitle("Schedule item") self.setMinimumSize(520, 480) @@ -96,11 +107,17 @@ class ScheduleItemDialog(QDialog): self._client = client self.beamline = beamline - if self.beamline in ['x01da', 'x10da']: + if self.beamline in ["x01da", "x10da"]: + logger.info(f"Loading bl-specific modules for beamline {self.beamline}") from ....bec_ipython_client.plugins.digital_twin.digital_twin import DigitalTwinCore from ..digital_twin.digital_twin import DigitalTwin - from ..scan_control_xas.scan_control_xas import ScanControlXAS from ..edge_selector import EdgeSelector + from ..scan_control_xas.scan_control_xas import ScanControlXAS + + self.DigitalTwinCore = DigitalTwinCore + self.DigitalTwin = DigitalTwin + self.EdgeSelector = EdgeSelector + self.ScanControlXAS = ScanControlXAS layout = QVBoxLayout(self) self.tabs = QTabWidget() @@ -108,7 +125,7 @@ class ScheduleItemDialog(QDialog): self._build_scan_tab() self._build_move_tab() - if self.beamline in ['x01da', 'x10da']: + if self.beamline in ["x01da", "x10da"]: self._build_digital_twin_tab() self._build_custom_tab() @@ -137,8 +154,8 @@ class ScheduleItemDialog(QDialog): # client=None resolves to the same process-wide BEC client # (bec_dispatcher.client) our own widget uses - no second Redis # connection is opened. - if self.beamline in ['x01da', 'x10da']: - self.scan_control = ScanControlXAS(parent=tab, client=self._client) + if self.beamline in ["x01da", "x10da"]: + self.scan_control = self.ScanControlXAS(parent=tab, client=self._client) else: self.scan_control = ScanControl(parent=tab, client=self._client) self.scan_control.button_run_scan.hide() @@ -240,7 +257,7 @@ class ScheduleItemDialog(QDialog): # doesn't have to grow to match it. scroll = QScrollArea() scroll.setWidgetResizable(True) - self.digital_twin = DigitalTwin(parent=scroll, client=self._client) + self.digital_twin = self.DigitalTwin(parent=scroll, client=self._client) # Hide move and abs open buttons for mover in self.digital_twin.mover.mover_widgets: mover.btn_action.hide() @@ -303,7 +320,7 @@ class ScheduleItemDialog(QDialog): self.custom_edit.setPlaceholderText("scans.xas_simple_scan(12000, 14000, 2, 10)") layout.addWidget(self.custom_edit) - if self.beamline in ['x01da', 'x10da']: + if self.beamline in ["x01da", "x10da"]: abs_form = self._create_abs_form() if abs_form is not None: layout.addWidget(abs_form) @@ -332,6 +349,7 @@ class ScheduleItemDialog(QDialog): form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) self.abs_selector = QComboBox() self.abs_selector.addItems(["Open", "Force open", "Close"]) + form.addRow("Action", self.abs_selector) button_layout = QHBoxLayout() generate_cmd = MyButton("Generate command", "default") @@ -346,12 +364,12 @@ class ScheduleItemDialog(QDialog): def _generate_abs_command(self): match self.abs_selector.currentText(): - case 'Open': - suffix = 'open()' - case 'Force open': - suffix = 'open(force=True)' - case 'Close': - suffix = 'close()' + case "Open": + suffix = "open()" + case "Force open": + suffix = "open(force=True)" + case "Close": + suffix = "close()" cmd = f"dev.abs.{suffix}" self.custom_edit.setText(cmd) @@ -411,6 +429,8 @@ class ScheduleItemDialog(QDialog): self.conc1.setValue(100 - new_val) def _generate_ic_command(self): + if self.conc1.value() + self.conc2.value() != 100: + return match self.ic_selector.currentText(): case "IC0": ic = "ic0" @@ -465,22 +485,26 @@ class ScheduleItemDialog(QDialog): edge_selector_layout.addWidget(edge_selector_label) edge_selector_layout.addWidget(self.edge_selector_button) edge_selector_layout.addWidget(self.edge_label) + edge_selector_layout.addStretch() self.edge_element = None self.edge_edge = None layout.addLayout(edge_selector_layout) + layout.addWidget(QLabel("Auto gain on")) + form = QFormLayout() + layout.addLayout(form) form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) self.ic0_check = QCheckBox("") - form.addRow("Auto gain on IC0", self.ic0_check) + form.addRow("IC0", self.ic0_check) self.ic1_check = QCheckBox("") - form.addRow(" on IC1", self.ic1_check) + form.addRow("IC1", self.ic1_check) self.ic2_check = QCheckBox("") - form.addRow(" on IC2", self.ic2_check) + form.addRow("IC2", self.ic2_check) self.pips_check = QCheckBox("") - form.addRow(" on PIPS", self.pips_check) + form.addRow("PIPS", self.pips_check) button_layout = QHBoxLayout() generate_cmd = MyButton("Generate command", "default") @@ -496,11 +520,11 @@ class ScheduleItemDialog(QDialog): def _update_edge(self, *_): match self.beamline: case "x01da": - dlg = EdgeSelector(self) + dlg = self.EdgeSelector(self) case "x10da": - dlg = EdgeSelector(self) + dlg = self.EdgeSelector(self) case _: - dlg = EdgeSelector(self) + dlg = self.EdgeSelector(self) if dlg.exec_(): self.edge_energy = dlg.selected_energy self.edge_label.setText( @@ -513,7 +537,12 @@ class ScheduleItemDialog(QDialog): if self.edge_edge is None or self.edge_element is None: return amplifiers = [] - for amp, name in [(self.ic0_check, 'ic0'), (self.ic1_check, 'ic1'), (self.ic2_check, 'ic2'), (self.pips_check, 'pips')]: + for amp, name in [ + (self.ic0_check, "ic0"), + (self.ic1_check, "ic1"), + (self.ic2_check, "ic2"), + (self.pips_check, "pips"), + ]: if amp.isChecked(): amplifiers.append(name) if amplifiers == []: diff --git a/debye_bec/device_configs/x01da_experimental_hutch.yaml b/debye_bec/device_configs/x01da_experimental_hutch.yaml index 219e0d0..cec7109 100644 --- a/debye_bec/device_configs/x01da_experimental_hutch.yaml +++ b/debye_bec/device_configs/x01da_experimental_hutch.yaml @@ -3,7 +3,7 @@ ## Experimental Hutch Photon Shutter ## ####################################### -eh-sh: +eh_sh: readoutPriority: baseline description: Experimental Hutch Photon Shutter deviceClass: debye_bec.devices.eh_shutter.EHPhotonShutter diff --git a/debye_bec/device_configs/x01da_optics.yaml b/debye_bec/device_configs/x01da_optics.yaml index ea61ae9..c96564d 100644 --- a/debye_bec/device_configs/x01da_optics.yaml +++ b/debye_bec/device_configs/x01da_optics.yaml @@ -3,7 +3,7 @@ ## Optics Photon Shutter ## ################################### -op-sh: +op_sh: readoutPriority: baseline description: Optics Hutch Photon Shutter deviceClass: debye_bec.devices.op_shutter.OPPhotonShutter diff --git a/debye_bec/devices/absorber.py b/debye_bec/devices/absorber.py index fa719db..29c3c9f 100644 --- a/debye_bec/devices/absorber.py +++ b/debye_bec/devices/absorber.py @@ -17,6 +17,7 @@ if TYPE_CHECKING: TIMEOUT_FOR_PV = 5 + class AbsorberError(Exception): """Absorber specific exception""" @@ -40,6 +41,7 @@ class STATUS(int, enum.Enum): MAN_OPEN = 13 UNDEFINED = 14 + class BL_ENABLE(int, enum.Enum): """Beamline enable""" @@ -64,7 +66,7 @@ class Absorber(PSIDeviceBase): string=True, doc="Absorber Status", ) - close4bl = Cpt(EpicsSignal, suffix='CLOSE4BL', kind='config', doc='Beamline enable') + close4bl = Cpt(EpicsSignal, suffix="CLOSE4BL", kind="config", doc="Beamline enable") def __init__(self, *, name: str, prefix: str = "", scan_info: ScanInfo | None = None, **kwargs): super().__init__(name=name, prefix=prefix, scan_info=scan_info, **kwargs) @@ -73,15 +75,15 @@ class Absorber(PSIDeviceBase): # Wait for connection on all components, ensure IOC is connected self.wait_for_connection(all_signals=True, timeout=5) - def open(self, force:bool=False) -> DeviceStatus | None: + def open(self, force: bool = False) -> DeviceStatus | None: """Open the Absorber Args: force(bool): If needed, set bl status to enable and bl enable to ENABLE, defaults to False - + """ - if force and self.device_manager.devices.get('bl_status', None) is None: - raise AbsorberError('bl_status is not in device config, thus cannot use force = True') + if force and self.device_manager.devices.get("bl_status", None) is None: + raise AbsorberError("bl_status is not in device config, thus cannot use force = True") if self.status.get() == STATUS.CLOSED: if force: if self.device_manager.bl_status.get() == BlStatus.OFFLINE: diff --git a/debye_bec/devices/eh_shutter.py b/debye_bec/devices/eh_shutter.py index 52d06e3..27b141e 100644 --- a/debye_bec/devices/eh_shutter.py +++ b/debye_bec/devices/eh_shutter.py @@ -17,12 +17,14 @@ if TYPE_CHECKING: TIMEOUT_FOR_PV = 5 + class STATUS(int, enum.Enum): """Shutter States""" NOT_CLOSED = 0 CLOSED = 1 + class BL_ENABLE(int, enum.Enum): """Beamline enable""" @@ -30,15 +32,23 @@ class BL_ENABLE(int, enum.Enum): ENABLE = 1 -class OPPhotonShutter(PSIDeviceBase): +class EHPhotonShutter(PSIDeviceBase): """Class for the Experimental Hutch Photon Shutter""" USER_ACCESS = ["open", "close"] - request_open = Cpt(EpicsSignal, suffix="EH1-PSYS:SH-A-OPEN-SET", kind="config", doc="Open Shutter") - request_close = Cpt(EpicsSignal, suffix="EH1-PSYS:SH-A-CLOSE-SET", kind="config", doc="Close Shutter") + request_open = Cpt( + EpicsSignal, suffix="EH1-PSYS:SH-A-OPEN-SET", kind="config", doc="Open Shutter" + ) + request_close = Cpt( + EpicsSignal, suffix="EH1-PSYS:SH-A-CLOSE-SET", kind="config", doc="Close Shutter" + ) status = Cpt( - EpicsSignalRO, suffix="EH1", kind="normal", auto_monitor=True, doc="Shutter Status" + EpicsSignalRO, + suffix="EH1-PSYS:SH-A-CLOSE", + kind="normal", + auto_monitor=True, + doc="Shutter Status", ) status_string = Cpt( EpicsSignalRO, diff --git a/debye_bec/devices/op_shutter.py b/debye_bec/devices/op_shutter.py index 99b8ba1..4f963ad 100644 --- a/debye_bec/devices/op_shutter.py +++ b/debye_bec/devices/op_shutter.py @@ -17,6 +17,7 @@ if TYPE_CHECKING: TIMEOUT_FOR_PV = 5 + class OPPhotonShutterError(Exception): """Shutter specific exception""" @@ -27,6 +28,7 @@ class STATUS(int, enum.Enum): NOT_CLOSED = 0 CLOSED = 1 + class BL_ENABLE(int, enum.Enum): """Beamline enable""" @@ -39,10 +41,18 @@ class OPPhotonShutter(PSIDeviceBase): USER_ACCESS = ["open", "close"] - request_open = Cpt(EpicsSignal, suffix="OP-PSYS:SH-A-OPEN-SET", kind="config", doc="Open Shutter") - request_close = Cpt(EpicsSignal, suffix="OP-PSYS:SH-A-CLOSE-SET", kind="config", doc="Close Shutter") + request_open = Cpt( + EpicsSignal, suffix="OP-PSYS:SH-A-OPEN-SET", kind="config", doc="Open Shutter" + ) + request_close = Cpt( + EpicsSignal, suffix="OP-PSYS:SH-A-CLOSE-SET", kind="config", doc="Close Shutter" + ) status = Cpt( - EpicsSignalRO, suffix="OP-PSYS:SH-A-CLOSE", kind="normal", auto_monitor=True, doc="Shutter Status" + EpicsSignalRO, + suffix="OP-PSYS:SH-A-CLOSE", + kind="normal", + auto_monitor=True, + doc="Shutter Status", ) status_string = Cpt( EpicsSignalRO, @@ -52,7 +62,7 @@ class OPPhotonShutter(PSIDeviceBase): string=True, doc="Shutter Status", ) - close4bl = Cpt(EpicsSignal, suffix='FE-BST1:CLOSE4BL', kind='config', doc='Beamline enable') + close4bl = Cpt(EpicsSignal, suffix="FE-BST1:CLOSE4BL", kind="config", doc="Beamline enable") def __init__(self, *, name: str, prefix: str = "", scan_info: ScanInfo | None = None, **kwargs): super().__init__(name=name, prefix=prefix, scan_info=scan_info, **kwargs) @@ -61,15 +71,17 @@ class OPPhotonShutter(PSIDeviceBase): # Wait for connection on all components, ensure IOC is connected self.wait_for_connection(all_signals=True, timeout=5) - def open(self, force:bool=False) -> DeviceStatus | None: + def open(self, force: bool = False) -> DeviceStatus | None: """Open the Shutter Args: force(bool): If needed, set bl status to enable and bl enable to ENABLE, defaults to False - + """ - if force and self.device_manager.devices.get('bl_status', None) is None: - raise OPPhotonShutterError('bl_status is not in device config, thus cannot use force = True') + if force and self.device_manager.devices.get("bl_status", None) is None: + raise OPPhotonShutterError( + "bl_status is not in device config, thus cannot use force = True" + ) if self.status.get() == STATUS.CLOSED: if force: if self.device_manager.bl_status.get() == BlStatus.OFFLINE: From 0a525e259d9f1fbce9a2774e17503814c7488413 Mon Sep 17 00:00:00 2001 From: hitz_s Date: Tue, 8 Sep 2026 10:23:30 +0200 Subject: [PATCH 21/56] feat(data_viewer): Add double click to open widget --- .../bec_widgets/widgets/data_viewer/data_viewer.py | 7 +++++++ .../widgets/data_viewer/widgets/qt_widgets.py | 11 +++++++++++ 2 files changed, 18 insertions(+) diff --git a/debye_bec/bec_widgets/widgets/data_viewer/data_viewer.py b/debye_bec/bec_widgets/widgets/data_viewer/data_viewer.py index d8addb3..f4ab865 100644 --- a/debye_bec/bec_widgets/widgets/data_viewer/data_viewer.py +++ b/debye_bec/bec_widgets/widgets/data_viewer/data_viewer.py @@ -55,6 +55,7 @@ class DataViewer(BECWidget, QWidget): self.current_row = 0 self.input.scan_sel.currentItemChanged_connect(self.scan_sel_changed) + self.input.scan_sel.itemDoubleClicked_connect(self.scan_sel_double_click) self.input.load_button.clicked_connect(self.load_scan_from_history) self.input.load_from_folder_button.clicked_connect(self.load_scan_from_folder) self.viewer.unload_button.clicked_connect(self.unload_all_scans) @@ -77,6 +78,12 @@ class DataViewer(BECWidget, QWidget): """Updates the current row value of the scan selection list""" self.current_row = kwargs["value"]().row() + @SafeSlot() + def scan_sel_double_click(self, *_, **kwargs): + """Updates the current row value of the scan selection list and loads the scan""" + self.current_row = kwargs["value"]().row() + self.load_scan_from_history() + @SafeSlot() def open_in_file_manager(self, *_): """Open the scan folder in the systems default file manager""" diff --git a/debye_bec/bec_widgets/widgets/data_viewer/widgets/qt_widgets.py b/debye_bec/bec_widgets/widgets/data_viewer/widgets/qt_widgets.py index 7242c1e..4f9add1 100644 --- a/debye_bec/bec_widgets/widgets/data_viewer/widgets/qt_widgets.py +++ b/debye_bec/bec_widgets/widgets/data_viewer/widgets/qt_widgets.py @@ -105,6 +105,17 @@ class ListWidget(QWidget): ) ) + def itemDoubleClicked_connect(self, func): + """Connect a function to Double Click event.""" + self.value.itemDoubleClicked.connect( + partial( + func, + identifier=self.identifier, + value_obj=self.value, + value=lambda: self.value.currentIndex(), + ) + ) + def setDisabled(self, disable): self.value.setDisabled(disable) From 6d5adc42053f8fc7f23f86a80b6f52a6e35b4bb6 Mon Sep 17 00:00:00 2001 From: hitz_s Date: Tue, 8 Sep 2026 11:35:40 +0200 Subject: [PATCH 22/56] wip --- .../plugins/digital_twin/digital_twin.py | 389 ------ .../__init__.py | 0 .../beamline.py | 0 .../digital_twin_core/digital_twin_core.py | 1119 +++++++++++++++++ .../types.py | 0 .../x01da_offsets.yaml | 0 .../x01da_parameters.py | 0 .../x10da_offsets.yaml | 0 .../x10da_parameters.py | 592 ++++----- .../startup/post_startup.py | 2 +- .../widgets/digital_twin/__init__.py | 3 - .../digital_twin/calculations/__init__.py | 0 .../calculations/calc_sideview.py | 70 -- .../calculations/calc_surfaces.py | 159 --- .../digital_twin/calculations/calc_varia.py | 519 -------- .../widgets/digital_twin/digital_twin.py | 96 +- .../widgets/digital_twin/offsets.py | 83 -- .../digital_twin/panels/input_panel.py | 2 +- .../digital_twin/panels/mover_panel.py | 2 +- .../widgets/digital_twin/panels/plots.py | 30 +- .../bec_widgets/widgets/digital_twin/types.py | 83 -- .../digital_twin/widgets/move_widget.py | 3 +- .../widgets/digital_twin/x01da_offsets.yaml | 50 - .../widgets/digital_twin/x01da_parameters.py | 323 ----- .../widgets/digital_twin/x10da_offsets.yaml | 59 - .../widgets/digital_twin/x10da_parameters.py | 296 ----- .../widgets/scheduler/item_dialog.py | 2 +- .../widgets/scheduler/scheduler.py | 2 +- 28 files changed, 1477 insertions(+), 2407 deletions(-) delete mode 100644 debye_bec/bec_ipython_client/plugins/digital_twin/digital_twin.py rename debye_bec/bec_ipython_client/plugins/{digital_twin => digital_twin_core}/__init__.py (100%) rename debye_bec/bec_ipython_client/plugins/{digital_twin => digital_twin_core}/beamline.py (100%) create mode 100644 debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py rename debye_bec/bec_ipython_client/plugins/{digital_twin => digital_twin_core}/types.py (100%) rename debye_bec/bec_ipython_client/plugins/{digital_twin => digital_twin_core}/x01da_offsets.yaml (100%) rename debye_bec/bec_ipython_client/plugins/{digital_twin => digital_twin_core}/x01da_parameters.py (100%) rename debye_bec/bec_ipython_client/plugins/{digital_twin => digital_twin_core}/x10da_offsets.yaml (100%) rename debye_bec/bec_ipython_client/plugins/{digital_twin => digital_twin_core}/x10da_parameters.py (96%) delete mode 100644 debye_bec/bec_widgets/widgets/digital_twin/calculations/__init__.py delete mode 100644 debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_sideview.py delete mode 100644 debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_surfaces.py delete mode 100644 debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_varia.py delete mode 100644 debye_bec/bec_widgets/widgets/digital_twin/offsets.py delete mode 100644 debye_bec/bec_widgets/widgets/digital_twin/types.py delete mode 100644 debye_bec/bec_widgets/widgets/digital_twin/x01da_offsets.yaml delete mode 100644 debye_bec/bec_widgets/widgets/digital_twin/x01da_parameters.py delete mode 100644 debye_bec/bec_widgets/widgets/digital_twin/x10da_offsets.yaml delete mode 100644 debye_bec/bec_widgets/widgets/digital_twin/x10da_parameters.py diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin/digital_twin.py b/debye_bec/bec_ipython_client/plugins/digital_twin/digital_twin.py deleted file mode 100644 index 28019d2..0000000 --- a/debye_bec/bec_ipython_client/plugins/digital_twin/digital_twin.py +++ /dev/null @@ -1,389 +0,0 @@ -from pathlib import Path - -import numpy as np -import yaml -from bec_lib import bec_logger -from bec_lib.logger import bec_logger - -from . import parameters as bl -from .beamline import get_beamline_id -from .types import BeamlineId, ConfigDict - -OFFSET_FILE_X01DA = Path(__file__).with_name("x01da_offsets.yaml") -OFFSET_FILE_X10DA = Path(__file__).with_name("x10da_offsets.yaml") - -logger = bec_logger.logger - -""" -The idea is to move the core logic of digital_twin to this file. Only keep the gui elements in the widget. -This way, the scheduler widget can access digital twin without loading the GUI (GUI is still needed for the item creation, but not the item execution) - Scheduler will extract assistant inputs (get_assistant_config) during item creation - Scheduler will use digital_twin.calculate_positons to calculate positions and digital_twin.move_all to move the motors -""" - - -class DigitalTwinCore: - - def __init__(self): - logger.info("This is the digital twin from the ipython client!") - self.beamline = get_beamline_id() - self.offset_file = Path() - match self.beamline: - case "x01da": - self.offset_file = OFFSET_FILE_X01DA - case "x10da": - self.offset_file = OFFSET_FILE_X10DA - self.offsets = {} - self.load_offsets() - - def move_with_config(self, config): - positions = self.calc_positions(self.beamline, config) - positions = self.apply_offsets(positions, nested_config=True) - logger.info(f"Would now move to these positions: {positions}") - - def load_offsets(self): - if self.offsets == {}: - logger.info("Load beamline offsets") - if not self.offset_file.exists(): - raise FileNotFoundError(f"Offset file not found: {self.offset_file}") - - with self.offset_file.open("r", encoding="utf-8") as f: - data = yaml.safe_load(f) - - if not isinstance(data, dict): - raise ValueError(f"Expected a YAML mapping, got {type(data).__name__}") - - self.offsets = data - else: - logger.info("Unload beamline offsets") - self.offsets = {} - - def apply_offsets(self, config, nested_config=False): - for axis, axis_data in config.items(): - if axis in self.offsets: - axis_offsets = self.offsets[axis] - if "modifier" in axis_offsets and "offset" in axis_offsets: - for idx, rng in enumerate(axis_offsets["modifier"]["range"]): - modifier_axis = axis_offsets["modifier"]["axis"] - modifier_value = ( - config[modifier_axis]["value"] - if nested_config - else config[modifier_axis] - ) - if rng[0] < modifier_value < rng[1]: - if nested_config: - axis_data["value"] += axis_offsets["offset"][idx] - else: - config[axis] += axis_offsets["offset"][idx] - break - elif "offset" in axis_offsets: - if nested_config: - axis_data["value"] += axis_offsets["offset"] - else: - config[axis] += axis_offsets["offset"] - return config - - def remove_offsets(self, config): - for axis, _ in config.items(): - if axis in self.offsets: - axis_offsets = self.offsets[axis] - if "modifier" in axis_offsets and "offset" in axis_offsets: - for idx, rng in enumerate(axis_offsets["modifier"]["range"]): - if rng[0] < config[axis_offsets["modifier"]["axis"]] < rng[1]: - config[axis] -= axis_offsets["offset"][idx] - break - elif "offset" in axis_offsets: - config[axis] -= axis_offsets["offset"] - return config - - @staticmethod - def calc_positions(beamline: BeamlineId, cfg: ConfigDict) -> dict[str, dict[str, float]]: - """ - Calculates the positions of axes based on a beamline config. - - Args: - cfg(ConfigDict): Dictionary with beamline config - - Returns: - dict[str, dict[str, float]]: Dictionary mapping device names to dictionaries - containing a "value" key with the corresponding float value (position). - """ - - pos = {} - - ## FE slits - trxr = -np.arctan(cfg["h_acc"]) * bl.feSlits.center1[1] - trxw = ( - (np.arctan(cfg["h_acc"]) * bl.feSlits.center1[1]) - / bl.feSlits.center1[1] - * bl.feSlits.center2[1] - ) - tryb = -np.arctan(cfg["v_acc"]) * bl.feSlits.center1[1] - tryt = ( - (np.arctan(cfg["v_acc"]) * bl.feSlits.center1[1]) - / bl.feSlits.center1[1] - * bl.feSlits.center2[1] - ) - - xgap = trxw - trxr - ygap = tryt - tryb - - pos["sldi_gapx"] = {"value": xgap} - pos["sldi_gapy"] = {"value": ygap} - - ## Collimating Mirror - obj_dist = bl.cm.center[1] # object distance - beam_vs = 2 * obj_dist * np.tan(cfg["v_acc"]) # vertical size of beam after CM - - # TRX - if cfg["cm_stripe"] in bl.cm.surface: - index = bl.cm.surface.index(cfg["cm_stripe"]) - else: - raise ValueError(f"Requested stripe {cfg['cm_stripe']} not found in parameters!") - cm_trx = -(bl.cm.limOptX[0][index] + bl.cm.limOptX[1][index]) / 2 - pos["cm_trx"] = {"value": cm_trx} - - # TRY - height = obj_dist * np.tan(cfg["v_acc"]) ** 2 * 1 / np.tan(cfg["cm_pitch"]) - pos["cm_try"] = {"value": height} - - # Pitch - pos["cm_rotx"] = { - "value": -cfg["cm_pitch"] * 1e3 - } # invert and convert to mrad (same as EGU of rotx axis) - - # Bending Radius - radius = ( - 2.0 * obj_dist / np.sin(cfg["cm_pitch"]) - ) # Elements of modern X-ray Physics, page 108 ff. - pos["cm_bnd_radius"] = {"value": radius * 1e-6} # Convert to km - - ## Monochromator - if cfg["mo1_mode"] == "Monochromatic": - # Add 2x CM pitch to the bragg angle - bragg = cfg["mo1_bragg"] - elif cfg["mo1_mode"] == "Pinkbeam": - # Align xtal surfaces parallel to beam - bragg = 0 - else: - raise ValueError("Monochromator mode not supported") - pos["mo1_bragg_angle"] = {"value": bragg / np.pi * 180} # Bragg angle in deg - - # TRY, Height - l = bl.mo1.xtalGap[0] / np.sin(cfg["mo1_bragg"]) - yhor = l * np.cos(2.0 * (cfg["mo1_bragg"] + cfg["cm_pitch"])) - yver = yhor * np.tan(2.0 * cfg["cm_pitch"]) - - if cfg["mo1_mode"] == "Monochromatic": - beam_offset_mo1 = ( - l * np.sin(2.0 * (cfg["mo1_bragg"] + cfg["cm_pitch"])) - yver - ) # Resultat ist korrekt! - elif cfg["mo1_mode"] == "Pinkbeam": - beam_offset_mo1 = 0 - else: - raise ValueError("Monochromator mode not supported") - - def csc(a): - return 1 / np.sin(a) - - def cot(a): - return 1 / np.tan(a) - - # calculate height of center of first crystal surface - f = bl.mo1.rotOffset # rotation offset, mm - d = bl.mo1.heightOffset # xtal height offset, mm - c = d * csc(cfg["mo1_bragg"]) - f * cot(cfg["mo1_bragg"]) - - # Calculate height of center of rotation - b = np.sqrt( - d**2 * csc(cfg["mo1_bragg"]) ** 2 - - 2 * d * f * cot(cfg["mo1_bragg"]) * csc(cfg["mo1_bragg"]) - + f**2 * cot(cfg["mo1_bragg"]) ** 2 - + f**2 - ) - h = np.cos(np.pi / 2 - np.arctan(f / c) - cfg["mo1_bragg"] - 2 * cfg["cm_pitch"]) * b - h2 = ((bl.mo1.center[1] - bl.cm.center[1]) - np.sqrt(b**2 - h**2)) * np.tan( - 2 * cfg["cm_pitch"] - ) - height_mo1_real = ( - h + h2 - ) # per design, the height should not change if the pitch of the CM is not changed! - if cfg["mo1_mode"] == "Monochromatic": - pass - elif cfg["mo1_mode"] == "Pinkbeam": - height_mo1_real = ( - height_mo1_real - 13 - ) # Move down to let beam pass between both crystal without touching copper cooler - else: - raise ValueError("Monochromator mode not supported") - pos["mo1_try"] = {"value": height_mo1_real} - - # TRX, Crystal selection - if cfg["mo1_mode"] == "Monochromatic": - xtal = cfg["mo1_xtal"].translate( - str.maketrans("", "", "()") - ) # Remove brackets from xtal name to conform with parameters - if xtal in bl.mo1.xtal: - index = bl.mo1.xtal.index(xtal) - else: - raise ValueError(f"Requested xtal {xtal} not found in parameters!") - pos["mo1_trx"] = {"value": bl.mo1.xtalOffsetX[index]} - else: - pos["mo1_trx"] = {"value": 0} - - diag = bl.mo1.xtalGap[0] / np.sin(cfg["mo1_bragg"]) # Calculations for Mono - dz = diag * np.cos(2 * (cfg["cm_pitch"] + cfg["mo1_bragg"])) - - ## Slits 1 - d = bl.opSlits1.center[1] - bl.cm.center[1] - dz - sl1_beam_height = d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1 - pos["sl1_centery"] = {"value": sl1_beam_height} - pos["sl1_gapy"] = {"value": beam_vs} - - ## Beam Monitor 1 - d = bl.opBM1.center[1] - bl.cm.center[1] - dz - bm1_beam_height = d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1 - pos["bm1_try"] = {"value": bm1_beam_height} - - ## Focusing Mirror - p = bl.fm.center[1] - q = cfg["smpl"] - bl.fm.center[1] - f = (p * q) / (p + q) # focal length - - # Bender radius - if cfg["fm_qy"] is None: - radius = 2 * q / np.sin(cfg["fm_rotx"]) # ideal bending radius for focused beam - else: - radius = ( - 2 * cfg["fm_qy"] / np.sin(cfg["fm_rotx"]) - ) # ideal bending radius for unfocused beam - pos["fm_bnd_radius"] = {"value": radius * 1e-6} # Convert to km - - # Pitch - d = bl.fm.center[1] - bl.cm.center[1] - dz - fm_rotx = ( - 2 * cfg["cm_pitch"] - cfg["fm_rotx"] - ) # calculate pitch in absolute values (according to horizontal plane) - pos["fm_rotx"] = { - "value": -fm_rotx * 1e3 - } # invert and convert to mrad (same as EGU of rotx axis) - - if cfg["fm_stripe"] in ("Rh (toroid)", "Pt (toroid)"): - - # TRY - if cfg["fm_stripe"] == "Rh (toroid)": - r = bl.fm.r[0] - h_cyl = bl.fm.hToroid[0] - else: # PT toroid - r = bl.fm.r[1] - h_cyl = bl.fm.hToroid[1] - width_beam = 2 * bl.fm.center[1] * np.tan(cfg["h_acc"] * 1e-3) - alpha = np.arccos(1 - width_beam**2 / (2 * r**2)) - h = r - (r * np.cos(alpha / 2)) - fm_beam_height = (d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1) * cfg[ - "fm_gain_height" - ] - fm_height = (d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1 - h_cyl + h / 2) * cfg[ - "fm_gain_height" - ] - pos["fm_try"] = {"value": fm_height} - - # TRX - if cfg["fm_stripe"] == "Rh (toroid)": - x_cyl = -bl.fm.xToroid[0] - else: - x_cyl = -bl.fm.xToroid[1] - pos["fm_trx"] = {"value": x_cyl} - - elif cfg["fm_stripe"] in ("Rh (flat)", "Pt (flat)"): - - # TRY - fm_height = (d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1) * cfg["fm_gain_height"] - fm_beam_height = fm_height - pos["fm_try"] = {"value": fm_height} - - # TRX - if cfg["fm_stripe"] == "Rh (flat)": - x_flat = -bl.fm.xFlat[0] - else: - x_flat = -bl.fm.xFlat[1] - pos["fm_trx"] = {"value": x_flat} - - else: - raise ValueError("FM Stripe selection not valid") - - pos["fm_roty"] = {"value": 0} - pos["fm_rotz"] = {"value": 0} - - ## Slits 2 - if hasattr(bl, "opSlits2"): - d = bl.opSlits2.center[1] - bl.fm.center[1] - sl2_beam_height = fm_beam_height - d * np.tan( - -(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"]) - ) - pos["sl2_centery"] = {"value": sl2_beam_height} - pos["sl2_gapy"] = {"value": beam_vs} - - ## Beam Monitor 2 - d = bl.opBM2.center[1] - bl.fm.center[1] - bm2_beam_height = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - pos["bm2_try"] = {"value": bm2_beam_height} - - ## Optical Table - - if beamline == "x01da": - # TRY - d = bl.ehWindow.center[1] - bl.fm.center[1] - ot_height = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - pos["ot_try"] = {"value": ot_height} - - # Pitch - ot_pitch = -(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"]) - pos["ot_rotx"] = {"value": ot_pitch * 1e3} - - # TRZ ES1 - ot_es1_trz = cfg["smpl"] - pos["ot_es1_trz"] = {"value": ot_es1_trz} - - # ES0 exit window - pos["es0wi_try"] = { - "value": 5 - } # At 5mm, the middle of the window is 500 mm from the table (neutral position) - else: - # Exit window height - d = bl.ehWindow.center[1] - bl.fm.center[1] - es0wi_try = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - pos["es0wi_try"] = {"value": es0wi_try} - - # ES1 table height - d = bl.es1.center[1] - bl.fm.center[1] - es1_try = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - pos["es1_try"] = {"value": es1_try} - - # IC0 height - d = bl.es1ic0.center[1] - bl.fm.center[1] - es1ic0_try = ( - fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - es1_try - ) - pos["es1ic0_try"] = {"value": es1ic0_try} - - # IC1 height - d = bl.es1ic1.center[1] - bl.fm.center[1] - es1ic1_try = ( - fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - es1_try - ) - pos["es1ic1_try"] = {"value": es1ic1_try} - - # IC2 height - d = bl.es1ic2.center[1] - bl.fm.center[1] - es1ic2_try = ( - fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - es1_try - ) - pos["es1ic2_try"] = {"value": es1ic2_try} - - # ES2 table height - d = bl.es2.center[1] - bl.fm.center[1] - es2_try = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - pos["es2_try"] = {"value": es2_try} - - return pos diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin/__init__.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/__init__.py similarity index 100% rename from debye_bec/bec_ipython_client/plugins/digital_twin/__init__.py rename to debye_bec/bec_ipython_client/plugins/digital_twin_core/__init__.py diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin/beamline.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/beamline.py similarity index 100% rename from debye_bec/bec_ipython_client/plugins/digital_twin/beamline.py rename to debye_bec/bec_ipython_client/plugins/digital_twin_core/beamline.py diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py new file mode 100644 index 0000000..8acc1b5 --- /dev/null +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py @@ -0,0 +1,1119 @@ +import re +from pathlib import Path +from typing import Literal, cast + +import numpy as np +import yaml +from bec_lib import bec_logger +from scipy.interpolate import UnivariateSpline +from xrt.backends.raycing.physconsts import AVOGADRO, CHeVcm + +from . import parameters as bl +from .beamline import get_beamline_id +from .types import BeamlineId, ConfigDict, DataDict, SurfaceDict + +H = 6.62606957e-34 +E = 1.602176634e-19 +C = 299792458 +RE = 2.8179e-15 + +OFFSET_FILE_X01DA = Path(__file__).with_name("x01da_offsets.yaml") +OFFSET_FILE_X10DA = Path(__file__).with_name("x10da_offsets.yaml") + +logger = bec_logger.logger + +""" +The idea is to move the core logic of digital_twin to this file. Only keep the gui elements in the widget. +This way, the scheduler widget can access digital twin without loading the GUI (GUI is still needed for the item creation, but not the item execution) + Scheduler will extract assistant inputs (get_assistant_config) during item creation + Scheduler will use digital_twin.calculate_positons to calculate positions and digital_twin.move_all to move the motors +""" + + +class DigitalTwinCore: + + def __init__(self): + logger.info("This is the digital twin from the ipython client!") + self.beamline = get_beamline_id() + self.offset_file = Path() + match self.beamline: + case "x01da": + self.offset_file = OFFSET_FILE_X01DA + case "x10da": + self.offset_file = OFFSET_FILE_X10DA + self.offsets = {} + self.load_offsets() + + def move_with_config(self, config): + positions = self.calc_positions(self.beamline, config) + positions = self.apply_offsets(positions, nested_config=True) + logger.info(f"Would now move to these positions: {positions}") + + def load_offsets(self): + if self.offsets == {}: + logger.info("Load beamline offsets") + if not self.offset_file.exists(): + raise FileNotFoundError(f"Offset file not found: {self.offset_file}") + + with self.offset_file.open("r", encoding="utf-8") as f: + data = yaml.safe_load(f) + + if not isinstance(data, dict): + raise ValueError(f"Expected a YAML mapping, got {type(data).__name__}") + + self.offsets = data + else: + logger.info("Unload beamline offsets") + self.offsets = {} + + def apply_offsets(self, config, nested_config=False): + for axis, axis_data in config.items(): + if axis in self.offsets: + axis_offsets = self.offsets[axis] + if "modifier" in axis_offsets and "offset" in axis_offsets: + for idx, rng in enumerate(axis_offsets["modifier"]["range"]): + modifier_axis = axis_offsets["modifier"]["axis"] + modifier_value = ( + config[modifier_axis]["value"] + if nested_config + else config[modifier_axis] + ) + if rng[0] < modifier_value < rng[1]: + if nested_config: + axis_data["value"] += axis_offsets["offset"][idx] + else: + config[axis] += axis_offsets["offset"][idx] + break + elif "offset" in axis_offsets: + if nested_config: + axis_data["value"] += axis_offsets["offset"] + else: + config[axis] += axis_offsets["offset"] + return config + + def remove_offsets(self, config): + for axis, _ in config.items(): + if axis in self.offsets: + axis_offsets = self.offsets[axis] + if "modifier" in axis_offsets and "offset" in axis_offsets: + for idx, rng in enumerate(axis_offsets["modifier"]["range"]): + if rng[0] < config[axis_offsets["modifier"]["axis"]] < rng[1]: + config[axis] -= axis_offsets["offset"][idx] + break + elif "offset" in axis_offsets: + config[axis] -= axis_offsets["offset"] + return config + + @staticmethod + def calc_positions(beamline: BeamlineId, cfg: ConfigDict) -> dict[str, dict[str, float]]: + """ + Calculates the positions of axes based on a beamline config. + + Args: + cfg(ConfigDict): Dictionary with beamline config + + Returns: + dict[str, dict[str, float]]: Dictionary mapping device names to dictionaries + containing a "value" key with the corresponding float value (position). + """ + + pos = {} + + ## FE slits + trxr = -np.arctan(cfg["h_acc"]) * bl.feSlits.center1[1] + trxw = ( + (np.arctan(cfg["h_acc"]) * bl.feSlits.center1[1]) + / bl.feSlits.center1[1] + * bl.feSlits.center2[1] + ) + tryb = -np.arctan(cfg["v_acc"]) * bl.feSlits.center1[1] + tryt = ( + (np.arctan(cfg["v_acc"]) * bl.feSlits.center1[1]) + / bl.feSlits.center1[1] + * bl.feSlits.center2[1] + ) + + xgap = trxw - trxr + ygap = tryt - tryb + + pos["sldi_gapx"] = {"value": xgap} + pos["sldi_gapy"] = {"value": ygap} + + ## Collimating Mirror + obj_dist = bl.cm.center[1] # object distance + beam_vs = 2 * obj_dist * np.tan(cfg["v_acc"]) # vertical size of beam after CM + + # TRX + if cfg["cm_stripe"] in bl.cm.surface: + index = bl.cm.surface.index(cfg["cm_stripe"]) + else: + raise ValueError(f"Requested stripe {cfg['cm_stripe']} not found in parameters!") + cm_trx = -(bl.cm.limOptX[0][index] + bl.cm.limOptX[1][index]) / 2 + pos["cm_trx"] = {"value": cm_trx} + + # TRY + height = obj_dist * np.tan(cfg["v_acc"]) ** 2 * 1 / np.tan(cfg["cm_pitch"]) + pos["cm_try"] = {"value": height} + + # Pitch + pos["cm_rotx"] = { + "value": -cfg["cm_pitch"] * 1e3 + } # invert and convert to mrad (same as EGU of rotx axis) + + # Bending Radius + radius = ( + 2.0 * obj_dist / np.sin(cfg["cm_pitch"]) + ) # Elements of modern X-ray Physics, page 108 ff. + pos["cm_bnd_radius"] = {"value": radius * 1e-6} # Convert to km + + ## Monochromator + if cfg["mo1_mode"] == "Monochromatic": + # Add 2x CM pitch to the bragg angle + bragg = cfg["mo1_bragg"] + elif cfg["mo1_mode"] == "Pinkbeam": + # Align xtal surfaces parallel to beam + bragg = 0 + else: + raise ValueError("Monochromator mode not supported") + pos["mo1_bragg_angle"] = {"value": bragg / np.pi * 180} # Bragg angle in deg + + # TRY, Height + l = bl.mo1.xtalGap[0] / np.sin(cfg["mo1_bragg"]) + yhor = l * np.cos(2.0 * (cfg["mo1_bragg"] + cfg["cm_pitch"])) + yver = yhor * np.tan(2.0 * cfg["cm_pitch"]) + + if cfg["mo1_mode"] == "Monochromatic": + beam_offset_mo1 = ( + l * np.sin(2.0 * (cfg["mo1_bragg"] + cfg["cm_pitch"])) - yver + ) # Resultat ist korrekt! + elif cfg["mo1_mode"] == "Pinkbeam": + beam_offset_mo1 = 0 + else: + raise ValueError("Monochromator mode not supported") + + def csc(a): + return 1 / np.sin(a) + + def cot(a): + return 1 / np.tan(a) + + # calculate height of center of first crystal surface + f = bl.mo1.rotOffset # rotation offset, mm + d = bl.mo1.heightOffset # xtal height offset, mm + c = d * csc(cfg["mo1_bragg"]) - f * cot(cfg["mo1_bragg"]) + + # Calculate height of center of rotation + b = np.sqrt( + d**2 * csc(cfg["mo1_bragg"]) ** 2 + - 2 * d * f * cot(cfg["mo1_bragg"]) * csc(cfg["mo1_bragg"]) + + f**2 * cot(cfg["mo1_bragg"]) ** 2 + + f**2 + ) + h = np.cos(np.pi / 2 - np.arctan(f / c) - cfg["mo1_bragg"] - 2 * cfg["cm_pitch"]) * b + h2 = ((bl.mo1.center[1] - bl.cm.center[1]) - np.sqrt(b**2 - h**2)) * np.tan( + 2 * cfg["cm_pitch"] + ) + height_mo1_real = ( + h + h2 + ) # per design, the height should not change if the pitch of the CM is not changed! + if cfg["mo1_mode"] == "Monochromatic": + pass + elif cfg["mo1_mode"] == "Pinkbeam": + height_mo1_real = ( + height_mo1_real - 13 + ) # Move down to let beam pass between both crystal without touching copper cooler + else: + raise ValueError("Monochromator mode not supported") + pos["mo1_try"] = {"value": height_mo1_real} + + # TRX, Crystal selection + if cfg["mo1_mode"] == "Monochromatic": + xtal = cfg["mo1_xtal"].translate( + str.maketrans("", "", "()") + ) # Remove brackets from xtal name to conform with parameters + if xtal in bl.mo1.xtal: + index = bl.mo1.xtal.index(xtal) + else: + raise ValueError(f"Requested xtal {xtal} not found in parameters!") + pos["mo1_trx"] = {"value": bl.mo1.xtalOffsetX[index]} + else: + pos["mo1_trx"] = {"value": 0} + + diag = bl.mo1.xtalGap[0] / np.sin(cfg["mo1_bragg"]) # Calculations for Mono + dz = diag * np.cos(2 * (cfg["cm_pitch"] + cfg["mo1_bragg"])) + + ## Slits 1 + d = bl.opSlits1.center[1] - bl.cm.center[1] - dz + sl1_beam_height = d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1 + pos["sl1_centery"] = {"value": sl1_beam_height} + pos["sl1_gapy"] = {"value": beam_vs} + + ## Beam Monitor 1 + d = bl.opBM1.center[1] - bl.cm.center[1] - dz + bm1_beam_height = d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1 + pos["bm1_try"] = {"value": bm1_beam_height} + + ## Focusing Mirror + p = bl.fm.center[1] + q = cfg["smpl"] - bl.fm.center[1] + f = (p * q) / (p + q) # focal length + + # Bender radius + if cfg["fm_qy"] is None: + radius = 2 * q / np.sin(cfg["fm_rotx"]) # ideal bending radius for focused beam + else: + radius = ( + 2 * cfg["fm_qy"] / np.sin(cfg["fm_rotx"]) + ) # ideal bending radius for unfocused beam + pos["fm_bnd_radius"] = {"value": radius * 1e-6} # Convert to km + + # Pitch + d = bl.fm.center[1] - bl.cm.center[1] - dz + fm_rotx = ( + 2 * cfg["cm_pitch"] - cfg["fm_rotx"] + ) # calculate pitch in absolute values (according to horizontal plane) + pos["fm_rotx"] = { + "value": -fm_rotx * 1e3 + } # invert and convert to mrad (same as EGU of rotx axis) + + if cfg["fm_stripe"] in ("Rh (toroid)", "Pt (toroid)"): + + # TRY + if cfg["fm_stripe"] == "Rh (toroid)": + r = bl.fm.r[0] + h_cyl = bl.fm.hToroid[0] + else: # PT toroid + r = bl.fm.r[1] + h_cyl = bl.fm.hToroid[1] + width_beam = 2 * bl.fm.center[1] * np.tan(cfg["h_acc"] * 1e-3) + alpha = np.arccos(1 - width_beam**2 / (2 * r**2)) + h = r - (r * np.cos(alpha / 2)) + fm_beam_height = (d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1) * cfg[ + "fm_gain_height" + ] + fm_height = (d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1 - h_cyl + h / 2) * cfg[ + "fm_gain_height" + ] + pos["fm_try"] = {"value": fm_height} + + # TRX + if cfg["fm_stripe"] == "Rh (toroid)": + x_cyl = -bl.fm.xToroid[0] + else: + x_cyl = -bl.fm.xToroid[1] + pos["fm_trx"] = {"value": x_cyl} + + elif cfg["fm_stripe"] in ("Rh (flat)", "Pt (flat)"): + + # TRY + fm_height = (d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1) * cfg["fm_gain_height"] + fm_beam_height = fm_height + pos["fm_try"] = {"value": fm_height} + + # TRX + if cfg["fm_stripe"] == "Rh (flat)": + x_flat = -bl.fm.xFlat[0] + else: + x_flat = -bl.fm.xFlat[1] + pos["fm_trx"] = {"value": x_flat} + + else: + raise ValueError("FM Stripe selection not valid") + + pos["fm_roty"] = {"value": 0} + pos["fm_rotz"] = {"value": 0} + + ## Slits 2 + if hasattr(bl, "opSlits2"): + d = bl.opSlits2.center[1] - bl.fm.center[1] + sl2_beam_height = fm_beam_height - d * np.tan( + -(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"]) + ) + pos["sl2_centery"] = {"value": sl2_beam_height} + pos["sl2_gapy"] = {"value": beam_vs} + + ## Beam Monitor 2 + d = bl.opBM2.center[1] - bl.fm.center[1] + bm2_beam_height = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) + pos["bm2_try"] = {"value": bm2_beam_height} + + ## Optical Table + + if beamline == "x01da": + # TRY + d = bl.ehWindow.center[1] - bl.fm.center[1] + ot_height = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) + pos["ot_try"] = {"value": ot_height} + + # Pitch + ot_pitch = -(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"]) + pos["ot_rotx"] = {"value": ot_pitch * 1e3} + + # TRZ ES1 + ot_es1_trz = cfg["smpl"] + pos["ot_es1_trz"] = {"value": ot_es1_trz} + + # ES0 exit window + pos["es0wi_try"] = { + "value": 5 + } # At 5mm, the middle of the window is 500 mm from the table (neutral position) + else: + # Exit window height + d = bl.ehWindow.center[1] - bl.fm.center[1] + es0wi_try = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) + pos["es0wi_try"] = {"value": es0wi_try} + + # ES1 table height + d = bl.es1.center[1] - bl.fm.center[1] + es1_try = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) + pos["es1_try"] = {"value": es1_try} + + # IC0 height + d = bl.es1ic0.center[1] - bl.fm.center[1] + es1ic0_try = ( + fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - es1_try + ) + pos["es1ic0_try"] = {"value": es1ic0_try} + + # IC1 height + d = bl.es1ic1.center[1] - bl.fm.center[1] + es1ic1_try = ( + fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - es1_try + ) + pos["es1ic1_try"] = {"value": es1ic1_try} + + # IC2 height + d = bl.es1ic2.center[1] - bl.fm.center[1] + es1ic2_try = ( + fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - es1_try + ) + pos["es1ic2_try"] = {"value": es1ic2_try} + + # ES2 table height + d = bl.es2.center[1] - bl.fm.center[1] + es2_try = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) + pos["es2_try"] = {"value": es2_try} + + return pos + + @staticmethod + def sldi_gap_to_acc(sldi_gapx: float, sldi_gapy: float) -> tuple[float, float]: + """ + Calculate the slits acceptance based on the gap values + + Args: + sldi_gapx(float): GAPX value of the slits in mm + sldi_gapy(float): GAPY value of the slits in mm + + Returns: + tuple[float, float]: Horizontal and vertical acceptance in rad + """ + d1 = bl.feSlits.center1[1] + d2 = bl.feSlits.center2[1] + h_acc = np.tan(sldi_gapx / (d2 + d1)) + v_acc = np.tan(sldi_gapy / (d2 + d1)) + return h_acc, v_acc + + @staticmethod + def cm_trx_to_stripe(cm_trx: float) -> str | None: + """ + Based on the trx value of the collimating mirror, return + the correct stripe + + Args: + cm_trx(float): Collimating mirror trx value + + Returns + str | None: Stripe of the mirror, None if not found + """ + cm_stripe = None + for name, low, high in zip(bl.cm.surface, bl.cm.limOptX[0], bl.cm.limOptX[1]): + if low <= cm_trx <= high: + cm_stripe = name + return cm_stripe + + @staticmethod + def cm_stripe_to_trx(cm_stripe: str) -> float | None: + """ + Based on the stripe of the collimating mirror, return + the trx value + + Args: + cm_stripe(str): Stripe of the collimating mirror + + Returns: + float | None: TRX value of the stripe. None if not found + """ + for name, low, high in zip(bl.cm.surface, bl.cm.limOptX[0], bl.cm.limOptX[1]): + if cm_stripe == name: + return -(low + high) / 2 + return None + + @staticmethod + def fm_trx_to_stripe(fm_trx: float) -> str | None: + """ + Based on the trx value of the focusing mirror, return + the correct stripe + + Args: + fm_trx(float): focusing mirror trx value + + Returns + str | None: Stripe of the mirror, None if not found + """ + fm_stripe = None + if hasattr(bl.fm, "surfaceFlat"): + for name, low, high in zip( + bl.fm.surfaceFlat, bl.fm.limOptXFlat[1], bl.fm.limOptXFlat[0] + ): + if low <= fm_trx <= high: + fm_stripe = name + " (flat)" + for name, low, high in zip( + bl.fm.surfaceToroid, bl.fm.limOptXToroid[1], bl.fm.limOptXToroid[0] + ): + if low <= fm_trx <= high: + fm_stripe = name + " (toroid)" + return fm_stripe + + @staticmethod + def fm_stripe_to_trx(fm_stripe: str) -> float | None: + """ + Based on the stripe of the focusing mirror, return + the trx value + + Args: + fm_stripe(str): Stripe of the focusing mirror + + Returns: + float | None: TRX value of the stripe. None if not found + """ + if hasattr(bl.fm, "surfaceFlat"): + for name, low, high in zip( + bl.fm.surfaceFlat, bl.fm.limOptXFlat[1], bl.fm.limOptXFlat[0] + ): + if fm_stripe == name + " (flat)": + return (low + high) / 2 + for name, low, high in zip( + bl.fm.surfaceToroid, bl.fm.limOptXToroid[1], bl.fm.limOptXToroid[0] + ): + if fm_stripe == name + " (toroid)": + return -(low + high) / 2 + return None + + @staticmethod + def mo1_energy_resolution(xtal: Literal["Si111", "Si311"], energy: float) -> float: + """ + Calculate the energy resolution of the monochromator + + Args: + xtal(str): Xtal name. "Si111" or "Si311" + energy(float): Energy in eV + + Returns: + float: Energy resolution in eV + """ + index = bl.mo1.xtal.index(xtal) + crystal = bl.mo1.material1[index] + + dtheta = np.linspace(-30, 90, 601) + theta = crystal.get_Bragg_angle(energy) + dtheta * 1e-6 + refl = np.abs(crystal.get_amplitude(energy, np.sin(theta))[0]) ** 2 # single crystal + + refl2 = refl**2 # DCM with parallel crystals + + # FWHM of the DCM curve + spline = UnivariateSpline(dtheta, refl2 - refl2.max() / 2, s=0) + roots = cast(np.ndarray, spline.roots()) + r1, r2 = float(roots[0]), float(roots[1]) + fwhm_rad = (r2 - r1) * 1e-6 # µrad → rad + + # Energy resolution + theta_b = crystal.get_Bragg_angle(energy) + de_over_e = fwhm_rad / np.tan(theta_b) + de = de_over_e * energy + + # logger.info(f"DCM FWHM : {r2-r1:.2f} µrad") + # logger.info(f"ΔE/E : {dE_over_E:.2e}") + # logger.info(f"ΔE : {dE:.3f} eV at {E} eV") + + return de + + @staticmethod + def cm_reflectivity(cm_stripe: str, cm_pitch: float, energy: float) -> float: + """ + Calculate the reflectivity of the mirror stripe based + on the pitch and energy. + + Args: + cm_stripe(str): Mirror stripe + cm_pitch(float): Pitch of the mirror (beam incidence angle) + energy(float): Energy of the beam in eV + + Returns: + float: Reflectivity [0-1] + """ + if cm_stripe is None: + return np.nan + index = bl.cm.surface.index(cm_stripe) + rs, _ = bl.cm.material[index].get_amplitude(energy, np.sin(cm_pitch))[0:2] + refl = abs(rs) ** 2 + return refl + + @staticmethod + def fm_reflectivity(fm_stripe: str, fm_pitch: float, energy: float) -> float: + """ + Calculate the reflectivity of the mirror stripe based + on the pitch and energy. + + Args: + cm_stripe(str): Mirror stripe + cm_pitch(float): Pitch of the mirror (beam incidence angle) + energy(float): Energy of the beam in eV + + Returns: + float: Reflectivity [0-1] + """ + if fm_stripe is None: + return np.nan + if fm_stripe in ("Rh (toroid)", "Pt (toroid)"): + surface = bl.fm.surfaceToroid + material = bl.fm.materialToroid + stripe = re.sub(r"\s*\(.*?\)", "", fm_stripe).strip() + index = surface.index(stripe) + else: + surface = bl.fm.surfaceFlat + material = bl.fm.materialFlat + stripe = re.sub(r"\s*\(.*?\)", "", fm_stripe).strip() + index = surface.index(stripe) + rs, _ = material[index].get_amplitude(energy, np.sin(fm_pitch))[0:2] + refl = abs(rs) ** 2 + return refl + + @staticmethod + def mo1_bragg_angle( + mo_mode: Literal["Monochromatic", "Pinkbeam"], + d_spacing: float, + energy: float, + cm_pitch: float, + ) -> tuple[float, float]: + """ + Calculate the bragg angle of the monochromator. + Corrects for the collimating mirror pitch. + + Args: + mo_mode(str): Monochromator mode. "Monochromatic" or "Pinkbeam" + d_spacing(float): D-spacing of the crystal in Angstrom + energy(float): Energy of the beam in eV + cm_pitch(float): Pitch of collimating mirror in rad + + Returns: + tuple[float, float]: Bragg angle and corrected bragg angle + """ + wl = C * H / (E * energy) + val = wl / (2 * d_spacing * 1e-10) + bragg_angle = 0 + if val > -1 and val < 1: + bragg_angle = np.asin(val) + if mo_mode == "Monochromatic": + # Add 2x CM pitch to the bragg angle + bragg_angle_cor = (2 * cm_pitch) + bragg_angle + else: + # Align xtal surfaces parallel to beam + bragg_angle_cor = 2 * cm_pitch + return bragg_angle, bragg_angle_cor + + @staticmethod + def fm_ideal_pitch( + fm_focus: Literal["Defocused", "Focused", "Manual"], + fm_stripe: str, + smpl: float, + sldi_hacc: float | None = None, + sldi_vacc: float | None = None, + fm_focx: float | None = None, + fm_focy: float | None = None, + ) -> tuple[float, float | None]: + """ + Calculates the ideal pitch for the focusing mirror depending on the + focusing strategy. + If "Defocused" is chosed, sldi_hacc, sldi_vacc, fm_focx and fm_focy + must be provided. + + Args: + fm_focus(str): Focus strategy. "Defocused", "Focused" or "Manual + fm_stripe(str): Mirror stripe + smpl(float): Sample position in mm from source + sldi_hacc(float): Horizontal acceptance of frontend slits. Defaults to None + sldi_vacc(float): Vertical acceptance of frontend slits. Defaults to None + fm_focx(float): Requested horizontal spot size in mm. Defaults to None + fm_focy(float): Requested vertical spot size in mm. Defaults to None + + Returns: + tuple[float, float | None]: Pitch of mirror in rad, qy in mm + """ + + # logger.info("Calculate pitch and qy now...") + # logger.info(f"sldi_hacc: {sldi_hacc}") + # logger.info(f"sldi_vacc: {sldi_vacc}") + # logger.info(f"fm_stripe: {fm_stripe}") + # logger.info(f"smpl: {smpl}") + p_cm = bl.cm.center[1] # posCM + p = bl.fm.center[1] # posFM + q = smpl - bl.fm.center[1] # dist posFM to posEX + if fm_focus == "Defocused": + assert sldi_hacc is not None, "sldi_hacc must be provided for Defocused mode" + assert sldi_vacc is not None, "sldi_vacc must be provided for Defocused mode" + assert fm_focx is not None, "fm_focx must be provided for Defocused mode" + assert fm_focy is not None, "fm_focy must be provided for Defocused mode" + a = 2 * np.tan(sldi_hacc) * bl.fm.center[1] # Beam width at focusing mirror + # logger.info(f"a: {a}") + # logger.info(f"sldi_hacc: {sldi_hacc}") + # logger.info(f"bl.fm.center[1]: {bl.fm.center[1]}") + # logger.info(f"p: {p}") + # logger.info(f"q: {q}") + b = ( + 2 * np.tan(sldi_vacc) * bl.cm.center[1] + ) # Beam height at focusing mirror (collimated beam) + x = fm_focx + # logger.info(f"x: {x}") + x = 0.098821 * x**2 + 0.512344 * x # polynom to correct for spot size + # logger.info(f"x (corrected): {x}") + y = fm_focy + y = 3.183562 * y**2 + 1.258364 * y # polynom to correct for spot size + qx = q + x * p / a + qy = q + y * p_cm / b + f = (p * qx) / (p + qx) # focal length + # logger.info(f"qx: {qx}") + # logger.info(f"f: {f}") + else: # Calculate for focused beam on sample in "manual" and "focused" mode + qy = None + f = (p * q) / (p + q) # focal length + pitch = 0 + if "Rh" in fm_stripe: + pitch = np.arcsin(bl.fm.r[0] / (2 * f)) # ideal pitch for FM + if "Pt" in fm_stripe: + pitch = np.arcsin(bl.fm.r[1] / (2 * f)) # ideal pitch for FM + # logger.info(f"fm_pitch: {pitch}") + # logger.info(f"qy: {qy}") + return pitch, qy + + @staticmethod + def calc_beamsize( + sldi_hacc: float, + sldi_vacc: float, + fm_stripe: str, + fm_pitch: float, + fm_radius: float, + smpl: float, + ) -> tuple[float, float | None]: + """ + Calculate the resulting beamsize according to the input parameters + + Args: + sldi_hacc(float): Horizontal acceptance of frontend slits + sldi_vacc(float): Vertical acceptance of frontend slits + fm_stripe(str): Mirror stripe + fm_pitch(float): Focusing mirror pitch in rad + fm_radius(float): Focusing mirror bender radius in m + smpl(float): Sample position in mm from source + + Returns: + tuple[float, float | None]: horizontal spot size, vertical spot size, both in mm + """ + + # logger.info("Calculate beamsize now...") + # logger.info(f"sldi_hacc: {sldi_hacc}") + # logger.info(f"sldi_vacc: {sldi_vacc}") + # logger.info(f"fm_stripe: {fm_stripe}") + # logger.info(f"fm_pitch: {fm_pitch}") + # logger.info(f"fm_radius: {fm_radius}") + # logger.info(f"smpl: {smpl}") + p_cm = bl.cm.center[1] # posCM + p = bl.fm.center[1] # posFM + q = smpl - bl.fm.center[1] # dist posFM to posEX + qy = fm_radius * np.sin(fm_pitch) / 2 + a = 2 * np.tan(sldi_hacc) * bl.fm.center[1] # Beam width at focusing mirror + b = ( + 2 * np.tan(sldi_vacc) * bl.cm.center[1] + ) # Beam height at focusing mirror (collimated beam) + f = 0 + if "Rh" in fm_stripe: + f = bl.fm.r[0] / (2 * np.sin(fm_pitch)) + if "Pt" in fm_stripe: + f = bl.fm.r[1] / (2 * np.sin(fm_pitch)) + qx = p * f / (p - f) + x = a * (qx - q) / p + y = b * (qy - q) / p_cm + # Change this | to a plus if calculation is not correct + fm_focx = -4 * (64043 - 125000 * np.sqrt(0.26249637 + 0.395284 * x)) / 98821 + # Change this | to a plus if calculation is not correct + fm_focy = -1 * (314591 - 250000 * np.sqrt(1.58347995 + 12.734248 * y)) / 1591781 + # logger.info(f"f: {f}") + # logger.info(f"qx: {qx}") + # logger.info(f"qy: {qy}") + # logger.info(f"fm_focx: {fm_focx}") + # logger.info(f"fm_focy: {fm_focy}") + return fm_focx, fm_focy + + @staticmethod + def cm_critical_angle(cm_stripe: Literal["Si", "Pt", "Rh"], energy) -> float: + """ + Calculate the critical angle of the mirror stripe + + Args: + cm_stripe(str): Mirror stripe. "Si", "Pt" or "Rh" + energy(float): Energy in eV + + Returns: + float: Critical angle in rad + """ + if cm_stripe == "Si": + stripe = bl.stripeSi + elif cm_stripe == "Pt": + stripe = bl.stripePt + else: + stripe = bl.stripeRh + w = CHeVcm / 100 / energy # convert energy [eV] to wavelength [m] + f1 = stripe.elements[0].Z + np.real(stripe.elements[0].get_f1f2(energy)) + number_density = stripe.rho * 1e3 * AVOGADRO / (stripe.elements[0].mass / 1e3) + critical_angle = np.sqrt(number_density * RE * w**2 * f1 / np.pi) + return critical_angle + + @staticmethod + def mirror_surface_geometries( + mirror: Literal["cm", "fm_toroid", "fm_flat"], + ) -> dict[str, tuple[float, float, float, float]]: + """ + Return the mirror stripe geometries + + Args: + mirror(str): Mirror. "cm", "fm_toroid" or "fm_flat" + + Returns: + dict[str, tuple[float, float, float, float]]: Dictionary mapping surface + names to tuples of (x, y, width, height). + """ + if mirror == "cm": + surface = bl.cm.surface + lim_opt_x = bl.cm.limOptX + lim_opt_y = bl.cm.limOptY + elif mirror == "fm_toroid": + surface = bl.fm.surfaceToroid + lim_opt_x = bl.fm.limOptXToroid + lim_opt_y = bl.fm.limOptYToroid + elif mirror == "fm_flat": + surface = bl.fm.surfaceFlat + lim_opt_x = bl.fm.limOptXFlat + lim_opt_y = bl.fm.limOptYFlat + else: + raise ValueError(f"Requested mirror {mirror} not available!") + geom = {} + for sf, lx, hx, ly, hy in zip( + surface, lim_opt_x[0], lim_opt_x[1], lim_opt_y[0], lim_opt_y[1] + ): + geom[sf] = (lx, ly, hx - lx, hy - ly) + return geom + + @staticmethod + def mo_surface_geometries( + mo: Literal["mo1"], plane: Literal[0, 1] + ) -> dict[str, tuple[float, float, float, float]]: + """ + Return the monochromator xtal geometries + + Args: + mo(str): Monochromator. Only "mo1" implemented + plane(int): Surface of xtal. 0 and 1 (First and second) + + Returns: + dict[str, tuple[float, float, float, float]]: Dictionary mapping surface + names to tuples of (x, y, width, height). + """ + if mo == "mo1": + xtal = bl.mo1.xtal + xtal_width = bl.mo1.xtalWidth + xtal_offset_x = bl.mo1.xtalOffsetX + if plane == 0: + xtal_length = bl.mo1.xtalLength1 + else: + xtal_length = bl.mo1.xtalLength2 + else: + return {} + geom = {} + for sf, w, offx, length in zip(xtal, xtal_width, xtal_offset_x, xtal_length): + geom[sf] = (offx - w / 2, -length / 2, w, length) + return geom + + @staticmethod + def wall_geometries() -> list[list[float]]: + """ + Return the wall geometries + + Returns: + list[list[float]]: List of [x, y, width, height] geometry values for each wall. + """ + geom = [] + if not hasattr(bl, "walls"): + return geom + for i, _ in enumerate(bl.walls.start): + geom.append( + [ + bl.walls.start[i], + bl.walls.height[i][0], + bl.walls.end[i] - bl.walls.start[i], + bl.walls.height[i][1] - bl.walls.height[i][0], + ] + ) + return geom + + @staticmethod + def pipe_geometries() -> list[dict[str, np.ndarray]]: + """ + Return the wall geometries + + Returns: + list[dict[str, np.ndarray]]: List of dictionaries with keys "x" and "y", + each containing a numpy array of two float values representing + the start and end coordinates of the pipe top and bottom edges. + """ + pipes = [] + if not hasattr(bl, "vacuum_pipes"): + return pipes + for i, _ in enumerate(bl.vacuum_pipes.center): + top = bl.vacuum_pipes.center[i] + bl.vacuum_pipes.diameter[i] / 2 + bl.sourceHeight + bottom = bl.vacuum_pipes.center[i] - bl.vacuum_pipes.diameter[i] / 2 + bl.sourceHeight + pipes.append( + { + "x": np.array([bl.vacuum_pipes.start[i], bl.vacuum_pipes.end[i]]), + "y": np.array([top, top]), + } + ) + pipes.append( + { + "x": np.array([bl.vacuum_pipes.start[i], bl.vacuum_pipes.end[i]]), + "y": np.array([bottom, bottom]), + } + ) + return pipes + + @staticmethod + def table_to_smpl_pos(table: str) -> float: + """ + Return the sample position based on the table name. + + Args: + table (str): Table name, e.g. ES1 or ES2 + """ + + if table == bl.es1.name: + return bl.es1.center[1] + if table == bl.es2.name: + return bl.es2.center[1] + raise ValueError(f"Table {table} not found in beamline parameter file") + + @staticmethod + def calc_sideview(cfg: ConfigDict) -> DataDict: + """ + Calculates the sideview coordinates based on a beamline config. + + Args: + cfg(ConfigDict): Dictionary with beamline config + + Returns: + DataDict: Sideview data + """ + + beam: DataDict = {"x": [], "y": []} + + beam["x"] = [] + beam["y"] = [] + beam["x"].append(0) # Source + beam["y"].append(bl.sourceHeight) + beam["x"].append(bl.cm.center[1]) # CM + beam["y"].append(bl.sourceHeight) + if cfg["mo1_mode"] == "Monochromatic": + diag = bl.mo1.xtalGap[0] / np.sin(cfg["mo1_bragg"]) # Calculations for Mono + dy = diag * np.sin(2 * (cfg["cm_pitch"] + cfg["mo1_bragg"])) + dz = diag * np.cos(2 * (cfg["cm_pitch"] + cfg["mo1_bragg"])) + beam["x"].append(bl.mo1.center[1] - dz / 2) # Mono 1.1 + beam["y"].append( + bl.sourceHeight + + np.tan(2 * cfg["cm_pitch"]) * (bl.mo1.center[1] - dz / 2 - bl.cm.center[1]) + ) + beam["x"].append(bl.mo1.center[1] + dz / 2) # Mono 1.2 + beam["y"].append( + bl.sourceHeight + + np.tan(2 * cfg["cm_pitch"]) * (bl.mo1.center[1] - dz / 2 - bl.cm.center[1]) + + dy + ) + beam["x"].append(bl.fm.center[1]) # FM + beam["y"].append( + bl.sourceHeight + + np.tan(2 * cfg["cm_pitch"]) * (bl.fm.center[1] - bl.cm.center[1] - dz) + + dy + ) + beam["x"].append(cfg["smpl"]) # Experiment + beam["y"].append( + bl.sourceHeight + + np.tan(2 * cfg["cm_pitch"]) * (bl.fm.center[1] - bl.cm.center[1] - dz) + + dy + + np.tan(2 * (cfg["cm_pitch"] - cfg["fm_rotx"])) * (cfg["smpl"] - bl.fm.center[1]) + ) + elif cfg["mo1_mode"] == "Pinkbeam": + beam["x"].append(bl.fm.center[1]) # FM + beam["y"].append( + bl.sourceHeight + np.tan(2 * cfg["cm_pitch"]) * (bl.fm.center[1] - bl.cm.center[1]) + ) + beam["x"].append(cfg["smpl"]) # Experiment + beam["y"].append( + bl.sourceHeight + + np.tan(2 * cfg["cm_pitch"]) * (bl.fm.center[1] - bl.cm.center[1]) + + np.tan(2 * (cfg["cm_pitch"] - cfg["fm_rotx"])) * (cfg["smpl"] - bl.fm.center[1]) + ) + + return beam + + @staticmethod + def calc_surfaces(cfg: ConfigDict) -> SurfaceDict: + """ + Calculates the surface coordinates based on a beamline config. + + Args: + cfg(ConfigDict): Dictionary with beamline config + + Returns: + SurfaceDict: Surface data + """ + + out: SurfaceDict = { + "cm": {"x": [], "y": []}, + "mo1_1": {"x": [], "y": []}, + "mo1_2": {"x": [], "y": []}, + "fm": {"x": [], "y": []}, + } + + # Collimating mirror + l = 2 * bl.cm.center[1] * np.tan(cfg["v_acc"]) / np.sin(cfg["cm_pitch"]) + + w1 = 2 * (bl.cm.center[1] - l / 2) * np.tan(cfg["h_acc"]) + w2 = 2 * (bl.cm.center[1] + l / 2) * np.tan(cfg["h_acc"]) + + # index = bl.cm.surface.index(cfg["cm_stripe"]) + + cen = -cfg["cm_trx"] + + out["cm"]["x"] = [cen - w1 / 2, cen - w2 / 2, cen + w2 / 2, cen + w1 / 2] + out["cm"]["y"] = [-l / 2, l / 2, l / 2, -l / 2] + + # Monochromator + # calculate height of center of first crystal surface + c = bl.mo1.heightOffset * 1 / np.sin(cfg["mo1_bragg"]) - bl.mo1.rotOffset * 1 / np.tan( + cfg["mo1_bragg"] + ) + e = bl.mo1.xtalGap[0] / np.tan(cfg["mo1_bragg"]) - c + + xtal = cfg["mo1_xtal"].translate( + str.maketrans("", "", "()") + ) # Remove brackets from xtal name to conform with parameters + index = bl.mo1.xtal.index(xtal) + + xtal_pos = bl.mo1.xtalOffsetX[index] + xtal_length_1 = bl.mo1.xtalLength1[index] + xtal_length_2 = bl.mo1.xtalLength2[index] + + width_beam = 2 * bl.mo1.center[1] * np.tan(cfg["h_acc"]) + + height_beam = 2 * bl.cm.center[1] * np.tan(cfg["v_acc"]) + w = height_beam / np.sin(cfg["mo1_bragg"]) + + if cfg["mo1_mode"] == "Monochromatic": + out["mo1_1"]["x"] = [ + xtal_pos - width_beam / 2, + xtal_pos + width_beam / 2, + xtal_pos + width_beam / 2, + xtal_pos - width_beam / 2, + ] + out["mo1_1"]["y"] = [ + xtal_length_1 / 2 - c - w / 2, + xtal_length_1 / 2 - c - w / 2, + xtal_length_1 / 2 - c + w / 2, + xtal_length_1 / 2 - c + w / 2, + ] + out["mo1_2"]["x"] = [ + xtal_pos - width_beam / 2, + xtal_pos + width_beam / 2, + xtal_pos + width_beam / 2, + xtal_pos - width_beam / 2, + ] + out["mo1_2"]["y"] = [ + -xtal_length_2 / 2 + e - w / 2, + -xtal_length_2 / 2 + e - w / 2, + -xtal_length_2 / 2 + e + w / 2, + -xtal_length_2 / 2 + e + w / 2, + ] + else: # Pinkbeam + out["mo1_1"]["x"] = [] + out["mo1_1"]["y"] = [] + out["mo1_2"]["x"] = [] + out["mo1_2"]["y"] = [] + + if cfg["fm_stripe"] is None: + return out + # Focusing mirror + if cfg["fm_stripe"] in ("Rh (toroid)", "Pt (toroid)"): + surface = bl.fm.surfaceToroid + stripe = re.sub(r"\s*\(.*?\)", "", cfg["fm_stripe"]).strip() + index = surface.index(stripe) + r = bl.fm.r[index] + else: + surface = bl.fm.surfaceFlat + stripe = re.sub(r"\s*\(.*?\)", "", cfg["fm_stripe"]).strip() + index = surface.index(stripe) + r = bl.fm.r[index] + off = -cfg["fm_trx"] + + width_beam = 2 * bl.fm.center[1] * np.tan(cfg["h_acc"]) + + if cfg["fm_stripe"] in ("Rh (toroid)", "Pt (toroid)"): + + l = height_beam / np.sin(cfg["fm_rotx"]) + alpha = np.arccos(1 - width_beam**2 / (2 * r**2)) + h = r - (r * np.cos(alpha / 2)) + z = h / np.tan(cfg["fm_rotx"]) + + x = [off - width_beam / 2, off - width_beam / 2] + y = [l / 2 - z / 2, -l / 2 - z / 2] + + res = 20 + x_elipse = np.linspace(0, np.pi, res) + y_elipse = np.linspace(0, np.pi, res) + x_elipse = [-width_beam / 2 * np.cos(i) + off for i in x_elipse] + y_elipse = [width_beam * np.sin(i) * z / width_beam - l / 2 - z / 2 for i in y_elipse] + + x.extend(x_elipse) + y.extend(y_elipse) + + x.extend([off + width_beam / 2, off + width_beam / 2]) + y.extend([-l / 2 - z / 2, l / 2 - z / 2]) + + res = 50 + x_elipse = np.linspace(np.pi, 0, res) + y_elipse = np.linspace(np.pi, 0, res) + x_elipse = [-width_beam / 2 * np.cos(i) + off for i in x_elipse] + y_elipse = [width_beam * np.sin(i) * z / width_beam + l / 2 - z / 2 for i in y_elipse] + + x.extend(x_elipse) + y.extend(y_elipse) + + out["fm"]["x"] = x + out["fm"]["y"] = y + + else: # flat surface, no toroid + l = height_beam / np.sin(cfg["fm_rotx"]) + + w1 = 2 * (bl.fm.center[1] - l / 2) * np.tan(cfg["h_acc"]) + w2 = 2 * (bl.fm.center[1] + l / 2) * np.tan(cfg["h_acc"]) + + out["fm"]["x"] = [off - w1 / 2, off + w1 / 2, off + w2 / 2, off - w2 / 2] + out["fm"]["y"] = [-l / 2, -l / 2, l / 2, l / 2] + + return out diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin/types.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/types.py similarity index 100% rename from debye_bec/bec_ipython_client/plugins/digital_twin/types.py rename to debye_bec/bec_ipython_client/plugins/digital_twin_core/types.py diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin/x01da_offsets.yaml b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_offsets.yaml similarity index 100% rename from debye_bec/bec_ipython_client/plugins/digital_twin/x01da_offsets.yaml rename to debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_offsets.yaml diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin/x01da_parameters.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_parameters.py similarity index 100% rename from debye_bec/bec_ipython_client/plugins/digital_twin/x01da_parameters.py rename to debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_parameters.py diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin/x10da_offsets.yaml b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_offsets.yaml similarity index 100% rename from debye_bec/bec_ipython_client/plugins/digital_twin/x10da_offsets.yaml rename to debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_offsets.yaml diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin/x10da_parameters.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_parameters.py similarity index 96% rename from debye_bec/bec_ipython_client/plugins/digital_twin/x10da_parameters.py rename to debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_parameters.py index b7b40a5..c0bd4e0 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin/x10da_parameters.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_parameters.py @@ -1,296 +1,296 @@ -""" -X10DA / SuperXAS Beamline Parameters. -This file describes the parameter of each component of the SuperXAS beamline -to be used for raytracing and geometrical calculations. -""" - -from collections import namedtuple - -import numpy as np -import xrt.backends.raycing.materials as rm - -# XRT definitions -filterBeryl = rm.Material("Be", rho=1.85, kind="plate") # pyright: ignore[reportArgumentType] -filterDiamond = rm.Material("C", rho=3.52, kind="plate") # pyright: ignore[reportArgumentType] -filterGraphite = rm.Material("C", rho=2.266, kind="plate") # pyright: ignore[reportArgumentType] - -stripeSi = rm.Material("Si", rho=2.33) # pyright: ignore[reportArgumentType] -stripePt = rm.Material("Pt", rho=21.45) # pyright: ignore[reportArgumentType] -stripeRh = rm.Material("Rh", rho=12.41) # pyright: ignore[reportArgumentType] -stripeCr = rm.Material("Cr", rho=7.14) # pyright: ignore[reportArgumentType] -stripePyrex = rm.Material( - "Si", rho=2.20 -) # Use Si as bare element and the density of SiO2 # pyright: ignore[reportArgumentType] - -si111_1 = rm.CrystalSi(hkl=(1, 1, 1), tK=77) # first xtal surface -si311_1 = rm.CrystalSi(hkl=(3, 1, 1), tK=77) # first xtal surface -si333_1 = rm.CrystalSi(hkl=(3, 3, 3), tK=77) # first xtal surface -si511_1 = rm.CrystalSi(hkl=(5, 1, 1), tK=77) # first xtal surface -si111_2 = rm.CrystalSi(hkl=(1, 1, 1), tK=77) # second xtal surface -si311_2 = rm.CrystalSi(hkl=(3, 1, 1), tK=77) # second xtal surface -si333_2 = rm.CrystalSi(hkl=(3, 3, 3), tK=77) # second xtal surface -si511_2 = rm.CrystalSi(hkl=(5, 1, 1), tK=77) # second xtal surface - -filterDiamond = rm.Material("C", rho=3.52, kind="plate") # pyright: ignore[reportArgumentType] -filterBe = rm.Material("Be", rho=1.85, kind="plate") # pyright: ignore[reportArgumentType] -filterSi3N4 = rm.Material( - ["Si", "N"], quantities=[3, 4], rho=3.44, kind="plate" -) # pyright: ignore[reportArgumentType] -filterAl = rm.Material("Al", rho=2.69, kind="plate") # pyright: ignore[reportArgumentType] -filterGraphite = rm.Material("C", rho=2.266, kind="plate") # pyright: ignore[reportArgumentType] - -# General parameters -sourceHeight = 0 - -# Synchrotron -synchrotron = namedtuple( - "synchrotron", ["eE", "eI", "eEspread", "eEpsilonX", "eEpsilonZ", "betaX", "betaZ"] -) - -sls1 = synchrotron( - eE=2.4, eI=0.4, eEspread=0.878e-3, eEpsilonX=5.63, eEpsilonZ=0.007, betaX=0.45, betaZ=14.4 -) - -sls2 = synchrotron( - eE=2.7, eI=0.4, eEspread=1.147e-3, eEpsilonX=0.156, eEpsilonZ=0.01, betaX=0.18, betaZ=4.6 -) - -# Source -bendingMagnet = namedtuple("bendingMagnet", ["name", "center", "sync", "B0"]) - -sls1_14t = bendingMagnet(name="FE-BM-SLS1-1.4T", center=(0, 0, 0), sync=sls1, B0=1.4) - -sls2_21t = bendingMagnet(name="FE-BM-SLS2-2.1T", center=(0, 0, 0), sync=sls2, B0=2.1) - -sls2_35t = bendingMagnet(name="FE-BM-SLS2-3.5T", center=(0, 0, 0), sync=sls2, B0=3.5) - -sls2_50t = bendingMagnet(name="FE-BM-SLS2-5.0T", center=(0, 0, 0), sync=sls2, B0=5.0) - -# FE slits -fe_slits = namedtuple("slits", ["name", "center", "center1", "center2", "maxDivH", "maxDivV"]) - -feSlits = fe_slits( - name="FE-SLITS", - center=(0, 6117, sourceHeight), - center1=(0, 5038.4, sourceHeight), - center2=(0, 5282.9, sourceHeight), - maxDivH=1.8e-3, - maxDivV=0.8e-3, -) - -# Filters -filt = namedtuple( - "filt", ["name", "center", "pitch", "limPhysX", "limPhysY", "surface", "material", "thickness"] -) - -feWindow = filt( - name="FE-WINDOW", - center=(0.0, 6158, sourceHeight), - pitch=np.pi / 2, - limPhysX=(-6, 6), - limPhysY=(-3.0, 3.0), - surface="None", - material=filterDiamond, - thickness=0.1, -) -feWindow = feWindow._replace( - surface="CVD Diamond window {0:0.0f} $\\mu$m".format(feWindow.thickness * 1e3) -) - -feFilt = filt( - name="FE-FI", - center=(0.0, 6590, sourceHeight), - pitch=np.pi / 2, - limPhysX=(-15, 15), - limPhysY=(-10, 10), - surface="None", - material=filterGraphite, - thickness=0.25, -) -feFilt = feFilt._replace(surface="Graphite filter {0:0.0f} $\\mu$m".format(feFilt.thickness * 1e3)) - -# Collimating mirror -collimatingMirror = namedtuple( - "collimatingMirror", - [ - "name", - "center", - "surface", - "material", - "limPhysX", - "limPhysY", - "limOptX", - "limOptY", - "R", - "pitch", - "jack1", - "jack2", - "jack3", - "tx1", - "tx2", - ], -) - -cm = collimatingMirror( - name="FE-CM", - center=[0, 7560.8, sourceHeight], - surface=("Pt", "Si", "Rh"), - material=(stripePt, stripeSi, stripeRh), - limPhysX=(-30, 30), - limPhysY=(-600, 600), - limOptX=((-21, -0.5, 11), (-4, 9.5, 23)), - limOptY=((-500, -500, -500), (500, 500, 500)), - R=[3e6, 15e6], - pitch=[1.4e-3, 4.5e-3], - jack1=[0.0, 7210.0, 0.0], # Tripod X, Y, Z (global) - jack2=[-210.0, 8310.0, 0.0], - jack3=[210.0, 8310.0, 0.0], - tx1=[0.0, -575.5], # X-Stage 1 [x, y] (local) - tx2=[0.0, 575], -) # X-Stage 2 - -apertures = namedtuple("apertures", ["name", "center", "opening"]) - -fePS = apertures( - name="FE-PS", center=[0, 8760, sourceHeight], opening=[-39 / 2, 39 / 2, -10, 29] -) # left, right, bottom, top - -opWbBsBlock = apertures( - name="OP-WB-BS-BLOCK", center=[0.0, 13606 - 135, sourceHeight], opening=[-18.0, 18.0, 42, 76] -) # left, right, bottom, top - -opSlits1 = apertures( - name="OP-SLITS 1", center=[0, 14145 - 135, sourceHeight], opening=[-35 / 2, 35 / 2, 47.5, 82.5] -) - -# OP Beam Monitors -op_bm = namedtuple("op_bm", ["name", "center"]) - -opBM1 = op_bm(name="OP Beam Monitor 1", center=(0, 14525 - 135, sourceHeight)) - -opBM2 = op_bm(name="OP Beam Monitor 2", center=(0, 17161.6 - 135, sourceHeight)) - -# Monochromator -monochromator = namedtuple( - "monochromator", - [ - "name", - "center", - "xtal", - "material1", - "material2", - "xtalWidth", - "xtalOffsetX", - "xtalLength1", - "xtalLength2", - "xtalGap", - "rotOffset", - "heightOffset", - "braggLim", - "jack1", - "jack2", - "jack3", - "tx", - ], -) - -mo1 = monochromator( - name="OP-CCM1", - center=[0.0, 11670 - 135, sourceHeight], - xtal=("Si311", "Si111"), - material1=(si311_1, si111_1), - material2=(si311_2, si111_2), - xtalWidth=(20, 20), - xtalOffsetX=(19.2, -19.2), - xtalLength1=(60, 60), - xtalLength2=(60, 60), - xtalGap=(8, 8), - rotOffset=6, # not sure what it is - heightOffset=8.5, # not sure what it is - braggLim=[4, 35], - jack1=[0.0, 11350.0, 0.0], # Tripod not available! - jack2=[-400.0, 12350.0, 0.0], - jack3=[400.0, 12350.0, 0.0], - tx=0.0, -) # X-Stage [x] - -# Focusing mirror -focusingMirror = namedtuple( - "focusingMirror", - [ - "name", - "center", - "surfaceToroid", - "materialToroid", - "limPhysXToroid", - "limPhysYToroid", - "limOptXToroid", - "limOptYToroid", - "R", - "pitch", - "r", - "xToroid", - "hToroid", - "jack1", - "jack2", - "jack3", - "tx1", - "tx2", - ], -) - -OFFSET_TRX = 46.8735 - -fm = focusingMirror( - name="OP-FM", - center=[0.0, 15580 - 135, sourceHeight], - surfaceToroid=("Rh", "Pt"), - materialToroid=(stripeRh, stripePt), - limPhysXToroid=(-54.0, 54.0), - limPhysYToroid=(-565.0, 565.0), - limOptXToroid=( - (43.388 + OFFSET_TRX, -4.865 + OFFSET_TRX), - (4.865 + OFFSET_TRX, -40.882 + OFFSET_TRX), - ), - limOptYToroid=((-500.0, -500.0), (500.0, 500.0)), - R=[3e6, 15e6], - pitch=[1.4e-3, 4.5e-3], - r=[30, 20], - xToroid=[24.126 + OFFSET_TRX, -22 + OFFSET_TRX], # offset in local x - hToroid=[7.0, 11.3], # depth of the cylinder at x = xCylinder1 and x = xCylinder2. - jack1=[0.0, 14980.0, 0.0], - jack2=[-75.0, 16180.0, 0.0], - jack3=[75.0, 16180.0, 0.0], - tx1=[0.0, -575.0], # X-Stage 1 [x, y] - tx2=[0.0, 575.0], -) # X-Stage 2 [x, y] - -# Entry wall experimental hutch: 21593 mm from source (SLS2) - -# Exit window -ehWindow = filt( - name="EH-WINDOW", - center=(0.0, 22063, sourceHeight), - pitch=np.pi / 2, - limPhysX=(-10.0, 10.0), - limPhysY=(17.5, 92.5), - surface="None", - material=filterBe, - thickness=0.25, -) -ehWindow = ehWindow._replace( - surface="Beryllium window {0:0.0f} $\\mu$m".format(ehWindow.thickness * 1e3) -) - -# Sample -sample = namedtuple("sample", ["name", "center"]) - -es1 = sample(name="ES1", center=[0, 23823, sourceHeight]) -es2 = sample(name="ES2", center=[0, 25843, sourceHeight]) - -# Ionization chambers -ic = namedtuple("sample", ["name", "center"]) - -es1ic0 = ic(name="ES1 IC0", center=[0, 23633, sourceHeight]) -es1ic1 = ic(name="ES1 IC1", center=[0, 24383, sourceHeight]) -es1ic2 = ic(name="ES1 IC2", center=[0, 24723, sourceHeight]) +""" +X10DA / SuperXAS Beamline Parameters. +This file describes the parameter of each component of the SuperXAS beamline +to be used for raytracing and geometrical calculations. +""" + +from collections import namedtuple + +import numpy as np +import xrt.backends.raycing.materials as rm + +# XRT definitions +filterBeryl = rm.Material("Be", rho=1.85, kind="plate") # pyright: ignore[reportArgumentType] +filterDiamond = rm.Material("C", rho=3.52, kind="plate") # pyright: ignore[reportArgumentType] +filterGraphite = rm.Material("C", rho=2.266, kind="plate") # pyright: ignore[reportArgumentType] + +stripeSi = rm.Material("Si", rho=2.33) # pyright: ignore[reportArgumentType] +stripePt = rm.Material("Pt", rho=21.45) # pyright: ignore[reportArgumentType] +stripeRh = rm.Material("Rh", rho=12.41) # pyright: ignore[reportArgumentType] +stripeCr = rm.Material("Cr", rho=7.14) # pyright: ignore[reportArgumentType] +stripePyrex = rm.Material( + "Si", rho=2.20 +) # Use Si as bare element and the density of SiO2 # pyright: ignore[reportArgumentType] + +si111_1 = rm.CrystalSi(hkl=(1, 1, 1), tK=77) # first xtal surface +si311_1 = rm.CrystalSi(hkl=(3, 1, 1), tK=77) # first xtal surface +si333_1 = rm.CrystalSi(hkl=(3, 3, 3), tK=77) # first xtal surface +si511_1 = rm.CrystalSi(hkl=(5, 1, 1), tK=77) # first xtal surface +si111_2 = rm.CrystalSi(hkl=(1, 1, 1), tK=77) # second xtal surface +si311_2 = rm.CrystalSi(hkl=(3, 1, 1), tK=77) # second xtal surface +si333_2 = rm.CrystalSi(hkl=(3, 3, 3), tK=77) # second xtal surface +si511_2 = rm.CrystalSi(hkl=(5, 1, 1), tK=77) # second xtal surface + +filterDiamond = rm.Material("C", rho=3.52, kind="plate") # pyright: ignore[reportArgumentType] +filterBe = rm.Material("Be", rho=1.85, kind="plate") # pyright: ignore[reportArgumentType] +filterSi3N4 = rm.Material( + ["Si", "N"], quantities=[3, 4], rho=3.44, kind="plate" +) # pyright: ignore[reportArgumentType] +filterAl = rm.Material("Al", rho=2.69, kind="plate") # pyright: ignore[reportArgumentType] +filterGraphite = rm.Material("C", rho=2.266, kind="plate") # pyright: ignore[reportArgumentType] + +# General parameters +sourceHeight = 0 + +# Synchrotron +synchrotron = namedtuple( + "synchrotron", ["eE", "eI", "eEspread", "eEpsilonX", "eEpsilonZ", "betaX", "betaZ"] +) + +sls1 = synchrotron( + eE=2.4, eI=0.4, eEspread=0.878e-3, eEpsilonX=5.63, eEpsilonZ=0.007, betaX=0.45, betaZ=14.4 +) + +sls2 = synchrotron( + eE=2.7, eI=0.4, eEspread=1.147e-3, eEpsilonX=0.156, eEpsilonZ=0.01, betaX=0.18, betaZ=4.6 +) + +# Source +bendingMagnet = namedtuple("bendingMagnet", ["name", "center", "sync", "B0"]) + +sls1_14t = bendingMagnet(name="FE-BM-SLS1-1.4T", center=(0, 0, 0), sync=sls1, B0=1.4) + +sls2_21t = bendingMagnet(name="FE-BM-SLS2-2.1T", center=(0, 0, 0), sync=sls2, B0=2.1) + +sls2_35t = bendingMagnet(name="FE-BM-SLS2-3.5T", center=(0, 0, 0), sync=sls2, B0=3.5) + +sls2_50t = bendingMagnet(name="FE-BM-SLS2-5.0T", center=(0, 0, 0), sync=sls2, B0=5.0) + +# FE slits +fe_slits = namedtuple("slits", ["name", "center", "center1", "center2", "maxDivH", "maxDivV"]) + +feSlits = fe_slits( + name="FE-SLITS", + center=(0, 6117, sourceHeight), + center1=(0, 5038.4, sourceHeight), + center2=(0, 5282.9, sourceHeight), + maxDivH=1.8e-3, + maxDivV=0.8e-3, +) + +# Filters +filt = namedtuple( + "filt", ["name", "center", "pitch", "limPhysX", "limPhysY", "surface", "material", "thickness"] +) + +feWindow = filt( + name="FE-WINDOW", + center=(0.0, 6158, sourceHeight), + pitch=np.pi / 2, + limPhysX=(-6, 6), + limPhysY=(-3.0, 3.0), + surface="None", + material=filterDiamond, + thickness=0.1, +) +feWindow = feWindow._replace( + surface="CVD Diamond window {0:0.0f} $\\mu$m".format(feWindow.thickness * 1e3) +) + +feFilt = filt( + name="FE-FI", + center=(0.0, 6590, sourceHeight), + pitch=np.pi / 2, + limPhysX=(-15, 15), + limPhysY=(-10, 10), + surface="None", + material=filterGraphite, + thickness=0.25, +) +feFilt = feFilt._replace(surface="Graphite filter {0:0.0f} $\\mu$m".format(feFilt.thickness * 1e3)) + +# Collimating mirror +collimatingMirror = namedtuple( + "collimatingMirror", + [ + "name", + "center", + "surface", + "material", + "limPhysX", + "limPhysY", + "limOptX", + "limOptY", + "R", + "pitch", + "jack1", + "jack2", + "jack3", + "tx1", + "tx2", + ], +) + +cm = collimatingMirror( + name="FE-CM", + center=[0, 7560.8, sourceHeight], + surface=("Pt", "Si", "Rh"), + material=(stripePt, stripeSi, stripeRh), + limPhysX=(-30, 30), + limPhysY=(-600, 600), + limOptX=((-21, -0.5, 11), (-4, 9.5, 23)), + limOptY=((-500, -500, -500), (500, 500, 500)), + R=[3e6, 15e6], + pitch=[1.4e-3, 4.5e-3], + jack1=[0.0, 7210.0, 0.0], # Tripod X, Y, Z (global) + jack2=[-210.0, 8310.0, 0.0], + jack3=[210.0, 8310.0, 0.0], + tx1=[0.0, -575.5], # X-Stage 1 [x, y] (local) + tx2=[0.0, 575], +) # X-Stage 2 + +apertures = namedtuple("apertures", ["name", "center", "opening"]) + +fePS = apertures( + name="FE-PS", center=[0, 8760, sourceHeight], opening=[-39 / 2, 39 / 2, -10, 29] +) # left, right, bottom, top + +opWbBsBlock = apertures( + name="OP-WB-BS-BLOCK", center=[0.0, 13606 - 135, sourceHeight], opening=[-18.0, 18.0, 42, 76] +) # left, right, bottom, top + +opSlits1 = apertures( + name="OP-SLITS 1", center=[0, 14145 - 135, sourceHeight], opening=[-35 / 2, 35 / 2, 47.5, 82.5] +) + +# OP Beam Monitors +op_bm = namedtuple("op_bm", ["name", "center"]) + +opBM1 = op_bm(name="OP Beam Monitor 1", center=(0, 14525 - 135, sourceHeight)) + +opBM2 = op_bm(name="OP Beam Monitor 2", center=(0, 17161.6 - 135, sourceHeight)) + +# Monochromator +monochromator = namedtuple( + "monochromator", + [ + "name", + "center", + "xtal", + "material1", + "material2", + "xtalWidth", + "xtalOffsetX", + "xtalLength1", + "xtalLength2", + "xtalGap", + "rotOffset", + "heightOffset", + "braggLim", + "jack1", + "jack2", + "jack3", + "tx", + ], +) + +mo1 = monochromator( + name="OP-CCM1", + center=[0.0, 11670 - 135, sourceHeight], + xtal=("Si311", "Si111"), + material1=(si311_1, si111_1), + material2=(si311_2, si111_2), + xtalWidth=(20, 20), + xtalOffsetX=(19.2, -19.2), + xtalLength1=(60, 60), + xtalLength2=(60, 60), + xtalGap=(8, 8), + rotOffset=6, # not sure what it is + heightOffset=8.5, # not sure what it is + braggLim=[4, 35], + jack1=[0.0, 11350.0, 0.0], # Tripod not available! + jack2=[-400.0, 12350.0, 0.0], + jack3=[400.0, 12350.0, 0.0], + tx=0.0, +) # X-Stage [x] + +# Focusing mirror +focusingMirror = namedtuple( + "focusingMirror", + [ + "name", + "center", + "surfaceToroid", + "materialToroid", + "limPhysXToroid", + "limPhysYToroid", + "limOptXToroid", + "limOptYToroid", + "R", + "pitch", + "r", + "xToroid", + "hToroid", + "jack1", + "jack2", + "jack3", + "tx1", + "tx2", + ], +) + +OFFSET_TRX = 46.8735 + +fm = focusingMirror( + name="OP-FM", + center=[0.0, 15580 - 135, sourceHeight], + surfaceToroid=("Rh", "Pt"), + materialToroid=(stripeRh, stripePt), + limPhysXToroid=(-54.0, 54.0), + limPhysYToroid=(-565.0, 565.0), + limOptXToroid=( + (43.388 + OFFSET_TRX, -4.865 + OFFSET_TRX), + (4.865 + OFFSET_TRX, -40.882 + OFFSET_TRX), + ), + limOptYToroid=((-500.0, -500.0), (500.0, 500.0)), + R=[3e6, 15e6], + pitch=[1.4e-3, 4.5e-3], + r=[30, 20], + xToroid=[24.126 + OFFSET_TRX, -22 + OFFSET_TRX], # offset in local x + hToroid=[7.0, 11.3], # depth of the cylinder at x = xCylinder1 and x = xCylinder2. + jack1=[0.0, 14980.0, 0.0], + jack2=[-75.0, 16180.0, 0.0], + jack3=[75.0, 16180.0, 0.0], + tx1=[0.0, -575.0], # X-Stage 1 [x, y] + tx2=[0.0, 575.0], +) # X-Stage 2 [x, y] + +# Entry wall experimental hutch: 21593 mm from source (SLS2) + +# Exit window +ehWindow = filt( + name="EH-WINDOW", + center=(0.0, 22063, sourceHeight), + pitch=np.pi / 2, + limPhysX=(-10.0, 10.0), + limPhysY=(17.5, 92.5), + surface="None", + material=filterBe, + thickness=0.25, +) +ehWindow = ehWindow._replace( + surface="Beryllium window {0:0.0f} $\\mu$m".format(ehWindow.thickness * 1e3) +) + +# Sample +sample = namedtuple("sample", ["name", "center"]) + +es1 = sample(name="ES1", center=[0, 23823, sourceHeight]) +es2 = sample(name="ES2", center=[0, 25843, sourceHeight]) + +# Ionization chambers +ic = namedtuple("sample", ["name", "center"]) + +es1ic0 = ic(name="ES1 IC0", center=[0, 23633, sourceHeight]) +es1ic1 = ic(name="ES1 IC1", center=[0, 24383, sourceHeight]) +es1ic2 = ic(name="ES1 IC2", center=[0, 24723, sourceHeight]) diff --git a/debye_bec/bec_ipython_client/startup/post_startup.py b/debye_bec/bec_ipython_client/startup/post_startup.py index d1778bb..0fd9d82 100644 --- a/debye_bec/bec_ipython_client/startup/post_startup.py +++ b/debye_bec/bec_ipython_client/startup/post_startup.py @@ -41,7 +41,7 @@ logger = bec_logger.logger logger.info("Using the Debye startup script.") -from debye_bec.bec_ipython_client.plugins.digital_twin.digital_twin import DigitalTwinCore +from debye_bec.bec_ipython_client.plugins.digital_twin_core.digital_twin_core import DigitalTwinCore from debye_bec.bec_ipython_client.plugins.auto_gain import AutoGain digital_twin = DigitalTwinCore() diff --git a/debye_bec/bec_widgets/widgets/digital_twin/__init__.py b/debye_bec/bec_widgets/widgets/digital_twin/__init__.py index a42cb09..e69de29 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/__init__.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/__init__.py @@ -1,3 +0,0 @@ -from .beamline import get_parameters - -parameters = get_parameters() diff --git a/debye_bec/bec_widgets/widgets/digital_twin/calculations/__init__.py b/debye_bec/bec_widgets/widgets/digital_twin/calculations/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_sideview.py b/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_sideview.py deleted file mode 100644 index 135c76d..0000000 --- a/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_sideview.py +++ /dev/null @@ -1,70 +0,0 @@ -""" -Calculates the sideview coordinates based on a beamline config. -""" - -import numpy as np - -from .. import parameters as bl -from ..types import ConfigDict, DataDict - - -def calc_sideview(cfg: ConfigDict) -> DataDict: - """ - Calculates the sideview coordinates based on a beamline config. - - Args: - cfg(ConfigDict): Dictionary with beamline config - - Returns: - DataDict: Sideview data - """ - - beam: DataDict = {"x": [], "y": []} - - beam["x"] = [] - beam["y"] = [] - beam["x"].append(0) # Source - beam["y"].append(bl.sourceHeight) - beam["x"].append(bl.cm.center[1]) # CM - beam["y"].append(bl.sourceHeight) - if cfg["mo1_mode"] == "Monochromatic": - diag = bl.mo1.xtalGap[0] / np.sin(cfg["mo1_bragg"]) # Calculations for Mono - dy = diag * np.sin(2 * (cfg["cm_pitch"] + cfg["mo1_bragg"])) - dz = diag * np.cos(2 * (cfg["cm_pitch"] + cfg["mo1_bragg"])) - beam["x"].append(bl.mo1.center[1] - dz / 2) # Mono 1.1 - beam["y"].append( - bl.sourceHeight - + np.tan(2 * cfg["cm_pitch"]) * (bl.mo1.center[1] - dz / 2 - bl.cm.center[1]) - ) - beam["x"].append(bl.mo1.center[1] + dz / 2) # Mono 1.2 - beam["y"].append( - bl.sourceHeight - + np.tan(2 * cfg["cm_pitch"]) * (bl.mo1.center[1] - dz / 2 - bl.cm.center[1]) - + dy - ) - beam["x"].append(bl.fm.center[1]) # FM - beam["y"].append( - bl.sourceHeight - + np.tan(2 * cfg["cm_pitch"]) * (bl.fm.center[1] - bl.cm.center[1] - dz) - + dy - ) - beam["x"].append(cfg["smpl"]) # Experiment - beam["y"].append( - bl.sourceHeight - + np.tan(2 * cfg["cm_pitch"]) * (bl.fm.center[1] - bl.cm.center[1] - dz) - + dy - + np.tan(2 * (cfg["cm_pitch"] - cfg["fm_rotx"])) * (cfg["smpl"] - bl.fm.center[1]) - ) - elif cfg["mo1_mode"] == "Pinkbeam": - beam["x"].append(bl.fm.center[1]) # FM - beam["y"].append( - bl.sourceHeight + np.tan(2 * cfg["cm_pitch"]) * (bl.fm.center[1] - bl.cm.center[1]) - ) - beam["x"].append(cfg["smpl"]) # Experiment - beam["y"].append( - bl.sourceHeight - + np.tan(2 * cfg["cm_pitch"]) * (bl.fm.center[1] - bl.cm.center[1]) - + np.tan(2 * (cfg["cm_pitch"] - cfg["fm_rotx"])) * (cfg["smpl"] - bl.fm.center[1]) - ) - - return beam diff --git a/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_surfaces.py b/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_surfaces.py deleted file mode 100644 index 2ef4a59..0000000 --- a/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_surfaces.py +++ /dev/null @@ -1,159 +0,0 @@ -""" -Calculates the surface coordinates based on a beamline config. -""" - -import re - -import numpy as np -from bec_lib import bec_logger - -from .. import parameters as bl -from ..types import ConfigDict, SurfaceDict - -logger = bec_logger.logger - - -def calc_surfaces(cfg: ConfigDict) -> SurfaceDict: - """ - Calculates the surface coordinates based on a beamline config. - - Args: - cfg(ConfigDict): Dictionary with beamline config - - Returns: - SurfaceDict: Surface data - """ - - out: SurfaceDict = { - "cm": {"x": [], "y": []}, - "mo1_1": {"x": [], "y": []}, - "mo1_2": {"x": [], "y": []}, - "fm": {"x": [], "y": []}, - } - - # Collimating mirror - l = 2 * bl.cm.center[1] * np.tan(cfg["v_acc"]) / np.sin(cfg["cm_pitch"]) - - w1 = 2 * (bl.cm.center[1] - l / 2) * np.tan(cfg["h_acc"]) - w2 = 2 * (bl.cm.center[1] + l / 2) * np.tan(cfg["h_acc"]) - - # index = bl.cm.surface.index(cfg["cm_stripe"]) - - cen = -cfg["cm_trx"] - - out["cm"]["x"] = [cen - w1 / 2, cen - w2 / 2, cen + w2 / 2, cen + w1 / 2] - out["cm"]["y"] = [-l / 2, l / 2, l / 2, -l / 2] - - # Monochromator - # calculate height of center of first crystal surface - c = bl.mo1.heightOffset * 1 / np.sin(cfg["mo1_bragg"]) - bl.mo1.rotOffset * 1 / np.tan( - cfg["mo1_bragg"] - ) - e = bl.mo1.xtalGap[0] / np.tan(cfg["mo1_bragg"]) - c - - xtal = cfg["mo1_xtal"].translate( - str.maketrans("", "", "()") - ) # Remove brackets from xtal name to conform with parameters - index = bl.mo1.xtal.index(xtal) - - xtal_pos = bl.mo1.xtalOffsetX[index] - xtal_length_1 = bl.mo1.xtalLength1[index] - xtal_length_2 = bl.mo1.xtalLength2[index] - - width_beam = 2 * bl.mo1.center[1] * np.tan(cfg["h_acc"]) - - height_beam = 2 * bl.cm.center[1] * np.tan(cfg["v_acc"]) - w = height_beam / np.sin(cfg["mo1_bragg"]) - - if cfg["mo1_mode"] == "Monochromatic": - out["mo1_1"]["x"] = [ - xtal_pos - width_beam / 2, - xtal_pos + width_beam / 2, - xtal_pos + width_beam / 2, - xtal_pos - width_beam / 2, - ] - out["mo1_1"]["y"] = [ - xtal_length_1 / 2 - c - w / 2, - xtal_length_1 / 2 - c - w / 2, - xtal_length_1 / 2 - c + w / 2, - xtal_length_1 / 2 - c + w / 2, - ] - out["mo1_2"]["x"] = [ - xtal_pos - width_beam / 2, - xtal_pos + width_beam / 2, - xtal_pos + width_beam / 2, - xtal_pos - width_beam / 2, - ] - out["mo1_2"]["y"] = [ - -xtal_length_2 / 2 + e - w / 2, - -xtal_length_2 / 2 + e - w / 2, - -xtal_length_2 / 2 + e + w / 2, - -xtal_length_2 / 2 + e + w / 2, - ] - else: # Pinkbeam - out["mo1_1"]["x"] = [] - out["mo1_1"]["y"] = [] - out["mo1_2"]["x"] = [] - out["mo1_2"]["y"] = [] - - if cfg["fm_stripe"] is None: - return out - # Focusing mirror - if cfg["fm_stripe"] in ("Rh (toroid)", "Pt (toroid)"): - surface = bl.fm.surfaceToroid - stripe = re.sub(r"\s*\(.*?\)", "", cfg["fm_stripe"]).strip() - index = surface.index(stripe) - r = bl.fm.r[index] - else: - surface = bl.fm.surfaceFlat - stripe = re.sub(r"\s*\(.*?\)", "", cfg["fm_stripe"]).strip() - index = surface.index(stripe) - r = bl.fm.r[index] - off = -cfg["fm_trx"] - - width_beam = 2 * bl.fm.center[1] * np.tan(cfg["h_acc"]) - - if cfg["fm_stripe"] in ("Rh (toroid)", "Pt (toroid)"): - - l = height_beam / np.sin(cfg["fm_rotx"]) - alpha = np.arccos(1 - width_beam**2 / (2 * r**2)) - h = r - (r * np.cos(alpha / 2)) - z = h / np.tan(cfg["fm_rotx"]) - - x = [off - width_beam / 2, off - width_beam / 2] - y = [l / 2 - z / 2, -l / 2 - z / 2] - - res = 20 - x_elipse = np.linspace(0, np.pi, res) - y_elipse = np.linspace(0, np.pi, res) - x_elipse = [-width_beam / 2 * np.cos(i) + off for i in x_elipse] - y_elipse = [width_beam * np.sin(i) * z / width_beam - l / 2 - z / 2 for i in y_elipse] - - x.extend(x_elipse) - y.extend(y_elipse) - - x.extend([off + width_beam / 2, off + width_beam / 2]) - y.extend([-l / 2 - z / 2, l / 2 - z / 2]) - - res = 50 - x_elipse = np.linspace(np.pi, 0, res) - y_elipse = np.linspace(np.pi, 0, res) - x_elipse = [-width_beam / 2 * np.cos(i) + off for i in x_elipse] - y_elipse = [width_beam * np.sin(i) * z / width_beam + l / 2 - z / 2 for i in y_elipse] - - x.extend(x_elipse) - y.extend(y_elipse) - - out["fm"]["x"] = x - out["fm"]["y"] = y - - else: # flat surface, no toroid - l = height_beam / np.sin(cfg["fm_rotx"]) - - w1 = 2 * (bl.fm.center[1] - l / 2) * np.tan(cfg["h_acc"]) - w2 = 2 * (bl.fm.center[1] + l / 2) * np.tan(cfg["h_acc"]) - - out["fm"]["x"] = [off - w1 / 2, off + w1 / 2, off + w2 / 2, off - w2 / 2] - out["fm"]["y"] = [-l / 2, -l / 2, l / 2, l / 2] - - return out diff --git a/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_varia.py b/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_varia.py deleted file mode 100644 index 5c80afb..0000000 --- a/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_varia.py +++ /dev/null @@ -1,519 +0,0 @@ -""" -Various calculations for the digital twin -""" - -import re -from typing import Literal, cast - -import numpy as np -from bec_lib import bec_logger -from scipy.interpolate import UnivariateSpline -from xrt.backends.raycing.physconsts import AVOGADRO, CHeVcm - -from .. import parameters as bl - -logger = bec_logger.logger - -H = 6.62606957e-34 -E = 1.602176634e-19 -C = 299792458 -RE = 2.8179e-15 - - -def sldi_gap_to_acc(sldi_gapx: float, sldi_gapy: float) -> tuple[float, float]: - """ - Calculate the slits acceptance based on the gap values - - Args: - sldi_gapx(float): GAPX value of the slits in mm - sldi_gapy(float): GAPY value of the slits in mm - - Returns: - tuple[float, float]: Horizontal and vertical acceptance in rad - """ - d1 = bl.feSlits.center1[1] - d2 = bl.feSlits.center2[1] - h_acc = np.tan(sldi_gapx / (d2 + d1)) - v_acc = np.tan(sldi_gapy / (d2 + d1)) - return h_acc, v_acc - - -def cm_trx_to_stripe(cm_trx: float) -> str | None: - """ - Based on the trx value of the collimating mirror, return - the correct stripe - - Args: - cm_trx(float): Collimating mirror trx value - - Returns - str | None: Stripe of the mirror, None if not found - """ - cm_stripe = None - for name, low, high in zip(bl.cm.surface, bl.cm.limOptX[0], bl.cm.limOptX[1]): - if low <= cm_trx <= high: - cm_stripe = name - return cm_stripe - - -def cm_stripe_to_trx(cm_stripe: str) -> float | None: - """ - Based on the stripe of the collimating mirror, return - the trx value - - Args: - cm_stripe(str): Stripe of the collimating mirror - - Returns: - float | None: TRX value of the stripe. None if not found - """ - for name, low, high in zip(bl.cm.surface, bl.cm.limOptX[0], bl.cm.limOptX[1]): - if cm_stripe == name: - return -(low + high) / 2 - return None - - -def fm_trx_to_stripe(fm_trx: float) -> str | None: - """ - Based on the trx value of the focusing mirror, return - the correct stripe - - Args: - fm_trx(float): focusing mirror trx value - - Returns - str | None: Stripe of the mirror, None if not found - """ - fm_stripe = None - if hasattr(bl.fm, "surfaceFlat"): - for name, low, high in zip(bl.fm.surfaceFlat, bl.fm.limOptXFlat[1], bl.fm.limOptXFlat[0]): - if low <= fm_trx <= high: - fm_stripe = name + " (flat)" - for name, low, high in zip(bl.fm.surfaceToroid, bl.fm.limOptXToroid[1], bl.fm.limOptXToroid[0]): - if low <= fm_trx <= high: - fm_stripe = name + " (toroid)" - return fm_stripe - - -def fm_stripe_to_trx(fm_stripe: str) -> float | None: - """ - Based on the stripe of the focusing mirror, return - the trx value - - Args: - fm_stripe(str): Stripe of the focusing mirror - - Returns: - float | None: TRX value of the stripe. None if not found - """ - if hasattr(bl.fm, "surfaceFlat"): - for name, low, high in zip(bl.fm.surfaceFlat, bl.fm.limOptXFlat[1], bl.fm.limOptXFlat[0]): - if fm_stripe == name + " (flat)": - return (low + high) / 2 - for name, low, high in zip(bl.fm.surfaceToroid, bl.fm.limOptXToroid[1], bl.fm.limOptXToroid[0]): - if fm_stripe == name + " (toroid)": - return -(low + high) / 2 - return None - - -def mo1_energy_resolution(xtal: Literal["Si111", "Si311"], energy: float) -> float: - """ - Calculate the energy resolution of the monochromator - - Args: - xtal(str): Xtal name. "Si111" or "Si311" - energy(float): Energy in eV - - Returns: - float: Energy resolution in eV - """ - index = bl.mo1.xtal.index(xtal) - crystal = bl.mo1.material1[index] - - dtheta = np.linspace(-30, 90, 601) - theta = crystal.get_Bragg_angle(energy) + dtheta * 1e-6 - refl = np.abs(crystal.get_amplitude(energy, np.sin(theta))[0]) ** 2 # single crystal - - refl2 = refl**2 # DCM with parallel crystals - - # FWHM of the DCM curve - spline = UnivariateSpline(dtheta, refl2 - refl2.max() / 2, s=0) - roots = cast(np.ndarray, spline.roots()) - r1, r2 = float(roots[0]), float(roots[1]) - fwhm_rad = (r2 - r1) * 1e-6 # µrad → rad - - # Energy resolution - theta_b = crystal.get_Bragg_angle(energy) - de_over_e = fwhm_rad / np.tan(theta_b) - de = de_over_e * energy - - # logger.info(f"DCM FWHM : {r2-r1:.2f} µrad") - # logger.info(f"ΔE/E : {dE_over_E:.2e}") - # logger.info(f"ΔE : {dE:.3f} eV at {E} eV") - - return de - - -def cm_reflectivity(cm_stripe: str, cm_pitch: float, energy: float) -> float: - """ - Calculate the reflectivity of the mirror stripe based - on the pitch and energy. - - Args: - cm_stripe(str): Mirror stripe - cm_pitch(float): Pitch of the mirror (beam incidence angle) - energy(float): Energy of the beam in eV - - Returns: - float: Reflectivity [0-1] - """ - if cm_stripe is None: - return np.nan - index = bl.cm.surface.index(cm_stripe) - rs, _ = bl.cm.material[index].get_amplitude(energy, np.sin(cm_pitch))[0:2] - refl = abs(rs) ** 2 - return refl - - -def fm_reflectivity(fm_stripe: str, fm_pitch: float, energy: float) -> float: - """ - Calculate the reflectivity of the mirror stripe based - on the pitch and energy. - - Args: - cm_stripe(str): Mirror stripe - cm_pitch(float): Pitch of the mirror (beam incidence angle) - energy(float): Energy of the beam in eV - - Returns: - float: Reflectivity [0-1] - """ - if fm_stripe is None: - return np.nan - if fm_stripe in ("Rh (toroid)", "Pt (toroid)"): - surface = bl.fm.surfaceToroid - material = bl.fm.materialToroid - stripe = re.sub(r"\s*\(.*?\)", "", fm_stripe).strip() - index = surface.index(stripe) - else: - surface = bl.fm.surfaceFlat - material = bl.fm.materialFlat - stripe = re.sub(r"\s*\(.*?\)", "", fm_stripe).strip() - index = surface.index(stripe) - rs, _ = material[index].get_amplitude(energy, np.sin(fm_pitch))[0:2] - refl = abs(rs) ** 2 - return refl - - -def mo1_bragg_angle( - mo_mode: Literal["Monochromatic", "Pinkbeam"], d_spacing: float, energy: float, cm_pitch: float -) -> tuple[float, float]: - """ - Calculate the bragg angle of the monochromator. - Corrects for the collimating mirror pitch. - - Args: - mo_mode(str): Monochromator mode. "Monochromatic" or "Pinkbeam" - d_spacing(float): D-spacing of the crystal in Angstrom - energy(float): Energy of the beam in eV - cm_pitch(float): Pitch of collimating mirror in rad - - Returns: - tuple[float, float]: Bragg angle and corrected bragg angle - """ - wl = C * H / (E * energy) - val = wl / (2 * d_spacing * 1e-10) - bragg_angle = 0 - if val > -1 and val < 1: - bragg_angle = np.asin(val) - if mo_mode == "Monochromatic": - # Add 2x CM pitch to the bragg angle - bragg_angle_cor = (2 * cm_pitch) + bragg_angle - else: - # Align xtal surfaces parallel to beam - bragg_angle_cor = 2 * cm_pitch - return bragg_angle, bragg_angle_cor - - -def fm_ideal_pitch( - fm_focus: Literal["Defocused", "Focused", "Manual"], - fm_stripe: str, - smpl: float, - sldi_hacc: float | None = None, - sldi_vacc: float | None = None, - fm_focx: float | None = None, - fm_focy: float | None = None, -) -> tuple[float, float | None]: - """ - Calculates the ideal pitch for the focusing mirror depending on the - focusing strategy. - If "Defocused" is chosed, sldi_hacc, sldi_vacc, fm_focx and fm_focy - must be provided. - - Args: - fm_focus(str): Focus strategy. "Defocused", "Focused" or "Manual - fm_stripe(str): Mirror stripe - smpl(float): Sample position in mm from source - sldi_hacc(float): Horizontal acceptance of frontend slits. Defaults to None - sldi_vacc(float): Vertical acceptance of frontend slits. Defaults to None - fm_focx(float): Requested horizontal spot size in mm. Defaults to None - fm_focy(float): Requested vertical spot size in mm. Defaults to None - - Returns: - tuple[float, float | None]: Pitch of mirror in rad, qy in mm - """ - - # logger.info("Calculate pitch and qy now...") - # logger.info(f"sldi_hacc: {sldi_hacc}") - # logger.info(f"sldi_vacc: {sldi_vacc}") - # logger.info(f"fm_stripe: {fm_stripe}") - # logger.info(f"smpl: {smpl}") - p_cm = bl.cm.center[1] # posCM - p = bl.fm.center[1] # posFM - q = smpl - bl.fm.center[1] # dist posFM to posEX - if fm_focus == "Defocused": - assert sldi_hacc is not None, "sldi_hacc must be provided for Defocused mode" - assert sldi_vacc is not None, "sldi_vacc must be provided for Defocused mode" - assert fm_focx is not None, "fm_focx must be provided for Defocused mode" - assert fm_focy is not None, "fm_focy must be provided for Defocused mode" - a = 2 * np.tan(sldi_hacc) * bl.fm.center[1] # Beam width at focusing mirror - # logger.info(f"a: {a}") - # logger.info(f"sldi_hacc: {sldi_hacc}") - # logger.info(f"bl.fm.center[1]: {bl.fm.center[1]}") - # logger.info(f"p: {p}") - # logger.info(f"q: {q}") - b = ( - 2 * np.tan(sldi_vacc) * bl.cm.center[1] - ) # Beam height at focusing mirror (collimated beam) - x = fm_focx - # logger.info(f"x: {x}") - x = 0.098821 * x**2 + 0.512344 * x # polynom to correct for spot size - # logger.info(f"x (corrected): {x}") - y = fm_focy - y = 3.183562 * y**2 + 1.258364 * y # polynom to correct for spot size - qx = q + x * p / a - qy = q + y * p_cm / b - f = (p * qx) / (p + qx) # focal length - # logger.info(f"qx: {qx}") - # logger.info(f"f: {f}") - else: # Calculate for focused beam on sample in "manual" and "focused" mode - qy = None - f = (p * q) / (p + q) # focal length - pitch = 0 - if "Rh" in fm_stripe: - pitch = np.arcsin(bl.fm.r[0] / (2 * f)) # ideal pitch for FM - if "Pt" in fm_stripe: - pitch = np.arcsin(bl.fm.r[1] / (2 * f)) # ideal pitch for FM - # logger.info(f"fm_pitch: {pitch}") - # logger.info(f"qy: {qy}") - return pitch, qy - - -def calc_beamsize( - sldi_hacc: float, - sldi_vacc: float, - fm_stripe: str, - fm_pitch: float, - fm_radius: float, - smpl: float, -) -> tuple[float, float | None]: - """ - Calculate the resulting beamsize according to the input parameters - - Args: - sldi_hacc(float): Horizontal acceptance of frontend slits - sldi_vacc(float): Vertical acceptance of frontend slits - fm_stripe(str): Mirror stripe - fm_pitch(float): Focusing mirror pitch in rad - fm_radius(float): Focusing mirror bender radius in m - smpl(float): Sample position in mm from source - - Returns: - tuple[float, float | None]: horizontal spot size, vertical spot size, both in mm - """ - - # logger.info("Calculate beamsize now...") - # logger.info(f"sldi_hacc: {sldi_hacc}") - # logger.info(f"sldi_vacc: {sldi_vacc}") - # logger.info(f"fm_stripe: {fm_stripe}") - # logger.info(f"fm_pitch: {fm_pitch}") - # logger.info(f"fm_radius: {fm_radius}") - # logger.info(f"smpl: {smpl}") - p_cm = bl.cm.center[1] # posCM - p = bl.fm.center[1] # posFM - q = smpl - bl.fm.center[1] # dist posFM to posEX - qy = fm_radius * np.sin(fm_pitch) / 2 - a = 2 * np.tan(sldi_hacc) * bl.fm.center[1] # Beam width at focusing mirror - b = 2 * np.tan(sldi_vacc) * bl.cm.center[1] # Beam height at focusing mirror (collimated beam) - f = 0 - if "Rh" in fm_stripe: - f = bl.fm.r[0] / (2 * np.sin(fm_pitch)) - if "Pt" in fm_stripe: - f = bl.fm.r[1] / (2 * np.sin(fm_pitch)) - qx = p * f / (p - f) - x = a * (qx - q) / p - y = b * (qy - q) / p_cm - # Change this | to a plus if calculation is not correct - fm_focx = -4 * (64043 - 125000 * np.sqrt(0.26249637 + 0.395284 * x)) / 98821 - # Change this | to a plus if calculation is not correct - fm_focy = -1 * (314591 - 250000 * np.sqrt(1.58347995 + 12.734248 * y)) / 1591781 - # logger.info(f"f: {f}") - # logger.info(f"qx: {qx}") - # logger.info(f"qy: {qy}") - # logger.info(f"fm_focx: {fm_focx}") - # logger.info(f"fm_focy: {fm_focy}") - return fm_focx, fm_focy - - -def cm_critical_angle(cm_stripe: Literal["Si", "Pt", "Rh"], energy) -> float: - """ - Calculate the critical angle of the mirror stripe - - Args: - cm_stripe(str): Mirror stripe. "Si", "Pt" or "Rh" - energy(float): Energy in eV - - Returns: - float: Critical angle in rad - """ - if cm_stripe == "Si": - stripe = bl.stripeSi - elif cm_stripe == "Pt": - stripe = bl.stripePt - else: - stripe = bl.stripeRh - w = CHeVcm / 100 / energy # convert energy [eV] to wavelength [m] - f1 = stripe.elements[0].Z + np.real(stripe.elements[0].get_f1f2(energy)) - number_density = stripe.rho * 1e3 * AVOGADRO / (stripe.elements[0].mass / 1e3) - critical_angle = np.sqrt(number_density * RE * w**2 * f1 / np.pi) - return critical_angle - - -def mirror_surface_geometries( - mirror: Literal["cm", "fm_toroid", "fm_flat"], -) -> dict[str, tuple[float, float, float, float]]: - """ - Return the mirror stripe geometries - - Args: - mirror(str): Mirror. "cm", "fm_toroid" or "fm_flat" - - Returns: - dict[str, tuple[float, float, float, float]]: Dictionary mapping surface - names to tuples of (x, y, width, height). - """ - if mirror == "cm": - surface = bl.cm.surface - lim_opt_x = bl.cm.limOptX - lim_opt_y = bl.cm.limOptY - elif mirror == "fm_toroid": - surface = bl.fm.surfaceToroid - lim_opt_x = bl.fm.limOptXToroid - lim_opt_y = bl.fm.limOptYToroid - elif mirror == "fm_flat": - surface = bl.fm.surfaceFlat - lim_opt_x = bl.fm.limOptXFlat - lim_opt_y = bl.fm.limOptYFlat - else: - raise ValueError(f"Requested mirror {mirror} not available!") - geom = {} - for sf, lx, hx, ly, hy in zip(surface, lim_opt_x[0], lim_opt_x[1], lim_opt_y[0], lim_opt_y[1]): - geom[sf] = (lx, ly, hx - lx, hy - ly) - return geom - - -def mo_surface_geometries( - mo: Literal["mo1"], plane: Literal[0, 1] -) -> dict[str, tuple[float, float, float, float]]: - """ - Return the monochromator xtal geometries - - Args: - mo(str): Monochromator. Only "mo1" implemented - plane(int): Surface of xtal. 0 and 1 (First and second) - - Returns: - dict[str, tuple[float, float, float, float]]: Dictionary mapping surface - names to tuples of (x, y, width, height). - """ - if mo == "mo1": - xtal = bl.mo1.xtal - xtal_width = bl.mo1.xtalWidth - xtal_offset_x = bl.mo1.xtalOffsetX - if plane == 0: - xtal_length = bl.mo1.xtalLength1 - else: - xtal_length = bl.mo1.xtalLength2 - else: - return {} - geom = {} - for sf, w, offx, length in zip(xtal, xtal_width, xtal_offset_x, xtal_length): - geom[sf] = (offx - w / 2, -length / 2, w, length) - return geom - - -def wall_geometries() -> list[list[float]]: - """ - Return the wall geometries - - Returns: - list[list[float]]: List of [x, y, width, height] geometry values for each wall. - """ - geom = [] - if not hasattr(bl, "walls"): - return geom - for i, _ in enumerate(bl.walls.start): - geom.append( - [ - bl.walls.start[i], - bl.walls.height[i][0], - bl.walls.end[i] - bl.walls.start[i], - bl.walls.height[i][1] - bl.walls.height[i][0], - ] - ) - return geom - - -def pipe_geometries() -> list[dict[str, np.ndarray]]: - """ - Return the wall geometries - - Returns: - list[dict[str, np.ndarray]]: List of dictionaries with keys "x" and "y", - each containing a numpy array of two float values representing - the start and end coordinates of the pipe top and bottom edges. - """ - pipes = [] - if not hasattr(bl, "vacuum_pipes"): - return pipes - for i, _ in enumerate(bl.vacuum_pipes.center): - top = bl.vacuum_pipes.center[i] + bl.vacuum_pipes.diameter[i] / 2 + bl.sourceHeight - bottom = bl.vacuum_pipes.center[i] - bl.vacuum_pipes.diameter[i] / 2 + bl.sourceHeight - pipes.append( - { - "x": np.array([bl.vacuum_pipes.start[i], bl.vacuum_pipes.end[i]]), - "y": np.array([top, top]), - } - ) - pipes.append( - { - "x": np.array([bl.vacuum_pipes.start[i], bl.vacuum_pipes.end[i]]), - "y": np.array([bottom, bottom]), - } - ) - return pipes - - -def table_to_smpl_pos(table: str) -> float: - """ - Return the sample position based on the table name. - - Args: - table (str): Table name, e.g. ES1 or ES2 - """ - - if table == bl.es1.name: - return bl.es1.center[1] - if table == bl.es2.name: - return bl.es2.center[1] - raise ValueError(f"Table {table} not found in beamline parameter file") diff --git a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py index 3fb7ca7..2a01e02 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py @@ -34,32 +34,14 @@ from qtpy.QtWidgets import ( QWidget, ) -from ....bec_ipython_client.plugins.digital_twin.digital_twin import DigitalTwinCore +from ....bec_ipython_client.plugins.digital_twin_core.beamline import get_beamline_id +from ....bec_ipython_client.plugins.digital_twin_core.digital_twin_core import DigitalTwinCore +from ....bec_ipython_client.plugins.digital_twin_core.types import ConfigDict from ..edge_selector import EdgeSelector -from .beamline import get_beamline_id -from .calculations.calc_sideview import calc_sideview -from .calculations.calc_surfaces import calc_surfaces -from .calculations.calc_varia import ( - calc_beamsize, - cm_critical_angle, - cm_reflectivity, - cm_stripe_to_trx, - cm_trx_to_stripe, - fm_ideal_pitch, - fm_reflectivity, - fm_stripe_to_trx, - fm_trx_to_stripe, - mo1_bragg_angle, - mo1_energy_resolution, - sldi_gap_to_acc, - table_to_smpl_pos, -) -from .offsets import Offsets from .panels.input_panel import InputPanel from .panels.mover_panel import MoverPanel from .panels.plots import SideviewPlot, SurfacePlots from .panels.settings_panel import SettingsPanel -from .types import ConfigDict from .widgets.qt_widgets import ComboBox, InputNumberField logger = bec_logger.logger @@ -88,8 +70,6 @@ class DigitalTwin(BECWidget, QWidget): # Debugging, override beamline! # self.beamline = BeamlineId.X10DA - self.offsets = Offsets() - # Check if devices are all in config self.check_bec_config() self.bec_dispatcher.connect_slot( @@ -117,8 +97,8 @@ class DigitalTwin(BECWidget, QWidget): self.plot_layout = QVBoxLayout(self.plot_widget) self.plot_layout.setContentsMargins(4, 4, 4, 4) self.plot_layout.setSpacing(6) - self.sideview_plot = SideviewPlot() - self.surface_plots = SurfacePlots(self.beamline) + self.sideview_plot = SideviewPlot(self.core) + self.surface_plots = SurfacePlots(self.beamline, self.core) self.plot_layout.addWidget(self.sideview_plot, stretch=1) self.plot_layout.addWidget(self.surface_plots, stretch=1) self.plot_widget.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) @@ -393,9 +373,9 @@ class DigitalTwin(BECWidget, QWidget): fm_qy = self.qy cm_stripe = self.input.cm_stripe.currentText() - cm_trx = cm_stripe_to_trx(cm_stripe) + cm_trx = self.core.cm_stripe_to_trx(cm_stripe) fm_stripe = self.input.fm_stripe.currentText() - fm_trx = fm_stripe_to_trx(fm_stripe) + fm_trx = self.core.fm_stripe_to_trx(fm_stripe) assert cm_trx is not None, f"No cm_trx found for given stripe {cm_stripe}!" assert fm_trx is not None, f"No fm_trx found for given stripe {fm_stripe}!" @@ -405,7 +385,7 @@ class DigitalTwin(BECWidget, QWidget): smpl = self.input.smpl.value() case ComboBox(): table = self.input.smpl.currentText() - smpl = table_to_smpl_pos(table) + smpl = self.core.table_to_smpl_pos(table) config: ConfigDict = { "energy": self.input.energy.value(), @@ -427,7 +407,7 @@ class DigitalTwin(BECWidget, QWidget): # Apply offsets if apply_offset: - config = self.offsets.apply_offsets(config, nested_config=False) + config = self.core.apply_offsets(config, nested_config=False) # Convert to SI units! config["h_acc"] *= 1e-3 @@ -453,12 +433,12 @@ class DigitalTwin(BECWidget, QWidget): mo1_bragg = self.dev.mo1_bragg.read(cached=True) sldi_gapx = self.dev.sldi_gapx.read(cached=True)["sldi_gapx"]["value"] sldi_gapy = self.dev.sldi_gapy.read(cached=True)["sldi_gapy"]["value"] - h_acc, v_acc = sldi_gap_to_acc(sldi_gapx, sldi_gapy) + h_acc, v_acc = self.core.sldi_gap_to_acc(sldi_gapx, sldi_gapy) cm_trx = self.dev.cm_trx.read(cached=True)["cm_trx"]["value"] - cm_stripe = cm_trx_to_stripe(-cm_trx) + cm_stripe = self.core.cm_trx_to_stripe(-cm_trx) cm_pitch = self.dev.cm_rotx.read(cached=True)["cm_rotx"]["value"] fm_trx = self.dev.fm_trx.read(cached=True)["fm_trx"]["value"] - fm_stripe = fm_trx_to_stripe(-fm_trx) + fm_stripe = self.core.fm_trx_to_stripe(-fm_trx) fm_rotx = self.dev.fm_rotx.read(cached=True)["fm_rotx"]["value"] fm_rotx_real = 2 * cm_pitch - fm_rotx @@ -467,7 +447,7 @@ class DigitalTwin(BECWidget, QWidget): smpl = self.dev.ot_es1_trz.read(cached=True)["ot_es1_trz"]["value"] case ComboBox(): table = self.input.smpl.currentText() - smpl = table_to_smpl_pos(table) + smpl = self.core.table_to_smpl_pos(table) raw = { # Config in SI units! "energy": mo1_bragg["mo1_bragg"]["value"], @@ -576,13 +556,13 @@ class DigitalTwin(BECWidget, QWidget): pos["ot_es1_trz"] = self.dev.ot_es1_trz.read(cached=True)["ot_es1_trz"]["value"] # Removing offsets - pos = self.offsets.remove_offsets(pos) + pos = self.core.remove_offsets(pos) self.input.energy.set_number(self.dev.mo1_bragg.read(cached=True)["mo1_bragg"]["value"]) - h_acc, v_acc = sldi_gap_to_acc(pos["sldi_gapx"], pos["sldi_gapy"]) + h_acc, v_acc = self.core.sldi_gap_to_acc(pos["sldi_gapx"], pos["sldi_gapy"]) self.input.sldi_hacc.set_number(h_acc * 1e3) self.input.sldi_vacc.set_number(v_acc * 1e3) - self.input.cm_stripe.set_current_text(cm_trx_to_stripe(-pos["cm_trx"])) + self.input.cm_stripe.set_current_text(self.core.cm_trx_to_stripe(-pos["cm_trx"])) self.input.cm_pitch.set_number(pos["cm_rotx"]) if abs(pos["mo1_trx"]) > 5: mo1_mode = "Monochromatic" @@ -592,7 +572,7 @@ class DigitalTwin(BECWidget, QWidget): self.input.mo1_xtal.set_current_text( self.dev.mo1_bragg.read(cached=True)["mo1_bragg_crystal_current_xtal_string"]["value"] ) - fm_stripe = fm_trx_to_stripe(-pos["fm_trx"]) + fm_stripe = self.core.fm_trx_to_stripe(-pos["fm_trx"]) self.input.fm_stripe.set_current_text(fm_stripe) fm_rotx_real = 2 * pos["cm_rotx"] - pos["fm_rotx"] self.input.fm_rotx.set_number(fm_rotx_real) @@ -603,10 +583,10 @@ class DigitalTwin(BECWidget, QWidget): self.input.smpl.set_number(pos["ot_es1_trz"]) case ComboBox(): table = self.ask_table_selection(self.input.smpl.currentText()) - smpl = table_to_smpl_pos(table) + smpl = self.core.table_to_smpl_pos(table) self.input.smpl.set_current_text(table) - fm_focx, fm_focy = calc_beamsize( + fm_focx, fm_focy = self.core.calc_beamsize( h_acc, v_acc, fm_stripe, -fm_rotx_real * 1e-3, pos["fm_bnd_radius"] * 1e6, smpl ) if fm_focx < 0.08 and fm_focy < 0.08: @@ -665,8 +645,8 @@ class DigitalTwin(BECWidget, QWidget): Defaults to True """ - self.offsets.load_offsets() - if self.offsets.offsets != {}: + self.core.load_offsets() + if self.core.offsets != {}: # Offsets were loaded if recalculate: self.calc_assistant(identifier="init") @@ -700,7 +680,7 @@ class DigitalTwin(BECWidget, QWidget): intro_label.setWordWrap(True) layout.addWidget(intro_label) - file = QLabel(str(self.offsets.offset_file)) + file = QLabel(str(self.core.offset_file)) file.setWordWrap(True) font = QFont() font.setItalic(True) @@ -718,7 +698,7 @@ class DigitalTwin(BECWidget, QWidget): return super().represent_sequence(tag, sequence, flow_style=True) text_edit.setPlainText( - yaml.dump(self.offsets.offsets, Dumper=InlineListDumper, sort_keys=False) + yaml.dump(self.core.offsets, Dumper=InlineListDumper, sort_keys=False) ) layout.addWidget(text_edit) @@ -759,9 +739,9 @@ class DigitalTwin(BECWidget, QWidget): Updates the plots for the reality scene """ config = self.get_reality_config() - data = calc_sideview(config) + data = self.core.calc_sideview(config) self.sideview_plot.update_curves("reality", data=data) - surfaces = calc_surfaces(config) + surfaces = self.core.calc_surfaces(config) self.surface_plots.update_surfaces(scene="reality", data=surfaces) @SafeSlot() @@ -791,7 +771,7 @@ class DigitalTwin(BECWidget, QWidget): ) # Remove brackets from xtal name to conform with parameters xtal = cast(Literal["Si111", "Si311"], xtal) energy = self.input.energy.value() - self.input.mo1_eres.setValue(mo1_energy_resolution(xtal, energy)) + self.input.mo1_eres.setValue(self.core.mo1_energy_resolution(xtal, energy)) def calc_cm_reflectivity(self): """ @@ -800,9 +780,11 @@ class DigitalTwin(BECWidget, QWidget): cm_stripe = self.input.cm_stripe.currentText() cm_pitch = -self.input.cm_pitch.value() * 1e-3 energy = self.input.energy.value() - self.input.cm_refl.setValue(100 * cm_reflectivity(cm_stripe, cm_pitch, energy)) + self.input.cm_refl.setValue(100 * self.core.cm_reflectivity(cm_stripe, cm_pitch, energy)) self.input.cm_refl.setLabel(f"Reflectivity at \n{energy:.0f} eV") - self.input.cm_refl_harm.setValue(100 * cm_reflectivity(cm_stripe, cm_pitch, 3 * energy)) + self.input.cm_refl_harm.setValue( + 100 * self.core.cm_reflectivity(cm_stripe, cm_pitch, 3 * energy) + ) self.input.cm_refl_harm.setLabel(f"Reflectivity at \n{3*energy:.0f} eV") def calc_fm_reflectivity(self): @@ -816,9 +798,11 @@ class DigitalTwin(BECWidget, QWidget): else: fm_rotx = -self.input.fm_rotx_ideal.value() * 1e-3 energy = self.input.energy.value() - self.input.fm_refl.setValue(100 * fm_reflectivity(fm_stripe, fm_rotx, energy)) + self.input.fm_refl.setValue(100 * self.core.fm_reflectivity(fm_stripe, fm_rotx, energy)) self.input.fm_refl.setLabel(f"Reflectivity at \n{energy:.0f} eV") - self.input.fm_refl_harm.setValue(100 * fm_reflectivity(fm_stripe, fm_rotx, 3 * energy)) + self.input.fm_refl_harm.setValue( + 100 * self.core.fm_reflectivity(fm_stripe, fm_rotx, 3 * energy) + ) self.input.fm_refl_harm.setLabel(f"Reflectivity at \n{3*energy:.0f} eV") def calc_cm_fm_harm_suppr(self): @@ -838,14 +822,14 @@ class DigitalTwin(BECWidget, QWidget): Updates the sideview plot based on the assistant values """ config = self.get_assistant_config(apply_offset=True) - data = calc_sideview(config) + data = self.core.calc_sideview(config) self.sideview_plot.update_curves("assistant", data) def calc_assistant_surfaces(self): """ Updates the surface plot based on the assistant values """ - surfaces = calc_surfaces(self.get_assistant_config()) + surfaces = self.core.calc_surfaces(self.get_assistant_config()) self.surface_plots.update_surfaces(scene="assistant", data=surfaces) def calc_positions(self): @@ -908,7 +892,7 @@ class DigitalTwin(BECWidget, QWidget): cm_pitch = -self.dev.cm_rotx.read(cached=True)["cm_rotx"]["value"] * 1e-3 mo1_mode = cast(Literal["Monochromatic", "Pinkbeam"], self.input.mo1_mode.currentText()) energy = self.input.energy.value() - theta, _ = mo1_bragg_angle(mo1_mode, d_spacing, energy, cm_pitch) + theta, _ = self.core.mo1_bragg_angle(mo1_mode, d_spacing, energy, cm_pitch) self.bragg_angle = theta self.input.mo1_bragg_angle.setValue(theta / np.pi * 180) @@ -939,12 +923,12 @@ class DigitalTwin(BECWidget, QWidget): smpl = self.input.smpl.value() case ComboBox(): table = self.input.smpl.currentText() - smpl = table_to_smpl_pos(table) + smpl = self.core.table_to_smpl_pos(table) sldi_hacc = self.input.sldi_hacc.value() * 1e-3 sldi_vacc = self.input.sldi_vacc.value() * 1e-3 fm_focx = self.input.fm_focx.value() fm_focy = self.input.fm_focy.value() - fm_rotx, qy = fm_ideal_pitch( + fm_rotx, qy = self.core.fm_ideal_pitch( fm_focus, fm_stripe, smpl, sldi_hacc, sldi_vacc, fm_focx, fm_focy ) self.qy = qy @@ -956,7 +940,7 @@ class DigitalTwin(BECWidget, QWidget): """ cm_stripe = cast(Literal["Si", "Pt", "Rh"], self.input.cm_stripe.currentText()) energy = self.input.energy.value() - self.input.cm_pitch_critical.setValue(-cm_critical_angle(cm_stripe, energy) * 1e3) + self.input.cm_pitch_critical.setValue(-self.core.cm_critical_angle(cm_stripe, energy) * 1e3) if __name__ == "__main__": diff --git a/debye_bec/bec_widgets/widgets/digital_twin/offsets.py b/debye_bec/bec_widgets/widgets/digital_twin/offsets.py deleted file mode 100644 index e905afc..0000000 --- a/debye_bec/bec_widgets/widgets/digital_twin/offsets.py +++ /dev/null @@ -1,83 +0,0 @@ -""" -Offset class to load or unload offsets from a file -""" - -from pathlib import Path - -import yaml -from bec_lib import bec_logger - -from .beamline import get_beamline_id - -OFFSET_FILE_X01DA = Path(__file__).with_name("x01da_offsets.yaml") -OFFSET_FILE_X10DA = Path(__file__).with_name("x10da_offsets.yaml") - -logger = bec_logger.logger - - -class Offsets: - - def __init__(self, *arg, **kwargs): - self.beamline = get_beamline_id() - self.offset_file = Path() - match self.beamline: - case "x01da": - self.offset_file = OFFSET_FILE_X01DA - case "x10da": - self.offset_file = OFFSET_FILE_X10DA - self.offsets = {} - - def load_offsets(self): - if self.offsets == {}: - logger.info("Load beamline offsets") - if not self.offset_file.exists(): - raise FileNotFoundError(f"Offset file not found: {self.offset_file}") - - with self.offset_file.open("r", encoding="utf-8") as f: - data = yaml.safe_load(f) - - if not isinstance(data, dict): - raise ValueError(f"Expected a YAML mapping, got {type(data).__name__}") - - self.offsets = data - else: - logger.info("Unload beamline offsets") - self.offsets = {} - - def apply_offsets(self, config, nested_config=False): - for axis, axis_data in config.items(): - if axis in self.offsets: - axis_offsets = self.offsets[axis] - if "modifier" in axis_offsets and "offset" in axis_offsets: - for idx, rng in enumerate(axis_offsets["modifier"]["range"]): - modifier_axis = axis_offsets["modifier"]["axis"] - modifier_value = ( - config[modifier_axis]["value"] - if nested_config - else config[modifier_axis] - ) - if rng[0] < modifier_value < rng[1]: - if nested_config: - axis_data["value"] += axis_offsets["offset"][idx] - else: - config[axis] += axis_offsets["offset"][idx] - break - elif "offset" in axis_offsets: - if nested_config: - axis_data["value"] += axis_offsets["offset"] - else: - config[axis] += axis_offsets["offset"] - return config - - def remove_offsets(self, config): - for axis, _ in config.items(): - if axis in self.offsets: - axis_offsets = self.offsets[axis] - if "modifier" in axis_offsets and "offset" in axis_offsets: - for idx, rng in enumerate(axis_offsets["modifier"]["range"]): - if rng[0] < config[axis_offsets["modifier"]["axis"]] < rng[1]: - config[axis] -= axis_offsets["offset"][idx] - break - elif "offset" in axis_offsets: - config[axis] -= axis_offsets["offset"] - return config diff --git a/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py b/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py index 8bebec6..5c4cd1b 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py @@ -7,7 +7,7 @@ from typing import Union # pylint: disable=E0611 from qtpy.QtWidgets import QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget -from ..types import BeamlineId +from .....bec_ipython_client.plugins.digital_twin_core.types import BeamlineId from ..widgets.qt_widgets import ( Button, ComboBox, diff --git a/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py b/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py index 4b43a3d..148d0ef 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py @@ -7,7 +7,7 @@ from typing import Literal # pylint: disable=E0611 from qtpy.QtWidgets import QVBoxLayout, QWidget -from ..types import BeamlineId +from .....bec_ipython_client.plugins.digital_twin_core.types import BeamlineId from ..widgets.move_widget import AbsorberWidget, MoveWidget from ..widgets.qt_widgets import Group diff --git a/debye_bec/bec_widgets/widgets/digital_twin/panels/plots.py b/debye_bec/bec_widgets/widgets/digital_twin/panels/plots.py index b7d7131..0d8f383 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/panels/plots.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/panels/plots.py @@ -15,13 +15,11 @@ from qtpy.QtGui import QBrush, QColor # pylint: disable=E0611 from qtpy.QtWidgets import QApplication, QGraphicsRectItem, QHBoxLayout, QVBoxLayout, QWidget -from ..calculations.calc_varia import ( - mirror_surface_geometries, - mo_surface_geometries, - pipe_geometries, - wall_geometries, +from .....bec_ipython_client.plugins.digital_twin_core.types import ( + BeamlineId, + DataDict, + SurfaceDict, ) -from ..types import BeamlineId, DataDict, SurfaceDict from ..widgets.qt_widgets import Group logger = bec_logger.logger @@ -30,9 +28,10 @@ logger = bec_logger.logger class SurfacePlots(QWidget): """Plot widget with two curves and legend.""" - def __init__(self, beamline: BeamlineId, parent=None): + def __init__(self, beamline: BeamlineId, core, parent=None): super().__init__(parent=parent) self.beamline = beamline + self.core = core self._layout = QHBoxLayout(self) self._layout.setContentsMargins(4, 4, 4, 4) self._layout.setSpacing(6) @@ -169,15 +168,15 @@ class SurfacePlots(QWidget): for name, plot in self.plots.items(): if name == "cm": - plot_surface(plot["widget"], mirror_surface_geometries("cm")) + plot_surface(plot["widget"], self.core.mirror_surface_geometries("cm")) elif name == "mo1_1": - plot_surface(plot["widget"], mo_surface_geometries("mo1", 0)) + plot_surface(plot["widget"], self.core.mo_surface_geometries("mo1", 0)) elif name == "mo1_2": - plot_surface(plot["widget"], mo_surface_geometries("mo1", 1)) + plot_surface(plot["widget"], self.core.mo_surface_geometries("mo1", 1)) elif name == "fm": if self.beamline == "x01da": - plot_surface(plot["widget"], mirror_surface_geometries("fm_flat")) - plot_surface(plot["widget"], mirror_surface_geometries("fm_toroid")) + plot_surface(plot["widget"], self.core.mirror_surface_geometries("fm_flat")) + plot_surface(plot["widget"], self.core.mirror_surface_geometries("fm_toroid")) else: raise ValueError(f"Plot {name} not found!") for name, plot in self.plots.items(): @@ -203,8 +202,9 @@ class SurfacePlots(QWidget): class SideviewPlot(QWidget): """Plot widget with two curves and legend.""" - def __init__(self, parent=None): + def __init__(self, core, parent=None): super().__init__(parent=parent) + self.core = core self._layout = QVBoxLayout(self) self._layout.setContentsMargins(4, 4, 4, 4) self._layout.setSpacing(0) @@ -303,7 +303,7 @@ class SideviewPlot(QWidget): def plot_vacuum_pipes(self): """Plot vacuum pipes""" - pipes = pipe_geometries() + pipes = self.core.pipe_geometries() for pipe in pipes: self.pipes.append( self.plot_widget.plot( @@ -313,7 +313,7 @@ class SideviewPlot(QWidget): def plot_walls(self): """Plot walls""" - walls = wall_geometries() + walls = self.core.wall_geometries() for wall in walls: rect = QGraphicsRectItem(wall[0], wall[1], wall[2], wall[3]) rect.setBrush(QBrush(QColor(*self.color_impenetrable))) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/types.py b/debye_bec/bec_widgets/widgets/digital_twin/types.py deleted file mode 100644 index d5c0393..0000000 --- a/debye_bec/bec_widgets/widgets/digital_twin/types.py +++ /dev/null @@ -1,83 +0,0 @@ -"""Types used for the beamline config and for plotting data""" - -from enum import Enum -from typing import TypedDict - - -class BeamlineId(str, Enum): - """ - Identifier for supported beamlines. - """ - - X01DA = "x01da" - X10DA = "x10da" - - -class ConfigDict(TypedDict): - """ - Typed dictionary representing the beamline configuration. - - Attributes: - energy (float): Beam energy. - h_acc (float): Horizontal acceptance. - v_acc (float): Vertical acceptance. - cm_pitch (float): CM pitch angle. - cm_stripe (str): CM stripe name. - cm_trx (float): CM translation x. - mo1_mode (str): MO1 mode. - mo1_xtal (str): MO1 crystal. - mo1_bragg (float): MO1 Bragg angle. - fm_rotx (float): FM rotation x. - fm_stripe (str): FM stripe name. - fm_trx (float): FM translation x. - fm_qy (float): FM qy value. - fm_gain_height (int): FM gain height. - smpl (float): Sample value. - """ - - energy: float - h_acc: float - v_acc: float - cm_pitch: float - cm_stripe: str - cm_trx: float - mo1_mode: str - mo1_xtal: str - mo1_bragg: float - fm_rotx: float - fm_stripe: str - fm_trx: float - fm_qy: None | float - fm_gain_height: int - smpl: float - - -class DataDict(TypedDict): - """ - Typed dictionary representing plot data. - - Attributes: - x (list[float]): List of x-axis values. - y (list[float]): List of y-axis values. - """ - - x: list - y: list - - -class SurfaceDict(TypedDict): - """ - Typed dictionary representing the surfaces of a scene, - grouping plot data by surface type. - - Attributes: - cm (DataDict): Data for the cm surface. - mo1_1 (DataDict): Data for the mo1_1 surface. - mo1_2 (DataDict): Data for the mo1_2 surface. - fm (DataDict): Data for the fm surface. - """ - - cm: DataDict - mo1_1: DataDict - mo1_2: DataDict - fm: DataDict diff --git a/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py b/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py index 0aa6f24..6df4065 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py @@ -15,9 +15,10 @@ from qtpy.QtCore import QObject, QPropertyAnimation, Qt, QThread from qtpy.QtGui import QTransform from qtpy.QtWidgets import QApplication, QHBoxLayout, QLabel, QPushButton, QWidget +from .....bec_ipython_client.plugins.digital_twin_core.types import BeamlineId + # pylint: disable=E0402 from .....devices.absorber import STATUS as ABS_STATUS -from ..types import BeamlineId logger = bec_logger.logger diff --git a/debye_bec/bec_widgets/widgets/digital_twin/x01da_offsets.yaml b/debye_bec/bec_widgets/widgets/digital_twin/x01da_offsets.yaml deleted file mode 100644 index f475d96..0000000 --- a/debye_bec/bec_widgets/widgets/digital_twin/x01da_offsets.yaml +++ /dev/null @@ -1,50 +0,0 @@ -cm_try: - offset: 0.15 - -mo1_trx: - modifier: - axis: mo1_trx - range: [[-30, -0.1], [0.1, 30]] - offset: [-2.3, 1.31] - -mo1_try: - modifier: - axis: mo1_trx - range: [[-30, -0.1], [0.1, 30]] - offset: [-1.78, -1.78] - -sl1_centery: - offset: -1.2 - -fm_trx: - modifier: - axis: fm_trx - range: [[-66, -31], [-24, 7], [11, 31], [38, 66]] - offset: [-0.61, 0, 0, -0.16] - -fm_try: - modifier: - axis: fm_trx - range: [[-66, -31], [-24, 7], [11, 31], [38, 66]] - offset: [0.028, 0, 0, -0.45] - -fm_rotx: - modifier: - axis: fm_trx - range: [[-66, -31], [-24, 7], [11, 31], [38, 66]] - offset: [0.027, 0, 0, 0.045] - -fm_roty: - modifier: - axis: fm_trx - range: [[-66, -31], [-24, 7], [11, 31], [38, 66]] - offset: [-0.038, 0, 0, -0.053] - -sl2_centery: - offset: -0.7 - -ot_try: - offset: -0.49 - -ot_rotx: - offset: 0 \ No newline at end of file diff --git a/debye_bec/bec_widgets/widgets/digital_twin/x01da_parameters.py b/debye_bec/bec_widgets/widgets/digital_twin/x01da_parameters.py deleted file mode 100644 index 214cb7d..0000000 --- a/debye_bec/bec_widgets/widgets/digital_twin/x01da_parameters.py +++ /dev/null @@ -1,323 +0,0 @@ -""" -X01DA / Debye Beamline Parameters. -This file describes the parameter of each component of the Debye beamline -to be used for raytracing and geometrical calculations. -""" - -from collections import namedtuple - -import numpy as np -import xrt.backends.raycing.materials as rm - -# XRT definitions -filterBeryl = rm.Material("Be", rho=1.85, kind="plate") # pyright: ignore[reportArgumentType] -filterDiamond = rm.Material("C", rho=3.52, kind="plate") # pyright: ignore[reportArgumentType] -filterGraphite = rm.Material("C", rho=2.266, kind="plate") # pyright: ignore[reportArgumentType] - -stripeSi = rm.Material("Si", rho=2.33) # pyright: ignore[reportArgumentType] -stripePt = rm.Material("Pt", rho=21.45) # pyright: ignore[reportArgumentType] -stripeRh = rm.Material("Rh", rho=12.41) # pyright: ignore[reportArgumentType] -stripeCr = rm.Material("Cr", rho=7.14) # pyright: ignore[reportArgumentType] -stripePyrex = rm.Material( - "Si", rho=2.20 -) # Use Si as bare element and the density of SiO2 # pyright: ignore[reportArgumentType] - -si111_1 = rm.CrystalSi(hkl=(1, 1, 1), tK=77) # first xtal surface -si311_1 = rm.CrystalSi(hkl=(3, 1, 1), tK=77) # first xtal surface -si333_1 = rm.CrystalSi(hkl=(3, 3, 3), tK=77) # first xtal surface -si511_1 = rm.CrystalSi(hkl=(5, 1, 1), tK=77) # first xtal surface -si111_2 = rm.CrystalSi(hkl=(1, 1, 1), tK=77) # second xtal surface -si311_2 = rm.CrystalSi(hkl=(3, 1, 1), tK=77) # second xtal surface -si333_2 = rm.CrystalSi(hkl=(3, 3, 3), tK=77) # second xtal surface -si511_2 = rm.CrystalSi(hkl=(5, 1, 1), tK=77) # second xtal surface - -filterDiamond = rm.Material("C", rho=3.52, kind="plate") # pyright: ignore[reportArgumentType] -filterBe = rm.Material("Be", rho=1.85, kind="plate") # pyright: ignore[reportArgumentType] -filterSi3N4 = rm.Material( - ["Si", "N"], quantities=[3, 4], rho=3.44, kind="plate" -) # pyright: ignore[reportArgumentType] -filterAl = rm.Material("Al", rho=2.69, kind="plate") # pyright: ignore[reportArgumentType] -filterGraphite = rm.Material("C", rho=2.266, kind="plate") # pyright: ignore[reportArgumentType] - -# General parameters -sourceHeight = 0 - -# Synchrotron -synchrotron = namedtuple( - "synchrotron", ["eE", "eI", "eEspread", "eEpsilonX", "eEpsilonZ", "betaX", "betaZ"] -) - -sls1 = synchrotron( - eE=2.4, eI=0.4, eEspread=0.878e-3, eEpsilonX=5.63, eEpsilonZ=0.007, betaX=0.45, betaZ=14.4 -) - -sls2 = synchrotron( - eE=2.7, eI=0.4, eEspread=1.147e-3, eEpsilonX=0.156, eEpsilonZ=0.01, betaX=0.18, betaZ=4.6 -) - -# Source -bendingMagnet = namedtuple("bendingMagnet", ["name", "center", "sync", "B0"]) - -sls1_14t = bendingMagnet(name="FE-BM-SLS1-1.4T", center=(0, 0, 0), sync=sls1, B0=1.4) - -sls2_21t = bendingMagnet(name="FE-BM-SLS2-2.1T", center=(0, 0, 0), sync=sls2, B0=2.1) - -sls2_35t = bendingMagnet(name="FE-BM-SLS2-3.5T", center=(0, 0, 0), sync=sls2, B0=3.5) - -sls2_50t = bendingMagnet(name="FE-BM-SLS2-5.0T", center=(0, 0, 0), sync=sls2, B0=5.0) - -# FE slits -fe_slits = namedtuple("slits", ["name", "center", "center1", "center2", "maxDivH", "maxDivV"]) - -feSlits = fe_slits( - name="FE-SLITS", - center=(0, 6117, sourceHeight), - center1=(0, 5045, sourceHeight), - center2=(0, 5289.5, sourceHeight), - maxDivH=1.8e-3, - maxDivV=0.8e-3, -) - -# FE Window -filt = namedtuple( - "filt", ["name", "center", "pitch", "limPhysX", "limPhysY", "surface", "material", "thickness"] -) - -feWindow = filt( - name="FE-WINDOW", - center=(0.0, 7020, sourceHeight), - pitch=np.pi / 2, - limPhysX=(-6, 6), - limPhysY=(-3.0, 3.0), - surface="None", - material=filterDiamond, - thickness=0.1, -) -feWindow = feWindow._replace(surface=f"CVD Diamond window {feWindow.thickness*1e3:0.0f} $\\mu$m") - -# Collimating mirror -collimatingMirror = namedtuple( - "collimatingMirror", - [ - "name", - "center", - "surface", - "material", - "limPhysX", - "limPhysY", - "limOptX", - "limOptY", - "R", - "pitch", - "jack1", - "jack2", - "jack3", - "tx1", - "tx2", - ], -) - -cm = collimatingMirror( - name="FE-CM", - center=[0, 6890, sourceHeight], - surface=("Si", "Pt", "Rh"), - material=(stripeSi, stripePt, stripeRh), - limPhysX=(-34, 34), - limPhysY=(-600, 600), - limOptX=((-21, -7, 14), (-11, 11, 23)), - limOptY=((-500, -500, -500), (500, 500, 500)), - R=[3e6, 15e6], - pitch=[-5.0e-3, -0.0e-3], - jack1=[0.0, 7210.0, 0.0], # Tripod X, Y, Z (global) - jack2=[-210.0, 8310.0, 0.0], - jack3=[210.0, 8310.0, 0.0], - tx1=[0.0, -575.5], # X-Stage 1 [x, y] (local) - tx2=[0.0, 575], -) # X-Stage 2 - -apertures = namedtuple("apertures", ["name", "center", "opening"]) - -fePS = apertures( - name="FE-PS", center=[0, 8815, sourceHeight], opening=[-20.0, 20.0, -20.0 + 12.5, 20.0 + 12.5] -) # left, right, bottom, top - -opWbBsBlock = apertures( - name="OP-WB-BS-BLOCK", center=[0.0, 13860, sourceHeight], opening=[-18.0, 18.0, 25, 85.5] -) # left, right, bottom, top -# opening=[-18., 18., 42, 76], # X10DA - -# Monochromator -monochromator = namedtuple( - "monochromator", - [ - "name", - "center", - "xtal", - "material1", - "material2", - "xtalWidth", - "xtalOffsetX", - "xtalLength1", - "xtalLength2", - "xtalGap", - "rotOffset", - "heightOffset", - "braggLim", - "jack1", - "jack2", - "jack3", - "tx", - ], -) - -mo1 = monochromator( - name="OP-MO1", - center=[0.0, 11750, sourceHeight], - xtal=("Si311", "Si111"), - material1=(si311_1, si111_1), - material2=(si311_2, si111_2), - xtalWidth=(24, 24), - xtalOffsetX=(-21.2, 21.2), - xtalLength1=(55, 55), - xtalLength2=(105, 105), - xtalGap=(8, 8), - rotOffset=6, - heightOffset=8.5, - braggLim=[3.6, 33], - jack1=[0.0, 11350.0, 0.0], # Tripod maybe not available! - jack2=[-400.0, 12350.0, 0.0], - jack3=[400.0, 12350.0, 0.0], - tx=0.0, -) # X-Stage [x] - -mo2 = monochromator( - name="OP-CCM2", - center=[0.0, 13250, sourceHeight], - xtal=("Si311", "Si111"), - material1=(si311_1, si111_1), - material2=(si311_2, si111_2), - xtalWidth=(24, 24), - xtalOffsetX=(-21, 21), - xtalLength1=(55, 55), - xtalLength2=(105, 105), - xtalGap=(8, 8), - rotOffset=6, - heightOffset=8.5, - braggLim=[3.6, 33], - jack1=[0.0, 13350.0, 0.0], # Tripod maybe not available! - jack2=[-400.0, 14350.0, 0.0], - jack3=[400.0, 14350.0, 0.0], - tx=0.0, -) # X-Stage [x] - -# OP Slits -op_slits = namedtuple("op_slits", ["name", "center"]) - -opSlits1 = op_slits(name="OP-SLITS 1", center=(0, 14349.6, sourceHeight)) - -opSlits2 = op_slits(name="OP-SLITS 2", center=(0, 18134.8, sourceHeight)) - -# OP Beam Monitors -op_bm = namedtuple("op_bm", ["name", "center"]) - -opBM1 = op_bm(name="OP Beam Monitor 1", center=(0, 14599.6, sourceHeight)) - -opBM2 = op_bm(name="OP Beam Monitor 2", center=(0, 18384.8, sourceHeight)) - -# Focusing mirror -focusingMirror = namedtuple( - "focusingMirror", - [ - "name", - "center", - "surfaceToroid", - "materialToroid", - "surfaceFlat", - "materialFlat", - "limPhysXToroid", - "limPhysYToroid", - "limPhysXFlat", - "limPhysYFlat", - "limOptXToroid", - "limOptYToroid", - "limOptXFlat", - "limOptYFlat", - "R", - "pitch", - "r", - "xToroid", - "xFlat", - "hToroid", - "jack1", - "jack2", - "jack3", - "tx1", - "tx2", - ], -) - -fm = focusingMirror( - name="OP-FM", - center=[0.0, 15670, sourceHeight], # nominal height 58 mm above ring, SLS1! - surfaceToroid=("Rh", "Pt"), - materialToroid=(stripeRh, stripePt), - surfaceFlat=("Rh", "Pt"), - materialFlat=(stripeRh, stripePt), - limPhysXToroid=(-79.0, 79.0), - limPhysYToroid=(-575.0, 575.0), - limPhysXFlat=(-79.0, 79.0), - limPhysYFlat=(-575.0, 575.0), - limOptXToroid=((-38, 66), (-66, 31)), - limOptYToroid=((-500.0, -500.0), (500.0, 500.0)), - limOptXFlat=((-11.45, 23.55), (-30.45, -6.45)), - limOptYFlat=((-500.0, -500.0), (500.0, 500.0)), - R=[3e6, 15e6], - pitch=[-5.0e-3, 0e-3], - r=[35.510, 24.986], - xToroid=[-52, 48.5], # offset in local x - xFlat=[-20.95, 8.55], - hToroid=[2.88, 7.15], # depth of the cylinder at x = xCylinder1 and x = xCylinder2. - jack1=[-130.0, 15535 - 538.0, 0.0], - jack2=[130.0, 15535 + 538.0, 0.0], - jack3=[0.0, 15535 + 538.0, 0.0], - tx1=[0.0, -575.0], # X-Stage 1 [x, y] - tx2=[0.0, 575.0], -) # X-Stage 2 [x, y] - -# EH Window -ehWindow = filt( - name="EH-WINDOW", - center=(0.0, 19998.3, sourceHeight), - pitch=np.pi / 2, - limPhysX=(-20.0, 20.0), - limPhysY=(-4, 4), - surface="None", - material=filterSi3N4, - thickness=0.002, -) -ehWindow = ehWindow._replace(surface=f"Beryllium window {ehWindow.thickness*1e3:0.0f} $\\mu$m") - -# Sample -sample = namedtuple("sample", ["name", "center"]) - -smpl = sample(name="EH-SMPL", center=[0, 23365, sourceHeight]) - -smpl2 = sample(name="EH-SMPL2", center=[0, 27500, sourceHeight]) - -tables = {} - -# Vacuum pipes -# DN40CF ID = 35 mm oder 37 mm -# DN50CF ID = 47.5 mm -# DN63CF ID = 60.2 mm oder 66 mm -# DN100CF ID = 97.4 mm oder 104 mm -pipe = namedtuple("pipes", ["center", "diameter", "start", "end"]) -vacuum_pipes = pipe( - center=[27.5, (37.5 + 27.5) / 2, 37.5, 62.5, 72.5], - diameter=[97.4, 97.4, 97.4, 97.4, 97.4], - start=[10952.88, 11750 + 250, mo2.center[1] + 250, 14000, fm.center[1]], - end=[11750 - 250, mo2.center[1] - 250, 14000, fm.center[1], ehWindow.center[1]], -) - -Walls = namedtuple("walls", ["start", "end", "height"]) -walls = Walls(start=[13999.30], end=[13999 + 75.5 + 30], height=[[-20, 25]]) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/x10da_offsets.yaml b/debye_bec/bec_widgets/widgets/digital_twin/x10da_offsets.yaml deleted file mode 100644 index f0fe9a8..0000000 --- a/debye_bec/bec_widgets/widgets/digital_twin/x10da_offsets.yaml +++ /dev/null @@ -1,59 +0,0 @@ - -cm_try: - offset: -0.7 - -mo1_try: - offset: -31.42 - -mo1_trx: - modifier: - axis: mo1_trx - range: [[-30, -0.1], [0.1, 30]] - offset: [-4.3, 0] - -sl1_centery: - offset: -55.54 - -bm1_try: - offset: 52.22 - -fm_trx: - modifier: - axis: fm_trx - range: [[-100, -48], [-47, 0]] - offset: [-0.3, 0.52] - -fm_try: - modifier: - axis: fm_trx - range: [[-100, -48], [-47, 0]] - offset: [-42.56, -41.49] - -# pitch -fm_rotx: - modifier: - axis: fm_trx - range: [[-100, -48], [-47, 0]] - offset: [1.30, 1.049] - -# yaw -fm_roty: - modifier: - axis: fm_trx - range: [[-100, -48], [-47, 0]] - offset: [1.754, 1.924] - -bm2_try: - offset: -19 - -es0wi_try: - offset: -71.98 - -es1_try: - offset: -113.26 - -es1ic1_try: - offset: 10.39 - -es1ic2_try: - offset: 3.55 diff --git a/debye_bec/bec_widgets/widgets/digital_twin/x10da_parameters.py b/debye_bec/bec_widgets/widgets/digital_twin/x10da_parameters.py deleted file mode 100644 index b7b40a5..0000000 --- a/debye_bec/bec_widgets/widgets/digital_twin/x10da_parameters.py +++ /dev/null @@ -1,296 +0,0 @@ -""" -X10DA / SuperXAS Beamline Parameters. -This file describes the parameter of each component of the SuperXAS beamline -to be used for raytracing and geometrical calculations. -""" - -from collections import namedtuple - -import numpy as np -import xrt.backends.raycing.materials as rm - -# XRT definitions -filterBeryl = rm.Material("Be", rho=1.85, kind="plate") # pyright: ignore[reportArgumentType] -filterDiamond = rm.Material("C", rho=3.52, kind="plate") # pyright: ignore[reportArgumentType] -filterGraphite = rm.Material("C", rho=2.266, kind="plate") # pyright: ignore[reportArgumentType] - -stripeSi = rm.Material("Si", rho=2.33) # pyright: ignore[reportArgumentType] -stripePt = rm.Material("Pt", rho=21.45) # pyright: ignore[reportArgumentType] -stripeRh = rm.Material("Rh", rho=12.41) # pyright: ignore[reportArgumentType] -stripeCr = rm.Material("Cr", rho=7.14) # pyright: ignore[reportArgumentType] -stripePyrex = rm.Material( - "Si", rho=2.20 -) # Use Si as bare element and the density of SiO2 # pyright: ignore[reportArgumentType] - -si111_1 = rm.CrystalSi(hkl=(1, 1, 1), tK=77) # first xtal surface -si311_1 = rm.CrystalSi(hkl=(3, 1, 1), tK=77) # first xtal surface -si333_1 = rm.CrystalSi(hkl=(3, 3, 3), tK=77) # first xtal surface -si511_1 = rm.CrystalSi(hkl=(5, 1, 1), tK=77) # first xtal surface -si111_2 = rm.CrystalSi(hkl=(1, 1, 1), tK=77) # second xtal surface -si311_2 = rm.CrystalSi(hkl=(3, 1, 1), tK=77) # second xtal surface -si333_2 = rm.CrystalSi(hkl=(3, 3, 3), tK=77) # second xtal surface -si511_2 = rm.CrystalSi(hkl=(5, 1, 1), tK=77) # second xtal surface - -filterDiamond = rm.Material("C", rho=3.52, kind="plate") # pyright: ignore[reportArgumentType] -filterBe = rm.Material("Be", rho=1.85, kind="plate") # pyright: ignore[reportArgumentType] -filterSi3N4 = rm.Material( - ["Si", "N"], quantities=[3, 4], rho=3.44, kind="plate" -) # pyright: ignore[reportArgumentType] -filterAl = rm.Material("Al", rho=2.69, kind="plate") # pyright: ignore[reportArgumentType] -filterGraphite = rm.Material("C", rho=2.266, kind="plate") # pyright: ignore[reportArgumentType] - -# General parameters -sourceHeight = 0 - -# Synchrotron -synchrotron = namedtuple( - "synchrotron", ["eE", "eI", "eEspread", "eEpsilonX", "eEpsilonZ", "betaX", "betaZ"] -) - -sls1 = synchrotron( - eE=2.4, eI=0.4, eEspread=0.878e-3, eEpsilonX=5.63, eEpsilonZ=0.007, betaX=0.45, betaZ=14.4 -) - -sls2 = synchrotron( - eE=2.7, eI=0.4, eEspread=1.147e-3, eEpsilonX=0.156, eEpsilonZ=0.01, betaX=0.18, betaZ=4.6 -) - -# Source -bendingMagnet = namedtuple("bendingMagnet", ["name", "center", "sync", "B0"]) - -sls1_14t = bendingMagnet(name="FE-BM-SLS1-1.4T", center=(0, 0, 0), sync=sls1, B0=1.4) - -sls2_21t = bendingMagnet(name="FE-BM-SLS2-2.1T", center=(0, 0, 0), sync=sls2, B0=2.1) - -sls2_35t = bendingMagnet(name="FE-BM-SLS2-3.5T", center=(0, 0, 0), sync=sls2, B0=3.5) - -sls2_50t = bendingMagnet(name="FE-BM-SLS2-5.0T", center=(0, 0, 0), sync=sls2, B0=5.0) - -# FE slits -fe_slits = namedtuple("slits", ["name", "center", "center1", "center2", "maxDivH", "maxDivV"]) - -feSlits = fe_slits( - name="FE-SLITS", - center=(0, 6117, sourceHeight), - center1=(0, 5038.4, sourceHeight), - center2=(0, 5282.9, sourceHeight), - maxDivH=1.8e-3, - maxDivV=0.8e-3, -) - -# Filters -filt = namedtuple( - "filt", ["name", "center", "pitch", "limPhysX", "limPhysY", "surface", "material", "thickness"] -) - -feWindow = filt( - name="FE-WINDOW", - center=(0.0, 6158, sourceHeight), - pitch=np.pi / 2, - limPhysX=(-6, 6), - limPhysY=(-3.0, 3.0), - surface="None", - material=filterDiamond, - thickness=0.1, -) -feWindow = feWindow._replace( - surface="CVD Diamond window {0:0.0f} $\\mu$m".format(feWindow.thickness * 1e3) -) - -feFilt = filt( - name="FE-FI", - center=(0.0, 6590, sourceHeight), - pitch=np.pi / 2, - limPhysX=(-15, 15), - limPhysY=(-10, 10), - surface="None", - material=filterGraphite, - thickness=0.25, -) -feFilt = feFilt._replace(surface="Graphite filter {0:0.0f} $\\mu$m".format(feFilt.thickness * 1e3)) - -# Collimating mirror -collimatingMirror = namedtuple( - "collimatingMirror", - [ - "name", - "center", - "surface", - "material", - "limPhysX", - "limPhysY", - "limOptX", - "limOptY", - "R", - "pitch", - "jack1", - "jack2", - "jack3", - "tx1", - "tx2", - ], -) - -cm = collimatingMirror( - name="FE-CM", - center=[0, 7560.8, sourceHeight], - surface=("Pt", "Si", "Rh"), - material=(stripePt, stripeSi, stripeRh), - limPhysX=(-30, 30), - limPhysY=(-600, 600), - limOptX=((-21, -0.5, 11), (-4, 9.5, 23)), - limOptY=((-500, -500, -500), (500, 500, 500)), - R=[3e6, 15e6], - pitch=[1.4e-3, 4.5e-3], - jack1=[0.0, 7210.0, 0.0], # Tripod X, Y, Z (global) - jack2=[-210.0, 8310.0, 0.0], - jack3=[210.0, 8310.0, 0.0], - tx1=[0.0, -575.5], # X-Stage 1 [x, y] (local) - tx2=[0.0, 575], -) # X-Stage 2 - -apertures = namedtuple("apertures", ["name", "center", "opening"]) - -fePS = apertures( - name="FE-PS", center=[0, 8760, sourceHeight], opening=[-39 / 2, 39 / 2, -10, 29] -) # left, right, bottom, top - -opWbBsBlock = apertures( - name="OP-WB-BS-BLOCK", center=[0.0, 13606 - 135, sourceHeight], opening=[-18.0, 18.0, 42, 76] -) # left, right, bottom, top - -opSlits1 = apertures( - name="OP-SLITS 1", center=[0, 14145 - 135, sourceHeight], opening=[-35 / 2, 35 / 2, 47.5, 82.5] -) - -# OP Beam Monitors -op_bm = namedtuple("op_bm", ["name", "center"]) - -opBM1 = op_bm(name="OP Beam Monitor 1", center=(0, 14525 - 135, sourceHeight)) - -opBM2 = op_bm(name="OP Beam Monitor 2", center=(0, 17161.6 - 135, sourceHeight)) - -# Monochromator -monochromator = namedtuple( - "monochromator", - [ - "name", - "center", - "xtal", - "material1", - "material2", - "xtalWidth", - "xtalOffsetX", - "xtalLength1", - "xtalLength2", - "xtalGap", - "rotOffset", - "heightOffset", - "braggLim", - "jack1", - "jack2", - "jack3", - "tx", - ], -) - -mo1 = monochromator( - name="OP-CCM1", - center=[0.0, 11670 - 135, sourceHeight], - xtal=("Si311", "Si111"), - material1=(si311_1, si111_1), - material2=(si311_2, si111_2), - xtalWidth=(20, 20), - xtalOffsetX=(19.2, -19.2), - xtalLength1=(60, 60), - xtalLength2=(60, 60), - xtalGap=(8, 8), - rotOffset=6, # not sure what it is - heightOffset=8.5, # not sure what it is - braggLim=[4, 35], - jack1=[0.0, 11350.0, 0.0], # Tripod not available! - jack2=[-400.0, 12350.0, 0.0], - jack3=[400.0, 12350.0, 0.0], - tx=0.0, -) # X-Stage [x] - -# Focusing mirror -focusingMirror = namedtuple( - "focusingMirror", - [ - "name", - "center", - "surfaceToroid", - "materialToroid", - "limPhysXToroid", - "limPhysYToroid", - "limOptXToroid", - "limOptYToroid", - "R", - "pitch", - "r", - "xToroid", - "hToroid", - "jack1", - "jack2", - "jack3", - "tx1", - "tx2", - ], -) - -OFFSET_TRX = 46.8735 - -fm = focusingMirror( - name="OP-FM", - center=[0.0, 15580 - 135, sourceHeight], - surfaceToroid=("Rh", "Pt"), - materialToroid=(stripeRh, stripePt), - limPhysXToroid=(-54.0, 54.0), - limPhysYToroid=(-565.0, 565.0), - limOptXToroid=( - (43.388 + OFFSET_TRX, -4.865 + OFFSET_TRX), - (4.865 + OFFSET_TRX, -40.882 + OFFSET_TRX), - ), - limOptYToroid=((-500.0, -500.0), (500.0, 500.0)), - R=[3e6, 15e6], - pitch=[1.4e-3, 4.5e-3], - r=[30, 20], - xToroid=[24.126 + OFFSET_TRX, -22 + OFFSET_TRX], # offset in local x - hToroid=[7.0, 11.3], # depth of the cylinder at x = xCylinder1 and x = xCylinder2. - jack1=[0.0, 14980.0, 0.0], - jack2=[-75.0, 16180.0, 0.0], - jack3=[75.0, 16180.0, 0.0], - tx1=[0.0, -575.0], # X-Stage 1 [x, y] - tx2=[0.0, 575.0], -) # X-Stage 2 [x, y] - -# Entry wall experimental hutch: 21593 mm from source (SLS2) - -# Exit window -ehWindow = filt( - name="EH-WINDOW", - center=(0.0, 22063, sourceHeight), - pitch=np.pi / 2, - limPhysX=(-10.0, 10.0), - limPhysY=(17.5, 92.5), - surface="None", - material=filterBe, - thickness=0.25, -) -ehWindow = ehWindow._replace( - surface="Beryllium window {0:0.0f} $\\mu$m".format(ehWindow.thickness * 1e3) -) - -# Sample -sample = namedtuple("sample", ["name", "center"]) - -es1 = sample(name="ES1", center=[0, 23823, sourceHeight]) -es2 = sample(name="ES2", center=[0, 25843, sourceHeight]) - -# Ionization chambers -ic = namedtuple("sample", ["name", "center"]) - -es1ic0 = ic(name="ES1 IC0", center=[0, 23633, sourceHeight]) -es1ic1 = ic(name="ES1 IC1", center=[0, 24383, sourceHeight]) -es1ic2 = ic(name="ES1 IC2", center=[0, 24723, sourceHeight]) diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index 79d6bc3..02066bf 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -109,7 +109,7 @@ class ScheduleItemDialog(QDialog): self.beamline = beamline if self.beamline in ["x01da", "x10da"]: logger.info(f"Loading bl-specific modules for beamline {self.beamline}") - from ....bec_ipython_client.plugins.digital_twin.digital_twin import DigitalTwinCore + from ....bec_ipython_client.plugins.digital_twin_core.digital_twin_core import DigitalTwinCore from ..digital_twin.digital_twin import DigitalTwin from ..edge_selector import EdgeSelector from ..scan_control_xas.scan_control_xas import ScanControlXAS diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index b398d16..97e25a2 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -156,7 +156,7 @@ class Scheduler(BECWidget, QWidget): logger.info( 'Scheduler running at X01DA or X10DA, import and load digital twin and auto-gain' ) - from ....bec_ipython_client.plugins.digital_twin.digital_twin import DigitalTwinCore + from ....bec_ipython_client.plugins.digital_twin_core.digital_twin_core import DigitalTwinCore from ....bec_ipython_client.plugins.auto_gain import AutoGain self.digital_twin = DigitalTwinCore() self.auto_gain = AutoGain() From 578be60a2d5c2f65157e2a7c45d585dbaba9dad7 Mon Sep 17 00:00:00 2001 From: hitz_s Date: Wed, 9 Sep 2026 10:11:43 +0200 Subject: [PATCH 23/56] wip --- .../bec_ipython_client/plugins/auto_gain.py | 94 ++++-- .../digital_twin_core/digital_twin_core.py | 149 +++++++++- .../digital_twin_core/motion_worker.py | 269 ++++++++++++++++++ .../plugins/digital_twin_core/types.py | 8 +- .../widgets/digital_twin/digital_twin.py | 97 ++++--- .../digital_twin/panels/input_panel.py | 58 ++-- .../digital_twin/panels/mover_panel.py | 28 +- .../digital_twin/widgets/move_widget.py | 265 ++--------------- 8 files changed, 634 insertions(+), 334 deletions(-) create mode 100644 debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py diff --git a/debye_bec/bec_ipython_client/plugins/auto_gain.py b/debye_bec/bec_ipython_client/plugins/auto_gain.py index a5ccd5c..35b8d14 100644 --- a/debye_bec/bec_ipython_client/plugins/auto_gain.py +++ b/debye_bec/bec_ipython_client/plugins/auto_gain.py @@ -6,11 +6,12 @@ from bisect import bisect_right import xraydb from bec_lib import bec_logger +from ophyd_devices import CompareStatus from ...devices.absorber import STATUS as ABS_STATUS from ...devices.eh_shutter import STATUS as EH_PH_STATUS from ...devices.ionization_chambers.ionization_chamber_enums import AmplifierEnable -from ...devices.nidaq.nidaq_enums import NidaqState +from ...devices.nidaq.nidaq_enums import EpicsMode, NidaqState from ...devices.op_shutter import STATUS as OP_PH_STATUS logger = bec_logger.logger @@ -21,10 +22,12 @@ EMAX = 200 MIN_RING_CURRENT = 5 # Minimum ring current to use auto-gain NOMINAL_RING_CURRENT = 400 # Nominal ring current of SLS2 +TIMEOUT_PUT_PV = 5 # Timeout to set a PV + MONO_VELOCITY = 20 # Move velocity in deg/s -TIMEOUT_MONO_PV = 5 # Timeout to set a PV on the mono TIMEOUT_MONO_MOVE = 30 # Timeout to finish a movement on the mono +LINKED_CHANNELS = {"ic0", "ic1"} AVAILABLE_GAINS = [1e6, 1e7, 5e7, 1e8, 1e9] # ascending order MIN_SIGNAL = 0.05 # Minimum signal to count as valid signal FULL_SCALE_V = 10.0 # NIDAQ AI full-scale range @@ -58,6 +61,10 @@ class AutoGain: """Start the auto-gain sequence. Measure the signals of the specified amplifiers and set the gains accordingly. Makes sure there is actually beam available. + Note: + If 'ic0' and 'ic1' are in the amplifier argument, the same gain will be assigned + to both amplifiers to get the best glitch removal during processing later. + Args: element(str): Element which defines the energy at which the gain will be set, e.g. 'Cu' edge(str): Corresponding edge, e.g. 'L1' @@ -155,11 +162,16 @@ class AutoGain: init_vel = self.dev.mo1_bragg.velocity.get() logger.info(f"Move mono to start of {emin} eV") + self.dev.mo1_bragg.velocity.put(MONO_VELOCITY) + status = CompareStatus(self.dev.mo1_bragg.velocity, MONO_VELOCITY) + status.wait(TIMEOUT_PUT_PV) status = self.dev.mo1_bragg.move(emin) status.wait(TIMEOUT_MONO_MOVE) # Set NIDAQ to max mode - # TODO implement + self.dev.nidaq.epics_mode.put(EpicsMode.MAX) + status = CompareStatus(self.dev.nidaq.epics_mode, EpicsMode.MAX) + status.wait(timeout=TIMEOUT_PUT_PV) # Set gains to lowest gain for name, ch in active_channels.items(): @@ -180,15 +192,14 @@ class AutoGain: raise AutoGainError("Ring current dropped to 0 mA right before measurement") # Scan range, recording the peak NIDAQ signal per channel - status = self.dev.mo1_bragg.velocity.put(MONO_VELOCITY) - status.wait(TIMEOUT_MONO_PV) self.dev.mo1_bragg.move(emax).wait(timeout=TIMEOUT_MONO_MOVE) status.wait(TIMEOUT_MONO_MOVE) for name, ch in active_channels.items(): data[name] = max(data[name], ch["signal"].get()) # Rest max values of NIDAQ signals - # TODO implement + self.dev.nidaq.epics_max_reset.put(True) + time.sleep(0.1) # Measure current ring current again ring_current_2 = self._get_ring_current() @@ -202,52 +213,83 @@ class AutoGain: # Choose gain per channel based on the max signal recorded during the scan remeasure = False + processed = set() + for name, ch in active_channels.items(): - raw_signal = data[name] - logger.info(f"Raw signal for self.device {name} is {raw_signal} V") - if comp_ring_current: - raw_signal = raw_signal * NOMINAL_RING_CURRENT / ring_current - logger.info(f"Compensate for ring current, new raw signal is {raw_signal} V") - if raw_signal < MIN_SIGNAL: - logger.info(f"Raw signal for self.device {name} is below {MIN_SIGNAL}") - # Choose next gain to be 100x the current gain, or if this gain does not exist, - # choose the next smaller one - if ch["gain"] == AVAILABLE_GAINS[-1]: + if name in processed: + continue + + # ic0/ic1 must always end up with the same gain -> treat whichever of + # them are present (one or both) as a single group for this decision + if name in LINKED_CHANNELS: + group_names = [n for n in LINKED_CHANNELS if n in active_channels] + else: + group_names = [name] + + group_signals = [] + for gname in group_names: + gsig = data[gname] + logger.info(f"Raw signal for device {gname} is {gsig} V") + if comp_ring_current: + gsig = gsig * NOMINAL_RING_CURRENT / ring_current + logger.info(f"Compensate for ring current, new raw signal is {gsig} V") + group_signals.append(gsig) + + # worst case: the weakest signal drives "need more gain", + # the strongest signal drives "don't saturate" + raw_signal_min = min(group_signals) + raw_signal_max = max(group_signals) + gain_ref = ch[ + "gain" + ] # linked channels always share gain, so any member's value works + label = "/".join(group_names) + + if raw_signal_min < MIN_SIGNAL: + logger.info(f"Raw signal for {label} is below {MIN_SIGNAL}") + if gain_ref == AVAILABLE_GAINS[-1]: logger.warning( - f"Amplifier of {name} at highest gain {ch['gain']} and still not" + f"Amplifier of {label} at highest gain {gain_ref} and still not" + f" measured signal above {MIN_SIGNAL}" ) else: next_gain = AVAILABLE_GAINS[ - bisect_right(AVAILABLE_GAINS, ch["gain"] * 100) - 1 + bisect_right(AVAILABLE_GAINS, gain_ref * 100) - 1 ] - ch["self.dev"].set_gain(next_gain) - logger.info( - f"Setting gain of self.device {name} to {next_gain:.0e} and remeasure" - ) + for gname in group_names: + active_channels[gname]["dev"].set_gain(next_gain) + active_channels[gname]["gain"] = next_gain + logger.info(f"Setting gain of {label} to {next_gain:.0e} and remeasure") remeasure = True else: gain = max( ( g for g in AVAILABLE_GAINS - if raw_signal / ch["gain"] * g <= FULL_SCALE_V * SAFETY_MARGIN + if raw_signal_max / gain_ref * g <= FULL_SCALE_V * SAFETY_MARGIN ), default=min(AVAILABLE_GAINS), ) - ch["self.dev"].set_gain(gain) - logger.info(f"Calculated final gain for {name} of {gain:.0e}") + for gname in group_names: + active_channels[gname]["dev"].set_gain(gain) + active_channels[gname]["gain"] = gain + logger.info(f"Calculated final gain for {label} of {gain:.0e}") + + processed.update(group_names) # Wait for mono to return to start position status.wait(TIMEOUT_MONO_MOVE) # Reset NIDAQ to mean mode - # TODO implement + self.dev.nidaq.epics_mode.put(EpicsMode.MEAN) + status = CompareStatus(self.dev.nidaq.epics_mode, EpicsMode.MEAN) + status.wait(timeout=TIMEOUT_PUT_PV) # Wait for mono to move to initial position and reset velocity status = self.dev.mo1_bragg.move(init_pos) status.wait(TIMEOUT_MONO_MOVE) self.dev.mo1_bragg.velocity.put(init_vel) + status = CompareStatus(self.dev.mo1_bragg.velocity, init_vel) + status.wait(timeout=TIMEOUT_PUT_PV) def _get_ring_current(self) -> float: ring_current = 0 diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py index 8acc1b5..b147608 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py @@ -1,4 +1,6 @@ +import builtins import re +import threading from pathlib import Path from typing import Literal, cast @@ -10,6 +12,7 @@ from xrt.backends.raycing.physconsts import AVOGADRO, CHeVcm from . import parameters as bl from .beamline import get_beamline_id +from .motion_worker import MotionWorker from .types import BeamlineId, ConfigDict, DataDict, SurfaceDict H = 6.62606957e-34 @@ -22,18 +25,65 @@ OFFSET_FILE_X10DA = Path(__file__).with_name("x10da_offsets.yaml") logger = bec_logger.logger -""" -The idea is to move the core logic of digital_twin to this file. Only keep the gui elements in the widget. -This way, the scheduler widget can access digital twin without loading the GUI (GUI is still needed for the item creation, but not the item execution) - Scheduler will extract assistant inputs (get_assistant_config) during item creation - Scheduler will use digital_twin.calculate_positons to calculate positions and digital_twin.move_all to move the motors -""" + +class _ExclusiveGroupManager: + """Coordinates one exclusive group: only motors from the same + subgroup may be active at once; a different subgroup must wait until + the active one fully finishes.""" + + def __init__(self): + self._cond = threading.Condition() + self._active_subgroup = None + self._active_count = 0 + + def acquire(self, subgroup_id): + with self._cond: + while self._active_subgroup is not None and self._active_subgroup != subgroup_id: + self._cond.wait() + self._active_subgroup = subgroup_id + self._active_count += 1 + + def release(self): + with self._cond: + self._active_count -= 1 + if self._active_count == 0: + self._active_subgroup = None + self._cond.notify_all() + + +# Each entry is one exclusive group, made of subgroups. Motors in the same +# subgroup may move concurrently; motors in different subgroups of the +# same group may not. Motors not listed here move completely freely. +# Example from below: Each listed cm_* motor needs to move alone, but +# sldi_gapx and sldi_gapy can move together. sldi_gapx can move together +# with ot_try +EXCLUSIVE_GROUPS: list[list[list[str]]] = [ + [["sldi_gapx", "sldi_gapy"], ["sldi_centerx", "sldi_centery"]], + [["cm_trx"], ["cm_roty"], ["cm_try"], ["cm_rotx"], ["cm_rotz"]], + [["fm_trx"], ["fm_roty"], ["fm_try"], ["fm_rotx"], ["fm_rotz"]], + [["sl1_gapx", "sl1_gapy"], ["sl1_centerx", "sl1_centery"]], + [["sl2_gapx", "sl2_gapy"], ["sl2_centerx", "sl2_centery"]], + [["ot_try"], ["ot_rotx"]], +] + + +class DigitalTwinCoreError(Exception): + """DigitalTwinCore specific error""" class DigitalTwinCore: def __init__(self): logger.info("This is the digital twin from the ipython client!") + dev = builtins.__dict__.get("dev") + bec = builtins.__dict__.get("bec") + if dev is None: + raise DigitalTwinCoreError("Did not get dev") + if bec is None: + raise DigitalTwinCoreError("Did not get bec") + self.dev = dev + self.bec = bec + self.beamline = get_beamline_id() self.offset_file = Path() match self.beamline: @@ -44,10 +94,69 @@ class DigitalTwinCore: self.offsets = {} self.load_offsets() + def _exclusive_group_key(self, motor: str): + """Return (group_index, subgroup_index) for `motor`, or (None, None) + if it isn't part of any exclusive group and can move freely.""" + for gi, group in enumerate(EXCLUSIVE_GROUPS): + for si, subgroup in enumerate(group): + if motor in subgroup: + return gi, si + return None, None + def move_with_config(self, config): + """ + Move all motors in `config` to their target positions, all starting at + once. Motors are free to move concurrently unless they belong to the + same exclusive group (see `EXCLUSIVE_GROUPS`) but different subgroups, + in which case one subgroup must fully finish before another starts. + + Returns: + dict: {"success": True, "moved": [...]} if every motor completed + without error, else {"success": False, "moved": [...], + "failures": {motor: error}}. + """ positions = self.calc_positions(self.beamline, config) positions = self.apply_offsets(positions, nested_config=True) - logger.info(f"Would now move to these positions: {positions}") + + managers: dict[int, _ExclusiveGroupManager] = {} + for motor in positions: + gi, _ = self._exclusive_group_key(motor) + if gi is not None: + managers.setdefault(gi, _ExclusiveGroupManager()) + + moved: list[str] = [] + failures: dict[str, Exception | str] = {} + results_lock = threading.Lock() + + def run_motor(motor: str, target: float): + gi, si = self._exclusive_group_key(motor) + manager = managers.get(gi) if gi is not None else None + if manager: + manager.acquire(si) + try: + worker = MotionWorker(self.beamline, self.dev, motor, target) + worker.run() # blocks this thread until finished or errored + with results_lock: + if worker.last_exception is not None: + failures[motor] = worker.last_exception + else: + moved.append(motor) + finally: + if manager: + manager.release() + + threads = [ + threading.Thread(target=run_motor, args=(motor, pos["value"]), daemon=True) + for motor, pos in positions.items() + ] + for t in threads: + t.start() + for t in threads: + t.join() + + if failures: + return {"success": False, "moved": moved, "failures": failures} + return {"success": True, "moved": moved} def load_offsets(self): if self.offsets == {}: @@ -255,7 +364,7 @@ class DigitalTwinCore: ## Focusing Mirror p = bl.fm.center[1] - q = cfg["smpl"] - bl.fm.center[1] + q = (cfg["ot_es1_trz"] + cfg["es1man_trz"]) - bl.fm.center[1] f = (p * q) / (p + q) # focal length # Bender radius @@ -350,9 +459,22 @@ class DigitalTwinCore: pos["ot_rotx"] = {"value": ot_pitch * 1e3} # TRZ ES1 - ot_es1_trz = cfg["smpl"] + ot_es1_trz = cfg["ot_es1_trz"] pos["ot_es1_trz"] = {"value": ot_es1_trz} + # Sample manipulator TRZ + es1man_trz = cfg["es1man_trz"] + if es1man_trz is None: + raise ValueError("es1man_trz is None") + pos["es1man_trz"] = {"value": es1man_trz} + + # TRZ ES2 + smpl_to_xrd = cfg["smpl_to_xrd"] + if smpl_to_xrd is None: + raise ValueError("smpl_to_xrd is None") + ot_es2_trz = smpl_to_xrd + ot_es1_trz + es1man_trz - 32 + pos["ot_es2_trz"] = {"value": ot_es2_trz} + # ES0 exit window pos["es0wi_try"] = { "value": 5 @@ -930,6 +1052,7 @@ class DigitalTwinCore: beam["y"].append(bl.sourceHeight) beam["x"].append(bl.cm.center[1]) # CM beam["y"].append(bl.sourceHeight) + smpl = cfg["ot_es1_trz"] + cfg["es1man_trz"] if cfg["mo1_mode"] == "Monochromatic": diag = bl.mo1.xtalGap[0] / np.sin(cfg["mo1_bragg"]) # Calculations for Mono dy = diag * np.sin(2 * (cfg["cm_pitch"] + cfg["mo1_bragg"])) @@ -951,23 +1074,23 @@ class DigitalTwinCore: + np.tan(2 * cfg["cm_pitch"]) * (bl.fm.center[1] - bl.cm.center[1] - dz) + dy ) - beam["x"].append(cfg["smpl"]) # Experiment + beam["x"].append(smpl) # Experiment beam["y"].append( bl.sourceHeight + np.tan(2 * cfg["cm_pitch"]) * (bl.fm.center[1] - bl.cm.center[1] - dz) + dy - + np.tan(2 * (cfg["cm_pitch"] - cfg["fm_rotx"])) * (cfg["smpl"] - bl.fm.center[1]) + + np.tan(2 * (cfg["cm_pitch"] - cfg["fm_rotx"])) * (smpl - bl.fm.center[1]) ) elif cfg["mo1_mode"] == "Pinkbeam": beam["x"].append(bl.fm.center[1]) # FM beam["y"].append( bl.sourceHeight + np.tan(2 * cfg["cm_pitch"]) * (bl.fm.center[1] - bl.cm.center[1]) ) - beam["x"].append(cfg["smpl"]) # Experiment + beam["x"].append(smpl) # Experiment beam["y"].append( bl.sourceHeight + np.tan(2 * cfg["cm_pitch"]) * (bl.fm.center[1] - bl.cm.center[1]) - + np.tan(2 * (cfg["cm_pitch"] - cfg["fm_rotx"])) * (cfg["smpl"] - bl.fm.center[1]) + + np.tan(2 * (cfg["cm_pitch"] - cfg["fm_rotx"])) * (smpl - bl.fm.center[1]) ) return beam diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py new file mode 100644 index 0000000..dfbadf5 --- /dev/null +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py @@ -0,0 +1,269 @@ +"""Move an axis through BEC""" + +import threading +import time +from typing import Callable + +from bec_lib import bec_logger + +# pylint: disable=E0402 +from ....devices.absorber import STATUS as ABS_STATUS +from .types import BeamlineId + +logger = bec_logger.logger + + +class MotionWorker: + """ + Executes motion on the specified motor and includes some safety during + motion for certain motors. Pure Python / Qt-independent: reports + progress via plain callables instead of Qt signals, so it can run on + any thread (or be unit-tested without a QApplication). + """ + + def __init__( + self, + beamline: BeamlineId, + dev, + motor, + target_pos: float, + on_position_changed: Callable[[float], None] | None = None, + on_error: Callable[[], None] | None = None, + on_finished: Callable[[], None] | None = None, + ): + self.beamline = beamline + self.dev = dev + self.motor = motor + self._target = target_pos + self._stop_flag = threading.Event() + self.on_position_changed = on_position_changed + self.on_error = on_error + self.on_finished = on_finished + self.last_exception: Exception | None = None + + def _emit_position_changed(self, pos: float): + if self.on_position_changed is not None: + self.on_position_changed(pos) + + def _emit_error(self): + if self.on_error is not None: + self.on_error() + + def _emit_finished(self): + if self.on_finished is not None: + self.on_finished() + + def stop(self): + """Sets the stop flag""" + self._stop_flag.set() + + def run(self): + """Prepares the movement based on the axis (motor)""" + match self.motor: + case ( + "sldi_gapx" + | "sldi_gapy" + | "sldi_centerx" + | "sldi_centery" + | "sl1_gapx" + | "sl1_gapy" + | "sl1_centerx" + | "sl1_centery" + | "bm1_try" + | "sl2_gapx" + | "sl2_gapy" + | "sl2_centerx" + | "sl2_centery" + | "bm2_try" + | "es0wi_try" + | "es1_try" + | "es2_try" + | "ot_try" + | "ot_rotx" + | "ot_es1_trz" + | "ot_es2_trz" + | "es1ic0_try" + | "es1ic1_try" + | "es1ic2_try" + ): + self.motion() + case "cm_trx": + self.motion( + abs_closed=True, + surveyed_axes=[{"device": self.dev["cm_roty"], "abs_tol": 0.05}], + ) + case "cm_roty": + self.motion( + abs_closed=True, surveyed_axes=[{"device": self.dev["cm_trx"], "abs_tol": 0.05}] + ) + case "cm_try": + self.motion( + abs_closed=True, + surveyed_axes=[ + {"device": self.dev["cm_rotx"], "abs_tol": 0.05}, + {"device": self.dev["cm_rotz"], "abs_tol": 0.05}, + ], + ) + case "cm_rotx": + self.motion( + abs_closed=True, + surveyed_axes=[ + {"device": self.dev["cm_try"], "abs_tol": 0.05}, + {"device": self.dev["cm_rotz"], "abs_tol": 0.05}, + ], + ) + case "cm_rotz": + self.motion( + abs_closed=True, + surveyed_axes=[ + {"device": self.dev["cm_try"], "abs_tol": 0.05}, + {"device": self.dev["cm_rotx"], "abs_tol": 0.05}, + ], + ) + case "cm_bnd": + if self.beamline == "x01da": + p1 = ( + 1 / (self.dev.cm_bnd_radius.read()["cm_bnd_radius"]["value"] * 1e3) + 0.0284 + ) / 2e-6 + p2 = (1 / (self._target * 1e3) + 0.0284) / 2e-6 + else: + p1 = 541900 / self.dev.cm_bnd_radius.read()["cm_bnd_radius"]["value"] - 32570 + p2 = 541900 / self._target - 32570 + self._target = p2 - p1 + self.motion(relative=True, rb={"device": self.dev["cm_bnd_radius"]}) + case "mo1_try" | "mo1_trx" | "mo1_roty": + self.motion(abs_closed=True) + case "mo1_bragg_angle": + if self.beamline == "x01da": + self.motion() + else: # x10da needs to move goniometer + self.motion(alias="mo1_rotx") + case "fm_trx": + self.motion( + abs_closed=True, + surveyed_axes=[{"device": self.dev["fm_roty"], "abs_tol": 0.05}], + ) + case "fm_roty": + self.motion( + abs_closed=True, surveyed_axes=[{"device": self.dev["fm_trx"], "abs_tol": 0.05}] + ) + case "fm_try": + if self.beamline == "x01da": + abs_tol = 0.05 + else: # superxas mirror less stable thus needs higher tolerance + abs_tol = 0.2 + self.motion( + abs_closed=True, + surveyed_axes=[ + {"device": self.dev["fm_rotx"], "abs_tol": abs_tol}, + {"device": self.dev["fm_rotz"], "abs_tol": abs_tol}, + ], + ) + case "fm_rotx": + if self.beamline == "x01da": + abs_tol = 0.05 + else: # superxas mirror less stable thus needs higher tolerance + abs_tol = 0.2 + self.motion( + abs_closed=True, + surveyed_axes=[ + {"device": self.dev["fm_try"], "abs_tol": abs_tol}, + {"device": self.dev["fm_rotz"], "abs_tol": abs_tol}, + ], + ) + case "fm_rotz": + if self.beamline == "x01da": + abs_tol = 0.05 + else: # superxas mirror less stable thus needs higher tolerance + abs_tol = 0.2 + self.motion( + abs_closed=True, + surveyed_axes=[ + {"device": self.dev["fm_try"], "abs_tol": abs_tol}, + {"device": self.dev["fm_rotx"], "abs_tol": abs_tol}, + ], + ) + case "fm_bnd": + if self.beamline == "x01da": + p1 = ( + 1 / (self.dev.fm_bnd_radius.read()["fm_bnd_radius"]["value"] * 1e3) + + 4.28e-5 + ) / 1.84e-9 + p2 = (1 / (self._target * 1e3) + 4.28e-5) / 1.84e-9 + else: + p1 = ( + 593088.7 / self.dev.fm_bnd_radius.read()["fm_bnd_radius"]["value"] + + 26124.41 + ) + p2 = 593088.7 / self._target + 26124.41 + self._target = p2 - p1 + self.motion(relative=True, rb={"device": self.dev["fm_bnd_radius"]}) + case _: + logger.warning(f"Motor {self.motor} not integrated in digital twin!") + + def motion( + self, + abs_closed: bool = False, + relative: bool = False, + rb=None, + surveyed_axes=None, + alias=None, + ): + """ + Moves an axis while surverying a set of axes (if set). + Example surveyed_axes: + [{'device': bec_device_object, 'abs_tol': 0.1},] + + Args: + surveyed_axes (list): List of dictionaries of devices + """ + logger.info(f"Move axis {self.motor} to target {self._target}, move_relative={relative}") + try: + if alias: + self.motor = alias + if abs_closed: + if self.dev.abs.status.get() == ABS_STATUS.OPEN: + status = self.dev.abs.close() + status.wait(timeout=5) + if surveyed_axes is not None: + for surv_ax in surveyed_axes: + surv_ax["name"] = surv_ax["device"].dotted_name + surv_ax["old_value"] = surv_ax["device"].read(cached=True)[surv_ax["name"]][ + "value" + ] + if rb is not None: + rb["name"] = rb["device"].dotted_name + status = self.dev[self.motor].move(self._target, relative=relative) + last_check = time.time() + update_interval = 0.1 + while status.status == "RUNNING": + now = time.time() + if time.time() - last_check < update_interval: + time.sleep(0.01) + last_check = now + if self._stop_flag.is_set(): + self.dev[self.motor].stop() + self._stop_flag.clear() + if rb is not None: + self._emit_position_changed(rb["device"].read(cached=True)[rb["name"]]["value"]) + else: + self._emit_position_changed( + self.dev[self.motor].read(cached=True)[self.motor]["value"] + ) + if surveyed_axes is not None: + for surv_ax in surveyed_axes: + fb = surv_ax["device"].read(cached=True)[surv_ax["name"]]["value"] + if abs(fb - surv_ax["old_value"]) > surv_ax["abs_tol"]: + self.dev[self.motor].stop() + self.last_exception = RuntimeError( + f"{surv_ax['name']} deviated beyond tolerance {surv_ax['abs_tol']} during {self.motor} move" + ) + self._emit_error() + self._emit_finished() + return + self._emit_finished() + except Exception as e: + logger.error(f"Error during movement of {self.motor}: {e}") + self.last_exception = e + self._emit_error() + self._emit_finished() diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/types.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/types.py index d5c0393..7c66f50 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/types.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/types.py @@ -32,7 +32,9 @@ class ConfigDict(TypedDict): fm_trx (float): FM translation x. fm_qy (float): FM qy value. fm_gain_height (int): FM gain height. - smpl (float): Sample value. + ot_es1_trz (float): Position of ES1 table. + es1man_trz (float): Position of Sample Manipulator TRZ + smpl_to_xrd (float): Sample to XRD detector distance """ energy: float @@ -49,7 +51,9 @@ class ConfigDict(TypedDict): fm_trx: float fm_qy: None | float fm_gain_height: int - smpl: float + ot_es1_trz: float + es1man_trz: float + smpl_to_xrd: None | float class DataDict(TypedDict): diff --git a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py index 2a01e02..0901da6 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py @@ -42,7 +42,6 @@ from .panels.input_panel import InputPanel from .panels.mover_panel import MoverPanel from .panels.plots import SideviewPlot, SurfacePlots from .panels.settings_panel import SettingsPanel -from .widgets.qt_widgets import ComboBox, InputNumberField logger = bec_logger.logger @@ -133,11 +132,11 @@ class DigitalTwin(BECWidget, QWidget): self.input.fm_rotx.value_changed_connect(self.calc_assistant) self.input.fm_focx.value_changed_connect(self.calc_assistant) self.input.fm_focy.value_changed_connect(self.calc_assistant) - match self.input.smpl: - case InputNumberField(): - self.input.smpl.value_changed_connect(self.calc_assistant) - case ComboBox(): - self.input.smpl.activated_connect(self.calc_assistant) + if self.beamline == "x01da": + self.input.ot_es1_trz.value_changed_connect(self.calc_assistant) + else: + self.input.table.activated_connect(self.calc_assistant) + self.input.es1man_trz.value_changed_connect(self.calc_assistant) self.input.adapt_reality.clicked_connect(self.adapt_reality) self.settings.load_offsets.clicked_connect(self.load_offsets) @@ -216,6 +215,7 @@ class DigitalTwin(BECWidget, QWidget): "fm_rotz", "bm2_try", "es0wi_try", + "es1man_trz", ] if self.beamline == "x01da": # X01DA specific devices devices.extend( @@ -226,6 +226,7 @@ class DigitalTwin(BECWidget, QWidget): "sl2_gapy", "ot_try", "ot_es1_trz", + "ot_es2_trz", ] ) if self.beamline == "x10da": # X10DA specific devices @@ -344,7 +345,9 @@ class DigitalTwin(BECWidget, QWidget): self.calc_fm_reflectivity() self.calc_cm_fm_harm_suppr() self.calc_fm_ideal_pitch() - case "smpl": + case "ot_es1_trz": + self.calc_fm_ideal_pitch() + case "es1man_trz": self.calc_fm_ideal_pitch() self.calc_positions() self.calc_assistant_sideview() @@ -380,12 +383,15 @@ class DigitalTwin(BECWidget, QWidget): assert cm_trx is not None, f"No cm_trx found for given stripe {cm_stripe}!" assert fm_trx is not None, f"No fm_trx found for given stripe {fm_stripe}!" - match self.input.smpl: - case InputNumberField(): - smpl = self.input.smpl.value() - case ComboBox(): - table = self.input.smpl.currentText() - smpl = self.core.table_to_smpl_pos(table) + if self.beamline == "x01da": + ot_es1_trz = self.input.ot_es1_trz.value() + smpl_to_xrd = self.input.smpl_to_xrd.value() + else: + table = self.input.table.currentText() + ot_es1_trz = self.core.table_to_smpl_pos(table) + smpl_to_xrd = None + + es1man_trz = self.input.es1man_trz.value() config: ConfigDict = { "energy": self.input.energy.value(), @@ -402,7 +408,9 @@ class DigitalTwin(BECWidget, QWidget): "fm_trx": fm_trx, "fm_qy": fm_qy, "fm_gain_height": 1, - "smpl": smpl, + "ot_es1_trz": ot_es1_trz, + "es1man_trz": es1man_trz, + "smpl_to_xrd": smpl_to_xrd, } # Apply offsets @@ -441,13 +449,16 @@ class DigitalTwin(BECWidget, QWidget): fm_stripe = self.core.fm_trx_to_stripe(-fm_trx) fm_rotx = self.dev.fm_rotx.read(cached=True)["fm_rotx"]["value"] fm_rotx_real = 2 * cm_pitch - fm_rotx + es1man_trz = self.dev.es1man_trz.read(cached=True)["es1man_trz"]["value"] - match self.input.smpl: - case InputNumberField(): - smpl = self.dev.ot_es1_trz.read(cached=True)["ot_es1_trz"]["value"] - case ComboBox(): - table = self.input.smpl.currentText() - smpl = self.core.table_to_smpl_pos(table) + if self.beamline == "x01da": + ot_es1_trz = self.dev.ot_es1_trz.read(cached=True)["ot_es1_trz"]["value"] + ot_es2_trz = self.dev.ot_es2_trz.read(cached=True)["ot_es2_trz"]["value"] + smpl_to_xrd = ot_es2_trz - ot_es1_trz - es1man_trz + 32 + else: + table = self.input.table.currentText() + ot_es1_trz = self.core.table_to_smpl_pos(table) + smpl_to_xrd = None raw = { # Config in SI units! "energy": mo1_bragg["mo1_bragg"]["value"], @@ -464,7 +475,9 @@ class DigitalTwin(BECWidget, QWidget): "fm_trx": fm_trx, "fm_qy": None, "fm_gain_height": 1, - "smpl": smpl, + "ot_es1_trz": ot_es1_trz, + "es1man_trz": es1man_trz, + "smpl_to_xrd": smpl_to_xrd, } config = cast(ConfigDict, raw) # logger.info(f'Config created: {config}') @@ -517,7 +530,9 @@ class DigitalTwin(BECWidget, QWidget): if self.beamline == "x01da": self.mover.ot_try.set_feedback(self.dev.ot_try.read(cached=True)["ot_try"]["value"]) self.mover.ot_rotx.set_feedback(self.dev.ot_rotx.read(cached=True)["ot_rotx"]["value"]) - self.mover.ot_es1_trz.set_feedback(smpl) + self.mover.ot_es1_trz.set_feedback(ot_es1_trz) + self.mover.ot_es2_trz.set_feedback(ot_es2_trz) + self.mover.es1man_trz.set_feedback(es1man_trz) self.mover.es0wi_try.set_feedback( self.dev.es0wi_try.read(cached=True)["es0wi_try"]["value"] ) @@ -552,8 +567,14 @@ class DigitalTwin(BECWidget, QWidget): pos["fm_trx"] = self.dev.fm_trx.read(cached=True)["fm_trx"]["value"] pos["fm_rotx"] = self.dev.fm_rotx.read(cached=True)["fm_rotx"]["value"] pos["fm_bnd_radius"] = self.dev.fm_bnd_radius.read(cached=True)["fm_bnd_radius"]["value"] + pos["es1man_trz"] = self.dev.es1man_trz.read(cached=True)["es1man_trz"]["value"] if self.beamline == "x01da": pos["ot_es1_trz"] = self.dev.ot_es1_trz.read(cached=True)["ot_es1_trz"]["value"] + pos["ot_es2_trz"] = self.dev.ot_es2_trz.read(cached=True)["ot_es2_trz"]["value"] + pos["smpl_to_xrd"] = pos["ot_es2_trz"] - pos["ot_es1_trz"] - pos["es1man_trz"] + 32 + else: + table = self.ask_table_selection(self.input.table.currentText()) + pos["ot_es1_trz"] = self.core.table_to_smpl_pos(table) # Removing offsets pos = self.core.remove_offsets(pos) @@ -577,14 +598,14 @@ class DigitalTwin(BECWidget, QWidget): fm_rotx_real = 2 * pos["cm_rotx"] - pos["fm_rotx"] self.input.fm_rotx.set_number(fm_rotx_real) - match self.input.smpl: - case InputNumberField(): - smpl = pos["ot_es1_trz"] - self.input.smpl.set_number(pos["ot_es1_trz"]) - case ComboBox(): - table = self.ask_table_selection(self.input.smpl.currentText()) - smpl = self.core.table_to_smpl_pos(table) - self.input.smpl.set_current_text(table) + if self.beamline == "x01da": + self.input.ot_es1_trz.set_number(pos["ot_es1_trz"]) + self.input.smpl_to_xrd.set_number(pos["smpl_to_xrd"]) + else: + table = self.ask_table_selection(self.input.table.currentText()) + self.input.table.set_current_text(table) + + smpl = pos["ot_es1_trz"] + pos["es1man_trz"] fm_focx, fm_focy = self.core.calc_beamsize( h_acc, v_acc, fm_stripe, -fm_rotx_real * 1e-3, pos["fm_bnd_radius"] * 1e6, smpl @@ -866,7 +887,9 @@ class DigitalTwin(BECWidget, QWidget): self.mover.ot_try.set_target(out["ot_try"]["value"]) self.mover.ot_rotx.set_target(out["ot_rotx"]["value"]) self.mover.ot_es1_trz.set_target(out["ot_es1_trz"]["value"]) + self.mover.ot_es2_trz.set_target(out["ot_es2_trz"]["value"]) self.mover.es0wi_try.set_target(out["es0wi_try"]["value"]) + self.mover.es1man_trz.set_target(out["es1man_trz"]["value"]) if self.beamline == "x10da": self.mover.es1_try.set_target(out["es1_try"]["value"]) self.mover.es1ic0_try.set_target(out["es1ic0_try"]["value"]) @@ -918,12 +941,14 @@ class DigitalTwin(BECWidget, QWidget): Literal["Defocused", "Focused", "Manual"], self.input.fm_focus.currentText() ) fm_stripe = self.input.fm_stripe.currentText() - match self.input.smpl: - case InputNumberField(): - smpl = self.input.smpl.value() - case ComboBox(): - table = self.input.smpl.currentText() - smpl = self.core.table_to_smpl_pos(table) + es1man_trz = self.input.es1man_trz.value() + if self.beamline == "x01da": + ot_es1_trz = self.input.ot_es1_trz.value() + else: + table = self.input.table.currentText() + ot_es1_trz = self.core.table_to_smpl_pos(table) + smpl = ot_es1_trz + es1man_trz + sldi_hacc = self.input.sldi_hacc.value() * 1e-3 sldi_vacc = self.input.sldi_vacc.value() * 1e-3 fm_focx = self.input.fm_focx.value() diff --git a/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py b/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py index 5c4cd1b..3b4a377 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py @@ -173,7 +173,45 @@ class InputPanel(QWidget): # Sample self.cm_fm_harm_suppr = NumberIndicator("Total Suppression Factor at x eV", "", decimals=0) - self.smpl = self._create_smpl(beamline) + + self.es1man_trz = InputNumberField( + "es1man_trz", + "Sample Manipulator TRZ", + unit="mm", + init=0, + decimals=1, + single_step=1, + ll=-60, + hl=60, + ) + + if beamline == BeamlineId.X01DA: + self.ot_es1_trz = InputNumberField( + "ot_es1_trz", + "ES1 Position", + unit="mm", + init=23511, + decimals=0, + single_step=100, + ll=23000, + hl=30000, + ) + self.smpl_to_xrd = InputNumberField( + "smpl_to_xrd", + "Sample to XRD Det", + unit="mm", + init=320, + decimals=0, + single_step=10, + ll=320, + hl=6000, + ) + self.smpl_group = Group( + "Sample Position", [self.ot_es1_trz, self.es1man_trz, self.smpl_to_xrd] + ) + else: + self.table = ComboBox("table", "Sample Position", ["ES1", "ES2"]) + self.smpl_group = Group("Sample Position", [self.ot_es1_trz, self.es1man_trz]) # Assemble complete assistant group self.input_group = Group( @@ -186,25 +224,9 @@ class InputPanel(QWidget): self.mo1_ass_group, self.fm_ass_group, self.cm_fm_harm_suppr, - self.smpl, + self.smpl_group, ], ) self._layout.addWidget(self.input_group) self._layout.addStretch() - - def _create_smpl(self, beamline: BeamlineId) -> Union[InputNumberField, ComboBox]: - match beamline: - case BeamlineId.X01DA: - return InputNumberField( - "smpl", - "Sample Position", - unit="mm", - init=23511, - decimals=0, - single_step=100, - ll=23000, - hl=30000, - ) - case BeamlineId.X10DA: - return ComboBox("smpl", "Sample Position", ["ES1", "ES2"]) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py b/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py index 148d0ef..bd43e05 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py @@ -343,6 +343,16 @@ class MoverPanel(QWidget): deadband=5, ) self.mover_widgets.append(self.ot_es1_trz) + self.es1man_trz = MoveWidget( + beamline=beamline, + dev=dev, + motor="es1man_trz", + label="MANIP TRZ", + unit="mm", + decimals=2, + deadband=0.1, + ) + self.mover_widgets.append(self.es1man_trz) if beamline == "x10da": self.es1_try = MoveWidget( @@ -390,13 +400,25 @@ class MoverPanel(QWidget): self.mover_widgets.append(self.es1ic2_try) if beamline == "x01da": - self.es1_mov_group = Group("Experimental Station 1", [self.ot_es1_trz]) + self.es1_mov_group = Group("Experimental Station 1", [self.ot_es1_trz, self.es1man_trz]) else: self.es1_mov_group = Group( "Experimental Station 1", [self.es1_try, self.es1ic1_try, self.es1ic2_try] ) # Experimental Station 2 + if beamline == "x01da": + self.ot_es2_trz = MoveWidget( + beamline=beamline, + dev=dev, + motor="ot_es2_trz", + label="ES2 TRZ", + unit="mm", + decimals=0, + deadband=5, + ) + self.mover_widgets.append(self.ot_es2_trz) + if beamline == "x10da": self.es2_try = MoveWidget( beamline=beamline, @@ -409,6 +431,9 @@ class MoverPanel(QWidget): ) self.mover_widgets.append(self.es2_try) + if beamline == "x01da": + self.es2_mov_group = Group("Experimental Station 2", [self.ot_es2_trz]) + else: self.es2_mov_group = Group("Experimental Station 2", [self.es2_try]) # Assemble complete mover group @@ -428,6 +453,7 @@ class MoverPanel(QWidget): self.ot_mov_group, self.es0_mov_group, self.es1_mov_group, + self.es2_mov_group, ], ) else: diff --git a/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py b/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py index 6df4065..1347d30 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py @@ -1,7 +1,6 @@ """Move widget to display an axis and also move it through BEC""" import threading -import time from typing import Literal, Optional from bec_lib import bec_logger @@ -11,15 +10,13 @@ from bec_widgets.utils.colors import get_accent_colors # pylint: disable=E0611 from qtpy.QtCore import Property # type: ignore[attr-defined] from qtpy.QtCore import Signal # type: ignore[attr-defined] -from qtpy.QtCore import QObject, QPropertyAnimation, Qt, QThread +from qtpy.QtCore import QObject, QPropertyAnimation, Qt from qtpy.QtGui import QTransform from qtpy.QtWidgets import QApplication, QHBoxLayout, QLabel, QPushButton, QWidget +from .....bec_ipython_client.plugins.digital_twin_core.motion_worker import MotionWorker from .....bec_ipython_client.plugins.digital_twin_core.types import BeamlineId -# pylint: disable=E0402 -from .....devices.absorber import STATUS as ABS_STATUS - logger = bec_logger.logger @@ -124,222 +121,13 @@ class StatusIcon(QWidget): self._label.setPixmap(icon) -class MotionWorker(QObject): - """ - Executes motion on the specified motor and includes some safety during - motion for certain motors. - """ +class _WorkerSignals(QObject): + """Tiny QObject just to own signals, since MotionWorker itself is no longer a QObject.""" position_changed = Signal(float) error = Signal() finished = Signal() - def __init__(self, beamline: BeamlineId, dev, motor, target_pos: float): - super().__init__() - self.beamline = beamline - self.dev = dev - self.motor = motor - self._target = target_pos - self._stop_flag = threading.Event() - - def stop(self): - """Sets the stop flag""" - self._stop_flag.set() - - def run(self): - """Prepares the movement based on the axis (motor)""" - match self.motor: - case "sldi_gapx" | "sldi_gapy" | "sldi_centerx" | "sldi_centery": - self.motion() - case "cm_trx": - self.motion( - abs_closed=True, - surveyed_axes=[{"device": self.dev["cm_roty"], "abs_tol": 0.05}], - ) - case "cm_roty": - self.motion( - abs_closed=True, surveyed_axes=[{"device": self.dev["cm_trx"], "abs_tol": 0.05}] - ) - case "cm_try": - self.motion( - abs_closed=True, - surveyed_axes=[ - {"device": self.dev["cm_rotx"], "abs_tol": 0.05}, - {"device": self.dev["cm_rotz"], "abs_tol": 0.05}, - ], - ) - case "cm_rotx": - self.motion( - abs_closed=True, - surveyed_axes=[ - {"device": self.dev["cm_try"], "abs_tol": 0.05}, - {"device": self.dev["cm_rotz"], "abs_tol": 0.05}, - ], - ) - case "cm_rotz": - self.motion( - abs_closed=True, - surveyed_axes=[ - {"device": self.dev["cm_try"], "abs_tol": 0.05}, - {"device": self.dev["cm_rotx"], "abs_tol": 0.05}, - ], - ) - case "cm_bnd": - if self.beamline == "x01da": - p1 = ( - 1 / (self.dev.cm_bnd_radius.read()["cm_bnd_radius"]["value"] * 1e3) + 0.0284 - ) / 2e-6 - p2 = (1 / (self._target * 1e3) + 0.0284) / 2e-6 - else: - p1 = 541900 / self.dev.cm_bnd_radius.read()["cm_bnd_radius"]["value"] - 32570 - p2 = 541900 / self._target - 32570 - self._target = p2 - p1 - self.motion(relative=True, rb={"device": self.dev["cm_bnd_radius"]}) - case "mo1_try" | "mo1_trx" | "mo1_roty": - self.motion(abs_closed=True) - case "mo1_bragg_angle": - if self.beamline == "x01da": - self.motion() - else: # x10da needs to move goniometer - self.motion(alias="mo1_rotx") - case "sl1_centery" | "sl1_gapy" | "bm1_try": - self.motion() - case "fm_trx": - self.motion( - abs_closed=True, - surveyed_axes=[{"device": self.dev["fm_roty"], "abs_tol": 0.05}], - ) - case "fm_roty": - self.motion( - abs_closed=True, surveyed_axes=[{"device": self.dev["fm_trx"], "abs_tol": 0.05}] - ) - case "fm_try": - if self.beamline == "x01da": - abs_tol = 0.05 - else: # superxas mirror less stable thus needs higher tolerance - abs_tol = 0.2 - self.motion( - abs_closed=True, - surveyed_axes=[ - {"device": self.dev["fm_rotx"], "abs_tol": abs_tol}, - {"device": self.dev["fm_rotz"], "abs_tol": abs_tol}, - ], - ) - case "fm_rotx": - if self.beamline == "x01da": - abs_tol = 0.05 - else: # superxas mirror less stable thus needs higher tolerance - abs_tol = 0.2 - self.motion( - abs_closed=True, - surveyed_axes=[ - {"device": self.dev["fm_try"], "abs_tol": abs_tol}, - {"device": self.dev["fm_rotz"], "abs_tol": abs_tol}, - ], - ) - case "fm_rotz": - if self.beamline == "x01da": - abs_tol = 0.05 - else: # superxas mirror less stable thus needs higher tolerance - abs_tol = 0.2 - self.motion( - abs_closed=True, - surveyed_axes=[ - {"device": self.dev["fm_try"], "abs_tol": abs_tol}, - {"device": self.dev["fm_rotx"], "abs_tol": abs_tol}, - ], - ) - case "fm_bnd": - if self.beamline == "x01da": - p1 = ( - 1 / (self.dev.fm_bnd_radius.read()["fm_bnd_radius"]["value"] * 1e3) - + 4.28e-5 - ) / 1.84e-9 - p2 = (1 / (self._target * 1e3) + 4.28e-5) / 1.84e-9 - else: - p1 = ( - 593088.7 / self.dev.fm_bnd_radius.read()["fm_bnd_radius"]["value"] - + 26124.41 - ) - p2 = 593088.7 / self._target + 26124.41 - self._target = p2 - p1 - self.motion(relative=True, rb={"device": self.dev["fm_bnd_radius"]}) - case "sl2_centery" | "sl2_gapy" | "bm2_try": - self.motion() - case "ot_try" | "ot_rotx" | "ot_es1_trz": - self.motion() - case "es0wi_try": - self.motion() - case "es1_try" | "es2_try": - self.motion() - case "es1ic0_try" | "es1ic1_try" | "es1ic2_try": - self.motion() - case _: - logger.warning(f"Motor {self.motor} not integrated in digital twin!") - - def motion( - self, - abs_closed: bool = False, - relative: bool = False, - rb=None, - surveyed_axes=None, - alias=None, - ): - """ - Moves an axis while surverying a set of axes (if set). - Example surveyed_axes: - [{'device': bec_device_object, 'abs_tol': 0.1},] - - Args: - surveyed_axes (list): List of dictionaries of devices - """ - logger.info(f"Move axis {self.motor} to target {self._target}, move_relative={relative}") - try: - if alias: - self.motor = alias - if abs_closed: - if self.dev.abs.status.get() == ABS_STATUS.OPEN: - status = self.dev.abs.close() - status.wait(timeout=5) - if surveyed_axes is not None: - for surv_ax in surveyed_axes: - surv_ax["name"] = surv_ax["device"].dotted_name - surv_ax["old_value"] = surv_ax["device"].read(cached=True)[surv_ax["name"]][ - "value" - ] - if rb is not None: - rb["name"] = rb["device"].dotted_name - status = self.dev[self.motor].move(self._target, relative=relative) - last_check = time.time() - update_interval = 0.1 - while status.status == "RUNNING": - now = time.time() - if time.time() - last_check < update_interval: - time.sleep(0.01) - last_check = now - if self._stop_flag.is_set(): - self.dev[self.motor].stop() - self._stop_flag.clear() - if rb is not None: - self.position_changed.emit(rb["device"].read(cached=True)[rb["name"]]["value"]) - else: - self.position_changed.emit( - self.dev[self.motor].read(cached=True)[self.motor]["value"] - ) - if surveyed_axes is not None: - for surv_ax in surveyed_axes: - fb = surv_ax["device"].read(cached=True)[surv_ax["name"]]["value"] - if abs(fb - surv_ax["old_value"]) > surv_ax["abs_tol"]: - self.dev[self.motor].stop() - self.error.emit() - self.finished.emit() - break - self.finished.emit() - except Exception as e: - logger.error(f"Error during movement of {self.motor}: {e}") - self.error.emit() - self.finished.emit() - class MoveWidget(QWidget): """ @@ -361,8 +149,9 @@ class MoveWidget(QWidget): self.motor = motor self.deadband = deadband self.status = Status.IN_POSITION - self._thread: QThread | None = None + self._thread: threading.Thread | None = None self._worker: MotionWorker | None = None + self._signals: _WorkerSignals | None = None self.text_color = (0, 0, 0) @@ -488,7 +277,7 @@ class MoveWidget(QWidget): def _on_button_clicked(self): """Starts or stops motion depending on current situation""" - if self._thread and self._thread.isRunning(): + if self._thread and self._thread.is_alive(): self._stop_motion() else: self._start_motion() @@ -503,18 +292,22 @@ class MoveWidget(QWidget): self._set_status(Status.MOVING) self._apply_button_style("stop") - self._worker = MotionWorker(self.beamline, self.dev, self.motor, target) - self._thread = QThread() - self._worker.moveToThread(self._thread) - - self._thread.started.connect(self._worker.run) - self._worker.position_changed.connect(self._on_position_changed) - self._worker.error.connect(self._on_error) - self._worker.error.connect(self._thread.quit) - self._worker.finished.connect(self._on_motion_finished) - self._worker.finished.connect(self._thread.quit) - self._thread.finished.connect(self._cleanup_thread) + self._signals = _WorkerSignals() + self._signals.position_changed.connect(self._on_position_changed) + self._signals.error.connect(self._on_error) + self._signals.finished.connect(self._on_motion_finished) + self._signals.finished.connect(self._cleanup_thread) + self._worker = MotionWorker( + self.beamline, + self.dev, + self.motor, + target, + on_position_changed=self._signals.position_changed.emit, + on_error=self._signals.error.emit, + on_finished=self._signals.finished.emit, + ) + self._thread = threading.Thread(target=self._worker.run, daemon=True) self._thread.start() def _on_error(self): @@ -547,20 +340,16 @@ class MoveWidget(QWidget): def _cleanup_thread(self): """Cleaning up of the mover thread""" - if self._thread: - self._thread.deleteLater() - self._thread = None - if self._worker: - self._worker.deleteLater() - self._worker = None + self._thread = None + self._worker = None + self._signals = None def shutdown(self): """Cleaning up of the mover when shutting down the application""" if self._worker: self._worker.stop() - if self._thread: - self._thread.quit() - self._thread.wait(2000) # max 2 s grace period + if self._thread and self._thread.is_alive(): + self._thread.join(2.0) # max 2 s grace period class AbsorberWidget(QWidget): From 7082b9ff7b960cb3c7cf8f2c25fc24f5d32dd88f Mon Sep 17 00:00:00 2001 From: hitz_s Date: Wed, 9 Sep 2026 11:32:05 +0200 Subject: [PATCH 24/56] wip --- .../digital_twin_core/digital_twin_core.py | 56 +- .../widgets/digital_twin/digital_twin.py | 84 ++- .../widgets/scheduler/item_dialog.py | 659 ++++++++++-------- 3 files changed, 484 insertions(+), 315 deletions(-) diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py index b147608..243afa1 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py @@ -87,7 +87,7 @@ class DigitalTwinCore: self.beamline = get_beamline_id() self.offset_file = Path() match self.beamline: - case "x01da": + case BeamlineId.X01DA: self.offset_file = OFFSET_FILE_X01DA case "x10da": self.offset_file = OFFSET_FILE_X10DA @@ -115,7 +115,7 @@ class DigitalTwinCore: without error, else {"success": False, "moved": [...], "failures": {motor: error}}. """ - positions = self.calc_positions(self.beamline, config) + positions = self.calc_positions(config) positions = self.apply_offsets(positions, nested_config=True) managers: dict[int, _ExclusiveGroupManager] = {} @@ -213,8 +213,7 @@ class DigitalTwinCore: config[axis] -= axis_offsets["offset"] return config - @staticmethod - def calc_positions(beamline: BeamlineId, cfg: ConfigDict) -> dict[str, dict[str, float]]: + def calc_positions(self, cfg: ConfigDict) -> dict[str, dict[str, float]]: """ Calculates the positions of axes based on a beamline config. @@ -363,17 +362,9 @@ class DigitalTwinCore: pos["bm1_try"] = {"value": bm1_beam_height} ## Focusing Mirror - p = bl.fm.center[1] - q = (cfg["ot_es1_trz"] + cfg["es1man_trz"]) - bl.fm.center[1] - f = (p * q) / (p + q) # focal length - - # Bender radius - if cfg["fm_qy"] is None: - radius = 2 * q / np.sin(cfg["fm_rotx"]) # ideal bending radius for focused beam - else: - radius = ( - 2 * cfg["fm_qy"] / np.sin(cfg["fm_rotx"]) - ) # ideal bending radius for unfocused beam + radius = self.calc_fm_bnd_radius( + cfg["ot_es1_trz"] + cfg["es1man_trz"], cfg["fm_qy"], cfg["fm_rotx"] + ) pos["fm_bnd_radius"] = {"value": radius * 1e-6} # Convert to km # Pitch @@ -448,7 +439,7 @@ class DigitalTwinCore: ## Optical Table - if beamline == "x01da": + if self.beamline == BeamlineId.X01DA: # TRY d = bl.ehWindow.center[1] - bl.fm.center[1] ot_height = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) @@ -622,6 +613,30 @@ class DigitalTwinCore: return -(low + high) / 2 return None + @staticmethod + def calc_fm_bnd_radius(smpl: float, fm_qy: None | float, fm_rotx: float): + """ + Calculate the fm bender radius + + Args: + smpl(float): Sample position in mm + fm_qy(None|float): FM qy value + fm_rotx(float: FM rotx position + + Returns: + float: bending radius in m + """ + # p = bl.fm.center[1] + q = smpl - bl.fm.center[1] + # f = (p * q) / (p + q) # focal length + + # Bender radius + if fm_qy is None: + radius = 2 * q / np.sin(fm_rotx) # ideal bending radius for focused beam + else: + radius = 2 * fm_qy / np.sin(fm_rotx) # ideal bending radius for unfocused beam + return radius + @staticmethod def mo1_energy_resolution(xtal: Literal["Si111", "Si311"], energy: float) -> float: """ @@ -1032,6 +1047,15 @@ class DigitalTwinCore: return bl.es2.center[1] raise ValueError(f"Table {table} not found in beamline parameter file") + @staticmethod + def smpl_pos_to_table(smpl_pos: float) -> str: + """Return the table name based on the sample position.""" + if np.isclose(smpl_pos, bl.es1.center[1]): + return bl.es1.name + if np.isclose(smpl_pos, bl.es2.center[1]): + return bl.es2.name + raise ValueError(f"Sample position {smpl_pos} not found in beamline parameter file") + @staticmethod def calc_sideview(cfg: ConfigDict) -> DataDict: """ diff --git a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py index 0901da6..ea583c7 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py @@ -34,9 +34,8 @@ from qtpy.QtWidgets import ( QWidget, ) -from ....bec_ipython_client.plugins.digital_twin_core.beamline import get_beamline_id from ....bec_ipython_client.plugins.digital_twin_core.digital_twin_core import DigitalTwinCore -from ....bec_ipython_client.plugins.digital_twin_core.types import ConfigDict +from ....bec_ipython_client.plugins.digital_twin_core.types import BeamlineId, ConfigDict from ..edge_selector import EdgeSelector from .panels.input_panel import InputPanel from .panels.mover_panel import MoverPanel @@ -65,7 +64,7 @@ class DigitalTwin(BECWidget, QWidget): self.core = DigitalTwinCore() - self.beamline = get_beamline_id() + self.beamline = self.core.beamline # Debugging, override beamline! # self.beamline = BeamlineId.X10DA @@ -132,7 +131,7 @@ class DigitalTwin(BECWidget, QWidget): self.input.fm_rotx.value_changed_connect(self.calc_assistant) self.input.fm_focx.value_changed_connect(self.calc_assistant) self.input.fm_focy.value_changed_connect(self.calc_assistant) - if self.beamline == "x01da": + if self.beamline == BeamlineId.X01DA: self.input.ot_es1_trz.value_changed_connect(self.calc_assistant) else: self.input.table.activated_connect(self.calc_assistant) @@ -217,7 +216,7 @@ class DigitalTwin(BECWidget, QWidget): "es0wi_try", "es1man_trz", ] - if self.beamline == "x01da": # X01DA specific devices + if self.beamline == BeamlineId.X01DA: # X01DA specific devices devices.extend( [ "cm_bnd_radius", @@ -371,7 +370,7 @@ class DigitalTwin(BECWidget, QWidget): elif fm_focus == "Focused": fm_rotx = self.input.fm_rotx_ideal.value() fm_qy = None - else: # Focused + else: # Defocused fm_rotx = self.input.fm_rotx_ideal.value() fm_qy = self.qy @@ -383,7 +382,7 @@ class DigitalTwin(BECWidget, QWidget): assert cm_trx is not None, f"No cm_trx found for given stripe {cm_stripe}!" assert fm_trx is not None, f"No fm_trx found for given stripe {fm_stripe}!" - if self.beamline == "x01da": + if self.beamline == BeamlineId.X01DA: ot_es1_trz = self.input.ot_es1_trz.value() smpl_to_xrd = self.input.smpl_to_xrd.value() else: @@ -426,6 +425,57 @@ class DigitalTwin(BECWidget, QWidget): # logger.info(f'Config created: {config}') return config + def set_assistant_config(self, config: ConfigDict) -> None: + """ + Applies an assistant config to the input Qt widgets. + + Args: + config: Assistant configuration, as returned by + ``get_assistant_config``. The acceleration and angular + values are expected to be in SI units. + """ + self.input.energy.set_number(config["energy"]) + self.input.sldi_hacc.set_number(config["h_acc"] * 1e3) + self.input.sldi_vacc.set_number(config["v_acc"] * 1e3) + self.input.cm_pitch.set_number(-config["cm_pitch"] * 1e3) + self.input.cm_stripe.set_current_text(config["cm_stripe"]) + self.input.fm_stripe.set_current_text(config["fm_stripe"]) + self.input.mo1_mode.set_current_text(config["mo1_mode"]) + self.input.mo1_xtal.set_current_text(config["mo1_xtal"]) + + self.bragg_angle = config["mo1_bragg"] + + fm_rotx = -config["fm_rotx"] * 1e3 + + self.qy = config["fm_qy"] + fm_rotx_real = 2 * config["cm_pitch"] - config["fm_rotx"] + smpl = config["ot_es1_trz"] + config["es1man_trz"] + radius = self.core.calc_fm_bnd_radius(smpl, config["fm_qy"], config["fm_rotx"]) + fm_focx, fm_focy = self.core.calc_beamsize( + config["h_acc"], config["v_acc"], config["fm_stripe"], fm_rotx_real * 1e-3, radius, smpl + ) + if config["fm_qy"] is not None: + self.input.fm_focus.set_current_text("Defocused") + self.input.fm_focx.set_number(fm_focx) + self.input.fm_focy.set_number(fm_focy) + elif fm_focx < 0.08 and fm_focy < 0.08: + self.input.fm_focus.set_current_text("Focused") + else: + self.input.fm_focus.set_current_text("Manual") + self.input.fm_rotx_ideal.setValue(fm_rotx) + + if self.beamline == BeamlineId.X01DA: + self.input.ot_es1_trz.set_number(config["ot_es1_trz"]) + if config["smpl_to_xrd"] is not None: + self.input.smpl_to_xrd.set_number(config["smpl_to_xrd"]) + else: + table = self.core.smpl_pos_to_table(config["ot_es1_trz"]) + self.input.table.set_current_text(table) + + self.input.es1man_trz.set_number(config["es1man_trz"]) + + self.calc_assistant(identifier="init") + def get_reality_config(self) -> ConfigDict: """ Assembles the digital twin config based on the real axis positions. @@ -451,7 +501,7 @@ class DigitalTwin(BECWidget, QWidget): fm_rotx_real = 2 * cm_pitch - fm_rotx es1man_trz = self.dev.es1man_trz.read(cached=True)["es1man_trz"]["value"] - if self.beamline == "x01da": + if self.beamline == BeamlineId.X01DA: ot_es1_trz = self.dev.ot_es1_trz.read(cached=True)["ot_es1_trz"]["value"] ot_es2_trz = self.dev.ot_es2_trz.read(cached=True)["ot_es2_trz"]["value"] smpl_to_xrd = ot_es2_trz - ot_es1_trz - es1man_trz + 32 @@ -519,7 +569,7 @@ class DigitalTwin(BECWidget, QWidget): self.mover.fm_rotx.set_feedback(fm_rotx) self.mover.fm_roty.set_feedback(self.dev.fm_roty.read(cached=True)["fm_roty"]["value"]) self.mover.fm_rotz.set_feedback(self.dev.fm_rotz.read(cached=True)["fm_rotz"]["value"]) - if self.beamline == "x01da": + if self.beamline == BeamlineId.X01DA: self.mover.sl2_centery.set_feedback( self.dev.sl2_centery.read(cached=True)["sl2_centery"]["value"] ) @@ -527,7 +577,7 @@ class DigitalTwin(BECWidget, QWidget): self.dev.sl2_gapy.read(cached=True)["sl2_gapy"]["value"] ) self.mover.bm2_try.set_feedback(self.dev.bm2_try.read(cached=True)["bm2_try"]["value"]) - if self.beamline == "x01da": + if self.beamline == BeamlineId.X01DA: self.mover.ot_try.set_feedback(self.dev.ot_try.read(cached=True)["ot_try"]["value"]) self.mover.ot_rotx.set_feedback(self.dev.ot_rotx.read(cached=True)["ot_rotx"]["value"]) self.mover.ot_es1_trz.set_feedback(ot_es1_trz) @@ -568,7 +618,7 @@ class DigitalTwin(BECWidget, QWidget): pos["fm_rotx"] = self.dev.fm_rotx.read(cached=True)["fm_rotx"]["value"] pos["fm_bnd_radius"] = self.dev.fm_bnd_radius.read(cached=True)["fm_bnd_radius"]["value"] pos["es1man_trz"] = self.dev.es1man_trz.read(cached=True)["es1man_trz"]["value"] - if self.beamline == "x01da": + if self.beamline == BeamlineId.X01DA: pos["ot_es1_trz"] = self.dev.ot_es1_trz.read(cached=True)["ot_es1_trz"]["value"] pos["ot_es2_trz"] = self.dev.ot_es2_trz.read(cached=True)["ot_es2_trz"]["value"] pos["smpl_to_xrd"] = pos["ot_es2_trz"] - pos["ot_es1_trz"] - pos["es1man_trz"] + 32 @@ -598,7 +648,7 @@ class DigitalTwin(BECWidget, QWidget): fm_rotx_real = 2 * pos["cm_rotx"] - pos["fm_rotx"] self.input.fm_rotx.set_number(fm_rotx_real) - if self.beamline == "x01da": + if self.beamline == BeamlineId.X01DA: self.input.ot_es1_trz.set_number(pos["ot_es1_trz"]) self.input.smpl_to_xrd.set_number(pos["smpl_to_xrd"]) else: @@ -768,7 +818,7 @@ class DigitalTwin(BECWidget, QWidget): @SafeSlot() def open_edge_selector(self, *_): match self.beamline: - case "x01da": + case BeamlineId.X01DA: dlg = EdgeSelector(self, llim=X01DA_E_MIN, hlim=X01DA_E_MAX) case "x10da": dlg = EdgeSelector(self, llim=X10DA_E_MIN, hlim=X10DA_E_MAX) @@ -858,7 +908,7 @@ class DigitalTwin(BECWidget, QWidget): Calculates the positions for the axes based on the assistant values """ config = self.get_assistant_config() - out = self.core.calc_positions(self.beamline, config) + out = self.core.calc_positions(config) out = self.core.apply_offsets(out, nested_config=True) self.mover.sldi_gapx.set_target(out["sldi_gapx"]["value"]) @@ -879,11 +929,11 @@ class DigitalTwin(BECWidget, QWidget): self.mover.fm_rotx.set_target(out["fm_rotx"]["value"]) self.mover.fm_roty.set_target(out["fm_roty"]["value"]) self.mover.fm_rotz.set_target(out["fm_rotz"]["value"]) - if self.beamline == "x01da": + if self.beamline == BeamlineId.X01DA: self.mover.sl2_centery.set_target(out["sl2_centery"]["value"]) self.mover.sl2_gapy.set_target(out["sl2_gapy"]["value"]) self.mover.bm2_try.set_target(out["bm2_try"]["value"]) - if self.beamline == "x01da": + if self.beamline == BeamlineId.X01DA: self.mover.ot_try.set_target(out["ot_try"]["value"]) self.mover.ot_rotx.set_target(out["ot_rotx"]["value"]) self.mover.ot_es1_trz.set_target(out["ot_es1_trz"]["value"]) @@ -942,7 +992,7 @@ class DigitalTwin(BECWidget, QWidget): ) fm_stripe = self.input.fm_stripe.currentText() es1man_trz = self.input.es1man_trz.value() - if self.beamline == "x01da": + if self.beamline == BeamlineId.X01DA: ot_es1_trz = self.input.ot_es1_trz.value() else: table = self.input.table.currentText() diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index 02066bf..aaae858 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -2,9 +2,13 @@ The dialog behind the schedule widget's "Add..."/"Edit..." buttons. Rather than asking the operator to remember and type -`scans.xas_simple_scan(12000, 14000, 2, 10)`-style commands, this presents: +`scans.xas_simple_scan(12000, 14000, 2, 10)`-style commands, this presents +a dropdown of item types; picking one swaps in that item's own form below +the dropdown (a `QStackedWidget` page per item, kept in the same order as +the dropdown so a combo index also works as a stack index - see +`_add_page`). The available items are: -- a "Scan" tab: BEC's own `bec_widgets` `ScanControl` widget, embedded +- "ScanControl": BEC's own `bec_widgets` `ScanControl` widget, embedded as-is - scan selection, its live-generated per-scan argument form, docs tooltips, metadata, "recall last scan parameters", all of it. Reusing it instead of a plugin-owned reimplementation means this stays @@ -13,31 +17,40 @@ Rather than asking the operator to remember and type GUI. `ScanControl.button_run_scan` ("Start") is hidden here: this dialog only ever wants the configured scan name/args/kwargs, never an immediate submission - see `_collect_scan_result`. -- a "Move" tab: pick a device and a target value/relative flag; -- a "Digital Twin" tab: the beamline-alignment `DigitalTwin` widget, - embedded the same way as ScanControl. Instead of submitting anything - itself, OK captures a *snapshot* of `DigitalTwin.get_assistant_config()` - and stores it - execution later calls `move_all_axes(...)` with that - frozen config, so editing the (possibly separately open) Digital Twin - widget afterwards never affects an already-added schedule item, exactly - like a Scan item's captured args/kwargs aren't affected by reopening +- "Move": pick a device and a target value/relative flag. +- "Digital Twin": the beamline-alignment `DigitalTwin` widget, embedded + the same way as ScanControl. Instead of submitting anything itself, OK + captures a *snapshot* of `DigitalTwin.get_assistant_config()` and stores + it - execution later calls `move_all_axes(...)` with that frozen + config, so editing the (possibly separately open) Digital Twin widget + afterwards never affects an already-added schedule item, exactly like a + Scan item's captured args/kwargs aren't affected by reopening ScanControl elsewhere. See `_collect_digital_twin_result`. -- an "Other" tab: a free-text field for anything else (including RPC - calls to other widgets), plus a couple of beamline-specific quick-fill - forms (ionization chamber gas mix, reference foil). +- "Absorber", "Ionization Chamber", "Reference foil changer", "Auto-Gain": + beamline-specific quick-fill forms. Each has its own `_collect_*_result` + that either builds a command straight from the form fields or raises + `ValueError` with a message explaining what's missing or invalid - + `_on_accept` catches that and shows it in a message box, rather than + silently doing nothing the way the old "Generate command" buttons used + to. Each also has a `_prefill_*_form` so "Edit..." can reselect the + exact same field values, not just show the generated command as text. +- "Other": a free-text field for anything else (including RPC calls to + other widgets); also the fallback shown, pre-filled with the raw + command, for any saved item this dialog can't reconstruct into a form + (see `_apply_initial`). -Whichever tab is used, the dialog's only output is the same kind of plain -command string the executor already knows how to run - this dialog adds a -friendlier way to *build* that string, it doesn't change what happens with -it afterwards. `kind`/`form_state` are carried along purely so "Edit..." -can reopen the dialog pre-filled instead of asking the user to start over -- except for the Digital Twin tab, where "Edit..." currently falls back to -showing the generated command as read/write text on the "Other" tab rather -than reloading the captured config back into DigitalTwin's input fields; -see the note on `_apply_initial`. +Whichever item is selected, the dialog's only output is the same kind of +plain command string the executor already knows how to run - this dialog +adds a friendlier way to *build* that string, it doesn't change what +happens with it afterwards. `kind`/`form_state` are carried along purely +so "Edit..." can reopen the dialog pre-filled instead of asking the user +to start over - except for the Digital Twin item, where "Edit..." +currently falls back to showing the generated command as read/write text +on the "Other" page rather than reloading the captured config back into +DigitalTwin's input fields; see the note on `_apply_initial`. The Digital Twin item reuses `kind="move"` (not a new kind): it submits -through `scans.mv(...)`, exactly like the plain Move tab, so it should be +through `scans.mv(...)`, exactly like the plain Move item, so it should be treated the same way everywhere else in the plugin that branches on kind - not guard-protected, and counted under the "Movements" notification toggle. A `form_state["source"] = "digital_twin"` marker is only used @@ -63,13 +76,12 @@ from qtpy.QtWidgets import ( QDialogButtonBox, QDoubleSpinBox, QFormLayout, - QGroupBox, QHBoxLayout, QLabel, QLineEdit, QMessageBox, QScrollArea, - QTabWidget, + QStackedWidget, QVBoxLayout, QWidget, ) @@ -78,12 +90,10 @@ from .qt_widgets import MyButton logger = bec_logger.logger -# Tab indices, named instead of magic numbers now that there are four - -# see _collect_result()/_apply_initial(). -_TAB_SCAN = 0 -_TAB_MOVE = 1 -_TAB_DIGITAL_TWIN = 2 -_TAB_OTHER = 3 +# Beamlines that get the XAS scan control, the Digital Twin item, and the +# beamline-specific quick-fill items (Absorber, Ionization Chamber, +# Reference foil changer, Auto-Gain). +_XAS_BEAMLINES = ("x01da", "x10da") class ScheduleItemDialog(QDialog): @@ -107,9 +117,13 @@ class ScheduleItemDialog(QDialog): self._client = client self.beamline = beamline - if self.beamline in ["x01da", "x10da"]: + self._is_xas_beamline = self.beamline in _XAS_BEAMLINES + + if self._is_xas_beamline: logger.info(f"Loading bl-specific modules for beamline {self.beamline}") - from ....bec_ipython_client.plugins.digital_twin_core.digital_twin_core import DigitalTwinCore + from ....bec_ipython_client.plugins.digital_twin_core.digital_twin_core import ( + DigitalTwinCore, + ) from ..digital_twin.digital_twin import DigitalTwin from ..edge_selector import EdgeSelector from ..scan_control_xas.scan_control_xas import ScanControlXAS @@ -120,14 +134,38 @@ class ScheduleItemDialog(QDialog): self.ScanControlXAS = ScanControlXAS layout = QVBoxLayout(self) - self.tabs = QTabWidget() - layout.addWidget(self.tabs) - self._build_scan_tab() - self._build_move_tab() - if self.beamline in ["x01da", "x10da"]: - self._build_digital_twin_tab() - self._build_custom_tab() + self.item_combo = QComboBox() + layout.addWidget(self.item_combo) + + self.stack = QStackedWidget() + layout.addWidget(self.stack) + + self._build_scan_page() + self._build_move_page() + if self._is_xas_beamline: + self._build_digital_twin_page() + self._build_abs_page() + self._build_ic_page() + self._build_reffoil_page() + self._build_auto_gain_page() + self._build_other_page() + + self.item_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) + + # Dispatch table keyed by the dropdown item's data (see + # _add_page) - one place to register a new item type instead of + # scattering per-item checks through _collect_result(). + self._collectors = { + "scan": self._collect_scan_result, + "move": self._collect_move_result, + "digital_twin": self._collect_digital_twin_result, + "abs": self._collect_abs_result, + "ic": self._collect_ic_result, + "reffoil": self._collect_reffoil_result, + "auto_gain": self._collect_auto_gain_result, + "other": self._collect_custom_result, + } buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttons.button(QDialogButtonBox.Ok).setText("Add") @@ -145,23 +183,42 @@ class ScheduleItemDialog(QDialog): self._apply_initial(initial or {}) # ------------------------------------------------------------------ # - # Scan tab - embeds BEC's own ScanControl widget + # Dropdown/page plumbing # ------------------------------------------------------------------ # - def _build_scan_tab(self): - tab = QWidget() - layout = QVBoxLayout(tab) + def _add_page(self, key: str, label: str, widget: QWidget): + # The combo and the stack are always appended to together, so a + # combo index doubles as a stack index - no separate key->index + # map needed. `key` is what _collect_result()/_apply_initial() + # dispatch on. + self.item_combo.addItem(label, key) + self.stack.addWidget(widget) + + def _select_page(self, key: str) -> bool: + """Switch the dropdown to `key`'s page; False if that item isn't available.""" + idx = self.item_combo.findData(key) + if idx < 0: + return False + self.item_combo.setCurrentIndex(idx) + return True + + # ------------------------------------------------------------------ # + # ScanControl - embeds BEC's own ScanControl widget + # ------------------------------------------------------------------ # + def _build_scan_page(self): + page = QWidget() + layout = QVBoxLayout(page) # client=None resolves to the same process-wide BEC client # (bec_dispatcher.client) our own widget uses - no second Redis # connection is opened. - if self.beamline in ["x01da", "x10da"]: - self.scan_control = self.ScanControlXAS(parent=tab, client=self._client) + if self._is_xas_beamline: + self.scan_control = self.ScanControlXAS(parent=page, client=self._client) else: - self.scan_control = ScanControl(parent=tab, client=self._client) + self.scan_control = ScanControl(parent=page, client=self._client) self.scan_control.button_run_scan.hide() layout.addWidget(self.scan_control) - self.tabs.addTab(tab, "Scan") + self._add_page("scan", "ScanControl", page) def _collect_scan_result(self) -> dict: # Same call ScanControl.run_scan() makes before actually @@ -183,7 +240,7 @@ class ScheduleItemDialog(QDialog): "form_state": {"scan_name": scan_name, "args": args, "kwargs": kwargs}, } - def _prefill_scan_tab(self, scan_name: str, args: list, kwargs: dict): + def _prefill_scan_page(self, scan_name: str, args: list, kwargs: dict): # ScanControl restores parameters for a scan from its own config # cache (see `ScanControl.restore_scan_parameters`); pre-loading # that cache before switching to the scan reuses that mechanism @@ -195,15 +252,14 @@ class ScheduleItemDialog(QDialog): self.scan_control.restore_scan_parameters(scan_name) # ------------------------------------------------------------------ # - # Move tab + # Move # ------------------------------------------------------------------ # - def _build_move_tab(self): - tab = QWidget() - form = QFormLayout(tab) + def _build_move_page(self): + page = QWidget() + form = QFormLayout(page) form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) self.move_device_combo = DeviceComboBox(self, device_filter=[BECDeviceFilter.POSITIONER]) - form.addRow("Device", self.move_device_combo) self.move_value_spin = QDoubleSpinBox() @@ -214,13 +270,14 @@ class ScheduleItemDialog(QDialog): self.move_device_combo.currentIndexChanged.connect(self._adjust_spinbox) - self.tabs.addTab(tab, "Move") + self._add_page("move", "Move", page) def _adjust_spinbox(self, _) -> None: - prec = self._dev[self.move_device_combo.currentText()].precision - units = self._dev[self.move_device_combo.currentText()].egu() - ll = self._dev[self.move_device_combo.currentText()].low_limit - hl = self._dev[self.move_device_combo.currentText()].high_limit + device = self._dev[self.move_device_combo.currentText()] + prec = device.precision + units = device.egu() + ll = device.low_limit + hl = device.high_limit self.move_value_spin.setDecimals(prec) self.move_value_spin.setSuffix(f" {units}") @@ -245,12 +302,19 @@ class ScheduleItemDialog(QDialog): "form_state": {"device_name": device_name, "value": value, "relative": relative}, } + def _prefill_move_page(self, state: dict): + idx = self.move_device_combo.findText(state.get("device_name", "")) + if idx >= 0: + self.move_device_combo.setCurrentIndex(idx) + self.move_value_spin.setValue(float(state.get("value", 0.0))) + self.move_relative_check.setChecked(bool(state.get("relative", False))) + # ------------------------------------------------------------------ # - # Digital Twin tab - embeds the beamline-alignment DigitalTwin widget + # Digital Twin - embeds the beamline-alignment DigitalTwin widget # ------------------------------------------------------------------ # - def _build_digital_twin_tab(self): - tab = QWidget() - outer = QVBoxLayout(tab) + def _build_digital_twin_page(self): + page = QWidget() + outer = QVBoxLayout(page) # DigitalTwin defaults to a large fixed size (it's normally its # own top-level window) - wrap it in a scroll area so this dialog @@ -275,20 +339,15 @@ class ScheduleItemDialog(QDialog): hint.setStyleSheet("color: gray;") outer.addWidget(hint) - self.tabs.addTab(tab, "Digital Twin") + self._add_page("digital_twin", "Digital Twin", page) def _collect_digital_twin_result(self) -> dict: + # A frozen snapshot of the configured targets, not a live handle - + # editing the Digital Twin widget afterwards must not affect an + # already-added schedule item (see module docstring). config = self.digital_twin.get_assistant_config() - # beamline = self.digital_twin.beamline - - # # Init the class when the scheduler is opened - # digital_twin = DigitalTwinCore() - # # The command below would then execute the movement - # digital_twin.move_with_config(config) - cmd = f"digital_twin.move_with_config({config})" - - return {"command": f"{cmd}", "kind": "custom", "form_state": {"text": cmd}} + return {"command": cmd, "kind": "custom", "form_state": {"text": cmd, "config": config}} def _cleanup_digital_twin(self, *_): digital_twin = getattr(self, "digital_twin", None) @@ -303,124 +362,91 @@ class ScheduleItemDialog(QDialog): except Exception: # pylint: disable=broad-except logger.exception("Failed to clean up the embedded Digital Twin widget.") + def _prefill_digital_twin_page(self, state: dict): + config = state["config"] + self.digital_twin.set_assistant_config(config) + # ------------------------------------------------------------------ # - # Custom tab + # Absorber # ------------------------------------------------------------------ # - def _build_custom_tab(self): - tab = QWidget() - layout = QVBoxLayout(tab) - layout.addWidget( - QLabel( - "Free-form command, evaluated against `scans` and `dev` - use this for " - "anything the other tabs don't cover, e.g. an RPC call to another widget." - ) + def _build_abs_page(self): + if "abs" not in self._dev: + return + page = QWidget() + form = QFormLayout(page) + form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) + + self.abs_selector = QComboBox() + self.abs_selector.addItems(["Open", "Force open", "Close"]) + form.addRow("Action", self.abs_selector) + + self._add_page("abs", "Absorber", page) + + def _collect_abs_result(self) -> dict: + action = self.abs_selector.currentText() + suffix = {"Open": "open()", "Force open": "open(force=True)", "Close": "close()"}.get( + action ) - self.custom_edit = QLineEdit() - # TODO Change to a different placeholder text - self.custom_edit.setPlaceholderText("scans.xas_simple_scan(12000, 14000, 2, 10)") - layout.addWidget(self.custom_edit) - - if self.beamline in ["x01da", "x10da"]: - abs_form = self._create_abs_form() - if abs_form is not None: - layout.addWidget(abs_form) - - ic_form = self._create_ionization_chamber_form() - if ic_form is not None: - layout.addWidget(ic_form) - - reffoil_form = self._create_reffoil_form() - if reffoil_form is not None: - layout.addWidget(reffoil_form) - - auto_gain_form = self._create_auto_gain_form() - if auto_gain_form is not None: - layout.addWidget(auto_gain_form) - - layout.addStretch(1) - self.tabs.addTab(tab, "Other") - - def _create_abs_form(self): - if "abs" in self._dev: - abs_group = QGroupBox("Frontend Absorber") - layout = QVBoxLayout(abs_group) - form = QFormLayout() - layout.addLayout(form) - form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) - self.abs_selector = QComboBox() - self.abs_selector.addItems(["Open", "Force open", "Close"]) - form.addRow("Action", self.abs_selector) - - button_layout = QHBoxLayout() - generate_cmd = MyButton("Generate command", "default") - button_layout.addWidget(generate_cmd) - button_layout.addStretch(1) - layout.addLayout(button_layout) - - generate_cmd.clicked.connect(self._generate_abs_command) - - return abs_group - return None - - def _generate_abs_command(self): - match self.abs_selector.currentText(): - case "Open": - suffix = "open()" - case "Force open": - suffix = "open(force=True)" - case "Close": - suffix = "close()" + if suffix is None: + raise ValueError("Select an absorber action.") cmd = f"dev.abs.{suffix}" - self.custom_edit.setText(cmd) + return { + "command": cmd, + "kind": "custom", + "form_state": {"text": cmd, "source": "abs", "action": action}, + } - def _create_ionization_chamber_form(self): - if all(key in self._dev for key in ("ic0", "ic1", "ic2")): - ic_group = QGroupBox("Ionization chamber filling") - layout = QVBoxLayout(ic_group) - form = QFormLayout() - layout.addLayout(form) - form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) - self.ic_selector = QComboBox() - self.ic_selector.addItems(["IC0", "IC1", "IC2"]) - gases = ["He", "N2", "Ar", "Kr"] - self.gas1 = QComboBox() - self.gas2 = QComboBox() - self.gas1.addItems(gases) - self.gas2.addItems(gases) - self.conc1 = QDoubleSpinBox() - self.conc2 = QDoubleSpinBox() - for conc in [self.conc1, self.conc2]: - conc.setDecimals(0) - conc.setSuffix(" %") - conc.setMinimum(0) - conc.setMaximum(100) - conc.setSingleStep(1) - self.pressure = QDoubleSpinBox() - self.pressure.setDecimals(3) - self.pressure.setSuffix(" bar abs") - self.pressure.setMinimum(1) - self.pressure.setMaximum(3) - self.pressure.setSingleStep(0.1) + def _prefill_abs_form(self, state: dict): + idx = self.abs_selector.findText(state.get("action", "")) + if idx >= 0: + self.abs_selector.setCurrentIndex(idx) - form.addRow("Ionization chamber", self.ic_selector) - form.addRow("Gas 1", self.gas1) - form.addRow("Concentration 1", self.conc1) - form.addRow("Gas 2", self.gas2) - form.addRow("Concentration 2", self.conc2) - form.addRow("Pressure", self.pressure) + # ------------------------------------------------------------------ # + # Ionization chamber + # ------------------------------------------------------------------ # + def _build_ic_page(self): + if not all(key in self._dev for key in ("ic0", "ic1", "ic2")): + return + page = QWidget() + form = QFormLayout(page) + form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) - button_layout = QHBoxLayout() - generate_cmd = MyButton("Generate command", "default") - button_layout.addWidget(generate_cmd) - button_layout.addStretch(1) - layout.addLayout(button_layout) + self.ic_selector = QComboBox() + self.ic_selector.addItems(["IC0", "IC1", "IC2"]) - self.conc1.valueChanged.connect(self._equalize_ic_conc) - self.conc2.valueChanged.connect(self._equalize_ic_conc) - generate_cmd.clicked.connect(self._generate_ic_command) + gases = ["He", "N2", "Ar", "Kr"] + self.gas1 = QComboBox() + self.gas2 = QComboBox() + self.gas1.addItems(gases) + self.gas2.addItems(gases) - return ic_group - return None + self.conc1 = QDoubleSpinBox() + self.conc2 = QDoubleSpinBox() + for conc in (self.conc1, self.conc2): + conc.setDecimals(0) + conc.setSuffix(" %") + conc.setMinimum(0) + conc.setMaximum(100) + conc.setSingleStep(1) + + self.pressure = QDoubleSpinBox() + self.pressure.setDecimals(3) + self.pressure.setSuffix(" bar abs") + self.pressure.setMinimum(1) + self.pressure.setMaximum(3) + self.pressure.setSingleStep(0.1) + + form.addRow("Ionization chamber", self.ic_selector) + form.addRow("Gas 1", self.gas1) + form.addRow("Concentration 1", self.conc1) + form.addRow("Gas 2", self.gas2) + form.addRow("Concentration 2", self.conc2) + form.addRow("Pressure", self.pressure) + + self.conc1.valueChanged.connect(self._equalize_ic_conc) + self.conc2.valueChanged.connect(self._equalize_ic_conc) + + self._add_page("ic", "Ionization Chamber", page) def _equalize_ic_conc(self, new_val): if self.conc1.value() == new_val: # conc1 was changed @@ -428,66 +454,98 @@ class ScheduleItemDialog(QDialog): else: self.conc1.setValue(100 - new_val) - def _generate_ic_command(self): - if self.conc1.value() + self.conc2.value() != 100: - return - match self.ic_selector.currentText(): - case "IC0": - ic = "ic0" - case "IC1": - ic = "ic1" - case "IC2": - ic = "ic2" + def _collect_ic_result(self) -> dict: + total = self.conc1.value() + self.conc2.value() + if total != 100: + raise ValueError(f"Gas concentrations must add up to 100% (currently {total:.0f}%).") + chamber = self.ic_selector.currentText() + ic = {"IC0": "ic0", "IC1": "ic1", "IC2": "ic2"}[chamber] cmd = ( f"dev.{ic}.fill(" - + f"gas1='{self.gas1.currentText()}', conc1={self.conc1.value()}, " - + f"gas2='{self.gas2.currentText()}', conc2={self.conc2.value()}, " - + f"pressure={self.pressure.value()}, wait=True)" + f"gas1='{self.gas1.currentText()}', conc1={self.conc1.value()}, " + f"gas2='{self.gas2.currentText()}', conc2={self.conc2.value()}, " + f"pressure={self.pressure.value()}, wait=True)" ) - self.custom_edit.setText(cmd) + return { + "command": cmd, + "kind": "custom", + "form_state": { + "text": cmd, + "source": "ic", + "chamber": chamber, + "gas1": self.gas1.currentText(), + "conc1": self.conc1.value(), + "gas2": self.gas2.currentText(), + "conc2": self.conc2.value(), + "pressure": self.pressure.value(), + }, + } - def _create_reffoil_form(self): - if "reffoilchanger" in self._dev: - reffoil_group = QGroupBox("Reference foil changer") - layout = QVBoxLayout(reffoil_group) - form = QFormLayout() - layout.addLayout(form) - form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) - self.reffoil_selector = QComboBox() - available_foils = self._dev.reffoilchanger.get_all_foils() - self.reffoil_selector.addItems(available_foils) + def _prefill_ic_form(self, state: dict): + idx = self.ic_selector.findText(state.get("chamber", "")) + if idx >= 0: + self.ic_selector.setCurrentIndex(idx) + idx = self.gas1.findText(state.get("gas1", "")) + if idx >= 0: + self.gas1.setCurrentIndex(idx) + idx = self.gas2.findText(state.get("gas2", "")) + if idx >= 0: + self.gas2.setCurrentIndex(idx) + # Set conc2 last: conc1's valueChanged->_equalize_ic_conc would + # otherwise immediately overwrite it. + self.conc1.setValue(float(state.get("conc1", 0))) + self.conc2.setValue(float(state.get("conc2", 0))) + self.pressure.setValue(float(state.get("pressure", self.pressure.minimum()))) - form.addRow("Reference foil", self.reffoil_selector) + # ------------------------------------------------------------------ # + # Reference foil changer + # ------------------------------------------------------------------ # + def _build_reffoil_page(self): + if "reffoilchanger" not in self._dev: + return + page = QWidget() + form = QFormLayout(page) + form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) - button_layout = QHBoxLayout() - generate_cmd = MyButton("Generate command", "default") - button_layout.addWidget(generate_cmd) - button_layout.addStretch(1) - layout.addLayout(button_layout) + self.reffoil_selector = QComboBox() + self.reffoil_selector.addItems(self._dev.reffoilchanger.get_all_foils()) + form.addRow("Reference foil", self.reffoil_selector) - generate_cmd.clicked.connect(self._generate_reffoil_command) + self._add_page("reffoil", "Reference foil changer", page) - return reffoil_group - return None + def _collect_reffoil_result(self) -> dict: + foil = self.reffoil_selector.currentText() + if not foil: + raise ValueError("Select a reference foil.") + cmd = f"dev.reffoilchanger.insert(ref='{foil}', wait=True)" + return { + "command": cmd, + "kind": "custom", + "form_state": {"text": cmd, "source": "reffoil", "foil": foil}, + } - def _generate_reffoil_command(self): - cmd = f"dev.reffoilchanger.insert(ref='{self.reffoil_selector.currentText()}', wait=True)" - self.custom_edit.setText(cmd) + def _prefill_reffoil_form(self, state: dict): + idx = self.reffoil_selector.findText(state.get("foil", "")) + if idx >= 0: + self.reffoil_selector.setCurrentIndex(idx) - def _create_auto_gain_form(self): - auto_gain_group = QGroupBox("Auto Gain") - layout = QVBoxLayout(auto_gain_group) + # ------------------------------------------------------------------ # + # Auto-Gain + # ------------------------------------------------------------------ # + def _build_auto_gain_page(self): + page = QWidget() + layout = QVBoxLayout(page) edge_selector_layout = QHBoxLayout() - edge_selector_label = QLabel("Absorption edge:") + edge_selector_layout.addWidget(QLabel("Absorption edge:")) self.edge_selector_button = MyButton("Choose", "default") self.edge_label = QLabel("No edge selected") - edge_selector_layout.addWidget(edge_selector_label) edge_selector_layout.addWidget(self.edge_selector_button) edge_selector_layout.addWidget(self.edge_label) edge_selector_layout.addStretch() self.edge_element = None self.edge_edge = None + self.edge_energy = None layout.addLayout(edge_selector_layout) @@ -506,49 +564,90 @@ class ScheduleItemDialog(QDialog): self.pips_check = QCheckBox("") form.addRow("PIPS", self.pips_check) - button_layout = QHBoxLayout() - generate_cmd = MyButton("Generate command", "default") - button_layout.addWidget(generate_cmd) - button_layout.addStretch(1) - layout.addLayout(button_layout) - self.edge_selector_button.clicked.connect(self._update_edge) - generate_cmd.clicked.connect(self._generate_auto_gain_command) - return auto_gain_group + self._add_page("auto_gain", "Auto-Gain", page) def _update_edge(self, *_): - match self.beamline: - case "x01da": - dlg = self.EdgeSelector(self) - case "x10da": - dlg = self.EdgeSelector(self) - case _: - dlg = self.EdgeSelector(self) + # NOTE: EdgeSelector is currently the same dialog for every + # beamline; this hook is here so a beamline-specific selector can + # be swapped in later without touching callers. + dlg = self.EdgeSelector(self) if dlg.exec_(): + self.edge_element = dlg.selected_element + self.edge_edge = dlg.selected_edge self.edge_energy = dlg.selected_energy self.edge_label.setText( f"{dlg.selected_element}, {dlg.selected_edge}-edge, {dlg.selected_energy:0.1f} eV" ) - self.edge_element = dlg.selected_element - self.edge_edge = dlg.selected_edge - def _generate_auto_gain_command(self): - if self.edge_edge is None or self.edge_element is None: - return - amplifiers = [] - for amp, name in [ + def _collect_auto_gain_result(self) -> dict: + if self.edge_element is None or self.edge_edge is None: + raise ValueError("Choose an absorption edge first.") + amplifier_checks = [ (self.ic0_check, "ic0"), (self.ic1_check, "ic1"), (self.ic2_check, "ic2"), (self.pips_check, "pips"), - ]: - if amp.isChecked(): - amplifiers.append(name) - if amplifiers == []: - return - cmd = f"auto_gain.start(element={self.edge_element}, edge={self.edge_edge}, {amplifiers}, comp_ring_current=True)" - self.custom_edit.setText(cmd) + ] + amplifiers = [name for check, name in amplifier_checks if check.isChecked()] + if not amplifiers: + raise ValueError("Select at least one amplifier for auto gain.") + cmd = ( + f"auto_gain.start(element={self.edge_element}, edge={self.edge_edge}, " + f"{amplifiers}, comp_ring_current=True)" + ) + return { + "command": cmd, + "kind": "custom", + "form_state": { + "text": cmd, + "source": "auto_gain", + "element": self.edge_element, + "edge": self.edge_edge, + "energy": self.edge_energy, + "ic0": self.ic0_check.isChecked(), + "ic1": self.ic1_check.isChecked(), + "ic2": self.ic2_check.isChecked(), + "pips": self.pips_check.isChecked(), + }, + } + + def _prefill_auto_gain_form(self, state: dict): + element = state.get("element") + edge = state.get("edge") + if element is not None and edge is not None: + self.edge_element = element + self.edge_edge = edge + self.edge_energy = state.get("energy") + if self.edge_energy is not None: + self.edge_label.setText(f"{element}, {edge}-edge, {self.edge_energy:0.1f} eV") + else: + self.edge_label.setText(f"{element}, {edge}-edge") + self.ic0_check.setChecked(bool(state.get("ic0", False))) + self.ic1_check.setChecked(bool(state.get("ic1", False))) + self.ic2_check.setChecked(bool(state.get("ic2", False))) + self.pips_check.setChecked(bool(state.get("pips", False))) + + # ------------------------------------------------------------------ # + # Other + # ------------------------------------------------------------------ # + def _build_other_page(self): + page = QWidget() + layout = QVBoxLayout(page) + layout.addWidget( + QLabel( + "Free-form command, evaluated against `scans` and `dev` - use this for " + "anything the other items don't cover, e.g. an RPC call to another widget." + ) + ) + self.custom_edit = QLineEdit() + # TODO Change to a different placeholder text + self.custom_edit.setPlaceholderText("scans.xas_simple_scan(12000, 14000, 2, 10)") + layout.addWidget(self.custom_edit) + layout.addStretch(1) + + self._add_page("other", "Other", page) def _collect_custom_result(self) -> dict: text = self.custom_edit.text().strip() @@ -562,34 +661,33 @@ class ScheduleItemDialog(QDialog): def _apply_initial(self, initial: dict): kind = initial.get("kind") state = initial.get("form_state") or {} + source = state.get("source") if kind == "scan" and state.get("scan_name"): - self._prefill_scan_tab( + self._prefill_scan_page( state["scan_name"], state.get("args") or [], state.get("kwargs") or {} ) - self.tabs.setCurrentIndex(_TAB_SCAN) - elif kind == "move" and state.get("source") == "digital_twin": - # Reloading a captured config back into DigitalTwin's own input - # fields would need inverting get_assistant_config()'s unit - # conversions and mode branching (fm_focus, mo1_mode, ...) - # field-by-field - not implemented yet. Fall back to showing - # the generated command as read/write text instead of silently - # dropping the captured config; the "Add" (=Ok) button below - # will just resubmit that text unchanged unless it's edited. - self.custom_edit.setText(initial.get("command", "")) - self.tabs.setCurrentIndex(_TAB_OTHER) + self._select_page("scan") + elif kind == "custom" and source == "digital_twin": + self._prefill_digital_twin_page(state) + self._select_page("digital_twin") elif kind == "move" and state.get("device_name"): - idx = self.move_device_combo.findText(state["device_name"]) - if idx >= 0: - self.move_device_combo.setCurrentIndex(idx) - self.move_value_spin.setValue(float(state.get("value", 0.0))) - self.move_relative_check.setChecked(bool(state.get("relative", False))) - self.tabs.setCurrentIndex(_TAB_MOVE) + self._prefill_move_page(state) + self._select_page("move") + elif kind == "custom" and source == "abs" and self._select_page("abs"): + self._prefill_abs_form(state) + elif kind == "custom" and source == "ic" and self._select_page("ic"): + self._prefill_ic_form(state) + elif kind == "custom" and source == "reffoil" and self._select_page("reffoil"): + self._prefill_reffoil_form(state) + elif kind == "custom" and source == "auto_gain" and self._select_page("auto_gain"): + self._prefill_auto_gain_form(state) elif initial.get("command"): - # "custom" kind, or a legacy/unrecognized item - fall back to - # showing the raw command text as-is. + # "custom" kind with no (recognized/available) source, or a + # legacy/unrecognized item - fall back to showing the raw + # command text as-is. self.custom_edit.setText(state.get("text", initial["command"])) - self.tabs.setCurrentIndex(_TAB_OTHER) + self._select_page("other") else: logger.warning(f"Unknown kind: {kind}") @@ -597,20 +695,17 @@ class ScheduleItemDialog(QDialog): try: result = self._collect_result() except ValueError as exc: - QMessageBox.warning(self, "Missing input", str(exc)) + QMessageBox.warning(self, "Can't build command", str(exc)) return self._result = result self.accept() def _collect_result(self) -> dict: - current = self.tabs.currentIndex() - if current == _TAB_SCAN: - return self._collect_scan_result() - if current == _TAB_MOVE: - return self._collect_move_result() - if current == _TAB_DIGITAL_TWIN: - return self._collect_digital_twin_result() - return self._collect_custom_result() + key = self.item_combo.currentData() + handler = self._collectors.get(key) + if handler is None: + raise ValueError(f"Unknown item type: {key!r}") + return handler() def result(self) -> dict: """Valid after `exec_()` returns `QDialog.Accepted`.""" From 0cb3b4ce57b989328f8552984df00e741c50d6a3 Mon Sep 17 00:00:00 2001 From: hitz_s Date: Wed, 9 Sep 2026 15:14:18 +0200 Subject: [PATCH 25/56] wip --- .../digital_twin_core/motion_worker.py | 3 +- .../widgets/scheduler/item_dialog.py | 68 ++++-------------- .../widgets/scheduler/schedule_item.py | 1 + .../widgets/scheduler/scheduler.py | 71 +++++++++++++++---- debye_bec/devices/absorber.py | 10 ++- debye_bec/devices/eh_shutter.py | 10 ++- debye_bec/devices/op_shutter.py | 10 ++- 7 files changed, 95 insertions(+), 78 deletions(-) diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py index dfbadf5..7b1ac6e 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py @@ -223,8 +223,7 @@ class MotionWorker: self.motor = alias if abs_closed: if self.dev.abs.status.get() == ABS_STATUS.OPEN: - status = self.dev.abs.close() - status.wait(timeout=5) + status = self.dev.abs.close(wait=True) if surveyed_axes is not None: for surv_ax in surveyed_axes: surv_ax["name"] = surv_ax["device"].dotted_name diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index aaae858..2a6ceff 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -1,60 +1,5 @@ """ The dialog behind the schedule widget's "Add..."/"Edit..." buttons. - -Rather than asking the operator to remember and type -`scans.xas_simple_scan(12000, 14000, 2, 10)`-style commands, this presents -a dropdown of item types; picking one swaps in that item's own form below -the dropdown (a `QStackedWidget` page per item, kept in the same order as -the dropdown so a combo index also works as a stack index - see -`_add_page`). The available items are: - -- "ScanControl": BEC's own `bec_widgets` `ScanControl` widget, embedded - as-is - scan selection, its live-generated per-scan argument form, - docs tooltips, metadata, "recall last scan parameters", all of it. - Reusing it instead of a plugin-owned reimplementation means this stays - in sync with BEC's scan capabilities for free, and looks/behaves exactly - like the scan controls an operator already knows from elsewhere in the - GUI. `ScanControl.button_run_scan` ("Start") is hidden here: this dialog - only ever wants the configured scan name/args/kwargs, never an - immediate submission - see `_collect_scan_result`. -- "Move": pick a device and a target value/relative flag. -- "Digital Twin": the beamline-alignment `DigitalTwin` widget, embedded - the same way as ScanControl. Instead of submitting anything itself, OK - captures a *snapshot* of `DigitalTwin.get_assistant_config()` and stores - it - execution later calls `move_all_axes(...)` with that frozen - config, so editing the (possibly separately open) Digital Twin widget - afterwards never affects an already-added schedule item, exactly like a - Scan item's captured args/kwargs aren't affected by reopening - ScanControl elsewhere. See `_collect_digital_twin_result`. -- "Absorber", "Ionization Chamber", "Reference foil changer", "Auto-Gain": - beamline-specific quick-fill forms. Each has its own `_collect_*_result` - that either builds a command straight from the form fields or raises - `ValueError` with a message explaining what's missing or invalid - - `_on_accept` catches that and shows it in a message box, rather than - silently doing nothing the way the old "Generate command" buttons used - to. Each also has a `_prefill_*_form` so "Edit..." can reselect the - exact same field values, not just show the generated command as text. -- "Other": a free-text field for anything else (including RPC calls to - other widgets); also the fallback shown, pre-filled with the raw - command, for any saved item this dialog can't reconstruct into a form - (see `_apply_initial`). - -Whichever item is selected, the dialog's only output is the same kind of -plain command string the executor already knows how to run - this dialog -adds a friendlier way to *build* that string, it doesn't change what -happens with it afterwards. `kind`/`form_state` are carried along purely -so "Edit..." can reopen the dialog pre-filled instead of asking the user -to start over - except for the Digital Twin item, where "Edit..." -currently falls back to showing the generated command as read/write text -on the "Other" page rather than reloading the captured config back into -DigitalTwin's input fields; see the note on `_apply_initial`. - -The Digital Twin item reuses `kind="move"` (not a new kind): it submits -through `scans.mv(...)`, exactly like the plain Move item, so it should be -treated the same way everywhere else in the plugin that branches on kind - -not guard-protected, and counted under the "Movements" notification -toggle. A `form_state["source"] = "digital_twin"` marker is only used -locally, by this dialog, to tell the two apart when reopening for Edit. """ from __future__ import annotations @@ -153,6 +98,13 @@ class ScheduleItemDialog(QDialog): self.item_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) + # Shared across all items (not per-page), since it's a property + # of the schedule item, not of any one form. + self.pause_on_failure_check = QCheckBox("Pause schedule if item execution fails") + layout.addWidget(self.pause_on_failure_check) + + self.item_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) + # Dispatch table keyed by the dropdown item's data (see # _add_page) - one place to register a new item type instead of # scattering per-item checks through _collect_result(). @@ -659,6 +611,8 @@ class ScheduleItemDialog(QDialog): # pre-fill (edit mode) / result extraction # ------------------------------------------------------------------ # def _apply_initial(self, initial: dict): + self.pause_on_failure_check.setChecked(bool(initial.get("pause_on_failure", False))) + kind = initial.get("kind") state = initial.get("form_state") or {} source = state.get("source") @@ -705,7 +659,9 @@ class ScheduleItemDialog(QDialog): handler = self._collectors.get(key) if handler is None: raise ValueError(f"Unknown item type: {key!r}") - return handler() + result = handler() + result["pause_on_failure"] = self.pause_on_failure_check.isChecked() + return result def result(self) -> dict: """Valid after `exec_()` returns `QDialog.Accepted`.""" diff --git a/debye_bec/bec_widgets/widgets/scheduler/schedule_item.py b/debye_bec/bec_widgets/widgets/scheduler/schedule_item.py index b675094..f58fb07 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/schedule_item.py +++ b/debye_bec/bec_widgets/widgets/scheduler/schedule_item.py @@ -40,6 +40,7 @@ class ScheduleItem(BaseModel): # time - `kind`/`form_state` only drive the UI. kind: ScheduleItemKind = "custom" form_state: dict | None = None + pause_on_failure: bool # Bookkeeping used to reconnect to a submission that is still (or was) # in flight on the BEC scan/device server, after this widget has been diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 97e25a2..9ebaaf1 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -64,7 +64,9 @@ from .schedule_logic import index_of, pick_next_runnable, protected_prefix_lengt logger = bec_logger.logger _ACTIVE_QUEUE_STATES = ("PENDING", "RUNNING") -_ITEM_ID_ROLE = Qt.UserRole + 1 # QListWidgetItem data role used to map a row back to an item_id +_ITEM_ID_ROLE = ( + Qt.ItemDataRole.UserRole + 1 +) # QListWidgetItem data role used to map a row back to an item_id ICON_SIZE = 20 _ICON_MAP = { @@ -152,12 +154,15 @@ class Scheduler(BECWidget, QWidget): self.beamline = self.get_beamline() self.connector = self.client.connector - if self.beamline in ['x01da', 'x10da']: + if self.beamline in ["x01da", "x10da"]: logger.info( - 'Scheduler running at X01DA or X10DA, import and load digital twin and auto-gain' + "Scheduler running at X01DA or X10DA, import and load digital twin and auto-gain" ) - from ....bec_ipython_client.plugins.digital_twin_core.digital_twin_core import DigitalTwinCore from ....bec_ipython_client.plugins.auto_gain import AutoGain + from ....bec_ipython_client.plugins.digital_twin_core.digital_twin_core import ( + DigitalTwinCore, + ) + self.digital_twin = DigitalTwinCore() self.auto_gain = AutoGain() else: @@ -470,7 +475,18 @@ class Scheduler(BECWidget, QWidget): self.list_widget.clear() selected_row = None for row, item in enumerate(items): - text = f"{item.command}" + text = "" + if item.form_state is not None: + if item.command.startswith("scans.xas_simple_scan"): + text = ( + f"XAS simple scan from {item.form_state['kwargs']['start']} eV to " + + f"{item.form_state['kwargs']['stop']} eV, {item.form_state['kwargs']['scan_time']}" + + f" s per spectrum, measure {item.form_state['kwargs']['scan_duration']}s. " + + f"Comment: {item.form_state['kwargs']['metadata']['comment']}, " + + f"Sample Name: {item.form_state['kwargs']['metadata']['sample_name']}" + ) + if text == "": + text = f"{item.command}" if item.error: text += f" ({item.error.strip().splitlines()[-1]})" list_item = QListWidgetItem(text, self.list_widget) @@ -700,7 +716,7 @@ class Scheduler(BECWidget, QWidget): @SafeSlot() def _on_notifications_clicked(self): dialog = NotificationSettingsDialog(self.schedule.notifications, self.client, parent=self) - if dialog.exec_() != QDialog.Accepted: + if dialog.exec_() != QDialog.DialogCode.Accepted: return with self._lock: self.schedule.notifications = dialog.result_settings() @@ -736,7 +752,7 @@ class Scheduler(BECWidget, QWidget): def _on_guard_clicked(self): device_names = sorted(self.dev.keys()) dialog = GuardSettingsDialog(self.schedule.guard, device_names, parent=self) - if dialog.exec_() != QDialog.Accepted: + if dialog.exec_() != QDialog.DialogCode.Accepted: return with self._lock: self.schedule.guard = dialog.result_settings() @@ -775,15 +791,21 @@ class Scheduler(BECWidget, QWidget): # ---- UI-triggered edit actions ---- # @SafeSlot() def _on_add_clicked(self): - dialog = ScheduleItemDialog(self.scans, self.dev, parent=self, client=self.client, beamline=self.beamline) - if dialog.exec_() != QDialog.Accepted: + dialog = ScheduleItemDialog( + self.scans, self.dev, parent=self, client=self.client, beamline=self.beamline + ) + if dialog.exec_() != QDialog.DialogCode.Accepted: return result = dialog.result() with self._lock: idx = self._index_of_locked(self._selected_item_id) insert_at = None if idx is None else idx + 1 new_id = self.add_item( - result["command"], index=insert_at, kind=result["kind"], form_state=result["form_state"] + result["command"], + index=insert_at, + kind=result["kind"], + form_state=result["form_state"], + pause_on_failure=result["pause_on_failure"], ) self._selected_item_id = new_id self._refresh_ui() @@ -797,7 +819,12 @@ class Scheduler(BECWidget, QWidget): idx = self._index_of_locked(self._selected_item_id) item = self.schedule.items[idx] if idx is not None else None initial = ( - {"kind": item.kind, "command": item.command, "form_state": item.form_state} + { + "kind": item.kind, + "command": item.command, + "form_state": item.form_state, + "pause_on_failure": item.pause_on_failure, + } if item is not None else None ) @@ -809,7 +836,7 @@ class Scheduler(BECWidget, QWidget): dialog = ScheduleItemDialog( self.scans, self.dev, parent=self, initial=initial, client=self.client ) - if dialog.exec_() != QDialog.Accepted: + if dialog.exec_() != QDialog.DialogCode.Accepted: return result = dialog.result() try: @@ -818,6 +845,7 @@ class Scheduler(BECWidget, QWidget): result["command"], kind=result["kind"], form_state=result["form_state"], + pause_on_failure=result["pause_on_failure"], ) except RuntimeError as exc: QMessageBox.warning(self, "Cannot edit item", str(exc)) @@ -876,6 +904,7 @@ class Scheduler(BECWidget, QWidget): "command": item.command, "kind": item.kind, "form_state": dict(item.form_state) if item.form_state else None, + "pause_on_failure": item.pause_on_failure, } logger.info(f"Copied schedule item: {self._clipboard_item['command']}") self._update_buttons() @@ -900,6 +929,7 @@ class Scheduler(BECWidget, QWidget): index=insert_at, kind=self._clipboard_item["kind"], form_state=self._clipboard_item["form_state"], + pause_on_failure=self._clipboard_item["pause_on_failure"], ) self._selected_item_id = new_id self._refresh_ui() @@ -983,6 +1013,7 @@ class Scheduler(BECWidget, QWidget): index: int | None = None, kind: str = "custom", form_state: dict | None = None, + pause_on_failure: bool = False, ) -> str: """ RPC-exposed: insert a new, PENDING command into the schedule. @@ -1009,7 +1040,11 @@ class Scheduler(BECWidget, QWidget): with self._lock: protected = self._protected_prefix_length_locked() item = ScheduleItem( - item_id=str(uuid.uuid4()), command=command, kind=kind, form_state=form_state + item_id=str(uuid.uuid4()), + command=command, + kind=kind, + form_state=form_state, + pause_on_failure=pause_on_failure, ) if index is None or index >= len(self.schedule.items): self.schedule.items.append(item) @@ -1020,7 +1055,12 @@ class Scheduler(BECWidget, QWidget): return item.item_id def edit_item( - self, item_id: str, command: str, kind: str = "custom", form_state: dict | None = None + self, + item_id: str, + command: str, + kind: str = "custom", + form_state: dict | None = None, + pause_on_failure: bool = True, ): """ RPC-exposed: change the command of an item that has not started @@ -1041,6 +1081,7 @@ class Scheduler(BECWidget, QWidget): item.command = command item.kind = kind item.form_state = form_state + item.pause_on_failure = pause_on_failure self._persist_locked() self.schedule_changed.emit() @@ -1255,6 +1296,8 @@ class Scheduler(BECWidget, QWidget): item.status = ScheduleItemStatus.FAILED item.error = traceback.format_exc() logger.error(f"Schedule item failed: {item.command}\n{item.error}") + if item.pause_on_failure: + self._abort_requested = True finally: if not self._closing.is_set(): with self._lock: diff --git a/debye_bec/devices/absorber.py b/debye_bec/devices/absorber.py index 29c3c9f..f069962 100644 --- a/debye_bec/devices/absorber.py +++ b/debye_bec/devices/absorber.py @@ -75,7 +75,7 @@ class Absorber(PSIDeviceBase): # Wait for connection on all components, ensure IOC is connected self.wait_for_connection(all_signals=True, timeout=5) - def open(self, force: bool = False) -> DeviceStatus | None: + def open(self, force: bool = False, wait: bool = True) -> CompareStatus | None: """Open the Absorber Args: @@ -94,15 +94,21 @@ class Absorber(PSIDeviceBase): status.wait(timeout=TIMEOUT_FOR_PV) self.request.put(1) status = CompareStatus(self.status, STATUS.OPEN, timeout=self.timeout_for_move) + if wait: + status.wait(timeout=self.timeout_for_move) + return None return status else: return None - def close(self) -> DeviceStatus | None: + def close(self, wait: bool = True) -> CompareStatus | None: """Close the Absorber""" if self.status.get() == STATUS.OPEN: self.request.put(1) status = CompareStatus(self.status, STATUS.CLOSED, timeout=self.timeout_for_move) + if wait: + status.wait(timeout=self.timeout_for_move) + return None return status else: return None diff --git a/debye_bec/devices/eh_shutter.py b/debye_bec/devices/eh_shutter.py index 27b141e..ad9d30b 100644 --- a/debye_bec/devices/eh_shutter.py +++ b/debye_bec/devices/eh_shutter.py @@ -66,20 +66,26 @@ class EHPhotonShutter(PSIDeviceBase): # Wait for connection on all components, ensure IOC is connected self.wait_for_connection(all_signals=True, timeout=5) - def open(self) -> DeviceStatus | None: + def open(self, wait: bool = True) -> CompareStatus | None: """Open the Shutter""" if self.status.get() == STATUS.CLOSED: self.request_open.put(1) status = CompareStatus(self.status, STATUS.NOT_CLOSED, timeout=self.timeout_for_move) + if wait: + status.wait(timeout=self.timeout_for_move) + return None return status else: return None - def close(self) -> DeviceStatus | None: + def close(self, wait: bool = True) -> CompareStatus | None: """Close the Shutter""" if self.status.get() == STATUS.NOT_CLOSED: self.request_close.put(1) status = CompareStatus(self.status, STATUS.CLOSED, timeout=self.timeout_for_move) + if wait: + status.wait(timeout=self.timeout_for_move) + return None return status else: return None diff --git a/debye_bec/devices/op_shutter.py b/debye_bec/devices/op_shutter.py index 4f963ad..68b0a8d 100644 --- a/debye_bec/devices/op_shutter.py +++ b/debye_bec/devices/op_shutter.py @@ -71,7 +71,7 @@ class OPPhotonShutter(PSIDeviceBase): # Wait for connection on all components, ensure IOC is connected self.wait_for_connection(all_signals=True, timeout=5) - def open(self, force: bool = False) -> DeviceStatus | None: + def open(self, force: bool = False, wait: bool = True) -> CompareStatus | None: """Open the Shutter Args: @@ -92,15 +92,21 @@ class OPPhotonShutter(PSIDeviceBase): status.wait(timeout=TIMEOUT_FOR_PV) self.request_open.put(1) status = CompareStatus(self.status, STATUS.NOT_CLOSED, timeout=self.timeout_for_move) + if wait: + status.wait(timeout=self.timeout_for_move) + return None return status else: return None - def close(self) -> DeviceStatus | None: + def close(self, wait: bool = True) -> CompareStatus | None: """Close the Shutter""" if self.status.get() == STATUS.NOT_CLOSED: self.request_close.put(1) status = CompareStatus(self.status, STATUS.CLOSED, timeout=self.timeout_for_move) + if wait: + status.wait(timeout=self.timeout_for_move) + return None return status else: return None From f756d30ce33f78bfcd7fb7dba8908e06a3033500 Mon Sep 17 00:00:00 2001 From: x01da Date: Mon, 14 Sep 2026 08:08:44 +0200 Subject: [PATCH 26/56] bugfixes --- .../digital_twin_core/digital_twin_core.py | 5 +-- .../widgets/digital_twin/digital_twin.py | 2 +- .../widgets/scheduler/item_dialog.py | 13 ++++++-- .../widgets/scheduler/scheduler.py | 9 ++++-- debye_bec/devices/absorber.py | 30 ++++++++++------- debye_bec/devices/eh_shutter.py | 10 ++---- debye_bec/devices/op_shutter.py | 32 +++++++++++-------- 7 files changed, 62 insertions(+), 39 deletions(-) diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py index 243afa1..c89dbe0 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py @@ -73,7 +73,7 @@ class DigitalTwinCoreError(Exception): class DigitalTwinCore: - def __init__(self): + def __init__(self, load_offsets: bool = True): logger.info("This is the digital twin from the ipython client!") dev = builtins.__dict__.get("dev") bec = builtins.__dict__.get("bec") @@ -92,7 +92,8 @@ class DigitalTwinCore: case "x10da": self.offset_file = OFFSET_FILE_X10DA self.offsets = {} - self.load_offsets() + if load_offsets: + self.load_offsets() def _exclusive_group_key(self, motor: str): """Return (group_index, subgroup_index) for `motor`, or (None, None) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py index ea583c7..205d380 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py @@ -62,7 +62,7 @@ class DigitalTwin(BECWidget, QWidget): super().__init__(parent=parent, *arg, **kwargs) self.get_bec_shortcuts() - self.core = DigitalTwinCore() + self.core = DigitalTwinCore(load_offsets=False) # Offsets are loaded through GUI later self.beamline = self.core.beamline # Debugging, override beamline! diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index 2a6ceff..4a64828 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -299,7 +299,11 @@ class ScheduleItemDialog(QDialog): # already-added schedule item (see module docstring). config = self.digital_twin.get_assistant_config() cmd = f"digital_twin.move_with_config({config})" - return {"command": cmd, "kind": "custom", "form_state": {"text": cmd, "config": config}} + return { + "command": cmd, + "kind": "custom", + "form_state": {"text": cmd, "source": "digital_twin", "config": config}, + } def _cleanup_digital_twin(self, *_): digital_twin = getattr(self, "digital_twin", None) @@ -516,6 +520,8 @@ class ScheduleItemDialog(QDialog): self.pips_check = QCheckBox("") form.addRow("PIPS", self.pips_check) + layout.addStretch() + self.edge_selector_button.clicked.connect(self._update_edge) self._add_page("auto_gain", "Auto-Gain", page) @@ -613,6 +619,8 @@ class ScheduleItemDialog(QDialog): def _apply_initial(self, initial: dict): self.pause_on_failure_check.setChecked(bool(initial.get("pause_on_failure", False))) + logger.info(f"Got initial: {initial}") + kind = initial.get("kind") state = initial.get("form_state") or {} source = state.get("source") @@ -622,9 +630,8 @@ class ScheduleItemDialog(QDialog): state["scan_name"], state.get("args") or [], state.get("kwargs") or {} ) self._select_page("scan") - elif kind == "custom" and source == "digital_twin": + elif kind == "custom" and source == "digital_twin" and self._select_page("digital_twin"): self._prefill_digital_twin_page(state) - self._select_page("digital_twin") elif kind == "move" and state.get("device_name"): self._prefill_move_page(state) self._select_page("move") diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 9ebaaf1..6b947ef 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -812,7 +812,7 @@ class Scheduler(BECWidget, QWidget): self._update_buttons() @SafeSlot() - def _on_edit_clicked(self, _): + def _on_edit_clicked(self, *_): if self._selected_item_id is None: return with self._lock: @@ -834,7 +834,12 @@ class Scheduler(BECWidget, QWidget): logger.info(f"Initial: {initial}") dialog = ScheduleItemDialog( - self.scans, self.dev, parent=self, initial=initial, client=self.client + self.scans, + self.dev, + parent=self, + initial=initial, + client=self.client, + beamline=self.beamline, ) if dialog.exec_() != QDialog.DialogCode.Accepted: return diff --git a/debye_bec/devices/absorber.py b/debye_bec/devices/absorber.py index f069962..5f90a42 100644 --- a/debye_bec/devices/absorber.py +++ b/debye_bec/devices/absorber.py @@ -7,13 +7,14 @@ from typing import TYPE_CHECKING from ophyd import Component as Cpt from ophyd import EpicsSignal, EpicsSignalRO -from ophyd_devices import CompareStatus, DeviceStatus +from ophyd_devices import CompareStatus from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase from .utils.bl_status_enum import BlStatus if TYPE_CHECKING: from bec_lib.devicemanager import ScanInfo + from bec_server.device_server.device_server import DeviceManagerDS TIMEOUT_FOR_PV = 5 @@ -68,8 +69,19 @@ class Absorber(PSIDeviceBase): ) close4bl = Cpt(EpicsSignal, suffix="CLOSE4BL", kind="config", doc="Beamline enable") - def __init__(self, *, name: str, prefix: str = "", scan_info: ScanInfo | None = None, **kwargs): - super().__init__(name=name, prefix=prefix, scan_info=scan_info, **kwargs) + def __init__( + self, + *, + name: str, + prefix: str = "", + scan_info: ScanInfo | None = None, + device_manager: DeviceManagerDS | None = None, + **kwargs, + ): + super().__init__( + name=name, prefix=prefix, scan_info=scan_info, device_manager=device_manager, **kwargs + ) + self.device_manager = device_manager self.timeout_for_move = 10 # Wait for connection on all components, ensure IOC is connected @@ -82,12 +94,10 @@ class Absorber(PSIDeviceBase): force(bool): If needed, set bl status to enable and bl enable to ENABLE, defaults to False """ - if force and self.device_manager.devices.get("bl_status", None) is None: - raise AbsorberError("bl_status is not in device config, thus cannot use force = True") if self.status.get() == STATUS.CLOSED: if force: - if self.device_manager.bl_status.get() == BlStatus.OFFLINE: - status = self.device_manager.bl_status.put(BlStatus.ATTENDED) + if self.device_manager.devices.bl_status.get() == BlStatus.OFFLINE: + status = self.device_manager.devices.bl_status.put(BlStatus.ATTENDED) status.wait(timeout=TIMEOUT_FOR_PV) if self.close4bl.get() == BL_ENABLE.DISABLE: status = self.close4bl.set(BL_ENABLE.ENABLE) @@ -98,8 +108,7 @@ class Absorber(PSIDeviceBase): status.wait(timeout=self.timeout_for_move) return None return status - else: - return None + return None def close(self, wait: bool = True) -> CompareStatus | None: """Close the Absorber""" @@ -110,5 +119,4 @@ class Absorber(PSIDeviceBase): status.wait(timeout=self.timeout_for_move) return None return status - else: - return None + return None diff --git a/debye_bec/devices/eh_shutter.py b/debye_bec/devices/eh_shutter.py index ad9d30b..f6b1de5 100644 --- a/debye_bec/devices/eh_shutter.py +++ b/debye_bec/devices/eh_shutter.py @@ -7,11 +7,9 @@ from typing import TYPE_CHECKING from ophyd import Component as Cpt from ophyd import EpicsSignal, EpicsSignalRO -from ophyd_devices import CompareStatus, DeviceStatus +from ophyd_devices import CompareStatus from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase -from .utils.bl_status_enum import BlStatus - if TYPE_CHECKING: from bec_lib.devicemanager import ScanInfo @@ -75,8 +73,7 @@ class EHPhotonShutter(PSIDeviceBase): status.wait(timeout=self.timeout_for_move) return None return status - else: - return None + return None def close(self, wait: bool = True) -> CompareStatus | None: """Close the Shutter""" @@ -87,5 +84,4 @@ class EHPhotonShutter(PSIDeviceBase): status.wait(timeout=self.timeout_for_move) return None return status - else: - return None + return None diff --git a/debye_bec/devices/op_shutter.py b/debye_bec/devices/op_shutter.py index 68b0a8d..2d71a75 100644 --- a/debye_bec/devices/op_shutter.py +++ b/debye_bec/devices/op_shutter.py @@ -7,13 +7,14 @@ from typing import TYPE_CHECKING from ophyd import Component as Cpt from ophyd import EpicsSignal, EpicsSignalRO -from ophyd_devices import CompareStatus, DeviceStatus +from ophyd_devices import CompareStatus from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase from .utils.bl_status_enum import BlStatus if TYPE_CHECKING: from bec_lib.devicemanager import ScanInfo + from bec_server.device_server.device_server import DeviceManagerDS TIMEOUT_FOR_PV = 5 @@ -64,8 +65,19 @@ class OPPhotonShutter(PSIDeviceBase): ) close4bl = Cpt(EpicsSignal, suffix="FE-BST1:CLOSE4BL", kind="config", doc="Beamline enable") - def __init__(self, *, name: str, prefix: str = "", scan_info: ScanInfo | None = None, **kwargs): - super().__init__(name=name, prefix=prefix, scan_info=scan_info, **kwargs) + def __init__( + self, + *, + name: str, + prefix: str = "", + scan_info: ScanInfo | None = None, + device_manager: DeviceManagerDS | None = None, + **kwargs, + ): + super().__init__( + name=name, prefix=prefix, scan_info=scan_info, device_manager=device_manager, **kwargs + ) + self.device_manager = device_manager self.timeout_for_move = 10 # Wait for connection on all components, ensure IOC is connected @@ -78,14 +90,10 @@ class OPPhotonShutter(PSIDeviceBase): force(bool): If needed, set bl status to enable and bl enable to ENABLE, defaults to False """ - if force and self.device_manager.devices.get("bl_status", None) is None: - raise OPPhotonShutterError( - "bl_status is not in device config, thus cannot use force = True" - ) if self.status.get() == STATUS.CLOSED: if force: - if self.device_manager.bl_status.get() == BlStatus.OFFLINE: - status = self.device_manager.bl_status.put(BlStatus.ATTENDED) + if self.device_manager.devices.bl_status.get() == BlStatus.OFFLINE: + status = self.device_manager.devices.bl_status.put(BlStatus.ATTENDED) status.wait(timeout=TIMEOUT_FOR_PV) if self.close4bl.get() == BL_ENABLE.DISABLE: status = self.close4bl.set(BL_ENABLE.ENABLE) @@ -96,8 +104,7 @@ class OPPhotonShutter(PSIDeviceBase): status.wait(timeout=self.timeout_for_move) return None return status - else: - return None + return None def close(self, wait: bool = True) -> CompareStatus | None: """Close the Shutter""" @@ -108,5 +115,4 @@ class OPPhotonShutter(PSIDeviceBase): status.wait(timeout=self.timeout_for_move) return None return status - else: - return None + return None From 318979a5d53d00ef7edc868de3676417bc96ca9d Mon Sep 17 00:00:00 2001 From: x01da Date: Mon, 14 Sep 2026 14:21:52 +0200 Subject: [PATCH 27/56] wip --- .../bec_ipython_client/plugins/auto_gain.py | 32 +++++++++------- .../digital_twin_core/digital_twin_core.py | 2 +- .../widgets/digital_twin/digital_twin.py | 37 ++++++++++++++----- .../scan_control_xas/scan_control_xas.py | 2 + .../widgets/scheduler/scheduler.py | 23 +++++++++++- .../ionization_chambers/ionization_chamber.py | 14 +++---- 6 files changed, 77 insertions(+), 33 deletions(-) diff --git a/debye_bec/bec_ipython_client/plugins/auto_gain.py b/debye_bec/bec_ipython_client/plugins/auto_gain.py index 35b8d14..45fd085 100644 --- a/debye_bec/bec_ipython_client/plugins/auto_gain.py +++ b/debye_bec/bec_ipython_client/plugins/auto_gain.py @@ -158,25 +158,27 @@ class AutoGain: logger.info("All checks done, start preparing for measurement") # Get initial monochromator position and velocity - init_pos = self.dev.mo1_bragg.position.get() - init_vel = self.dev.mo1_bragg.velocity.get() + init_pos = self.dev.mo1_bragg.position + init_vel = self.dev.mo1_bragg.velocity logger.info(f"Move mono to start of {emin} eV") self.dev.mo1_bragg.velocity.put(MONO_VELOCITY) - status = CompareStatus(self.dev.mo1_bragg.velocity, MONO_VELOCITY) - status.wait(TIMEOUT_PUT_PV) + # TODO, subscribe to the signal, not the property! + # status = CompareStatus(self.dev.mo1_bragg.velocity, MONO_VELOCITY) + # status.wait(TIMEOUT_PUT_PV) status = self.dev.mo1_bragg.move(emin) status.wait(TIMEOUT_MONO_MOVE) # Set NIDAQ to max mode self.dev.nidaq.epics_mode.put(EpicsMode.MAX) - status = CompareStatus(self.dev.nidaq.epics_mode, EpicsMode.MAX) - status.wait(timeout=TIMEOUT_PUT_PV) + # status = CompareStatus(self.dev.nidaq.epics_mode, EpicsMode.MAX) + # status.wait(timeout=TIMEOUT_PUT_PV) # Set gains to lowest gain for name, ch in active_channels.items(): lowest_gain = AVAILABLE_GAINS[0] - ch["self.dev"].set_gain(lowest_gain) + logger.info(f"Setting gain to {lowest_gain:.0e}".replace("+", "")) + ch["self.dev"].set_gain(f"{lowest_gain:.0e}".replace("+", "")) ch["gain"] = lowest_gain remeasure = True @@ -256,7 +258,9 @@ class AutoGain: bisect_right(AVAILABLE_GAINS, gain_ref * 100) - 1 ] for gname in group_names: - active_channels[gname]["dev"].set_gain(next_gain) + active_channels[gname]["self.dev"].set_gain( + f"{next_gain:.0e}".replace("+", "") + ) active_channels[gname]["gain"] = next_gain logger.info(f"Setting gain of {label} to {next_gain:.0e} and remeasure") remeasure = True @@ -270,7 +274,7 @@ class AutoGain: default=min(AVAILABLE_GAINS), ) for gname in group_names: - active_channels[gname]["dev"].set_gain(gain) + active_channels[gname]["self.dev"].set_gain(gain) active_channels[gname]["gain"] = gain logger.info(f"Calculated final gain for {label} of {gain:.0e}") @@ -281,15 +285,15 @@ class AutoGain: # Reset NIDAQ to mean mode self.dev.nidaq.epics_mode.put(EpicsMode.MEAN) - status = CompareStatus(self.dev.nidaq.epics_mode, EpicsMode.MEAN) - status.wait(timeout=TIMEOUT_PUT_PV) + # status = CompareStatus(self.dev.nidaq.epics_mode, EpicsMode.MEAN) + # status.wait(timeout=TIMEOUT_PUT_PV) # Wait for mono to move to initial position and reset velocity status = self.dev.mo1_bragg.move(init_pos) status.wait(TIMEOUT_MONO_MOVE) - self.dev.mo1_bragg.velocity.put(init_vel) - status = CompareStatus(self.dev.mo1_bragg.velocity, init_vel) - status.wait(timeout=TIMEOUT_PUT_PV) + self.dev.mo1_bragg.velocity.put(init_vel) # TODO: Fix, not using property! + # status = CompareStatus(self.dev.mo1_bragg.velocity, init_vel) + # status.wait(timeout=TIMEOUT_PUT_PV) def _get_ring_current(self) -> float: ring_current = 0 diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py index c89dbe0..6e7a772 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py @@ -622,7 +622,7 @@ class DigitalTwinCore: Args: smpl(float): Sample position in mm fm_qy(None|float): FM qy value - fm_rotx(float: FM rotx position + fm_rotx(float: FM rotx position in rad Returns: float: bending radius in m diff --git a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py index 205d380..c612c92 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py @@ -133,6 +133,7 @@ class DigitalTwin(BECWidget, QWidget): self.input.fm_focy.value_changed_connect(self.calc_assistant) if self.beamline == BeamlineId.X01DA: self.input.ot_es1_trz.value_changed_connect(self.calc_assistant) + self.input.smpl_to_xrd.value_changed_connect(self.calc_assistant) else: self.input.table.activated_connect(self.calc_assistant) self.input.es1man_trz.value_changed_connect(self.calc_assistant) @@ -348,6 +349,8 @@ class DigitalTwin(BECWidget, QWidget): self.calc_fm_ideal_pitch() case "es1man_trz": self.calc_fm_ideal_pitch() + case "smpl_to_xrd": + self.calc_fm_ideal_pitch() self.calc_positions() self.calc_assistant_sideview() self.calc_assistant_surfaces() @@ -396,7 +399,7 @@ class DigitalTwin(BECWidget, QWidget): "energy": self.input.energy.value(), "h_acc": self.input.sldi_hacc.value(), "v_acc": self.input.sldi_vacc.value(), - "cm_pitch": -self.input.cm_pitch.value(), + "cm_pitch": -np.float64(self.input.cm_pitch.value()), "cm_stripe": cm_stripe, "cm_trx": cm_trx, "mo1_mode": self.input.mo1_mode.currentText(), @@ -428,16 +431,26 @@ class DigitalTwin(BECWidget, QWidget): def set_assistant_config(self, config: ConfigDict) -> None: """ Applies an assistant config to the input Qt widgets. + Config must be without offsets! Args: config: Assistant configuration, as returned by ``get_assistant_config``. The acceleration and angular values are expected to be in SI units. """ + + config = ConfigDict(config) # Important: Copy dict to not change the original + + # Convert to mrad units! + config["h_acc"] *= 1e3 + config["v_acc"] *= 1e3 + config["cm_pitch"] *= -1e3 + config["fm_rotx"] *= 1e3 + self.input.energy.set_number(config["energy"]) - self.input.sldi_hacc.set_number(config["h_acc"] * 1e3) - self.input.sldi_vacc.set_number(config["v_acc"] * 1e3) - self.input.cm_pitch.set_number(-config["cm_pitch"] * 1e3) + self.input.sldi_hacc.set_number(config["h_acc"]) + self.input.sldi_vacc.set_number(config["v_acc"]) + self.input.cm_pitch.set_number(config["cm_pitch"]) self.input.cm_stripe.set_current_text(config["cm_stripe"]) self.input.fm_stripe.set_current_text(config["fm_stripe"]) self.input.mo1_mode.set_current_text(config["mo1_mode"]) @@ -445,14 +458,19 @@ class DigitalTwin(BECWidget, QWidget): self.bragg_angle = config["mo1_bragg"] - fm_rotx = -config["fm_rotx"] * 1e3 + fm_rotx = -config["fm_rotx"] self.qy = config["fm_qy"] - fm_rotx_real = 2 * config["cm_pitch"] - config["fm_rotx"] + smpl = config["ot_es1_trz"] + config["es1man_trz"] - radius = self.core.calc_fm_bnd_radius(smpl, config["fm_qy"], config["fm_rotx"]) + radius = self.core.calc_fm_bnd_radius(smpl, config["fm_qy"], config["fm_rotx"] * 1e-3) fm_focx, fm_focy = self.core.calc_beamsize( - config["h_acc"], config["v_acc"], config["fm_stripe"], fm_rotx_real * 1e-3, radius, smpl + config["h_acc"] * 1e-3, + config["v_acc"] * 1e-3, + config["fm_stripe"], + -fm_rotx * 1e-3, + radius, + smpl, ) if config["fm_qy"] is not None: self.input.fm_focus.set_current_text("Defocused") @@ -462,7 +480,7 @@ class DigitalTwin(BECWidget, QWidget): self.input.fm_focus.set_current_text("Focused") else: self.input.fm_focus.set_current_text("Manual") - self.input.fm_rotx_ideal.setValue(fm_rotx) + self.input.fm_rotx_ideal.setValue(fm_rotx * 1e-3) if self.beamline == BeamlineId.X01DA: self.input.ot_es1_trz.set_number(config["ot_es1_trz"]) @@ -646,6 +664,7 @@ class DigitalTwin(BECWidget, QWidget): fm_stripe = self.core.fm_trx_to_stripe(-pos["fm_trx"]) self.input.fm_stripe.set_current_text(fm_stripe) fm_rotx_real = 2 * pos["cm_rotx"] - pos["fm_rotx"] + logger.info(f"In adapt reality, fm_rotx_real is {fm_rotx_real}") self.input.fm_rotx.set_number(fm_rotx_real) if self.beamline == BeamlineId.X01DA: diff --git a/debye_bec/bec_widgets/widgets/scan_control_xas/scan_control_xas.py b/debye_bec/bec_widgets/widgets/scan_control_xas/scan_control_xas.py index 995ea76..daa5772 100644 --- a/debye_bec/bec_widgets/widgets/scan_control_xas/scan_control_xas.py +++ b/debye_bec/bec_widgets/widgets/scan_control_xas/scan_control_xas.py @@ -37,6 +37,8 @@ from ..edge_selector import EdgeSelector logger = bec_logger.logger ALLOWED_SCANS = [ + "acquire", + "line_scan", "xas_simple_scan", "xas_simple_scan_with_xrd", "xas_advanced_scan", diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 6b947ef..00c5b8b 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -10,6 +10,7 @@ or finished cannot. from __future__ import annotations import json +import re import sys import threading import time @@ -485,6 +486,23 @@ class Scheduler(BECWidget, QWidget): + f"Comment: {item.form_state['kwargs']['metadata']['comment']}, " + f"Sample Name: {item.form_state['kwargs']['metadata']['sample_name']}" ) + elif re.match(r"^dev\..*\.move", item.command): + if item.form_state["relative"]: + text = ( + f"Move {item.form_state['device_name']} by {item.form_state['value']}" + ) + else: + text = ( + f"Move {item.form_state['device_name']} to {item.form_state['value']}" + ) + elif item.command.startswith("dev.ic"): + text = ( + f"Fill {item.form_state['chamber']} with {item.form_state['conc1']} % " + + f"{item.form_state['gas1']} and {item.form_state['conc2']} % " + + f"{item.form_state['gas2']} to {item.form_state['pressure']} bar" + ) + elif item.command.startswith("dev.reffoilchanger"): + text = f"Insert {item.form_state['ref']} reference foil" if text == "": text = f"{item.command}" if item.error: @@ -831,8 +849,6 @@ class Scheduler(BECWidget, QWidget): if initial is None: return - logger.info(f"Initial: {initial}") - dialog = ScheduleItemDialog( self.scans, self.dev, @@ -1072,6 +1088,9 @@ class Scheduler(BECWidget, QWidget): yet. Raises `RuntimeError` for an item that is already running/finished. """ + + logger.info(f"edit item with form_state: {form_state}") + command = command.strip() if not command: raise ValueError("command must not be empty") diff --git a/debye_bec/devices/ionization_chambers/ionization_chamber.py b/debye_bec/devices/ionization_chambers/ionization_chamber.py index 9d2bd2c..92a560d 100644 --- a/debye_bec/devices/ionization_chambers/ionization_chamber.py +++ b/debye_bec/devices/ionization_chambers/ionization_chamber.py @@ -120,13 +120,13 @@ class IonizationChamber0(PSIDeviceBase): self.timeout_for_pvwait = 2.5 super().__init__(name=name, prefix=prefix, scan_info=scan_info, **kwargs) - @typechecked - def set_gain(self, gain: Literal["1e6", "1e7", "5e7", "1e8", "1e9"]) -> None: + def set_gain(self, gain: float | str) -> None: """Configure the gain setting of the specified channel Args: gain (Literal['1e6', '1e7', '5e7', '1e8', '1e9']) : Desired gain """ + # TODO: Fix docstring if self.amp.cOnOff.get() == AmplifierEnable.OFF: status = CompareStatus(self.amp.cOnOff, AmplifierEnable.ON) @@ -135,15 +135,15 @@ class IonizationChamber0(PSIDeviceBase): status.wait(self.timeout_for_pvwait) match gain: - case "1e6": + case "1e6" | 1e6: self.amp.cGain_ENUM.put(AmplifierGain.G1E6) - case "1e7": + case "1e7" | 1e7: self.amp.cGain_ENUM.put(AmplifierGain.G1E7) - case "5e7": + case "5e7" | 5e7: self.amp.cGain_ENUM.put(AmplifierGain.G5E7) - case "1e8": + case "1e8" | 1e8: self.amp.cGain_ENUM.put(AmplifierGain.G1E8) - case "1e9": + case "1e9" | 1e9: self.amp.cGain_ENUM.put(AmplifierGain.G1E9) def set_filter( From 3fb4895ce48a01676f58d4fa21e6f64387981ac1 Mon Sep 17 00:00:00 2001 From: x01da Date: Tue, 15 Sep 2026 08:54:34 +0200 Subject: [PATCH 28/56] wip --- .../bec_ipython_client/plugins/auto_gain.py | 273 ++++++++++-------- .../widgets/scheduler/scheduler.py | 16 +- .../ionization_chambers/ionization_chamber.py | 37 ++- .../ionization_chamber_enums.py | 9 + debye_bec/devices/nidaq/nidaq_enums.py | 3 +- 5 files changed, 193 insertions(+), 145 deletions(-) diff --git a/debye_bec/bec_ipython_client/plugins/auto_gain.py b/debye_bec/bec_ipython_client/plugins/auto_gain.py index 45fd085..bfc2957 100644 --- a/debye_bec/bec_ipython_client/plugins/auto_gain.py +++ b/debye_bec/bec_ipython_client/plugins/auto_gain.py @@ -6,7 +6,6 @@ from bisect import bisect_right import xraydb from bec_lib import bec_logger -from ophyd_devices import CompareStatus from ...devices.absorber import STATUS as ABS_STATUS from ...devices.eh_shutter import STATUS as EH_PH_STATUS @@ -19,7 +18,7 @@ logger = bec_logger.logger EMIN = -100 EMAX = 200 -MIN_RING_CURRENT = 5 # Minimum ring current to use auto-gain +MIN_RING_CURRENT = -1 # Minimum ring current to use auto-gain NOMINAL_RING_CURRENT = 400 # Nominal ring current of SLS2 TIMEOUT_PUT_PV = 5 # Timeout to set a PV @@ -34,6 +33,22 @@ FULL_SCALE_V = 10.0 # NIDAQ AI full-scale range SAFETY_MARGIN = 0.9 # keep max signal under 90% of full scale +def wait_for_signal(signal, value, timeout: float) -> None: + """Function to wait for a signal to reach a certain value. + + Args: + signal: Signal to read from + value: Target value the signal should reach + timeout(float): Timeout in seconds before a TimeoutError is raised + + """ + start = time.time() + while time.time() - start < timeout: + if signal.get() == value: + return + raise TimeoutError(f"Signal {signal} did not reach value {value} within {timeout} seconds.") + + class AutoGainError(Exception): """AutoGain specific error""" @@ -155,145 +170,151 @@ class AutoGain: if ch["self.dev"].gmes.status.get() != 1: raise AutoGainError(f"Gas filling of ionization chamber {name} is not OK") - logger.info("All checks done, start preparing for measurement") - # Get initial monochromator position and velocity init_pos = self.dev.mo1_bragg.position - init_vel = self.dev.mo1_bragg.velocity + init_vel = self.dev.mo1_bragg.velocity.get() - logger.info(f"Move mono to start of {emin} eV") - self.dev.mo1_bragg.velocity.put(MONO_VELOCITY) - # TODO, subscribe to the signal, not the property! - # status = CompareStatus(self.dev.mo1_bragg.velocity, MONO_VELOCITY) - # status.wait(TIMEOUT_PUT_PV) - status = self.dev.mo1_bragg.move(emin) - status.wait(TIMEOUT_MONO_MOVE) - - # Set NIDAQ to max mode - self.dev.nidaq.epics_mode.put(EpicsMode.MAX) - # status = CompareStatus(self.dev.nidaq.epics_mode, EpicsMode.MAX) - # status.wait(timeout=TIMEOUT_PUT_PV) - - # Set gains to lowest gain + # Get initial gains for name, ch in active_channels.items(): - lowest_gain = AVAILABLE_GAINS[0] - logger.info(f"Setting gain to {lowest_gain:.0e}".replace("+", "")) - ch["self.dev"].set_gain(f"{lowest_gain:.0e}".replace("+", "")) - ch["gain"] = lowest_gain + ch["init_gain"] = ch["self.dev"].amp.cGain_ENUM.get() - remeasure = True - logger.info(f"Start measurement from {emin} eV to {emax} eV") - while remeasure: - # Create temporary storage for max signal per channel - data = {name: 0 for name in active_channels} + logger.info("All checks done, start preparing for measurement") - # Measure current ring current - ring_current_1 = self._get_ring_current() - logger.info(f"Ring current right before measurement: {ring_current_1} mA") - if ring_current_1 == 0: - raise AutoGainError("Ring current dropped to 0 mA right before measurement") - - # Scan range, recording the peak NIDAQ signal per channel - self.dev.mo1_bragg.move(emax).wait(timeout=TIMEOUT_MONO_MOVE) - status.wait(TIMEOUT_MONO_MOVE) - for name, ch in active_channels.items(): - data[name] = max(data[name], ch["signal"].get()) - - # Rest max values of NIDAQ signals - self.dev.nidaq.epics_max_reset.put(True) - time.sleep(0.1) - - # Measure current ring current again - ring_current_2 = self._get_ring_current() - logger.info(f"Ring current right after measurement: {ring_current_2} mA") - if ring_current_2 == 0: - raise AutoGainError("Ring current dropped to 0 mA during measurement") - ring_current = (ring_current_1 + ring_current_2) / 2 - - # Move back to first monochromator position + try: + logger.info(f"Move mono to start of {emin} eV") + self.dev.mo1_bragg.velocity.put(MONO_VELOCITY) + wait_for_signal(self.dev.mo1_bragg.velocity, MONO_VELOCITY, timeout=TIMEOUT_PUT_PV) status = self.dev.mo1_bragg.move(emin) - - # Choose gain per channel based on the max signal recorded during the scan - remeasure = False - processed = set() - - for name, ch in active_channels.items(): - if name in processed: - continue - - # ic0/ic1 must always end up with the same gain -> treat whichever of - # them are present (one or both) as a single group for this decision - if name in LINKED_CHANNELS: - group_names = [n for n in LINKED_CHANNELS if n in active_channels] - else: - group_names = [name] - - group_signals = [] - for gname in group_names: - gsig = data[gname] - logger.info(f"Raw signal for device {gname} is {gsig} V") - if comp_ring_current: - gsig = gsig * NOMINAL_RING_CURRENT / ring_current - logger.info(f"Compensate for ring current, new raw signal is {gsig} V") - group_signals.append(gsig) - - # worst case: the weakest signal drives "need more gain", - # the strongest signal drives "don't saturate" - raw_signal_min = min(group_signals) - raw_signal_max = max(group_signals) - gain_ref = ch[ - "gain" - ] # linked channels always share gain, so any member's value works - label = "/".join(group_names) - - if raw_signal_min < MIN_SIGNAL: - logger.info(f"Raw signal for {label} is below {MIN_SIGNAL}") - if gain_ref == AVAILABLE_GAINS[-1]: - logger.warning( - f"Amplifier of {label} at highest gain {gain_ref} and still not" - + f" measured signal above {MIN_SIGNAL}" - ) - else: - next_gain = AVAILABLE_GAINS[ - bisect_right(AVAILABLE_GAINS, gain_ref * 100) - 1 - ] - for gname in group_names: - active_channels[gname]["self.dev"].set_gain( - f"{next_gain:.0e}".replace("+", "") - ) - active_channels[gname]["gain"] = next_gain - logger.info(f"Setting gain of {label} to {next_gain:.0e} and remeasure") - remeasure = True - else: - gain = max( - ( - g - for g in AVAILABLE_GAINS - if raw_signal_max / gain_ref * g <= FULL_SCALE_V * SAFETY_MARGIN - ), - default=min(AVAILABLE_GAINS), - ) - for gname in group_names: - active_channels[gname]["self.dev"].set_gain(gain) - active_channels[gname]["gain"] = gain - logger.info(f"Calculated final gain for {label} of {gain:.0e}") - - processed.update(group_names) - - # Wait for mono to return to start position status.wait(TIMEOUT_MONO_MOVE) + # Set NIDAQ to max mode + self.dev.nidaq.epics_mode.put(EpicsMode.MAX) + wait_for_signal(self.dev.nidaq.epics_mode, EpicsMode.MAX, timeout=TIMEOUT_PUT_PV) + + # Set gains to lowest gain + for name, ch in active_channels.items(): + lowest_gain = AVAILABLE_GAINS[0] + ch["self.dev"].set_gain(lowest_gain) + ch["gain"] = lowest_gain + + remeasure = True + logger.info(f"Start measurement from {emin} eV to {emax} eV") + while remeasure: + # Rest max values of NIDAQ signals + self.dev.nidaq.epics_max_reset.put(True) + time.sleep(0.2) + + # Create temporary storage for max signal per channel + data = {name: 0 for name in active_channels} + + # Measure current ring current + ring_current_1 = self._get_ring_current() + logger.info(f"Ring current right before measurement: {ring_current_1} mA") + if ring_current_1 < MIN_RING_CURRENT: + raise AutoGainError( + f"Ring current dropped below {MIN_RING_CURRENT} mA right before measurement" + ) + + # Scan range, recording the peak NIDAQ signal per channel + self.dev.mo1_bragg.move(emax).wait(timeout=TIMEOUT_MONO_MOVE) + status.wait(TIMEOUT_MONO_MOVE) + for name, ch in active_channels.items(): + data[name] = max(data[name], ch["signal"].get()) + + # Measure current ring current again + ring_current_2 = self._get_ring_current() + logger.info(f"Ring current right after measurement: {ring_current_2} mA") + if ring_current_2 < MIN_RING_CURRENT: + raise AutoGainError( + f"Ring current dropped below {MIN_RING_CURRENT} mA during measurement" + ) + ring_current = (ring_current_1 + ring_current_2) / 2 + + # Move back to first monochromator position + status = self.dev.mo1_bragg.move(emin) + + # Choose gain per channel based on the max signal recorded during the scan + remeasure = False + processed = set() + + for name, ch in active_channels.items(): + if name in processed: + continue + + # ic0/ic1 must always end up with the same gain -> treat whichever of + # them are present (one or both) as a single group for this decision + if name in LINKED_CHANNELS: + group_names = [n for n in LINKED_CHANNELS if n in active_channels] + else: + group_names = [name] + + group_signals = [] + for gname in group_names: + gsig = data[gname] + logger.info(f"Raw signal for device {gname} is {gsig} V") + if comp_ring_current: + gsig = gsig * NOMINAL_RING_CURRENT / ring_current + logger.info(f"Compensate for ring current, new raw signal is {gsig} V") + group_signals.append(gsig) + + # worst case: the weakest signal drives "need more gain", + # the strongest signal drives "don't saturate" + raw_signal_min = min(group_signals) + raw_signal_max = max(group_signals) + gain_ref = ch[ + "gain" + ] # linked channels always share gain, so any member's value works + label = "/".join(group_names) + + if raw_signal_min < MIN_SIGNAL: + logger.info(f"Raw signal for {label} is below {MIN_SIGNAL}") + if gain_ref == AVAILABLE_GAINS[-1]: + logger.warning( + f"Amplifier of {label} at highest gain {gain_ref} and still not" + + f" measured signal above {MIN_SIGNAL}" + ) + else: + next_gain = AVAILABLE_GAINS[ + bisect_right(AVAILABLE_GAINS, gain_ref * 100) - 1 + ] + for gname in group_names: + active_channels[gname]["self.dev"].set_gain(next_gain) + active_channels[gname]["gain"] = next_gain + logger.info(f"Setting gain of {label} to {next_gain:.0e} and remeasure") + remeasure = True + else: + gain = max( + ( + g + for g in AVAILABLE_GAINS + if raw_signal_max / gain_ref * g <= FULL_SCALE_V * SAFETY_MARGIN + ), + default=min(AVAILABLE_GAINS), + ) + for gname in group_names: + active_channels[gname]["self.dev"].set_gain(gain) + active_channels[gname]["gain"] = gain + logger.info(f"Calculated final gain for {label} of {gain:.0e}") + + processed.update(group_names) + + # Wait for mono to return to start position + status.wait(TIMEOUT_MONO_MOVE) + except Exception as e: + logger.error("Error during measurement, reset gains to their initial values") + for name, ch in active_channels.items(): + ch["self.dev"].amp.cGain_ENUM.put(ch["init_gain"]) + raise AutoGainError(f"During execution of auto-gain, an exception occured: {e}") from e + # Reset NIDAQ to mean mode self.dev.nidaq.epics_mode.put(EpicsMode.MEAN) - # status = CompareStatus(self.dev.nidaq.epics_mode, EpicsMode.MEAN) - # status.wait(timeout=TIMEOUT_PUT_PV) + wait_for_signal(self.dev.nidaq.epics_mode, EpicsMode.MEAN, timeout=TIMEOUT_PUT_PV) # Wait for mono to move to initial position and reset velocity status = self.dev.mo1_bragg.move(init_pos) status.wait(TIMEOUT_MONO_MOVE) - self.dev.mo1_bragg.velocity.put(init_vel) # TODO: Fix, not using property! - # status = CompareStatus(self.dev.mo1_bragg.velocity, init_vel) - # status.wait(timeout=TIMEOUT_PUT_PV) + self.dev.mo1_bragg.velocity.put(init_vel) + wait_for_signal(self.dev.mo1_bragg.velocity, init_vel, timeout=TIMEOUT_PUT_PV) def _get_ring_current(self) -> float: ring_current = 0 diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 00c5b8b..2bb5b06 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -488,9 +488,7 @@ class Scheduler(BECWidget, QWidget): ) elif re.match(r"^dev\..*\.move", item.command): if item.form_state["relative"]: - text = ( - f"Move {item.form_state['device_name']} by {item.form_state['value']}" - ) + text = f"Move {item.form_state['device_name']} by {item.form_state['value']:+g}" else: text = ( f"Move {item.form_state['device_name']} to {item.form_state['value']}" @@ -502,7 +500,17 @@ class Scheduler(BECWidget, QWidget): + f"{item.form_state['gas2']} to {item.form_state['pressure']} bar" ) elif item.command.startswith("dev.reffoilchanger"): - text = f"Insert {item.form_state['ref']} reference foil" + text = f"Insert {item.form_state['foil']} reference foil" + elif item.command.startswith("digital_twin.move_with_config({"): + config = item.form_state["config"] + if config["mo1_mode"] == "Monochromatic": + text = f"Align Beamline for {config['energy']} eV" + else: + text = "Align Beamline for pinkbeam" + text += f" (CM: {config['cm_stripe']} at {config['cm_pitch']*1e3} mrad" + if config["mo1_mode"] == "Monochromatic": + text += f", MO1: {config['mo1_xtal']}" + text += f", FM: {config['fm_stripe']} at {config['fm_rotx']*1e3} mrad)" if text == "": text = f"{item.command}" if item.error: diff --git a/debye_bec/devices/ionization_chambers/ionization_chamber.py b/debye_bec/devices/ionization_chambers/ionization_chamber.py index 92a560d..6b8a107 100644 --- a/debye_bec/devices/ionization_chambers/ionization_chamber.py +++ b/debye_bec/devices/ionization_chambers/ionization_chamber.py @@ -14,6 +14,7 @@ from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase from typeguard import typechecked from debye_bec.devices.ionization_chambers.ionization_chamber_enums import ( + GAIN_MAP, AmplifierEnable, AmplifierFilter, AmplifierGain, @@ -120,13 +121,17 @@ class IonizationChamber0(PSIDeviceBase): self.timeout_for_pvwait = 2.5 super().__init__(name=name, prefix=prefix, scan_info=scan_info, **kwargs) - def set_gain(self, gain: float | str) -> None: + def set_gain(self, gain: float) -> None: """Configure the gain setting of the specified channel Args: - gain (Literal['1e6', '1e7', '5e7', '1e8', '1e9']) : Desired gain + gain(float): Amplifier gain to set. Accepts either a float/int or a string, + e.g. 1e6 or "1e6". Must be one of: 1e6, 1e7, 5e7, 1e8, 1e9. + + Raises: + ValueError: If `gain` cannot be converted to a float, or does not + match one of the supported gain values. """ - # TODO: Fix docstring if self.amp.cOnOff.get() == AmplifierEnable.OFF: status = CompareStatus(self.amp.cOnOff, AmplifierEnable.ON) @@ -134,17 +139,21 @@ class IonizationChamber0(PSIDeviceBase): self.amp.cOnOff.put(AmplifierEnable.ON) status.wait(self.timeout_for_pvwait) - match gain: - case "1e6" | 1e6: - self.amp.cGain_ENUM.put(AmplifierGain.G1E6) - case "1e7" | 1e7: - self.amp.cGain_ENUM.put(AmplifierGain.G1E7) - case "5e7" | 5e7: - self.amp.cGain_ENUM.put(AmplifierGain.G5E7) - case "1e8" | 1e8: - self.amp.cGain_ENUM.put(AmplifierGain.G1E8) - case "1e9" | 1e9: - self.amp.cGain_ENUM.put(AmplifierGain.G1E9) + try: + key = float(gain) + except (TypeError, ValueError) as exc: + raise ValueError(f"Invalid gain: {gain!r}") from exc + + try: + enum_val = GAIN_MAP[key] + except KeyError as exc: + raise ValueError( + f"Unsupported gain: {gain!r}. Must be one of {sorted(GAIN_MAP)}" + ) from exc + + self.amp.cGain_ENUM.put(enum_val) + status = CompareStatus(self.amp.cGain_ENUM, enum_val) + status.wait(self.timeout_for_pvwait) def set_filter( self, value: Literal["1us", "3us", "10us", "30us", "100us", "300us", "1ms", "3ms"] diff --git a/debye_bec/devices/ionization_chambers/ionization_chamber_enums.py b/debye_bec/devices/ionization_chambers/ionization_chamber_enums.py index 2cd7ecb..74bff1d 100644 --- a/debye_bec/devices/ionization_chambers/ionization_chamber_enums.py +++ b/debye_bec/devices/ionization_chambers/ionization_chamber_enums.py @@ -19,6 +19,15 @@ class AmplifierGain(int, enum.Enum): G1E9 = 4 +GAIN_MAP = { + 1e6: AmplifierGain.G1E6, + 1e7: AmplifierGain.G1E7, + 5e7: AmplifierGain.G5E7, + 1e8: AmplifierGain.G1E8, + 1e9: AmplifierGain.G1E9, +} + + class AmplifierFilter(int, enum.Enum): """Enum class for the filter of the channel""" diff --git a/debye_bec/devices/nidaq/nidaq_enums.py b/debye_bec/devices/nidaq/nidaq_enums.py index 9b659ee..19adf39 100644 --- a/debye_bec/devices/nidaq/nidaq_enums.py +++ b/debye_bec/devices/nidaq/nidaq_enums.py @@ -59,8 +59,9 @@ class EncoderFactors(int, enum.Enum): X2 = 5 X4 = 6 + class EpicsMode(int, enum.Enum): """Mode when sending through EPICS""" MEAN = 0 - MAX = 0 + MAX = 1 From ebef7a610d2e126bc5309feb950ba39dfe792603 Mon Sep 17 00:00:00 2001 From: x01da Date: Tue, 15 Sep 2026 14:04:01 +0200 Subject: [PATCH 29/56] wip --- .../digital_twin/panels/input_panel.py | 2 +- .../widgets/scheduler/qt_widgets.py | 13 ++++++++ .../widgets/scheduler/scheduler.py | 31 +++++++++++++++---- 3 files changed, 39 insertions(+), 7 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py b/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py index 3b4a377..3616160 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py @@ -211,7 +211,7 @@ class InputPanel(QWidget): ) else: self.table = ComboBox("table", "Sample Position", ["ES1", "ES2"]) - self.smpl_group = Group("Sample Position", [self.ot_es1_trz, self.es1man_trz]) + self.smpl_group = Group("Sample Position", [self.es1man_trz]) # Assemble complete assistant group self.input_group = Group( diff --git a/debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py b/debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py index 4f47e49..ce5d057 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py +++ b/debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py @@ -12,6 +12,19 @@ class MyListWidget(QListWidget): copyPressed = Signal() pastePressed = Signal() + def __init__(self, parent=None): + super().__init__(parent) + self.setStyleSheet(""" + QListWidget::item { + border-bottom: 1px solid #444444; + padding: 4px; + } + QListWidget::item:selected { + background-color: #3a3a3a; + border-bottom: 1px solid #444444; + } + """) + def keyPressEvent(self, event): if event.key() == Qt.Key_Delete and self.currentItem() is not None: self.deletePressed.emit() diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 2bb5b06..7f56f7f 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -482,8 +482,8 @@ class Scheduler(BECWidget, QWidget): text = ( f"XAS simple scan from {item.form_state['kwargs']['start']} eV to " + f"{item.form_state['kwargs']['stop']} eV, {item.form_state['kwargs']['scan_time']}" - + f" s per spectrum, measure {item.form_state['kwargs']['scan_duration']}s. " - + f"Comment: {item.form_state['kwargs']['metadata']['comment']}, " + + f" s per spectrum, measure {item.form_state['kwargs']['scan_duration']}s" + + f"\n Comment: {item.form_state['kwargs']['metadata']['comment']}, " + f"Sample Name: {item.form_state['kwargs']['metadata']['sample_name']}" ) elif re.match(r"^dev\..*\.move", item.command): @@ -504,13 +504,32 @@ class Scheduler(BECWidget, QWidget): elif item.command.startswith("digital_twin.move_with_config({"): config = item.form_state["config"] if config["mo1_mode"] == "Monochromatic": - text = f"Align Beamline for {config['energy']} eV" + text = f"Align Beamline for {config['energy']:.0f} eV" else: text = "Align Beamline for pinkbeam" - text += f" (CM: {config['cm_stripe']} at {config['cm_pitch']*1e3} mrad" + text += ( + f"\n FE: {config['h_acc']*1e3:.3f} mrad x {config['v_acc']*1e3:.3f} mrad" + + f"\n CM: {config['cm_stripe']} at {config['cm_pitch']*1e3:.3f} mrad" + ) if config["mo1_mode"] == "Monochromatic": - text += f", MO1: {config['mo1_xtal']}" - text += f", FM: {config['fm_stripe']} at {config['fm_rotx']*1e3} mrad)" + text += f"\n MO1: {config['mo1_xtal']}" + text += f"\n FM: {config['fm_stripe']} at {config['fm_rotx']*1e3:.3f} mrad" + if self.beamline == "x01da": + text += f"\n ES1: {config['ot_es1_trz']:.0f} mm" + text += f"\n SMPL_TRZ: {config['es1man_trz']:.3f} mm" + if self.beamline == "x01da": + text += f"\n SMPL-XRD: {config['smpl_to_xrd']:.3f} mm" + elif item.command.startswith("auto_gain.start("): + config = item.form_state + text += f"Auto-configure gains for {item.form_state['element']}, {item.form_state['edge']}-edge" + devices = "" + for device in ["ic0", "ic1", "ic2", "pips"]: + if config[device] is True: + if len(devices) == 0: + devices += f"\n for devices: {device}" + else: + devices += f", {device}" + text += devices if text == "": text = f"{item.command}" if item.error: From b0d2ed64345802eb71acf5657d052ec00d67e649 Mon Sep 17 00:00:00 2001 From: x01da Date: Tue, 15 Sep 2026 14:51:20 +0200 Subject: [PATCH 30/56] wip --- .../widgets/scheduler/qt_widgets.py | 113 +++++- .../widgets/scheduler/scheduler.py | 321 ++++++++++++------ 2 files changed, 316 insertions(+), 118 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py b/debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py index ce5d057..cb3ee0b 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py +++ b/debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py @@ -1,37 +1,119 @@ from bec_widgets.utils.colors import get_accent_colors -from qtpy.QtCore import Qt, Signal +from qtpy.QtCore import QModelIndex, QSize, Qt, Signal # pylint: disable=E0611 from qtpy.QtGui import QKeySequence -from qtpy.QtWidgets import QListWidget, QPushButton +from qtpy.QtWidgets import QHeaderView, QPushButton, QStyle, QStyledItemDelegate, QTableView + +_ROW_MARGIN = 2 # total vertical padding (top+bottom) added around the text block -class MyListWidget(QListWidget): +class _MultilineTextDelegate(QStyledItemDelegate): + """ + Paints and sizes a cell whose DisplayRole text may contain literal + '\\n' line breaks (schedule item labels are built with explicit line + breaks, e.g. the digital-twin config summary). The base + QStyledItemDelegate only reliably shows a single line, so without this + a multi-line label got clipped once rows stopped auto-sizing the way + QListWidgetItem used to. `sizeHint()` reports the full multi-line + height so the view's ResizeToContents row mode can actually fit it. + + Selection is painted here with `option.palette.highlight()` - the + same approach BecLogTableView's `_LogCellDelegate` uses - so the row + gets the theme's native (blue) highlight color instead of whatever a + stylesheet might otherwise hardcode. + """ + + def paint(self, painter, option, index): + painter.save() + if option.state & QStyle.StateFlag.State_Selected: + painter.fillRect(option.rect, option.palette.highlight()) + painter.setPen(option.palette.highlightedText().color()) + else: + painter.setPen(option.palette.text().color()) + painter.setFont(option.font) + + text = index.data(Qt.ItemDataRole.DisplayRole) or "" + rect = option.rect.adjusted(4, _ROW_MARGIN // 2, -4, -(_ROW_MARGIN // 2)) + # painter.drawText(rect, int(Qt.TextFlag.TextWordWrap), text) + painter.drawText( + rect, + int( + Qt.TextFlag.TextWordWrap + | Qt.AlignmentFlag.AlignLeft + | Qt.AlignmentFlag.AlignVCenter + ), + text, + ) + painter.restore() + + def sizeHint(self, option, index): + text = index.data(Qt.ItemDataRole.DisplayRole) or "" + lines = text.count("\n") + 1 + height = option.fontMetrics.lineSpacing() * lines + _ROW_MARGIN + width = super().sizeHint(option, index).width() + return QSize(width, height) + + +class MyTableView(QTableView): deletePressed = Signal() emptySpaceClicked = Signal() copyPressed = Signal() pastePressed = Signal() - def __init__(self, parent=None): + # Column layout is fixed: 0 = status icon, 1 = text (stretches), 2 = pause-on-failure icon. + TEXT_COLUMN = 1 + + def __init__(self, parent=None, status_col_width: int = 60, pause_col_width: int = 130): super().__init__(parent) + + self._status_col_width = status_col_width + self._pause_col_width = pause_col_width + + self.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows) + self.setSelectionMode(QTableView.SelectionMode.SingleSelection) + self.setEditTriggers(QTableView.EditTrigger.NoEditTriggers) + self.setShowGrid(False) + self.setWordWrap(True) + + self.setItemDelegateForColumn(self.TEXT_COLUMN, _MultilineTextDelegate(self)) + + self.verticalHeader().hide() + # ResizeToContents (not Fixed) so a row grows to fit however many + # lines its text cell reports via the delegate's sizeHint above - + # this is what lets multi-line item text show in full again. + self.verticalHeader().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents) + + # No `:selected` rule here on purpose - leaving it out lets Qt fall + # back to the palette highlight color (blue) for selected rows, + # matching BecLogTableView instead of a hardcoded dark gray. self.setStyleSheet(""" - QListWidget::item { + QTableView::item { border-bottom: 1px solid #444444; padding: 4px; } - QListWidget::item:selected { - background-color: #3a3a3a; - border-bottom: 1px solid #444444; - } - """) + """) + + def configure_columns(self): + header = self.horizontalHeader() + + header.setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed) + header.setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch) + header.setSectionResizeMode(2, QHeaderView.ResizeMode.Fixed) + + header.resizeSection(0, self._status_col_width) + header.resizeSection(2, self._pause_col_width) + + header.setStretchLastSection(False) + header.setDefaultAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) def keyPressEvent(self, event): - if event.key() == Qt.Key_Delete and self.currentItem() is not None: + if event.key() == Qt.Key_Delete and self.currentIndex().isValid(): self.deletePressed.emit() event.accept() return - if event.matches(QKeySequence.StandardKey.Copy) and self.currentItem() is not None: + if event.matches(QKeySequence.StandardKey.Copy) and self.currentIndex().isValid(): self.copyPressed.emit() event.accept() return @@ -44,9 +126,12 @@ class MyListWidget(QListWidget): super().keyPressEvent(event) def mousePressEvent(self, event): - if event.button() == Qt.LeftButton and self.itemAt(event.position().toPoint()) is None: + if ( + event.button() == Qt.LeftButton + and not self.indexAt(event.position().toPoint()).isValid() + ): self.clearSelection() - self.setCurrentRow(-1) + self.setCurrentIndex(QModelIndex()) self.emptySpaceClicked.emit() return diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 7f56f7f..ff903f1 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -30,16 +30,16 @@ from bec_widgets.utils.error_popups import SafeSlot from pydantic import ValidationError # pylint: disable=E0611 -from qtpy.QtCore import Qt, QTimer, Signal +from qtpy.QtCore import QAbstractTableModel, QModelIndex, Qt, QTimer, Signal from qtpy.QtWidgets import ( QApplication, QDialog, QFileDialog, QGroupBox, QHBoxLayout, + QHeaderView, QLabel, QLineEdit, - QListWidgetItem, QMessageBox, QPlainTextEdit, QVBoxLayout, @@ -58,16 +58,13 @@ from .notifications import ( notify_item_finished, notify_schedule_state, ) -from .qt_widgets import MyButton, MyListWidget +from .qt_widgets import MyButton, MyTableView from .schedule_item import Schedule, ScheduleItem from .schedule_logic import index_of, pick_next_runnable, protected_prefix_length logger = bec_logger.logger _ACTIVE_QUEUE_STATES = ("PENDING", "RUNNING") -_ITEM_ID_ROLE = ( - Qt.ItemDataRole.UserRole + 1 -) # QListWidgetItem data role used to map a row back to an item_id ICON_SIZE = 20 _ICON_MAP = { @@ -79,6 +76,178 @@ _ICON_MAP = { } +def build_item_display_text(item: ScheduleItem, beamline: str | None) -> str: + """ + Build the human-readable label for a schedule item, pulled out of the + old `_refresh_ui` QListWidgetItem-building loop so the table model's + `data()` can call it too. Pure function of (item, beamline) - no Qt + widgets, no locking - so it's safe to call from the model on every + repaint. + """ + text = "" + if item.form_state is not None: + if item.command.startswith("scans.xas_simple_scan"): + text = ( + f"XAS simple scan from {item.form_state['kwargs']['start']} eV to " + + f"{item.form_state['kwargs']['stop']} eV, {item.form_state['kwargs']['scan_time']}" + + f" s per spectrum, measure {item.form_state['kwargs']['scan_duration']}s" + + f"\n Comment: {item.form_state['kwargs']['metadata']['comment']}, " + + f"Sample Name: {item.form_state['kwargs']['metadata']['sample_name']}" + ) + elif re.match(r"^dev\..*\.move", item.command): + if item.form_state["relative"]: + text = f"Move {item.form_state['device_name']} by {item.form_state['value']:+g}" + else: + text = f"Move {item.form_state['device_name']} to {item.form_state['value']}" + elif item.command.startswith("dev.ic"): + text = ( + f"Fill {item.form_state['chamber']} with {item.form_state['conc1']} % " + + f"{item.form_state['gas1']} and {item.form_state['conc2']} % " + + f"{item.form_state['gas2']} to {item.form_state['pressure']} bar" + ) + elif item.command.startswith("dev.reffoilchanger"): + text = f"Insert {item.form_state['foil']} reference foil" + elif item.command.startswith("digital_twin.move_with_config({"): + config = item.form_state["config"] + if config["mo1_mode"] == "Monochromatic": + text = f"Align Beamline for {config['energy']:.0f} eV" + else: + text = "Align Beamline for pinkbeam" + text += ( + f"\n FE: {config['h_acc']*1e3:.3f} mrad x {config['v_acc']*1e3:.3f} mrad" + + f"\n CM: {config['cm_stripe']} at {config['cm_pitch']*1e3:.3f} mrad" + ) + if config["mo1_mode"] == "Monochromatic": + text += f"\n MO1: {config['mo1_xtal']}" + text += f"\n FM: {config['fm_stripe']} at {config['fm_rotx']*1e3:.3f} mrad" + if beamline == "x01da": + text += f"\n ES1: {config['ot_es1_trz']:.0f} mm" + text += f"\n SMPL_TRZ: {config['es1man_trz']:.3f} mm" + if beamline == "x01da": + text += f"\n SMPL-XRD: {config['smpl_to_xrd']:.3f} mm" + elif item.command.startswith("auto_gain.start("): + config = item.form_state + text += f"Auto-configure gains for {item.form_state['element']}, {item.form_state['edge']}-edge" + devices = "" + for device in ["ic0", "ic1", "ic2", "pips"]: + if config[device] is True: + if len(devices) == 0: + devices += f"\n for devices: {device}" + else: + devices += f", {device}" + text += devices + if text == "": + text = f"{item.command}" + if item.error: + text += f" ({item.error.strip().splitlines()[-1]})" + return text + + +class ScheduleTableModel(QAbstractTableModel): + """ + Read-mostly table model over `Schedule.items`, rebuilt in one shot via + `set_items()` whenever the Scheduler widget refreshes - the same + "clear and repopulate" pattern the old QListWidget code used, just + routed through Qt's model/view API instead of manual + QListWidgetItem management. Mirrors the shape of `BecLogTableView`'s + `BecLogsTableModel`: a flat Python list backing store, `data()` + dispatching on `role`/`column`, icons returned as pixmaps via + `DecorationRole`. + """ + + COL_STATUS = 0 + COL_TEXT = 1 + COL_PAUSE = 2 + _HEADERS = ("Status", "Item", "Pause on failure") + + def __init__(self, parent=None, beamline: str | None = None): + super().__init__(parent) + self._items: list[ScheduleItem] = [] + self._beamline = beamline + # Drives the "selected row -> white status icon" recolor; kept + # separate from the view's own selection model so the icon color + # survives a `set_items()` reset (which clears Qt's selection). + self._selected_item_id: str | None = None + + def rowCount(self, parent: QModelIndex = QModelIndex()) -> int: + return 0 if parent.isValid() else len(self._items) + + def columnCount(self, parent: QModelIndex = QModelIndex()) -> int: + return 0 if parent.isValid() else len(self._HEADERS) + + def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole): + if role == Qt.ItemDataRole.DisplayRole and orientation == Qt.Orientation.Horizontal: + return self._HEADERS[section] + return None + + def set_items(self, items: list[ScheduleItem]): + self.beginResetModel() + self._items = list(items) + self.endResetModel() + + def set_selected_item_id(self, item_id: str | None): + """ + Repaint just the status-icon column for the recolor - avoids a + full model reset, which would otherwise drop the view's own + selection/scroll state on every click. + """ + self._selected_item_id = item_id + if self._items: + top_left = self.index(0, self.COL_STATUS) + bottom_right = self.index(len(self._items) - 1, self.COL_STATUS) + self.dataChanged.emit(top_left, bottom_right, [Qt.ItemDataRole.DecorationRole]) + + def item_id(self, row: int) -> str | None: + if 0 <= row < len(self._items): + return self._items[row].item_id + return None + + def row_of(self, item_id: str | None) -> int | None: + if item_id is None: + return None + for row, item in enumerate(self._items): + if item.item_id == item_id: + return row + return None + + def item_at(self, row: int) -> ScheduleItem | None: + return self._items[row] if 0 <= row < len(self._items) else None + + def data(self, index: QModelIndex, role=Qt.ItemDataRole.DisplayRole): + if not index.isValid(): + return None + item = self._items[index.row()] + col = index.column() + + if role == Qt.ItemDataRole.DecorationRole: + if col == self.COL_STATUS: + icon_name, color = _ICON_MAP[item.status] + if item.item_id == self._selected_item_id: + color = "#FFFFFF" + return material_icon( + icon_name, size=(ICON_SIZE, ICON_SIZE), color=color, convert_to_pixmap=True + ) + if col == self.COL_PAUSE and item.pause_on_failure: + return material_icon( + "pause_circle", + size=(ICON_SIZE, ICON_SIZE), + color="#e6d922", + convert_to_pixmap=True, + ) + return None + + if role == Qt.ItemDataRole.DisplayRole and col == self.COL_TEXT: + return build_item_display_text(item, self._beamline) + + if role == Qt.ItemDataRole.ToolTipRole: + if col == self.COL_PAUSE: + return "Pauses the schedule if this item fails" if item.pause_on_failure else None + if item.error: + return item.error + + return None + + class ScheduleWidgetConfig(ConnectionConfig): """ Per-instance identity/settings for `ScheduleWidget`, following the same @@ -252,15 +421,18 @@ class Scheduler(BECWidget, QWidget): edit_row.addStretch() schedule_layout.addLayout(edit_row) - self.list_widget = MyListWidget() - self.list_widget.currentRowChanged.connect(self._on_selection_changed) - self.list_widget.deletePressed.connect(self._on_delete_clicked) - self.list_widget.emptySpaceClicked.connect(self._on_empty_space_clicked) - self.list_widget.itemDoubleClicked.connect(self._on_edit_clicked) - self.list_widget.copyPressed.connect(self._on_copy_clicked) - self.list_widget.pastePressed.connect(self._on_paste_clicked) + self._table_model = ScheduleTableModel(parent=self, beamline=self.beamline) + self.table_view = MyTableView() + self.table_view.setModel(self._table_model) + self.table_view.configure_columns() + self.table_view.selectionModel().currentRowChanged.connect(self._on_selection_changed) + self.table_view.deletePressed.connect(self._on_delete_clicked) + self.table_view.emptySpaceClicked.connect(self._on_empty_space_clicked) + self.table_view.doubleClicked.connect(self._on_edit_clicked) + self.table_view.copyPressed.connect(self._on_copy_clicked) + self.table_view.pastePressed.connect(self._on_paste_clicked) - schedule_layout.addWidget(self.list_widget) + schedule_layout.addWidget(self.table_view) schedule_layout.addWidget(QLabel("Notes")) self.notes_edit = QPlainTextEdit() @@ -472,78 +644,23 @@ class Scheduler(BECWidget, QWidget): self.schedule_name_input.setText(schedule_name) - self.list_widget.blockSignals(True) - self.list_widget.clear() - selected_row = None - for row, item in enumerate(items): - text = "" - if item.form_state is not None: - if item.command.startswith("scans.xas_simple_scan"): - text = ( - f"XAS simple scan from {item.form_state['kwargs']['start']} eV to " - + f"{item.form_state['kwargs']['stop']} eV, {item.form_state['kwargs']['scan_time']}" - + f" s per spectrum, measure {item.form_state['kwargs']['scan_duration']}s" - + f"\n Comment: {item.form_state['kwargs']['metadata']['comment']}, " - + f"Sample Name: {item.form_state['kwargs']['metadata']['sample_name']}" - ) - elif re.match(r"^dev\..*\.move", item.command): - if item.form_state["relative"]: - text = f"Move {item.form_state['device_name']} by {item.form_state['value']:+g}" - else: - text = ( - f"Move {item.form_state['device_name']} to {item.form_state['value']}" - ) - elif item.command.startswith("dev.ic"): - text = ( - f"Fill {item.form_state['chamber']} with {item.form_state['conc1']} % " - + f"{item.form_state['gas1']} and {item.form_state['conc2']} % " - + f"{item.form_state['gas2']} to {item.form_state['pressure']} bar" - ) - elif item.command.startswith("dev.reffoilchanger"): - text = f"Insert {item.form_state['foil']} reference foil" - elif item.command.startswith("digital_twin.move_with_config({"): - config = item.form_state["config"] - if config["mo1_mode"] == "Monochromatic": - text = f"Align Beamline for {config['energy']:.0f} eV" - else: - text = "Align Beamline for pinkbeam" - text += ( - f"\n FE: {config['h_acc']*1e3:.3f} mrad x {config['v_acc']*1e3:.3f} mrad" - + f"\n CM: {config['cm_stripe']} at {config['cm_pitch']*1e3:.3f} mrad" - ) - if config["mo1_mode"] == "Monochromatic": - text += f"\n MO1: {config['mo1_xtal']}" - text += f"\n FM: {config['fm_stripe']} at {config['fm_rotx']*1e3:.3f} mrad" - if self.beamline == "x01da": - text += f"\n ES1: {config['ot_es1_trz']:.0f} mm" - text += f"\n SMPL_TRZ: {config['es1man_trz']:.3f} mm" - if self.beamline == "x01da": - text += f"\n SMPL-XRD: {config['smpl_to_xrd']:.3f} mm" - elif item.command.startswith("auto_gain.start("): - config = item.form_state - text += f"Auto-configure gains for {item.form_state['element']}, {item.form_state['edge']}-edge" - devices = "" - for device in ["ic0", "ic1", "ic2", "pips"]: - if config[device] is True: - if len(devices) == 0: - devices += f"\n for devices: {device}" - else: - devices += f", {device}" - text += devices - if text == "": - text = f"{item.command}" - if item.error: - text += f" ({item.error.strip().splitlines()[-1]})" - list_item = QListWidgetItem(text, self.list_widget) - list_item.setData(_ITEM_ID_ROLE, item.item_id) - if item.item_id == self._selected_item_id: - selected_row = row - self._update_icons() - if selected_row is not None: - self.list_widget.setCurrentRow(selected_row) + selection_model = self.table_view.selectionModel() + selection_model.blockSignals(True) + + # Repopulate the model (full reset, same "clear and rebuild" idea + # the old QListWidget code used); the selected item's status-icon + # color is baked in via `_selected_item_id` so the highlighted row + # keeps its white icon straight after the reset repaints it. + self._table_model._selected_item_id = self._selected_item_id + self._table_model.set_items(items) + + row = self._table_model.row_of(self._selected_item_id) + if row is not None: + self.table_view.selectRow(row) else: self._selected_item_id = None - self.list_widget.blockSignals(False) + + selection_model.blockSignals(False) # Don't stomp on notes the operator is actively typing (e.g. a # remote update, or our own debounce timer firing right after @@ -554,6 +671,8 @@ class Scheduler(BECWidget, QWidget): self.notes_edit.setPlainText(notes) self.notes_edit.blockSignals(False) + self._update_buttons() + def _update_guard_label(self, *_): if self._guard.enabled: state = "OK" if self._guard.is_clear() else "PAUSED - waiting to resume" @@ -600,18 +719,6 @@ class Scheduler(BECWidget, QWidget): self.copy_btn.setEnabled(selected_item is not None) self.paste_btn.setEnabled(self._clipboard_item is not None) - def _update_icons(self): - items = list(self.schedule.items) - for row, item in enumerate(items): - icon_name, color = _ICON_MAP[item.status] - if self._selected_item_id == item.item_id: - color = "#FFFFFF" - icon = material_icon( - icon_name, size=(ICON_SIZE, ICON_SIZE), color=color, convert_to_pixmap=True - ) - list_item = self.list_widget.item(row) - list_item.setIcon(icon) - @SafeSlot() def _on_schedule_name_change(self): name = self.schedule_name_input.text() @@ -619,16 +726,16 @@ class Scheduler(BECWidget, QWidget): self.schedule.schedule_name = name self._persist_locked() - @SafeSlot() - def _on_selection_changed(self, row: int): - item = self.list_widget.item(row) if row >= 0 else None - self._selected_item_id = item.data(_ITEM_ID_ROLE) if item is not None else None - self._update_icons() + @SafeSlot(QModelIndex, QModelIndex) + def _on_selection_changed(self, current: QModelIndex, previous: QModelIndex): + item_id = self._table_model.item_id(current.row()) if current.isValid() else None + self._selected_item_id = item_id + self._table_model.set_selected_item_id(item_id) self._update_buttons() @SafeSlot() def _on_empty_space_clicked(self): - self.list_widget.setCurrentRow(-1) + self.table_view.setCurrentIndex(QModelIndex()) self._refresh_ui() # ---- notes ---- # @@ -857,6 +964,7 @@ class Scheduler(BECWidget, QWidget): self._update_buttons() @SafeSlot() + @SafeSlot(QModelIndex) def _on_edit_clicked(self, *_): if self._selected_item_id is None: return @@ -904,14 +1012,19 @@ class Scheduler(BECWidget, QWidget): def _on_delete_clicked(self): if self._selected_item_id is None: return - row = self.list_widget.currentRow() + row = self.table_view.currentIndex().row() try: self.delete_item(self._selected_item_id) except RuntimeError as exc: QMessageBox.warning(self, "Cannot delete item", str(exc)) return self._selected_item_id = None - self._on_selection_changed(max(0, row - 1)) + # delete_item()'s schedule_changed emit already ran _refresh_ui() + # with an empty selection; now re-select the row that took the + # deleted item's place (or the new last row, if it was last). + new_row = max(0, row - 1) + if 0 <= new_row < self._table_model.rowCount(): + self.table_view.selectRow(new_row) self._refresh_ui() @SafeSlot() From f2fad8bced98d6e590c5c8357cb8e127920dc8fc Mon Sep 17 00:00:00 2001 From: x01da Date: Tue, 15 Sep 2026 15:16:25 +0200 Subject: [PATCH 31/56] wip --- .../bec_widgets/widgets/scheduler/qt_widgets.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py b/debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py index cb3ee0b..884da3a 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py +++ b/debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py @@ -87,12 +87,12 @@ class MyTableView(QTableView): # No `:selected` rule here on purpose - leaving it out lets Qt fall # back to the palette highlight color (blue) for selected rows, # matching BecLogTableView instead of a hardcoded dark gray. - self.setStyleSheet(""" - QTableView::item { - border-bottom: 1px solid #444444; - padding: 4px; - } - """) + # self.setStyleSheet(""" + # QTableView::item { + # border-bottom: 1px solid #444444; + # padding: 4px; + # } + # """) def configure_columns(self): header = self.horizontalHeader() From 06feec47a07f566cf643c4ac9a58f0fd22f2810d Mon Sep 17 00:00:00 2001 From: hitz_s Date: Wed, 23 Sep 2026 10:09:45 +0200 Subject: [PATCH 32/56] wip digital twin --- .../digital_twin_core/motion_worker.py | 6 +- .../digital_twin_core/x01da_parameters.py | 2 +- .../digital_twin_core/x10da_parameters.py | 3 + .../widgets/digital_twin/digital_twin.py | 179 +++++++++++++++++- .../digital_twin/panels/settings_panel.py | 17 +- 5 files changed, 198 insertions(+), 9 deletions(-) diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py index 7b1ac6e..0cd07c6 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py @@ -244,10 +244,12 @@ class MotionWorker: self.dev[self.motor].stop() self._stop_flag.clear() if rb is not None: - self._emit_position_changed(rb["device"].read(cached=True)[rb["name"]]["value"]) + self._emit_position_changed( + rb["device"].read(cached=False)[rb["name"]]["value"] + ) else: self._emit_position_changed( - self.dev[self.motor].read(cached=True)[self.motor]["value"] + self.dev[self.motor].read(cached=False)[self.motor]["value"] ) if surveyed_axes is not None: for surv_ax in surveyed_axes: diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_parameters.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_parameters.py index 214cb7d..66fa86c 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_parameters.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_parameters.py @@ -320,4 +320,4 @@ vacuum_pipes = pipe( ) Walls = namedtuple("walls", ["start", "end", "height"]) -walls = Walls(start=[13999.30], end=[13999 + 75.5 + 30], height=[[-20, 25]]) +walls = Walls(start=[13999.30], end=[13999 + 75.5 + 30], height=[[-20, 25]]) # WBBS diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_parameters.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_parameters.py index c0bd4e0..bcb5b46 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_parameters.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_parameters.py @@ -294,3 +294,6 @@ ic = namedtuple("sample", ["name", "center"]) es1ic0 = ic(name="ES1 IC0", center=[0, 23633, sourceHeight]) es1ic1 = ic(name="ES1 IC1", center=[0, 24383, sourceHeight]) es1ic2 = ic(name="ES1 IC2", center=[0, 24723, sourceHeight]) + +Walls = namedtuple("walls", ["start", "end", "height"]) +walls = Walls(start=[13472], end=[13472 + 354], height=[[-20, 36]]) # WBBS diff --git a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py index c612c92..ce052fb 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py @@ -2,9 +2,13 @@ Digital Twin: Custom BEC widget to support the beamline alignment. """ +import json import sys +import time +from pathlib import Path from typing import Literal, cast +import h5py import numpy as np import yaml from bec_lib import bec_logger @@ -22,9 +26,11 @@ from qtpy.QtWidgets import ( QComboBox, QDialog, QDialogButtonBox, + QFileDialog, QFrame, QHBoxLayout, QLabel, + QMessageBox, QPlainTextEdit, QPushButton, QScrollArea, @@ -141,6 +147,9 @@ class DigitalTwin(BECWidget, QWidget): self.input.adapt_reality.clicked_connect(self.adapt_reality) self.settings.load_offsets.clicked_connect(self.load_offsets) self.settings.show_offsets.clicked_connect(self.show_offsets) + self.settings.save_config.clicked_connect(self.save_config) + self.settings.load_from_config.clicked_connect(self.load_from_config) + self.settings.load_from_scan.clicked_connect(self.load_from_scan) self.edge_selector_energy = 0.0 self.bragg_angle = 0.0 @@ -506,7 +515,7 @@ class DigitalTwin(BECWidget, QWidget): mo1_mode = "Monochromatic" else: mo1_mode = "Pinkbeam" - mo1_bragg = self.dev.mo1_bragg.read(cached=True) + mo1_bragg = self.dev.mo1_bragg.read(cached=False) sldi_gapx = self.dev.sldi_gapx.read(cached=True)["sldi_gapx"]["value"] sldi_gapy = self.dev.sldi_gapy.read(cached=True)["sldi_gapy"]["value"] h_acc, v_acc = self.core.sldi_gap_to_acc(sldi_gapx, sldi_gapy) @@ -647,7 +656,7 @@ class DigitalTwin(BECWidget, QWidget): # Removing offsets pos = self.core.remove_offsets(pos) - self.input.energy.set_number(self.dev.mo1_bragg.read(cached=True)["mo1_bragg"]["value"]) + self.input.energy.set_number(self.dev.mo1_bragg.read(cached=False)["mo1_bragg"]["value"]) h_acc, v_acc = self.core.sldi_gap_to_acc(pos["sldi_gapx"], pos["sldi_gapy"]) self.input.sldi_hacc.set_number(h_acc * 1e3) self.input.sldi_vacc.set_number(v_acc * 1e3) @@ -659,7 +668,7 @@ class DigitalTwin(BECWidget, QWidget): mo1_mode = "Pinkbeam" self.input.mo1_mode.set_current_text(mo1_mode) self.input.mo1_xtal.set_current_text( - self.dev.mo1_bragg.read(cached=True)["mo1_bragg_crystal_current_xtal_string"]["value"] + self.dev.mo1_bragg.read(cached=False)["mo1_bragg_crystal_current_xtal_string"]["value"] ) fm_stripe = self.core.fm_trx_to_stripe(-pos["fm_trx"]) self.input.fm_stripe.set_current_text(fm_stripe) @@ -798,6 +807,166 @@ class DigitalTwin(BECWidget, QWidget): dialog.exec() + @SafeSlot() + def save_config(self, *_): + config = self.get_assistant_config() + + hostname = self.client._hostname + start = hostname.find("x") + if start != -1: + beamline = hostname[start : start + 5] + active_account = self.client.active_account + folder = f"/sls/{beamline}/data/{active_account}/raw/widgets/digital_twin/configs" + else: + folder = "/sls" + + folder = Path(folder) + folder.mkdir(parents=True, exist_ok=True) + + t = time.localtime() + fmt_time = time.strftime("%Y%m%d_%H%M%S", t) + default_filename = "config_" + fmt_time + ".json" + + filename, _ = QFileDialog.getSaveFileName( + self, + "Save dictionary", + str(folder / default_filename), + "JSON files (*.json);;All files (*)", + ) + + if not filename: + return None + + path = Path(filename) + + if path.suffix.lower() != ".json": + path = path.with_suffix(".json") + + with path.open("w", encoding="utf-8") as f: + json.dump(config, f, indent=4, ensure_ascii=False) + + return path + + @SafeSlot() + def load_from_config(self, *_): + hostname = self.client._hostname + start = hostname.find("x") + if start != -1: + beamline = hostname[start : start + 5] + active_account = self.client.active_account + folder = f"/sls/{beamline}/data/{active_account}/raw/widgets/digital_twin/configs" + else: + folder = "/sls" + + path, _ = QFileDialog.getOpenFileName( + self, "Load config from file", folder, "JSON files (*.json);;All files (*)" + ) + if not path: + return + + try: + with open(path, encoding="utf-8") as f: + config = json.load(f) + except (OSError, json.JSONDecodeError) as exc: + QMessageBox.critical( + self, "Load failed", f"Could not load a config from {path}:\n{exc}" + ) + return + + self.set_assistant_config(config) + + @SafeSlot() + def load_from_scan(self, *_): + hostname = self.client._hostname + start = hostname.find("x") + if start != -1: + beamline = hostname[start : start + 5] + active_account = self.client.active_account + start_folder = f"/sls/{beamline}/data/{active_account}/raw" + else: + start_folder = "/sls" + + filename, _ = QFileDialog.getOpenFileName( + self, "Open scan", start_folder, "h5 files (*.h5);;All files (*)" + ) + + if not filename: + return None, None + + path = Path(filename) + + with h5py.File(path, "r") as f: + devices = cast(h5py.Group, f["entry/collection/devices"]) + + pos = {} + # fmt:off + pos["sldi_gapx"] = cast(h5py.Dataset, devices["sldi_gapx/sldi_gapx/value"])[()] + pos["sldi_gapy"] = cast(h5py.Dataset, devices["sldi_gapy/sldi_gapy/value"])[()] + pos["cm_trx"] = cast(h5py.Dataset, devices["cm_trx/cm_trx/value"])[()] + pos["cm_rotx"] = cast(h5py.Dataset, devices["cm_rotx/cm_rotx/value"])[()] + pos["mo1_trx"] = cast(h5py.Dataset, devices["mo1_trx/mo1_trx/value"])[()] + pos["fm_trx"] = cast(h5py.Dataset, devices["fm_trx/fm_trx/value"])[()] + pos["fm_rotx"] = cast(h5py.Dataset, devices["fm_rotx/fm_rotx/value"])[()] + pos["fm_bnd_radius"] = cast(h5py.Dataset, devices["fm_bnd_radius/fm_bnd_radius/value"])[()] + pos["es1man_trz"] = cast(h5py.Dataset, devices["es1man_trz/es1man_trz/value"])[()] + if self.beamline == BeamlineId.X01DA: + pos["ot_es1_trz"] = cast(h5py.Dataset, devices["ot_es1_trz/ot_es1_trz/value"])[()] + pos["ot_es2_trz"] = cast(h5py.Dataset, devices["ot_es2_trz/ot_es2_trz/value"])[()] + pos["smpl_to_xrd"] = pos["ot_es2_trz"] - pos["ot_es1_trz"] - pos["es1man_trz"] + 32 + else: + table = self.ask_table_selection(self.input.table.currentText()) + pos["ot_es1_trz"] = self.core.table_to_smpl_pos(table) + # fmt:on + + # Removing offsets + pos = self.core.remove_offsets(pos) + + self.input.energy.set_number( + cast(h5py.Dataset, devices["mo1_bragg/mo1_bragg/value"])[()] + ) + h_acc, v_acc = self.core.sldi_gap_to_acc(pos["sldi_gapx"], pos["sldi_gapy"]) + self.input.sldi_hacc.set_number(h_acc * 1e3) + self.input.sldi_vacc.set_number(v_acc * 1e3) + self.input.cm_stripe.set_current_text(self.core.cm_trx_to_stripe(-pos["cm_trx"])) + self.input.cm_pitch.set_number(pos["cm_rotx"]) + if abs(pos["mo1_trx"]) > 5: + mo1_mode = "Monochromatic" + else: + mo1_mode = "Pinkbeam" + self.input.mo1_mode.set_current_text(mo1_mode) + self.input.mo1_xtal.set_current_text( + cast( + h5py.Dataset, devices["mo1_bragg/mo1_bragg_crystal_current_xtal_string/value"] + )[()] + ) + + fm_stripe = self.core.fm_trx_to_stripe(-pos["fm_trx"]) + self.input.fm_stripe.set_current_text(fm_stripe) + fm_rotx_real = 2 * pos["cm_rotx"] - pos["fm_rotx"] + logger.info(f"In adapt reality, fm_rotx_real is {fm_rotx_real}") + self.input.fm_rotx.set_number(fm_rotx_real) + + if self.beamline == BeamlineId.X01DA: + self.input.ot_es1_trz.set_number(pos["ot_es1_trz"]) + self.input.smpl_to_xrd.set_number(pos["smpl_to_xrd"]) + else: + table = self.ask_table_selection(self.input.table.currentText()) + self.input.table.set_current_text(table) + + smpl = pos["ot_es1_trz"] + pos["es1man_trz"] + + fm_focx, fm_focy = self.core.calc_beamsize( + h_acc, v_acc, fm_stripe, -fm_rotx_real * 1e-3, pos["fm_bnd_radius"] * 1e6, smpl + ) + if fm_focx < 0.08 and fm_focy < 0.08: + self.input.fm_focus.set_current_text("Focused") + else: + self.input.fm_focus.set_current_text("Defocused") + self.input.fm_focx.set_number(fm_focx) + self.input.fm_focy.set_number(fm_focy) + + self.calc_assistant(identifier="init") + def update_fm_mode(self): """ Updates the focusing mirror input group based on the @@ -972,11 +1141,11 @@ class DigitalTwin(BECWidget, QWidget): """ xtal = self.input.mo1_xtal.currentText() if xtal == "Si(111)": - d_spacing = self.dev.mo1_bragg.crystal.d_spacing_si111.read(cached=True)[ + d_spacing = self.dev.mo1_bragg.crystal.d_spacing_si111.read(cached=False)[ "mo1_bragg_crystal_d_spacing_si111" ]["value"] elif xtal == "Si(311)": - d_spacing = self.dev.mo1_bragg.crystal.d_spacing_si311.read(cached=True)[ + d_spacing = self.dev.mo1_bragg.crystal.d_spacing_si311.read(cached=False)[ "mo1_bragg_crystal_d_spacing_si311" ]["value"] else: diff --git a/debye_bec/bec_widgets/widgets/digital_twin/panels/settings_panel.py b/debye_bec/bec_widgets/widgets/digital_twin/panels/settings_panel.py index 2bf74d2..c621bbc 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/panels/settings_panel.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/panels/settings_panel.py @@ -27,5 +27,20 @@ class SettingsPanel(QWidget): "Axes Offsets", [self.load_offsets, self.offsets_status, self.show_offsets] ) - self._layout.addWidget(self.offset_group) + self.load_from_scan = Button( + label="Load from Scan", label_button="Load from Scan", enabled=True + ) + self.load_from_config = Button( + label="Load from Config", label_button="Load from Config", enabled=True + ) + self.save_config = Button(label="Save Config", label_button="Save Config", enabled=True) + + self.import_export_group = Group( + "Import/Export", [self.load_from_scan, self.load_from_config, self.save_config] + ) + + # Assemble complete settings group + self.settings_group = Group("Settings", [self.offset_group, self.import_export_group]) + + self._layout.addWidget(self.settings_group) self._layout.addStretch() From b4d2ac190675846523a304b950aad133524e7c33 Mon Sep 17 00:00:00 2001 From: hitz_s Date: Wed, 23 Sep 2026 14:10:07 +0200 Subject: [PATCH 33/56] wip digital twin --- .../digital_twin_core/digital_twin_core.py | 3 + .../plugins/digital_twin_core/types.py | 2 + .../digital_twin_core/x01da_offsets.yaml | 6 + .../digital_twin/azimuth_calculator.py | 339 + .../widgets/digital_twin/digital_twin.py | 76 +- .../widgets/digital_twin/glitches_preview.py | 148 + .../digital_twin/panels/input_panel.py | 26 +- .../digital_twin/panels/mover_panel.py | 22 +- .../digital_twin/widgets/qt_widgets.py | 10 + ..._Si-LN2_8-8-8_4500-60000eV_-180-180deg.pro | 7812 ++++++++++++++++ ...311_Si-LN2_8-8-8_4500-60000eV_0-360deg.pro | 7902 +++++++++++++++++ 11 files changed, 16341 insertions(+), 5 deletions(-) create mode 100644 debye_bec/bec_widgets/widgets/digital_twin/azimuth_calculator.py create mode 100644 debye_bec/bec_widgets/widgets/digital_twin/glitches_preview.py create mode 100644 debye_bec/bec_widgets/widgets/digital_twin/xop_si111_Si-LN2_8-8-8_4500-60000eV_-180-180deg.pro create mode 100644 debye_bec/bec_widgets/widgets/digital_twin/xop_si311_Si-LN2_8-8-8_4500-60000eV_0-360deg.pro diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py index 6e7a772..f9876d9 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py @@ -351,6 +351,9 @@ class DigitalTwinCore: diag = bl.mo1.xtalGap[0] / np.sin(cfg["mo1_bragg"]) # Calculations for Mono dz = diag * np.cos(2 * (cfg["cm_pitch"] + cfg["mo1_bragg"])) + # roty, Azimuthal angle + pos["mo1_roty"] = {"value": cfg["mo1_roty"]} + ## Slits 1 d = bl.opSlits1.center[1] - bl.cm.center[1] - dz sl1_beam_height = d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1 diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/types.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/types.py index 7c66f50..913c951 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/types.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/types.py @@ -27,6 +27,7 @@ class ConfigDict(TypedDict): mo1_mode (str): MO1 mode. mo1_xtal (str): MO1 crystal. mo1_bragg (float): MO1 Bragg angle. + mo1_roty (float): MO1 Azimuthal angle. fm_rotx (float): FM rotation x. fm_stripe (str): FM stripe name. fm_trx (float): FM translation x. @@ -46,6 +47,7 @@ class ConfigDict(TypedDict): mo1_mode: str mo1_xtal: str mo1_bragg: float + mo1_roty: float fm_rotx: float fm_stripe: str fm_trx: float diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_offsets.yaml b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_offsets.yaml index f475d96..83f9ff0 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_offsets.yaml +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_offsets.yaml @@ -13,6 +13,12 @@ mo1_try: range: [[-30, -0.1], [0.1, 30]] offset: [-1.78, -1.78] +mo1_roty: + modifier: + axis: mo1_trx + range: [[-30, -0.1], [0.1, 30]] # Si311, Si111 + offset: [136.80017, 89.15503] + sl1_centery: offset: -1.2 diff --git a/debye_bec/bec_widgets/widgets/digital_twin/azimuth_calculator.py b/debye_bec/bec_widgets/widgets/digital_twin/azimuth_calculator.py new file mode 100644 index 0000000..a32c3cd --- /dev/null +++ b/debye_bec/bec_widgets/widgets/digital_twin/azimuth_calculator.py @@ -0,0 +1,339 @@ +""" +Find the azimuthal (phi) setting of a monochromator crystal by matching +glitches detected in a real measured spectrum against a line list exported +by XOP's MARE "spaghetti" tool. + +Pipeline +-------- +1. parse_xop_macro(path) -- read an XOP MARE-glitches .pro macro and + extract, for every reflection, (hkl, + alpha0, k, p2/4, fh). These four numbers + fully determine that reflection's glitch + energy as a function of azimuth phi via + XOP's own formula: + + lambda(phi) = 1 / sqrt((k/cos(phi-alpha0))^2 + p2/4) + E(phi) = hc / lambda(phi) + +2. detect_glitches(E, I) -- find dip positions in a real measured + (energy, intensity) scan: smooth to get a + baseline, subtract, find negative peaks + in the residual. + +3. find_azimuth(...) -- for a grid of candidate phi, compute every + reflection's predicted glitch energy, + score how well the detected dip energies + line up with predicted (fh-weighted) + lines, and return the best-fit phi. + +Self-test at the bottom regenerates synthetic "measured" glitches at a +known phi from the XOP line list itself and checks that find_azimuth +recovers that phi -- a good sanity check before trusting it on real data. +""" + +import re + +import numpy as np +from scipy.optimize import minimize_scalar +from scipy.signal import find_peaks, savgol_filter + +HC = 12398.42 # eV * Angstrom + + +# ---------------------------------------------------------------------- +# 1. Parse an XOP MARE-glitches macro +# ---------------------------------------------------------------------- +def parse_xop_macro(path): + """ + Returns a list of dicts: {hkl: (h,k,l), alpha0: deg, k: float, + p2_4: float, fh: float}, one per reflection line in the macro. + + XOP prints one comment line per reflection with columns: + h k l alpha0 k p2/4 th2 th2 th2 th3 th3 th3 + lambda lambda lambda BrgAngU BrgAngG fh + (18 numeric columns). We parse those lines directly rather than the + 'y3 = 1D/sqrt(...)' code lines -- same numbers, simpler regex. + + A handful of lines in real XOP output have a formatting bug where two + columns run together with no separating space (e.g. an l=-1 column + immediately followed by a tiny alpha0 like 8.5e-7, printed as + '-18.53774E-007'). Those are detected (h,k,l must be integers) and + skipped rather than silently mis-parsed. + """ + reflections = [] + skipped = 0 + with open(path) as f: + for line in f: + line = line.rstrip("\n") + if not line.startswith(";"): + continue + tokens = line[1:].split() + if len(tokens) != 18: + if len(tokens) >= 4 and re.match(r"^-?\d+$", tokens[0]): + skipped += ( + 1 # looks like a corrupted data line (columns ran together) + ) + continue # otherwise a header/comment/label line -- not data + try: + vals = [float(t) for t in tokens] + except ValueError: + continue # header row (e.g. "h k l alpha0 ...") -- not data + h, k, l = vals[0], vals[1], vals[2] + if not all(abs(x - round(x)) < 1e-6 for x in (h, k, l)): + skipped += 1 # corrupted line (merged columns) + continue + alpha0, k_param, p2_4 = vals[3], vals[4], vals[5] + fh = vals[-1] + reflections.append( + dict( + hkl=(int(h), int(k), int(l)), + alpha0=alpha0, + k=k_param, + p2_4=p2_4, + fh=fh, + ) + ) + print( + f"parse_xop_macro: parsed {len(reflections)} reflections, " + f"skipped {skipped} malformed line(s)" + ) + return reflections + + +def filter_reflections(reflections, max_h=None, max_k=None, max_l=None, min_fh=None): + """ + Return only the reflections with |h|<=max_h, |k|<=max_k, |l|<=max_l + and fh>=min_fh. Any limit left as None means "no limit" on that axis. + Useful for cutting a large XOP line list (hundreds of reflections) + down to the strong, low-index ones that actually matter. + """ + out = [] + for r in reflections: + h, k, l = r["hkl"] + if max_h is not None and abs(h) > max_h: + continue + if max_k is not None and abs(k) > max_k: + continue + if max_l is not None and abs(l) > max_l: + continue + if min_fh is not None and r["fh"] < min_fh: + continue + out.append(r) + return out + + +# ---------------------------------------------------------------------- +# 2. Predict glitch energies at a given azimuth from the parsed line list +# ---------------------------------------------------------------------- +def predicted_energies(reflections, phi_deg, energy_range=None): + """ + Returns (E_pred, fh, hkl_list) for every reflection whose glitch falls + at a finite, real energy at this azimuth (optionally restricted to + energy_range = (Emin, Emax)). + """ + alpha0 = np.array([r["alpha0"] for r in reflections]) + kpar = np.array([r["k"] for r in reflections]) + p24 = np.array([r["p2_4"] for r in reflections]) + fh = np.array([r["fh"] for r in reflections]) + hkl = [r["hkl"] for r in reflections] + + cosval = np.cos(np.radians(phi_deg - alpha0)) + with np.errstate(divide="ignore", invalid="ignore"): + term = kpar / cosval + E = HC * np.sqrt(term**2 + p24) + + valid = np.isfinite(E) + if energy_range is not None: + lo, hi = energy_range + valid &= (E >= lo) & (E <= hi) + + idx = np.where(valid)[0] + return E[idx], fh[idx], [hkl[i] for i in idx] + + +# ---------------------------------------------------------------------- +# 3. Detect glitches (dips) in a real measured spectrum -- split into +# reusable steps so a GUI can recompute/redraw each one live. +# ---------------------------------------------------------------------- +def sanitize_window(smooth_window, smooth_order, n_points): + """Coerce a smoothing window into something savgol_filter will accept: + odd, >= smooth_order + 2, and not larger than the data.""" + w = min(smooth_window, n_points - (1 - n_points % 2)) + if w % 2 == 0: + w -= 1 + w = max(w, smooth_order + 2 if (smooth_order + 2) % 2 == 1 else smooth_order + 3) + return w + + +def compute_baseline(energy, intensity, smooth_window=51, smooth_order=3): + """ + Sorts by energy and returns (energy_sorted, intensity_sorted, baseline, + residual). This is step 1 (smoothing) on its own, so a GUI can redraw + the baseline/residual live as the window/order controls move. + """ + energy = np.asarray(energy, dtype=float) + intensity = np.asarray(intensity, dtype=float) + order = np.argsort(energy) + energy, intensity = energy[order], intensity[order] + w = sanitize_window(smooth_window, smooth_order, len(intensity)) + baseline = savgol_filter(intensity, w, smooth_order) + residual = intensity - baseline + return energy, intensity, baseline, residual + + +def find_dips(energy, residual, prominence=None, prominence_sigma=3.0): + """ + Step 2 (peak finding) on its own, so a GUI can redraw just the + detected-dip markers as the prominence control moves, without + recomputing the baseline. Returns (glitch_energies, prominences, + prominence_used). + """ + if prominence is None: + prominence = prominence_sigma * np.std(residual) + peaks, props = find_peaks(-residual, prominence=prominence) + return energy[peaks], props["prominences"], prominence + + +def detect_glitches( + energy, + intensity, + smooth_window=51, + smooth_order=3, + prominence=None, + prominence_sigma=3.0, +): + """ + Convenience wrapper chaining compute_baseline + find_dips for + non-interactive use (see find_crystal_azimuth). Returns + (glitch_energies, prominences) as before. + """ + energy, intensity, baseline, residual = compute_baseline( + energy, intensity, smooth_window, smooth_order + ) + glitch_E, prom, _ = find_dips(energy, residual, prominence, prominence_sigma) + return glitch_E, prom + + +# ---------------------------------------------------------------------- +# 4. Score a candidate azimuth against the detected glitches +# ---------------------------------------------------------------------- +def azimuth_score(phi_deg, reflections, detected_energies, energy_range, sigma_eV=3.0): + """ + For each detected glitch energy, find the best-matching predicted + line (weighted by its fh, discounted by a Gaussian in energy + distance) and sum those best-match scores. High score = many detected + dips coincide with real, strong predicted lines at this phi. + """ + E_pred, fh, _ = predicted_energies(reflections, phi_deg, energy_range) + if len(E_pred) == 0 or len(detected_energies) == 0: + return 0.0 + diffs = detected_energies[:, None] - E_pred[None, :] + gauss = np.exp(-0.5 * (diffs / sigma_eV) ** 2) + weighted = gauss * fh[None, :] + return weighted.max(axis=1).sum() + + +# ---------------------------------------------------------------------- +# 5. Main search: scan phi, then refine locally +# ---------------------------------------------------------------------- +def find_azimuth( + reflections, detected_energies, energy_range, phi_grid=None, sigma_eV=3.0 +): + """ + Returns (phi_best, score_best, phi_grid, scores) so the coarse scan + can be plotted as a diagnostic (a clean single maximum is a good + sign; multiple comparable peaks means the data is ambiguous, e.g. too + few glitches in range, or a real point-group ambiguity). + """ + detected_energies = np.asarray(detected_energies, dtype=float) + if phi_grid is None: + phi_grid = np.arange(0.0, 180.0, 0.5) + + scores = np.array( + [ + azimuth_score(p, reflections, detected_energies, energy_range, sigma_eV) + for p in phi_grid + ] + ) + i_best = int(np.argmax(scores)) + phi_coarse = phi_grid[i_best] + + res = minimize_scalar( + lambda p: -azimuth_score( + p, reflections, detected_energies, energy_range, sigma_eV + ), + bounds=(phi_coarse - 0.1, phi_coarse + 0.1), + method="bounded", + ) + return res.x, -res.fun, phi_grid, scores + + +# ---------------------------------------------------------------------- +# 6. End-to-end convenience wrapper +# ---------------------------------------------------------------------- +def find_crystal_azimuth( + macro_path, + energy, + intensity, + energy_range, + smooth_window=51, + smooth_order=3, + prominence=None, + sigma_eV=3.0, + phi_grid=None, +): + """ + One-call pipeline: parse the XOP macro, detect glitches in the + measurement, and return the best-fit azimuth. + """ + reflections = parse_xop_macro(macro_path) + glitch_E, glitch_prom = detect_glitches( + energy, intensity, smooth_window, smooth_order, prominence + ) + print( + f"find_crystal_azimuth: detected {len(glitch_E)} candidate glitches " + f"in [{energy_range[0]}, {energy_range[1]}] eV" + ) + phi_best, score_best, phi_grid, scores = find_azimuth( + reflections, glitch_E, energy_range, phi_grid, sigma_eV + ) + return dict( + phi_deg=phi_best, + score=score_best, + glitch_energies=glitch_E, + glitch_prominences=glitch_prom, + phi_grid=phi_grid, + scores=scores, + reflections=reflections, + ) + + +# ---------------------------------------------------------------------- +# Self-test: regenerate synthetic glitches at a KNOWN phi from the macro +# itself, then check find_azimuth recovers it. No real measurement needed. +# ---------------------------------------------------------------------- +if __name__ == "__main__": + import sys + + macro_path = sys.argv[1] if len(sys.argv) > 1 else "sample_xop.pro" + true_phi = float(sys.argv[2]) if len(sys.argv) > 2 else -20.0 + energy_range = (4000.0, 12000.0) + + reflections = parse_xop_macro(macro_path) + E_true, fh_true, hkl_true = predicted_energies(reflections, true_phi, energy_range) + + # keep only reasonably strong lines, as a real measurement would only + # show glitches with non-negligible structure factor + keep = fh_true > np.percentile(fh_true, 50) if len(fh_true) else [] + synthetic_glitches = E_true[keep] + print( + f"Self-test: {len(synthetic_glitches)} synthetic glitches at true phi={true_phi}" + ) + + phi_best, score_best, phi_grid, scores = find_azimuth( + reflections, synthetic_glitches, energy_range + ) + print( + f"Self-test: recovered phi = {phi_best:.2f} deg " + f"(true = {true_phi} deg), score = {score_best:.2f}" + ) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py index ce052fb..304dc0f 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py @@ -43,6 +43,7 @@ from qtpy.QtWidgets import ( from ....bec_ipython_client.plugins.digital_twin_core.digital_twin_core import DigitalTwinCore from ....bec_ipython_client.plugins.digital_twin_core.types import BeamlineId, ConfigDict from ..edge_selector import EdgeSelector +from .glitches_preview import GlitchesPreview from .panels.input_panel import InputPanel from .panels.mover_panel import MoverPanel from .panels.plots import SideviewPlot, SurfacePlots @@ -132,6 +133,7 @@ class DigitalTwin(BECWidget, QWidget): self.input.cm_pitch.value_changed_connect(self.calc_assistant) self.input.mo1_mode.activated_connect(self.calc_assistant) self.input.mo1_xtal.activated_connect(self.calc_assistant) + self.input.mo1_glitch_preview.clicked_connect(self.open_glitches_preview) self.input.fm_stripe.activated_connect(self.calc_assistant) self.input.fm_focus.activated_connect(self.calc_assistant) self.input.fm_rotx.value_changed_connect(self.calc_assistant) @@ -152,6 +154,8 @@ class DigitalTwin(BECWidget, QWidget): self.settings.load_from_scan.clicked_connect(self.load_from_scan) self.edge_selector_energy = 0.0 + self.edge_selector_element = "" + self.edge_selector_edge = "" self.bragg_angle = 0.0 self.qy = 0.0 @@ -230,6 +234,7 @@ class DigitalTwin(BECWidget, QWidget): devices.extend( [ "cm_bnd_radius", + "mo1_roty", "fm_bnd_radius", "sl2_centery", "sl2_gapy", @@ -316,6 +321,7 @@ class DigitalTwin(BECWidget, QWidget): self.calc_cm_fm_harm_suppr() self.calc_fm_ideal_pitch() self.calc_mo1_energy_resolution() + self.update_mo1_azm_angle() case "energy": self.update_edge_selected() self.calc_mo1_bragg_angle() @@ -340,6 +346,7 @@ class DigitalTwin(BECWidget, QWidget): case "mo1_xtal": self.calc_mo1_bragg_angle() self.calc_mo1_energy_resolution() + self.update_mo1_azm_angle() case "fm_focus": self.update_fm_mode() self.calc_fm_ideal_pitch() @@ -414,6 +421,7 @@ class DigitalTwin(BECWidget, QWidget): "mo1_mode": self.input.mo1_mode.currentText(), "mo1_xtal": self.input.mo1_xtal.currentText(), "mo1_bragg": self.bragg_angle, + "mo1_roty": self.input.mo1_azm_angle.value(), "fm_rotx": -fm_rotx, "fm_stripe": fm_stripe, "fm_trx": fm_trx, @@ -464,6 +472,8 @@ class DigitalTwin(BECWidget, QWidget): self.input.fm_stripe.set_current_text(config["fm_stripe"]) self.input.mo1_mode.set_current_text(config["mo1_mode"]) self.input.mo1_xtal.set_current_text(config["mo1_xtal"]) + if self.beamline == BeamlineId.X01DA: + self.input.mo1_azm_angle.set_number(config["mo1_roty"]) self.bragg_angle = config["mo1_bragg"] @@ -529,10 +539,12 @@ class DigitalTwin(BECWidget, QWidget): es1man_trz = self.dev.es1man_trz.read(cached=True)["es1man_trz"]["value"] if self.beamline == BeamlineId.X01DA: + mo1_roty = self.dev.mo1_roty.read(cached=True)["mo1_roty"]["value"] ot_es1_trz = self.dev.ot_es1_trz.read(cached=True)["ot_es1_trz"]["value"] ot_es2_trz = self.dev.ot_es2_trz.read(cached=True)["ot_es2_trz"]["value"] smpl_to_xrd = ot_es2_trz - ot_es1_trz - es1man_trz + 32 else: + mo1_roty = 0 # No axis for roty available at SuperXAS table = self.input.table.currentText() ot_es1_trz = self.core.table_to_smpl_pos(table) smpl_to_xrd = None @@ -547,6 +559,7 @@ class DigitalTwin(BECWidget, QWidget): "mo1_mode": mo1_mode, "mo1_xtal": mo1_bragg["mo1_bragg_crystal_current_xtal_string"]["value"], "mo1_bragg": mo1_bragg["mo1_bragg_angle"]["value"] / 180 * np.pi, + "mo1_roty": mo1_roty, "fm_rotx": -fm_rotx_real * 1e-3, "fm_stripe": fm_stripe, "fm_trx": fm_trx, @@ -583,6 +596,10 @@ class DigitalTwin(BECWidget, QWidget): self.mover.mo1_bragg_angle.set_feedback(mo1_bragg["mo1_bragg_angle"]["value"]) self.mover.mo1_trx.set_feedback(mo1_trx) self.mover.mo1_try.set_feedback(self.dev.mo1_try.read(cached=True)["mo1_try"]["value"]) + if self.beamline == BeamlineId.X01DA: + self.mover.mo1_roty.set_feedback( + self.dev.mo1_roty.read(cached=True)["mo1_roty"]["value"] + ) self.mover.sl1_centery.set_feedback( self.dev.sl1_centery.read(cached=True)["sl1_centery"]["value"] ) @@ -641,6 +658,10 @@ class DigitalTwin(BECWidget, QWidget): pos["cm_trx"] = self.dev.cm_trx.read(cached=True)["cm_trx"]["value"] pos["cm_rotx"] = self.dev.cm_rotx.read(cached=True)["cm_rotx"]["value"] pos["mo1_trx"] = self.dev.mo1_trx.read(cached=True)["mo1_trx"]["value"] + if self.beamline == BeamlineId.X01DA: + pos["mo1_roty"] = self.dev.mo1_roty.read(cached=True)["mo1_roty"]["value"] + else: + pos["mo1_roty"] = 0 pos["fm_trx"] = self.dev.fm_trx.read(cached=True)["fm_trx"]["value"] pos["fm_rotx"] = self.dev.fm_rotx.read(cached=True)["fm_rotx"]["value"] pos["fm_bnd_radius"] = self.dev.fm_bnd_radius.read(cached=True)["fm_bnd_radius"]["value"] @@ -670,6 +691,10 @@ class DigitalTwin(BECWidget, QWidget): self.input.mo1_xtal.set_current_text( self.dev.mo1_bragg.read(cached=False)["mo1_bragg_crystal_current_xtal_string"]["value"] ) + if self.beamline == BeamlineId.X01DA: + self.input.mo1_azm_angle.set_number(pos["mo1_roty"]) + else: + self.input.mo1_azm_angle.setValue(pos["mo1_roty"]) fm_stripe = self.core.fm_trx_to_stripe(-pos["fm_trx"]) self.input.fm_stripe.set_current_text(fm_stripe) fm_rotx_real = 2 * pos["cm_rotx"] - pos["fm_rotx"] @@ -905,6 +930,10 @@ class DigitalTwin(BECWidget, QWidget): pos["cm_trx"] = cast(h5py.Dataset, devices["cm_trx/cm_trx/value"])[()] pos["cm_rotx"] = cast(h5py.Dataset, devices["cm_rotx/cm_rotx/value"])[()] pos["mo1_trx"] = cast(h5py.Dataset, devices["mo1_trx/mo1_trx/value"])[()] + if self.beamline == BeamlineId.X01DA: + pos["mo1_roty"] = cast(h5py.Dataset, devices["mo1_roty/mo1_roty/value"])[()] + else: + pos["mo1_roty"] = 0 pos["fm_trx"] = cast(h5py.Dataset, devices["fm_trx/fm_trx/value"])[()] pos["fm_rotx"] = cast(h5py.Dataset, devices["fm_rotx/fm_rotx/value"])[()] pos["fm_bnd_radius"] = cast(h5py.Dataset, devices["fm_bnd_radius/fm_bnd_radius/value"])[()] @@ -940,6 +969,10 @@ class DigitalTwin(BECWidget, QWidget): )[()] ) + if self.beamline == BeamlineId.X01DA: + self.input.mo1_azm_angle.set_number(pos["mo1_roty"]) + else: + self.input.mo1_azm_angle.setValue(pos["mo1_roty"]) fm_stripe = self.core.fm_trx_to_stripe(-pos["fm_trx"]) self.input.fm_stripe.set_current_text(fm_stripe) fm_rotx_real = 2 * pos["cm_rotx"] - pos["fm_rotx"] @@ -967,6 +1000,39 @@ class DigitalTwin(BECWidget, QWidget): self.calc_assistant(identifier="init") + def update_mo1_azm_angle(self): + if self.beamline == BeamlineId.X01DA: + mo1_roty = self.dev.mo1_roty.describe(cached=True)["mo1_roty"] + ll = mo1_roty["lower_ctrl_limit"] + hl = mo1_roty["upper_ctrl_limit"] + + # Apply offsets + ll = self.core.apply_offsets({"mo1_roty": ll}, nested_config=False) + hl = self.core.apply_offsets({"mo1_roty": hl}, nested_config=False) + + self.input.mo1_azm_angle.set_range(ll, hl) + else: + azm_angle = self.core.apply_offsets({"mo1_roty": 0}, nested_config=False) + self.input.mo1_azm_angle.setValue(azm_angle) + + def open_glitches_preview(self): + xtal = self.input.mo1_xtal.currentText() + azm_angle = self.input.mo1_azm_angle.value() + if self.beamline == BeamlineId.X01DA: + ll, hl = self.input.mo1_azm_angle.get_range() + else: + ll, hl = None, None + if self.edge_selector_energy != 0: + dlg = GlitchesPreview( + self, xtal, azm_angle, ll, hl, self.edge_selector_element, self.edge_selector_edge + ) + else: + dlg = GlitchesPreview(self, xtal, azm_angle, self.input.energy.value()) + if dlg.exec_(): + self.input.mo1_xtal.set_current_text(dlg.xtal_selector.currentText()) + if self.beamline == BeamlineId.X01DA: + self.input.mo1_azm_angle.set_number(dlg.azm_angle) + def update_fm_mode(self): """ Updates the focusing mirror input group based on the @@ -1015,6 +1081,8 @@ class DigitalTwin(BECWidget, QWidget): if dlg.exec_(): self.input.edge_selected.setText(f"{dlg.selected_element}, {dlg.selected_edge}-edge") self.edge_selector_energy = dlg.selected_energy + self.edge_selector_element = dlg.selected_element + self.edge_selector_edge = dlg.selected_edge self.input.energy.set_number(dlg.selected_energy) def update_edge_selected(self): @@ -1108,6 +1176,8 @@ class DigitalTwin(BECWidget, QWidget): self.mover.mo1_bragg_angle.set_target(out["mo1_bragg_angle"]["value"]) self.mover.mo1_trx.set_target(out["mo1_trx"]["value"]) self.mover.mo1_try.set_target(out["mo1_try"]["value"]) + if self.beamline == BeamlineId.X01DA: + self.mover.mo1_roty.set_target(out["mo1_roty"]["value"]) self.mover.sl1_centery.set_target(out["sl1_centery"]["value"]) self.mover.sl1_gapy.set_target(out["sl1_gapy"]["value"]) self.mover.bm1_try.set_target(out["bm1_try"]["value"]) @@ -1128,7 +1198,7 @@ class DigitalTwin(BECWidget, QWidget): self.mover.ot_es2_trz.set_target(out["ot_es2_trz"]["value"]) self.mover.es0wi_try.set_target(out["es0wi_try"]["value"]) self.mover.es1man_trz.set_target(out["es1man_trz"]["value"]) - if self.beamline == "x10da": + if self.beamline == BeamlineId.X10DA: self.mover.es1_try.set_target(out["es1_try"]["value"]) self.mover.es1ic0_try.set_target(out["es1ic0_try"]["value"]) self.mover.es1ic1_try.set_target(out["es1ic1_try"]["value"]) @@ -1166,10 +1236,14 @@ class DigitalTwin(BECWidget, QWidget): self.input.mo1_xtal.setVisible(True) self.input.mo1_bragg_angle.setVisible(True) self.input.mo1_eres.setVisible(True) + self.input.mo1_azm_angle.setVisible(True) + self.input.mo1_glitch_preview.setVisible(True) else: self.input.mo1_xtal.setVisible(False) self.input.mo1_bragg_angle.setVisible(False) self.input.mo1_eres.setVisible(False) + self.input.mo1_azm_angle.setVisible(False) + self.input.mo1_glitch_preview.setVisible(False) def calc_fm_ideal_pitch(self): """ diff --git a/debye_bec/bec_widgets/widgets/digital_twin/glitches_preview.py b/debye_bec/bec_widgets/widgets/digital_twin/glitches_preview.py new file mode 100644 index 0000000..4707e69 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/digital_twin/glitches_preview.py @@ -0,0 +1,148 @@ +""" +GlitchesPreview: QDialog to preview monochromator glitches +""" + +import numpy as np +import pyqtgraph as pg +import xraydb +from bec_lib import bec_logger +from bec_widgets.utils.colors import Colors, get_accent_colors +from bec_widgets.utils.error_popups import SafeSlot + +# pylint: disable=E0611 +from qtpy.QtWidgets import QDialog, QHBoxLayout, QLabel, QPushButton, QVBoxLayout + +from .azimuth_calculator import parse_xop_macro, predicted_energies +from .widgets.qt_widgets import ComboBox, InputNumberField + +logger = bec_logger.logger + +EV_BELOW = 200 +EV_ABOVE = 1000 + + +def edge_step(energies, edge_energy, width_ev=1.5): + """Plain logistic step 0 -> 1 (no EXAFS/pre-edge), for a readable + visual reference of where a real edge would fall.""" + x = np.clip(-(energies - edge_energy) / width_ev, -500, 500) + return 1.0 / (1.0 + np.exp(x)) + + +class GlitchesPreview(QDialog): + """QDialog to preview monochromator glitches""" + + def __init__( + self, + parent, + xtal: str, + azm_angle: float, + azm_ll: float | None = None, + azm_hl: float | None = None, + element: str | None = "", + edge: str | None = "", + energy: float = 12000, + ): + super().__init__(parent) + self.setWindowTitle("Glitches Preview") + + if element != "": + self.energy = xraydb.xray_edge(element, edge, energy_only=True) + self.energies = np.linspace(energy - EV_BELOW, energy + EV_ABOVE, 1000) + self.mu = edge_step(self.energies, self.energy) + else: + self.energy = energy + self.energies = np.linspace(energy - EV_BELOW, energy + EV_ABOVE, 1000) + self.mu = np.ones(len(self.energies)) + + layout = QVBoxLayout(self) + text = QLabel("Preview of monochromator glitches.") + layout.addWidget(text) + + self.xtal_selector = ComboBox("mo1_xtal", "Crystal", ["Si(111)", "Si(311)"]) + self.xtal_selector.set_current_text(xtal) + self.xtal_selector.activated_connect(self.update_plot) + layout.addWidget(self.xtal_selector) + + self.azm_angle = azm_angle + self.azm_input = None + if azm_hl is not None and azm_ll is not None: + azm_input = InputNumberField( + "azm_angle", + "Azm. Angle", + unit="deg", + init=azm_angle, + decimals=3, + single_step=0.01, + ll=azm_ll, + hl=azm_hl, + ) + azm_input.value_changed_connect(self.update_plot) + layout.addWidget(azm_input) + accept_text = "Select xtal and azm. angle" + else: + accept_text = "Select xtal" + + self.plot = pg.PlotWidget() + self.plot.setLabel("bottom", "Energy", units="eV") + self.plot.setLabel("left", "Beam Intensity") + self.plot.addLegend() + self.plot.setYRange(-0.15, 1.2) + color = Colors.golden_angle_color(colormap="plasma", num=1, format="HEX") + self.curve_edge = self.plot.plot(pen=pg.mkPen(color=color, width=2)) + layout.addWidget(self.plot) + + button_layout = QHBoxLayout() + self._cancel_button = QPushButton("Close") + self._cancel_button.clicked.connect(self.reject) + self._cancel_button.setStyleSheet( + f"QPushButton {{background-color: {get_accent_colors().default.name()}; color: white;}}" + ) + self._select_button = QPushButton(accept_text) + self._select_button.setEnabled(False) + self._select_button.clicked.connect(self.accept) + self._select_button.setStyleSheet( + f"QPushButton {{background-color: {get_accent_colors().default.name()}; color: white;}}" + ) + + button_layout.addStretch() + button_layout.addWidget(self._cancel_button) + button_layout.addWidget(self._select_button) + button_layout.addStretch() + + layout.addLayout(button_layout) + + self.adjustSize() + self.setFixedSize(self.sizeHint()) + + self.reflections_si111 = parse_xop_macro( + "xop_si111_Si-LN2_8-8-8_4500-60000eV_-180-180deg.pro" + ) + self.reflections_si311 = parse_xop_macro("xop_si311_Si-LN2_8-8-8_4500-60000eV_0-360deg.pro") + + @SafeSlot() + def update_plot(self): + if isinstance(self.azm_input, InputNumberField): + self.azm_angle = self.azm_input.value() + if self.xtal_selector.currentText() == "Si(111)": + reflections = self.reflections_si111 + else: + reflections = self.reflections_si311 + e_pred, fh, _ = predicted_energies( + reflections, self.azm_angle, (self.energies[0], self.energies[-1]) + ) + if len(fh) == 0: + self.curve_edge.setData(self.energies, self.mu) + logger.info(f"phi = {self.azm_angle:.1f} deg | 0 glitches in window") + return + + logw = np.log10(fh) + wnorm = ( + (logw - logw.min()) / (logw.max() - logw.min()) + if logw.max() > logw.min() + else np.ones_like(logw) + ) + + for e, wn in zip(e_pred, wnorm): + depth = 0.02 + 0.08 * wn + mu = self.mu - depth * np.exp(-0.5 * ((self.energies - e) / 1.5) ** 2) + self.curve_edge.setData(self.energies, mu) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py b/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py index 3616160..4599a54 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py @@ -113,8 +113,32 @@ class InputPanel(QWidget): self.mo1_xtal = ComboBox("mo1_xtal", "Crystal", ["Si(111)", "Si(311)"]) self.mo1_bragg_angle = NumberIndicator("Bragg Angle", "deg", decimals=1) self.mo1_eres = NumberIndicator("Energy Resolution", "eV", decimals=2) + + if beamline == BeamlineId.X01DA: + self.mo1_azm_angle = InputNumberField( + "azm_angle", + "Azm. Angle", + unit="deg", + init=0, + decimals=3, + single_step=0.01, + ll=-10, + hl=10, + ) + else: + self.mo1_azm_angle = NumberIndicator("Azm. Angle", "deg", decimals=3) + self.mo1_glitch_preview = Button("Glitches Preview", "Open", enabled=True) + self.mo1_ass_group = Group( - "Monochromator", [self.mo1_mode, self.mo1_xtal, self.mo1_bragg_angle, self.mo1_eres] + "Monochromator", + [ + self.mo1_mode, + self.mo1_xtal, + self.mo1_bragg_angle, + self.mo1_eres, + self.mo1_azm_angle, + self.mo1_glitch_preview, + ], ) # Focusing Mirror diff --git a/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py b/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py index bd43e05..2c98af5 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py @@ -136,9 +136,25 @@ class MoverPanel(QWidget): ) self.mover_widgets.append(self.mo1_try) - self.mo1_mov_group = Group( - "Monochromator", [self.mo1_bragg_angle, self.mo1_trx, self.mo1_try] - ) + if beamline == BeamlineId.X01DA: + self.mo1_roty = MoveWidget( + beamline=beamline, + dev=dev, + motor="mo1_roty", + label="ROTY", + unit="deg", + decimals=3, + deadband=0.01, + ) + self.mover_widgets.append(self.mo1_roty) + + self.mo1_mov_group = Group( + "Monochromator", [self.mo1_bragg_angle, self.mo1_trx, self.mo1_try, self.mo1_roty] + ) + else: + self.mo1_mov_group = Group( + "Monochromator", [self.mo1_bragg_angle, self.mo1_trx, self.mo1_try] + ) # OP Slits 1 self.sl1_centery = MoveWidget( diff --git a/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py b/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py index b127418..9b984a1 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py @@ -106,10 +106,20 @@ class InputNumberField(QWidget): if prefix is not None: self.val.setPrefix(prefix + " ") layout.addWidget(self.val) + self.ll = ll + self.hl = hl def set_number(self, number): self.val.setValue(number) + def set_range(self, ll, hl): + self.val.setRange(ll, hl) + self.ll = ll + self.hl = hl + + def get_range(self): + return (self.ll, self.hl) + def has_focus(self) -> bool: return self.val.hasFocus() diff --git a/debye_bec/bec_widgets/widgets/digital_twin/xop_si111_Si-LN2_8-8-8_4500-60000eV_-180-180deg.pro b/debye_bec/bec_widgets/widgets/digital_twin/xop_si111_Si-LN2_8-8-8_4500-60000eV_-180-180deg.pro new file mode 100644 index 0000000..b61fa07 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/digital_twin/xop_si111_Si-LN2_8-8-8_4500-60000eV_-180-180deg.pro @@ -0,0 +1,7812 @@ +; (xop/mare spaghetti macro) +; +; XOP/IDL macro created by MARE +; (Do not change this macro. Use Edit Parameters for user customization.) +; xop/mare multiple diffraction +; +; inputs: +; crystal index: 2 +; crystal name: Si_LN2 +; Main reflection: [1,1,1] +; Max reflections: [8,8,8] +; Wavelength [A] 1.5400000 +; Delta Wavelength [A] 0.0100000 +; Phi [deg] -20.000000 +; Delta Phi [deg] 0.10000000 +; Display: 0 +; Using reflections with fh > 1.0000000e-008 +; +; Computed parameters: +; Number of good reflections: 864 +; M vector (corresponding to phi=0) [1,-1,0] +; Intensity of main reflection: 6821.5499 +; Structure Factor fh of main reflection: 60.536598 +; Reflection with maximum intensity: +; number: 66 +; miller indices: -2 -2 0 +; fh value: 70.708675 +; +;parms = {n:500L, xmin:-90.,xmax:90.,eV:['0','A','eV'],ymin:0.,ymax:3.5} +alpha = makearray1(parms.n,parms.xmin,parms.xmax,/double) +IF Fix(parms.eV[0]) EQ 1 THEN ytitle='Photon energy [eV]' ELSE ytitle='Wavelength [A]' +plot,alpha,alpha*0,xrange=[parms.xmin,parms.xmax],yrange=[parms.ymin,parms.ymax],/nodata,/xstyle,/ystyle,title='MARE-spaghetti, Main diffraction: [1,1,1] Si_LN2',xtitle='Azimuthal angle [deg]',ytitle=ytitle +lambdas=[1.5300000,1.5400000,1.5500000] +phis=[-20.100000,-20.000000,-19.900000] +IF Fix(parms.eV[0]) EQ 1 THEN yy=physical_constants('hc')/lambdas ELSE yy=lambdas +labelflg = Fix(parms.labels[0]) +; -------------------------------- +; Reflection nr: 1 +; h k l alpha0 k p2/4 th2 th2 th2 th3 th3 th3 lambda lambda lambda BrgAngU BrgAngG fh +; -1 -1 -3 90.0000 0.902425 0.0254491 -1000.00 -1000.00 -1000.00 -1000.00 -1000.00 -1000.00 0.380117 0.378310 0.376502 28.0620 6.63612 46.7334 +ilabel=randomu(seed)*(parms.n-1) +y3 = 1D/sqrt((0.90242477/cos((alpha-90.000000)*!dpi/180))^2+0.025449077) +IF Fix(parms.eV[0]) EQ 1 THEN y3=physical_constants('hc',/Double)/y3 +oplot,alpha,y3,color= 1 +IF labelflg THEN XYouts,CharS=0.95,alpha[iLabel],y3[iLabel]+.02 1.0000000e-008 +; +; Computed parameters: +; Number of good reflections: 874 +; M vector (corresponding to phi=0) [1,-3,0] +; Intensity of main reflection: 1723.9218 +; Structure Factor fh of main reflection: 46.733379 +; Reflection with maximum intensity: +; number: 67 +; miller indices: -2 -2 0 +; fh value: 70.708675 +; +;parms = {n:500L, xmin:-90.,xmax:90.,eV:['0','A','eV'],ymin:0.,ymax:3.5} +alpha = makearray1(parms.n,parms.xmin,parms.xmax,/double) +IF Fix(parms.eV[0]) EQ 1 THEN ytitle='Photon energy [eV]' ELSE ytitle='Wavelength [A]' +plot,alpha,alpha*0,xrange=[parms.xmin,parms.xmax],yrange=[parms.ymin,parms.ymax],/nodata,/xstyle,/ystyle,title='MARE-spaghetti, Main diffraction: [3,1,1] Si_LN2',xtitle='Azimuthal angle [deg]',ytitle=ytitle +lambdas=[1.5300000,1.5400000,1.5500000] +phis=[-20.100000,-20.000000,-19.900000] +IF Fix(parms.eV[0]) EQ 1 THEN yy=physical_constants('hc')/lambdas ELSE yy=lambdas +labelflg = Fix(parms.labels[0]) +; -------------------------------- +; Reflection nr: 1 +; h k l alpha0 k p2/4 th2 th2 th2 th3 th3 th3 lambda lambda lambda BrgAngU BrgAngG fh +; -1 -1 -1 42.1304 0.864006 0.0933133 -1000.00 -1000.00 -1000.00 -1000.00 -1000.00 -1000.00 0.532081 0.533797 0.535511 14.2216 4.88496 60.5366 +ilabel=randomu(seed)*(parms.n-1) +y3 = 1D/sqrt((0.86400594/cos((alpha-42.130415)*!dpi/180))^2+0.093313283) +IF Fix(parms.eV[0]) EQ 1 THEN y3=physical_constants('hc',/Double)/y3 +oplot,alpha,y3,color= 1 +IF labelflg THEN XYouts,CharS=0.95,alpha[iLabel],y3[iLabel]+.02 Date: Wed, 23 Sep 2026 15:07:43 +0200 Subject: [PATCH 34/56] wip --- .../plugins/digital_twin_core/x10da_offsets.yaml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_offsets.yaml b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_offsets.yaml index f0fe9a8..c96e922 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_offsets.yaml +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_offsets.yaml @@ -11,6 +11,12 @@ mo1_trx: range: [[-30, -0.1], [0.1, 30]] offset: [-4.3, 0] +mo1_roty: + modifier: + axis: mo1_trx + range: [[-30, -0.1], [0.1, 30]] # Si111, Si311 + offset: [116.400, 137.605] + sl1_centery: offset: -55.54 From 93d5a4d03dc1bbaa1fb13837dc0c860c98eaa426 Mon Sep 17 00:00:00 2001 From: hitz_s Date: Wed, 23 Sep 2026 15:33:49 +0200 Subject: [PATCH 35/56] wip --- debye_bec/bec_widgets/widgets/scheduler/scheduler.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index ff903f1..76451fe 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -136,6 +136,9 @@ def build_item_display_text(item: ScheduleItem, beamline: str | None) -> str: else: devices += f", {device}" text += devices + elif item.command.startswith("dev.abs."): + action = item.form_state["action"] + text += f"{action} Absorber" if text == "": text = f"{item.command}" if item.error: From 64a8cc035fd56c98593be6ed0e1bb3a8ca6c033f Mon Sep 17 00:00:00 2001 From: hitz_s Date: Thu, 24 Sep 2026 08:08:21 +0200 Subject: [PATCH 36/56] Add curent_foil to reference foil changer --- debye_bec/devices/reffoilchanger.py | 69 ++++++++++++++++++- .../file_writer/debye_nexus_structure.py | 12 +++- 2 files changed, 78 insertions(+), 3 deletions(-) diff --git a/debye_bec/devices/reffoilchanger.py b/debye_bec/devices/reffoilchanger.py index 9bd5a9c..d3daee9 100644 --- a/debye_bec/devices/reffoilchanger.py +++ b/debye_bec/devices/reffoilchanger.py @@ -5,8 +5,9 @@ from __future__ import annotations import enum from typing import TYPE_CHECKING +from bec_lib.logger import bec_logger from ophyd import Component as Cpt -from ophyd import EpicsSignal, EpicsSignalRO, EpicsSignalWithRBV +from ophyd import EpicsSignal, EpicsSignalRO, EpicsSignalWithRBV, Signal from ophyd.status import DeviceStatus from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase from ophyd_devices.utils.errors import DeviceStopError @@ -14,6 +15,8 @@ from ophyd_devices.utils.errors import DeviceStopError if TYPE_CHECKING: from bec_lib.devicemanager import ScanInfo +logger = bec_logger.logger + class Status(int, enum.Enum): """Enum class for the status field""" @@ -34,6 +37,63 @@ class OpMode(int, enum.Enum): ERRORMODE = 3 +N_FOILS = 38 + + +class CurrentFoilSignal(Signal): + """ + Soft signal reflecting the description of the foil currently + inserted. Recomputed whenever 'ref_rb', 'status' or any of the + `foilNN` signals on the parent device change. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._subscribed = False + + def _foil_signal(self): + if self.parent.status.get() != Status.INSERTED: + return None + idx = self.parent.ref_rb.get() + try: + idx = int(round(idx)) + 1 + except (TypeError, ValueError): + return None + return getattr(self.parent, f"foil{idx:02d}", None) + + def _compute(self): + sig = self._foil_signal() + if sig is None: + return "" + try: + return sig.get() + except Exception: + logger.exception("current_foil: failed to read %s", sig.name) + return "" + + def get(self, **kwargs): + self._readback = self._compute() + return self._readback + + def _on_upstream_change(self, value=None, timestamp=None, **kwargs): + old_value = self._readback + new_value = self._compute() + self._readback = new_value + self._run_subs( + sub_type=self.SUB_VALUE, old_value=old_value, value=new_value, timestamp=timestamp + ) + + def subscribe_to_parent_signals(self): + if self._subscribed: + return + self.parent.ref_rb.subscribe(self._on_upstream_change, run=False) + self.parent.status.subscribe(self._on_upstream_change, run=False) + for i in range(1, N_FOILS + 1): + getattr(self.parent, f"foil{i:02d}").subscribe(self._on_upstream_change, run=False) + self._subscribed = True + self._readback = self._compute() + + class Reffoilchanger(PSIDeviceBase): """Class for the ES2 Reference Foil Changer""" @@ -71,8 +131,12 @@ class Reffoilchanger(PSIDeviceBase): ) ref_set = Cpt(EpicsSignal, suffix="ES2-REF:SELN-SET", kind="config", doc="Requested reference") ref_rb = Cpt( - EpicsSignalRO, suffix="ES2-REF:SELN-RB", kind="config", doc="Currently set reference" + EpicsSignalRO, + suffix="ES2-REF:SELN-RB", + kind="config", + doc="Currently set reference (angle)", ) + current_foil = Cpt(CurrentFoilSignal, value="", kind="normal", doc="Inserted reference") foil01 = Cpt(EpicsSignalRO, suffix="ES-REFFOIL:FOIL01.DESC", kind="config", doc="Foil 01") foil02 = Cpt(EpicsSignalRO, suffix="ES-REFFOIL:FOIL02.DESC", kind="config", doc="Foil 02") @@ -115,6 +179,7 @@ class Reffoilchanger(PSIDeviceBase): def __init__(self, *, name: str, prefix: str = "", scan_info: ScanInfo | None = None, **kwargs): super().__init__(name=name, prefix=prefix, scan_info=scan_info, **kwargs) + self.current_foil.subscribe_to_parent_signals() self.foils = [ self.foil01, diff --git a/debye_bec/file_writer/debye_nexus_structure.py b/debye_bec/file_writer/debye_nexus_structure.py index 79f1044..f647b29 100644 --- a/debye_bec/file_writer/debye_nexus_structure.py +++ b/debye_bec/file_writer/debye_nexus_structure.py @@ -236,7 +236,9 @@ class DebyeNexusStructure(DefaultFormat): self.configuration.get("nidaq", {}).get("nidaq_add_chans", {}).get("value") ) - rle = self.configuration.get("nidaq", {}).get("nidaq_enable_compression", {}).get("value") + rle = ( + self.configuration.get("nidaq", {}).get("nidaq_enable_compression", {}).get("value") + ) measurement_mode = entry.create_group(name="mode") measurement_mode.attrs["NX_class"] = "NX_CHAR" @@ -288,6 +290,14 @@ class DebyeNexusStructure(DefaultFormat): ) ref_trans.attrs["NX_class"] = "NX_CHAR" + foil = ( + self.device_manager.devices.reffoilchanger.read(cached=True) + .get("current_foil") + .get("value") + ) + ref_foil = ai2ai4_active.create_dataset(name="Reference", data=foil) + ref_foil.attrs["NX_class"] = "NX_CHAR" + main_data = entry.create_group(name="data") main_data.attrs["NX_class"] = "NXdata" From 6452b7cea46f18fa2f36ffa7d48148a7f32ea9f2 Mon Sep 17 00:00:00 2001 From: hitz_s Date: Thu, 24 Sep 2026 14:37:59 +0200 Subject: [PATCH 37/56] wip --- .../widgets/scheduler/schedule_logic.py | 10 +++-- .../widgets/scheduler/scheduler.py | 39 +++++++++++++++---- 2 files changed, 38 insertions(+), 11 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/scheduler/schedule_logic.py b/debye_bec/bec_widgets/widgets/scheduler/schedule_logic.py index 4073793..c229619 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/schedule_logic.py +++ b/debye_bec/bec_widgets/widgets/scheduler/schedule_logic.py @@ -46,7 +46,7 @@ def index_of(items: list[ScheduleItem], item_id: str | None) -> int | None: def pick_next_runnable( - items: list[ScheduleItem], repeat_aborted_item + items: list[ScheduleItem], repeat_aborted_item, first_item: int = 0 ) -> ScheduleItem | Literal["stop"] | None: """ What the execution loop should do next: always re-derived from scratch @@ -57,9 +57,13 @@ def pick_next_runnable( earlier item failed/was aborted (execution stays parked there until the operator intervenes), or `None` if every item is COMPLETED. """ - logger.info(f"pick next runnable, repeat abort item is {repeat_aborted_item}") - for item in items: + logger.info( + f"pick next runnable, repeat abort item is {repeat_aborted_item} and first item is {first_item}" + ) + for idx, item in enumerate(items): logger.info(f"item: {item}") + if idx < first_item: + continue if item.status == ScheduleItemStatus.COMPLETED: continue if item.status == ScheduleItemStatus.ABORTED: diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 76451fe..2bcf498 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -460,14 +460,16 @@ class Scheduler(BECWidget, QWidget): run_row = QHBoxLayout() self.run_btn = MyButton("Run / Continue", "success") - self.abort_btn = MyButton("Abort", "emergency") - self.reset_btn = MyButton("Reset", "warning") - for button in (self.run_btn, self.abort_btn, self.reset_btn): + self.run_from_current_btn = MyButton("Run / Continue from current selection", "success") + self.abort_btn = MyButton("Pause after current item", "emergency") + self.reset_btn = MyButton("Reset Schedule Status", "warning") + for button in (self.run_btn, self.run_from_current_btn, self.abort_btn, self.reset_btn): run_row.addWidget(button) run_row.addStretch() control_layout.addLayout(run_row) self.run_btn.clicked.connect(self.run_schedule) + self.run_from_current_btn.connect(self.run_schedule_from_selection) self.abort_btn.clicked.connect(self.abort_schedule) self.reset_btn.clicked.connect(self.reset_schedule) @@ -660,8 +662,10 @@ class Scheduler(BECWidget, QWidget): row = self._table_model.row_of(self._selected_item_id) if row is not None: self.table_view.selectRow(row) + self.run_from_current_btn.setEnabled(True) else: self._selected_item_id = None + self.run_from_current_btn.setEnabled(False) selection_model.blockSignals(False) @@ -722,6 +726,13 @@ class Scheduler(BECWidget, QWidget): self.copy_btn.setEnabled(selected_item is not None) self.paste_btn.setEnabled(self._clipboard_item is not None) + # Update execution control buttons + state = self._current_report is None # True if schedule is not running + self.run_btn.setEnabled(state) + self.run_from_current_btn.setEnabled(state) + self.abort_btn.setEnabled(not state) + self.reset_btn.setEnabled(state) + @SafeSlot() def _on_schedule_name_change(self): name = self.schedule_name_input.text() @@ -1103,7 +1114,7 @@ class Scheduler(BECWidget, QWidget): # RPC-exposed actions (USER_ACCESS) # ------------------------------------------------------------------ # @SafeSlot() - def run_schedule(self): + def run_schedule(self, first_item: int = 0): """Run the schedule, continuing from wherever it last left off.""" with self._lock: if self.schedule.is_running: @@ -1126,9 +1137,21 @@ class Scheduler(BECWidget, QWidget): self.submit_task( self._run_all, repeat_aborted_item, + first_item, on_complete=self._on_run_finished, on_failed=self._on_run_failed, ) + self._refresh_ui() + + @SafeSlot() + def run_schedule_from_selection(self): + """Run the schedule, starting from the current selected item.""" + if self._selected_item_id is None: + return + with self._lock: + idx = self._index_of_locked(self._selected_item_id) + if idx is not None: + self.run_schedule(idx) @SafeSlot() def abort_schedule(self): @@ -1314,9 +1337,9 @@ class Scheduler(BECWidget, QWidget): # the `schedule_changed` Qt signal so they are marshalled back onto # the GUI thread instead of touching widgets directly) # ------------------------------------------------------------------ # - def _pick_next_runnable_locked(self, repeat_aborted_item): + def _pick_next_runnable_locked(self, repeat_aborted_item, first_item): """Must be called while holding `self._lock`; see `schedule_logic.pick_next_runnable`.""" - return pick_next_runnable(self.schedule.items, repeat_aborted_item) + return pick_next_runnable(self.schedule.items, repeat_aborted_item, first_item) @SafeSlot() def _on_run_finished(self): @@ -1356,7 +1379,7 @@ class Scheduler(BECWidget, QWidget): super().cleanup() - def _run_all(self, repeat_aborted_item): + def _run_all(self, repeat_aborted_item, first_item): notify_schedule_state( self.client, self.schedule.notifications, self.schedule.schedule_name, "started" ) @@ -1369,7 +1392,7 @@ class Scheduler(BECWidget, QWidget): } while not self._abort_requested and not self._closing.is_set(): with self._lock: - next_item = self._pick_next_runnable_locked(repeat_aborted_item) + next_item = self._pick_next_runnable_locked(repeat_aborted_item, first_item) if next_item is None or next_item == "stop": logger.info("Next item is None or stop") break From 4479a5ab57abaa18693e977be46b776ee99f11c7 Mon Sep 17 00:00:00 2001 From: x01da Date: Mon, 28 Sep 2026 12:51:00 +0200 Subject: [PATCH 38/56] wip --- .../digital_twin_core/digital_twin_core.py | 29 +++-- .../digital_twin_core/x01da_offsets.yaml | 2 +- .../digital_twin_core/x10da_offsets.yaml | 2 +- .../widgets/digital_twin/digital_twin.py | 104 +++++++++++++----- .../widgets/digital_twin/glitches_preview.py | 71 ++++++++---- .../digital_twin/widgets/qt_widgets.py | 3 + 6 files changed, 148 insertions(+), 63 deletions(-) diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py index f9876d9..9ebf663 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py @@ -337,14 +337,7 @@ class DigitalTwinCore: # TRX, Crystal selection if cfg["mo1_mode"] == "Monochromatic": - xtal = cfg["mo1_xtal"].translate( - str.maketrans("", "", "()") - ) # Remove brackets from xtal name to conform with parameters - if xtal in bl.mo1.xtal: - index = bl.mo1.xtal.index(xtal) - else: - raise ValueError(f"Requested xtal {xtal} not found in parameters!") - pos["mo1_trx"] = {"value": bl.mo1.xtalOffsetX[index]} + pos["mo1_trx"] = {"value": self.mo1_xtal_to_trx(cfg["mo1_xtal"])} else: pos["mo1_trx"] = {"value": 0} @@ -679,6 +672,26 @@ class DigitalTwinCore: return de + @staticmethod + def mo1_xtal_to_trx(xtal: str) -> float: + """ + Returns the trx position for a given xtal. + + Args: + xtal(str): Xtal, e.g. "Si(111)" + + Returns: + float: Position of trx + """ + xtal = xtal.translate( + str.maketrans("", "", "()") + ) # Remove brackets from xtal name to conform with parameters + if xtal in bl.mo1.xtal: + index = bl.mo1.xtal.index(xtal) + else: + raise ValueError(f"Requested xtal {xtal} not found in parameters!") + return bl.mo1.xtalOffsetX[index] + @staticmethod def cm_reflectivity(cm_stripe: str, cm_pitch: float, energy: float) -> float: """ diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_offsets.yaml b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_offsets.yaml index 83f9ff0..2fe5196 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_offsets.yaml +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_offsets.yaml @@ -17,7 +17,7 @@ mo1_roty: modifier: axis: mo1_trx range: [[-30, -0.1], [0.1, 30]] # Si311, Si111 - offset: [136.80017, 89.15503] + offset: [-136.80017, -89.15503] sl1_centery: offset: -1.2 diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_offsets.yaml b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_offsets.yaml index c96e922..947e9b5 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_offsets.yaml +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_offsets.yaml @@ -15,7 +15,7 @@ mo1_roty: modifier: axis: mo1_trx range: [[-30, -0.1], [0.1, 30]] # Si111, Si311 - offset: [116.400, 137.605] + offset: [-116.400, -137.605] sl1_centery: offset: -55.54 diff --git a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py index 304dc0f..9702c5f 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py @@ -133,6 +133,8 @@ class DigitalTwin(BECWidget, QWidget): self.input.cm_pitch.value_changed_connect(self.calc_assistant) self.input.mo1_mode.activated_connect(self.calc_assistant) self.input.mo1_xtal.activated_connect(self.calc_assistant) + if self.beamline == BeamlineId.X01DA: + self.input.mo1_azm_angle.value_changed_connect(self.calc_assistant) self.input.mo1_glitch_preview.clicked_connect(self.open_glitches_preview) self.input.fm_stripe.activated_connect(self.calc_assistant) self.input.fm_focus.activated_connect(self.calc_assistant) @@ -157,6 +159,8 @@ class DigitalTwin(BECWidget, QWidget): self.edge_selector_element = "" self.edge_selector_edge = "" self.bragg_angle = 0.0 + self.old_xtal = self.input.mo1_xtal.currentText() + self.azm_ranges = {} self.qy = 0.0 # Initialize all values @@ -347,6 +351,8 @@ class DigitalTwin(BECWidget, QWidget): self.calc_mo1_bragg_angle() self.calc_mo1_energy_resolution() self.update_mo1_azm_angle() + case "mo1_azm_angle": + self.update_mo1_azm_angle() case "fm_focus": self.update_fm_mode() self.calc_fm_ideal_pitch() @@ -432,6 +438,8 @@ class DigitalTwin(BECWidget, QWidget): "smpl_to_xrd": smpl_to_xrd, } + config["mo1_trx"] = self.core.mo1_xtal_to_trx(self.input.mo1_xtal.currentText()) + # Apply offsets if apply_offset: config = self.core.apply_offsets(config, nested_config=False) @@ -688,17 +696,34 @@ class DigitalTwin(BECWidget, QWidget): else: mo1_mode = "Pinkbeam" self.input.mo1_mode.set_current_text(mo1_mode) - self.input.mo1_xtal.set_current_text( - self.dev.mo1_bragg.read(cached=False)["mo1_bragg_crystal_current_xtal_string"]["value"] - ) + current_xtal = self.dev.mo1_bragg.read(cached=False)[ + "mo1_bragg_crystal_current_xtal_string" + ]["value"] + self.input.mo1_xtal.set_current_text(current_xtal) if self.beamline == BeamlineId.X01DA: + mo1_roty_desc = self.dev.mo1_roty.describe()["mo1_roty"] + + for item in self.input.mo1_xtal.get_all_texts(): + mo1_trx = self.core.mo1_xtal_to_trx(item) + ll = self.core.remove_offsets( + {"mo1_roty": mo1_roty_desc["lower_ctrl_limit"], "mo1_trx": mo1_trx} + )["mo1_roty"] + hl = self.core.remove_offsets( + {"mo1_roty": mo1_roty_desc["upper_ctrl_limit"], "mo1_trx": mo1_trx} + )["mo1_roty"] + self.azm_ranges[item] = {} + self.azm_ranges[item]["ll"] = ll + self.azm_ranges[item]["hl"] = hl + + self.input.mo1_azm_angle.set_range( + self.azm_ranges[current_xtal]["ll"], self.azm_ranges[current_xtal]["hl"] + ) self.input.mo1_azm_angle.set_number(pos["mo1_roty"]) else: self.input.mo1_azm_angle.setValue(pos["mo1_roty"]) fm_stripe = self.core.fm_trx_to_stripe(-pos["fm_trx"]) self.input.fm_stripe.set_current_text(fm_stripe) fm_rotx_real = 2 * pos["cm_rotx"] - pos["fm_rotx"] - logger.info(f"In adapt reality, fm_rotx_real is {fm_rotx_real}") self.input.fm_rotx.set_number(fm_rotx_real) if self.beamline == BeamlineId.X01DA: @@ -964,9 +989,12 @@ class DigitalTwin(BECWidget, QWidget): mo1_mode = "Pinkbeam" self.input.mo1_mode.set_current_text(mo1_mode) self.input.mo1_xtal.set_current_text( - cast( - h5py.Dataset, devices["mo1_bragg/mo1_bragg_crystal_current_xtal_string/value"] - )[()] + str( + cast( + h5py.Dataset, + devices["mo1_bragg/mo1_bragg_crystal_current_xtal_string/value"], + )[()] + ) ) if self.beamline == BeamlineId.X01DA: @@ -976,7 +1004,6 @@ class DigitalTwin(BECWidget, QWidget): fm_stripe = self.core.fm_trx_to_stripe(-pos["fm_trx"]) self.input.fm_stripe.set_current_text(fm_stripe) fm_rotx_real = 2 * pos["cm_rotx"] - pos["fm_rotx"] - logger.info(f"In adapt reality, fm_rotx_real is {fm_rotx_real}") self.input.fm_rotx.set_number(fm_rotx_real) if self.beamline == BeamlineId.X01DA: @@ -1000,38 +1027,57 @@ class DigitalTwin(BECWidget, QWidget): self.calc_assistant(identifier="init") - def update_mo1_azm_angle(self): + def update_mo1_azm_angle(self, desired_azm_angle: float | None = None): + new_xtal = self.input.mo1_xtal.currentText() + old_mo1_trx = self.core.mo1_xtal_to_trx(self.old_xtal) + new_mo1_trx = self.core.mo1_xtal_to_trx(new_xtal) + old_mo1_roty = self.core.apply_offsets( + {"mo1_roty": self.input.mo1_azm_angle.value(), "mo1_trx": old_mo1_trx} + )["mo1_roty"] + new_azm_angle = self.core.remove_offsets( + {"mo1_roty": old_mo1_roty, "mo1_trx": new_mo1_trx} + )["mo1_roty"] + # Apply new range if self.beamline == BeamlineId.X01DA: - mo1_roty = self.dev.mo1_roty.describe(cached=True)["mo1_roty"] - ll = mo1_roty["lower_ctrl_limit"] - hl = mo1_roty["upper_ctrl_limit"] - - # Apply offsets - ll = self.core.apply_offsets({"mo1_roty": ll}, nested_config=False) - hl = self.core.apply_offsets({"mo1_roty": hl}, nested_config=False) - - self.input.mo1_azm_angle.set_range(ll, hl) + self.input.mo1_azm_angle.set_range( + self.azm_ranges[new_xtal]["ll"], self.azm_ranges[new_xtal]["hl"] + ) + if desired_azm_angle is not None: + self.input.mo1_azm_angle.set_number(desired_azm_angle) + else: + self.input.mo1_azm_angle.set_number(new_azm_angle) else: - azm_angle = self.core.apply_offsets({"mo1_roty": 0}, nested_config=False) - self.input.mo1_azm_angle.setValue(azm_angle) + self.input.mo1_azm_angle.setValue(new_azm_angle) + self.old_xtal = new_xtal def open_glitches_preview(self): - xtal = self.input.mo1_xtal.currentText() - azm_angle = self.input.mo1_azm_angle.value() - if self.beamline == BeamlineId.X01DA: - ll, hl = self.input.mo1_azm_angle.get_range() - else: - ll, hl = None, None + + if self.azm_ranges == {}: + logger.info( + "No azimuthal ranges found, can't open glitches preview. First adapt to reality once" + ) + return + + current_xtal = self.input.mo1_xtal.currentText() + current_azm = self.input.mo1_azm_angle.value() + if self.edge_selector_energy != 0: dlg = GlitchesPreview( - self, xtal, azm_angle, ll, hl, self.edge_selector_element, self.edge_selector_edge + self, + current_xtal, + current_azm, + self.azm_ranges, + self.edge_selector_element, + self.edge_selector_edge, ) else: - dlg = GlitchesPreview(self, xtal, azm_angle, self.input.energy.value()) + dlg = GlitchesPreview( + self, current_xtal, current_azm, self.azm_ranges, energy=self.input.energy.value() + ) if dlg.exec_(): self.input.mo1_xtal.set_current_text(dlg.xtal_selector.currentText()) if self.beamline == BeamlineId.X01DA: - self.input.mo1_azm_angle.set_number(dlg.azm_angle) + self.update_mo1_azm_angle(dlg.azm_angle) def update_fm_mode(self): """ diff --git a/debye_bec/bec_widgets/widgets/digital_twin/glitches_preview.py b/debye_bec/bec_widgets/widgets/digital_twin/glitches_preview.py index 4707e69..cc1a7c6 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/glitches_preview.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/glitches_preview.py @@ -2,6 +2,8 @@ GlitchesPreview: QDialog to preview monochromator glitches """ +from pathlib import Path + import numpy as np import pyqtgraph as pg import xraydb @@ -34,10 +36,9 @@ class GlitchesPreview(QDialog): def __init__( self, parent, - xtal: str, - azm_angle: float, - azm_ll: float | None = None, - azm_hl: float | None = None, + current_xtal: str, + current_azm: float, + ranges: dict, element: str | None = "", edge: str | None = "", energy: float = 12000, @@ -47,11 +48,11 @@ class GlitchesPreview(QDialog): if element != "": self.energy = xraydb.xray_edge(element, edge, energy_only=True) - self.energies = np.linspace(energy - EV_BELOW, energy + EV_ABOVE, 1000) + self.energies = np.linspace(self.energy - EV_BELOW, self.energy + EV_ABOVE, 1000) self.mu = edge_step(self.energies, self.energy) else: self.energy = energy - self.energies = np.linspace(energy - EV_BELOW, energy + EV_ABOVE, 1000) + self.energies = np.linspace(self.energy - EV_BELOW, self.energy + EV_ABOVE, 1000) self.mu = np.ones(len(self.energies)) layout = QVBoxLayout(self) @@ -59,35 +60,37 @@ class GlitchesPreview(QDialog): layout.addWidget(text) self.xtal_selector = ComboBox("mo1_xtal", "Crystal", ["Si(111)", "Si(311)"]) - self.xtal_selector.set_current_text(xtal) - self.xtal_selector.activated_connect(self.update_plot) + self.xtal_selector.set_current_text(current_xtal) + self.xtal_selector.activated_connect(self.change_xtal) + self.old_xtal = current_xtal layout.addWidget(self.xtal_selector) - self.azm_angle = azm_angle + self.azm_angle = current_azm + self.ranges = ranges self.azm_input = None - if azm_hl is not None and azm_ll is not None: - azm_input = InputNumberField( + if ranges[current_xtal]["ll"] is not None and ranges[current_xtal]["hl"] is not None: + self.azm_input = InputNumberField( "azm_angle", "Azm. Angle", unit="deg", - init=azm_angle, + init=self.azm_angle, decimals=3, single_step=0.01, - ll=azm_ll, - hl=azm_hl, + ll=ranges[current_xtal]["ll"], + hl=ranges[current_xtal]["hl"], ) - azm_input.value_changed_connect(self.update_plot) - layout.addWidget(azm_input) - accept_text = "Select xtal and azm. angle" + self.azm_input.value_changed_connect(self.update_plot) + layout.addWidget(self.azm_input) + accept_text = "Select crystal and azimuthal angle" else: - accept_text = "Select xtal" + accept_text = "Select crystal" self.plot = pg.PlotWidget() self.plot.setLabel("bottom", "Energy", units="eV") self.plot.setLabel("left", "Beam Intensity") self.plot.addLegend() self.plot.setYRange(-0.15, 1.2) - color = Colors.golden_angle_color(colormap="plasma", num=1, format="HEX") + color = Colors.golden_angle_color(colormap="plasma", num=1, format="HEX")[0] self.curve_edge = self.plot.plot(pen=pg.mkPen(color=color, width=2)) layout.addWidget(self.plot) @@ -98,12 +101,16 @@ class GlitchesPreview(QDialog): f"QPushButton {{background-color: {get_accent_colors().default.name()}; color: white;}}" ) self._select_button = QPushButton(accept_text) - self._select_button.setEnabled(False) self._select_button.clicked.connect(self.accept) self._select_button.setStyleSheet( f"QPushButton {{background-color: {get_accent_colors().default.name()}; color: white;}}" ) + self._cancel_button.setAutoDefault(False) + self._cancel_button.setDefault(False) + self._select_button.setAutoDefault(False) + self._select_button.setDefault(False) + button_layout.addStretch() button_layout.addWidget(self._cancel_button) button_layout.addWidget(self._select_button) @@ -115,21 +122,35 @@ class GlitchesPreview(QDialog): self.setFixedSize(self.sizeHint()) self.reflections_si111 = parse_xop_macro( - "xop_si111_Si-LN2_8-8-8_4500-60000eV_-180-180deg.pro" + Path(__file__).with_name("xop_si111_Si-LN2_8-8-8_4500-60000eV_-180-180deg.pro") ) - self.reflections_si311 = parse_xop_macro("xop_si311_Si-LN2_8-8-8_4500-60000eV_0-360deg.pro") + self.reflections_si311 = parse_xop_macro( + Path(__file__).with_name("xop_si311_Si-LN2_8-8-8_4500-60000eV_0-360deg.pro") + ) + self.update_plot() @SafeSlot() - def update_plot(self): + def change_xtal(self, *_, **__): + diff = self.azm_angle - self.ranges[self.old_xtal]["ll"] + xtal_info = self.ranges[self.xtal_selector.currentText()] + self.azm_input.set_range(xtal_info["ll"], xtal_info["hl"]) + self.azm_input.set_number(xtal_info["ll"] + diff) + self.old_xtal = self.xtal_selector.currentText() + self.update_plot() + + @SafeSlot() + def update_plot(self, *_, **__): if isinstance(self.azm_input, InputNumberField): self.azm_angle = self.azm_input.value() if self.xtal_selector.currentText() == "Si(111)": reflections = self.reflections_si111 else: reflections = self.reflections_si311 + e_pred, fh, _ = predicted_energies( reflections, self.azm_angle, (self.energies[0], self.energies[-1]) ) + if len(fh) == 0: self.curve_edge.setData(self.energies, self.mu) logger.info(f"phi = {self.azm_angle:.1f} deg | 0 glitches in window") @@ -142,7 +163,9 @@ class GlitchesPreview(QDialog): else np.ones_like(logw) ) + mu = self.mu for e, wn in zip(e_pred, wnorm): depth = 0.02 + 0.08 * wn - mu = self.mu - depth * np.exp(-0.5 * ((self.energies - e) / 1.5) ** 2) + mu = mu - depth * np.exp(-0.5 * ((self.energies - e) / 1.5) ** 2) + self.curve_edge.setData(self.energies, mu) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py b/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py index 9b984a1..646abe9 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py @@ -174,6 +174,9 @@ class ComboBox(QWidget): def setDisabled(self, disable): self.value.setDisabled(disable) + def get_all_texts(self) -> list[str]: + return [self.value.itemText(i) for i in range(self.value.count())] + class Button(QWidget): def __init__(self, label=None, label_button: str = "", enabled=False): From 5eba9dbc4cd056ceaa600ded106fa7da6cc72b1f Mon Sep 17 00:00:00 2001 From: x01da Date: Mon, 28 Sep 2026 14:43:25 +0200 Subject: [PATCH 39/56] wip --- .../widgets/scheduler/item_dialog.py | 3 +- .../widgets/scheduler/scheduler.py | 35 +++++++++++++++---- debye_bec/devices/reffoilchanger.py | 2 +- .../file_writer/debye_nexus_structure.py | 4 +-- 4 files changed, 33 insertions(+), 11 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index 4a64828..b5a0315 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -247,11 +247,12 @@ class ScheduleItemDialog(QDialog): if not device_name: raise ValueError("No movable device available/selected.") value = self.move_value_spin.value() + units = self.move_value_spin.suffix() relative = self.move_relative_check.isChecked() return { "command": f"dev.{device_name}.move({value!r}, relative={relative!r})", "kind": "move", - "form_state": {"device_name": device_name, "value": value, "relative": relative}, + "form_state": {"device_name": device_name, "value": value, "units": units, "relative": relative}, } def _prefill_move_page(self, state: dict): diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 2bcf498..5b203e6 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -96,9 +96,9 @@ def build_item_display_text(item: ScheduleItem, beamline: str | None) -> str: ) elif re.match(r"^dev\..*\.move", item.command): if item.form_state["relative"]: - text = f"Move {item.form_state['device_name']} by {item.form_state['value']:+g}" + text = f"Move {item.form_state['device_name']} by {item.form_state['value']:+g} {item.form_state['units']}" else: - text = f"Move {item.form_state['device_name']} to {item.form_state['value']}" + text = f"Move {item.form_state['device_name']} to {item.form_state['value']} {item.form_state['units']}" elif item.command.startswith("dev.ic"): text = ( f"Fill {item.form_state['chamber']} with {item.form_state['conc1']} % " @@ -345,6 +345,7 @@ class Scheduler(BECWidget, QWidget): self._endpoint = schedule_endpoint(self.schedule_name) self._lock = threading.Lock() # guards self.schedule (see module docstring) self._abort_requested = False + self._pause_requested = False self._guard_interrupt_requested = False # see "Guard interaction" in module docstring self._current_report = None # ScanReport of the item currently executing, if any self._current_item_kind: str | None = None # kind of the item _current_report belongs to @@ -461,16 +462,24 @@ class Scheduler(BECWidget, QWidget): run_row = QHBoxLayout() self.run_btn = MyButton("Run / Continue", "success") self.run_from_current_btn = MyButton("Run / Continue from current selection", "success") - self.abort_btn = MyButton("Pause after current item", "emergency") + self.abort_btn = MyButton("Pause now", "emergency") + self.pause_btn = MyButton("Pause after current item", "warning") self.reset_btn = MyButton("Reset Schedule Status", "warning") - for button in (self.run_btn, self.run_from_current_btn, self.abort_btn, self.reset_btn): + for button in ( + self.run_btn, + self.run_from_current_btn, + self.pause_btn, + self.abort_btn, + self.reset_btn, + ): run_row.addWidget(button) run_row.addStretch() control_layout.addLayout(run_row) self.run_btn.clicked.connect(self.run_schedule) - self.run_from_current_btn.connect(self.run_schedule_from_selection) + self.run_from_current_btn.clicked.connect(self.run_schedule_from_selection) self.abort_btn.clicked.connect(self.abort_schedule) + self.pause_btn.clicked.connect(self.pause_schedule) self.reset_btn.clicked.connect(self.reset_schedule) layout.addWidget(control_group) @@ -729,8 +738,9 @@ class Scheduler(BECWidget, QWidget): # Update execution control buttons state = self._current_report is None # True if schedule is not running self.run_btn.setEnabled(state) - self.run_from_current_btn.setEnabled(state) + self.run_from_current_btn.setEnabled(state and self._selected_item_id is not None) self.abort_btn.setEnabled(not state) + self.pause_btn.setEnabled(not state) self.reset_btn.setEnabled(state) @SafeSlot() @@ -1131,6 +1141,7 @@ class Scheduler(BECWidget, QWidget): == QMessageBox.StandardButton.Yes ) self._abort_requested = False + self._pause_requested = False self.schedule.is_running = True self._persist_locked() self.schedule_changed.emit() @@ -1163,6 +1174,10 @@ class Scheduler(BECWidget, QWidget): except Exception: # pylint: disable=broad-except logger.exception("Failed to cancel the currently running schedule item") + @SafeSlot() + def pause_schedule(self): + self._pause_requested = True + @SafeSlot() def reset_schedule(self): """Clear all execution state and start the schedule over from item 1.""" @@ -1390,7 +1405,9 @@ class Scheduler(BECWidget, QWidget): "auto_gain": self.auto_gain, "np": np, } - while not self._abort_requested and not self._closing.is_set(): + while ( + not self._abort_requested and not self._closing.is_set() and not self._pause_requested + ): with self._lock: next_item = self._pick_next_runnable_locked(repeat_aborted_item, first_item) if next_item is None or next_item == "stop": @@ -1411,6 +1428,10 @@ class Scheduler(BECWidget, QWidget): self.schedule.schedule_name, "widget_closed", ) + elif self._pause_requested: + notify_schedule_state( + self.client, self.schedule.notifications, self.schedule.schedule_name, "paused" + ) else: notify_schedule_state( self.client, self.schedule.notifications, self.schedule.schedule_name, "finished" diff --git a/debye_bec/devices/reffoilchanger.py b/debye_bec/devices/reffoilchanger.py index d3daee9..4a2a6a6 100644 --- a/debye_bec/devices/reffoilchanger.py +++ b/debye_bec/devices/reffoilchanger.py @@ -56,7 +56,7 @@ class CurrentFoilSignal(Signal): return None idx = self.parent.ref_rb.get() try: - idx = int(round(idx)) + 1 + idx = int(round(idx)) except (TypeError, ValueError): return None return getattr(self.parent, f"foil{idx:02d}", None) diff --git a/debye_bec/file_writer/debye_nexus_structure.py b/debye_bec/file_writer/debye_nexus_structure.py index f647b29..af74e79 100644 --- a/debye_bec/file_writer/debye_nexus_structure.py +++ b/debye_bec/file_writer/debye_nexus_structure.py @@ -1,6 +1,6 @@ from bec_server.file_writer.default_writer import DefaultFormat -import debye_bec.bec_widgets.widgets.digital_twin.x01da_parameters as bl +import debye_bec.bec_ipython_client.plugins.digital_twin_core.x01da_parameters as bl class DebyeNexusStructure(DefaultFormat): @@ -292,7 +292,7 @@ class DebyeNexusStructure(DefaultFormat): foil = ( self.device_manager.devices.reffoilchanger.read(cached=True) - .get("current_foil") + .get("reffoilchanger_current_foil") .get("value") ) ref_foil = ai2ai4_active.create_dataset(name="Reference", data=foil) From 0173e0b9b9079801c2f7ab693bcbc493fe41b5b2 Mon Sep 17 00:00:00 2001 From: x01da Date: Wed, 14 Oct 2026 08:59:18 +0200 Subject: [PATCH 40/56] fix(data_viewer): use float64 for plotting to avoid castint from float64 to float32 --- .../widgets/data_viewer/panels/data_view.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/data_viewer/panels/data_view.py b/debye_bec/bec_widgets/widgets/data_viewer/panels/data_view.py index e9b368c..4dff090 100644 --- a/debye_bec/bec_widgets/widgets/data_viewer/panels/data_view.py +++ b/debye_bec/bec_widgets/widgets/data_viewer/panels/data_view.py @@ -190,11 +190,11 @@ class DataView(QWidget): if is_2d: n_rows, _ = data.shape - row_data = data[0].astype(np.float32) + row_data = data[0].astype(np.float64) else: - row_data = data.reshape(-1).astype(np.float32) + row_data = data.reshape(-1).astype(np.float64) - x = np.arange(row_data.size, dtype=np.float32) + x = np.arange(row_data.size, dtype=np.float64) self.plot_widget = pg.PlotWidget() plot_item = self.plot_widget.getPlotItem() @@ -233,8 +233,8 @@ class DataView(QWidget): def on_row_changed(row): current_row_label.setText(str(row)) - new_data = data[row].astype(np.float32) - new_x = np.arange(new_data.size, dtype=np.float32) + new_data = data[row].astype(np.float64) + new_x = np.arange(new_data.size, dtype=np.float64) curve.setData(new_x, new_data) plot_item.enableAutoRange() # type: ignore[attr-defined] @@ -382,7 +382,7 @@ class DataView(QWidget): for c in range(show_cols): val = flat[r, c] txt = ( - f"{val:.6g}" + f"{val:.12g}" if is_float else f"{val:.4g}" if is_complex else str(val.decode()) if is_bytes else str(val) ) From e2c18867359bd51cd2a90d96bfe9a18b9261d8b2 Mon Sep 17 00:00:00 2001 From: x01da Date: Mon, 19 Oct 2026 08:48:45 +0200 Subject: [PATCH 41/56] fix(scheduler): auto-gain command --- debye_bec/bec_widgets/widgets/scheduler/item_dialog.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index b5a0315..e79f92e 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -252,7 +252,12 @@ class ScheduleItemDialog(QDialog): return { "command": f"dev.{device_name}.move({value!r}, relative={relative!r})", "kind": "move", - "form_state": {"device_name": device_name, "value": value, "units": units, "relative": relative}, + "form_state": { + "device_name": device_name, + "value": value, + "units": units, + "relative": relative, + }, } def _prefill_move_page(self, state: dict): @@ -554,7 +559,7 @@ class ScheduleItemDialog(QDialog): raise ValueError("Select at least one amplifier for auto gain.") cmd = ( f"auto_gain.start(element={self.edge_element}, edge={self.edge_edge}, " - f"{amplifiers}, comp_ring_current=True)" + f"amplifier={amplifiers}, comp_ring_current=True)" ) return { "command": cmd, From 76e28a0dcbb6f1ca2c20f0b881ceb3d063d67eee Mon Sep 17 00:00:00 2001 From: x01da Date: Mon, 19 Oct 2026 08:49:01 +0200 Subject: [PATCH 42/56] remove unused physical motors --- .../x01da_experimental_hutch.yaml | 126 ++++---- debye_bec/device_configs/x01da_frontend.yaml | 162 +++++----- debye_bec/device_configs/x01da_optics.yaml | 282 +++++++++--------- 3 files changed, 285 insertions(+), 285 deletions(-) diff --git a/debye_bec/device_configs/x01da_experimental_hutch.yaml b/debye_bec/device_configs/x01da_experimental_hutch.yaml index cec7109..7f9de2c 100644 --- a/debye_bec/device_configs/x01da_experimental_hutch.yaml +++ b/debye_bec/device_configs/x01da_experimental_hutch.yaml @@ -17,25 +17,25 @@ eh_sh: ## Optical Table ## ################################### -ot_tryu: - readoutPriority: baseline - description: Optical Table Y-Translation Upstream - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-ES-OT:TRYU - onFailure: retry - enabled: true - softwareTrigger: false +# ot_tryu: +# readoutPriority: baseline +# description: Optical Table Y-Translation Upstream +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-ES-OT:TRYU +# onFailure: retry +# enabled: true +# softwareTrigger: false -ot_tryd: - readoutPriority: baseline - description: Optical Table Y-Translation Downstream - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-ES-OT:TRYD - onFailure: retry - enabled: true - softwareTrigger: false +# ot_tryd: +# readoutPriority: baseline +# description: Optical Table Y-Translation Downstream +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-ES-OT:TRYD +# onFailure: retry +# enabled: true +# softwareTrigger: false ot_es1_trz: readoutPriority: baseline @@ -109,45 +109,45 @@ es0filter: ## Slits ES0 ## ################################### -es0sl_trxr: - readoutPriority: baseline - description: End Station slits X-translation Ring-edge - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-ES0-SL:TRXR - onFailure: retry - enabled: true - softwareTrigger: false +# es0sl_trxr: +# readoutPriority: baseline +# description: End Station slits X-translation Ring-edge +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-ES0-SL:TRXR +# onFailure: retry +# enabled: true +# softwareTrigger: false -es0sl_trxw: - readoutPriority: baseline - description: End Station slits X-translation Wall-edge - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-ES0-SL:TRXW - onFailure: retry - enabled: true - softwareTrigger: false +# es0sl_trxw: +# readoutPriority: baseline +# description: End Station slits X-translation Wall-edge +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-ES0-SL:TRXW +# onFailure: retry +# enabled: true +# softwareTrigger: false -es0sl_tryb: - readoutPriority: baseline - description: End Station slits Y-translation Bottom-edge - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-ES0-SL:TRYB - onFailure: retry - enabled: true - softwareTrigger: false +# es0sl_tryb: +# readoutPriority: baseline +# description: End Station slits Y-translation Bottom-edge +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-ES0-SL:TRYB +# onFailure: retry +# enabled: true +# softwareTrigger: false -es0sl_tryt: - readoutPriority: baseline - description: End Station slits X-translation Top-edge - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-ES0-SL:TRYT - onFailure: retry - enabled: true - softwareTrigger: false +# es0sl_tryt: +# readoutPriority: baseline +# description: End Station slits X-translation Top-edge +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-ES0-SL:TRYT +# onFailure: retry +# enabled: true +# softwareTrigger: false es0sl_center: readoutPriority: baseline @@ -281,15 +281,15 @@ es1bm1_trx: enabled: true softwareTrigger: false -es1det2_trx: - readoutPriority: baseline - description: End Station SDD 2 X-translation - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-ES1-DET2:TRX - onFailure: retry - enabled: true - softwareTrigger: false +# es1det2_trx: +# readoutPriority: baseline +# description: End Station SDD 2 X-translation +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-ES1-DET2:TRX +# onFailure: retry +# enabled: true +# softwareTrigger: false ################################### ## IC1 + IC2 Manipulator ## diff --git a/debye_bec/device_configs/x01da_frontend.yaml b/debye_bec/device_configs/x01da_frontend.yaml index 77a4236..df7c033 100644 --- a/debye_bec/device_configs/x01da_frontend.yaml +++ b/debye_bec/device_configs/x01da_frontend.yaml @@ -17,45 +17,45 @@ abs: ## Frontend Slits ## ################################### -sldi_trxr: - readoutPriority: baseline - description: Front-end slit diaphragm X-translation Ring-edge - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-FE-SLDI:TRXR - onFailure: retry - enabled: true - softwareTrigger: false +# sldi_trxr: +# readoutPriority: baseline +# description: Front-end slit diaphragm X-translation Ring-edge +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-FE-SLDI:TRXR +# onFailure: retry +# enabled: true +# softwareTrigger: false -sldi_trxw: - readoutPriority: baseline - description: Front-end slit diaphragm X-translation Wall-edge - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-FE-SLDI:TRXW - onFailure: retry - enabled: true - softwareTrigger: false +# sldi_trxw: +# readoutPriority: baseline +# description: Front-end slit diaphragm X-translation Wall-edge +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-FE-SLDI:TRXW +# onFailure: retry +# enabled: true +# softwareTrigger: false -sldi_tryb: - readoutPriority: baseline - description: Front-end slit diaphragm Y-translation Bottom-edge - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-FE-SLDI:TRYB - onFailure: retry - enabled: true - softwareTrigger: false +# sldi_tryb: +# readoutPriority: baseline +# description: Front-end slit diaphragm Y-translation Bottom-edge +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-FE-SLDI:TRYB +# onFailure: retry +# enabled: true +# softwareTrigger: false -sldi_tryt: - readoutPriority: baseline - description: Front-end slit diaphragm X-translation Top-edge - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-FE-SLDI:TRYT - onFailure: retry - enabled: true - softwareTrigger: false +# sldi_tryt: +# readoutPriority: baseline +# description: Front-end slit diaphragm X-translation Top-edge +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-FE-SLDI:TRYT +# onFailure: retry +# enabled: true +# softwareTrigger: false sldi_centerx: readoutPriority: baseline @@ -101,55 +101,55 @@ sldi_gapy: ## Collimating Mirror ## ################################### -cm_trxu: - readoutPriority: baseline - description: Collimating Mirror X-translation upstream - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-FE-CM:TRXU - onFailure: retry - enabled: true - softwareTrigger: false +# cm_trxu: +# readoutPriority: baseline +# description: Collimating Mirror X-translation upstream +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-FE-CM:TRXU +# onFailure: retry +# enabled: true +# softwareTrigger: false -cm_trxd: - readoutPriority: baseline - description: Collimating Mirror X-translation downstream - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-FE-CM:TRXD - onFailure: retry - enabled: true - softwareTrigger: false +# cm_trxd: +# readoutPriority: baseline +# description: Collimating Mirror X-translation downstream +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-FE-CM:TRXD +# onFailure: retry +# enabled: true +# softwareTrigger: false -cm_tryu: - readoutPriority: baseline - description: Collimating Mirror Y-translation upstream - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-FE-CM:TRYU - onFailure: retry - enabled: true - softwareTrigger: false +# cm_tryu: +# readoutPriority: baseline +# description: Collimating Mirror Y-translation upstream +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-FE-CM:TRYU +# onFailure: retry +# enabled: true +# softwareTrigger: false -cm_trydr: - readoutPriority: baseline - description: Collimating Mirror Y-translation downstream ring - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-FE-CM:TRYDR - onFailure: retry - enabled: true - softwareTrigger: false +# cm_trydr: +# readoutPriority: baseline +# description: Collimating Mirror Y-translation downstream ring +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-FE-CM:TRYDR +# onFailure: retry +# enabled: true +# softwareTrigger: false -cm_trydw: - readoutPriority: baseline - description: Collimating Mirror Y-translation downstream wall - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-FE-CM:TRYDW - onFailure: retry - enabled: true - softwareTrigger: false +# cm_trydw: +# readoutPriority: baseline +# description: Collimating Mirror Y-translation downstream wall +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-FE-CM:TRYDW +# onFailure: retry +# enabled: true +# softwareTrigger: false cm_bnd: readoutPriority: baseline diff --git a/debye_bec/device_configs/x01da_optics.yaml b/debye_bec/device_configs/x01da_optics.yaml index c96564d..a903ea6 100644 --- a/debye_bec/device_configs/x01da_optics.yaml +++ b/debye_bec/device_configs/x01da_optics.yaml @@ -51,57 +51,57 @@ mo1_roty: ## Optics Slits + Beam Monitor 1 ## ################################### -sl1_trxr: - readoutPriority: baseline - description: Optics slits 1 X-translation Ring-edge - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-OP-SL1:TRXR - onFailure: retry - enabled: true - softwareTrigger: false - deviceTags: - - optics - - slits +# sl1_trxr: +# readoutPriority: baseline +# description: Optics slits 1 X-translation Ring-edge +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-OP-SL1:TRXR +# onFailure: retry +# enabled: true +# softwareTrigger: false +# deviceTags: +# - optics +# - slits -sl1_trxw: - readoutPriority: baseline - description: Optics slits 1 X-translation Wall-edge - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-OP-SL1:TRXW - onFailure: retry - enabled: true - softwareTrigger: false - deviceTags: - - optics - - slits +# sl1_trxw: +# readoutPriority: baseline +# description: Optics slits 1 X-translation Wall-edge +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-OP-SL1:TRXW +# onFailure: retry +# enabled: true +# softwareTrigger: false +# deviceTags: +# - optics +# - slits -sl1_tryb: - readoutPriority: baseline - description: Optics slits 1 Y-translation Bottom-edge - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-OP-SL1:TRYB - onFailure: retry - enabled: true - softwareTrigger: false - deviceTags: - - optics - - slits +# sl1_tryb: +# readoutPriority: baseline +# description: Optics slits 1 Y-translation Bottom-edge +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-OP-SL1:TRYB +# onFailure: retry +# enabled: true +# softwareTrigger: false +# deviceTags: +# - optics +# - slits -sl1_tryt: - readoutPriority: baseline - description: Optics slits 1 X-translation Top-edge - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-OP-SL1:TRYT - onFailure: retry - enabled: true - softwareTrigger: false - deviceTags: - - optics - - slits +# sl1_tryt: +# readoutPriority: baseline +# description: Optics slits 1 X-translation Top-edge +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-OP-SL1:TRYT +# onFailure: retry +# enabled: true +# softwareTrigger: false +# deviceTags: +# - optics +# - slits bm1_try: readoutPriority: baseline @@ -172,55 +172,55 @@ sl1_gapy: ## Focusing Mirror ## ################################### -fm_trxu: - readoutPriority: baseline - description: Focusing Mirror X-translation upstream - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-OP-FM:TRXU - onFailure: retry - enabled: true - softwareTrigger: false +# fm_trxu: +# readoutPriority: baseline +# description: Focusing Mirror X-translation upstream +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-OP-FM:TRXU +# onFailure: retry +# enabled: true +# softwareTrigger: false -fm_trxd: - readoutPriority: baseline - description: Focusing Mirror X-translation downstream - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-OP-FM:TRXD - onFailure: retry - enabled: true - softwareTrigger: false +# fm_trxd: +# readoutPriority: baseline +# description: Focusing Mirror X-translation downstream +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-OP-FM:TRXD +# onFailure: retry +# enabled: true +# softwareTrigger: false -fm_tryd: - readoutPriority: baseline - description: Focusing Mirror Y-translation downstream - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-OP-FM:TRYD - onFailure: retry - enabled: true - softwareTrigger: false +# fm_tryd: +# readoutPriority: baseline +# description: Focusing Mirror Y-translation downstream +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-OP-FM:TRYD +# onFailure: retry +# enabled: true +# softwareTrigger: false -fm_tryur: - readoutPriority: baseline - description: Focusing Mirror Y-translation upstream ring - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-OP-FM:TRYUR - onFailure: retry - enabled: true - softwareTrigger: false +# fm_tryur: +# readoutPriority: baseline +# description: Focusing Mirror Y-translation upstream ring +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-OP-FM:TRYUR +# onFailure: retry +# enabled: true +# softwareTrigger: false -fm_tryuw: - readoutPriority: baseline - description: Focusing Mirror Y-translation upstream wall - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-OP-FM:TRYUW - onFailure: retry - enabled: true - softwareTrigger: false +# fm_tryuw: +# readoutPriority: baseline +# description: Focusing Mirror Y-translation upstream wall +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-OP-FM:TRYUW +# onFailure: retry +# enabled: true +# softwareTrigger: false fm_bnd: readoutPriority: baseline @@ -307,57 +307,57 @@ fm_ztcp: ## Optics Slits + Beam Monitor 2 ## ################################### -sl2_trxr: - readoutPriority: baseline - description: Optics slits 2 X-translation Ring-edge - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-OP-SL2:TRXR - onFailure: retry - enabled: true - softwareTrigger: false - deviceTags: - - optics - - slits +# sl2_trxr: +# readoutPriority: baseline +# description: Optics slits 2 X-translation Ring-edge +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-OP-SL2:TRXR +# onFailure: retry +# enabled: true +# softwareTrigger: false +# deviceTags: +# - optics +# - slits -sl2_trxw: - readoutPriority: baseline - description: Optics slits 2 X-translation Wall-edge - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-OP-SL2:TRXW - onFailure: retry - enabled: true - softwareTrigger: false - deviceTags: - - optics - - slits +# sl2_trxw: +# readoutPriority: baseline +# description: Optics slits 2 X-translation Wall-edge +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-OP-SL2:TRXW +# onFailure: retry +# enabled: true +# softwareTrigger: false +# deviceTags: +# - optics +# - slits -sl2_tryb: - readoutPriority: baseline - description: Optics slits 2 Y-translation Bottom-edge - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-OP-SL2:TRYB - onFailure: retry - enabled: true - softwareTrigger: false - deviceTags: - - optics - - slits +# sl2_tryb: +# readoutPriority: baseline +# description: Optics slits 2 Y-translation Bottom-edge +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-OP-SL2:TRYB +# onFailure: retry +# enabled: true +# softwareTrigger: false +# deviceTags: +# - optics +# - slits -sl2_tryt: - readoutPriority: baseline - description: Optics slits 2 X-translation Top-edge - deviceClass: ophyd_devices.EpicsMotorEC - deviceConfig: - prefix: X01DA-OP-SL2:TRYT - onFailure: retry - enabled: true - softwareTrigger: false - deviceTags: - - optics - - slits +# sl2_tryt: +# readoutPriority: baseline +# description: Optics slits 2 X-translation Top-edge +# deviceClass: ophyd_devices.EpicsMotorEC +# deviceConfig: +# prefix: X01DA-OP-SL2:TRYT +# onFailure: retry +# enabled: true +# softwareTrigger: false +# deviceTags: +# - optics +# - slits bm2_try: readoutPriority: baseline From 14a41bfaa8af2bccf86f158786cd410df306236e Mon Sep 17 00:00:00 2001 From: hitz_s Date: Mon, 19 Oct 2026 15:07:27 +0200 Subject: [PATCH 43/56] feat(auto_gain): Build own gui --- .../{auto_gain.py => auto_gain_core.py} | 55 ++++- .../startup/post_startup.py | 4 +- .../bec_widgets/widgets/auto_gain/__init__,py | 0 .../widgets/auto_gain/auto_gain.py | 194 ++++++++++++++++++ .../widgets/auto_gain/auto_gain.pyproject | 1 + .../widgets/auto_gain/auto_gain_plugin.py | 57 +++++ .../widgets/auto_gain/qt_widgets.py | 183 +++++++++++++++++ .../widgets/auto_gain/register_auto_gain.py | 15 ++ .../widgets/restart_server/restart_server.py | 4 - .../widgets/scheduler/item_dialog.py | 105 +++------- .../widgets/scheduler/scheduler.py | 23 +-- 11 files changed, 530 insertions(+), 111 deletions(-) rename debye_bec/bec_ipython_client/plugins/{auto_gain.py => auto_gain_core.py} (88%) create mode 100644 debye_bec/bec_widgets/widgets/auto_gain/__init__,py create mode 100644 debye_bec/bec_widgets/widgets/auto_gain/auto_gain.py create mode 100644 debye_bec/bec_widgets/widgets/auto_gain/auto_gain.pyproject create mode 100644 debye_bec/bec_widgets/widgets/auto_gain/auto_gain_plugin.py create mode 100644 debye_bec/bec_widgets/widgets/auto_gain/qt_widgets.py create mode 100644 debye_bec/bec_widgets/widgets/auto_gain/register_auto_gain.py diff --git a/debye_bec/bec_ipython_client/plugins/auto_gain.py b/debye_bec/bec_ipython_client/plugins/auto_gain_core.py similarity index 88% rename from debye_bec/bec_ipython_client/plugins/auto_gain.py rename to debye_bec/bec_ipython_client/plugins/auto_gain_core.py index bfc2957..6a1c348 100644 --- a/debye_bec/bec_ipython_client/plugins/auto_gain.py +++ b/debye_bec/bec_ipython_client/plugins/auto_gain_core.py @@ -26,7 +26,6 @@ TIMEOUT_PUT_PV = 5 # Timeout to set a PV MONO_VELOCITY = 20 # Move velocity in deg/s TIMEOUT_MONO_MOVE = 30 # Timeout to finish a movement on the mono -LINKED_CHANNELS = {"ic0", "ic1"} AVAILABLE_GAINS = [1e6, 1e7, 5e7, 1e8, 1e9] # ascending order MIN_SIGNAL = 0.05 # Minimum signal to count as valid signal FULL_SCALE_V = 10.0 # NIDAQ AI full-scale range @@ -53,7 +52,7 @@ class AutoGainError(Exception): """AutoGain specific error""" -class AutoGain: +class AutoGainCore: """Module to automatically set the gains for the selected amplifiers""" def __init__(self): @@ -65,14 +64,27 @@ class AutoGain: raise AutoGainError("Did not get bec") self.dev = dev self.bec = bec + self.linked_channels = None + self.prohibited_gains = {} + + def available_gains(self, amplifier): + """Returns a list of gains which are allowed for the amplifier""" + if amplifier in self.prohibited_gains: + gains = AVAILABLE_GAINS + for prohibited_gain in self.prohibited_gains[amplifier]: + gains.remove(prohibited_gain) + return gains + return AVAILABLE_GAINS def start( self, element: str, edge: str, amplifier: list[str] | None = None, + link_ic0_ic1: bool = True, comp_ring_current: bool = True, - ) -> None: + prohibited_gains: dict | None = None, + ) -> dict: """Start the auto-gain sequence. Measure the signals of the specified amplifiers and set the gains accordingly. Makes sure there is actually beam available. @@ -85,8 +97,11 @@ class AutoGain: edge(str): Corresponding edge, e.g. 'L1' amplifier(list[str]): Amplifiers where auto-gain should be applied to Defaults to all amplifiers -> ['ic0', 'ic1', 'ic2', 'pips'] + link_ic0_ic1(bool): Apply same gain to ic0 and ic1. Defaults to True comp_ring_current(bool): Respects the current ring current and calculates the gain(s) for a nominal ring current of 400 mA. Defaults to True + prohibited_gains(dict): Gains which are not allowed to be used. + E.g.: {'ic0': [1e6]}. Defaults to None Raises: If NIDAQ is not in measurement mode @@ -101,6 +116,16 @@ class AutoGain: If the ring current drops to 0 mA during the measurement (beamdump) """ + if link_ic0_ic1: + self.linked_channels = {"ic0", "ic1"} + else: + self.linked_channels = {} + + if prohibited_gains is None: + self.prohibited_gains = {} + else: + self.prohibited_gains = prohibited_gains + if amplifier is None: amplifier = ["ic0", "ic1", "ic2", "pips"] @@ -180,6 +205,8 @@ class AutoGain: logger.info("All checks done, start preparing for measurement") + results = {} + try: logger.info(f"Move mono to start of {emin} eV") self.dev.mo1_bragg.velocity.put(MONO_VELOCITY) @@ -193,7 +220,7 @@ class AutoGain: # Set gains to lowest gain for name, ch in active_channels.items(): - lowest_gain = AVAILABLE_GAINS[0] + lowest_gain = self.available_gains(name)[0] ch["self.dev"].set_gain(lowest_gain) ch["gain"] = lowest_gain @@ -243,8 +270,8 @@ class AutoGain: # ic0/ic1 must always end up with the same gain -> treat whichever of # them are present (one or both) as a single group for this decision - if name in LINKED_CHANNELS: - group_names = [n for n in LINKED_CHANNELS if n in active_channels] + if name in self.linked_channels: + group_names = [n for n in self.linked_channels if n in active_channels] else: group_names = [name] @@ -268,14 +295,14 @@ class AutoGain: if raw_signal_min < MIN_SIGNAL: logger.info(f"Raw signal for {label} is below {MIN_SIGNAL}") - if gain_ref == AVAILABLE_GAINS[-1]: + if gain_ref == self.available_gains(name)[-1]: logger.warning( f"Amplifier of {label} at highest gain {gain_ref} and still not" + f" measured signal above {MIN_SIGNAL}" ) else: - next_gain = AVAILABLE_GAINS[ - bisect_right(AVAILABLE_GAINS, gain_ref * 100) - 1 + next_gain = self.available_gains(name)[ + bisect_right(self.available_gains(name), gain_ref * 100) - 1 ] for gname in group_names: active_channels[gname]["self.dev"].set_gain(next_gain) @@ -286,15 +313,19 @@ class AutoGain: gain = max( ( g - for g in AVAILABLE_GAINS + for g in self.available_gains(name) if raw_signal_max / gain_ref * g <= FULL_SCALE_V * SAFETY_MARGIN ), - default=min(AVAILABLE_GAINS), + default=min(self.available_gains(name)), ) for gname in group_names: active_channels[gname]["self.dev"].set_gain(gain) active_channels[gname]["gain"] = gain logger.info(f"Calculated final gain for {label} of {gain:.0e}") + results[label] = { + "gain": gain, + "max_signal": raw_signal_max / gain_ref * gain, + } processed.update(group_names) @@ -316,6 +347,8 @@ class AutoGain: self.dev.mo1_bragg.velocity.put(init_vel) wait_for_signal(self.dev.mo1_bragg.velocity, init_vel, timeout=TIMEOUT_PUT_PV) + return results + def _get_ring_current(self) -> float: ring_current = 0 retries = 0 diff --git a/debye_bec/bec_ipython_client/startup/post_startup.py b/debye_bec/bec_ipython_client/startup/post_startup.py index 0fd9d82..a5dc63c 100644 --- a/debye_bec/bec_ipython_client/startup/post_startup.py +++ b/debye_bec/bec_ipython_client/startup/post_startup.py @@ -41,11 +41,11 @@ logger = bec_logger.logger logger.info("Using the Debye startup script.") +from debye_bec.bec_ipython_client.plugins.auto_gain_core import AutoGainCore from debye_bec.bec_ipython_client.plugins.digital_twin_core.digital_twin_core import DigitalTwinCore -from debye_bec.bec_ipython_client.plugins.auto_gain import AutoGain digital_twin = DigitalTwinCore() logger.success("Digital Twin Core loaded. Use 'digital_twin' to access it.") -auto_gain = AutoGain() +auto_gain = AutoGainCore() logger.success("Auto-Gain module loaded. Use 'auto_gain' to access it.") diff --git a/debye_bec/bec_widgets/widgets/auto_gain/__init__,py b/debye_bec/bec_widgets/widgets/auto_gain/__init__,py new file mode 100644 index 0000000..e69de29 diff --git a/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.py b/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.py new file mode 100644 index 0000000..56f774c --- /dev/null +++ b/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.py @@ -0,0 +1,194 @@ +""" +Auto Gain: Custom BEC widget to automatically set gains. +""" + +import sys + +from bec_lib import bec_logger +from bec_lib.logger import bec_logger +from bec_widgets.utils.bec_dispatcher import BECDispatcher +from bec_widgets.utils.bec_widget import BECWidget +from bec_widgets.utils.colors import apply_theme, get_accent_colors +from bec_widgets.utils.error_popups import SafeSlot +from qtpy.QtCore import QObject, QThread, Signal + +# pylint: disable=E0611 +from qtpy.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget + +from ....bec_ipython_client.plugins.auto_gain_core import AutoGainCore +from ..edge_selector import EdgeSelector +from .qt_widgets import CheckBox, Group, MatrixSelector, MyButton, TextIndicator + +logger = bec_logger.logger + + +class Worker(QObject): + progress = Signal(str) + completed = Signal(int) + + @SafeSlot(int) + def start(self, config: dict): + core = AutoGainCore() + self.progress.emit("AutoGain started") + results = core.start( + config["element"], + config["edge"], + amplifier=config["all_amplifiers"], + link_ic0_ic1=config["link_ic0_ic1"], + comp_ring_current=config["compensate_ring_current"], + prohibited_gains=config["prohibited_gains"], + ) + results_string = "" + init = True + for amplifier, result in results.items(): + if not init: + results_string += "\n" + else: + init = False + results_string += f"{amplifier} set to gain {result['gain']:.0e}, max signal {result['max_signal']:.3f} V" + self.progress.emit(results_string) + self.completed.emit(True) + + +class AutoGain(BECWidget, QWidget): + """ + Main widget of auto gain widget. + """ + + PLUGIN = True + ICON_NAME = "tune" + + def __init__(self, show_control: bool = True, *arg, parent=None, **kwargs): + super().__init__(parent=parent, *arg, **kwargs) + self.get_bec_shortcuts() + + central = QWidget() + self.root_layout = QVBoxLayout(central) + + self.edge_selector_button = MyButton("Choose", "default") + self.edge_label = QLabel("No edge selected") + self.edge_group = Group( + "Edge selection", [self.edge_selector_button, self.edge_label], orientation="horizontal" + ) + self.edge_element = None + self.edge_edge = None + self.edge_energy = None + + self.root_layout.addWidget(self.edge_group) + + self.ic0_check = CheckBox("ic0", "IC0") + self.ic1_check = CheckBox("ic1", "IC1") + self.ic2_check = CheckBox("ic2", "IC2") + self.pips_check = CheckBox("pips", "PIPS") + self.apply_group = Group( + "Apply auto gain on", [self.ic0_check, self.ic1_check, self.ic2_check, self.pips_check] + ) + self.root_layout.addWidget(self.apply_group) + + self.link_ic0_ic1 = CheckBox("link_ic0_ic1", "Link IC0/IC1 gains") + self.link_ic0_ic1.setChecked(True) + + self.comp_ring_current = CheckBox("comp_ring_current", "Calculate for 400 mA ring current") + self.comp_ring_current.setChecked(True) + + self.prohibited_gains = MatrixSelector("Prohibited gains") + + self.expert_group = Group( + "Expert settings", [self.link_ic0_ic1, self.comp_ring_current, self.prohibited_gains] + ) + + self.root_layout.addWidget(self.expert_group) + + self.start_button = MyButton("Start", "success") + self.status = TextIndicator(label="Status") + self.status.setText("Standby") + self.status.setColor(get_accent_colors().default.name()) + + self.control_group = Group("Control", [self.start_button, self.status]) + + if show_control: + self.root_layout.addWidget(self.control_group) + + self.root_layout.addStretch() + + self.setLayout(self.root_layout) + self.setWindowTitle("Auto Gain") + + self.edge_selector_button.clicked.connect(self._update_edge) + self.start_button.clicked.connect(self._start) + + self.worker = Worker() + self.worker_thread = QThread() + self.worker.progress.connect(self._update_status) + self.worker.completed.connect(self._complete) + self.worker.moveToThread(self.worker_thread) + + def _update_edge(self, *_): + dlg = EdgeSelector(self) + if dlg.exec_(): + self.edge_element = dlg.selected_element + self.edge_edge = dlg.selected_edge + self.edge_energy = dlg.selected_energy + self.edge_label.setText( + f"{dlg.selected_element}, {dlg.selected_edge}-edge, {dlg.selected_energy:0.1f} eV" + ) + + def _start(self): + if not self.worker_thread.isRunning(): + self.start_button.setEnabled(False) + self.status.setColor(get_accent_colors().warning.name()) + self.worker_thread.start() + + def _update_status(self, text): + self.status.setText(text) + + def _complete(self, *_): + self.start_button.setEnabled(True) + self.status.setColor(get_accent_colors().success.name()) + + def load_config(self, config: dict): + self.edge_element = config["element"] + self.edge_edge = config["edge"] + self.edge_energy = config["energy"] + self.ic0_check.setChecked(config["ic0"]) + self.ic1_check.setChecked(config["ic1"]) + self.ic2_check.setChecked(config["ic2"]) + self.pips_check.setChecked(config["pips"]) + self.link_ic0_ic1.setChecked(config["link_ic0_ic1"]) + self.comp_ring_current.setChecked(config["compensate_ring_current"]) + self.prohibited_gains.set_selection(config["prohibited_gains"]) + + def get_config(self) -> dict: + if self.edge_element is None or self.edge_edge is None: + raise ValueError("Choose an absorption edge first.") + amplifier_checks = [ + (self.ic0_check, "ic0"), + (self.ic1_check, "ic1"), + (self.ic2_check, "ic2"), + (self.pips_check, "pips"), + ] + amplifiers = [name for check, name in amplifier_checks if check.isChecked()] + if not amplifiers: + raise ValueError("Select at least one amplifier for auto gain.") + return { + "element": self.edge_element, + "edge": self.edge_edge, + "energy": self.edge_energy, + "ic0": self.ic0_check.isChecked, + "ic1": self.ic1_check.isChecked, + "ic2": self.ic2_check.isChecked, + "pips": self.pips_check.isChecked, + "all_amplifiers": amplifiers, + "link_ic0_ic1": self.link_ic0_ic1.isChecked, + "compensate_ring_current": self.comp_ring_current.isChecked, + "prohibited_gains": self.prohibited_gains.selection(), + } + + +if __name__ == "__main__": + app = QApplication(sys.argv) + apply_theme("light") + dispatcher = BECDispatcher(gui_id="auto_gain") + win = AutoGain() + win.show() + sys.exit(app.exec_()) diff --git a/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.pyproject b/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.pyproject new file mode 100644 index 0000000..56f7f23 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.pyproject @@ -0,0 +1 @@ +{'files': ['auto_gain.py']} \ No newline at end of file diff --git a/debye_bec/bec_widgets/widgets/auto_gain/auto_gain_plugin.py b/debye_bec/bec_widgets/widgets/auto_gain/auto_gain_plugin.py new file mode 100644 index 0000000..0c2bb03 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/auto_gain/auto_gain_plugin.py @@ -0,0 +1,57 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +from bec_widgets.utils.bec_designer import designer_material_icon +from qtpy.QtDesigner import QDesignerCustomWidgetInterface +from qtpy.QtWidgets import QWidget + +from .auto_gain import AutoGain + +DOM_XML = """ + + + + +""" + + +class AutoGainPlugin(QDesignerCustomWidgetInterface): # pragma: no cover + def __init__(self): + super().__init__() + self._form_editor = None + + def createWidget(self, parent): + if parent is None: + return QWidget() + t = AutoGain(parent) + return t + + def domXml(self): + return DOM_XML + + def group(self): + return "" + + def icon(self): + return designer_material_icon(AutoGain.ICON_NAME) + + def includeFile(self): + return "auto_gain" + + def initialize(self, form_editor): + self._form_editor = form_editor + + def isContainer(self): + return False + + def isInitialized(self): + return self._form_editor is not None + + def name(self): + return "AutoGain" + + def toolTip(self): + return "AutoGain" + + def whatsThis(self): + return self.toolTip() diff --git a/debye_bec/bec_widgets/widgets/auto_gain/qt_widgets.py b/debye_bec/bec_widgets/widgets/auto_gain/qt_widgets.py new file mode 100644 index 0000000..3052869 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/auto_gain/qt_widgets.py @@ -0,0 +1,183 @@ +from bec_widgets.utils.colors import get_accent_colors +from qtpy.QtCore import Qt + +# pylint: disable=E0611 +from qtpy.QtWidgets import ( + QCheckBox, + QGridLayout, + QGroupBox, + QHBoxLayout, + QLabel, + QLayout, + QPushButton, + QVBoxLayout, + QWidget, +) + +LABEL_WIDTH = 118 +ROW_MARGINS = (4, 0, 4, 0) +ROW_SPACING = 6 + + +class Group(QGroupBox): + def __init__(self, label, objs, orientation="vertical"): + super().__init__(label) + if orientation == "vertical": + self._layout = QVBoxLayout(self) + elif orientation == "horizontal": + self._layout = QHBoxLayout(self) + else: + raise ValueError(f"Orientation {orientation} is not supported!") + for obj in objs: + if isinstance(obj, QWidget): + self._layout.addWidget(obj) + elif isinstance(obj, QLayout): + self._layout.addLayout(obj) + + +class CheckBox(QWidget): + def __init__(self, identifier="", label=""): + super().__init__() + layout = QHBoxLayout(self) + layout.setContentsMargins(*ROW_MARGINS) + layout.setSpacing(ROW_SPACING) + self.identifier = identifier + self.label = QLabel(label) + self.label.setFixedWidth(LABEL_WIDTH) + self.label.setWordWrap(True) + layout.addWidget(self.label) + self.checkbox = QCheckBox() + layout.addWidget(self.checkbox) + + def setChecked(self, set_checked: bool = True): + self.checkbox.setChecked(set_checked) + + def isChecked(self): + return self.checkbox.isChecked() + + +class MatrixSelector(QWidget): + """Checkbox matrix for selecting amplifier/value combinations. + + Displays a grid with one row per amplifier (IC0, IC1, IC2, PIPS) and one + column per value (1e6, 1e7, 5e7, 1e8, 1e9). Each cell is a checkbox, so any + combination of rows and columns can be selected independently. + + Use `selection()` to read the current state as a dict mapping the + lowercase row name to a list of the selected column values (as floats), + e.g. ``{"ic0": [1e6], "ic1": [1e6, 5e7]}``. Rows with no checked boxes are + omitted. + + Attributes: + ROWS (list[str]): Row titles, in display order. + COLS (list[str]): Column titles, in display order. These are also + parsed with ``float()`` to produce the values returned by + `selection()`. + checks (dict[tuple[str, str], QCheckBox]): Checkboxes keyed by + ``(row, col)`` using the original title strings. + + Example: + >>> selector = MatrixSelector() + >>> my_layout.addWidget(selector) + >>> selector.selection() + {'ic0': [1000000.0], 'ic1': [1000000.0, 50000000.0]} + """ + + ROWS = ["IC0", "IC1", "IC2", "PIPS"] + COLS = ["1e6", "1e7", "5e7", "1e8", "1e9"] + + def __init__(self, label: str = "", parent=None): + super().__init__(parent) + layout = QHBoxLayout(self) + layout.setContentsMargins(*ROW_MARGINS) + layout.setSpacing(ROW_SPACING) + self.label = QLabel(label) + self.label.setFixedWidth(LABEL_WIDTH) + self.label.setWordWrap(True) + layout.addWidget(self.label) + + grid_layout = QGridLayout() + + # Column headers + for c, col in enumerate(self.COLS, start=1): + grid_layout.addWidget(QLabel(col), 0, c, alignment=Qt.AlignmentFlag.AlignCenter) + + # Row headers + checkboxes + self.checks = {} + for r, row in enumerate(self.ROWS, start=1): + grid_layout.addWidget(QLabel(row), r, 0) + for c, col in enumerate(self.COLS, start=1): + cb = QCheckBox() + grid_layout.addWidget(cb, r, c, alignment=Qt.AlignmentFlag.AlignCenter) + self.checks[(row, col)] = cb + + layout.addLayout(grid_layout) + layout.addStretch() + + def selection(self): + """Return e.g. {"ic0": [1e6], "ic1": [1e6, 5e7]}; rows with no selection are omitted.""" + result = {} + for row in self.ROWS: + values = [float(col) for col in self.COLS if self.checks[(row, col)].isChecked()] + if values: + result[row.lower()] = values + return result + + def set_selection(self, selection): + """Set the checkboxes from a dict as returned by `selection()`. + + Rows not present in `selection` are cleared. Values that don't match + any column are ignored. + """ + # Normalize keys to lowercase and values to floats for comparison + wanted = {key.lower(): {float(v) for v in values} for key, values in selection.items()} + for row in self.ROWS: + row_values = wanted.get(row.lower(), set()) + for col in self.COLS: + cb = self.checks[(row, col)] + cb.setChecked(float(col) in row_values) + + +class MyButton(QPushButton): + def __init__(self, text="", color="default", parent=None): + self.color = color + super().__init__(text, parent) + self.apply_theme() + + def apply_theme(self): + if self.isEnabled(): + colors = get_accent_colors() + color = getattr(colors, self.color).name() + self.setStyleSheet(f"QPushButton {{ background-color: {color}; color: white; }}") + else: + self.setStyleSheet( + "QPushButton {{background-color: rgb(120, 120, 120); color: white;}}" + ) + + def setEnabled(self, enable: bool = True): + super().setEnabled(enable) + self.apply_theme() + + +class TextIndicator(QWidget): + def __init__(self, label): + super().__init__() + layout = QHBoxLayout(self) + layout.setContentsMargins(*ROW_MARGINS) + layout.setSpacing(ROW_SPACING) + self.label = QLabel(label) + self.label.setFixedWidth(LABEL_WIDTH) + self.label.setWordWrap(True) + layout.addWidget(self.label) + self.text = QLabel("-") + self.text.setAlignment(Qt.AlignTop) # type: ignore + layout.addWidget(self.text) + + def setLabel(self, label) -> None: + self.label.setText(label) + + def setText(self, text): + self.text.setText(text) + + def setColor(self, color: str): + self.text.setStyleSheet(f"QLabel {{color:{color}}}") diff --git a/debye_bec/bec_widgets/widgets/auto_gain/register_auto_gain.py b/debye_bec/bec_widgets/widgets/auto_gain/register_auto_gain.py new file mode 100644 index 0000000..2ee7a62 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/auto_gain/register_auto_gain.py @@ -0,0 +1,15 @@ +def main(): # pragma: no cover + from qtpy import PYSIDE6 + + if not PYSIDE6: + print("PYSIDE6 is not available in the environment. Cannot patch designer.") + return + from PySide6.QtDesigner import QPyDesignerCustomWidgetCollection + + from .auto_gain_plugin import AutoGainPlugin + + QPyDesignerCustomWidgetCollection.addCustomWidget(AutoGainPlugin()) + + +if __name__ == "__main__": # pragma: no cover + main() diff --git a/debye_bec/bec_widgets/widgets/restart_server/restart_server.py b/debye_bec/bec_widgets/widgets/restart_server/restart_server.py index c068137..18f3f9e 100644 --- a/debye_bec/bec_widgets/widgets/restart_server/restart_server.py +++ b/debye_bec/bec_widgets/widgets/restart_server/restart_server.py @@ -21,10 +21,6 @@ logger = bec_logger.logger class RestartServer(BECWidget, QWidget): """ Main widget of server restart widget. - - This widget has no visible UI of its own - it only drives the confirmation/ - progress dialog. The surrounding dock panel is hidden as soon as we can find - it, so the user only ever sees the dialog, never an empty "Restart Server" tab. """ PLUGIN = True diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index e79f92e..3770df0 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -69,12 +69,14 @@ class ScheduleItemDialog(QDialog): from ....bec_ipython_client.plugins.digital_twin_core.digital_twin_core import ( DigitalTwinCore, ) + from ..auto_gain.auto_gain import AutoGain from ..digital_twin.digital_twin import DigitalTwin from ..edge_selector import EdgeSelector from ..scan_control_xas.scan_control_xas import ScanControlXAS self.DigitalTwinCore = DigitalTwinCore self.DigitalTwin = DigitalTwin + self.AutoGain = AutoGain self.EdgeSelector = EdgeSelector self.ScanControlXAS = ScanControlXAS @@ -496,102 +498,41 @@ class ScheduleItemDialog(QDialog): # ------------------------------------------------------------------ # def _build_auto_gain_page(self): page = QWidget() - layout = QVBoxLayout(page) + outer = QVBoxLayout(page) - edge_selector_layout = QHBoxLayout() - edge_selector_layout.addWidget(QLabel("Absorption edge:")) - self.edge_selector_button = MyButton("Choose", "default") - self.edge_label = QLabel("No edge selected") - edge_selector_layout.addWidget(self.edge_selector_button) - edge_selector_layout.addWidget(self.edge_label) - edge_selector_layout.addStretch() - self.edge_element = None - self.edge_edge = None - self.edge_energy = None + scroll = QScrollArea() + scroll.setWidgetResizable(True) + self.auto_gain = self.AutoGain(show_control=False, parent=scroll, client=self._client) - layout.addLayout(edge_selector_layout) + scroll.setWidget(self.auto_gain) + outer.addWidget(scroll) - layout.addWidget(QLabel("Auto gain on")) + hint = QLabel( + "Configure the auto-gain functionality, then confirm with Add below - the " + "auto-gain will only be executed when this schedule item runs, not immediately." + ) + hint.setWordWrap(True) + hint.setStyleSheet("color: gray;") + outer.addWidget(hint) - form = QFormLayout() - layout.addLayout(form) - form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) - - self.ic0_check = QCheckBox("") - form.addRow("IC0", self.ic0_check) - self.ic1_check = QCheckBox("") - form.addRow("IC1", self.ic1_check) - self.ic2_check = QCheckBox("") - form.addRow("IC2", self.ic2_check) - self.pips_check = QCheckBox("") - form.addRow("PIPS", self.pips_check) - - layout.addStretch() - - self.edge_selector_button.clicked.connect(self._update_edge) - - self._add_page("auto_gain", "Auto-Gain", page) - - def _update_edge(self, *_): - # NOTE: EdgeSelector is currently the same dialog for every - # beamline; this hook is here so a beamline-specific selector can - # be swapped in later without touching callers. - dlg = self.EdgeSelector(self) - if dlg.exec_(): - self.edge_element = dlg.selected_element - self.edge_edge = dlg.selected_edge - self.edge_energy = dlg.selected_energy - self.edge_label.setText( - f"{dlg.selected_element}, {dlg.selected_edge}-edge, {dlg.selected_energy:0.1f} eV" - ) + self._add_page("auto_gain", "Auto Gain", page) def _collect_auto_gain_result(self) -> dict: - if self.edge_element is None or self.edge_edge is None: - raise ValueError("Choose an absorption edge first.") - amplifier_checks = [ - (self.ic0_check, "ic0"), - (self.ic1_check, "ic1"), - (self.ic2_check, "ic2"), - (self.pips_check, "pips"), - ] - amplifiers = [name for check, name in amplifier_checks if check.isChecked()] - if not amplifiers: - raise ValueError("Select at least one amplifier for auto gain.") + config = self.auto_gain.get_config() + cmd = ( - f"auto_gain.start(element={self.edge_element}, edge={self.edge_edge}, " - f"amplifier={amplifiers}, comp_ring_current=True)" + f"auto_gain.start(element={config['element']}, edge={config['edge']}, " + f"amplifier={config['all_amplifiers']}, comp_ring_current=" + f"{config['compensate_ring_current']}, prohibited_gains={config['prohibited_gains']})" ) return { "command": cmd, "kind": "custom", - "form_state": { - "text": cmd, - "source": "auto_gain", - "element": self.edge_element, - "edge": self.edge_edge, - "energy": self.edge_energy, - "ic0": self.ic0_check.isChecked(), - "ic1": self.ic1_check.isChecked(), - "ic2": self.ic2_check.isChecked(), - "pips": self.pips_check.isChecked(), - }, + "form_state": {"text": cmd, "source": "auto_gain", "config": config}, } def _prefill_auto_gain_form(self, state: dict): - element = state.get("element") - edge = state.get("edge") - if element is not None and edge is not None: - self.edge_element = element - self.edge_edge = edge - self.edge_energy = state.get("energy") - if self.edge_energy is not None: - self.edge_label.setText(f"{element}, {edge}-edge, {self.edge_energy:0.1f} eV") - else: - self.edge_label.setText(f"{element}, {edge}-edge") - self.ic0_check.setChecked(bool(state.get("ic0", False))) - self.ic1_check.setChecked(bool(state.get("ic1", False))) - self.ic2_check.setChecked(bool(state.get("ic2", False))) - self.pips_check.setChecked(bool(state.get("pips", False))) + self.auto_gain.load_config(state["config"]) # ------------------------------------------------------------------ # # Other diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 5b203e6..ae3bb06 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -126,16 +126,15 @@ def build_item_display_text(item: ScheduleItem, beamline: str | None) -> str: if beamline == "x01da": text += f"\n SMPL-XRD: {config['smpl_to_xrd']:.3f} mm" elif item.command.startswith("auto_gain.start("): - config = item.form_state - text += f"Auto-configure gains for {item.form_state['element']}, {item.form_state['edge']}-edge" - devices = "" - for device in ["ic0", "ic1", "ic2", "pips"]: - if config[device] is True: - if len(devices) == 0: - devices += f"\n for devices: {device}" - else: - devices += f", {device}" - text += devices + config = item.form_state["config"] + text += f"Auto-configure gains for {config['element']}, {config['edge']}-edge" + text += f"\nfor devices {config['all_amplifiers']}" + if config["link_ic0_ic1"]: + text += "\nLink IC0 and IC1 gains" + if config["compensate_ring_current"]: + text += "\nCalculate for 400 mA ring current" + if config["prohibited_gains"] != {}: + text += f"\nProhibited gains: {config['prohibited_gains']}" elif item.command.startswith("dev.abs."): action = item.form_state["action"] text += f"{action} Absorber" @@ -331,13 +330,13 @@ class Scheduler(BECWidget, QWidget): logger.info( "Scheduler running at X01DA or X10DA, import and load digital twin and auto-gain" ) - from ....bec_ipython_client.plugins.auto_gain import AutoGain + from ....bec_ipython_client.plugins.auto_gain_core import AutoGainCore from ....bec_ipython_client.plugins.digital_twin_core.digital_twin_core import ( DigitalTwinCore, ) self.digital_twin = DigitalTwinCore() - self.auto_gain = AutoGain() + self.auto_gain = AutoGainCore() else: self.digital_twin = None self.auto_gain = None From a182c3f773975d267da3ca1665ae25b4a4df7d9e Mon Sep 17 00:00:00 2001 From: x01da Date: Wed, 21 Oct 2026 09:46:04 +0200 Subject: [PATCH 44/56] fix(auto_gain): testing and bugfixes auto_gain_core, auto_gain GUI, auto_gain implementation in scheduler --- .../plugins/auto_gain_core.py | 5 +- .../widgets/auto_gain/auto_gain.py | 67 ++++++++++--------- debye_bec/bec_widgets/widgets/client.py | 29 +++++++- .../bec_widgets/widgets/designer_plugins.py | 2 + .../widgets/digital_twin/beamline.py | 51 -------------- .../widgets/scheduler/item_dialog.py | 7 +- .../widgets/scheduler/scheduler.py | 11 ++- 7 files changed, 85 insertions(+), 87 deletions(-) delete mode 100644 debye_bec/bec_widgets/widgets/digital_twin/beamline.py diff --git a/debye_bec/bec_ipython_client/plugins/auto_gain_core.py b/debye_bec/bec_ipython_client/plugins/auto_gain_core.py index 6a1c348..c57f508 100644 --- a/debye_bec/bec_ipython_client/plugins/auto_gain_core.py +++ b/debye_bec/bec_ipython_client/plugins/auto_gain_core.py @@ -70,7 +70,7 @@ class AutoGainCore: def available_gains(self, amplifier): """Returns a list of gains which are allowed for the amplifier""" if amplifier in self.prohibited_gains: - gains = AVAILABLE_GAINS + gains = AVAILABLE_GAINS.copy() for prohibited_gain in self.prohibited_gains[amplifier]: gains.remove(prohibited_gain) return gains @@ -224,6 +224,8 @@ class AutoGainCore: ch["self.dev"].set_gain(lowest_gain) ch["gain"] = lowest_gain + time.sleep(0.5) + remeasure = True logger.info(f"Start measurement from {emin} eV to {emax} eV") while remeasure: @@ -307,6 +309,7 @@ class AutoGainCore: for gname in group_names: active_channels[gname]["self.dev"].set_gain(next_gain) active_channels[gname]["gain"] = next_gain + time.sleep(0.5) logger.info(f"Setting gain of {label} to {next_gain:.0e} and remeasure") remeasure = True else: diff --git a/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.py b/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.py index 56f774c..97dd964 100644 --- a/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.py +++ b/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.py @@ -26,28 +26,31 @@ class Worker(QObject): progress = Signal(str) completed = Signal(int) - @SafeSlot(int) + @SafeSlot(dict) def start(self, config: dict): - core = AutoGainCore() - self.progress.emit("AutoGain started") - results = core.start( - config["element"], - config["edge"], - amplifier=config["all_amplifiers"], - link_ic0_ic1=config["link_ic0_ic1"], - comp_ring_current=config["compensate_ring_current"], - prohibited_gains=config["prohibited_gains"], - ) - results_string = "" - init = True - for amplifier, result in results.items(): - if not init: - results_string += "\n" - else: - init = False - results_string += f"{amplifier} set to gain {result['gain']:.0e}, max signal {result['max_signal']:.3f} V" - self.progress.emit(results_string) - self.completed.emit(True) + success = False + try: + core = AutoGainCore() + self.progress.emit(f"AutoGain started with config {config}") + results = core.start( + config["element"], + config["edge"], + amplifier=config["all_amplifiers"], + link_ic0_ic1=config["link_ic0_ic1"], + comp_ring_current=config["compensate_ring_current"], + prohibited_gains=config["prohibited_gains"], + ) + lines = [ + f"{amp} set to gain {res['gain']:.0e}, max signal {res['max_signal']:.3f} V" + for amp, res in results.items() + ] + self.progress.emit("\n".join(lines)) + success = True + except Exception as exc: + logger.exception("Auto gain failed") + self.progress.emit(f"Error: {exc}") + finally: + self.completed.emit(success) class AutoGain(BECWidget, QWidget): @@ -58,6 +61,8 @@ class AutoGain(BECWidget, QWidget): PLUGIN = True ICON_NAME = "tune" + start_worker = Signal(dict) + def __init__(self, show_control: bool = True, *arg, parent=None, **kwargs): super().__init__(parent=parent, *arg, **kwargs) self.get_bec_shortcuts() @@ -86,10 +91,8 @@ class AutoGain(BECWidget, QWidget): self.root_layout.addWidget(self.apply_group) self.link_ic0_ic1 = CheckBox("link_ic0_ic1", "Link IC0/IC1 gains") - self.link_ic0_ic1.setChecked(True) self.comp_ring_current = CheckBox("comp_ring_current", "Calculate for 400 mA ring current") - self.comp_ring_current.setChecked(True) self.prohibited_gains = MatrixSelector("Prohibited gains") @@ -118,10 +121,13 @@ class AutoGain(BECWidget, QWidget): self.start_button.clicked.connect(self._start) self.worker = Worker() + self.start_worker.connect(self.worker.start) self.worker_thread = QThread() + self.worker.moveToThread(self.worker_thread) + self.worker.progress.connect(self._update_status) self.worker.completed.connect(self._complete) - self.worker.moveToThread(self.worker_thread) + self.worker.completed.connect(self.worker_thread.quit) def _update_edge(self, *_): dlg = EdgeSelector(self) @@ -138,6 +144,7 @@ class AutoGain(BECWidget, QWidget): self.start_button.setEnabled(False) self.status.setColor(get_accent_colors().warning.name()) self.worker_thread.start() + self.start_worker.emit(self.get_config()) def _update_status(self, text): self.status.setText(text) @@ -174,13 +181,13 @@ class AutoGain(BECWidget, QWidget): "element": self.edge_element, "edge": self.edge_edge, "energy": self.edge_energy, - "ic0": self.ic0_check.isChecked, - "ic1": self.ic1_check.isChecked, - "ic2": self.ic2_check.isChecked, - "pips": self.pips_check.isChecked, + "ic0": self.ic0_check.isChecked(), + "ic1": self.ic1_check.isChecked(), + "ic2": self.ic2_check.isChecked(), + "pips": self.pips_check.isChecked(), "all_amplifiers": amplifiers, - "link_ic0_ic1": self.link_ic0_ic1.isChecked, - "compensate_ring_current": self.comp_ring_current.isChecked, + "link_ic0_ic1": self.link_ic0_ic1.isChecked(), + "compensate_ring_current": self.comp_ring_current.isChecked(), "prohibited_gains": self.prohibited_gains.selection(), } diff --git a/debye_bec/bec_widgets/widgets/client.py b/debye_bec/bec_widgets/widgets/client.py index 94aa2c0..481d214 100644 --- a/debye_bec/bec_widgets/widgets/client.py +++ b/debye_bec/bec_widgets/widgets/client.py @@ -13,6 +13,7 @@ logger = bec_logger.logger _Widgets = { + "AutoGain": "AutoGain", "DataViewer": "DataViewer", "DigitalTwin": "DigitalTwin", "RestartServer": "RestartServer", @@ -21,6 +22,30 @@ _Widgets = { } +class AutoGain(RPCBase): + """Main widget of auto gain widget.""" + + _IMPORT_MODULE = "debye_bec.bec_widgets.widgets.auto_gain.auto_gain" + + @rpc_call + def remove(self): + """ + Cleanup the BECConnector + """ + + @rpc_call + def attach(self): + """ + None + """ + + @rpc_call + def detach(self): + """ + Detach the widget from its parent dock widget (if widget is in the dock), making it a floating widget. + """ + + class DataViewer(RPCBase): """Main widget of Data Viewer""" @@ -124,7 +149,7 @@ class Scheduler(RPCBase): _IMPORT_MODULE = "debye_bec.bec_widgets.widgets.scheduler.scheduler" @rpc_call - def run_schedule(self): + def run_schedule(self, first_item: "int" = 0): """ Run the schedule, continuing from wherever it last left off. """ @@ -154,6 +179,7 @@ class Scheduler(RPCBase): index: "int | None" = None, kind: "str" = "custom", form_state: "dict | None" = None, + pause_on_failure: "bool" = False, ) -> "str": """ RPC-exposed: insert a new, PENDING command into the schedule. @@ -181,6 +207,7 @@ class Scheduler(RPCBase): command: "str", kind: "str" = "custom", form_state: "dict | None" = None, + pause_on_failure: "bool" = True, ): """ RPC-exposed: change the command of an item that has not started diff --git a/debye_bec/bec_widgets/widgets/designer_plugins.py b/debye_bec/bec_widgets/widgets/designer_plugins.py index aaf7251..7a355e6 100644 --- a/debye_bec/bec_widgets/widgets/designer_plugins.py +++ b/debye_bec/bec_widgets/widgets/designer_plugins.py @@ -5,6 +5,7 @@ from __future__ import annotations # pylint: skip-file designer_plugins = { + "AutoGain": ("debye_bec.bec_widgets.widgets.auto_gain.auto_gain", "AutoGain"), "DataViewer": ("debye_bec.bec_widgets.widgets.data_viewer.data_viewer", "DataViewer"), "DigitalTwin": ("debye_bec.bec_widgets.widgets.digital_twin.digital_twin", "DigitalTwin"), "RestartServer": ( @@ -19,6 +20,7 @@ designer_plugins = { } widget_icons = { + "AutoGain": "tune", "DataViewer": "find_in_page", "DigitalTwin": "lightbulb", "RestartServer": "restart_alt", diff --git a/debye_bec/bec_widgets/widgets/digital_twin/beamline.py b/debye_bec/bec_widgets/widgets/digital_twin/beamline.py deleted file mode 100644 index 3653284..0000000 --- a/debye_bec/bec_widgets/widgets/digital_twin/beamline.py +++ /dev/null @@ -1,51 +0,0 @@ -import socket - -from bec_lib import bec_logger - -from .types import BeamlineId - -logger = bec_logger.logger - - -def get_beamline_id() -> BeamlineId: - """ - Based on the bec servers hostname, tries to extract the beamline - identifier (e.g. x01da, x10da, etc). - - Raises: - ValueError if beamline cannot be extracted from hostname or beamline not implemented. - """ - bec_hostname = socket.gethostname() - start = bec_hostname.find("x") - if start != -1: - beamline = bec_hostname[start : start + 5] - match beamline: - case "x01da": - return BeamlineId.X01DA - case "x10da": - return BeamlineId.X10DA - case _: - raise ValueError(f"Not implemented beamline {beamline}") - else: - logger.warning(f"Failed to extract beamline from bec server hostname {bec_hostname}") - choice = input("Do you want to manually select a beamline? (yes/no): ").strip().lower() - if choice in ["yes", "y"]: - bl = input(f"Choose from: {[bl.value for bl in BeamlineId]}") - if bl in BeamlineId: - logger.info(f"Manually selected beamline {bl}") - return BeamlineId(bl) - else: - raise ValueError(f"Wrong selection {bl}") - else: - raise ValueError("Cannot open digital twin without a beamline") - - -def get_parameters(): - beamline = get_beamline_id() - if beamline == "x01da": - from . import x01da_parameters as parameters - elif beamline == "x10da": - from . import x10da_parameters as parameters - else: - raise ValueError(f"Unknown beamline: {beamline}") - return parameters diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index 3770df0..b75b026 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -521,9 +521,10 @@ class ScheduleItemDialog(QDialog): config = self.auto_gain.get_config() cmd = ( - f"auto_gain.start(element={config['element']}, edge={config['edge']}, " - f"amplifier={config['all_amplifiers']}, comp_ring_current=" - f"{config['compensate_ring_current']}, prohibited_gains={config['prohibited_gains']})" + f"auto_gain.start(element='{config['element']}', edge='{config['edge']}', " + + f"amplifier={config['all_amplifiers']}, link_ic0_ic1={config['link_ic0_ic1']}, " + + f"comp_ring_current= {config['compensate_ring_current']}, " + + f"prohibited_gains={config['prohibited_gains']})" ) return { "command": cmd, diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index ae3bb06..e5e6ae4 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -134,7 +134,15 @@ def build_item_display_text(item: ScheduleItem, beamline: str | None) -> str: if config["compensate_ring_current"]: text += "\nCalculate for 400 mA ring current" if config["prohibited_gains"] != {}: - text += f"\nProhibited gains: {config['prohibited_gains']}" + prohibited_gains = ( + "{" + + ", ".join( + f"{amp}: [" + ", ".join(f"{g:.0e}" for g in gains) + "]" + for amp, gains in config["prohibited_gains"].items() + ) + + "}" + ) + text += "\nProhibited gains: " + prohibited_gains elif item.command.startswith("dev.abs."): action = item.form_state["action"] text += f"{action} Absorber" @@ -559,6 +567,7 @@ class Scheduler(BECWidget, QWidget): def _load_or_seed_schedule(self) -> Schedule: logger.info("load or seed schedule") msg: VariableMessage | None = self.connector.get(self._endpoint) + # msg = None # Overwrite any existing schedule in redis if msg is not None: logger.info(f"Got msg from endpoint: {msg.value}") return Schedule.model_validate(msg.value) From 7144e55a7b718d77e891b586548f99eaef0c4b6a Mon Sep 17 00:00:00 2001 From: hitz_s Date: Wed, 21 Oct 2026 13:51:52 +0200 Subject: [PATCH 45/56] wip(digital_twin): Move selection button. motion interlock --- .../digital_twin_core/digital_twin_core.py | 112 +++++++++++----- .../digital_twin_core/motion_worker.py | 7 + .../widgets/digital_twin/digital_twin.py | 17 ++- .../digital_twin/panels/mover_panel.py | 48 ++++++- .../digital_twin/widgets/move_widget.py | 125 +++++++++++++----- .../digital_twin/widgets/qt_widgets.py | 35 +++-- 6 files changed, 255 insertions(+), 89 deletions(-) diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py index 9ebf663..31f53fe 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py @@ -12,7 +12,7 @@ from xrt.backends.raycing.physconsts import AVOGADRO, CHeVcm from . import parameters as bl from .beamline import get_beamline_id -from .motion_worker import MotionWorker +from .motion_worker import MotionOutcome, MotionWorker from .types import BeamlineId, ConfigDict, DataDict, SurfaceDict H = 6.62606957e-34 @@ -27,21 +27,27 @@ logger = bec_logger.logger class _ExclusiveGroupManager: - """Coordinates one exclusive group: only motors from the same - subgroup may be active at once; a different subgroup must wait until - the active one fully finishes.""" - def __init__(self): self._cond = threading.Condition() self._active_subgroup = None self._active_count = 0 - def acquire(self, subgroup_id): + def acquire(self, subgroup_id, cancelled=None, on_wait=None) -> bool: + """Block until the subgroup may run. Returns False if cancelled while waiting.""" with self._cond: + notified = False while self._active_subgroup is not None and self._active_subgroup != subgroup_id: - self._cond.wait() + if cancelled and cancelled(): + return False + if on_wait and not notified: + on_wait() + notified = True + self._cond.wait(0.1) # timeout so cancellation is noticed + if cancelled and cancelled(): + return False self._active_subgroup = subgroup_id self._active_count += 1 + return True def release(self): with self._cond: @@ -95,6 +101,8 @@ class DigitalTwinCore: if load_offsets: self.load_offsets() + self._group_managers = {gi: _ExclusiveGroupManager() for gi in range(len(EXCLUSIVE_GROUPS))} + def _exclusive_group_key(self, motor: str): """Return (group_index, subgroup_index) for `motor`, or (None, None) if it isn't part of any exclusive group and can move freely.""" @@ -104,60 +112,94 @@ class DigitalTwinCore: return gi, si return None, None - def move_with_config(self, config): + def run_exclusive( + self, worker, abort=None, cancel=None, on_waiting=None, on_started=None + ) -> str: """ - Move all motors in `config` to their target positions, all starting at + Run `worker` once its exclusive group allows it. Blocks the calling thread. + + abort: shared by a batch of motors; set on the first failure so that + motors of the batch that have not started yet are not started. + cancel: per-motor event (user pressed Stop while waiting). + """ + events = [e for e in (abort, cancel) if e is not None] + cancelled = lambda: any(e.is_set() for e in events) + + gi, si = self._exclusive_group_key( + worker.motor + ) # before run(): aliases change worker.motor + manager = self._group_managers[gi] if gi is not None else None + + if manager is not None and not manager.acquire(si, cancelled, on_waiting): + return MotionOutcome.CANCELLED + try: + if cancelled(): + return MotionOutcome.CANCELLED + if on_started: + on_started() + try: + worker.run() + except Exception as e: # raised outside motion()'s own try/except + logger.error(f"Error preparing movement of {worker.motor}: {e}") + worker.last_exception = e + if worker.last_exception is not None: + if abort is not None: + abort.set() + return MotionOutcome.FAILED + return MotionOutcome.DONE + finally: + if manager is not None: + manager.release() + + def move_with_config(self, config, motors: list | None = None): + """ + Move all motors according to the "config" to their target positions, all starting at once. Motors are free to move concurrently unless they belong to the same exclusive group (see `EXCLUSIVE_GROUPS`) but different subgroups, in which case one subgroup must fully finish before another starts. + If "motors" is provided, only these motors will be moved Returns: dict: {"success": True, "moved": [...]} if every motor completed without error, else {"success": False, "moved": [...], - "failures": {motor: error}}. + "failures": {motor: error}} or "aborted": {motor} """ positions = self.calc_positions(config) positions = self.apply_offsets(positions, nested_config=True) - managers: dict[int, _ExclusiveGroupManager] = {} - for motor in positions: - gi, _ = self._exclusive_group_key(motor) - if gi is not None: - managers.setdefault(gi, _ExclusiveGroupManager()) + if motors is not None: + positions = {m: p for m, p in positions.items() if m in motors} - moved: list[str] = [] + abort = threading.Event() + moved, aborted = [], [] failures: dict[str, Exception | str] = {} results_lock = threading.Lock() def run_motor(motor: str, target: float): - gi, si = self._exclusive_group_key(motor) - manager = managers.get(gi) if gi is not None else None - if manager: - manager.acquire(si) - try: - worker = MotionWorker(self.beamline, self.dev, motor, target) - worker.run() # blocks this thread until finished or errored - with results_lock: - if worker.last_exception is not None: - failures[motor] = worker.last_exception - else: - moved.append(motor) - finally: - if manager: - manager.release() + worker = MotionWorker(self.beamline, self.dev, motor, target) + outcome = self.run_exclusive(worker, abort=abort) + with results_lock: + if outcome == MotionOutcome.DONE: + moved.append(motor) + elif outcome == MotionOutcome.FAILED: + failures[motor] = worker.last_exception + else: + aborted.append(motor) threads = [ - threading.Thread(target=run_motor, args=(motor, pos["value"]), daemon=True) - for motor, pos in positions.items() + threading.Thread(target=run_motor, args=(m, p["value"]), daemon=True) + for m, p in positions.items() ] for t in threads: t.start() for t in threads: t.join() + result = {"success": not failures, "moved": moved} if failures: - return {"success": False, "moved": moved, "failures": failures} - return {"success": True, "moved": moved} + result["failures"] = failures + result["aborted"] = aborted # never started because of the failure + return result def load_offsets(self): if self.offsets == {}: diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py index 0cd07c6..8eef9f3 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py @@ -13,6 +13,12 @@ from .types import BeamlineId logger = bec_logger.logger +class MotionOutcome: + DONE = "done" + FAILED = "failed" + CANCELLED = "cancelled" # stopped by the user, or aborted because another motor failed + + class MotionWorker: """ Executes motion on the specified motor and includes some safety during @@ -239,6 +245,7 @@ class MotionWorker: now = time.time() if time.time() - last_check < update_interval: time.sleep(0.01) + continue last_check = now if self._stop_flag.is_set(): self.dev[self.motor].stop() diff --git a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py index 9702c5f..5be5b50 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py @@ -4,6 +4,7 @@ Digital Twin: Custom BEC widget to support the beamline alignment. import json import sys +import threading import time from pathlib import Path from typing import Literal, cast @@ -108,7 +109,7 @@ class DigitalTwin(BECWidget, QWidget): self.plot_layout.addWidget(self.surface_plots, stretch=1) self.plot_widget.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) - self.mover = MoverPanel(self.beamline, self.dev) + self.mover = MoverPanel(self.core, self.beamline, self.dev) self.input_scroll = self._scroll_area(self.input_widget, min_width=320, max_width=360) self.mover_scroll = self._scroll_area(self.mover, min_width=380, max_width=460) @@ -155,6 +156,8 @@ class DigitalTwin(BECWidget, QWidget): self.settings.load_from_config.clicked_connect(self.load_from_config) self.settings.load_from_scan.clicked_connect(self.load_from_scan) + self.mover.multi_move.clicked_connect(self._multi_move) + self.edge_selector_energy = 0.0 self.edge_selector_element = "" self.edge_selector_edge = "" @@ -803,7 +806,7 @@ class DigitalTwin(BECWidget, QWidget): self.settings.load_offsets.setText("Unload") self.settings.offsets_status.setText("Loaded and applied") self.settings.offsets_status.setColor(get_accent_colors().success.name()) - self.settings.show_offsets.enable_button(True) + self.settings.show_offsets.setEnabled(True) else: # Offsets were unloaded self.calc_assistant(identifier="init") @@ -811,7 +814,7 @@ class DigitalTwin(BECWidget, QWidget): self.settings.load_offsets.setText("Load") self.settings.offsets_status.setText("No offsets") self.settings.offsets_status.setColor(get_accent_colors().default.name()) - self.settings.show_offsets.enable_button(False) + self.settings.show_offsets.setEnabled(False) @SafeSlot() def show_offsets(self, *_): @@ -1325,6 +1328,14 @@ class DigitalTwin(BECWidget, QWidget): energy = self.input.energy.value() self.input.cm_pitch_critical.setValue(-self.core.cm_critical_angle(cm_stripe, energy) * 1e3) + def _multi_move(self): + """ + Move the selected motors at the same time (if permitted).""" + abort = threading.Event() # one failure aborts the not-yet-started motors of this batch + for w in self.mover.mover_widgets: + if w.checkbox.isChecked(): + w.start_motion(abort=abort) + if __name__ == "__main__": app = QApplication(sys.argv) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py b/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py index 2c98af5..0a0696d 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py @@ -9,22 +9,25 @@ from qtpy.QtWidgets import QVBoxLayout, QWidget from .....bec_ipython_client.plugins.digital_twin_core.types import BeamlineId from ..widgets.move_widget import AbsorberWidget, MoveWidget -from ..widgets.qt_widgets import Group +from ..widgets.qt_widgets import Button, Group, QLabel class MoverPanel(QWidget): """ "Panel to move an axis to a certain position""" - def __init__(self, beamline: BeamlineId, dev, parent=None): + def __init__(self, core, beamline: BeamlineId, dev, parent=None): super().__init__(parent) self._layout = QVBoxLayout(self) self._layout.setContentsMargins(4, 4, 4, 4) self._layout.setSpacing(4) + self.core = core + self.mover_widgets = [] # FE Slits self.sldi_gapx = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="sldi_gapx", @@ -36,6 +39,7 @@ class MoverPanel(QWidget): self.mover_widgets.append(self.sldi_gapx) self.sldi_gapy = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="sldi_gapy", @@ -55,6 +59,7 @@ class MoverPanel(QWidget): # Collimating mirror self.cm_trx = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="cm_trx", @@ -66,6 +71,7 @@ class MoverPanel(QWidget): self.mover_widgets.append(self.cm_trx) self.cm_try = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="cm_try", @@ -77,6 +83,7 @@ class MoverPanel(QWidget): self.mover_widgets.append(self.cm_try) self.cm_bnd = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="cm_bnd", @@ -88,6 +95,7 @@ class MoverPanel(QWidget): self.mover_widgets.append(self.cm_bnd) self.cm_rotx = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="cm_rotx", @@ -104,6 +112,7 @@ class MoverPanel(QWidget): # Monochromator self.mo1_bragg_angle = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="mo1_bragg_angle", @@ -115,6 +124,7 @@ class MoverPanel(QWidget): self.mover_widgets.append(self.mo1_bragg_angle) self.mo1_trx = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="mo1_trx", @@ -126,6 +136,7 @@ class MoverPanel(QWidget): self.mover_widgets.append(self.mo1_trx) self.mo1_try = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="mo1_try", @@ -138,6 +149,7 @@ class MoverPanel(QWidget): if beamline == BeamlineId.X01DA: self.mo1_roty = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="mo1_roty", @@ -158,6 +170,7 @@ class MoverPanel(QWidget): # OP Slits 1 self.sl1_centery = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="sl1_centery", @@ -169,6 +182,7 @@ class MoverPanel(QWidget): self.mover_widgets.append(self.sl1_centery) self.sl1_gapy = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="sl1_gapy", @@ -183,6 +197,7 @@ class MoverPanel(QWidget): # OP Beam Monitor 1 self.bm1_try = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="bm1_try", @@ -197,6 +212,7 @@ class MoverPanel(QWidget): # Focusing Mirror self.fm_trx = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="fm_trx", @@ -208,6 +224,7 @@ class MoverPanel(QWidget): self.mover_widgets.append(self.fm_trx) self.fm_try = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="fm_try", @@ -219,6 +236,7 @@ class MoverPanel(QWidget): self.mover_widgets.append(self.fm_try) self.fm_bnd = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="fm_bnd", @@ -230,6 +248,7 @@ class MoverPanel(QWidget): self.mover_widgets.append(self.fm_bnd) self.fm_rotx = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="fm_rotx", @@ -241,6 +260,7 @@ class MoverPanel(QWidget): self.mover_widgets.append(self.fm_rotx) self.fm_roty = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="fm_roty", @@ -252,6 +272,7 @@ class MoverPanel(QWidget): self.mover_widgets.append(self.fm_roty) self.fm_rotz = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="fm_rotz", @@ -270,6 +291,7 @@ class MoverPanel(QWidget): if beamline == "x01da": # OP Slits 2 self.sl2_centery = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="sl2_centery", @@ -281,6 +303,7 @@ class MoverPanel(QWidget): self.mover_widgets.append(self.sl2_centery) self.sl2_gapy = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="sl2_gapy", @@ -295,6 +318,7 @@ class MoverPanel(QWidget): # OP Beam Monitor 2 self.bm2_try = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="bm2_try", @@ -310,6 +334,7 @@ class MoverPanel(QWidget): if beamline == "x01da": # Optical Table self.ot_try = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="ot_try", @@ -321,6 +346,7 @@ class MoverPanel(QWidget): self.mover_widgets.append(self.ot_try) self.ot_rotx = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="ot_rotx", @@ -335,6 +361,7 @@ class MoverPanel(QWidget): # Experimental Station 0 self.es0wi_try = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="es0wi_try", @@ -350,6 +377,7 @@ class MoverPanel(QWidget): # Experimental Station 1 if beamline == "x01da": self.ot_es1_trz = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="ot_es1_trz", @@ -360,6 +388,7 @@ class MoverPanel(QWidget): ) self.mover_widgets.append(self.ot_es1_trz) self.es1man_trz = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="es1man_trz", @@ -372,6 +401,7 @@ class MoverPanel(QWidget): if beamline == "x10da": self.es1_try = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="es1_try", @@ -383,6 +413,7 @@ class MoverPanel(QWidget): self.mover_widgets.append(self.es1_try) self.es1ic0_try = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="es1ic0_try", @@ -394,6 +425,7 @@ class MoverPanel(QWidget): self.mover_widgets.append(self.es1ic0_try) self.es1ic1_try = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="es1ic1_try", @@ -405,6 +437,7 @@ class MoverPanel(QWidget): self.mover_widgets.append(self.es1ic1_try) self.es1ic2_try = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="es1ic2_try", @@ -425,6 +458,7 @@ class MoverPanel(QWidget): # Experimental Station 2 if beamline == "x01da": self.ot_es2_trz = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="ot_es2_trz", @@ -437,6 +471,7 @@ class MoverPanel(QWidget): if beamline == "x10da": self.es2_try = MoveWidget( + core=self.core, beamline=beamline, dev=dev, motor="es2_try", @@ -452,6 +487,13 @@ class MoverPanel(QWidget): else: self.es2_mov_group = Group("Experimental Station 2", [self.es2_try]) + # Multi-Mover + self.multi_move = Button(label_button="Move Selection", enabled=True, color="success") + self.multi_move_info = QLabel( + "Not all motors can move together at the same time, digital twin will take care of that." + ) + self.multi_move_group = Group("Multi Move", [self.multi_move, self.multi_move_info]) + # Assemble complete mover group if beamline == "x01da": self.mover_group = Group( @@ -470,6 +512,7 @@ class MoverPanel(QWidget): self.es0_mov_group, self.es1_mov_group, self.es2_mov_group, + self.multi_move_group, ], ) else: @@ -487,6 +530,7 @@ class MoverPanel(QWidget): self.es0_mov_group, self.es1_mov_group, self.es2_mov_group, + self.multi_move_group, ], ) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py b/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py index 1347d30..c53e397 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py @@ -12,21 +12,23 @@ from qtpy.QtCore import Property # type: ignore[attr-defined] from qtpy.QtCore import Signal # type: ignore[attr-defined] from qtpy.QtCore import QObject, QPropertyAnimation, Qt from qtpy.QtGui import QTransform -from qtpy.QtWidgets import QApplication, QHBoxLayout, QLabel, QPushButton, QWidget +from qtpy.QtWidgets import QApplication, QCheckBox, QHBoxLayout, QLabel, QPushButton, QWidget -from .....bec_ipython_client.plugins.digital_twin_core.motion_worker import MotionWorker +from .....bec_ipython_client.plugins.digital_twin_core.motion_worker import ( + MotionOutcome, + MotionWorker, +) from .....bec_ipython_client.plugins.digital_twin_core.types import BeamlineId logger = bec_logger.logger class Status: - """Status class for the axis""" - - IN_POSITION = "in_position" # green mdi.check-circle - NOT_IN_POSITION = "not_in_position" # orange mdi.close-circle - MOVING = "moving" # blue mdi.loading (spinning) - ERROR = "error" # red mdi.alert-circle + IN_POSITION = "in_position" # green + NOT_IN_POSITION = "not_in_position" # orange + QUEUED = "queued" # grey, waiting for another motor group + MOVING = "moving" # blue + ERROR = "error" # red class StatusIcon(QWidget): @@ -42,6 +44,7 @@ class StatusIcon(QWidget): Status.NOT_IN_POSITION: ("cancel", "#e6d922"), Status.ERROR: ("warning", "#e74c3c"), Status.MOVING: ("cycle", "#2980b9"), + Status.QUEUED: ("hourglass_empty", "#7f8c8d"), } def __init__(self, parent=None): @@ -122,10 +125,10 @@ class StatusIcon(QWidget): class _WorkerSignals(QObject): - """Tiny QObject just to own signals, since MotionWorker itself is no longer a QObject.""" - position_changed = Signal(float) error = Signal() + waiting = Signal() # must wait for another subgroup + started = Signal() # slot acquired, motion begins finished = Signal() @@ -138,10 +141,13 @@ class MoveWidget(QWidget): - Start / Stop button """ - def __init__( - self, beamline: BeamlineId, dev, motor, label: str = "", unit=None, decimals=3, deadband=0.0 - ): + _STATUS_TOOLTIPS = {Status.QUEUED: "Waiting for other motors to finish"} + + def __init__(self, core, beamline, dev, motor, label="", unit=None, decimals=3, deadband=0.0): super().__init__() + self.core = core + self._cancel: threading.Event | None = None + self.fb = 0.0 self.target = 0 self.beamline = beamline @@ -162,6 +168,11 @@ class MoveWidget(QWidget): layout.setContentsMargins(4, 0, 4, 0) layout.setSpacing(4) + # Checkbox + self.checkbox = QCheckBox() + self.checkbox.setChecked(True) + layout.addWidget(self.checkbox) + # Name self.label = QLabel(label) self.label.setFixedWidth(76) @@ -226,6 +237,11 @@ class MoveWidget(QWidget): + f"{{background-color: {get_accent_colors().emergency.name()}; color: white;}}" ) + @property + def is_busy(self) -> bool: + """True from start until the finished signal was handled (moving OR queued).""" + return self._thread is not None + def set_target(self, target): """Change the target value in the ui""" self.target = target @@ -262,13 +278,13 @@ class MoveWidget(QWidget): ) def _set_status(self, status: str): - """Set the current status icon in the ui""" self.status = status self.status_icon.set_status(status) + self.status_icon.setToolTip(self._STATUS_TOOLTIPS.get(status, "")) def _on_target_or_fb_changed(self): """Re-evaluate in-position status whenever the target value changes.""" - if self.status in (Status.ERROR, Status.MOVING): + if self.status in (Status.ERROR, Status.MOVING, Status.QUEUED): return if abs(self.fb - self.target) <= self.deadband: self._set_status(Status.IN_POSITION) @@ -276,49 +292,86 @@ class MoveWidget(QWidget): self._set_status(Status.NOT_IN_POSITION) def _on_button_clicked(self): - """Starts or stops motion depending on current situation""" - if self._thread and self._thread.is_alive(): + if self.is_busy: self._stop_motion() else: - self._start_motion() + self.start_motion() - def _start_motion(self): - """Start a motion""" - target = self.target - if abs(target - self.fb) <= self.deadband: + def start_motion(self, abort: threading.Event | None = None): + """Start a motion. `abort` is shared by a batch (Move Selection) so that one failure + prevents the not-yet-started motors of that batch from starting.""" + if self.is_busy: + return + if abs(self.target - self.fb) <= self.deadband: self._set_status(Status.IN_POSITION) return - self._set_status(Status.MOVING) self._apply_button_style("stop") + self._cancel = threading.Event() - self._signals = _WorkerSignals() - self._signals.position_changed.connect(self._on_position_changed) - self._signals.error.connect(self._on_error) - self._signals.finished.connect(self._on_motion_finished) - self._signals.finished.connect(self._cleanup_thread) + signals = _WorkerSignals() + signals.waiting.connect(self._on_waiting) + signals.started.connect(self._on_started) + signals.position_changed.connect(self._on_position_changed) + signals.error.connect(self._on_error) + signals.finished.connect(self._on_motion_finished) + signals.finished.connect(self._cleanup_thread) + self._signals = signals - self._worker = MotionWorker( + # No on_finished here: _run emits it exactly once (MotionWorker.run never calls + # it for motors that are "not integrated in digital twin"). + worker = MotionWorker( self.beamline, self.dev, self.motor, - target, - on_position_changed=self._signals.position_changed.emit, - on_error=self._signals.error.emit, - on_finished=self._signals.finished.emit, + self.target, + on_position_changed=signals.position_changed.emit, + on_error=signals.error.emit, + ) + self._worker = worker + self._thread = threading.Thread( + target=self._run, args=(worker, signals, self._cancel, abort), daemon=True ) - self._thread = threading.Thread(target=self._worker.run, daemon=True) self._thread.start() + def _run(self, worker, signals, cancel, abort): + try: + outcome = self.core.run_exclusive(...) + if outcome == MotionOutcome.FAILED and worker.last_exception is not None: + signals.error.emit() # harmless if motion() already emitted it + finally: + signals.finished.emit() + try: + self.core.run_exclusive( + worker, + abort=abort, + cancel=cancel, + on_waiting=signals.waiting.emit, + on_started=signals.started.emit, + ) + except Exception: + signals.error.emit() + raise + finally: + signals.finished.emit() + + def _on_waiting(self): + self._set_status(Status.QUEUED) + + def _on_started(self): + self._set_status(Status.MOVING) + def _on_error(self): """Called when an error occurs""" self._set_status(Status.ERROR) self._apply_button_style("start") def _stop_motion(self): - """Attempts to stop the motion""" + """Stop a running motor, or remove a queued one from the queue.""" + if self._cancel: + self._cancel.set() # releases a waiting motor within ~0.1 s if self._worker: - self._worker.stop() + self._worker.stop() # stops a running motor def _on_position_changed(self, pos: float): """Change the feedback value in the ui""" diff --git a/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py b/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py index 646abe9..95c8d46 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py @@ -179,7 +179,9 @@ class ComboBox(QWidget): class Button(QWidget): - def __init__(self, label=None, label_button: str = "", enabled=False): + def __init__( + self, label=None, label_button: str = "", enabled: bool = False, color: str = "default" + ): super().__init__() layout = QHBoxLayout(self) layout.setContentsMargins(*ROW_MARGINS) @@ -189,28 +191,35 @@ class Button(QWidget): self.label.setFixedWidth(LABEL_WIDTH) layout.addWidget(self.label) self.button = QPushButton(label_button) - self.enable_button(enabled) + self.setEnabled(enabled) layout.addWidget(self.button) + self.color = color def clicked_connect(self, func): """Connect a function to the button press.""" self.button.clicked.connect(func) - def enable_button(self, enable: bool = False): - if enable: - self.button.setStyleSheet( - f"QPushButton {{background-color: {get_accent_colors().default.name()}; color: white;}}" - ) - self.button.setEnabled(True) - else: # disabled - self.button.setStyleSheet( - "QPushButton {{background-color: rgb(120, 120, 120); color: white;}}" - ) - self.button.setDisabled(True) + def setEnabled(self, enable: bool = True): + self.button.setEnabled(enable) + self.apply_theme() def setText(self, text): self.button.setText(text) + def setColor(self, color: str): + self.color = color + self.apply_theme() + + def apply_theme(self): + if self.button.isEnabled(): + colors = get_accent_colors() + color = getattr(colors, self.color).name() + self.button.setStyleSheet(f"QPushButton {{ background-color: {color}; color: white; }}") + else: + self.button.setStyleSheet( + "QPushButton {{background-color: rgb(120, 120, 120); color: white;}}" + ) + class TextIndicator(QWidget): def __init__(self, label): From 0215d6ef6c7d4e379fe14d3549a91f015c047e90 Mon Sep 17 00:00:00 2001 From: hitz_s Date: Thu, 22 Oct 2026 08:30:25 +0200 Subject: [PATCH 46/56] feat(auto_gain): Implement for X10DA --- .../plugins/auto_gain_core.py | 144 +++++++++++------- .../{digital_twin_core => }/beamline.py | 23 ++- .../plugins/digital_twin_core/__init__.py | 2 +- .../digital_twin_core/digital_twin_core.py | 13 +- .../digital_twin_core/motion_worker.py | 2 +- .../widgets/auto_gain/auto_gain.py | 20 ++- .../widgets/auto_gain/qt_widgets.py | 32 ++-- .../digital_twin/panels/input_panel.py | 2 +- .../digital_twin/panels/mover_panel.py | 2 +- .../digital_twin/widgets/move_widget.py | 1 - 10 files changed, 151 insertions(+), 90 deletions(-) rename debye_bec/bec_ipython_client/plugins/{digital_twin_core => }/beamline.py (79%) diff --git a/debye_bec/bec_ipython_client/plugins/auto_gain_core.py b/debye_bec/bec_ipython_client/plugins/auto_gain_core.py index c57f508..6152d99 100644 --- a/debye_bec/bec_ipython_client/plugins/auto_gain_core.py +++ b/debye_bec/bec_ipython_client/plugins/auto_gain_core.py @@ -12,21 +12,23 @@ from ...devices.eh_shutter import STATUS as EH_PH_STATUS from ...devices.ionization_chambers.ionization_chamber_enums import AmplifierEnable from ...devices.nidaq.nidaq_enums import EpicsMode, NidaqState from ...devices.op_shutter import STATUS as OP_PH_STATUS +from .beamline import BeamlineId, get_beamline_id logger = bec_logger.logger -EMIN = -100 -EMAX = 200 +EMIN = -200 # Minimum energy will be edge energy - EMIN +EMAX = 1000 # Maximum energy will be edge energy + EMAX -MIN_RING_CURRENT = -1 # Minimum ring current to use auto-gain +MIN_RING_CURRENT = 1 # Minimum ring current to use auto-gain NOMINAL_RING_CURRENT = 400 # Nominal ring current of SLS2 TIMEOUT_PUT_PV = 5 # Timeout to set a PV -MONO_VELOCITY = 20 # Move velocity in deg/s +MONO_VELOCITY = 20 # Move velocity in deg/s (only X01DA) TIMEOUT_MONO_MOVE = 30 # Timeout to finish a movement on the mono -AVAILABLE_GAINS = [1e6, 1e7, 5e7, 1e8, 1e9] # ascending order +AVAILABLE_GAINS_X01DA = [1e6, 1e7, 5e7, 1e8, 1e9] # ascending order +AVAILABLE_GAINS_X10DA = [1e6, 1e7, 1e8, 1e9, 1e10] # ascending order MIN_SIGNAL = 0.05 # Minimum signal to count as valid signal FULL_SCALE_V = 10.0 # NIDAQ AI full-scale range SAFETY_MARGIN = 0.9 # keep max signal under 90% of full scale @@ -64,17 +66,22 @@ class AutoGainCore: raise AutoGainError("Did not get bec") self.dev = dev self.bec = bec + self.beamline = get_beamline_id() + if self.beamline == BeamlineId.X01DA: + self.available_gains = AVAILABLE_GAINS_X01DA + else: + self.available_gains = AVAILABLE_GAINS_X10DA self.linked_channels = None self.prohibited_gains = {} - def available_gains(self, amplifier): + def allowed_gains(self, amplifier): """Returns a list of gains which are allowed for the amplifier""" if amplifier in self.prohibited_gains: - gains = AVAILABLE_GAINS.copy() + gains = self.available_gains.copy() for prohibited_gain in self.prohibited_gains[amplifier]: gains.remove(prohibited_gain) return gains - return AVAILABLE_GAINS + return self.available_gains def start( self, @@ -96,7 +103,9 @@ class AutoGainCore: element(str): Element which defines the energy at which the gain will be set, e.g. 'Cu' edge(str): Corresponding edge, e.g. 'L1' amplifier(list[str]): Amplifiers where auto-gain should be applied to - Defaults to all amplifiers -> ['ic0', 'ic1', 'ic2', 'pips'] + Defaults to all amplifiers -> + X01DA = ['ic0', 'ic1', 'ic2', 'pips'] + X10DA = ['ic0', 'ic1', 'ic2'] link_ic0_ic1(bool): Apply same gain to ic0 and ic1. Defaults to True comp_ring_current(bool): Respects the current ring current and calculates the gain(s) for a nominal ring current of 400 mA. Defaults to True @@ -127,7 +136,10 @@ class AutoGainCore: self.prohibited_gains = prohibited_gains if amplifier is None: - amplifier = ["ic0", "ic1", "ic2", "pips"] + if self.beamline == BeamlineId.X01DA: + amplifier = ["ic0", "ic1", "ic2", "pips"] + else: + amplifier = ["ic0", "ic1", "ic2"] # Make sure NIDAQ is in standby mode if self.dev.nidaq.state.get() != NidaqState.STANDBY: @@ -155,15 +167,17 @@ class AutoGainCore: emin = energy + EMIN emax = energy + EMAX - # Check range of mono - low_limit = self.dev.mo1_bragg.low_lim.get() - high_limit = self.dev.mo1_bragg.high_lim.get() - if emin < low_limit or emax > high_limit: - raise ValueError( - f"Chosen element/edge {element}/{edge} with edge energy of {energy}" - + " is outside of accessible range of monochromator " - + f"{low_limit:.1f} eV - {high_limit:.1f} eV" - ) + # Check range of mono (only X01DA) + if self.beamline == BeamlineId.X01DA: + low_limit = self.dev.mo1_bragg.low_lim.get() + high_limit = self.dev.mo1_bragg.high_lim.get() + if emin < low_limit or emax > high_limit: + raise ValueError( + f"Chosen element/edge {element}/{edge} with edge energy of {energy}" + + " is outside of accessible range of monochromator " + + f"{low_limit:.1f} eV - {high_limit:.1f} eV" + ) + # X10DA energy axis (goniometer) does not have lo/hi limits # Map amplifier names to their NIDAQ channels channel_map = { @@ -174,30 +188,38 @@ class AutoGainCore: } active_channels = {name: ch for name, ch in channel_map.items() if name in amplifier} - # Check if amplifieres are switched on - for name, ch in active_channels.items(): - if ch["self.dev"].amp.cOnOff.get() != AmplifierEnable.ON: - raise AutoGainError(f"Amplifier of self.device {name} is not enabled") + # Tests only for X01DA: + if self.beamline == BeamlineId.X01DA: + # Check if amplifieres are switched on (only X01DA) + for name, ch in active_channels.items(): + if ch["self.dev"].amp.cOnOff.get() != AmplifierEnable.ON: + raise AutoGainError(f"Amplifier of self.device {name} is not enabled") - # Check high voltage on ionization chambers - for name, ch in active_channels.items(): - if name != "pips": - if ch["self.dev"].hv_en.ena.get() != 1: - raise AutoGainError(f"High voltage of ionization chamber {name} is not enabled") - if ch["self.dev"].hv.hv_v.get() < 1000: - raise AutoGainError(f"HV voltage of ionization chamber {name} is < 1000") - if ch["self.dev"].hv.grid_v.get() < 1000: - raise AutoGainError(f"Grid voltage of ionization chamber {name} is < 1000") + # Check high voltage on ionization chambers (only X01DA) + for name, ch in active_channels.items(): + if name != "pips": + if ch["self.dev"].hv_en.ena.get() != 1: + raise AutoGainError( + f"High voltage of ionization chamber {name} is not enabled" + ) + if ch["self.dev"].hv.hv_v.get() < 1000: + raise AutoGainError(f"HV voltage of ionization chamber {name} is < 1000") + if ch["self.dev"].hv.grid_v.get() < 1000: + raise AutoGainError(f"Grid voltage of ionization chamber {name} is < 1000") - # Check gas filling of ionization chambers - for name, ch in active_channels.items(): - if name != "pips": - if ch["self.dev"].gmes.status.get() != 1: - raise AutoGainError(f"Gas filling of ionization chamber {name} is not OK") + # Check gas filling of ionization chambers (only X01DA) + for name, ch in active_channels.items(): + if name != "pips": + if ch["self.dev"].gmes.status.get() != 1: + raise AutoGainError(f"Gas filling of ionization chamber {name} is not OK") # Get initial monochromator position and velocity - init_pos = self.dev.mo1_bragg.position - init_vel = self.dev.mo1_bragg.velocity.get() + if self.beamline == BeamlineId.X01DA: + init_pos = self.dev.mo1_bragg.position + init_vel = self.dev.mo1_bragg.velocity.get() + else: + init_pos = self.dev.mo1_rotx_energy.get() + init_vel = None # Get initial gains for name, ch in active_channels.items(): @@ -209,9 +231,12 @@ class AutoGainCore: try: logger.info(f"Move mono to start of {emin} eV") - self.dev.mo1_bragg.velocity.put(MONO_VELOCITY) - wait_for_signal(self.dev.mo1_bragg.velocity, MONO_VELOCITY, timeout=TIMEOUT_PUT_PV) - status = self.dev.mo1_bragg.move(emin) + if self.beamline == BeamlineId.X01DA: + self.dev.mo1_bragg.velocity.put(MONO_VELOCITY) + wait_for_signal(self.dev.mo1_bragg.velocity, MONO_VELOCITY, timeout=TIMEOUT_PUT_PV) + status = self.dev.mo1_bragg.move(emin) + else: + status = self.dev.mo1_rotx_energy.move(emin) status.wait(TIMEOUT_MONO_MOVE) # Set NIDAQ to max mode @@ -220,7 +245,7 @@ class AutoGainCore: # Set gains to lowest gain for name, ch in active_channels.items(): - lowest_gain = self.available_gains(name)[0] + lowest_gain = self.allowed_gains(name)[0] ch["self.dev"].set_gain(lowest_gain) ch["gain"] = lowest_gain @@ -245,8 +270,10 @@ class AutoGainCore: ) # Scan range, recording the peak NIDAQ signal per channel - self.dev.mo1_bragg.move(emax).wait(timeout=TIMEOUT_MONO_MOVE) - status.wait(TIMEOUT_MONO_MOVE) + if self.beamline == BeamlineId.X01DA: + self.dev.mo1_bragg.move(emax).wait(timeout=TIMEOUT_MONO_MOVE) + else: + self.dev.mo1_rotx_energy.move(emax).wait(timeout=TIMEOUT_MONO_MOVE) for name, ch in active_channels.items(): data[name] = max(data[name], ch["signal"].get()) @@ -260,7 +287,10 @@ class AutoGainCore: ring_current = (ring_current_1 + ring_current_2) / 2 # Move back to first monochromator position - status = self.dev.mo1_bragg.move(emin) + if self.beamline == BeamlineId.X01DA: + status = self.dev.mo1_bragg.move(emin) + else: + status = self.dev.mo1_rotx_energy.move(emin) # Choose gain per channel based on the max signal recorded during the scan remeasure = False @@ -297,14 +327,14 @@ class AutoGainCore: if raw_signal_min < MIN_SIGNAL: logger.info(f"Raw signal for {label} is below {MIN_SIGNAL}") - if gain_ref == self.available_gains(name)[-1]: + if gain_ref == self.allowed_gains(name)[-1]: logger.warning( f"Amplifier of {label} at highest gain {gain_ref} and still not" + f" measured signal above {MIN_SIGNAL}" ) else: - next_gain = self.available_gains(name)[ - bisect_right(self.available_gains(name), gain_ref * 100) - 1 + next_gain = self.allowed_gains(name)[ + bisect_right(self.allowed_gains(name), gain_ref * 100) - 1 ] for gname in group_names: active_channels[gname]["self.dev"].set_gain(next_gain) @@ -316,10 +346,10 @@ class AutoGainCore: gain = max( ( g - for g in self.available_gains(name) + for g in self.allowed_gains(name) if raw_signal_max / gain_ref * g <= FULL_SCALE_V * SAFETY_MARGIN ), - default=min(self.available_gains(name)), + default=min(self.allowed_gains(name)), ) for gname in group_names: active_channels[gname]["self.dev"].set_gain(gain) @@ -345,10 +375,14 @@ class AutoGainCore: wait_for_signal(self.dev.nidaq.epics_mode, EpicsMode.MEAN, timeout=TIMEOUT_PUT_PV) # Wait for mono to move to initial position and reset velocity - status = self.dev.mo1_bragg.move(init_pos) - status.wait(TIMEOUT_MONO_MOVE) - self.dev.mo1_bragg.velocity.put(init_vel) - wait_for_signal(self.dev.mo1_bragg.velocity, init_vel, timeout=TIMEOUT_PUT_PV) + if self.beamline == BeamlineId.X01DA: + status = self.dev.mo1_bragg.move(init_pos) + status.wait(TIMEOUT_MONO_MOVE) + self.dev.mo1_bragg.velocity.put(init_vel) + wait_for_signal(self.dev.mo1_bragg.velocity, init_vel, timeout=TIMEOUT_PUT_PV) + else: + status = self.dev.mo1_rotx_energy.move(init_pos) + status.wait(TIMEOUT_MONO_MOVE) return results diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/beamline.py b/debye_bec/bec_ipython_client/plugins/beamline.py similarity index 79% rename from debye_bec/bec_ipython_client/plugins/digital_twin_core/beamline.py rename to debye_bec/bec_ipython_client/plugins/beamline.py index 3653284..9604799 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/beamline.py +++ b/debye_bec/bec_ipython_client/plugins/beamline.py @@ -1,12 +1,20 @@ import socket +from enum import Enum from bec_lib import bec_logger -from .types import BeamlineId - logger = bec_logger.logger +class BeamlineId(str, Enum): + """ + Identifier for supported beamlines. + """ + + X01DA = "x01da" + X10DA = "x10da" + + def get_beamline_id() -> BeamlineId: """ Based on the bec servers hostname, tries to extract the beamline @@ -38,14 +46,3 @@ def get_beamline_id() -> BeamlineId: raise ValueError(f"Wrong selection {bl}") else: raise ValueError("Cannot open digital twin without a beamline") - - -def get_parameters(): - beamline = get_beamline_id() - if beamline == "x01da": - from . import x01da_parameters as parameters - elif beamline == "x10da": - from . import x10da_parameters as parameters - else: - raise ValueError(f"Unknown beamline: {beamline}") - return parameters diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/__init__.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/__init__.py index a42cb09..b5d8096 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/__init__.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/__init__.py @@ -1,3 +1,3 @@ -from .beamline import get_parameters +from .digital_twin_core import get_parameters parameters = get_parameters() diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py index 31f53fe..9390cb5 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py @@ -10,8 +10,8 @@ from bec_lib import bec_logger from scipy.interpolate import UnivariateSpline from xrt.backends.raycing.physconsts import AVOGADRO, CHeVcm +from ..beamline import get_beamline_id from . import parameters as bl -from .beamline import get_beamline_id from .motion_worker import MotionOutcome, MotionWorker from .types import BeamlineId, ConfigDict, DataDict, SurfaceDict @@ -26,6 +26,17 @@ OFFSET_FILE_X10DA = Path(__file__).with_name("x10da_offsets.yaml") logger = bec_logger.logger +def get_parameters(): + beamline = get_beamline_id() + if beamline == "x01da": + from . import x01da_parameters as parameters + elif beamline == "x10da": + from . import x10da_parameters as parameters + else: + raise ValueError(f"Unknown beamline: {beamline}") + return parameters + + class _ExclusiveGroupManager: def __init__(self): self._cond = threading.Condition() diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py index 8eef9f3..7af312a 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py @@ -8,7 +8,7 @@ from bec_lib import bec_logger # pylint: disable=E0402 from ....devices.absorber import STATUS as ABS_STATUS -from .types import BeamlineId +from ..beamline import BeamlineId logger = bec_logger.logger diff --git a/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.py b/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.py index 97dd964..194d02d 100644 --- a/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.py +++ b/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.py @@ -5,17 +5,17 @@ Auto Gain: Custom BEC widget to automatically set gains. import sys from bec_lib import bec_logger -from bec_lib.logger import bec_logger from bec_widgets.utils.bec_dispatcher import BECDispatcher from bec_widgets.utils.bec_widget import BECWidget from bec_widgets.utils.colors import apply_theme, get_accent_colors from bec_widgets.utils.error_popups import SafeSlot -from qtpy.QtCore import QObject, QThread, Signal # pylint: disable=E0611 +from qtpy.QtCore import QObject, QThread, Signal from qtpy.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget from ....bec_ipython_client.plugins.auto_gain_core import AutoGainCore +from ....bec_ipython_client.plugins.beamline import BeamlineId, get_beamline_id from ..edge_selector import EdgeSelector from .qt_widgets import CheckBox, Group, MatrixSelector, MyButton, TextIndicator @@ -67,6 +67,8 @@ class AutoGain(BECWidget, QWidget): super().__init__(parent=parent, *arg, **kwargs) self.get_bec_shortcuts() + self.beamline = get_beamline_id() + central = QWidget() self.root_layout = QVBoxLayout(central) @@ -85,16 +87,22 @@ class AutoGain(BECWidget, QWidget): self.ic1_check = CheckBox("ic1", "IC1") self.ic2_check = CheckBox("ic2", "IC2") self.pips_check = CheckBox("pips", "PIPS") - self.apply_group = Group( - "Apply auto gain on", [self.ic0_check, self.ic1_check, self.ic2_check, self.pips_check] - ) + if self.beamline == BeamlineId.X01DA: + self.apply_group = Group( + "Apply auto gain on", + [self.ic0_check, self.ic1_check, self.ic2_check, self.pips_check], + ) + else: # PIPS of X10DA has fixed gain amplifier + self.apply_group = Group( + "Apply auto gain on", [self.ic0_check, self.ic1_check, self.ic2_check] + ) self.root_layout.addWidget(self.apply_group) self.link_ic0_ic1 = CheckBox("link_ic0_ic1", "Link IC0/IC1 gains") self.comp_ring_current = CheckBox("comp_ring_current", "Calculate for 400 mA ring current") - self.prohibited_gains = MatrixSelector("Prohibited gains") + self.prohibited_gains = MatrixSelector("Prohibited gains", beamline=self.beamline) self.expert_group = Group( "Expert settings", [self.link_ic0_ic1, self.comp_ring_current, self.prohibited_gains] diff --git a/debye_bec/bec_widgets/widgets/auto_gain/qt_widgets.py b/debye_bec/bec_widgets/widgets/auto_gain/qt_widgets.py index 3052869..54f0ed8 100644 --- a/debye_bec/bec_widgets/widgets/auto_gain/qt_widgets.py +++ b/debye_bec/bec_widgets/widgets/auto_gain/qt_widgets.py @@ -14,6 +14,8 @@ from qtpy.QtWidgets import ( QWidget, ) +from ....bec_ipython_client.plugins.beamline import BeamlineId + LABEL_WIDTH = 118 ROW_MARGINS = (4, 0, 4, 0) ROW_SPACING = 6 @@ -83,11 +85,21 @@ class MatrixSelector(QWidget): {'ic0': [1000000.0], 'ic1': [1000000.0, 50000000.0]} """ - ROWS = ["IC0", "IC1", "IC2", "PIPS"] - COLS = ["1e6", "1e7", "5e7", "1e8", "1e9"] + ROWS_X01DA = ["IC0", "IC1", "IC2", "PIPS"] + COLS_X01DA = ["1e6", "1e7", "5e7", "1e8", "1e9"] - def __init__(self, label: str = "", parent=None): + ROWS_X10DA = ["IC0", "IC1", "IC2"] + COLS_X10DA = ["1e6", "1e7", "1e8", "1e9", "1e10"] + + def __init__(self, label: str, beamline: BeamlineId, parent=None): super().__init__(parent) + if beamline == BeamlineId.X01DA: + self.cols = self.COLS_X01DA + self.rows = self.ROWS_X01DA + else: + self.cols = self.COLS_X10DA + self.rows = self.ROWS_X10DA + layout = QHBoxLayout(self) layout.setContentsMargins(*ROW_MARGINS) layout.setSpacing(ROW_SPACING) @@ -99,14 +111,14 @@ class MatrixSelector(QWidget): grid_layout = QGridLayout() # Column headers - for c, col in enumerate(self.COLS, start=1): + for c, col in enumerate(self.cols, start=1): grid_layout.addWidget(QLabel(col), 0, c, alignment=Qt.AlignmentFlag.AlignCenter) # Row headers + checkboxes self.checks = {} - for r, row in enumerate(self.ROWS, start=1): + for r, row in enumerate(self.rows, start=1): grid_layout.addWidget(QLabel(row), r, 0) - for c, col in enumerate(self.COLS, start=1): + for c, col in enumerate(self.cols, start=1): cb = QCheckBox() grid_layout.addWidget(cb, r, c, alignment=Qt.AlignmentFlag.AlignCenter) self.checks[(row, col)] = cb @@ -117,8 +129,8 @@ class MatrixSelector(QWidget): def selection(self): """Return e.g. {"ic0": [1e6], "ic1": [1e6, 5e7]}; rows with no selection are omitted.""" result = {} - for row in self.ROWS: - values = [float(col) for col in self.COLS if self.checks[(row, col)].isChecked()] + for row in self.rows: + values = [float(col) for col in self.cols if self.checks[(row, col)].isChecked()] if values: result[row.lower()] = values return result @@ -131,9 +143,9 @@ class MatrixSelector(QWidget): """ # Normalize keys to lowercase and values to floats for comparison wanted = {key.lower(): {float(v) for v in values} for key, values in selection.items()} - for row in self.ROWS: + for row in self.rows: row_values = wanted.get(row.lower(), set()) - for col in self.COLS: + for col in self.cols: cb = self.checks[(row, col)] cb.setChecked(float(col) in row_values) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py b/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py index 4599a54..86cfc51 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py @@ -7,7 +7,7 @@ from typing import Union # pylint: disable=E0611 from qtpy.QtWidgets import QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget -from .....bec_ipython_client.plugins.digital_twin_core.types import BeamlineId +from .....bec_ipython_client.plugins.beamline import BeamlineId from ..widgets.qt_widgets import ( Button, ComboBox, diff --git a/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py b/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py index 0a0696d..d4a6dd8 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py @@ -7,7 +7,7 @@ from typing import Literal # pylint: disable=E0611 from qtpy.QtWidgets import QVBoxLayout, QWidget -from .....bec_ipython_client.plugins.digital_twin_core.types import BeamlineId +from .....bec_ipython_client.plugins.beamline import BeamlineId from ..widgets.move_widget import AbsorberWidget, MoveWidget from ..widgets.qt_widgets import Button, Group, QLabel diff --git a/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py b/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py index c53e397..a7f6354 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py @@ -18,7 +18,6 @@ from .....bec_ipython_client.plugins.digital_twin_core.motion_worker import ( MotionOutcome, MotionWorker, ) -from .....bec_ipython_client.plugins.digital_twin_core.types import BeamlineId logger = bec_logger.logger From c142dedaaf3222f68075e22334bbe34c4dc9371a Mon Sep 17 00:00:00 2001 From: hitz_s Date: Thu, 22 Oct 2026 15:21:54 +0200 Subject: [PATCH 47/56] feat(univ_temp_cont): Introduction of Universal Temperature Controller --- .../temperature_controller/__init__.py | 0 .../temperature_controller/qt_widgets.py | 249 ++++++++++++++++++ .../register_temperature_controller.py | 15 ++ .../temperature_controller.py | 248 +++++++++++++++++ .../temperature_controller.pyproject | 1 + .../temperature_controller_plugin.py | 57 ++++ .../x01da_mobile_equipment.yaml | 14 + .../devices/univ_temp_cont/univ_temp_cont.py | 86 ++++++ .../univ_temp_cont/univ_temp_cont_enums.py | 83 ++++++ 9 files changed, 753 insertions(+) create mode 100644 debye_bec/bec_widgets/widgets/temperature_controller/__init__.py create mode 100644 debye_bec/bec_widgets/widgets/temperature_controller/qt_widgets.py create mode 100644 debye_bec/bec_widgets/widgets/temperature_controller/register_temperature_controller.py create mode 100644 debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py create mode 100644 debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.pyproject create mode 100644 debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller_plugin.py create mode 100644 debye_bec/device_configs/x01da_mobile_equipment.yaml create mode 100644 debye_bec/devices/univ_temp_cont/univ_temp_cont.py create mode 100644 debye_bec/devices/univ_temp_cont/univ_temp_cont_enums.py diff --git a/debye_bec/bec_widgets/widgets/temperature_controller/__init__.py b/debye_bec/bec_widgets/widgets/temperature_controller/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/debye_bec/bec_widgets/widgets/temperature_controller/qt_widgets.py b/debye_bec/bec_widgets/widgets/temperature_controller/qt_widgets.py new file mode 100644 index 0000000..d40015b --- /dev/null +++ b/debye_bec/bec_widgets/widgets/temperature_controller/qt_widgets.py @@ -0,0 +1,249 @@ +""" +Universal Qt widgets +""" + +from functools import partial + +from bec_widgets.utils.colors import get_accent_colors +from qtpy.QtCore import Qt + +# pylint: disable=E0611 +from qtpy.QtGui import QFont +from qtpy.QtWidgets import ( + QApplication, + QComboBox, + QDoubleSpinBox, + QGroupBox, + QHBoxLayout, + QLabel, + QPushButton, + QVBoxLayout, + QWidget, +) + +LABEL_WIDTH = 118 +ROW_MARGINS = (4, 0, 4, 0) +ROW_SPACING = 6 + + +class Group(QGroupBox): + def __init__(self, label, widgets): + super().__init__(label) + self.layout = QVBoxLayout(self) # type: ignore + self.layout.setContentsMargins(6, 6, 6, 6) + self.layout.setSpacing(4) + for widget in widgets: + self.layout.addWidget(widget) # type: ignore + + +class NumberIndicator(QWidget): + def __init__(self, label="", unit=None, highlight=False, decimals=3): + super().__init__() + layout = QHBoxLayout(self) + layout.setContentsMargins(*ROW_MARGINS) + layout.setSpacing(ROW_SPACING) + self.label = QLabel(label) + self.label.setFixedWidth(LABEL_WIDTH) + self.label.setWordWrap(True) + layout.addWidget(self.label) + self.val = QLabel("-") + self.val.setAlignment(Qt.AlignTop) # type: ignore + layout.addWidget(self.val) + self.unit = unit + self.highlight = highlight + self.decimals = decimals + self.number = 0 + if highlight: + font = QFont() + font.setBold(True) + font.setPointSize(14) + self.label.setFont(font) + self.val.setFont(font) + + def value(self) -> float: + return self.number + + def setLabel(self, label) -> None: + self.label.setText(label) + + def setValue(self, number): + self.number = number + text = f"{number:.{int(self.decimals)}f}" + if self.unit is not None: + text = text + " " + self.unit + self.val.setText(text) + + +class InputNumberField(QWidget): + def __init__( + self, + identifier="", + label="", + unit=None, + prefix=None, + init=0.0, + decimals=1, + single_step=0.1, + ll=-1e6, + hl=1e6, + ): + super().__init__() + layout = QHBoxLayout(self) + layout.setContentsMargins(*ROW_MARGINS) + layout.setSpacing(ROW_SPACING) + self.identifier = identifier + self.label = QLabel(label) + self.label.setFixedWidth(LABEL_WIDTH) + self.label.setWordWrap(True) + layout.addWidget(self.label) + self.val = QDoubleSpinBox() + self.val.setRange(ll, hl) + self.val.setDecimals(decimals) + self.val.setSingleStep(single_step) + self.val.setValue(init) + if unit is not None: + self.val.setSuffix(" " + unit) + if prefix is not None: + self.val.setPrefix(prefix + " ") + layout.addWidget(self.val) + self.ll = ll + self.hl = hl + + def set_number(self, number): + self.val.setValue(number) + + def set_range(self, ll, hl): + self.val.setRange(ll, hl) + self.ll = ll + self.hl = hl + + def setUnit(self, unit: str): + self.val.setSuffix(" " + unit) + + def get_range(self): + return (self.ll, self.hl) + + def has_focus(self) -> bool: + return self.val.hasFocus() + + def value(self) -> float: + return self.val.value() + + def value_changed_connect(self, func): + """Connect a function to the Enter/Return key press.""" + self.val.valueChanged.connect( + partial( + func, identifier=self.identifier, value_obj=self.val, value=lambda: self.val.value() + ) + ) + + +class ComboBox(QWidget): + def __init__(self, identifier="", label="", enums=None): + super().__init__() + layout = QHBoxLayout(self) + layout.setContentsMargins(*ROW_MARGINS) + layout.setSpacing(ROW_SPACING) + self.identifier = identifier + self.label = QLabel(label) + self.label.setFixedWidth(LABEL_WIDTH) + self.label.setWordWrap(True) + layout.addWidget(self.label) + self.value = QComboBox() + for entry in enums or []: + self.value.addItem(entry) + layout.addWidget(self.value) + + def set_current_text(self, text): + self.value.setCurrentText(text) + + def currentText(self) -> str: + return self.value.currentText() + + def has_focus(self) -> bool: + return QApplication.focusWidget() is self.value.view() + + def activated_connect(self, func): + """Connect a function to the Enter/Return key press.""" + self.value.activated.connect( + partial( + func, + identifier=self.identifier, + value_obj=self.value, + value=lambda: self.value.currentText(), + index=lambda: self.value.currentIndex(), + ) + ) + + def setDisabled(self, disable): + self.value.setDisabled(disable) + + def get_all_texts(self) -> list[str]: + return [self.value.itemText(i) for i in range(self.value.count())] + + +class Button(QWidget): + def __init__( + self, label=None, label_button: str = "", enabled: bool = False, color: str = "default" + ): + super().__init__() + layout = QHBoxLayout(self) + layout.setContentsMargins(*ROW_MARGINS) + layout.setSpacing(ROW_SPACING) + if label is not None: + self.label = QLabel(label) + self.label.setFixedWidth(LABEL_WIDTH) + layout.addWidget(self.label) + self.button = QPushButton(label_button) + self.setEnabled(enabled) + layout.addWidget(self.button) + self.color = color + + def clicked_connect(self, func): + """Connect a function to the button press.""" + self.button.clicked.connect(func) + + def setEnabled(self, enable: bool = True): + self.button.setEnabled(enable) + self.apply_theme() + + def setText(self, text): + self.button.setText(text) + + def setColor(self, color: str): + self.color = color + self.apply_theme() + + def apply_theme(self): + if self.button.isEnabled(): + colors = get_accent_colors() + color = getattr(colors, self.color).name() + self.button.setStyleSheet(f"QPushButton {{ background-color: {color}; color: white; }}") + else: + self.button.setStyleSheet( + "QPushButton {{background-color: rgb(120, 120, 120); color: white;}}" + ) + + +class TextIndicator(QWidget): + def __init__(self, label): + super().__init__() + layout = QHBoxLayout(self) + layout.setContentsMargins(*ROW_MARGINS) + layout.setSpacing(ROW_SPACING) + self.label = QLabel(label) + self.label.setFixedWidth(LABEL_WIDTH) + self.label.setWordWrap(True) + layout.addWidget(self.label) + self.text = QLabel("-") + self.text.setAlignment(Qt.AlignTop) # type: ignore + layout.addWidget(self.text) + + def setLabel(self, label) -> None: + self.label.setText(label) + + def setText(self, text): + self.text.setText(text) + + def setColor(self, color: str): + self.text.setStyleSheet(f"QLabel {{color:{color}}}") diff --git a/debye_bec/bec_widgets/widgets/temperature_controller/register_temperature_controller.py b/debye_bec/bec_widgets/widgets/temperature_controller/register_temperature_controller.py new file mode 100644 index 0000000..8e61271 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/temperature_controller/register_temperature_controller.py @@ -0,0 +1,15 @@ +def main(): # pragma: no cover + from qtpy import PYSIDE6 + + if not PYSIDE6: + print("PYSIDE6 is not available in the environment. Cannot patch designer.") + return + from PySide6.QtDesigner import QPyDesignerCustomWidgetCollection + + from .temperature_controller_plugin import TemperatureControllerPlugin + + QPyDesignerCustomWidgetCollection.addCustomWidget(TemperatureControllerPlugin()) + + +if __name__ == "__main__": # pragma: no cover + main() diff --git a/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py b/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py new file mode 100644 index 0000000..03e1eac --- /dev/null +++ b/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py @@ -0,0 +1,248 @@ +"""Temperature controller widget""" + +from __future__ import annotations + +import sys +import time +from collections import deque + +import numpy as np +from bec_lib import bec_logger +from bec_lib.endpoints import MessageEndpoints +from bec_widgets.utils.bec_dispatcher import BECDispatcher +from bec_widgets.utils.bec_widget import BECWidget +from bec_widgets.utils.colors import apply_theme, get_accent_colors +from bec_widgets.utils.error_popups import SafeSlot +from bec_widgets.widgets.plots.waveform.waveform import Waveform + +# pylint: disable=E0611 +from qtpy.QtCore import QTimer +from qtpy.QtWidgets import QApplication, QHBoxLayout, QVBoxLayout, QWidget + +from ....devices.univ_temp_cont.univ_temp_cont_enums import ( + RAMP_RATE_MAP, + UnivTempContHeaterTcFault, + UnivTempContOpMode, + UnivTempContPower, + UnivTempContRampRateUnit, + UnivTempContSensorBreak, +) +from .qt_widgets import ComboBox, Group, InputNumberField, NumberIndicator, TextIndicator + +logger = bec_logger.logger + +DEFAULT_WINDOW_S = 600 +REFRESH_MS = 200 +PLOT_SIGNALS = ["temperature", "setpoint", "output_power"] +READ_CONFIG_SIGNAL_MS = 1000 + + +class TemperatureControllerError(Exception): + """Temperature Controller specific error""" + + +class TemperatureController(BECWidget, QWidget): + """Waveform with predefined curves and one status label.""" + + PLUGIN = True + ICON_NAME = "mode_heat" + + def __init__(self, *arg, parent=None, **kwargs): + super().__init__(parent=parent, *arg, **kwargs) + self.get_bec_shortcuts() + + if "univ_temp_cont" not in self.dev: + raise TemperatureControllerError( + "Universal Temperature Controller is not in the config, abort." + ) + + self._window_s = DEFAULT_WINDOW_S + + root_layout = QHBoxLayout(self) + + control_layout = QVBoxLayout() + control_layout.setContentsMargins(4, 4, 4, 4) + control_layout.setSpacing(4) + + self.sensor_break = TextIndicator("Thermocouple") + self.operating_mode = TextIndicator("Operating mode") + self.output_power = NumberIndicator("Output Power", "%", decimals=0) + self.temperature = NumberIndicator("Temperature", "°C", decimals=0) + self.heater_temperature = NumberIndicator("Heater temperature", "°C", decimals=0) + self.heater_sensor_break = TextIndicator("Heater Thermocouple") + + status_group = Group( + "Status", + [ + self.sensor_break, + self.operating_mode, + self.output_power, + self.temperature, + self.heater_temperature, + self.heater_sensor_break, + ], + ) + + self.power_mode = ComboBox("power_mode", "Power mode", UnivTempContPower) + self.target_setpoint = InputNumberField( + "target_setpoint", "Target setpoint", "°C", decimals=0, single_step=1, ll=0, hl=850 + ) + self.setpoint = NumberIndicator("Setpoint", "°C", highlight=True, decimals=0) + self.ramp_rate = InputNumberField( + "ramp-rate", "Ramp rate", decimals=0, single_step=1, ll=0, hl=1e5 + ) + self.ramp_rate_unit = ComboBox("ramp_rate_unit", "Ramp rate unit", UnivTempContRampRateUnit) + + control_group = Group( + "Control", + [ + self.power_mode, + self.target_setpoint, + self.setpoint, + self.ramp_rate, + self.ramp_rate_unit, + ], + ) + + control_layout.addWidget(status_group) + control_layout.addWidget(control_group) + + root_layout.addLayout(control_layout) + + self.waveform = Waveform(parent=self, client=self.client, popups=False) + root_layout.addWidget(self.waveform, stretch=1) + + self.waveform.set(title="Title", x_label="X-Label") + + self._buffers: dict[str, deque] = {} + self._curves = {} + for signal in PLOT_SIGNALS: + self._buffers[signal] = deque() # (timestamp, value), trimmed by time + self._curves[signal] = self.waveform.plot( + x=[], y=[], label=self.dev.univ_temp_cont.signal.full_name + ) + + self.bec_dispatcher.connect_slot( + self._on_readback, MessageEndpoints.device_readback(self.dev.univ_temp_cont) + ) + self._refresh_timer = QTimer(self) + self._refresh_timer.timeout.connect(self._redraw) + self._refresh_timer.start(REFRESH_MS) + + self._config_signal_timer = QTimer(self) + self._config_signal_timer.timeout.connect(self._config_signal_read) + self._config_signal_timer.start(READ_CONFIG_SIGNAL_MS) + + self.power_mode.activated_connect(self._on_value_changed) + self.target_setpoint.value_changed_connect(self._on_value_changed) + self.ramp_rate.value_changed_connect(self._on_value_changed) + self.ramp_rate_unit.activated_connect(self._on_value_changed) + + @SafeSlot() + def _on_value_changed(self, identifier, _, value, **kwargs): + logger.info(f"Got identifier {identifier} with value {value} and kwargs {kwargs}") + if "index" in kwargs.keys(): + value = kwargs["index"] + self.dev.univ_temp_cont[identifier].put(value) + + @SafeSlot(dict, dict) + def _on_readback(self, msg: dict, *_): + signals = msg.get("signals", {}) + for signal, buf in self._buffers.items(): + entry = signals.get(signal) + if entry is None or entry.get("value") is None: + continue + buf.append((entry["timestamp"], entry["value"])) + value = signals["temperature"]["value"] + self.temperature.setValue(value) + value = signals["heater_temperature"]["value"] + self.heater_temperature.setValue(value) + value = signals["output_power"]["value"] + self.output_power.setValue(value) + value = signals["sensor_break"]["value"] + match value: + case UnivTempContSensorBreak.GOOD: + self.sensor_break.setText("OK") + self.sensor_break.setColor(get_accent_colors().success.name()) + case UnivTempContSensorBreak.SENSOR_BREAK: + self.sensor_break.setText("FAULT") + self.sensor_break.setColor(get_accent_colors().emergency.name()) + case _: + raise TemperatureControllerError(f"Not implemented sensor_break value {value}") + value = signals["heater_tc_fault"]["value"] + match value: + case UnivTempContHeaterTcFault.NO_FAULT: + self.heater_sensor_break.setText("OK") + self.heater_sensor_break.setColor(get_accent_colors().success.name()) + case UnivTempContHeaterTcFault.TC_OPEN_FAULT: + self.heater_sensor_break.setText("OPEN") + self.heater_sensor_break.setColor(get_accent_colors().warning.name()) + case ( + UnivTempContHeaterTcFault.OVER_UNDERVOLTAGE_FAULT + | UnivTempContHeaterTcFault.TC_LOW_FAULT + | UnivTempContHeaterTcFault.TC_HIGH_FAULT + | UnivTempContHeaterTcFault.COLD_JUNC_LOW_FAULT + | UnivTempContHeaterTcFault.COLD_JUNC_HIGH_FAULT + | UnivTempContHeaterTcFault.TC_RANGE_FAULT + | UnivTempContHeaterTcFault.COLD_JUNC_RNG_FAULT + ): + self.heater_sensor_break.setText("FAULT") + self.heater_sensor_break.setColor(get_accent_colors().emergency.name()) + case _: + raise TemperatureControllerError( + f"Not implemented heater_sensor_break value {value}" + ) + value = signals["op_mode"]["value"] + match value: + case UnivTempContOpMode.AUTO: + self.operating_mode.setText("AUTO") + self.operating_mode.setColor(get_accent_colors().success.name()) + case UnivTempContOpMode.MANUAL: + self.operating_mode.setText("MANUAL") + self.operating_mode.setColor(get_accent_colors().warning.name()) + case UnivTempContOpMode.STANDBY: + self.operating_mode.setText("STANDBY") + self.operating_mode.setColor(get_accent_colors().default.name()) + case _: + raise TemperatureControllerError(f"Not implemented op_mode value {value}") + value = signals["power"]["value"] + self.power_mode.set_current_text(value) + value = signals["target_setpoint"]["value"] + self.target_setpoint.set_number(value) + value = signals["setpoint"]["value"] + self.setpoint.setValue(value) + value = signals["ramp_rate"]["value"] + self.ramp_rate.set_number(value) + + def _config_signal_read(self): + value = self.dev.univ_temp_cont.ramp_rate_unit.read() + if value is None: + raise TemperatureControllerError("Reading ramp rate unit returned None!") + self.ramp_rate_unit.set_current_text(value) + self.ramp_rate.setUnit( + list(RAMP_RATE_MAP.keys())[list(RAMP_RATE_MAP.values()).index(value)] + ) + + def _redraw(self): + now = time.time() + cutoff = now - self._window_s + for key, buf in self._buffers.items(): + while buf and buf[0][0] < cutoff: + buf.popleft() + if not buf: + continue + t, v = zip(*buf) + self._curves[key].set_data(np.asarray(t) - now, np.asarray(v)) + + def cleanup(self): + self._refresh_timer.stop() + super().cleanup() + + +if __name__ == "__main__": + app = QApplication(sys.argv) + apply_theme("light") + dispatcher = BECDispatcher(gui_id="restart_server") + win = TemperatureController() + win.show() + sys.exit(app.exec_()) diff --git a/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.pyproject b/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.pyproject new file mode 100644 index 0000000..f4bc552 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.pyproject @@ -0,0 +1 @@ +{'files': ['temperature_controller.py']} \ No newline at end of file diff --git a/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller_plugin.py b/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller_plugin.py new file mode 100644 index 0000000..d56b14b --- /dev/null +++ b/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller_plugin.py @@ -0,0 +1,57 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +from bec_widgets.utils.bec_designer import designer_material_icon +from qtpy.QtDesigner import QDesignerCustomWidgetInterface +from qtpy.QtWidgets import QWidget + +from .temperature_controller import TemperatureController + +DOM_XML = """ + + + + +""" + + +class TemperatureControllerPlugin(QDesignerCustomWidgetInterface): # pragma: no cover + def __init__(self): + super().__init__() + self._form_editor = None + + def createWidget(self, parent): + if parent is None: + return QWidget() + t = TemperatureController(parent) + return t + + def domXml(self): + return DOM_XML + + def group(self): + return "" + + def icon(self): + return designer_material_icon(TemperatureController.ICON_NAME) + + def includeFile(self): + return "temperature_controller" + + def initialize(self, form_editor): + self._form_editor = form_editor + + def isContainer(self): + return False + + def isInitialized(self): + return self._form_editor is not None + + def name(self): + return "TemperatureController" + + def toolTip(self): + return "TemperatureController" + + def whatsThis(self): + return self.toolTip() diff --git a/debye_bec/device_configs/x01da_mobile_equipment.yaml b/debye_bec/device_configs/x01da_mobile_equipment.yaml new file mode 100644 index 0000000..5e1458a --- /dev/null +++ b/debye_bec/device_configs/x01da_mobile_equipment.yaml @@ -0,0 +1,14 @@ +###################################### +## Universal Temperature Controller ## +###################################### + +univ_temp_cont: + readoutPriority: monitored + description: Universal Temperature Controller + deviceClass: debye_bec.devices.univ_temp_cont.univ_temp_cont.UnivTempCont + deviceConfig: + auto_monitor: true + prefix: "X01DA-ES-CRS:" + onFailure: retry + enabled: true + softwareTrigger: false \ No newline at end of file diff --git a/debye_bec/devices/univ_temp_cont/univ_temp_cont.py b/debye_bec/devices/univ_temp_cont/univ_temp_cont.py new file mode 100644 index 0000000..0f8da55 --- /dev/null +++ b/debye_bec/devices/univ_temp_cont/univ_temp_cont.py @@ -0,0 +1,86 @@ +"""Universal Temperature Controller""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ophyd import Component as Cpt +from ophyd import EpicsSignal, EpicsSignalRO +from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase +from univ_temp_cont_enums import ( + UnivTempContAutoTune, + UnivTempContConnection, + UnivTempContHeaterTcFault, + UnivTempContOpMode, + UnivTempContPower, + UnivTempContRampRateUnit, + UnivTempContSensorBreak, + UnivTempContSetpointSelect, + UnivTempContThermocouple, +) + +if TYPE_CHECKING: + from bec_lib.devicemanager import ScanInfo + +TIMEOUT_FOR_PV = 5 + + +class UnivTempCont(PSIDeviceBase): + """Class for the Universal Temperature Controller""" + + temperature = Cpt(EpicsSignalRO, suffix="TEMPERATURE", kind="normal", doc="Temperature") + timestamp = Cpt(EpicsSignalRO, suffix="TIMESTAMP", kind="omitted", doc="Current timestamp") + setpoint = Cpt(EpicsSignalRO, suffix="SETPOINT", kind="normal", doc="Setpoint on Controller") + target_setpoint = Cpt( + EpicsSignal, suffix="TARGET-SETPOINT", kind="normal", doc="Target Setpoint" + ) + output_power = Cpt(EpicsSignalRO, suffix="OUTPUT-POWER", kind="normal", doc="Output Power %") + ramp_rate = Cpt(EpicsSignal, suffix="RAMP-RATE", kind="normal", doc="Ramp rate") + pb = Cpt(EpicsSignal, suffix="PB", kind="config", doc="Controller PB value") + ti = Cpt(EpicsSignal, suffix="TI", kind="config", doc="Controller TI value") + td = Cpt(EpicsSignal, suffix="TD", kind="config", doc="Controller TD value") + op_mode = Cpt(EpicsSignal, suffix="OP-MODE", kind="normal", doc="Operation mode") + setpoint_select = Cpt( + EpicsSignal, suffix="SETPOINT-SELECT", kind="config", doc="Local or remote setpoint" + ) + ramp_rate_unit = Cpt(EpicsSignal, suffix="RAMP-RATE-UNIT", kind="config", doc="Ramp rate unit") + autotune = Cpt(EpicsSignal, suffix="AUTOTUNE", kind="config", doc="Autotune function") + sensor_break = Cpt( + EpicsSignalRO, suffix="SENSOR-BREAK", kind="normal", doc="Thermocouple Status" + ) + thermocouple = Cpt(EpicsSignal, suffix="THERMOCOUPLE", kind="config", doc="Thermocouple type") + power = Cpt(EpicsSignal, suffix="POWER", kind="normal", doc="Power status") + controller_type = Cpt(EpicsSignalRO, suffix="TYPE", kind="config", doc="Controller type") + heartbeat = Cpt(EpicsSignalRO, suffix="HEARTBEAT", kind="normal", doc="Heartbeat") + connection = Cpt( + EpicsSignalRO, suffix="CONNECTION", kind="normal", doc="Connection to Eurotherm Controller" + ) + heater_temperature = Cpt( + EpicsSignalRO, + suffix="HEATER-TEMPERATURE", + kind="normal", + doc="Temperature of heating element", + ) + heater_tc_fault = Cpt( + EpicsSignalRO, + suffix="HEATER-TC-FAULT", + kind="normal", + doc="TC Fault inside heating element", + ) + + def __init__(self, *, name: str, prefix: str = "", scan_info: ScanInfo | None = None, **kwargs): + super().__init__(name=name, prefix=prefix, scan_info=scan_info, **kwargs) + + self.timeout_for_pvwait = 5 + # Wait for connection on all components, ensure IOC is connected + self.wait_for_connection(all_signals=True, timeout=5) + + def on_connected(self) -> None: + """ + Called after the device is connected and its signals are connected. + Default values for signals should be set here. + """ + if self.setpoint_select != UnivTempContSetpointSelect.REMOTE: + self.setpoint_select.set(UnivTempContSetpointSelect.REMOTE).wait( + timeout=self.timeout_for_pvwait + ) diff --git a/debye_bec/devices/univ_temp_cont/univ_temp_cont_enums.py b/debye_bec/devices/univ_temp_cont/univ_temp_cont_enums.py new file mode 100644 index 0000000..6c7e23b --- /dev/null +++ b/debye_bec/devices/univ_temp_cont/univ_temp_cont_enums.py @@ -0,0 +1,83 @@ +"""Enums for the universal temperature controller""" + +from enum import Enum + + +class UnivTempContOpMode(int, Enum): + """Class for operating mode""" + + AUTO = 0 + MANUAL = 1 + STANDBY = 2 + + +class UnivTempContSetpointSelect(int, Enum): + """Class for setpoint selection""" + + LOCAL = 0 + REMOTE = 1 + + +class UnivTempContRampRateUnit(int, Enum): + """Class for ramp rate unit selection""" + + DEG_C_MIN = 0 + DEG_C_H = 1 + DEG_C_S = 2 + + +RAMP_RATE_MAP = { + "°C/min": UnivTempContRampRateUnit.DEG_C_MIN, + "°C/h": UnivTempContRampRateUnit.DEG_C_H, + "°C/s": UnivTempContRampRateUnit.DEG_C_S, +} + + +class UnivTempContAutoTune(int, Enum): + """Class for autotune function""" + + NOTUNE = 0 + TUNE = 1 + + +class UnivTempContSensorBreak(int, Enum): + "Class for sensor break status" + + GOOD = 0 + SENSOR_BREAK = 1 + + +class UnivTempContThermocouple(int, Enum): + """Class for thermocouple type""" + + TYPE_J = 0 + Type_K = 1 + + +class UnivTempContPower(int, Enum): + """Class for power mode""" + + AUTO = 0 + STANDBY = 1 + CONFIGURATION = 2 + + +class UnivTempContConnection(int, Enum): + """Class for connection status""" + + DISCONNECTED = 0 + CONNECTED = 1 + + +class UnivTempContHeaterTcFault(int, Enum): + """Class for the heater thermocouple fault""" + + NO_FAULT = 0 + TC_OPEN_FAULT = 1 + OVER_UNDERVOLTAGE_FAULT = 2 + TC_LOW_FAULT = 3 + TC_HIGH_FAULT = 4 + COLD_JUNC_LOW_FAULT = 5 + COLD_JUNC_HIGH_FAULT = 6 + TC_RANGE_FAULT = 7 + COLD_JUNC_RNG_FAULT = 8 From 37a17ed29233fb5314a5e9c70277b05bfedcf07e Mon Sep 17 00:00:00 2001 From: x01da Date: Mon, 26 Oct 2026 12:52:11 +0100 Subject: [PATCH 48/56] wip(univ_temp_cont) --- debye_bec/bec_widgets/widgets/client.py | 25 ++++++ .../bec_widgets/widgets/designer_plugins.py | 5 ++ .../temperature_controller/qt_widgets.py | 22 ++++- .../temperature_controller.py | 80 ++++++++++++------- .../x01da_mobile_equipment.yaml | 1 - .../devices/univ_temp_cont/univ_temp_cont.py | 25 +++--- .../univ_temp_cont/univ_temp_cont_enums.py | 7 ++ 7 files changed, 115 insertions(+), 50 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/client.py b/debye_bec/bec_widgets/widgets/client.py index 481d214..14ea1a2 100644 --- a/debye_bec/bec_widgets/widgets/client.py +++ b/debye_bec/bec_widgets/widgets/client.py @@ -19,6 +19,7 @@ _Widgets = { "RestartServer": "RestartServer", "ScanControlXAS": "ScanControlXAS", "Scheduler": "Scheduler", + "TemperatureController": "TemperatureController", } @@ -242,3 +243,27 @@ class Scheduler(RPCBase): """ RPC-exposed: swap an item with the one directly after it. """ + + +class TemperatureController(RPCBase): + """Waveform with predefined curves and one status label.""" + + _IMPORT_MODULE = "debye_bec.bec_widgets.widgets.temperature_controller.temperature_controller" + + @rpc_call + def remove(self): + """ + Cleanup the BECConnector + """ + + @rpc_call + def attach(self): + """ + None + """ + + @rpc_call + def detach(self): + """ + Detach the widget from its parent dock widget (if widget is in the dock), making it a floating widget. + """ diff --git a/debye_bec/bec_widgets/widgets/designer_plugins.py b/debye_bec/bec_widgets/widgets/designer_plugins.py index 7a355e6..e4e1893 100644 --- a/debye_bec/bec_widgets/widgets/designer_plugins.py +++ b/debye_bec/bec_widgets/widgets/designer_plugins.py @@ -17,6 +17,10 @@ designer_plugins = { "ScanControlXAS", ), "Scheduler": ("debye_bec.bec_widgets.widgets.scheduler.scheduler", "Scheduler"), + "TemperatureController": ( + "debye_bec.bec_widgets.widgets.temperature_controller.temperature_controller", + "TemperatureController", + ), } widget_icons = { @@ -26,4 +30,5 @@ widget_icons = { "RestartServer": "restart_alt", "ScanControlXAS": "tune", "Scheduler": "assignment_add", + "TemperatureController": "mode_heat", } diff --git a/debye_bec/bec_widgets/widgets/temperature_controller/qt_widgets.py b/debye_bec/bec_widgets/widgets/temperature_controller/qt_widgets.py index d40015b..f4252c2 100644 --- a/debye_bec/bec_widgets/widgets/temperature_controller/qt_widgets.py +++ b/debye_bec/bec_widgets/widgets/temperature_controller/qt_widgets.py @@ -110,7 +110,8 @@ class InputNumberField(QWidget): self.hl = hl def set_number(self, number): - self.val.setValue(number) + if not self.val.hasFocus(): + self.val.setValue(number) def set_range(self, ll, hl): self.val.setRange(ll, hl) @@ -130,13 +131,21 @@ class InputNumberField(QWidget): return self.val.value() def value_changed_connect(self, func): - """Connect a function to the Enter/Return key press.""" + """Connect a function to a change in value.""" self.val.valueChanged.connect( partial( func, identifier=self.identifier, value_obj=self.val, value=lambda: self.val.value() ) ) + def editing_finished_connect(self, func): + """Connect a function to the Enter/Return press.""" + self.val.editingFinished.connect( + partial( + func, identifier=self.identifier, value_obj=self.val, value=lambda: self.val.value() + ) + ) + class ComboBox(QWidget): def __init__(self, identifier="", label="", enums=None): @@ -155,7 +164,12 @@ class ComboBox(QWidget): layout.addWidget(self.value) def set_current_text(self, text): - self.value.setCurrentText(text) + if not QApplication.focusWidget() is self.value.view(): + self.value.setCurrentText(text) + + def setCurrentIndex(self, index): + if not QApplication.focusWidget() is self.value.view(): + self.value.setCurrentIndex(index) def currentText(self) -> str: return self.value.currentText() @@ -170,8 +184,8 @@ class ComboBox(QWidget): func, identifier=self.identifier, value_obj=self.value, - value=lambda: self.value.currentText(), index=lambda: self.value.currentIndex(), + value=lambda: self.value.currentText(), ) ) diff --git a/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py b/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py index 03e1eac..27a837b 100644 --- a/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py +++ b/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py @@ -7,6 +7,7 @@ import time from collections import deque import numpy as np +import pyqtgraph as pg from bec_lib import bec_logger from bec_lib.endpoints import MessageEndpoints from bec_widgets.utils.bec_dispatcher import BECDispatcher @@ -20,6 +21,7 @@ from qtpy.QtCore import QTimer from qtpy.QtWidgets import QApplication, QHBoxLayout, QVBoxLayout, QWidget from ....devices.univ_temp_cont.univ_temp_cont_enums import ( + POWER_MAP, RAMP_RATE_MAP, UnivTempContHeaterTcFault, UnivTempContOpMode, @@ -31,6 +33,8 @@ from .qt_widgets import ComboBox, Group, InputNumberField, NumberIndicator, Text logger = bec_logger.logger +DEVICE_NAME = "univ_temp_cont" + DEFAULT_WINDOW_S = 600 REFRESH_MS = 200 PLOT_SIGNALS = ["temperature", "setpoint", "output_power"] @@ -51,7 +55,7 @@ class TemperatureController(BECWidget, QWidget): super().__init__(parent=parent, *arg, **kwargs) self.get_bec_shortcuts() - if "univ_temp_cont" not in self.dev: + if DEVICE_NAME not in self.dev: raise TemperatureControllerError( "Universal Temperature Controller is not in the config, abort." ) @@ -67,7 +71,7 @@ class TemperatureController(BECWidget, QWidget): self.sensor_break = TextIndicator("Thermocouple") self.operating_mode = TextIndicator("Operating mode") self.output_power = NumberIndicator("Output Power", "%", decimals=0) - self.temperature = NumberIndicator("Temperature", "°C", decimals=0) + self.temperature = NumberIndicator("Temperature", "°C", highlight=True, decimals=0) self.heater_temperature = NumberIndicator("Heater temperature", "°C", decimals=0) self.heater_sensor_break = TextIndicator("Heater Thermocouple") @@ -83,15 +87,15 @@ class TemperatureController(BECWidget, QWidget): ], ) - self.power_mode = ComboBox("power_mode", "Power mode", UnivTempContPower) + self.power_mode = ComboBox("power", "Power mode", POWER_MAP.keys()) self.target_setpoint = InputNumberField( "target_setpoint", "Target setpoint", "°C", decimals=0, single_step=1, ll=0, hl=850 ) self.setpoint = NumberIndicator("Setpoint", "°C", highlight=True, decimals=0) self.ramp_rate = InputNumberField( - "ramp-rate", "Ramp rate", decimals=0, single_step=1, ll=0, hl=1e5 + "ramp_rate", "Ramp rate", decimals=0, single_step=1, ll=0, hl=1e5 ) - self.ramp_rate_unit = ComboBox("ramp_rate_unit", "Ramp rate unit", UnivTempContRampRateUnit) + self.ramp_rate_unit = ComboBox("ramp_rate_unit", "Ramp rate unit", RAMP_RATE_MAP.keys()) control_group = Group( "Control", @@ -106,24 +110,29 @@ class TemperatureController(BECWidget, QWidget): control_layout.addWidget(status_group) control_layout.addWidget(control_group) + control_layout.addStretch() root_layout.addLayout(control_layout) - self.waveform = Waveform(parent=self, client=self.client, popups=False) + self.waveform = Waveform(parent=self, client=self.client, popups=True) root_layout.addWidget(self.waveform, stretch=1) - self.waveform.set(title="Title", x_label="X-Label") + self.waveform.set(title="", x_label="Time") + self.waveform.enable_toolbar = False + self.waveform.enable_side_panel = False + self.waveform.plot_item.setAxisItems({"bottom": pg.DateAxisItem(orientation="bottom")}) self._buffers: dict[str, deque] = {} self._curves = {} for signal in PLOT_SIGNALS: self._buffers[signal] = deque() # (timestamp, value), trimmed by time self._curves[signal] = self.waveform.plot( - x=[], y=[], label=self.dev.univ_temp_cont.signal.full_name + x=[], y=[], label=getattr(self.dev.univ_temp_cont, signal).full_name ) + self._curves[signal].set_symbol(None) self.bec_dispatcher.connect_slot( - self._on_readback, MessageEndpoints.device_readback(self.dev.univ_temp_cont) + self._on_readback, MessageEndpoints.device_readback(DEVICE_NAME) ) self._refresh_timer = QTimer(self) self._refresh_timer.timeout.connect(self._redraw) @@ -134,32 +143,37 @@ class TemperatureController(BECWidget, QWidget): self._config_signal_timer.start(READ_CONFIG_SIGNAL_MS) self.power_mode.activated_connect(self._on_value_changed) - self.target_setpoint.value_changed_connect(self._on_value_changed) - self.ramp_rate.value_changed_connect(self._on_value_changed) + self.target_setpoint.editing_finished_connect(self._on_value_changed) + self.ramp_rate.editing_finished_connect(self._on_value_changed) self.ramp_rate_unit.activated_connect(self._on_value_changed) + self.plot_init = True + @SafeSlot() - def _on_value_changed(self, identifier, _, value, **kwargs): - logger.info(f"Got identifier {identifier} with value {value} and kwargs {kwargs}") + def _on_value_changed(self, *_, **kwargs): if "index" in kwargs.keys(): - value = kwargs["index"] - self.dev.univ_temp_cont[identifier].put(value) + value = kwargs["index"]() + else: + value = kwargs["value"]() + signal = getattr(self.dev.univ_temp_cont, kwargs["identifier"]) + signal.put(value) @SafeSlot(dict, dict) def _on_readback(self, msg: dict, *_): signals = msg.get("signals", {}) + now = time.time() for signal, buf in self._buffers.items(): - entry = signals.get(signal) + entry = signals.get(DEVICE_NAME + "_" + signal) if entry is None or entry.get("value") is None: continue - buf.append((entry["timestamp"], entry["value"])) - value = signals["temperature"]["value"] + buf.append((now, entry["value"])) + value = signals[DEVICE_NAME + "_" + "temperature"]["value"] self.temperature.setValue(value) - value = signals["heater_temperature"]["value"] + value = signals[DEVICE_NAME + "_" + "heater_temperature"]["value"] self.heater_temperature.setValue(value) - value = signals["output_power"]["value"] + value = signals[DEVICE_NAME + "_" + "output_power"]["value"] self.output_power.setValue(value) - value = signals["sensor_break"]["value"] + value = signals[DEVICE_NAME + "_" + "sensor_break"]["value"] match value: case UnivTempContSensorBreak.GOOD: self.sensor_break.setText("OK") @@ -169,7 +183,7 @@ class TemperatureController(BECWidget, QWidget): self.sensor_break.setColor(get_accent_colors().emergency.name()) case _: raise TemperatureControllerError(f"Not implemented sensor_break value {value}") - value = signals["heater_tc_fault"]["value"] + value = signals[DEVICE_NAME + "_" + "heater_tc_fault"]["value"] match value: case UnivTempContHeaterTcFault.NO_FAULT: self.heater_sensor_break.setText("OK") @@ -192,7 +206,7 @@ class TemperatureController(BECWidget, QWidget): raise TemperatureControllerError( f"Not implemented heater_sensor_break value {value}" ) - value = signals["op_mode"]["value"] + value = signals[DEVICE_NAME + "_" + "op_mode"]["value"] match value: case UnivTempContOpMode.AUTO: self.operating_mode.setText("AUTO") @@ -205,22 +219,23 @@ class TemperatureController(BECWidget, QWidget): self.operating_mode.setColor(get_accent_colors().default.name()) case _: raise TemperatureControllerError(f"Not implemented op_mode value {value}") - value = signals["power"]["value"] - self.power_mode.set_current_text(value) - value = signals["target_setpoint"]["value"] + index = signals[DEVICE_NAME + "_" + "power"]["value"] + self.power_mode.setCurrentIndex(index) + value = signals[DEVICE_NAME + "_" + "target_setpoint"]["value"] self.target_setpoint.set_number(value) - value = signals["setpoint"]["value"] + value = signals[DEVICE_NAME + "_" + "setpoint"]["value"] self.setpoint.setValue(value) - value = signals["ramp_rate"]["value"] + value = signals[DEVICE_NAME + "_" + "ramp_rate"]["value"] self.ramp_rate.set_number(value) def _config_signal_read(self): value = self.dev.univ_temp_cont.ramp_rate_unit.read() if value is None: raise TemperatureControllerError("Reading ramp rate unit returned None!") - self.ramp_rate_unit.set_current_text(value) + index = value[DEVICE_NAME + "_ramp_rate_unit"]["value"] + self.ramp_rate_unit.setCurrentIndex(index) self.ramp_rate.setUnit( - list(RAMP_RATE_MAP.keys())[list(RAMP_RATE_MAP.values()).index(value)] + list(RAMP_RATE_MAP.keys())[list(RAMP_RATE_MAP.values()).index(index)] ) def _redraw(self): @@ -232,7 +247,10 @@ class TemperatureController(BECWidget, QWidget): if not buf: continue t, v = zip(*buf) - self._curves[key].set_data(np.asarray(t) - now, np.asarray(v)) + self._curves[key].set_data(np.asarray(t), np.asarray(v)) + if len(self._buffers[PLOT_SIGNALS[0]]) > 0 and self.plot_init: + self.plot_init = False + self.waveform.plot_item.enableAutoRange(axis=pg.ViewBox.XYAxes, enable=True) def cleanup(self): self._refresh_timer.stop() diff --git a/debye_bec/device_configs/x01da_mobile_equipment.yaml b/debye_bec/device_configs/x01da_mobile_equipment.yaml index 5e1458a..5594d8c 100644 --- a/debye_bec/device_configs/x01da_mobile_equipment.yaml +++ b/debye_bec/device_configs/x01da_mobile_equipment.yaml @@ -7,7 +7,6 @@ univ_temp_cont: description: Universal Temperature Controller deviceClass: debye_bec.devices.univ_temp_cont.univ_temp_cont.UnivTempCont deviceConfig: - auto_monitor: true prefix: "X01DA-ES-CRS:" onFailure: retry enabled: true diff --git a/debye_bec/devices/univ_temp_cont/univ_temp_cont.py b/debye_bec/devices/univ_temp_cont/univ_temp_cont.py index 0f8da55..e710a6b 100644 --- a/debye_bec/devices/univ_temp_cont/univ_temp_cont.py +++ b/debye_bec/devices/univ_temp_cont/univ_temp_cont.py @@ -7,17 +7,8 @@ from typing import TYPE_CHECKING from ophyd import Component as Cpt from ophyd import EpicsSignal, EpicsSignalRO from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase -from univ_temp_cont_enums import ( - UnivTempContAutoTune, - UnivTempContConnection, - UnivTempContHeaterTcFault, - UnivTempContOpMode, - UnivTempContPower, - UnivTempContRampRateUnit, - UnivTempContSensorBreak, - UnivTempContSetpointSelect, - UnivTempContThermocouple, -) + +from .univ_temp_cont_enums import UnivTempContSetpointSelect if TYPE_CHECKING: from bec_lib.devicemanager import ScanInfo @@ -28,7 +19,9 @@ TIMEOUT_FOR_PV = 5 class UnivTempCont(PSIDeviceBase): """Class for the Universal Temperature Controller""" - temperature = Cpt(EpicsSignalRO, suffix="TEMPERATURE", kind="normal", doc="Temperature") + temperature = Cpt( + EpicsSignalRO, suffix="TEMPERATURE", kind="normal", auto_monitor=True, doc="Temperature" + ) timestamp = Cpt(EpicsSignalRO, suffix="TIMESTAMP", kind="omitted", doc="Current timestamp") setpoint = Cpt(EpicsSignalRO, suffix="SETPOINT", kind="normal", doc="Setpoint on Controller") target_setpoint = Cpt( @@ -43,7 +36,9 @@ class UnivTempCont(PSIDeviceBase): setpoint_select = Cpt( EpicsSignal, suffix="SETPOINT-SELECT", kind="config", doc="Local or remote setpoint" ) - ramp_rate_unit = Cpt(EpicsSignal, suffix="RAMP-RATE-UNIT", kind="config", doc="Ramp rate unit") + ramp_rate_unit = Cpt( + EpicsSignal, suffix="RAMP-RATE-UNIT", kind="config", auto_monitor=True, doc="Ramp rate unit" + ) autotune = Cpt(EpicsSignal, suffix="AUTOTUNE", kind="config", doc="Autotune function") sensor_break = Cpt( EpicsSignalRO, suffix="SENSOR-BREAK", kind="normal", doc="Thermocouple Status" @@ -51,7 +46,9 @@ class UnivTempCont(PSIDeviceBase): thermocouple = Cpt(EpicsSignal, suffix="THERMOCOUPLE", kind="config", doc="Thermocouple type") power = Cpt(EpicsSignal, suffix="POWER", kind="normal", doc="Power status") controller_type = Cpt(EpicsSignalRO, suffix="TYPE", kind="config", doc="Controller type") - heartbeat = Cpt(EpicsSignalRO, suffix="HEARTBEAT", kind="normal", doc="Heartbeat") + heartbeat = Cpt( + EpicsSignalRO, suffix="HEARTBEAT", kind="normal", auto_monitor=True, doc="Heartbeat" + ) connection = Cpt( EpicsSignalRO, suffix="CONNECTION", kind="normal", doc="Connection to Eurotherm Controller" ) diff --git a/debye_bec/devices/univ_temp_cont/univ_temp_cont_enums.py b/debye_bec/devices/univ_temp_cont/univ_temp_cont_enums.py index 6c7e23b..ab1c7c9 100644 --- a/debye_bec/devices/univ_temp_cont/univ_temp_cont_enums.py +++ b/debye_bec/devices/univ_temp_cont/univ_temp_cont_enums.py @@ -62,6 +62,13 @@ class UnivTempContPower(int, Enum): CONFIGURATION = 2 +POWER_MAP = { + "Auto": UnivTempContPower.AUTO, + "Standby": UnivTempContPower.STANDBY, + "Configuration": UnivTempContPower.CONFIGURATION, +} + + class UnivTempContConnection(int, Enum): """Class for connection status""" From 8c28ff248d401668235fc9649b7a4cfe4ca9b85a Mon Sep 17 00:00:00 2001 From: x01da Date: Mon, 26 Oct 2026 13:00:30 +0100 Subject: [PATCH 49/56] fix(digital_twin): Fix various bugs --- .../bec_ipython_client/plugins/digital_twin_core/__init__.py | 3 --- .../plugins/digital_twin_core/digital_twin_core.py | 4 +++- .../bec_widgets/widgets/digital_twin/widgets/move_widget.py | 1 + .../bec_widgets/widgets/digital_twin/widgets/qt_widgets.py | 3 ++- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/__init__.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/__init__.py index b5d8096..e69de29 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/__init__.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/__init__.py @@ -1,3 +0,0 @@ -from .digital_twin_core import get_parameters - -parameters = get_parameters() diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py index 9390cb5..7bb9280 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py @@ -11,7 +11,6 @@ from scipy.interpolate import UnivariateSpline from xrt.backends.raycing.physconsts import AVOGADRO, CHeVcm from ..beamline import get_beamline_id -from . import parameters as bl from .motion_worker import MotionOutcome, MotionWorker from .types import BeamlineId, ConfigDict, DataDict, SurfaceDict @@ -37,6 +36,9 @@ def get_parameters(): return parameters +bl = get_parameters() + + class _ExclusiveGroupManager: def __init__(self): self._cond = threading.Condition() diff --git a/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py b/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py index a7f6354..9279a18 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py @@ -169,6 +169,7 @@ class MoveWidget(QWidget): # Checkbox self.checkbox = QCheckBox() + self.checkbox.setFixedWidth(30) self.checkbox.setChecked(True) layout.addWidget(self.checkbox) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py b/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py index 95c8d46..6067b90 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py @@ -167,6 +167,7 @@ class ComboBox(QWidget): func, identifier=self.identifier, value_obj=self.value, + index=lambda: self.value.currentIndex(), value=lambda: self.value.currentText(), ) ) @@ -191,9 +192,9 @@ class Button(QWidget): self.label.setFixedWidth(LABEL_WIDTH) layout.addWidget(self.label) self.button = QPushButton(label_button) - self.setEnabled(enabled) layout.addWidget(self.button) self.color = color + self.setEnabled(enabled) def clicked_connect(self, func): """Connect a function to the button press.""" From 7bb9f6300ce57d54777fb88aeac060a9fd3651b1 Mon Sep 17 00:00:00 2001 From: x01da Date: Mon, 26 Oct 2026 14:13:05 +0100 Subject: [PATCH 50/56] wip(digital_twin) --- .../digital_twin_core/motion_worker.py | 3 ++ .../widgets/digital_twin/digital_twin.py | 5 +-- .../digital_twin/panels/mover_panel.py | 2 ++ .../digital_twin/widgets/move_widget.py | 33 ++++++++++++++----- 4 files changed, 32 insertions(+), 11 deletions(-) diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py index 7af312a..192eb20 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py @@ -47,6 +47,8 @@ class MotionWorker: self.on_finished = on_finished self.last_exception: Exception | None = None + logger.info(f"motion worker init for motor {motor}") + def _emit_position_changed(self, pos: float): if self.on_position_changed is not None: self.on_position_changed(pos) @@ -65,6 +67,7 @@ class MotionWorker: def run(self): """Prepares the movement based on the axis (motor)""" + logger.info(f"Run motor {self.motor}") match self.motor: case ( "sldi_gapx" diff --git a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py index 5be5b50..166a204 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py @@ -324,9 +324,9 @@ class DigitalTwin(BECWidget, QWidget): self.calc_cm_crit_pitch() self.calc_cm_reflectivity() self.update_fm_mode() + self.calc_fm_ideal_pitch() self.calc_fm_reflectivity() self.calc_cm_fm_harm_suppr() - self.calc_fm_ideal_pitch() self.calc_mo1_energy_resolution() self.update_mo1_azm_angle() case "energy": @@ -367,9 +367,9 @@ class DigitalTwin(BECWidget, QWidget): self.calc_fm_reflectivity() self.calc_cm_fm_harm_suppr() case "fm_stripe": + self.calc_fm_ideal_pitch() self.calc_fm_reflectivity() self.calc_cm_fm_harm_suppr() - self.calc_fm_ideal_pitch() case "ot_es1_trz": self.calc_fm_ideal_pitch() case "es1man_trz": @@ -1331,6 +1331,7 @@ class DigitalTwin(BECWidget, QWidget): def _multi_move(self): """ Move the selected motors at the same time (if permitted).""" + logger.info("Multi move button pressed") abort = threading.Event() # one failure aborts the not-yet-started motors of this batch for w in self.mover.mover_widgets: if w.checkbox.isChecked(): diff --git a/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py b/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py index d4a6dd8..099931e 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py @@ -492,6 +492,8 @@ class MoverPanel(QWidget): self.multi_move_info = QLabel( "Not all motors can move together at the same time, digital twin will take care of that." ) + self.multi_move_info.setFixedWidth(352) + self.multi_move_info.setWordWrap(True) self.multi_move_group = Group("Multi Move", [self.multi_move, self.multi_move_info]) # Assemble complete mover group diff --git a/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py b/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py index 9279a18..3db7b1e 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py @@ -14,6 +14,7 @@ from qtpy.QtCore import QObject, QPropertyAnimation, Qt from qtpy.QtGui import QTransform from qtpy.QtWidgets import QApplication, QCheckBox, QHBoxLayout, QLabel, QPushButton, QWidget +from .....bec_ipython_client.plugins.digital_twin_core.digital_twin_core import DigitalTwinCore from .....bec_ipython_client.plugins.digital_twin_core.motion_worker import ( MotionOutcome, MotionWorker, @@ -142,7 +143,17 @@ class MoveWidget(QWidget): _STATUS_TOOLTIPS = {Status.QUEUED: "Waiting for other motors to finish"} - def __init__(self, core, beamline, dev, motor, label="", unit=None, decimals=3, deadband=0.0): + def __init__( + self, + core: DigitalTwinCore, + beamline, + dev, + motor, + label="", + unit=None, + decimals=3, + deadband=0.0, + ): super().__init__() self.core = core self._cancel: threading.Event | None = None @@ -169,7 +180,7 @@ class MoveWidget(QWidget): # Checkbox self.checkbox = QCheckBox() - self.checkbox.setFixedWidth(30) + self.checkbox.setFixedWidth(20) self.checkbox.setChecked(True) layout.addWidget(self.checkbox) @@ -197,7 +208,7 @@ class MoveWidget(QWidget): # Start / Stop button self.btn_action = QPushButton("Move") self.btn_action.setFixedWidth(64) - self.btn_action.setFixedHeight(20) + self.btn_action.setFixedHeight(24) self.btn_action.clicked.connect(self._on_button_clicked) layout.addWidget(self.btn_action) self.btn_mode = "start" @@ -292,6 +303,7 @@ class MoveWidget(QWidget): self._set_status(Status.NOT_IN_POSITION) def _on_button_clicked(self): + logger.info(f"Clicked on button, is busy: {self.is_busy}") if self.is_busy: self._stop_motion() else: @@ -300,15 +312,19 @@ class MoveWidget(QWidget): def start_motion(self, abort: threading.Event | None = None): """Start a motion. `abort` is shared by a batch (Move Selection) so that one failure prevents the not-yet-started motors of that batch from starting.""" + logger.info(f"start_motion on motor {self.motor}") if self.is_busy: return if abs(self.target - self.fb) <= self.deadband: + logger.info("Within deadband") self._set_status(Status.IN_POSITION) return self._apply_button_style("stop") self._cancel = threading.Event() + logger.info("Prepare stuff") + signals = _WorkerSignals() signals.waiting.connect(self._on_waiting) signals.started.connect(self._on_started) @@ -332,16 +348,13 @@ class MoveWidget(QWidget): self._thread = threading.Thread( target=self._run, args=(worker, signals, self._cancel, abort), daemon=True ) + logger.info("Start motion now...") self._thread.start() + logger.info("Motion has started") def _run(self, worker, signals, cancel, abort): try: - outcome = self.core.run_exclusive(...) - if outcome == MotionOutcome.FAILED and worker.last_exception is not None: - signals.error.emit() # harmless if motion() already emitted it - finally: - signals.finished.emit() - try: + logger.info("run_exclusive") self.core.run_exclusive( worker, abort=abort, @@ -350,9 +363,11 @@ class MoveWidget(QWidget): on_started=signals.started.emit, ) except Exception: + logger.info("Exception") signals.error.emit() raise finally: + logger.info("finally 2") signals.finished.emit() def _on_waiting(self): From cff6b9d695294871e3557082ee8fb9de4a846647 Mon Sep 17 00:00:00 2001 From: hitz_s Date: Mon, 26 Oct 2026 15:29:39 +0100 Subject: [PATCH 51/56] wip(temperature_controller) --- .../temperature_controller.py | 104 ++++++++++++++++-- .../univ_temp_cont/univ_temp_cont_enums.py | 6 + 2 files changed, 101 insertions(+), 9 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py b/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py index 27a837b..23a0f2c 100644 --- a/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py +++ b/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py @@ -18,25 +18,28 @@ from bec_widgets.widgets.plots.waveform.waveform import Waveform # pylint: disable=E0611 from qtpy.QtCore import QTimer -from qtpy.QtWidgets import QApplication, QHBoxLayout, QVBoxLayout, QWidget +from qtpy.QtWidgets import QApplication, QHBoxLayout, QLabel, QVBoxLayout, QWidget from ....devices.univ_temp_cont.univ_temp_cont_enums import ( POWER_MAP, RAMP_RATE_MAP, + THERMOCOUPLE_MAP, + UnivTempContAutoTune, UnivTempContHeaterTcFault, UnivTempContOpMode, UnivTempContPower, UnivTempContRampRateUnit, UnivTempContSensorBreak, ) -from .qt_widgets import ComboBox, Group, InputNumberField, NumberIndicator, TextIndicator +from .qt_widgets import Button, ComboBox, Group, InputNumberField, NumberIndicator, TextIndicator logger = bec_logger.logger DEVICE_NAME = "univ_temp_cont" DEFAULT_WINDOW_S = 600 -REFRESH_MS = 200 +MAX_WINDOW_S = 36000 +REFRESH_MS = 500 PLOT_SIGNALS = ["temperature", "setpoint", "output_power"] READ_CONFIG_SIGNAL_MS = 1000 @@ -108,14 +111,54 @@ class TemperatureController(BECWidget, QWidget): ], ) + self.pid_pb = InputNumberField("pb", "PB", decimals=0, single_step=1, ll=1, hl=9999) + self.pid_ti = InputNumberField( + "ti", "TI", decimals=0, single_step=1, ll=0, hl=9999, unit="s" + ) + self.pid_td = InputNumberField( + "td", "TD", decimals=0, single_step=1, ll=0, hl=9999, unit="s" + ) + + self.autotune = Button("Autotune", "Start", enabled=True, color="success") + self.autotune_status = TextIndicator("Autotune Status") + + pid_loop_group = Group( + "PID loop", [self.pid_pb, self.pid_ti, self.pid_td, self.autotune, self.autotune_status] + ) + + self.tc_info = QLabel("Controller will restart when changing value") + self.thermocouple = ComboBox("thermocouple", "Thermocouple", THERMOCOUPLE_MAP.keys()) + + configuration_group = Group("Configuration", [self.tc_info, self.thermocouple]) + control_layout.addWidget(status_group) control_layout.addWidget(control_group) + control_layout.addWidget(pid_loop_group) + control_layout.addWidget(configuration_group) control_layout.addStretch() root_layout.addLayout(control_layout) + waveform_layout = QVBoxLayout() + self.waveform = Waveform(parent=self, client=self.client, popups=True) - root_layout.addWidget(self.waveform, stretch=1) + + waveform_layout.addWidget(self.waveform, stretch=1) + + self.user_window_s = InputNumberField( + "", + "Plot range", + "s", + init=DEFAULT_WINDOW_S, + decimals=0, + single_step=60, + ll=1, + hl=MAX_WINDOW_S, + ) + + waveform_layout.addWidget(self.user_window_s) + + root_layout.addLayout(waveform_layout, stretch=1) self.waveform.set(title="", x_label="Time") self.waveform.enable_toolbar = False @@ -146,6 +189,11 @@ class TemperatureController(BECWidget, QWidget): self.target_setpoint.editing_finished_connect(self._on_value_changed) self.ramp_rate.editing_finished_connect(self._on_value_changed) self.ramp_rate_unit.activated_connect(self._on_value_changed) + self.pid_pb.editing_finished_connect(self._on_value_changed) + self.pid_ti.editing_finished_connect(self._on_value_changed) + self.pid_td.editing_finished_connect(self._on_value_changed) + self.autotune.clicked_connect(self._start_stop_autotune) + self.thermocouple.activated_connect(self._on_value_changed) self.plot_init = True @@ -158,6 +206,12 @@ class TemperatureController(BECWidget, QWidget): signal = getattr(self.dev.univ_temp_cont, kwargs["identifier"]) signal.put(value) + @SafeSlot() + def _start_stop_autotune(self, *_): + signal = getattr(self.dev.univ_temp_cont, "autotune") + val = signal.read()["autotune"]["value"] + signal.put(not val) + @SafeSlot(dict, dict) def _on_readback(self, msg: dict, *_): signals = msg.get("signals", {}) @@ -229,25 +283,57 @@ class TemperatureController(BECWidget, QWidget): self.ramp_rate.set_number(value) def _config_signal_read(self): + # Ramp rate unit value = self.dev.univ_temp_cont.ramp_rate_unit.read() - if value is None: - raise TemperatureControllerError("Reading ramp rate unit returned None!") index = value[DEVICE_NAME + "_ramp_rate_unit"]["value"] self.ramp_rate_unit.setCurrentIndex(index) self.ramp_rate.setUnit( list(RAMP_RATE_MAP.keys())[list(RAMP_RATE_MAP.values()).index(index)] ) + # PB + value = self.dev.univ_temp_cont.pb.read()[DEVICE_NAME + "_pb"]["value"] + self.pid_pb.set_number(value) + # TI + value = self.dev.univ_temp_cont.ti.read()[DEVICE_NAME + "_ti"]["value"] + self.pid_ti.set_number(value) + # TD + value = self.dev.univ_temp_cont.td.read()[DEVICE_NAME + "_td"]["value"] + self.pid_td.set_number(value) + # Autotune + value = self.dev.univ_temp_cont.autotune.read() + index = value[DEVICE_NAME + "_autotune"]["value"] + match index: + case UnivTempContAutoTune.NOTUNE: + self.autotune.setText("Start") + self.autotune.setColor("success") + self.autotune_status.setText("Not active") + self.autotune_status.setColor("default") + case UnivTempContAutoTune.TUNE: + self.autotune.setText("Stop") + self.autotune.setColor("emergency") + self.autotune_status.setText("Active") + self.autotune_status.setColor("warning") + case _: + raise TemperatureControllerError(f"Not implemented autotune value {index}") + # Thermocouple + value = self.dev.univ_temp_cont.thermocouple.read() + index = value[DEVICE_NAME + "_thermocouple"]["value"] + self.thermocouple.setCurrentIndex(index) def _redraw(self): now = time.time() - cutoff = now - self._window_s + cutoff = now - MAX_WINDOW_S + view_cutoff = now - min(self.user_window_s.value(), MAX_WINDOW_S) + for key, buf in self._buffers.items(): while buf and buf[0][0] < cutoff: buf.popleft() if not buf: continue - t, v = zip(*buf) - self._curves[key].set_data(np.asarray(t), np.asarray(v)) + + t, v = map(np.asarray, zip(*buf)) + i = np.searchsorted(t, view_cutoff, side="left") + self._curves[key].set_data(t[i:], v[i:]) if len(self._buffers[PLOT_SIGNALS[0]]) > 0 and self.plot_init: self.plot_init = False self.waveform.plot_item.enableAutoRange(axis=pg.ViewBox.XYAxes, enable=True) diff --git a/debye_bec/devices/univ_temp_cont/univ_temp_cont_enums.py b/debye_bec/devices/univ_temp_cont/univ_temp_cont_enums.py index ab1c7c9..97fc191 100644 --- a/debye_bec/devices/univ_temp_cont/univ_temp_cont_enums.py +++ b/debye_bec/devices/univ_temp_cont/univ_temp_cont_enums.py @@ -54,6 +54,12 @@ class UnivTempContThermocouple(int, Enum): Type_K = 1 +THERMOCOUPLE_MAP = { + "Type J": UnivTempContThermocouple.TYPE_J, + "Type K": UnivTempContThermocouple.Type_K, +} + + class UnivTempContPower(int, Enum): """Class for power mode""" From 0f72f290b474cd15e25f8b22da0292d38dcc33f2 Mon Sep 17 00:00:00 2001 From: x01da Date: Wed, 28 Oct 2026 08:55:54 +0100 Subject: [PATCH 52/56] wip(temperature_controller) --- .../temperature_controller/qt_widgets.py | 9 ++++- .../temperature_controller.py | 34 +++++++++++++------ 2 files changed, 31 insertions(+), 12 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/temperature_controller/qt_widgets.py b/debye_bec/bec_widgets/widgets/temperature_controller/qt_widgets.py index f4252c2..f5ad06f 100644 --- a/debye_bec/bec_widgets/widgets/temperature_controller/qt_widgets.py +++ b/debye_bec/bec_widgets/widgets/temperature_controller/qt_widgets.py @@ -209,9 +209,9 @@ class Button(QWidget): self.label.setFixedWidth(LABEL_WIDTH) layout.addWidget(self.label) self.button = QPushButton(label_button) + self.color = color self.setEnabled(enabled) layout.addWidget(self.button) - self.color = color def clicked_connect(self, func): """Connect a function to the button press.""" @@ -252,6 +252,7 @@ class TextIndicator(QWidget): self.text = QLabel("-") self.text.setAlignment(Qt.AlignTop) # type: ignore layout.addWidget(self.text) + self.color = "default" def setLabel(self, label) -> None: self.label.setText(label) @@ -260,4 +261,10 @@ class TextIndicator(QWidget): self.text.setText(text) def setColor(self, color: str): + self.color = color + self.apply_theme() + + def apply_theme(self): + colors = get_accent_colors() + color = getattr(colors, self.color).name() self.text.setStyleSheet(f"QLabel {{color:{color}}}") diff --git a/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py b/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py index 23a0f2c..e65a277 100644 --- a/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py +++ b/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py @@ -12,7 +12,7 @@ from bec_lib import bec_logger from bec_lib.endpoints import MessageEndpoints from bec_widgets.utils.bec_dispatcher import BECDispatcher from bec_widgets.utils.bec_widget import BECWidget -from bec_widgets.utils.colors import apply_theme, get_accent_colors +from bec_widgets.utils.colors import apply_theme from bec_widgets.utils.error_popups import SafeSlot from bec_widgets.widgets.plots.waveform.waveform import Waveform @@ -145,6 +145,7 @@ class TemperatureController(BECWidget, QWidget): waveform_layout.addWidget(self.waveform, stretch=1) + waveform_settings_layout = QHBoxLayout() self.user_window_s = InputNumberField( "", "Plot range", @@ -155,13 +156,15 @@ class TemperatureController(BECWidget, QWidget): ll=1, hl=MAX_WINDOW_S, ) + waveform_settings_layout.addWidget(self.user_window_s) + waveform_settings_layout.addStretch() - waveform_layout.addWidget(self.user_window_s) + waveform_layout.addLayout(waveform_settings_layout) root_layout.addLayout(waveform_layout, stretch=1) self.waveform.set(title="", x_label="Time") - self.waveform.enable_toolbar = False + self.waveform.enable_toolbar = True self.waveform.enable_side_panel = False self.waveform.plot_item.setAxisItems({"bottom": pg.DateAxisItem(orientation="bottom")}) @@ -197,6 +200,15 @@ class TemperatureController(BECWidget, QWidget): self.plot_init = True + @SafeSlot() + def apply_theme(self, theme): + self.sensor_break.apply_theme() + self.operating_mode.apply_theme() + self.heater_sensor_break.apply_theme() + self.autotune_status.apply_theme() + self.autotune.apply_theme() + return super().apply_theme(theme) + @SafeSlot() def _on_value_changed(self, *_, **kwargs): if "index" in kwargs.keys(): @@ -231,20 +243,20 @@ class TemperatureController(BECWidget, QWidget): match value: case UnivTempContSensorBreak.GOOD: self.sensor_break.setText("OK") - self.sensor_break.setColor(get_accent_colors().success.name()) + self.sensor_break.setColor("success") case UnivTempContSensorBreak.SENSOR_BREAK: self.sensor_break.setText("FAULT") - self.sensor_break.setColor(get_accent_colors().emergency.name()) + self.sensor_break.setColor("emergency") case _: raise TemperatureControllerError(f"Not implemented sensor_break value {value}") value = signals[DEVICE_NAME + "_" + "heater_tc_fault"]["value"] match value: case UnivTempContHeaterTcFault.NO_FAULT: self.heater_sensor_break.setText("OK") - self.heater_sensor_break.setColor(get_accent_colors().success.name()) + self.heater_sensor_break.setColor("success") case UnivTempContHeaterTcFault.TC_OPEN_FAULT: self.heater_sensor_break.setText("OPEN") - self.heater_sensor_break.setColor(get_accent_colors().warning.name()) + self.heater_sensor_break.setColor("warning") case ( UnivTempContHeaterTcFault.OVER_UNDERVOLTAGE_FAULT | UnivTempContHeaterTcFault.TC_LOW_FAULT @@ -255,7 +267,7 @@ class TemperatureController(BECWidget, QWidget): | UnivTempContHeaterTcFault.COLD_JUNC_RNG_FAULT ): self.heater_sensor_break.setText("FAULT") - self.heater_sensor_break.setColor(get_accent_colors().emergency.name()) + self.heater_sensor_break.setColor("emergency") case _: raise TemperatureControllerError( f"Not implemented heater_sensor_break value {value}" @@ -264,13 +276,13 @@ class TemperatureController(BECWidget, QWidget): match value: case UnivTempContOpMode.AUTO: self.operating_mode.setText("AUTO") - self.operating_mode.setColor(get_accent_colors().success.name()) + self.operating_mode.setColor("success") case UnivTempContOpMode.MANUAL: self.operating_mode.setText("MANUAL") - self.operating_mode.setColor(get_accent_colors().warning.name()) + self.operating_mode.setColor("warning") case UnivTempContOpMode.STANDBY: self.operating_mode.setText("STANDBY") - self.operating_mode.setColor(get_accent_colors().default.name()) + self.operating_mode.setColor("default") case _: raise TemperatureControllerError(f"Not implemented op_mode value {value}") index = signals[DEVICE_NAME + "_" + "power"]["value"] From 317e52a1bca195769c5bfb4a25334cf3450dbb90 Mon Sep 17 00:00:00 2001 From: hitz_s Date: Mon, 2 Nov 2026 11:05:25 +0100 Subject: [PATCH 53/56] wip(temperature_controller, scheduler) --- .../widgets/scheduler/item_dialog.py | 68 +++++++ .../widgets/scheduler/scheduler.py | 12 ++ .../temperature_controller/qt_widgets.py | 3 + .../temperature_controller.py | 189 ++++++++++++------ .../devices/univ_temp_cont/univ_temp_cont.py | 39 +++- 5 files changed, 243 insertions(+), 68 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index b75b026..60aa164 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -73,12 +73,14 @@ class ScheduleItemDialog(QDialog): from ..digital_twin.digital_twin import DigitalTwin from ..edge_selector import EdgeSelector from ..scan_control_xas.scan_control_xas import ScanControlXAS + from ..temperature_controller.temperature_controller import TemperatureControllerControl self.DigitalTwinCore = DigitalTwinCore self.DigitalTwin = DigitalTwin self.AutoGain = AutoGain self.EdgeSelector = EdgeSelector self.ScanControlXAS = ScanControlXAS + self.TemperatureController = TemperatureControllerControl layout = QVBoxLayout(self) @@ -96,6 +98,7 @@ class ScheduleItemDialog(QDialog): self._build_ic_page() self._build_reffoil_page() self._build_auto_gain_page() + self._build_temperature_controller_page() self._build_other_page() self.item_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) @@ -118,6 +121,7 @@ class ScheduleItemDialog(QDialog): "ic": self._collect_ic_result, "reffoil": self._collect_reffoil_result, "auto_gain": self._collect_auto_gain_result, + "temperautre_control": self._collect_temperature_controller_result, "other": self._collect_custom_result, } @@ -535,6 +539,69 @@ class ScheduleItemDialog(QDialog): def _prefill_auto_gain_form(self, state: dict): self.auto_gain.load_config(state["config"]) + # ------------------------------------------------------------------ # + # Temperature Controller + # ------------------------------------------------------------------ # + def _build_tempature_controller_page(self): + page = QWidget() + outer = QVBoxLayout(page) + + scroll = QScrollArea() + scroll.setWidgetResizable(True) + self.temperature_controller = self.TemperatureController(config_only=True, parent=scroll, client=self._client) + + scroll.setWidget(self.temperature_controller) + outer.addWidget(scroll) + + # hint = QLabel( + # "Configure the auto-gain functionality, then confirm with Add below - the " + # "auto-gain will only be executed when this schedule item runs, not immediately." + # ) + # hint.setWordWrap(True) + # hint.setStyleSheet("color: gray;") + # outer.addWidget(hint) + + self._add_page("temperature_controller", "Temperature Controller", page) + + def _collect_temperature_controller_result(self) -> dict: + config = self.temperature_controller.get_config() + + cmd = f"dev.univ_temp_cont.load_config(config={config})" + return { + "command": cmd, + "kind": "custom", + "form_state": {"text": cmd, "source": "temperature_controller", "config": config}, + } + + def _prefill_temperature_controller_form(self, state: dict): + self.temperature_controller.load_config(state["config"]) + + # ------------------------------------------------------------------ # + # Sleep + # ------------------------------------------------------------------ # + def _build_sleep_page(self): + page = QWidget() + form = QFormLayout(page) + form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) + + self.sleep_spin = QDoubleSpinBox(suffix=" s") + form.addRow("Sleep for", self.sleep_spin) + + self._add_page("sleep", "Sleep", page) + + def _collect_sleep_result(self) -> dict: + value = self.sleep_spin.value() + return { + "command": f"time.sleep({value})", + "kind": "sleep", + "form_state": { + "value": value, + }, + } + + def _prefill_sleep_page(self, state: dict): + self.sleep_spin.setValue(float(state.get("value", 0.0))) + # ------------------------------------------------------------------ # # Other # ------------------------------------------------------------------ # @@ -591,6 +658,7 @@ class ScheduleItemDialog(QDialog): self._prefill_reffoil_form(state) elif kind == "custom" and source == "auto_gain" and self._select_page("auto_gain"): self._prefill_auto_gain_form(state) + elif kind == "custom" and source == "temperature_controller" and self._select_page("temperature_controller") elif initial.get("command"): # "custom" kind with no (recognized/available) source, or a # legacy/unrecognized item - fall back to showing the raw diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index e5e6ae4..9f50ce1 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -143,6 +143,18 @@ def build_item_display_text(item: ScheduleItem, beamline: str | None) -> str: + "}" ) text += "\nProhibited gains: " + prohibited_gains + elif item.command.startswith("dev.univ_temp_cont.load_config("): + config = item.form_state["config"] + match config["power_mode"]: + case "Standby": + text += "Switch temperature controller to standby" + case "Configuration": + text += "Switch temperature controller to configuration mode" + case _: + text += ( + f"Set temperature controller target setpoint to {config['target_setpoint']}" + + f" °C\nwith ramp rate of {config['rampe_rate']} {config['ramp_rate_unit']}" + ) elif item.command.startswith("dev.abs."): action = item.form_state["action"] text += f"{action} Absorber" diff --git a/debye_bec/bec_widgets/widgets/temperature_controller/qt_widgets.py b/debye_bec/bec_widgets/widgets/temperature_controller/qt_widgets.py index f5ad06f..5c0f15e 100644 --- a/debye_bec/bec_widgets/widgets/temperature_controller/qt_widgets.py +++ b/debye_bec/bec_widgets/widgets/temperature_controller/qt_widgets.py @@ -171,6 +171,9 @@ class ComboBox(QWidget): if not QApplication.focusWidget() is self.value.view(): self.value.setCurrentIndex(index) + def currentIndex(self): + return self.value.currentIndex() + def currentText(self) -> str: return self.value.currentText() diff --git a/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py b/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py index e65a277..4460585 100644 --- a/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py +++ b/debye_bec/bec_widgets/widgets/temperature_controller/temperature_controller.py @@ -5,6 +5,7 @@ from __future__ import annotations import sys import time from collections import deque +from typing import Literal import numpy as np import pyqtgraph as pg @@ -15,11 +16,16 @@ from bec_widgets.utils.bec_widget import BECWidget from bec_widgets.utils.colors import apply_theme from bec_widgets.utils.error_popups import SafeSlot from bec_widgets.widgets.plots.waveform.waveform import Waveform +from pydantic import BaseModel +from PySide6.QtCore import QLocale, QPoint, QRect, QSize, Qt +from PySide6.QtGui import QCursor, QFont, QIcon, QPalette, QRegion +from PySide6.QtWidgets import QSizePolicy # pylint: disable=E0611 from qtpy.QtCore import QTimer from qtpy.QtWidgets import QApplication, QHBoxLayout, QLabel, QVBoxLayout, QWidget +from ....devices.univ_temp_cont.univ_temp_cont import ConfigDict from ....devices.univ_temp_cont.univ_temp_cont_enums import ( POWER_MAP, RAMP_RATE_MAP, @@ -48,6 +54,61 @@ class TemperatureControllerError(Exception): """Temperature Controller specific error""" +class TemperatureControllerControl(QWidget): + def __init__(self, config_only: bool = False, *arg, parent=None, **kwargs) -> None: + super().__init__(*arg, parent=parent, **kwargs) + + self._layout = QVBoxLayout(self) + + self.power_mode = ComboBox("power", "Power mode", POWER_MAP.keys()) + self.target_setpoint = InputNumberField( + "target_setpoint", "Target setpoint", "°C", decimals=0, single_step=1, ll=0, hl=850 + ) + self.ramp_rate = InputNumberField( + "ramp_rate", "Ramp rate", decimals=0, single_step=1, ll=0, hl=1e5 + ) + self.ramp_rate_unit = ComboBox("ramp_rate_unit", "Ramp rate unit", RAMP_RATE_MAP.keys()) + + if not config_only: + self.setpoint = NumberIndicator("Setpoint", "°C", highlight=True, decimals=0) + widgets = [ + self.power_mode, + self.target_setpoint, + self.setpoint, + self.ramp_rate, + self.ramp_rate_unit, + ] + else: + widgets = [self.power_mode, self.target_setpoint, self.ramp_rate, self.ramp_rate_unit] + + control_group = Group("Control", widgets) + self.ramp_rate_unit.activated_connect(self._on_ramp_rate_unit_change) + self._on_ramp_rate_unit_change() + + self._layout.addWidget(control_group) + + @SafeSlot() + def _on_ramp_rate_unit_change(self, *_, **__): + index = self.ramp_rate_unit.currentIndex() + self.ramp_rate.setUnit( + list(RAMP_RATE_MAP.keys())[list(RAMP_RATE_MAP.values()).index(index)] + ) + + def get_config(self) -> ConfigDict: + return ConfigDict( + power_mode=self.power_mode.currentText(), + target_setpoint=self.target_setpoint.value(), + ramp_rate=self.ramp_rate.value(), + ramp_rate_unit=self.ramp_rate_unit.currentText(), + ) + + def load_config(self, config: ConfigDict) -> None: + self.power_mode.setCurrentIndex(POWER_MAP[config.power_mode]) + self.ramp_rate_unit.setCurrentIndex(RAMP_RATE_MAP[config.ramp_rate_unit]) + self.ramp_rate.set_number(config.ramp_rate) + self.target_setpoint.set_number(config.target_setpoint) + + class TemperatureController(BECWidget, QWidget): """Waveform with predefined curves and one status label.""" @@ -65,6 +126,42 @@ class TemperatureController(BECWidget, QWidget): self._window_s = DEFAULT_WINDOW_S + self.init_ui() + + self._buffers: dict[str, deque] = {} + self._curves = {} + for signal in PLOT_SIGNALS: + self._buffers[signal] = deque() # (timestamp, value), trimmed by time + self._curves[signal] = self.waveform.plot( + x=[], y=[], label=getattr(self.dev.univ_temp_cont, signal).full_name + ) + self._curves[signal].set_symbol(None) + + self.bec_dispatcher.connect_slot( + self._on_readback, MessageEndpoints.device_readback(DEVICE_NAME) + ) + self._refresh_timer = QTimer(self) + self._refresh_timer.timeout.connect(self._redraw) + self._refresh_timer.start(REFRESH_MS) + + self._config_signal_timer = QTimer(self) + self._config_signal_timer.timeout.connect(self._config_signal_read) + self._config_signal_timer.start(READ_CONFIG_SIGNAL_MS) + + self.control.power_mode.activated_connect(self._on_value_changed) + self.control.target_setpoint.editing_finished_connect(self._on_value_changed) + self.control.ramp_rate.editing_finished_connect(self._on_value_changed) + self.control.ramp_rate_unit.activated_connect(self._on_value_changed) + self.pid_pb.editing_finished_connect(self._on_value_changed) + self.pid_ti.editing_finished_connect(self._on_value_changed) + self.pid_td.editing_finished_connect(self._on_value_changed) + self.autotune.clicked_connect(self._start_stop_autotune) + self.thermocouple.activated_connect(self._on_value_changed) + + self.plot_init = True + + def init_ui(self) -> None: + """Init the UI for the temperature controller widget, should only take place once.""" root_layout = QHBoxLayout(self) control_layout = QVBoxLayout() @@ -90,26 +187,7 @@ class TemperatureController(BECWidget, QWidget): ], ) - self.power_mode = ComboBox("power", "Power mode", POWER_MAP.keys()) - self.target_setpoint = InputNumberField( - "target_setpoint", "Target setpoint", "°C", decimals=0, single_step=1, ll=0, hl=850 - ) - self.setpoint = NumberIndicator("Setpoint", "°C", highlight=True, decimals=0) - self.ramp_rate = InputNumberField( - "ramp_rate", "Ramp rate", decimals=0, single_step=1, ll=0, hl=1e5 - ) - self.ramp_rate_unit = ComboBox("ramp_rate_unit", "Ramp rate unit", RAMP_RATE_MAP.keys()) - - control_group = Group( - "Control", - [ - self.power_mode, - self.target_setpoint, - self.setpoint, - self.ramp_rate, - self.ramp_rate_unit, - ], - ) + self.control = TemperatureControllerControl() self.pid_pb = InputNumberField("pb", "PB", decimals=0, single_step=1, ll=1, hl=9999) self.pid_ti = InputNumberField( @@ -132,7 +210,7 @@ class TemperatureController(BECWidget, QWidget): configuration_group = Group("Configuration", [self.tc_info, self.thermocouple]) control_layout.addWidget(status_group) - control_layout.addWidget(control_group) + control_layout.addWidget(self.control) control_layout.addWidget(pid_loop_group) control_layout.addWidget(configuration_group) control_layout.addStretch() @@ -141,10 +219,6 @@ class TemperatureController(BECWidget, QWidget): waveform_layout = QVBoxLayout() - self.waveform = Waveform(parent=self, client=self.client, popups=True) - - waveform_layout.addWidget(self.waveform, stretch=1) - waveform_settings_layout = QHBoxLayout() self.user_window_s = InputNumberField( "", @@ -161,6 +235,10 @@ class TemperatureController(BECWidget, QWidget): waveform_layout.addLayout(waveform_settings_layout) + self.waveform = Waveform(parent=self, client=self.client, popups=True) + + waveform_layout.addWidget(self.waveform, stretch=1) + root_layout.addLayout(waveform_layout, stretch=1) self.waveform.set(title="", x_label="Time") @@ -168,38 +246,6 @@ class TemperatureController(BECWidget, QWidget): self.waveform.enable_side_panel = False self.waveform.plot_item.setAxisItems({"bottom": pg.DateAxisItem(orientation="bottom")}) - self._buffers: dict[str, deque] = {} - self._curves = {} - for signal in PLOT_SIGNALS: - self._buffers[signal] = deque() # (timestamp, value), trimmed by time - self._curves[signal] = self.waveform.plot( - x=[], y=[], label=getattr(self.dev.univ_temp_cont, signal).full_name - ) - self._curves[signal].set_symbol(None) - - self.bec_dispatcher.connect_slot( - self._on_readback, MessageEndpoints.device_readback(DEVICE_NAME) - ) - self._refresh_timer = QTimer(self) - self._refresh_timer.timeout.connect(self._redraw) - self._refresh_timer.start(REFRESH_MS) - - self._config_signal_timer = QTimer(self) - self._config_signal_timer.timeout.connect(self._config_signal_read) - self._config_signal_timer.start(READ_CONFIG_SIGNAL_MS) - - self.power_mode.activated_connect(self._on_value_changed) - self.target_setpoint.editing_finished_connect(self._on_value_changed) - self.ramp_rate.editing_finished_connect(self._on_value_changed) - self.ramp_rate_unit.activated_connect(self._on_value_changed) - self.pid_pb.editing_finished_connect(self._on_value_changed) - self.pid_ti.editing_finished_connect(self._on_value_changed) - self.pid_td.editing_finished_connect(self._on_value_changed) - self.autotune.clicked_connect(self._start_stop_autotune) - self.thermocouple.activated_connect(self._on_value_changed) - - self.plot_init = True - @SafeSlot() def apply_theme(self, theme): self.sensor_break.apply_theme() @@ -209,6 +255,20 @@ class TemperatureController(BECWidget, QWidget): self.autotune.apply_theme() return super().apply_theme(theme) + def load_config(self, config: ConfigDict) -> None: + # Power mode + signal = getattr(self.dev.univ_temp_cont, "power") + signal.put(POWER_MAP[config.power_mode]) + # Ramp rate unit + signal = getattr(self.dev.univ_temp_cont, "ramp_rate_unit") + signal.put(RAMP_RATE_MAP[config.ramp_rate_unit]) + # Ramp rate + signal = getattr(self.dev.univ_temp_cont, "ramp_rate") + signal.put(config.ramp_rate) + # Target setpoint + signal = getattr(self.dev.univ_temp_cont, "target_setpoint") + signal.put(config.target_setpoint) + @SafeSlot() def _on_value_changed(self, *_, **kwargs): if "index" in kwargs.keys(): @@ -286,22 +346,19 @@ class TemperatureController(BECWidget, QWidget): case _: raise TemperatureControllerError(f"Not implemented op_mode value {value}") index = signals[DEVICE_NAME + "_" + "power"]["value"] - self.power_mode.setCurrentIndex(index) + self.control.power_mode.setCurrentIndex(index) value = signals[DEVICE_NAME + "_" + "target_setpoint"]["value"] - self.target_setpoint.set_number(value) + self.control.target_setpoint.set_number(value) value = signals[DEVICE_NAME + "_" + "setpoint"]["value"] - self.setpoint.setValue(value) + self.control.setpoint.setValue(value) value = signals[DEVICE_NAME + "_" + "ramp_rate"]["value"] - self.ramp_rate.set_number(value) + self.control.ramp_rate.set_number(value) def _config_signal_read(self): # Ramp rate unit value = self.dev.univ_temp_cont.ramp_rate_unit.read() index = value[DEVICE_NAME + "_ramp_rate_unit"]["value"] - self.ramp_rate_unit.setCurrentIndex(index) - self.ramp_rate.setUnit( - list(RAMP_RATE_MAP.keys())[list(RAMP_RATE_MAP.values()).index(index)] - ) + self.control.ramp_rate_unit.setCurrentIndex(index) # PB value = self.dev.univ_temp_cont.pb.read()[DEVICE_NAME + "_pb"]["value"] self.pid_pb.set_number(value) @@ -359,6 +416,6 @@ if __name__ == "__main__": app = QApplication(sys.argv) apply_theme("light") dispatcher = BECDispatcher(gui_id="restart_server") - win = TemperatureController() + win = TemperatureControllerControl(config_only=True) win.show() sys.exit(app.exec_()) diff --git a/debye_bec/devices/univ_temp_cont/univ_temp_cont.py b/debye_bec/devices/univ_temp_cont/univ_temp_cont.py index e710a6b..0f4c2bb 100644 --- a/debye_bec/devices/univ_temp_cont/univ_temp_cont.py +++ b/debye_bec/devices/univ_temp_cont/univ_temp_cont.py @@ -2,13 +2,14 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Literal from ophyd import Component as Cpt from ophyd import EpicsSignal, EpicsSignalRO from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase +from pydantic import BaseModel -from .univ_temp_cont_enums import UnivTempContSetpointSelect +from .univ_temp_cont_enums import POWER_MAP, RAMP_RATE_MAP, UnivTempContSetpointSelect if TYPE_CHECKING: from bec_lib.devicemanager import ScanInfo @@ -16,9 +17,20 @@ if TYPE_CHECKING: TIMEOUT_FOR_PV = 5 +class ConfigDict(BaseModel): + """A configuration dictionary.""" + + power_mode: Literal[tuple(POWER_MAP)] # type: ignore[valid-type] + target_setpoint: float + ramp_rate: float + ramp_rate_unit: Literal[tuple(RAMP_RATE_MAP)] # type: ignore[valid-type] + + class UnivTempCont(PSIDeviceBase): """Class for the Universal Temperature Controller""" + USER_ACCESS = ["load_config"] + temperature = Cpt( EpicsSignalRO, suffix="TEMPERATURE", kind="normal", auto_monitor=True, doc="Temperature" ) @@ -81,3 +93,26 @@ class UnivTempCont(PSIDeviceBase): self.setpoint_select.set(UnivTempContSetpointSelect.REMOTE).wait( timeout=self.timeout_for_pvwait ) + + def load_config( + self, + config: ConfigDict | None = None, + power_mode: str = "", + ramp_rate_unit: str = "", + ramp_rate: float = 0, + target_setpoint: float = 0, + ) -> None: + if config is None: + config = ConfigDict( + power_mode=power_mode, + ramp_rate_unit=ramp_rate_unit, + ramp_rate=ramp_rate, + target_setpoint=target_setpoint, + ) + # Load a config to the controller (power, setpoint and ramp rate) + self.power.set(POWER_MAP[config.power_mode]).wait(timeout=self.timeout_for_pvwait) + self.ramp_rate_unit.set(RAMP_RATE_MAP[config.ramp_rate_unit]).wait( + timeout=self.timeout_for_pvwait + ) + self.ramp_rate.set(config.ramp_rate).wait(timeout=self.timeout_for_pvwait) + self.target_setpoint.set(config.target_setpoint).wait(timeout=self.timeout_for_pvwait) From 02f60b8de0d1e8b7537dc1f63be77ff4f1118724 Mon Sep 17 00:00:00 2001 From: x01da Date: Mon, 2 Nov 2026 11:33:35 +0100 Subject: [PATCH 54/56] bugfixes --- debye_bec/bec_widgets/widgets/scheduler/item_dialog.py | 10 ++++++---- debye_bec/bec_widgets/widgets/scheduler/scheduler.py | 2 +- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index 60aa164..57a9166 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -121,7 +121,7 @@ class ScheduleItemDialog(QDialog): "ic": self._collect_ic_result, "reffoil": self._collect_reffoil_result, "auto_gain": self._collect_auto_gain_result, - "temperautre_control": self._collect_temperature_controller_result, + "temperature_controller": self._collect_temperature_controller_result, "other": self._collect_custom_result, } @@ -542,16 +542,17 @@ class ScheduleItemDialog(QDialog): # ------------------------------------------------------------------ # # Temperature Controller # ------------------------------------------------------------------ # - def _build_tempature_controller_page(self): + def _build_temperature_controller_page(self): page = QWidget() outer = QVBoxLayout(page) scroll = QScrollArea() scroll.setWidgetResizable(True) - self.temperature_controller = self.TemperatureController(config_only=True, parent=scroll, client=self._client) + self.temperature_controller = self.TemperatureController(config_only=True, parent=scroll) scroll.setWidget(self.temperature_controller) outer.addWidget(scroll) + outer.addStretch() # hint = QLabel( # "Configure the auto-gain functionality, then confirm with Add below - the " @@ -658,7 +659,8 @@ class ScheduleItemDialog(QDialog): self._prefill_reffoil_form(state) elif kind == "custom" and source == "auto_gain" and self._select_page("auto_gain"): self._prefill_auto_gain_form(state) - elif kind == "custom" and source == "temperature_controller" and self._select_page("temperature_controller") + elif kind == "custom" and source == "temperature_controller" and self._select_page("temperature_controller"): + self._prefill_temperature_controller_form(state) elif initial.get("command"): # "custom" kind with no (recognized/available) source, or a # legacy/unrecognized item - fall back to showing the raw diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 9f50ce1..61a786b 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -153,7 +153,7 @@ def build_item_display_text(item: ScheduleItem, beamline: str | None) -> str: case _: text += ( f"Set temperature controller target setpoint to {config['target_setpoint']}" - + f" °C\nwith ramp rate of {config['rampe_rate']} {config['ramp_rate_unit']}" + + f" °C\nwith ramp rate of {config['ramp_rate']} {config['ramp_rate_unit']}" ) elif item.command.startswith("dev.abs."): action = item.form_state["action"] From 9862fb30a1b2217189dcd9409bc689256fca7466 Mon Sep 17 00:00:00 2001 From: hitz_s Date: Thu, 12 Nov 2026 14:42:37 +0100 Subject: [PATCH 55/56] feat(scheduler)!: background blocks, beamline-state gating and action registry Restructure the Scheduler widget and extend its functionality: - New schedule table: line, status, command, report, pause on failure, pause on state, wait for completion. Items running while a background item (wait_for_completion=False) is busy are indented with a guide line. - New execution loop (executor.py) supporting background items and the "Wait until parent has completed" item. - Pause on state: embed BEC's BeamlineStateManager (scan-interlock controls hidden) and gate items on all beamline states being VALID or WARNING; running gated scans are cancelled and repeated after recovery. Replaces the custom signal guard. - Replace eval of command strings with a JSON-serialisable function registry (actions.py). - Add a delay item (hours/minutes/seconds), interruptible by "Pause now". - Add wait for completion / pause on state options to the item dialog; remove the free-form "Other" page. - Remove Microsoft Teams notifications. - Fix: failures without "pause on failure" no longer stop the schedule, start/stop notifications respect the enabled flag, remote updates are no longer ignored after renaming a schedule. - Split the package into models, actions, executor, state monitor and table modules; update docstrings; add unit tests. BREAKING CHANGE: schedules are stored as action + params instead of command strings. Old schedules in Redis are logged and replaced by an empty schedule; old JSON files can no longer be loaded. The RPC methods add_item/edit_item now take action and params instead of command, kind and form_state. Co-Authored-By: Claude Opus 5.5 --- debye_bec/bec_widgets/widgets/client.py | 108 +- .../bec_widgets/widgets/scheduler/actions.py | 512 +++++ .../bec_widgets/widgets/scheduler/enums.py | 11 - .../bec_widgets/widgets/scheduler/executor.py | 442 ++++ .../bec_widgets/widgets/scheduler/guard.py | 188 -- .../widgets/scheduler/guard_dialog.py | 94 - .../widgets/scheduler/interlock_hiding.py | 102 + .../widgets/scheduler/item_dialog.py | 809 +++---- .../bec_widgets/widgets/scheduler/models.py | 170 ++ .../widgets/scheduler/notification_dialog.py | 206 +- .../widgets/scheduler/notifications.py | 171 +- .../widgets/scheduler/qt_widgets.py | 159 -- .../widgets/scheduler/schedule_item.py | 70 - .../widgets/scheduler/schedule_logic.py | 160 +- .../widgets/scheduler/schedule_table.py | 397 ++++ .../widgets/scheduler/scheduler.py | 1902 ++++++----------- .../widgets/scheduler/state_monitor.py | 190 ++ .../bec_widgets/widgets/scheduler/widgets.py | 35 + .../test_scheduler_executor.py | 284 +++ .../tests_bec_widgets/test_scheduler_logic.py | 311 +++ .../test_scheduler_state_monitor.py | 117 + 21 files changed, 3925 insertions(+), 2513 deletions(-) create mode 100644 debye_bec/bec_widgets/widgets/scheduler/actions.py delete mode 100644 debye_bec/bec_widgets/widgets/scheduler/enums.py create mode 100644 debye_bec/bec_widgets/widgets/scheduler/executor.py delete mode 100644 debye_bec/bec_widgets/widgets/scheduler/guard.py delete mode 100644 debye_bec/bec_widgets/widgets/scheduler/guard_dialog.py create mode 100644 debye_bec/bec_widgets/widgets/scheduler/interlock_hiding.py create mode 100644 debye_bec/bec_widgets/widgets/scheduler/models.py delete mode 100644 debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py delete mode 100644 debye_bec/bec_widgets/widgets/scheduler/schedule_item.py create mode 100644 debye_bec/bec_widgets/widgets/scheduler/schedule_table.py create mode 100644 debye_bec/bec_widgets/widgets/scheduler/state_monitor.py create mode 100644 debye_bec/bec_widgets/widgets/scheduler/widgets.py create mode 100644 tests/tests_bec_widgets/test_scheduler_executor.py create mode 100644 tests/tests_bec_widgets/test_scheduler_logic.py create mode 100644 tests/tests_bec_widgets/test_scheduler_state_monitor.py diff --git a/debye_bec/bec_widgets/widgets/client.py b/debye_bec/bec_widgets/widgets/client.py index 14ea1a2..af1dff4 100644 --- a/debye_bec/bec_widgets/widgets/client.py +++ b/debye_bec/bec_widgets/widgets/client.py @@ -145,103 +145,125 @@ class ScanControlXAS(RPCBase): class Scheduler(RPCBase): - """Schedule, persist and execute a sequence of BEC scan/device commands.""" + """Schedule, persist and execute a sequence of BEC actions.""" _IMPORT_MODULE = "debye_bec.bec_widgets.widgets.scheduler.scheduler" @rpc_call - def run_schedule(self, first_item: "int" = 0): + def run_schedule(self, first_item: "int" = 0, retry_unfinished: "bool" = False) -> "None": """ - Run the schedule, continuing from wherever it last left off. + Start (or continue) executing the schedule. + + Already COMPLETED items are skipped. Does nothing if the schedule is already running. + + Args: + first_item: Index of the item to start with; items above it are ignored. + retry_unfinished: If True, FAILED and ABORTED items are executed again. """ @rpc_call - def abort_schedule(self): + def pause_schedule(self) -> "None": """ - Request that the schedule stop after the current item. + Pause after the currently running item(s) have finished. """ @rpc_call - def reset_schedule(self): + def abort_schedule(self) -> "None": """ - Clear all execution state and start the schedule over from item 1. + Pause now: cancel running scans/moves, interrupt delays and stop the schedule. + """ + + @rpc_call + def reset_schedule(self) -> "None": + """ + Mark all items PENDING again and clear their execution state (not while running). """ @rpc_call def get_status(self) -> "dict": """ - RPC-exposed: current schedule state, e.g. for another widget or a script. + The complete schedule (definition and execution state) as a JSON-compatible dict. """ @rpc_call def add_item( self, - command: "str", + action: "str", + params: "dict | None" = None, index: "int | None" = None, - kind: "str" = "custom", - form_state: "dict | None" = None, + wait_for_completion: "bool" = True, pause_on_failure: "bool" = False, + pause_on_state: "bool" = False, ) -> "str": """ - RPC-exposed: insert a new, PENDING command into the schedule. - Safe to call while the schedule is running. + Insert a new PENDING item. Args: - command: command text, evaluated the same way as the existing - items (against `scans`/`dev`) once the schedule runs. - index: position to insert at (0 = first). Clamped so the item - can never land before something already running or - finished. Defaults to appending at the end. - kind/form_state: optional structured description of how - `command` was built (see `schedule_item.ScheduleItem`), - used to reopen the Edit dialog pre-filled. Leave as - defaults for a plain, hand-typed command. + action: Registered action name, e.g. "scan", "move", "delay", "wait_for_parent". + params: JSON-serialisable parameters of the action, e.g. + `{"device": "samx", "value": 1.0, "relative": False}` for "move" or + `{"seconds": 60}` for "delay". + index: Insert position (0 = first). Clamped so the item never lands before an item + that has already started. Defaults to the end. + wait_for_completion: If False, the following items start while this one runs. + pause_on_failure: Pause the schedule if this item fails. + pause_on_state: Only start while all beamline states are VALID/WARNING. Returns: - The new item's item_id. + The id of the new item. + + Raises: + ValueError: Unknown action. + TypeError: Parameters are not JSON-serialisable. """ @rpc_call def edit_item( self, item_id: "str", - command: "str", - kind: "str" = "custom", - form_state: "dict | None" = None, - pause_on_failure: "bool" = True, - ): + action: "str", + params: "dict | None" = None, + wait_for_completion: "bool" = True, + pause_on_failure: "bool" = False, + pause_on_state: "bool" = False, + ) -> "None": """ - RPC-exposed: change the command of an item that has not started - yet. Raises `RuntimeError` for an item that is already - running/finished. + Replace the definition of an item that has not started yet (see `add_item` for the + arguments). + + Raises: + RuntimeError: The item has already started or finished. """ @rpc_call - def delete_item(self, item_id: "str"): + def delete_item(self, item_id: "str") -> "None": """ - RPC-exposed: remove an item that has not started yet. Raises - `RuntimeError` for an item that is already running/finished. + Remove an item that has not started yet. + + Raises: + RuntimeError: The item has already started or finished. """ @rpc_call - def move_item(self, item_id: "str", new_index: "int"): + def move_item(self, item_id: "str", new_index: "int") -> "None": """ - RPC-exposed: move an item that has not started yet to a new - position (0 = first, but never before something already - running/finished). Raises `RuntimeError` for an item that is - already running/finished. + Move an item that has not started yet to `new_index` (never before an item that has + already started). + + Raises: + RuntimeError: The item has already started or finished. """ @rpc_call - def move_item_up(self, item_id: "str"): + def move_item_up(self, item_id: "str") -> "None": """ - RPC-exposed: swap an item with the one directly before it. + Swap an item with the one above it. """ @rpc_call - def move_item_down(self, item_id: "str"): + def move_item_down(self, item_id: "str") -> "None": """ - RPC-exposed: swap an item with the one directly after it. + Swap an item with the one below it. """ diff --git a/debye_bec/bec_widgets/widgets/scheduler/actions.py b/debye_bec/bec_widgets/widgets/scheduler/actions.py new file mode 100644 index 0000000..985e347 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/actions.py @@ -0,0 +1,512 @@ +""" +Function registry of the Scheduler widget. + +A schedule item never stores executable code. It stores the *name* of a registered action plus +JSON-serialisable parameters (`ScheduleItem.action` / `ScheduleItem.params`). At execution time +the executor looks the action up in `ACTIONS` and calls its `run` function with an +`ExecutionContext` (BEC shortcuts and beamline helpers) and the stored parameters. This replaces +the former `eval` of command strings: only registered, reviewed functions can ever be executed, +and a schedule stays saveable as plain JSON. + +Adding a new item type means: + +1. writing a `run(ctx, **params)` function (and a `describe(params, beamline)` function for the + "Command" column), +2. registering both with `register_action(ActionSpec(...))`, +3. adding a page to `item_dialog.ScheduleItemDialog` that produces the parameters. +""" + +from __future__ import annotations + +import threading +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Callable, Literal + +if TYPE_CHECKING: # pragma: no cover + from .models import ScheduleItem + +ActionCategory = Literal["scan", "move", "device", "delay", "control"] + +#: Registry key of the "Wait until parent has completed" control item. +WAIT_FOR_PARENT = "wait_for_parent" +#: Registry key of the delay item. +DELAY = "delay" + + +class ActionInterrupted(Exception): + """Raised by an action that was interrupted by an abort of the schedule.""" + + +@dataclass +class ExecutionContext: + """ + Everything an action may need at execution time. + + Attributes: + scans: BEC scan shortcut (`client.scans`). + dev: BEC device container (`client.device_manager.devices`). + digital_twin: `DigitalTwinCore` instance, if available at this beamline. + auto_gain: `AutoGainCore` instance, if available at this beamline. + beamline: Beamline name, e.g. "x01da". + abort_event: Set when the schedule is aborted or the widget is closed; long-running local + actions (e.g. delays) must return early when it is set. + """ + + scans: Any + dev: Any + digital_twin: Any = None + auto_gain: Any = None + beamline: str | None = None + abort_event: threading.Event = field(default_factory=threading.Event) + + +@dataclass(frozen=True) +class ActionSpec: + """ + Description of one registered schedule action. + + Attributes: + name: Registry key, stored in `ScheduleItem.action` (and therefore in Redis/JSON). Never + rename the key of an existing action, or saved schedules can no longer be loaded. + label: Human-readable name, e.g. for the item dialog. + category: Used for notification filtering and execution rules: + "scan" and "move" submit requests to the BEC scan server, "device" covers other + device actions and beamline tools, "delay" is a local wait and "control" items only + steer the schedule itself. + run: `run(ctx, **params) -> handle`. May block until done, or return a handle with + `wait()` (and optionally `cancel()`), e.g. a BEC `ScanReport`. `None` for control + actions, which are handled by the executor itself. + describe: `describe(params, beamline) -> str`, the text of the "Command" column. + report: Optional `report(handle, item, ctx) -> str | None`, the text of the "Report" + column after a successful execution. Defaults to `default_report`. + cancellable: True if the returned handle supports `cancel()` (e.g. scans/moves), so that + the item can be interrupted when the schedule is aborted or a beamline state trips. + """ + + name: str + label: str + category: ActionCategory + run: Callable[..., Any] | None + describe: Callable[[dict, str | None], str] + report: Callable[[Any, "ScheduleItem", ExecutionContext], str | None] | None = None + cancellable: bool = False + + +ACTIONS: dict[str, ActionSpec] = {} + + +def register_action(spec: ActionSpec) -> ActionSpec: + """ + Add an action to the registry. + + Args: + spec: The action to register. + + Returns: + The registered spec (so this can be used inline). + + Raises: + ValueError: If an action with the same name is already registered. + """ + if spec.name in ACTIONS: + raise ValueError(f"A schedule action named {spec.name!r} is already registered.") + ACTIONS[spec.name] = spec + return spec + + +def get_action(name: str) -> ActionSpec: + """ + Look up a registered action. + + Raises: + KeyError: If no action with this name is registered. + """ + try: + return ACTIONS[name] + except KeyError: + raise KeyError(f"Unknown schedule action {name!r}.") from None + + +def run_action(ctx: ExecutionContext, action: str, params: dict) -> Any: + """ + Execute a registered action - the single dispatch point used by the executor. + + Args: + ctx: Execution context. + action: Registry key of the action. + params: Keyword arguments for the action's `run` function. + + Returns: + Whatever the action returns (e.g. a `ScanReport` to wait on), or None. + + Raises: + KeyError: If the action is not registered. + ValueError: If the action is a control action that cannot be run directly. + """ + spec = get_action(action) + if spec.run is None: + raise ValueError(f"Schedule action {action!r} is handled by the executor.") + return spec.run(ctx, **params) + + +def describe_item(item: "ScheduleItem", beamline: str | None) -> str: + """ + Text for the "Command" column of an item. Never raises: an unknown action or malformed + parameters fall back to a generic representation. + """ + spec = ACTIONS.get(item.action) + if spec is None: + return f"Unknown action '{item.action}' {item.params}" + try: + return spec.describe(item.params, beamline) + except Exception: # pylint: disable=broad-except + return f"{spec.label} {item.params}" + + +def default_report(handle: Any, item: "ScheduleItem", _ctx: ExecutionContext) -> str | None: + """Fallback "Report" text: the scan number, or a short summary of a returned value.""" + if item.scan_number is not None: + return f"Scan #{item.scan_number} done" + if handle is None or hasattr(handle, "wait"): + return "Done" + text = str(handle) + return text if len(text) <= 120 else text[:117] + "..." + + +def format_duration(seconds: float) -> str: + """Format a duration as e.g. "1 h 05 min 00 s" / "2 min 30 s" / "12 s".""" + seconds = max(0, int(round(seconds))) + hours, rest = divmod(seconds, 3600) + minutes, secs = divmod(rest, 60) + if hours: + return f"{hours} h {minutes:02d} min {secs:02d} s" + if minutes: + return f"{minutes} min {secs:02d} s" + return f"{secs} s" + + +def _format_call(name: str, args: list, kwargs: dict) -> str: + parts = [repr(a) for a in args] + parts += [f"{key}={value!r}" for key, value in kwargs.items()] + return f"{name}({', '.join(parts)})" + + +# ---------------------------------------------------------------------------------------------- # +# Scan +# ---------------------------------------------------------------------------------------------- # +def _run_scan(ctx: ExecutionContext, scan_name: str, args: list | None = None, kwargs=None): + scan = getattr(ctx.scans, scan_name, None) + if scan is None or scan_name.startswith("_"): + raise ValueError(f"Scan {scan_name!r} is not available in this BEC session.") + return scan(*(args or []), **(kwargs or {})) + + +def _describe_scan(params: dict, _beamline: str | None) -> str: + scan_name = params["scan_name"] + kwargs = params.get("kwargs") or {} + if scan_name == "xas_simple_scan": + metadata = kwargs.get("metadata") or {} + return ( + f"XAS simple scan from {kwargs.get('start')} eV to {kwargs.get('stop')} eV, " + f"{kwargs.get('scan_time')} s per spectrum, measure {kwargs.get('scan_duration')} s" + f"\nComment: {metadata.get('comment', '')}, " + f"Sample Name: {metadata.get('sample_name', '')}" + ) + return _format_call(f"scans.{scan_name}", params.get("args") or [], kwargs) + + +register_action( + ActionSpec( + name="scan", + label="Scan", + category="scan", + run=_run_scan, + describe=_describe_scan, + cancellable=True, + ) +) + + +# ---------------------------------------------------------------------------------------------- # +# Move +# ---------------------------------------------------------------------------------------------- # +def _run_move(ctx: ExecutionContext, device: str, value: float, relative: bool = False, **_): + return ctx.dev[device].move(value, relative=relative) + + +def _describe_move(params: dict, _beamline: str | None) -> str: + units = params.get("units", "") + if params.get("relative"): + return f"Move {params['device']} by {params['value']:+g} {units}".rstrip() + return f"Move {params['device']} to {params['value']:g} {units}".rstrip() + + +def _report_move(_handle, item: "ScheduleItem", ctx: ExecutionContext) -> str | None: + device = item.params["device"] + try: + position = ctx.dev[device].position + return f"Moved to {position:g} {item.params.get('units', '')}".rstrip() + except Exception: # pylint: disable=broad-except + return "Done" + + +register_action( + ActionSpec( + name="move", + label="Move", + category="move", + run=_run_move, + describe=_describe_move, + report=_report_move, + cancellable=True, + ) +) + + +# ---------------------------------------------------------------------------------------------- # +# Digital twin (X01DA / X10DA) +# ---------------------------------------------------------------------------------------------- # +def _run_digital_twin(ctx: ExecutionContext, config: dict): + if ctx.digital_twin is None: + raise RuntimeError("The digital twin is not available at this beamline.") + result = ctx.digital_twin.move_with_config(config) + if isinstance(result, dict) and not result.get("success", True): + details = {key: result[key] for key in ("failures", "aborted") if result.get(key)} + raise RuntimeError(f"Beamline alignment did not complete: {details}") + + +def _describe_digital_twin(params: dict, beamline: str | None) -> str: + config = params["config"] + monochromatic = config["mo1_mode"] == "Monochromatic" + text = ( + f"Align beamline for {config['energy']:.0f} eV" + if monochromatic + else "Align beamline for pink beam" + ) + text += ( + f"\nFE: {config['h_acc'] * 1e3:.3f} mrad x {config['v_acc'] * 1e3:.3f} mrad" + f"\nCM: {config['cm_stripe']} at {config['cm_pitch'] * 1e3:.3f} mrad" + ) + if monochromatic: + text += f"\nMO1: {config['mo1_xtal']}" + text += f"\nFM: {config['fm_stripe']} at {config['fm_rotx'] * 1e3:.3f} mrad" + if beamline == "x01da": + text += f"\nES1: {config['ot_es1_trz']:.0f} mm" + text += f"\nSMPL_TRZ: {config['es1man_trz']:.3f} mm" + if beamline == "x01da": + text += f"\nSMPL-XRD: {config['smpl_to_xrd']:.3f} mm" + return text + + +register_action( + ActionSpec( + name="digital_twin", + label="Digital Twin", + category="device", + run=_run_digital_twin, + describe=_describe_digital_twin, + report=lambda *_: "Beamline aligned", + ) +) + + +# ---------------------------------------------------------------------------------------------- # +# Auto-gain (X01DA / X10DA) +# ---------------------------------------------------------------------------------------------- # +def _run_auto_gain(ctx: ExecutionContext, config: dict): + if ctx.auto_gain is None: + raise RuntimeError("Auto-gain is not available at this beamline.") + return ctx.auto_gain.start( + element=config["element"], + edge=config["edge"], + amplifier=config["all_amplifiers"], + link_ic0_ic1=config["link_ic0_ic1"], + comp_ring_current=config["compensate_ring_current"], + prohibited_gains=config["prohibited_gains"], + ) + + +def _describe_auto_gain(params: dict, _beamline: str | None) -> str: + config = params["config"] + text = f"Auto-configure gains for {config['element']}, {config['edge']}-edge" + text += f"\nfor devices {config['all_amplifiers']}" + if config["link_ic0_ic1"]: + text += "\nLink IC0 and IC1 gains" + if config["compensate_ring_current"]: + text += "\nCalculate for 400 mA ring current" + if config["prohibited_gains"]: + prohibited = ", ".join( + f"{amp}: [" + ", ".join(f"{gain:.0e}" for gain in gains) + "]" + for amp, gains in config["prohibited_gains"].items() + ) + text += f"\nProhibited gains: {{{prohibited}}}" + return text + + +def _report_auto_gain(handle, _item, _ctx) -> str | None: + if isinstance(handle, dict) and handle: + return "Gains: " + ", ".join( + f"{key}={value:.0e}" if isinstance(value, (int, float)) else f"{key}={value}" + for key, value in handle.items() + ) + return "Done" + + +register_action( + ActionSpec( + name="auto_gain", + label="Auto Gain", + category="device", + run=_run_auto_gain, + describe=_describe_auto_gain, + report=_report_auto_gain, + ) +) + + +# ---------------------------------------------------------------------------------------------- # +# Absorber +# ---------------------------------------------------------------------------------------------- # +ABSORBER_ACTIONS = ("Open", "Force open", "Close") + + +def _run_absorber(ctx: ExecutionContext, action: str): + absorber = ctx.dev["abs"] + if action == "Open": + return absorber.open() + if action == "Force open": + return absorber.open(force=True) + if action == "Close": + return absorber.close() + raise ValueError(f"Unknown absorber action {action!r}.") + + +register_action( + ActionSpec( + name="absorber", + label="Absorber", + category="device", + run=_run_absorber, + describe=lambda params, _bl: f"{params['action']} absorber", + ) +) + + +# ---------------------------------------------------------------------------------------------- # +# Ionization chamber gas filling +# ---------------------------------------------------------------------------------------------- # +def _run_ic_fill( + ctx: ExecutionContext, + chamber: str, + gas1: str, + conc1: float, + gas2: str, + conc2: float, + pressure: float, +): + return ctx.dev[chamber.lower()].fill( + gas1=gas1, conc1=conc1, gas2=gas2, conc2=conc2, pressure=pressure, wait=True + ) + + +register_action( + ActionSpec( + name="ic_fill", + label="Ionization Chamber", + category="device", + run=_run_ic_fill, + describe=lambda p, _bl: ( + f"Fill {p['chamber']} with {p['conc1']:g} % {p['gas1']} and {p['conc2']:g} % " + f"{p['gas2']} to {p['pressure']:g} bar" + ), + ) +) + + +# ---------------------------------------------------------------------------------------------- # +# Reference foil changer +# ---------------------------------------------------------------------------------------------- # +def _run_reffoil(ctx: ExecutionContext, foil: str): + return ctx.dev["reffoilchanger"].insert(ref=foil, wait=True) + + +register_action( + ActionSpec( + name="reffoil", + label="Reference foil changer", + category="device", + run=_run_reffoil, + describe=lambda params, _bl: f"Insert {params['foil']} reference foil", + ) +) + + +# ---------------------------------------------------------------------------------------------- # +# Temperature controller +# ---------------------------------------------------------------------------------------------- # +def _run_temperature_controller(ctx: ExecutionContext, config: dict): + return ctx.dev["univ_temp_cont"].load_config(config=config) + + +def _describe_temperature_controller(params: dict, _beamline: str | None) -> str: + config = params["config"] + match config["power_mode"]: + case "Standby": + return "Switch temperature controller to standby" + case "Configuration": + return "Switch temperature controller to configuration mode" + case _: + return ( + f"Set temperature controller to {config['target_setpoint']} °C" + f"\nwith ramp rate of {config['ramp_rate']} {config['ramp_rate_unit']}" + ) + + +register_action( + ActionSpec( + name="temperature_controller", + label="Temperature Controller", + category="device", + run=_run_temperature_controller, + describe=_describe_temperature_controller, + ) +) + + +# ---------------------------------------------------------------------------------------------- # +# Delay +# ---------------------------------------------------------------------------------------------- # +def _run_delay(ctx: ExecutionContext, seconds: float): + # Event.wait instead of time.sleep, so that aborting the schedule interrupts the delay. + if ctx.abort_event.wait(timeout=max(0.0, float(seconds))): + raise ActionInterrupted("Delay interrupted.") + + +register_action( + ActionSpec( + name=DELAY, + label="Delay", + category="delay", + run=_run_delay, + describe=lambda params, _bl: f"Delay for {format_duration(params['seconds'])}", + report=lambda _h, item, _c: f"Waited {format_duration(item.params['seconds'])}", + ) +) + + +# ---------------------------------------------------------------------------------------------- # +# Wait until parent has completed (control item, executed by the executor itself) +# ---------------------------------------------------------------------------------------------- # +register_action( + ActionSpec( + name=WAIT_FOR_PARENT, + label="Wait until parent has completed", + category="control", + run=None, + describe=lambda _params, _bl: "Wait until parent has completed", + report=lambda *_: "Parent completed", + ) +) + +#: Actions that always block until done; "wait for completion" cannot be switched off for them. +ALWAYS_WAIT_ACTIONS = frozenset({DELAY, WAIT_FOR_PARENT}) diff --git a/debye_bec/bec_widgets/widgets/scheduler/enums.py b/debye_bec/bec_widgets/widgets/scheduler/enums.py deleted file mode 100644 index 71bc706..0000000 --- a/debye_bec/bec_widgets/widgets/scheduler/enums.py +++ /dev/null @@ -1,11 +0,0 @@ -from __future__ import annotations - -from enum import Enum - - -class ScheduleItemStatus(str, Enum): - PENDING = "pending" - RUNNING = "running" - COMPLETED = "completed" - FAILED = "failed" - ABORTED = "aborted" diff --git a/debye_bec/bec_widgets/widgets/scheduler/executor.py b/debye_bec/bec_widgets/widgets/scheduler/executor.py new file mode 100644 index 0000000..614df3b --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/executor.py @@ -0,0 +1,442 @@ +""" +Execution engine of the Scheduler widget. + +`ScheduleExecutor.run` is executed on a worker thread (started by the widget through +`BECWidget.submit_task`). It never touches Qt widgets: all state changes are written to the +shared `Schedule` under the widget's lock, persisted to Redis through `persist_locked`, and the +GUI is told to redraw through `emit_changed` (which emits a Qt signal, marshalled onto the GUI +thread). + +Execution rules +--------------- +- Items run top to bottom. The next item is re-derived after every step + (`schedule_logic.pick_next_runnable`), so PENDING items can be added, edited, moved or deleted + while the schedule runs. +- `wait_for_completion=True` (default): the item is run and waited for before continuing. +- `wait_for_completion=False` ("background item"): the item is started on its own thread and the + schedule continues with the items of its block (see `schedule_logic`). Before an item outside + that block starts, and at a "Wait until parent has completed" item, the executor waits for the + background item to complete. Children keep running if the parent finishes first. +- `pause_on_state=True`: before the item starts, the executor waits until all beamline states + are VALID or WARNING. If a state turns INVALID while such an item is a running scan, the scan + is cancelled, the item is reset to PENDING and repeated once the states have recovered. Other + item types are not interrupted. +- `pause_on_failure=True`: a failure of the item pauses the schedule after the current step; + otherwise the schedule continues with the next item. +- "Pause after current item" lets running items finish; "Pause now" (abort) additionally cancels + running scans/moves and interrupts delays. +- Closing the widget stops the loop without cancelling anything server-side; the widget + reconciles the persisted state with the BEC queue when it is opened again. +""" + +from __future__ import annotations + +import threading +import time +import traceback +from dataclasses import dataclass, field +from typing import Any, Callable, Literal + +from bec_lib.logger import bec_logger + +from .actions import ( + WAIT_FOR_PARENT, + ActionInterrupted, + ActionSpec, + ExecutionContext, + default_report, + get_action, + run_action, +) +from .models import ItemStatus, ScheduleItem +from .schedule_logic import block_parents, index_of, pick_next_runnable + +logger = bec_logger.logger + +RunOutcome = Literal["finished", "aborted", "paused", "paused_on_failure", "widget_closed"] + +_ACTIVE_QUEUE_STATES = ("PENDING", "RUNNING") +_POLL_INTERVAL = 0.2 + + +def is_queue_item_active(queue_item: Any) -> bool: + """True if a BEC queue item is still pending or running server-side.""" + return str(getattr(queue_item, "status", "")).upper() in _ACTIVE_QUEUE_STATES + + +@dataclass +class _Execution: + """Bookkeeping of one item that is currently being executed.""" + + item: ScheduleItem + spec: ActionSpec + handle: Any = None + interrupted: bool = False # cancelled because a beamline state tripped -> repeat later + done: threading.Event = field(default_factory=threading.Event) + + +class ScheduleExecutor: + """ + Runs the items of a schedule (see the module docstring for the rules). + + Args: + lock: The widget's lock guarding the schedule. + get_items: Returns the live list of schedule items. Only called while holding `lock`. + persist_locked: Writes the schedule to Redis; only called while holding `lock`. + emit_changed: Thread-safe "please redraw" callback. + context: Execution context handed to the registered actions. + state_monitor: Object with `is_ok()`, `wait_until_ok(should_abort)` and + `blocking_states()` (normally a `BeamlineStateMonitor`). + notify_item: Called (without lock) with an item after it COMPLETED, FAILED or ABORTED. + get_queue_storage: Returns BEC's queue storage; used to re-attach to requests that are + still running from a previous widget session. + closing: Set by the widget when it is being closed. + """ + + def __init__( + self, + *, + lock: threading.Lock, + get_items: Callable[[], list[ScheduleItem]], + persist_locked: Callable[[], None], + emit_changed: Callable[[], None], + context: ExecutionContext, + state_monitor: Any, + notify_item: Callable[[ScheduleItem], None], + get_queue_storage: Callable[[], Any], + closing: threading.Event, + ) -> None: + self._lock = lock + self._get_items = get_items + self._persist_locked = persist_locked + self._emit_changed = emit_changed + self._ctx = context + self._state_monitor = state_monitor + self._notify_item = notify_item + self._get_queue_storage = get_queue_storage + self._closing = closing + + self._abort = threading.Event() + self._pause = threading.Event() + self._paused_on_failure = False + self._foreground: _Execution | None = None + self._background: _Execution | None = None + self._attempted: set[str] = set() + + # ------------------------------------------------------------------------------------------ # + # Control (called from the GUI thread) + # ------------------------------------------------------------------------------------------ # + def request_pause(self) -> None: + """Stop after the running item(s) have finished ("Pause after current item").""" + self._pause.set() + + def request_abort(self) -> None: + """Stop now: cancel running scans/moves and interrupt delays ("Pause now").""" + self._abort.set() + self._ctx.abort_event.set() + for execution in (self._foreground, self._background): + if execution is not None and not execution.done.is_set(): + self._cancel(execution) + + def notify_closing(self) -> None: + """The widget is closing: interrupt local waits, but do not cancel server-side work.""" + self._ctx.abort_event.set() + + def on_states_tripped(self) -> None: + """ + A beamline state became INVALID: cancel running scans that have `pause_on_state` set. + They are reset to PENDING and repeated once the states have recovered. + """ + for execution in (self._foreground, self._background): + if execution is None or execution.done.is_set(): + continue + if not (execution.item.pause_on_state and execution.spec.cancellable): + continue + if execution.spec.category != "scan": + continue + logger.info(f"Beamline state tripped: interrupting scan item {execution.item.item_id}") + execution.interrupted = True + self._cancel(execution) + + def active_item_ids(self) -> set[str]: + """Ids of the items currently executed by this executor.""" + return { + execution.item.item_id + for execution in (self._foreground, self._background) + if execution is not None and not execution.done.is_set() + } + + # ------------------------------------------------------------------------------------------ # + # Main loop (worker thread) + # ------------------------------------------------------------------------------------------ # + def run(self, first_item_id: str | None = None, retry_unfinished: bool = False) -> RunOutcome: + """ + Execute the schedule until it is finished, paused, aborted or the widget is closed. + + Args: + first_item_id: Start with this item; items above it are ignored. None starts at the + top (already COMPLETED items are always skipped). + retry_unfinished: Run FAILED and ABORTED items again (once each). + + Returns: + Why the run ended. + """ + self._abort.clear() + self._pause.clear() + self._ctx.abort_event.clear() + self._paused_on_failure = False + self._attempted = set() + self._background = None + self._foreground = None + + outcome: RunOutcome = "finished" + while True: + outcome = self._stop_reason() + if outcome != "finished": + break + if self._background is not None and self._background.done.is_set(): + self._background = None + + with self._lock: + items = self._get_items() + first_index = index_of(items, first_item_id) or 0 + item = pick_next_runnable( + items, + retry_unfinished=retry_unfinished, + first_index=first_index, + active_ids=self.active_item_ids(), + attempted_ids=self._attempted, + ) + in_background_block = False + if item is not None and self._background is not None: + parent = block_parents(items)[index_of(items, item.item_id)] + in_background_block = ( + parent is not None + and items[parent].item_id == self._background.item.item_id + ) + + if item is None: + break + if self._background is not None and not in_background_block: + # Leaving the block of the running background item: wait for it first. + self._join_background() + continue + if item.status == ItemStatus.RUNNING: + self._reattach(item) + continue + if item.action == WAIT_FOR_PARENT: + self._run_wait_for_parent(item) + continue + if item.pause_on_state and not self._wait_for_states(item): + continue + + execution = self._start(item) + if item.wait_for_completion: + self._foreground = execution + self._execute(execution) + self._foreground = None + else: + self._background = execution + threading.Thread( + target=self._execute, + args=(execution,), + name=f"scheduler-background-{item.item_id}", + daemon=True, + ).start() + + if outcome != "widget_closed": + self._join_background() + if self._closing.is_set(): + return "widget_closed" + if outcome == "finished": + # The loop may also have ended because a pause/abort happened while joining. + outcome = self._stop_reason() + return outcome + + def _stop_reason(self) -> RunOutcome: + if self._closing.is_set(): + return "widget_closed" + if self._abort.is_set(): + return "aborted" + if self._pause.is_set(): + return "paused_on_failure" if self._paused_on_failure else "paused" + return "finished" + + def _should_stop_waiting(self) -> bool: + return self._closing.is_set() or self._abort.is_set() or self._pause.is_set() + + # ------------------------------------------------------------------------------------------ # + # Steps + # ------------------------------------------------------------------------------------------ # + def _start(self, item: ScheduleItem) -> _Execution: + spec = get_action(item.action) + with self._lock: + item.reset_execution() + item.status = ItemStatus.RUNNING + item.started_at = time.time() + self._attempted.add(item.item_id) + self._persist_locked() + self._emit_changed() + return _Execution(item=item, spec=spec) + + def _execute(self, execution: _Execution) -> None: + """Run one item to completion and record the outcome. Runs on a worker thread.""" + item, spec = execution.item, execution.spec + final_status: ItemStatus | None = None + try: + handle = run_action(self._ctx, item.action, item.params) + execution.handle = handle + request_id = getattr(getattr(handle, "request", None), "requestID", None) + if request_id is not None: + with self._lock: + item.request_id = request_id + self._persist_locked() + if execution.interrupted or self._abort.is_set(): + self._cancel(execution) + wait = getattr(handle, "wait", None) + if callable(wait): + wait() + if self._closing.is_set(): + return # leave RUNNING; reconciled when the widget is opened again + + scan_id, scan_number = _scan_info(handle) if request_id else (None, None) + with self._lock: + item.scan_id, item.scan_number = scan_id, scan_number + if execution.interrupted: + self._requeue(item) + elif self._abort.is_set() and spec.cancellable: + with self._lock: + item.status = ItemStatus.ABORTED + item.report = "Aborted" + else: + report = (spec.report or default_report)(handle, item, self._ctx) + with self._lock: + item.status = ItemStatus.COMPLETED + item.report = report + except Exception as exc: # pylint: disable=broad-except + if self._closing.is_set(): + return + if execution.interrupted: + self._requeue(item) + elif self._abort.is_set() or isinstance(exc, ActionInterrupted): + with self._lock: + item.status = ItemStatus.ABORTED + item.report = "Aborted" + else: + error = traceback.format_exc() + logger.error(f"Schedule item {item.action} {item.params} failed:\n{error}") + with self._lock: + item.status = ItemStatus.FAILED + item.error = error + item.report = _last_line(error) + if item.pause_on_failure: + self._paused_on_failure = True + self._pause.set() + finally: + if not self._closing.is_set(): + with self._lock: + if item.status != ItemStatus.PENDING: + item.finished_at = time.time() + final_status = item.status + self._persist_locked() + execution.done.set() + self._emit_changed() + + if final_status in (ItemStatus.COMPLETED, ItemStatus.FAILED, ItemStatus.ABORTED): + self._notify_item(item) + + def _requeue(self, item: ScheduleItem) -> None: + with self._lock: + item.reset_execution() + item.report = "Interrupted by beamline state, will be repeated" + logger.info(f"Schedule item {item.item_id} re-queued after beamline state trip") + + def _run_wait_for_parent(self, item: ScheduleItem) -> None: + self._start(item) + self._join_background() + if self._closing.is_set(): + return + with self._lock: + if self._abort.is_set(): + item.status = ItemStatus.ABORTED + item.report = "Aborted" + else: + item.status = ItemStatus.COMPLETED + item.report = get_action(WAIT_FOR_PARENT).report(None, item, self._ctx) + item.finished_at = time.time() + self._persist_locked() + self._emit_changed() + + def _join_background(self) -> None: + """Wait until the running background item (if any) has finished.""" + execution = self._background + if execution is None: + return + while not execution.done.wait(timeout=_POLL_INTERVAL): + if self._closing.is_set(): + return + self._background = None + + def _wait_for_states(self, item: ScheduleItem) -> bool: + """Wait until all beamline states are OK. False if paused/aborted/closed meanwhile.""" + if self._state_monitor.is_ok(): + return True + with self._lock: + blocking = ", ".join(self._state_monitor.blocking_states()) + item.report = f"Waiting for beamline states: {blocking}" + self._persist_locked() + self._emit_changed() + ok = self._state_monitor.wait_until_ok(should_abort=self._should_stop_waiting) + with self._lock: + item.report = None + self._persist_locked() + self._emit_changed() + return ok + + def _reattach(self, item: ScheduleItem) -> None: + """Follow a request that is still RUNNING from a previous widget session.""" + if not item.request_id: + with self._lock: + item.status = ItemStatus.ABORTED + item.report = "Interrupted (widget was closed)" + item.finished_at = time.time() + self._persist_locked() + self._emit_changed() + return + queue_storage = self._get_queue_storage() + while not self._should_stop_waiting(): + queue_item = queue_storage.find_queue_item_by_requestID(item.request_id) + if queue_item is None or not is_queue_item_active(queue_item): + with self._lock: + item.status = ItemStatus.COMPLETED + item.report = item.report or "Done" + item.finished_at = time.time() + self._persist_locked() + self._emit_changed() + return + time.sleep(0.5) + + @staticmethod + def _cancel(execution: _Execution) -> None: + cancel = getattr(execution.handle, "cancel", None) + if not callable(cancel): + return + try: + cancel() + except Exception: # pylint: disable=broad-except + logger.exception(f"Failed to cancel schedule item {execution.item.item_id}") + + +def _scan_info(handle: Any) -> tuple[str | None, int | None]: + try: + scan = handle.scan + except Exception: # pylint: disable=broad-except + return None, None + if scan is None: + return None, None + return getattr(scan, "scan_id", None), getattr(scan, "scan_number", None) + + +def _last_line(text: str) -> str: + lines = text.strip().splitlines() + return lines[-1] if lines else text diff --git a/debye_bec/bec_widgets/widgets/scheduler/guard.py b/debye_bec/bec_widgets/widgets/scheduler/guard.py deleted file mode 100644 index 2f0dd11..0000000 --- a/debye_bec/bec_widgets/widgets/scheduler/guard.py +++ /dev/null @@ -1,188 +0,0 @@ -""" -A small, self-contained utility for "if signal X drops below A, pause; once -it's back above B, resume" (hysteresis) behavior - e.g. auto-pausing scans -while the beam current is too low. - -This module knows nothing about schedules, scans, or the rest of this -plugin. It only monitors one BEC device's live readback value -(`MessageEndpoints.device_readback`, the same endpoint the device server -publishes for every monitored device) and emits Qt signals when the value -crosses one of the two configured thresholds. `schedule_widget.py` is the -only place that connects those signals to schedule-specific behavior -(aborting/deferring a scan item) - see its module docstring for how. -""" - -from __future__ import annotations - -import threading -import time - -from bec_lib.endpoints import MessageEndpoints -from bec_lib.logger import bec_logger -from pydantic import BaseModel -from qtpy.QtCore import QObject, Signal - -logger = bec_logger.logger - -MIN_UPDATE_INTERVAL = 1 - - -class GuardSettings(BaseModel): - """Persisted configuration for one `SignalGuard`.""" - - enabled: bool = False - device_name: str | None = None - pause_below: float | None = None - resume_above: float | None = None - - -class SignalGuard(QObject): - """ - Monitors one device's readback value and reports hysteresis-based - pause/resume crossings. - - - `paused` fires the first time the value drops below `pause_below` - (not again while it stays low). - - `resumed` fires the first time it then climbs back above - `resume_above` (not again while it stays high). - A value sitting between the two thresholds never re-triggers either - signal - that gap is the point of using two thresholds instead of one, - so a value oscillating right at a single cutoff wouldn't cause rapid - pause/resume flapping. - - Callbacks from `RedisConnector.register()` run on a background - (Redis-listener) thread, not the Qt GUI thread; `paused`/`resumed` are - Qt signals, so connecting to them with the default (auto) connection - type safely marshals delivery onto whatever thread the receiver lives - on - no extra locking needed on the receiving end. - """ - - value_update = Signal(float) - paused = Signal(float) - resumed = Signal(float) - - def __init__(self, connector, parent=None, dev=None): - super().__init__(parent) - self.dev = dev - self._connector = connector - self._lock = threading.Lock() - self._clear_event = threading.Event() - self._clear_event.set() # not blocking until configured/proven otherwise - - self.enabled = False - self.device_name: str | None = None - self.pause_below: float | None = None - self.resume_above: float | None = None - self.current_value: float | None = None - self.units: str = "" - self.prec: int = 3 - - self._subscribed_endpoint = None - - self.last_val_update = time.time() - - def configure(self, settings: GuardSettings): - """(Re)configure and (re)subscribe. Safe to call repeatedly, e.g. after editing settings.""" - self._unsubscribe() - - self.enabled = settings.enabled - self.device_name = settings.device_name - self.pause_below = settings.pause_below - self.resume_above = settings.resume_above - self.current_value = None - self._clear_event.set() - - if ( - self.enabled - and self.device_name - and self.pause_below is not None - and self.resume_above is not None - ): - self._subscribed_endpoint = MessageEndpoints.device_readback(self.device_name) - self._connector.register(topics=self._subscribed_endpoint, cb=self._on_readback) - description = self.dev[self.device_name].describe()[self.device_name] - self.units = description["units"] - self.prec = description["precision"] - - def _unsubscribe(self): - if self._subscribed_endpoint is not None: - try: - self._connector.unregister(topics=self._subscribed_endpoint, cb=self._on_readback) - except Exception: # pylint: disable=broad-except - logger.exception( - f"Failed to unsubscribe SignalGuard from {self._subscribed_endpoint}" - ) - self._subscribed_endpoint = None - - def _on_readback(self, msg): - device_msg = getattr(msg, "value", None) - if device_msg is None: - return - value = _extract_value(device_msg, self.device_name) - if value is None: - return - - crossed_pause = crossed_resume = False - with self._lock: - self.current_value = value - if self._clear_event.is_set(): - if value < self.pause_below: - self._clear_event.clear() - crossed_pause = True - elif value > self.resume_above: - self._clear_event.set() - crossed_resume = True - - if crossed_pause: - logger.info( - f"SignalGuard: {self.device_name} dropped to {value} (below {self.pause_below}) - pausing." - ) - self.paused.emit(value) - elif crossed_resume: - logger.info( - f"SignalGuard: {self.device_name} recovered to {value} (above {self.resume_above}) - resuming." - ) - self.resumed.emit(value) - - current_time = time.time() - if current_time - self.last_val_update > MIN_UPDATE_INTERVAL: - self.last_val_update = current_time - self.value_update.emit(value) - - def is_clear(self) -> bool: - """True if not currently blocking (disabled, or value above the resume threshold).""" - return (not self.enabled) or self._clear_event.is_set() - - def wait_until_clear(self, should_abort, poll_interval: float = 0.5) -> bool: - """ - Blocks the calling (non-GUI) thread until `is_clear()` becomes - True, checking `should_abort()` between polls so an operator abort - can still interrupt the wait. Returns True if it cleared, False if - `should_abort()` returned True first. - """ - if self.is_clear(): - return True - while not should_abort(): - if self._clear_event.wait(timeout=poll_interval): - return True - return False - - def cleanup(self): - self._unsubscribe() - - -def _extract_value(device_msg, device_name: str | None): - """ - `DeviceMessage.signals` is keyed by signal name, e.g. {"beam_current": - {"value": ..., "timestamp": ...}, ...}. For a simple scalar device the - primary signal is usually named after the device itself; fall back to - the first signal found if not (e.g. a differently-named primary signal - on a compound device). - """ - signals = getattr(device_msg, "signals", None) or {} - if device_name in signals: - return signals[device_name].get("value") - for signal in signals.values(): - if "value" in signal: - return signal["value"] - return None diff --git a/debye_bec/bec_widgets/widgets/scheduler/guard_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/guard_dialog.py deleted file mode 100644 index 3a7654f..0000000 --- a/debye_bec/bec_widgets/widgets/scheduler/guard_dialog.py +++ /dev/null @@ -1,94 +0,0 @@ -"""Small settings dialog for `guard.GuardSettings` - kept separate from the guard logic itself.""" - -from __future__ import annotations - -from qtpy.QtWidgets import ( - QCheckBox, - QComboBox, - QDialog, - QDialogButtonBox, - QDoubleSpinBox, - QFormLayout, - QLabel, - QMessageBox, - QVBoxLayout, -) - -from .guard import GuardSettings - -_DSPIN_RANGE = (-1e12, 1e12) - - -class GuardSettingsDialog(QDialog): - """Configure (or disable) the auto-pause/resume guard for scan items.""" - - def __init__(self, settings: GuardSettings, device_names: list[str], parent=None): - super().__init__(parent) - self.setWindowTitle("Auto-pause on signal") - - layout = QVBoxLayout(self) - info_label = QLabel( - "If enabled, the currently running scan is aborted as soon as the chosen " - "signal drops below the pause value, and automatically restarted once it " - "rises back above the resume value. Only scan items are affected - device " - "moves and custom/RPC commands are never interrupted by this." - ) - info_label.setWordWrap(True) - layout.addWidget(info_label) - - form = QFormLayout() - layout.addLayout(form) - - self.enabled_check = QCheckBox("Enable auto-pause") - self.enabled_check.setChecked(settings.enabled) - form.addRow("", self.enabled_check) - - self.device_combo = QComboBox() - self.device_combo.addItems(device_names) - if settings.device_name: - idx = self.device_combo.findText(settings.device_name) - if idx >= 0: - self.device_combo.setCurrentIndex(idx) - form.addRow("Signal (device)", self.device_combo) - - self.pause_below_spin = QDoubleSpinBox() - self.pause_below_spin.setDecimals(4) - self.pause_below_spin.setRange(*_DSPIN_RANGE) - if settings.pause_below is not None: - self.pause_below_spin.setValue(settings.pause_below) - form.addRow("Pause below", self.pause_below_spin) - - self.resume_above_spin = QDoubleSpinBox() - self.resume_above_spin.setDecimals(4) - self.resume_above_spin.setRange(*_DSPIN_RANGE) - if settings.resume_above is not None: - self.resume_above_spin.setValue(settings.resume_above) - form.addRow("Resume above", self.resume_above_spin) - - buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) - buttons.accepted.connect(self._on_accept) - buttons.rejected.connect(self.reject) - layout.addWidget(buttons) - - def _on_accept(self): - if self.enabled_check.isChecked(): - if not self.device_combo.currentText(): - QMessageBox.warning(self, "Missing input", "Select a device to monitor.") - return - if self.resume_above_spin.value() <= self.pause_below_spin.value(): - QMessageBox.warning( - self, - "Invalid thresholds", - "'Resume above' must be greater than 'Pause below' (hysteresis gap).", - ) - return - self.accept() - - def result_settings(self) -> GuardSettings: - """Valid after `exec_()` returns `QDialog.Accepted`.""" - return GuardSettings( - enabled=self.enabled_check.isChecked(), - device_name=self.device_combo.currentText() or None, - pause_below=self.pause_below_spin.value(), - resume_above=self.resume_above_spin.value(), - ) diff --git a/debye_bec/bec_widgets/widgets/scheduler/interlock_hiding.py b/debye_bec/bec_widgets/widgets/scheduler/interlock_hiding.py new file mode 100644 index 0000000..655be6a --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/interlock_hiding.py @@ -0,0 +1,102 @@ +""" +Hide the scan-interlock controls of BEC's stock `BeamlineStateManager`. + +The Scheduler embeds `bec_widgets`' own `BeamlineStateManager` unchanged, so that beamline states +are created, edited and removed exactly as everywhere else in BEC. The Scheduler, however, pauses +its items based on the states itself ("pause on state") and does not use the BEC scan interlock. +To avoid confusion, the interlock-related controls are hidden: + +- the "Scan interlock" toggle in the manager's toolbar, and +- the per-state "watched by scan interlock" lock button (and the interlock-only "Trigger + ScanInterlock on WARNING state" checkbox in the state's settings panel). + +There is no public API for this, so this module touches private attributes of +`BeamlineStateManager` / `BeamlineStatePill`. It is deliberately kept in one place and fails +soft: if `bec_widgets` renames those attributes, the controls simply stay visible and a warning +is logged. +""" + +from __future__ import annotations + +from bec_lib.logger import bec_logger +from bec_widgets.widgets.services.beamline_states.beamline_state_manager import BeamlineStateManager + +# pylint: disable=no-name-in-module # qtpy re-exports are not visible to pylint +from qtpy.QtCore import QTimer + +logger = bec_logger.logger + +_TOOLBAR_ACTIONS = ("scan_interlock", "scan_interlock_spacer") +_PILL_WIDGETS = ("_interlock_button", "_interlock_warning_checkbox") + + +def hide_scan_interlock_controls(manager: BeamlineStateManager) -> None: + """ + Hide the scan-interlock controls of `manager` once. + + Pills are created lazily, so use `install_scan_interlock_hiding` to keep them hidden. + """ + toolbar = getattr(manager, "_toolbar", None) + for name in _TOOLBAR_ACTIONS: + try: + action = toolbar.components.get_action(name).action + action.setVisible(False) + _hide_toolbar_entry_of(toolbar, action) + except Exception: # pylint: disable=broad-except + logger.warning( + f"Scheduler: could not hide BeamlineStateManager toolbar action {name!r}" + ) + try: + toolbar.update_separators() # drop the separator left in front of the hidden button + except Exception: # pylint: disable=broad-except + pass + + for pill in list(getattr(manager, "_state_pills", {}).values()): + for attr in _PILL_WIDGETS: + widget = getattr(pill, attr, None) + if widget is None: + logger.warning(f"Scheduler: BeamlineStatePill has no attribute {attr!r} to hide") + continue + widget.setVisible(False) + + +def _hide_toolbar_entry_of(toolbar, action) -> None: + """ + Hide the toolbar entry that displays `action`. + + Actions with a text label are not added to the toolbar directly: the toolbar holds a + `QToolButton` (with `action` as its default action, or the widget itself for widget actions) + wrapped in its own `QWidgetAction`. That wrapper must be hidden for the button to disappear. + """ + for entry in toolbar.actions(): + widget = toolbar.widgetForAction(entry) + if widget is None: + continue + default_action = getattr(widget, "defaultAction", lambda: None)() + if widget is action or default_action is action: + entry.setVisible(False) + + +def install_scan_interlock_hiding(manager: BeamlineStateManager) -> None: + """ + Hide the scan-interlock controls now and every time the manager (re)creates state pills. + + Pills are persistent editors of the manager's list model, created when rows are inserted; + hiding is therefore deferred to the next event-loop iteration, after the editors exist. + """ + + def _schedule_hide(*_): + QTimer.singleShot(0, manager, lambda: hide_scan_interlock_controls(manager)) + + model = getattr(manager, "_model", None) + if model is None: + logger.warning( + "Scheduler: BeamlineStateManager has no '_model'; interlock hiding is partial" + ) + else: + model.rowsInserted.connect(_schedule_hide) + model.modelReset.connect(_schedule_hide) + model.layoutChanged.connect(_schedule_hide) + model.dataChanged.connect(_schedule_hide) + hide_scan_interlock_controls(manager) + _schedule_hide() diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index 57a9166..230f173 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -1,10 +1,19 @@ """ -The dialog behind the schedule widget's "Add..."/"Edit..." buttons. +Dialog behind the Scheduler's "Add" and "Edit" buttons. + +Each item type has one page. A page collects the *parameters* of a registered action (see +`actions.py`) - it never builds executable code. The dialog's result is a dict + + {"action": str, "params": dict, "wait_for_completion": bool, + "pause_on_failure": bool, "pause_on_state": bool} + +which maps 1:1 onto `ScheduleItem` fields. """ from __future__ import annotations import math +from typing import Callable from bec_lib.logger import bec_logger from bec_widgets.widgets.control.device_input.device_combobox.device_combobox import ( @@ -13,7 +22,7 @@ from bec_widgets.widgets.control.device_input.device_combobox.device_combobox im ) from bec_widgets.widgets.control.scan_control.scan_control import ScanControl, ScanParameterConfig -# pylint: disable=E0611 +# pylint: disable=no-name-in-module # qtpy re-exports are not visible to pylint from qtpy.QtWidgets import ( QCheckBox, QComboBox, @@ -23,26 +32,45 @@ from qtpy.QtWidgets import ( QFormLayout, QHBoxLayout, QLabel, - QLineEdit, QMessageBox, QScrollArea, + QSpinBox, QStackedWidget, QVBoxLayout, QWidget, ) -from .qt_widgets import MyButton +from .actions import ABSORBER_ACTIONS, ALWAYS_WAIT_ACTIONS, DELAY, WAIT_FOR_PARENT logger = bec_logger.logger -# Beamlines that get the XAS scan control, the Digital Twin item, and the -# beamline-specific quick-fill items (Absorber, Ionization Chamber, -# Reference foil changer, Auto-Gain). -_XAS_BEAMLINES = ("x01da", "x10da") +# UI widgets are created in the _build_* helpers called from __init__. +# pylint: disable=attribute-defined-outside-init + +#: Beamlines with the XAS scan control and the beamline-specific items (Digital Twin, Absorber, +#: Ionization Chamber, Reference foil changer, Auto Gain, Temperature Controller). +XAS_BEAMLINES = ("x01da", "x10da") + + +def _hint(text: str) -> QLabel: + label = QLabel(text) + label.setWordWrap(True) + label.setStyleSheet("color: gray;") + return label class ScheduleItemDialog(QDialog): - """Add or edit one schedule item, via ScanControl, a move form, Digital Twin, or free text.""" + """ + Add or edit one schedule item. + + Args: + scans: BEC scans shortcut. + dev: BEC device container. + parent: Parent widget. + initial: An existing item's `ScheduleItem.definition()` to edit; None to add a new item. + client: BEC client (passed to embedded BEC widgets). + beamline: Beamline name; enables the beamline-specific pages at X01DA/X10DA. + """ def __init__( self, @@ -54,325 +82,285 @@ class ScheduleItemDialog(QDialog): beamline: str | None = None, ): super().__init__(parent) - self.setWindowTitle("Schedule item") + self.setWindowTitle("Edit schedule item" if initial else "Add schedule item") self.setMinimumSize(520, 480) self._scans = scans self._dev = dev self._client = client - + self._result: dict | None = None self.beamline = beamline - self._is_xas_beamline = self.beamline in _XAS_BEAMLINES + self._is_xas_beamline = beamline in XAS_BEAMLINES + + # action key -> collect() returning params / prefill(params) + self._collectors: dict[str, Callable[[], dict]] = {} + self._prefillers: dict[str, Callable[[dict], None]] = {} if self._is_xas_beamline: - logger.info(f"Loading bl-specific modules for beamline {self.beamline}") - from ....bec_ipython_client.plugins.digital_twin_core.digital_twin_core import ( - DigitalTwinCore, - ) - from ..auto_gain.auto_gain import AutoGain - from ..digital_twin.digital_twin import DigitalTwin - from ..edge_selector import EdgeSelector - from ..scan_control_xas.scan_control_xas import ScanControlXAS - from ..temperature_controller.temperature_controller import TemperatureControllerControl - - self.DigitalTwinCore = DigitalTwinCore - self.DigitalTwin = DigitalTwin - self.AutoGain = AutoGain - self.EdgeSelector = EdgeSelector - self.ScanControlXAS = ScanControlXAS - self.TemperatureController = TemperatureControllerControl + self._import_beamline_widgets() layout = QVBoxLayout(self) - self.item_combo = QComboBox() layout.addWidget(self.item_combo) - self.stack = QStackedWidget() - layout.addWidget(self.stack) + layout.addWidget(self.stack, 1) self._build_scan_page() self._build_move_page() if self._is_xas_beamline: self._build_digital_twin_page() - self._build_abs_page() + self._build_absorber_page() self._build_ic_page() self._build_reffoil_page() self._build_auto_gain_page() self._build_temperature_controller_page() - self._build_other_page() + self._build_delay_page() + self._build_wait_for_parent_page() - self.item_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) + # Item options, shared by all pages. + self.wait_for_completion_check = QCheckBox("Wait for completion") + self.wait_for_completion_check.setToolTip( + "Uncheck to run the following items while this one is still running. They are shown " + "indented until a 'Wait until parent has completed' item." + ) + self.wait_for_completion_check.setChecked(True) + self.pause_on_failure_check = QCheckBox("Pause schedule if this item fails") + self.pause_on_state_check = QCheckBox("Pause on beamline state") + self.pause_on_state_check.setToolTip( + "Wait for all beamline states to be valid (or warning) before starting this item. " + "A running scan is interrupted and repeated if a state becomes invalid." + ) + options = QHBoxLayout() + for check in ( + self.wait_for_completion_check, + self.pause_on_failure_check, + self.pause_on_state_check, + ): + options.addWidget(check) + options.addStretch() + layout.addLayout(options) - # Shared across all items (not per-page), since it's a property - # of the schedule item, not of any one form. - self.pause_on_failure_check = QCheckBox("Pause schedule if item execution fails") - layout.addWidget(self.pause_on_failure_check) + self.item_combo.currentIndexChanged.connect(self._on_page_changed) - self.item_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) - - # Dispatch table keyed by the dropdown item's data (see - # _add_page) - one place to register a new item type instead of - # scattering per-item checks through _collect_result(). - self._collectors = { - "scan": self._collect_scan_result, - "move": self._collect_move_result, - "digital_twin": self._collect_digital_twin_result, - "abs": self._collect_abs_result, - "ic": self._collect_ic_result, - "reffoil": self._collect_reffoil_result, - "auto_gain": self._collect_auto_gain_result, - "temperature_controller": self._collect_temperature_controller_result, - "other": self._collect_custom_result, - } - - buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) - buttons.button(QDialogButtonBox.Ok).setText("Add") + buttons = QDialogButtonBox( + QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel + ) + buttons.button(QDialogButtonBox.StandardButton.Ok).setText("Save" if initial else "Add") buttons.setStyleSheet("QPushButton {qproperty-icon: none;}") buttons.accepted.connect(self._on_accept) buttons.rejected.connect(self.reject) layout.addWidget(buttons) - # The embedded DigitalTwin instance runs a 1s polling timer and a - # bec_dispatcher subscription for its whole lifetime - stop both - # when this dialog closes, however it closes (OK, Cancel, or the - # window's own close button), not just on accept. + # The embedded DigitalTwin runs a polling timer and dispatcher subscriptions; stop them + # however the dialog is closed. self.finished.connect(self._cleanup_digital_twin) self._apply_initial(initial or {}) + self._on_page_changed() - # ------------------------------------------------------------------ # - # Dropdown/page plumbing - # ------------------------------------------------------------------ # - def _add_page(self, key: str, label: str, widget: QWidget): - # The combo and the stack are always appended to together, so a - # combo index doubles as a stack index - no separate key->index - # map needed. `key` is what _collect_result()/_apply_initial() - # dispatch on. - self.item_combo.addItem(label, key) + def _import_beamline_widgets(self) -> None: + logger.info(f"Loading beamline-specific item pages for {self.beamline}") + # pylint: disable=import-outside-toplevel + from ..auto_gain.auto_gain import AutoGain + from ..digital_twin.digital_twin import DigitalTwin + from ..scan_control_xas.scan_control_xas import ScanControlXAS + from ..temperature_controller.temperature_controller import TemperatureControllerControl + + self._digital_twin_cls = DigitalTwin + self._auto_gain_cls = AutoGain + self._scan_control_xas_cls = ScanControlXAS + self._temperature_controller_cls = TemperatureControllerControl + + # ------------------------------------------------------------------------------------------ # + # Page plumbing + # ------------------------------------------------------------------------------------------ # + def _add_page( + self, + action: str, + label: str, + widget: QWidget, + collect: Callable[[], dict], + prefill: Callable[[dict], None] | None = None, + ) -> None: + # Combo and stack are always appended together, so a combo index is a stack index. + self.item_combo.addItem(label, action) self.stack.addWidget(widget) + self._collectors[action] = collect + if prefill is not None: + self._prefillers[action] = prefill - def _select_page(self, key: str) -> bool: - """Switch the dropdown to `key`'s page; False if that item isn't available.""" - idx = self.item_combo.findData(key) + def _select_page(self, action: str) -> bool: + """Switch to the page of `action`; False if that page is not available.""" + idx = self.item_combo.findData(action) if idx < 0: return False self.item_combo.setCurrentIndex(idx) return True - # ------------------------------------------------------------------ # - # ScanControl - embeds BEC's own ScanControl widget - # ------------------------------------------------------------------ # - def _build_scan_page(self): + def _on_page_changed(self, *_) -> None: + self.stack.setCurrentIndex(self.item_combo.currentIndex()) + action = self.item_combo.currentData() + always_wait = action in ALWAYS_WAIT_ACTIONS + if always_wait: + self.wait_for_completion_check.setChecked(True) + self.wait_for_completion_check.setEnabled(not always_wait) + is_control = action == WAIT_FOR_PARENT + self.pause_on_failure_check.setEnabled(not is_control) + self.pause_on_state_check.setEnabled(not is_control) + if is_control: + self.pause_on_failure_check.setChecked(False) + self.pause_on_state_check.setChecked(False) + + # ------------------------------------------------------------------------------------------ # + # Scan (embeds BEC's ScanControl, or the XAS variant) + # ------------------------------------------------------------------------------------------ # + def _build_scan_page(self) -> None: page = QWidget() layout = QVBoxLayout(page) - - # client=None resolves to the same process-wide BEC client - # (bec_dispatcher.client) our own widget uses - no second Redis - # connection is opened. - if self._is_xas_beamline: - self.scan_control = self.ScanControlXAS(parent=page, client=self._client) - else: - self.scan_control = ScanControl(parent=page, client=self._client) + scan_control_cls = self._scan_control_xas_cls if self._is_xas_beamline else ScanControl + self.scan_control = scan_control_cls(parent=page, client=self._client) self.scan_control.button_run_scan.hide() layout.addWidget(self.scan_control) + self._add_page("scan", "Scan", page, self._collect_scan, self._prefill_scan) - self._add_page("scan", "ScanControl", page) - - def _collect_scan_result(self) -> dict: - # Same call ScanControl.run_scan() makes before actually - # submitting, to resolve a typed-but-unconfirmed scan name. + def _collect_scan(self) -> dict: + # Same call ScanControl.run_scan() makes to resolve a typed-but-unconfirmed scan name. self.scan_control.validate_scan_selection() scan_name = self.scan_control.current_scan if not scan_name: raise ValueError("No scan selected.") - - # bec_object=False: plain, repr-able values (e.g. a device name - # string rather than the live DeviceBase instance) - needed since - # the result has to survive a round-trip through Redis as text and - # be re-evaluated later, not just used in-process immediately. + # bec_object=False: plain values (device names instead of device objects), so the + # parameters are JSON-serialisable. args, kwargs = self.scan_control.get_scan_parameters(bec_object=False) - command = _format_scan_call(scan_name, args, kwargs) - return { - "command": command, - "kind": "scan", - "form_state": {"scan_name": scan_name, "args": args, "kwargs": kwargs}, - } + return {"scan_name": scan_name, "args": list(args), "kwargs": dict(kwargs)} - def _prefill_scan_page(self, scan_name: str, args: list, kwargs: dict): - # ScanControl restores parameters for a scan from its own config - # cache (see `ScanControl.restore_scan_parameters`); pre-loading - # that cache before switching to the scan reuses that mechanism - # instead of poking at its internal argument widgets directly. + def _prefill_scan(self, params: dict) -> None: + # Pre-load ScanControl's own parameter cache and let it restore the form. + scan_name = params["scan_name"] self.scan_control.config.scans[scan_name] = ScanParameterConfig( - name=scan_name, args=args, kwargs=kwargs + name=scan_name, args=params.get("args") or [], kwargs=params.get("kwargs") or {} ) self.scan_control.current_scan = scan_name self.scan_control.restore_scan_parameters(scan_name) - # ------------------------------------------------------------------ # + # ------------------------------------------------------------------------------------------ # # Move - # ------------------------------------------------------------------ # - def _build_move_page(self): + # ------------------------------------------------------------------------------------------ # + def _build_move_page(self) -> None: page = QWidget() form = QFormLayout(page) form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) - self.move_device_combo = DeviceComboBox(self, device_filter=[BECDeviceFilter.POSITIONER]) - form.addRow("Device", self.move_device_combo) - self.move_value_spin = QDoubleSpinBox() - form.addRow("Value", self.move_value_spin) - self.move_relative_check = QCheckBox("") + form.addRow("Device", self.move_device_combo) + form.addRow("Value", self.move_value_spin) form.addRow("Relative move", self.move_relative_check) + self.move_device_combo.currentTextChanged.connect(self._adjust_move_spinbox) + self._adjust_move_spinbox(self.move_device_combo.currentText()) + self._add_page("move", "Move", page, self._collect_move, self._prefill_move) - self.move_device_combo.currentIndexChanged.connect(self._adjust_spinbox) - - self._add_page("move", "Move", page) - - def _adjust_spinbox(self, _) -> None: - device = self._dev[self.move_device_combo.currentText()] - prec = device.precision - units = device.egu() - ll = device.low_limit - hl = device.high_limit - - self.move_value_spin.setDecimals(prec) - self.move_value_spin.setSuffix(f" {units}") - if (hl - ll) > 0: - self.move_value_spin.setMinimum(ll) - self.move_value_spin.setMaximum(hl) - self.move_value_spin.setSingleStep(10 ** round(math.log10((hl - ll) / 100))) - else: - self.move_value_spin.setMinimum(1e6) - self.move_value_spin.setMaximum(-1e6) + def _adjust_move_spinbox(self, device_name: str) -> None: + """Adapt precision, units and limits of the value spin box to the selected device.""" + if not device_name or device_name not in self._dev: + return + device = self._dev[device_name] + try: + precision, units = device.precision, device.egu() + low, high = device.low_limit, device.high_limit + except Exception: # pylint: disable=broad-except + logger.exception(f"Could not read limits/units of {device_name}") + return + self.move_value_spin.setDecimals(precision) + self.move_value_spin.setSuffix(f" {units}" if units else "") + if high - low > 0: + self.move_value_spin.setRange(low, high) + self.move_value_spin.setSingleStep(10 ** round(math.log10((high - low) / 100))) + else: # no limits configured + self.move_value_spin.setRange(-1e6, 1e6) self.move_value_spin.setSingleStep(1) - def _collect_move_result(self) -> dict: - device_name = self.move_device_combo.currentText() - if not device_name: + def _collect_move(self) -> dict: + device = self.move_device_combo.currentText() + if not device: raise ValueError("No movable device available/selected.") - value = self.move_value_spin.value() - units = self.move_value_spin.suffix() - relative = self.move_relative_check.isChecked() return { - "command": f"dev.{device_name}.move({value!r}, relative={relative!r})", - "kind": "move", - "form_state": { - "device_name": device_name, - "value": value, - "units": units, - "relative": relative, - }, + "device": device, + "value": self.move_value_spin.value(), + "relative": self.move_relative_check.isChecked(), + "units": self.move_value_spin.suffix().strip(), } - def _prefill_move_page(self, state: dict): - idx = self.move_device_combo.findText(state.get("device_name", "")) + def _prefill_move(self, params: dict) -> None: + idx = self.move_device_combo.findText(params.get("device", "")) if idx >= 0: self.move_device_combo.setCurrentIndex(idx) - self.move_value_spin.setValue(float(state.get("value", 0.0))) - self.move_relative_check.setChecked(bool(state.get("relative", False))) + self.move_value_spin.setValue(float(params.get("value", 0.0))) + self.move_relative_check.setChecked(bool(params.get("relative", False))) - # ------------------------------------------------------------------ # - # Digital Twin - embeds the beamline-alignment DigitalTwin widget - # ------------------------------------------------------------------ # - def _build_digital_twin_page(self): + # ------------------------------------------------------------------------------------------ # + # Digital Twin + # ------------------------------------------------------------------------------------------ # + def _build_digital_twin_page(self) -> None: page = QWidget() outer = QVBoxLayout(page) - - # DigitalTwin defaults to a large fixed size (it's normally its - # own top-level window) - wrap it in a scroll area so this dialog - # doesn't have to grow to match it. + # DigitalTwin is normally a large top-level window; wrap it in a scroll area. scroll = QScrollArea() scroll.setWidgetResizable(True) - self.digital_twin = self.DigitalTwin(parent=scroll, client=self._client) - # Hide move and abs open buttons + self.digital_twin = self._digital_twin_cls(parent=scroll, client=self._client) for mover in self.digital_twin.mover.mover_widgets: mover.btn_action.hide() self.digital_twin.mover.abs.btn_action.hide() - scroll.setWidget(self.digital_twin) outer.addWidget(scroll) - - hint = QLabel( - "Configure the beamline alignment above, then confirm with Add below - the " - "computed motor targets are captured now and moved together (in one combined " - "move) when this schedule item runs, not immediately." + outer.addWidget( + _hint( + "Configure the beamline alignment above. The motor targets are computed and moved " + "when this schedule item runs, not now." + ) + ) + self._add_page( + "digital_twin", + "Digital Twin", + page, + lambda: {"config": self.digital_twin.get_assistant_config()}, + lambda params: self.digital_twin.set_assistant_config(params["config"]), ) - hint.setWordWrap(True) - hint.setStyleSheet("color: gray;") - outer.addWidget(hint) - self._add_page("digital_twin", "Digital Twin", page) - - def _collect_digital_twin_result(self) -> dict: - # A frozen snapshot of the configured targets, not a live handle - - # editing the Digital Twin widget afterwards must not affect an - # already-added schedule item (see module docstring). - config = self.digital_twin.get_assistant_config() - cmd = f"digital_twin.move_with_config({config})" - return { - "command": cmd, - "kind": "custom", - "form_state": {"text": cmd, "source": "digital_twin", "config": config}, - } - - def _cleanup_digital_twin(self, *_): + def _cleanup_digital_twin(self, *_) -> None: digital_twin = getattr(self, "digital_twin", None) if digital_twin is None: return try: digital_twin._timer.stop() # pylint: disable=protected-access - except Exception: # pylint: disable=broad-except - logger.exception("Failed to stop the Digital Twin's reality-update timer.") - try: digital_twin.cleanup() except Exception: # pylint: disable=broad-except logger.exception("Failed to clean up the embedded Digital Twin widget.") - def _prefill_digital_twin_page(self, state: dict): - config = state["config"] - self.digital_twin.set_assistant_config(config) - - # ------------------------------------------------------------------ # + # ------------------------------------------------------------------------------------------ # # Absorber - # ------------------------------------------------------------------ # - def _build_abs_page(self): + # ------------------------------------------------------------------------------------------ # + def _build_absorber_page(self) -> None: if "abs" not in self._dev: return page = QWidget() form = QFormLayout(page) form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) - self.abs_selector = QComboBox() - self.abs_selector.addItems(["Open", "Force open", "Close"]) + self.abs_selector.addItems(list(ABSORBER_ACTIONS)) form.addRow("Action", self.abs_selector) - - self._add_page("abs", "Absorber", page) - - def _collect_abs_result(self) -> dict: - action = self.abs_selector.currentText() - suffix = {"Open": "open()", "Force open": "open(force=True)", "Close": "close()"}.get( - action + self._add_page( + "absorber", + "Absorber", + page, + lambda: {"action": self.abs_selector.currentText()}, + lambda params: self._set_combo(self.abs_selector, params.get("action")), ) - if suffix is None: - raise ValueError("Select an absorber action.") - cmd = f"dev.abs.{suffix}" - return { - "command": cmd, - "kind": "custom", - "form_state": {"text": cmd, "source": "abs", "action": action}, - } - def _prefill_abs_form(self, state: dict): - idx = self.abs_selector.findText(state.get("action", "")) - if idx >= 0: - self.abs_selector.setCurrentIndex(idx) - - # ------------------------------------------------------------------ # + # ------------------------------------------------------------------------------------------ # # Ionization chamber - # ------------------------------------------------------------------ # - def _build_ic_page(self): + # ------------------------------------------------------------------------------------------ # + def _build_ic_page(self) -> None: if not all(key in self._dev for key in ("ic0", "ic1", "ic2")): return page = QWidget() @@ -381,27 +369,19 @@ class ScheduleItemDialog(QDialog): self.ic_selector = QComboBox() self.ic_selector.addItems(["IC0", "IC1", "IC2"]) - gases = ["He", "N2", "Ar", "Kr"] - self.gas1 = QComboBox() - self.gas2 = QComboBox() + self.gas1, self.gas2 = QComboBox(), QComboBox() self.gas1.addItems(gases) self.gas2.addItems(gases) - - self.conc1 = QDoubleSpinBox() - self.conc2 = QDoubleSpinBox() + self.conc1, self.conc2 = QDoubleSpinBox(), QDoubleSpinBox() for conc in (self.conc1, self.conc2): conc.setDecimals(0) conc.setSuffix(" %") - conc.setMinimum(0) - conc.setMaximum(100) - conc.setSingleStep(1) - + conc.setRange(0, 100) self.pressure = QDoubleSpinBox() self.pressure.setDecimals(3) self.pressure.setSuffix(" bar abs") - self.pressure.setMinimum(1) - self.pressure.setMaximum(3) + self.pressure.setRange(1, 3) self.pressure.setSingleStep(0.1) form.addRow("Ionization chamber", self.ic_selector) @@ -411,289 +391,192 @@ class ScheduleItemDialog(QDialog): form.addRow("Concentration 2", self.conc2) form.addRow("Pressure", self.pressure) - self.conc1.valueChanged.connect(self._equalize_ic_conc) - self.conc2.valueChanged.connect(self._equalize_ic_conc) + self.conc1.valueChanged.connect(lambda value: self.conc2.setValue(100 - value)) + self.conc2.valueChanged.connect(lambda value: self.conc1.setValue(100 - value)) + self._add_page("ic_fill", "Ionization Chamber", page, self._collect_ic, self._prefill_ic) - self._add_page("ic", "Ionization Chamber", page) - - def _equalize_ic_conc(self, new_val): - if self.conc1.value() == new_val: # conc1 was changed - self.conc2.setValue(100 - new_val) - else: - self.conc1.setValue(100 - new_val) - - def _collect_ic_result(self) -> dict: + def _collect_ic(self) -> dict: total = self.conc1.value() + self.conc2.value() if total != 100: raise ValueError(f"Gas concentrations must add up to 100% (currently {total:.0f}%).") - chamber = self.ic_selector.currentText() - ic = {"IC0": "ic0", "IC1": "ic1", "IC2": "ic2"}[chamber] - cmd = ( - f"dev.{ic}.fill(" - f"gas1='{self.gas1.currentText()}', conc1={self.conc1.value()}, " - f"gas2='{self.gas2.currentText()}', conc2={self.conc2.value()}, " - f"pressure={self.pressure.value()}, wait=True)" - ) return { - "command": cmd, - "kind": "custom", - "form_state": { - "text": cmd, - "source": "ic", - "chamber": chamber, - "gas1": self.gas1.currentText(), - "conc1": self.conc1.value(), - "gas2": self.gas2.currentText(), - "conc2": self.conc2.value(), - "pressure": self.pressure.value(), - }, + "chamber": self.ic_selector.currentText(), + "gas1": self.gas1.currentText(), + "conc1": self.conc1.value(), + "gas2": self.gas2.currentText(), + "conc2": self.conc2.value(), + "pressure": self.pressure.value(), } - def _prefill_ic_form(self, state: dict): - idx = self.ic_selector.findText(state.get("chamber", "")) - if idx >= 0: - self.ic_selector.setCurrentIndex(idx) - idx = self.gas1.findText(state.get("gas1", "")) - if idx >= 0: - self.gas1.setCurrentIndex(idx) - idx = self.gas2.findText(state.get("gas2", "")) - if idx >= 0: - self.gas2.setCurrentIndex(idx) - # Set conc2 last: conc1's valueChanged->_equalize_ic_conc would - # otherwise immediately overwrite it. - self.conc1.setValue(float(state.get("conc1", 0))) - self.conc2.setValue(float(state.get("conc2", 0))) - self.pressure.setValue(float(state.get("pressure", self.pressure.minimum()))) + def _prefill_ic(self, params: dict) -> None: + self._set_combo(self.ic_selector, params.get("chamber")) + self._set_combo(self.gas1, params.get("gas1")) + self._set_combo(self.gas2, params.get("gas2")) + self.conc1.setValue(float(params.get("conc1", 0))) # also sets conc2 = 100 - conc1 + self.pressure.setValue(float(params.get("pressure", self.pressure.minimum()))) - # ------------------------------------------------------------------ # + # ------------------------------------------------------------------------------------------ # # Reference foil changer - # ------------------------------------------------------------------ # - def _build_reffoil_page(self): + # ------------------------------------------------------------------------------------------ # + def _build_reffoil_page(self) -> None: if "reffoilchanger" not in self._dev: return page = QWidget() form = QFormLayout(page) form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) - self.reffoil_selector = QComboBox() - self.reffoil_selector.addItems(self._dev.reffoilchanger.get_all_foils()) + self.reffoil_selector.addItems(self._dev["reffoilchanger"].get_all_foils()) form.addRow("Reference foil", self.reffoil_selector) + self._add_page( + "reffoil", + "Reference foil changer", + page, + self._collect_reffoil, + lambda params: self._set_combo(self.reffoil_selector, params.get("foil")), + ) - self._add_page("reffoil", "Reference foil changer", page) - - def _collect_reffoil_result(self) -> dict: + def _collect_reffoil(self) -> dict: foil = self.reffoil_selector.currentText() if not foil: raise ValueError("Select a reference foil.") - cmd = f"dev.reffoilchanger.insert(ref='{foil}', wait=True)" - return { - "command": cmd, - "kind": "custom", - "form_state": {"text": cmd, "source": "reffoil", "foil": foil}, - } + return {"foil": foil} - def _prefill_reffoil_form(self, state: dict): - idx = self.reffoil_selector.findText(state.get("foil", "")) - if idx >= 0: - self.reffoil_selector.setCurrentIndex(idx) - - # ------------------------------------------------------------------ # - # Auto-Gain - # ------------------------------------------------------------------ # - def _build_auto_gain_page(self): + # ------------------------------------------------------------------------------------------ # + # Auto Gain + # ------------------------------------------------------------------------------------------ # + def _build_auto_gain_page(self) -> None: page = QWidget() outer = QVBoxLayout(page) - scroll = QScrollArea() scroll.setWidgetResizable(True) - self.auto_gain = self.AutoGain(show_control=False, parent=scroll, client=self._client) - + self.auto_gain = self._auto_gain_cls(show_control=False, parent=scroll, client=self._client) scroll.setWidget(self.auto_gain) outer.addWidget(scroll) - - hint = QLabel( - "Configure the auto-gain functionality, then confirm with Add below - the " - "auto-gain will only be executed when this schedule item runs, not immediately." + outer.addWidget( + _hint("Configure the auto-gain above. It is executed when this schedule item runs.") ) - hint.setWordWrap(True) - hint.setStyleSheet("color: gray;") - outer.addWidget(hint) - - self._add_page("auto_gain", "Auto Gain", page) - - def _collect_auto_gain_result(self) -> dict: - config = self.auto_gain.get_config() - - cmd = ( - f"auto_gain.start(element='{config['element']}', edge='{config['edge']}', " - + f"amplifier={config['all_amplifiers']}, link_ic0_ic1={config['link_ic0_ic1']}, " - + f"comp_ring_current= {config['compensate_ring_current']}, " - + f"prohibited_gains={config['prohibited_gains']})" + self._add_page( + "auto_gain", + "Auto Gain", + page, + lambda: {"config": self.auto_gain.get_config()}, + lambda params: self.auto_gain.load_config(params["config"]), ) - return { - "command": cmd, - "kind": "custom", - "form_state": {"text": cmd, "source": "auto_gain", "config": config}, - } - def _prefill_auto_gain_form(self, state: dict): - self.auto_gain.load_config(state["config"]) - - # ------------------------------------------------------------------ # + # ------------------------------------------------------------------------------------------ # # Temperature Controller - # ------------------------------------------------------------------ # - def _build_temperature_controller_page(self): + # ------------------------------------------------------------------------------------------ # + def _build_temperature_controller_page(self) -> None: page = QWidget() outer = QVBoxLayout(page) - scroll = QScrollArea() scroll.setWidgetResizable(True) - self.temperature_controller = self.TemperatureController(config_only=True, parent=scroll) - + self.temperature_controller = self._temperature_controller_cls( + config_only=True, parent=scroll + ) scroll.setWidget(self.temperature_controller) outer.addWidget(scroll) outer.addStretch() + self._add_page( + "temperature_controller", + "Temperature Controller", + page, + lambda: {"config": self.temperature_controller.get_config()}, + lambda params: self.temperature_controller.load_config(params["config"]), + ) - # hint = QLabel( - # "Configure the auto-gain functionality, then confirm with Add below - the " - # "auto-gain will only be executed when this schedule item runs, not immediately." - # ) - # hint.setWordWrap(True) - # hint.setStyleSheet("color: gray;") - # outer.addWidget(hint) - - self._add_page("temperature_controller", "Temperature Controller", page) - - def _collect_temperature_controller_result(self) -> dict: - config = self.temperature_controller.get_config() - - cmd = f"dev.univ_temp_cont.load_config(config={config})" - return { - "command": cmd, - "kind": "custom", - "form_state": {"text": cmd, "source": "temperature_controller", "config": config}, - } - - def _prefill_temperature_controller_form(self, state: dict): - self.temperature_controller.load_config(state["config"]) - - # ------------------------------------------------------------------ # - # Sleep - # ------------------------------------------------------------------ # - def _build_sleep_page(self): + # ------------------------------------------------------------------------------------------ # + # Delay + # ------------------------------------------------------------------------------------------ # + def _build_delay_page(self) -> None: page = QWidget() form = QFormLayout(page) form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint) + self.delay_hours = QSpinBox(suffix=" h", maximum=999) + self.delay_minutes = QSpinBox(suffix=" min", maximum=59) + self.delay_seconds = QSpinBox(suffix=" s", maximum=59) + row = QHBoxLayout() + for spin in (self.delay_hours, self.delay_minutes, self.delay_seconds): + row.addWidget(spin) + form.addRow("Wait for", row) + form.addRow(_hint("The schedule waits for the given time before continuing.")) + self._add_page(DELAY, "Delay", page, self._collect_delay, self._prefill_delay) - self.sleep_spin = QDoubleSpinBox(suffix=" s") - form.addRow("Sleep for", self.sleep_spin) + def _collect_delay(self) -> dict: + seconds = ( + self.delay_hours.value() * 3600 + + self.delay_minutes.value() * 60 + + self.delay_seconds.value() + ) + if seconds <= 0: + raise ValueError("The delay must be longer than 0 s.") + return {"seconds": seconds} - self._add_page("sleep", "Sleep", page) + def _prefill_delay(self, params: dict) -> None: + hours, rest = divmod(int(params.get("seconds", 0)), 3600) + minutes, seconds = divmod(rest, 60) + self.delay_hours.setValue(hours) + self.delay_minutes.setValue(minutes) + self.delay_seconds.setValue(seconds) - def _collect_sleep_result(self) -> dict: - value = self.sleep_spin.value() - return { - "command": f"time.sleep({value})", - "kind": "sleep", - "form_state": { - "value": value, - }, - } - - def _prefill_sleep_page(self, state: dict): - self.sleep_spin.setValue(float(state.get("value", 0.0))) - - # ------------------------------------------------------------------ # - # Other - # ------------------------------------------------------------------ # - def _build_other_page(self): + # ------------------------------------------------------------------------------------------ # + # Wait until parent has completed + # ------------------------------------------------------------------------------------------ # + def _build_wait_for_parent_page(self) -> None: page = QWidget() layout = QVBoxLayout(page) layout.addWidget( - QLabel( - "Free-form command, evaluated against `scans` and `dev` - use this for " - "anything the other items don't cover, e.g. an RPC call to another widget." + _hint( + "Waits until the item above that runs without 'Wait for completion' (the parent) " + "has completed. Ends the indented block of items that run while the parent is " + "busy; the following items start only after the parent has finished." ) ) - self.custom_edit = QLineEdit() - # TODO Change to a different placeholder text - self.custom_edit.setPlaceholderText("scans.xas_simple_scan(12000, 14000, 2, 10)") - layout.addWidget(self.custom_edit) - layout.addStretch(1) + layout.addStretch() + self._add_page(WAIT_FOR_PARENT, "Wait until parent has completed", page, dict) - self._add_page("other", "Other", page) + # ------------------------------------------------------------------------------------------ # + # Prefill / result + # ------------------------------------------------------------------------------------------ # + @staticmethod + def _set_combo(combo: QComboBox, text: str | None) -> None: + idx = combo.findText(text or "") + if idx >= 0: + combo.setCurrentIndex(idx) - def _collect_custom_result(self) -> dict: - text = self.custom_edit.text().strip() - if not text: - raise ValueError("Command must not be empty.") - return {"command": text, "kind": "custom", "form_state": {"text": text}} - - # ------------------------------------------------------------------ # - # pre-fill (edit mode) / result extraction - # ------------------------------------------------------------------ # - def _apply_initial(self, initial: dict): + def _apply_initial(self, initial: dict) -> None: + self.wait_for_completion_check.setChecked(bool(initial.get("wait_for_completion", True))) self.pause_on_failure_check.setChecked(bool(initial.get("pause_on_failure", False))) - - logger.info(f"Got initial: {initial}") - - kind = initial.get("kind") - state = initial.get("form_state") or {} - source = state.get("source") - - if kind == "scan" and state.get("scan_name"): - self._prefill_scan_page( - state["scan_name"], state.get("args") or [], state.get("kwargs") or {} - ) - self._select_page("scan") - elif kind == "custom" and source == "digital_twin" and self._select_page("digital_twin"): - self._prefill_digital_twin_page(state) - elif kind == "move" and state.get("device_name"): - self._prefill_move_page(state) - self._select_page("move") - elif kind == "custom" and source == "abs" and self._select_page("abs"): - self._prefill_abs_form(state) - elif kind == "custom" and source == "ic" and self._select_page("ic"): - self._prefill_ic_form(state) - elif kind == "custom" and source == "reffoil" and self._select_page("reffoil"): - self._prefill_reffoil_form(state) - elif kind == "custom" and source == "auto_gain" and self._select_page("auto_gain"): - self._prefill_auto_gain_form(state) - elif kind == "custom" and source == "temperature_controller" and self._select_page("temperature_controller"): - self._prefill_temperature_controller_form(state) - elif initial.get("command"): - # "custom" kind with no (recognized/available) source, or a - # legacy/unrecognized item - fall back to showing the raw - # command text as-is. - self.custom_edit.setText(state.get("text", initial["command"])) - self._select_page("other") - else: - logger.warning(f"Unknown kind: {kind}") - - def _on_accept(self): - try: - result = self._collect_result() - except ValueError as exc: - QMessageBox.warning(self, "Can't build command", str(exc)) + self.pause_on_state_check.setChecked(bool(initial.get("pause_on_state", False))) + action = initial.get("action") + if action is None: return - self._result = result + if not self._select_page(action): + logger.warning(f"Item type {action!r} is not available at this beamline.") + return + prefill = self._prefillers.get(action) + if prefill is not None: + try: + prefill(initial.get("params") or {}) + except Exception: # pylint: disable=broad-except + logger.exception(f"Could not restore the parameters of a {action!r} item") + + def _on_accept(self) -> None: + action = self.item_combo.currentData() + try: + params = self._collectors[action]() + except ValueError as exc: + QMessageBox.warning(self, "Invalid item", str(exc)) + return + self._result = { + "action": action, + "params": params, + "wait_for_completion": self.wait_for_completion_check.isChecked(), + "pause_on_failure": self.pause_on_failure_check.isChecked(), + "pause_on_state": self.pause_on_state_check.isChecked(), + } self.accept() - def _collect_result(self) -> dict: - key = self.item_combo.currentData() - handler = self._collectors.get(key) - if handler is None: - raise ValueError(f"Unknown item type: {key!r}") - result = handler() - result["pause_on_failure"] = self.pause_on_failure_check.isChecked() - return result - - def result(self) -> dict: - """Valid after `exec_()` returns `QDialog.Accepted`.""" + def result(self) -> dict: # pylint: disable=invalid-overridden-method + """The item definition; valid after `exec_()` returned `QDialog.Accepted`.""" return self._result - - -def _format_scan_call(scan_name: str, args: list, kwargs: dict) -> str: - parts = [repr(a) for a in args] - parts += [f"{name}={value!r}" for name, value in kwargs.items()] - return f"scans.{scan_name}({', '.join(parts)})" diff --git a/debye_bec/bec_widgets/widgets/scheduler/models.py b/debye_bec/bec_widgets/widgets/scheduler/models.py new file mode 100644 index 0000000..2c4f71b --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/models.py @@ -0,0 +1,170 @@ +""" +Persisted data model of the Scheduler widget. + +Everything in here is a plain pydantic model. The whole `Schedule` document is stored in Redis as +the `.value` payload of a `bec_lib.messages.VariableMessage` (see `endpoints.schedule`) and can be +saved to / loaded from a JSON file. All fields must therefore stay JSON-serialisable; in +particular, a `ScheduleItem` describes *what* to run as a registry key (`action`) plus plain +parameters (`params`) - never as executable code (see `actions.py`). +""" + +from __future__ import annotations + +import uuid +from enum import Enum +from typing import Any + +from pydantic import AliasChoices, BaseModel, ConfigDict, Field, ValidationError, field_validator + + +class ItemStatus(str, Enum): + """Execution status of one schedule item.""" + + PENDING = "pending" + RUNNING = "running" + COMPLETED = "completed" + FAILED = "failed" + ABORTED = "aborted" + + +class NotificationTarget(str, Enum): + """BEC messaging service used to send schedule notifications.""" + + SCILOG = "scilog" + SIGNAL = "signal" + + +class NotificationSettings(BaseModel): + """Per-schedule notification preferences (see `notifications.py` for the send logic).""" + + model_config = ConfigDict(extra="ignore", populate_by_name=True) + + enabled: bool = False + notify_scan: bool = True + notify_move: bool = True + # Device actions and beamline tools (digital twin, auto-gain, ...). Older schedules stored + # this flag as "notify_rpc". + notify_device: bool = Field( + default=True, validation_alias=AliasChoices("notify_device", "notify_rpc") + ) + + target: NotificationTarget = NotificationTarget.SCILOG + events: list[ItemStatus] = Field(default_factory=list) + signal_number: str | None = None # a phone number, or a pre-registered Signal scope + + @field_validator("target", mode="before") + @classmethod + def _map_legacy_target(cls, value: Any) -> Any: + """Map targets that are no longer supported (e.g. the removed "teams") to SciLog.""" + valid = {target.value for target in NotificationTarget} + if isinstance(value, NotificationTarget): + return value + if not isinstance(value, str) or value not in valid: + return NotificationTarget.SCILOG + return value + + +class ScheduleItem(BaseModel): + """ + One entry of the schedule: what to run, how to run it, and its execution bookkeeping. + + Attributes: + item_id: Stable unique id, used to address the item from the UI and over RPC. + action: Key of the action in the function registry (`actions.ACTIONS`). + params: JSON-serialisable keyword arguments passed to the action. + status: Current execution status. + wait_for_completion: If False, the item is started and the schedule immediately + continues with the following items ("background item"). The following items are + shown indented until a "Wait until parent has completed" item, the next background + item or the end of the schedule. + pause_on_failure: Pause the schedule if this item fails. + pause_on_state: Only start this item while all beamline states are VALID or WARNING. + A gated scan that is running when a state becomes INVALID is cancelled and repeated + once the states have recovered. + report: Short human-readable result, shown in the "Report" column. + request_id / scan_id / scan_number: Set for items that submit a request to the BEC + scan server; used to re-attach to a still-running request after a widget restart. + error: Full traceback of the last failure. + started_at / finished_at: Unix timestamps of the last execution. + """ + + model_config = ConfigDict(extra="ignore") + + item_id: str = Field(default_factory=lambda: str(uuid.uuid4())) + action: str + params: dict[str, Any] = Field(default_factory=dict) + status: ItemStatus = ItemStatus.PENDING + + wait_for_completion: bool = True + pause_on_failure: bool = False + pause_on_state: bool = False + + report: str | None = None + request_id: str | None = None + scan_id: str | None = None + scan_number: int | None = None + error: str | None = None + started_at: float | None = None + finished_at: float | None = None + + def reset_execution(self) -> None: + """Clear all execution bookkeeping and mark the item PENDING again.""" + self.status = ItemStatus.PENDING + self.report = None + self.request_id = None + self.scan_id = None + self.scan_number = None + self.error = None + self.started_at = None + self.finished_at = None + + def definition(self) -> dict[str, Any]: + """The user-defined part of the item (no id, no execution state), e.g. for copy/paste.""" + return { + "action": self.action, + "params": dict(self.params), + "wait_for_completion": self.wait_for_completion, + "pause_on_failure": self.pause_on_failure, + "pause_on_state": self.pause_on_state, + } + + +class Schedule(BaseModel): + """The full persisted state of one named schedule.""" + + model_config = ConfigDict(extra="ignore") + + schedule_name: str + items: list[ScheduleItem] = Field(default_factory=list) + is_running: bool = False + notes: str = "" + notifications: NotificationSettings = Field(default_factory=NotificationSettings) + + +def is_legacy_schedule(data: Any) -> bool: + """ + True if `data` looks like a schedule written by the old, eval-based Scheduler widget + (items described by a `command` string instead of an `action` registry key). + """ + if not isinstance(data, dict): + return False + items = data.get("items") or [] + return any( + isinstance(item, dict) and "command" in item and "action" not in item for item in items + ) + + +def schedule_from_document(data: Any) -> tuple[Schedule | None, str | None]: + """ + Validate a persisted schedule document (from Redis or a JSON file) without raising. + + Returns: + `(schedule, None)` if the document is valid, otherwise `(None, problem)` where `problem` + is a short human-readable description, e.g. "an old schedule format". + """ + if is_legacy_schedule(data): + return None, "an old schedule format" + try: + return Schedule.model_validate(data), None + except (ValidationError, TypeError, KeyError, AttributeError) as exc: + return None, f"an invalid schedule ({exc.__class__.__name__})" diff --git a/debye_bec/bec_widgets/widgets/scheduler/notification_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/notification_dialog.py index cc7dd81..a2f3e99 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/notification_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/notification_dialog.py @@ -1,12 +1,10 @@ -""" -Settings dialog for `notifications.NotificationSettings` - kept separate -from the send logic itself (`notifications.py`). -""" +"""Settings dialog for the schedule notifications (`models.NotificationSettings`).""" from __future__ import annotations -from bec_lib.logger import bec_logger +# pylint: disable=no-name-in-module # qtpy re-exports are not visible to pylint from qtpy.QtWidgets import ( + QButtonGroup, QCheckBox, QComboBox, QDialog, @@ -15,21 +13,18 @@ from qtpy.QtWidgets import ( QLabel, QMessageBox, QPushButton, + QRadioButton, QVBoxLayout, ) -from .enums import ScheduleItemStatus -from .notifications import NotificationSettings, NotificationTarget, send_notification - -logger = bec_logger.logger +from .models import ItemStatus, NotificationSettings, NotificationTarget +from .notifications import send_notification def _service_state(client, name: str) -> tuple[bool, list[str]]: """ - Best-effort read of a messaging service's enabled/scopes state (see - the module docstring in notifications.py for why this is the only - introspection available). Never raises - a client without `messaging` - set up yet just looks like "not enabled, no scopes". + Best-effort read of a messaging service's enabled flag and registered scopes. BEC offers no + public accessor for this, hence the private attributes. Never raises. """ messaging = getattr(client, "messaging", None) service = getattr(messaging, name, None) if messaging is not None else None @@ -38,8 +33,21 @@ def _service_state(client, name: str) -> tuple[bool, list[str]]: return bool(getattr(service, "_enabled", False)), sorted(getattr(service, "_scopes", set())) +def _dim_label(text: str) -> QLabel: + label = QLabel(text) + label.setStyleSheet("color: gray;") + label.setWordWrap(True) + return label + + class NotificationSettingsDialog(QDialog): - """Choose whether/where/for-which-item-types finish/fail notifications are sent.""" + """Choose whether, where and for which items/events notifications are sent.""" + + _EVENTS = ( + (ItemStatus.COMPLETED, "Completed"), + (ItemStatus.ABORTED, "Aborted"), + (ItemStatus.FAILED, "Failed"), + ) def __init__(self, settings: NotificationSettings, client, parent=None): super().__init__(parent) @@ -48,12 +56,12 @@ class NotificationSettingsDialog(QDialog): self.setMinimumWidth(380) layout = QVBoxLayout(self) - info_label = QLabel( - "Sends a message through the selected BEC messaging service whenever a " - "schedule item finishes or fails." + info = QLabel( + "Sends a message through the selected BEC messaging service when the schedule " + "starts or stops, and when an item finishes." ) - info_label.setWordWrap(True) - layout.addWidget(info_label) + info.setWordWrap(True) + layout.addWidget(info) self.enabled_check = QCheckBox("Send notifications") self.enabled_check.setChecked(settings.enabled) @@ -65,51 +73,34 @@ class NotificationSettingsDialog(QDialog): self.scan_check.setChecked(settings.notify_scan) self.move_check = QCheckBox("Movements") self.move_check.setChecked(settings.notify_move) - self.rpc_check = QCheckBox("RPC / custom commands") - self.rpc_check.setChecked(settings.notify_rpc) - for check in (self.scan_check, self.move_check, self.rpc_check): + self.device_check = QCheckBox("Device actions and beamline tools") + self.device_check.setChecked(settings.notify_device) + for check in (self.scan_check, self.move_check, self.device_check): kind_layout.addWidget(check) layout.addWidget(kind_box) - target_box = QGroupBox("Send via") - target_layout = QVBoxLayout(target_box) - self.scilog_check = QCheckBox("SciLog") - self.teams_check = QCheckBox("Microsoft Teams") - self.signal_check = QCheckBox("Signal Messenger") - for check in (self.scilog_check, self.teams_check, self.signal_check): - target_layout.addWidget(check) - layout.addWidget(target_box) - - event_box = QGroupBox("Send on") + event_box = QGroupBox("Send when an item is") event_layout = QVBoxLayout(event_box) - self.completed_check = QCheckBox("Completed") - self.aborted_check = QCheckBox("Aborted") - self.failed_check = QCheckBox("Failed") - for check in (self.completed_check, self.aborted_check, self.failed_check): + self._event_checks: dict[ItemStatus, QCheckBox] = {} + for status, label in self._EVENTS: + check = QCheckBox(label) + check.setChecked(status in settings.events) event_layout.addWidget(check) + self._event_checks[status] = check layout.addWidget(event_box) - # Teams: contact/channel can only be a scope an admin has already - # registered for the deployment - there's no way to address an - # arbitrary Teams user from the client, so this is a dropdown, not - # free text (see notifications.py's module docstring). - self.teams_box = QGroupBox("Teams settings") - teams_layout = QVBoxLayout(self.teams_box) - teams_enabled, teams_scopes = _service_state(client, "teams") - self.teams_combo = QComboBox() - self.teams_combo.addItems(teams_scopes) - self.teams_combo.setEnabled(teams_enabled) - teams_layout.addWidget(QLabel("Contact or channel")) - teams_layout.addWidget(self.teams_combo) - if not teams_enabled: - teams_layout.addWidget(_dim_label("Teams messaging is not enabled for this session.")) - elif not teams_scopes: - teams_layout.addWidget(_dim_label("No Teams contacts/channels are registered.")) - layout.addWidget(self.teams_box) + target_box = QGroupBox("Send via") + target_layout = QVBoxLayout(target_box) + self.scilog_radio = QRadioButton("SciLog") + self.signal_radio = QRadioButton("Signal Messenger") + self._target_group = QButtonGroup(self) + for radio in (self.scilog_radio, self.signal_radio): + self._target_group.addButton(radio) + target_layout.addWidget(radio) + layout.addWidget(target_box) - # Signal: a raw phone number works directly (BEC normalizes it - - # see the docs), so this is an editable combo box: type a number, - # or pick a pre-registered scope if any exist. + # Signal: a raw phone number works directly, so this is an editable combo box offering + # any pre-registered scopes as suggestions. self.signal_box = QGroupBox("Signal settings") signal_layout = QVBoxLayout(self.signal_box) signal_enabled, signal_scopes = _service_state(client, "signal") @@ -117,115 +108,64 @@ class NotificationSettingsDialog(QDialog): self.signal_combo.setEditable(True) self.signal_combo.addItems(signal_scopes) self.signal_combo.setEnabled(signal_enabled) - signal_layout.addWidget(QLabel("Phone number or contact")) - self.signal_combo.setEditText("") + self.signal_combo.setEditText(settings.signal_number or "") self.signal_combo.lineEdit().setPlaceholderText("e.g. +41791234567") + signal_layout.addWidget(QLabel("Phone number or contact")) signal_layout.addWidget(self.signal_combo) if not signal_enabled: signal_layout.addWidget(_dim_label("Signal messaging is not enabled for this session.")) layout.addWidget(self.signal_box) - # pre-fill from the persisted settings - { - NotificationTarget.SCILOG: self.scilog_check, - NotificationTarget.TEAMS: self.teams_check, - NotificationTarget.SIGNAL: self.signal_check, - }.get(settings.target, self.scilog_check).setChecked(True) - for event in settings.events: - { - ScheduleItemStatus.COMPLETED: self.completed_check, - ScheduleItemStatus.ABORTED: self.aborted_check, - ScheduleItemStatus.FAILED: self.failed_check, - }.get(event).setChecked(True) - if settings.teams_scope: - idx = self.teams_combo.findText(settings.teams_scope) - if idx >= 0: - self.teams_combo.setCurrentIndex(idx) - if settings.signal_number: - self.signal_combo.setEditText(settings.signal_number) - - self.scilog_check.toggled.connect(lambda *_: self._sync_target_widgets(self.scilog_check)) - self.teams_check.toggled.connect(lambda *_: self._sync_target_widgets(self.teams_check)) - self.signal_check.toggled.connect(lambda *_: self._sync_target_widgets(self.signal_check)) + if settings.target == NotificationTarget.SIGNAL: + self.signal_radio.setChecked(True) + else: + self.scilog_radio.setChecked(True) + self.signal_radio.toggled.connect(self._sync_target_widgets) self.test_btn = QPushButton("Send test message") self.test_btn.clicked.connect(self._on_test_clicked) layout.addWidget(self.test_btn) - buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) + buttons = QDialogButtonBox( + QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel + ) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) layout.addWidget(buttons) self._sync_target_widgets() - def _sync_target_widgets(self, current_button: QCheckBox = None): - if current_button is None: - for button in [self.scilog_check, self.teams_check, self.signal_check]: - if button.isChecked(): - current_button = button - break - if current_button.isChecked(): - for button in [self.scilog_check, self.teams_check, self.signal_check]: - if button != current_button: - button.setChecked(False) - if current_button == self.teams_check: - self.teams_box.setVisible(True) - self.signal_box.setVisible(False) - elif current_button == self.signal_check: - self.teams_box.setVisible(False) - self.signal_box.setVisible(True) - else: - self.teams_box.setVisible(False) - self.signal_box.setVisible(False) - self.layout().activate() - self.adjustSize() + def _sync_target_widgets(self, *_) -> None: + self.signal_box.setVisible(self.signal_radio.isChecked()) + self.layout().activate() + self.adjustSize() def _current_settings(self) -> NotificationSettings: - if self.scilog_check.isChecked(): - target = NotificationTarget.SCILOG - elif self.teams_check.isChecked(): - target = NotificationTarget.TEAMS - elif self.signal_check.isChecked(): - target = NotificationTarget.SIGNAL - else: - raise ValueError(f"Target {target} not supported") - - events = [] - if self.completed_check.isChecked(): - events.append(ScheduleItemStatus.COMPLETED) - if self.aborted_check.isChecked(): - events.append(ScheduleItemStatus.ABORTED) - if self.failed_check.isChecked(): - events.append(ScheduleItemStatus.FAILED) - + target = ( + NotificationTarget.SIGNAL + if self.signal_radio.isChecked() + else NotificationTarget.SCILOG + ) return NotificationSettings( enabled=self.enabled_check.isChecked(), notify_scan=self.scan_check.isChecked(), notify_move=self.move_check.isChecked(), - notify_rpc=self.rpc_check.isChecked(), + notify_device=self.device_check.isChecked(), target=target, - events=events, - teams_scope=self.teams_combo.currentText().strip() or None, + events=[status for status, check in self._event_checks.items() if check.isChecked()], signal_number=self.signal_combo.currentText().strip() or None, ) - def _on_test_clicked(self): - settings = self._current_settings() + def _on_test_clicked(self) -> None: try: - send_notification(self._client, settings, "Test message from the BEC schedule widget.") + send_notification( + self._client, self._current_settings(), "Test message from the BEC Scheduler." + ) except Exception as exc: # pylint: disable=broad-except QMessageBox.critical(self, "Test message failed", str(exc)) return QMessageBox.information(self, "Test message sent", "The test message was sent.") def result_settings(self) -> NotificationSettings: - """Valid after `exec_()` returns `QDialog.Accepted`.""" + """The edited settings; valid after `exec_()` returned `QDialog.Accepted`.""" return self._current_settings() - - -def _dim_label(text: str) -> QLabel: - label = QLabel(text) - label.setStyleSheet("color: gray;") - label.setWordWrap(True) - return label diff --git a/debye_bec/bec_widgets/widgets/scheduler/notifications.py b/debye_bec/bec_widgets/widgets/scheduler/notifications.py index bd8fbf3..fd0169b 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/notifications.py +++ b/debye_bec/bec_widgets/widgets/scheduler/notifications.py @@ -1,158 +1,113 @@ """ -A small, self-contained "tell the user when something finished/failed" -feature, independent of scheduling/execution logic. +"Tell the user when something finished/failed" - independent of the scheduling logic. -Sends through BEC's own `client.messaging` container -(`bec_lib.messaging_services.MessagingContainer`, exposed as `bec.messaging` -in the IPython client) - the same mechanism documented at -https://bec.readthedocs.io/latest/how-to/general/send-messages-to-signal.html -and +Messages are sent through BEC's own messaging services (`client.messaging`), see +https://bec.readthedocs.io/latest/how-to/general/send-messages-to-signal.html and https://bec.readthedocs.io/latest/how-to/general/send-messages-to-scilog.html: - bec.messaging.signal.new("Beamline checks completed.").send(scope="+41791234567") bec.messaging.scilog.new("Beamline checks completed.").send() - bec.messaging.teams.new("Beamline checks completed.").send(scope=) + bec.messaging.signal.new("Beamline checks completed.").send(scope="+41791234567") -Notes on each service, read directly from `bec_lib.messaging_services` -rather than assumed: +- **SciLog** needs no scope: it posts to the logbook of the currently active pgroup. +- **Signal** accepts a raw phone number as scope (BEC normalises it, defaulting to the Swiss + country code) or the name of a pre-registered scope. -- **SciLog** needs no `scope` - it posts to the logbook of the currently - active pgroup automatically. -- **Signal** accepts a raw phone number as `scope` (BEC normalizes it, - defaulting to the Swiss country code for numbers without one - see the - docs above) *or* a pre-registered scope name for a group. -- **Teams** is a plain `MessagingService` with no Teams-specific methods: - a contact/channel can only be addressed by a `scope` an admin has - already registered for the deployment (`service._scopes`) - there is no - way to address an arbitrary Teams user/email directly from the client. - This is why the Teams UI in `notification_dialog.py` is a dropdown of - known scopes rather than free text, while Signal's is free text (with - any registered scopes offered as suggestions). - -`client.messaging.._enabled` / `._scopes` are the only -introspection available (no public accessor exists at the time of -writing) - used here and in the dialog to grey out a target that isn't -configured for the current session instead of only failing at send time. +The settings model (`NotificationSettings`) lives in `models.py`, as it is persisted with the +schedule. """ from __future__ import annotations -from enum import Enum +from typing import Literal from bec_lib.logger import bec_logger -from pydantic import BaseModel -from .enums import ScheduleItemStatus +from .actions import ACTIONS +from .models import NotificationSettings, NotificationTarget, ScheduleItem logger = bec_logger.logger +ScheduleState = Literal[ + "started", "finished", "aborted", "paused", "paused_on_failure", "widget_closed" +] -class NotificationTarget(str, Enum): - SCILOG = "scilog" - TEAMS = "teams" - SIGNAL = "signal" +_STATE_TEXT: dict[str, str] = { + "started": "has started", + "finished": "has finished", + "aborted": "was aborted", + "paused": "was paused", + "paused_on_failure": "was paused because an item failed", + "widget_closed": "has stopped prematurely because the widget was closed", +} -class NotificationSettings(BaseModel): - """Persisted per-schedule notification preferences.""" - - enabled: bool = False - notify_scan: bool = True - notify_move: bool = True - # "custom" is what this plugin calls the free-text tab (see - # item_dialog.py) - it covers RPC calls to other widgets as well as - # any hand-typed command, so it's exposed to the user as "RPC". - notify_rpc: bool = True - - target: NotificationTarget = NotificationTarget.SCILOG - events: list[ScheduleItemStatus] = [] - teams_scope: str | None = None # a pre-registered Teams scope (channel/contact) - signal_number: str | None = None # a phone number, or a pre-registered Signal scope - - -def _enabled_for_kind(settings: NotificationSettings, kind: str) -> bool: - if not settings.enabled: - return False +def _enabled_for_category(settings: NotificationSettings, category: str) -> bool: return { "scan": settings.notify_scan, "move": settings.notify_move, - "custom": settings.notify_rpc, - }.get(kind, False) + "device": settings.notify_device, + }.get(category, False) def send_notification(client, settings: NotificationSettings, text: str) -> None: """ - Send `text` through whichever service `settings.target` selects. + Send `text` through the service selected by `settings.target`. - Raises on failure (no target selected, missing Teams scope/Signal - number, the target service not enabled for this session, ...) - - callers that want a fire-and-forget send should catch around this. - `notify_item_finished` does; the dialog's "Send test message" button - deliberately does not, so the operator sees exactly what went wrong. + Raises: + ValueError: If the target is not configured (e.g. no Signal number). + Exception: Whatever the BEC messaging service raises. Callers that want a + fire-and-forget send must catch it; the dialog's "Send test message" button + deliberately does not, so the operator sees what went wrong. """ if settings.target == NotificationTarget.SCILOG: client.messaging.scilog.new(text).send() - elif settings.target == NotificationTarget.TEAMS: - if not settings.teams_scope: - raise ValueError("No Teams contact/channel selected.") - client.messaging.teams.new(text).send(scope=settings.teams_scope) elif settings.target == NotificationTarget.SIGNAL: if not settings.signal_number: raise ValueError("No Signal phone number/contact set.") client.messaging.signal.new(text).send(scope=settings.signal_number) else: - raise ValueError("No notification target selected.") + raise ValueError(f"Unsupported notification target {settings.target!r}.") def notify_item_finished( - client, - kind: str, - command: str, - scan_number: str, - final_status: ScheduleItemStatus, - settings: NotificationSettings, - error: str | None = None, -): + client, settings: NotificationSettings, item: ScheduleItem, description: str +) -> None: """ - Sends a message if notifications are enabled for `kind` and a target - is configured. Never raises - a notification failing to send should - not affect schedule execution. + Send a message about a finished schedule item, if notifications are enabled for the item's + category and final status. Never raises. + + Args: + client: BEC client. + settings: Notification settings of the schedule. + item: The finished item (COMPLETED, FAILED or ABORTED). + description: Human-readable description of the item (the "Command" column text). """ - if not _enabled_for_kind(settings, kind): + spec = ACTIONS.get(item.action) + if not settings.enabled or spec is None or not _enabled_for_category(settings, spec.category): return - if final_status not in settings.events: + if item.status not in settings.events: return - status_word = final_status.name - text = f"**BEC Scheduler Widget**\nStatus: {kind} {status_word}" - if scan_number is not None: - text = text + f"\nScan number: {scan_number}" - text = text + f"\n\nCommand: {command}" - if error: - text += f"\n\n{error.strip().splitlines()[-1]}" + text = f"**BEC Scheduler**\n{spec.label} {item.status.name.lower()}" + if item.scan_number is not None: + text += f"\nScan number: {item.scan_number}" + text += f"\n\n{description}" + if item.report: + text += f"\n\n{item.report}" + _send_safe(client, settings, text) - try: - send_notification(client, settings, text) - except Exception: # pylint: disable=broad-except - logger.exception(f"Failed to send schedule notification via {settings.target.value}") +def notify_schedule_state( + client, settings: NotificationSettings, schedule_name: str, state: ScheduleState +) -> None: + """Send a message when the schedule starts or stops (if notifications are on). Never raises.""" + if not settings.enabled: + return + text = f'**BEC Scheduler**\nSchedule "{schedule_name}" {_STATE_TEXT.get(state, state)}' + _send_safe(client, settings, text) -def notify_schedule_state(client, settings, schedule_name, state): - """ - Sends a message if notifications are enabled and a schedule is started or stopped. - Never raises - a notification failing to send should not affect schedule execution. - """ - text = f'**BEC Scheduler Widget**\nSchedule "{schedule_name}" ' - if state == "started": - text = text + "has started" - elif state == "aborted": - text = text + "was aborted" - elif state == "widget_closed": - text = text + "has finished prematurely because widget was closed" - elif state == "finished": - text = text + "has finished" - else: - logger.warning(f"Unknown schedule state {state}") + +def _send_safe(client, settings: NotificationSettings, text: str) -> None: try: send_notification(client, settings, text) except Exception: # pylint: disable=broad-except diff --git a/debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py b/debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py deleted file mode 100644 index 884da3a..0000000 --- a/debye_bec/bec_widgets/widgets/scheduler/qt_widgets.py +++ /dev/null @@ -1,159 +0,0 @@ -from bec_widgets.utils.colors import get_accent_colors -from qtpy.QtCore import QModelIndex, QSize, Qt, Signal - -# pylint: disable=E0611 -from qtpy.QtGui import QKeySequence -from qtpy.QtWidgets import QHeaderView, QPushButton, QStyle, QStyledItemDelegate, QTableView - -_ROW_MARGIN = 2 # total vertical padding (top+bottom) added around the text block - - -class _MultilineTextDelegate(QStyledItemDelegate): - """ - Paints and sizes a cell whose DisplayRole text may contain literal - '\\n' line breaks (schedule item labels are built with explicit line - breaks, e.g. the digital-twin config summary). The base - QStyledItemDelegate only reliably shows a single line, so without this - a multi-line label got clipped once rows stopped auto-sizing the way - QListWidgetItem used to. `sizeHint()` reports the full multi-line - height so the view's ResizeToContents row mode can actually fit it. - - Selection is painted here with `option.palette.highlight()` - the - same approach BecLogTableView's `_LogCellDelegate` uses - so the row - gets the theme's native (blue) highlight color instead of whatever a - stylesheet might otherwise hardcode. - """ - - def paint(self, painter, option, index): - painter.save() - if option.state & QStyle.StateFlag.State_Selected: - painter.fillRect(option.rect, option.palette.highlight()) - painter.setPen(option.palette.highlightedText().color()) - else: - painter.setPen(option.palette.text().color()) - painter.setFont(option.font) - - text = index.data(Qt.ItemDataRole.DisplayRole) or "" - rect = option.rect.adjusted(4, _ROW_MARGIN // 2, -4, -(_ROW_MARGIN // 2)) - # painter.drawText(rect, int(Qt.TextFlag.TextWordWrap), text) - painter.drawText( - rect, - int( - Qt.TextFlag.TextWordWrap - | Qt.AlignmentFlag.AlignLeft - | Qt.AlignmentFlag.AlignVCenter - ), - text, - ) - painter.restore() - - def sizeHint(self, option, index): - text = index.data(Qt.ItemDataRole.DisplayRole) or "" - lines = text.count("\n") + 1 - height = option.fontMetrics.lineSpacing() * lines + _ROW_MARGIN - width = super().sizeHint(option, index).width() - return QSize(width, height) - - -class MyTableView(QTableView): - deletePressed = Signal() - emptySpaceClicked = Signal() - copyPressed = Signal() - pastePressed = Signal() - - # Column layout is fixed: 0 = status icon, 1 = text (stretches), 2 = pause-on-failure icon. - TEXT_COLUMN = 1 - - def __init__(self, parent=None, status_col_width: int = 60, pause_col_width: int = 130): - super().__init__(parent) - - self._status_col_width = status_col_width - self._pause_col_width = pause_col_width - - self.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows) - self.setSelectionMode(QTableView.SelectionMode.SingleSelection) - self.setEditTriggers(QTableView.EditTrigger.NoEditTriggers) - self.setShowGrid(False) - self.setWordWrap(True) - - self.setItemDelegateForColumn(self.TEXT_COLUMN, _MultilineTextDelegate(self)) - - self.verticalHeader().hide() - # ResizeToContents (not Fixed) so a row grows to fit however many - # lines its text cell reports via the delegate's sizeHint above - - # this is what lets multi-line item text show in full again. - self.verticalHeader().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents) - - # No `:selected` rule here on purpose - leaving it out lets Qt fall - # back to the palette highlight color (blue) for selected rows, - # matching BecLogTableView instead of a hardcoded dark gray. - # self.setStyleSheet(""" - # QTableView::item { - # border-bottom: 1px solid #444444; - # padding: 4px; - # } - # """) - - def configure_columns(self): - header = self.horizontalHeader() - - header.setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed) - header.setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch) - header.setSectionResizeMode(2, QHeaderView.ResizeMode.Fixed) - - header.resizeSection(0, self._status_col_width) - header.resizeSection(2, self._pause_col_width) - - header.setStretchLastSection(False) - header.setDefaultAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) - - def keyPressEvent(self, event): - if event.key() == Qt.Key_Delete and self.currentIndex().isValid(): - self.deletePressed.emit() - event.accept() - return - - if event.matches(QKeySequence.StandardKey.Copy) and self.currentIndex().isValid(): - self.copyPressed.emit() - event.accept() - return - - if event.matches(QKeySequence.StandardKey.Paste): - self.pastePressed.emit() - event.accept() - return - - super().keyPressEvent(event) - - def mousePressEvent(self, event): - if ( - event.button() == Qt.LeftButton - and not self.indexAt(event.position().toPoint()).isValid() - ): - self.clearSelection() - self.setCurrentIndex(QModelIndex()) - self.emptySpaceClicked.emit() - return - - super().mousePressEvent(event) - - -class MyButton(QPushButton): - def __init__(self, text="", color="default", parent=None): - self.color = color - super().__init__(text, parent) - self.apply_theme() - - def apply_theme(self): - if self.isEnabled(): - colors = get_accent_colors() - color = getattr(colors, self.color).name() - self.setStyleSheet(f"QPushButton {{ background-color: {color}; color: white; }}") - else: - self.setStyleSheet( - "QPushButton {{background-color: rgb(120, 120, 120); color: white;}}" - ) - - def setEnabled(self, enable: bool = True): - super().setEnabled(enable) - self.apply_theme() diff --git a/debye_bec/bec_widgets/widgets/scheduler/schedule_item.py b/debye_bec/bec_widgets/widgets/scheduler/schedule_item.py deleted file mode 100644 index f58fb07..0000000 --- a/debye_bec/bec_widgets/widgets/scheduler/schedule_item.py +++ /dev/null @@ -1,70 +0,0 @@ -""" -Plain (non-BECMessage) data model for one schedule entry and the schedule -as a whole. - -These are ordinary pydantic models used only client-side, for validation -and convenience. They are never sent over Redis as their own type - only -ever as the `.value` payload of a `bec_lib.messages.VariableMessage` (see -`endpoints.schedule` for why). -""" - -from __future__ import annotations - -from enum import Enum -from typing import Literal - -from pydantic import BaseModel, Field - -from .enums import ScheduleItemStatus -from .guard import GuardSettings -from .notifications import NotificationSettings - -# Which tab of the Add/Edit dialog built `command`, and therefore how to -# re-open that dialog pre-filled with the same values for editing. "custom" -# covers hand-typed text (including RPC calls to other widgets), which has -# no structured `form_state` to restore beyond the raw text itself. -ScheduleItemKind = Literal["scan", "move", "custom"] - - -class ScheduleItem(BaseModel): - """A single command in the schedule, plus its execution bookkeeping.""" - - item_id: str - command: str - status: ScheduleItemStatus = ScheduleItemStatus.PENDING - - # How `command` was produced, and (for "scan"/"move") the structured - # inputs behind it, so the Add/Edit dialog can be reopened pre-filled - # instead of asking the user to re-type everything. `command` itself - # remains the single source of truth actually evaluated at execution - # time - `kind`/`form_state` only drive the UI. - kind: ScheduleItemKind = "custom" - form_state: dict | None = None - pause_on_failure: bool - - # Bookkeeping used to reconnect to a submission that is still (or was) - # in flight on the BEC scan/device server, after this widget has been - # closed and reopened. - request_id: str | None = None - scan_id: str | None = None - scan_number: int | None = None - - error: str | None = None - started_at: float | None = None - finished_at: float | None = None - - -class Schedule(BaseModel): - """The full, persisted state of one schedule-widget instance.""" - - schedule_name: str - items: list[ScheduleItem] = Field(default_factory=list) - is_running: bool = False - notes: str = "" - - # Settings for two independent, optional features (see notifications.py - # and guard.py) - persisted here alongside the schedule itself so they - # survive a widget restart too, but their *logic* lives entirely in - # those separate modules; this is just where their settings are stored. - notifications: NotificationSettings = Field(default_factory=NotificationSettings) - guard: GuardSettings = Field(default_factory=GuardSettings) diff --git a/debye_bec/bec_widgets/widgets/scheduler/schedule_logic.py b/debye_bec/bec_widgets/widgets/scheduler/schedule_logic.py index c229619..10e9adc 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/schedule_logic.py +++ b/debye_bec/bec_widgets/widgets/scheduler/schedule_logic.py @@ -1,35 +1,99 @@ """ -Pure bookkeeping over a list of `ScheduleItem`s - no Qt, no locking, no I/O. -Kept separate from `schedule_widget.py` for the same reason `guard.py` and -`notifications.py` are: it's testable on its own, and the widget should -only be responsible for Qt/orchestration, not figuring out which item runs -next. +Pure bookkeeping over a list of `ScheduleItem`s - no Qt, no locking, no I/O - so that it can be +unit-tested on its own. Callers (the widget and the executor) hold their own lock while calling +these functions. -The one invariant everything here assumes and preserves: at any moment, a -schedule's items form a (possibly empty) prefix that is no longer PENDING -(RUNNING - at most one, the one currently executing - COMPLETED, FAILED or -ABORTED), followed by a suffix that is entirely PENDING. `ScheduleWidget` -is responsible for only ever mutating the PENDING suffix (see its module -docstring) and for calling these functions while holding its lock; nothing -here does its own locking. +Two concepts are handled here: + +**Protected prefix.** Items are executed from top to bottom. Everything before the first PENDING +item has already started or finished (RUNNING, COMPLETED, FAILED, ABORTED) and must not be +moved, edited or deleted; new items can never be inserted before it. Because of background items +(see below), several items of that prefix may be RUNNING at the same time. + +**Blocks.** An item with `wait_for_completion=False` ("background item") is started and the +schedule immediately continues with the following items, which form its *block* and are shown +indented. A block ends + +- with a "Wait until parent has completed" item (which belongs to the block, as its last child), +- implicitly right before the next background item (no nesting), or +- at the end of the schedule. + +The block structure is derived from the item order every time it is needed and never stored, so +moving, adding or deleting items automatically updates which block an item belongs to. """ from __future__ import annotations -from typing import Literal +from enum import Enum -from bec_lib.logger import bec_logger +from .actions import WAIT_FOR_PARENT +from .models import ItemStatus, ScheduleItem -from .schedule_item import ScheduleItem, ScheduleItemStatus -logger = bec_logger.logger +class BlockRole(str, Enum): + """Position of an item relative to the block structure (used for drawing guide lines).""" + + NONE = "none" # not part of a block + PARENT = "parent" # background item that opens a block + PARENT_EMPTY = "parent_empty" # background item without any children + CHILD = "child" # inside a block + LAST_CHILD = "last_child" # last item of a block + + +def opens_block(item: ScheduleItem) -> bool: + """True if the item is a background item, i.e. starts a block of following items.""" + return not item.wait_for_completion and item.action != WAIT_FOR_PARENT + + +def block_parents(items: list[ScheduleItem]) -> list[int | None]: + """ + For every item, the index of the background item whose block it belongs to. + + Returns: + A list with one entry per item: the index of its parent, or None if the item is not + inside a block. Background items themselves are never inside a block. + """ + parents: list[int | None] = [] + current: int | None = None + for idx, item in enumerate(items): + if opens_block(item): + current = idx + parents.append(None) + elif current is not None: + parents.append(current) + if item.action == WAIT_FOR_PARENT: + current = None + else: + parents.append(None) + return parents + + +def item_depths(items: list[ScheduleItem]) -> list[int]: + """Indentation level of every item: 1 inside a block, 0 otherwise.""" + return [0 if parent is None else 1 for parent in block_parents(items)] + + +def block_roles(items: list[ScheduleItem]) -> list[BlockRole]: + """The `BlockRole` of every item, e.g. for drawing the block guide lines in the table.""" + parents = block_parents(items) + roles: list[BlockRole] = [] + for idx, item in enumerate(items): + next_parent = parents[idx + 1] if idx + 1 < len(items) else None + if opens_block(item): + roles.append(BlockRole.PARENT if next_parent == idx else BlockRole.PARENT_EMPTY) + elif parents[idx] is not None: + last = next_parent != parents[idx] + roles.append(BlockRole.LAST_CHILD if last else BlockRole.CHILD) + else: + roles.append(BlockRole.NONE) + return roles def protected_prefix_length(items: list[ScheduleItem]) -> int: - """How many items, from the start, are no longer PENDING.""" + """Number of leading items that are no longer PENDING (see module docstring).""" count = 0 for item in items: - if item.status != ScheduleItemStatus.PENDING: + if item.status != ItemStatus.PENDING: count += 1 else: break @@ -37,39 +101,53 @@ def protected_prefix_length(items: list[ScheduleItem]) -> int: def index_of(items: list[ScheduleItem], item_id: str | None) -> int | None: + """Index of the item with `item_id`, or None if there is no such item.""" if item_id is None: return None - for i, item in enumerate(items): + for idx, item in enumerate(items): if item.item_id == item_id: - return i + return idx return None def pick_next_runnable( - items: list[ScheduleItem], repeat_aborted_item, first_item: int = 0 -) -> ScheduleItem | Literal["stop"] | None: + items: list[ScheduleItem], + retry_unfinished: bool = False, + first_index: int = 0, + active_ids: frozenset[str] | set[str] = frozenset(), + attempted_ids: frozenset[str] | set[str] = frozenset(), +) -> ScheduleItem | None: """ - What the execution loop should do next: always re-derived from scratch - (never a remembered index/object) so edits made to the PENDING suffix - between calls are picked up correctly. + Decide which item the execution loop should handle next. - Returns the next item to run/attach to, the string `"stop"` if an - earlier item failed/was aborted (execution stays parked there until the - operator intervenes), or `None` if every item is COMPLETED. + This is always re-derived from the current list (never a remembered index), so edits to the + PENDING part of the schedule between two calls are picked up. + + Args: + items: The schedule items. + retry_unfinished: If True, FAILED and ABORTED items are run again (once per run, see + `attempted_ids`); otherwise they are skipped. + first_index: Items before this index are ignored ("run from selection"). + active_ids: Ids of items that are currently being executed by this executor (e.g. a + running background item); they are skipped. + attempted_ids: Ids of items already started during the current run. A FAILED/ABORTED + item is only retried if it has not been attempted in this run yet, so a failing + item cannot be retried in an endless loop. + + Returns: + The next PENDING item, a RUNNING item that is not owned by this executor (left over + from a previous widget session; the caller should re-attach to it), a FAILED/ABORTED + item if `retry_unfinished` is set, or None if nothing is left to do. """ - logger.info( - f"pick next runnable, repeat abort item is {repeat_aborted_item} and first item is {first_item}" - ) for idx, item in enumerate(items): - logger.info(f"item: {item}") - if idx < first_item: + if idx < first_index or item.item_id in active_ids: continue - if item.status == ScheduleItemStatus.COMPLETED: - continue - if item.status == ScheduleItemStatus.ABORTED: - if not repeat_aborted_item: - continue - if item.status == ScheduleItemStatus.FAILED: - return "stop" - return item # PENDING, RUNNING or ABORTED if repeat_aborted_item is set (reconciled as still active) + if item.status in (ItemStatus.PENDING, ItemStatus.RUNNING): + return item + if ( + retry_unfinished + and item.status in (ItemStatus.FAILED, ItemStatus.ABORTED) + and item.item_id not in attempted_ids + ): + return item return None diff --git a/debye_bec/bec_widgets/widgets/scheduler/schedule_table.py b/debye_bec/bec_widgets/widgets/scheduler/schedule_table.py new file mode 100644 index 0000000..d1929ed --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/schedule_table.py @@ -0,0 +1,397 @@ +""" +Table model and view showing a schedule. + +Columns: line number | status | command | report | pause on failure | pause on state | +wait for completion. All columns except "Command" and "Report" have a fixed width; those two +share the remaining width 50/50. + +Items inside the block of a background item (`wait_for_completion=False`) are indented in the +"Command" column, and a vertical guide line connects them with their parent, so it is visible +which items run while the parent is still busy (see `schedule_logic` for the block rules). +""" + +from __future__ import annotations + +import time + +from bec_qthemes import material_icon +from bec_widgets.utils.colors import get_accent_colors + +# pylint: disable=no-name-in-module # qtpy re-exports are not visible to pylint +from qtpy.QtCore import QAbstractTableModel, QModelIndex, QRect, QSize, Qt, Signal +from qtpy.QtGui import QKeySequence, QPen +from qtpy.QtWidgets import QHeaderView, QStyle, QStyledItemDelegate, QTableView + +from .actions import ACTIONS, DELAY, describe_item, format_duration +from .models import ItemStatus, ScheduleItem +from .schedule_logic import BlockRole, block_roles, item_depths + +# Qt virtual overrides (rowCount, data, paint, sizeHint, ...) keep Qt's names and docs. +# pylint: disable=invalid-name,missing-function-docstring,too-many-return-statements + + +ICON_SIZE = 20 +INDENT_WIDTH = 24 # px per indentation level in the "Command" column +_ROW_MARGIN = 6 # total vertical padding (top + bottom) of a text cell + +_STATUS_ICONS = { + ItemStatus.PENDING: ("hourglass", "#919090"), + ItemStatus.RUNNING: ("cycle", "#2980b9"), + ItemStatus.COMPLETED: ("check", "#27ae60"), + ItemStatus.FAILED: ("warning", "#e74c3c"), + ItemStatus.ABORTED: ("cancel", "#e6d922"), +} + +#: Custom data roles +DepthRole = Qt.ItemDataRole.UserRole + 1 +BlockRoleRole = Qt.ItemDataRole.UserRole + 2 + + +class ScheduleTableModel(QAbstractTableModel): + """ + Read-only table model over a snapshot of `Schedule.items`. + + The widget calls `set_items()` with a fresh copy whenever the schedule changes (a full model + reset - schedules are short, and this keeps the model free of locking). Display text comes + from the action registry (`actions.describe_item`), block indentation from + `schedule_logic.item_depths`. + """ + + COL_LINE = 0 + COL_STATUS = 1 + COL_COMMAND = 2 + COL_REPORT = 3 + COL_PAUSE_ON_FAILURE = 4 + COL_PAUSE_ON_STATE = 5 + COL_WAIT = 6 + HEADERS = ( + "Line", + "Status", + "Command", + "Report", + "Pause on failure", + "Pause on state", + "Wait for completion", + ) + ICON_COLUMNS = (COL_STATUS, COL_PAUSE_ON_FAILURE, COL_PAUSE_ON_STATE, COL_WAIT) + + def __init__(self, parent=None, beamline: str | None = None): + super().__init__(parent) + self._items: list[ScheduleItem] = [] + self._depths: list[int] = [] + self._roles: list[BlockRole] = [] + self._beamline = beamline + # The status icon of the selected row is drawn white (on the selection colour). Kept + # here rather than read from the view so it survives a model reset. + self._selected_item_id: str | None = None + + # ---- Qt model API ---- # + def rowCount(self, parent: QModelIndex = QModelIndex()) -> int: # noqa: N802 + return 0 if parent.isValid() else len(self._items) + + def columnCount(self, parent: QModelIndex = QModelIndex()) -> int: # noqa: N802 + return 0 if parent.isValid() else len(self.HEADERS) + + def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole): # noqa: N802 + if orientation != Qt.Orientation.Horizontal: + return None + if role == Qt.ItemDataRole.DisplayRole: + return self.HEADERS[section] + if role == Qt.ItemDataRole.TextAlignmentRole: + if section in (self.COL_COMMAND, self.COL_REPORT): + return int(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) + return int(Qt.AlignmentFlag.AlignCenter) + return None + + def data(self, index: QModelIndex, role=Qt.ItemDataRole.DisplayRole): + if not index.isValid(): + return None + row, col = index.row(), index.column() + item = self._items[row] + + if role == Qt.ItemDataRole.DisplayRole: + if col == self.COL_LINE: + return str(row + 1) + if col == self.COL_COMMAND: + return describe_item(item, self._beamline) + if col == self.COL_REPORT: + return self._report_text(item) + return None + if role == Qt.ItemDataRole.DecorationRole: + return self._icon(item, col) + if role == Qt.ItemDataRole.ToolTipRole: + return self._tooltip(item, col) + if role == Qt.ItemDataRole.TextAlignmentRole and col == self.COL_LINE: + return int(Qt.AlignmentFlag.AlignCenter) + if role == DepthRole: + return self._depths[row] + if role == BlockRoleRole: + return self._roles[row] + return None + + # ---- content ---- # + def set_items(self, items: list[ScheduleItem], selected_item_id: str | None = None) -> None: + """ + Replace the displayed items (full model reset). + + Args: + items: Snapshot of the schedule items. + selected_item_id: Item whose status icon is drawn for the selected row. + """ + self.beginResetModel() + self._selected_item_id = selected_item_id + self._items = list(items) + self._depths = item_depths(self._items) + self._roles = block_roles(self._items) + self.endResetModel() + + def set_selected_item_id(self, item_id: str | None) -> None: + """Remember the selected item and repaint the status icons (no full reset).""" + self._selected_item_id = item_id + self._emit_column_changed(self.COL_STATUS, [Qt.ItemDataRole.DecorationRole]) + + def refresh_live_cells(self) -> None: + """Repaint the report of running delays (remaining time). Called once per second.""" + if any(item.status == ItemStatus.RUNNING and item.action == DELAY for item in self._items): + self._emit_column_changed(self.COL_REPORT, [Qt.ItemDataRole.DisplayRole]) + + def item_id(self, row: int) -> str | None: + """Id of the item in `row`, or None.""" + return self._items[row].item_id if 0 <= row < len(self._items) else None + + def row_of(self, item_id: str | None) -> int | None: + """Row of the item with `item_id`, or None.""" + for row, item in enumerate(self._items): + if item.item_id == item_id: + return row + return None + + def _emit_column_changed(self, column: int, roles: list) -> None: + if self._items: + self.dataChanged.emit( + self.index(0, column), self.index(len(self._items) - 1, column), roles + ) + + # ---- cell content helpers ---- # + @staticmethod + def _report_text(item: ScheduleItem) -> str: + if item.status == ItemStatus.RUNNING and item.action == DELAY and item.started_at: + remaining = item.params.get("seconds", 0) - (time.time() - item.started_at) + return f"{format_duration(remaining)} remaining" + if item.status == ItemStatus.RUNNING and not item.report: + return "Running..." + return item.report or "" + + def _icon(self, item: ScheduleItem, col: int): + if col == self.COL_STATUS: + name, color = _STATUS_ICONS[item.status] + if item.item_id == self._selected_item_id: + color = "#FFFFFF" + return _pixmap(name, color) + if col == self.COL_PAUSE_ON_FAILURE and item.pause_on_failure: + return _pixmap("pause_circle", "#e6d922") + if col == self.COL_PAUSE_ON_STATE and item.pause_on_state: + return _pixmap("shield", "#2980b9") + if col == self.COL_WAIT and ACTIONS.get(item.action) is not None: + if ACTIONS[item.action].category == "control": + return None + if item.wait_for_completion: + return _pixmap("hourglass_bottom", "#919090") + return _pixmap("call_split", get_accent_colors().highlight.name()) + return None + + @staticmethod + def _tooltip(item: ScheduleItem, col: int) -> str | None: + if col == ScheduleTableModel.COL_STATUS: + return item.status.name.capitalize() + if col == ScheduleTableModel.COL_REPORT and item.error: + return item.error + if col == ScheduleTableModel.COL_PAUSE_ON_FAILURE: + return "Pauses the schedule if this item fails" if item.pause_on_failure else None + if col == ScheduleTableModel.COL_PAUSE_ON_STATE: + if item.pause_on_state: + return ( + "Waits for all beamline states to be valid before starting;\n" + "running scans are interrupted and repeated if a state becomes invalid" + ) + return None + if col == ScheduleTableModel.COL_WAIT: + if not item.wait_for_completion: + return "Runs in the background: the following (indented) items start right away" + return "The schedule waits for this item to complete" + return None + + +def _pixmap(name: str, color: str): + return material_icon(name, size=(ICON_SIZE, ICON_SIZE), color=color, convert_to_pixmap=True) + + +def _paint_background(painter, option) -> None: + if option.state & QStyle.StateFlag.State_Selected: + painter.fillRect(option.rect, option.palette.highlight()) + painter.setPen(option.palette.highlightedText().color()) + else: + painter.setPen(option.palette.text().color()) + + +class _TextDelegate(QStyledItemDelegate): + """ + Paints multi-line text (labels contain explicit line breaks) and reports the full multi-line + height, so the view's ResizeToContents row mode can fit it. If `indent` is True, the text is + indented by the item's block depth and the block guide line is drawn. + + Selection is painted with the palette highlight colour, like `BecLogTableView`. + """ + + def __init__(self, parent=None, indent: bool = False): + super().__init__(parent) + self._indent = indent + + def paint(self, painter, option, index): + painter.save() + _paint_background(painter, option) + painter.setFont(option.font) + text_pen = painter.pen() + + rect = option.rect.adjusted(6, _ROW_MARGIN // 2, -6, -(_ROW_MARGIN // 2)) + if self._indent: + depth = index.data(DepthRole) or 0 + self._paint_guide(painter, option.rect, index.data(BlockRoleRole)) + rect.setLeft(rect.left() + depth * INDENT_WIDTH) + painter.setPen(text_pen) + text = index.data(Qt.ItemDataRole.DisplayRole) or "" + flags = ( + Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter + ) + painter.drawText(rect, int(flags), text) + painter.restore() + + @staticmethod + def _paint_guide(painter, rect: QRect, role: BlockRole | None) -> None: + if role in (None, BlockRole.NONE, BlockRole.PARENT_EMPTY): + return + pen = QPen(get_accent_colors().highlight) + pen.setWidth(2) + painter.setPen(pen) + x = rect.left() + 10 + mid = rect.center().y() + if role == BlockRole.PARENT: + painter.drawLine(x, mid + 4, x, rect.bottom()) + else: + bottom = mid if role == BlockRole.LAST_CHILD else rect.bottom() + painter.drawLine(x, rect.top(), x, bottom) + painter.drawLine(x, mid, x + INDENT_WIDTH - 8, mid) + + def sizeHint(self, option, index): # noqa: N802 + text = index.data(Qt.ItemDataRole.DisplayRole) or "" + lines = text.count("\n") + 1 + height = option.fontMetrics.lineSpacing() * lines + _ROW_MARGIN + return QSize(super().sizeHint(option, index).width(), max(height, ICON_SIZE + _ROW_MARGIN)) + + +class _CenteredIconDelegate(QStyledItemDelegate): + """Paints the DecorationRole pixmap centred in the cell.""" + + def paint(self, painter, option, index): + painter.save() + _paint_background(painter, option) + pixmap = index.data(Qt.ItemDataRole.DecorationRole) + if pixmap is not None: + x = option.rect.center().x() - ICON_SIZE // 2 + y = option.rect.center().y() - ICON_SIZE // 2 + painter.drawPixmap(x, y, pixmap) + painter.restore() + + +class _CenteredTextDelegate(QStyledItemDelegate): + """Paints short single-line text centred in the cell (line numbers).""" + + def paint(self, painter, option, index): + painter.save() + _paint_background(painter, option) + painter.drawText( + option.rect, int(Qt.AlignmentFlag.AlignCenter), index.data(Qt.ItemDataRole.DisplayRole) + ) + painter.restore() + + +class ScheduleTableView(QTableView): + """ + Table view for a `ScheduleTableModel`: single row selection, fixed-width icon columns, + "Command" and "Report" sharing the remaining width, plus keyboard shortcuts. + + Signals: + deletePressed: The Delete key was pressed on a selected row. + copyPressed / pastePressed: The standard copy/paste shortcut was pressed. + emptySpaceClicked: The user clicked below the last row (clears the selection). + """ + + deletePressed = Signal() + emptySpaceClicked = Signal() + copyPressed = Signal() + pastePressed = Signal() + + FIXED_WIDTHS = { + ScheduleTableModel.COL_LINE: 50, + ScheduleTableModel.COL_STATUS: 60, + ScheduleTableModel.COL_PAUSE_ON_FAILURE: 120, + ScheduleTableModel.COL_PAUSE_ON_STATE: 110, + ScheduleTableModel.COL_WAIT: 145, + } + + def __init__(self, parent=None): + super().__init__(parent) + self.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows) + self.setSelectionMode(QTableView.SelectionMode.SingleSelection) + self.setEditTriggers(QTableView.EditTrigger.NoEditTriggers) + self.setShowGrid(False) + self.setWordWrap(True) + self.verticalHeader().hide() + # ResizeToContents so that a row grows with the number of text lines of its cells. + self.verticalHeader().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents) + + self.setItemDelegateForColumn(ScheduleTableModel.COL_LINE, _CenteredTextDelegate(self)) + self.setItemDelegateForColumn( + ScheduleTableModel.COL_COMMAND, _TextDelegate(self, indent=True) + ) + self.setItemDelegateForColumn(ScheduleTableModel.COL_REPORT, _TextDelegate(self)) + icon_delegate = _CenteredIconDelegate(self) + for col in ScheduleTableModel.ICON_COLUMNS: + self.setItemDelegateForColumn(col, icon_delegate) + + def configure_columns(self) -> None: + """Apply the column sizing; call after `setModel()`.""" + header = self.horizontalHeader() + header.setStretchLastSection(False) + for col, width in self.FIXED_WIDTHS.items(): + header.setSectionResizeMode(col, QHeaderView.ResizeMode.Fixed) + header.resizeSection(col, width) + # Both stretch columns get the same stretch factor -> the leftover width is shared 50/50. + header.setSectionResizeMode(ScheduleTableModel.COL_COMMAND, QHeaderView.ResizeMode.Stretch) + header.setSectionResizeMode(ScheduleTableModel.COL_REPORT, QHeaderView.ResizeMode.Stretch) + + def keyPressEvent(self, event): # noqa: N802 + if event.key() == Qt.Key.Key_Delete and self.currentIndex().isValid(): + self.deletePressed.emit() + event.accept() + return + if event.matches(QKeySequence.StandardKey.Copy) and self.currentIndex().isValid(): + self.copyPressed.emit() + event.accept() + return + if event.matches(QKeySequence.StandardKey.Paste): + self.pastePressed.emit() + event.accept() + return + super().keyPressEvent(event) + + def mousePressEvent(self, event): # noqa: N802 + if ( + event.button() == Qt.MouseButton.LeftButton + and not self.indexAt(event.position().toPoint()).isValid() + ): + self.clearSelection() + self.setCurrentIndex(QModelIndex()) + self.emptySpaceClicked.emit() + return + super().mousePressEvent(event) diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 61a786b..37104c5 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -1,303 +1,111 @@ """ -ScheduleWidget - persists an ordered schedule of BEC commands (scans, -device moves, ...) to Redis, executes them one by one, and survives being -closed and reopened - including while an item is still running -server-side. Items that have not started yet can be added, reordered or -deleted while the schedule is executing; items that have already started -or finished cannot. +Scheduler widget: build, persist and execute an ordered list of BEC actions (scans, moves, +beamline tools, delays, ...). + +Overview of the package: + +- `models.py`: persisted pydantic models (`Schedule`, `ScheduleItem`, notification settings). +- `actions.py`: function registry. Items store an action *name* plus JSON parameters; nothing is + ever `eval`-ed. +- `schedule_logic.py`: pure helpers (next item to run, protected prefix, block structure). +- `executor.py`: the execution loop, running on a worker thread. +- `state_monitor.py`: watches the BEC beamline states for "pause on state". +- `interlock_hiding.py`: hides the scan-interlock controls of the embedded BEC + `BeamlineStateManager`. +- `schedule_table.py`, `item_dialog.py`, `notification_dialog.py`, `widgets.py`: UI. +- `notifications.py`: SciLog/Signal notifications. + +Persistence: the whole schedule is one `VariableMessage` document in Redis (see `endpoints.py`), +keyed by the stable `schedule_name` of the widget config. It survives closing and reopening the +widget - also while an item is still running server-side; on reopen, the persisted state is +reconciled with BEC's scan queue. Items that have not started yet (PENDING) can be added, edited, +reordered or deleted at any time, also while the schedule runs; items that have started or +finished cannot. """ from __future__ import annotations import json -import re import sys import threading import time -import traceback -import uuid -from typing import Literal, Optional +from pathlib import Path -import numpy as np from bec_lib.endpoints import MessageEndpoints from bec_lib.logger import bec_logger from bec_lib.messages import VariableMessage -from bec_qthemes import material_icon from bec_widgets.utils.bec_connector import ConnectionConfig from bec_widgets.utils.bec_dispatcher import BECDispatcher from bec_widgets.utils.bec_widget import BECWidget from bec_widgets.utils.error_popups import SafeSlot -from pydantic import ValidationError +from bec_widgets.widgets.services.beamline_states.beamline_state_manager import BeamlineStateManager -# pylint: disable=E0611 -from qtpy.QtCore import QAbstractTableModel, QModelIndex, Qt, QTimer, Signal +# pylint: disable=no-name-in-module # qtpy re-exports are not visible to pylint +from qtpy.QtCore import QModelIndex, Qt, QTimer, Signal from qtpy.QtWidgets import ( QApplication, QDialog, QFileDialog, QGroupBox, QHBoxLayout, - QHeaderView, QLabel, QLineEdit, QMessageBox, QPlainTextEdit, + QSplitter, QVBoxLayout, QWidget, ) +from .actions import ACTIONS, ALWAYS_WAIT_ACTIONS, ExecutionContext, describe_item from .endpoints import schedule as schedule_endpoint -from .enums import ScheduleItemStatus -from .guard import SignalGuard -from .guard_dialog import GuardSettingsDialog -from .item_dialog import ScheduleItemDialog +from .executor import RunOutcome, ScheduleExecutor, is_queue_item_active +from .interlock_hiding import install_scan_interlock_hiding +from .item_dialog import XAS_BEAMLINES, ScheduleItemDialog +from .models import ItemStatus, NotificationTarget, Schedule, ScheduleItem, schedule_from_document from .notification_dialog import NotificationSettingsDialog -from .notifications import ( - NotificationSettings, - NotificationTarget, - notify_item_finished, - notify_schedule_state, -) -from .qt_widgets import MyButton, MyTableView -from .schedule_item import Schedule, ScheduleItem -from .schedule_logic import index_of, pick_next_runnable, protected_prefix_length +from .notifications import notify_item_finished, notify_schedule_state +from .schedule_logic import index_of, protected_prefix_length +from .schedule_table import ScheduleTableModel, ScheduleTableView +from .state_monitor import BeamlineStateMonitor +from .widgets import AccentButton logger = bec_logger.logger -_ACTIVE_QUEUE_STATES = ("PENDING", "RUNNING") - -ICON_SIZE = 20 -_ICON_MAP = { - ScheduleItemStatus.PENDING: ("hourglass", "#919090"), - ScheduleItemStatus.RUNNING: ("cycle", "#2980b9"), - ScheduleItemStatus.COMPLETED: ("check", "#27ae60"), - ScheduleItemStatus.FAILED: ("warning", "#e74c3c"), - ScheduleItemStatus.ABORTED: ("cancel", "#e6d922"), -} - - -def build_item_display_text(item: ScheduleItem, beamline: str | None) -> str: - """ - Build the human-readable label for a schedule item, pulled out of the - old `_refresh_ui` QListWidgetItem-building loop so the table model's - `data()` can call it too. Pure function of (item, beamline) - no Qt - widgets, no locking - so it's safe to call from the model on every - repaint. - """ - text = "" - if item.form_state is not None: - if item.command.startswith("scans.xas_simple_scan"): - text = ( - f"XAS simple scan from {item.form_state['kwargs']['start']} eV to " - + f"{item.form_state['kwargs']['stop']} eV, {item.form_state['kwargs']['scan_time']}" - + f" s per spectrum, measure {item.form_state['kwargs']['scan_duration']}s" - + f"\n Comment: {item.form_state['kwargs']['metadata']['comment']}, " - + f"Sample Name: {item.form_state['kwargs']['metadata']['sample_name']}" - ) - elif re.match(r"^dev\..*\.move", item.command): - if item.form_state["relative"]: - text = f"Move {item.form_state['device_name']} by {item.form_state['value']:+g} {item.form_state['units']}" - else: - text = f"Move {item.form_state['device_name']} to {item.form_state['value']} {item.form_state['units']}" - elif item.command.startswith("dev.ic"): - text = ( - f"Fill {item.form_state['chamber']} with {item.form_state['conc1']} % " - + f"{item.form_state['gas1']} and {item.form_state['conc2']} % " - + f"{item.form_state['gas2']} to {item.form_state['pressure']} bar" - ) - elif item.command.startswith("dev.reffoilchanger"): - text = f"Insert {item.form_state['foil']} reference foil" - elif item.command.startswith("digital_twin.move_with_config({"): - config = item.form_state["config"] - if config["mo1_mode"] == "Monochromatic": - text = f"Align Beamline for {config['energy']:.0f} eV" - else: - text = "Align Beamline for pinkbeam" - text += ( - f"\n FE: {config['h_acc']*1e3:.3f} mrad x {config['v_acc']*1e3:.3f} mrad" - + f"\n CM: {config['cm_stripe']} at {config['cm_pitch']*1e3:.3f} mrad" - ) - if config["mo1_mode"] == "Monochromatic": - text += f"\n MO1: {config['mo1_xtal']}" - text += f"\n FM: {config['fm_stripe']} at {config['fm_rotx']*1e3:.3f} mrad" - if beamline == "x01da": - text += f"\n ES1: {config['ot_es1_trz']:.0f} mm" - text += f"\n SMPL_TRZ: {config['es1man_trz']:.3f} mm" - if beamline == "x01da": - text += f"\n SMPL-XRD: {config['smpl_to_xrd']:.3f} mm" - elif item.command.startswith("auto_gain.start("): - config = item.form_state["config"] - text += f"Auto-configure gains for {config['element']}, {config['edge']}-edge" - text += f"\nfor devices {config['all_amplifiers']}" - if config["link_ic0_ic1"]: - text += "\nLink IC0 and IC1 gains" - if config["compensate_ring_current"]: - text += "\nCalculate for 400 mA ring current" - if config["prohibited_gains"] != {}: - prohibited_gains = ( - "{" - + ", ".join( - f"{amp}: [" + ", ".join(f"{g:.0e}" for g in gains) + "]" - for amp, gains in config["prohibited_gains"].items() - ) - + "}" - ) - text += "\nProhibited gains: " + prohibited_gains - elif item.command.startswith("dev.univ_temp_cont.load_config("): - config = item.form_state["config"] - match config["power_mode"]: - case "Standby": - text += "Switch temperature controller to standby" - case "Configuration": - text += "Switch temperature controller to configuration mode" - case _: - text += ( - f"Set temperature controller target setpoint to {config['target_setpoint']}" - + f" °C\nwith ramp rate of {config['ramp_rate']} {config['ramp_rate_unit']}" - ) - elif item.command.startswith("dev.abs."): - action = item.form_state["action"] - text += f"{action} Absorber" - if text == "": - text = f"{item.command}" - if item.error: - text += f" ({item.error.strip().splitlines()[-1]})" - return text - - -class ScheduleTableModel(QAbstractTableModel): - """ - Read-mostly table model over `Schedule.items`, rebuilt in one shot via - `set_items()` whenever the Scheduler widget refreshes - the same - "clear and repopulate" pattern the old QListWidget code used, just - routed through Qt's model/view API instead of manual - QListWidgetItem management. Mirrors the shape of `BecLogTableView`'s - `BecLogsTableModel`: a flat Python list backing store, `data()` - dispatching on `role`/`column`, icons returned as pixmaps via - `DecorationRole`. - """ - - COL_STATUS = 0 - COL_TEXT = 1 - COL_PAUSE = 2 - _HEADERS = ("Status", "Item", "Pause on failure") - - def __init__(self, parent=None, beamline: str | None = None): - super().__init__(parent) - self._items: list[ScheduleItem] = [] - self._beamline = beamline - # Drives the "selected row -> white status icon" recolor; kept - # separate from the view's own selection model so the icon color - # survives a `set_items()` reset (which clears Qt's selection). - self._selected_item_id: str | None = None - - def rowCount(self, parent: QModelIndex = QModelIndex()) -> int: - return 0 if parent.isValid() else len(self._items) - - def columnCount(self, parent: QModelIndex = QModelIndex()) -> int: - return 0 if parent.isValid() else len(self._HEADERS) - - def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole): - if role == Qt.ItemDataRole.DisplayRole and orientation == Qt.Orientation.Horizontal: - return self._HEADERS[section] - return None - - def set_items(self, items: list[ScheduleItem]): - self.beginResetModel() - self._items = list(items) - self.endResetModel() - - def set_selected_item_id(self, item_id: str | None): - """ - Repaint just the status-icon column for the recolor - avoids a - full model reset, which would otherwise drop the view's own - selection/scroll state on every click. - """ - self._selected_item_id = item_id - if self._items: - top_left = self.index(0, self.COL_STATUS) - bottom_right = self.index(len(self._items) - 1, self.COL_STATUS) - self.dataChanged.emit(top_left, bottom_right, [Qt.ItemDataRole.DecorationRole]) - - def item_id(self, row: int) -> str | None: - if 0 <= row < len(self._items): - return self._items[row].item_id - return None - - def row_of(self, item_id: str | None) -> int | None: - if item_id is None: - return None - for row, item in enumerate(self._items): - if item.item_id == item_id: - return row - return None - - def item_at(self, row: int) -> ScheduleItem | None: - return self._items[row] if 0 <= row < len(self._items) else None - - def data(self, index: QModelIndex, role=Qt.ItemDataRole.DisplayRole): - if not index.isValid(): - return None - item = self._items[index.row()] - col = index.column() - - if role == Qt.ItemDataRole.DecorationRole: - if col == self.COL_STATUS: - icon_name, color = _ICON_MAP[item.status] - if item.item_id == self._selected_item_id: - color = "#FFFFFF" - return material_icon( - icon_name, size=(ICON_SIZE, ICON_SIZE), color=color, convert_to_pixmap=True - ) - if col == self.COL_PAUSE and item.pause_on_failure: - return material_icon( - "pause_circle", - size=(ICON_SIZE, ICON_SIZE), - color="#e6d922", - convert_to_pixmap=True, - ) - return None - - if role == Qt.ItemDataRole.DisplayRole and col == self.COL_TEXT: - return build_item_display_text(item, self._beamline) - - if role == Qt.ItemDataRole.ToolTipRole: - if col == self.COL_PAUSE: - return "Pauses the schedule if this item fails" if item.pause_on_failure else None - if item.error: - return item.error - - return None +# UI widgets are created in the _build_* helpers called from __init__. +# pylint: disable=attribute-defined-outside-init class ScheduleWidgetConfig(ConnectionConfig): """ - Per-instance identity/settings for `ScheduleWidget`, following the same - pattern `bec_widgets` itself uses (e.g. `ScanControlConfig`): a - `ConnectionConfig` subclass constructed in `__init__` when none is - passed, carrying whatever small settings distinguish one instance from - another. + Configuration of a `Scheduler` instance. - `schedule_name` lives here rather than as a bare constructor kwarg for - that consistency - but note this is *not* where the schedule's actual - contents (items, guard/notification settings) live: `self.config` is - used for RPC identity and optional explicit GUI-layout save/restore, - not auto-persisted across an ordinary widget close/reopen the way this - plugin's Redis-backed `Schedule` document is. Conflating the two would - quietly reintroduce the "closed widget loses its schedule" problem this - plugin exists to solve. + Attributes: + schedule_name: Stable name of the schedule. It selects the Redis document the schedule is + persisted in, so a widget opened again with the same name finds its schedule again + (unlike `gui_id`, which changes on every construction). The schedule *contents* are + not part of this config; they live in Redis (see `endpoints.schedule`). """ schedule_name: str = "default_schedule" class Scheduler(BECWidget, QWidget): - """Schedule, persist and execute a sequence of BEC scan/device commands.""" + """ + Schedule, persist and execute a sequence of BEC actions. + + The schedule is shown as a table (line, status, command, report, pause on failure, pause on + state, wait for completion). Items that run in the background (`wait_for_completion=False`) + are followed by an indented block of items that run while the background item is busy. The + BEC beamline states are shown next to the schedule; items with "pause on state" only run + while all states are valid. + """ PLUGIN = True ICON_NAME = "assignment_add" USER_ACCESS = [ "run_schedule", + "pause_schedule", "abort_schedule", "reset_schedule", "get_status", @@ -309,8 +117,7 @@ class Scheduler(BECWidget, QWidget): "move_item_down", ] - # emitted (thread-safe, may come from the background execution task) - # whenever the schedule state changes and the UI should redraw + # Thread-safe "schedule changed, redraw" signal; may be emitted from the executor thread. schedule_changed = Signal() def __init__( @@ -328,110 +135,103 @@ class Scheduler(BECWidget, QWidget): schedule_name=schedule_name or "default_schedule", ) elif schedule_name is not None: - # Allow overriding even when a config object/dict was supplied, - # mirroring how ScanControl treats its own optional constructor - # args as overrides onto whatever config ends up in self.config. if isinstance(config, dict): config = dict(config, schedule_name=schedule_name) else: config.schedule_name = schedule_name super().__init__(parent=parent, client=client, gui_id=gui_id, config=config, **kwargs) - # A stable name, NOT self.gui_id: gui_id is regenerated every time - # the widget is constructed, so it could never be used to find a - # previously persisted schedule again after the widget is reopened. - self.schedule_name = self.config.schedule_name - + self.schedule_name: str = self.config.schedule_name self.get_bec_shortcuts() # -> self.client, self.dev, self.scans, self.queue - self.beamline = self.get_beamline() self.connector = self.client.connector + self.beamline = self._detect_beamline() - if self.beamline in ["x01da", "x10da"]: - logger.info( - "Scheduler running at X01DA or X10DA, import and load digital twin and auto-gain" - ) + self._endpoint = schedule_endpoint(self.schedule_name) + self._lock = threading.Lock() # guards self.schedule + self._closing = threading.Event() + self._run_active = False # True while this instance's executor runs + self._selected_item_id: str | None = None + self._clipboard_item: dict | None = None + self._notice: str | None = None + + # Notes are saved on a debounce timer, not on every keystroke. + self._notes_save_timer = QTimer(self) + self._notes_save_timer.setSingleShot(True) + self._notes_save_timer.setInterval(500) + self._notes_save_timer.timeout.connect(self._persist_notes) + + self.schedule: Schedule = self._load_or_seed_schedule() + self._reconcile_with_live_state() + + self.state_monitor = BeamlineStateMonitor(self.client, self.bec_dispatcher, parent=self) + self._executor = ScheduleExecutor( + lock=self._lock, + get_items=lambda: self.schedule.items, + persist_locked=self._persist_locked, + emit_changed=self._emit_schedule_changed, + context=self._build_execution_context(), + state_monitor=self.state_monitor, + notify_item=self._notify_item_finished, + get_queue_storage=lambda: self.client.queue.queue_storage, + closing=self._closing, + ) + self.state_monitor.tripped.connect(self._executor.on_states_tripped) + self.state_monitor.statuses_changed.connect(self._update_state_label) + + self._build_ui() + self.schedule_changed.connect(self._refresh_ui) + self._refresh_ui() + + # Remaining time of running delays. + self._live_timer = QTimer(self) + self._live_timer.setInterval(1000) + self._live_timer.timeout.connect(self._table_model.refresh_live_cells) + self._live_timer.start() + + # Stay in sync with other users of the same schedule (another widget instance, scripts). + self.bec_dispatcher.connect_slot(self._on_remote_update, self._endpoint) + + def _detect_beamline(self) -> str | None: + """Beamline name derived from the host name, e.g. "x01da".""" + hostname = getattr(self.client, "_hostname", "") or "" + start = hostname.find("x") + return hostname[start : start + 5] if start != -1 else None + + def _build_execution_context(self) -> ExecutionContext: + digital_twin = auto_gain = None + if self.beamline in XAS_BEAMLINES: + logger.info(f"Scheduler at {self.beamline}: loading digital twin and auto-gain") + # pylint: disable=import-outside-toplevel from ....bec_ipython_client.plugins.auto_gain_core import AutoGainCore from ....bec_ipython_client.plugins.digital_twin_core.digital_twin_core import ( DigitalTwinCore, ) - self.digital_twin = DigitalTwinCore() - self.auto_gain = AutoGainCore() - else: - self.digital_twin = None - self.auto_gain = None + digital_twin = DigitalTwinCore() + auto_gain = AutoGainCore() + return ExecutionContext( + scans=self.scans, + dev=self.dev, + digital_twin=digital_twin, + auto_gain=auto_gain, + beamline=self.beamline, + ) - self._endpoint = schedule_endpoint(self.schedule_name) - self._lock = threading.Lock() # guards self.schedule (see module docstring) - self._abort_requested = False - self._pause_requested = False - self._guard_interrupt_requested = False # see "Guard interaction" in module docstring - self._current_report = None # ScanReport of the item currently executing, if any - self._current_item_kind: str | None = None # kind of the item _current_report belongs to - self._selected_item_id: str | None = None # survives list repopulation on refresh - self._clipboard_item: dict | None = None # copy/paste buffer, see _on_copy_clicked - - # Notes are auto-saved on a debounce timer rather than on every - # keystroke - see _on_notes_changed/_persist_notes. - self._notes_save_timer = QTimer(self) - self._notes_save_timer.setSingleShot(True) - self._notes_save_timer.setInterval(200) - self._notes_save_timer.timeout.connect(self._persist_notes) - - self.schedule_changed.connect(self._refresh_ui) - - self.schedule: Schedule = self._load_or_seed_schedule() - self._reconcile_with_live_state() - - self._guard = SignalGuard(self.connector, parent=self, dev=self.dev) - self._guard.paused.connect(self._on_guard_paused) - self._guard.resumed.connect(self._on_guard_resumed) - self._guard.value_update.connect(self._update_guard_label) - self._guard.configure(self.schedule.guard) - - self._build_ui() - self._refresh_ui() - - # Stay in sync with any other subscriber touching the same - # schedule (another instance of this widget, a script, ...). - self.bec_dispatcher.connect_slot(self._on_remote_update, self._endpoint) - - self._closing = threading.Event() - - def get_beamline(self): - hostname = self.client._hostname - start = hostname.find("x") - if start != -1: - return hostname[start : start + 5] - - # ------------------------------------------------------------------ # + # ------------------------------------------------------------------------------------------ # # UI - # ------------------------------------------------------------------ # - def _build_ui(self): + # ------------------------------------------------------------------------------------------ # + def _build_ui(self) -> None: layout = QVBoxLayout(self) + splitter = QSplitter(Qt.Orientation.Horizontal) + splitter.addWidget(self._build_schedule_group()) + splitter.addWidget(self._build_states_group()) + splitter.setStretchFactor(0, 3) + splitter.setStretchFactor(1, 1) + layout.addWidget(splitter, 1) + layout.addWidget(self._build_control_group()) + layout.addWidget(self._build_settings_group()) - schedule_group = QGroupBox("Schedule") - schedule_layout = QVBoxLayout(schedule_group) - - schedule_name_layout = QHBoxLayout() - name_label = QLabel("Name") - self.schedule_name_input = QLineEdit() - schedule_name_layout.addWidget(name_label) - schedule_name_layout.addWidget(self.schedule_name_input) - schedule_name_layout.addStretch() - schedule_layout.addLayout(schedule_name_layout) - - self.schedule_name_input.editingFinished.connect(self._on_schedule_name_change) - - edit_row = QHBoxLayout() - self.add_btn = MyButton("Add", "default") - self.edit_btn = MyButton("Edit", "default") - self.delete_btn = MyButton("Delete", "default") - self.move_up_btn = MyButton("Move Up", "default") - self.move_down_btn = MyButton("Move Down", "default") - self.copy_btn = MyButton("Copy", "default") - self.paste_btn = MyButton("Paste", "default") - for button in ( + self._buttons = [ self.add_btn, self.edit_btn, self.delete_btn, @@ -439,13 +239,60 @@ class Scheduler(BECWidget, QWidget): self.move_down_btn, self.copy_btn, self.paste_btn, + self.run_btn, + self.run_from_selection_btn, + self.pause_btn, + self.abort_btn, + self.reset_btn, + self.notifications_btn, + self.save_file_btn, + self.load_file_btn, + ] + self._update_notifications_label() + self._update_state_label() + + def _build_schedule_group(self) -> QGroupBox: + group = QGroupBox("Schedule") + layout = QVBoxLayout(group) + + name_row = QHBoxLayout() + name_row.addWidget(QLabel("Name")) + self.schedule_name_input = QLineEdit() + self.schedule_name_input.editingFinished.connect(self._on_schedule_name_change) + name_row.addWidget(self.schedule_name_input) + name_row.addStretch() + layout.addLayout(name_row) + + edit_row = QHBoxLayout() + self.add_btn = AccentButton("Add") + self.edit_btn = AccentButton("Edit") + self.delete_btn = AccentButton("Delete") + self.move_up_btn = AccentButton("Move Up") + self.move_down_btn = AccentButton("Move Down") + self.copy_btn = AccentButton("Copy") + self.paste_btn = AccentButton("Paste") + for button, slot in ( + (self.add_btn, self._on_add_clicked), + (self.edit_btn, self._on_edit_clicked), + (self.delete_btn, self._on_delete_clicked), + (self.move_up_btn, self._on_move_up_clicked), + (self.move_down_btn, self._on_move_down_clicked), + (self.copy_btn, self._on_copy_clicked), + (self.paste_btn, self._on_paste_clicked), ): + button.clicked.connect(slot) edit_row.addWidget(button) edit_row.addStretch() - schedule_layout.addLayout(edit_row) + layout.addLayout(edit_row) + + self.notice_label = QLabel() + self.notice_label.setWordWrap(True) + self.notice_label.setStyleSheet("color: #e6a800;") + self.notice_label.setVisible(False) + layout.addWidget(self.notice_label) self._table_model = ScheduleTableModel(parent=self, beamline=self.beamline) - self.table_view = MyTableView() + self.table_view = ScheduleTableView() self.table_view.setModel(self._table_model) self.table_view.configure_columns() self.table_view.selectionModel().currentRowChanged.connect(self._on_selection_changed) @@ -454,342 +301,185 @@ class Scheduler(BECWidget, QWidget): self.table_view.doubleClicked.connect(self._on_edit_clicked) self.table_view.copyPressed.connect(self._on_copy_clicked) self.table_view.pastePressed.connect(self._on_paste_clicked) + layout.addWidget(self.table_view, 1) - schedule_layout.addWidget(self.table_view) - - schedule_layout.addWidget(QLabel("Notes")) + layout.addWidget(QLabel("Notes")) self.notes_edit = QPlainTextEdit() self.notes_edit.setPlaceholderText("Notes about this schedule...") self.notes_edit.setPlainText(self.schedule.notes) self.notes_edit.setMaximumHeight(100) - self.notes_edit.textChanged.connect(self._on_notes_changed) - schedule_layout.addWidget(self.notes_edit) + self.notes_edit.textChanged.connect(self._notes_save_timer.start) + layout.addWidget(self.notes_edit) + return group - self.add_btn.clicked.connect(self._on_add_clicked) - self.edit_btn.clicked.connect(self._on_edit_clicked) - self.delete_btn.clicked.connect(self._on_delete_clicked) - self.move_up_btn.clicked.connect(self._on_move_up_clicked) - self.move_down_btn.clicked.connect(self._on_move_down_clicked) - self.copy_btn.clicked.connect(self._on_copy_clicked) - self.paste_btn.clicked.connect(self._on_paste_clicked) - - layout.addWidget(schedule_group) - - control_group = QGroupBox("Control") - control_layout = QVBoxLayout(control_group) + def _build_states_group(self) -> QGroupBox: + group = QGroupBox("Beamline states") + layout = QVBoxLayout(group) + layout.setContentsMargins(2, 2, 2, 2) + # BEC's stock BeamlineStateManager; only its scan-interlock controls are hidden. + self.state_manager = BeamlineStateManager(parent=group, client=self.client) + install_scan_interlock_hiding(self.state_manager) + layout.addWidget(self.state_manager) + return group + def _build_control_group(self) -> QGroupBox: + group = QGroupBox("Control") + layout = QVBoxLayout(group) run_row = QHBoxLayout() - self.run_btn = MyButton("Run / Continue", "success") - self.run_from_current_btn = MyButton("Run / Continue from current selection", "success") - self.abort_btn = MyButton("Pause now", "emergency") - self.pause_btn = MyButton("Pause after current item", "warning") - self.reset_btn = MyButton("Reset Schedule Status", "warning") - for button in ( - self.run_btn, - self.run_from_current_btn, - self.pause_btn, - self.abort_btn, - self.reset_btn, + self.run_btn = AccentButton("Run / Continue", "success") + self.run_from_selection_btn = AccentButton("Run / Continue from selection", "success") + self.pause_btn = AccentButton("Pause after current item", "warning") + self.abort_btn = AccentButton("Pause now", "emergency") + self.reset_btn = AccentButton("Reset schedule status", "warning") + for button, slot in ( + (self.run_btn, self._on_run_clicked), + (self.run_from_selection_btn, self._on_run_from_selection_clicked), + (self.pause_btn, self.pause_schedule), + (self.abort_btn, self.abort_schedule), + (self.reset_btn, self._on_reset_clicked), ): + button.clicked.connect(slot) run_row.addWidget(button) run_row.addStretch() - control_layout.addLayout(run_row) + layout.addLayout(run_row) - self.run_btn.clicked.connect(self.run_schedule) - self.run_from_current_btn.clicked.connect(self.run_schedule_from_selection) - self.abort_btn.clicked.connect(self.abort_schedule) - self.pause_btn.clicked.connect(self.pause_schedule) - self.reset_btn.clicked.connect(self.reset_schedule) - - layout.addWidget(control_group) - - settings_group = QGroupBox("Settings") - settings_layout = QVBoxLayout(settings_group) - - guard_row = QHBoxLayout() - self.guard_btn = MyButton("Auto-pause", "default") - self.guard_status_label = QLabel() - guard_row.addWidget(self.guard_btn) - guard_row.addWidget(self.guard_status_label) - guard_row.addStretch() - notifications_row = QHBoxLayout() - self.notifications_btn = MyButton("Notifications", "default") - self.notification_status_label = QLabel() - notifications_row.addWidget(self.notifications_btn) - notifications_row.addWidget(self.notification_status_label) - notifications_row.addStretch() - settings_layout.addLayout(guard_row) - settings_layout.addLayout(notifications_row) + state_row = QHBoxLayout() + state_row.addWidget(QLabel("Beamline states:")) + self.state_status_label = QLabel() + state_row.addWidget(self.state_status_label) + state_row.addStretch() + layout.addLayout(state_row) + return group + def _build_settings_group(self) -> QGroupBox: + group = QGroupBox("Settings") + row = QHBoxLayout(group) + self.notifications_btn = AccentButton("Notifications") self.notifications_btn.clicked.connect(self._on_notifications_clicked) - self.guard_btn.clicked.connect(self._on_guard_clicked) - - layout.addWidget(settings_group) - - file_group = QGroupBox("File") - file_layout = QHBoxLayout(file_group) - self.save_file_btn = MyButton("Save to file", "default") - self.load_file_btn = MyButton("Load from file", "default") - file_layout.addWidget(self.save_file_btn) - file_layout.addWidget(self.load_file_btn) - file_layout.addStretch() - + self.notification_status_label = QLabel() + self.save_file_btn = AccentButton("Save to file") self.save_file_btn.clicked.connect(self._on_save_to_file_clicked) + self.load_file_btn = AccentButton("Load from file") self.load_file_btn.clicked.connect(self._on_load_from_file_clicked) + row.addWidget(self.notifications_btn) + row.addWidget(self.notification_status_label) + row.addStretch() + row.addWidget(self.save_file_btn) + row.addWidget(self.load_file_btn) + return group - layout.addWidget(file_group) - - self._update_guard_label() - self._update_notifications_label() - - self.apply_theme() - - def apply_theme(self, theme: Optional[Literal["dark", "light"]] = None): - """ - Apply the theme - - Args: - theme (Optional[str]): Theme, either "dark", "light", or None. Defaults to None. - """ - if theme is None: - app = QApplication.instance() - theme = app.theme.theme # type: ignore - - for button in [ - self.add_btn, - self.edit_btn, - self.delete_btn, - self.move_down_btn, - self.move_up_btn, - self.copy_btn, - self.paste_btn, - self.run_btn, - self.abort_btn, - self.reset_btn, - self.notifications_btn, - self.guard_btn, - self.save_file_btn, - self.load_file_btn, - ]: + @SafeSlot(str) + def apply_theme(self, theme: str | None = None) -> None: + """Re-colour the buttons after a theme change.""" + for button in getattr(self, "_buttons", []): button.apply_theme() - # ------------------------------------------------------------------ # - # persistence - # ------------------------------------------------------------------ # - def _load_or_seed_schedule(self) -> Schedule: - logger.info("load or seed schedule") - msg: VariableMessage | None = self.connector.get(self._endpoint) - # msg = None # Overwrite any existing schedule in redis - if msg is not None: - logger.info(f"Got msg from endpoint: {msg.value}") - return Schedule.model_validate(msg.value) - - logger.info("No schedule found, create one now") - schedule = Schedule(schedule_name=self.schedule_name, items=[]) - self.connector.set_and_publish( - self._endpoint, VariableMessage(value=schedule.model_dump(mode="json")) - ) - return schedule - - def _persist_locked(self): - """Write `self.schedule` to Redis. Caller must hold `self._lock`.""" - self.connector.set_and_publish( - self._endpoint, VariableMessage(value=self.schedule.model_dump(mode="json")) - ) - - def _persist(self): - with self._lock: - self._persist_locked() - - @SafeSlot(dict, dict) - def _on_remote_update(self, msg_content: dict, _): - value = msg_content.get("value") if msg_content else None - if not value or value.get("schedule_name") != self.schedule_name: - return - with self._lock: - new_schedule = Schedule.model_validate(value) - if new_schedule.is_running: - # This instance's own execution task owns the current - # ScheduleItem objects (and will re-persist its own state - # again shortly); accepting a wholesale replacement here - # would orphan those objects. See module docstring. - logger.info( - f"Ignoring remote schedule update for {self.schedule_name} while a local run is in progress." - ) - return - self.schedule = new_schedule - self._apply_guard_settings() - self._refresh_ui() - - # ------------------------------------------------------------------ # - # reconciliation: figure out real state after being closed/reopened - # ------------------------------------------------------------------ # - def _reconcile_with_live_state(self): - """ - For any item last seen as RUNNING, ask BEC's own queue state - - not our local memory, which may be stale or from a previous - process - what actually happened to it while we were gone. - """ - queue_storage = self.client.queue.queue_storage - - # Force a fresh pull of the current queue snapshot from Redis - # rather than relying on pubsub messages we may have missed while - # this widget instance did not exist. - status_msg = self.connector.get(MessageEndpoints.scan_queue_status()) - if status_msg is not None: - queue_storage.update_with_status(status_msg) - - with self._lock: - self.schedule.is_running = False - for item in self.schedule.items: - if item.status != ScheduleItemStatus.RUNNING or not item.request_id: - continue - queue_item = queue_storage.find_queue_item_by_requestID(item.request_id) - if queue_item is not None and self._is_queue_item_active(queue_item): - # genuinely still in flight server-side; leave it - # RUNNING - run_schedule() will re-attach to it - # instead of resubmitting. - continue - item.status = ScheduleItemStatus.COMPLETED - item.finished_at = time.time() - self._persist_locked() - - @staticmethod - def _is_queue_item_active(queue_item) -> bool: - return str(getattr(queue_item, "status", "")).upper() in _ACTIVE_QUEUE_STATES - - # ------------------------------------------------------------------ # - # the "protected prefix" invariant (see module docstring) - the actual - # logic lives in schedule_logic.py, pure and independently testable; - # these thin wrappers just apply it to the current, lock-held state. - # ------------------------------------------------------------------ # - def _protected_prefix_length_locked(self) -> int: - return protected_prefix_length(self.schedule.items) - - def _index_of_locked(self, item_id: str | None) -> int | None: - return index_of(self.schedule.items, item_id) - @SafeSlot() - def _refresh_ui(self): + def _refresh_ui(self) -> None: + """Redraw the table and controls from the current schedule.""" with self._lock: schedule_name = self.schedule.schedule_name - items = list(self.schedule.items) + items = [item.model_copy() for item in self.schedule.items] notes = self.schedule.notes - self.schedule_name_input.setText(schedule_name) + if not self.schedule_name_input.hasFocus(): + self.schedule_name_input.setText(schedule_name) selection_model = self.table_view.selectionModel() selection_model.blockSignals(True) - - # Repopulate the model (full reset, same "clear and rebuild" idea - # the old QListWidget code used); the selected item's status-icon - # color is baked in via `_selected_item_id` so the highlighted row - # keeps its white icon straight after the reset repaints it. - self._table_model._selected_item_id = self._selected_item_id - self._table_model.set_items(items) - + self._table_model.set_items(items, selected_item_id=self._selected_item_id) row = self._table_model.row_of(self._selected_item_id) if row is not None: self.table_view.selectRow(row) - self.run_from_current_btn.setEnabled(True) else: self._selected_item_id = None - self.run_from_current_btn.setEnabled(False) - selection_model.blockSignals(False) - # Don't stomp on notes the operator is actively typing (e.g. a - # remote update, or our own debounce timer firing right after - # local edits) - only resync when the field isn't focused and the - # text actually differs from what we already have. + # Do not overwrite notes the operator is typing. if not self.notes_edit.hasFocus() and self.notes_edit.toPlainText() != notes: self.notes_edit.blockSignals(True) self.notes_edit.setPlainText(notes) self.notes_edit.blockSignals(False) + self.notice_label.setText(self._notice or "") + self.notice_label.setVisible(bool(self._notice)) self._update_buttons() - def _update_guard_label(self, *_): - if self._guard.enabled: - state = "OK" if self._guard.is_clear() else "PAUSED - waiting to resume" - value = self._guard.current_value - units = self._guard.units - value_text = f"{value:.{self._guard.prec}f}" if value is not None else "?" - self.guard_status_label.setText( - f"Enabled: {self._guard.device_name} = {value_text} {units} " - f"(pause < {self._guard.pause_below:g}, resume > {self._guard.resume_above:g}) [{state}]" - ) - else: - self.guard_status_label.setText("Disabled") - - def _update_buttons(self): + def _update_buttons(self) -> None: with self._lock: - items = list(self.schedule.items) - is_running = self.schedule.is_running + items = self.schedule.items + running = self._run_active or self.schedule.is_running + idx = index_of(items, self._selected_item_id) + selected = items[idx] if idx is not None else None + count = len(items) - idx = None - selected_item = None - - if self._selected_item_id is not None: - for i, item in enumerate(items): - if item.item_id == self._selected_item_id: - idx, selected_item = i, item - break - - can_edit_selected = ( - selected_item is not None and selected_item.status == ScheduleItemStatus.PENDING - ) - - self.run_btn.setEnabled(not is_running) - self.add_btn.setEnabled(True) - self.edit_btn.setEnabled(can_edit_selected) - self.delete_btn.setEnabled(can_edit_selected) - self.move_up_btn.setEnabled(can_edit_selected and idx not in (None, 0)) - self.move_down_btn.setEnabled( - can_edit_selected and idx is not None and idx < len(items) - 1 - ) - # Copy just captures the command text, so it's fine on any item - # (e.g. copying a COMPLETED item's command to reuse it later). - # Paste always goes through add_item(), which already clamps the - # insert position past the protected prefix - see _on_paste_clicked. - self.copy_btn.setEnabled(selected_item is not None) + editable = selected is not None and selected.status == ItemStatus.PENDING + self.edit_btn.setEnabled(editable) + self.delete_btn.setEnabled(editable) + self.move_up_btn.setEnabled(editable and idx not in (None, 0)) + self.move_down_btn.setEnabled(editable and idx is not None and idx < count - 1) + # Copy works on any item (e.g. reuse a completed scan); paste always inserts a new + # PENDING item behind the protected prefix. + self.copy_btn.setEnabled(selected is not None) self.paste_btn.setEnabled(self._clipboard_item is not None) - # Update execution control buttons - state = self._current_report is None # True if schedule is not running - self.run_btn.setEnabled(state) - self.run_from_current_btn.setEnabled(state and self._selected_item_id is not None) - self.abort_btn.setEnabled(not state) - self.pause_btn.setEnabled(not state) - self.reset_btn.setEnabled(state) + self.run_btn.setEnabled(not running) + self.run_from_selection_btn.setEnabled(not running and selected is not None) + self.pause_btn.setEnabled(self._run_active) + self.abort_btn.setEnabled(self._run_active) + self.reset_btn.setEnabled(not running) + self.load_file_btn.setEnabled(not running) @SafeSlot() - def _on_schedule_name_change(self): - name = self.schedule_name_input.text() - with self._lock: - self.schedule.schedule_name = name - self._persist_locked() + def _update_state_label(self) -> None: + if not hasattr(self, "state_status_label"): + return + ok = self.state_monitor.is_ok() + self.state_status_label.setText(self.state_monitor.summary()) + self.state_status_label.setStyleSheet("" if ok else "color: #e74c3c; font-weight: bold;") + def _update_notifications_label(self) -> None: + settings = self.schedule.notifications + if not settings.enabled: + self.notification_status_label.setText("Disabled") + return + kinds = [ + name + for name, enabled in ( + ("scans", settings.notify_scan), + ("moves", settings.notify_move), + ("device actions", settings.notify_device), + ) + if enabled + ] + target = "SciLog" if settings.target == NotificationTarget.SCILOG else "Signal" + events = ", ".join(event.value for event in settings.events) or "no item events" + self.notification_status_label.setText( + f"Enabled: via {target} for {', '.join(kinds) or 'no items'} on {events}" + ) + + # ---- selection ---- # @SafeSlot(QModelIndex, QModelIndex) - def _on_selection_changed(self, current: QModelIndex, previous: QModelIndex): + def _on_selection_changed(self, current: QModelIndex, _previous: QModelIndex) -> None: item_id = self._table_model.item_id(current.row()) if current.isValid() else None self._selected_item_id = item_id self._table_model.set_selected_item_id(item_id) self._update_buttons() @SafeSlot() - def _on_empty_space_clicked(self): - self.table_view.setCurrentIndex(QModelIndex()) - self._refresh_ui() + def _on_empty_space_clicked(self) -> None: + self._selected_item_id = None + self._table_model.set_selected_item_id(None) + self._update_buttons() - # ---- notes ---- # - def _on_notes_changed(self): - # Debounced: restart the timer on every keystroke, only persist - # once typing pauses, so we're not writing to Redis on every - # character. - self._notes_save_timer.start() + @SafeSlot() + def _on_schedule_name_change(self) -> None: + with self._lock: + self.schedule.schedule_name = self.schedule_name_input.text().strip() + self._persist_locked() - def _persist_notes(self): + @SafeSlot() + def _persist_notes(self) -> None: text = self.notes_edit.toPlainText() with self._lock: if self.schedule.notes == text: @@ -797,58 +487,142 @@ class Scheduler(BECWidget, QWidget): self.schedule.notes = text self._persist_locked() - # ---- save / restore to file ---- # + # ------------------------------------------------------------------------------------------ # + # Persistence + # ------------------------------------------------------------------------------------------ # + def _load_or_seed_schedule(self) -> Schedule: + """ + Load the persisted schedule from Redis, or create an empty one. + + A document that cannot be validated (e.g. written by the old, eval-based Scheduler) never + blocks the widget: it is logged and replaced by an empty schedule. + """ + msg: VariableMessage | None = self.connector.get(self._endpoint) + value = msg.value if msg is not None else None + if value is not None: + schedule, problem = schedule_from_document(value) + if schedule is not None: + return schedule + logger.warning( + f"Found {problem} in BEC at {self._endpoint.endpoint}; starting with an empty " + "schedule." + ) + logger.info(f"Discarded schedule document: {value}") + self._notice = ( + f"Found {problem} in BEC - started with an empty schedule. The previous items " + "can no longer be loaded and were written to the BEC log." + ) + schedule = Schedule(schedule_name=self.schedule_name) + self.connector.set_and_publish( + self._endpoint, VariableMessage(value=schedule.model_dump(mode="json")) + ) + return schedule + + def _persist_locked(self) -> None: + """Write the schedule to Redis. The caller must hold `self._lock`.""" + self.connector.set_and_publish( + self._endpoint, VariableMessage(value=self.schedule.model_dump(mode="json")) + ) + + @SafeSlot(dict, dict) + def _on_remote_update(self, msg_content: dict, _metadata: dict) -> None: + """Adopt a schedule published by someone else (or our own echo) while not running.""" + value = msg_content.get("value") if msg_content else None + if not value or self._run_active: + # While this instance executes, its executor owns the item objects; replacing them + # would orphan the running items. It re-publishes its own state anyway. + return + new_schedule, problem = schedule_from_document(value) + if new_schedule is None: + logger.warning(f"Ignoring {problem} published on {self._endpoint.endpoint}") + return + with self._lock: + self.schedule = new_schedule + self._update_notifications_label() + self._refresh_ui() + + def _reconcile_with_live_state(self) -> None: + """ + Fix up items persisted as RUNNING by a previous widget session: ask BEC's queue (not our + stale memory) whether their requests are still active. Requests still in flight stay + RUNNING and are re-attached to on the next run; finished ones become COMPLETED. Local + actions (delays, device calls) without a request were interrupted by the widget closing + and become ABORTED. + """ + queue_storage = self.client.queue.queue_storage + status_msg = self.connector.get(MessageEndpoints.scan_queue_status()) + if status_msg is not None: + queue_storage.update_with_status(status_msg) + + with self._lock: + self.schedule.is_running = False + for item in self.schedule.items: + if item.status != ItemStatus.RUNNING: + continue + if item.request_id: + queue_item = queue_storage.find_queue_item_by_requestID(item.request_id) + if queue_item is not None and is_queue_item_active(queue_item): + continue + item.status = ItemStatus.COMPLETED + item.report = item.report or "Done" + else: + item.status = ItemStatus.ABORTED + item.report = "Interrupted (widget was closed)" + item.finished_at = time.time() + self._persist_locked() + + def _emit_schedule_changed(self) -> None: + if not self._closing.is_set(): + self.schedule_changed.emit() + + # ---- file save / load ---- # + def _default_data_dir(self) -> str: + if not self.beamline: + return "" + return f"/sls/{self.beamline}/data/{self.client.active_account}/raw" + @SafeSlot() - def _on_save_to_file_clicked(self): + def _on_save_to_file_clicked(self) -> None: with self._lock: data = self.schedule.model_dump(mode="json") - default_name = "schedule.json" - - active_account = self.client.active_account - default_name = f"/sls/{self.beamline}/data/{active_account}/raw/{default_name}" - + start = self._default_data_dir() + default_path = str(Path(start) / "schedule.json") if start else "schedule.json" path, _ = QFileDialog.getSaveFileName( - self, "Save schedule to file", default_name, "JSON files (*.json);;All files (*)" + self, "Save schedule to file", default_path, "JSON files (*.json);;All files (*)" ) if not path: return try: - with open(path, "w", encoding="utf-8") as f: - json.dump(data, f, indent=2) + Path(path).write_text(json.dumps(data, indent=2), encoding="utf-8") except OSError as exc: QMessageBox.critical(self, "Save failed", f"Could not write to {path}:\n{exc}") return logger.info(f"Saved schedule '{self.schedule_name}' to {path}") @SafeSlot() - def _on_load_from_file_clicked(self): - with self._lock: - if self.schedule.is_running: - QMessageBox.warning( - self, - "Cannot load", - "Stop the running schedule (Abort) before loading a new one from file.", - ) - return - - start_folder = "" - - active_account = self.client.active_account - start_folder = f"/sls/{self.beamline}/data/{active_account}/raw" - + def _on_load_from_file_clicked(self) -> None: path, _ = QFileDialog.getOpenFileName( - self, "Load schedule from file", start_folder, "JSON files (*.json);;All files (*)" + self, + "Load schedule from file", + self._default_data_dir(), + "JSON files (*.json);;All files (*)", ) if not path: return - try: - with open(path, encoding="utf-8") as f: - data = json.load(f) - loaded = Schedule.model_validate(data) - except (OSError, json.JSONDecodeError, ValidationError) as exc: + data = json.loads(Path(path).read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + QMessageBox.critical(self, "Load failed", f"Could not read {path}:\n{exc}") + return + loaded, problem = schedule_from_document(data) + if loaded is None: + hint = " Please re-create the schedule." if "old" in problem else "" + QMessageBox.critical(self, "Load failed", f"{path} contains {problem}.{hint}") + return + unknown = sorted({item.action for item in loaded.items if item.action not in ACTIONS}) + if unknown: QMessageBox.critical( - self, "Load failed", f"Could not load a schedule from {path}:\n{exc}" + self, "Load failed", f"{path} contains unknown item types: {', '.join(unknown)}" ) return @@ -857,177 +631,49 @@ class Scheduler(BECWidget, QWidget): confirm = QMessageBox.question( self, "Load schedule", - f"Replace the current {current_count} item(s) with {len(loaded.items)} " - f"item(s) from the file?\n\nAll items will be loaded as PENDING, regardless " - f"of their status when the file was saved.", + f"Replace the current {current_count} item(s) with {len(loaded.items)} item(s) from " + "the file?\n\nAll items are loaded as PENDING.", ) if confirm != QMessageBox.StandardButton.Yes: return - # Loading a file restores a *definition* (what to run), not a past - # execution: every item comes back PENDING with a fresh item_id and - # its execution bookkeeping cleared, and is_running is always - # forced False here - regardless of what the file says - so we - # never end up "reconciling" against request/scan ids from a - # different session. schedule_name is deliberately left as this - # widget's own name, not overwritten by the file's. - new_items = [ - item.model_copy( - update={ - "item_id": str(uuid.uuid4()), - "status": ScheduleItemStatus.PENDING, - "request_id": None, - "scan_id": None, - "scan_number": None, - "error": None, - "started_at": None, - "finished_at": None, - } - ) - for item in loaded.items - ] - + # A file restores a *definition* (what to run), not a past execution. + new_items = [ScheduleItem(**item.definition()) for item in loaded.items] with self._lock: - if self.schedule.is_running: - QMessageBox.warning( - self, "Cannot load", "The schedule started running while the dialog was open." - ) + if self._run_active or self.schedule.is_running: + QMessageBox.warning(self, "Cannot load", "The schedule started running meanwhile.") return self.schedule.schedule_name = loaded.schedule_name self.schedule.items = new_items self.schedule.notes = loaded.notes - self.schedule.guard = loaded.guard self.schedule.notifications = loaded.notifications self._persist_locked() - - self._guard.configure(self.schedule.guard) self._selected_item_id = None - logger.info( - f"Loaded schedule from {path} ({len(new_items)} item(s)) into '{self.schedule_name}'" - ) + self._notice = None + logger.info(f"Loaded schedule from {path} ({len(new_items)} item(s))") + self._update_notifications_label() self._refresh_ui() - self._update_buttons() - # ---- notifications / auto-pause settings ---- # + # ---- notifications ---- # @SafeSlot() - def _on_notifications_clicked(self): + def _on_notifications_clicked(self) -> None: dialog = NotificationSettingsDialog(self.schedule.notifications, self.client, parent=self) if dialog.exec_() != QDialog.DialogCode.Accepted: return with self._lock: self.schedule.notifications = dialog.result_settings() - self._update_notifications_label() self._persist_locked() - self._refresh_ui() + self._update_notifications_label() - def _update_notifications_label(self): - if self.schedule.notifications.enabled: - types = [] - if self.schedule.notifications.notify_scan: - types.append("scan") - if self.schedule.notifications.notify_move: - types.append("move") - if self.schedule.notifications.notify_rpc: - types.append("rpc") - match self.schedule.notifications.target: - case NotificationTarget.SIGNAL: - target = "Signal Messenger" - case NotificationTarget.TEAMS: - target = "Microsoft Teams" - case NotificationTarget.SCILOG: - target = "Scilog" - events = [] - for event in self.schedule.notifications.events: - events.append(event.value) - text = f"Enabled: Notify through {target}, for item type {types}, and events {events}" - else: - text = "Disabled" - self.notification_status_label.setText(text) - - @SafeSlot() - def _on_guard_clicked(self): - device_names = sorted(self.dev.keys()) - dialog = GuardSettingsDialog(self.schedule.guard, device_names, parent=self) - if dialog.exec_() != QDialog.DialogCode.Accepted: - return - with self._lock: - self.schedule.guard = dialog.result_settings() - self._persist_locked() - self._guard.configure(self.schedule.guard) - self._refresh_ui() - self._update_guard_label() - - def _apply_guard_settings(self): - """Re-subscribe the guard after `self.schedule.guard` changes (e.g. from a remote update).""" - self._guard.configure(self.schedule.guard) - self._update_guard_label() - - @SafeSlot(float) - def _on_guard_paused(self, value: float): - logger.info( - f"Auto-pause guard tripped for schedule {self.schedule_name} (value = {value}); interrupting the running scan, if any." + def _notify_item_finished(self, item: ScheduleItem) -> None: + notify_item_finished( + self.client, self.schedule.notifications, item, describe_item(item, self.beamline) ) - if self._current_report is not None and self._current_item_kind == "scan": - self._guard_interrupt_requested = True - try: - self._current_report.cancel() - except Exception: # pylint: disable=broad-except - logger.exception("Failed to cancel the running scan for the auto-pause guard") - self.schedule_changed.emit() - self._update_guard_label() - - @SafeSlot(float) - def _on_guard_resumed(self, value: float): - logger.info( - f"Auto-pause guard cleared for schedule {self.schedule_name} (value = {value}); the execution loop will " - "resume the next scan item automatically." - ) - self.schedule_changed.emit() - - # ---- UI-triggered edit actions ---- # - @SafeSlot() - def _on_add_clicked(self): - dialog = ScheduleItemDialog( - self.scans, self.dev, parent=self, client=self.client, beamline=self.beamline - ) - if dialog.exec_() != QDialog.DialogCode.Accepted: - return - result = dialog.result() - with self._lock: - idx = self._index_of_locked(self._selected_item_id) - insert_at = None if idx is None else idx + 1 - new_id = self.add_item( - result["command"], - index=insert_at, - kind=result["kind"], - form_state=result["form_state"], - pause_on_failure=result["pause_on_failure"], - ) - self._selected_item_id = new_id - self._refresh_ui() - self._update_buttons() - - @SafeSlot() - @SafeSlot(QModelIndex) - def _on_edit_clicked(self, *_): - if self._selected_item_id is None: - return - with self._lock: - idx = self._index_of_locked(self._selected_item_id) - item = self.schedule.items[idx] if idx is not None else None - initial = ( - { - "kind": item.kind, - "command": item.command, - "form_state": item.form_state, - "pause_on_failure": item.pause_on_failure, - } - if item is not None - else None - ) - if initial is None: - return + # ------------------------------------------------------------------------------------------ # + # UI-triggered edit actions + # ------------------------------------------------------------------------------------------ # + def _open_item_dialog(self, initial: dict | None = None) -> dict | None: dialog = ScheduleItemDialog( self.scans, self.dev, @@ -1037,23 +683,46 @@ class Scheduler(BECWidget, QWidget): beamline=self.beamline, ) if dialog.exec_() != QDialog.DialogCode.Accepted: - return - result = dialog.result() - try: - self.edit_item( - self._selected_item_id, - result["command"], - kind=result["kind"], - form_state=result["form_state"], - pause_on_failure=result["pause_on_failure"], - ) - except RuntimeError as exc: - QMessageBox.warning(self, "Cannot edit item", str(exc)) - return + return None + return dialog.result() + + def _insert_after_selection(self, definition: dict) -> None: + with self._lock: + idx = index_of(self.schedule.items, self._selected_item_id) + self._selected_item_id = self.add_item(index=None if idx is None else idx + 1, **definition) self._refresh_ui() @SafeSlot() - def _on_delete_clicked(self): + def _on_add_clicked(self) -> None: + result = self._open_item_dialog() + if result is not None: + self._insert_after_selection(result) + + @SafeSlot() + @SafeSlot(QModelIndex) + def _on_edit_clicked(self, *_) -> None: + with self._lock: + idx = index_of(self.schedule.items, self._selected_item_id) + item = self.schedule.items[idx] if idx is not None else None + initial = item.definition() if item is not None else None + editable = item is not None and item.status == ItemStatus.PENDING + if initial is None: + return + if not editable: + QMessageBox.information( + self, "Cannot edit item", "Only items that have not started yet can be edited." + ) + return + result = self._open_item_dialog(initial) + if result is None: + return + try: + self.edit_item(self._selected_item_id, **result) + except RuntimeError as exc: + QMessageBox.warning(self, "Cannot edit item", str(exc)) + + @SafeSlot() + def _on_delete_clicked(self) -> None: if self._selected_item_id is None: return row = self.table_view.currentIndex().row() @@ -1062,212 +731,204 @@ class Scheduler(BECWidget, QWidget): except RuntimeError as exc: QMessageBox.warning(self, "Cannot delete item", str(exc)) return - self._selected_item_id = None - # delete_item()'s schedule_changed emit already ran _refresh_ui() - # with an empty selection; now re-select the row that took the - # deleted item's place (or the new last row, if it was last). - new_row = max(0, row - 1) - if 0 <= new_row < self._table_model.rowCount(): - self.table_view.selectRow(new_row) + # Select the row that took the deleted item's place (or the new last row). + self._selected_item_id = self._table_model.item_id( + min(row, self._table_model.rowCount() - 1) + ) self._refresh_ui() @SafeSlot() - def _on_move_up_clicked(self): - if self._selected_item_id is None: - return - try: + def _on_move_up_clicked(self) -> None: + if self._selected_item_id is not None: self.move_item_up(self._selected_item_id) - except RuntimeError as exc: - QMessageBox.warning(self, "Cannot move item", str(exc)) @SafeSlot() - def _on_move_down_clicked(self): - if self._selected_item_id is None: - return - try: + def _on_move_down_clicked(self) -> None: + if self._selected_item_id is not None: self.move_item_down(self._selected_item_id) - except RuntimeError as exc: - QMessageBox.warning(self, "Cannot move item", str(exc)) @SafeSlot() - def _on_copy_clicked(self): - """ - Copy the selected item's command onto an internal clipboard. Only - the command/kind/form_state are captured (not status, timestamps, - request/scan ids, ...) since pasting always creates a fresh, - PENDING item - this is "copy the command", not "duplicate the - history". - """ - if self._selected_item_id is None: - return + def _on_copy_clicked(self) -> None: + """Copy the definition of the selected item (not its execution state).""" with self._lock: - idx = self._index_of_locked(self._selected_item_id) + idx = index_of(self.schedule.items, self._selected_item_id) if idx is None: return - item = self.schedule.items[idx] - self._clipboard_item = { - "command": item.command, - "kind": item.kind, - "form_state": dict(item.form_state) if item.form_state else None, - "pause_on_failure": item.pause_on_failure, - } - logger.info(f"Copied schedule item: {self._clipboard_item['command']}") + self._clipboard_item = self.schedule.items[idx].definition() self._update_buttons() @SafeSlot() - def _on_paste_clicked(self): - """ - Paste the copied command as a new item, right after whatever is - currently selected (or at the end, if nothing is selected) - same - placement `_on_add_clicked` uses. This goes through `add_item()` - unchanged, so the existing protected-prefix clamping applies here - too: pasting can never land before an item that's already - running or finished. - """ - if self._clipboard_item is None: - return + def _on_paste_clicked(self) -> None: + """Insert the copied item as a new PENDING item after the selection (or at the end).""" + if self._clipboard_item is not None: + self._insert_after_selection(dict(self._clipboard_item)) + + # ---- run control buttons ---- # + def _ask_retry_unfinished(self) -> bool | None: + """Ask whether FAILED/ABORTED items should be repeated. None = cancelled.""" with self._lock: - idx = self._index_of_locked(self._selected_item_id) - insert_at = None if idx is None else idx + 1 - new_id = self.add_item( - self._clipboard_item["command"], - index=insert_at, - kind=self._clipboard_item["kind"], - form_state=self._clipboard_item["form_state"], - pause_on_failure=self._clipboard_item["pause_on_failure"], + unfinished = sum( + item.status in (ItemStatus.FAILED, ItemStatus.ABORTED) + for item in self.schedule.items + ) + if not unfinished: + return False + answer = QMessageBox.question( + self, + "Repeat unfinished items", + f"{unfinished} item(s) failed or were aborted. Repeat them?", + QMessageBox.StandardButton.Yes + | QMessageBox.StandardButton.No + | QMessageBox.StandardButton.Cancel, ) - self._selected_item_id = new_id - self._refresh_ui() - self._update_buttons() + if answer == QMessageBox.StandardButton.Cancel: + return None + return answer == QMessageBox.StandardButton.Yes - # ------------------------------------------------------------------ # - # RPC-exposed actions (USER_ACCESS) - # ------------------------------------------------------------------ # @SafeSlot() - def run_schedule(self, first_item: int = 0): - """Run the schedule, continuing from wherever it last left off.""" + def _on_run_clicked(self) -> None: + retry = self._ask_retry_unfinished() + if retry is not None: + self.run_schedule(retry_unfinished=retry) + + @SafeSlot() + def _on_run_from_selection_clicked(self) -> None: with self._lock: - if self.schedule.is_running: + idx = index_of(self.schedule.items, self._selected_item_id) + if idx is None: + return + retry = self._ask_retry_unfinished() + if retry is not None: + self.run_schedule(first_item=idx, retry_unfinished=retry) + + @SafeSlot() + def _on_reset_clicked(self) -> None: + answer = QMessageBox.question( + self, + "Reset schedule status", + "Mark all items as PENDING again and clear their reports?", + ) + if answer == QMessageBox.StandardButton.Yes: + self.reset_schedule() + + # ------------------------------------------------------------------------------------------ # + # RPC-exposed run control + # ------------------------------------------------------------------------------------------ # + def run_schedule(self, first_item: int = 0, retry_unfinished: bool = False) -> None: + """ + Start (or continue) executing the schedule. + + Already COMPLETED items are skipped. Does nothing if the schedule is already running. + + Args: + first_item: Index of the item to start with; items above it are ignored. + retry_unfinished: If True, FAILED and ABORTED items are executed again. + """ + with self._lock: + if self._run_active or self.schedule.is_running: + logger.info(f"Schedule {self.schedule_name} is already running.") return - repeat_aborted_item = False - if any(item.status == ScheduleItemStatus.ABORTED for item in self.schedule.items): - repeat_aborted_item = ( - QMessageBox.question( - self, - "Repeat aborted scan", - "Would you like to repeat the aborted scan?", - QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, - ) - == QMessageBox.StandardButton.Yes - ) - self._abort_requested = False - self._pause_requested = False + items = self.schedule.items + first_id = items[first_item].item_id if 0 <= first_item < len(items) else None self.schedule.is_running = True self._persist_locked() - self.schedule_changed.emit() + self._run_active = True self.submit_task( self._run_all, - repeat_aborted_item, - first_item, + first_id, + retry_unfinished, on_complete=self._on_run_finished, on_failed=self._on_run_failed, ) self._refresh_ui() - @SafeSlot() - def run_schedule_from_selection(self): - """Run the schedule, starting from the current selected item.""" - if self._selected_item_id is None: - return + def pause_schedule(self) -> None: + """Pause after the currently running item(s) have finished.""" + if self._run_active: + self._executor.request_pause() + + def abort_schedule(self) -> None: + """Pause now: cancel running scans/moves, interrupt delays and stop the schedule.""" + if self._run_active: + self._executor.request_abort() + + def reset_schedule(self) -> None: + """Mark all items PENDING again and clear their execution state (not while running).""" with self._lock: - idx = self._index_of_locked(self._selected_item_id) - if idx is not None: - self.run_schedule(idx) - - @SafeSlot() - def abort_schedule(self): - """Request that the schedule stop after the current item.""" - self._abort_requested = True - if self._current_report is not None: - try: - self._current_report.cancel() - except Exception: # pylint: disable=broad-except - logger.exception("Failed to cancel the currently running schedule item") - - @SafeSlot() - def pause_schedule(self): - self._pause_requested = True - - @SafeSlot() - def reset_schedule(self): - """Clear all execution state and start the schedule over from item 1.""" - with self._lock: - if self.schedule.is_running: - logger.info("Cannot reset schedule, as schedule is running!") + if self._run_active or self.schedule.is_running: + logger.info("Cannot reset the schedule while it is running.") return for item in self.schedule.items: - logger.info(f"Reset schedule item {item}") - item.status = ScheduleItemStatus.PENDING - item.request_id = None - item.scan_id = None - item.scan_number = None - item.error = None - item.started_at = None - item.finished_at = None + item.reset_execution() self._persist_locked() self.schedule_changed.emit() def get_status(self) -> dict: - """RPC-exposed: current schedule state, e.g. for another widget or a script.""" + """The complete schedule (definition and execution state) as a JSON-compatible dict.""" with self._lock: return self.schedule.model_dump(mode="json") - # ------------------------------------------------------------------ # - # RPC-exposed schedule editing (add / edit / move / delete) - # - # All of these only ever touch the PENDING suffix of the schedule - - # see the "protected prefix" section of the module docstring. They can - # be called at any time, including while the schedule is running. - # ------------------------------------------------------------------ # + # ------------------------------------------------------------------------------------------ # + # RPC-exposed schedule editing. These only ever touch PENDING items and can be called at any + # time, also while the schedule is running. + # ------------------------------------------------------------------------------------------ # + @staticmethod + def _validated_definition( + action: str, + params: dict | None, + wait_for_completion: bool, + pause_on_failure: bool, + pause_on_state: bool, + ) -> dict: + if action not in ACTIONS: + raise ValueError(f"Unknown action {action!r}. Available: {sorted(ACTIONS)}") + params = dict(params or {}) + json.dumps(params) # raises TypeError if not JSON-serialisable + return { + "action": action, + "params": params, + "wait_for_completion": wait_for_completion or action in ALWAYS_WAIT_ACTIONS, + "pause_on_failure": pause_on_failure, + "pause_on_state": pause_on_state, + } + def add_item( self, - command: str, + action: str, + params: dict | None = None, index: int | None = None, - kind: str = "custom", - form_state: dict | None = None, + wait_for_completion: bool = True, pause_on_failure: bool = False, + pause_on_state: bool = False, ) -> str: """ - RPC-exposed: insert a new, PENDING command into the schedule. - Safe to call while the schedule is running. + Insert a new PENDING item. Args: - command: command text, evaluated the same way as the existing - items (against `scans`/`dev`) once the schedule runs. - index: position to insert at (0 = first). Clamped so the item - can never land before something already running or - finished. Defaults to appending at the end. - kind/form_state: optional structured description of how - `command` was built (see `schedule_item.ScheduleItem`), - used to reopen the Edit dialog pre-filled. Leave as - defaults for a plain, hand-typed command. + action: Registered action name, e.g. "scan", "move", "delay", "wait_for_parent". + params: JSON-serialisable parameters of the action, e.g. + `{"device": "samx", "value": 1.0, "relative": False}` for "move" or + `{"seconds": 60}` for "delay". + index: Insert position (0 = first). Clamped so the item never lands before an item + that has already started. Defaults to the end. + wait_for_completion: If False, the following items start while this one runs. + pause_on_failure: Pause the schedule if this item fails. + pause_on_state: Only start while all beamline states are VALID/WARNING. Returns: - The new item's item_id. - """ - command = command.strip() - if not command: - raise ValueError("command must not be empty") + The id of the new item. - with self._lock: - protected = self._protected_prefix_length_locked() - item = ScheduleItem( - item_id=str(uuid.uuid4()), - command=command, - kind=kind, - form_state=form_state, - pause_on_failure=pause_on_failure, + Raises: + ValueError: Unknown action. + TypeError: Parameters are not JSON-serialisable. + """ + item = ScheduleItem( + **self._validated_definition( + action, params, wait_for_completion, pause_on_failure, pause_on_state ) + ) + with self._lock: + protected = protected_prefix_length(self.schedule.items) if index is None or index >= len(self.schedule.items): self.schedule.items.append(item) else: @@ -1279,299 +940,134 @@ class Scheduler(BECWidget, QWidget): def edit_item( self, item_id: str, - command: str, - kind: str = "custom", - form_state: dict | None = None, - pause_on_failure: bool = True, - ): + action: str, + params: dict | None = None, + wait_for_completion: bool = True, + pause_on_failure: bool = False, + pause_on_state: bool = False, + ) -> None: """ - RPC-exposed: change the command of an item that has not started - yet. Raises `RuntimeError` for an item that is already - running/finished. + Replace the definition of an item that has not started yet (see `add_item` for the + arguments). + + Raises: + RuntimeError: The item has already started or finished. """ - - logger.info(f"edit item with form_state: {form_state}") - - command = command.strip() - if not command: - raise ValueError("command must not be empty") - + definition = self._validated_definition( + action, params, wait_for_completion, pause_on_failure, pause_on_state + ) with self._lock: - idx = self._index_of_locked(item_id) + idx = index_of(self.schedule.items, item_id) if idx is None: return item = self.schedule.items[idx] - if item.status != ScheduleItemStatus.PENDING: + if item.status != ItemStatus.PENDING: raise RuntimeError("Only items that have not started yet (PENDING) can be edited.") - item.command = command - item.kind = kind - item.form_state = form_state - item.pause_on_failure = pause_on_failure + for key, value in definition.items(): + setattr(item, key, value) self._persist_locked() self.schedule_changed.emit() - def delete_item(self, item_id: str): + def delete_item(self, item_id: str) -> None: """ - RPC-exposed: remove an item that has not started yet. Raises - `RuntimeError` for an item that is already running/finished. + Remove an item that has not started yet. + + Raises: + RuntimeError: The item has already started or finished. """ with self._lock: - idx = self._index_of_locked(item_id) + idx = index_of(self.schedule.items, item_id) if idx is None: return - if self.schedule.items[idx].status != ScheduleItemStatus.PENDING: + if self.schedule.items[idx].status != ItemStatus.PENDING: raise RuntimeError("Only items that have not started yet (PENDING) can be deleted.") del self.schedule.items[idx] self._persist_locked() self.schedule_changed.emit() - def move_item(self, item_id: str, new_index: int): + def move_item(self, item_id: str, new_index: int) -> None: """ - RPC-exposed: move an item that has not started yet to a new - position (0 = first, but never before something already - running/finished). Raises `RuntimeError` for an item that is - already running/finished. + Move an item that has not started yet to `new_index` (never before an item that has + already started). + + Raises: + RuntimeError: The item has already started or finished. """ with self._lock: - idx = self._index_of_locked(item_id) + idx = index_of(self.schedule.items, item_id) if idx is None: return - if self.schedule.items[idx].status != ScheduleItemStatus.PENDING: + if self.schedule.items[idx].status != ItemStatus.PENDING: raise RuntimeError("Only items that have not started yet (PENDING) can be moved.") - protected = self._protected_prefix_length_locked() item = self.schedule.items.pop(idx) + protected = protected_prefix_length(self.schedule.items) new_index = max(protected, min(new_index, len(self.schedule.items))) self.schedule.items.insert(new_index, item) self._persist_locked() self.schedule_changed.emit() - def move_item_up(self, item_id: str): - """RPC-exposed: swap an item with the one directly before it.""" + def move_item_up(self, item_id: str) -> None: + """Swap an item with the one above it.""" with self._lock: - idx = self._index_of_locked(item_id) - target = idx - 1 if idx is not None and idx > 0 else None - if target is not None: - self.move_item(item_id, target) - self._refresh_ui() - self._update_buttons() + idx = index_of(self.schedule.items, item_id) + if idx: + self.move_item(item_id, idx - 1) - def move_item_down(self, item_id: str): - """RPC-exposed: swap an item with the one directly after it.""" + def move_item_down(self, item_id: str) -> None: + """Swap an item with the one below it.""" with self._lock: - idx = self._index_of_locked(item_id) - n = len(self.schedule.items) - target = idx + 1 if idx is not None and idx < n - 1 else None - if target is not None: - self.move_item(item_id, target) - self._refresh_ui() - self._update_buttons() + idx = index_of(self.schedule.items, item_id) + count = len(self.schedule.items) + if idx is not None and idx < count - 1: + self.move_item(item_id, idx + 1) - # ------------------------------------------------------------------ # - # execution - runs in a background task (BECConnector.submit_task, - # backed by a QThreadPool worker thread; UI updates below go through - # the `schedule_changed` Qt signal so they are marshalled back onto - # the GUI thread instead of touching widgets directly) - # ------------------------------------------------------------------ # - def _pick_next_runnable_locked(self, repeat_aborted_item, first_item): - """Must be called while holding `self._lock`; see `schedule_logic.pick_next_runnable`.""" - return pick_next_runnable(self.schedule.items, repeat_aborted_item, first_item) + # ------------------------------------------------------------------------------------------ # + # Execution (worker thread, via submit_task) + # ------------------------------------------------------------------------------------------ # + def _run_all(self, first_item_id: str | None, retry_unfinished: bool) -> None: + """Worker-thread body of a run: notifications around `ScheduleExecutor.run`.""" + settings = self.schedule.notifications + notify_schedule_state(self.client, settings, self.schedule.schedule_name, "started") + outcome: RunOutcome = "widget_closed" + try: + outcome = self._executor.run(first_item_id, retry_unfinished) + finally: + notify_schedule_state(self.client, settings, self.schedule.schedule_name, outcome) + with self._lock: + self.schedule.is_running = False + self._persist_locked() @SafeSlot() - def _on_run_finished(self): + def _on_run_finished(self) -> None: + self._run_active = False self._refresh_ui() @SafeSlot(str) - def _on_run_failed(self, error: str): - logger.error(f"Schedule execution task failed unexpectedly: {error}") + def _on_run_failed(self, error: str) -> None: + logger.error(f"Schedule execution failed unexpectedly: {error}") + self._run_active = False with self._lock: self.schedule.is_running = False self._persist_locked() self._refresh_ui() - def _emit_schedule_changed(self): - if self._closing.is_set(): - return - - self.schedule_changed.emit() - - def closeEvent(self, event): - """Ensure cleanup is invoked when the widget is closed via the window system.""" - self.cleanup() - super().closeEvent(event) - - def cleanup(self): - """Stop background execution loops without cancelling server-side scans.""" + def cleanup(self) -> None: + """ + Stop the execution loop without cancelling server-side work, flush unsaved notes and + release all subscriptions. Child BEC widgets (the state manager) are cleaned up by + `BECWidget.cleanup`. + """ self._closing.set() - - # Flush any not-yet-saved notes edit instead of losing it - the - # debounce timer won't get a chance to fire once we're closing. + self._executor.notify_closing() + self._live_timer.stop() if self._notes_save_timer.isActive(): self._notes_save_timer.stop() self._persist_notes() - - # Interrupt guard wait loops if any thread is blocked in self._guard.wait_until_clear() - self._guard.cleanup() - + self.state_monitor.cleanup() super().cleanup() - def _run_all(self, repeat_aborted_item, first_item): - notify_schedule_state( - self.client, self.schedule.notifications, self.schedule.schedule_name, "started" - ) - namespace = { - "scans": self.scans, - "dev": self.dev, - "digital_twin": self.digital_twin, - "auto_gain": self.auto_gain, - "np": np, - } - while ( - not self._abort_requested and not self._closing.is_set() and not self._pause_requested - ): - with self._lock: - next_item = self._pick_next_runnable_locked(repeat_aborted_item, first_item) - if next_item is None or next_item == "stop": - logger.info("Next item is None or stop") - break - if next_item.status == ScheduleItemStatus.RUNNING: - self._await_running_item(next_item) - else: - self._execute_item(next_item, namespace) - if self._abort_requested: - notify_schedule_state( - self.client, self.schedule.notifications, self.schedule.schedule_name, "aborted" - ) - elif self._closing.is_set(): - notify_schedule_state( - self.client, - self.schedule.notifications, - self.schedule.schedule_name, - "widget_closed", - ) - elif self._pause_requested: - notify_schedule_state( - self.client, self.schedule.notifications, self.schedule.schedule_name, "paused" - ) - else: - notify_schedule_state( - self.client, self.schedule.notifications, self.schedule.schedule_name, "finished" - ) - with self._lock: - logger.info("in _run_all, set is_running to false") - self.schedule.is_running = False - self._persist_locked() - self._emit_schedule_changed() - def _execute_item(self, item: ScheduleItem, namespace: dict): - if item.kind == "scan": - # Block here until the guard is clear, operator aborts, or widget closes - cleared = self._guard.wait_until_clear( - should_abort=lambda: self._abort_requested or self._closing.is_set() - ) - self._emit_schedule_changed() - if not cleared or self._closing.is_set(): - return - - with self._lock: - item.status = ScheduleItemStatus.RUNNING - item.error = None - item.started_at = time.time() - self._persist_locked() - self._emit_schedule_changed() - - try: - report = eval( - item.command, {"__builtins__": {}}, namespace - ) # noqa: S307 pylint: disable=eval-used - self._current_report = report - self._current_item_kind = item.kind - - request = getattr(report, "request", None) - with self._lock: - item.request_id = getattr(request, "requestID", None) - self._persist_locked() - - # RPC commands may not return a status, thus have no wait() - if item.kind != "custom": - report.wait() - - if self._closing.is_set(): - # The widget was closed mid-item; exit without changing status in Redis. - # Reconciliation logic will handle state on reopen. - return - - scan = getattr(report, "scan", None) - with self._lock: - item.scan_id = getattr(scan, "scan_id", None) if scan else None - item.scan_number = getattr(scan, "scan_number", None) if scan else None - item.status = ( - ScheduleItemStatus.ABORTED - if self._abort_requested - else ScheduleItemStatus.COMPLETED - ) - except Exception: # pylint: disable=broad-except - if self._closing.is_set(): - return - with self._lock: - if self._guard_interrupt_requested: - item.status = ScheduleItemStatus.PENDING - item.request_id = None - item.scan_id = None - item.scan_number = None - item.error = None - item.started_at = None - self._guard_interrupt_requested = False - elif self._abort_requested: - item.status = ScheduleItemStatus.ABORTED - else: - item.status = ScheduleItemStatus.FAILED - item.error = traceback.format_exc() - logger.error(f"Schedule item failed: {item.command}\n{item.error}") - if item.pause_on_failure: - self._abort_requested = True - finally: - if not self._closing.is_set(): - with self._lock: - if item.status != ScheduleItemStatus.PENDING: - item.finished_at = time.time() - self._persist_locked() - final_status = item.status - self._current_report = None - self._current_item_kind = None - self._emit_schedule_changed() - else: - final_status = None - - if final_status in ( - ScheduleItemStatus.COMPLETED, - ScheduleItemStatus.FAILED, - ScheduleItemStatus.ABORTED, - ): - notify_item_finished( - self.client, - item.kind, - item.command, - item.scan_number, - final_status=final_status, - settings=self.schedule.notifications, - error=item.error, - ) - - def _await_running_item(self, item: ScheduleItem): - queue_storage = self.client.queue.queue_storage - while not self._abort_requested and not self._closing.is_set(): - queue_item = queue_storage.find_queue_item_by_requestID(item.request_id) - if queue_item is None or not self._is_queue_item_active(queue_item): - with self._lock: - item.status = ScheduleItemStatus.COMPLETED - item.finished_at = time.time() - self._persist_locked() - self._emit_schedule_changed() - return - time.sleep(0.5) - - -if __name__ == "__main__": +if __name__ == "__main__": # pragma: no cover app = QApplication(sys.argv) dispatcher = BECDispatcher(gui_id="Scheduler") win = Scheduler() diff --git a/debye_bec/bec_widgets/widgets/scheduler/state_monitor.py b/debye_bec/bec_widgets/widgets/scheduler/state_monitor.py new file mode 100644 index 0000000..d43ed6b --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/state_monitor.py @@ -0,0 +1,190 @@ +""" +Watch all BEC beamline states on behalf of the Scheduler ("pause on state"). + +Beamline states are created, edited and deleted with BEC's own `BeamlineStateManager` widget, +which the Scheduler embeds. This module only *reads* them: it follows +`MessageEndpoints.available_beamline_states()` to learn which states exist, subscribes to +`MessageEndpoints.beamline_state(name)` of each of them through the `BECDispatcher`, and keeps +track of whether all of them are acceptable (VALID or WARNING). + +Dispatcher callbacks run on the Qt GUI thread. The schedule executor runs on a worker thread and +only uses the thread-safe `is_ok()` / `wait_until_ok()` methods, backed by a `threading.Event`. +""" + +from __future__ import annotations + +import threading +from typing import Any, Callable + +from bec_lib.endpoints import MessageEndpoints +from bec_lib.logger import bec_logger +from bec_widgets.utils.error_popups import SafeSlot + +# pylint: disable=no-name-in-module # qtpy re-exports are not visible to pylint +from qtpy.QtCore import QObject, Signal + +logger = bec_logger.logger + +#: Beamline state statuses that do not pause gated schedule items. +OK_STATUSES = frozenset({"valid", "warning"}) + + +def _state_name(state: Any) -> str | None: + """Name of a `BeamlineStateConfig` (object or plain dict).""" + if isinstance(state, dict): + return state.get("name") + return getattr(state, "name", None) + + +class BeamlineStateMonitor(QObject): + """ + Aggregates the status of all beamline states. + + Signals: + tripped(): At least one state left VALID/WARNING (was OK before). + recovered(): All states are VALID/WARNING again (was not OK before). + statuses_changed(): Any status changed, or a state was added/removed. + + A state whose status is still unknown (e.g. right after creation, or if its device is not + reachable) counts as not OK, so that gated items never start on unverified conditions. + Without any beamline states, the monitor is always OK. + """ + + tripped = Signal() + recovered = Signal() + statuses_changed = Signal() + + def __init__(self, client, bec_dispatcher, parent: QObject | None = None) -> None: + super().__init__(parent) + self._client = client + self._dispatcher = bec_dispatcher + self._lock = threading.Lock() + self._statuses: dict[str, str] = {} + self._ok_event = threading.Event() + self._ok_event.set() + + self._dispatcher.connect_slot( + self._on_available_states, MessageEndpoints.available_beamline_states() + ) + msg = self._client.connector.get_last( + MessageEndpoints.available_beamline_states(), key="data" + ) + if msg is not None: + self._on_available_states(msg.content, msg.metadata) + + # ------------------------------------------------------------------------------------------ # + # Thread-safe queries (used by the executor's worker thread) + # ------------------------------------------------------------------------------------------ # + def is_ok(self) -> bool: + """True if every beamline state is VALID or WARNING (or no states exist).""" + return self._ok_event.is_set() + + def wait_until_ok(self, should_abort: Callable[[], bool], poll_interval: float = 0.5) -> bool: + """ + Block the calling (non-GUI) thread until `is_ok()` is True. + + Args: + should_abort: Polled between waits; the wait ends early if it returns True. + poll_interval: Seconds between two `should_abort` checks. + + Returns: + True if the states became OK, False if `should_abort()` returned True first. + """ + while not should_abort(): + if self._ok_event.wait(timeout=poll_interval): + return True + return False + + def statuses(self) -> dict[str, str]: + """A copy of the current `{state name: status}` mapping.""" + with self._lock: + return dict(self._statuses) + + def blocking_states(self) -> list[str]: + """Names of the states that currently prevent gated items from running.""" + with self._lock: + return sorted( + name for name, status in self._statuses.items() if status not in OK_STATUSES + ) + + def summary(self) -> str: + """One-line, human-readable summary, e.g. for a status label.""" + statuses = self.statuses() + if not statuses: + return "No beamline states defined" + blocking = self.blocking_states() + if not blocking: + return f"All {len(statuses)} beamline state(s) OK" + return f"Not OK: {', '.join(blocking)} - items with 'pause on state' will wait" + + # ------------------------------------------------------------------------------------------ # + # Dispatcher callbacks (GUI thread) + # ------------------------------------------------------------------------------------------ # + @SafeSlot(dict, dict) + def _on_available_states(self, content: dict, _metadata: dict | None = None) -> None: + names = {name for state in content.get("states", []) if (name := _state_name(state))} + with self._lock: + known = set(self._statuses) + for name in known - names: + self._dispatcher.disconnect_slot( + self._on_state_update, MessageEndpoints.beamline_state(name) + ) + with self._lock: + self._statuses.pop(name, None) + for name in names - known: + with self._lock: + self._statuses[name] = "unknown" + self._dispatcher.connect_slot( + self._on_state_update, MessageEndpoints.beamline_state(name) + ) + last = self._client.connector.get_last( + MessageEndpoints.beamline_state(name), key="data" + ) + if last is not None: + self._set_status(name, last.content.get("status")) + self._evaluate() + + @SafeSlot(dict, dict) + def _on_state_update(self, content: dict, _metadata: dict | None = None) -> None: + name = content.get("name") + if not name: + return + with self._lock: + if name not in self._statuses: + return # update of a state that was just removed + self._set_status(name, content.get("status")) + self._evaluate() + + def _set_status(self, name: str, status: Any) -> None: + with self._lock: + self._statuses[name] = str(status or "unknown").lower() + + def _evaluate(self) -> None: + with self._lock: + ok = all(status in OK_STATUSES for status in self._statuses.values()) + was_ok = self._ok_event.is_set() + if ok: + self._ok_event.set() + else: + self._ok_event.clear() + self.statuses_changed.emit() + if was_ok and not ok: + logger.info(f"Scheduler: beamline state(s) not OK: {self.blocking_states()}") + self.tripped.emit() + elif ok and not was_ok: + logger.info("Scheduler: all beamline states OK again.") + self.recovered.emit() + + def cleanup(self) -> None: + """Disconnect all dispatcher subscriptions and release waiting threads.""" + self._dispatcher.disconnect_slot( + self._on_available_states, MessageEndpoints.available_beamline_states() + ) + with self._lock: + names = list(self._statuses) + self._statuses.clear() + for name in names: + self._dispatcher.disconnect_slot( + self._on_state_update, MessageEndpoints.beamline_state(name) + ) + self._ok_event.set() diff --git a/debye_bec/bec_widgets/widgets/scheduler/widgets.py b/debye_bec/bec_widgets/widgets/scheduler/widgets.py new file mode 100644 index 0000000..ffff9a3 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/scheduler/widgets.py @@ -0,0 +1,35 @@ +"""Small reusable Qt widgets of the Scheduler.""" + +from __future__ import annotations + +from bec_widgets.utils.colors import get_accent_colors + +# pylint: disable=no-name-in-module # qtpy re-exports are not visible to pylint +from qtpy.QtWidgets import QPushButton + + +class AccentButton(QPushButton): + """ + Push button filled with one of BEC's accent colours ("default", "success", "warning", + "emergency", ...), greyed out while disabled. + """ + + def __init__(self, text: str = "", color: str = "default", parent=None): + self.color = color + super().__init__(text, parent) + self.apply_theme() + + def apply_theme(self) -> None: + """Re-apply the colours, e.g. after a theme change.""" + if self.isEnabled(): + color = getattr(get_accent_colors(), self.color).name() + self.setStyleSheet(f"QPushButton {{ background-color: {color}; color: white; }}") + else: + self.setStyleSheet( + "QPushButton { background-color: rgb(120, 120, 120); color: white; }" + ) + + def setEnabled(self, enable: bool = True) -> None: # noqa: N802 pylint: disable=invalid-name + """Enable/disable the button and update its colours.""" + super().setEnabled(enable) + self.apply_theme() diff --git a/tests/tests_bec_widgets/test_scheduler_executor.py b/tests/tests_bec_widgets/test_scheduler_executor.py new file mode 100644 index 0000000..dceae41 --- /dev/null +++ b/tests/tests_bec_widgets/test_scheduler_executor.py @@ -0,0 +1,284 @@ +"""Tests for the Scheduler's execution loop (`ScheduleExecutor`) with fake BEC handles.""" + +# pylint: disable=missing-function-docstring,missing-class-docstring +import threading +import time +from unittest import mock + +import pytest + +from debye_bec.bec_widgets.widgets.scheduler.actions import ExecutionContext +from debye_bec.bec_widgets.widgets.scheduler.executor import ScheduleExecutor +from debye_bec.bec_widgets.widgets.scheduler.models import ItemStatus, ScheduleItem + +TIMEOUT = 5 + + +class FakeHandle: + """Mimics a BEC ScanReport: `wait()` blocks until released, `cancel()` makes it raise.""" + + def __init__(self, release: threading.Event | None = None): + self.release = release or threading.Event() + if release is None: + self.release.set() + self.cancelled = threading.Event() + self.request = None + + def wait(self): + while not self.release.wait(0.01): + if self.cancelled.is_set(): + raise RuntimeError("cancelled") + if self.cancelled.is_set(): + raise RuntimeError("cancelled") + + def cancel(self): + self.cancelled.set() + + +class FakeStateMonitor: + def __init__(self): + self.ok = threading.Event() + self.ok.set() + + def is_ok(self): + return self.ok.is_set() + + def wait_until_ok(self, should_abort, poll_interval=0.01): + while not should_abort(): + if self.ok.wait(poll_interval): + return True + return False + + def blocking_states(self): + return [] if self.ok.is_set() else ["beam"] + + +class Harness: + def __init__(self, items: list[ScheduleItem]): + self.items = items + self.scans = mock.MagicMock() + self.dev = {"samx": mock.MagicMock()} + self.dev["samx"].move.return_value = FakeHandle() + self.monitor = FakeStateMonitor() + self.notified: list[str] = [] + self.closing = threading.Event() + self.executor = ScheduleExecutor( + lock=threading.Lock(), + get_items=lambda: self.items, + persist_locked=lambda: None, + emit_changed=lambda: None, + context=ExecutionContext(scans=self.scans, dev=self.dev), + state_monitor=self.monitor, + notify_item=lambda item: self.notified.append(item.item_id), + get_queue_storage=mock.MagicMock, + closing=self.closing, + ) + self.outcome = None + self.thread = None + + def start(self, **kwargs): + def _run(): + self.outcome = self.executor.run(**kwargs) + + self.thread = threading.Thread(target=_run, daemon=True) + self.thread.start() + + def join(self): + self.thread.join(TIMEOUT) + assert not self.thread.is_alive(), "executor did not finish" + return self.outcome + + +def _wait_until(predicate, timeout=TIMEOUT): + deadline = time.time() + timeout + while time.time() < deadline: + if predicate(): + return + time.sleep(0.01) + pytest.fail("condition not reached") + + +def _scan(item_id, wait=True, pause_on_state=False): + return ScheduleItem( + item_id=item_id, + action="scan", + params={"scan_name": "line_scan", "args": [], "kwargs": {}}, + wait_for_completion=wait, + pause_on_state=pause_on_state, + ) + + +def _delay(item_id, seconds=0.05): + return ScheduleItem(item_id=item_id, action="delay", params={"seconds": seconds}) + + +def _move(item_id, pause_on_failure=False): + return ScheduleItem( + item_id=item_id, + action="move", + params={"device": "samx", "value": 1.0, "relative": False, "units": "mm"}, + pause_on_failure=pause_on_failure, + ) + + +def _by_id(harness, item_id): + return next(item for item in harness.items if item.item_id == item_id) + + +def test_sequential_items_complete(): + harness = Harness([_move("m1"), _delay("d1"), _move("m2")]) + harness.start() + assert harness.join() == "finished" + assert all(item.status == ItemStatus.COMPLETED for item in harness.items) + assert harness.notified == ["m1", "d1", "m2"] + assert _by_id(harness, "d1").report.startswith("Waited") + + +def test_background_item_runs_concurrently_with_its_block(): + release = threading.Event() + parent_handle = FakeHandle(release) + harness = Harness( + [ + _scan("parent", wait=False), + _delay("child1"), + _delay("child2"), + ScheduleItem(item_id="join", action="wait_for_parent"), + _move("after"), + ] + ) + harness.scans.line_scan.return_value = parent_handle + harness.start() + + _wait_until(lambda: _by_id(harness, "child2").status == ItemStatus.COMPLETED) + assert _by_id(harness, "parent").status == ItemStatus.RUNNING + _wait_until(lambda: _by_id(harness, "join").status == ItemStatus.RUNNING) + time.sleep(0.1) + assert _by_id(harness, "after").status == ItemStatus.PENDING # still waiting for parent + + release.set() + assert harness.join() == "finished" + assert all(item.status == ItemStatus.COMPLETED for item in harness.items) + assert _by_id(harness, "after").started_at >= _by_id(harness, "parent").finished_at + + +def test_next_background_item_implicitly_waits_for_previous(): + release = threading.Event() + first, second = FakeHandle(release), FakeHandle() + harness = Harness([_scan("bg1", wait=False), _delay("child"), _scan("bg2", wait=False)]) + harness.scans.line_scan.side_effect = [first, second] + harness.start() + _wait_until(lambda: _by_id(harness, "child").status == ItemStatus.COMPLETED) + time.sleep(0.1) + assert _by_id(harness, "bg2").status == ItemStatus.PENDING + release.set() + assert harness.join() == "finished" + assert _by_id(harness, "bg2").started_at >= _by_id(harness, "bg1").finished_at + + +def test_failure_without_pause_continues(): + harness = Harness([_move("bad"), _move("good")]) + harness.dev["samx"].move.side_effect = [RuntimeError("motor error"), FakeHandle()] + harness.start() + assert harness.join() == "finished" + assert _by_id(harness, "bad").status == ItemStatus.FAILED + assert "motor error" in _by_id(harness, "bad").report + assert _by_id(harness, "good").status == ItemStatus.COMPLETED + + +def test_pause_on_failure_pauses(): + harness = Harness([_move("bad", pause_on_failure=True), _move("next")]) + harness.dev["samx"].move.side_effect = RuntimeError("motor error") + harness.start() + assert harness.join() == "paused_on_failure" + assert _by_id(harness, "bad").status == ItemStatus.FAILED + assert _by_id(harness, "next").status == ItemStatus.PENDING + + +def test_retry_unfinished_runs_failed_item_once(): + harness = Harness([_move("bad"), _move("next")]) + harness.items[0].status = ItemStatus.FAILED + harness.dev["samx"].move.side_effect = [RuntimeError("again"), FakeHandle()] + harness.start(retry_unfinished=True) + assert harness.join() == "finished" + assert _by_id(harness, "bad").status == ItemStatus.FAILED + assert _by_id(harness, "next").status == ItemStatus.COMPLETED + assert harness.dev["samx"].move.call_count == 2 + + +def test_abort_interrupts_delay(): + harness = Harness([_delay("long", seconds=100), _move("next")]) + harness.start() + _wait_until(lambda: _by_id(harness, "long").status == ItemStatus.RUNNING) + harness.executor.request_abort() + assert harness.join() == "aborted" + assert _by_id(harness, "long").status == ItemStatus.ABORTED + assert _by_id(harness, "next").status == ItemStatus.PENDING + + +def test_pause_after_current_item(): + harness = Harness([_delay("d1", seconds=0.2), _move("next")]) + harness.start() + _wait_until(lambda: _by_id(harness, "d1").status == ItemStatus.RUNNING) + harness.executor.request_pause() + assert harness.join() == "paused" + assert _by_id(harness, "d1").status == ItemStatus.COMPLETED + assert _by_id(harness, "next").status == ItemStatus.PENDING + + +def test_pause_on_state_waits_for_states(): + harness = Harness([_move("gated")]) + harness.items[0].pause_on_state = True + harness.monitor.ok.clear() + harness.start() + _wait_until(lambda: (_by_id(harness, "gated").report or "").startswith("Waiting")) + assert _by_id(harness, "gated").status == ItemStatus.PENDING + harness.monitor.ok.set() + assert harness.join() == "finished" + assert _by_id(harness, "gated").status == ItemStatus.COMPLETED + + +def test_state_trip_cancels_and_repeats_gated_scan(): + first = FakeHandle(threading.Event()) # blocks until cancelled + second = FakeHandle() + harness = Harness([_scan("scan", pause_on_state=True)]) + harness.scans.line_scan.side_effect = [first, second] + harness.start() + _wait_until(lambda: _by_id(harness, "scan").status == ItemStatus.RUNNING) + + harness.monitor.ok.clear() + harness.executor.on_states_tripped() + _wait_until(lambda: first.cancelled.is_set()) + _wait_until(lambda: (_by_id(harness, "scan").report or "").startswith("Waiting")) + harness.monitor.ok.set() + + assert harness.join() == "finished" + assert _by_id(harness, "scan").status == ItemStatus.COMPLETED + assert harness.scans.line_scan.call_count == 2 + + +def test_state_trip_does_not_interrupt_ungated_scan(): + release = threading.Event() + handle = FakeHandle(release) + harness = Harness([_scan("scan", pause_on_state=False)]) + harness.scans.line_scan.return_value = handle + harness.start() + _wait_until(lambda: _by_id(harness, "scan").status == ItemStatus.RUNNING) + harness.executor.on_states_tripped() + assert not handle.cancelled.is_set() + release.set() + assert harness.join() == "finished" + + +def test_closing_leaves_running_item_untouched(): + harness = Harness([_scan("scan")]) + harness.scans.line_scan.return_value = FakeHandle(threading.Event()) + harness.start() + _wait_until(lambda: _by_id(harness, "scan").status == ItemStatus.RUNNING) + harness.closing.set() + harness.executor.notify_closing() + # The fake scan only ends when cancelled; closing must not cancel it server-side. + time.sleep(0.1) + assert _by_id(harness, "scan").status == ItemStatus.RUNNING + harness.scans.line_scan.return_value.cancel() + assert harness.join() == "widget_closed" + assert _by_id(harness, "scan").status == ItemStatus.RUNNING diff --git a/tests/tests_bec_widgets/test_scheduler_logic.py b/tests/tests_bec_widgets/test_scheduler_logic.py new file mode 100644 index 0000000..e53d534 --- /dev/null +++ b/tests/tests_bec_widgets/test_scheduler_logic.py @@ -0,0 +1,311 @@ +"""Tests for the Scheduler's data model, action registry and pure scheduling logic.""" + +# pylint: disable=missing-function-docstring +import json +from unittest import mock + +import pytest + +from debye_bec.bec_widgets.widgets.scheduler.actions import ( + ACTIONS, + ExecutionContext, + describe_item, + format_duration, + run_action, +) +from debye_bec.bec_widgets.widgets.scheduler.models import ( + ItemStatus, + NotificationTarget, + Schedule, + ScheduleItem, + is_legacy_schedule, + schedule_from_document, +) +from debye_bec.bec_widgets.widgets.scheduler.schedule_logic import ( + BlockRole, + block_parents, + block_roles, + item_depths, + pick_next_runnable, + protected_prefix_length, +) + +# A schedule document as written to Redis by the previous (eval-based) Scheduler version. +LEGACY_SCHEDULE = { + "schedule_name": "default_schedule", + "items": [ + { + "item_id": "a", + "command": "dev.samx.move(1.0, relative=False)", + "status": "completed", + "kind": "move", + "form_state": {"device_name": "samx", "value": 1.0, "units": "mm", "relative": False}, + "pause_on_failure": False, + } + ], + "is_running": False, + "notes": "", + "notifications": {"enabled": True, "target": "teams", "teams_scope": "x", "events": []}, + "guard": {"enabled": False, "device_name": None, "pause_below": None, "resume_above": None}, +} + +# Sample parameters for every registered action (the "describe" text must work with them). +SAMPLE_PARAMS = { + "scan": {"scan_name": "line_scan", "args": ["samx", -1, 1], "kwargs": {"steps": 10}}, + "move": {"device": "samx", "value": 1.5, "relative": True, "units": "mm"}, + "digital_twin": { + "config": { + "mo1_mode": "Monochromatic", + "energy": 9000, + "h_acc": 1e-3, + "v_acc": 1e-4, + "cm_stripe": "Rh", + "cm_pitch": 2e-3, + "mo1_xtal": "Si111", + "fm_stripe": "Pt", + "fm_rotx": 3e-3, + "ot_es1_trz": 100, + "es1man_trz": 1.0, + "smpl_to_xrd": 200.0, + } + }, + "auto_gain": { + "config": { + "element": "Cu", + "edge": "K", + "all_amplifiers": ["ic0", "ic1"], + "link_ic0_ic1": True, + "compensate_ring_current": True, + "prohibited_gains": {"ic0": [1e6]}, + } + }, + "absorber": {"action": "Open"}, + "ic_fill": { + "chamber": "IC1", + "gas1": "N2", + "conc1": 80.0, + "gas2": "Ar", + "conc2": 20.0, + "pressure": 1.5, + }, + "reffoil": {"foil": "Cu"}, + "temperature_controller": { + "config": { + "power_mode": "On", + "target_setpoint": 120, + "ramp_rate": 10, + "ramp_rate_unit": "K/min", + } + }, + "delay": {"seconds": 3725}, + "wait_for_parent": {}, +} + + +def _item(action="delay", wait=True, status=ItemStatus.PENDING, item_id=None, **params): + kwargs = {"item_id": item_id} if item_id else {} + return ScheduleItem( + action=action, + params=params or SAMPLE_PARAMS[action], + wait_for_completion=wait, + status=status, + **kwargs, + ) + + +# ---------------------------------------------------------------------------------------------- # +# models +# ---------------------------------------------------------------------------------------------- # +def test_legacy_schedule_is_detected_and_rejected(): + assert is_legacy_schedule(LEGACY_SCHEDULE) + with pytest.raises(Exception): + Schedule.model_validate(LEGACY_SCHEDULE) + + +def test_legacy_teams_target_maps_to_scilog(): + schedule = Schedule.model_validate({**LEGACY_SCHEDULE, "items": []}) + assert schedule.notifications.target == NotificationTarget.SCILOG + assert schedule.notifications.enabled + + +def test_legacy_notify_rpc_alias(): + schedule = Schedule.model_validate( + {"schedule_name": "s", "notifications": {"notify_rpc": False}} + ) + assert schedule.notifications.notify_device is False + + +def test_schedule_json_round_trip(): + schedule = Schedule( + schedule_name="s", items=[_item(action) for action in SAMPLE_PARAMS], notes="hello" + ) + data = json.loads(json.dumps(schedule.model_dump(mode="json"))) + assert Schedule.model_validate(data) == schedule + + +def test_reset_execution_and_definition(): + item = _item("move", status=ItemStatus.FAILED) + item.error, item.report, item.scan_number = "boom", "boom", 3 + item.reset_execution() + assert item.status == ItemStatus.PENDING + assert (item.error, item.report, item.scan_number) == (None, None, None) + assert set(item.definition()) == { + "action", + "params", + "wait_for_completion", + "pause_on_failure", + "pause_on_state", + } + + +# ---------------------------------------------------------------------------------------------- # +# actions +# ---------------------------------------------------------------------------------------------- # +def test_every_action_has_sample_params_and_description(): + assert set(ACTIONS) == set(SAMPLE_PARAMS) + for action, params in SAMPLE_PARAMS.items(): + json.dumps(params) + text = describe_item(_item(action), "x01da") + assert text and "Unknown action" not in text + + +def test_describe_unknown_action_does_not_raise(): + item = ScheduleItem(action="does_not_exist", params={"a": 1}) + assert "does_not_exist" in describe_item(item, None) + + +def test_run_action_unknown_raises(): + with pytest.raises(KeyError): + run_action(ExecutionContext(scans=None, dev=None), "does_not_exist", {}) + + +def test_run_scan_dispatches_to_scans(): + scans = mock.MagicMock() + ctx = ExecutionContext(scans=scans, dev=None) + run_action(ctx, "scan", SAMPLE_PARAMS["scan"]) + scans.line_scan.assert_called_once_with("samx", -1, 1, steps=10) + + +def test_run_scan_rejects_private_names(): + ctx = ExecutionContext(scans=mock.MagicMock(), dev=None) + with pytest.raises(ValueError): + run_action(ctx, "scan", {"scan_name": "_run", "args": [], "kwargs": {}}) + + +def test_run_move_dispatches_to_device(): + dev = {"samx": mock.MagicMock()} + run_action(ExecutionContext(scans=None, dev=dev), "move", SAMPLE_PARAMS["move"]) + dev["samx"].move.assert_called_once_with(1.5, relative=True) + + +def test_run_digital_twin_failure_raises(): + twin = mock.MagicMock() + twin.move_with_config.return_value = {"success": False, "failures": {"m": "x"}} + ctx = ExecutionContext(scans=None, dev=None, digital_twin=twin) + with pytest.raises(RuntimeError): + run_action(ctx, "digital_twin", SAMPLE_PARAMS["digital_twin"]) + + +def test_run_delay_is_interrupted_by_abort(): + ctx = ExecutionContext(scans=None, dev=None) + ctx.abort_event.set() + with pytest.raises(Exception): + run_action(ctx, "delay", {"seconds": 100}) + + +def test_control_action_cannot_be_run_directly(): + with pytest.raises(ValueError): + run_action(ExecutionContext(scans=None, dev=None), "wait_for_parent", {}) + + +def test_format_duration(): + assert format_duration(3725) == "1 h 02 min 05 s" + assert format_duration(150) == "2 min 30 s" + assert format_duration(5) == "5 s" + + +# ---------------------------------------------------------------------------------------------- # +# block structure +# ---------------------------------------------------------------------------------------------- # +def test_blocks_explicit_close(): + items = [ + _item("move"), + _item("scan", wait=False), + _item("temperature_controller"), + _item("delay"), + _item("wait_for_parent"), + _item("move"), + ] + assert block_parents(items) == [None, None, 1, 1, 1, None] + assert item_depths(items) == [0, 0, 1, 1, 1, 0] + assert block_roles(items) == [ + BlockRole.NONE, + BlockRole.PARENT, + BlockRole.CHILD, + BlockRole.CHILD, + BlockRole.LAST_CHILD, + BlockRole.NONE, + ] + + +def test_blocks_implicit_close_by_next_background_item_and_end(): + items = [_item("scan", wait=False), _item("delay"), _item("scan", wait=False), _item("delay")] + assert block_parents(items) == [None, 0, None, 2] + assert block_roles(items)[1] == BlockRole.LAST_CHILD + assert block_roles(items)[3] == BlockRole.LAST_CHILD + + +def test_background_item_without_children(): + items = [_item("scan", wait=False), _item("scan", wait=False)] + assert block_roles(items) == [BlockRole.PARENT_EMPTY, BlockRole.PARENT_EMPTY] + + +def test_wait_for_parent_outside_block_is_top_level(): + items = [_item("wait_for_parent"), _item("move")] + assert item_depths(items) == [0, 0] + + +# ---------------------------------------------------------------------------------------------- # +# next item / protected prefix +# ---------------------------------------------------------------------------------------------- # +def test_protected_prefix_with_several_running_items(): + items = [ + _item(status=ItemStatus.COMPLETED), + _item(status=ItemStatus.RUNNING), + _item(status=ItemStatus.RUNNING), + _item(), + ] + assert protected_prefix_length(items) == 3 + + +def test_pick_next_skips_completed_failed_and_active(): + items = [ + _item(status=ItemStatus.COMPLETED), + _item(status=ItemStatus.FAILED), + _item(status=ItemStatus.RUNNING, item_id="bg"), + _item(item_id="next"), + ] + assert pick_next_runnable(items, active_ids={"bg"}).item_id == "next" + + +def test_pick_next_retries_unfinished_once(): + items = [_item(status=ItemStatus.FAILED, item_id="f"), _item(item_id="p")] + assert pick_next_runnable(items, retry_unfinished=True).item_id == "f" + assert pick_next_runnable(items, retry_unfinished=True, attempted_ids={"f"}).item_id == "p" + + +def test_pick_next_respects_first_index_and_end(): + items = [_item(item_id="a"), _item(item_id="b")] + assert pick_next_runnable(items, first_index=1).item_id == "b" + assert pick_next_runnable([_item(status=ItemStatus.COMPLETED)]) is None + + +def test_schedule_from_document_never_raises(): + schedule, problem = schedule_from_document(LEGACY_SCHEDULE) + assert schedule is None and "old" in problem + schedule, problem = schedule_from_document({"items": "garbage"}) + assert schedule is None and problem + schedule, problem = schedule_from_document(None) + assert schedule is None and problem + schedule, problem = schedule_from_document({"schedule_name": "s", "items": []}) + assert problem is None and schedule.schedule_name == "s" diff --git a/tests/tests_bec_widgets/test_scheduler_state_monitor.py b/tests/tests_bec_widgets/test_scheduler_state_monitor.py new file mode 100644 index 0000000..f66ef30 --- /dev/null +++ b/tests/tests_bec_widgets/test_scheduler_state_monitor.py @@ -0,0 +1,117 @@ +"""Tests for the Scheduler's beamline-state monitor and the interlock hiding helper.""" + +# pylint: disable=missing-function-docstring,redefined-outer-name +from types import SimpleNamespace +from unittest import mock + +import pytest +from bec_lib.endpoints import MessageEndpoints +from qtpy.QtWidgets import QApplication + +from debye_bec.bec_widgets.widgets.scheduler.interlock_hiding import hide_scan_interlock_controls +from debye_bec.bec_widgets.widgets.scheduler.state_monitor import BeamlineStateMonitor + + +@pytest.fixture(scope="module") +def qapp(): + return QApplication.instance() or QApplication([]) + + +class FakeDispatcher: + def __init__(self): + self.slots: dict[str, object] = {} + + def connect_slot(self, slot, topic): + self.slots[topic.endpoint] = slot + + def disconnect_slot(self, slot, topic): + self.slots.pop(topic.endpoint, None) + + def publish_state(self, name, status): + self.slots[MessageEndpoints.beamline_state(name).endpoint]( + {"name": name, "status": status, "label": ""}, {} + ) + + +@pytest.fixture +def monitor(qapp): # pylint: disable=unused-argument + client = mock.MagicMock() + client.connector.get_last.return_value = None + dispatcher = FakeDispatcher() + mon = BeamlineStateMonitor(client, dispatcher) + yield mon, dispatcher + mon.cleanup() + + +def _set_available(dispatcher, *names): + dispatcher.slots[MessageEndpoints.available_beamline_states().endpoint]( + {"states": [SimpleNamespace(name=name) for name in names]}, {} + ) + + +def test_no_states_is_ok(monitor): + mon, _ = monitor + assert mon.is_ok() + assert mon.summary() == "No beamline states defined" + + +def test_new_state_is_unknown_until_reported(monitor): + mon, dispatcher = monitor + _set_available(dispatcher, "beam") + assert not mon.is_ok() + dispatcher.publish_state("beam", "valid") + assert mon.is_ok() + + +def test_warning_is_ok_invalid_trips_and_recovers(monitor): + mon, dispatcher = monitor + tripped, recovered = mock.MagicMock(), mock.MagicMock() + mon.tripped.connect(tripped) + mon.recovered.connect(recovered) + _set_available(dispatcher, "beam", "shutter") + tripped.assert_called_once() # new states are "unknown" until they report + dispatcher.publish_state("beam", "valid") + dispatcher.publish_state("shutter", "warning") + assert mon.is_ok() + recovered.assert_called_once() + + dispatcher.publish_state("shutter", "invalid") + assert not mon.is_ok() + assert mon.blocking_states() == ["shutter"] + assert tripped.call_count == 2 + + dispatcher.publish_state("shutter", "valid") + assert mon.is_ok() + assert recovered.call_count == 2 + + +def test_removed_state_is_unsubscribed(monitor): + mon, dispatcher = monitor + _set_available(dispatcher, "beam") + dispatcher.publish_state("beam", "invalid") + assert not mon.is_ok() + _set_available(dispatcher) + assert mon.is_ok() + assert MessageEndpoints.beamline_state("beam").endpoint not in dispatcher.slots + + +def test_wait_until_ok_aborts(monitor): + mon, dispatcher = monitor + _set_available(dispatcher, "beam") + assert mon.wait_until_ok(should_abort=lambda: True) is False + + +def test_hide_scan_interlock_controls(): + action = mock.MagicMock() + pill = SimpleNamespace(_interlock_button=mock.MagicMock(), _interlock_warning_checkbox=None) + manager = SimpleNamespace( + _toolbar=SimpleNamespace( + components=SimpleNamespace(get_action=lambda name: SimpleNamespace(action=action)) + ), + _state_pills={"beam": pill}, + ) + hide_scan_interlock_controls(manager) # must not raise on the missing checkbox + action.setVisible.assert_called_with(False) + pill._interlock_button.setVisible.assert_called_once_with( + False + ) # pylint: disable=protected-access From 9367194e3525cd5ed02cfda221f9afb65572f138 Mon Sep 17 00:00:00 2001 From: hitz_s Date: Mon, 16 Nov 2026 08:07:35 +0100 Subject: [PATCH 56/56] fix(scheduler): temperature controller items, row heights and layout - Store the temperature controller config as a plain dict and pass its values to load_config() as keyword arguments, so the item is JSON-serialisable; the item dialog now rejects non-JSON parameters with a clear message. - Size table rows to the word-wrapped text at the current column width and recompute them when columns resize, so long commands are shown in full. - Start the block guide line at the top of the first child row instead of drawing it over the parent's text. - Move the notes field below the schedule name and put the file save/load buttons on their own left-aligned row. Co-Authored-By: Claude Opus 5.5 --- .../bec_widgets/widgets/scheduler/actions.py | 9 ++- .../widgets/scheduler/item_dialog.py | 19 ++++- .../widgets/scheduler/schedule_table.py | 71 +++++++++++++------ .../widgets/scheduler/scheduler.py | 32 +++++---- .../tests_bec_widgets/test_scheduler_logic.py | 9 +++ 5 files changed, 102 insertions(+), 38 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/scheduler/actions.py b/debye_bec/bec_widgets/widgets/scheduler/actions.py index 985e347..9d2571f 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/actions.py +++ b/debye_bec/bec_widgets/widgets/scheduler/actions.py @@ -445,7 +445,14 @@ register_action( # Temperature controller # ---------------------------------------------------------------------------------------------- # def _run_temperature_controller(ctx: ExecutionContext, config: dict): - return ctx.dev["univ_temp_cont"].load_config(config=config) + # Pass plain values: the device builds its own ConfigDict from them, so no pydantic object + # has to be stored in (or sent from) the schedule. + return ctx.dev["univ_temp_cont"].load_config( + power_mode=config["power_mode"], + target_setpoint=config["target_setpoint"], + ramp_rate=config["ramp_rate"], + ramp_rate_unit=config["ramp_rate_unit"], + ) def _describe_temperature_controller(params: dict, _beamline: str | None) -> str: diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index 230f173..8249938 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -12,7 +12,9 @@ which maps 1:1 onto `ScheduleItem` fields. from __future__ import annotations +import json import math +from types import SimpleNamespace from typing import Callable from bec_lib.logger import bec_logger @@ -481,8 +483,12 @@ class ScheduleItemDialog(QDialog): "temperature_controller", "Temperature Controller", page, - lambda: {"config": self.temperature_controller.get_config()}, - lambda params: self.temperature_controller.load_config(params["config"]), + # get_config() returns a pydantic ConfigDict; store it as a plain (JSON) dict. + lambda: {"config": self.temperature_controller.get_config().model_dump(mode="json")}, + # load_config() only reads attributes, so a namespace over the stored dict suffices. + lambda params: self.temperature_controller.load_config( + SimpleNamespace(**params["config"]) + ), ) # ------------------------------------------------------------------------------------------ # @@ -568,6 +574,15 @@ class ScheduleItemDialog(QDialog): except ValueError as exc: QMessageBox.warning(self, "Invalid item", str(exc)) return + try: + json.dumps(params) + except TypeError as exc: + # A page returned a non-JSON value (e.g. a pydantic model) - a programming error. + logger.error(f"Parameters of {action!r} are not JSON-serialisable: {params!r}") + QMessageBox.critical( + self, "Invalid item", f"The item parameters cannot be saved (not JSON): {exc}" + ) + return self._result = { "action": action, "params": params, diff --git a/debye_bec/bec_widgets/widgets/scheduler/schedule_table.py b/debye_bec/bec_widgets/widgets/scheduler/schedule_table.py index d1929ed..84f8a40 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/schedule_table.py +++ b/debye_bec/bec_widgets/widgets/scheduler/schedule_table.py @@ -18,7 +18,7 @@ from bec_qthemes import material_icon from bec_widgets.utils.colors import get_accent_colors # pylint: disable=no-name-in-module # qtpy re-exports are not visible to pylint -from qtpy.QtCore import QAbstractTableModel, QModelIndex, QRect, QSize, Qt, Signal +from qtpy.QtCore import QAbstractTableModel, QModelIndex, QRect, QSize, Qt, QTimer, Signal from qtpy.QtGui import QKeySequence, QPen from qtpy.QtWidgets import QHeaderView, QStyle, QStyledItemDelegate, QTableView @@ -236,57 +236,73 @@ def _paint_background(painter, option) -> None: class _TextDelegate(QStyledItemDelegate): """ - Paints multi-line text (labels contain explicit line breaks) and reports the full multi-line - height, so the view's ResizeToContents row mode can fit it. If `indent` is True, the text is - indented by the item's block depth and the block guide line is drawn. + Paints word-wrapped, multi-line text and reports the height the wrapped text needs at the + current column width, so the view's ResizeToContents row mode shows the full text. If + `indent` is True, the text is indented by the item's block depth and the block guide line + is drawn. Selection is painted with the palette highlight colour, like `BecLogTableView`. """ + _FLAGS = Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter + _H_MARGIN = 6 + def __init__(self, parent=None, indent: bool = False): super().__init__(parent) self._indent = indent + def _text_rect(self, cell: QRect, index: QModelIndex) -> QRect: + """Area of the cell the text is drawn in (margins and block indentation removed).""" + rect = cell.adjusted(self._H_MARGIN, _ROW_MARGIN // 2, -self._H_MARGIN, -(_ROW_MARGIN // 2)) + if self._indent: + rect.setLeft(rect.left() + (index.data(DepthRole) or 0) * INDENT_WIDTH) + return rect + def paint(self, painter, option, index): painter.save() _paint_background(painter, option) painter.setFont(option.font) text_pen = painter.pen() - - rect = option.rect.adjusted(6, _ROW_MARGIN // 2, -6, -(_ROW_MARGIN // 2)) if self._indent: - depth = index.data(DepthRole) or 0 self._paint_guide(painter, option.rect, index.data(BlockRoleRole)) - rect.setLeft(rect.left() + depth * INDENT_WIDTH) painter.setPen(text_pen) text = index.data(Qt.ItemDataRole.DisplayRole) or "" - flags = ( - Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter - ) - painter.drawText(rect, int(flags), text) + painter.drawText(self._text_rect(option.rect, index), int(self._FLAGS), text) painter.restore() @staticmethod def _paint_guide(painter, rect: QRect, role: BlockRole | None) -> None: - if role in (None, BlockRole.NONE, BlockRole.PARENT_EMPTY): + """ + Draw the block guide line of a child row: a vertical line from the top edge of the row + (i.e. the bottom edge of the row above, ending there so it never crosses the parent's + text) down to the next child, plus a short tick towards the indented text. + """ + if role not in (BlockRole.CHILD, BlockRole.LAST_CHILD): return pen = QPen(get_accent_colors().highlight) pen.setWidth(2) painter.setPen(pen) x = rect.left() + 10 mid = rect.center().y() - if role == BlockRole.PARENT: - painter.drawLine(x, mid + 4, x, rect.bottom()) - else: - bottom = mid if role == BlockRole.LAST_CHILD else rect.bottom() - painter.drawLine(x, rect.top(), x, bottom) - painter.drawLine(x, mid, x + INDENT_WIDTH - 8, mid) + bottom = mid if role == BlockRole.LAST_CHILD else rect.bottom() + painter.drawLine(x, rect.top(), x, bottom) + painter.drawLine(x, mid, x + INDENT_WIDTH - 8, mid) def sizeHint(self, option, index): # noqa: N802 text = index.data(Qt.ItemDataRole.DisplayRole) or "" - lines = text.count("\n") + 1 - height = option.fontMetrics.lineSpacing() * lines + _ROW_MARGIN - return QSize(super().sizeHint(option, index).width(), max(height, ICON_SIZE + _ROW_MARGIN)) + view = self.parent() + column_width = ( + view.columnWidth(index.column()) + if isinstance(view, QTableView) + else option.rect.width() + ) + cell = QRect(0, 0, max(column_width, 1), 100000) + width = max(self._text_rect(cell, index).width(), 20) + text_height = option.fontMetrics.boundingRect( + QRect(0, 0, width, 100000), int(self._FLAGS), text + ).height() + height = max(text_height + _ROW_MARGIN, ICON_SIZE + _ROW_MARGIN) + return QSize(column_width, height) class _CenteredIconDelegate(QStyledItemDelegate): @@ -359,6 +375,17 @@ class ScheduleTableView(QTableView): for col in ScheduleTableModel.ICON_COLUMNS: self.setItemDelegateForColumn(col, icon_delegate) + # Wrapped text needs more or fewer lines when the stretching columns change width, so + # the row heights are recomputed (once per event-loop pass) after any column resize. + self._row_resize_timer = QTimer(self) + self._row_resize_timer.setSingleShot(True) + self._row_resize_timer.setInterval(0) + self._row_resize_timer.timeout.connect(self._resize_rows) + self.horizontalHeader().sectionResized.connect(self._row_resize_timer.start) + + def _resize_rows(self) -> None: + self.verticalHeader().resizeSections(QHeaderView.ResizeMode.ResizeToContents) + def configure_columns(self) -> None: """Apply the column sizing; call after `setModel()`.""" header = self.horizontalHeader() diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 37104c5..054d209 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -263,6 +263,14 @@ class Scheduler(BECWidget, QWidget): name_row.addStretch() layout.addLayout(name_row) + layout.addWidget(QLabel("Notes")) + self.notes_edit = QPlainTextEdit() + self.notes_edit.setPlaceholderText("Notes about this schedule...") + self.notes_edit.setPlainText(self.schedule.notes) + self.notes_edit.setMaximumHeight(100) + self.notes_edit.textChanged.connect(self._notes_save_timer.start) + layout.addWidget(self.notes_edit) + edit_row = QHBoxLayout() self.add_btn = AccentButton("Add") self.edit_btn = AccentButton("Edit") @@ -303,13 +311,6 @@ class Scheduler(BECWidget, QWidget): self.table_view.pastePressed.connect(self._on_paste_clicked) layout.addWidget(self.table_view, 1) - layout.addWidget(QLabel("Notes")) - self.notes_edit = QPlainTextEdit() - self.notes_edit.setPlaceholderText("Notes about this schedule...") - self.notes_edit.setPlainText(self.schedule.notes) - self.notes_edit.setMaximumHeight(100) - self.notes_edit.textChanged.connect(self._notes_save_timer.start) - layout.addWidget(self.notes_edit) return group def _build_states_group(self) -> QGroupBox: @@ -353,7 +354,11 @@ class Scheduler(BECWidget, QWidget): def _build_settings_group(self) -> QGroupBox: group = QGroupBox("Settings") - row = QHBoxLayout(group) + layout = QVBoxLayout(group) + notifications_row = QHBoxLayout() + file_row = QHBoxLayout() + layout.addLayout(notifications_row) + layout.addLayout(file_row) self.notifications_btn = AccentButton("Notifications") self.notifications_btn.clicked.connect(self._on_notifications_clicked) self.notification_status_label = QLabel() @@ -361,11 +366,12 @@ class Scheduler(BECWidget, QWidget): self.save_file_btn.clicked.connect(self._on_save_to_file_clicked) self.load_file_btn = AccentButton("Load from file") self.load_file_btn.clicked.connect(self._on_load_from_file_clicked) - row.addWidget(self.notifications_btn) - row.addWidget(self.notification_status_label) - row.addStretch() - row.addWidget(self.save_file_btn) - row.addWidget(self.load_file_btn) + notifications_row.addWidget(self.notifications_btn) + notifications_row.addWidget(self.notification_status_label) + notifications_row.addStretch() + file_row.addWidget(self.save_file_btn) + file_row.addWidget(self.load_file_btn) + file_row.addStretch() return group @SafeSlot(str) diff --git a/tests/tests_bec_widgets/test_scheduler_logic.py b/tests/tests_bec_widgets/test_scheduler_logic.py index e53d534..7267177 100644 --- a/tests/tests_bec_widgets/test_scheduler_logic.py +++ b/tests/tests_bec_widgets/test_scheduler_logic.py @@ -309,3 +309,12 @@ def test_schedule_from_document_never_raises(): assert schedule is None and problem schedule, problem = schedule_from_document({"schedule_name": "s", "items": []}) assert problem is None and schedule.schedule_name == "s" + + +def test_run_temperature_controller_passes_plain_values(): + dev = {"univ_temp_cont": mock.MagicMock()} + params = SAMPLE_PARAMS["temperature_controller"] + run_action(ExecutionContext(scans=None, dev=dev), "temperature_controller", params) + dev["univ_temp_cont"].load_config.assert_called_once_with( + power_mode="On", target_setpoint=120, ramp_rate=10, ramp_rate_unit="K/min" + )