diff --git a/pxiii_bec/bec_widgets/ComissioningGUIDraft.ui b/pxiii_bec/bec_widgets/ComissioningGUIDraft.ui new file mode 100644 index 0000000..be17da6 --- /dev/null +++ b/pxiii_bec/bec_widgets/ComissioningGUIDraft.ui @@ -0,0 +1,135 @@ + + + Form + + + + 0 + 0 + 1801 + 1459 + + + + + 1801 + 1459 + + + + Form + + + + + + 0 + + + + Control Panel + + + + + + + + + + + + + + + + + + + Logbook + + + + + + + 24 + + + + Coming soon... + + + + + + + + Take a break + + + + + + + + + Qt::Orientation::Horizontal + + + + 1073 + 20 + + + + + + + + Qt::Orientation::Vertical + + + + 20 + 40 + + + + + + + + + + + + + ScanControl + QWidget +
scan_control
+
+ + Waveform + QWidget +
waveform
+
+ + BECQueue + QWidget +
bec_queue
+
+ + Minesweeper + QWidget +
minesweeper
+
+ + ScanHistory + QWidget +
scan_history
+
+
+ + +
diff --git a/pxiii_bec/bec_widgets/widgets/client.py b/pxiii_bec/bec_widgets/widgets/client.py new file mode 100644 index 0000000..abc25f8 --- /dev/null +++ b/pxiii_bec/bec_widgets/widgets/client.py @@ -0,0 +1,40 @@ +# This file was automatically generated by generate_cli.py +# type: ignore + +from __future__ import annotations + +from bec_lib.logger import bec_logger + +from bec_widgets.cli.rpc.rpc_base import RPCBase, rpc_call + +logger = bec_logger.logger + +# pylint: skip-file + + +_Widgets = { + "ScanHistory": "ScanHistory", +} + + +class ScanHistory(RPCBase): + @rpc_call + def select_scan_from_history(self, value: "int") -> "None": + """ + Set scan from CLI. + + Args: + value (int) : value from history -1 ...-10000 + """ + + @rpc_call + def add_scan_from_history(self) -> "None": + """ + Load selected scan from history. + """ + + @rpc_call + def clear_plot(self) -> "None": + """ + Delete all curves on the plot. + """ diff --git a/pxiii_bec/bec_widgets/widgets/scan_history/__init__.py b/pxiii_bec/bec_widgets/widgets/scan_history/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pxiii_bec/bec_widgets/widgets/scan_history/register_scan_history.py b/pxiii_bec/bec_widgets/widgets/scan_history/register_scan_history.py new file mode 100644 index 0000000..8de6b85 --- /dev/null +++ b/pxiii_bec/bec_widgets/widgets/scan_history/register_scan_history.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 pxiii_bec.bec_widgets.widgets.scan_history.scan_history_plugin import ScanHistoryPlugin + + QPyDesignerCustomWidgetCollection.addCustomWidget(ScanHistoryPlugin()) + + +if __name__ == "__main__": # pragma: no cover + main() diff --git a/pxiii_bec/bec_widgets/widgets/scan_history/scan_history.py b/pxiii_bec/bec_widgets/widgets/scan_history/scan_history.py new file mode 100644 index 0000000..33072f8 --- /dev/null +++ b/pxiii_bec/bec_widgets/widgets/scan_history/scan_history.py @@ -0,0 +1,191 @@ +from __future__ import annotations + +import os +from typing import TYPE_CHECKING, TypedDict + +from bec_lib.logger import bec_logger +from bec_qthemes import material_icon +from bec_widgets.utils.bec_widget import BECWidget + + +from bec_widgets.utils.error_popups import SafeSlot +from bec_widgets.utils.ui_loader import UILoader +from qtpy.QtWidgets import QVBoxLayout, QWidget + +logger = bec_logger.logger + +if TYPE_CHECKING: + from qtpy.QtWidgets import QPushButton, QLabel, QSpinBox + from bec_widgets.widgets.plots.waveform.waveform import Waveform + from bec_widgets.widgets.control.device_input.device_combobox.device_combobox import DeviceComboBox + from bec_widgets.widgets.editors.text_box.text_box import TextBox + + +class ScanHistoryUIComponents(TypedDict): + waveform: Waveform + metadata_text_box: TextBox + monitor_label: QLabel + monitor_combobox: DeviceComboBox + history_label: QLabel + history_spin_box: QSpinBox + history_add: QPushButton + history_clear: QPushButton + + +class ScanHistory(BECWidget, QWidget): + USER_ACCESS = ["select_scan_from_history", "add_scan_from_history", "clear_plot"] + PLUGIN = True + ui_file = "./scan_history.ui" + components: ScanHistoryUIComponents + + def __init__(self, parent=None, **kwargs): + super().__init__(parent=parent, **kwargs) + self._load_ui() + + def _load_ui(self): + current_path = os.path.dirname(__file__) + self.ui = UILoader(self).loader(os.path.join(current_path, self.ui_file)) + layout = QVBoxLayout() + layout.addWidget(self.ui) + self.setLayout(layout) + + self.components: ScanHistoryUIComponents = { + "waveform" : self.ui.waveform, + "metadata_text_box" : self.ui.metadata_text_box, + "monitor_label" : self.ui.monitor_label, + "monitor_combobox" : self.ui.monitor_combobox, + "history_label" : self.ui.history_label, + "history_spin_box" : self.ui.history_spin_box, + "history_add" : self.ui.history_add, + "history_clear" : self.ui.history_clear, + } + + icon_options = {"size": (16, 16), "convert_to_pixmap": False} + + self.components['monitor_combobox'].apply_filter = False + self.components['monitor_combobox'].devices = ['dccm_diode_bottom', 'dccm_diode_top'] + + self.components['history_spin_box'].setMinimum(-10000) + self.components['history_spin_box'].setMaximum(-1) + self.components['history_spin_box'].valueChanged.connect(self._scan_history_selected) + self._scan_history_selected(-1) + self.components['history_spin_box'].setValue(-1) + self.components['history_add'].setText("Load") + self.components['history_add'].setStyleSheet( + "background-color: #129490; color: white; font-weight: bold; font-size: 12px;" + ) + + self.components['history_clear'].setText("Clear") + self.components['history_clear'].setStyleSheet( + "background-color: #065143; color: white; font-weight: bold; font-size: 12px;" + ) + + self.components['history_add'].clicked.connect(self._refresh_plot) + self.components['history_clear'].clicked.connect(self.clear_plot) + self.setWindowTitle("Scan History") + self._scan_history_selected(-1) + + @SafeSlot() + def add_scan_from_history(self) -> None: + """Load selected scan from history.""" + self.components['history_add'].click() + + @SafeSlot() + def clear_plot(self) -> None: + """Delete all curves on the plot.""" + self.components['waveform'].clear_all() + + @SafeSlot() + def _refresh_plot(self) -> None: + """Refresh plot.""" + spin_box_value = self.components['history_spin_box'].value() + self._check_scan_in_history(spin_box_value) + + # Get the data from the client + data = self.client.history[spin_box_value] + + # Check that the plot does not already have a curve with the same data + scan_number = int(data.metadata.bec['scan_number']) + monitor_name = self.components['monitor_combobox'].currentText() + # Get signal hints + signal_name = getattr(self.client.device_manager.devices, monitor_name)._hints + signal_name = signal_name[0] if len(signal_name)>0 else signal_name + + curve_label = f"Scan-{scan_number}-{monitor_name}-{signal_name}" + if len([curve for curve in self.components['waveform'].curves if curve.config.label == curve_label]): + return + if not hasattr(data.devices, monitor_name): + raise ValueError(f"Device {monitor_name} not found in data.") + + # Get scan motors and check that the plot x_axis motor is the same as the scan motor, if not, clear the plot + scan_motors = [motor.decode() for motor in data.metadata.bec['scan_motors']] + x_motor_name = self.components['waveform'].x_mode + if x_motor_name not in scan_motors: + self.clear_plot() + self.components['waveform'].x_mode = x_motor_name = scan_motors[0] + + # fetching the data + monitor_data = getattr(data.devices, monitor_name).read()[signal_name]['value'] + motor_data = getattr(data.devices, x_motor_name).read()[x_motor_name]['value'] + + # Plot custom curve, with custom label + self.components['waveform'].plot(x=motor_data, y=monitor_data, label=curve_label) + x_label = f"{x_motor_name} / [{getattr(self.client.device_manager.devices, x_motor_name).egu()}]" + self.components['waveform'].x_label = x_label + + def _check_scan_in_history(self, history_value:int) -> None: + """ + Check if scan is in history. + + Args: + history_value (int): Value from history -1...-10000 + """ + if len(self.client.history) < abs(history_value): + self.components['metadata_text_box'].set_plain_text(f"Scan history does not have the request scan {history_value} of history with length: {len(self.client.history)}") + return + + + def select_scan_from_history(self, value:int) -> None: + """ + Set scan from CLI. + + Args: + value (int) : value from history -1 ...-10000 + """ + if value >=0: + raise ValueError(f"Value must be smaller or equal -1, provided {value}") + self.components['history_spin_box'].setValue(value) + + @SafeSlot(int) + def _scan_history_selected(self, spin_box_value:int) -> None: + self._check_scan_in_history(spin_box_value) + data = self.client.history[spin_box_value] + data.metadata.bec['scan_motors'][0].decode() + + text = str(data) + scan_motor_text = "\n" + "Scan Motors: " + for motor in data.metadata.bec['scan_motors']: + scan_motor_text += f" {motor.decode()}" + + self.components['metadata_text_box'].set_plain_text(text + scan_motor_text) + + @SafeSlot(str) + def _set_x_axis(self, device_x:str) -> None: + self.components['waveform'].x_mode = device_x + + @SafeSlot(str) + def _plot_new_device(self, device:str) -> None: + # if len(curve for curve in self.components["waveform"].curves if curve.config.label == f"{device}-{device}": + self.components["waveform"].plot(device) + + +if __name__ == "__main__": # pragma: no cover + import sys + + from qtpy.QtWidgets import QApplication + + app = QApplication(sys.argv) + widget = ScanHistory() + + widget.show() + sys.exit(app.exec_()) diff --git a/pxiii_bec/bec_widgets/widgets/scan_history/scan_history.pyproject b/pxiii_bec/bec_widgets/widgets/scan_history/scan_history.pyproject new file mode 100644 index 0000000..591325d --- /dev/null +++ b/pxiii_bec/bec_widgets/widgets/scan_history/scan_history.pyproject @@ -0,0 +1 @@ +{'files': ['scan_history.py']} \ No newline at end of file diff --git a/pxiii_bec/bec_widgets/widgets/scan_history/scan_history.ui b/pxiii_bec/bec_widgets/widgets/scan_history/scan_history.ui new file mode 100644 index 0000000..a1ba889 --- /dev/null +++ b/pxiii_bec/bec_widgets/widgets/scan_history/scan_history.ui @@ -0,0 +1,115 @@ + + + Form + + + + 0 + 0 + 955 + 796 + + + + Form + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + + + + + + + + + + + BPM Monitor + + + + + + + + + + Scan History + + + + + + + + + + Add scan + + + + + + + clear all + + + + + + + + + + 0 + 0 + + + + + 795 + 191 + + + + + + + + + + + TextBox + QWidget +
text_box
+
+ + DeviceComboBox + QComboBox +
device_combobox
+
+ + Waveform + QWidget +
waveform
+
+
+ + +
diff --git a/pxiii_bec/bec_widgets/widgets/scan_history/scan_history_plugin.py b/pxiii_bec/bec_widgets/widgets/scan_history/scan_history_plugin.py new file mode 100644 index 0000000..51a986f --- /dev/null +++ b/pxiii_bec/bec_widgets/widgets/scan_history/scan_history_plugin.py @@ -0,0 +1,54 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +from qtpy.QtDesigner import QDesignerCustomWidgetInterface + +from bec_widgets.utils.bec_designer import designer_material_icon +from pxiii_bec.bec_widgets.widgets.scan_history.scan_history import ScanHistory + +DOM_XML = """ + + + + +""" + + +class ScanHistoryPlugin(QDesignerCustomWidgetInterface): # pragma: no cover + def __init__(self): + super().__init__() + self._form_editor = None + + def createWidget(self, parent): + t = ScanHistory(parent) + return t + + def domXml(self): + return DOM_XML + + def group(self): + return "" + + def icon(self): + return designer_material_icon(ScanHistory.ICON_NAME) + + def includeFile(self): + return "scan_history" + + 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 "ScanHistory" + + def toolTip(self): + return "ScanHistory" + + def whatsThis(self): + return self.toolTip() diff --git a/pxiii_bec/scripts/alignment_fit.py b/pxiii_bec/scripts/alignment_fit.py new file mode 100644 index 0000000..5cd0418 --- /dev/null +++ b/pxiii_bec/scripts/alignment_fit.py @@ -0,0 +1,49 @@ +import numpy as np +from scipy.ndimage import gaussian_filter1d +from lmfit.models import GaussianModel + + +def alignment_fit_and_plot( + history_index: int, + device_name: str, + signal_name: str | None = None, + smoothing_sigma: float = 2.0, +): + """ + Get data for a completed scan from the BEC history, apply smoothing, gaussian fit, + gradient, and plot all the results. + + Args: + history_index (int): scan to fetch, e.g. -1 for the most recent scan + device_name (str): the device for which to get the monitoring data + + """ + # Fetch scan data from the history + # by default, signal = device name, unless otherwise specified + signal = signal_name or device_name + scan = bec.history[history_index] + md = scan.metadata["bec"] + data = scan.devices[device_name][signal].read()["value"] + # motor name is a bytes object in the metadata, so make a string + motor_name = md["scan_motors"][0].decode() + + # Create a plot and a text box to display results + dock_area = bec.gui.new() + wf = dock_area.new().new(bec.gui.available_widgets.Waveform) + wf.title = f"Scan {md['scan_number']}: {md['scan_name']} of {motor_name}" + text = dock_area.new(position="right").new(widget=bec.gui.available_widgets.TextBox) + + # Calculate some processed data and add everything to the plot + wf.plot(data, label="Raw data") + smoothed_data = gaussian_filter1d(data, smoothing_sigma) + wf.plot(smoothed_data, label="Smoothed") + gradient = np.gradient(smoothed_data) + wf.plot(gradient, label="gradient") + + # Fit a Gaussian model to the smoothed data and show the fitting parameters in the textbox + x_data = scan.devices[motor_name][motor_name].read()["value"] + model = GaussianModel() + result = model.fit(smoothed_data, x=x_data) + text.set_plain_text(f"Fit parameters: \n{result.params.pretty_repr()}") + + return result diff --git a/pxiii_bec/scripts/kat.py b/pxiii_bec/scripts/kat.py new file mode 100644 index 0000000..423a483 --- /dev/null +++ b/pxiii_bec/scripts/kat.py @@ -0,0 +1,30 @@ +def scan_theta2(scan_start, scan_end, stepno, exp): + # Save the motor starting position + start_value = dev.dccm_theta2.read()['dccm_theta2']['value'] + print(f"Motor position is {start_value}") + + # Run the scan + s = scans.line_scan(dev.dccm_theta2, scan_start, scan_end, steps=stepno, exp_time=exp, relative=True) + + # data = s.devices[dccm_xbpm][dccm_xbpm].read()["value"] + + # Move motor back to starting position and print XBPM reading + umv(dev.dccm_theta2, start_value) + xbpm_reading = dev.dccm_xbpm.read()['dccm_xbpm']['value'] + print(f"Moving dccm_theta2 back to start position of where XBPM Reading is {xbpm_reading}") + end_value = dev.dccm_theta2.read()['dccm_theta2']['value'] + print(f"Motor was at {start_value} before the scan, now at {end_value}") + + # # Create a plot to display the results + dock_area = bec.gui.new() + wf = dock_area.new().new(bec.gui.available_widgets.Waveform) + wf.title = f"Scan of DCCM_theta2" + wf.plot(x_name='dccm_theta2', y_name='dccm_xbpm') + wf.add_dap_curve(device_label='dccm_xbpm-dccm_xbpm', dap_name='GaussianModel') + print(dap_xbpm.dap_params) + + + + + +