source: sasview/src/sas/qtgui/Utilities/GridPanel.py @ 99f8760

ESS_GUIESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_openclESS_GUI_sync_sascalc
Last change on this file since 99f8760 was 99f8760, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 5 years ago

Improvements to batch save/load SASVIEW-1222.
Project save/load will now recreate the grid window as well as retain
result theories under dataset indices.

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