source: sasview/src/sas/qtgui/Perspectives/Fitting/ConstraintWidget.py @ 460bdf4

ESS_GUIESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_opencl
Last change on this file since 460bdf4 was 460bdf4, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 5 months ago

Fixed bug for when subsequent C&S jobs would fail.
Modified constraint display to correspond better to the control state.

  • Property mode set to 100644
File size: 36.3 KB
Line 
1import logging
2import copy
3
4from twisted.internet import threads
5
6import sas.qtgui.Utilities.GuiUtils as GuiUtils
7import sas.qtgui.Utilities.LocalConfig as LocalConfig
8
9from PyQt5 import QtGui, QtCore, QtWidgets
10
11from sas.sascalc.fit.BumpsFitting import BumpsFit as Fit
12
13import sas.qtgui.Utilities.ObjectLibrary as ObjectLibrary
14from sas.qtgui.Perspectives.Fitting.UI.ConstraintWidgetUI import Ui_ConstraintWidgetUI
15from sas.qtgui.Perspectives.Fitting.FittingWidget import FittingWidget
16from sas.qtgui.Perspectives.Fitting.FitThread import FitThread
17from sas.qtgui.Perspectives.Fitting.ConsoleUpdate import ConsoleUpdate
18from sas.qtgui.Perspectives.Fitting.ComplexConstraint import ComplexConstraint
19from sas.qtgui.Perspectives.Fitting.Constraint import Constraint
20
21class DnDTableWidget(QtWidgets.QTableWidget):
22    def __init__(self, *args, **kwargs):
23        super().__init__(*args, **kwargs)
24
25        self.setDragEnabled(True)
26        self.setAcceptDrops(True)
27        self.viewport().setAcceptDrops(True)
28        self.setDragDropOverwriteMode(False)
29        self.setDropIndicatorShown(True)
30
31        self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
32        self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
33        self.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
34
35        self._is_dragged = False
36
37    def isDragged(self):
38        """
39        Return the drag status
40        """
41        return self._is_dragged
42
43    def dragEnterEvent(self, event):
44        """
45        Called automatically on a drag in the TableWidget
46        """
47        self._is_dragged = True
48        event.accept()
49
50    def dragLeaveEvent(self, event):
51        """
52        Called automatically on a drag stop
53        """
54        self._is_dragged = False
55        event.accept()
56
57    def dropEvent(self, event: QtGui.QDropEvent):
58        if not event.isAccepted() and event.source() == self:
59            drop_row = self.drop_on(event)
60            rows = sorted(set(item.row() for item in self.selectedItems()))
61            rows_to_move = [[QtWidgets.QTableWidgetItem(self.item(row_index, column_index)) for column_index in range(self.columnCount())]
62                            for row_index in rows]
63            for row_index in reversed(rows):
64                self.removeRow(row_index)
65                if row_index < drop_row:
66                    drop_row -= 1
67
68            for row_index, data in enumerate(rows_to_move):
69                row_index += drop_row
70                self.insertRow(row_index)
71                for column_index, column_data in enumerate(data):
72                    self.setItem(row_index, column_index, column_data)
73            event.accept()
74            for row_index in range(len(rows_to_move)):
75                self.item(drop_row + row_index, 0).setSelected(True)
76                self.item(drop_row + row_index, 1).setSelected(True)
77        super().dropEvent(event)
78        # Reset the drag flag. Must be done after the drop even got accepted!
79        self._is_dragged = False
80
81    def drop_on(self, event):
82        index = self.indexAt(event.pos())
83        if not index.isValid():
84            return self.rowCount()
85
86        return index.row() + 1 if self.is_below(event.pos(), index) else index.row()
87
88    def is_below(self, pos, index):
89        rect = self.visualRect(index)
90        margin = 2
91        if pos.y() - rect.top() < margin:
92            return False
93        elif rect.bottom() - pos.y() < margin:
94            return True
95
96        return rect.contains(pos, True) and not \
97            (int(self.model().flags(index)) & QtCore.Qt.ItemIsDropEnabled) and \
98            pos.y() >= rect.center().y()
99
100
101class ConstraintWidget(QtWidgets.QWidget, Ui_ConstraintWidgetUI):
102    """
103    Constraints Dialog to select the desired parameter/model constraints.
104    """
105    fitCompleteSignal = QtCore.pyqtSignal(tuple)
106    batchCompleteSignal = QtCore.pyqtSignal(tuple)
107    fitFailedSignal = QtCore.pyqtSignal(tuple)
108
109    def __init__(self, parent=None):
110        super(ConstraintWidget, self).__init__()
111
112        self.parent = parent
113        self.setupUi(self)
114
115        self.currentType = "FitPage"
116        # Page id for fitting
117        # To keep with previous SasView values, use 300 as the start offset
118        self.page_id = 301
119        self.tab_id = self.page_id
120        # fitpage order in the widget
121        self._row_order = []
122
123        # Set the table widget into layout
124        self.tblTabList = DnDTableWidget(self)
125        self.tblLayout.addWidget(self.tblTabList)
126
127        # Are we chain fitting?
128        self.is_chain_fitting = False
129
130        # Is the fit job running?
131        self.is_running = False
132        self.calc_fit = None
133
134        # Remember previous content of modified cell
135        self.current_cell = ""
136
137        # Tabs used in simultaneous fitting
138        # tab_name : True/False
139        self.tabs_for_fitting = {}
140
141        # Set up the widgets
142        self.initializeWidgets()
143
144        # Set up signals/slots
145        self.initializeSignals()
146
147        # Create the list of tabs
148        self.initializeFitList()
149
150    def acceptsData(self):
151        """ Tells the caller this widget doesn't accept data """
152        return False
153
154    def initializeWidgets(self):
155        """
156        Set up various widget states
157        """
158        # disable special cases until properly defined
159        self.label.setVisible(False)
160        self.cbCases.setVisible(False)
161
162        labels = ['FitPage', 'Model', 'Data', 'Mnemonic']
163        # tab widget - headers
164        self.editable_tab_columns = [labels.index('Mnemonic')]
165        self.tblTabList.setColumnCount(len(labels))
166        self.tblTabList.setHorizontalHeaderLabels(labels)
167        self.tblTabList.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
168
169        self.tblTabList.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
170        self.tblTabList.customContextMenuRequested.connect(self.showModelContextMenu)
171
172        # Single Fit is the default, so disable chainfit
173        self.chkChain.setVisible(False)
174
175        # disabled constraint
176        labels = ['Constraint']
177        self.tblConstraints.setColumnCount(len(labels))
178        self.tblConstraints.setHorizontalHeaderLabels(labels)
179        self.tblConstraints.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
180        self.tblConstraints.setEnabled(False)
181        header = self.tblConstraints.horizontalHeaderItem(0)
182        header.setToolTip("Double click a row below to edit the constraint.")
183
184        self.tblConstraints.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
185        self.tblConstraints.customContextMenuRequested.connect(self.showConstrContextMenu)
186
187    def initializeSignals(self):
188        """
189        Set up signals/slots for this widget
190        """
191        # simple widgets
192        self.btnSingle.toggled.connect(self.onFitTypeChange)
193        self.btnBatch.toggled.connect(self.onFitTypeChange)
194        self.cbCases.currentIndexChanged.connect(self.onSpecialCaseChange)
195        self.cmdFit.clicked.connect(self.onFit)
196        self.cmdHelp.clicked.connect(self.onHelp)
197        self.cmdAdd.clicked.connect(self.showMultiConstraint)
198        self.chkChain.toggled.connect(self.onChainFit)
199
200        # QTableWidgets
201        self.tblTabList.cellChanged.connect(self.onTabCellEdit)
202        self.tblTabList.cellDoubleClicked.connect(self.onTabCellEntered)
203        self.tblConstraints.cellChanged.connect(self.onConstraintChange)
204
205        # Internal signals
206        self.fitCompleteSignal.connect(self.fitComplete)
207        self.batchCompleteSignal.connect(self.batchComplete)
208        self.fitFailedSignal.connect(self.fitFailed)
209
210        # External signals
211        self.parent.tabsModifiedSignal.connect(self.initializeFitList)
212
213    def updateSignalsFromTab(self, tab=None):
214        """
215        Intercept update signals from fitting tabs
216        """
217        if tab is None:
218            return
219        tab_object = ObjectLibrary.getObject(tab)
220
221        # Disconnect all local slots, if connected
222        if tab_object.receivers(tab_object.newModelSignal) > 0:
223            tab_object.newModelSignal.disconnect()
224        if tab_object.receivers(tab_object.constraintAddedSignal) > 0:
225            tab_object.constraintAddedSignal.disconnect()
226
227        # Reconnect tab signals to local slots
228        tab_object.constraintAddedSignal.connect(self.initializeFitList)
229        tab_object.newModelSignal.connect(self.initializeFitList)
230
231    def onFitTypeChange(self, checked):
232        """
233        Respond to the fit type change
234        single fit/batch fit
235        """
236        source = self.sender().objectName()
237        self.currentType = "BatchPage" if source == "btnBatch" else "FitPage"
238        self.chkChain.setVisible(source=="btnBatch")
239        self.initializeFitList()
240
241    def onSpecialCaseChange(self, index):
242        """
243        Respond to the combobox change for special case constraint sets
244        """
245        pass
246
247    def getTabsForFit(self):
248        """
249        Returns list of tab names selected for fitting
250        """
251        return [tab for tab in self.tabs_for_fitting if self.tabs_for_fitting[tab]]
252
253    def onChainFit(self, is_checked):
254        """
255        Respond to selecting the Chain Fit checkbox
256        """
257        self.is_chain_fitting = is_checked
258
259    def onFit(self):
260        """
261        Perform the constrained/simultaneous fit
262        """
263        # Stop if we're running
264        if self.is_running:
265            self.is_running = False
266            #re-enable the Fit button
267            self.cmdFit.setStyleSheet('QPushButton {color: black;}')
268            self.cmdFit.setText("Fit")
269            # stop the fitpages
270            self.calc_fit.stop()
271            return
272
273        # Find out all tabs to fit
274        tabs_to_fit = self.getTabsForFit()
275
276        # Single fitter for the simultaneous run
277        fitter = Fit()
278        fitter.fitter_id = self.page_id
279
280        # prepare fitting problems for each tab
281        #
282        page_ids = []
283        fitter_id = 0
284        sim_fitter_list=[fitter]
285        # Prepare the fitter object
286        try:
287            for tab in tabs_to_fit:
288                if not self.isTabImportable(tab): continue
289                tab_object = ObjectLibrary.getObject(tab)
290                if tab_object is None:
291                    # No such tab!
292                    return
293                sim_fitter_list, fitter_id = \
294                    tab_object.prepareFitters(fitter=sim_fitter_list[0], fit_id=fitter_id)
295                page_ids.append([tab_object.page_id])
296        except ValueError:
297            # No parameters selected in one of the tabs
298            no_params_msg = "Fitting cannot be performed.\n" +\
299                            "Not all tabs chosen for fitting have parameters selected for fitting."
300            QtWidgets.QMessageBox.warning(self,
301                                          'Warning',
302                                           no_params_msg,
303                                           QtWidgets.QMessageBox.Ok)
304
305            return
306
307        # Create the fitting thread, based on the fitter
308        completefn = self.onBatchFitComplete if self.currentType=='BatchPage' else self.onFitComplete
309
310        if LocalConfig.USING_TWISTED:
311            handler = None
312            updater = None
313        else:
314            handler = ConsoleUpdate(parent=self.parent,
315                                    manager=self,
316                                    improvement_delta=0.1)
317            updater = handler.update_fit
318
319        batch_inputs = {}
320        batch_outputs = {}
321
322        # Notify the parent about fitting started
323        self.parent.fittingStartedSignal.emit(tabs_to_fit)
324
325        # new fit thread object
326        self.calc_fit = FitThread(handler=handler,
327                             fn=sim_fitter_list,
328                             batch_inputs=batch_inputs,
329                             batch_outputs=batch_outputs,
330                             page_id=page_ids,
331                             updatefn=updater,
332                             completefn=completefn,
333                             reset_flag=self.is_chain_fitting)
334
335        if LocalConfig.USING_TWISTED:
336            # start the trhrhread with twisted
337            self.calc_fit = threads.deferToThread(self.calc_fit.compute)
338            self.calc_fit.addCallback(completefn)
339            self.calc_fit.addErrback(self.onFitFailed)
340        else:
341            # Use the old python threads + Queue
342            self.calc_fit.queue()
343            self.calc_fit.ready(2.5)
344
345        # modify the Fit button
346        self.cmdFit.setStyleSheet('QPushButton {color: red;}')
347        self.cmdFit.setText('Stop fit')
348        self.parent.communicate.statusBarUpdateSignal.emit('Fitting started...')
349        self.is_running = True
350
351    def onHelp(self):
352        """
353        Show the "Fitting" section of help
354        """
355        tree_location = "/user/qtgui/Perspectives/Fitting/"
356
357        helpfile = "fitting_help.html#simultaneous-fit-mode"
358        help_location = tree_location + helpfile
359
360        # OMG, really? Crawling up the object hierarchy...
361        self.parent.parent.showHelp(help_location)
362
363    def onTabCellEdit(self, row, column):
364        """
365        Respond to check/uncheck and to modify the model moniker actions
366        """
367        # If this "Edit" is just a response from moving rows around,
368        # update the tab order and leave
369        if self.tblTabList.isDragged():
370            self._row_order = []
371            for i in range(self.tblTabList.rowCount()):
372                self._row_order.append(self.tblTabList.item(i,0).data(0))
373            return
374
375        item = self.tblTabList.item(row, column)
376        if column == 0:
377            # Update the tabs for fitting list
378            tab_name = item.text()
379            self.tabs_for_fitting[tab_name] = (item.checkState() == QtCore.Qt.Checked)
380            # Enable fitting only when there are models to fit
381            self.cmdFit.setEnabled(any(self.tabs_for_fitting.values()))
382
383        if column not in self.editable_tab_columns:
384            return
385        new_moniker = item.data(0)
386
387        # The new name should be validated on the fly, with QValidator
388        # but let's just assure it post-factum
389        is_good_moniker = self.validateMoniker(new_moniker)
390        if not is_good_moniker:
391            self.tblTabList.blockSignals(True)
392            item.setBackground(QtCore.Qt.red)
393            self.tblTabList.blockSignals(False)
394            self.cmdFit.setEnabled(False)
395            if new_moniker == "":
396                msg = "Please use a non-empty name."
397            else:
398                msg = "Please use a unique name."
399            self.parent.communicate.statusBarUpdateSignal.emit(msg)
400            item.setToolTip(msg)
401            return
402        self.tblTabList.blockSignals(True)
403        item.setBackground(QtCore.Qt.white)
404        self.tblTabList.blockSignals(False)
405        self.cmdFit.setEnabled(True)
406        item.setToolTip("")
407        msg = "Fitpage name changed to {}.".format(new_moniker)
408        self.parent.communicate.statusBarUpdateSignal.emit(msg)
409
410        if not self.current_cell:
411            return
412        # Remember the value
413        if self.current_cell not in self.available_tabs:
414            return
415        temp_tab = self.available_tabs[self.current_cell]
416        # Remove the key from the dictionaries
417        self.available_tabs.pop(self.current_cell, None)
418        # Change the model name
419        model = temp_tab.kernel_module
420        model.name = new_moniker
421        # Replace constraint name
422        temp_tab.replaceConstraintName(self.current_cell, new_moniker)
423        # Replace constraint name in the remaining tabs
424        for tab in self.available_tabs.values():
425            tab.replaceConstraintName(self.current_cell, new_moniker)
426        # Reinitialize the display
427        self.initializeFitList()
428
429    def onConstraintChange(self, row, column):
430        """
431        Modify the constraint's "active" instance variable.
432        """
433        item = self.tblConstraints.item(row, column)
434        if column != 0: return
435        # Update the tabs for fitting list
436        constraint = self.available_constraints[row]
437        constraint.active = (item.checkState() == QtCore.Qt.Checked)
438        # Update the constraint formula
439        constraint = self.available_constraints[row]
440        function = item.text()
441        # remove anything left of '=' to get the constraint
442        function = function[function.index('=')+1:]
443        # No check on function here - trust the user (R)
444        if function != constraint.func:
445            # This becomes rather difficult to validate now.
446            # Turn off validation for Edit Constraint
447            constraint.func = function
448            constraint.validate = False
449
450    def onTabCellEntered(self, row, column):
451        """
452        Remember the original tab list cell data.
453        Needed for reverting back on bad validation
454        """
455        if column != 3:
456            return
457        self.current_cell = self.tblTabList.item(row, column).data(0)
458
459    def onFitComplete(self, result):
460        """
461        Send the fit complete signal to main thread
462        """
463        self.fitCompleteSignal.emit(result)
464
465    def fitComplete(self, result):
466        """
467        Respond to the successful fit complete signal
468        """
469        #re-enable the Fit button
470        self.cmdFit.setStyleSheet('QPushButton {color: black;}')
471        self.cmdFit.setText("Fit")
472        self.is_running = False
473
474        # Notify the parent about completed fitting
475        self.parent.fittingStoppedSignal.emit(self.getTabsForFit())
476
477        # Assure the fitting succeeded
478        if result is None or not result:
479            msg = "Fitting failed. Please ensure correctness of chosen constraints."
480            self.parent.communicate.statusBarUpdateSignal.emit(msg)
481            return
482
483        # get the elapsed time
484        elapsed = result[1]
485
486        # result list
487        results = result[0][0]
488
489        # Find out all tabs to fit
490        tabs_to_fit = [tab for tab in self.tabs_for_fitting if self.tabs_for_fitting[tab]]
491
492        # update all involved tabs
493        for i, tab in enumerate(tabs_to_fit):
494            tab_object = ObjectLibrary.getObject(tab)
495            if tab_object is None:
496                # No such tab. removed while job was running
497                return
498            # Make sure result and target objects are the same (same model moniker)
499            if tab_object.kernel_module.name == results[i].model.name:
500                tab_object.fitComplete(([[results[i]]], elapsed))
501
502        msg = "Fitting completed successfully in: %s s.\n" % GuiUtils.formatNumber(elapsed)
503        self.parent.communicate.statusBarUpdateSignal.emit(msg)
504
505    def onBatchFitComplete(self, result):
506        """
507        Send the fit complete signal to main thread
508        """
509        self.batchCompleteSignal.emit(result)
510
511    def batchComplete(self, result):
512        """
513        Respond to the successful batch fit complete signal
514        """
515        #re-enable the Fit button
516        self.cmdFit.setStyleSheet('QPushButton {color: black;}')
517        self.cmdFit.setText("Fit")
518        self.is_running = False
519
520        # Notify the parent about completed fitting
521        self.parent.fittingStoppedSignal.emit(self.getTabsForFit())
522
523        # get the elapsed time
524        elapsed = result[1]
525
526        if result is None:
527            msg = "Fitting failed."
528            self.parent.communicate.statusBarUpdateSignal.emit(msg)
529            return
530
531        # Show the grid panel
532        page_name = "ConstSimulPage"
533        results = copy.deepcopy(result[0])
534        results.append(page_name)
535        self.parent.communicate.sendDataToGridSignal.emit(results)
536
537        msg = "Fitting completed successfully in: %s s.\n" % GuiUtils.formatNumber(elapsed)
538        self.parent.communicate.statusBarUpdateSignal.emit(msg)
539
540    def onFitFailed(self, reason):
541        """
542        Send the fit failed signal to main thread
543        """
544        self.fitFailedSignal.emit(result)
545
546    def fitFailed(self, reason):
547        """
548        Respond to fitting failure.
549        """
550        #re-enable the Fit button
551        self.cmdFit.setStyleSheet('QPushButton {color: black;}')
552        self.cmdFit.setText("Fit")
553        self.is_running = False
554
555        # Notify the parent about completed fitting
556        self.parent.fittingStoppedSignal.emit(self.getTabsForFit())
557
558        msg = "Fitting failed: %s s.\n" % reason
559        self.parent.communicate.statusBarUpdateSignal.emit(msg)
560
561    def isTabImportable(self, tab):
562        """
563        Determines if the tab can be imported and included in the widget
564        """
565        if not isinstance(tab, str): return False
566        if not self.currentType in tab: return False
567        object = ObjectLibrary.getObject(tab)
568        if not isinstance(object, FittingWidget): return False
569        if not object.data_is_loaded : return False
570        return True
571
572    def showModelContextMenu(self, position):
573        """
574        Show context specific menu in the tab table widget.
575        """
576        menu = QtWidgets.QMenu()
577        rows = [s.row() for s in self.tblTabList.selectionModel().selectedRows()]
578        num_rows = len(rows)
579        if num_rows <= 0:
580            return
581        # Select for fitting
582        param_string = "Fit Page " if num_rows==1 else "Fit Pages "
583
584        self.actionSelect = QtWidgets.QAction(self)
585        self.actionSelect.setObjectName("actionSelect")
586        self.actionSelect.setText(QtCore.QCoreApplication.translate("self", "Select "+param_string+" for fitting"))
587        # Unselect from fitting
588        self.actionDeselect = QtWidgets.QAction(self)
589        self.actionDeselect.setObjectName("actionDeselect")
590        self.actionDeselect.setText(QtCore.QCoreApplication.translate("self", "De-select "+param_string+" from fitting"))
591
592        self.actionRemoveConstraint = QtWidgets.QAction(self)
593        self.actionRemoveConstraint.setObjectName("actionRemoveConstrain")
594        self.actionRemoveConstraint.setText(QtCore.QCoreApplication.translate("self", "Remove all constraints on selected models"))
595
596        self.actionMutualMultiConstrain = QtWidgets.QAction(self)
597        self.actionMutualMultiConstrain.setObjectName("actionMutualMultiConstrain")
598        self.actionMutualMultiConstrain.setText(QtCore.QCoreApplication.translate("self", "Mutual constrain of parameters in selected models..."))
599
600        menu.addAction(self.actionSelect)
601        menu.addAction(self.actionDeselect)
602        menu.addSeparator()
603
604        if num_rows >= 2:
605            menu.addAction(self.actionMutualMultiConstrain)
606
607        # Define the callbacks
608        self.actionMutualMultiConstrain.triggered.connect(self.showMultiConstraint)
609        self.actionSelect.triggered.connect(self.selectModels)
610        self.actionDeselect.triggered.connect(self.deselectModels)
611        try:
612            menu.exec_(self.tblTabList.viewport().mapToGlobal(position))
613        except AttributeError as ex:
614            logging.error("Error generating context menu: %s" % ex)
615        return
616
617    def showConstrContextMenu(self, position):
618        """
619        Show context specific menu in the tab table widget.
620        """
621        menu = QtWidgets.QMenu()
622        rows = [s.row() for s in self.tblConstraints.selectionModel().selectedRows()]
623        num_rows = len(rows)
624        if num_rows <= 0:
625            return
626        # Select for fitting
627        param_string = "constraint " if num_rows==1 else "constraints "
628
629        self.actionSelect = QtWidgets.QAction(self)
630        self.actionSelect.setObjectName("actionSelect")
631        self.actionSelect.setText(QtCore.QCoreApplication.translate("self", "Select "+param_string+" for fitting"))
632        # Unselect from fitting
633        self.actionDeselect = QtWidgets.QAction(self)
634        self.actionDeselect.setObjectName("actionDeselect")
635        self.actionDeselect.setText(QtCore.QCoreApplication.translate("self", "De-select "+param_string+" from fitting"))
636
637        self.actionRemoveConstraint = QtWidgets.QAction(self)
638        self.actionRemoveConstraint.setObjectName("actionRemoveConstrain")
639        self.actionRemoveConstraint.setText(QtCore.QCoreApplication.translate("self", "Remove "+param_string))
640
641        menu.addAction(self.actionSelect)
642        menu.addAction(self.actionDeselect)
643        menu.addSeparator()
644        menu.addAction(self.actionRemoveConstraint)
645
646        # Define the callbacks
647        self.actionRemoveConstraint.triggered.connect(self.deleteConstraint)
648        self.actionSelect.triggered.connect(self.selectConstraints)
649        self.actionDeselect.triggered.connect(self.deselectConstraints)
650        try:
651            menu.exec_(self.tblConstraints.viewport().mapToGlobal(position))
652        except AttributeError as ex:
653            logging.error("Error generating context menu: %s" % ex)
654        return
655
656    def selectConstraints(self):
657        """
658        Selected constraints are chosen for fitting
659        """
660        status = QtCore.Qt.Checked
661        self.setRowSelection(self.tblConstraints, status)
662
663    def deselectConstraints(self):
664        """
665        Selected constraints are removed for fitting
666        """
667        status = QtCore.Qt.Unchecked
668        self.setRowSelection(self.tblConstraints, status)
669
670    def selectModels(self):
671        """
672        Selected models are chosen for fitting
673        """
674        status = QtCore.Qt.Checked
675        self.setRowSelection(self.tblTabList, status)
676
677    def deselectModels(self):
678        """
679        Selected models are removed for fitting
680        """
681        status = QtCore.Qt.Unchecked
682        self.setRowSelection(self.tblTabList, status)
683
684    def selectedParameters(self, widget):
685        """ Returns list of selected (highlighted) parameters """
686        return [s.row() for s in widget.selectionModel().selectedRows()]
687
688    def setRowSelection(self, widget, status=QtCore.Qt.Unchecked):
689        """
690        Selected models are chosen for fitting
691        """
692        # Convert to proper indices and set requested enablement
693        for row in self.selectedParameters(widget):
694            widget.item(row, 0).setCheckState(status)
695
696    def deleteConstraint(self):#, row):
697        """
698        Delete all selected constraints.
699        """
700        # Removing rows from the table we're iterating over,
701        # so prepare a list of data first
702        constraints_to_delete = []
703        for row in self.selectedParameters(self.tblConstraints):
704            constraints_to_delete.append(self.tblConstraints.item(row, 0).data(0))
705        for constraint in constraints_to_delete:
706            moniker = constraint[:constraint.index(':')]
707            param = constraint[constraint.index(':')+1:constraint.index('=')].strip()
708            tab = self.available_tabs[moniker]
709            tab.deleteConstraintOnParameter(param)
710        # Constraints removed - refresh the table widget
711        self.initializeFitList()
712
713    def uneditableItem(self, data=""):
714        """
715        Returns an uneditable Table Widget Item
716        """
717        item = QtWidgets.QTableWidgetItem(data)
718        item.setFlags( QtCore.Qt.ItemIsSelectable |  QtCore.Qt.ItemIsEnabled )
719        return item
720
721    def updateFitLine(self, tab):
722        """
723        Update a single line of the table widget with tab info
724        """
725        fit_page = ObjectLibrary.getObject(tab)
726        model = fit_page.kernel_module
727        if model is None:
728            return
729        tab_name = tab
730        model_name = model.id
731        moniker = model.name
732        model_data = fit_page.data
733        model_filename = model_data.filename
734        self.available_tabs[moniker] = fit_page
735
736        # Update the model table widget
737        pos = self.tblTabList.rowCount()
738        self.tblTabList.insertRow(pos)
739        item = self.uneditableItem(tab_name)
740        item.setFlags(item.flags() ^ QtCore.Qt.ItemIsUserCheckable)
741        if tab_name in self.tabs_for_fitting:
742            state = QtCore.Qt.Checked if self.tabs_for_fitting[tab_name] else QtCore.Qt.Unchecked
743            item.setCheckState(state)
744        else:
745            item.setCheckState(QtCore.Qt.Checked)
746            self.tabs_for_fitting[tab_name] = True
747
748        # Disable signals so we don't get infinite call recursion
749        self.tblTabList.blockSignals(True)
750        self.tblTabList.setItem(pos, 0, item)
751        self.tblTabList.setItem(pos, 1, self.uneditableItem(model_name))
752        self.tblTabList.setItem(pos, 2, self.uneditableItem(model_filename))
753        # Moniker is editable, so no option change
754        item = QtWidgets.QTableWidgetItem(moniker)
755        self.tblTabList.setItem(pos, 3, item)
756        self.tblTabList.blockSignals(False)
757
758        # Check if any constraints present in tab
759        constraint_names = fit_page.getComplexConstraintsForModel()
760        constraints = fit_page.getConstraintObjectsForModel()
761        if not constraints: 
762            return
763        self.tblConstraints.setEnabled(True)
764        self.tblConstraints.blockSignals(True)
765        for constraint, constraint_name in zip(constraints, constraint_names):
766            # Create the text for widget item
767            label = moniker + ":"+ constraint_name[0] + " = " + constraint_name[1]
768            pos = self.tblConstraints.rowCount()
769            self.available_constraints[pos] = constraint
770
771            # Show the text in the constraint table
772            item = self.uneditableItem(label)
773            item = QtWidgets.QTableWidgetItem(label)
774            item.setFlags(item.flags() ^ QtCore.Qt.ItemIsUserCheckable)
775            item.setCheckState(QtCore.Qt.Checked)
776            self.tblConstraints.insertRow(pos)
777            self.tblConstraints.setItem(pos, 0, item)
778        self.tblConstraints.blockSignals(False)
779
780    def initializeFitList(self):
781        """
782        Fill the list of model/data sets for fitting/constraining
783        """
784        # look at the object library to find all fit tabs
785        # Show the content of the current "model"
786        objects = ObjectLibrary.listObjects()
787
788        # Tab dict
789        # moniker -> (kernel_module, data)
790        self.available_tabs = {}
791        # Constraint dict
792        # moniker -> [constraints]
793        self.available_constraints = {}
794
795        # Reset the table widgets
796        self.tblTabList.setRowCount(0)
797        self.tblConstraints.setRowCount(0)
798
799        # Fit disabled
800        self.cmdFit.setEnabled(False)
801
802        if not objects:
803            return
804
805        tabs = [tab for tab in ObjectLibrary.listObjects() if self.isTabImportable(tab)]
806        if not self._row_order:
807            # Initialize tab order list
808            self._row_order = tabs
809        else:
810            tabs = self.orderedSublist(self._row_order, tabs)
811            self._row_order = tabs
812
813        for tab in tabs:
814            self.updateFitLine(tab)
815            self.updateSignalsFromTab(tab)
816            # We have at least 1 fit page, allow fitting
817            self.cmdFit.setEnabled(True)
818
819    def orderedSublist(self, order_list, target_list):
820        """
821        Orders the target_list such that any elements
822        present in order_list show up first and in the order
823        from order_list.
824        """
825        tmp_list = []
826        # 1. get the non-matching elements
827        nonmatching = list(set(target_list) - set(order_list))
828        # 2: start with matching tabs, in the correct order
829        for elem in order_list:
830            if elem in target_list:
831                tmp_list.append(elem)
832        # 3. add the remaning tabs in any order
833        ordered_list = tmp_list + nonmatching
834        return ordered_list
835
836    def validateMoniker(self, new_moniker=None):
837        """
838        Check new_moniker for correctness.
839        It must be non-empty.
840        It must not be the same as other monikers.
841        """
842        if not new_moniker:
843            return False
844
845        for existing_moniker in self.available_tabs:
846            if existing_moniker == new_moniker and existing_moniker != self.current_cell:
847                return False
848
849        return True
850
851    def getObjectByName(self, name):
852        """
853        Given name of the fit, returns associated fit object
854        """
855        for object_name in ObjectLibrary.listObjects():
856            object = ObjectLibrary.getObject(object_name)
857            if isinstance(object, FittingWidget):
858                try:
859                    if object.kernel_module.name == name:
860                        return object
861                except AttributeError:
862                    # Disregard atribute errors - empty fit widgets
863                    continue
864        return None
865
866    def onAcceptConstraint(self, con_tuple):
867        """
868        Receive constraint tuple from the ComplexConstraint dialog and adds contraint
869        """
870        #"M1, M2, M3" etc
871        model_name, constraint = con_tuple
872        constrained_tab = self.getObjectByName(model_name)
873        if constrained_tab is None:
874            return
875
876        # Find the constrained parameter row
877        constrained_row = constrained_tab.getRowFromName(constraint.param)
878
879        # Update the tab
880        constrained_tab.addConstraintToRow(constraint, constrained_row)
881
882        # Select this parameter for adjusting/fitting
883        constrained_tab.selectCheckbox(constrained_row)
884
885
886    def showMultiConstraint(self):
887        """
888        Invoke the complex constraint editor
889        """
890        selected_rows = self.selectedParameters(self.tblTabList)
891
892        tab_list = [ObjectLibrary.getObject(self.tblTabList.item(s, 0).data(0)) for s in range(self.tblTabList.rowCount())]
893        # Create and display the widget for param1 and param2
894        cc_widget = ComplexConstraint(self, tabs=tab_list)
895        cc_widget.constraintReadySignal.connect(self.onAcceptConstraint)
896
897        if cc_widget.exec_() != QtWidgets.QDialog.Accepted:
898            return
899
900    def getFitPage(self):
901        """
902        Retrieves the state of this page
903        """
904        param_list = []
905
906        param_list.append(['is_constraint', 'True'])
907        param_list.append(['data_id', "cs_tab"+str(self.page_id)])
908        param_list.append(['current_type', self.currentType])
909        param_list.append(['is_chain_fitting', str(self.is_chain_fitting)])
910        param_list.append(['special_case', self.cbCases.currentText()])
911
912        return param_list
913
914    def getFitModel(self):
915        """
916        Retrieves current model
917        """
918        model_list = []
919
920        checked_models = {}
921        for row in range(self.tblTabList.rowCount()):
922            model_name = self.tblTabList.item(row,1).data(0)
923            active = self.tblTabList.item(row,0).checkState()# == QtCore.Qt.Checked
924            checked_models[model_name] = str(active)
925
926        checked_constraints = {}
927        for row in range(self.tblConstraints.rowCount()):
928            model_name = self.tblConstraints.item(row,0).data(0)
929            active = self.tblConstraints.item(row,0).checkState()# == QtCore.Qt.Checked
930            checked_constraints[model_name] = str(active)
931
932        model_list.append(['checked_models', checked_models])
933        model_list.append(['checked_constraints', checked_constraints])
934        return model_list
935
936    def createPageForParameters(self, parameters=None):
937        """
938        Update the page with passed parameter values
939        """
940        # checked models
941        if not 'checked_models' in parameters:
942            return
943        models = parameters['checked_models'][0]
944        for model, check_state in models.items():
945            for row in range(self.tblTabList.rowCount()):
946                model_name = self.tblTabList.item(row,1).data(0)
947                if model_name != model:
948                    continue
949                # check/uncheck item
950                self.tblTabList.item(row,0).setCheckState(int(check_state))
951
952        if not 'checked_constraints' in parameters:
953            return
954        # checked constraints
955        models = parameters['checked_constraints'][0]
956        for model, check_state in models.items():
957            for row in range(self.tblConstraints.rowCount()):
958                model_name = self.tblConstraints.item(row,0).data(0)
959                if model_name != model:
960                    continue
961                # check/uncheck item
962                self.tblConstraints.item(row,0).setCheckState(int(check_state))
963
964        # fit/batch radio
965        isBatch = parameters['current_type'][0] == 'BatchPage'
966        if isBatch:
967            self.btnBatch.toggle()
968
969        # chain
970        is_chain = parameters['is_chain_fitting'][0] == 'True'
971        if isBatch:
972            self.chkChain.setChecked(is_chain)
973
974    def getReport(self):
975        """
976        Wrapper for non-existent functionality.
977        Tell the user to use the reporting tool
978        on separate fit pages.
979        """
980        msg = "Please use Report Results directly on fit pages"
981        msg += " involved in the Constrained and Simultaneous fitting process."
982        msgbox = QtWidgets.QMessageBox(self)
983        msgbox.setIcon(QtWidgets.QMessageBox.Warning)
984        msgbox.setText(msg)
985        msgbox.setWindowTitle("Fit Report")
986        _ = msgbox.exec_()
987        return
Note: See TracBrowser for help on using the repository browser.