[2d0e0c1] | 1 | # global |
---|
| 2 | import sys |
---|
| 3 | import os |
---|
[b0c5e8c] | 4 | import types |
---|
[e90988c] | 5 | import webbrowser |
---|
[b0c5e8c] | 6 | |
---|
[4992ff2] | 7 | from PyQt5 import QtCore |
---|
| 8 | from PyQt5 import QtGui |
---|
| 9 | from PyQt5 import QtWidgets |
---|
[2d0e0c1] | 10 | |
---|
| 11 | from sas.qtgui.UI import images_rc |
---|
| 12 | from sas.qtgui.UI import main_resources_rc |
---|
[b0c5e8c] | 13 | import sas.qtgui.Utilities.GuiUtils as GuiUtils |
---|
| 14 | |
---|
[2d0e0c1] | 15 | from bumps import fitters |
---|
| 16 | import bumps.options |
---|
| 17 | |
---|
| 18 | from sas.qtgui.Perspectives.Fitting.UI.FittingOptionsUI import Ui_FittingOptions |
---|
| 19 | |
---|
| 20 | # Set the default optimizer |
---|
| 21 | |
---|
[aa47ea5] | 22 | class FittingMethodParameter: |
---|
[04a269f] | 23 | """ |
---|
| 24 | Descriptive meta data of a single parameter of an optimizer. |
---|
| 25 | """ |
---|
[aa47ea5] | 26 | _shortName = None |
---|
| 27 | _longName = None |
---|
| 28 | _type = None |
---|
| 29 | _defaultValue = None |
---|
| 30 | value = None |
---|
| 31 | |
---|
| 32 | def __init__(self, shortName, longName, dtype, defaultValue): |
---|
| 33 | self._shortName = shortName |
---|
| 34 | self._longName = longName |
---|
| 35 | self._type = dtype |
---|
| 36 | self._defaultValue = defaultValue |
---|
| 37 | self.value = defaultValue |
---|
| 38 | |
---|
| 39 | @property |
---|
| 40 | def shortName(self): |
---|
| 41 | return self._shortName |
---|
| 42 | |
---|
| 43 | @property |
---|
| 44 | def longName(self): |
---|
| 45 | return self._longName |
---|
| 46 | |
---|
| 47 | @property |
---|
| 48 | def type(self): |
---|
| 49 | return self._type |
---|
| 50 | |
---|
| 51 | @property |
---|
| 52 | def defaultValue(self): |
---|
| 53 | return self._defaultValue |
---|
| 54 | |
---|
| 55 | def __str__(self): |
---|
| 56 | return "'{}' ({}): {} ({})".format( |
---|
| 57 | self.longName, self.sortName, self.defaultValue, self.type) |
---|
| 58 | |
---|
| 59 | class FittingMethod: |
---|
| 60 | """ |
---|
| 61 | Represents a generic fitting method. |
---|
| 62 | """ |
---|
| 63 | _shortName = None |
---|
| 64 | _longName = None |
---|
| 65 | _params = None # dict of <param short names>: <FittingMethodParam> |
---|
| 66 | |
---|
| 67 | def __init__(self, shortName, longName, params): |
---|
| 68 | self._shortName = shortName |
---|
| 69 | self._longName = longName |
---|
| 70 | self._params = dict(zip([p.shortName for p in params], params)) |
---|
| 71 | |
---|
| 72 | @property |
---|
| 73 | def shortName(self): |
---|
| 74 | return self._shortName |
---|
| 75 | |
---|
| 76 | @property |
---|
| 77 | def longName(self): |
---|
| 78 | return self._longName |
---|
| 79 | |
---|
| 80 | @property |
---|
| 81 | def params(self): |
---|
| 82 | return self._params |
---|
| 83 | |
---|
[740a738] | 84 | def storeConfig(self): |
---|
| 85 | """ |
---|
| 86 | To be overridden by subclasses specific to optimizers. |
---|
| 87 | """ |
---|
| 88 | pass |
---|
| 89 | |
---|
[aa47ea5] | 90 | def __str__(self): |
---|
| 91 | return "\n".join(["{} ({})".format(self.longName, self.shortName)] |
---|
| 92 | + [str(p) for p in self.params]) |
---|
| 93 | |
---|
| 94 | class FittingMethods: |
---|
| 95 | """ |
---|
| 96 | A container for the available fitting methods. |
---|
| 97 | Allows SasView to employ other methods than those provided by the bumps package. |
---|
| 98 | """ |
---|
| 99 | _methods = None # a dict containing FitMethod objects |
---|
| 100 | _default = None |
---|
| 101 | |
---|
| 102 | def __init__(self): |
---|
| 103 | """Receives a list of FittingMethod instances to be initialized with.""" |
---|
| 104 | self._methods = dict() |
---|
| 105 | |
---|
| 106 | def add(self, fittingMethod): |
---|
| 107 | if not isinstance(fittingMethod, FittingMethod): |
---|
| 108 | return |
---|
| 109 | self._methods[fittingMethod.longName] = fittingMethod |
---|
| 110 | |
---|
| 111 | @property |
---|
| 112 | def longNames(self): |
---|
| 113 | return list(self._methods.keys()) |
---|
| 114 | |
---|
| 115 | @property |
---|
| 116 | def ids(self): |
---|
| 117 | return [fm.shortName for fm in self._methods.values()] |
---|
| 118 | |
---|
[04a269f] | 119 | def __getitem__(self, longName): |
---|
| 120 | return self._methods[longName] |
---|
[aa47ea5] | 121 | |
---|
[740a738] | 122 | def __len__(self): |
---|
| 123 | return len(self._methods) |
---|
| 124 | |
---|
| 125 | def __iter__(self): |
---|
| 126 | return self._methods.__iter__ |
---|
| 127 | |
---|
[aa47ea5] | 128 | @property |
---|
| 129 | def default(self): |
---|
| 130 | return self._default |
---|
| 131 | |
---|
| 132 | def setDefault(self, methodName): |
---|
| 133 | assert methodName in self._methods # silently fail instead? |
---|
| 134 | self._default = self._methods[methodName] |
---|
| 135 | |
---|
| 136 | def __str__(self): |
---|
| 137 | return "\n".join(["{}: {}".format(key, fm) for key, fm in self._methods.items()]) |
---|
[72f4834] | 138 | |
---|
[740a738] | 139 | class FittingMethodBumps(FittingMethod): |
---|
| 140 | def storeConfig(self): |
---|
| 141 | """ |
---|
| 142 | Writes the user settings of given fitting method back to the optimizer backend |
---|
| 143 | where it is used once the 'fit' button is hit in the GUI. |
---|
| 144 | """ |
---|
| 145 | fitConfig = bumps.options.FIT_CONFIG |
---|
| 146 | fitConfig.selected_id = self.shortName |
---|
| 147 | for param in self.params.values(): |
---|
| 148 | fitConfig.values[self.shortName][param.shortName] = param.value |
---|
| 149 | |
---|
| 150 | class FittingMethodsBumps(FittingMethods): |
---|
| 151 | def __init__(self): |
---|
| 152 | """ |
---|
| 153 | Import fitting methods indicated by the provided list of ids from the bumps package. |
---|
| 154 | """ |
---|
| 155 | super(FittingMethodsBumps, self).__init__() |
---|
| 156 | ids = fitters.FIT_ACTIVE_IDS |
---|
| 157 | for f in fitters.FITTERS: |
---|
| 158 | if f.id not in ids: |
---|
| 159 | continue |
---|
| 160 | params = [] |
---|
| 161 | for shortName, defValue in f.settings: |
---|
| 162 | longName, dtype = bumps.options.FIT_FIELDS[shortName] |
---|
[22b4962] | 163 | dtype = self._convertParamType(dtype) |
---|
[740a738] | 164 | param = FittingMethodParameter(shortName, longName, dtype, defValue) |
---|
| 165 | params.append(param) |
---|
| 166 | self.add(FittingMethodBumps(f.id, f.name, params)) |
---|
| 167 | |
---|
[22b4962] | 168 | @staticmethod |
---|
| 169 | def _convertParamType(dtype): |
---|
| 170 | if dtype is bumps.options.parse_int: |
---|
| 171 | dtype = int |
---|
| 172 | elif isinstance(dtype, bumps.options.ChoiceList): |
---|
| 173 | dtype = tuple(dtype.choices) |
---|
| 174 | return dtype |
---|
| 175 | |
---|
[4992ff2] | 176 | class FittingOptions(QtWidgets.QDialog, Ui_FittingOptions): |
---|
[2d0e0c1] | 177 | """ |
---|
| 178 | Hard-coded version of the fit options dialog available from BUMPS. |
---|
| 179 | This should be make more "dynamic". |
---|
| 180 | bumps.options.FIT_FIELDS gives mapping between parameter names, parameter strings and field type |
---|
| 181 | (double line edit, integer line edit, combo box etc.), e.g. |
---|
| 182 | FIT_FIELDS = dict( |
---|
| 183 | samples = ("Samples", parse_int), |
---|
| 184 | xtol = ("x tolerance", float)) |
---|
| 185 | |
---|
| 186 | bumps.fitters.<algorithm>.settings gives mapping between algorithm, parameter name and default value: |
---|
| 187 | e.g. |
---|
| 188 | settings = [('steps', 1000), ('starts', 1), ('radius', 0.15), ('xtol', 1e-6), ('ftol', 1e-8)] |
---|
| 189 | """ |
---|
[b0c5e8c] | 190 | fit_option_changed = QtCore.pyqtSignal(str) |
---|
[aa47ea5] | 191 | # storing of fitting methods here for now, dependencies might indicate a better place later |
---|
[04a269f] | 192 | _fittingMethods = None |
---|
| 193 | |
---|
| 194 | @property |
---|
| 195 | def fittingMethods(self): |
---|
| 196 | return self._fittingMethods |
---|
[2d0e0c1] | 197 | |
---|
[c9d6b9f] | 198 | def __init__(self, parent=None): |
---|
[2d0e0c1] | 199 | super(FittingOptions, self).__init__(parent) |
---|
| 200 | self.setupUi(self) |
---|
[33c0561] | 201 | # disable the context help icon |
---|
| 202 | self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint) |
---|
[85487ebd] | 203 | self.setWindowTitle("Fit Algorithms") |
---|
[fec5842] | 204 | # no reason to have this widget resizable |
---|
| 205 | self.layout().setSizeConstraint(QtWidgets.QLayout.SetFixedSize) |
---|
[2d0e0c1] | 206 | |
---|
| 207 | # Fill up the algorithm combo, based on what BUMPS says is available |
---|
[740a738] | 208 | self._fittingMethods = FittingMethodsBumps() |
---|
[aa47ea5] | 209 | # option 1: hardcode the list of bumps fitting methods according to forms |
---|
| 210 | # option 2: create forms dynamically based on selected fitting methods |
---|
[740a738] | 211 | self.fittingMethods.add(FittingMethod('mcsas', 'McSAS', [])) # FIXME just testing for now |
---|
[aa47ea5] | 212 | self.fittingMethods.setDefault('Levenberg-Marquardt') |
---|
[22b4962] | 213 | |
---|
[aa47ea5] | 214 | # build up the comboBox finally |
---|
| 215 | self.cbAlgorithm.addItems(self.fittingMethods.longNames) |
---|
[2d0e0c1] | 216 | |
---|
| 217 | # Handle the Apply button click |
---|
[4992ff2] | 218 | self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).clicked.connect(self.onApply) |
---|
[b0c5e8c] | 219 | # handle the Help button click |
---|
[4992ff2] | 220 | self.buttonBox.button(QtWidgets.QDialogButtonBox.Help).clicked.connect(self.onHelp) |
---|
[2d0e0c1] | 221 | |
---|
[b0c5e8c] | 222 | # Assign appropriate validators |
---|
| 223 | self.assignValidators() |
---|
| 224 | |
---|
[72f4834] | 225 | # OK has to be initialized to True, after initial validator setup |
---|
[4992ff2] | 226 | self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(True) |
---|
[72f4834] | 227 | |
---|
[fec5842] | 228 | # Handle the combo box changes |
---|
| 229 | self.cbAlgorithm.currentIndexChanged.connect(self.onAlgorithmChange) |
---|
| 230 | |
---|
| 231 | # Set the default index and trigger filling the layout |
---|
| 232 | default_index = self.cbAlgorithm.findText(self.fittingMethods.default.longName) |
---|
| 233 | self.cbAlgorithm.setCurrentIndex(default_index) |
---|
| 234 | |
---|
[b0c5e8c] | 235 | def assignValidators(self): |
---|
| 236 | """ |
---|
[04a269f] | 237 | Sets the appropriate validators to the line edits as defined by FittingMethodParameter |
---|
[b0c5e8c] | 238 | """ |
---|
[af893db] | 239 | fm = self.fittingMethods[self.currentOptimizer] |
---|
[04a269f] | 240 | for param in fm.params.values(): |
---|
[b0c5e8c] | 241 | validator = None |
---|
[22b4962] | 242 | if param.type == int: |
---|
[b0c5e8c] | 243 | validator = QtGui.QIntValidator() |
---|
[72f4834] | 244 | validator.setBottom(0) |
---|
[04a269f] | 245 | elif param.type == float: |
---|
[d6b8a1d] | 246 | validator = GuiUtils.DoubleValidator() |
---|
[72f4834] | 247 | validator.setBottom(0) |
---|
[b0c5e8c] | 248 | else: |
---|
| 249 | continue |
---|
[04a269f] | 250 | line_edit = self.paramWidget(fm, param.shortName) |
---|
| 251 | if hasattr(line_edit, 'setValidator') and validator is not None: |
---|
| 252 | line_edit.setValidator(validator) |
---|
| 253 | line_edit.textChanged.connect(self.check_state) |
---|
| 254 | line_edit.textChanged.emit(line_edit.text()) |
---|
[72f4834] | 255 | |
---|
| 256 | def check_state(self, *args, **kwargs): |
---|
| 257 | sender = self.sender() |
---|
| 258 | validator = sender.validator() |
---|
| 259 | state = validator.validate(sender.text(), 0)[0] |
---|
| 260 | if state == QtGui.QValidator.Acceptable: |
---|
| 261 | color = '' # default |
---|
[4992ff2] | 262 | self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(True) |
---|
[72f4834] | 263 | else: |
---|
| 264 | color = '#fff79a' # yellow |
---|
[4992ff2] | 265 | self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False) |
---|
[72f4834] | 266 | |
---|
| 267 | sender.setStyleSheet('QLineEdit { background-color: %s }' % color) |
---|
[2d0e0c1] | 268 | |
---|
[22b4962] | 269 | def _clearLayout(self): |
---|
| 270 | layout = self.groupBox.layout() |
---|
| 271 | for i in reversed(list(range(layout.count()))): |
---|
| 272 | # reversed removal avoids renumbering possibly |
---|
| 273 | item = layout.takeAt(i) |
---|
| 274 | try: # spaceritem does not have a widget |
---|
[fec5842] | 275 | if item.widget().objectName() == "cbAlgorithm": |
---|
| 276 | continue # do not delete the checkbox, will be added later again |
---|
[22b4962] | 277 | item.widget().setParent(None) |
---|
| 278 | item.widget().deleteLater() |
---|
| 279 | except AttributeError: |
---|
| 280 | pass |
---|
| 281 | |
---|
| 282 | @staticmethod |
---|
| 283 | def _makeLabel(name): |
---|
| 284 | lbl = QtWidgets.QLabel(name + ":") |
---|
| 285 | lbl.setAlignment(QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) |
---|
[fec5842] | 286 | lbl.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, |
---|
| 287 | QtWidgets.QSizePolicy.Fixed)) |
---|
[22b4962] | 288 | lbl.setWordWrap(True) |
---|
| 289 | return lbl |
---|
| 290 | |
---|
| 291 | @staticmethod |
---|
| 292 | def _inputWidgetFromType(ptype, parent): |
---|
| 293 | """ |
---|
| 294 | Creates a widget for user input based on the given data type to be entered. |
---|
| 295 | """ |
---|
| 296 | widget = None |
---|
| 297 | if ptype in (float, int): |
---|
| 298 | widget = QtWidgets.QLineEdit(parent) |
---|
| 299 | elif isinstance(ptype, (tuple, list)): |
---|
| 300 | widget = QtWidgets.QComboBox(parent) |
---|
| 301 | widget.addItems(ptype) |
---|
| 302 | return widget |
---|
| 303 | |
---|
| 304 | def _fillLayout(self): |
---|
| 305 | fm = self.fittingMethods[self.currentOptimizer] |
---|
| 306 | layout = self.groupBox.layout() |
---|
[fec5842] | 307 | layout.addWidget(self.cbAlgorithm, 0, 0, 1, -1) |
---|
[22b4962] | 308 | for param in fm.params.values(): |
---|
[fec5842] | 309 | row = layout.rowCount()+1 |
---|
[22b4962] | 310 | layout.addWidget(self._makeLabel(param.longName), row, 0) |
---|
| 311 | widget = self._inputWidgetFromType(param.type, self) |
---|
| 312 | if widget is None: |
---|
| 313 | continue |
---|
| 314 | widgetName = param.shortName+'_'+fm.shortName |
---|
| 315 | layout.addWidget(widget, row, 1) |
---|
| 316 | setattr(self, widgetName, widget) |
---|
| 317 | layout.addItem(QtWidgets.QSpacerItem(0, 0, vPolicy=QtWidgets.QSizePolicy.Expanding)) |
---|
| 318 | |
---|
[2d0e0c1] | 319 | def onAlgorithmChange(self, index): |
---|
| 320 | """ |
---|
| 321 | Change the page in response to combo box index |
---|
| 322 | """ |
---|
| 323 | # Find the algorithm ID from name |
---|
[af893db] | 324 | selectedName = self.currentOptimizer |
---|
[22b4962] | 325 | |
---|
| 326 | self._clearLayout() |
---|
| 327 | self._fillLayout() |
---|
| 328 | |
---|
[2d0e0c1] | 329 | # Select the requested widget |
---|
[04a269f] | 330 | self.updateWidgetFromConfig() |
---|
[b0c5e8c] | 331 | self.assignValidators() |
---|
| 332 | |
---|
[b67bfa7] | 333 | # OK has to be reinitialized to True |
---|
[4992ff2] | 334 | self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(True) |
---|
[b67bfa7] | 335 | |
---|
[04a269f] | 336 | def paramWidget(self, fittingMethod, paramShortName): |
---|
| 337 | """ |
---|
| 338 | Returns the widget associated to a FittingMethodParameter. |
---|
| 339 | """ |
---|
| 340 | if paramShortName not in fittingMethod.params: |
---|
| 341 | return None |
---|
| 342 | widget_name = 'self.'+paramShortName+'_'+fittingMethod.shortName |
---|
| 343 | widget = None |
---|
| 344 | try: |
---|
| 345 | widget = eval(widget_name) |
---|
| 346 | except AttributeError: |
---|
| 347 | pass |
---|
| 348 | return widget |
---|
| 349 | |
---|
[2d0e0c1] | 350 | def onApply(self): |
---|
| 351 | """ |
---|
[b0c5e8c] | 352 | Update the fitter object |
---|
[2d0e0c1] | 353 | """ |
---|
[af893db] | 354 | fm = self.fittingMethods[self.currentOptimizer] |
---|
[04a269f] | 355 | for param in fm.params.values(): |
---|
| 356 | line_edit = self.paramWidget(fm, param.shortName) |
---|
[ff3b293] | 357 | if line_edit is None or not isinstance(line_edit, QtWidgets.QLineEdit): |
---|
| 358 | continue |
---|
| 359 | color = line_edit.palette().color(QtGui.QPalette.Background).name() |
---|
| 360 | if color == '#fff79a': |
---|
| 361 | # Show a custom tooltip and return |
---|
| 362 | tooltip = "<html><b>Please enter valid values in all fields.</html>" |
---|
| 363 | QtWidgets.QToolTip.showText(line_edit.mapToGlobal( |
---|
[04a269f] | 364 | QtCore.QPoint(line_edit.rect().right(), line_edit.rect().bottom() + 2)), |
---|
| 365 | tooltip) |
---|
[ff3b293] | 366 | return |
---|
| 367 | |
---|
[04a269f] | 368 | # update config values from widgets before any notification is sent |
---|
[ea1753f] | 369 | try: |
---|
| 370 | self.updateConfigFromWidget(fm) |
---|
| 371 | except ValueError: |
---|
| 372 | # Don't update bumps if widget has bad data |
---|
| 373 | self.reject |
---|
[2d0e0c1] | 374 | |
---|
[740a738] | 375 | fm.storeConfig() # write the current settings to bumps module |
---|
[04a269f] | 376 | # Notify the perspective, so the window title is updated |
---|
| 377 | self.fit_option_changed.emit(self.cbAlgorithm.currentText()) |
---|
[ff3b293] | 378 | self.close() |
---|
[b0c5e8c] | 379 | |
---|
| 380 | def onHelp(self): |
---|
| 381 | """ |
---|
| 382 | Show the "Fitting options" section of help |
---|
| 383 | """ |
---|
[e90988c] | 384 | tree_location = GuiUtils.HELP_DIRECTORY_LOCATION |
---|
[aed0532] | 385 | tree_location += "/user/qtgui/Perspectives/Fitting/" |
---|
[b0c5e8c] | 386 | |
---|
| 387 | # Actual file anchor will depend on the combo box index |
---|
| 388 | # Note that we can be clusmy here, since bad current_fitter_id |
---|
| 389 | # will just make the page displayed from the top |
---|
[fec5842] | 390 | current_fitter_id = self.fittingMethods[self.currentOptimizer].shortName |
---|
| 391 | helpfile = "optimizer.html#fit-" + current_fitter_id |
---|
[b0c5e8c] | 392 | help_location = tree_location + helpfile |
---|
[e90988c] | 393 | webbrowser.open('file://' + os.path.realpath(help_location)) |
---|
[b0c5e8c] | 394 | |
---|
[04a269f] | 395 | @property |
---|
| 396 | def currentOptimizer(self): |
---|
[2d0e0c1] | 397 | """ |
---|
| 398 | Sends back the current choice of parameters |
---|
| 399 | """ |
---|
[af893db] | 400 | value = self.cbAlgorithm.currentText() |
---|
| 401 | return str(value) # is str() really needed? |
---|
[2d0e0c1] | 402 | |
---|
[04a269f] | 403 | def updateWidgetFromConfig(self): |
---|
[2d0e0c1] | 404 | """ |
---|
| 405 | Given the ID of the current optimizer, fetch the values |
---|
| 406 | and update the widget |
---|
| 407 | """ |
---|
[46477950] | 408 | fm = self.fittingMethods[self.currentOptimizer] |
---|
[04a269f] | 409 | for param in fm.params.values(): |
---|
[2d0e0c1] | 410 | # Find the widget name of the option |
---|
| 411 | # e.g. 'samples' for 'dream' is 'self.samples_dream' |
---|
[22b4962] | 412 | widget_name = 'self.'+param.shortName+'_'+fm.shortName |
---|
| 413 | if isinstance(param.type, (tuple, list)): |
---|
[2d0e0c1] | 414 | control = eval(widget_name) |
---|
[04a269f] | 415 | control.setCurrentIndex(control.findText(str(param.value))) |
---|
[2d0e0c1] | 416 | else: |
---|
[04a269f] | 417 | eval(widget_name).setText(str(param.value)) |
---|
[2d0e0c1] | 418 | |
---|
[ea1753f] | 419 | def updateConfigFromWidget(self, fittingMethod): |
---|
| 420 | # update config values from widgets before any notification is sent |
---|
| 421 | for param in fittingMethod.params.values(): |
---|
| 422 | widget = self.paramWidget(fittingMethod, param.shortName) |
---|
| 423 | if widget is None: |
---|
| 424 | continue |
---|
| 425 | new_value = None |
---|
| 426 | if isinstance(widget, QtWidgets.QComboBox): |
---|
| 427 | new_value = widget.currentText() |
---|
| 428 | else: |
---|
| 429 | try: |
---|
| 430 | new_value = int(widget.text()) |
---|
| 431 | except ValueError: |
---|
| 432 | new_value = float(widget.text()) |
---|
| 433 | if new_value is not None: |
---|
| 434 | fittingMethod.params[param.shortName].value = new_value |
---|