1 | import logging |
---|
2 | |
---|
3 | from twisted.internet import threads |
---|
4 | |
---|
5 | import sas.qtgui.Utilities.GuiUtils as GuiUtils |
---|
6 | import sas.qtgui.Utilities.LocalConfig as LocalConfig |
---|
7 | |
---|
8 | from PyQt5 import QtGui, QtCore, QtWidgets |
---|
9 | |
---|
10 | from sas.sascalc.fit.BumpsFitting import BumpsFit as Fit |
---|
11 | |
---|
12 | import sas.qtgui.Utilities.ObjectLibrary as ObjectLibrary |
---|
13 | from sas.qtgui.Perspectives.Fitting.UI.ConstraintWidgetUI import Ui_ConstraintWidgetUI |
---|
14 | from sas.qtgui.Perspectives.Fitting.FittingWidget import FittingWidget |
---|
15 | from sas.qtgui.Perspectives.Fitting.FitThread import FitThread |
---|
16 | from sas.qtgui.Perspectives.Fitting.ConsoleUpdate import ConsoleUpdate |
---|
17 | from sas.qtgui.Perspectives.Fitting.ComplexConstraint import ComplexConstraint |
---|
18 | from sas.qtgui.Perspectives.Fitting.Constraint import Constraint |
---|
19 | |
---|
20 | class ConstraintWidget(QtWidgets.QWidget, Ui_ConstraintWidgetUI): |
---|
21 | """ |
---|
22 | Constraints Dialog to select the desired parameter/model constraints. |
---|
23 | """ |
---|
24 | |
---|
25 | def __init__(self, parent=None): |
---|
26 | super(ConstraintWidget, self).__init__() |
---|
27 | self.parent = parent |
---|
28 | self.setupUi(self) |
---|
29 | self.currentType = "FitPage" |
---|
30 | # Page id for fitting |
---|
31 | # To keep with previous SasView values, use 300 as the start offset |
---|
32 | self.page_id = 301 |
---|
33 | |
---|
34 | # Are we chain fitting? |
---|
35 | self.is_chain_fitting = False |
---|
36 | |
---|
37 | # Remember previous content of modified cell |
---|
38 | self.current_cell = "" |
---|
39 | |
---|
40 | # Tabs used in simultaneous fitting |
---|
41 | # tab_name : True/False |
---|
42 | self.tabs_for_fitting = {} |
---|
43 | |
---|
44 | # Set up the widgets |
---|
45 | self.initializeWidgets() |
---|
46 | |
---|
47 | # Set up signals/slots |
---|
48 | self.initializeSignals() |
---|
49 | |
---|
50 | # Create the list of tabs |
---|
51 | self.initializeFitList() |
---|
52 | |
---|
53 | def acceptsData(self): |
---|
54 | """ Tells the caller this widget doesn't accept data """ |
---|
55 | return False |
---|
56 | |
---|
57 | def initializeWidgets(self): |
---|
58 | """ |
---|
59 | Set up various widget states |
---|
60 | """ |
---|
61 | labels = ['FitPage', 'Model', 'Data', 'Mnemonic'] |
---|
62 | # tab widget - headers |
---|
63 | self.editable_tab_columns = [labels.index('Mnemonic')] |
---|
64 | self.tblTabList.setColumnCount(len(labels)) |
---|
65 | self.tblTabList.setHorizontalHeaderLabels(labels) |
---|
66 | self.tblTabList.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch) |
---|
67 | |
---|
68 | self.tblTabList.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) |
---|
69 | self.tblTabList.customContextMenuRequested.connect(self.showModelContextMenu) |
---|
70 | |
---|
71 | # Single Fit is the default, so disable chainfit |
---|
72 | self.chkChain.setVisible(False) |
---|
73 | |
---|
74 | # disabled constraint |
---|
75 | labels = ['Constraint'] |
---|
76 | self.tblConstraints.setColumnCount(len(labels)) |
---|
77 | self.tblConstraints.setHorizontalHeaderLabels(labels) |
---|
78 | self.tblConstraints.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch) |
---|
79 | self.tblConstraints.setEnabled(False) |
---|
80 | |
---|
81 | self.tblConstraints.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) |
---|
82 | self.tblConstraints.customContextMenuRequested.connect(self.showConstrContextMenu) |
---|
83 | |
---|
84 | def initializeSignals(self): |
---|
85 | """ |
---|
86 | Set up signals/slots for this widget |
---|
87 | """ |
---|
88 | # simple widgets |
---|
89 | self.btnSingle.toggled.connect(self.onFitTypeChange) |
---|
90 | self.btnBatch.toggled.connect(self.onFitTypeChange) |
---|
91 | self.cbCases.currentIndexChanged.connect(self.onSpecialCaseChange) |
---|
92 | self.cmdFit.clicked.connect(self.onFit) |
---|
93 | self.cmdHelp.clicked.connect(self.onHelp) |
---|
94 | self.chkChain.toggled.connect(self.onChainFit) |
---|
95 | |
---|
96 | # QTableWidgets |
---|
97 | self.tblTabList.cellChanged.connect(self.onTabCellEdit) |
---|
98 | self.tblTabList.cellDoubleClicked.connect(self.onTabCellEntered) |
---|
99 | self.tblConstraints.cellChanged.connect(self.onConstraintChange) |
---|
100 | |
---|
101 | # External signals |
---|
102 | self.parent.tabsModifiedSignal.connect(self.initializeFitList) |
---|
103 | |
---|
104 | def updateSignalsFromTab(self, tab=None): |
---|
105 | """ |
---|
106 | Intercept update signals from fitting tabs |
---|
107 | """ |
---|
108 | if tab is None: |
---|
109 | return |
---|
110 | tab_object = ObjectLibrary.getObject(tab) |
---|
111 | |
---|
112 | # Disconnect all local slots |
---|
113 | #tab_object.disconnect() |
---|
114 | |
---|
115 | # Reconnect tab signals to local slots |
---|
116 | tab_object.constraintAddedSignal.connect(self.initializeFitList) |
---|
117 | tab_object.newModelSignal.connect(self.initializeFitList) |
---|
118 | |
---|
119 | def onFitTypeChange(self, checked): |
---|
120 | """ |
---|
121 | Respond to the fit type change |
---|
122 | single fit/batch fit |
---|
123 | """ |
---|
124 | source = self.sender().objectName() |
---|
125 | self.currentType = "BatchPage" if source == "btnBatch" else "FitPage" |
---|
126 | self.chkChain.setVisible(source=="btnBatch") |
---|
127 | self.initializeFitList() |
---|
128 | |
---|
129 | def onSpecialCaseChange(self, index): |
---|
130 | """ |
---|
131 | Respond to the combobox change for special case constraint sets |
---|
132 | """ |
---|
133 | pass |
---|
134 | |
---|
135 | def getTabsForFit(self): |
---|
136 | """ |
---|
137 | Returns list of tab names selected for fitting |
---|
138 | """ |
---|
139 | return [tab for tab in self.tabs_for_fitting if self.tabs_for_fitting[tab]] |
---|
140 | |
---|
141 | def onChainFit(self, is_checked): |
---|
142 | """ |
---|
143 | Respond to selecting the Chain Fit checkbox |
---|
144 | """ |
---|
145 | self.is_chain_fitting = is_checked |
---|
146 | |
---|
147 | def onFit(self): |
---|
148 | """ |
---|
149 | Perform the constrained/simultaneous fit |
---|
150 | """ |
---|
151 | # Find out all tabs to fit |
---|
152 | tabs_to_fit = self.getTabsForFit() |
---|
153 | |
---|
154 | # Single fitter for the simultaneous run |
---|
155 | fitter = Fit() |
---|
156 | fitter.fitter_id = self.page_id |
---|
157 | |
---|
158 | # Notify the parent about fitting started |
---|
159 | self.parent.fittingStartedSignal.emit(tabs_to_fit) |
---|
160 | |
---|
161 | # prepare fitting problems for each tab |
---|
162 | # |
---|
163 | page_ids = [] |
---|
164 | fitter_id = 0 |
---|
165 | sim_fitter_list=[fitter] |
---|
166 | # Prepare the fitter object |
---|
167 | try: |
---|
168 | for tab in tabs_to_fit: |
---|
169 | tab_object = ObjectLibrary.getObject(tab) |
---|
170 | if tab_object is None: |
---|
171 | # No such tab! |
---|
172 | return |
---|
173 | sim_fitter_list, fitter_id = \ |
---|
174 | tab_object.prepareFitters(fitter=sim_fitter_list[0], fit_id=fitter_id) |
---|
175 | page_ids.append([tab_object.page_id]) |
---|
176 | except ValueError: |
---|
177 | # No parameters selected in one of the tabs |
---|
178 | no_params_msg = "Fitting can not be performed.\n" +\ |
---|
179 | "Not all tabs chosen for fitting have parameters selected for fitting." |
---|
180 | QtWidgets.QMessageBox.warning(self, |
---|
181 | 'Warning', |
---|
182 | no_params_msg, |
---|
183 | QtWidgets.QMessageBox.Ok) |
---|
184 | |
---|
185 | return |
---|
186 | |
---|
187 | # Create the fitting thread, based on the fitter |
---|
188 | completefn = self.onBatchFitComplete if self.currentType=='BatchPage' else self.onFitComplete |
---|
189 | |
---|
190 | if LocalConfig.USING_TWISTED: |
---|
191 | handler = None |
---|
192 | updater = None |
---|
193 | else: |
---|
194 | handler = ConsoleUpdate(parent=self.parent, |
---|
195 | manager=self, |
---|
196 | improvement_delta=0.1) |
---|
197 | updater = handler.update_fit |
---|
198 | |
---|
199 | batch_inputs = {} |
---|
200 | batch_outputs = {} |
---|
201 | |
---|
202 | # new fit thread object |
---|
203 | calc_fit = FitThread(handler=handler, |
---|
204 | fn=sim_fitter_list, |
---|
205 | batch_inputs=batch_inputs, |
---|
206 | batch_outputs=batch_outputs, |
---|
207 | page_id=page_ids, |
---|
208 | updatefn=updater, |
---|
209 | completefn=completefn, |
---|
210 | reset_flag=self.is_chain_fitting) |
---|
211 | |
---|
212 | if LocalConfig.USING_TWISTED: |
---|
213 | # start the trhrhread with twisted |
---|
214 | calc_thread = threads.deferToThread(calc_fit.compute) |
---|
215 | calc_thread.addCallback(completefn) |
---|
216 | calc_thread.addErrback(self.onFitFailed) |
---|
217 | else: |
---|
218 | # Use the old python threads + Queue |
---|
219 | calc_fit.queue() |
---|
220 | calc_fit.ready(2.5) |
---|
221 | |
---|
222 | |
---|
223 | #disable the Fit button |
---|
224 | self.cmdFit.setText('Running...') |
---|
225 | self.parent.communicate.statusBarUpdateSignal.emit('Fitting started...') |
---|
226 | self.cmdFit.setEnabled(False) |
---|
227 | |
---|
228 | def onHelp(self): |
---|
229 | """ |
---|
230 | Show the "Fitting" section of help |
---|
231 | """ |
---|
232 | tree_location = "/user/qtgui/Perspectives/Fitting/" |
---|
233 | |
---|
234 | helpfile = "fitting_help.html#simultaneous-fit-mode" |
---|
235 | help_location = tree_location + helpfile |
---|
236 | |
---|
237 | # OMG, really? Crawling up the object hierarchy... |
---|
238 | self.parent.parent.showHelp(help_location) |
---|
239 | |
---|
240 | def onTabCellEdit(self, row, column): |
---|
241 | """ |
---|
242 | Respond to check/uncheck and to modify the model moniker actions |
---|
243 | """ |
---|
244 | item = self.tblTabList.item(row, column) |
---|
245 | if column == 0: |
---|
246 | # Update the tabs for fitting list |
---|
247 | tab_name = item.text() |
---|
248 | self.tabs_for_fitting[tab_name] = (item.checkState() == QtCore.Qt.Checked) |
---|
249 | # Enable fitting only when there are models to fit |
---|
250 | self.cmdFit.setEnabled(any(self.tabs_for_fitting.values())) |
---|
251 | |
---|
252 | if column not in self.editable_tab_columns: |
---|
253 | return |
---|
254 | new_moniker = item.data(0) |
---|
255 | |
---|
256 | # The new name should be validated on the fly, with QValidator |
---|
257 | # but let's just assure it post-factum |
---|
258 | is_good_moniker = self.validateMoniker(new_moniker) |
---|
259 | if not is_good_moniker: |
---|
260 | self.tblTabList.blockSignals(True) |
---|
261 | item.setBackground(QtCore.Qt.red) |
---|
262 | self.tblTabList.blockSignals(False) |
---|
263 | self.cmdFit.setEnabled(False) |
---|
264 | return |
---|
265 | self.tblTabList.blockSignals(True) |
---|
266 | item.setBackground(QtCore.Qt.white) |
---|
267 | self.tblTabList.blockSignals(False) |
---|
268 | self.cmdFit.setEnabled(True) |
---|
269 | if not self.current_cell: |
---|
270 | return |
---|
271 | # Remember the value |
---|
272 | if self.current_cell not in self.available_tabs: |
---|
273 | return |
---|
274 | temp_tab = self.available_tabs[self.current_cell] |
---|
275 | # Remove the key from the dictionaries |
---|
276 | self.available_tabs.pop(self.current_cell, None) |
---|
277 | # Change the model name |
---|
278 | model = temp_tab.kernel_module |
---|
279 | model.name = new_moniker |
---|
280 | # Replace constraint name |
---|
281 | temp_tab.replaceConstraintName(self.current_cell, new_moniker) |
---|
282 | # Replace constraint name in the remaining tabs |
---|
283 | for tab in self.available_tabs.values(): |
---|
284 | tab.replaceConstraintName(self.current_cell, new_moniker) |
---|
285 | # Reinitialize the display |
---|
286 | self.initializeFitList() |
---|
287 | |
---|
288 | def onConstraintChange(self, row, column): |
---|
289 | """ |
---|
290 | Modify the constraint's "active" instance variable. |
---|
291 | """ |
---|
292 | item = self.tblConstraints.item(row, column) |
---|
293 | if column == 0: |
---|
294 | # Update the tabs for fitting list |
---|
295 | constraint = self.available_constraints[row] |
---|
296 | constraint.active = (item.checkState() == QtCore.Qt.Checked) |
---|
297 | |
---|
298 | def onTabCellEntered(self, row, column): |
---|
299 | """ |
---|
300 | Remember the original tab list cell data. |
---|
301 | Needed for reverting back on bad validation |
---|
302 | """ |
---|
303 | if column != 3: |
---|
304 | return |
---|
305 | self.current_cell = self.tblTabList.item(row, column).data(0) |
---|
306 | |
---|
307 | def onFitComplete(self, result): |
---|
308 | """ |
---|
309 | Respond to the successful fit complete signal |
---|
310 | """ |
---|
311 | #re-enable the Fit button |
---|
312 | self.cmdFit.setText("Fit") |
---|
313 | self.cmdFit.setEnabled(True) |
---|
314 | |
---|
315 | # Notify the parent about completed fitting |
---|
316 | self.parent.fittingStoppedSignal.emit(self.getTabsForFit()) |
---|
317 | |
---|
318 | # Assure the fitting succeeded |
---|
319 | if result is None or not result: |
---|
320 | msg = "Fitting failed. Please ensure correctness of chosen constraints." |
---|
321 | self.parent.communicate.statusBarUpdateSignal.emit(msg) |
---|
322 | return |
---|
323 | |
---|
324 | # get the elapsed time |
---|
325 | elapsed = result[1] |
---|
326 | |
---|
327 | # result list |
---|
328 | results = result[0][0] |
---|
329 | |
---|
330 | # Find out all tabs to fit |
---|
331 | tabs_to_fit = [tab for tab in self.tabs_for_fitting if self.tabs_for_fitting[tab]] |
---|
332 | |
---|
333 | # update all involved tabs |
---|
334 | for i, tab in enumerate(tabs_to_fit): |
---|
335 | tab_object = ObjectLibrary.getObject(tab) |
---|
336 | if tab_object is None: |
---|
337 | # No such tab. removed while job was running |
---|
338 | return |
---|
339 | # Make sure result and target objects are the same (same model moniker) |
---|
340 | if tab_object.kernel_module.name == results[i].model.name: |
---|
341 | tab_object.fitComplete(([[results[i]]], elapsed)) |
---|
342 | |
---|
343 | msg = "Fitting completed successfully in: %s s.\n" % GuiUtils.formatNumber(elapsed) |
---|
344 | self.parent.communicate.statusBarUpdateSignal.emit(msg) |
---|
345 | |
---|
346 | def onBatchFitComplete(self, result): |
---|
347 | """ |
---|
348 | Respond to the successful batch fit complete signal |
---|
349 | """ |
---|
350 | #re-enable the Fit button |
---|
351 | self.cmdFit.setText("Fit") |
---|
352 | self.cmdFit.setEnabled(True) |
---|
353 | |
---|
354 | # Notify the parent about completed fitting |
---|
355 | self.parent.fittingStoppedSignal.emit(self.getTabsForFit()) |
---|
356 | |
---|
357 | # get the elapsed time |
---|
358 | elapsed = result[1] |
---|
359 | |
---|
360 | if result is None: |
---|
361 | msg = "Fitting failed." |
---|
362 | self.parent.communicate.statusBarUpdateSignal.emit(msg) |
---|
363 | return |
---|
364 | |
---|
365 | # Show the grid panel |
---|
366 | self.parent.communicate.sendDataToGridSignal.emit(result[0]) |
---|
367 | |
---|
368 | msg = "Fitting completed successfully in: %s s.\n" % GuiUtils.formatNumber(elapsed) |
---|
369 | self.parent.communicate.statusBarUpdateSignal.emit(msg) |
---|
370 | |
---|
371 | def onFitFailed(self, reason): |
---|
372 | """ |
---|
373 | Respond to fitting failure. |
---|
374 | """ |
---|
375 | #re-enable the Fit button |
---|
376 | self.cmdFit.setText("Fit") |
---|
377 | self.cmdFit.setEnabled(True) |
---|
378 | |
---|
379 | # Notify the parent about completed fitting |
---|
380 | self.parent.fittingStoppedSignal.emit(self.getTabsForFit()) |
---|
381 | |
---|
382 | msg = "Fitting failed: %s s.\n" % reason |
---|
383 | self.parent.communicate.statusBarUpdateSignal.emit(msg) |
---|
384 | |
---|
385 | def isTabImportable(self, tab): |
---|
386 | """ |
---|
387 | Determines if the tab can be imported and included in the widget |
---|
388 | """ |
---|
389 | if not isinstance(tab, str): return False |
---|
390 | if not self.currentType in tab: return False |
---|
391 | object = ObjectLibrary.getObject(tab) |
---|
392 | if not isinstance(object, FittingWidget): return False |
---|
393 | if not object.data_is_loaded : return False |
---|
394 | return True |
---|
395 | |
---|
396 | def showModelContextMenu(self, position): |
---|
397 | """ |
---|
398 | Show context specific menu in the tab table widget. |
---|
399 | """ |
---|
400 | menu = QtWidgets.QMenu() |
---|
401 | rows = [s.row() for s in self.tblTabList.selectionModel().selectedRows()] |
---|
402 | num_rows = len(rows) |
---|
403 | if num_rows <= 0: |
---|
404 | return |
---|
405 | # Select for fitting |
---|
406 | param_string = "Fit Page " if num_rows==1 else "Fit Pages " |
---|
407 | |
---|
408 | self.actionSelect = QtWidgets.QAction(self) |
---|
409 | self.actionSelect.setObjectName("actionSelect") |
---|
410 | self.actionSelect.setText(QtCore.QCoreApplication.translate("self", "Select "+param_string+" for fitting")) |
---|
411 | # Unselect from fitting |
---|
412 | self.actionDeselect = QtWidgets.QAction(self) |
---|
413 | self.actionDeselect.setObjectName("actionDeselect") |
---|
414 | self.actionDeselect.setText(QtCore.QCoreApplication.translate("self", "De-select "+param_string+" from fitting")) |
---|
415 | |
---|
416 | self.actionRemoveConstraint = QtWidgets.QAction(self) |
---|
417 | self.actionRemoveConstraint.setObjectName("actionRemoveConstrain") |
---|
418 | self.actionRemoveConstraint.setText(QtCore.QCoreApplication.translate("self", "Remove all constraints on selected models")) |
---|
419 | |
---|
420 | self.actionMutualMultiConstrain = QtWidgets.QAction(self) |
---|
421 | self.actionMutualMultiConstrain.setObjectName("actionMutualMultiConstrain") |
---|
422 | self.actionMutualMultiConstrain.setText(QtCore.QCoreApplication.translate("self", "Mutual constrain of parameters in selected models...")) |
---|
423 | |
---|
424 | menu.addAction(self.actionSelect) |
---|
425 | menu.addAction(self.actionDeselect) |
---|
426 | menu.addSeparator() |
---|
427 | |
---|
428 | if num_rows >= 2: |
---|
429 | menu.addAction(self.actionMutualMultiConstrain) |
---|
430 | |
---|
431 | # Define the callbacks |
---|
432 | self.actionMutualMultiConstrain.triggered.connect(self.showMultiConstraint) |
---|
433 | self.actionSelect.triggered.connect(self.selectModels) |
---|
434 | self.actionDeselect.triggered.connect(self.deselectModels) |
---|
435 | try: |
---|
436 | menu.exec_(self.tblTabList.viewport().mapToGlobal(position)) |
---|
437 | except AttributeError as ex: |
---|
438 | logging.error("Error generating context menu: %s" % ex) |
---|
439 | return |
---|
440 | |
---|
441 | def showConstrContextMenu(self, position): |
---|
442 | """ |
---|
443 | Show context specific menu in the tab table widget. |
---|
444 | """ |
---|
445 | menu = QtWidgets.QMenu() |
---|
446 | rows = [s.row() for s in self.tblConstraints.selectionModel().selectedRows()] |
---|
447 | num_rows = len(rows) |
---|
448 | if num_rows <= 0: |
---|
449 | return |
---|
450 | # Select for fitting |
---|
451 | param_string = "constraint " if num_rows==1 else "constraints " |
---|
452 | |
---|
453 | self.actionSelect = QtWidgets.QAction(self) |
---|
454 | self.actionSelect.setObjectName("actionSelect") |
---|
455 | self.actionSelect.setText(QtCore.QCoreApplication.translate("self", "Select "+param_string+" for fitting")) |
---|
456 | # Unselect from fitting |
---|
457 | self.actionDeselect = QtWidgets.QAction(self) |
---|
458 | self.actionDeselect.setObjectName("actionDeselect") |
---|
459 | self.actionDeselect.setText(QtCore.QCoreApplication.translate("self", "De-select "+param_string+" from fitting")) |
---|
460 | |
---|
461 | self.actionRemoveConstraint = QtWidgets.QAction(self) |
---|
462 | self.actionRemoveConstraint.setObjectName("actionRemoveConstrain") |
---|
463 | self.actionRemoveConstraint.setText(QtCore.QCoreApplication.translate("self", "Remove "+param_string)) |
---|
464 | |
---|
465 | menu.addAction(self.actionSelect) |
---|
466 | menu.addAction(self.actionDeselect) |
---|
467 | menu.addSeparator() |
---|
468 | menu.addAction(self.actionRemoveConstraint) |
---|
469 | |
---|
470 | # Define the callbacks |
---|
471 | self.actionRemoveConstraint.triggered.connect(self.deleteConstraint) |
---|
472 | self.actionSelect.triggered.connect(self.selectConstraints) |
---|
473 | self.actionDeselect.triggered.connect(self.deselectConstraints) |
---|
474 | try: |
---|
475 | menu.exec_(self.tblConstraints.viewport().mapToGlobal(position)) |
---|
476 | except AttributeError as ex: |
---|
477 | logging.error("Error generating context menu: %s" % ex) |
---|
478 | return |
---|
479 | |
---|
480 | def selectConstraints(self): |
---|
481 | """ |
---|
482 | Selected constraints are chosen for fitting |
---|
483 | """ |
---|
484 | status = QtCore.Qt.Checked |
---|
485 | self.setRowSelection(self.tblConstraints, status) |
---|
486 | |
---|
487 | def deselectConstraints(self): |
---|
488 | """ |
---|
489 | Selected constraints are removed for fitting |
---|
490 | """ |
---|
491 | status = QtCore.Qt.Unchecked |
---|
492 | self.setRowSelection(self.tblConstraints, status) |
---|
493 | |
---|
494 | def selectModels(self): |
---|
495 | """ |
---|
496 | Selected models are chosen for fitting |
---|
497 | """ |
---|
498 | status = QtCore.Qt.Checked |
---|
499 | self.setRowSelection(self.tblTabList, status) |
---|
500 | |
---|
501 | def deselectModels(self): |
---|
502 | """ |
---|
503 | Selected models are removed for fitting |
---|
504 | """ |
---|
505 | status = QtCore.Qt.Unchecked |
---|
506 | self.setRowSelection(self.tblTabList, status) |
---|
507 | |
---|
508 | def selectedParameters(self, widget): |
---|
509 | """ Returns list of selected (highlighted) parameters """ |
---|
510 | return [s.row() for s in widget.selectionModel().selectedRows()] |
---|
511 | |
---|
512 | def setRowSelection(self, widget, status=QtCore.Qt.Unchecked): |
---|
513 | """ |
---|
514 | Selected models are chosen for fitting |
---|
515 | """ |
---|
516 | # Convert to proper indices and set requested enablement |
---|
517 | for row in self.selectedParameters(widget): |
---|
518 | widget.item(row, 0).setCheckState(status) |
---|
519 | |
---|
520 | def deleteConstraint(self):#, row): |
---|
521 | """ |
---|
522 | Delete all selected constraints. |
---|
523 | """ |
---|
524 | # Removing rows from the table we're iterating over, |
---|
525 | # so prepare a list of data first |
---|
526 | constraints_to_delete = [] |
---|
527 | for row in self.selectedParameters(self.tblConstraints): |
---|
528 | constraints_to_delete.append(self.tblConstraints.item(row, 0).data(0)) |
---|
529 | for constraint in constraints_to_delete: |
---|
530 | moniker = constraint[:constraint.index(':')] |
---|
531 | param = constraint[constraint.index(':')+1:constraint.index('=')].strip() |
---|
532 | tab = self.available_tabs[moniker] |
---|
533 | tab.deleteConstraintOnParameter(param) |
---|
534 | # Constraints removed - refresh the table widget |
---|
535 | self.initializeFitList() |
---|
536 | |
---|
537 | def uneditableItem(self, data=""): |
---|
538 | """ |
---|
539 | Returns an uneditable Table Widget Item |
---|
540 | """ |
---|
541 | item = QtWidgets.QTableWidgetItem(data) |
---|
542 | item.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled ) |
---|
543 | return item |
---|
544 | |
---|
545 | def updateFitLine(self, tab): |
---|
546 | """ |
---|
547 | Update a single line of the table widget with tab info |
---|
548 | """ |
---|
549 | fit_page = ObjectLibrary.getObject(tab) |
---|
550 | model = fit_page.kernel_module |
---|
551 | if model is None: |
---|
552 | return |
---|
553 | tab_name = tab |
---|
554 | model_name = model.id |
---|
555 | moniker = model.name |
---|
556 | model_data = fit_page.data |
---|
557 | model_filename = model_data.filename |
---|
558 | self.available_tabs[moniker] = fit_page |
---|
559 | |
---|
560 | # Update the model table widget |
---|
561 | pos = self.tblTabList.rowCount() |
---|
562 | self.tblTabList.insertRow(pos) |
---|
563 | item = self.uneditableItem(tab_name) |
---|
564 | item.setFlags(item.flags() ^ QtCore.Qt.ItemIsUserCheckable) |
---|
565 | if tab_name in self.tabs_for_fitting: |
---|
566 | state = QtCore.Qt.Checked if self.tabs_for_fitting[tab_name] else QtCore.Qt.Unchecked |
---|
567 | item.setCheckState(state) |
---|
568 | else: |
---|
569 | item.setCheckState(QtCore.Qt.Checked) |
---|
570 | self.tabs_for_fitting[tab_name] = True |
---|
571 | |
---|
572 | # Disable signals so we don't get infinite call recursion |
---|
573 | self.tblTabList.blockSignals(True) |
---|
574 | self.tblTabList.setItem(pos, 0, item) |
---|
575 | self.tblTabList.setItem(pos, 1, self.uneditableItem(model_name)) |
---|
576 | self.tblTabList.setItem(pos, 2, self.uneditableItem(model_filename)) |
---|
577 | # Moniker is editable, so no option change |
---|
578 | item = QtWidgets.QTableWidgetItem(moniker) |
---|
579 | self.tblTabList.setItem(pos, 3, item) |
---|
580 | self.tblTabList.blockSignals(False) |
---|
581 | |
---|
582 | # Check if any constraints present in tab |
---|
583 | constraint_names = fit_page.getComplexConstraintsForModel() |
---|
584 | constraints = fit_page.getConstraintObjectsForModel() |
---|
585 | if not constraints: |
---|
586 | return |
---|
587 | self.tblConstraints.setEnabled(True) |
---|
588 | self.tblConstraints.blockSignals(True) |
---|
589 | for constraint, constraint_name in zip(constraints, constraint_names): |
---|
590 | # Create the text for widget item |
---|
591 | label = moniker + ":"+ constraint_name[0] + " = " + constraint_name[1] |
---|
592 | pos = self.tblConstraints.rowCount() |
---|
593 | self.available_constraints[pos] = constraint |
---|
594 | |
---|
595 | # Show the text in the constraint table |
---|
596 | item = self.uneditableItem(label) |
---|
597 | item.setFlags(item.flags() ^ QtCore.Qt.ItemIsUserCheckable) |
---|
598 | item.setCheckState(QtCore.Qt.Checked) |
---|
599 | self.tblConstraints.insertRow(pos) |
---|
600 | self.tblConstraints.setItem(pos, 0, item) |
---|
601 | self.tblConstraints.blockSignals(False) |
---|
602 | |
---|
603 | def initializeFitList(self): |
---|
604 | """ |
---|
605 | Fill the list of model/data sets for fitting/constraining |
---|
606 | """ |
---|
607 | # look at the object library to find all fit tabs |
---|
608 | # Show the content of the current "model" |
---|
609 | objects = ObjectLibrary.listObjects() |
---|
610 | |
---|
611 | # Tab dict |
---|
612 | # moniker -> (kernel_module, data) |
---|
613 | self.available_tabs = {} |
---|
614 | # Constraint dict |
---|
615 | # moniker -> [constraints] |
---|
616 | self.available_constraints = {} |
---|
617 | |
---|
618 | # Reset the table widgets |
---|
619 | self.tblTabList.setRowCount(0) |
---|
620 | self.tblConstraints.setRowCount(0) |
---|
621 | |
---|
622 | # Fit disabled |
---|
623 | self.cmdFit.setEnabled(False) |
---|
624 | |
---|
625 | if not objects: |
---|
626 | return |
---|
627 | |
---|
628 | tabs = [tab for tab in ObjectLibrary.listObjects() if self.isTabImportable(tab)] |
---|
629 | for tab in tabs: |
---|
630 | self.updateFitLine(tab) |
---|
631 | self.updateSignalsFromTab(tab) |
---|
632 | # We have at least 1 fit page, allow fitting |
---|
633 | self.cmdFit.setEnabled(True) |
---|
634 | |
---|
635 | def validateMoniker(self, new_moniker=None): |
---|
636 | """ |
---|
637 | Check new_moniker for correctness. |
---|
638 | It must be non-empty. |
---|
639 | It must not be the same as other monikers. |
---|
640 | """ |
---|
641 | if not new_moniker: |
---|
642 | return False |
---|
643 | |
---|
644 | for existing_moniker in self.available_tabs: |
---|
645 | if existing_moniker == new_moniker and existing_moniker != self.current_cell: |
---|
646 | return False |
---|
647 | |
---|
648 | return True |
---|
649 | |
---|
650 | def getObjectByName(self, name): |
---|
651 | """ |
---|
652 | Given name of the fit, returns associated fit object |
---|
653 | """ |
---|
654 | for object_name in ObjectLibrary.listObjects(): |
---|
655 | object = ObjectLibrary.getObject(object_name) |
---|
656 | if isinstance(object, FittingWidget): |
---|
657 | try: |
---|
658 | if object.kernel_module.name == name: |
---|
659 | return object |
---|
660 | except AttributeError: |
---|
661 | # Disregard atribute errors - empty fit widgets |
---|
662 | continue |
---|
663 | return None |
---|
664 | |
---|
665 | def showMultiConstraint(self): |
---|
666 | """ |
---|
667 | Invoke the complex constraint editor |
---|
668 | """ |
---|
669 | selected_rows = self.selectedParameters(self.tblTabList) |
---|
670 | assert(len(selected_rows)==2) |
---|
671 | |
---|
672 | tab_list = [ObjectLibrary.getObject(self.tblTabList.item(s, 0).data(0)) for s in selected_rows] |
---|
673 | # Create and display the widget for param1 and param2 |
---|
674 | cc_widget = ComplexConstraint(self, tabs=tab_list) |
---|
675 | if cc_widget.exec_() != QtWidgets.QDialog.Accepted: |
---|
676 | return |
---|
677 | |
---|
678 | constraint = Constraint() |
---|
679 | model1, param1, operator, constraint_text = cc_widget.constraint() |
---|
680 | |
---|
681 | constraint.func = constraint_text |
---|
682 | # param1 is the parameter we're constraining |
---|
683 | constraint.param = param1 |
---|
684 | |
---|
685 | # Find the right tab |
---|
686 | constrained_tab = self.getObjectByName(model1) |
---|
687 | if constrained_tab is None: |
---|
688 | return |
---|
689 | |
---|
690 | # Find the constrained parameter row |
---|
691 | constrained_row = constrained_tab.getRowFromName(param1) |
---|
692 | |
---|
693 | # Update the tab |
---|
694 | constrained_tab.addConstraintToRow(constraint, constrained_row) |
---|