source: sasview/src/sas/qtgui/Perspectives/Fitting/FittingOptions.py @ f3cc979

ESS_GUIESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since f3cc979 was ff3b293, checked in by Piotr Rozyczko <rozyczko@…>, 6 years ago

Improve error handling in Chi2 calculations.
Improve bad input communication in Fit Algorithms
SASVIEW-988

  • Property mode set to 100644
File size: 8.7 KB
Line 
1# global
2import sys
3import os
4import types
5import webbrowser
6
7from PyQt5 import QtCore
8from PyQt5 import QtGui
9from PyQt5 import QtWidgets
10
11from sas.qtgui.UI import images_rc
12from sas.qtgui.UI import main_resources_rc
13import sas.qtgui.Utilities.GuiUtils as GuiUtils
14
15from bumps import fitters
16import bumps.options
17
18from sas.qtgui.Perspectives.Fitting.UI.FittingOptionsUI import Ui_FittingOptions
19
20# Set the default optimizer
21fitters.FIT_DEFAULT_ID = 'lm'
22
23
24class FittingOptions(QtWidgets.QDialog, Ui_FittingOptions):
25    """
26    Hard-coded version of the fit options dialog available from BUMPS.
27    This should be make more "dynamic".
28    bumps.options.FIT_FIELDS gives mapping between parameter names, parameter strings and field type
29     (double line edit, integer line edit, combo box etc.), e.g.
30        FIT_FIELDS = dict(
31            samples = ("Samples", parse_int),
32            xtol = ("x tolerance", float))
33
34    bumps.fitters.<algorithm>.settings gives mapping between algorithm, parameter name and default value:
35        e.g.
36        settings = [('steps', 1000), ('starts', 1), ('radius', 0.15), ('xtol', 1e-6), ('ftol', 1e-8)]
37    """
38    fit_option_changed = QtCore.pyqtSignal(str)
39
40    def __init__(self, parent=None, config=None):
41        super(FittingOptions, self).__init__(parent)
42        self.setupUi(self)
43
44        self.config = config
45
46        # no reason to have this widget resizable
47        self.setFixedSize(self.minimumSizeHint())
48
49        self.setWindowTitle("Fit Algorithms")
50
51        # Fill up the algorithm combo, based on what BUMPS says is available
52        self.cbAlgorithm.addItems([n.name for n in fitters.FITTERS if n.id in fitters.FIT_ACTIVE_IDS])
53
54        # Handle the Apply button click
55        self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).clicked.connect(self.onApply)
56        # handle the Help button click
57        self.buttonBox.button(QtWidgets.QDialogButtonBox.Help).clicked.connect(self.onHelp)
58
59        # Handle the combo box changes
60        self.cbAlgorithm.currentIndexChanged.connect(self.onAlgorithmChange)
61
62        # Set the default index
63        default_name = [n.name for n in fitters.FITTERS if n.id == fitters.FIT_DEFAULT_ID][0]
64        default_index = self.cbAlgorithm.findText(default_name)
65        self.cbAlgorithm.setCurrentIndex(default_index)
66
67        # Assign appropriate validators
68        self.assignValidators()
69
70        # Set defaults
71        self.current_fitter_id = fitters.FIT_DEFAULT_ID
72
73        # OK has to be initialized to True, after initial validator setup
74        self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(True)
75
76    def assignValidators(self):
77        """
78        Use options.FIT_FIELDS to assert which line edit gets what validator
79        """
80        for option in bumps.options.FIT_FIELDS.keys():
81            (f_name, f_type) = bumps.options.FIT_FIELDS[option]
82            validator = None
83            if type(f_type) == types.FunctionType:
84                validator = QtGui.QIntValidator()
85                validator.setBottom(0)
86            elif f_type == float:
87                validator = GuiUtils.DoubleValidator()
88                validator.setBottom(0)
89            else:
90                continue
91            for fitter_id in fitters.FIT_ACTIVE_IDS:
92                line_edit = self.widgetFromOption(str(option), current_fitter=str(fitter_id))
93                if hasattr(line_edit, 'setValidator') and validator is not None:
94                    line_edit.setValidator(validator)
95                    line_edit.textChanged.connect(self.check_state)
96                    line_edit.textChanged.emit(line_edit.text())
97
98    def check_state(self, *args, **kwargs):
99        sender = self.sender()
100        validator = sender.validator()
101        state = validator.validate(sender.text(), 0)[0]
102        if state == QtGui.QValidator.Acceptable:
103            color = '' # default
104            self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(True)
105        else:
106            color = '#fff79a' # yellow
107            self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)
108
109        sender.setStyleSheet('QLineEdit { background-color: %s }' % color)
110
111    def onAlgorithmChange(self, index):
112        """
113        Change the page in response to combo box index
114        """
115        # Find the algorithm ID from name
116        self.current_fitter_id = \
117            [n.id for n in fitters.FITTERS if n.name == str(self.cbAlgorithm.currentText())][0]
118
119        # find the right stacked widget
120        widget_name = "self.page_"+str(self.current_fitter_id)
121
122        # Convert the name into widget instance
123        widget_to_activate = eval(widget_name)
124        index_for_this_id = self.stackedWidget.indexOf(widget_to_activate)
125
126        # Select the requested widget
127        self.stackedWidget.setCurrentIndex(index_for_this_id)
128
129        self.updateWidgetFromBumps(self.current_fitter_id)
130
131        self.assignValidators()
132
133        # OK has to be reinitialized to True
134        self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(True)
135
136    def onApply(self):
137        """
138        Update the fitter object
139        """
140        options = self.config.values[self.current_fitter_id]
141        for option in options.keys():
142            # Find the widget name of the option
143            # e.g. 'samples' for 'dream' is 'self.samples_dream'
144            widget_name = 'self.'+option+'_'+self.current_fitter_id
145            line_edit = eval(widget_name)
146            if line_edit is None or not isinstance(line_edit, QtWidgets.QLineEdit):
147                continue
148            color = line_edit.palette().color(QtGui.QPalette.Background).name()
149            if color == '#fff79a':
150                # Show a custom tooltip and return
151                tooltip = "<html><b>Please enter valid values in all fields.</html>"
152                QtWidgets.QToolTip.showText(line_edit.mapToGlobal(
153                    QtCore.QPoint(line_edit.rect().right(), line_edit.rect().bottom() + 2)), tooltip)
154                return
155
156        # Notify the perspective, so the window title is updated
157        self.fit_option_changed.emit(self.cbAlgorithm.currentText())
158
159        def bumpsUpdate(option):
160            """
161            Utility method for bumps state update
162            """
163            widget = self.widgetFromOption(option)
164            if widget is None:
165                return
166            try:
167                new_value = widget.currentText() if isinstance(widget, QtWidgets.QComboBox) \
168                    else float(widget.text())
169                self.config.values[self.current_fitter_id][option] = new_value
170            except ValueError:
171                # Don't update bumps if widget has bad data
172                self.reject
173
174        # Update the BUMPS singleton
175        [bumpsUpdate(o) for o in self.config.values[self.current_fitter_id].keys()]
176        self.close()
177
178    def onHelp(self):
179        """
180        Show the "Fitting options" section of help
181        """
182        tree_location = GuiUtils.HELP_DIRECTORY_LOCATION
183        tree_location += "/user/qtgui/Perspectives/Fitting/"
184
185        # Actual file anchor will depend on the combo box index
186        # Note that we can be clusmy here, since bad current_fitter_id
187        # will just make the page displayed from the top
188        helpfile = "optimizer.html#fit-" + self.current_fitter_id
189        help_location = tree_location + helpfile
190        webbrowser.open('file://' + os.path.realpath(help_location))
191
192    def widgetFromOption(self, option_id, current_fitter=None):
193        """
194        returns widget's element linked to the given option_id
195        """
196        if current_fitter is None:
197            current_fitter = self.current_fitter_id
198        if option_id not in list(bumps.options.FIT_FIELDS.keys()): return None
199        option = option_id + '_' + current_fitter
200        if not hasattr(self, option): return None
201        return eval('self.' + option)
202
203    def getResults(self):
204        """
205        Sends back the current choice of parameters
206        """
207        algorithm = self.cbAlgorithm.currentText()
208        return algorithm
209
210    def updateWidgetFromBumps(self, fitter_id):
211        """
212        Given the ID of the current optimizer, fetch the values
213        and update the widget
214        """
215        options = self.config.values[fitter_id]
216        for option in options.keys():
217            # Find the widget name of the option
218            # e.g. 'samples' for 'dream' is 'self.samples_dream'
219            widget_name = 'self.'+option+'_'+fitter_id
220            if option not in bumps.options.FIT_FIELDS:
221                return
222            if isinstance(bumps.options.FIT_FIELDS[option][1], bumps.options.ChoiceList):
223                control = eval(widget_name)
224                control.setCurrentIndex(control.findText(str(options[option])))
225            else:
226                eval(widget_name).setText(str(options[option]))
227
228        pass
Note: See TracBrowser for help on using the repository browser.