source: sasview/src/sas/qtgui/Perspectives/Fitting/ConstraintWidget.py @ 5d14851a

ESS_GUIESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_opencl
Last change on this file since 5d14851a was 14e1ff0, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 6 years ago

Allow for C&S fitting cancellation. SASVIEW-1280

  • Property mode set to 100644
File size: 36.2 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
473        # Notify the parent about completed fitting
474        self.parent.fittingStoppedSignal.emit(self.getTabsForFit())
475
476        # Assure the fitting succeeded
477        if result is None or not result:
478            msg = "Fitting failed. Please ensure correctness of chosen constraints."
479            self.parent.communicate.statusBarUpdateSignal.emit(msg)
480            return
481
482        # get the elapsed time
483        elapsed = result[1]
484
485        # result list
486        results = result[0][0]
487
488        # Find out all tabs to fit
489        tabs_to_fit = [tab for tab in self.tabs_for_fitting if self.tabs_for_fitting[tab]]
490
491        # update all involved tabs
492        for i, tab in enumerate(tabs_to_fit):
493            tab_object = ObjectLibrary.getObject(tab)
494            if tab_object is None:
495                # No such tab. removed while job was running
496                return
497            # Make sure result and target objects are the same (same model moniker)
498            if tab_object.kernel_module.name == results[i].model.name:
499                tab_object.fitComplete(([[results[i]]], elapsed))
500
501        msg = "Fitting completed successfully in: %s s.\n" % GuiUtils.formatNumber(elapsed)
502        self.parent.communicate.statusBarUpdateSignal.emit(msg)
503
504    def onBatchFitComplete(self, result):
505        """
506        Send the fit complete signal to main thread
507        """
508        self.batchCompleteSignal.emit(result)
509
510    def batchComplete(self, result):
511        """
512        Respond to the successful batch fit complete signal
513        """
514        #re-enable the Fit button
515        self.cmdFit.setStyleSheet('QPushButton {color: black;}')
516        self.cmdFit.setText("Fit")
517
518        # Notify the parent about completed fitting
519        self.parent.fittingStoppedSignal.emit(self.getTabsForFit())
520
521        # get the elapsed time
522        elapsed = result[1]
523
524        if result is None:
525            msg = "Fitting failed."
526            self.parent.communicate.statusBarUpdateSignal.emit(msg)
527            return
528
529        # Show the grid panel
530        page_name = "ConstSimulPage"
531        results = copy.deepcopy(result[0])
532        results.append(page_name)
533        self.parent.communicate.sendDataToGridSignal.emit(results)
534
535        msg = "Fitting completed successfully in: %s s.\n" % GuiUtils.formatNumber(elapsed)
536        self.parent.communicate.statusBarUpdateSignal.emit(msg)
537
538    def onFitFailed(self, reason):
539        """
540        Send the fit failed signal to main thread
541        """
542        self.fitFailedSignal.emit(result)
543
544    def fitFailed(self, reason):
545        """
546        Respond to fitting failure.
547        """
548        #re-enable the Fit button
549        self.cmdFit.setStyleSheet('QPushButton {color: black;}')
550        self.cmdFit.setText("Fit")
551
552        # Notify the parent about completed fitting
553        self.parent.fittingStoppedSignal.emit(self.getTabsForFit())
554
555        msg = "Fitting failed: %s s.\n" % reason
556        self.parent.communicate.statusBarUpdateSignal.emit(msg)
557
558    def isTabImportable(self, tab):
559        """
560        Determines if the tab can be imported and included in the widget
561        """
562        if not isinstance(tab, str): return False
563        if not self.currentType in tab: return False
564        object = ObjectLibrary.getObject(tab)
565        if not isinstance(object, FittingWidget): return False
566        if not object.data_is_loaded : return False
567        return True
568
569    def showModelContextMenu(self, position):
570        """
571        Show context specific menu in the tab table widget.
572        """
573        menu = QtWidgets.QMenu()
574        rows = [s.row() for s in self.tblTabList.selectionModel().selectedRows()]
575        num_rows = len(rows)
576        if num_rows <= 0:
577            return
578        # Select for fitting
579        param_string = "Fit Page " if num_rows==1 else "Fit Pages "
580
581        self.actionSelect = QtWidgets.QAction(self)
582        self.actionSelect.setObjectName("actionSelect")
583        self.actionSelect.setText(QtCore.QCoreApplication.translate("self", "Select "+param_string+" for fitting"))
584        # Unselect from fitting
585        self.actionDeselect = QtWidgets.QAction(self)
586        self.actionDeselect.setObjectName("actionDeselect")
587        self.actionDeselect.setText(QtCore.QCoreApplication.translate("self", "De-select "+param_string+" from fitting"))
588
589        self.actionRemoveConstraint = QtWidgets.QAction(self)
590        self.actionRemoveConstraint.setObjectName("actionRemoveConstrain")
591        self.actionRemoveConstraint.setText(QtCore.QCoreApplication.translate("self", "Remove all constraints on selected models"))
592
593        self.actionMutualMultiConstrain = QtWidgets.QAction(self)
594        self.actionMutualMultiConstrain.setObjectName("actionMutualMultiConstrain")
595        self.actionMutualMultiConstrain.setText(QtCore.QCoreApplication.translate("self", "Mutual constrain of parameters in selected models..."))
596
597        menu.addAction(self.actionSelect)
598        menu.addAction(self.actionDeselect)
599        menu.addSeparator()
600
601        if num_rows >= 2:
602            menu.addAction(self.actionMutualMultiConstrain)
603
604        # Define the callbacks
605        self.actionMutualMultiConstrain.triggered.connect(self.showMultiConstraint)
606        self.actionSelect.triggered.connect(self.selectModels)
607        self.actionDeselect.triggered.connect(self.deselectModels)
608        try:
609            menu.exec_(self.tblTabList.viewport().mapToGlobal(position))
610        except AttributeError as ex:
611            logging.error("Error generating context menu: %s" % ex)
612        return
613
614    def showConstrContextMenu(self, position):
615        """
616        Show context specific menu in the tab table widget.
617        """
618        menu = QtWidgets.QMenu()
619        rows = [s.row() for s in self.tblConstraints.selectionModel().selectedRows()]
620        num_rows = len(rows)
621        if num_rows <= 0:
622            return
623        # Select for fitting
624        param_string = "constraint " if num_rows==1 else "constraints "
625
626        self.actionSelect = QtWidgets.QAction(self)
627        self.actionSelect.setObjectName("actionSelect")
628        self.actionSelect.setText(QtCore.QCoreApplication.translate("self", "Select "+param_string+" for fitting"))
629        # Unselect from fitting
630        self.actionDeselect = QtWidgets.QAction(self)
631        self.actionDeselect.setObjectName("actionDeselect")
632        self.actionDeselect.setText(QtCore.QCoreApplication.translate("self", "De-select "+param_string+" from fitting"))
633
634        self.actionRemoveConstraint = QtWidgets.QAction(self)
635        self.actionRemoveConstraint.setObjectName("actionRemoveConstrain")
636        self.actionRemoveConstraint.setText(QtCore.QCoreApplication.translate("self", "Remove "+param_string))
637
638        menu.addAction(self.actionSelect)
639        menu.addAction(self.actionDeselect)
640        menu.addSeparator()
641        menu.addAction(self.actionRemoveConstraint)
642
643        # Define the callbacks
644        self.actionRemoveConstraint.triggered.connect(self.deleteConstraint)
645        self.actionSelect.triggered.connect(self.selectConstraints)
646        self.actionDeselect.triggered.connect(self.deselectConstraints)
647        try:
648            menu.exec_(self.tblConstraints.viewport().mapToGlobal(position))
649        except AttributeError as ex:
650            logging.error("Error generating context menu: %s" % ex)
651        return
652
653    def selectConstraints(self):
654        """
655        Selected constraints are chosen for fitting
656        """
657        status = QtCore.Qt.Checked
658        self.setRowSelection(self.tblConstraints, status)
659
660    def deselectConstraints(self):
661        """
662        Selected constraints are removed for fitting
663        """
664        status = QtCore.Qt.Unchecked
665        self.setRowSelection(self.tblConstraints, status)
666
667    def selectModels(self):
668        """
669        Selected models are chosen for fitting
670        """
671        status = QtCore.Qt.Checked
672        self.setRowSelection(self.tblTabList, status)
673
674    def deselectModels(self):
675        """
676        Selected models are removed for fitting
677        """
678        status = QtCore.Qt.Unchecked
679        self.setRowSelection(self.tblTabList, status)
680
681    def selectedParameters(self, widget):
682        """ Returns list of selected (highlighted) parameters """
683        return [s.row() for s in widget.selectionModel().selectedRows()]
684
685    def setRowSelection(self, widget, status=QtCore.Qt.Unchecked):
686        """
687        Selected models are chosen for fitting
688        """
689        # Convert to proper indices and set requested enablement
690        for row in self.selectedParameters(widget):
691            widget.item(row, 0).setCheckState(status)
692
693    def deleteConstraint(self):#, row):
694        """
695        Delete all selected constraints.
696        """
697        # Removing rows from the table we're iterating over,
698        # so prepare a list of data first
699        constraints_to_delete = []
700        for row in self.selectedParameters(self.tblConstraints):
701            constraints_to_delete.append(self.tblConstraints.item(row, 0).data(0))
702        for constraint in constraints_to_delete:
703            moniker = constraint[:constraint.index(':')]
704            param = constraint[constraint.index(':')+1:constraint.index('=')].strip()
705            tab = self.available_tabs[moniker]
706            tab.deleteConstraintOnParameter(param)
707        # Constraints removed - refresh the table widget
708        self.initializeFitList()
709
710    def uneditableItem(self, data=""):
711        """
712        Returns an uneditable Table Widget Item
713        """
714        item = QtWidgets.QTableWidgetItem(data)
715        item.setFlags( QtCore.Qt.ItemIsSelectable |  QtCore.Qt.ItemIsEnabled )
716        return item
717
718    def updateFitLine(self, tab):
719        """
720        Update a single line of the table widget with tab info
721        """
722        fit_page = ObjectLibrary.getObject(tab)
723        model = fit_page.kernel_module
724        if model is None:
725            return
726        tab_name = tab
727        model_name = model.id
728        moniker = model.name
729        model_data = fit_page.data
730        model_filename = model_data.filename
731        self.available_tabs[moniker] = fit_page
732
733        # Update the model table widget
734        pos = self.tblTabList.rowCount()
735        self.tblTabList.insertRow(pos)
736        item = self.uneditableItem(tab_name)
737        item.setFlags(item.flags() ^ QtCore.Qt.ItemIsUserCheckable)
738        if tab_name in self.tabs_for_fitting:
739            state = QtCore.Qt.Checked if self.tabs_for_fitting[tab_name] else QtCore.Qt.Unchecked
740            item.setCheckState(state)
741        else:
742            item.setCheckState(QtCore.Qt.Checked)
743            self.tabs_for_fitting[tab_name] = True
744
745        # Disable signals so we don't get infinite call recursion
746        self.tblTabList.blockSignals(True)
747        self.tblTabList.setItem(pos, 0, item)
748        self.tblTabList.setItem(pos, 1, self.uneditableItem(model_name))
749        self.tblTabList.setItem(pos, 2, self.uneditableItem(model_filename))
750        # Moniker is editable, so no option change
751        item = QtWidgets.QTableWidgetItem(moniker)
752        self.tblTabList.setItem(pos, 3, item)
753        self.tblTabList.blockSignals(False)
754
755        # Check if any constraints present in tab
756        constraint_names = fit_page.getComplexConstraintsForModel()
757        constraints = fit_page.getConstraintObjectsForModel()
758        if not constraints: 
759            return
760        self.tblConstraints.setEnabled(True)
761        self.tblConstraints.blockSignals(True)
762        for constraint, constraint_name in zip(constraints, constraint_names):
763            # Create the text for widget item
764            label = moniker + ":"+ constraint_name[0] + " = " + constraint_name[1]
765            pos = self.tblConstraints.rowCount()
766            self.available_constraints[pos] = constraint
767
768            # Show the text in the constraint table
769            item = self.uneditableItem(label)
770            item = QtWidgets.QTableWidgetItem(label)
771            item.setFlags(item.flags() ^ QtCore.Qt.ItemIsUserCheckable)
772            item.setCheckState(QtCore.Qt.Checked)
773            self.tblConstraints.insertRow(pos)
774            self.tblConstraints.setItem(pos, 0, item)
775        self.tblConstraints.blockSignals(False)
776
777    def initializeFitList(self):
778        """
779        Fill the list of model/data sets for fitting/constraining
780        """
781        # look at the object library to find all fit tabs
782        # Show the content of the current "model"
783        objects = ObjectLibrary.listObjects()
784
785        # Tab dict
786        # moniker -> (kernel_module, data)
787        self.available_tabs = {}
788        # Constraint dict
789        # moniker -> [constraints]
790        self.available_constraints = {}
791
792        # Reset the table widgets
793        self.tblTabList.setRowCount(0)
794        self.tblConstraints.setRowCount(0)
795
796        # Fit disabled
797        self.cmdFit.setEnabled(False)
798
799        if not objects:
800            return
801
802        tabs = [tab for tab in ObjectLibrary.listObjects() if self.isTabImportable(tab)]
803        if not self._row_order:
804            # Initialize tab order list
805            self._row_order = tabs
806        else:
807            tabs = self.orderedSublist(self._row_order, tabs)
808            self._row_order = tabs
809
810        for tab in tabs:
811            self.updateFitLine(tab)
812            self.updateSignalsFromTab(tab)
813            # We have at least 1 fit page, allow fitting
814            self.cmdFit.setEnabled(True)
815
816    def orderedSublist(self, order_list, target_list):
817        """
818        Orders the target_list such that any elements
819        present in order_list show up first and in the order
820        from order_list.
821        """
822        tmp_list = []
823        # 1. get the non-matching elements
824        nonmatching = list(set(target_list) - set(order_list))
825        # 2: start with matching tabs, in the correct order
826        for elem in order_list:
827            if elem in target_list:
828                tmp_list.append(elem)
829        # 3. add the remaning tabs in any order
830        ordered_list = tmp_list + nonmatching
831        return ordered_list
832
833    def validateMoniker(self, new_moniker=None):
834        """
835        Check new_moniker for correctness.
836        It must be non-empty.
837        It must not be the same as other monikers.
838        """
839        if not new_moniker:
840            return False
841
842        for existing_moniker in self.available_tabs:
843            if existing_moniker == new_moniker and existing_moniker != self.current_cell:
844                return False
845
846        return True
847
848    def getObjectByName(self, name):
849        """
850        Given name of the fit, returns associated fit object
851        """
852        for object_name in ObjectLibrary.listObjects():
853            object = ObjectLibrary.getObject(object_name)
854            if isinstance(object, FittingWidget):
855                try:
856                    if object.kernel_module.name == name:
857                        return object
858                except AttributeError:
859                    # Disregard atribute errors - empty fit widgets
860                    continue
861        return None
862
863    def onAcceptConstraint(self, con_tuple):
864        """
865        Receive constraint tuple from the ComplexConstraint dialog and adds contraint
866        """
867        #"M1, M2, M3" etc
868        model_name, constraint = con_tuple
869        constrained_tab = self.getObjectByName(model_name)
870        if constrained_tab is None:
871            return
872
873        # Find the constrained parameter row
874        constrained_row = constrained_tab.getRowFromName(constraint.param)
875
876        # Update the tab
877        constrained_tab.addConstraintToRow(constraint, constrained_row)
878
879        # Select this parameter for adjusting/fitting
880        constrained_tab.selectCheckbox(constrained_row)
881
882
883    def showMultiConstraint(self):
884        """
885        Invoke the complex constraint editor
886        """
887        selected_rows = self.selectedParameters(self.tblTabList)
888
889        tab_list = [ObjectLibrary.getObject(self.tblTabList.item(s, 0).data(0)) for s in range(self.tblTabList.rowCount())]
890        # Create and display the widget for param1 and param2
891        cc_widget = ComplexConstraint(self, tabs=tab_list)
892        cc_widget.constraintReadySignal.connect(self.onAcceptConstraint)
893
894        if cc_widget.exec_() != QtWidgets.QDialog.Accepted:
895            return
896
897    def getFitPage(self):
898        """
899        Retrieves the state of this page
900        """
901        param_list = []
902
903        param_list.append(['is_constraint', 'True'])
904        param_list.append(['data_id', "cs_tab"+str(self.page_id)])
905        param_list.append(['current_type', self.currentType])
906        param_list.append(['is_chain_fitting', str(self.is_chain_fitting)])
907        param_list.append(['special_case', self.cbCases.currentText()])
908
909        return param_list
910
911    def getFitModel(self):
912        """
913        Retrieves current model
914        """
915        model_list = []
916
917        checked_models = {}
918        for row in range(self.tblTabList.rowCount()):
919            model_name = self.tblTabList.item(row,1).data(0)
920            active = self.tblTabList.item(row,0).checkState()# == QtCore.Qt.Checked
921            checked_models[model_name] = str(active)
922
923        checked_constraints = {}
924        for row in range(self.tblConstraints.rowCount()):
925            model_name = self.tblConstraints.item(row,0).data(0)
926            active = self.tblConstraints.item(row,0).checkState()# == QtCore.Qt.Checked
927            checked_constraints[model_name] = str(active)
928
929        model_list.append(['checked_models', checked_models])
930        model_list.append(['checked_constraints', checked_constraints])
931        return model_list
932
933    def createPageForParameters(self, parameters=None):
934        """
935        Update the page with passed parameter values
936        """
937        # checked models
938        if not 'checked_models' in parameters:
939            return
940        models = parameters['checked_models'][0]
941        for model, check_state in models.items():
942            for row in range(self.tblTabList.rowCount()):
943                model_name = self.tblTabList.item(row,1).data(0)
944                if model_name != model:
945                    continue
946                # check/uncheck item
947                self.tblTabList.item(row,0).setCheckState(int(check_state))
948
949        if not 'checked_constraints' in parameters:
950            return
951        # checked constraints
952        models = parameters['checked_constraints'][0]
953        for model, check_state in models.items():
954            for row in range(self.tblConstraints.rowCount()):
955                model_name = self.tblConstraints.item(row,0).data(0)
956                if model_name != model:
957                    continue
958                # check/uncheck item
959                self.tblConstraints.item(row,0).setCheckState(int(check_state))
960
961        # fit/batch radio
962        isBatch = parameters['current_type'][0] == 'BatchPage'
963        if isBatch:
964            self.btnBatch.toggle()
965
966        # chain
967        is_chain = parameters['is_chain_fitting'][0] == 'True'
968        if isBatch:
969            self.chkChain.setChecked(is_chain)
970
971    def getReport(self):
972        """
973        Wrapper for non-existent functionality.
974        Tell the user to use the reporting tool
975        on separate fit pages.
976        """
977        msg = "Please use Report Results directly on fit pages"
978        msg += " involved in the Constrained and Simultaneous fitting process."
979        msgbox = QtWidgets.QMessageBox(self)
980        msgbox.setIcon(QtWidgets.QMessageBox.Warning)
981        msgbox.setText(msg)
982        msgbox.setWindowTitle("Fit Report")
983        _ = msgbox.exec_()
984        return
Note: See TracBrowser for help on using the repository browser.