source: sasview/src/sas/qtgui/Perspectives/Fitting/ConstraintWidget.py @ 085e3c9d

ESS_GUI_iss959
Last change on this file since 085e3c9d was aed0532, checked in by Piotr Rozyczko <rozyczko@…>, 7 years ago

Updated references to help files

  • Property mode set to 100644
File size: 25.5 KB
RevLine 
[731efec]1import logging
[676f137]2
[116dd4c1]3from twisted.internet import threads
4
[676f137]5import sas.qtgui.Utilities.GuiUtils as GuiUtils
[14ec91c5]6import sas.qtgui.Utilities.LocalConfig as LocalConfig
7
[676f137]8from PyQt5 import QtGui, QtCore, QtWidgets
9
[116dd4c1]10from sas.sascalc.fit.BumpsFitting import BumpsFit as Fit
[676f137]11
[116dd4c1]12import sas.qtgui.Utilities.ObjectLibrary as ObjectLibrary
[676f137]13from sas.qtgui.Perspectives.Fitting.UI.ConstraintWidgetUI import Ui_ConstraintWidgetUI
[be8f4b0]14from sas.qtgui.Perspectives.Fitting.FittingWidget import FittingWidget
[116dd4c1]15from sas.qtgui.Perspectives.Fitting.FitThread import FitThread
16from sas.qtgui.Perspectives.Fitting.ConsoleUpdate import ConsoleUpdate
[2d466e4]17from sas.qtgui.Perspectives.Fitting.ComplexConstraint import ComplexConstraint
[14ec91c5]18from sas.qtgui.Perspectives.Fitting.Constraint import Constraint
[676f137]19
20class ConstraintWidget(QtWidgets.QWidget, Ui_ConstraintWidgetUI):
21    """
[be8f4b0]22    Constraints Dialog to select the desired parameter/model constraints.
[676f137]23    """
24
[14ec91c5]25    def __init__(self, parent=None):
[676f137]26        super(ConstraintWidget, self).__init__()
27        self.parent = parent
28        self.setupUi(self)
29        self.currentType = "FitPage"
[116dd4c1]30        # Page id for fitting
31        # To keep with previous SasView values, use 300 as the start offset
[14ec91c5]32        self.page_id = 301
[676f137]33
[91ad45c]34        # Are we chain fitting?
35        self.is_chain_fitting = False
36
[47d7d2d]37        # Remember previous content of modified cell
38        self.current_cell = ""
39
[ba01ad1]40        # Tabs used in simultaneous fitting
41        # tab_name : True/False
42        self.tabs_for_fitting = {}
43
[be8f4b0]44        # Set up the widgets
45        self.initializeWidgets()
46
[676f137]47        # Set up signals/slots
48        self.initializeSignals()
49
50        # Create the list of tabs
[be8f4b0]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        """
[47d7d2d]61        labels = ['FitPage', 'Model', 'Data', 'Mnemonic']
[be8f4b0]62        # tab widget - headers
[47d7d2d]63        self.editable_tab_columns = [labels.index('Mnemonic')]
[be8f4b0]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
[91ad45c]71        # Single Fit is the default, so disable chainfit
72        self.chkChain.setVisible(False)
73
[be8f4b0]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)
[676f137]83
84    def initializeSignals(self):
85        """
86        Set up signals/slots for this widget
87        """
[47d7d2d]88        # simple widgets
[676f137]89        self.btnSingle.toggled.connect(self.onFitTypeChange)
90        self.btnBatch.toggled.connect(self.onFitTypeChange)
[be8f4b0]91        self.cbCases.currentIndexChanged.connect(self.onSpecialCaseChange)
[676f137]92        self.cmdFit.clicked.connect(self.onFit)
93        self.cmdHelp.clicked.connect(self.onHelp)
[91ad45c]94        self.chkChain.toggled.connect(self.onChainFit)
[47d7d2d]95
96        # QTableWidgets
[ba01ad1]97        self.tblTabList.cellChanged.connect(self.onTabCellEdit)
[47d7d2d]98        self.tblTabList.cellDoubleClicked.connect(self.onTabCellEntered)
99        self.tblConstraints.cellChanged.connect(self.onConstraintChange)
100
101        # External signals
[a90c9c5]102        self.parent.tabsModifiedSignal.connect(self.initializeFitList)
[be8f4b0]103
104    def updateSignalsFromTab(self, tab=None):
105        """
106        Intercept update signals from fitting tabs
107        """
[731efec]108        if tab is None:
109            return
110        tab_object = ObjectLibrary.getObject(tab)
111
112        # Disconnect all local slots
[3b3b40b]113        #tab_object.disconnect()
[731efec]114
115        # Reconnect tab signals to local slots
116        tab_object.constraintAddedSignal.connect(self.initializeFitList)
117        tab_object.newModelSignal.connect(self.initializeFitList)
[676f137]118
119    def onFitTypeChange(self, checked):
120        """
121        Respond to the fit type change
122        single fit/batch fit
123        """
[ba01ad1]124        source = self.sender().objectName()
125        self.currentType = "BatchPage" if source == "btnBatch" else "FitPage"
[91ad45c]126        self.chkChain.setVisible(source=="btnBatch")
[ba01ad1]127        self.initializeFitList()
[676f137]128
129    def onSpecialCaseChange(self, index):
130        """
131        Respond to the combobox change for special case constraint sets
132        """
133        pass
134
[14ec91c5]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
[91ad45c]141    def onChainFit(self, is_checked):
142        """
143        Respond to selecting the Chain Fit checkbox
144        """
145        self.is_chain_fitting = is_checked
146
[676f137]147    def onFit(self):
148        """
149        Perform the constrained/simultaneous fit
150        """
[116dd4c1]151        # Find out all tabs to fit
[14ec91c5]152        tabs_to_fit = self.getTabsForFit()
[116dd4c1]153
154        # Single fitter for the simultaneous run
[6ca0da0]155        fitter = Fit()
156        fitter.fitter_id = self.page_id
[116dd4c1]157
[14ec91c5]158        # Notify the parent about fitting started
159        self.parent.fittingStartedSignal.emit(tabs_to_fit)
160
[116dd4c1]161        # prepare fitting problems for each tab
162        #
163        page_ids = []
164        fitter_id = 0
[6ca0da0]165        sim_fitter_list=[fitter]
[c6343a5]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
[8b480d27]173                sim_fitter_list, fitter_id = \
174                    tab_object.prepareFitters(fitter=sim_fitter_list[0], fit_id=fitter_id)
[c6343a5]175                page_ids.append([tab_object.page_id])
[6ca0da0]176        except ValueError:
[c6343a5]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."
[e4c475b7]180            QtWidgets.QMessageBox.warning(self,
[3b3b40b]181                                          'Warning',
182                                           no_params_msg,
183                                           QtWidgets.QMessageBox.Ok)
[c6343a5]184
185            return
[116dd4c1]186
187        # Create the fitting thread, based on the fitter
188        completefn = self.onBatchFitComplete if self.currentType=='BatchPage' else self.onFitComplete
189
[14ec91c5]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
[116dd4c1]198
199        batch_inputs = {}
200        batch_outputs = {}
201
202        # new fit thread object
203        calc_fit = FitThread(handler=handler,
[6ca0da0]204                             fn=sim_fitter_list,
[116dd4c1]205                             batch_inputs=batch_inputs,
206                             batch_outputs=batch_outputs,
207                             page_id=page_ids,
208                             updatefn=updater,
[91ad45c]209                             completefn=completefn,
210                             reset_flag=self.is_chain_fitting)
[116dd4c1]211
[14ec91c5]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)
[116dd4c1]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)
[676f137]227
228    def onHelp(self):
229        """
[c6343a5]230        Show the "Fitting" section of help
[676f137]231        """
[aed0532]232        tree_location = "/user/qtgui/Perspectives/Fitting/"
[c6343a5]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)
[676f137]239
[ba01ad1]240    def onTabCellEdit(self, row, column):
[47d7d2d]241        """
[ba01ad1]242        Respond to check/uncheck and to modify the model moniker actions
[47d7d2d]243        """
[ba01ad1]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
[47d7d2d]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:
[eb1a386]260            self.tblTabList.blockSignals(True)
[47d7d2d]261            item.setBackground(QtCore.Qt.red)
[eb1a386]262            self.tblTabList.blockSignals(False)
[47d7d2d]263            self.cmdFit.setEnabled(False)
[ba01ad1]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)
[0764593]282        # Replace constraint name in the remaining tabs
283        for tab in self.available_tabs.values():
284            tab.replaceConstraintName(self.current_cell, new_moniker)
[ba01ad1]285        # Reinitialize the display
286        self.initializeFitList()
[47d7d2d]287
288    def onConstraintChange(self, row, column):
289        """
[116dd4c1]290        Modify the constraint's "active" instance variable.
[47d7d2d]291        """
[ba01ad1]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)
[47d7d2d]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
[116dd4c1]307    def onFitComplete(self, result):
308        """
309        Respond to the successful fit complete signal
310        """
[17968c3]311        #re-enable the Fit button
312        self.cmdFit.setText("Fit")
313        self.cmdFit.setEnabled(True)
314
[14ec91c5]315        # Notify the parent about completed fitting
316        self.parent.fittingStoppedSignal.emit(self.getTabsForFit())
317
[235d766]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
[c6343a5]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))
[116dd4c1]342
[17968c3]343        msg = "Fitting completed successfully in: %s s.\n" % GuiUtils.formatNumber(elapsed)
344        self.parent.communicate.statusBarUpdateSignal.emit(msg)
345
[116dd4c1]346    def onBatchFitComplete(self, result):
347        """
348        Respond to the successful batch fit complete signal
349        """
[17968c3]350        #re-enable the Fit button
351        self.cmdFit.setText("Fit")
352        self.cmdFit.setEnabled(True)
353
[14ec91c5]354        # Notify the parent about completed fitting
355        self.parent.fittingStoppedSignal.emit(self.getTabsForFit())
356
[17968c3]357        # get the elapsed time
358        elapsed = result[1]
359
[d4dac80]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])
[17968c3]367
368        msg = "Fitting completed successfully in: %s s.\n" % GuiUtils.formatNumber(elapsed)
369        self.parent.communicate.statusBarUpdateSignal.emit(msg)
370
[116dd4c1]371    def onFitFailed(self, reason):
372        """
[17968c3]373        Respond to fitting failure.
[116dd4c1]374        """
[17968c3]375        #re-enable the Fit button
376        self.cmdFit.setText("Fit")
377        self.cmdFit.setEnabled(True)
378
[14ec91c5]379        # Notify the parent about completed fitting
380        self.parent.fittingStoppedSignal.emit(self.getTabsForFit())
381
[17968c3]382        msg = "Fitting failed: %s s.\n" % reason
383        self.parent.communicate.statusBarUpdateSignal.emit(msg)
[116dd4c1]384 
[be8f4b0]385    def isTabImportable(self, tab):
[676f137]386        """
[be8f4b0]387        Determines if the tab can be imported and included in the widget
[676f137]388        """
[da9a0722]389        if not isinstance(tab, str): return False
[be8f4b0]390        if not self.currentType in tab: return False
391        object = ObjectLibrary.getObject(tab)
392        if not isinstance(object, FittingWidget): return False
[91ad45c]393        if not object.data_is_loaded : return False
[be8f4b0]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:
[676f137]404            return
[be8f4b0]405        # Select for fitting
406        param_string = "Fit Page " if num_rows==1 else "Fit Pages "
[676f137]407
[be8f4b0]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)
[676f137]430
[be8f4b0]431        # Define the callbacks
[47d7d2d]432        self.actionMutualMultiConstrain.triggered.connect(self.showMultiConstraint)
[be8f4b0]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):
[676f137]442        """
[be8f4b0]443        Show context specific menu in the tab table widget.
[676f137]444        """
[be8f4b0]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"))
[676f137]460
[be8f4b0]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        """
[47d7d2d]524        # Removing rows from the table we're iterating over,
525        # so prepare a list of data first
[be8f4b0]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
[47d7d2d]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
[be8f4b0]545    def updateFitLine(self, tab):
546        """
547        Update a single line of the table widget with tab info
548        """
[ba01ad1]549        fit_page = ObjectLibrary.getObject(tab)
550        model = fit_page.kernel_module
[be8f4b0]551        if model is None:
552            return
553        tab_name = tab
554        model_name = model.id
555        moniker = model.name
[ba01ad1]556        model_data = fit_page.data
[be8f4b0]557        model_filename = model_data.filename
[ba01ad1]558        self.available_tabs[moniker] = fit_page
[be8f4b0]559
560        # Update the model table widget
561        pos = self.tblTabList.rowCount()
562        self.tblTabList.insertRow(pos)
[47d7d2d]563        item = self.uneditableItem(tab_name)
564        item.setFlags(item.flags() ^ QtCore.Qt.ItemIsUserCheckable)
[ba01ad1]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
[731efec]572        # Disable signals so we don't get infinite call recursion
573        self.tblTabList.blockSignals(True)
[be8f4b0]574        self.tblTabList.setItem(pos, 0, item)
[47d7d2d]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)
[be8f4b0]581
582        # Check if any constraints present in tab
[235d766]583        constraint_names = fit_page.getComplexConstraintsForModel()
[ba01ad1]584        constraints = fit_page.getConstraintObjectsForModel()
[be8f4b0]585        if not constraints: 
586            return
587        self.tblConstraints.setEnabled(True)
[731efec]588        self.tblConstraints.blockSignals(True)
[ba01ad1]589        for constraint, constraint_name in zip(constraints, constraint_names):
[be8f4b0]590            # Create the text for widget item
[ba01ad1]591            label = moniker + ":"+ constraint_name[0] + " = " + constraint_name[1]
592            pos = self.tblConstraints.rowCount()
593            self.available_constraints[pos] = constraint
[be8f4b0]594
595            # Show the text in the constraint table
[ba01ad1]596            item = self.uneditableItem(label)
597            item.setFlags(item.flags() ^ QtCore.Qt.ItemIsUserCheckable)
[be8f4b0]598            item.setCheckState(QtCore.Qt.Checked)
599            self.tblConstraints.insertRow(pos)
600            self.tblConstraints.setItem(pos, 0, item)
[731efec]601        self.tblConstraints.blockSignals(False)
[be8f4b0]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
[676f137]627
[be8f4b0]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)
[47d7d2d]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
[c5a2722f]650    def getObjectByName(self, name):
[731efec]651        """
652        Given name of the fit, returns associated fit object
653        """
[c5a2722f]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
[47d7d2d]665    def showMultiConstraint(self):
666        """
667        Invoke the complex constraint editor
668        """
[2d466e4]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
[c5a2722f]678        constraint = Constraint()
679        model1, param1, operator, constraint_text = cc_widget.constraint()
680
681        constraint.func = constraint_text
[3b3b40b]682        # param1 is the parameter we're constraining
[ba01ad1]683        constraint.param = param1
[3b3b40b]684
[c5a2722f]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)
Note: See TracBrowser for help on using the repository browser.