source: sasview/src/sas/qtgui/Utilities/GridPanel.py @ 712db9e

ESS_GUIESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 712db9e was 7879745, checked in by Piotr Rozyczko <piotrrozyczko@…>, 6 years ago

theta and phi may not be present always.

  • Property mode set to 100644
File size: 18.3 KB
Line 
1import os
2import sys
3import time
4import logging
5import webbrowser
6
7from PyQt5 import QtCore, QtWidgets, QtGui
8
9import sas.qtgui.Utilities.GuiUtils as GuiUtils
10from sas.qtgui.Plotting.PlotterData import Data1D
11from sas.qtgui.Utilities.UI.GridPanelUI import Ui_GridPanelUI
12
13
14class BatchOutputPanel(QtWidgets.QMainWindow, Ui_GridPanelUI):
15    """
16    Class for stateless grid-like printout of model parameters for mutiple models
17    """
18    ERROR_COLUMN_CAPTION = " (Err)"
19    IS_WIN = (sys.platform == 'win32')
20    def __init__(self, parent = None, output_data=None):
21
22        super(BatchOutputPanel, self).__init__(parent._parent)
23        self.setupUi(self)
24
25        self.parent = parent
26        if hasattr(self.parent, "communicate"):
27            self.communicate = parent.communicate
28
29        self.addToolbarActions()
30
31        # file name for the dataset
32        self.grid_filename = ""
33
34        self.has_data = False if output_data is None else True
35        # Tab numbering
36        self.tab_number = 1
37
38        # System dependent menu items
39        if not self.IS_WIN:
40            self.actionOpen_with_Excel.setVisible(False)
41
42        # list of QTableWidgets, indexed by tab number
43        self.tables = []
44        self.tables.append(self.tblParams)
45
46        # context menu on the table
47        self.tblParams.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
48        self.tblParams.customContextMenuRequested.connect(self.showContextMenu)
49
50        # Command buttons
51        self.cmdHelp.clicked.connect(self.onHelp)
52        self.cmdPlot.clicked.connect(self.onPlot)
53
54        # Fill in the table from input data
55        self.setupTable(widget=self.tblParams, data=output_data)
56        #TODO: This is not what was inteded to be.
57        if output_data is not None:
58            # Set a table tooltip describing the model
59            model_name = output_data[0][0].model.id
60            self.tabWidget.setTabToolTip(0, model_name)
61
62    def closeEvent(self, event):
63        """
64        Overwrite QDialog close method to allow for custom widget close
65        """
66        # Maybe we should just minimize
67        self.setWindowState(QtCore.Qt.WindowMinimized)
68        event.ignore()
69
70    def addToolbarActions(self):
71        """
72        Assing actions and callbacks to the File menu items
73        """
74        self.actionOpen.triggered.connect(self.actionLoadData)
75        self.actionOpen_with_Excel.triggered.connect(self.actionSendToExcel)
76        self.actionSave.triggered.connect(self.actionSaveFile)
77
78    def actionLoadData(self):
79        """
80        Open file load dialog and load a .csv file
81        """
82        datafile = QtWidgets.QFileDialog.getOpenFileName(
83            self, "Choose a file with results", "", "CSV files (*.csv)", None,
84            QtWidgets.QFileDialog.DontUseNativeDialog)[0]
85
86        if not datafile:
87            logging.info("No data file chosen.")
88            return
89
90        with open(datafile, 'r') as csv_file:
91            lines = csv_file.readlines()
92
93        self.setupTableFromCSV(lines)
94        self.has_data = True
95
96    def currentTable(self):
97        """
98        Returns the currently shown QTabWidget
99        """
100        return self.tables[self.tabWidget.currentIndex()]
101
102    def showContextMenu(self, position):
103        """
104        Show context specific menu in the tab table widget.
105        """
106        menu = QtWidgets.QMenu()
107        rows = [s.row() for s in self.currentTable().selectionModel().selectedRows()]
108        num_rows = len(rows)
109        if num_rows <= 0:
110            return
111        # Find out which items got selected and in which row
112        # Select for fitting
113
114        self.actionPlotResults = QtWidgets.QAction(self)
115        self.actionPlotResults.setObjectName("actionPlot")
116        self.actionPlotResults.setText(QtCore.QCoreApplication.translate("self", "Plot selected fits."))
117
118        menu.addAction(self.actionPlotResults)
119
120        # Define the callbacks
121        self.actionPlotResults.triggered.connect(self.onPlot)
122        try:
123            menu.exec_(self.currentTable().viewport().mapToGlobal(position))
124        except AttributeError as ex:
125            logging.error("Error generating context menu: %s" % ex)
126        return
127
128    def addTabPage(self):
129        """
130        Add new tab page with QTableWidget
131        """
132        layout = QtWidgets.QVBoxLayout()
133        tab_widget = QtWidgets.QTableWidget(parent=self)
134        # Same behaviour as the original tblParams
135        tab_widget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
136        tab_widget.setAlternatingRowColors(True)
137        tab_widget.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
138        tab_widget.setLayout(layout)
139        # Simple naming here.
140        # One would think naming the tab with current model name would be good.
141        # However, some models have LONG names, which doesn't look well on the tab bar.
142        self.tab_number += 1
143        tab_name = "Tab " + str(self.tab_number)
144        # each table needs separate slots.
145        tab_widget.customContextMenuRequested.connect(self.showContextMenu)
146        self.tables.append(tab_widget)
147        self.tabWidget.addTab(tab_widget, tab_name)
148        # Make the new tab active
149        self.tabWidget.setCurrentIndex(self.tab_number-1)
150
151    def addFitResults(self, results):
152        """
153        Create a new tab with batch fitting results
154        """
155        self.addTabPage()
156        # Update the new widget
157        # Fill in the table from input data in the last/newest page
158        assert(self.tables)
159        self.setupTable(widget=self.tables[-1], data=results)
160        self.has_data = True
161
162        # Set a table tooltip describing the model
163        model_name = results[0][0].model.id
164        self.tabWidget.setTabToolTip(self.tabWidget.count()-1, model_name)
165
166
167    @classmethod
168    def onHelp(cls):
169        """
170        Open a local url in the default browser
171        """
172        location = GuiUtils.HELP_DIRECTORY_LOCATION
173        url = "/user/qtgui/Perspectives/Fitting/fitting_help.html#batch-fit-mode"
174        try:
175            webbrowser.open('file://' + os.path.realpath(location+url))
176        except webbrowser.Error as ex:
177            logging.warning("Cannot display help. %s" % ex)
178
179    def onPlot(self):
180        """
181        Plot selected fits by sending signal to the parent
182        """
183        rows = [s.row() for s in self.currentTable().selectionModel().selectedRows()]
184        if not rows:
185            msg = "Nothing to plot!"
186            self.parent.communicate.statusBarUpdateSignal.emit(msg)
187            return
188        data = self.dataFromTable(self.currentTable())
189        # data['Data'] -> ['filename1', 'filename2', ...]
190        # look for the 'Data' column and extract the filename
191        for row in rows:
192            try:
193                filename = data['Data'][row]
194                # emit a signal so the plots are being shown
195                self.communicate.plotFromFilenameSignal.emit(filename)
196            except (IndexError, AttributeError):
197                # data messed up.
198                return
199
200    @classmethod
201    def dataFromTable(cls, table):
202        """
203        Creates a dictionary {<parameter>:[list of values]} from the parameter table
204        """
205        assert(isinstance(table, QtWidgets.QTableWidget))
206        params = {}
207        for column in range(table.columnCount()):
208            value = [table.item(row, column).data(0) for row in range(table.rowCount())]
209            key = table.horizontalHeaderItem(column).data(0)
210            params[key] = value
211        return params
212
213    def actionSendToExcel(self):
214        """
215        Generates a .csv file and opens the default CSV reader
216        """
217        if not self.grid_filename:
218            import tempfile
219            tmpfile = tempfile.NamedTemporaryFile(delete=False, mode="w+", suffix=".csv")
220            self.grid_filename = tmpfile.name
221            data = self.dataFromTable(self.currentTable())
222            t = time.localtime(time.time())
223            time_str = time.strftime("%b %d %H:%M of %Y", t)
224            details = "File Generated by SasView "
225            details += "on %s.\n" % time_str
226            self.writeBatchToFile(data=data, tmpfile=tmpfile, details=details)
227            tmpfile.close()
228
229        try:
230            from win32com.client import Dispatch
231            excel_app = Dispatch('Excel.Application')
232            excel_app.Workbooks.Open(self.grid_filename)
233            excel_app.Visible = 1
234        except Exception as ex:
235            msg = "Error occured when calling Excel.\n"
236            msg += ex
237            self.parent.communicate.statusBarUpdateSignal.emit(msg)
238
239    def actionSaveFile(self):
240        """
241        Generate a .csv file and dump it do disk
242        """
243        t = time.localtime(time.time())
244        time_str = time.strftime("%b %d %H %M of %Y", t)
245        default_name = "Batch_Fitting_"+time_str+".csv"
246
247        wildcard = "CSV files (*.csv);;"
248        kwargs = {
249            'caption'   : 'Save As',
250            'directory' : default_name,
251            'filter'    : wildcard,
252            'parent'    : None,
253        }
254        # Query user for filename.
255        filename_tuple = QtWidgets.QFileDialog.getSaveFileName(**kwargs)
256        filename = filename_tuple[0]
257
258        # User cancelled.
259        if not filename:
260            return
261        data = self.dataFromTable(self.currentTable())
262        details = "File generated by SasView\n"
263        with open(filename, 'w') as csv_file:
264            self.writeBatchToFile(data=data, tmpfile=csv_file, details=details)
265
266    def setupTableFromCSV(self, csv_data):
267        """
268        Create tablewidget items and show them, based on params
269        """
270        # Is this an empty grid?
271        if self.has_data:
272            # Add a new page
273            self.addTabPage()
274            # Access the newly created QTableWidget
275            current_page = self.tables[-1]
276        else:
277            current_page = self.tblParams
278        # headers
279        param_list = csv_data[1].rstrip().split(',')
280        # need to remove the 2 header rows to get the total data row number
281        rows = len(csv_data) -2
282        assert(rows > -1)
283        columns = len(param_list)
284        current_page.setColumnCount(columns)
285        current_page.setRowCount(rows)
286
287        for i, param in enumerate(param_list):
288            current_page.setHorizontalHeaderItem(i, QtWidgets.QTableWidgetItem(param))
289
290        # first - Chi2 and data filename
291        for i_row, row in enumerate(csv_data[2:]):
292            for i_col, col in enumerate(row.rstrip().split(',')):
293                current_page.setItem(i_row, i_col, QtWidgets.QTableWidgetItem(col))
294
295        current_page.resizeColumnsToContents()
296
297    def setupTable(self, widget=None, data=None):
298        """
299        Create tablewidget items and show them, based on params
300        """
301        # quietly leave is nothing to show
302        if data is None or widget is None:
303            return
304
305        # Figure out the headers
306        model = data[0][0]
307
308        # TODO: add a conditional for magnetic models
309        param_list = [m for m in model.model.params.keys() if ":" not in m]
310
311        # Check if 2D model. If not, remove theta/phi
312        if isinstance(model.data.sas_data, Data1D):
313            if 'theta' in param_list:
314                param_list.remove('theta')
315            if 'phi' in param_list:
316                param_list.remove('phi')
317
318        rows = len(data)
319        columns = len(param_list)
320
321        widget.setColumnCount(columns+2) # add 2 initial columns defined below
322        widget.setRowCount(rows)
323
324        # Insert two additional columns
325        param_list.insert(0, "Data")
326        param_list.insert(0, "Chi2")
327        for i, param in enumerate(param_list):
328            widget.setHorizontalHeaderItem(i, QtWidgets.QTableWidgetItem(param))
329
330        # dictionary of parameter errors for post-processing
331        # [param_name] = [param_column_nr, error_for_row_1, error_for_row_2,...]
332        error_columns = {}
333        # first - Chi2 and data filename
334        for i_row, row in enumerate(data):
335            # each row corresponds to a single fit
336            chi2 = row[0].fitness
337            filename = ""
338            if hasattr(row[0].data, "sas_data"):
339                filename = row[0].data.sas_data.filename
340            widget.setItem(i_row, 0, QtWidgets.QTableWidgetItem(GuiUtils.formatNumber(chi2, high=True)))
341            widget.setItem(i_row, 1, QtWidgets.QTableWidgetItem(str(filename)))
342            # Now, all the parameters
343            for i_col, param in enumerate(param_list[2:]):
344                if param in row[0].param_list:
345                    # parameter is on the to-optimize list - get the optimized value
346                    par_value = row[0].pvec[row[0].param_list.index(param)]
347                    # parse out errors and store them for later use
348                    err_value = row[0].stderr[row[0].param_list.index(param)]
349                    if param in error_columns:
350                        error_columns[param].append(err_value)
351                    else:
352                        error_columns[param] = [i_col, err_value]
353                else:
354                    # parameter was not varied
355                    par_value = row[0].model.params[param]
356
357                widget.setItem(i_row, i_col+2, QtWidgets.QTableWidgetItem(
358                    GuiUtils.formatNumber(par_value, high=True)))
359
360        # Add errors
361        error_list = list(error_columns.keys())
362        for error_param in error_list[::-1]: # must be reverse to keep column indices
363            # the offset for the err column: +2 from the first two extra columns, +1 to append this column
364            error_column = error_columns[error_param][0]+3
365            error_values = error_columns[error_param][1:]
366            widget.insertColumn(error_column)
367
368            column_name = error_param + self.ERROR_COLUMN_CAPTION
369            widget.setHorizontalHeaderItem(error_column, QtWidgets.QTableWidgetItem(column_name))
370
371            for i_row, error in enumerate(error_values):
372                item = QtWidgets.QTableWidgetItem(GuiUtils.formatNumber(error, high=True))
373                # Fancy, italic font for errors
374                font = QtGui.QFont()
375                font.setItalic(True)
376                item.setFont(font)
377                widget.setItem(i_row, error_column, item)
378
379        # resize content
380        widget.resizeColumnsToContents()
381
382    @classmethod
383    def writeBatchToFile(cls, data, tmpfile, details=""):
384        """
385        Helper to write result from batch into cvs file
386        """
387        name = tmpfile.name
388        if data is None or name is None or name.strip() == "":
389            return
390        _, ext = os.path.splitext(name)
391        separator = "\t"
392        if ext.lower() == ".csv":
393            separator = ","
394        tmpfile.write(details)
395        for col_name in data.keys():
396            tmpfile.write(col_name)
397            tmpfile.write(separator)
398        tmpfile.write('\n')
399        max_list = [len(value) for value in data.values()]
400        if len(max_list) == 0:
401            return
402        max_index = max(max_list)
403        index = 0
404        while index < max_index:
405            for value_list in data.values():
406                if index < len(value_list):
407                    tmpfile.write(str(value_list[index]))
408                    tmpfile.write(separator)
409                else:
410                    tmpfile.write('')
411                    tmpfile.write(separator)
412            tmpfile.write('\n')
413            index += 1
414
415
416class BatchInversionOutputPanel(BatchOutputPanel):
417    """
418        Class for stateless grid-like printout of P(r) parameters for any number
419        of data sets
420    """
421    def __init__(self, parent = None, output_data=None):
422
423        super(BatchInversionOutputPanel, self).__init__(parent._parent, output_data)
424        _translate = QtCore.QCoreApplication.translate
425        self.setWindowTitle(_translate("GridPanelUI", "Batch P(r) Results"))
426
427    def setupTable(self, widget=None,  data=None):
428        """
429        Create tablewidget items and show them, based on params
430        """
431        # headers
432        param_list = ['Filename', 'Rg [Å]', 'Chi^2/dof', 'I(Q=0)', 'Oscillations',
433                      'Background [Å^-1]', 'P+ Fraction', 'P+1-theta Fraction',
434                      'Calc. Time [sec]']
435
436        if data is None:
437            return
438        keys = data.keys()
439        rows = len(keys)
440        columns = len(param_list)
441        self.tblParams.setColumnCount(columns)
442        self.tblParams.setRowCount(rows)
443
444        for i, param in enumerate(param_list):
445            self.tblParams.setHorizontalHeaderItem(i, QtWidgets.QTableWidgetItem(param))
446
447        # first - Chi2 and data filename
448        for i_row, (filename, pr) in enumerate(data.items()):
449            out = pr.out
450            cov = pr.cov
451            if out is None:
452                logging.warning("P(r) for {} did not converge.".format(filename))
453                continue
454            self.tblParams.setItem(i_row, 0, QtWidgets.QTableWidgetItem(
455                "{}".format(filename)))
456            self.tblParams.setItem(i_row, 1, QtWidgets.QTableWidgetItem(
457                "{:.3g}".format(pr.rg(out))))
458            self.tblParams.setItem(i_row, 2, QtWidgets.QTableWidgetItem(
459                "{:.3g}".format(pr.chi2[0])))
460            self.tblParams.setItem(i_row, 3, QtWidgets.QTableWidgetItem(
461                "{:.3g}".format(pr.iq0(out))))
462            self.tblParams.setItem(i_row, 4, QtWidgets.QTableWidgetItem(
463                "{:.3g}".format(pr.oscillations(out))))
464            self.tblParams.setItem(i_row, 5, QtWidgets.QTableWidgetItem(
465                "{:.3g}".format(pr.background)))
466            self.tblParams.setItem(i_row, 6, QtWidgets.QTableWidgetItem(
467                "{:.3g}".format(pr.get_positive(out))))
468            self.tblParams.setItem(i_row, 7, QtWidgets.QTableWidgetItem(
469                "{:.3g}".format(pr.get_pos_err(out, cov))))
470            self.tblParams.setItem(i_row, 8, QtWidgets.QTableWidgetItem(
471                "{:.2g}".format(pr.elapsed)))
472
473        self.tblParams.resizeColumnsToContents()
474
475    @classmethod
476    def onHelp(cls):
477        """
478        Open a local url in the default browser
479        """
480        location = GuiUtils.HELP_DIRECTORY_LOCATION
481        url = "/user/sasgui/perspectives/pr/pr_help.html#batch-pr-mode"
482        try:
483            webbrowser.open('file://' + os.path.realpath(location + url))
484        except webbrowser.Error as ex:
485            logging.warning("Cannot display help. %s" % ex)
486
487    def closeEvent(self, event):
488        """Tell the parent window the window closed"""
489        self.parent.batchResultsWindow = None
490        event.accept()
Note: See TracBrowser for help on using the repository browser.