From 6523e1e77970aff69e3a7e7d4ebdef29ad6ac6f5 Mon Sep 17 00:00:00 2001 From: heli2src Date: Tue, 10 Nov 2026 18:48:11 +0100 Subject: [PATCH 01/12] reorganise stdf_browser --- pylab_ml/__init__.py | 11 +- pylab_ml/plugins/__init__.py | 0 pylab_ml/plugins/stdf_browser/MANIFEST.in | 2 - .../{stdf_browser => }/__init__.py | 0 .../stdf_browser/{stdf_browser => }/api.py | 0 .../stdf_browser/{stdf_browser => }/plugin.py | 100 ++++++++++++------ .../plugins/stdf_browser/requirements/run.txt | 5 - pylab_ml/plugins/stdf_browser/setup.py | 27 ----- .../stdf_browser/stdf_browser/README.md | 4 - .../{stdf_browser => }/widgets/main_widget.py | 26 ++--- .../{stdf_browser => }/widgets/showstdf.py | 3 - .../{stdf_browser => }/widgets/showstdf.ui | 0 pyproject.toml | 8 +- 13 files changed, 93 insertions(+), 93 deletions(-) create mode 100644 pylab_ml/plugins/__init__.py delete mode 100644 pylab_ml/plugins/stdf_browser/MANIFEST.in rename pylab_ml/plugins/stdf_browser/{stdf_browser => }/__init__.py (100%) rename pylab_ml/plugins/stdf_browser/{stdf_browser => }/api.py (100%) rename pylab_ml/plugins/stdf_browser/{stdf_browser => }/plugin.py (52%) delete mode 100644 pylab_ml/plugins/stdf_browser/requirements/run.txt delete mode 100644 pylab_ml/plugins/stdf_browser/setup.py delete mode 100644 pylab_ml/plugins/stdf_browser/stdf_browser/README.md rename pylab_ml/plugins/stdf_browser/{stdf_browser => }/widgets/main_widget.py (90%) rename pylab_ml/plugins/stdf_browser/{stdf_browser => }/widgets/showstdf.py (99%) rename pylab_ml/plugins/stdf_browser/{stdf_browser => }/widgets/showstdf.ui (100%) diff --git a/pylab_ml/__init__.py b/pylab_ml/__init__.py index e8eb89d9..034103e4 100644 --- a/pylab_ml/__init__.py +++ b/pylab_ml/__init__.py @@ -3,12 +3,13 @@ """ __version__ = '0.0.0' -__all__ = [ +__all__ = [ # files: "attributes", - "base_instrument", + "base_instrument", "collate_instrument", "dummy", "ident", + # directories: "baseclass", "common", "dmm", @@ -17,8 +18,10 @@ "matrix", "misc", "plugins", - "pollux", + "position_controller", "scope", + "scripts", "smu", - "thermostreamer" + "thermostreamer", + "widgets" ] diff --git a/pylab_ml/plugins/__init__.py b/pylab_ml/plugins/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/pylab_ml/plugins/stdf_browser/MANIFEST.in b/pylab_ml/plugins/stdf_browser/MANIFEST.in deleted file mode 100644 index afef7153..00000000 --- a/pylab_ml/plugins/stdf_browser/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -include requirements/run.txt -include stdf_browser/README.md diff --git a/pylab_ml/plugins/stdf_browser/stdf_browser/__init__.py b/pylab_ml/plugins/stdf_browser/__init__.py similarity index 100% rename from pylab_ml/plugins/stdf_browser/stdf_browser/__init__.py rename to pylab_ml/plugins/stdf_browser/__init__.py diff --git a/pylab_ml/plugins/stdf_browser/stdf_browser/api.py b/pylab_ml/plugins/stdf_browser/api.py similarity index 100% rename from pylab_ml/plugins/stdf_browser/stdf_browser/api.py rename to pylab_ml/plugins/stdf_browser/api.py diff --git a/pylab_ml/plugins/stdf_browser/stdf_browser/plugin.py b/pylab_ml/plugins/stdf_browser/plugin.py similarity index 52% rename from pylab_ml/plugins/stdf_browser/stdf_browser/plugin.py rename to pylab_ml/plugins/stdf_browser/plugin.py index 83257f45..1737d557 100644 --- a/pylab_ml/plugins/stdf_browser/stdf_browser/plugin.py +++ b/pylab_ml/plugins/stdf_browser/plugin.py @@ -1,50 +1,63 @@ # -*- coding: utf-8 -*- # -# Copyright © Spyder Project Contributors -# Licensed under the terms of the MIT License -# (see spyder/__init__.py for details) +# Copyright © Semi-ATE Contributors +# Licensed under the terms of the GNU GENERAL PUBLIC LICENSE V2 +# (see pylab_ml/LICENSE for details) """ STDF browser Plugin. """ +import os +import logging -# Local imports +# Spyder imports from spyder.api.plugins import Plugins, SpyderDockablePlugin -from spyder.api.plugin_registration.decorators import on_plugin_available -from spyder.api.shellconnect.mixins import ShellConnectMixin +from spyder.api.plugin_registration.decorators import on_plugin_available # on_plugin_teardown from spyder.api.translations import get_translation -from stdf_browser.widgets.main_widget import StdfWidget + +# Semi-ATE imports from ate_spyder.plugin import ATE +from ate_spyder_lab_control.plugin_control import LabControlPlugin + +# Local imports +from pylab_ml.plugins.stdf_browser.widgets.main_widget import StdfWidget # Localization _ = get_translation("spyder") +#Logging +logger = logging.getLogger(__name__) + class StdfBrowser(SpyderDockablePlugin): # ShellConnectMixin """Stdf-Browser plugin.""" NAME = "Stdf" - WIDGET_CLASS = StdfWidget - CONF_SECTION = NAME - REQUIRES = [ATE.NAME] #_setup_stdf_widget - OPTIONAL = [Plugins.Toolbar, "ate"] - CONF_FILE = False + REQUIRES = [ATE.NAME, Plugins.Toolbar, LabControlPlugin.NAME] #_setup_stdf_widget + OPTIONAL = [] TABIFY = [Plugins.VariableExplorer, Plugins.Help] + WIDGET_CLASS = StdfWidget + CONF_SECTION = NAME + # DISABLE_ACTIONS_WHEN_HIDDEN = False # ---- SpyderDockablePlugin API # ------------------------------------------------------------------------ @staticmethod - def get_name(): + def get_name() -> str: return _("Stdf") - def get_description(self): + @staticmethod + def get_description() -> str: return _("Display and explore STDF-Data.") - def get_icon(self): - return self.create_icon("hist") + @classmethod + def get_icon(cls): + return cls.create_icon("hist") def on_initialize(self): + logger.debug("StdfBrowser:on_initialize") + print(" StdfBrowser:on_initialize") # widget: StdfWidget = self.get_widget() # print("stdf-browser.on_initialize()") pass @@ -61,41 +74,60 @@ def on_initialize(self): @on_plugin_available(plugin=ATE.NAME) def on_ate_available(self): """ Connect to ATE plugin when it becomes available and set up the STDF widget with the project information from ATE. """ - widget: StdfWidget = self.get_widget() + print(" StdfBrowser:on_ate_available() start") ate: ATE = self.get_plugin(ATE.NAME) ate.sig_ate_project_loaded.connect(self._setup_stdf_widget) ate.sig_ate_progname.connect(self.runflow_changed) + ate.sig_stop_debugging.connect(self.runflow_stop) + print(" StdfBrowser:on_ate_available() done") + + @on_plugin_available(plugin=LabControlPlugin.NAME) + def on_labcontrol_available(self): + print(" StdfBrowser:on_labcontrol_available() do nothing") def _setup_stdf_widget(self): """ Set up the STDF widget with the project information from ATE when a new project is loaded. """ + print(" StdfBrowser:_setup_stdf_widget start") widget: StdfWidget = self.get_widget() ate: ATE = self.get_plugin(ATE.NAME) project_info = ate.get_project_navigation() - #widget.setup_widget(project_info) - - # @on_plugin_available(plugin=Plugins.Toolbar) - # def on_toolbar_available(self): - # toolbar = self.get_plugin(Plugins.Toolbar) - # # print(toolbar.get_application_toolbar("ate_toolbar")) # get an exception, "ate_toolbar" not found! Available toolbars are: ['file_toolbar', 'run_toolbar', 'debug_toolbar', 'main_toolbar'] - # for bar in toolbar.toolbarslist: - # ateToolbar = bar if bar.ID == "ate_toolbar" else None - # if ateToolbar is not None and hasattr(ateToolbar, 'external_signal'): - # print("stdf-broser.on_toolbar_available: Connect to Plugins.Toolbar") - # ateToolbar.external_signal.connect(self.externalcallback) - # else: - # print(f"stdf-broser.on_toolbar_available: Couldn't connect to Plugins.Toolbar = {ateToolbar}") - # self.ateToolbar = ateToolbar + widget.widget.path = os.path.join(project_info.project_directory, "output") + + ateToolbar = self.find_ate_toolbar() + self.ateToolbar = ateToolbar if ateToolbar is not None else None + print(" StdfBrowser:_setup_stdf_widget done") def runflow_changed(self, progname: str): """ Update the STDF widget with the new program name when the runflow changes in ATE. """ widget: StdfWidget = self.get_widget() - print('StdfBrowser.runflow_changed()') + print(f' StdfBrowser.runflow_changed({progname})') + print(f' {widget.widget.path}') #path = f"{self.ateToolbar.project_info.project_directory}/src/{self.ateToolbar.project_info.active_hardware}/{self.ateToolbar.project_info.active_base}" #print(f'stdf-broser.externalcallback {path} {filename}') - #widget.set_filename(path, filename) + widget.set_filename(widget.widget.path, progname) + + def runflow_stop(self): + print(' StdfBrowser.runflow_stop() but do nothing') def externalcallback(self, filename): """ Update the STDF widget with the new filename when the external signal is emitted from the ATE toolbar. """ + print(f' StdfBrowser.externalcallback {filename}') path = f"{self.ateToolbar.project_info.project_directory}/src/{self.ateToolbar.project_info.active_hardware}/{self.ateToolbar.project_info.active_base}" - print(f'stdf-broser.externalcallback {path} {filename}') + #self.get_widget().set_filename(path, filename) + + def find_ate_toolbar(self): + toolbar = self.get_plugin(Plugins.Toolbar) + ateToolbar = None + for bar in toolbar.toolbarslist: + print(f" {bar.ID}") + if bar.ID == "ATE Plugin toolbar": + ateToolbar = bar + break + if ateToolbar is not None and hasattr(ateToolbar, 'external_signal'): + print(" StdfBrowser.on_toolbar_available: Connect to Plugins.Toolbar") + ateToolbar.external_signal.connect(self.externalcallback) + else: + print(f" StdfBrowser.on_toolbar_available: Couldn't connect to Plugins.Toolbar = {ateToolbar}") + return ateToolbar + diff --git a/pylab_ml/plugins/stdf_browser/requirements/run.txt b/pylab_ml/plugins/stdf_browser/requirements/run.txt deleted file mode 100644 index 8d297e25..00000000 --- a/pylab_ml/plugins/stdf_browser/requirements/run.txt +++ /dev/null @@ -1,5 +0,0 @@ -pandas -numpy -matplotlib -Semi-ATE-Metis -LabMl-adjutancy \ No newline at end of file diff --git a/pylab_ml/plugins/stdf_browser/setup.py b/pylab_ml/plugins/stdf_browser/setup.py deleted file mode 100644 index eeb4f731..00000000 --- a/pylab_ml/plugins/stdf_browser/setup.py +++ /dev/null @@ -1,27 +0,0 @@ -from setuptools import find_packages, setup -from pathlib import Path -from stdf_browser import __version__ - -version = __version__ -requirements_path = Path(Path(__file__).parents[0], "requirements/run.txt") - -with requirements_path.open("r") as f: - install_requires = list(f) -readme_path = Path(Path(__file__).parent, "./stdf_browser/README.md") -with readme_path.open("r") as f: - long_description = f.read() -setup( - name="stdf-browser", - version=version, - requires=["spyder"], - description="Spyder STDF plugin for display and explore STDF data", - long_description=long_description, - long_description_content_type="text/markdown", - author="The Semi-ATE Project Contributors", - author_email="ate.organization@gmail.com", - license="GPL-2.0-only", - packages=find_packages(), - install_requires=install_requires, - include_package_data=True, - entry_points={"spyder.plugins": ["Stdf = stdf_browser.plugin:StdfBrowser"]} -) diff --git a/pylab_ml/plugins/stdf_browser/stdf_browser/README.md b/pylab_ml/plugins/stdf_browser/stdf_browser/README.md deleted file mode 100644 index 22d3ba34..00000000 --- a/pylab_ml/plugins/stdf_browser/stdf_browser/README.md +++ /dev/null @@ -1,4 +0,0 @@ -## The Stdf-Browser package - -This package provides a simple STDF-Browser. - diff --git a/pylab_ml/plugins/stdf_browser/stdf_browser/widgets/main_widget.py b/pylab_ml/plugins/stdf_browser/widgets/main_widget.py similarity index 90% rename from pylab_ml/plugins/stdf_browser/stdf_browser/widgets/main_widget.py rename to pylab_ml/plugins/stdf_browser/widgets/main_widget.py index 35717e80..9e66c04d 100644 --- a/pylab_ml/plugins/stdf_browser/stdf_browser/widgets/main_widget.py +++ b/pylab_ml/plugins/stdf_browser/widgets/main_widget.py @@ -6,25 +6,19 @@ """ # Third party imports -from PyQt5 import QtWidgets, QtCore from qtpy.QtWidgets import QHBoxLayout # Local imports -from spyder.api.config.decorators import on_conf_change from spyder.api.translations import get_translation from spyder.api.widgets.main_widget import PluginMainWidgetMenus from spyder.api.widgets.main_widget import PluginMainWidget from spyder.utils.misc import getcwd_or_home -from spyder.utils.palette import QStylePalette -from stdf_browser.widgets.showstdf import Test_Results +from pylab_ml.plugins.stdf_browser.widgets.showstdf import Test_Results # Localization _ = get_translation("spyder") -MAIN_BG_COLOR = QStylePalette.COLOR_BACKGROUND_1 - - # --- Constants # ---------------------------------------------------------------------------- class StdfWidgetActions: @@ -55,6 +49,10 @@ class StdfWidgetToolbarItems: # ---------------------------------------------------------------------------- class StdfWidget(PluginMainWidget): # ShellConnectMainWidget ,PluginMainWidget """ Main widget for the STDF plugin. """ + + SHOW_MESSAGE_WHEN_EMPTY = False + IMAGE_WHEN_EMPTY = "plots" + MESSAGE_WHEN_EMPTY = _("No result to show") def __init__(self, name=None, plugin=None, parent=None): """ Initialize the main widget. @@ -72,7 +70,7 @@ def __init__(self, name=None, plugin=None, parent=None): #QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts) # Widgets - self.widget = Test_Results(parent=self, background_color=MAIN_BG_COLOR) + self.widget = Test_Results(parent=self) # Resize to a huge width to get the right size of the thumbnail # scrollbar at startup. @@ -92,6 +90,7 @@ def get_focus_widget(self): def setup(self): """ Setup the main widget. This is called after the widget is created and before it is shown for the first time. """ + print(" StdfWidget.setup()") layout = QHBoxLayout() layout.addWidget(self.widget) self.setLayout(layout) @@ -113,7 +112,7 @@ def setup(self): tip=_("Import data..."), icon=self.create_icon("fileimport"), triggered=self.import_data, - # register_shortcut=True, # uesed in the plot-plugin from spyder, but in this plugin an exceptin occure :-() + # register_shortcut=True, # used in the plot-plugin from spyder, but in this plugin an exceptin occure :-() ) reload_data_action = self.create_action( @@ -160,6 +159,7 @@ def setup(self): context_menu = self.create_menu(PluginMainWidgetMenus.Context) for item in [import_data_action]: self.add_item_to_menu(item, menu=context_menu) + print(" StdfWidget.setup() done") def update_actions(self): """ Update the enabled/disabled state of actions based on the current context. """ @@ -193,6 +193,7 @@ def update_actions(self): def on_close(self): """ Handle the widget being closed. """ + print(" StdfWidget.on_close") return super().on_close() # ---- Public API: @@ -200,12 +201,12 @@ def on_close(self): def import_data(self): """Import data.""" - print('StdfWidget.import_data') + print(' StdfWidget.import_data') self.widget.open_files() def reload_data(self): """Reload data.""" - print('StdfWidget.reload_data') + print(' StdfWidget.reload_data') if self.widget.filename != "": self.widget.open_files(self.widget.path + "/" + self.widget.filename) else: @@ -213,8 +214,9 @@ def reload_data(self): def set_filename(self, path, filename): """ Set the filename and path for the widget. """ + print(f" StdfWidget.set_filename({path}, {filename})") self.widget.path = path - self.widget.filename = filename.lower() + ".stdf" + self.widget.filename = filename + ".stdf" def graph_show(self): """Show graph.""" diff --git a/pylab_ml/plugins/stdf_browser/stdf_browser/widgets/showstdf.py b/pylab_ml/plugins/stdf_browser/widgets/showstdf.py similarity index 99% rename from pylab_ml/plugins/stdf_browser/stdf_browser/widgets/showstdf.py rename to pylab_ml/plugins/stdf_browser/widgets/showstdf.py index 259d4630..e7dccfdd 100644 --- a/pylab_ml/plugins/stdf_browser/stdf_browser/widgets/showstdf.py +++ b/pylab_ml/plugins/stdf_browser/widgets/showstdf.py @@ -28,9 +28,6 @@ # spyder library imports from spyder.api.widgets.mixins import SpyderWidgetMixin -__author__ = "Hariharan Karthikeyan" -__credits__ = ["Hariharan Karthikeyan"] -__email__ = "Hariharan.Karthikeyan@tdk.com" __version__ = "0.0.5" diff --git a/pylab_ml/plugins/stdf_browser/stdf_browser/widgets/showstdf.ui b/pylab_ml/plugins/stdf_browser/widgets/showstdf.ui similarity index 100% rename from pylab_ml/plugins/stdf_browser/stdf_browser/widgets/showstdf.ui rename to pylab_ml/plugins/stdf_browser/widgets/showstdf.ui diff --git a/pyproject.toml b/pyproject.toml index f78d866c..664d63c0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,9 +24,9 @@ classifiers = [ "Operating System :: Microsoft :: Windows", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", "Development Status :: 2 - Pre-Alpha", "Intended Audience :: Education", "Intended Audience :: Science/Research", @@ -50,6 +50,7 @@ dependencies = [ "nidmm==1.4.2", "niscope==1.4.1", "nitclk==1.4.1", + "numpy", "matplotlib", "paho-mqtt", "pandas", @@ -61,6 +62,8 @@ dependencies = [ "regex", "svgelements", "semi-ate-common", + "Semi-ATE-Metis", + "tables", "pyyaml" ] @@ -86,6 +89,7 @@ test = [ [project.entry-points."spyder.plugins"] lab_gui = "plugin_gui:LabGuiPlugin" + Stdf = "pylab_ml.plugins.stdf_browser.plugin:StdfBrowser" [project.scripts] enter_semiate = "pylab_ml.scripts.enter_semiate:main" From d8f941a2d3f5db0aa461e156e2a55f9305d65b20 Mon Sep 17 00:00:00 2001 From: heli2src Date: Wed, 11 Nov 2026 17:01:46 +0100 Subject: [PATCH 02/12] fix error in plugin --- pylab_ml/plugins/stdf_browser/plugin.py | 63 +++++++------------------ 1 file changed, 17 insertions(+), 46 deletions(-) diff --git a/pylab_ml/plugins/stdf_browser/plugin.py b/pylab_ml/plugins/stdf_browser/plugin.py index 1737d557..7efbacb0 100644 --- a/pylab_ml/plugins/stdf_browser/plugin.py +++ b/pylab_ml/plugins/stdf_browser/plugin.py @@ -29,11 +29,11 @@ logger = logging.getLogger(__name__) -class StdfBrowser(SpyderDockablePlugin): # ShellConnectMixin +class StdfBrowser(SpyderDockablePlugin): """Stdf-Browser plugin.""" NAME = "Stdf" - REQUIRES = [ATE.NAME, Plugins.Toolbar, LabControlPlugin.NAME] #_setup_stdf_widget + REQUIRES = [ATE.NAME, LabControlPlugin.NAME] OPTIONAL = [] TABIFY = [Plugins.VariableExplorer, Plugins.Help] WIDGET_CLASS = StdfWidget @@ -57,16 +57,6 @@ def get_icon(cls): def on_initialize(self): logger.debug("StdfBrowser:on_initialize") - print(" StdfBrowser:on_initialize") - # widget: StdfWidget = self.get_widget() - # print("stdf-browser.on_initialize()") - pass - -# def update_font(self): -# print("stdf-browser.update_font()") -# color_scheme = self.get_color_scheme() -# font = self.get_font() -# self.get_widget().update_font(font, color_scheme) # necessary? # ---- Private API # ------------------------------------------------------------------------ @@ -74,60 +64,41 @@ def on_initialize(self): @on_plugin_available(plugin=ATE.NAME) def on_ate_available(self): """ Connect to ATE plugin when it becomes available and set up the STDF widget with the project information from ATE. """ - print(" StdfBrowser:on_ate_available() start") ate: ATE = self.get_plugin(ATE.NAME) ate.sig_ate_project_loaded.connect(self._setup_stdf_widget) ate.sig_ate_progname.connect(self.runflow_changed) ate.sig_stop_debugging.connect(self.runflow_stop) - print(" StdfBrowser:on_ate_available() done") + self._testing = False @on_plugin_available(plugin=LabControlPlugin.NAME) def on_labcontrol_available(self): - print(" StdfBrowser:on_labcontrol_available() do nothing") + labcontrol: LabControlPlugin = self.get_plugin(LabControlPlugin.NAME) + labcontrol._widget.change_status_display.connect(self.change_controlstatus) def _setup_stdf_widget(self): """ Set up the STDF widget with the project information from ATE when a new project is loaded. """ - print(" StdfBrowser:_setup_stdf_widget start") widget: StdfWidget = self.get_widget() ate: ATE = self.get_plugin(ATE.NAME) project_info = ate.get_project_navigation() widget.widget.path = os.path.join(project_info.project_directory, "output") - - ateToolbar = self.find_ate_toolbar() - self.ateToolbar = ateToolbar if ateToolbar is not None else None - print(" StdfBrowser:_setup_stdf_widget done") def runflow_changed(self, progname: str): """ Update the STDF widget with the new program name when the runflow changes in ATE. """ widget: StdfWidget = self.get_widget() - print(f' StdfBrowser.runflow_changed({progname})') - print(f' {widget.widget.path}') - #path = f"{self.ateToolbar.project_info.project_directory}/src/{self.ateToolbar.project_info.active_hardware}/{self.ateToolbar.project_info.active_base}" - #print(f'stdf-broser.externalcallback {path} {filename}') - widget.set_filename(widget.widget.path, progname) + widget._filename = progname def runflow_stop(self): - print(' StdfBrowser.runflow_stop() but do nothing') + print(' StdfBrowser.runflow_stop()') + + def change_controlstatus(self, msg, extendmsg=""): + if msg == "terminated" or (msg == "idle" and self._testing): + widget: StdfWidget = self.get_widget() + widget.set_filename(widget.widget.path, widget._filename) + # widget.reload_data() + elif msg== "idle": + self._testing = True - def externalcallback(self, filename): - """ Update the STDF widget with the new filename when the external signal is emitted from the ATE toolbar. """ - print(f' StdfBrowser.externalcallback {filename}') - path = f"{self.ateToolbar.project_info.project_directory}/src/{self.ateToolbar.project_info.active_hardware}/{self.ateToolbar.project_info.active_base}" + if msg == "terminated": + self._testing = False - #self.get_widget().set_filename(path, filename) - - def find_ate_toolbar(self): - toolbar = self.get_plugin(Plugins.Toolbar) - ateToolbar = None - for bar in toolbar.toolbarslist: - print(f" {bar.ID}") - if bar.ID == "ATE Plugin toolbar": - ateToolbar = bar - break - if ateToolbar is not None and hasattr(ateToolbar, 'external_signal'): - print(" StdfBrowser.on_toolbar_available: Connect to Plugins.Toolbar") - ateToolbar.external_signal.connect(self.externalcallback) - else: - print(f" StdfBrowser.on_toolbar_available: Couldn't connect to Plugins.Toolbar = {ateToolbar}") - return ateToolbar From 059f22c0d3f5f7deca4662890f64d67f355b5e52 Mon Sep 17 00:00:00 2001 From: heli2src Date: Wed, 11 Nov 2026 17:02:18 +0100 Subject: [PATCH 03/12] fix error with the latest panda version --- pylab_ml/plugins/stdf_browser/widgets/showstdf.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/pylab_ml/plugins/stdf_browser/widgets/showstdf.py b/pylab_ml/plugins/stdf_browser/widgets/showstdf.py index e7dccfdd..017e0c11 100644 --- a/pylab_ml/plugins/stdf_browser/widgets/showstdf.py +++ b/pylab_ml/plugins/stdf_browser/widgets/showstdf.py @@ -179,7 +179,7 @@ def raw_hdf5_data(self): # Making separate dataframe to concatenate the results of various IC's # of a particular test to a single list - ptr2.drop(columns=ptr2.columns[0], axis=1, inplace=True) + ptr2.drop(columns=ptr2.columns[0], inplace=True) # Deleting the duplicate rows in the 'TestNo' column ptr.drop_duplicates(subset=["TestNo"], inplace=True, ignore_index=True) @@ -315,8 +315,7 @@ def raw_hdf5_data(self): "MPR.START_IN", "MPR.INCR_IN", "MPR.RTN_INDX", - ], - axis=1, + ] ) # Creating empty lists which will be used in the below operation @@ -346,7 +345,7 @@ def raw_hdf5_data(self): # Adding 'Result' and 'Test_Failed' columns mpr = mpr.assign(Results=res_split, Test_Failed=test_failed_mpr, Units=units) - mpr = mpr.drop(["Result"], axis=1) + mpr = mpr.drop(["Result"]) # Storing 'Mean', 'Maximum', 'Minimum' and 'Root Mean Square' value # of test results of a test in 'max_result' variable From d377b46b72a11fc128cc8e65353e99704e69aa59 Mon Sep 17 00:00:00 2001 From: heli2src Date: Wed, 11 Nov 2026 17:50:33 +0100 Subject: [PATCH 04/12] fix error with value --- .github/workflows/CICD.yml | 2 +- pylab_ml/plugins/stdf_browser/widgets/showstdf.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/CICD.yml b/.github/workflows/CICD.yml index 6575b7e3..7ffd3320 100644 --- a/.github/workflows/CICD.yml +++ b/.github/workflows/CICD.yml @@ -21,7 +21,7 @@ jobs: strategy: fail-fast: false matrix: - PYTHON_VERSION: ['3.9', '3.10', '3.11'] + PYTHON_VERSION: ['3.11', '3.12', '3.13', '3.14'] steps: - name: Checkout Pull Requests uses: actions/checkout@v6 diff --git a/pylab_ml/plugins/stdf_browser/widgets/showstdf.py b/pylab_ml/plugins/stdf_browser/widgets/showstdf.py index 017e0c11..24d183e9 100644 --- a/pylab_ml/plugins/stdf_browser/widgets/showstdf.py +++ b/pylab_ml/plugins/stdf_browser/widgets/showstdf.py @@ -1212,6 +1212,7 @@ def plot_graph_ptr(self, selected): results = self.tableWidget_ptr.item(selectIndex, TaPtrItems["Results"]).text()[1:-1].split(" ") data = [] for value in results: + value = value[0:value.find(',')] if value.find(',')>0 else value if value != "": data.append(str2float(value)) if ltl != utl: From 723a7a8bf063be11ec4629de317bb3d8c98dbe13 Mon Sep 17 00:00:00 2001 From: heli2src Date: Wed, 11 Nov 2026 19:01:48 +0100 Subject: [PATCH 05/12] fix wrong mpr dekodierung --- pylab_ml/plugins/stdf_browser/plugin.py | 2 +- pylab_ml/plugins/stdf_browser/widgets/showstdf.py | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/pylab_ml/plugins/stdf_browser/plugin.py b/pylab_ml/plugins/stdf_browser/plugin.py index 7efbacb0..2344ebc2 100644 --- a/pylab_ml/plugins/stdf_browser/plugin.py +++ b/pylab_ml/plugins/stdf_browser/plugin.py @@ -94,7 +94,7 @@ def change_controlstatus(self, msg, extendmsg=""): if msg == "terminated" or (msg == "idle" and self._testing): widget: StdfWidget = self.get_widget() widget.set_filename(widget.widget.path, widget._filename) - # widget.reload_data() + widget.reload_data() elif msg== "idle": self._testing = True diff --git a/pylab_ml/plugins/stdf_browser/widgets/showstdf.py b/pylab_ml/plugins/stdf_browser/widgets/showstdf.py index 24d183e9..da4e0b6a 100644 --- a/pylab_ml/plugins/stdf_browser/widgets/showstdf.py +++ b/pylab_ml/plugins/stdf_browser/widgets/showstdf.py @@ -315,7 +315,8 @@ def raw_hdf5_data(self): "MPR.START_IN", "MPR.INCR_IN", "MPR.RTN_INDX", - ] + ], + axis = 1 ) # Creating empty lists which will be used in the below operation @@ -345,7 +346,7 @@ def raw_hdf5_data(self): # Adding 'Result' and 'Test_Failed' columns mpr = mpr.assign(Results=res_split, Test_Failed=test_failed_mpr, Units=units) - mpr = mpr.drop(["Result"]) + mpr = mpr.drop(["Result"], axis=1) # Storing 'Mean', 'Maximum', 'Minimum' and 'Root Mean Square' value # of test results of a test in 'max_result' variable From 994653e1cb41b251f42aa579efca5b79575c29c2 Mon Sep 17 00:00:00 2001 From: heli2src Date: Thu, 12 Nov 2026 13:48:02 +0100 Subject: [PATCH 06/12] fix menu-icons not enabled --- .../stdf_browser/widgets/main_widget.py | 93 ++++++------ .../plugins/stdf_browser/widgets/showstdf.py | 136 +++++++++--------- 2 files changed, 123 insertions(+), 106 deletions(-) diff --git a/pylab_ml/plugins/stdf_browser/widgets/main_widget.py b/pylab_ml/plugins/stdf_browser/widgets/main_widget.py index 9e66c04d..bbd694f8 100644 --- a/pylab_ml/plugins/stdf_browser/widgets/main_widget.py +++ b/pylab_ml/plugins/stdf_browser/widgets/main_widget.py @@ -4,6 +4,7 @@ """ Stdf Main Widget. """ +import os # Third party imports from qtpy.QtWidgets import QHBoxLayout @@ -12,7 +13,6 @@ from spyder.api.translations import get_translation from spyder.api.widgets.main_widget import PluginMainWidgetMenus from spyder.api.widgets.main_widget import PluginMainWidget -from spyder.utils.misc import getcwd_or_home from pylab_ml.plugins.stdf_browser.widgets.showstdf import Test_Results # Localization @@ -49,14 +49,14 @@ class StdfWidgetToolbarItems: # ---------------------------------------------------------------------------- class StdfWidget(PluginMainWidget): # ShellConnectMainWidget ,PluginMainWidget """ Main widget for the STDF plugin. """ - + SHOW_MESSAGE_WHEN_EMPTY = False IMAGE_WHEN_EMPTY = "plots" MESSAGE_WHEN_EMPTY = _("No result to show") def __init__(self, name=None, plugin=None, parent=None): - """ Initialize the main widget. - + """ Initialize the main widget. + Parameters ---------- name: str @@ -67,10 +67,10 @@ def __init__(self, name=None, plugin=None, parent=None): The parent widget. """ super().__init__(name, plugin, parent) - #QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts) # Widgets - self.widget = Test_Results(parent=self) + self.widget = Test_Results(parent=self) + # self.widget.sig_data_changed(self.update_actions) # Resize to a huge width to get the right size of the thumbnail # scrollbar at startup. @@ -84,13 +84,11 @@ def get_title(self): def get_focus_widget(self): """ Return the widget to give focus to when this plugin's dockwidget is raised. """ - widget = self.current_widget() - - return widget + # widget = self.current_widget # existiert nur in ShellConnectMainWidget! + return self.widget def setup(self): """ Setup the main widget. This is called after the widget is created and before it is shown for the first time. """ - print(" StdfWidget.setup()") layout = QHBoxLayout() layout.addWidget(self.widget) self.setLayout(layout) @@ -159,37 +157,44 @@ def setup(self): context_menu = self.create_menu(PluginMainWidgetMenus.Context) for item in [import_data_action]: self.add_item_to_menu(item, menu=context_menu) - print(" StdfWidget.setup() done") def update_actions(self): """ Update the enabled/disabled state of actions based on the current context. """ - value = False -# widget = self.current_widget() - - for __, action in self.get_actions().items(): + has_file = self._has_file() + has_data = self._has_data() + + states = { + StdfWidgetActions.Import: True, + StdfWidgetActions.Reload: has_file, # only if the file known + StdfWidgetActions.Graph: has_data, # only if the file load + StdfWidgetActions.Json: has_data, # only if the file load + } + for name, enabled in states.items(): try: - if action and action not in [self.undock_action, - self.close_action, - self.dock_action, - self.toggle_view_action, - self.lock_unlock_action]: - action.setEnabled(value) - - # IMPORTANT: Since we are defining the main actions in here - # and the context is WidgetWithChildrenShortcut we need to - # assign the same actions to the children widgets in order - # for shortcuts to work - # if figviewer: - # figviewer_actions = figviewer.actions() - # # thumbnails_sb_actions = thumbnails_sb.actions() - - # if action not in figviewer_actions: - # figviewer.addAction(action) - - # if action not in thumbnails_sb_actions: - # thumbnails_sb.addAction(action) - except (RuntimeError, AttributeError): - pass + action = self.get_action(name) + except KeyError: + continue + action.setEnabled(enabled) + # IMPORTANT: Since we are defining the main actions in here + # and the context is WidgetWithChildrenShortcut we need to + # assign the same actions to the children widgets in order + # for shortcuts to work + # if figviewer: + # figviewer_actions = figviewer.actions() + # # thumbnails_sb_actions = thumbnails_sb.actions() + + # if action not in figviewer_actions: + # figviewer.addAction(action) + + # if action not in thumbnails_sb_actions: + # thumbnails_sb.addAction(action) + + + def _has_file(self): + return bool(getattr(self.widget, "filename", "")) + + def _has_data(self): + return len(self.widget.mpr_table)>0 or len(self.widget.ptr_table)>0 def on_close(self): """ Handle the widget being closed. """ @@ -201,22 +206,28 @@ def on_close(self): def import_data(self): """Import data.""" - print(' StdfWidget.import_data') + print('StdfWidget.import_data') + result_h5 = os.path.join(self.widget.path, "result_h5", "no_lot.h5") + if os.path.isfile(result_h5): + os.remove(result_h5) self.widget.open_files() + self.update_actions() def reload_data(self): """Reload data.""" - print(' StdfWidget.reload_data') + print('StdfWidget.reload_data') if self.widget.filename != "": - self.widget.open_files(self.widget.path + "/" + self.widget.filename) + self.widget.open_files(os.path.join(self.widget.path, self.widget.filename)) else: self.import_data() + self.update_actions() def set_filename(self, path, filename): """ Set the filename and path for the widget. """ - print(f" StdfWidget.set_filename({path}, {filename})") + print(f"StdfWidget.set_filename({path}, {filename})") self.widget.path = path self.widget.filename = filename + ".stdf" + self.update_actions() def graph_show(self): """Show graph.""" diff --git a/pylab_ml/plugins/stdf_browser/widgets/showstdf.py b/pylab_ml/plugins/stdf_browser/widgets/showstdf.py index da4e0b6a..21e32dec 100644 --- a/pylab_ml/plugins/stdf_browser/widgets/showstdf.py +++ b/pylab_ml/plugins/stdf_browser/widgets/showstdf.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -""" +""" This script contains the 'showStdf' class which is used to convert the '.stdf' file into '.hdf5' file and then preprocess the data to fill in the 'QTableWidget' in the PyQt window. It also contains the 'Test_Results' class which is used to display the preprocessed data in the PyQt window and also to generate graphs from the data. @@ -14,7 +14,7 @@ # Third library imports from qtpy import PYQT5 -from qtpy.QtCore import Qt, QCoreApplication +from qtpy.QtCore import Signal, Qt, QCoreApplication from qtpy.QtWidgets import (QApplication, QWidget, QFileDialog, QMenu, QTableWidgetItem) from qtpy.uic import loadUi @@ -28,7 +28,7 @@ # spyder library imports from spyder.api.widgets.mixins import SpyderWidgetMixin -__version__ = "0.0.5" +__version__ = "0.0.6" TaPtrItems = { @@ -54,16 +54,16 @@ def str2float(string): - """ + """ This function is used to convert the string value of 'LTL' and 'UTL' columns to float values for comparison with the test results. - + eg. str2float("1.234 kV") will return 1234.0 - + Parameters ---------- string : str The string value of 'LTL' or 'UTL' column, which contains the value along with the SI unit and the unit of measurement. - + Returns ------- float @@ -74,12 +74,12 @@ def str2float(string): class showStdf: - """ + """ This class is used to convert the '.stdf' file into '.hdf5' file and then preprocess the data to fill in the 'QTableWidget' in the PyQt window. It also contains methods to display the preprocessed data in the PyQt window and to generate graphs from the data. """ - + RESULTDIR = "result_h5" # Dictionary for the Suffix in the [LSL, LTL, UTL, USL] columns @@ -106,10 +106,10 @@ class showStdf: } def __init__(self, path, filename, lot, resultdir, update_Progress_bar=None): - """ - Initializes the showStdf class with the given parameters and checks if the corresponding '.hdf5' file already exists. + """ + Initializes the showStdf class with the given parameters and checks if the corresponding '.hdf5' file already exists. If it exists and is older than the '.stdf' file, it removes the '.hdf5' file to ensure that the data is updated when the '.stdf' file is processed again. - + Parameters ---------- path : str @@ -128,20 +128,22 @@ def __init__(self, path, filename, lot, resultdir, update_Progress_bar=None): self.path = path self.resultdir = resultdir self.update_Progress_bar = update_Progress_bar + self.ptr_table = [] + self.mpr_table = [] if Path(self.hdf5_file).is_file() and os.path.getmtime(path + "/" + filename) > os.path.getmtime(self.hdf5_file): os.remove(self.hdf5_file) def init(self): """ - This method checks if the corresponding '.hdf5' file already exists. + This method checks if the corresponding '.hdf5' file already exists. If it does not exist, it converts the '.stdf' file into '.hdf5' file using the 'stdf2ph5' module and stores it in the specified directory. - + Returns ------- bool True if the '.hdf5' file exists or was successfully created, False otherwise. - """ + """ if not Path(self.hdf5_file).is_file(): stdf = stdf2ph5.SHP(False, update_progress=self.update_Progress_bar) if not STDFHelper.is_plain_stdf(f"{self.path}/{self.filename}"): @@ -431,15 +433,17 @@ def __lt__(self, other): class Test_Results(QWidget, SpyderWidgetMixin): """ - This class is used to display the preprocessed data in the PyQt window and also to generate graphs from the data. + This class is used to display the preprocessed data in the PyQt window and also to generate graphs from the data. It inherits from QWidget and SpyderWidgetMixin to create a custom widget for displaying test results. """ - + sig_data_changed = Signal() + + def __init__(self, parent=None, background_color=None): """ - Initializes the Test_Results class and loads the UI file developed in QtDesigner. + Initializes the Test_Results class and loads the UI file developed in QtDesigner. It also sets up the necessary variables and connects the signals to the respective functions. - + Parameters ---------- parent : QWidget, optional @@ -460,6 +464,7 @@ def __init__(self, parent=None, background_color=None): self._filename = "" self.filename = "" self.ptr_table = [] + self.mpr_table = [] self.adjustUI() # Connect to the mentioned functions when 'PushButton' is triggered @@ -474,14 +479,14 @@ def adjustUI(self): self.llotid.setText("") def open_files(self, fname=""): - """ + """ This method is used to open the '.stdf' file and load the data into the PyQt window. - + Parameters ---------- fname : str, optional The path to the '.stdf' file. If not provided, a file dialog will be opened to select the file. - + Returns ------- bool @@ -543,10 +548,10 @@ def open_files(self, fname=""): # To load Pandas dataframes def loaddata(self): - """ - This method is used to load the data from the '.hdf5' file into Pandas DataFrames. + """ + This method is used to load the data from the '.hdf5' file into Pandas DataFrames. It uses the 'showStdf' class to read the data and preprocess it for further analysis. - + Returns ------- bool @@ -567,7 +572,7 @@ def generate_graph_from_json(self): """ This method is used to generate graphs from the data stored in a '.json' file. It reads the JSON file, processes the data, and creates plots using Matplotlib. - + Returns ------- bool @@ -727,7 +732,7 @@ def generate_graph_from_json(self): # Function to generate the '.pdf' files containing all the images def generate_pdf(self): - """ + """ This method is used to generate a PDF file containing all the images in a folder. It reads all the images in the specified folder, converts them to RGB format, and saves them as a single PDF file. """ @@ -762,9 +767,9 @@ def generate_pdf(self): img_rgb.save(pdf_path + pdf_file, save_all=True, append_images=image_pdf_list) def fill_ptr_data(self): - """ + """ This method is used to fill the 'PTR' data in the 'QTableWidget' in the PyQt window. - It iterates through the columns of the 'ptr_table' DataFrame and sets the values in the corresponding cells of the 'QTableWidget'. + It iterates through the columns of the 'ptr_table' DataFrame and sets the values in the corresponding cells of the 'QTableWidget'. It also updates the progress bar to indicate the progress of filling the data. """ # Set no. of rows in PyQt5 Widget @@ -796,17 +801,17 @@ def filter_test_name_ptr(self, filter_test): """ This method is used to filter the 'PTR' data in the 'QTableWidget' based on the test name. It hides the rows that do not match the specified filter. - + Parameters ---------- filter_test : str The test name to filter the data by. If an empty string is provided, all rows will be shown. - + Returns ------- None. """ - + temp = [] self.keyPressEvent(None) if filter_test == '': @@ -831,7 +836,7 @@ def filter_test_name_ptr(self, filter_test): # To fill 'MPR' data in 'QTableWidget' def fill_mpr_data(self): - """ + """ This method is used to fill the 'MPR' data in the 'QTableWidget' in the PyQt window. It iterates through the columns of the 'mpr_table' DataFrame and sets the values in the corresponding cells of the 'QTableWidget'. It also updates the progress bar to indicate the progress of filling the data. @@ -856,12 +861,12 @@ def filter_test_name_mpr(self, filter_test): """ This method is used to filter the 'MPR' data in the 'QTableWidget' based on the test name. It hides the rows that do not match the specified filter. - + Parameters ---------- filter_test : str The test name to filter the data by. If an empty string is provided, all rows will be shown. - + Returns ------- None. @@ -944,9 +949,9 @@ def load_IC_data(self): # Assigning desiered column width to particular columns def set_column_width(self): - """ + """ This method is used to set the column width of the 'QTableWidget' in the PyQt window. - It assigns specific widths to each column based on the content and importance of the data. + It assigns specific widths to each column based on the content and importance of the data. It also sets a minimum section size for the horizontal header to ensure that the columns are not too narrow. """ self.tableWidget_ptr.horizontalHeader().setMinimumSectionSize(10) @@ -973,14 +978,14 @@ def set_column_width(self): # To Colour values based on whether test has been passed (PTR Table) def colour_pass_fail_ptr_data(self): - """ + """ This method is used to color the values in the 'PTR' table based on whether the test has been passed or failed. - It iterates through the rows of the 'ptr_table' DataFrame and checks the values in the 'Test_Failed' column. - If the value is '0', it means the test has passed, and the corresponding cells are colored green. - If the value is not '0', it means the test has failed, and the corresponding cells are colored red. + It iterates through the rows of the 'ptr_table' DataFrame and checks the values in the 'Test_Failed' column. + If the value is '0', it means the test has passed, and the corresponding cells are colored green. + If the value is not '0', it means the test has failed, and the corresponding cells are colored red. Additionally, if there are any IC values that are out of limits, they are colored yellow. """ - + for j in range(0, len(self.ptr_table)): # If values in the 'Test_Failed' column is '0' then test Passed if self.ptr_table["Test_Failed"][j] == 0: @@ -1003,9 +1008,9 @@ def colour_pass_fail_ptr_data(self): def colour_pass_fail_mpr_data(self): """ This method is used to color the values in the 'MPR' table based on whether the test has been passed or failed. - It iterates through the rows of the 'mpr_table' DataFrame and checks the values in the 'Test_Failed' column. - If the value is '0', it means the test has passed, and the corresponding cells are colored green. - If the value is not '0', it means the test has failed, and the corresponding cells are colored red. + It iterates through the rows of the 'mpr_table' DataFrame and checks the values in the 'Test_Failed' column. + If the value is '0', it means the test has passed, and the corresponding cells are colored green. + If the value is not '0', it means the test has failed, and the corresponding cells are colored red. """ for j in range(0, len(self.mpr_table)): @@ -1024,10 +1029,10 @@ def colour_pass_fail_mpr_data(self): # Action function on the event of 'Cell Clicked' in QTableWidget def plot_select(self, selected): - """ + """ This method is triggered when a cell in the 'MPR' table is clicked. It retrieves the index of the selected row and updates the 'last_selected_row' variable. - If no row is selected, it prints a message indicating that no row is selected. - + If no row is selected, it prints a message indicating that no row is selected. + Parameters ---------- selected : QItemSelection @@ -1041,9 +1046,9 @@ def plot_select(self, selected): # To open menu on Right-Click def contextMenuEvent(self, event): """ - This method is triggered when the user right-clicks on the 'MPR' table. + This method is triggered when the user right-clicks on the 'MPR' table. It checks if any row is selected and opens a context menu with options to plot a graph or add a graph. - + Parameters ---------- event : QContextMenuEvent @@ -1062,7 +1067,7 @@ def contextMenuEvent(self, event): # Function to plot graph def graph_show(self): - """ + """ This method is used to plot the graph based on the selected rows in the 'MPR' table. It checks the number of selected rows and plots the graph accordingly. """ @@ -1191,13 +1196,13 @@ def plot_graph_ptr(self, selected): """ This method is used to plot the graph based on the selected row in the 'PTR' table. It retrieves the index of the selected row and updates the status label with the selected line number. - + Parameters ---------- selected : QItemSelection The selection object that contains the indexes of the selected cells. """ - + if len(selected.indexes()) == 0: self.lstatus.setText('') return @@ -1227,6 +1232,7 @@ def plot_graph_ptr(self, selected): if len(si.split(" ")) > 1: ylabel = f'{ylabel}\n ({si.split(" ")[1]})' plt.ylabel(ylabel, rotation=90) + self.graph_show() @property def filename(self): @@ -1254,7 +1260,7 @@ def filename(self, name): def printProgressBar(self, iteration, total, prefix="", suffix="", decimals=1, length=100, fill="█", printEnd="\r"): """ Call in a loop to create terminal progress bar - + Parameters ---------- iteration : int @@ -1273,7 +1279,7 @@ def printProgressBar(self, iteration, total, prefix="", suffix="", decimals=1, l Bar fill character (Str) printEnd : str, optional End character (e.g. "\r", "\r\n") (Str) - + Returns ------- None. @@ -1288,17 +1294,17 @@ def printProgressBar(self, iteration, total, prefix="", suffix="", decimals=1, l def update_Progress_bar(self, count, maxcount): """ - This method is used to update the progress bar in the PyQt window. - It sets the range and value of the progress bar based on the current count and maximum count. + This method is used to update the progress bar in the PyQt window. + It sets the range and value of the progress bar based on the current count and maximum count. It also processes any pending events to ensure that the progress bar is updated in real-time. - + Parameters ---------- count : int The current count or progress value. maxcount : int The maximum count or total value for the progress bar. - + Returns ------- None. @@ -1314,12 +1320,12 @@ def close_window(self): # 'Esc' key event to reset the click counter if unknowingly pressed def keyPressEvent(self, event): - """ - This method is triggered when a key is pressed. - If the 'Esc' key is pressed, it resets the 'last_selected_row' variable and clears the 'clicked_index' list. - It also updates the status label to indicate that no line is selected. - If the 'Return' key is pressed, it calls the 'load_IC_data' method to load the IC data into the table. - + """ + This method is triggered when a key is pressed. + If the 'Esc' key is pressed, it resets the 'last_selected_row' variable and clears the 'clicked_index' list. + It also updates the status label to indicate that no line is selected. + If the 'Return' key is pressed, it calls the 'load_IC_data' method to load the IC data into the table. + Parameters ---------- event : QKeyEvent From e5990bd312640bcefd4d3969790b48e374c58ccb Mon Sep 17 00:00:00 2001 From: Christian Jung Date: Thu, 12 Nov 2026 16:15:43 +0100 Subject: [PATCH 07/12] reorganise showstdf + clear tables if reload --- .../stdf_browser/widgets/main_widget.py | 64 +- .../plugins/stdf_browser/widgets/showstdf.py | 973 ----------------- .../stdf_browser/widgets/test_results.py | 988 ++++++++++++++++++ 3 files changed, 1028 insertions(+), 997 deletions(-) create mode 100644 pylab_ml/plugins/stdf_browser/widgets/test_results.py diff --git a/pylab_ml/plugins/stdf_browser/widgets/main_widget.py b/pylab_ml/plugins/stdf_browser/widgets/main_widget.py index bbd694f8..9f320582 100644 --- a/pylab_ml/plugins/stdf_browser/widgets/main_widget.py +++ b/pylab_ml/plugins/stdf_browser/widgets/main_widget.py @@ -11,9 +11,9 @@ # Local imports from spyder.api.translations import get_translation -from spyder.api.widgets.main_widget import PluginMainWidgetMenus -from spyder.api.widgets.main_widget import PluginMainWidget -from pylab_ml.plugins.stdf_browser.widgets.showstdf import Test_Results +from spyder.api.widgets.main_widget import ( + PluginMainWidget, PluginMainWidgetMenus) +from pylab_ml.plugins.stdf_browser.widgets.test_results import Test_Results # Localization _ = get_translation("spyder") @@ -50,9 +50,12 @@ class StdfWidgetToolbarItems: class StdfWidget(PluginMainWidget): # ShellConnectMainWidget ,PluginMainWidget """ Main widget for the STDF plugin. """ - SHOW_MESSAGE_WHEN_EMPTY = False + SHOW_MESSAGE_WHEN_EMPTY = True IMAGE_WHEN_EMPTY = "plots" - MESSAGE_WHEN_EMPTY = _("No result to show") + MESSAGE_WHEN_EMPTY = _("No STDF file loaded") + DESCRIPTION_WHEN_EMPTY = _( + "Use the import button in the toolbar to open a STDF file." + ) def __init__(self, name=None, plugin=None, parent=None): """ Initialize the main widget. @@ -70,11 +73,15 @@ def __init__(self, name=None, plugin=None, parent=None): # Widgets self.widget = Test_Results(parent=self) - # self.widget.sig_data_changed(self.update_actions) + self.set_content_widget(self.widget) + + self.widget.sig_data_changed.connect(self._on_data_changed) + + self.show_empty_message() # Resize to a huge width to get the right size of the thumbnail # scrollbar at startup. - self.resize(50000, self.height()) + # self.resize(50000, self.height()) # ---- PluginMainWidget API # ------------------------------------------------------------------------ @@ -89,10 +96,6 @@ def get_focus_widget(self): def setup(self): """ Setup the main widget. This is called after the widget is created and before it is shown for the first time. """ - layout = QHBoxLayout() - layout.addWidget(self.widget) - self.setLayout(layout) - # Menu actions # self.fit_action = self.create_action( # name=StdfWidgetActions.ToggleAutoFitPlotting, @@ -124,7 +127,7 @@ def setup(self): graph_show_action = self.create_action( name=StdfWidgetActions.Graph, text=_("Show grap"), - tip=_("Show grap..."), + tip=_("Plot the selected MPR rows"), icon=self.create_icon("plot"), triggered=self.graph_show, ) @@ -137,8 +140,6 @@ def setup(self): triggered=self.generate_graph_from_json, ) - # Options menu - # Main toolbar main_toolbar = self.get_main_toolbar() for item in [ @@ -155,8 +156,8 @@ def setup(self): # Context menu context_menu = self.create_menu(PluginMainWidgetMenus.Context) - for item in [import_data_action]: - self.add_item_to_menu(item, menu=context_menu) + self.add_item_to_menu(import_data_action, menu=context_menu) + def update_actions(self): """ Update the enabled/disabled state of actions based on the current context. """ @@ -165,9 +166,9 @@ def update_actions(self): states = { StdfWidgetActions.Import: True, - StdfWidgetActions.Reload: has_file, # only if the file known - StdfWidgetActions.Graph: has_data, # only if the file load - StdfWidgetActions.Json: has_data, # only if the file load + StdfWidgetActions.Reload: bool(self.widget.filename), # only if the file known + StdfWidgetActions.Graph: self.weidgt.has_mpr, # only if the file load + StdfWidgetActions.Json: has_data, # only if the file load } for name, enabled in states.items(): try: @@ -189,10 +190,6 @@ def update_actions(self): # if action not in thumbnails_sb_actions: # thumbnails_sb.addAction(action) - - def _has_file(self): - return bool(getattr(self.widget, "filename", "")) - def _has_data(self): return len(self.widget.mpr_table)>0 or len(self.widget.ptr_table)>0 @@ -201,6 +198,21 @@ def on_close(self): print(" StdfWidget.on_close") return super().on_close() + def on_close(self): + if self.widget.plot_window is not None: + self.widget.plot_window.close() + return super().on_close() + + # ---- Private API + # ------------------------------------------------------------------------ + def _on_data_changed(self): + """ Zwischen Leerbild und Inhalt umschalten. """ + if self.widget.has_data(): + self.show_content_widget() + else: + self.show_empty_message() + self.update_actions() + # ---- Public API: # ------------------------------------------------------------------------ @@ -211,7 +223,7 @@ def import_data(self): if os.path.isfile(result_h5): os.remove(result_h5) self.widget.open_files() - self.update_actions() + # self.update_actions() def reload_data(self): """Reload data.""" @@ -229,6 +241,10 @@ def set_filename(self, path, filename): self.widget.filename = filename + ".stdf" self.update_actions() + def clear(self): + """ Daten verwerfen und wieder das Leerbild zeigen. """ + self.widget.clear_data() + def graph_show(self): """Show graph.""" self.widget.graph_show() diff --git a/pylab_ml/plugins/stdf_browser/widgets/showstdf.py b/pylab_ml/plugins/stdf_browser/widgets/showstdf.py index 21e32dec..7a185b2e 100644 --- a/pylab_ml/plugins/stdf_browser/widgets/showstdf.py +++ b/pylab_ml/plugins/stdf_browser/widgets/showstdf.py @@ -7,51 +7,14 @@ """ # Standard library imports -import json -import sys import os from pathlib import Path # Third library imports -from qtpy import PYQT5 -from qtpy.QtCore import Signal, Qt, QCoreApplication -from qtpy.QtWidgets import (QApplication, QWidget, QFileDialog, QMenu, - QTableWidgetItem) -from qtpy.uic import loadUi -from qtpy import QtWidgets, QtGui from Metis.tools import stdf2ph5, STDFHelper -from PIL import Image -import matplotlib.pyplot as plt import pandas as pd import numpy as np -# spyder library imports -from spyder.api.widgets.mixins import SpyderWidgetMixin - -__version__ = "0.0.6" - - -TaPtrItems = { - "TestNo": 0, - "Test Name": 1, - "LSL": 2, - "LTL": 3, - "Results": 4, - "empty1": 5, - "IC 1": 6, - "IC 2": 7, - "IC 3": 8, - "empty2": 9, - "UTL": 10, - "USL": 11, - "Mean": 12, - "Min": 13, - "Max": 14, - "RMS": 15, - "Test Failed": 16, - "ICFailed": 17, -} - def str2float(string): """ @@ -420,939 +383,3 @@ def raw_hdf5_data(self): print("MPR field is empty ... ") return ptr, mpr - - -class TableWidget(QTableWidgetItem): - """Custom QTableWidgetItem for handling numeric comparisons.""" - def __lt__(self, other): - try: - return float(self.text()) < float(other.text()) - except Exception: - return QTableWidgetItem.__lt__(self, other) - - -class Test_Results(QWidget, SpyderWidgetMixin): - """ - This class is used to display the preprocessed data in the PyQt window and also to generate graphs from the data. - It inherits from QWidget and SpyderWidgetMixin to create a custom widget for displaying test results. - """ - sig_data_changed = Signal() - - - def __init__(self, parent=None, background_color=None): - """ - Initializes the Test_Results class and loads the UI file developed in QtDesigner. - It also sets up the necessary variables and connects the signals to the respective functions. - - Parameters - ---------- - parent : QWidget, optional - The parent widget of this Test_Results widget. If None, it will be a top-level window. - background_color : str, optional - The background color of the widget. If None, the default color will be used. - """ - if PYQT5: - super().__init__(parent=parent, class_parent=parent) - else: - QWidget.__init__(self, parent) - SpyderWidgetMixin.__init__(self, class_parent=parent) - - # Loading 'ui' files developed in 'QtDesigner' - loadUi(__file__.replace(".py", ".ui"), self) - - self.path = "" - self._filename = "" - self.filename = "" - self.ptr_table = [] - self.mpr_table = [] - self.adjustUI() - - # Connect to the mentioned functions when 'PushButton' is triggered - self.last_selected_row = -1 - self.clicked_index = [] - - def adjustUI(self): - """ This method is used to adjust the UI elements of the PyQt window, such as setting the column width of the 'QTableWidget' and hiding the progress bar and status labels.""" - self.set_column_width() - self.progressBar.hide() - self.lstatus.setText("") - self.llotid.setText("") - - def open_files(self, fname=""): - """ - This method is used to open the '.stdf' file and load the data into the PyQt window. - - Parameters - ---------- - fname : str, optional - The path to the '.stdf' file. If not provided, a file dialog will be opened to select the file. - - Returns - ------- - bool - True if the file was successfully opened and data was loaded, False otherwise. - """ - path = os.getcwd() if self.path == "" else self.path - if fname == "" or not fname: - fname = QFileDialog().getOpenFileName(self, "Open STDF File", path, "stdf Files (*.stdf *.std)") - fname = fname[0] - if fname == "": - return - - self.path, self.filename = os.path.split(fname) - if not os.path.exists(fname): - return - self.progressBar.show() - QCoreApplication.processEvents() - - # To load Pandas dataframes - if not self.loaddata(): - self.progressBar.hide() - return False - - # Generate 'pdf' from the '.json' files - # self.jsonFile.clicked.connect(self.generate_graph_from_json) - - # To fill 'PTR' data in 'QTableWidget' - self.fill_ptr_data() - - # To fill 'MPR' data in 'QTableWidget' - self.fill_mpr_data() - - # Assigning desiered column width to particular columns - self.set_column_width() - - # To Colour values based on whether test has been passed (PTR Table) - self.colour_pass_fail_ptr_data() - - # Implement signal function on the event of 'Cell Clicked' - self.tableWidget_ptr.selectionModel().selectionChanged.connect(self.plot_graph_ptr) - - self.enter_filter_test_name_ptr.textChanged.connect(self.filter_test_name_ptr) - self.enter_filter_test_name_mpr.textChanged.connect(self.filter_test_name_mpr) - self.tabWidget.currentChanged.connect(lambda: self.keyPressEvent(None)) - self.last_selected_row = -1 - self.clicked_index = [] - - try: - # To Colour values based on whether test has been passed (MPR) - self.colour_pass_fail_mpr_data() - - # Implement signal function on the event of 'Cell Clicked' - self.tableWidget_mpr.selectionModel().selectionChanged.connect(self.plot_select) - - # If there is no 'MPR' data, conditional formatting is not required - except Exception: - print("No values to Format in MPR Tab ...") - self.progressBar.hide() - - # To load Pandas dataframes - def loaddata(self): - """ - This method is used to load the data from the '.hdf5' file into Pandas DataFrames. - It uses the 'showStdf' class to read the data and preprocess it for further analysis. - - Returns - ------- - bool - True if the data was successfully loaded, False otherwise. - """ - print(f"Test_Results.loaddata : {self.path, self.filename, self.lot}") - self.hdf5_data = showStdf(self.path, self.filename, self.lot, "result_h5", update_Progress_bar=self.update_Progress_bar) - if not self.hdf5_data.init(): - self.lfilename.setText(f".../{self.filename} is not a valid stdf file") - return False - self.table_data = self.hdf5_data.raw_hdf5_data() - self.ptr_table = self.table_data[0] - self.mpr_table = self.table_data[1] - return True - - # To generate '.png' images from the '.json' file - def generate_graph_from_json(self): - """ - This method is used to generate graphs from the data stored in a '.json' file. - It reads the JSON file, processes the data, and creates plots using Matplotlib. - - Returns - ------- - bool - True if the graphs were successfully generated, False otherwise. - """ - try: - # Load the '.json' file - jname = QFileDialog().getOpenFileName(self, "Open File", os.getcwd(), "JSON files (*.json)") - with open(jname[0], "r") as f: - self.json_data = json.load(f) - - temp_folder = "STDF_Graph_Folder" - self.graph_folder = os.path.join(self.path, temp_folder) - - # If directory doesn't exist, then create it - if not os.path.exists(self.graph_folder): - os.makedirs(self.graph_folder) - try: - for i in range(0, len(self.json_data)): - if "y" not in self.json_data[str(i)]: - temp_a = self.mpr_table["Results"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][ - self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["x"][1] - ].tolist() - temp_b = self.mpr_table["MPR.LO_LIMIT"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][0] - temp_c = self.mpr_table["MPR.HI_LIMIT"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][0] - temp_d = self.mpr_table["Min_Value"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][ - self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["x"][1] - ] - temp_e = self.mpr_table["Max_Value"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][ - self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["x"][1] - ] - temp_f = self.mpr_table["Mean_Value"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][ - self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["x"][1] - ] - temp_g = self.mpr_table["Result_Count"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][0] - temp_h = str(self.mpr_table["Units"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][0]) - plt.plot(temp_a[0], "bo", markersize=1) - plt.hlines(temp_b, 0, temp_g, color="r") - plt.hlines(temp_c, 0, temp_g, color="r") - plt.hlines(temp_d, 0, temp_g, color="m") - plt.hlines(temp_e, 0, temp_g, color="m") - plt.hlines(temp_f, 0, temp_g, color="y") - plt.title(self.json_data[str(i)]["title"]) - plt.ylabel(temp_h) - - if "y" in self.json_data[str(i)]: - temp_a = self.mpr_table["Results"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][ - self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["x"][1] - ].tolist() - temp_b = self.mpr_table["Results"][self.mpr_table["Test"] == self.json_data[str(i)]["y"][0]][ - self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["y"][1] - ].tolist() - temp_c = ( - self.json_data[str(i)]["x"][0] - + "[" - + str(self.json_data[str(i)]["x"][1]) - + "]" - + " vs " - + self.json_data[str(i)]["y"][0] - + "[" - + str(self.json_data[str(i)]["y"][1]) - + "]" - ) - temp_d = str(self.mpr_table["Units"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][0]) - temp_e = str(self.mpr_table["Units"][self.mpr_table["Test"] == self.json_data[str(i)]["y"][0]][0]) - plt.plot(temp_a[0], temp_b[0], "bo", markersize=1) - plt.xlabel(temp_d) - plt.ylabel(temp_e) - plt.title(self.json_data[str(i)]["title"]) - plt.legend([temp_c]) - - if "y1" in self.json_data[str(i)]: - temp_a = self.mpr_table["Results"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][ - self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["x"][1] - ].tolist() - temp_b = self.mpr_table["Results"][self.mpr_table["Test"] == self.json_data[str(i)]["y1"][0]][ - self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["y1"][1] - ].tolist() - temp_c = ( - self.json_data[str(i)]["x"][0] - + "[" - + str(self.json_data[str(i)]["x"][1]) - + "]" - + " vs " - + self.json_data[str(i)]["y"][0] - + "[" - + str(self.json_data[str(i)]["y"][1]) - + "]" - ) - temp_d = ( - self.json_data[str(i)]["x"][0] - + "[" - + str(self.json_data[str(i)]["x"][1]) - + "]" - + " vs " - + self.json_data[str(i)]["y1"][0] - + "[" - + str(self.json_data[str(i)]["y1"][1]) - + "]" - ) - plt.plot(temp_a[0], temp_b[0], "go", markersize=1) - plt.legend([temp_c, temp_d]) - - if "y2" in self.json_data[str(i)]: - temp_a = self.mpr_table["Results"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][ - self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["x"][1] - ].tolist() - temp_b = self.mpr_table["Results"][self.mpr_table["Test"] == self.json_data[str(i)]["y2"][0]][ - self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["y2"][1] - ].tolist() - temp_c = ( - self.json_data[str(i)]["x"][0] - + "[" - + str(self.json_data[str(i)]["x"][1]) - + "]" - + " vs " - + self.json_data[str(i)]["y"][0] - + "[" - + str(self.json_data[str(i)]["y"][1]) - + "]" - ) - temp_d = ( - self.json_data[str(i)]["x"][0] - + "[" - + str(self.json_data[str(i)]["x"][1]) - + "]" - + " vs " - + self.json_data[str(i)]["y1"][0] - + "[" - + str(self.json_data[str(i)]["y1"][1]) - + "]" - ) - temp_e = ( - self.json_data[str(i)]["x"][0] - + "[" - + str(self.json_data[str(i)]["x"][1]) - + "]" - + " vs " - + self.json_data[str(i)]["y2"][0] - + "[" - + str(self.json_data[str(i)]["y2"][1]) - + "]" - ) - plt.plot(temp_a[0], temp_b[0], "ro", markersize=1) - plt.legend([temp_c, temp_d, temp_e]) - - # Filename is assigned as the 'title' key in the '.json' file - filename = self.json_data[str(i)]["title"] + ".png" - plt.savefig(os.path.join(self.graph_folder, filename)) - self.printProgressBar(i, len(self.json_data) - 1, prefix="Graph Generation:", suffix="Complete", length=50) - plt.clf() - self.generate_pdf() - except Exception: - print("There is no MPR data to plot the graph or the plots already exists ...") - except Exception: - print("Select the JSON file correctly ...") - - # Function to generate the '.pdf' files containing all the images - def generate_pdf(self): - """ - This method is used to generate a PDF file containing all the images in a folder. - It reads all the images in the specified folder, converts them to RGB format, and saves them as a single PDF file. - """ - - # Empty list to append all the images in a folder - image_pdf_list = [] - - for i in os.listdir(self.graph_folder): - global img_rgb - image_file = os.path.join(self.graph_folder, i) - - # Open an Image - img = Image.open(image_file) - - # Convert the Image to a 'RGB' format - img_rgb = img.convert("RGB") - image_pdf_list.append(img_rgb) - - # Remove the image at the last index of the folder - image_pdf_list.pop(-1) - - # Create a PDF folder to store the '.pdf' file - pdf_directory = "PDF/" - pdf_path = os.path.join(self.graph_folder, pdf_directory) - - if not os.path.exists(pdf_path): - os.makedirs(pdf_path) - - pdf_file = "STDF_Graph_" + self.lot + ".pdf" - - # Save the PDF file - img_rgb.save(pdf_path + pdf_file, save_all=True, append_images=image_pdf_list) - - def fill_ptr_data(self): - """ - This method is used to fill the 'PTR' data in the 'QTableWidget' in the PyQt window. - It iterates through the columns of the 'ptr_table' DataFrame and sets the values in the corresponding cells of the 'QTableWidget'. - It also updates the progress bar to indicate the progress of filling the data. - """ - # Set no. of rows in PyQt5 Widget - self.keyPressEvent(None) - self.tableWidget_ptr.setRowCount(len(self.ptr_table)) - col = 0 - self.progressBar.show() - for column in self.ptr_table.columns[0:5]: - row = 0 - for j in range(0, len(self.ptr_table)): - for val in self.ptr_table[column][[j]]: - self.tableWidget_ptr.setItem(row, col, TableWidget(str(val))) - row += 1 - col += 1 - self.printProgressBar(col, 17, prefix="Progress PTR:", suffix="Complete", length=50) - - col = 10 - for column in self.ptr_table.columns[5:13]: - row = 0 - for j in range(0, len(self.ptr_table)): - for val in self.ptr_table[column][[j]]: - self.tableWidget_ptr.setItem(row, col, TableWidget(str(val))) - row += 1 - col += 1 - self.printProgressBar(col, 17, prefix="Progress PTR:", suffix="Complete", length=50) - self.progressBar.hide() - - def filter_test_name_ptr(self, filter_test): - """ - This method is used to filter the 'PTR' data in the 'QTableWidget' based on the test name. - It hides the rows that do not match the specified filter. - - Parameters - ---------- - filter_test : str - The test name to filter the data by. If an empty string is provided, all rows will be shown. - - Returns - ------- - None. - """ - - temp = [] - self.keyPressEvent(None) - if filter_test == '': - for i in range(self.tableWidget_ptr.rowCount()): - self.tableWidget_ptr.setRowHidden(i, False) - else: - for i in range(self.tableWidget_ptr.rowCount()): - item = self.tableWidget_ptr.item(i, 1) - if item is None: - continue - match = filter_test.lower() in item.text().lower() - if match: - temp.append(i) - self.tableWidget_ptr.setRowHidden(i, True) - - if temp == []: - for i in range(self.tableWidget_ptr.rowCount()): - self.tableWidget_ptr.setRowHidden(i, True) - - for val in temp: - self.tableWidget_ptr.setRowHidden(val, False) - - # To fill 'MPR' data in 'QTableWidget' - def fill_mpr_data(self): - """ - This method is used to fill the 'MPR' data in the 'QTableWidget' in the PyQt window. - It iterates through the columns of the 'mpr_table' DataFrame and sets the values in the corresponding cells of the 'QTableWidget'. - It also updates the progress bar to indicate the progress of filling the data. - """ - # Set no. of rows in PyQt5 Widget - self.keyPressEvent(None) - self.progressBar.show() - self.tableWidget_mpr.setRowCount(len(self.mpr_table)) - col = 0 - for column in self.mpr_table.columns[0:14]: - row = 0 - for j in range(0, len(self.mpr_table)): - for val in self.mpr_table[column][[j]]: - # self.tableWidget_mpr.setItem(row, col, QtWidgets.QTableWidgetItem(str(val))) - self.tableWidget_mpr.setItem(row, col, TableWidget(str(val))) - row += 1 - col += 1 - self.printProgressBar(col, len(self.mpr_table.columns) - 3, prefix="Progress MPR:", suffix="Complete", length=50) - self.progressBar.hide() - - def filter_test_name_mpr(self, filter_test): - """ - This method is used to filter the 'MPR' data in the 'QTableWidget' based on the test name. - It hides the rows that do not match the specified filter. - - Parameters - ---------- - filter_test : str - The test name to filter the data by. If an empty string is provided, all rows will be shown. - - Returns - ------- - None. - """ - temp = [] - self.keyPressEvent(None) - if filter_test == '': - for i in range(self.tableWidget_mpr.rowCount()): - self.tableWidget_mpr.setRowHidden(i, False) - else: - for i in range(self.tableWidget_mpr.rowCount()): - item = self.tableWidget_mpr.item(i, 2) - if item is None: - continue - match = filter_test.lower() in item.text().lower() - if match: - temp.append(i) - self.tableWidget_mpr.setRowHidden(i, True) - - if temp == []: - for i in range(self.tableWidget_mpr.rowCount()): - self.tableWidget_mpr.setRowHidden(i, True) - - for val in temp: - self.tableWidget_mpr.setRowHidden(val, False) - - def load_IC_data(self): - """ - This method is used to load the IC data into the 'QTableWidget' in the PyQt window. - It retrieves the selected IC values from the input fields and updates the corresponding cells in the table. - It also highlights the cells that are out of the specified limits. - """ - try: - selected_IC1 = int(self.ic_Number1.text()) - 1 - except Exception: - selected_IC1 = 100000 - try: - selected_IC2 = int(self.ic_Number2.text()) - 1 - except Exception: - selected_IC2 = 100000 - try: - selected_IC3 = int(self.ic_Number3.text()) - 1 - except Exception: - selected_IC3 = 100000 - - self.tableWidget_ptr.sortItems(0) - - for i in range(0, len(self.ptr_table)): - ltl = str2float(self.ptr_table["LTL"][i]) - utl = str2float(self.ptr_table["UTL"][i]) - try: - if len(self.ptr_table["Result_Append"][i]) > (selected_IC1): - val = self.ptr_table["Result_Append"][i][selected_IC1] - self.tableWidget_ptr.setItem(i, 6, QtWidgets.QTableWidgetItem(str(val))) - if ltl != utl and ((self.ptr_table["Result_Append"][i][selected_IC1] < ltl) or ( - self.ptr_table["Result_Append"][i][selected_IC1] > utl)): - self.tableWidget_ptr.item(i, 6).setBackground(QtGui.QColor(255, 0, 0)) - else: - self.tableWidget_ptr.setItem(i, 6, QtWidgets.QTableWidgetItem("NA")) - - if len(self.ptr_table["Result_Append"][i]) > (selected_IC2): - val = self.ptr_table["Result_Append"][i][selected_IC2] - self.tableWidget_ptr.setItem(i, 7, QtWidgets.QTableWidgetItem(str(val))) - if ltl != utl and ((self.ptr_table["Result_Append"][i][selected_IC2] < ltl) or ( - self.ptr_table["Result_Append"][i][selected_IC2] > utl)): - self.tableWidget_ptr.item(i, 7).setBackground(QtGui.QColor(255, 0, 0)) - else: - self.tableWidget_ptr.setItem(i, 7, QtWidgets.QTableWidgetItem("NA")) - - if len(self.ptr_table["Result_Append"][i]) > (selected_IC3): - val = self.ptr_table["Result_Append"][i][selected_IC3] - self.tableWidget_ptr.setItem(i, 8, QtWidgets.QTableWidgetItem(str(val))) - if ltl != utl and ((self.ptr_table["Result_Append"][i][selected_IC3] < ltl) or ( - self.ptr_table["Result_Append"][i][selected_IC3] > utl)): - self.tableWidget_ptr.item(i, 8).setBackground(QtGui.QColor(255, 0, 0)) - else: - self.tableWidget_ptr.setItem(i, 8, QtWidgets.QTableWidgetItem("NA")) - except Exception: - pass - - # Assigning desiered column width to particular columns - def set_column_width(self): - """ - This method is used to set the column width of the 'QTableWidget' in the PyQt window. - It assigns specific widths to each column based on the content and importance of the data. - It also sets a minimum section size for the horizontal header to ensure that the columns are not too narrow. - """ - self.tableWidget_ptr.horizontalHeader().setMinimumSectionSize(10) - self.tableWidget_ptr.setColumnWidth(TaPtrItems["TestNo"], 50) - self.tableWidget_ptr.setColumnWidth(TaPtrItems["Test Name"], 180) - self.tableWidget_ptr.setColumnWidth(TaPtrItems["LSL"], 75) - self.tableWidget_ptr.setColumnWidth(TaPtrItems["LTL"], 75) - self.tableWidget_ptr.setColumnWidth(TaPtrItems["Results"], 150) - self.tableWidget_ptr.setColumnWidth(TaPtrItems["IC 1"], 30) - self.tableWidget_ptr.setColumnWidth(TaPtrItems["IC 2"], 30) - self.tableWidget_ptr.setColumnWidth(TaPtrItems["IC 3"], 30) - self.tableWidget_ptr.setColumnWidth(TaPtrItems["empty1"], 10) - self.tableWidget_ptr.setColumnWidth(TaPtrItems["empty2"], 10) - self.tableWidget_ptr.setColumnWidth(TaPtrItems["UTL"], 75) - self.tableWidget_ptr.setColumnWidth(TaPtrItems["USL"], 75) - self.tableWidget_ptr.setColumnWidth(TaPtrItems["Test Failed"], 80) - for j in range(0, len(self.ptr_table)): - self.tableWidget_ptr.setItem(j, TaPtrItems["empty1"], QtWidgets.QTableWidgetItem()) - self.tableWidget_ptr.item(j, TaPtrItems["empty1"]).setBackground(QtGui.QColor(240, 240, 240)) - self.tableWidget_ptr.setItem(j, TaPtrItems["empty2"], QtWidgets.QTableWidgetItem()) - self.tableWidget_ptr.item(j, TaPtrItems["empty2"]).setBackground(QtGui.QColor(240, 240, 240)) - - self.tableWidget_mpr.setColumnWidth(6, 300) - - # To Colour values based on whether test has been passed (PTR Table) - def colour_pass_fail_ptr_data(self): - """ - This method is used to color the values in the 'PTR' table based on whether the test has been passed or failed. - It iterates through the rows of the 'ptr_table' DataFrame and checks the values in the 'Test_Failed' column. - If the value is '0', it means the test has passed, and the corresponding cells are colored green. - If the value is not '0', it means the test has failed, and the corresponding cells are colored red. - Additionally, if there are any IC values that are out of limits, they are colored yellow. - """ - - for j in range(0, len(self.ptr_table)): - # If values in the 'Test_Failed' column is '0' then test Passed - if self.ptr_table["Test_Failed"][j] == 0: - - # Green Colour if test is passed - # self.tableWidget_ptr.item(j, TaPtrItems["Results"]).setForeground(QtGui.QColor(0, 255, 0)) - self.tableWidget_ptr.item(j, TaPtrItems["Test Failed"]).setForeground(QtGui.QColor(0, 255, 0)) - pass - else: - - # Red Colour if test is failed - self.tableWidget_ptr.item(j, TaPtrItems["Test Name"]).setForeground(QtGui.QColor(255, 0, 0)) - self.tableWidget_ptr.item(j, TaPtrItems["Results"]).setForeground(QtGui.QColor(255, 0, 0)) - self.tableWidget_ptr.item(j, TaPtrItems["Test Failed"]).setForeground(QtGui.QColor(255, 0, 0)) - - # Yellow Colour in the IC# Failed - self.tableWidget_ptr.item(j, TaPtrItems["ICFailed"]).setForeground(QtGui.QColor(255, 255, 0)) - - # To Colour values based on whether test has been passed (MPR Table) - def colour_pass_fail_mpr_data(self): - """ - This method is used to color the values in the 'MPR' table based on whether the test has been passed or failed. - It iterates through the rows of the 'mpr_table' DataFrame and checks the values in the 'Test_Failed' column. - If the value is '0', it means the test has passed, and the corresponding cells are colored green. - If the value is not '0', it means the test has failed, and the corresponding cells are colored red. - """ - for j in range(0, len(self.mpr_table)): - - # If values in the 'Test_Failed' column is '0' then test Passed - if self.mpr_table["Test_Failed"][j] == 0: - - # Green Colour if test is passed - self.tableWidget_mpr.item(j, 6).setForeground(QtGui.QColor(0, 255, 0)) - self.tableWidget_mpr.item(j, 13).setForeground(QtGui.QColor(0, 255, 0)) - else: - - # Red Colour if test is failed - self.tableWidget_mpr.item(j, 1).setForeground(QtGui.QColor(255, 0, 0)) - self.tableWidget_mpr.item(j, 6).setForeground(QtGui.QColor(255, 0, 0)) - self.tableWidget_mpr.item(j, 13).setForeground(QtGui.QColor(255, 0, 0)) - - # Action function on the event of 'Cell Clicked' in QTableWidget - def plot_select(self, selected): - """ - This method is triggered when a cell in the 'MPR' table is clicked. It retrieves the index of the selected row and updates the 'last_selected_row' variable. - If no row is selected, it prints a message indicating that no row is selected. - - Parameters - ---------- - selected : QItemSelection - The selection object that contains the indexes of the selected cells. - """ - if len(selected.indexes()) > 0: - self.last_selected_row = selected.indexes()[0].row() - else: - print('no row selected') - - # To open menu on Right-Click - def contextMenuEvent(self, event): - """ - This method is triggered when the user right-clicks on the 'MPR' table. - It checks if any row is selected and opens a context menu with options to plot a graph or add a graph. - - Parameters - ---------- - event : QContextMenuEvent - The context menu event that triggered this method. - """ - if self.tableWidget_mpr.selectionModel().selection().indexes(): - menu = QMenu(self) - plotAction = menu.addAction("Plot Graph") if self.clicked_index != [] else None - addAction = menu.addAction("Add Graph") - action = menu.exec_(self.mapToGlobal(event.pos())) - if action == plotAction: - self.graph_show() - elif action == addAction and self.last_selected_row != -1 and self.last_selected_row not in self.clicked_index: - self.clicked_index.append(self.last_selected_row) - self.lstatus.setText(f'line {[i+1 for i in self.clicked_index]} selected') - - # Function to plot graph - def graph_show(self): - """ - This method is used to plot the graph based on the selected rows in the 'MPR' table. - It checks the number of selected rows and plots the graph accordingly. - """ - try: - if len(self.clicked_index) == 1: - # plt.clf() - plt.autoscale(True) - plt.figure(figsize=(3.2, 2.4), dpi=200) - plt.title(self._filename + " \\ " + self.lot + "\n") - - ylabel = self.mpr_table["Test"][self.clicked_index[0]] - ylabel = f'{ylabel}\n ({self.mpr_table["Units"][self.clicked_index[0]]})' - #if len(si.split(" ")) > 1: - # ylabel = f'{ylabel}\n ({si.split(" ")[1]})' - # plt.ylabel(self.mpr_table["Units"][self.clicked_index[0]]) - plt.ylabel(ylabel, rotation=90) - - ltl = self.mpr_table["MPR.LO_LIMIT"][self.clicked_index[0]] - utl = self.mpr_table["MPR.HI_LIMIT"][self.clicked_index[0]] - if ltl not in [-np.inf, np.inf]: - plt.hlines(self.mpr_table["MPR.LO_LIMIT"][self.clicked_index[0]], 0, self.mpr_table["Result_Count"][self.clicked_index[0]], color="r") - if utl not in [-np.inf, np.inf]: - plt.hlines(self.mpr_table["MPR.HI_LIMIT"][self.clicked_index[0]], 0, self.mpr_table["Result_Count"][self.clicked_index[0]], color="r") - plt.hlines(self.mpr_table["Min_Value"][self.clicked_index[0]], 0, self.mpr_table["Result_Count"][self.clicked_index[0]], color="m") - plt.hlines(self.mpr_table["Max_Value"][self.clicked_index[0]], 0, self.mpr_table["Result_Count"][self.clicked_index[0]], color="m") - plt.hlines(self.mpr_table["Mean_Value"][self.clicked_index[0]], 0, self.mpr_table["Result_Count"][self.clicked_index[0]], color="y") - # plt.plot(results, "bo", markersize=0.1, alpha=0.1) - plt.plot(self.mpr_table["Results"][self.clicked_index[0]], "bo-", markeredgecolor="magenta", markersize=1) - # plt.legend([self.mpr_table["Test"][self.clicked_index[0]], "LTL and UTL", "_nolegend_", "Min and Max", "_nolegend_", "Mean"]) - - elif len(self.clicked_index) == 2: - # label_a = self.mpr_table["Units"][self.clicked_index[0]] + "[" + str(self.mpr_table["PART_INDEX"][self.clicked_index[0]]) + "]" - # label_b = self.mpr_table["Units"][self.clicked_index[1]] + "[" + str(self.mpr_table["PART_INDEX"][self.clicked_index[1]]) + "]" - # temp_c = temp_a + " vs " + temp_b - - plt.figure(figsize=(3.2, 2.4), dpi=200) - # plt.plot(self.mpr_table["Results"][self.clicked_index[0]], self.mpr_table["Results"][self.clicked_index[1]], "go", markersize=0.3, alpha=0.5) - # plt.title(self._filename + " \\ " + self.lot + "\n" + self.mpr_table["Test"][self.clicked_index[0]]) - plt.title(self._filename + " \\ " + self.lot + "\n") - # plt.xlabel(self.mpr_table["Units"][self.clicked_index[0]]) - # plt.ylabel(self.mpr_table["Units"][self.clicked_index[1]]) - # plt.legend([temp_c]) - plt.plot(self.mpr_table["Results"][self.clicked_index[0]], "go-", markersize=0.3, alpha=0.5) - plt.plot(self.mpr_table["Results"][self.clicked_index[1]], "ro-", markersize=0.3, alpha=0.5) - label_0 = self.mpr_table["Test"][self.clicked_index[0]] - label_1 = self.mpr_table["Test"][self.clicked_index[1]] - plt.ylabel(f'{self.mpr_table["Units"][self.clicked_index[0]]}', rotation=90) - plt.legend([label_0, label_1]) - - elif len(self.clicked_index) == 3: - temp_a = self.mpr_table["Units"][self.clicked_index[0]] + "[" + str(self.mpr_table["PART_INDEX"][self.clicked_index[0]]) + "]" - temp_b = self.mpr_table["Units"][self.clicked_index[1]] + "[" + str(self.mpr_table["PART_INDEX"][self.clicked_index[1]]) + "]" - temp_c = temp_a + " vs " + temp_b - temp_d = self.mpr_table["Units"][self.clicked_index[2]] + "[" + str(self.mpr_table["PART_INDEX"][self.clicked_index[2]]) + "]" - temp_e = temp_a + " vs " + temp_d - - plt.figure(figsize=(3.2, 2.4), dpi=200) - plt.plot(self.mpr_table["Results"][self.clicked_index[0]], self.mpr_table["Results"][self.clicked_index[1]], "go", markersize=0.1, alpha=0.5) - plt.plot(self.mpr_table["Results"][self.clicked_index[0]], self.mpr_table["Results"][self.clicked_index[2]], "ro", markersize=0.1, alpha=0.5) - plt.title(self._filename + " \\ " + self.lot + "\n" + self.mpr_table["Test"][self.clicked_index[0]]) - plt.xlabel(self.mpr_table["Units"][self.clicked_index[0]]) - plt.ylabel(self.mpr_table["Units"][self.clicked_index[1]] + " / " + self.mpr_table["Units"][self.clicked_index[2]]) - plt.legend([temp_c, temp_e]) - - elif len(self.clicked_index) == 4: - temp_a = self.mpr_table["Units"][self.clicked_index[0]] + "[" + str(self.mpr_table["PART_INDEX"][self.clicked_index[0]]) + "]" - temp_b = self.mpr_table["Units"][self.clicked_index[1]] + "[" + str(self.mpr_table["PART_INDEX"][self.clicked_index[1]]) + "]" - temp_c = temp_a + " vs " + temp_b - temp_d = self.mpr_table["Units"][self.clicked_index[2]] + "[" + str(self.mpr_table["PART_INDEX"][self.clicked_index[2]]) + "]" - temp_e = temp_a + " vs " + temp_d - temp_f = self.mpr_table["Units"][self.clicked_index[3]] + "[" + str(self.mpr_table["PART_INDEX"][self.clicked_index[3]]) + "]" - temp_g = temp_a + " vs " + temp_f - - plt.figure(figsize=(3.2, 2.4), dpi=200) - plt.plot( - self.mpr_table["Results"][self.clicked_index[0]], - self.mpr_table["Results"][self.clicked_index[1]], - "go", - markersize=0.1, - alpha=0.5, - label=temp_c, - ) - plt.plot( - self.mpr_table["Results"][self.clicked_index[0]], - self.mpr_table["Results"][self.clicked_index[2]], - "ro", - markersize=0.1, - alpha=0.5, - label=temp_e, - ) - plt.plot( - self.mpr_table["Results"][self.clicked_index[0]], - self.mpr_table["Results"][self.clicked_index[3]], - "yo", - markersize=0.1, - alpha=0.5, - label=temp_g, - ) - plt.title(self.mpr_table["Test"][self.clicked_index[0]]) - plt.xlabel(self.mpr_table["Units"][self.clicked_index[0]]) - plt.ylabel( - self.mpr_table["Units"][self.clicked_index[1]] - + " / " - + self.mpr_table["Units"][self.clicked_index[2]] - + " / " - + self.mpr_table["Units"][self.clicked_index[3]] - ) - plt.legend([temp_c, temp_e, temp_g]) - - else: - pass - - plt.show() - - except ValueError: - plt.title("Result Count must match ... ") - print("Result Count must match ... ") - plt.show() - - self.clicked_index.clear() - self.lstatus.setText('') - self.last_selected_row = -1 - - # Function to plot graph in PTR Tab - def plot_graph_ptr(self, selected): - """ - This method is used to plot the graph based on the selected row in the 'PTR' table. - It retrieves the index of the selected row and updates the status label with the selected line number. - - Parameters - ---------- - selected : QItemSelection - The selection object that contains the indexes of the selected cells. - """ - - if len(selected.indexes()) == 0: - self.lstatus.setText('') - return - selectIndex = selected.indexes()[0].row() - # testNo = int(self.tableWidget_ptr.item(selectIndex, 0).text()) - index = selectIndex - self.lstatus.setText(f'ptr line {index+1} selected') - - plt.clf() - plt.autoscale(True) - ltl = str2float(self.tableWidget_ptr.item(selectIndex, TaPtrItems["LTL"]).text()) - utl = str2float(self.tableWidget_ptr.item(selectIndex, TaPtrItems["UTL"]).text()) - results = self.tableWidget_ptr.item(selectIndex, TaPtrItems["Results"]).text()[1:-1].split(" ") - data = [] - for value in results: - value = value[0:value.find(',')] if value.find(',')>0 else value - if value != "": - data.append(str2float(value)) - if ltl != utl: - plt.hlines(ltl, 0, len(data)-1, color="r") - plt.hlines(utl, 0, len(data)-1, color="r") - plt.plot(data, "bo-", markeredgecolor="magenta", markersize=3) - plt.title(self._filename + " \\ " + self.lot + "\n") - plt.xlabel("Part Index") - si = self.tableWidget_ptr.item(selectIndex, TaPtrItems["LTL"]).text().strip() - ylabel = self.tableWidget_ptr.item(selectIndex, TaPtrItems["Test Name"]).text() - if len(si.split(" ")) > 1: - ylabel = f'{ylabel}\n ({si.split(" ")[1]})' - plt.ylabel(ylabel, rotation=90) - self.graph_show() - - @property - def filename(self): - """ Get the current filename. """ - return self._filename - - @filename.setter - def filename(self, name): - status = "" - self.llotid.setText("") - if name == "" and self._filename == "": - self.lfilename.setText("no file loaded") - return - elif name != "": - self._filename = name - self.lfilename.setText(f"{self.path}/{self._filename}") - if not os.path.exists(f"{self.path}/{self._filename}"): - status = "file not exist" - else: - self.lot = STDFHelper.get_lot_id(f"{self.path}/{self._filename}") - self.llotid.setText(self.lot) - self.lstatus.setText(status) - - # Fuction to get the status bar for uploading in QtWindow - def printProgressBar(self, iteration, total, prefix="", suffix="", decimals=1, length=100, fill="█", printEnd="\r"): - """ - Call in a loop to create terminal progress bar - - Parameters - ---------- - iteration : int - Current iteration (Int) - total : int - Total iterations (Int) - prefix : str, optional - Prefix string (Str) - suffix : str, optional - Suffix string (Str) - decimals : int, optional - Positive number of decimals in percent complete (Int) - length : int, optional - Character length of bar (Int) - fill : str, optional - Bar fill character (Str) - printEnd : str, optional - End character (e.g. "\r", "\r\n") (Str) - - Returns - ------- - None. - """ - percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) - filledLength = int(length * iteration // total) - bar = fill * filledLength + "-" * (length - filledLength) - self.update_Progress_bar(iteration, total) - # print(f"\r{prefix} |{bar}| {percent}% {suffix}", end=printEnd) - # if iteration == total: - # print() - - def update_Progress_bar(self, count, maxcount): - """ - This method is used to update the progress bar in the PyQt window. - It sets the range and value of the progress bar based on the current count and maximum count. - It also processes any pending events to ensure that the progress bar is updated in real-time. - - Parameters - ---------- - count : int - The current count or progress value. - maxcount : int - The maximum count or total value for the progress bar. - - Returns - ------- - None. - """ - self.progressBar.setRange(1, maxcount) - self.progressBar.setValue(count) - QCoreApplication.processEvents() - - # Trigger Function to close the window - def close_window(self): - """ This method is used to close the PyQt window. It can be triggered by a button click or any other event that requires the window to be closed. """ - self.close() - - # 'Esc' key event to reset the click counter if unknowingly pressed - def keyPressEvent(self, event): - """ - This method is triggered when a key is pressed. - If the 'Esc' key is pressed, it resets the 'last_selected_row' variable and clears the 'clicked_index' list. - It also updates the status label to indicate that no line is selected. - If the 'Return' key is pressed, it calls the 'load_IC_data' method to load the IC data into the table. - - Parameters - ---------- - event : QKeyEvent - The key event that triggered this method. - """ - print("Esc") - if event is None or event.key() == Qt.Key_Escape: - self.last_selected_row = -1 - self.clicked_index.clear() - self.lstatus.setText('') - elif event is not None and event.key() == Qt.Key_Return: - self.load_IC_data() - - -if __name__ == "__main__": - from IPython import get_ipython - - get_ipython().run_line_magic('matplotlib', 'qt') # or 'inline' - app = QApplication(sys.argv) - mainwindow = Test_Results() - widget = QtWidgets.QStackedWidget() - widget.addWidget(mainwindow) - widget.setWindowTitle("Semi-ATE Test Results") - widget.resize(1920, 960) - mainwindow.open_files() - widget.show() - try: - sys.exit(app.exec_()) - except Exception: - print("File Closed ...") diff --git a/pylab_ml/plugins/stdf_browser/widgets/test_results.py b/pylab_ml/plugins/stdf_browser/widgets/test_results.py new file mode 100644 index 00000000..dfede23e --- /dev/null +++ b/pylab_ml/plugins/stdf_browser/widgets/test_results.py @@ -0,0 +1,988 @@ +# -*- coding: utf-8 -*- + +""" +This script contains the 'showStdf' class which is used to convert the '.stdf' file into '.hdf5' file and +then preprocess the data to fill in the 'QTableWidget' in the PyQt window. It also contains the 'Test_Results' class +which is used to display the preprocessed data in the PyQt window and also to generate graphs from the data. +""" + +# Standard library imports +import json +import sys +import os + +# Third library imports +from qtpy import PYQT5 +from qtpy.QtCore import Signal, Qt, QCoreApplication +from qtpy.QtWidgets import (QApplication, QWidget, QFileDialog, QMenu, + QTableWidgetItem, QVBoxLayout) +from matplotlib.figure import Figure +from matplotlib.backends.backend_qtagg import ( + FigureCanvasQTAgg as FigureCanvas, + NavigationToolbar2QT as NavigationToolbar) +from qtpy.uic import loadUi +from qtpy import QtWidgets, QtGui +from Metis.tools import STDFHelper +from PIL import Image +import matplotlib.pyplot as plt +import pandas as pd +import numpy as np + +# spyder library imports +from spyder.api.widgets.mixins import SpyderWidgetMixin + +from pylab_ml.plugins.stdf_browser.widgets.showstdf import showStdf, str2float + +__version__ = "0.0.6" + + +TaPtrItems = { + "TestNo": 0, + "Test Name": 1, + "LSL": 2, + "LTL": 3, + "Results": 4, + "empty1": 5, + "IC 1": 6, + "IC 2": 7, + "IC 3": 8, + "empty2": 9, + "UTL": 10, + "USL": 11, + "Mean": 12, + "Min": 13, + "Max": 14, + "RMS": 15, + "Test Failed": 16, + "ICFailed": 17, +} + + +class PlotWindow(QWidget): + """Eigenständiges, wiederverwendbares Fenster mit Matplotlib-Canvas.""" + + def __init__(self, parent=None): + super().__init__(parent, Qt.Window) + self.setWindowTitle("STDF Plot") + self.figure = Figure(figsize=(6.4, 4.8), dpi=100, tight_layout=True) + self.canvas = FigureCanvas(self.figure) + self.toolbar = NavigationToolbar(self.canvas, self) + + layout = QVBoxLayout(self) + layout.addWidget(self.toolbar) + layout.addWidget(self.canvas) + self.resize(800, 600) + + def new_axes(self): + """Figur leeren und neue Achse zurückgeben.""" + self.figure.clear() + return self.figure.add_subplot(111) + + def refresh(self): + """Neu zeichnen und Fenster anzeigen (ohne der Tabelle den Fokus zu nehmen).""" + self.canvas.draw_idle() + if not self.isVisible(): + self.show() + self.raise_() + + +class TableWidget(QTableWidgetItem): + """Custom QTableWidgetItem for handling numeric comparisons.""" + def __lt__(self, other): + try: + return float(self.text()) < float(other.text()) + except Exception: + return QTableWidgetItem.__lt__(self, other) + + +class Test_Results(QWidget, SpyderWidgetMixin): + """ + This class is used to display the preprocessed data in the PyQt window and also to generate graphs from the data. + It inherits from QWidget and SpyderWidgetMixin to create a custom widget for displaying test results. + """ + sig_data_changed = Signal() + + + def __init__(self, parent=None, background_color=None): + """ + Initializes the Test_Results class and loads the UI file developed in QtDesigner. + It also sets up the necessary variables and connects the signals to the respective functions. + + Parameters + ---------- + parent : QWidget, optional + The parent widget of this Test_Results widget. If None, it will be a top-level window. + background_color : str, optional + The background color of the widget. If None, the default color will be used. + """ + if PYQT5: + super().__init__(parent=parent, class_parent=parent) + else: + QWidget.__init__(self, parent) + SpyderWidgetMixin.__init__(self, class_parent=parent) + + # Loading 'ui' files developed in 'QtDesigner' + loadUi(__file__.replace(".py", ".ui"), self) + + self.path = "" + self._filename = "" + self.lot = "" + self.ptr_table = pd.DataFrame() + self.mpr_table = pd.DataFrame() + self.last_selected_row = -1 + self.clicked_index = [] + self.plot_window = None + self._updating = False + + self.filename = "" + self.adjustUI() + self._connect_signals() + + def _connect_signals(self): + # currentCellChanged reagiert auf Maus UND Tastatur + self.tableWidget_ptr.currentCellChanged.connect(self._on_ptr_cell_changed) + self.tableWidget_mpr.currentCellChanged.connect(self._on_mpr_cell_changed) + # Klick auf bereits gewählte Zeile: geschlossenes Plotfenster wieder zeigen + self.tableWidget_ptr.cellClicked.connect(self._reshow_plot_window) + self.tableWidget_mpr.cellClicked.connect(self._reshow_plot_window) + + self.enter_filter_test_name_ptr.textChanged.connect(self.filter_test_name_ptr) + self.enter_filter_test_name_mpr.textChanged.connect(self.filter_test_name_mpr) + self.tabWidget.currentChanged.connect(lambda _: self.keyPressEvent(None)) + + def adjustUI(self): + """ This method is used to adjust the UI elements of the PyQt window, such as setting the column width of the 'QTableWidget' and hiding the progress bar and status labels.""" + self.set_column_width() + self.progressBar.hide() + self.lstatus.setText("") + self.llotid.setText("") + + def clear_data(self): + """ Geladene Daten verwerfen (-> Spyder zeigt das Leerbild). """ + self.clear_tables() + self.ptr_table = pd.DataFrame() + self.mpr_table = pd.DataFrame() + self.keyPressEvent(None) + if self.plot_window is not None: + self.plot_window.close() + self.sig_data_changed.emit() + + def open_files(self, fname=""): + """ + This method is used to open the '.stdf' file and load the data into the PyQt window. + + Parameters + ---------- + fname : str, optional + The path to the '.stdf' file. If not provided, a file dialog will be opened to select the file. + + Returns + ------- + bool + True if the file was successfully opened and data was loaded, False otherwise. + """ + path = self.path or os.getcwd() + if not fname: + fname, _ = QFileDialog.getOpenFileName( + self, "Open STDF File", path, "stdf Files (*.stdf *.std)") + if not fname: + return False + if not os.path.exists(fname): + return False + + self.path, self.filename = os.path.split(fname) + self.progressBar.show() + QCoreApplication.processEvents() + try: + if not self.loaddata(): + return False + self._updating = True + self.keyPressEvent(None) + self._fill_tables() + finally: + self._updating = False + self.progressBar.hide() + + self.sig_data_changed.emit() + return True + + def clear_tables(self): + """Beide Tabellen vollständig leeren.""" + for table in (self.tableWidget_ptr, self.tableWidget_mpr): + table.clearSelection() + table.clearContents() + table.setRowCount(0) + + def _fill_tables(self): + tables = [self.tableWidget_ptr, self.tableWidget_mpr] + # Sortierung während des Füllens AUS, sonst springen Zeilen bei setItem() + sorting = [(t, t.isSortingEnabled()) for t in tables] + for t in tables: + t.setSortingEnabled(False) + + self.clear_tables() + self.fill_ptr_data() + self.fill_mpr_data() + self.set_column_width() + self.colour_pass_fail_ptr_data() + if self.has_mpr(): + self.colour_pass_fail_mpr_data() + + for t, enabled in sorting: + t.setSortingEnabled(enabled) + + # Evtl. eingegebene Filter erneut anwenden + self.filter_test_name_ptr(self.enter_filter_test_name_ptr.text()) + self.filter_test_name_mpr(self.enter_filter_test_name_mpr.text()) + + def fill_ptr_data(self): + """ + This method is used to fill the 'PTR' data in the 'QTableWidget' in the PyQt window. + It iterates through the columns of the 'ptr_table' DataFrame and sets the values in the corresponding cells of the 'QTableWidget'. + It also updates the progress bar to indicate the progress of filling the data. + """ + table = self.tableWidget_ptr + columns = list(self.ptr_table.columns[0:5]) + list(self.ptr_table.columns[5:13]) + targets = list(range(0, 5)) + list(range(10, 18)) # siehe TaPtrItems + table.setRowCount(len(self.ptr_table)) + + for n, (column, col) in enumerate(zip(columns, targets), start=1): + for row, val in enumerate(self.ptr_table[column].tolist()): + item = TableWidget(str(val)) + if col == 0: + item.setData(Qt.UserRole, row) # DataFrame-Position merken + table.setItem(row, col, item) + self.printProgressBar(n, len(columns)) + + def fill_mpr_data(self): + """ + This method is used to fill the 'MPR' data in the 'QTableWidget' in the PyQt window. + It iterates through the columns of the 'mpr_table' DataFrame and sets the values in the corresponding cells of the 'QTableWidget'. + It also updates the progress bar to indicate the progress of filling the data. + """ + table = self.tableWidget_mpr + if not self.has_mpr(): + table.setRowCount(1) + table.setItem(0, 2, QTableWidgetItem("MPR data is empty")) + return + + columns = list(self.mpr_table.columns[0:14]) + table.setRowCount(len(self.mpr_table)) + for col, column in enumerate(columns): + for row, val in enumerate(self.mpr_table[column].tolist()): + item = TableWidget(str(val)) + if col == 0: + item.setData(Qt.UserRole, row) + table.setItem(row, col, item) + self.printProgressBar(col + 1, len(columns)) + + def has_data(self): + return isinstance(self.ptr_table, pd.DataFrame) and not self.ptr_table.empty + + def has_mpr(self): + return (isinstance(self.mpr_table, pd.DataFrame) + and "Results" in self.mpr_table.columns + and not self.mpr_table.empty) + + # To load Pandas dataframes + def loaddata(self): + """ + This method is used to load the data from the '.hdf5' file into Pandas DataFrames. + It uses the 'showStdf' class to read the data and preprocess it for further analysis. + + Returns + ------- + bool + True if the data was successfully loaded, False otherwise. + """ + print(f"Test_Results.loaddata : {self.path, self.filename, self.lot}") + self.hdf5_data = showStdf(self.path, self.filename, self.lot, "result_h5", update_Progress_bar=self.update_Progress_bar) + if not self.hdf5_data.init(): + self.lfilename.setText(f".../{self.filename} is not a valid stdf file") + return False + self.table_data = self.hdf5_data.raw_hdf5_data() + self.ptr_table = self.table_data[0] + self.mpr_table = self.table_data[1] + return True + + # To generate '.png' images from the '.json' file + def generate_graph_from_json(self): + """ + This method is used to generate graphs from the data stored in a '.json' file. + It reads the JSON file, processes the data, and creates plots using Matplotlib. + + Returns + ------- + bool + True if the graphs were successfully generated, False otherwise. + """ + try: + # Load the '.json' file + jname = QFileDialog().getOpenFileName(self, "Open File", os.getcwd(), "JSON files (*.json)") + with open(jname[0], "r") as f: + self.json_data = json.load(f) + + temp_folder = "STDF_Graph_Folder" + self.graph_folder = os.path.join(self.path, temp_folder) + + # If directory doesn't exist, then create it + if not os.path.exists(self.graph_folder): + os.makedirs(self.graph_folder) + try: + for i in range(0, len(self.json_data)): + if "y" not in self.json_data[str(i)]: + temp_a = self.mpr_table["Results"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][ + self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["x"][1] + ].tolist() + temp_b = self.mpr_table["MPR.LO_LIMIT"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][0] + temp_c = self.mpr_table["MPR.HI_LIMIT"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][0] + temp_d = self.mpr_table["Min_Value"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][ + self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["x"][1] + ] + temp_e = self.mpr_table["Max_Value"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][ + self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["x"][1] + ] + temp_f = self.mpr_table["Mean_Value"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][ + self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["x"][1] + ] + temp_g = self.mpr_table["Result_Count"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][0] + temp_h = str(self.mpr_table["Units"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][0]) + plt.plot(temp_a[0], "bo", markersize=1) + plt.hlines(temp_b, 0, temp_g, color="r") + plt.hlines(temp_c, 0, temp_g, color="r") + plt.hlines(temp_d, 0, temp_g, color="m") + plt.hlines(temp_e, 0, temp_g, color="m") + plt.hlines(temp_f, 0, temp_g, color="y") + plt.title(self.json_data[str(i)]["title"]) + plt.ylabel(temp_h) + + if "y" in self.json_data[str(i)]: + temp_a = self.mpr_table["Results"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][ + self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["x"][1] + ].tolist() + temp_b = self.mpr_table["Results"][self.mpr_table["Test"] == self.json_data[str(i)]["y"][0]][ + self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["y"][1] + ].tolist() + temp_c = ( + self.json_data[str(i)]["x"][0] + + "[" + + str(self.json_data[str(i)]["x"][1]) + + "]" + + " vs " + + self.json_data[str(i)]["y"][0] + + "[" + + str(self.json_data[str(i)]["y"][1]) + + "]" + ) + temp_d = str(self.mpr_table["Units"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][0]) + temp_e = str(self.mpr_table["Units"][self.mpr_table["Test"] == self.json_data[str(i)]["y"][0]][0]) + plt.plot(temp_a[0], temp_b[0], "bo", markersize=1) + plt.xlabel(temp_d) + plt.ylabel(temp_e) + plt.title(self.json_data[str(i)]["title"]) + plt.legend([temp_c]) + + if "y1" in self.json_data[str(i)]: + temp_a = self.mpr_table["Results"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][ + self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["x"][1] + ].tolist() + temp_b = self.mpr_table["Results"][self.mpr_table["Test"] == self.json_data[str(i)]["y1"][0]][ + self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["y1"][1] + ].tolist() + temp_c = ( + self.json_data[str(i)]["x"][0] + + "[" + + str(self.json_data[str(i)]["x"][1]) + + "]" + + " vs " + + self.json_data[str(i)]["y"][0] + + "[" + + str(self.json_data[str(i)]["y"][1]) + + "]" + ) + temp_d = ( + self.json_data[str(i)]["x"][0] + + "[" + + str(self.json_data[str(i)]["x"][1]) + + "]" + + " vs " + + self.json_data[str(i)]["y1"][0] + + "[" + + str(self.json_data[str(i)]["y1"][1]) + + "]" + ) + plt.plot(temp_a[0], temp_b[0], "go", markersize=1) + plt.legend([temp_c, temp_d]) + + if "y2" in self.json_data[str(i)]: + temp_a = self.mpr_table["Results"][self.mpr_table["Test"] == self.json_data[str(i)]["x"][0]][ + self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["x"][1] + ].tolist() + temp_b = self.mpr_table["Results"][self.mpr_table["Test"] == self.json_data[str(i)]["y2"][0]][ + self.mpr_table["PART_INDEX"] == self.json_data[str(i)]["y2"][1] + ].tolist() + temp_c = ( + self.json_data[str(i)]["x"][0] + + "[" + + str(self.json_data[str(i)]["x"][1]) + + "]" + + " vs " + + self.json_data[str(i)]["y"][0] + + "[" + + str(self.json_data[str(i)]["y"][1]) + + "]" + ) + temp_d = ( + self.json_data[str(i)]["x"][0] + + "[" + + str(self.json_data[str(i)]["x"][1]) + + "]" + + " vs " + + self.json_data[str(i)]["y1"][0] + + "[" + + str(self.json_data[str(i)]["y1"][1]) + + "]" + ) + temp_e = ( + self.json_data[str(i)]["x"][0] + + "[" + + str(self.json_data[str(i)]["x"][1]) + + "]" + + " vs " + + self.json_data[str(i)]["y2"][0] + + "[" + + str(self.json_data[str(i)]["y2"][1]) + + "]" + ) + plt.plot(temp_a[0], temp_b[0], "ro", markersize=1) + plt.legend([temp_c, temp_d, temp_e]) + + # Filename is assigned as the 'title' key in the '.json' file + filename = self.json_data[str(i)]["title"] + ".png" + plt.savefig(os.path.join(self.graph_folder, filename)) + self.printProgressBar(i, len(self.json_data) - 1, prefix="Graph Generation:", suffix="Complete", length=50) + plt.clf() + self.generate_pdf() + except Exception: + print("There is no MPR data to plot the graph or the plots already exists ...") + except Exception: + print("Select the JSON file correctly ...") + + # Function to generate the '.pdf' files containing all the images + def generate_pdf(self): + """ + This method is used to generate a PDF file containing all the images in a folder. + It reads all the images in the specified folder, converts them to RGB format, and saves them as a single PDF file. + """ + + # Empty list to append all the images in a folder + image_pdf_list = [] + + for i in os.listdir(self.graph_folder): + global img_rgb + image_file = os.path.join(self.graph_folder, i) + + # Open an Image + img = Image.open(image_file) + + # Convert the Image to a 'RGB' format + img_rgb = img.convert("RGB") + image_pdf_list.append(img_rgb) + + # Remove the image at the last index of the folder + image_pdf_list.pop(-1) + + # Create a PDF folder to store the '.pdf' file + pdf_directory = "PDF/" + pdf_path = os.path.join(self.graph_folder, pdf_directory) + + if not os.path.exists(pdf_path): + os.makedirs(pdf_path) + + pdf_file = "STDF_Graph_" + self.lot + ".pdf" + + # Save the PDF file + img_rgb.save(pdf_path + pdf_file, save_all=True, append_images=image_pdf_list) + + def filter_test_name_ptr(self, filter_test): + """ + This method is used to filter the 'PTR' data in the 'QTableWidget' based on the test name. + It hides the rows that do not match the specified filter. + + Parameters + ---------- + filter_test : str + The test name to filter the data by. If an empty string is provided, all rows will be shown. + + Returns + ------- + None. + """ + + temp = [] + self.keyPressEvent(None) + if filter_test == '': + for i in range(self.tableWidget_ptr.rowCount()): + self.tableWidget_ptr.setRowHidden(i, False) + else: + for i in range(self.tableWidget_ptr.rowCount()): + item = self.tableWidget_ptr.item(i, 1) + if item is None: + continue + match = filter_test.lower() in item.text().lower() + if match: + temp.append(i) + self.tableWidget_ptr.setRowHidden(i, True) + + if temp == []: + for i in range(self.tableWidget_ptr.rowCount()): + self.tableWidget_ptr.setRowHidden(i, True) + + for val in temp: + self.tableWidget_ptr.setRowHidden(val, False) + + def filter_test_name_mpr(self, filter_test): + """ + This method is used to filter the 'MPR' data in the 'QTableWidget' based on the test name. + It hides the rows that do not match the specified filter. + + Parameters + ---------- + filter_test : str + The test name to filter the data by. If an empty string is provided, all rows will be shown. + + Returns + ------- + None. + """ + temp = [] + self.keyPressEvent(None) + if filter_test == '': + for i in range(self.tableWidget_mpr.rowCount()): + self.tableWidget_mpr.setRowHidden(i, False) + else: + for i in range(self.tableWidget_mpr.rowCount()): + item = self.tableWidget_mpr.item(i, 2) + if item is None: + continue + match = filter_test.lower() in item.text().lower() + if match: + temp.append(i) + self.tableWidget_mpr.setRowHidden(i, True) + + if temp == []: + for i in range(self.tableWidget_mpr.rowCount()): + self.tableWidget_mpr.setRowHidden(i, True) + + for val in temp: + self.tableWidget_mpr.setRowHidden(val, False) + + def load_IC_data(self): + """ + This method is used to load the IC data into the 'QTableWidget' in the PyQt window. + It retrieves the selected IC values from the input fields and updates the corresponding cells in the table. + It also highlights the cells that are out of the specified limits. + """ + try: + selected_IC1 = int(self.ic_Number1.text()) - 1 + except Exception: + selected_IC1 = 100000 + try: + selected_IC2 = int(self.ic_Number2.text()) - 1 + except Exception: + selected_IC2 = 100000 + try: + selected_IC3 = int(self.ic_Number3.text()) - 1 + except Exception: + selected_IC3 = 100000 + + self.tableWidget_ptr.sortItems(0) + + for i in range(0, len(self.ptr_table)): + ltl = str2float(self.ptr_table["LTL"][i]) + utl = str2float(self.ptr_table["UTL"][i]) + try: + if len(self.ptr_table["Result_Append"][i]) > (selected_IC1): + val = self.ptr_table["Result_Append"][i][selected_IC1] + self.tableWidget_ptr.setItem(i, 6, QtWidgets.QTableWidgetItem(str(val))) + if ltl != utl and ((self.ptr_table["Result_Append"][i][selected_IC1] < ltl) or ( + self.ptr_table["Result_Append"][i][selected_IC1] > utl)): + self.tableWidget_ptr.item(i, 6).setBackground(QtGui.QColor(255, 0, 0)) + else: + self.tableWidget_ptr.setItem(i, 6, QtWidgets.QTableWidgetItem("NA")) + + if len(self.ptr_table["Result_Append"][i]) > (selected_IC2): + val = self.ptr_table["Result_Append"][i][selected_IC2] + self.tableWidget_ptr.setItem(i, 7, QtWidgets.QTableWidgetItem(str(val))) + if ltl != utl and ((self.ptr_table["Result_Append"][i][selected_IC2] < ltl) or ( + self.ptr_table["Result_Append"][i][selected_IC2] > utl)): + self.tableWidget_ptr.item(i, 7).setBackground(QtGui.QColor(255, 0, 0)) + else: + self.tableWidget_ptr.setItem(i, 7, QtWidgets.QTableWidgetItem("NA")) + + if len(self.ptr_table["Result_Append"][i]) > (selected_IC3): + val = self.ptr_table["Result_Append"][i][selected_IC3] + self.tableWidget_ptr.setItem(i, 8, QtWidgets.QTableWidgetItem(str(val))) + if ltl != utl and ((self.ptr_table["Result_Append"][i][selected_IC3] < ltl) or ( + self.ptr_table["Result_Append"][i][selected_IC3] > utl)): + self.tableWidget_ptr.item(i, 8).setBackground(QtGui.QColor(255, 0, 0)) + else: + self.tableWidget_ptr.setItem(i, 8, QtWidgets.QTableWidgetItem("NA")) + except Exception: + pass + + # Assigning desiered column width to particular columns + def set_column_width(self): + """ + This method is used to set the column width of the 'QTableWidget' in the PyQt window. + It assigns specific widths to each column based on the content and importance of the data. + It also sets a minimum section size for the horizontal header to ensure that the columns are not too narrow. + """ + self.tableWidget_ptr.horizontalHeader().setMinimumSectionSize(10) + self.tableWidget_ptr.setColumnWidth(TaPtrItems["TestNo"], 50) + self.tableWidget_ptr.setColumnWidth(TaPtrItems["Test Name"], 180) + self.tableWidget_ptr.setColumnWidth(TaPtrItems["LSL"], 75) + self.tableWidget_ptr.setColumnWidth(TaPtrItems["LTL"], 75) + self.tableWidget_ptr.setColumnWidth(TaPtrItems["Results"], 150) + self.tableWidget_ptr.setColumnWidth(TaPtrItems["IC 1"], 30) + self.tableWidget_ptr.setColumnWidth(TaPtrItems["IC 2"], 30) + self.tableWidget_ptr.setColumnWidth(TaPtrItems["IC 3"], 30) + self.tableWidget_ptr.setColumnWidth(TaPtrItems["empty1"], 10) + self.tableWidget_ptr.setColumnWidth(TaPtrItems["empty2"], 10) + self.tableWidget_ptr.setColumnWidth(TaPtrItems["UTL"], 75) + self.tableWidget_ptr.setColumnWidth(TaPtrItems["USL"], 75) + self.tableWidget_ptr.setColumnWidth(TaPtrItems["Test Failed"], 80) + for j in range(0, len(self.ptr_table)): + self.tableWidget_ptr.setItem(j, TaPtrItems["empty1"], QtWidgets.QTableWidgetItem()) + self.tableWidget_ptr.item(j, TaPtrItems["empty1"]).setBackground(QtGui.QColor(240, 240, 240)) + self.tableWidget_ptr.setItem(j, TaPtrItems["empty2"], QtWidgets.QTableWidgetItem()) + self.tableWidget_ptr.item(j, TaPtrItems["empty2"]).setBackground(QtGui.QColor(240, 240, 240)) + + self.tableWidget_mpr.setColumnWidth(6, 300) + + # To Colour values based on whether test has been passed (PTR Table) + def colour_pass_fail_ptr_data(self): + """ + This method is used to color the values in the 'PTR' table based on whether the test has been passed or failed. + It iterates through the rows of the 'ptr_table' DataFrame and checks the values in the 'Test_Failed' column. + If the value is '0', it means the test has passed, and the corresponding cells are colored green. + If the value is not '0', it means the test has failed, and the corresponding cells are colored red. + Additionally, if there are any IC values that are out of limits, they are colored yellow. + """ + + for j in range(0, len(self.ptr_table)): + # If values in the 'Test_Failed' column is '0' then test Passed + if self.ptr_table["Test_Failed"][j] == 0: + + # Green Colour if test is passed + # self.tableWidget_ptr.item(j, TaPtrItems["Results"]).setForeground(QtGui.QColor(0, 255, 0)) + self.tableWidget_ptr.item(j, TaPtrItems["Test Failed"]).setForeground(QtGui.QColor(0, 255, 0)) + pass + else: + + # Red Colour if test is failed + self.tableWidget_ptr.item(j, TaPtrItems["Test Name"]).setForeground(QtGui.QColor(255, 0, 0)) + self.tableWidget_ptr.item(j, TaPtrItems["Results"]).setForeground(QtGui.QColor(255, 0, 0)) + self.tableWidget_ptr.item(j, TaPtrItems["Test Failed"]).setForeground(QtGui.QColor(255, 0, 0)) + + # Yellow Colour in the IC# Failed + self.tableWidget_ptr.item(j, TaPtrItems["ICFailed"]).setForeground(QtGui.QColor(255, 255, 0)) + + # To Colour values based on whether test has been passed (MPR Table) + def colour_pass_fail_mpr_data(self): + """ + This method is used to color the values in the 'MPR' table based on whether the test has been passed or failed. + It iterates through the rows of the 'mpr_table' DataFrame and checks the values in the 'Test_Failed' column. + If the value is '0', it means the test has passed, and the corresponding cells are colored green. + If the value is not '0', it means the test has failed, and the corresponding cells are colored red. + """ + for j in range(0, len(self.mpr_table)): + + # If values in the 'Test_Failed' column is '0' then test Passed + if self.mpr_table["Test_Failed"][j] == 0: + + # Green Colour if test is passed + self.tableWidget_mpr.item(j, 6).setForeground(QtGui.QColor(0, 255, 0)) + self.tableWidget_mpr.item(j, 13).setForeground(QtGui.QColor(0, 255, 0)) + else: + + # Red Colour if test is failed + self.tableWidget_mpr.item(j, 1).setForeground(QtGui.QColor(255, 0, 0)) + self.tableWidget_mpr.item(j, 6).setForeground(QtGui.QColor(255, 0, 0)) + self.tableWidget_mpr.item(j, 13).setForeground(QtGui.QColor(255, 0, 0)) + + @property + def filename(self): + """ Get the current filename. """ + return self._filename + + @filename.setter + def filename(self, name): + status = "" + self.llotid.setText("") + if name == "" and self._filename == "": + self.lfilename.setText("no file loaded") + return + elif name != "": + self._filename = name + self.lfilename.setText(f"{self.path}/{self._filename}") + if not os.path.exists(f"{self.path}/{self._filename}"): + status = "file not exist" + else: + self.lot = STDFHelper.get_lot_id(f"{self.path}/{self._filename}") + self.llotid.setText(self.lot) + self.lstatus.setText(status) + + # Fuction to get the status bar for uploading in QtWindow + def printProgressBar(self, iteration, total, prefix="", suffix="", decimals=1, length=100, fill="█", printEnd="\r"): + """ + Call in a loop to create terminal progress bar + + Parameters + ---------- + iteration : int + Current iteration (Int) + total : int + Total iterations (Int) + prefix : str, optional + Prefix string (Str) + suffix : str, optional + Suffix string (Str) + decimals : int, optional + Positive number of decimals in percent complete (Int) + length : int, optional + Character length of bar (Int) + fill : str, optional + Bar fill character (Str) + printEnd : str, optional + End character (e.g. "\r", "\r\n") (Str) + + Returns + ------- + None. + """ + # percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) + # filledLength = int(length * iteration // total) + # bar = fill * filledLength + "-" * (length - filledLength) + self.update_Progress_bar(iteration, total) + + def update_Progress_bar(self, count, maxcount): + """ + This method is used to update the progress bar in the PyQt window. + It sets the range and value of the progress bar based on the current count and maximum count. + It also processes any pending events to ensure that the progress bar is updated in real-time. + + Parameters + ---------- + count : int + The current count or progress value. + maxcount : int + The maximum count or total value for the progress bar. + + Returns + ------- + None. + """ + self.progressBar.setRange(1, maxcount) + self.progressBar.setValue(count) + QCoreApplication.processEvents() + + # Trigger Function to close the window + def close_window(self): + """ This method is used to close the PyQt window. It can be triggered by a button click or any other event that requires the window to be closed. """ + self.close() + + # ---- Hilfsfunktionen + @staticmethod + def _df_index(table, row): + """DataFrame-Position zu einer (evtl. sortierten) Tabellenzeile.""" + item = table.item(row, 0) + if item is None: + return None + idx = item.data(Qt.UserRole) + return None if idx is None else int(idx) + + @staticmethod + def _limit(text): + try: + return str2float(str(text)) + except (ValueError, IndexError): + return None # z.B. leere Grenze ("inf" wurde zu "") + + def _get_plot_window(self): + if self.plot_window is None: + self.plot_window = PlotWindow(self) + return self.plot_window + + def _reshow_plot_window(self, row, col): + if self.plot_window is not None and not self.plot_window.isVisible(): + self.plot_window.refresh() + + # ---- PTR + def _on_ptr_cell_changed(self, row, col, prev_row, prev_col): + if self._updating or row < 0 or row == prev_row: + return + self.plot_ptr_row(row) + + def plot_ptr_row(self, row): + idx = self._df_index(self.tableWidget_ptr, row) + if idx is None: + return + rec = self.ptr_table.iloc[idx] + self.lstatus.setText(f"ptr line {row + 1} selected") + + data = np.asarray(rec["Result_Append"], dtype=float) + ltl, utl = self._limit(rec["LTL"]), self._limit(rec["UTL"]) + + pw = self._get_plot_window() + ax = pw.new_axes() + if ltl != utl: # ltl == utl == 0 -> keine Grenzen + for lim in (ltl, utl): + if lim is not None: + ax.axhline(lim, color="r") + ax.plot(data, "bo-", markeredgecolor="magenta", markersize=3) + ax.set_title(f"{self.filename} \\ {self.lot}") + ax.set_xlabel("Part Index") + + ylabel = str(rec["Test"]) + parts = str(rec["LTL"]).split() + if len(parts) > 1: + ylabel += f"\n({parts[1]})" + elif rec.get("PTR.UNITS"): + ylabel += f"\n({rec['PTR.UNITS']})" + ax.set_ylabel(ylabel) + pw.refresh() + + # ---- MPR + def _on_mpr_cell_changed(self, row, col, prev_row, prev_col): + if self._updating or row < 0: + return + idx = self._df_index(self.tableWidget_mpr, row) + if idx is None: + return + self.last_selected_row = idx # DataFrame-Index, nicht sichtbare Zeile + if row != prev_row: + self.plot_mpr([idx]) + + def plot_mpr(self, indices): + if not self.has_mpr() or not indices: + return + pw = self._get_plot_window() + ax = pw.new_axes() + try: + self._draw_mpr(ax, indices[:4]) + except ValueError: + ax.clear() + ax.set_title("Result Count must match ...") + pw.refresh() + + def _draw_mpr(self, ax, idx): + t = self.mpr_table + title = f"{self.filename} \\ {self.lot}" + + if len(idx) == 1: + i = idx[0] + count = t["Result_Count"][i] + for lim in (t["MPR.LO_LIMIT"][i], t["MPR.HI_LIMIT"][i]): + if np.isfinite(lim): + ax.hlines(lim, 0, count, color="r") + ax.hlines([t["Min_Value"][i], t["Max_Value"][i]], 0, count, color="m") + ax.hlines(t["Mean_Value"][i], 0, count, color="y") + ax.plot(t["Results"][i], "bo-", markeredgecolor="magenta", markersize=1) + ax.set_title(title) + ax.set_ylabel(f'{t["Test"][i]}\n({t["Units"][i]})') + + elif len(idx) == 2: + for i, fmt in zip(idx, ("go-", "ro-")): + ax.plot(t["Results"][i], fmt, markersize=0.3, alpha=0.5, + label=t["Test"][i]) + ax.set_title(title) + ax.set_ylabel(t["Units"][idx[0]]) + ax.legend() + + else: # 3 oder 4: erste Auswahl = x, weitere = y + def lab(i): + return f'{t["Units"][i]}[{t["PART_INDEX"][i]}]' + x = t["Results"][idx[0]] + for i, fmt in zip(idx[1:], ("go", "ro", "yo")): + ax.plot(x, t["Results"][i], fmt, markersize=1, alpha=0.5, + label=f"{lab(idx[0])} vs {lab(i)}") + ax.set_title(f'{title}\n{t["Test"][idx[0]]}') + ax.set_xlabel(t["Units"][idx[0]]) + ax.set_ylabel(" / ".join(str(t["Units"][i]) for i in idx[1:])) + ax.legend() + + def graph_show(self): + """This method is used to plot the graph based on the selected rows in the 'MPR' table. + It checks the number of selected rows and plots the graph accordingly.""" + indices = list(self.clicked_index) + if not indices and self.last_selected_row >= 0: + indices = [self.last_selected_row] + self.plot_mpr(indices) + self.clicked_index.clear() + self.lstatus.setText("") + + def contextMenuEvent(self, event): + """ + This method is triggered when the user right-clicks on the 'MPR' table. + It checks if any row is selected and opens a context menu with options to plot a graph or add a graph. + + Parameters + ---------- + event : QContextMenuEvent + The context menu event that triggered this method. + """ + if not (self.tableWidget_mpr.isVisible() and self.has_mpr()): + return + if not self.tableWidget_mpr.selectionModel().selection().indexes(): + return + menu = QMenu(self) + plot_action = menu.addAction("Plot Graph") if self.clicked_index else None + add_action = menu.addAction("Add Graph") + action = menu.exec_(self.mapToGlobal(event.pos())) + if action is None: # Menü abgebrochen + return + if action is plot_action: + self.graph_show() + elif (action is add_action and self.last_selected_row != -1 + and self.last_selected_row not in self.clicked_index): + self.clicked_index.append(self.last_selected_row) + self.lstatus.setText( + f"line {[i + 1 for i in self.clicked_index]} selected") + + def keyPressEvent(self, event): + """ + This method is triggered when a key is pressed. + If the 'Esc' key is pressed, it resets the 'last_selected_row' variable and clears the 'clicked_index' list. + It also updates the status label to indicate that no line is selected. + If the 'Return' key is pressed, it calls the 'load_IC_data' method to load the IC data into the table. + + Parameters + ---------- + event : QKeyEvent + The key event that triggered this method. + """ + print("Esc") + if event is None or event.key() == Qt.Key_Escape: + self.last_selected_row = -1 + self.clicked_index.clear() + self.lstatus.setText("") + elif event.key() == Qt.Key_Return: + self.load_IC_data() + +if __name__ == "__main__": + from IPython import get_ipython + + get_ipython().run_line_magic('matplotlib', 'qt') # or 'inline' + app = QApplication(sys.argv) + mainwindow = Test_Results() + widget = QtWidgets.QStackedWidget() + widget.addWidget(mainwindow) + widget.setWindowTitle("Semi-ATE Test Results") + widget.resize(1920, 960) + mainwindow.open_files() + widget.show() + try: + sys.exit(app.exec_()) + except Exception: + print("File Closed ...") From 5013b13c95b17c24f3e251e2dcda421601f9cbf0 Mon Sep 17 00:00:00 2001 From: heli2src Date: Thu, 12 Nov 2026 18:36:50 +0100 Subject: [PATCH 08/12] rewrite plot selection for mpr data --- .../stdf_browser/widgets/main_widget.py | 38 +-- .../plugins/stdf_browser/widgets/showstdf.py | 262 +++++++++--------- .../stdf_browser/widgets/test_results.py | 249 +++++++++++------ .../widgets/{showstdf.ui => test_results.ui} | 0 4 files changed, 311 insertions(+), 238 deletions(-) rename pylab_ml/plugins/stdf_browser/widgets/{showstdf.ui => test_results.ui} (100%) diff --git a/pylab_ml/plugins/stdf_browser/widgets/main_widget.py b/pylab_ml/plugins/stdf_browser/widgets/main_widget.py index 9f320582..9d99e481 100644 --- a/pylab_ml/plugins/stdf_browser/widgets/main_widget.py +++ b/pylab_ml/plugins/stdf_browser/widgets/main_widget.py @@ -76,13 +76,10 @@ def __init__(self, name=None, plugin=None, parent=None): self.set_content_widget(self.widget) self.widget.sig_data_changed.connect(self._on_data_changed) + self.widget.sig_mpr_selection_changed.connect(self.update_actions) self.show_empty_message() - # Resize to a huge width to get the right size of the thumbnail - # scrollbar at startup. - # self.resize(50000, self.height()) - # ---- PluginMainWidget API # ------------------------------------------------------------------------ def get_title(self): @@ -161,44 +158,25 @@ def setup(self): def update_actions(self): """ Update the enabled/disabled state of actions based on the current context. """ - has_file = self._has_file() - has_data = self._has_data() - states = { StdfWidgetActions.Import: True, - StdfWidgetActions.Reload: bool(self.widget.filename), # only if the file known - StdfWidgetActions.Graph: self.weidgt.has_mpr, # only if the file load - StdfWidgetActions.Json: has_data, # only if the file load + StdfWidgetActions.Reload: bool(self.widget.filename), + StdfWidgetActions.Graph: self.widget.can_plot_mpr(), + StdfWidgetActions.Json: self.widget.has_data(), } for name, enabled in states.items(): try: - action = self.get_action(name) - except KeyError: + self.get_action(name).setEnabled(enabled) + except Exception: continue - action.setEnabled(enabled) - # IMPORTANT: Since we are defining the main actions in here - # and the context is WidgetWithChildrenShortcut we need to - # assign the same actions to the children widgets in order - # for shortcuts to work - # if figviewer: - # figviewer_actions = figviewer.actions() - # # thumbnails_sb_actions = thumbnails_sb.actions() - - # if action not in figviewer_actions: - # figviewer.addAction(action) - # if action not in thumbnails_sb_actions: - # thumbnails_sb.addAction(action) + def _has_file(self): + return bool(getattr(self.widget, "filename", "")) def _has_data(self): return len(self.widget.mpr_table)>0 or len(self.widget.ptr_table)>0 def on_close(self): - """ Handle the widget being closed. """ - print(" StdfWidget.on_close") - return super().on_close() - - def on_close(self): if self.widget.plot_window is not None: self.widget.plot_window.close() return super().on_close() diff --git a/pylab_ml/plugins/stdf_browser/widgets/showstdf.py b/pylab_ml/plugins/stdf_browser/widgets/showstdf.py index 7a185b2e..e1cecb85 100644 --- a/pylab_ml/plugins/stdf_browser/widgets/showstdf.py +++ b/pylab_ml/plugins/stdf_browser/widgets/showstdf.py @@ -125,135 +125,141 @@ def raw_hdf5_data(self): The preprocessed data as a Pandas DataFrame. """ # PREPROCESSING "PTR" DATA - ptr = pd.read_hdf(self.hdf5_file, f"/raw_stdf_data/{self.filename}/PTR", mode="a") - - # Renaming columns to simple names - ptr.rename(columns={"PTR.TEST_NUM": "TestNo", "PTR.RESULT": "Result", "PTR.TEST_TXT": "Test"}, inplace=True) - - # Sorting the values according to 'TestNo' column - ptr.sort_values(["TestNo", "PART_INDEX"], inplace=True) - - ptr["fmt"] = ptr["PTR.C_HLMFMT"].apply(lambda x: x.decode()[1:]) - fmt = "7.3f" - - # Assigning values 10 to the power of 'PTR.RES_SCAL' column - ptr["mul"] = 10 ** ptr["PTR.RES_SCAL"].apply(lambda x: float(x)) - - # Rounding off the decimal digits to 3 values for easy readability - ptr2 = ptr.groupby("TestNo")["Result"].apply(list).reset_index(name="Result_Append") - - # Making separate dataframe to concatenate the results of various IC's - # of a particular test to a single list - ptr2.drop(columns=ptr2.columns[0], inplace=True) - - # Deleting the duplicate rows in the 'TestNo' column - ptr.drop_duplicates(subset=["TestNo"], inplace=True, ignore_index=True) - - # Combining 'Result_Append' column to the 'ptr' dataframe - ptr = ptr.assign(Result_Append=ptr2) - - # Creating empty lists which will be used in the below operation - mean_result_ptr = [] - min_result_ptr = [] - max_result_ptr = [] - root_mean_square_ptr = [] - test_failed_ptr = [] - failed_idx_ptr = [] - failed_IC_ptr = [] - - # Assigning values from the 'SI' dictionary above to the 'ptr['mul']' - ptr["SI"] = ptr["mul"].apply(lambda x: self.SI[x]) - - ptr["LTL"] = ( - (ptr["PTR.LO_LIMIT"] * ptr["mul"]).apply(lambda x: f"{x:{fmt}} ") + ptr["SI"].apply(lambda x: x) + ptr["PTR.UNITS"].apply(lambda x: x.decode()) - ) - ptr["UTL"] = ( - (ptr["PTR.HI_LIMIT"] * ptr["mul"]).apply(lambda x: f"{x:{fmt}} ") + ptr["SI"].apply(lambda x: x) + ptr["PTR.UNITS"].apply(lambda x: x.decode()) - ) - ptr["Test"] = ptr["Test"].apply(lambda x: x.decode()) - ptr["LSL"] = ( - (ptr["PTR.LO_SPEC"] * ptr["mul"]).apply(lambda x: f"{x:{fmt}} ") + ptr["SI"].apply(lambda x: x) + ptr["PTR.UNITS"].apply(lambda x: x.decode()) - ) - ptr["USL"] = ( - (ptr["PTR.HI_SPEC"] * ptr["mul"]).apply(lambda x: f"{x:{fmt}} ") + ptr["SI"].apply(lambda x: x) + ptr["PTR.UNITS"].apply(lambda x: x.decode()) - ) - - ptr["LSL"] = ptr["LSL"].apply(lambda x: x if x.find("inf") < 0 else "") - ptr["LTL"] = ptr["LTL"].apply(lambda x: x if x.find("inf") < 0 else "") - ptr["UTL"] = ptr["UTL"].apply(lambda x: x if x.find("inf") < 0 else "") - ptr["USL"] = ptr["USL"].apply(lambda x: x if x.find("inf") < 0 else "") - ptr["PTR.UNITS"] = ptr["PTR.UNITS"].apply(lambda x: x.decode()) - - # Storing 'Mean', 'Maximum', 'Minimum' and 'Root Mean Square' value of - # test results of a test in 'max_result' variable - for i in range(0, len(ptr)): - result = ptr["Result_Append"].copy(deep=False) - result[i] = (np.array(result[i]) * ptr["mul"][i]).round(decimals=3) - - mean_result_ptr.append(np.mean(ptr["Result_Append"][i])) - min_result_ptr.append(np.min(ptr["Result_Append"][i])) - max_result_ptr.append(np.max(ptr["Result_Append"][i])) - root_mean_square_ptr.append(np.sqrt(np.mean(np.square(ptr["Result_Append"][i])))) - - ltl = str2float(ptr["LTL"][i]) - utl = str2float(ptr["UTL"][i]) - - if ltl == utl == 0: - test_failed_ptr.insert(i, 0) - elif (result[i] < ltl).any() or (result[i] > utl).any(): - test_failed_ptr.insert(i, 1) - else: - test_failed_ptr.insert(i, 0) - - temp_a = result[i] < ltl - temp_b = result[i] > utl - try: - temp = [a or b for a, b in zip(temp_a, temp_b)] - except Exception: - temp = [temp_a or temp_b] - failed_idx_ptr.insert(i, temp) - - # To find which 'IC' failed in a particular test - if ltl == utl == 0: - failed_IC_ptr.insert(i, 0) - elif any(failed_idx_ptr[i]): - temp_c = ((np.where(failed_idx_ptr[i])[0]) + 1).tolist() - failed_IC_ptr.insert(i, temp_c) - else: - # '0' means all IC's in a test are passed - failed_IC_ptr.insert(i, 0) - - ptr = ptr.assign( - Mean_Value=mean_result_ptr, - Min_Value=min_result_ptr, - Max_Value=max_result_ptr, - RMS=root_mean_square_ptr, - Test_Failed=test_failed_ptr, - IC_Failed=failed_IC_ptr, - ) - - # Rounding off the decimal digits to 2 values for easy readability - ptr[["Mean_Value", "Min_Value", "Max_Value", "RMS"]] = ptr[["Mean_Value", "Min_Value", "Max_Value", "RMS"]].round(decimals=2) - ptr = ptr[ - [ - "TestNo", - "Test", - "LSL", - "LTL", - "Result_Append", - "UTL", - "USL", - "Mean_Value", - "Min_Value", - "Max_Value", - "RMS", - "Test_Failed", - "IC_Failed", - "PTR.LO_LIMIT", - "PTR.HI_LIMIT", - "PTR.UNITS", + try: + ptr = pd.read_hdf(self.hdf5_file, f"/raw_stdf_data/{self.filename}/PTR", mode="a") + except (KeyError, FileNotFoundError): + ptr = None + + if ptr is None or ptr.empty: + ptr = pd.DataFrame() + else: + # Renaming columns to simple names + ptr.rename(columns={"PTR.TEST_NUM": "TestNo", "PTR.RESULT": "Result", "PTR.TEST_TXT": "Test"}, inplace=True) + + # Sorting the values according to 'TestNo' column + ptr.sort_values(["TestNo", "PART_INDEX"], inplace=True) + + ptr["fmt"] = ptr["PTR.C_HLMFMT"].apply(lambda x: x.decode()[1:]) + fmt = "7.3f" + + # Assigning values 10 to the power of 'PTR.RES_SCAL' column + ptr["mul"] = 10 ** ptr["PTR.RES_SCAL"].apply(lambda x: float(x)) + + # Rounding off the decimal digits to 3 values for easy readability + ptr2 = ptr.groupby("TestNo")["Result"].apply(list).reset_index(name="Result_Append") + + # Making separate dataframe to concatenate the results of various IC's + # of a particular test to a single list + ptr2.drop(columns=ptr2.columns[0], inplace=True) + + # Deleting the duplicate rows in the 'TestNo' column + ptr.drop_duplicates(subset=["TestNo"], inplace=True, ignore_index=True) + + # Combining 'Result_Append' column to the 'ptr' dataframe + ptr = ptr.assign(Result_Append=ptr2) + + # Creating empty lists which will be used in the below operation + mean_result_ptr = [] + min_result_ptr = [] + max_result_ptr = [] + root_mean_square_ptr = [] + test_failed_ptr = [] + failed_idx_ptr = [] + failed_IC_ptr = [] + + # Assigning values from the 'SI' dictionary above to the 'ptr['mul']' + ptr["SI"] = ptr["mul"].apply(lambda x: self.SI[x]) + + ptr["LTL"] = ( + (ptr["PTR.LO_LIMIT"] * ptr["mul"]).apply(lambda x: f"{x:{fmt}} ") + ptr["SI"].apply(lambda x: x) + ptr["PTR.UNITS"].apply(lambda x: x.decode()) + ) + ptr["UTL"] = ( + (ptr["PTR.HI_LIMIT"] * ptr["mul"]).apply(lambda x: f"{x:{fmt}} ") + ptr["SI"].apply(lambda x: x) + ptr["PTR.UNITS"].apply(lambda x: x.decode()) + ) + ptr["Test"] = ptr["Test"].apply(lambda x: x.decode()) + ptr["LSL"] = ( + (ptr["PTR.LO_SPEC"] * ptr["mul"]).apply(lambda x: f"{x:{fmt}} ") + ptr["SI"].apply(lambda x: x) + ptr["PTR.UNITS"].apply(lambda x: x.decode()) + ) + ptr["USL"] = ( + (ptr["PTR.HI_SPEC"] * ptr["mul"]).apply(lambda x: f"{x:{fmt}} ") + ptr["SI"].apply(lambda x: x) + ptr["PTR.UNITS"].apply(lambda x: x.decode()) + ) + + ptr["LSL"] = ptr["LSL"].apply(lambda x: x if x.find("inf") < 0 else "") + ptr["LTL"] = ptr["LTL"].apply(lambda x: x if x.find("inf") < 0 else "") + ptr["UTL"] = ptr["UTL"].apply(lambda x: x if x.find("inf") < 0 else "") + ptr["USL"] = ptr["USL"].apply(lambda x: x if x.find("inf") < 0 else "") + ptr["PTR.UNITS"] = ptr["PTR.UNITS"].apply(lambda x: x.decode()) + + # Storing 'Mean', 'Maximum', 'Minimum' and 'Root Mean Square' value of + # test results of a test in 'max_result' variable + for i in range(0, len(ptr)): + result = ptr["Result_Append"].copy(deep=False) + result[i] = (np.array(result[i]) * ptr["mul"][i]).round(decimals=3) + + mean_result_ptr.append(np.mean(ptr["Result_Append"][i])) + min_result_ptr.append(np.min(ptr["Result_Append"][i])) + max_result_ptr.append(np.max(ptr["Result_Append"][i])) + root_mean_square_ptr.append(np.sqrt(np.mean(np.square(ptr["Result_Append"][i])))) + + ltl = str2float(ptr["LTL"][i]) + utl = str2float(ptr["UTL"][i]) + + if ltl == utl == 0: + test_failed_ptr.insert(i, 0) + elif (result[i] < ltl).any() or (result[i] > utl).any(): + test_failed_ptr.insert(i, 1) + else: + test_failed_ptr.insert(i, 0) + + temp_a = result[i] < ltl + temp_b = result[i] > utl + try: + temp = [a or b for a, b in zip(temp_a, temp_b)] + except Exception: + temp = [temp_a or temp_b] + failed_idx_ptr.insert(i, temp) + + # To find which 'IC' failed in a particular test + if ltl == utl == 0: + failed_IC_ptr.insert(i, 0) + elif any(failed_idx_ptr[i]): + temp_c = ((np.where(failed_idx_ptr[i])[0]) + 1).tolist() + failed_IC_ptr.insert(i, temp_c) + else: + # '0' means all IC's in a test are passed + failed_IC_ptr.insert(i, 0) + + ptr = ptr.assign( + Mean_Value=mean_result_ptr, + Min_Value=min_result_ptr, + Max_Value=max_result_ptr, + RMS=root_mean_square_ptr, + Test_Failed=test_failed_ptr, + IC_Failed=failed_IC_ptr, + ) + + # Rounding off the decimal digits to 2 values for easy readability + ptr[["Mean_Value", "Min_Value", "Max_Value", "RMS"]] = ptr[["Mean_Value", "Min_Value", "Max_Value", "RMS"]].round(decimals=2) + ptr = ptr[ + [ + "TestNo", + "Test", + "LSL", + "LTL", + "Result_Append", + "UTL", + "USL", + "Mean_Value", + "Min_Value", + "Max_Value", + "RMS", + "Test_Failed", + "IC_Failed", + "PTR.LO_LIMIT", + "PTR.HI_LIMIT", + "PTR.UNITS", + ] ] - ] # PREPROCESSING "MPR" DATA try: diff --git a/pylab_ml/plugins/stdf_browser/widgets/test_results.py b/pylab_ml/plugins/stdf_browser/widgets/test_results.py index dfede23e..81a88dbb 100644 --- a/pylab_ml/plugins/stdf_browser/widgets/test_results.py +++ b/pylab_ml/plugins/stdf_browser/widgets/test_results.py @@ -15,7 +15,7 @@ from qtpy import PYQT5 from qtpy.QtCore import Signal, Qt, QCoreApplication from qtpy.QtWidgets import (QApplication, QWidget, QFileDialog, QMenu, - QTableWidgetItem, QVBoxLayout) + QTableWidgetItem, QVBoxLayout, QAbstractItemView) from matplotlib.figure import Figure from matplotlib.backends.backend_qtagg import ( FigureCanvasQTAgg as FigureCanvas, @@ -58,6 +58,23 @@ } +TaMprItems = { + "TestNo": 0, + "Test": 1, + "PART_INDEX": 2, + "Result_Count": 3, + "LSL": 4, + "LTL": 5, + "Results": 6, + "UTL": 7, + "USL": 8, + "Mean": 9, + "Min": 10, + "Max": 11, + "RMS": 12, + "Test Failed": 13, +} + class PlotWindow(QWidget): """Eigenständiges, wiederverwendbares Fenster mit Matplotlib-Canvas.""" @@ -101,6 +118,7 @@ class Test_Results(QWidget, SpyderWidgetMixin): It inherits from QWidget and SpyderWidgetMixin to create a custom widget for displaying test results. """ sig_data_changed = Signal() + sig_mpr_selection_changed = Signal() def __init__(self, parent=None, background_color=None): @@ -129,30 +147,43 @@ def __init__(self, parent=None, background_color=None): self.lot = "" self.ptr_table = pd.DataFrame() self.mpr_table = pd.DataFrame() - self.last_selected_row = -1 - self.clicked_index = [] self.plot_window = None self._updating = False self.filename = "" self.adjustUI() self._connect_signals() + self.update_tabs() def _connect_signals(self): # currentCellChanged reagiert auf Maus UND Tastatur self.tableWidget_ptr.currentCellChanged.connect(self._on_ptr_cell_changed) - self.tableWidget_mpr.currentCellChanged.connect(self._on_mpr_cell_changed) - # Klick auf bereits gewählte Zeile: geschlossenes Plotfenster wieder zeigen self.tableWidget_ptr.cellClicked.connect(self._reshow_plot_window) - self.tableWidget_mpr.cellClicked.connect(self._reshow_plot_window) + # MPR: ganze Zeilen, Mehrfachauswahl (Strg/Shift), KEIN automatischer Plot + self.tableWidget_mpr.setSelectionBehavior(QAbstractItemView.SelectRows) + self.tableWidget_mpr.setSelectionMode(QAbstractItemView.ExtendedSelection) + self.tableWidget_mpr.selectionModel().selectionChanged.connect( + self._on_mpr_selection_changed) + + # Filter self.enter_filter_test_name_ptr.textChanged.connect(self.filter_test_name_ptr) self.enter_filter_test_name_mpr.textChanged.connect(self.filter_test_name_mpr) - self.tabWidget.currentChanged.connect(lambda _: self.keyPressEvent(None)) + # Nach dem Filtern können ausgewählte Zeilen ausgeblendet sein -> Icon neu prüfen + self.enter_filter_test_name_mpr.textChanged.connect( + lambda _: self.sig_mpr_selection_changed.emit()) + + self.tabWidget.currentChanged.connect(self._on_tab_changed) def adjustUI(self): """ This method is used to adjust the UI elements of the PyQt window, such as setting the column width of the 'QTableWidget' and hiding the progress bar and status labels.""" self.set_column_width() + self._arrange_columns() + + # header_item = self.tableWidget_mpr.horizontalHeaderItem(TaMprItems["Test"]) + # if header_item is not None: + # header_item.setText("Test Name") + # print("setText") self.progressBar.hide() self.lstatus.setText("") self.llotid.setText("") @@ -163,6 +194,7 @@ def clear_data(self): self.ptr_table = pd.DataFrame() self.mpr_table = pd.DataFrame() self.keyPressEvent(None) + self.update_tabs() if self.plot_window is not None: self.plot_window.close() self.sig_data_changed.emit() @@ -199,6 +231,7 @@ def open_files(self, fname=""): self._updating = True self.keyPressEvent(None) self._fill_tables() + self.update_tabs() finally: self._updating = False self.progressBar.hide() @@ -224,7 +257,8 @@ def _fill_tables(self): self.fill_ptr_data() self.fill_mpr_data() self.set_column_width() - self.colour_pass_fail_ptr_data() + if self.has_ptr(): + self.colour_pass_fail_ptr_data() if self.has_mpr(): self.colour_pass_fail_mpr_data() @@ -262,8 +296,7 @@ def fill_mpr_data(self): """ table = self.tableWidget_mpr if not self.has_mpr(): - table.setRowCount(1) - table.setItem(0, 2, QTableWidgetItem("MPR data is empty")) + table.setRowCount(0) return columns = list(self.mpr_table.columns[0:14]) @@ -277,6 +310,9 @@ def fill_mpr_data(self): self.printProgressBar(col + 1, len(columns)) def has_data(self): + return self.has_ptr() or self.has_mpr() + + def has_ptr(self): return isinstance(self.ptr_table, pd.DataFrame) and not self.ptr_table.empty def has_mpr(self): @@ -705,11 +741,10 @@ def colour_pass_fail_mpr_data(self): self.tableWidget_mpr.item(j, 6).setForeground(QtGui.QColor(0, 255, 0)) self.tableWidget_mpr.item(j, 13).setForeground(QtGui.QColor(0, 255, 0)) else: - # Red Colour if test is failed - self.tableWidget_mpr.item(j, 1).setForeground(QtGui.QColor(255, 0, 0)) - self.tableWidget_mpr.item(j, 6).setForeground(QtGui.QColor(255, 0, 0)) - self.tableWidget_mpr.item(j, 13).setForeground(QtGui.QColor(255, 0, 0)) + self.tableWidget_mpr.item(j, TaMprItems["Test"]).setForeground(QtGui.QColor(255, 0, 0)) + self.tableWidget_mpr.item(j, TaMprItems["Results"]).setForeground(QtGui.QColor(255, 0, 0)) + self.tableWidget_mpr.item(j, TaMprItems["Test Failed"]).setForeground(QtGui.QColor(255, 0, 0)) @property def filename(self): @@ -766,6 +801,24 @@ def printProgressBar(self, iteration, total, prefix="", suffix="", decimals=1, l # bar = fill * filledLength + "-" * (length - filledLength) self.update_Progress_bar(iteration, total) + def update_tabs(self): + """PTR-/MPR-Display the register only if the corresponding data is available""" + tabs = [ + (self._tab_index_of(self.tableWidget_ptr), self.has_ptr()), + (self._tab_index_of(self.tableWidget_mpr), self.has_mpr()), + ] + for index, visible in tabs: + if index >= 0: + self.tabWidget.setTabVisible(index, visible) + + # Falls das aktuelle Register ausgeblendet wurde -> auf sichtbares wechseln + current = self.tabWidget.currentIndex() + if current < 0 or not self.tabWidget.isTabVisible(current): + for index, visible in tabs: + if index >= 0 and visible: + self.tabWidget.setCurrentIndex(index) + break + def update_Progress_bar(self, count, maxcount): """ This method is used to update the progress bar in the PyQt window. @@ -809,6 +862,47 @@ def _limit(text): except (ValueError, IndexError): return None # z.B. leere Grenze ("inf" wurde zu "") + # ---- Register ein-/ausblenden + def _tab_index_of(self, widget): + """Index der Tab-Seite, die 'widget' enthält (-1 falls keine).""" + for i in range(self.tabWidget.count()): + page = self.tabWidget.widget(i) + if page is widget or page.isAncestorOf(widget): + return i + return -1 + + # ---- Spaltenreihenfolge (nur visuell, logische Indizes bleiben gleich) + @staticmethod + def _move_column_after(table, logical, after_logical): + """Spalte 'logical' visuell direkt hinter 'after_logical' platzieren.""" + header = table.horizontalHeader() + src = header.visualIndex(logical) + dst = header.visualIndex(after_logical) + if src < 0 or dst < 0: + return + if src > dst: + dst += 1 # beim Verschieben nach links hinter das Ziel + if src != dst: + header.moveSection(src, dst) + + def _arrange_columns(self): + # PTR: Test Name | Test Failed | IC Failed | LSL | ... + self._move_column_after(self.tableWidget_ptr, + TaPtrItems["Test Failed"], TaPtrItems["Test Name"]) + self._move_column_after(self.tableWidget_ptr, + TaPtrItems["ICFailed"], TaPtrItems["Test Failed"]) + + # MPR: Test | Test Name | Test Failed | Part INdex | Result_Count | ... + self._move_column_after(self.tableWidget_mpr, + TaMprItems["Test"], TaMprItems["PART_INDEX"]) + self._move_column_after(self.tableWidget_mpr, + TaMprItems["Test Failed"], TaMprItems["PART_INDEX"]) + + # Optional: Benutzer darf Spalten per Drag & Drop verschieben + # self.tableWidget_ptr.horizontalHeader().setSectionsMovable(True) + # self.tableWidget_mpr.horizontalHeader().setSectionsMovable(True) + + def _get_plot_window(self): if self.plot_window is None: self.plot_window = PlotWindow(self) @@ -818,6 +912,40 @@ def _reshow_plot_window(self, row, col): if self.plot_window is not None and not self.plot_window.isVisible(): self.plot_window.refresh() + # ---- MPR-Auswahl + def _on_tab_changed(self, index): + self.keyPressEvent(None) + self.sig_mpr_selection_changed.emit() # Icon hängt auch vom Register ab + + def _on_mpr_selection_changed(self, selected=None, deselected=None): + if self._updating: + return + n = len(self.selected_mpr_indices()) + self.lstatus.setText(f"{n} MPR line(s) selected" if n else "") + self.sig_mpr_selection_changed.emit() + + def selected_mpr_indices(self): + """DataFrame-Indizes aller ausgewählten, sichtbaren MPR-Zeilen + (in der aktuell angezeigten Reihenfolge).""" + if not self.has_mpr(): + return [] + table = self.tableWidget_mpr + rows = sorted({i.row() for i in table.selectionModel().selectedIndexes()}) + result = [] + for row in rows: + if table.isRowHidden(row): # durch Filter ausgeblendet + continue + idx = self._df_index(table, row) + if idx is not None: + result.append(idx) + return result + + def can_plot_mpr(self): + """True, wenn das MPR-Register aktiv ist und Zeilen ausgewählt sind.""" + return (self.has_mpr() + and self.tabWidget.currentIndex() == self._tab_index_of(self.tableWidget_mpr) + and bool(self.selected_mpr_indices())) + # ---- PTR def _on_ptr_cell_changed(self, row, col, prev_row, prev_col): if self._updating or row < 0 or row == prev_row: @@ -854,26 +982,12 @@ def plot_ptr_row(self, row): pw.refresh() # ---- MPR - def _on_mpr_cell_changed(self, row, col, prev_row, prev_col): - if self._updating or row < 0: - return - idx = self._df_index(self.tableWidget_mpr, row) - if idx is None: - return - self.last_selected_row = idx # DataFrame-Index, nicht sichtbare Zeile - if row != prev_row: - self.plot_mpr([idx]) - def plot_mpr(self, indices): if not self.has_mpr() or not indices: return pw = self._get_plot_window() ax = pw.new_axes() - try: - self._draw_mpr(ax, indices[:4]) - except ValueError: - ax.clear() - ax.set_title("Result Count must match ...") + self._draw_mpr(ax, indices) pw.refresh() def _draw_mpr(self, ax, idx): @@ -881,74 +995,50 @@ def _draw_mpr(self, ax, idx): title = f"{self.filename} \\ {self.lot}" if len(idx) == 1: + # Einzelzeile: Verlauf mit Grenzen, Min/Max und Mittelwert i = idx[0] count = t["Result_Count"][i] for lim in (t["MPR.LO_LIMIT"][i], t["MPR.HI_LIMIT"][i]): if np.isfinite(lim): - ax.hlines(lim, 0, count, color="r") + ax.hlines(lim, 0, count, color="r", label="_nolegend_") ax.hlines([t["Min_Value"][i], t["Max_Value"][i]], 0, count, color="m") ax.hlines(t["Mean_Value"][i], 0, count, color="y") ax.plot(t["Results"][i], "bo-", markeredgecolor="magenta", markersize=1) - ax.set_title(title) + ax.set_title(f"{title}\n{t['Test'][i]} [{t['PART_INDEX'][i]}]") ax.set_ylabel(f'{t["Test"][i]}\n({t["Units"][i]})') + else: + # Mehrere Zeilen: alle Verläufe überlagert (Farben aus dem Standard-Zyklus) + for i in idx: + ax.plot(t["Results"][i], "o-", markersize=1, linewidth=0.8, + label=f'{t["Test"][i]} [{t["PART_INDEX"][i]}]') + units = list(dict.fromkeys(str(t["Units"][i]) for i in idx)) + ax.set_title(f"{title}\n{len(idx)} MPR rows") + ax.set_ylabel(" / ".join(units)) + if len(idx) <= 15: + ax.legend(fontsize="small") + else: + ax.legend(fontsize="x-small", ncol=2) - elif len(idx) == 2: - for i, fmt in zip(idx, ("go-", "ro-")): - ax.plot(t["Results"][i], fmt, markersize=0.3, alpha=0.5, - label=t["Test"][i]) - ax.set_title(title) - ax.set_ylabel(t["Units"][idx[0]]) - ax.legend() - - else: # 3 oder 4: erste Auswahl = x, weitere = y - def lab(i): - return f'{t["Units"][i]}[{t["PART_INDEX"][i]}]' - x = t["Results"][idx[0]] - for i, fmt in zip(idx[1:], ("go", "ro", "yo")): - ax.plot(x, t["Results"][i], fmt, markersize=1, alpha=0.5, - label=f"{lab(idx[0])} vs {lab(i)}") - ax.set_title(f'{title}\n{t["Test"][idx[0]]}') - ax.set_xlabel(t["Units"][idx[0]]) - ax.set_ylabel(" / ".join(str(t["Units"][i]) for i in idx[1:])) - ax.legend() + ax.set_xlabel("Result Index") + ax.grid(True, alpha=0.3) def graph_show(self): """This method is used to plot the graph based on the selected rows in the 'MPR' table. It checks the number of selected rows and plots the graph accordingly.""" - indices = list(self.clicked_index) - if not indices and self.last_selected_row >= 0: - indices = [self.last_selected_row] - self.plot_mpr(indices) - self.clicked_index.clear() - self.lstatus.setText("") + indices = self.selected_mpr_indices() + if indices: + self.plot_mpr(indices) def contextMenuEvent(self, event): """ - This method is triggered when the user right-clicks on the 'MPR' table. - It checks if any row is selected and opens a context menu with options to plot a graph or add a graph. - - Parameters - ---------- - event : QContextMenuEvent - The context menu event that triggered this method. + This method is triggered when the user select on the 'MPR' table. """ - if not (self.tableWidget_mpr.isVisible() and self.has_mpr()): - return - if not self.tableWidget_mpr.selectionModel().selection().indexes(): + if not self.can_plot_mpr(): return menu = QMenu(self) - plot_action = menu.addAction("Plot Graph") if self.clicked_index else None - add_action = menu.addAction("Add Graph") - action = menu.exec_(self.mapToGlobal(event.pos())) - if action is None: # Menü abgebrochen - return - if action is plot_action: + plot_action = menu.addAction("Plot selected rows") + if menu.exec_(self.mapToGlobal(event.pos())) is plot_action: self.graph_show() - elif (action is add_action and self.last_selected_row != -1 - and self.last_selected_row not in self.clicked_index): - self.clicked_index.append(self.last_selected_row) - self.lstatus.setText( - f"line {[i + 1 for i in self.clicked_index]} selected") def keyPressEvent(self, event): """ @@ -962,10 +1052,9 @@ def keyPressEvent(self, event): event : QKeyEvent The key event that triggered this method. """ - print("Esc") if event is None or event.key() == Qt.Key_Escape: - self.last_selected_row = -1 - self.clicked_index.clear() + if event is not None: # nur echte Esc-Taste + self.tableWidget_mpr.clearSelection() self.lstatus.setText("") elif event.key() == Qt.Key_Return: self.load_IC_data() diff --git a/pylab_ml/plugins/stdf_browser/widgets/showstdf.ui b/pylab_ml/plugins/stdf_browser/widgets/test_results.ui similarity index 100% rename from pylab_ml/plugins/stdf_browser/widgets/showstdf.ui rename to pylab_ml/plugins/stdf_browser/widgets/test_results.ui From a3d32634b440540a387ad2f78051a6bc13431d4b Mon Sep 17 00:00:00 2001 From: heli2src Date: Tue, 17 Nov 2026 15:57:45 +0100 Subject: [PATCH 09/12] fix exception with value is inf --- pylab_ml/plugins/stdf_browser/widgets/showstdf.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/pylab_ml/plugins/stdf_browser/widgets/showstdf.py b/pylab_ml/plugins/stdf_browser/widgets/showstdf.py index e1cecb85..f32795c7 100644 --- a/pylab_ml/plugins/stdf_browser/widgets/showstdf.py +++ b/pylab_ml/plugins/stdf_browser/widgets/showstdf.py @@ -32,6 +32,9 @@ def str2float(string): float The float value of the input string after removing the SI unit and the unit of measurement. """ + if string == "": + return string + print(f"str2float({string})") result = string.strip().split(" ") return float(result[0]) @@ -206,13 +209,13 @@ def raw_hdf5_data(self): if ltl == utl == 0: test_failed_ptr.insert(i, 0) - elif (result[i] < ltl).any() or (result[i] > utl).any(): + elif (ltl !="" and (result[i] < ltl).any()) or (utl != "" and (result[i] > utl).any()): test_failed_ptr.insert(i, 1) else: test_failed_ptr.insert(i, 0) - temp_a = result[i] < ltl - temp_b = result[i] > utl + temp_a = False if ltl == "" else result[i] < ltl + temp_b = False if utl == "" else result[i] > utl try: temp = [a or b for a, b in zip(temp_a, temp_b)] except Exception: @@ -222,7 +225,7 @@ def raw_hdf5_data(self): # To find which 'IC' failed in a particular test if ltl == utl == 0: failed_IC_ptr.insert(i, 0) - elif any(failed_idx_ptr[i]): + elif np.any(failed_idx_ptr[i]): temp_c = ((np.where(failed_idx_ptr[i])[0]) + 1).tolist() failed_IC_ptr.insert(i, temp_c) else: From e8e99b6a2e209436c2caa3e910a13bd738cd2dc4 Mon Sep 17 00:00:00 2001 From: heli2src Date: Tue, 17 Nov 2026 16:09:04 +0100 Subject: [PATCH 10/12] add Note for the STDF browser --- README.md | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1d05bc18..efe3031d 100644 --- a/README.md +++ b/README.md @@ -51,4 +51,20 @@ pip install -e . # install the pylab-ml instrument lib, the spyder plugin f # and the STDF-data widget for spyder ``` -When we started with this package we did not know **[pymeasure ](https://pymeasure.readthedocs.io/en/latest/introduction.html)** yet. Therefore there are some overlaps with this package. \ No newline at end of file +The STDF browser plugin uses the latest libraries from STDF and Metis, which have not yet been released in Conda and Pip. +Therefore, these libraries must still be downloaded directly from GitHub: + +```bash +cd .. +git clone https://github.com/Semi-ATE/Metis +cd Metis +pip install -e . + +cd .. + +git clone https://github.com/Semi-ATE/STDF.git +cd STDF +pip install -e . +``` + +If you need more instruments, check out **[pymeasure ](https://pymeasure.readthedocs.io/en/latest/introduction.html)**. From 3e893a3a6a79e27f25a39fed118727daba468d7c Mon Sep 17 00:00:00 2001 From: Christian Jung Date: Wed, 18 Nov 2026 10:38:02 +0100 Subject: [PATCH 11/12] add in mpr add+remove plot --- .../stdf_browser/widgets/main_widget.py | 1 - .../stdf_browser/widgets/test_results.py | 162 +++++++++++++++--- 2 files changed, 142 insertions(+), 21 deletions(-) diff --git a/pylab_ml/plugins/stdf_browser/widgets/main_widget.py b/pylab_ml/plugins/stdf_browser/widgets/main_widget.py index 9d99e481..f6b0d63b 100644 --- a/pylab_ml/plugins/stdf_browser/widgets/main_widget.py +++ b/pylab_ml/plugins/stdf_browser/widgets/main_widget.py @@ -7,7 +7,6 @@ import os # Third party imports -from qtpy.QtWidgets import QHBoxLayout # Local imports from spyder.api.translations import get_translation diff --git a/pylab_ml/plugins/stdf_browser/widgets/test_results.py b/pylab_ml/plugins/stdf_browser/widgets/test_results.py index 81a88dbb..4c1a1d84 100644 --- a/pylab_ml/plugins/stdf_browser/widgets/test_results.py +++ b/pylab_ml/plugins/stdf_browser/widgets/test_results.py @@ -78,6 +78,8 @@ class PlotWindow(QWidget): """Eigenständiges, wiederverwendbares Fenster mit Matplotlib-Canvas.""" + sig_closed = Signal() + def __init__(self, parent=None): super().__init__(parent, Qt.Window) self.setWindowTitle("STDF Plot") @@ -102,6 +104,10 @@ def refresh(self): self.show() self.raise_() + def closeEvent(self, event): + self.sig_closed.emit() + super().closeEvent(event) + class TableWidget(QTableWidgetItem): """Custom QTableWidgetItem for handling numeric comparisons.""" @@ -121,6 +127,11 @@ class Test_Results(QWidget, SpyderWidgetMixin): sig_mpr_selection_changed = Signal() + # Anzahl der Zeilen (ab der 2.), die eine eigene y-Achse bekommen. + # 1 -> nur die zweite Zeile, 2 -> zweite und dritte Zeile, ... + OWN_Y_AXIS_ROWS = 1 + + def __init__(self, parent=None, background_color=None): """ Initializes the Test_Results class and loads the UI file developed in QtDesigner. @@ -152,6 +163,7 @@ def __init__(self, parent=None, background_color=None): self.filename = "" self.adjustUI() + self._plotted_mpr = [] # DataFrame-Indizes der MPR-Zeilen im Plot self._connect_signals() self.update_tabs() @@ -165,6 +177,9 @@ def _connect_signals(self): self.tableWidget_mpr.setSelectionMode(QAbstractItemView.ExtendedSelection) self.tableWidget_mpr.selectionModel().selectionChanged.connect( self._on_mpr_selection_changed) + self.tableWidget_mpr.setContextMenuPolicy(Qt.CustomContextMenu) + self.tableWidget_mpr.customContextMenuRequested.connect( + self._show_mpr_context_menu) # Filter self.enter_filter_test_name_ptr.textChanged.connect(self.filter_test_name_ptr) @@ -190,6 +205,7 @@ def adjustUI(self): def clear_data(self): """ Geladene Daten verwerfen (-> Spyder zeigt das Leerbild). """ + self._plotted_mpr = [] self.clear_tables() self.ptr_table = pd.DataFrame() self.mpr_table = pd.DataFrame() @@ -228,6 +244,7 @@ def open_files(self, fname=""): try: if not self.loaddata(): return False + self._plotted_mpr = [] self._updating = True self.keyPressEvent(None) self._fill_tables() @@ -902,10 +919,10 @@ def _arrange_columns(self): # self.tableWidget_ptr.horizontalHeader().setSectionsMovable(True) # self.tableWidget_mpr.horizontalHeader().setSectionsMovable(True) - def _get_plot_window(self): if self.plot_window is None: self.plot_window = PlotWindow(self) + self.plot_window.sig_closed.connect(self._on_plot_window_closed) return self.plot_window def _reshow_plot_window(self, row, col): @@ -962,6 +979,7 @@ def plot_ptr_row(self, row): data = np.asarray(rec["Result_Append"], dtype=float) ltl, utl = self._limit(rec["LTL"]), self._limit(rec["UTL"]) + self._plotted_mpr = [] pw = self._get_plot_window() ax = pw.new_axes() if ltl != utl: # ltl == utl == 0 -> keine Grenzen @@ -985,10 +1003,60 @@ def plot_ptr_row(self, row): def plot_mpr(self, indices): if not self.has_mpr() or not indices: return + self._plotted_mpr = list(dict.fromkeys(indices)) # Duplikate entfernen + self._redraw_mpr_plot() + + def add_to_mpr_plot(self, indices): + """Zeilen zum bestehenden MPR-Plot hinzufügen.""" + if not self.has_mpr() or not indices: + return + if not self._plotted_mpr or self.plot_window is None \ + or not self.plot_window.isVisible(): + # Noch kein MPR-Plot vorhanden -> wie 'Plot' + self.plot_mpr(indices) + return + self._plotted_mpr += [i for i in indices if i not in self._plotted_mpr] + self._redraw_mpr_plot() + + def remove_from_mpr_plot(self, indices): + """Zeilen aus dem bestehenden MPR-Plot entfernen.""" + if not self._plotted_mpr: + return + remaining = [i for i in self._plotted_mpr if i not in indices] + if remaining == self._plotted_mpr: + return # nichts davon war im Plot + if not remaining: + # Letzte Kurve entfernt -> Fenster schließen + # (closeEvent -> sig_closed -> _plotted_mpr wird geleert) + if self.plot_window is not None: + self.plot_window.close() + self._plotted_mpr = [] + self.lstatus.setText("") + return + self._plotted_mpr = remaining + self._redraw_mpr_plot() + + def _redraw_mpr_plot(self): pw = self._get_plot_window() ax = pw.new_axes() - self._draw_mpr(ax, indices) + self._draw_mpr(ax, self._plotted_mpr) pw.refresh() + self.lstatus.setText(f"{len(self._plotted_mpr)} MPR line(s) in plot") + + def _on_plot_window_closed(self): + self._plotted_mpr = [] + + def _create_y_axes(self, ax, count): + """Liste von 'count' Achsen mit gemeinsamer x-Achse: + [linke Achse, rechte Achse, weitere versetzte rechte Achsen ...].""" + axes = [ax] + for k in range(1, count): + twin = ax.twinx() + if k > 1: + # weitere Achsen nach rechts versetzen, damit sie sich nicht überlagern + twin.spines["right"].set_position(("axes", 1.0 + 0.15 * (k - 1))) + axes.append(twin) + return axes def _draw_mpr(self, ax, idx): t = self.mpr_table @@ -1000,28 +1068,59 @@ def _draw_mpr(self, ax, idx): count = t["Result_Count"][i] for lim in (t["MPR.LO_LIMIT"][i], t["MPR.HI_LIMIT"][i]): if np.isfinite(lim): - ax.hlines(lim, 0, count, color="r", label="_nolegend_") + ax.hlines(lim, 0, count, color="r") ax.hlines([t["Min_Value"][i], t["Max_Value"][i]], 0, count, color="m") ax.hlines(t["Mean_Value"][i], 0, count, color="y") ax.plot(t["Results"][i], "bo-", markeredgecolor="magenta", markersize=1) ax.set_title(f"{title}\n{t['Test'][i]} [{t['PART_INDEX'][i]}]") ax.set_ylabel(f'{t["Test"][i]}\n({t["Units"][i]})') + ax.set_xlabel("Result Index") + ax.grid(True, alpha=0.3) + return + + # Mehrere Zeilen: 1. Zeile links, 2. (ggf. weitere) mit eigener y-Achse + colors = plt.rcParams["axes.prop_cycle"].by_key()["color"] + n_axes = min(len(idx), 1 + self.OWN_Y_AXIS_ROWS) + axes = self._create_y_axes(ax, n_axes) + + handles = [] + left_rows = [] # Zeilen auf der linken Achse + for n, i in enumerate(idx): + color = colors[n % len(colors)] + target = axes[n] if n < n_axes else axes[0] + if target is axes[0]: + left_rows.append(i) + line, = target.plot(t["Results"][i], "o-", color=color, + markersize=1, linewidth=0.8, + label=f'{t["Test"][i]} [{t["PART_INDEX"][i]}]') + handles.append(line) + + # Eigene Achse in Kurvenfarbe beschriften + if target is not axes[0]: + target.set_ylabel(f'{t["Test"][i]}\n({t["Units"][i]})', color=color) + target.tick_params(axis="y", colors=color) + target.spines["right"].set_color(color) + + # Linke Achse beschriften + if len(left_rows) == 1: + i = left_rows[0] + color = colors[0] + ax.set_ylabel(f'{t["Test"][i]}\n({t["Units"][i]})', color=color) + ax.tick_params(axis="y", colors=color) + ax.spines["left"].set_color(color) else: - # Mehrere Zeilen: alle Verläufe überlagert (Farben aus dem Standard-Zyklus) - for i in idx: - ax.plot(t["Results"][i], "o-", markersize=1, linewidth=0.8, - label=f'{t["Test"][i]} [{t["PART_INDEX"][i]}]') - units = list(dict.fromkeys(str(t["Units"][i]) for i in idx)) - ax.set_title(f"{title}\n{len(idx)} MPR rows") + units = list(dict.fromkeys(str(t["Units"][i]) for i in left_rows)) ax.set_ylabel(" / ".join(units)) - if len(idx) <= 15: - ax.legend(fontsize="small") - else: - ax.legend(fontsize="x-small", ncol=2) + ax.set_title(f"{title}\n{len(idx)} MPR rows") ax.set_xlabel("Result Index") ax.grid(True, alpha=0.3) + # Gemeinsame Legende auf der obersten Achse (sonst von Kurven verdeckt) + axes[-1].legend(handles=handles, + fontsize="small" if len(idx) <= 15 else "x-small", + ncol=1 if len(idx) <= 15 else 2) + def graph_show(self): """This method is used to plot the graph based on the selected rows in the 'MPR' table. It checks the number of selected rows and plots the graph accordingly.""" @@ -1029,16 +1128,39 @@ def graph_show(self): if indices: self.plot_mpr(indices) - def contextMenuEvent(self, event): - """ - This method is triggered when the user select on the 'MPR' table. - """ - if not self.can_plot_mpr(): + def _show_mpr_context_menu(self, pos): + """Kontextmenü nur bei Rechtsklick auf eine selektierte MPR-Zeile.""" + table = self.tableWidget_mpr + index = table.indexAt(pos) + if not index.isValid() or not self.has_mpr(): + return + + selected_rows = {i.row() for i in table.selectionModel().selectedIndexes()} + if index.row() not in selected_rows: return + + indices = self.selected_mpr_indices() + if not indices: + return + + plot_visible = self.plot_window is not None and self.plot_window.isVisible() + new = [i for i in indices if i not in self._plotted_mpr] + in_plot = [i for i in indices if i in self._plotted_mpr] if plot_visible else [] + menu = QMenu(self) plot_action = menu.addAction("Plot selected rows") - if menu.exec_(self.mapToGlobal(event.pos())) is plot_action: - self.graph_show() + add_action = menu.addAction("Add") + add_action.setEnabled(bool(new)) + remove_action = menu.addAction("Remove") + remove_action.setEnabled(bool(in_plot)) + + action = menu.exec_(table.viewport().mapToGlobal(pos)) + if action is plot_action: + self.plot_mpr(indices) + elif action is add_action: + self.add_to_mpr_plot(indices) + elif action is remove_action: + self.remove_from_mpr_plot(indices) def keyPressEvent(self, event): """ From 4b8804f5b2786cbd01720e9681308a5826837eef Mon Sep 17 00:00:00 2001 From: heli2src Date: Wed, 18 Nov 2026 11:31:24 +0100 Subject: [PATCH 12/12] increase OWN_Y_AXIS_ROWS --- pylab_ml/plugins/stdf_browser/widgets/test_results.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pylab_ml/plugins/stdf_browser/widgets/test_results.py b/pylab_ml/plugins/stdf_browser/widgets/test_results.py index 4c1a1d84..395dcfea 100644 --- a/pylab_ml/plugins/stdf_browser/widgets/test_results.py +++ b/pylab_ml/plugins/stdf_browser/widgets/test_results.py @@ -129,7 +129,7 @@ class Test_Results(QWidget, SpyderWidgetMixin): # Anzahl der Zeilen (ab der 2.), die eine eigene y-Achse bekommen. # 1 -> nur die zweite Zeile, 2 -> zweite und dritte Zeile, ... - OWN_Y_AXIS_ROWS = 1 + OWN_Y_AXIS_ROWS = 3 def __init__(self, parent=None, background_color=None):