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

ESS_GUIESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since e5ae812 was e5ae812, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 5 years ago

Added C&S tab serialization.

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