1 | import os |
---|
2 | import sys |
---|
3 | import time |
---|
4 | import logging |
---|
5 | import webbrowser |
---|
6 | |
---|
7 | from PyQt5 import QtCore, QtWidgets, QtGui |
---|
8 | |
---|
9 | import sas.qtgui.Utilities.GuiUtils as GuiUtils |
---|
10 | from sas.qtgui.Plotting.PlotterData import Data1D |
---|
11 | from sas.qtgui.Utilities.UI.GridPanelUI import Ui_GridPanelUI |
---|
12 | |
---|
13 | |
---|
14 | class 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 | # System dependent menu items |
---|
40 | if not self.IS_WIN: |
---|
41 | self.actionOpen_with_Excel.setVisible(False) |
---|
42 | |
---|
43 | # list of QTableWidgets, indexed by tab number |
---|
44 | self.tables = [] |
---|
45 | self.tables.append(self.tblParams) |
---|
46 | |
---|
47 | # context menu on the table |
---|
48 | self.tblParams.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) |
---|
49 | self.tblParams.customContextMenuRequested.connect(self.showContextMenu) |
---|
50 | |
---|
51 | # Command buttons |
---|
52 | self.cmdHelp.clicked.connect(self.onHelp) |
---|
53 | self.cmdPlot.clicked.connect(self.onPlot) |
---|
54 | |
---|
55 | # Fill in the table from input data |
---|
56 | self.setupTable(widget=self.tblParams, data=output_data) |
---|
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 | # notify the parent so it hides this window |
---|
67 | self.windowClosedSignal.emit() |
---|
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 | if self.has_data: |
---|
156 | self.addTabPage() |
---|
157 | # Update the new widget |
---|
158 | # Fill in the table from input data in the last/newest page |
---|
159 | assert(self.tables) |
---|
160 | self.setupTable(widget=self.tables[-1], data=results) |
---|
161 | self.has_data = True |
---|
162 | |
---|
163 | # Set a table tooltip describing the model |
---|
164 | model_name = results[0][0].model.id |
---|
165 | self.tabWidget.setTabToolTip(self.tabWidget.count()-1, model_name) |
---|
166 | |
---|
167 | |
---|
168 | @classmethod |
---|
169 | def onHelp(cls): |
---|
170 | """ |
---|
171 | Open a local url in the default browser |
---|
172 | """ |
---|
173 | location = GuiUtils.HELP_DIRECTORY_LOCATION |
---|
174 | url = "/user/qtgui/Perspectives/Fitting/fitting_help.html#batch-fit-mode" |
---|
175 | try: |
---|
176 | webbrowser.open('file://' + os.path.realpath(location+url)) |
---|
177 | except webbrowser.Error as ex: |
---|
178 | logging.warning("Cannot display help. %s" % ex) |
---|
179 | |
---|
180 | def onPlot(self): |
---|
181 | """ |
---|
182 | Plot selected fits by sending signal to the parent |
---|
183 | """ |
---|
184 | rows = [s.row() for s in self.currentTable().selectionModel().selectedRows()] |
---|
185 | if not rows: |
---|
186 | msg = "Nothing to plot!" |
---|
187 | self.parent.communicate.statusBarUpdateSignal.emit(msg) |
---|
188 | return |
---|
189 | data = self.dataFromTable(self.currentTable()) |
---|
190 | # data['Data'] -> ['filename1', 'filename2', ...] |
---|
191 | # look for the 'Data' column and extract the filename |
---|
192 | for row in rows: |
---|
193 | try: |
---|
194 | filename = data['Data'][row] |
---|
195 | # emit a signal so the plots are being shown |
---|
196 | self.communicate.plotFromFilenameSignal.emit(filename) |
---|
197 | except (IndexError, AttributeError): |
---|
198 | # data messed up. |
---|
199 | return |
---|
200 | |
---|
201 | @classmethod |
---|
202 | def dataFromTable(cls, table): |
---|
203 | """ |
---|
204 | Creates a dictionary {<parameter>:[list of values]} from the parameter table |
---|
205 | """ |
---|
206 | assert(isinstance(table, QtWidgets.QTableWidget)) |
---|
207 | params = {} |
---|
208 | for column in range(table.columnCount()): |
---|
209 | value = [table.item(row, column).data(0) for row in range(table.rowCount())] |
---|
210 | key = table.horizontalHeaderItem(column).data(0) |
---|
211 | params[key] = value |
---|
212 | return params |
---|
213 | |
---|
214 | def actionSendToExcel(self): |
---|
215 | """ |
---|
216 | Generates a .csv file and opens the default CSV reader |
---|
217 | """ |
---|
218 | if not self.grid_filename: |
---|
219 | import tempfile |
---|
220 | tmpfile = tempfile.NamedTemporaryFile(delete=False, mode="w+", suffix=".csv") |
---|
221 | self.grid_filename = tmpfile.name |
---|
222 | data = self.dataFromTable(self.currentTable()) |
---|
223 | t = time.localtime(time.time()) |
---|
224 | time_str = time.strftime("%b %d %H:%M of %Y", t) |
---|
225 | details = "File Generated by SasView " |
---|
226 | details += "on %s.\n" % time_str |
---|
227 | self.writeBatchToFile(data=data, tmpfile=tmpfile, details=details) |
---|
228 | tmpfile.close() |
---|
229 | |
---|
230 | try: |
---|
231 | from win32com.client import Dispatch |
---|
232 | excel_app = Dispatch('Excel.Application') |
---|
233 | excel_app.Workbooks.Open(self.grid_filename) |
---|
234 | excel_app.Visible = 1 |
---|
235 | except Exception as ex: |
---|
236 | msg = "Error occured when calling Excel.\n" |
---|
237 | msg += ex |
---|
238 | self.parent.communicate.statusBarUpdateSignal.emit(msg) |
---|
239 | |
---|
240 | def actionSaveFile(self): |
---|
241 | """ |
---|
242 | Generate a .csv file and dump it do disk |
---|
243 | """ |
---|
244 | t = time.localtime(time.time()) |
---|
245 | time_str = time.strftime("%b %d %H %M of %Y", t) |
---|
246 | default_name = "Batch_Fitting_"+time_str+".csv" |
---|
247 | |
---|
248 | wildcard = "CSV files (*.csv);;" |
---|
249 | kwargs = { |
---|
250 | 'caption' : 'Save As', |
---|
251 | 'directory' : default_name, |
---|
252 | 'filter' : wildcard, |
---|
253 | 'parent' : None, |
---|
254 | } |
---|
255 | # Query user for filename. |
---|
256 | filename_tuple = QtWidgets.QFileDialog.getSaveFileName(**kwargs) |
---|
257 | filename = filename_tuple[0] |
---|
258 | |
---|
259 | # User cancelled. |
---|
260 | if not filename: |
---|
261 | return |
---|
262 | data = self.dataFromTable(self.currentTable()) |
---|
263 | details = "File generated by SasView\n" |
---|
264 | with open(filename, 'w') as csv_file: |
---|
265 | self.writeBatchToFile(data=data, tmpfile=csv_file, details=details) |
---|
266 | |
---|
267 | def setupTableFromCSV(self, csv_data): |
---|
268 | """ |
---|
269 | Create tablewidget items and show them, based on params |
---|
270 | """ |
---|
271 | # Is this an empty grid? |
---|
272 | if self.has_data: |
---|
273 | # Add a new page |
---|
274 | self.addTabPage() |
---|
275 | # Access the newly created QTableWidget |
---|
276 | current_page = self.tables[-1] |
---|
277 | else: |
---|
278 | current_page = self.tblParams |
---|
279 | # headers |
---|
280 | param_list = csv_data[1].rstrip().split(',') |
---|
281 | # need to remove the 2 header rows to get the total data row number |
---|
282 | rows = len(csv_data) -2 |
---|
283 | assert(rows > -1) |
---|
284 | columns = len(param_list) |
---|
285 | current_page.setColumnCount(columns) |
---|
286 | current_page.setRowCount(rows) |
---|
287 | |
---|
288 | for i, param in enumerate(param_list): |
---|
289 | current_page.setHorizontalHeaderItem(i, QtWidgets.QTableWidgetItem(param)) |
---|
290 | |
---|
291 | # first - Chi2 and data filename |
---|
292 | for i_row, row in enumerate(csv_data[2:]): |
---|
293 | for i_col, col in enumerate(row.rstrip().split(',')): |
---|
294 | current_page.setItem(i_row, i_col, QtWidgets.QTableWidgetItem(col)) |
---|
295 | |
---|
296 | current_page.resizeColumnsToContents() |
---|
297 | |
---|
298 | def setupTable(self, widget=None, data=None): |
---|
299 | """ |
---|
300 | Create tablewidget items and show them, based on params |
---|
301 | """ |
---|
302 | # quietly leave is nothing to show |
---|
303 | if data is None or widget is None: |
---|
304 | return |
---|
305 | |
---|
306 | # Figure out the headers |
---|
307 | model = data[0][0] |
---|
308 | |
---|
309 | # TODO: add a conditional for magnetic models |
---|
310 | param_list = [m for m in model.model.params.keys() if ":" not in m] |
---|
311 | |
---|
312 | # Check if 2D model. If not, remove theta/phi |
---|
313 | if isinstance(model.data.sas_data, Data1D): |
---|
314 | if 'theta' in param_list: |
---|
315 | param_list.remove('theta') |
---|
316 | if 'phi' in param_list: |
---|
317 | param_list.remove('phi') |
---|
318 | |
---|
319 | rows = len(data) |
---|
320 | columns = len(param_list) |
---|
321 | |
---|
322 | widget.setColumnCount(columns+2) # add 2 initial columns defined below |
---|
323 | widget.setRowCount(rows) |
---|
324 | |
---|
325 | # Insert two additional columns |
---|
326 | param_list.insert(0, "Data") |
---|
327 | param_list.insert(0, "Chi2") |
---|
328 | for i, param in enumerate(param_list): |
---|
329 | widget.setHorizontalHeaderItem(i, QtWidgets.QTableWidgetItem(param)) |
---|
330 | |
---|
331 | # dictionary of parameter errors for post-processing |
---|
332 | # [param_name] = [param_column_nr, error_for_row_1, error_for_row_2,...] |
---|
333 | error_columns = {} |
---|
334 | # first - Chi2 and data filename |
---|
335 | for i_row, row in enumerate(data): |
---|
336 | # each row corresponds to a single fit |
---|
337 | chi2 = row[0].fitness |
---|
338 | filename = "" |
---|
339 | if hasattr(row[0].data, "sas_data"): |
---|
340 | filename = row[0].data.sas_data.filename |
---|
341 | widget.setItem(i_row, 0, QtWidgets.QTableWidgetItem(GuiUtils.formatNumber(chi2, high=True))) |
---|
342 | widget.setItem(i_row, 1, QtWidgets.QTableWidgetItem(str(filename))) |
---|
343 | # Now, all the parameters |
---|
344 | for i_col, param in enumerate(param_list[2:]): |
---|
345 | if param in row[0].param_list: |
---|
346 | # parameter is on the to-optimize list - get the optimized value |
---|
347 | par_value = row[0].pvec[row[0].param_list.index(param)] |
---|
348 | # parse out errors and store them for later use |
---|
349 | err_value = row[0].stderr[row[0].param_list.index(param)] |
---|
350 | if param in error_columns: |
---|
351 | error_columns[param].append(err_value) |
---|
352 | else: |
---|
353 | error_columns[param] = [i_col, err_value] |
---|
354 | else: |
---|
355 | # parameter was not varied |
---|
356 | par_value = row[0].model.params[param] |
---|
357 | |
---|
358 | widget.setItem(i_row, i_col+2, QtWidgets.QTableWidgetItem( |
---|
359 | GuiUtils.formatNumber(par_value, high=True))) |
---|
360 | |
---|
361 | # Add errors |
---|
362 | error_list = list(error_columns.keys()) |
---|
363 | for error_param in error_list[::-1]: # must be reverse to keep column indices |
---|
364 | # the offset for the err column: +2 from the first two extra columns, +1 to append this column |
---|
365 | error_column = error_columns[error_param][0]+3 |
---|
366 | error_values = error_columns[error_param][1:] |
---|
367 | widget.insertColumn(error_column) |
---|
368 | |
---|
369 | column_name = error_param + self.ERROR_COLUMN_CAPTION |
---|
370 | widget.setHorizontalHeaderItem(error_column, QtWidgets.QTableWidgetItem(column_name)) |
---|
371 | |
---|
372 | for i_row, error in enumerate(error_values): |
---|
373 | item = QtWidgets.QTableWidgetItem(GuiUtils.formatNumber(error, high=True)) |
---|
374 | # Fancy, italic font for errors |
---|
375 | font = QtGui.QFont() |
---|
376 | font.setItalic(True) |
---|
377 | item.setFont(font) |
---|
378 | widget.setItem(i_row, error_column, item) |
---|
379 | |
---|
380 | # resize content |
---|
381 | widget.resizeColumnsToContents() |
---|
382 | |
---|
383 | @classmethod |
---|
384 | def writeBatchToFile(cls, data, tmpfile, details=""): |
---|
385 | """ |
---|
386 | Helper to write result from batch into cvs file |
---|
387 | """ |
---|
388 | name = tmpfile.name |
---|
389 | if data is None or name is None or name.strip() == "": |
---|
390 | return |
---|
391 | _, ext = os.path.splitext(name) |
---|
392 | separator = "\t" |
---|
393 | if ext.lower() == ".csv": |
---|
394 | separator = "," |
---|
395 | tmpfile.write(details) |
---|
396 | for col_name in data.keys(): |
---|
397 | tmpfile.write(col_name) |
---|
398 | tmpfile.write(separator) |
---|
399 | tmpfile.write('\n') |
---|
400 | max_list = [len(value) for value in data.values()] |
---|
401 | if len(max_list) == 0: |
---|
402 | return |
---|
403 | max_index = max(max_list) |
---|
404 | index = 0 |
---|
405 | while index < max_index: |
---|
406 | for value_list in data.values(): |
---|
407 | if index < len(value_list): |
---|
408 | tmpfile.write(str(value_list[index])) |
---|
409 | tmpfile.write(separator) |
---|
410 | else: |
---|
411 | tmpfile.write('') |
---|
412 | tmpfile.write(separator) |
---|
413 | tmpfile.write('\n') |
---|
414 | index += 1 |
---|
415 | |
---|
416 | |
---|
417 | class BatchInversionOutputPanel(BatchOutputPanel): |
---|
418 | """ |
---|
419 | Class for stateless grid-like printout of P(r) parameters for any number |
---|
420 | of data sets |
---|
421 | """ |
---|
422 | def __init__(self, parent = None, output_data=None): |
---|
423 | |
---|
424 | super(BatchInversionOutputPanel, self).__init__(parent._parent, output_data) |
---|
425 | _translate = QtCore.QCoreApplication.translate |
---|
426 | self.setWindowTitle(_translate("GridPanelUI", "Batch P(r) Results")) |
---|
427 | |
---|
428 | def setupTable(self, widget=None, data=None): |
---|
429 | """ |
---|
430 | Create tablewidget items and show them, based on params |
---|
431 | """ |
---|
432 | # headers |
---|
433 | param_list = ['Filename', 'Rg [Ã
]', 'Chi^2/dof', 'I(Q=0)', 'Oscillations', |
---|
434 | 'Background [Ã
^-1]', 'P+ Fraction', 'P+1-theta Fraction', |
---|
435 | 'Calc. Time [sec]'] |
---|
436 | |
---|
437 | if data is None: |
---|
438 | return |
---|
439 | keys = data.keys() |
---|
440 | rows = len(keys) |
---|
441 | columns = len(param_list) |
---|
442 | self.tblParams.setColumnCount(columns) |
---|
443 | self.tblParams.setRowCount(rows) |
---|
444 | |
---|
445 | for i, param in enumerate(param_list): |
---|
446 | self.tblParams.setHorizontalHeaderItem(i, QtWidgets.QTableWidgetItem(param)) |
---|
447 | |
---|
448 | # first - Chi2 and data filename |
---|
449 | for i_row, (filename, pr) in enumerate(data.items()): |
---|
450 | out = pr.out |
---|
451 | cov = pr.cov |
---|
452 | if out is None: |
---|
453 | logging.warning("P(r) for {} did not converge.".format(filename)) |
---|
454 | continue |
---|
455 | self.tblParams.setItem(i_row, 0, QtWidgets.QTableWidgetItem( |
---|
456 | "{}".format(filename))) |
---|
457 | self.tblParams.setItem(i_row, 1, QtWidgets.QTableWidgetItem( |
---|
458 | "{:.3g}".format(pr.rg(out)))) |
---|
459 | self.tblParams.setItem(i_row, 2, QtWidgets.QTableWidgetItem( |
---|
460 | "{:.3g}".format(pr.chi2[0]))) |
---|
461 | self.tblParams.setItem(i_row, 3, QtWidgets.QTableWidgetItem( |
---|
462 | "{:.3g}".format(pr.iq0(out)))) |
---|
463 | self.tblParams.setItem(i_row, 4, QtWidgets.QTableWidgetItem( |
---|
464 | "{:.3g}".format(pr.oscillations(out)))) |
---|
465 | self.tblParams.setItem(i_row, 5, QtWidgets.QTableWidgetItem( |
---|
466 | "{:.3g}".format(pr.background))) |
---|
467 | self.tblParams.setItem(i_row, 6, QtWidgets.QTableWidgetItem( |
---|
468 | "{:.3g}".format(pr.get_positive(out)))) |
---|
469 | self.tblParams.setItem(i_row, 7, QtWidgets.QTableWidgetItem( |
---|
470 | "{:.3g}".format(pr.get_pos_err(out, cov)))) |
---|
471 | self.tblParams.setItem(i_row, 8, QtWidgets.QTableWidgetItem( |
---|
472 | "{:.2g}".format(pr.elapsed))) |
---|
473 | |
---|
474 | self.tblParams.resizeColumnsToContents() |
---|
475 | |
---|
476 | @classmethod |
---|
477 | def onHelp(cls): |
---|
478 | """ |
---|
479 | Open a local url in the default browser |
---|
480 | """ |
---|
481 | location = GuiUtils.HELP_DIRECTORY_LOCATION |
---|
482 | url = "/user/sasgui/perspectives/pr/pr_help.html#batch-pr-mode" |
---|
483 | try: |
---|
484 | webbrowser.open('file://' + os.path.realpath(location + url)) |
---|
485 | except webbrowser.Error as ex: |
---|
486 | logging.warning("Cannot display help. %s" % ex) |
---|
487 | |
---|
488 | def closeEvent(self, event): |
---|
489 | """Tell the parent window the window closed""" |
---|
490 | self.parent.batchResultsWindow = None |
---|
491 | event.accept() |
---|