[60af928] | 1 | import json |
---|
[cd31251] | 2 | import os |
---|
[60af928] | 3 | from collections import defaultdict |
---|
[b3e8629] | 4 | |
---|
[60af928] | 5 | |
---|
[5236449] | 6 | import logging |
---|
| 7 | import traceback |
---|
[cbcdd2c] | 8 | from twisted.internet import threads |
---|
[1bc27f1] | 9 | import numpy as np |
---|
[e90988c] | 10 | import webbrowser |
---|
[5236449] | 11 | |
---|
[4992ff2] | 12 | from PyQt5 import QtCore |
---|
| 13 | from PyQt5 import QtGui |
---|
| 14 | from PyQt5 import QtWidgets |
---|
[60af928] | 15 | |
---|
[5d1440e1] | 16 | from sasmodels import product |
---|
[60af928] | 17 | from sasmodels import generate |
---|
| 18 | from sasmodels import modelinfo |
---|
[5236449] | 19 | from sasmodels.sasview_model import load_standard_models |
---|
[358b39d] | 20 | from sasmodels.weights import MODELS as POLYDISPERSITY_MODELS |
---|
| 21 | |
---|
[f182f93] | 22 | from sas.sascalc.fit.BumpsFitting import BumpsFit as Fit |
---|
[5236449] | 23 | |
---|
[83eb5208] | 24 | import sas.qtgui.Utilities.GuiUtils as GuiUtils |
---|
[14ec91c5] | 25 | import sas.qtgui.Utilities.LocalConfig as LocalConfig |
---|
| 26 | |
---|
[dc5ef15] | 27 | from sas.qtgui.Utilities.CategoryInstaller import CategoryInstaller |
---|
| 28 | from sas.qtgui.Plotting.PlotterData import Data1D |
---|
| 29 | from sas.qtgui.Plotting.PlotterData import Data2D |
---|
[5236449] | 30 | |
---|
[1bc27f1] | 31 | from sas.qtgui.Perspectives.Fitting.UI.FittingWidgetUI import Ui_FittingWidgetUI |
---|
[dc5ef15] | 32 | from sas.qtgui.Perspectives.Fitting.FitThread import FitThread |
---|
[7adc2a8] | 33 | from sas.qtgui.Perspectives.Fitting.ConsoleUpdate import ConsoleUpdate |
---|
| 34 | |
---|
[dc5ef15] | 35 | from sas.qtgui.Perspectives.Fitting.ModelThread import Calc1D |
---|
| 36 | from sas.qtgui.Perspectives.Fitting.ModelThread import Calc2D |
---|
[4d457df] | 37 | from sas.qtgui.Perspectives.Fitting.FittingLogic import FittingLogic |
---|
| 38 | from sas.qtgui.Perspectives.Fitting import FittingUtilities |
---|
[1bc27f1] | 39 | from sas.qtgui.Perspectives.Fitting.SmearingWidget import SmearingWidget |
---|
| 40 | from sas.qtgui.Perspectives.Fitting.OptionsWidget import OptionsWidget |
---|
| 41 | from sas.qtgui.Perspectives.Fitting.FitPage import FitPage |
---|
[ad6b4e2] | 42 | from sas.qtgui.Perspectives.Fitting.ViewDelegate import ModelViewDelegate |
---|
[6011788] | 43 | from sas.qtgui.Perspectives.Fitting.ViewDelegate import PolyViewDelegate |
---|
[b00414d] | 44 | from sas.qtgui.Perspectives.Fitting.ViewDelegate import MagnetismViewDelegate |
---|
[14ec91c5] | 45 | from sas.qtgui.Perspectives.Fitting.Constraint import Constraint |
---|
[eae226b] | 46 | from sas.qtgui.Perspectives.Fitting.MultiConstraint import MultiConstraint |
---|
[60af928] | 47 | |
---|
[8222f171] | 48 | |
---|
[60af928] | 49 | TAB_MAGNETISM = 4 |
---|
| 50 | TAB_POLY = 3 |
---|
[cbcdd2c] | 51 | CATEGORY_DEFAULT = "Choose category..." |
---|
[4d457df] | 52 | CATEGORY_STRUCTURE = "Structure Factor" |
---|
[351b53e] | 53 | STRUCTURE_DEFAULT = "None" |
---|
[60af928] | 54 | |
---|
[358b39d] | 55 | DEFAULT_POLYDISP_FUNCTION = 'gaussian' |
---|
| 56 | |
---|
[7adc2a8] | 57 | |
---|
[13cd397] | 58 | class ToolTippedItemModel(QtGui.QStandardItemModel): |
---|
[f54ce30] | 59 | """ |
---|
| 60 | Subclass from QStandardItemModel to allow displaying tooltips in |
---|
| 61 | QTableView model. |
---|
| 62 | """ |
---|
[d0dfcb2] | 63 | def __init__(self, parent=None): |
---|
[13cd397] | 64 | QtGui.QStandardItemModel.__init__(self,parent) |
---|
| 65 | |
---|
[fbfc488] | 66 | def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole): |
---|
[f54ce30] | 67 | """ |
---|
| 68 | Displays tooltip for each column's header |
---|
| 69 | :param section: |
---|
| 70 | :param orientation: |
---|
| 71 | :param role: |
---|
| 72 | :return: |
---|
| 73 | """ |
---|
[13cd397] | 74 | if role == QtCore.Qt.ToolTipRole: |
---|
| 75 | if orientation == QtCore.Qt.Horizontal: |
---|
[b3e8629] | 76 | return str(self.header_tooltips[section]) |
---|
[ca7c6bd] | 77 | |
---|
[a95c44b] | 78 | return QtGui.QStandardItemModel.headerData(self, section, orientation, role) |
---|
[13cd397] | 79 | |
---|
[4992ff2] | 80 | class FittingWidget(QtWidgets.QWidget, Ui_FittingWidgetUI): |
---|
[60af928] | 81 | """ |
---|
[f46f6dc] | 82 | Main widget for selecting form and structure factor models |
---|
[60af928] | 83 | """ |
---|
[be8f4b0] | 84 | constraintAddedSignal = QtCore.pyqtSignal(list) |
---|
| 85 | newModelSignal = QtCore.pyqtSignal() |
---|
[1bc27f1] | 86 | def __init__(self, parent=None, data=None, tab_id=1): |
---|
[60af928] | 87 | |
---|
| 88 | super(FittingWidget, self).__init__() |
---|
| 89 | |
---|
[86f88d1] | 90 | # Necessary globals |
---|
[cbcdd2c] | 91 | self.parent = parent |
---|
[2a432e7] | 92 | |
---|
| 93 | # Which tab is this widget displayed in? |
---|
| 94 | self.tab_id = tab_id |
---|
| 95 | |
---|
| 96 | # Main Data[12]D holder |
---|
[ee18d33] | 97 | self.logic = FittingLogic() |
---|
[2a432e7] | 98 | |
---|
| 99 | # Globals |
---|
| 100 | self.initializeGlobals() |
---|
| 101 | |
---|
| 102 | # Main GUI setup up |
---|
| 103 | self.setupUi(self) |
---|
| 104 | self.setWindowTitle("Fitting") |
---|
| 105 | |
---|
| 106 | # Set up tabs widgets |
---|
| 107 | self.initializeWidgets() |
---|
| 108 | |
---|
| 109 | # Set up models and views |
---|
| 110 | self.initializeModels() |
---|
| 111 | |
---|
| 112 | # Defaults for the structure factors |
---|
| 113 | self.setDefaultStructureCombo() |
---|
| 114 | |
---|
| 115 | # Make structure factor and model CBs disabled |
---|
| 116 | self.disableModelCombo() |
---|
| 117 | self.disableStructureCombo() |
---|
| 118 | |
---|
| 119 | # Generate the category list for display |
---|
| 120 | self.initializeCategoryCombo() |
---|
| 121 | |
---|
| 122 | # Connect signals to controls |
---|
| 123 | self.initializeSignals() |
---|
| 124 | |
---|
| 125 | # Initial control state |
---|
| 126 | self.initializeControls() |
---|
| 127 | |
---|
| 128 | # Display HTML content |
---|
[e90988c] | 129 | #self.setupHelp() |
---|
[2a432e7] | 130 | |
---|
[457d961] | 131 | # New font to display angstrom symbol |
---|
| 132 | new_font = 'font-family: -apple-system, "Helvetica Neue", "Ubuntu";' |
---|
| 133 | self.label_17.setStyleSheet(new_font) |
---|
| 134 | self.label_19.setStyleSheet(new_font) |
---|
| 135 | |
---|
[2a432e7] | 136 | self._index = None |
---|
| 137 | if data is not None: |
---|
| 138 | self.data = data |
---|
| 139 | |
---|
| 140 | @property |
---|
| 141 | def data(self): |
---|
| 142 | return self.logic.data |
---|
| 143 | |
---|
| 144 | @data.setter |
---|
| 145 | def data(self, value): |
---|
| 146 | """ data setter """ |
---|
[f7d14a1] | 147 | # Value is either a list of indices for batch fitting or a simple index |
---|
| 148 | # for standard fitting. Assure we have a list, regardless. |
---|
[ee18d33] | 149 | if isinstance(value, list): |
---|
| 150 | self.is_batch_fitting = True |
---|
| 151 | else: |
---|
| 152 | value = [value] |
---|
| 153 | |
---|
| 154 | assert isinstance(value[0], QtGui.QStandardItem) |
---|
[2a432e7] | 155 | # _index contains the QIndex with data |
---|
[ee18d33] | 156 | self._index = value[0] |
---|
| 157 | |
---|
| 158 | # Keep reference to all datasets for batch |
---|
| 159 | self.all_data = value |
---|
[2a432e7] | 160 | |
---|
| 161 | # Update logics with data items |
---|
[f7d14a1] | 162 | # Logics.data contains only a single Data1D/Data2D object |
---|
[ee18d33] | 163 | self.logic.data = GuiUtils.dataFromItem(value[0]) |
---|
[2a432e7] | 164 | |
---|
| 165 | # Overwrite data type descriptor |
---|
| 166 | self.is2D = True if isinstance(self.logic.data, Data2D) else False |
---|
| 167 | |
---|
[f7d14a1] | 168 | # Let others know we're full of data now |
---|
[2a432e7] | 169 | self.data_is_loaded = True |
---|
| 170 | |
---|
| 171 | # Enable/disable UI components |
---|
| 172 | self.setEnablementOnDataLoad() |
---|
| 173 | |
---|
| 174 | def initializeGlobals(self): |
---|
| 175 | """ |
---|
| 176 | Initialize global variables used in this class |
---|
| 177 | """ |
---|
[cbcdd2c] | 178 | # SasModel is loaded |
---|
[60af928] | 179 | self.model_is_loaded = False |
---|
[cbcdd2c] | 180 | # Data[12]D passed and set |
---|
[5236449] | 181 | self.data_is_loaded = False |
---|
[ee18d33] | 182 | # Batch/single fitting |
---|
| 183 | self.is_batch_fitting = False |
---|
[7fd20fc] | 184 | self.is_chain_fitting = False |
---|
[cbcdd2c] | 185 | # Current SasModel in view |
---|
[5236449] | 186 | self.kernel_module = None |
---|
[cbcdd2c] | 187 | # Current SasModel view dimension |
---|
[60af928] | 188 | self.is2D = False |
---|
[cbcdd2c] | 189 | # Current SasModel is multishell |
---|
[86f88d1] | 190 | self.model_has_shells = False |
---|
[cbcdd2c] | 191 | # Utility variable to enable unselectable option in category combobox |
---|
[86f88d1] | 192 | self._previous_category_index = 0 |
---|
[cbcdd2c] | 193 | # Utility variable for multishell display |
---|
[86f88d1] | 194 | self._last_model_row = 0 |
---|
[cbcdd2c] | 195 | # Dictionary of {model name: model class} for the current category |
---|
[5236449] | 196 | self.models = {} |
---|
[f182f93] | 197 | # Parameters to fit |
---|
| 198 | self.parameters_to_fit = None |
---|
[180bd54] | 199 | # Fit options |
---|
| 200 | self.q_range_min = 0.005 |
---|
| 201 | self.q_range_max = 0.1 |
---|
| 202 | self.npts = 25 |
---|
| 203 | self.log_points = False |
---|
| 204 | self.weighting = 0 |
---|
[2add354] | 205 | self.chi2 = None |
---|
[6011788] | 206 | # Does the control support UNDO/REDO |
---|
| 207 | # temporarily off |
---|
[2241130] | 208 | self.undo_supported = False |
---|
| 209 | self.page_stack = [] |
---|
[377ade1] | 210 | self.all_data = [] |
---|
[8222f171] | 211 | # Polydisp widget table default index for function combobox |
---|
| 212 | self.orig_poly_index = 3 |
---|
[6011788] | 213 | |
---|
[116dd4c1] | 214 | # Page id for fitting |
---|
| 215 | # To keep with previous SasView values, use 200 as the start offset |
---|
| 216 | self.page_id = 200 + self.tab_id |
---|
| 217 | |
---|
[d48cc19] | 218 | # Data for chosen model |
---|
| 219 | self.model_data = None |
---|
| 220 | |
---|
[a9b568c] | 221 | # Which shell is being currently displayed? |
---|
| 222 | self.current_shell_displayed = 0 |
---|
[0d13814] | 223 | # List of all shell-unique parameters |
---|
| 224 | self.shell_names = [] |
---|
[b00414d] | 225 | |
---|
| 226 | # Error column presence in parameter display |
---|
[f182f93] | 227 | self.has_error_column = False |
---|
[aca8418] | 228 | self.has_poly_error_column = False |
---|
[b00414d] | 229 | self.has_magnet_error_column = False |
---|
[a9b568c] | 230 | |
---|
[2a432e7] | 231 | # signal communicator |
---|
[cbcdd2c] | 232 | self.communicate = self.parent.communicate |
---|
[60af928] | 233 | |
---|
[2a432e7] | 234 | def initializeWidgets(self): |
---|
| 235 | """ |
---|
| 236 | Initialize widgets for tabs |
---|
| 237 | """ |
---|
[180bd54] | 238 | # Options widget |
---|
[4992ff2] | 239 | layout = QtWidgets.QGridLayout() |
---|
[180bd54] | 240 | self.options_widget = OptionsWidget(self, self.logic) |
---|
[1bc27f1] | 241 | layout.addWidget(self.options_widget) |
---|
[180bd54] | 242 | self.tabOptions.setLayout(layout) |
---|
| 243 | |
---|
[e1e3e09] | 244 | # Smearing widget |
---|
[4992ff2] | 245 | layout = QtWidgets.QGridLayout() |
---|
[e1e3e09] | 246 | self.smearing_widget = SmearingWidget(self) |
---|
[1bc27f1] | 247 | layout.addWidget(self.smearing_widget) |
---|
[180bd54] | 248 | self.tabResolution.setLayout(layout) |
---|
[e1e3e09] | 249 | |
---|
[b1e36a3] | 250 | # Define bold font for use in various controls |
---|
[1bc27f1] | 251 | self.boldFont = QtGui.QFont() |
---|
[a0f5c36] | 252 | self.boldFont.setBold(True) |
---|
| 253 | |
---|
| 254 | # Set data label |
---|
[b1e36a3] | 255 | self.label.setFont(self.boldFont) |
---|
| 256 | self.label.setText("No data loaded") |
---|
| 257 | self.lblFilename.setText("") |
---|
| 258 | |
---|
[6ff2eb3] | 259 | # Magnetic angles explained in one picture |
---|
[4992ff2] | 260 | self.magneticAnglesWidget = QtWidgets.QWidget() |
---|
| 261 | labl = QtWidgets.QLabel(self.magneticAnglesWidget) |
---|
[6ff2eb3] | 262 | pixmap = QtGui.QPixmap(GuiUtils.IMAGES_DIRECTORY_LOCATION + '/M_angles_pic.bmp') |
---|
| 263 | labl.setPixmap(pixmap) |
---|
| 264 | self.magneticAnglesWidget.setFixedSize(pixmap.width(), pixmap.height()) |
---|
| 265 | |
---|
[2a432e7] | 266 | def initializeModels(self): |
---|
| 267 | """ |
---|
| 268 | Set up models and views |
---|
| 269 | """ |
---|
[86f88d1] | 270 | # Set the main models |
---|
[cd31251] | 271 | # We can't use a single model here, due to restrictions on flattening |
---|
| 272 | # the model tree with subclassed QAbstractProxyModel... |
---|
[13cd397] | 273 | self._model_model = ToolTippedItemModel() |
---|
| 274 | self._poly_model = ToolTippedItemModel() |
---|
| 275 | self._magnet_model = ToolTippedItemModel() |
---|
[60af928] | 276 | |
---|
| 277 | # Param model displayed in param list |
---|
| 278 | self.lstParams.setModel(self._model_model) |
---|
[5236449] | 279 | self.readCategoryInfo() |
---|
[4992ff2] | 280 | |
---|
[60af928] | 281 | self.model_parameters = None |
---|
[ad6b4e2] | 282 | |
---|
| 283 | # Delegates for custom editing and display |
---|
| 284 | self.lstParams.setItemDelegate(ModelViewDelegate(self)) |
---|
| 285 | |
---|
[86f88d1] | 286 | self.lstParams.setAlternatingRowColors(True) |
---|
[61a92d4] | 287 | stylesheet = """ |
---|
[457d961] | 288 | |
---|
| 289 | QTreeView { |
---|
| 290 | paint-alternating-row-colors-for-empty-area:0; |
---|
| 291 | } |
---|
| 292 | |
---|
[2a432e7] | 293 | QTreeView::item:hover { |
---|
| 294 | background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #e7effd, stop: 1 #cbdaf1); |
---|
| 295 | border: 1px solid #bfcde4; |
---|
[61a92d4] | 296 | } |
---|
[2a432e7] | 297 | |
---|
| 298 | QTreeView::item:selected { |
---|
| 299 | border: 1px solid #567dbc; |
---|
| 300 | } |
---|
| 301 | |
---|
| 302 | QTreeView::item:selected:active{ |
---|
| 303 | background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #6ea1f1, stop: 1 #567dbc); |
---|
| 304 | } |
---|
| 305 | |
---|
| 306 | QTreeView::item:selected:!active { |
---|
| 307 | background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #6b9be8, stop: 1 #577fbf); |
---|
| 308 | } |
---|
| 309 | """ |
---|
[61a92d4] | 310 | self.lstParams.setStyleSheet(stylesheet) |
---|
[672b8ab] | 311 | self.lstParams.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) |
---|
[7fd20fc] | 312 | self.lstParams.customContextMenuRequested.connect(self.showModelContextMenu) |
---|
[457d961] | 313 | self.lstParams.setAttribute(QtCore.Qt.WA_MacShowFocusRect, False) |
---|
[60af928] | 314 | # Poly model displayed in poly list |
---|
[811bec1] | 315 | self.lstPoly.setModel(self._poly_model) |
---|
[60af928] | 316 | self.setPolyModel() |
---|
| 317 | self.setTableProperties(self.lstPoly) |
---|
[6011788] | 318 | # Delegates for custom editing and display |
---|
[aca8418] | 319 | self.lstPoly.setItemDelegate(PolyViewDelegate(self)) |
---|
| 320 | # Polydispersity function combo response |
---|
| 321 | self.lstPoly.itemDelegate().combo_updated.connect(self.onPolyComboIndexChange) |
---|
[e43fc91] | 322 | self.lstPoly.itemDelegate().filename_updated.connect(self.onPolyFilenameChange) |
---|
[60af928] | 323 | |
---|
| 324 | # Magnetism model displayed in magnetism list |
---|
| 325 | self.lstMagnetic.setModel(self._magnet_model) |
---|
| 326 | self.setMagneticModel() |
---|
| 327 | self.setTableProperties(self.lstMagnetic) |
---|
[b00414d] | 328 | # Delegates for custom editing and display |
---|
| 329 | self.lstMagnetic.setItemDelegate(MagnetismViewDelegate(self)) |
---|
[60af928] | 330 | |
---|
[2a432e7] | 331 | def initializeCategoryCombo(self): |
---|
| 332 | """ |
---|
| 333 | Model category combo setup |
---|
| 334 | """ |
---|
[60af928] | 335 | category_list = sorted(self.master_category_dict.keys()) |
---|
[86f88d1] | 336 | self.cbCategory.addItem(CATEGORY_DEFAULT) |
---|
[60af928] | 337 | self.cbCategory.addItems(category_list) |
---|
[4d457df] | 338 | self.cbCategory.addItem(CATEGORY_STRUCTURE) |
---|
[6f7f652] | 339 | self.cbCategory.setCurrentIndex(0) |
---|
[60af928] | 340 | |
---|
[e1e3e09] | 341 | def setEnablementOnDataLoad(self): |
---|
| 342 | """ |
---|
| 343 | Enable/disable various UI elements based on data loaded |
---|
| 344 | """ |
---|
[cbcdd2c] | 345 | # Tag along functionality |
---|
[b1e36a3] | 346 | self.label.setText("Data loaded from: ") |
---|
[a0f5c36] | 347 | self.lblFilename.setText(self.logic.data.filename) |
---|
[5236449] | 348 | self.updateQRange() |
---|
[e1e3e09] | 349 | # Switch off Data2D control |
---|
| 350 | self.chk2DView.setEnabled(False) |
---|
| 351 | self.chk2DView.setVisible(False) |
---|
[6ff2eb3] | 352 | self.chkMagnetism.setEnabled(self.is2D) |
---|
[4fdb727] | 353 | self.tabFitting.setTabEnabled(TAB_MAGNETISM, self.is2D) |
---|
[ee18d33] | 354 | # Combo box or label for file name" |
---|
| 355 | if self.is_batch_fitting: |
---|
| 356 | self.lblFilename.setVisible(False) |
---|
| 357 | for dataitem in self.all_data: |
---|
| 358 | filename = GuiUtils.dataFromItem(dataitem).filename |
---|
| 359 | self.cbFileNames.addItem(filename) |
---|
| 360 | self.cbFileNames.setVisible(True) |
---|
[7fd20fc] | 361 | self.chkChainFit.setEnabled(True) |
---|
| 362 | self.chkChainFit.setVisible(True) |
---|
[38eb433] | 363 | # This panel is not designed to view individual fits, so disable plotting |
---|
| 364 | self.cmdPlot.setVisible(False) |
---|
[180bd54] | 365 | # Similarly on other tabs |
---|
| 366 | self.options_widget.setEnablementOnDataLoad() |
---|
[f7d14a1] | 367 | self.onSelectModel() |
---|
[e1e3e09] | 368 | # Smearing tab |
---|
| 369 | self.smearing_widget.updateSmearing(self.data) |
---|
[60af928] | 370 | |
---|
[f46f6dc] | 371 | def acceptsData(self): |
---|
| 372 | """ Tells the caller this widget can accept new dataset """ |
---|
[5236449] | 373 | return not self.data_is_loaded |
---|
[f46f6dc] | 374 | |
---|
[6f7f652] | 375 | def disableModelCombo(self): |
---|
[cbcdd2c] | 376 | """ Disable the combobox """ |
---|
[6f7f652] | 377 | self.cbModel.setEnabled(False) |
---|
[b1e36a3] | 378 | self.lblModel.setEnabled(False) |
---|
[6f7f652] | 379 | |
---|
| 380 | def enableModelCombo(self): |
---|
[cbcdd2c] | 381 | """ Enable the combobox """ |
---|
[6f7f652] | 382 | self.cbModel.setEnabled(True) |
---|
[b1e36a3] | 383 | self.lblModel.setEnabled(True) |
---|
[6f7f652] | 384 | |
---|
| 385 | def disableStructureCombo(self): |
---|
[cbcdd2c] | 386 | """ Disable the combobox """ |
---|
[6f7f652] | 387 | self.cbStructureFactor.setEnabled(False) |
---|
[b1e36a3] | 388 | self.lblStructure.setEnabled(False) |
---|
[6f7f652] | 389 | |
---|
| 390 | def enableStructureCombo(self): |
---|
[cbcdd2c] | 391 | """ Enable the combobox """ |
---|
[6f7f652] | 392 | self.cbStructureFactor.setEnabled(True) |
---|
[b1e36a3] | 393 | self.lblStructure.setEnabled(True) |
---|
[6f7f652] | 394 | |
---|
[0268aed] | 395 | def togglePoly(self, isChecked): |
---|
[454670d] | 396 | """ Enable/disable the polydispersity tab """ |
---|
[0268aed] | 397 | self.tabFitting.setTabEnabled(TAB_POLY, isChecked) |
---|
| 398 | |
---|
| 399 | def toggleMagnetism(self, isChecked): |
---|
[454670d] | 400 | """ Enable/disable the magnetism tab """ |
---|
[0268aed] | 401 | self.tabFitting.setTabEnabled(TAB_MAGNETISM, isChecked) |
---|
| 402 | |
---|
[7fd20fc] | 403 | def toggleChainFit(self, isChecked): |
---|
| 404 | """ Enable/disable chain fitting """ |
---|
| 405 | self.is_chain_fitting = isChecked |
---|
| 406 | |
---|
[0268aed] | 407 | def toggle2D(self, isChecked): |
---|
[454670d] | 408 | """ Enable/disable the controls dependent on 1D/2D data instance """ |
---|
[0268aed] | 409 | self.chkMagnetism.setEnabled(isChecked) |
---|
| 410 | self.is2D = isChecked |
---|
[1970780] | 411 | # Reload the current model |
---|
[e1e3e09] | 412 | if self.kernel_module: |
---|
| 413 | self.onSelectModel() |
---|
[5236449] | 414 | |
---|
[86f88d1] | 415 | def initializeControls(self): |
---|
| 416 | """ |
---|
| 417 | Set initial control enablement |
---|
| 418 | """ |
---|
[ee18d33] | 419 | self.cbFileNames.setVisible(False) |
---|
[86f88d1] | 420 | self.cmdFit.setEnabled(False) |
---|
[d48cc19] | 421 | self.cmdPlot.setEnabled(False) |
---|
[180bd54] | 422 | self.options_widget.cmdComputePoints.setVisible(False) # probably redundant |
---|
[86f88d1] | 423 | self.chkPolydispersity.setEnabled(True) |
---|
| 424 | self.chkPolydispersity.setCheckState(False) |
---|
| 425 | self.chk2DView.setEnabled(True) |
---|
| 426 | self.chk2DView.setCheckState(False) |
---|
| 427 | self.chkMagnetism.setEnabled(False) |
---|
| 428 | self.chkMagnetism.setCheckState(False) |
---|
[7fd20fc] | 429 | self.chkChainFit.setEnabled(False) |
---|
| 430 | self.chkChainFit.setVisible(False) |
---|
[cbcdd2c] | 431 | # Tabs |
---|
[86f88d1] | 432 | self.tabFitting.setTabEnabled(TAB_POLY, False) |
---|
| 433 | self.tabFitting.setTabEnabled(TAB_MAGNETISM, False) |
---|
| 434 | self.lblChi2Value.setText("---") |
---|
[e1e3e09] | 435 | # Smearing tab |
---|
| 436 | self.smearing_widget.updateSmearing(self.data) |
---|
[180bd54] | 437 | # Line edits in the option tab |
---|
| 438 | self.updateQRange() |
---|
[86f88d1] | 439 | |
---|
| 440 | def initializeSignals(self): |
---|
| 441 | """ |
---|
| 442 | Connect GUI element signals |
---|
| 443 | """ |
---|
[cbcdd2c] | 444 | # Comboboxes |
---|
[cd31251] | 445 | self.cbStructureFactor.currentIndexChanged.connect(self.onSelectStructureFactor) |
---|
| 446 | self.cbCategory.currentIndexChanged.connect(self.onSelectCategory) |
---|
| 447 | self.cbModel.currentIndexChanged.connect(self.onSelectModel) |
---|
[ee18d33] | 448 | self.cbFileNames.currentIndexChanged.connect(self.onSelectBatchFilename) |
---|
[cbcdd2c] | 449 | # Checkboxes |
---|
[86f88d1] | 450 | self.chk2DView.toggled.connect(self.toggle2D) |
---|
| 451 | self.chkPolydispersity.toggled.connect(self.togglePoly) |
---|
| 452 | self.chkMagnetism.toggled.connect(self.toggleMagnetism) |
---|
[7fd20fc] | 453 | self.chkChainFit.toggled.connect(self.toggleChainFit) |
---|
[cbcdd2c] | 454 | # Buttons |
---|
[5236449] | 455 | self.cmdFit.clicked.connect(self.onFit) |
---|
[cbcdd2c] | 456 | self.cmdPlot.clicked.connect(self.onPlot) |
---|
[2add354] | 457 | self.cmdHelp.clicked.connect(self.onHelp) |
---|
[6ff2eb3] | 458 | self.cmdMagneticDisplay.clicked.connect(self.onDisplayMagneticAngles) |
---|
[cbcdd2c] | 459 | |
---|
| 460 | # Respond to change in parameters from the UI |
---|
[b00414d] | 461 | self._model_model.itemChanged.connect(self.onMainParamsChange) |
---|
[eae226b] | 462 | #self.constraintAddedSignal.connect(self.modifyViewOnConstraint) |
---|
[cd31251] | 463 | self._poly_model.itemChanged.connect(self.onPolyModelChange) |
---|
[b00414d] | 464 | self._magnet_model.itemChanged.connect(self.onMagnetModelChange) |
---|
[86f88d1] | 465 | |
---|
[180bd54] | 466 | # Signals from separate tabs asking for replot |
---|
| 467 | self.options_widget.plot_signal.connect(self.onOptionsUpdate) |
---|
| 468 | |
---|
[d3c0b95] | 469 | def modelName(self): |
---|
| 470 | """ |
---|
| 471 | Returns model name, by default M<tab#>, e.g. M1, M2 |
---|
| 472 | """ |
---|
| 473 | return "M%i" % self.tab_id |
---|
| 474 | |
---|
| 475 | def nameForFittedData(self, name): |
---|
| 476 | """ |
---|
| 477 | Generate name for the current fit |
---|
| 478 | """ |
---|
| 479 | if self.is2D: |
---|
| 480 | name += "2d" |
---|
| 481 | name = "%s [%s]" % (self.modelName(), name) |
---|
| 482 | return name |
---|
[7fd20fc] | 483 | |
---|
[d3c0b95] | 484 | def showModelContextMenu(self, position): |
---|
| 485 | """ |
---|
| 486 | Show context specific menu in the parameter table. |
---|
| 487 | When clicked on parameter(s): fitting/constraints options |
---|
| 488 | When clicked on white space: model description |
---|
| 489 | """ |
---|
[eae226b] | 490 | rows = [s.row() for s in self.lstParams.selectionModel().selectedRows()] |
---|
[7fd20fc] | 491 | menu = self.showModelDescription() if not rows else self.modelContextMenu(rows) |
---|
| 492 | try: |
---|
| 493 | menu.exec_(self.lstParams.viewport().mapToGlobal(position)) |
---|
| 494 | except AttributeError as ex: |
---|
| 495 | logging.error("Error generating context menu: %s" % ex) |
---|
| 496 | return |
---|
| 497 | |
---|
| 498 | def modelContextMenu(self, rows): |
---|
[eae226b] | 499 | """ |
---|
[d3c0b95] | 500 | Create context menu for the parameter selection |
---|
[eae226b] | 501 | """ |
---|
[7fd20fc] | 502 | menu = QtWidgets.QMenu() |
---|
[eae226b] | 503 | num_rows = len(rows) |
---|
[63319b0] | 504 | if num_rows < 1: |
---|
| 505 | return menu |
---|
[7fd20fc] | 506 | # Select for fitting |
---|
[eae226b] | 507 | param_string = "parameter " if num_rows==1 else "parameters " |
---|
| 508 | to_string = "to its current value" if num_rows==1 else "to their current values" |
---|
[d3c0b95] | 509 | has_constraints = any([self.rowHasConstraint(i) for i in rows]) |
---|
[eae226b] | 510 | |
---|
[7fd20fc] | 511 | self.actionSelect = QtWidgets.QAction(self) |
---|
| 512 | self.actionSelect.setObjectName("actionSelect") |
---|
[eae226b] | 513 | self.actionSelect.setText(QtCore.QCoreApplication.translate("self", "Select "+param_string+" for fitting")) |
---|
[7fd20fc] | 514 | # Unselect from fitting |
---|
| 515 | self.actionDeselect = QtWidgets.QAction(self) |
---|
| 516 | self.actionDeselect.setObjectName("actionDeselect") |
---|
[eae226b] | 517 | self.actionDeselect.setText(QtCore.QCoreApplication.translate("self", "De-select "+param_string+" from fitting")) |
---|
[7fd20fc] | 518 | |
---|
| 519 | self.actionConstrain = QtWidgets.QAction(self) |
---|
| 520 | self.actionConstrain.setObjectName("actionConstrain") |
---|
[eae226b] | 521 | self.actionConstrain.setText(QtCore.QCoreApplication.translate("self", "Constrain "+param_string + to_string)) |
---|
| 522 | |
---|
| 523 | self.actionRemoveConstraint = QtWidgets.QAction(self) |
---|
| 524 | self.actionRemoveConstraint.setObjectName("actionRemoveConstrain") |
---|
| 525 | self.actionRemoveConstraint.setText(QtCore.QCoreApplication.translate("self", "Remove constraint")) |
---|
[7fd20fc] | 526 | |
---|
| 527 | self.actionMultiConstrain = QtWidgets.QAction(self) |
---|
| 528 | self.actionMultiConstrain.setObjectName("actionMultiConstrain") |
---|
| 529 | self.actionMultiConstrain.setText(QtCore.QCoreApplication.translate("self", "Constrain selected parameters to their current values")) |
---|
| 530 | |
---|
| 531 | self.actionMutualMultiConstrain = QtWidgets.QAction(self) |
---|
| 532 | self.actionMutualMultiConstrain.setObjectName("actionMutualMultiConstrain") |
---|
| 533 | self.actionMutualMultiConstrain.setText(QtCore.QCoreApplication.translate("self", "Mutual constrain of selected parameters...")) |
---|
| 534 | |
---|
| 535 | menu.addAction(self.actionSelect) |
---|
| 536 | menu.addAction(self.actionDeselect) |
---|
| 537 | menu.addSeparator() |
---|
| 538 | |
---|
[d3c0b95] | 539 | if has_constraints: |
---|
[eae226b] | 540 | menu.addAction(self.actionRemoveConstraint) |
---|
[d3c0b95] | 541 | #if num_rows == 1: |
---|
| 542 | # menu.addAction(self.actionEditConstraint) |
---|
[eae226b] | 543 | else: |
---|
[7fd20fc] | 544 | menu.addAction(self.actionConstrain) |
---|
[d3c0b95] | 545 | if num_rows == 2: |
---|
| 546 | menu.addAction(self.actionMutualMultiConstrain) |
---|
[7fd20fc] | 547 | |
---|
| 548 | # Define the callbacks |
---|
[0595bb7] | 549 | self.actionConstrain.triggered.connect(self.addSimpleConstraint) |
---|
[eae226b] | 550 | self.actionRemoveConstraint.triggered.connect(self.deleteConstraint) |
---|
[0595bb7] | 551 | self.actionMutualMultiConstrain.triggered.connect(self.showMultiConstraint) |
---|
[7fd20fc] | 552 | self.actionSelect.triggered.connect(self.selectParameters) |
---|
| 553 | self.actionDeselect.triggered.connect(self.deselectParameters) |
---|
| 554 | return menu |
---|
| 555 | |
---|
[0595bb7] | 556 | def showMultiConstraint(self): |
---|
[7fd20fc] | 557 | """ |
---|
| 558 | Show the constraint widget and receive the expression |
---|
| 559 | """ |
---|
[0595bb7] | 560 | selected_rows = self.lstParams.selectionModel().selectedRows() |
---|
[676f137] | 561 | assert(len(selected_rows)==2) |
---|
[0595bb7] | 562 | |
---|
| 563 | params_list = [s.data() for s in selected_rows] |
---|
[eae226b] | 564 | # Create and display the widget for param1 and param2 |
---|
[7fd20fc] | 565 | mc_widget = MultiConstraint(self, params=params_list) |
---|
[eae226b] | 566 | if mc_widget.exec_() != QtWidgets.QDialog.Accepted: |
---|
| 567 | return |
---|
| 568 | |
---|
[0595bb7] | 569 | constraint = Constraint() |
---|
| 570 | c_text = mc_widget.txtConstraint.text() |
---|
| 571 | |
---|
[eae226b] | 572 | # widget.params[0] is the parameter we're constraining |
---|
| 573 | constraint.param = mc_widget.params[0] |
---|
[47d7d2d] | 574 | # Function should have the model name preamble |
---|
[eae226b] | 575 | constraint.func = c_text |
---|
[7fd20fc] | 576 | |
---|
[eae226b] | 577 | # Create a new item and add the Constraint object as a child |
---|
| 578 | item = QtGui.QStandardItem() |
---|
| 579 | item.setData(constraint) |
---|
| 580 | |
---|
[d3c0b95] | 581 | # Which row is the constrained parameter in? |
---|
[2d466e4] | 582 | row = self.getRowFromName(constraint.param) |
---|
[eae226b] | 583 | self._model_model.item(row, 1).setChild(0, item) |
---|
[be8f4b0] | 584 | self.constraintAddedSignal.emit([row]) |
---|
[d3c0b95] | 585 | |
---|
[eae226b] | 586 | # Show visual hints for the constraint |
---|
[0595bb7] | 587 | font = QtGui.QFont() |
---|
| 588 | font.setItalic(True) |
---|
| 589 | brush = QtGui.QBrush(QtGui.QColor('blue')) |
---|
[eae226b] | 590 | self.modifyViewOnRow(row, font=font, brush=brush) |
---|
| 591 | |
---|
[d3c0b95] | 592 | # Notify the user |
---|
[eae226b] | 593 | self.communicate.statusBarUpdateSignal.emit('Constraints added') |
---|
| 594 | |
---|
[2d466e4] | 595 | def getRowFromName(self, name): |
---|
[eae226b] | 596 | """ |
---|
[d3c0b95] | 597 | Given parameter name get the row number in self._model_model |
---|
[eae226b] | 598 | """ |
---|
| 599 | for row in range(self._model_model.rowCount()): |
---|
| 600 | row_name = self._model_model.item(row).text() |
---|
| 601 | if row_name == name: |
---|
| 602 | return row |
---|
| 603 | return None |
---|
| 604 | |
---|
[2d466e4] | 605 | def getParamNames(self): |
---|
| 606 | """ |
---|
| 607 | Return list of all parameters for the current model |
---|
| 608 | """ |
---|
| 609 | return [self._model_model.item(row).text() for row in range(self._model_model.rowCount())] |
---|
| 610 | |
---|
[eae226b] | 611 | def modifyViewOnRow(self, row, font=None, brush=None): |
---|
| 612 | """ |
---|
| 613 | Chage how the given row of the main model is shown |
---|
| 614 | """ |
---|
| 615 | fields_enabled = False |
---|
| 616 | if font is None: |
---|
| 617 | font = QtGui.QFont() |
---|
| 618 | fields_enabled = True |
---|
| 619 | if brush is None: |
---|
| 620 | brush = QtGui.QBrush() |
---|
| 621 | fields_enabled = True |
---|
[0595bb7] | 622 | self._model_model.blockSignals(True) |
---|
| 623 | # Modify font and foreground of affected rows |
---|
| 624 | for column in range(0, self._model_model.columnCount()): |
---|
| 625 | self._model_model.item(row, column).setForeground(brush) |
---|
| 626 | self._model_model.item(row, column).setFont(font) |
---|
[eae226b] | 627 | self._model_model.item(row, column).setEditable(fields_enabled) |
---|
[0595bb7] | 628 | self._model_model.blockSignals(False) |
---|
| 629 | |
---|
[c5a2722f] | 630 | def addConstraintToRow(self, constraint=None, row=0): |
---|
| 631 | """ |
---|
| 632 | Adds the constraint object to requested row |
---|
| 633 | """ |
---|
| 634 | # Create a new item and add the Constraint object as a child |
---|
| 635 | assert(isinstance(constraint, Constraint)) |
---|
| 636 | assert(0<=row<=self._model_model.rowCount()) |
---|
| 637 | |
---|
| 638 | item = QtGui.QStandardItem() |
---|
| 639 | item.setData(constraint) |
---|
| 640 | self._model_model.item(row, 1).setChild(0, item) |
---|
| 641 | # Set min/max to the value constrained |
---|
| 642 | self.constraintAddedSignal.emit([row]) |
---|
| 643 | # Show visual hints for the constraint |
---|
| 644 | font = QtGui.QFont() |
---|
| 645 | font.setItalic(True) |
---|
| 646 | brush = QtGui.QBrush(QtGui.QColor('blue')) |
---|
| 647 | self.modifyViewOnRow(row, font=font, brush=brush) |
---|
| 648 | self.communicate.statusBarUpdateSignal.emit('Constraint added') |
---|
| 649 | |
---|
[0595bb7] | 650 | def addSimpleConstraint(self): |
---|
[7fd20fc] | 651 | """ |
---|
| 652 | Adds a constraint on a single parameter. |
---|
[2add354] | 653 | """ |
---|
[d3c0b95] | 654 | min_col = self.lstParams.itemDelegate().param_min |
---|
| 655 | max_col = self.lstParams.itemDelegate().param_max |
---|
[0595bb7] | 656 | for row in self.selectedParameters(): |
---|
| 657 | param = self._model_model.item(row, 0).text() |
---|
| 658 | value = self._model_model.item(row, 1).text() |
---|
[d3c0b95] | 659 | min = self._model_model.item(row, min_col).text() |
---|
| 660 | max = self._model_model.item(row, max_col).text() |
---|
[eae226b] | 661 | # Create a Constraint object |
---|
[be8f4b0] | 662 | constraint = Constraint(param=param, value=value, min=min, max=max, func=value) |
---|
[eae226b] | 663 | # Create a new item and add the Constraint object as a child |
---|
[0595bb7] | 664 | item = QtGui.QStandardItem() |
---|
| 665 | item.setData(constraint) |
---|
| 666 | self._model_model.item(row, 1).setChild(0, item) |
---|
[eae226b] | 667 | # Set min/max to the value constrained |
---|
[d3c0b95] | 668 | self._model_model.item(row, min_col).setText(value) |
---|
| 669 | self._model_model.item(row, max_col).setText(value) |
---|
[be8f4b0] | 670 | self.constraintAddedSignal.emit([row]) |
---|
[eae226b] | 671 | # Show visual hints for the constraint |
---|
| 672 | font = QtGui.QFont() |
---|
| 673 | font.setItalic(True) |
---|
| 674 | brush = QtGui.QBrush(QtGui.QColor('blue')) |
---|
| 675 | self.modifyViewOnRow(row, font=font, brush=brush) |
---|
[7fd20fc] | 676 | self.communicate.statusBarUpdateSignal.emit('Constraint added') |
---|
| 677 | pass |
---|
| 678 | |
---|
[eae226b] | 679 | def deleteConstraint(self): |
---|
| 680 | """ |
---|
| 681 | Delete constraints from selected parameters. |
---|
| 682 | """ |
---|
[be8f4b0] | 683 | self.deleteConstraintOnParameter(param=None) |
---|
| 684 | |
---|
| 685 | def deleteConstraintOnParameter(self, param=None): |
---|
| 686 | """ |
---|
| 687 | Delete the constraint on model parameter 'param' |
---|
| 688 | """ |
---|
[d3c0b95] | 689 | min_col = self.lstParams.itemDelegate().param_min |
---|
| 690 | max_col = self.lstParams.itemDelegate().param_max |
---|
[be8f4b0] | 691 | for row in range(self._model_model.rowCount()): |
---|
[eae226b] | 692 | # Get the Constraint object from of the model item |
---|
| 693 | item = self._model_model.item(row, 1) |
---|
[d3c0b95] | 694 | if not item.hasChildren(): |
---|
| 695 | continue |
---|
[eae226b] | 696 | constraint = item.child(0).data() |
---|
[d3c0b95] | 697 | if constraint is None: |
---|
| 698 | continue |
---|
| 699 | if not isinstance(constraint, Constraint): |
---|
| 700 | continue |
---|
[be8f4b0] | 701 | if param and constraint.param != param: |
---|
| 702 | continue |
---|
| 703 | # Now we got the right row. Delete the constraint and clean up |
---|
[eae226b] | 704 | # Retrieve old values and put them on the model |
---|
| 705 | if constraint.min is not None: |
---|
[d3c0b95] | 706 | self._model_model.item(row, min_col).setText(constraint.min) |
---|
[eae226b] | 707 | if constraint.max is not None: |
---|
[d3c0b95] | 708 | self._model_model.item(row, max_col).setText(constraint.max) |
---|
[eae226b] | 709 | # Remove constraint item |
---|
| 710 | item.removeRow(0) |
---|
[be8f4b0] | 711 | self.constraintAddedSignal.emit([row]) |
---|
[eae226b] | 712 | self.modifyViewOnRow(row) |
---|
[be8f4b0] | 713 | break |
---|
| 714 | |
---|
[eae226b] | 715 | self.communicate.statusBarUpdateSignal.emit('Constraint removed') |
---|
| 716 | pass |
---|
| 717 | |
---|
[be8f4b0] | 718 | |
---|
[d3c0b95] | 719 | def getConstraintForRow(self, row): |
---|
| 720 | """ |
---|
| 721 | For the given row, return its constraint, if any |
---|
| 722 | """ |
---|
| 723 | try: |
---|
| 724 | item = self._model_model.item(row, 1) |
---|
| 725 | return item.child(0).data() |
---|
| 726 | except AttributeError: |
---|
| 727 | # return none when no constraints |
---|
| 728 | return None |
---|
| 729 | |
---|
[eae226b] | 730 | def rowHasConstraint(self, row): |
---|
| 731 | """ |
---|
| 732 | Finds out if row of the main model has a constraint child |
---|
| 733 | """ |
---|
| 734 | item = self._model_model.item(row,1) |
---|
[be8f4b0] | 735 | if item.hasChildren(): |
---|
| 736 | c = item.child(0).data() |
---|
| 737 | if isinstance(c, Constraint) and c.func: |
---|
| 738 | return True |
---|
| 739 | return False |
---|
[116dd4c1] | 740 | |
---|
| 741 | def rowHasActiveConstraint(self, row): |
---|
| 742 | """ |
---|
| 743 | Finds out if row of the main model has an active constraint child |
---|
| 744 | """ |
---|
| 745 | item = self._model_model.item(row,1) |
---|
| 746 | if item.hasChildren(): |
---|
| 747 | c = item.child(0).data() |
---|
| 748 | if isinstance(c, Constraint) and c.func and c.active: |
---|
| 749 | return True |
---|
| 750 | return False |
---|
[eae226b] | 751 | |
---|
[7fd20fc] | 752 | def selectParameters(self): |
---|
| 753 | """ |
---|
[d3c0b95] | 754 | Selected parameter is chosen for fitting |
---|
[7fd20fc] | 755 | """ |
---|
| 756 | status = QtCore.Qt.Checked |
---|
| 757 | self.setParameterSelection(status) |
---|
| 758 | |
---|
| 759 | def deselectParameters(self): |
---|
| 760 | """ |
---|
| 761 | Selected parameters are removed for fitting |
---|
| 762 | """ |
---|
| 763 | status = QtCore.Qt.Unchecked |
---|
| 764 | self.setParameterSelection(status) |
---|
| 765 | |
---|
| 766 | def selectedParameters(self): |
---|
| 767 | """ Returns list of selected (highlighted) parameters """ |
---|
[d3c0b95] | 768 | return [s.row() for s in self.lstParams.selectionModel().selectedRows() |
---|
| 769 | if self.isCheckable(s.row())] |
---|
[7fd20fc] | 770 | |
---|
| 771 | def setParameterSelection(self, status=QtCore.Qt.Unchecked): |
---|
| 772 | """ |
---|
| 773 | Selected parameters are chosen for fitting |
---|
| 774 | """ |
---|
| 775 | # Convert to proper indices and set requested enablement |
---|
| 776 | for row in self.selectedParameters(): |
---|
| 777 | self._model_model.item(row, 0).setCheckState(status) |
---|
[d3c0b95] | 778 | pass # debugger hook |
---|
| 779 | |
---|
| 780 | def getConstraintsForModel(self): |
---|
| 781 | """ |
---|
| 782 | Return a list of tuples. Each tuple contains constraints mapped as |
---|
| 783 | ('constrained parameter', 'function to constrain') |
---|
| 784 | e.g. [('sld','5*sld_solvent')] |
---|
| 785 | """ |
---|
[47d7d2d] | 786 | model_name = self.kernel_module.name |
---|
[d3c0b95] | 787 | param_number = self._model_model.rowCount() |
---|
[be8f4b0] | 788 | def preamble(s): |
---|
| 789 | func = self._model_model.item(s, 1).child(0).data().func |
---|
| 790 | value = self._model_model.item(s, 1).child(0).data().value |
---|
| 791 | if func == value: |
---|
| 792 | return "" |
---|
[c5a2722f] | 793 | |
---|
[be8f4b0] | 794 | return model_name + "." |
---|
[d3c0b95] | 795 | params = [(self._model_model.item(s, 0).text(), |
---|
[c5a2722f] | 796 | #preamble(s) +self._model_model.item(s, 1).child(0).data().func) |
---|
| 797 | self._model_model.item(s, 1).child(0).data().func) |
---|
[116dd4c1] | 798 | for s in range(param_number) if self.rowHasActiveConstraint(s)] |
---|
[d3c0b95] | 799 | return params |
---|
[7fd20fc] | 800 | |
---|
[ba01ad1] | 801 | def getConstraintObjectsForModel(self): |
---|
| 802 | """ |
---|
| 803 | Returns Constraint objects present on the whole model |
---|
| 804 | """ |
---|
| 805 | param_number = self._model_model.rowCount() |
---|
| 806 | constraints = [self._model_model.item(s, 1).child(0).data() |
---|
| 807 | for s in range(param_number) if self.rowHasConstraint(s)] |
---|
| 808 | |
---|
| 809 | return constraints |
---|
| 810 | |
---|
[7fd20fc] | 811 | def showModelDescription(self): |
---|
| 812 | """ |
---|
| 813 | Creates a window with model description, when right clicked in the treeview |
---|
[2add354] | 814 | """ |
---|
| 815 | msg = 'Model description:\n' |
---|
| 816 | if self.kernel_module is not None: |
---|
| 817 | if str(self.kernel_module.description).rstrip().lstrip() == '': |
---|
| 818 | msg += "Sorry, no information is available for this model." |
---|
| 819 | else: |
---|
| 820 | msg += self.kernel_module.description + '\n' |
---|
| 821 | else: |
---|
| 822 | msg += "You must select a model to get information on this" |
---|
| 823 | |
---|
[4992ff2] | 824 | menu = QtWidgets.QMenu() |
---|
| 825 | label = QtWidgets.QLabel(msg) |
---|
[d6b8a1d] | 826 | action = QtWidgets.QWidgetAction(self) |
---|
[672b8ab] | 827 | action.setDefaultWidget(label) |
---|
| 828 | menu.addAction(action) |
---|
[7fd20fc] | 829 | return menu |
---|
[2add354] | 830 | |
---|
[0268aed] | 831 | def onSelectModel(self): |
---|
[cbcdd2c] | 832 | """ |
---|
[0268aed] | 833 | Respond to select Model from list event |
---|
[cbcdd2c] | 834 | """ |
---|
[d6b8a1d] | 835 | model = self.cbModel.currentText() |
---|
[0268aed] | 836 | |
---|
[b3e8629] | 837 | # empty combobox forced to be read |
---|
| 838 | if not model: |
---|
| 839 | return |
---|
[0268aed] | 840 | # Reset structure factor |
---|
| 841 | self.cbStructureFactor.setCurrentIndex(0) |
---|
| 842 | |
---|
[f182f93] | 843 | # Reset parameters to fit |
---|
| 844 | self.parameters_to_fit = None |
---|
[d7ff531] | 845 | self.has_error_column = False |
---|
[aca8418] | 846 | self.has_poly_error_column = False |
---|
[f182f93] | 847 | |
---|
[fd1ae6d1] | 848 | self.respondToModelStructure(model=model, structure_factor=None) |
---|
| 849 | |
---|
[ee18d33] | 850 | def onSelectBatchFilename(self, data_index): |
---|
| 851 | """ |
---|
| 852 | Update the logic based on the selected file in batch fitting |
---|
| 853 | """ |
---|
| 854 | self._index = self.all_data[data_index] |
---|
| 855 | self.logic.data = GuiUtils.dataFromItem(self.all_data[data_index]) |
---|
| 856 | self.updateQRange() |
---|
| 857 | |
---|
[fd1ae6d1] | 858 | def onSelectStructureFactor(self): |
---|
| 859 | """ |
---|
| 860 | Select Structure Factor from list |
---|
| 861 | """ |
---|
| 862 | model = str(self.cbModel.currentText()) |
---|
| 863 | category = str(self.cbCategory.currentText()) |
---|
| 864 | structure = str(self.cbStructureFactor.currentText()) |
---|
| 865 | if category == CATEGORY_STRUCTURE: |
---|
| 866 | model = None |
---|
| 867 | self.respondToModelStructure(model=model, structure_factor=structure) |
---|
| 868 | |
---|
[47d7d2d] | 869 | def replaceConstraintName(self, old_name, new_name=""): |
---|
| 870 | """ |
---|
| 871 | Replace names of models in defined constraints |
---|
| 872 | """ |
---|
| 873 | param_number = self._model_model.rowCount() |
---|
| 874 | # loop over parameters |
---|
| 875 | for row in range(param_number): |
---|
| 876 | if self.rowHasConstraint(row): |
---|
| 877 | func = self._model_model.item(row, 1).child(0).data().func |
---|
| 878 | if old_name in func: |
---|
| 879 | new_func = func.replace(old_name, new_name) |
---|
| 880 | self._model_model.item(row, 1).child(0).data().func = new_func |
---|
| 881 | |
---|
| 882 | pass |
---|
| 883 | |
---|
[9c0ce68] | 884 | def updateData(self): |
---|
| 885 | """ |
---|
| 886 | Helper function for recalculation of data used in plotting |
---|
| 887 | """ |
---|
| 888 | # Update the chart |
---|
[0268aed] | 889 | if self.data_is_loaded: |
---|
[d48cc19] | 890 | self.cmdPlot.setText("Show Plot") |
---|
[0268aed] | 891 | self.calculateQGridForModel() |
---|
| 892 | else: |
---|
[d48cc19] | 893 | self.cmdPlot.setText("Calculate") |
---|
[0268aed] | 894 | # Create default datasets if no data passed |
---|
| 895 | self.createDefaultDataset() |
---|
| 896 | |
---|
[9c0ce68] | 897 | def respondToModelStructure(self, model=None, structure_factor=None): |
---|
| 898 | # Set enablement on calculate/plot |
---|
| 899 | self.cmdPlot.setEnabled(True) |
---|
| 900 | |
---|
| 901 | # kernel parameters -> model_model |
---|
| 902 | self.SASModelToQModel(model, structure_factor) |
---|
| 903 | |
---|
| 904 | # Update plot |
---|
| 905 | self.updateData() |
---|
| 906 | |
---|
[6011788] | 907 | # Update state stack |
---|
[00b3b40] | 908 | self.updateUndo() |
---|
[2add354] | 909 | |
---|
[be8f4b0] | 910 | # Let others know |
---|
| 911 | self.newModelSignal.emit() |
---|
| 912 | |
---|
[cd31251] | 913 | def onSelectCategory(self): |
---|
[60af928] | 914 | """ |
---|
| 915 | Select Category from list |
---|
| 916 | """ |
---|
[d6b8a1d] | 917 | category = self.cbCategory.currentText() |
---|
[86f88d1] | 918 | # Check if the user chose "Choose category entry" |
---|
[4d457df] | 919 | if category == CATEGORY_DEFAULT: |
---|
[86f88d1] | 920 | # if the previous category was not the default, keep it. |
---|
| 921 | # Otherwise, just return |
---|
| 922 | if self._previous_category_index != 0: |
---|
[351b53e] | 923 | # We need to block signals, or else state changes on perceived unchanged conditions |
---|
| 924 | self.cbCategory.blockSignals(True) |
---|
[86f88d1] | 925 | self.cbCategory.setCurrentIndex(self._previous_category_index) |
---|
[351b53e] | 926 | self.cbCategory.blockSignals(False) |
---|
[86f88d1] | 927 | return |
---|
| 928 | |
---|
[4d457df] | 929 | if category == CATEGORY_STRUCTURE: |
---|
[6f7f652] | 930 | self.disableModelCombo() |
---|
| 931 | self.enableStructureCombo() |
---|
[29eb947] | 932 | self._model_model.clear() |
---|
[6f7f652] | 933 | return |
---|
| 934 | |
---|
[cbcdd2c] | 935 | # Safely clear and enable the model combo |
---|
[6f7f652] | 936 | self.cbModel.blockSignals(True) |
---|
| 937 | self.cbModel.clear() |
---|
| 938 | self.cbModel.blockSignals(False) |
---|
| 939 | self.enableModelCombo() |
---|
| 940 | self.disableStructureCombo() |
---|
| 941 | |
---|
[86f88d1] | 942 | self._previous_category_index = self.cbCategory.currentIndex() |
---|
[cbcdd2c] | 943 | # Retrieve the list of models |
---|
[4d457df] | 944 | model_list = self.master_category_dict[category] |
---|
[cbcdd2c] | 945 | # Populate the models combobox |
---|
[b1e36a3] | 946 | self.cbModel.addItems(sorted([model for (model, _) in model_list])) |
---|
[4d457df] | 947 | |
---|
[0268aed] | 948 | def onPolyModelChange(self, item): |
---|
| 949 | """ |
---|
| 950 | Callback method for updating the main model and sasmodel |
---|
| 951 | parameters with the GUI values in the polydispersity view |
---|
| 952 | """ |
---|
| 953 | model_column = item.column() |
---|
| 954 | model_row = item.row() |
---|
| 955 | name_index = self._poly_model.index(model_row, 0) |
---|
[7fb471d] | 956 | parameter_name = str(name_index.data()).lower() # "distribution of sld" etc. |
---|
[c1e380e] | 957 | if "distribution of" in parameter_name: |
---|
[358b39d] | 958 | # just the last word |
---|
| 959 | parameter_name = parameter_name.rsplit()[-1] |
---|
[c1e380e] | 960 | |
---|
[06b0138] | 961 | # Extract changed value. |
---|
[8eaa101] | 962 | if model_column == self.lstPoly.itemDelegate().poly_parameter: |
---|
[00b3b40] | 963 | # Is the parameter checked for fitting? |
---|
[0268aed] | 964 | value = item.checkState() |
---|
[1643d8ed] | 965 | parameter_name = parameter_name + '.width' |
---|
[c1e380e] | 966 | if value == QtCore.Qt.Checked: |
---|
| 967 | self.parameters_to_fit.append(parameter_name) |
---|
| 968 | else: |
---|
| 969 | if parameter_name in self.parameters_to_fit: |
---|
| 970 | self.parameters_to_fit.remove(parameter_name) |
---|
[b00414d] | 971 | self.cmdFit.setEnabled(self.parameters_to_fit != [] and self.logic.data_is_loaded) |
---|
[c1e380e] | 972 | return |
---|
[8eaa101] | 973 | elif model_column in [self.lstPoly.itemDelegate().poly_min, self.lstPoly.itemDelegate().poly_max]: |
---|
[aca8418] | 974 | try: |
---|
[fbfc488] | 975 | value = GuiUtils.toDouble(item.text()) |
---|
[0261bc1] | 976 | except TypeError: |
---|
[aca8418] | 977 | # Can't be converted properly, bring back the old value and exit |
---|
| 978 | return |
---|
| 979 | |
---|
| 980 | current_details = self.kernel_module.details[parameter_name] |
---|
| 981 | current_details[model_column-1] = value |
---|
[8eaa101] | 982 | elif model_column == self.lstPoly.itemDelegate().poly_function: |
---|
[919d47c] | 983 | # name of the function - just pass |
---|
| 984 | return |
---|
[0268aed] | 985 | else: |
---|
| 986 | try: |
---|
[fbfc488] | 987 | value = GuiUtils.toDouble(item.text()) |
---|
[0261bc1] | 988 | except TypeError: |
---|
[0268aed] | 989 | # Can't be converted properly, bring back the old value and exit |
---|
| 990 | return |
---|
| 991 | |
---|
[aca8418] | 992 | # Update the sasmodel |
---|
| 993 | # PD[ratio] -> width, npts -> npts, nsigs -> nsigmas |
---|
[919d47c] | 994 | self.kernel_module.setParam(parameter_name + '.' + \ |
---|
[8eaa101] | 995 | self.lstPoly.itemDelegate().columnDict()[model_column], value) |
---|
[0268aed] | 996 | |
---|
[9c0ce68] | 997 | # Update plot |
---|
| 998 | self.updateData() |
---|
| 999 | |
---|
[b00414d] | 1000 | def onMagnetModelChange(self, item): |
---|
| 1001 | """ |
---|
| 1002 | Callback method for updating the sasmodel magnetic parameters with the GUI values |
---|
| 1003 | """ |
---|
| 1004 | model_column = item.column() |
---|
| 1005 | model_row = item.row() |
---|
| 1006 | name_index = self._magnet_model.index(model_row, 0) |
---|
[fbfc488] | 1007 | parameter_name = str(self._magnet_model.data(name_index)) |
---|
[b00414d] | 1008 | |
---|
| 1009 | if model_column == 0: |
---|
| 1010 | value = item.checkState() |
---|
| 1011 | if value == QtCore.Qt.Checked: |
---|
| 1012 | self.parameters_to_fit.append(parameter_name) |
---|
| 1013 | else: |
---|
| 1014 | if parameter_name in self.parameters_to_fit: |
---|
| 1015 | self.parameters_to_fit.remove(parameter_name) |
---|
| 1016 | self.cmdFit.setEnabled(self.parameters_to_fit != [] and self.logic.data_is_loaded) |
---|
| 1017 | # Update state stack |
---|
| 1018 | self.updateUndo() |
---|
| 1019 | return |
---|
| 1020 | |
---|
| 1021 | # Extract changed value. |
---|
| 1022 | try: |
---|
[fbfc488] | 1023 | value = GuiUtils.toDouble(item.text()) |
---|
[0261bc1] | 1024 | except TypeError: |
---|
[b00414d] | 1025 | # Unparsable field |
---|
| 1026 | return |
---|
| 1027 | |
---|
[fbfc488] | 1028 | property_index = self._magnet_model.headerData(1, model_column)-1 # Value, min, max, etc. |
---|
[b00414d] | 1029 | |
---|
| 1030 | # Update the parameter value - note: this supports +/-inf as well |
---|
| 1031 | self.kernel_module.params[parameter_name] = value |
---|
| 1032 | |
---|
| 1033 | # min/max to be changed in self.kernel_module.details[parameter_name] = ['Ang', 0.0, inf] |
---|
| 1034 | self.kernel_module.details[parameter_name][property_index] = value |
---|
| 1035 | |
---|
| 1036 | # Force the chart update when actual parameters changed |
---|
| 1037 | if model_column == 1: |
---|
| 1038 | self.recalculatePlotData() |
---|
| 1039 | |
---|
| 1040 | # Update state stack |
---|
| 1041 | self.updateUndo() |
---|
| 1042 | |
---|
[2add354] | 1043 | def onHelp(self): |
---|
| 1044 | """ |
---|
| 1045 | Show the "Fitting" section of help |
---|
| 1046 | """ |
---|
[e90988c] | 1047 | tree_location = "/user/sasgui/perspectives/fitting/" |
---|
[70080a0] | 1048 | |
---|
| 1049 | # Actual file will depend on the current tab |
---|
| 1050 | tab_id = self.tabFitting.currentIndex() |
---|
| 1051 | helpfile = "fitting.html" |
---|
| 1052 | if tab_id == 0: |
---|
| 1053 | helpfile = "fitting_help.html" |
---|
| 1054 | elif tab_id == 1: |
---|
| 1055 | helpfile = "residuals_help.html" |
---|
| 1056 | elif tab_id == 2: |
---|
[e90988c] | 1057 | helpfile = "resolution.html" |
---|
[70080a0] | 1058 | elif tab_id == 3: |
---|
[e90988c] | 1059 | helpfile = "pd/polydispersity.html" |
---|
[70080a0] | 1060 | elif tab_id == 4: |
---|
[e90988c] | 1061 | helpfile = "magnetism/magnetism.html" |
---|
[70080a0] | 1062 | help_location = tree_location + helpfile |
---|
[d6b8a1d] | 1063 | |
---|
[e90988c] | 1064 | self.showHelp(help_location) |
---|
| 1065 | |
---|
| 1066 | def showHelp(self, url): |
---|
| 1067 | """ |
---|
| 1068 | Calls parent's method for opening an HTML page |
---|
| 1069 | """ |
---|
| 1070 | self.parent.showHelp(url) |
---|
[2add354] | 1071 | |
---|
[6ff2eb3] | 1072 | def onDisplayMagneticAngles(self): |
---|
| 1073 | """ |
---|
| 1074 | Display a simple image showing direction of magnetic angles |
---|
| 1075 | """ |
---|
| 1076 | self.magneticAnglesWidget.show() |
---|
| 1077 | |
---|
[0268aed] | 1078 | def onFit(self): |
---|
| 1079 | """ |
---|
| 1080 | Perform fitting on the current data |
---|
| 1081 | """ |
---|
[116dd4c1] | 1082 | # initialize fitter constants |
---|
[f182f93] | 1083 | fit_id = 0 |
---|
| 1084 | handler = None |
---|
| 1085 | batch_inputs = {} |
---|
| 1086 | batch_outputs = {} |
---|
| 1087 | #--------------------------------- |
---|
[14ec91c5] | 1088 | if LocalConfig.USING_TWISTED: |
---|
[7adc2a8] | 1089 | handler = None |
---|
| 1090 | updater = None |
---|
| 1091 | else: |
---|
| 1092 | handler = ConsoleUpdate(parent=self.parent, |
---|
| 1093 | manager=self, |
---|
| 1094 | improvement_delta=0.1) |
---|
| 1095 | updater = handler.update_fit |
---|
[f182f93] | 1096 | |
---|
[116dd4c1] | 1097 | # Prepare the fitter object |
---|
[c6343a5] | 1098 | try: |
---|
| 1099 | fitters, _ = self.prepareFitters() |
---|
| 1100 | except ValueError as ex: |
---|
| 1101 | # This should not happen! GUI explicitly forbids this situation |
---|
| 1102 | self.communicate.statusBarUpdateSignal.emit('Fitting attempt without parameters.') |
---|
| 1103 | return |
---|
[f182f93] | 1104 | |
---|
| 1105 | # Create the fitting thread, based on the fitter |
---|
[ee18d33] | 1106 | completefn = self.batchFitComplete if self.is_batch_fitting else self.fitComplete |
---|
| 1107 | |
---|
[f182f93] | 1108 | calc_fit = FitThread(handler=handler, |
---|
[116dd4c1] | 1109 | fn=fitters, |
---|
| 1110 | batch_inputs=batch_inputs, |
---|
| 1111 | batch_outputs=batch_outputs, |
---|
| 1112 | page_id=[[self.page_id]], |
---|
| 1113 | updatefn=updater, |
---|
| 1114 | completefn=completefn) |
---|
[7adc2a8] | 1115 | |
---|
[14ec91c5] | 1116 | if LocalConfig.USING_TWISTED: |
---|
[7adc2a8] | 1117 | # start the trhrhread with twisted |
---|
| 1118 | calc_thread = threads.deferToThread(calc_fit.compute) |
---|
[14ec91c5] | 1119 | calc_thread.addCallback(completefn) |
---|
[7adc2a8] | 1120 | calc_thread.addErrback(self.fitFailed) |
---|
| 1121 | else: |
---|
| 1122 | # Use the old python threads + Queue |
---|
| 1123 | calc_fit.queue() |
---|
| 1124 | calc_fit.ready(2.5) |
---|
[f182f93] | 1125 | |
---|
[d7ff531] | 1126 | self.communicate.statusBarUpdateSignal.emit('Fitting started...') |
---|
[14ec91c5] | 1127 | # Disable some elements |
---|
| 1128 | self.setFittingStarted() |
---|
[0268aed] | 1129 | |
---|
[f182f93] | 1130 | def updateFit(self): |
---|
| 1131 | """ |
---|
| 1132 | """ |
---|
[b3e8629] | 1133 | print("UPDATE FIT") |
---|
[0268aed] | 1134 | pass |
---|
| 1135 | |
---|
[02ddfb4] | 1136 | def fitFailed(self, reason): |
---|
| 1137 | """ |
---|
| 1138 | """ |
---|
[b3e8629] | 1139 | print("FIT FAILED: ", reason) |
---|
[02ddfb4] | 1140 | pass |
---|
| 1141 | |
---|
[ee18d33] | 1142 | def batchFitComplete(self, result): |
---|
| 1143 | """ |
---|
| 1144 | Receive and display batch fitting results |
---|
| 1145 | """ |
---|
| 1146 | #re-enable the Fit button |
---|
[14ec91c5] | 1147 | self.setFittingStopped() |
---|
[ee18d33] | 1148 | |
---|
| 1149 | print ("BATCH FITTING FINISHED") |
---|
| 1150 | # Add the Qt version of wx.aui.AuiNotebook and populate it |
---|
| 1151 | pass |
---|
| 1152 | |
---|
[f182f93] | 1153 | def fitComplete(self, result): |
---|
| 1154 | """ |
---|
| 1155 | Receive and display fitting results |
---|
| 1156 | "result" is a tuple of actual result list and the fit time in seconds |
---|
| 1157 | """ |
---|
| 1158 | #re-enable the Fit button |
---|
[14ec91c5] | 1159 | self.setFittingStopped() |
---|
[d7ff531] | 1160 | |
---|
| 1161 | assert result is not None |
---|
| 1162 | |
---|
[ee18d33] | 1163 | res_list = result[0][0] |
---|
[f182f93] | 1164 | res = res_list[0] |
---|
| 1165 | if res.fitness is None or \ |
---|
[180bd54] | 1166 | not np.isfinite(res.fitness) or \ |
---|
[1bc27f1] | 1167 | np.any(res.pvec is None) or \ |
---|
[180bd54] | 1168 | not np.all(np.isfinite(res.pvec)): |
---|
[eae226b] | 1169 | msg = "Fitting did not converge!" |
---|
[454670d] | 1170 | self.communicate.statusBarUpdateSignal.emit(msg) |
---|
[f182f93] | 1171 | logging.error(msg) |
---|
| 1172 | return |
---|
| 1173 | |
---|
| 1174 | elapsed = result[1] |
---|
| 1175 | msg = "Fitting completed successfully in: %s s.\n" % GuiUtils.formatNumber(elapsed) |
---|
| 1176 | self.communicate.statusBarUpdateSignal.emit(msg) |
---|
| 1177 | |
---|
[2add354] | 1178 | self.chi2 = res.fitness |
---|
[aca8418] | 1179 | param_list = res.param_list # ['radius', 'radius.width'] |
---|
| 1180 | param_values = res.pvec # array([ 0.36221662, 0.0146783 ]) |
---|
| 1181 | param_stderr = res.stderr # array([ 1.71293015, 1.71294233]) |
---|
[b3e8629] | 1182 | params_and_errors = list(zip(param_values, param_stderr)) |
---|
| 1183 | param_dict = dict(zip(param_list, params_and_errors)) |
---|
[f182f93] | 1184 | |
---|
| 1185 | # Dictionary of fitted parameter: value, error |
---|
| 1186 | # e.g. param_dic = {"sld":(1.703, 0.0034), "length":(33.455, -0.0983)} |
---|
| 1187 | self.updateModelFromList(param_dict) |
---|
| 1188 | |
---|
[aca8418] | 1189 | self.updatePolyModelFromList(param_dict) |
---|
| 1190 | |
---|
[b00414d] | 1191 | self.updateMagnetModelFromList(param_dict) |
---|
| 1192 | |
---|
[d7ff531] | 1193 | # update charts |
---|
| 1194 | self.onPlot() |
---|
| 1195 | |
---|
[f182f93] | 1196 | # Read only value - we can get away by just printing it here |
---|
[2add354] | 1197 | chi2_repr = GuiUtils.formatNumber(self.chi2, high=True) |
---|
[f182f93] | 1198 | self.lblChi2Value.setText(chi2_repr) |
---|
| 1199 | |
---|
[116dd4c1] | 1200 | def prepareFitters(self, fitter=None, fit_id=0): |
---|
| 1201 | """ |
---|
| 1202 | Prepare the Fitter object for use in fitting |
---|
| 1203 | """ |
---|
| 1204 | # fitter = None -> single/batch fitting |
---|
| 1205 | # fitter = Fit() -> simultaneous fitting |
---|
| 1206 | |
---|
| 1207 | # Data going in |
---|
| 1208 | data = self.logic.data |
---|
| 1209 | model = self.kernel_module |
---|
| 1210 | qmin = self.q_range_min |
---|
| 1211 | qmax = self.q_range_max |
---|
| 1212 | params_to_fit = self.parameters_to_fit |
---|
[c6343a5] | 1213 | if (not params_to_fit): |
---|
| 1214 | raise ValueError('Fitting requires at least one parameter to optimize.') |
---|
[116dd4c1] | 1215 | |
---|
| 1216 | # Potential weights added directly to data |
---|
| 1217 | self.addWeightingToData(data) |
---|
| 1218 | |
---|
| 1219 | # Potential smearing added |
---|
| 1220 | # Remember that smearing_min/max can be None -> |
---|
| 1221 | # deal with it until Python gets discriminated unions |
---|
| 1222 | smearing, accuracy, smearing_min, smearing_max = self.smearing_widget.state() |
---|
| 1223 | |
---|
| 1224 | constraints = self.getConstraintsForModel() |
---|
| 1225 | smearer = None |
---|
| 1226 | handler = None |
---|
| 1227 | batch_inputs = {} |
---|
| 1228 | batch_outputs = {} |
---|
| 1229 | |
---|
| 1230 | fitters = [] |
---|
| 1231 | for fit_index in self.all_data: |
---|
| 1232 | fitter_single = Fit() if fitter is None else fitter |
---|
| 1233 | data = GuiUtils.dataFromItem(fit_index) |
---|
| 1234 | try: |
---|
| 1235 | fitter_single.set_model(model, fit_id, params_to_fit, data=data, |
---|
| 1236 | constraints=constraints) |
---|
| 1237 | except ValueError as ex: |
---|
| 1238 | logging.error("Setting model parameters failed with: %s" % ex) |
---|
| 1239 | return |
---|
| 1240 | |
---|
| 1241 | qmin, qmax, _ = self.logic.computeRangeFromData(data) |
---|
| 1242 | fitter_single.set_data(data=data, id=fit_id, smearer=smearer, qmin=qmin, |
---|
| 1243 | qmax=qmax) |
---|
| 1244 | fitter_single.select_problem_for_fit(id=fit_id, value=1) |
---|
| 1245 | if fitter is None: |
---|
| 1246 | # Assign id to the new fitter only |
---|
| 1247 | fitter_single.fitter_id = [self.page_id] |
---|
| 1248 | fit_id += 1 |
---|
| 1249 | fitters.append(fitter_single) |
---|
| 1250 | |
---|
| 1251 | return fitters, fit_id |
---|
| 1252 | |
---|
[f182f93] | 1253 | def iterateOverModel(self, func): |
---|
| 1254 | """ |
---|
| 1255 | Take func and throw it inside the model row loop |
---|
| 1256 | """ |
---|
[b3e8629] | 1257 | for row_i in range(self._model_model.rowCount()): |
---|
[f182f93] | 1258 | func(row_i) |
---|
| 1259 | |
---|
| 1260 | def updateModelFromList(self, param_dict): |
---|
| 1261 | """ |
---|
| 1262 | Update the model with new parameters, create the errors column |
---|
| 1263 | """ |
---|
| 1264 | assert isinstance(param_dict, dict) |
---|
| 1265 | if not dict: |
---|
| 1266 | return |
---|
| 1267 | |
---|
[919d47c] | 1268 | def updateFittedValues(row): |
---|
[f182f93] | 1269 | # Utility function for main model update |
---|
[d7ff531] | 1270 | # internal so can use closure for param_dict |
---|
[919d47c] | 1271 | param_name = str(self._model_model.item(row, 0).text()) |
---|
[b3e8629] | 1272 | if param_name not in list(param_dict.keys()): |
---|
[f182f93] | 1273 | return |
---|
| 1274 | # modify the param value |
---|
[454670d] | 1275 | param_repr = GuiUtils.formatNumber(param_dict[param_name][0], high=True) |
---|
[919d47c] | 1276 | self._model_model.item(row, 1).setText(param_repr) |
---|
[f182f93] | 1277 | if self.has_error_column: |
---|
[454670d] | 1278 | error_repr = GuiUtils.formatNumber(param_dict[param_name][1], high=True) |
---|
[919d47c] | 1279 | self._model_model.item(row, 2).setText(error_repr) |
---|
[f182f93] | 1280 | |
---|
[919d47c] | 1281 | def updatePolyValues(row): |
---|
| 1282 | # Utility function for updateof polydispersity part of the main model |
---|
| 1283 | param_name = str(self._model_model.item(row, 0).text())+'.width' |
---|
[b3e8629] | 1284 | if param_name not in list(param_dict.keys()): |
---|
[919d47c] | 1285 | return |
---|
| 1286 | # modify the param value |
---|
| 1287 | param_repr = GuiUtils.formatNumber(param_dict[param_name][0], high=True) |
---|
| 1288 | self._model_model.item(row, 0).child(0).child(0,1).setText(param_repr) |
---|
| 1289 | |
---|
| 1290 | def createErrorColumn(row): |
---|
[f182f93] | 1291 | # Utility function for error column update |
---|
| 1292 | item = QtGui.QStandardItem() |
---|
[919d47c] | 1293 | def createItem(param_name): |
---|
[f182f93] | 1294 | error_repr = GuiUtils.formatNumber(param_dict[param_name][1], high=True) |
---|
| 1295 | item.setText(error_repr) |
---|
[919d47c] | 1296 | def curr_param(): |
---|
| 1297 | return str(self._model_model.item(row, 0).text()) |
---|
| 1298 | |
---|
[b3e8629] | 1299 | [createItem(param_name) for param_name in list(param_dict.keys()) if curr_param() == param_name] |
---|
[919d47c] | 1300 | |
---|
[f182f93] | 1301 | error_column.append(item) |
---|
| 1302 | |
---|
[2da5759] | 1303 | # block signals temporarily, so we don't end up |
---|
| 1304 | # updating charts with every single model change on the end of fitting |
---|
| 1305 | self._model_model.blockSignals(True) |
---|
[d7ff531] | 1306 | self.iterateOverModel(updateFittedValues) |
---|
[919d47c] | 1307 | self.iterateOverModel(updatePolyValues) |
---|
[2da5759] | 1308 | self._model_model.blockSignals(False) |
---|
[f182f93] | 1309 | |
---|
| 1310 | if self.has_error_column: |
---|
| 1311 | return |
---|
| 1312 | |
---|
| 1313 | error_column = [] |
---|
[8f2548c] | 1314 | self.lstParams.itemDelegate().addErrorColumn() |
---|
[d7ff531] | 1315 | self.iterateOverModel(createErrorColumn) |
---|
[f182f93] | 1316 | |
---|
[d7ff531] | 1317 | # switch off reponse to model change |
---|
| 1318 | self._model_model.blockSignals(True) |
---|
[f182f93] | 1319 | self._model_model.insertColumn(2, error_column) |
---|
[d7ff531] | 1320 | self._model_model.blockSignals(False) |
---|
[f182f93] | 1321 | FittingUtilities.addErrorHeadersToModel(self._model_model) |
---|
[d7ff531] | 1322 | # Adjust the table cells width. |
---|
| 1323 | # TODO: find a way to dynamically adjust column width while resized expanding |
---|
| 1324 | self.lstParams.resizeColumnToContents(0) |
---|
| 1325 | self.lstParams.resizeColumnToContents(4) |
---|
| 1326 | self.lstParams.resizeColumnToContents(5) |
---|
[4992ff2] | 1327 | self.lstParams.setSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) |
---|
[d7ff531] | 1328 | |
---|
| 1329 | self.has_error_column = True |
---|
[f182f93] | 1330 | |
---|
[aca8418] | 1331 | def updatePolyModelFromList(self, param_dict): |
---|
| 1332 | """ |
---|
| 1333 | Update the polydispersity model with new parameters, create the errors column |
---|
| 1334 | """ |
---|
| 1335 | assert isinstance(param_dict, dict) |
---|
| 1336 | if not dict: |
---|
| 1337 | return |
---|
| 1338 | |
---|
[b00414d] | 1339 | def iterateOverPolyModel(func): |
---|
| 1340 | """ |
---|
| 1341 | Take func and throw it inside the poly model row loop |
---|
| 1342 | """ |
---|
[b3e8629] | 1343 | for row_i in range(self._poly_model.rowCount()): |
---|
[b00414d] | 1344 | func(row_i) |
---|
| 1345 | |
---|
[aca8418] | 1346 | def updateFittedValues(row_i): |
---|
| 1347 | # Utility function for main model update |
---|
| 1348 | # internal so can use closure for param_dict |
---|
| 1349 | if row_i >= self._poly_model.rowCount(): |
---|
| 1350 | return |
---|
| 1351 | param_name = str(self._poly_model.item(row_i, 0).text()).rsplit()[-1] + '.width' |
---|
[b3e8629] | 1352 | if param_name not in list(param_dict.keys()): |
---|
[aca8418] | 1353 | return |
---|
| 1354 | # modify the param value |
---|
| 1355 | param_repr = GuiUtils.formatNumber(param_dict[param_name][0], high=True) |
---|
| 1356 | self._poly_model.item(row_i, 1).setText(param_repr) |
---|
| 1357 | if self.has_poly_error_column: |
---|
| 1358 | error_repr = GuiUtils.formatNumber(param_dict[param_name][1], high=True) |
---|
| 1359 | self._poly_model.item(row_i, 2).setText(error_repr) |
---|
| 1360 | |
---|
[919d47c] | 1361 | |
---|
[aca8418] | 1362 | def createErrorColumn(row_i): |
---|
| 1363 | # Utility function for error column update |
---|
| 1364 | if row_i >= self._poly_model.rowCount(): |
---|
| 1365 | return |
---|
| 1366 | item = QtGui.QStandardItem() |
---|
[919d47c] | 1367 | |
---|
| 1368 | def createItem(param_name): |
---|
[aca8418] | 1369 | error_repr = GuiUtils.formatNumber(param_dict[param_name][1], high=True) |
---|
| 1370 | item.setText(error_repr) |
---|
[919d47c] | 1371 | |
---|
| 1372 | def poly_param(): |
---|
| 1373 | return str(self._poly_model.item(row_i, 0).text()).rsplit()[-1] + '.width' |
---|
| 1374 | |
---|
[b3e8629] | 1375 | [createItem(param_name) for param_name in list(param_dict.keys()) if poly_param() == param_name] |
---|
[919d47c] | 1376 | |
---|
[aca8418] | 1377 | error_column.append(item) |
---|
| 1378 | |
---|
| 1379 | # block signals temporarily, so we don't end up |
---|
| 1380 | # updating charts with every single model change on the end of fitting |
---|
| 1381 | self._poly_model.blockSignals(True) |
---|
[b00414d] | 1382 | iterateOverPolyModel(updateFittedValues) |
---|
[aca8418] | 1383 | self._poly_model.blockSignals(False) |
---|
| 1384 | |
---|
| 1385 | if self.has_poly_error_column: |
---|
| 1386 | return |
---|
| 1387 | |
---|
[8eaa101] | 1388 | self.lstPoly.itemDelegate().addErrorColumn() |
---|
[aca8418] | 1389 | error_column = [] |
---|
[b00414d] | 1390 | iterateOverPolyModel(createErrorColumn) |
---|
[aca8418] | 1391 | |
---|
| 1392 | # switch off reponse to model change |
---|
| 1393 | self._poly_model.blockSignals(True) |
---|
| 1394 | self._poly_model.insertColumn(2, error_column) |
---|
| 1395 | self._poly_model.blockSignals(False) |
---|
| 1396 | FittingUtilities.addErrorPolyHeadersToModel(self._poly_model) |
---|
| 1397 | |
---|
| 1398 | self.has_poly_error_column = True |
---|
| 1399 | |
---|
[b00414d] | 1400 | def updateMagnetModelFromList(self, param_dict): |
---|
| 1401 | """ |
---|
| 1402 | Update the magnetic model with new parameters, create the errors column |
---|
| 1403 | """ |
---|
| 1404 | assert isinstance(param_dict, dict) |
---|
| 1405 | if not dict: |
---|
| 1406 | return |
---|
[cee5c78] | 1407 | if self._model_model.rowCount() == 0: |
---|
| 1408 | return |
---|
[b00414d] | 1409 | |
---|
| 1410 | def iterateOverMagnetModel(func): |
---|
| 1411 | """ |
---|
| 1412 | Take func and throw it inside the magnet model row loop |
---|
| 1413 | """ |
---|
[b3e8629] | 1414 | for row_i in range(self._model_model.rowCount()): |
---|
[b00414d] | 1415 | func(row_i) |
---|
| 1416 | |
---|
| 1417 | def updateFittedValues(row): |
---|
| 1418 | # Utility function for main model update |
---|
| 1419 | # internal so can use closure for param_dict |
---|
[cee5c78] | 1420 | if self._magnet_model.item(row, 0) is None: |
---|
| 1421 | return |
---|
[b00414d] | 1422 | param_name = str(self._magnet_model.item(row, 0).text()) |
---|
[b3e8629] | 1423 | if param_name not in list(param_dict.keys()): |
---|
[b00414d] | 1424 | return |
---|
| 1425 | # modify the param value |
---|
| 1426 | param_repr = GuiUtils.formatNumber(param_dict[param_name][0], high=True) |
---|
| 1427 | self._magnet_model.item(row, 1).setText(param_repr) |
---|
| 1428 | if self.has_magnet_error_column: |
---|
| 1429 | error_repr = GuiUtils.formatNumber(param_dict[param_name][1], high=True) |
---|
| 1430 | self._magnet_model.item(row, 2).setText(error_repr) |
---|
| 1431 | |
---|
| 1432 | def createErrorColumn(row): |
---|
| 1433 | # Utility function for error column update |
---|
| 1434 | item = QtGui.QStandardItem() |
---|
| 1435 | def createItem(param_name): |
---|
| 1436 | error_repr = GuiUtils.formatNumber(param_dict[param_name][1], high=True) |
---|
| 1437 | item.setText(error_repr) |
---|
| 1438 | def curr_param(): |
---|
| 1439 | return str(self._magnet_model.item(row, 0).text()) |
---|
| 1440 | |
---|
[b3e8629] | 1441 | [createItem(param_name) for param_name in list(param_dict.keys()) if curr_param() == param_name] |
---|
[b00414d] | 1442 | |
---|
| 1443 | error_column.append(item) |
---|
| 1444 | |
---|
| 1445 | # block signals temporarily, so we don't end up |
---|
| 1446 | # updating charts with every single model change on the end of fitting |
---|
| 1447 | self._magnet_model.blockSignals(True) |
---|
| 1448 | iterateOverMagnetModel(updateFittedValues) |
---|
| 1449 | self._magnet_model.blockSignals(False) |
---|
| 1450 | |
---|
| 1451 | if self.has_magnet_error_column: |
---|
| 1452 | return |
---|
| 1453 | |
---|
| 1454 | self.lstMagnetic.itemDelegate().addErrorColumn() |
---|
| 1455 | error_column = [] |
---|
| 1456 | iterateOverMagnetModel(createErrorColumn) |
---|
| 1457 | |
---|
| 1458 | # switch off reponse to model change |
---|
| 1459 | self._magnet_model.blockSignals(True) |
---|
| 1460 | self._magnet_model.insertColumn(2, error_column) |
---|
| 1461 | self._magnet_model.blockSignals(False) |
---|
| 1462 | FittingUtilities.addErrorHeadersToModel(self._magnet_model) |
---|
| 1463 | |
---|
| 1464 | self.has_magnet_error_column = True |
---|
| 1465 | |
---|
[0268aed] | 1466 | def onPlot(self): |
---|
| 1467 | """ |
---|
| 1468 | Plot the current set of data |
---|
| 1469 | """ |
---|
[d48cc19] | 1470 | # Regardless of previous state, this should now be `plot show` functionality only |
---|
| 1471 | self.cmdPlot.setText("Show Plot") |
---|
[88e1f57] | 1472 | # Force data recalculation so existing charts are updated |
---|
| 1473 | self.recalculatePlotData() |
---|
[d48cc19] | 1474 | self.showPlot() |
---|
| 1475 | |
---|
| 1476 | def recalculatePlotData(self): |
---|
| 1477 | """ |
---|
| 1478 | Generate a new dataset for model |
---|
| 1479 | """ |
---|
[180bd54] | 1480 | if not self.data_is_loaded: |
---|
[0268aed] | 1481 | self.createDefaultDataset() |
---|
| 1482 | self.calculateQGridForModel() |
---|
| 1483 | |
---|
[d48cc19] | 1484 | def showPlot(self): |
---|
| 1485 | """ |
---|
| 1486 | Show the current plot in MPL |
---|
| 1487 | """ |
---|
| 1488 | # Show the chart if ready |
---|
| 1489 | data_to_show = self.data if self.data_is_loaded else self.model_data |
---|
| 1490 | if data_to_show is not None: |
---|
| 1491 | self.communicate.plotRequestedSignal.emit([data_to_show]) |
---|
| 1492 | |
---|
[180bd54] | 1493 | def onOptionsUpdate(self): |
---|
[0268aed] | 1494 | """ |
---|
[180bd54] | 1495 | Update local option values and replot |
---|
[0268aed] | 1496 | """ |
---|
[180bd54] | 1497 | self.q_range_min, self.q_range_max, self.npts, self.log_points, self.weighting = \ |
---|
| 1498 | self.options_widget.state() |
---|
[61a92d4] | 1499 | # set Q range labels on the main tab |
---|
| 1500 | self.lblMinRangeDef.setText(str(self.q_range_min)) |
---|
| 1501 | self.lblMaxRangeDef.setText(str(self.q_range_max)) |
---|
[d48cc19] | 1502 | self.recalculatePlotData() |
---|
[6c8fb2c] | 1503 | |
---|
[0268aed] | 1504 | def setDefaultStructureCombo(self): |
---|
| 1505 | """ |
---|
| 1506 | Fill in the structure factors combo box with defaults |
---|
| 1507 | """ |
---|
| 1508 | structure_factor_list = self.master_category_dict.pop(CATEGORY_STRUCTURE) |
---|
| 1509 | factors = [factor[0] for factor in structure_factor_list] |
---|
| 1510 | factors.insert(0, STRUCTURE_DEFAULT) |
---|
| 1511 | self.cbStructureFactor.clear() |
---|
| 1512 | self.cbStructureFactor.addItems(sorted(factors)) |
---|
| 1513 | |
---|
[4d457df] | 1514 | def createDefaultDataset(self): |
---|
| 1515 | """ |
---|
| 1516 | Generate default Dataset 1D/2D for the given model |
---|
| 1517 | """ |
---|
| 1518 | # Create default datasets if no data passed |
---|
| 1519 | if self.is2D: |
---|
[180bd54] | 1520 | qmax = self.q_range_max/np.sqrt(2) |
---|
[4d457df] | 1521 | qstep = self.npts |
---|
| 1522 | self.logic.createDefault2dData(qmax, qstep, self.tab_id) |
---|
[180bd54] | 1523 | return |
---|
| 1524 | elif self.log_points: |
---|
| 1525 | qmin = -10.0 if self.q_range_min < 1.e-10 else np.log10(self.q_range_min) |
---|
[1bc27f1] | 1526 | qmax = 10.0 if self.q_range_max > 1.e10 else np.log10(self.q_range_max) |
---|
[180bd54] | 1527 | interval = np.logspace(start=qmin, stop=qmax, num=self.npts, endpoint=True, base=10.0) |
---|
[4d457df] | 1528 | else: |
---|
[180bd54] | 1529 | interval = np.linspace(start=self.q_range_min, stop=self.q_range_max, |
---|
[1bc27f1] | 1530 | num=self.npts, endpoint=True) |
---|
[180bd54] | 1531 | self.logic.createDefault1dData(interval, self.tab_id) |
---|
[60af928] | 1532 | |
---|
[5236449] | 1533 | def readCategoryInfo(self): |
---|
[60af928] | 1534 | """ |
---|
| 1535 | Reads the categories in from file |
---|
| 1536 | """ |
---|
| 1537 | self.master_category_dict = defaultdict(list) |
---|
| 1538 | self.by_model_dict = defaultdict(list) |
---|
| 1539 | self.model_enabled_dict = defaultdict(bool) |
---|
| 1540 | |
---|
[cbcdd2c] | 1541 | categorization_file = CategoryInstaller.get_user_file() |
---|
| 1542 | if not os.path.isfile(categorization_file): |
---|
| 1543 | categorization_file = CategoryInstaller.get_default_file() |
---|
| 1544 | with open(categorization_file, 'rb') as cat_file: |
---|
[60af928] | 1545 | self.master_category_dict = json.load(cat_file) |
---|
[5236449] | 1546 | self.regenerateModelDict() |
---|
[60af928] | 1547 | |
---|
[5236449] | 1548 | # Load the model dict |
---|
| 1549 | models = load_standard_models() |
---|
| 1550 | for model in models: |
---|
| 1551 | self.models[model.name] = model |
---|
| 1552 | |
---|
| 1553 | def regenerateModelDict(self): |
---|
[60af928] | 1554 | """ |
---|
[cbcdd2c] | 1555 | Regenerates self.by_model_dict which has each model name as the |
---|
[60af928] | 1556 | key and the list of categories belonging to that model |
---|
| 1557 | along with the enabled mapping |
---|
| 1558 | """ |
---|
| 1559 | self.by_model_dict = defaultdict(list) |
---|
| 1560 | for category in self.master_category_dict: |
---|
| 1561 | for (model, enabled) in self.master_category_dict[category]: |
---|
| 1562 | self.by_model_dict[model].append(category) |
---|
| 1563 | self.model_enabled_dict[model] = enabled |
---|
| 1564 | |
---|
[86f88d1] | 1565 | def addBackgroundToModel(self, model): |
---|
| 1566 | """ |
---|
| 1567 | Adds background parameter with default values to the model |
---|
| 1568 | """ |
---|
[cbcdd2c] | 1569 | assert isinstance(model, QtGui.QStandardItemModel) |
---|
[86f88d1] | 1570 | checked_list = ['background', '0.001', '-inf', 'inf', '1/cm'] |
---|
[4d457df] | 1571 | FittingUtilities.addCheckedListToModel(model, checked_list) |
---|
[2add354] | 1572 | last_row = model.rowCount()-1 |
---|
| 1573 | model.item(last_row, 0).setEditable(False) |
---|
| 1574 | model.item(last_row, 4).setEditable(False) |
---|
[86f88d1] | 1575 | |
---|
| 1576 | def addScaleToModel(self, model): |
---|
| 1577 | """ |
---|
| 1578 | Adds scale parameter with default values to the model |
---|
| 1579 | """ |
---|
[cbcdd2c] | 1580 | assert isinstance(model, QtGui.QStandardItemModel) |
---|
[86f88d1] | 1581 | checked_list = ['scale', '1.0', '0.0', 'inf', ''] |
---|
[4d457df] | 1582 | FittingUtilities.addCheckedListToModel(model, checked_list) |
---|
[2add354] | 1583 | last_row = model.rowCount()-1 |
---|
| 1584 | model.item(last_row, 0).setEditable(False) |
---|
| 1585 | model.item(last_row, 4).setEditable(False) |
---|
[86f88d1] | 1586 | |
---|
[9d266d2] | 1587 | def addWeightingToData(self, data): |
---|
| 1588 | """ |
---|
| 1589 | Adds weighting contribution to fitting data |
---|
[1bc27f1] | 1590 | """ |
---|
[e1e3e09] | 1591 | # Send original data for weighting |
---|
[dc5ef15] | 1592 | weight = FittingUtilities.getWeight(data=data, is2d=self.is2D, flag=self.weighting) |
---|
[180bd54] | 1593 | update_module = data.err_data if self.is2D else data.dy |
---|
[6964d44] | 1594 | # Overwrite relevant values in data |
---|
[180bd54] | 1595 | update_module = weight |
---|
[9d266d2] | 1596 | |
---|
[0268aed] | 1597 | def updateQRange(self): |
---|
| 1598 | """ |
---|
| 1599 | Updates Q Range display |
---|
| 1600 | """ |
---|
| 1601 | if self.data_is_loaded: |
---|
| 1602 | self.q_range_min, self.q_range_max, self.npts = self.logic.computeDataRange() |
---|
| 1603 | # set Q range labels on the main tab |
---|
| 1604 | self.lblMinRangeDef.setText(str(self.q_range_min)) |
---|
| 1605 | self.lblMaxRangeDef.setText(str(self.q_range_max)) |
---|
| 1606 | # set Q range labels on the options tab |
---|
[180bd54] | 1607 | self.options_widget.updateQRange(self.q_range_min, self.q_range_max, self.npts) |
---|
[0268aed] | 1608 | |
---|
[4d457df] | 1609 | def SASModelToQModel(self, model_name, structure_factor=None): |
---|
[60af928] | 1610 | """ |
---|
[cbcdd2c] | 1611 | Setting model parameters into table based on selected category |
---|
[60af928] | 1612 | """ |
---|
| 1613 | # Crete/overwrite model items |
---|
| 1614 | self._model_model.clear() |
---|
[5236449] | 1615 | |
---|
[fd1ae6d1] | 1616 | # First, add parameters from the main model |
---|
| 1617 | if model_name is not None: |
---|
| 1618 | self.fromModelToQModel(model_name) |
---|
[5236449] | 1619 | |
---|
[fd1ae6d1] | 1620 | # Then, add structure factor derived parameters |
---|
[cd31251] | 1621 | if structure_factor is not None and structure_factor != "None": |
---|
[fd1ae6d1] | 1622 | if model_name is None: |
---|
| 1623 | # Instantiate the current sasmodel for SF-only models |
---|
| 1624 | self.kernel_module = self.models[structure_factor]() |
---|
| 1625 | self.fromStructureFactorToQModel(structure_factor) |
---|
[cd31251] | 1626 | else: |
---|
[fd1ae6d1] | 1627 | # Allow the SF combobox visibility for the given sasmodel |
---|
| 1628 | self.enableStructureFactorControl(structure_factor) |
---|
[cd31251] | 1629 | |
---|
[fd1ae6d1] | 1630 | # Then, add multishells |
---|
| 1631 | if model_name is not None: |
---|
| 1632 | # Multishell models need additional treatment |
---|
| 1633 | self.addExtraShells() |
---|
[86f88d1] | 1634 | |
---|
[5236449] | 1635 | # Add polydispersity to the model |
---|
[86f88d1] | 1636 | self.setPolyModel() |
---|
[5236449] | 1637 | # Add magnetic parameters to the model |
---|
[86f88d1] | 1638 | self.setMagneticModel() |
---|
[5236449] | 1639 | |
---|
[a9b568c] | 1640 | # Adjust the table cells width |
---|
| 1641 | self.lstParams.resizeColumnToContents(0) |
---|
[4992ff2] | 1642 | self.lstParams.setSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) |
---|
[a9b568c] | 1643 | |
---|
[5236449] | 1644 | # Now we claim the model has been loaded |
---|
[86f88d1] | 1645 | self.model_is_loaded = True |
---|
[be8f4b0] | 1646 | # Change the model name to a monicker |
---|
| 1647 | self.kernel_module.name = self.modelName() |
---|
[86f88d1] | 1648 | |
---|
[fd1ae6d1] | 1649 | # (Re)-create headers |
---|
| 1650 | FittingUtilities.addHeadersToModel(self._model_model) |
---|
[6964d44] | 1651 | self.lstParams.header().setFont(self.boldFont) |
---|
[fd1ae6d1] | 1652 | |
---|
[5236449] | 1653 | # Update Q Ranges |
---|
| 1654 | self.updateQRange() |
---|
| 1655 | |
---|
[fd1ae6d1] | 1656 | def fromModelToQModel(self, model_name): |
---|
| 1657 | """ |
---|
| 1658 | Setting model parameters into QStandardItemModel based on selected _model_ |
---|
| 1659 | """ |
---|
| 1660 | kernel_module = generate.load_kernel_module(model_name) |
---|
| 1661 | self.model_parameters = modelinfo.make_parameter_table(getattr(kernel_module, 'parameters', [])) |
---|
| 1662 | |
---|
| 1663 | # Instantiate the current sasmodel |
---|
| 1664 | self.kernel_module = self.models[model_name]() |
---|
| 1665 | |
---|
| 1666 | # Explicitly add scale and background with default values |
---|
[6964d44] | 1667 | temp_undo_state = self.undo_supported |
---|
| 1668 | self.undo_supported = False |
---|
[fd1ae6d1] | 1669 | self.addScaleToModel(self._model_model) |
---|
| 1670 | self.addBackgroundToModel(self._model_model) |
---|
[6964d44] | 1671 | self.undo_supported = temp_undo_state |
---|
[fd1ae6d1] | 1672 | |
---|
[0d13814] | 1673 | self.shell_names = self.shellNamesList() |
---|
| 1674 | |
---|
[fd1ae6d1] | 1675 | # Update the QModel |
---|
[aca8418] | 1676 | new_rows = FittingUtilities.addParametersToModel(self.model_parameters, self.kernel_module, self.is2D) |
---|
| 1677 | |
---|
[fd1ae6d1] | 1678 | for row in new_rows: |
---|
| 1679 | self._model_model.appendRow(row) |
---|
| 1680 | # Update the counter used for multishell display |
---|
| 1681 | self._last_model_row = self._model_model.rowCount() |
---|
| 1682 | |
---|
| 1683 | def fromStructureFactorToQModel(self, structure_factor): |
---|
| 1684 | """ |
---|
| 1685 | Setting model parameters into QStandardItemModel based on selected _structure factor_ |
---|
| 1686 | """ |
---|
| 1687 | structure_module = generate.load_kernel_module(structure_factor) |
---|
| 1688 | structure_parameters = modelinfo.make_parameter_table(getattr(structure_module, 'parameters', [])) |
---|
[5d1440e1] | 1689 | structure_kernel = self.models[structure_factor]() |
---|
| 1690 | |
---|
| 1691 | self.kernel_module._model_info = product.make_product_info(self.kernel_module._model_info, structure_kernel._model_info) |
---|
[fd1ae6d1] | 1692 | |
---|
| 1693 | new_rows = FittingUtilities.addSimpleParametersToModel(structure_parameters, self.is2D) |
---|
| 1694 | for row in new_rows: |
---|
| 1695 | self._model_model.appendRow(row) |
---|
| 1696 | # Update the counter used for multishell display |
---|
| 1697 | self._last_model_row = self._model_model.rowCount() |
---|
| 1698 | |
---|
[b00414d] | 1699 | def onMainParamsChange(self, item): |
---|
[cd31251] | 1700 | """ |
---|
| 1701 | Callback method for updating the sasmodel parameters with the GUI values |
---|
| 1702 | """ |
---|
[cbcdd2c] | 1703 | model_column = item.column() |
---|
[cd31251] | 1704 | |
---|
| 1705 | if model_column == 0: |
---|
[f182f93] | 1706 | self.checkboxSelected(item) |
---|
[2add354] | 1707 | self.cmdFit.setEnabled(self.parameters_to_fit != [] and self.logic.data_is_loaded) |
---|
[6964d44] | 1708 | # Update state stack |
---|
| 1709 | self.updateUndo() |
---|
[cd31251] | 1710 | return |
---|
| 1711 | |
---|
[f182f93] | 1712 | model_row = item.row() |
---|
| 1713 | name_index = self._model_model.index(model_row, 0) |
---|
| 1714 | |
---|
[b00414d] | 1715 | # Extract changed value. |
---|
[2add354] | 1716 | try: |
---|
[fbfc488] | 1717 | value = GuiUtils.toDouble(item.text()) |
---|
[0261bc1] | 1718 | except TypeError: |
---|
[2add354] | 1719 | # Unparsable field |
---|
| 1720 | return |
---|
[fbfc488] | 1721 | |
---|
| 1722 | parameter_name = str(self._model_model.data(name_index)) # sld, background etc. |
---|
[cbcdd2c] | 1723 | |
---|
[00b3b40] | 1724 | # Update the parameter value - note: this supports +/-inf as well |
---|
[cbcdd2c] | 1725 | self.kernel_module.params[parameter_name] = value |
---|
| 1726 | |
---|
[8a32a6ff] | 1727 | # Update the parameter value - note: this supports +/-inf as well |
---|
[8f2548c] | 1728 | param_column = self.lstParams.itemDelegate().param_value |
---|
| 1729 | min_column = self.lstParams.itemDelegate().param_min |
---|
| 1730 | max_column = self.lstParams.itemDelegate().param_max |
---|
| 1731 | if model_column == param_column: |
---|
[8a32a6ff] | 1732 | self.kernel_module.setParam(parameter_name, value) |
---|
[8f2548c] | 1733 | elif model_column == min_column: |
---|
[8a32a6ff] | 1734 | # min/max to be changed in self.kernel_module.details[parameter_name] = ['Ang', 0.0, inf] |
---|
[8f2548c] | 1735 | self.kernel_module.details[parameter_name][1] = value |
---|
| 1736 | elif model_column == max_column: |
---|
| 1737 | self.kernel_module.details[parameter_name][2] = value |
---|
| 1738 | else: |
---|
| 1739 | # don't update the chart |
---|
| 1740 | return |
---|
[00b3b40] | 1741 | |
---|
| 1742 | # TODO: magnetic params in self.kernel_module.details['M0:parameter_name'] = value |
---|
| 1743 | # TODO: multishell params in self.kernel_module.details[??] = value |
---|
[cbcdd2c] | 1744 | |
---|
[d7ff531] | 1745 | # Force the chart update when actual parameters changed |
---|
| 1746 | if model_column == 1: |
---|
[d48cc19] | 1747 | self.recalculatePlotData() |
---|
[7d077d1] | 1748 | |
---|
[2241130] | 1749 | # Update state stack |
---|
[00b3b40] | 1750 | self.updateUndo() |
---|
[2241130] | 1751 | |
---|
[7fd20fc] | 1752 | def isCheckable(self, row): |
---|
| 1753 | return self._model_model.item(row, 0).isCheckable() |
---|
| 1754 | |
---|
[f182f93] | 1755 | def checkboxSelected(self, item): |
---|
| 1756 | # Assure we're dealing with checkboxes |
---|
| 1757 | if not item.isCheckable(): |
---|
| 1758 | return |
---|
| 1759 | status = item.checkState() |
---|
| 1760 | |
---|
| 1761 | # If multiple rows selected - toggle all of them, filtering uncheckable |
---|
| 1762 | # Switch off signaling from the model to avoid recursion |
---|
| 1763 | self._model_model.blockSignals(True) |
---|
| 1764 | # Convert to proper indices and set requested enablement |
---|
[7fd20fc] | 1765 | self.setParameterSelection(status) |
---|
| 1766 | #[self._model_model.item(row, 0).setCheckState(status) for row in self.selectedParameters()] |
---|
[f182f93] | 1767 | self._model_model.blockSignals(False) |
---|
| 1768 | |
---|
| 1769 | # update the list of parameters to fit |
---|
[c1e380e] | 1770 | main_params = self.checkedListFromModel(self._model_model) |
---|
| 1771 | poly_params = self.checkedListFromModel(self._poly_model) |
---|
[b00414d] | 1772 | magnet_params = self.checkedListFromModel(self._magnet_model) |
---|
| 1773 | |
---|
[c1e380e] | 1774 | # Retrieve poly params names |
---|
[358b39d] | 1775 | poly_params = [param.rsplit()[-1] + '.width' for param in poly_params] |
---|
[c1e380e] | 1776 | |
---|
[b00414d] | 1777 | self.parameters_to_fit = main_params + poly_params + magnet_params |
---|
[c1e380e] | 1778 | |
---|
| 1779 | def checkedListFromModel(self, model): |
---|
| 1780 | """ |
---|
| 1781 | Returns list of checked parameters for given model |
---|
| 1782 | """ |
---|
| 1783 | def isChecked(row): |
---|
| 1784 | return model.item(row, 0).checkState() == QtCore.Qt.Checked |
---|
| 1785 | |
---|
| 1786 | return [str(model.item(row_index, 0).text()) |
---|
[b3e8629] | 1787 | for row_index in range(model.rowCount()) |
---|
[c1e380e] | 1788 | if isChecked(row_index)] |
---|
[f182f93] | 1789 | |
---|
[6fd4e36] | 1790 | def createNewIndex(self, fitted_data): |
---|
| 1791 | """ |
---|
| 1792 | Create a model or theory index with passed Data1D/Data2D |
---|
| 1793 | """ |
---|
| 1794 | if self.data_is_loaded: |
---|
[0268aed] | 1795 | if not fitted_data.name: |
---|
| 1796 | name = self.nameForFittedData(self.data.filename) |
---|
| 1797 | fitted_data.title = name |
---|
| 1798 | fitted_data.name = name |
---|
| 1799 | fitted_data.filename = name |
---|
[7d077d1] | 1800 | fitted_data.symbol = "Line" |
---|
[6fd4e36] | 1801 | self.updateModelIndex(fitted_data) |
---|
| 1802 | else: |
---|
[0268aed] | 1803 | name = self.nameForFittedData(self.kernel_module.name) |
---|
| 1804 | fitted_data.title = name |
---|
| 1805 | fitted_data.name = name |
---|
| 1806 | fitted_data.filename = name |
---|
| 1807 | fitted_data.symbol = "Line" |
---|
[6fd4e36] | 1808 | self.createTheoryIndex(fitted_data) |
---|
| 1809 | |
---|
| 1810 | def updateModelIndex(self, fitted_data): |
---|
| 1811 | """ |
---|
| 1812 | Update a QStandardModelIndex containing model data |
---|
| 1813 | """ |
---|
[00b3b40] | 1814 | name = self.nameFromData(fitted_data) |
---|
[0268aed] | 1815 | # Make this a line if no other defined |
---|
[7d077d1] | 1816 | if hasattr(fitted_data, 'symbol') and fitted_data.symbol is None: |
---|
[0268aed] | 1817 | fitted_data.symbol = 'Line' |
---|
[6fd4e36] | 1818 | # Notify the GUI manager so it can update the main model in DataExplorer |
---|
[b3e8629] | 1819 | GuiUtils.updateModelItemWithPlot(self._index, fitted_data, name) |
---|
[6fd4e36] | 1820 | |
---|
| 1821 | def createTheoryIndex(self, fitted_data): |
---|
| 1822 | """ |
---|
| 1823 | Create a QStandardModelIndex containing model data |
---|
| 1824 | """ |
---|
[00b3b40] | 1825 | name = self.nameFromData(fitted_data) |
---|
| 1826 | # Notify the GUI manager so it can create the theory model in DataExplorer |
---|
[b3e8629] | 1827 | new_item = GuiUtils.createModelItemWithPlot(fitted_data, name=name) |
---|
[00b3b40] | 1828 | self.communicate.updateTheoryFromPerspectiveSignal.emit(new_item) |
---|
| 1829 | |
---|
| 1830 | def nameFromData(self, fitted_data): |
---|
| 1831 | """ |
---|
| 1832 | Return name for the dataset. Terribly impure function. |
---|
| 1833 | """ |
---|
[0268aed] | 1834 | if fitted_data.name is None: |
---|
[00b3b40] | 1835 | name = self.nameForFittedData(self.logic.data.filename) |
---|
[0268aed] | 1836 | fitted_data.title = name |
---|
| 1837 | fitted_data.name = name |
---|
| 1838 | fitted_data.filename = name |
---|
| 1839 | else: |
---|
| 1840 | name = fitted_data.name |
---|
[00b3b40] | 1841 | return name |
---|
[5236449] | 1842 | |
---|
[4d457df] | 1843 | def methodCalculateForData(self): |
---|
| 1844 | '''return the method for data calculation''' |
---|
| 1845 | return Calc1D if isinstance(self.data, Data1D) else Calc2D |
---|
| 1846 | |
---|
| 1847 | def methodCompleteForData(self): |
---|
| 1848 | '''return the method for result parsin on calc complete ''' |
---|
| 1849 | return self.complete1D if isinstance(self.data, Data1D) else self.complete2D |
---|
| 1850 | |
---|
[b1e36a3] | 1851 | def calculateQGridForModel(self): |
---|
[86f88d1] | 1852 | """ |
---|
| 1853 | Prepare the fitting data object, based on current ModelModel |
---|
| 1854 | """ |
---|
[180bd54] | 1855 | if self.kernel_module is None: |
---|
| 1856 | return |
---|
[4d457df] | 1857 | # Awful API to a backend method. |
---|
| 1858 | method = self.methodCalculateForData()(data=self.data, |
---|
[1bc27f1] | 1859 | model=self.kernel_module, |
---|
| 1860 | page_id=0, |
---|
| 1861 | qmin=self.q_range_min, |
---|
| 1862 | qmax=self.q_range_max, |
---|
| 1863 | smearer=None, |
---|
| 1864 | state=None, |
---|
| 1865 | weight=None, |
---|
| 1866 | fid=None, |
---|
| 1867 | toggle_mode_on=False, |
---|
| 1868 | completefn=None, |
---|
| 1869 | update_chisqr=True, |
---|
| 1870 | exception_handler=self.calcException, |
---|
| 1871 | source=None) |
---|
[4d457df] | 1872 | |
---|
| 1873 | calc_thread = threads.deferToThread(method.compute) |
---|
| 1874 | calc_thread.addCallback(self.methodCompleteForData()) |
---|
[c1e380e] | 1875 | calc_thread.addErrback(self.calculateDataFailed) |
---|
[6964d44] | 1876 | |
---|
[aca8418] | 1877 | def calculateDataFailed(self, reason): |
---|
[6964d44] | 1878 | """ |
---|
[c1e380e] | 1879 | Thread returned error |
---|
[6964d44] | 1880 | """ |
---|
[b3e8629] | 1881 | print("Calculate Data failed with ", reason) |
---|
[5236449] | 1882 | |
---|
[cbcdd2c] | 1883 | def complete1D(self, return_data): |
---|
[5236449] | 1884 | """ |
---|
[4d457df] | 1885 | Plot the current 1D data |
---|
| 1886 | """ |
---|
[d48cc19] | 1887 | fitted_data = self.logic.new1DPlot(return_data, self.tab_id) |
---|
| 1888 | self.calculateResiduals(fitted_data) |
---|
| 1889 | self.model_data = fitted_data |
---|
[cbcdd2c] | 1890 | |
---|
| 1891 | def complete2D(self, return_data): |
---|
| 1892 | """ |
---|
[4d457df] | 1893 | Plot the current 2D data |
---|
| 1894 | """ |
---|
[6fd4e36] | 1895 | fitted_data = self.logic.new2DPlot(return_data) |
---|
| 1896 | self.calculateResiduals(fitted_data) |
---|
[d48cc19] | 1897 | self.model_data = fitted_data |
---|
[6fd4e36] | 1898 | |
---|
| 1899 | def calculateResiduals(self, fitted_data): |
---|
| 1900 | """ |
---|
| 1901 | Calculate and print Chi2 and display chart of residuals |
---|
| 1902 | """ |
---|
| 1903 | # Create a new index for holding data |
---|
[7d077d1] | 1904 | fitted_data.symbol = "Line" |
---|
[6964d44] | 1905 | |
---|
| 1906 | # Modify fitted_data with weighting |
---|
| 1907 | self.addWeightingToData(fitted_data) |
---|
| 1908 | |
---|
[6fd4e36] | 1909 | self.createNewIndex(fitted_data) |
---|
| 1910 | # Calculate difference between return_data and logic.data |
---|
[2add354] | 1911 | self.chi2 = FittingUtilities.calculateChi2(fitted_data, self.logic.data) |
---|
[6fd4e36] | 1912 | # Update the control |
---|
[2add354] | 1913 | chi2_repr = "---" if self.chi2 is None else GuiUtils.formatNumber(self.chi2, high=True) |
---|
[f182f93] | 1914 | self.lblChi2Value.setText(chi2_repr) |
---|
[cbcdd2c] | 1915 | |
---|
[d48cc19] | 1916 | self.communicate.plotUpdateSignal.emit([fitted_data]) |
---|
| 1917 | |
---|
[0268aed] | 1918 | # Plot residuals if actual data |
---|
[aca8418] | 1919 | if not self.data_is_loaded: |
---|
| 1920 | return |
---|
| 1921 | |
---|
| 1922 | residuals_plot = FittingUtilities.plotResiduals(self.data, fitted_data) |
---|
| 1923 | residuals_plot.id = "Residual " + residuals_plot.id |
---|
| 1924 | self.createNewIndex(residuals_plot) |
---|
[d6b8a1d] | 1925 | #self.communicate.plotUpdateSignal.emit([residuals_plot]) |
---|
[5236449] | 1926 | |
---|
| 1927 | def calcException(self, etype, value, tb): |
---|
| 1928 | """ |
---|
[c1e380e] | 1929 | Thread threw an exception. |
---|
[5236449] | 1930 | """ |
---|
[c1e380e] | 1931 | # TODO: remimplement thread cancellation |
---|
[5236449] | 1932 | logging.error("".join(traceback.format_exception(etype, value, tb))) |
---|
[60af928] | 1933 | |
---|
| 1934 | def setTableProperties(self, table): |
---|
| 1935 | """ |
---|
| 1936 | Setting table properties |
---|
| 1937 | """ |
---|
| 1938 | # Table properties |
---|
| 1939 | table.verticalHeader().setVisible(False) |
---|
| 1940 | table.setAlternatingRowColors(True) |
---|
[4992ff2] | 1941 | table.setSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) |
---|
| 1942 | table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) |
---|
[f46f6dc] | 1943 | table.resizeColumnsToContents() |
---|
| 1944 | |
---|
[60af928] | 1945 | # Header |
---|
| 1946 | header = table.horizontalHeader() |
---|
[4992ff2] | 1947 | header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents) |
---|
| 1948 | header.ResizeMode(QtWidgets.QHeaderView.Interactive) |
---|
[f46f6dc] | 1949 | |
---|
[4992ff2] | 1950 | # Qt5: the following 2 lines crash - figure out why! |
---|
[e43fc91] | 1951 | # Resize column 0 and 7 to content |
---|
[4992ff2] | 1952 | #header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents) |
---|
| 1953 | #header.setSectionResizeMode(7, QtWidgets.QHeaderView.ResizeToContents) |
---|
[60af928] | 1954 | |
---|
| 1955 | def setPolyModel(self): |
---|
| 1956 | """ |
---|
| 1957 | Set polydispersity values |
---|
| 1958 | """ |
---|
[86f88d1] | 1959 | if not self.model_parameters: |
---|
| 1960 | return |
---|
| 1961 | self._poly_model.clear() |
---|
| 1962 | |
---|
[e43fc91] | 1963 | [self.setPolyModelParameters(i, param) for i, param in \ |
---|
[aca8418] | 1964 | enumerate(self.model_parameters.form_volume_parameters) if param.polydisperse] |
---|
[4d457df] | 1965 | FittingUtilities.addPolyHeadersToModel(self._poly_model) |
---|
[60af928] | 1966 | |
---|
[e43fc91] | 1967 | def setPolyModelParameters(self, i, param): |
---|
[aca8418] | 1968 | """ |
---|
[0d13814] | 1969 | Standard of multishell poly parameter driver |
---|
[aca8418] | 1970 | """ |
---|
[0d13814] | 1971 | param_name = param.name |
---|
| 1972 | # see it the parameter is multishell |
---|
[06b0138] | 1973 | if '[' in param.name: |
---|
[0d13814] | 1974 | # Skip empty shells |
---|
| 1975 | if self.current_shell_displayed == 0: |
---|
| 1976 | return |
---|
| 1977 | else: |
---|
| 1978 | # Create as many entries as current shells |
---|
[b3e8629] | 1979 | for ishell in range(1, self.current_shell_displayed+1): |
---|
[0d13814] | 1980 | # Remove [n] and add the shell numeral |
---|
| 1981 | name = param_name[0:param_name.index('[')] + str(ishell) |
---|
[e43fc91] | 1982 | self.addNameToPolyModel(i, name) |
---|
[0d13814] | 1983 | else: |
---|
| 1984 | # Just create a simple param entry |
---|
[e43fc91] | 1985 | self.addNameToPolyModel(i, param_name) |
---|
[0d13814] | 1986 | |
---|
[e43fc91] | 1987 | def addNameToPolyModel(self, i, param_name): |
---|
[0d13814] | 1988 | """ |
---|
| 1989 | Creates a checked row in the poly model with param_name |
---|
| 1990 | """ |
---|
[144ec831] | 1991 | # Polydisp. values from the sasmodel |
---|
[0d13814] | 1992 | width = self.kernel_module.getParam(param_name + '.width') |
---|
| 1993 | npts = self.kernel_module.getParam(param_name + '.npts') |
---|
| 1994 | nsigs = self.kernel_module.getParam(param_name + '.nsigmas') |
---|
| 1995 | _, min, max = self.kernel_module.details[param_name] |
---|
[144ec831] | 1996 | |
---|
| 1997 | # Construct a row with polydisp. related variable. |
---|
| 1998 | # This will get added to the polydisp. model |
---|
| 1999 | # Note: last argument needs extra space padding for decent display of the control |
---|
[0d13814] | 2000 | checked_list = ["Distribution of " + param_name, str(width), |
---|
| 2001 | str(min), str(max), |
---|
[e43fc91] | 2002 | str(npts), str(nsigs), "gaussian ",''] |
---|
[aca8418] | 2003 | FittingUtilities.addCheckedListToModel(self._poly_model, checked_list) |
---|
| 2004 | |
---|
| 2005 | # All possible polydisp. functions as strings in combobox |
---|
[4992ff2] | 2006 | func = QtWidgets.QComboBox() |
---|
[b3e8629] | 2007 | func.addItems([str(name_disp) for name_disp in POLYDISPERSITY_MODELS.keys()]) |
---|
[e43fc91] | 2008 | # Set the default index |
---|
[aca8418] | 2009 | func.setCurrentIndex(func.findText(DEFAULT_POLYDISP_FUNCTION)) |
---|
[e43fc91] | 2010 | ind = self._poly_model.index(i,self.lstPoly.itemDelegate().poly_function) |
---|
| 2011 | self.lstPoly.setIndexWidget(ind, func) |
---|
| 2012 | func.currentIndexChanged.connect(lambda: self.onPolyComboIndexChange(str(func.currentText()), i)) |
---|
| 2013 | |
---|
| 2014 | def onPolyFilenameChange(self, row_index): |
---|
| 2015 | """ |
---|
| 2016 | Respond to filename_updated signal from the delegate |
---|
| 2017 | """ |
---|
| 2018 | # For the given row, invoke the "array" combo handler |
---|
| 2019 | array_caption = 'array' |
---|
[8222f171] | 2020 | |
---|
[e43fc91] | 2021 | # Get the combo box reference |
---|
| 2022 | ind = self._poly_model.index(row_index, self.lstPoly.itemDelegate().poly_function) |
---|
| 2023 | widget = self.lstPoly.indexWidget(ind) |
---|
[8222f171] | 2024 | |
---|
[e43fc91] | 2025 | # Update the combo box so it displays "array" |
---|
| 2026 | widget.blockSignals(True) |
---|
| 2027 | widget.setCurrentIndex(self.lstPoly.itemDelegate().POLYDISPERSE_FUNCTIONS.index(array_caption)) |
---|
| 2028 | widget.blockSignals(False) |
---|
[aca8418] | 2029 | |
---|
[8222f171] | 2030 | # Invoke the file reader |
---|
| 2031 | self.onPolyComboIndexChange(array_caption, row_index) |
---|
| 2032 | |
---|
[aca8418] | 2033 | def onPolyComboIndexChange(self, combo_string, row_index): |
---|
| 2034 | """ |
---|
| 2035 | Modify polydisp. defaults on function choice |
---|
| 2036 | """ |
---|
[144ec831] | 2037 | # Get npts/nsigs for current selection |
---|
[aca8418] | 2038 | param = self.model_parameters.form_volume_parameters[row_index] |
---|
[e43fc91] | 2039 | file_index = self._poly_model.index(row_index, self.lstPoly.itemDelegate().poly_function) |
---|
| 2040 | combo_box = self.lstPoly.indexWidget(file_index) |
---|
[aca8418] | 2041 | |
---|
[919d47c] | 2042 | def updateFunctionCaption(row): |
---|
| 2043 | # Utility function for update of polydispersity function name in the main model |
---|
[1643d8ed] | 2044 | param_name = str(self._model_model.item(row, 0).text()) |
---|
[919d47c] | 2045 | if param_name != param.name: |
---|
| 2046 | return |
---|
[144ec831] | 2047 | # Modify the param value |
---|
[919d47c] | 2048 | self._model_model.item(row, 0).child(0).child(0,4).setText(combo_string) |
---|
| 2049 | |
---|
[aca8418] | 2050 | if combo_string == 'array': |
---|
| 2051 | try: |
---|
[e43fc91] | 2052 | self.loadPolydispArray(row_index) |
---|
[919d47c] | 2053 | # Update main model for display |
---|
| 2054 | self.iterateOverModel(updateFunctionCaption) |
---|
[e43fc91] | 2055 | # disable the row |
---|
| 2056 | lo = self.lstPoly.itemDelegate().poly_pd |
---|
| 2057 | hi = self.lstPoly.itemDelegate().poly_function |
---|
[b3e8629] | 2058 | [self._poly_model.item(row_index, i).setEnabled(False) for i in range(lo, hi)] |
---|
[aca8418] | 2059 | return |
---|
[e43fc91] | 2060 | except IOError: |
---|
[8222f171] | 2061 | combo_box.setCurrentIndex(self.orig_poly_index) |
---|
[e43fc91] | 2062 | # Pass for cancel/bad read |
---|
| 2063 | pass |
---|
[aca8418] | 2064 | |
---|
| 2065 | # Enable the row in case it was disabled by Array |
---|
[919d47c] | 2066 | self._poly_model.blockSignals(True) |
---|
[e43fc91] | 2067 | max_range = self.lstPoly.itemDelegate().poly_filename |
---|
[b3e8629] | 2068 | [self._poly_model.item(row_index, i).setEnabled(True) for i in range(7)] |
---|
[e43fc91] | 2069 | file_index = self._poly_model.index(row_index, self.lstPoly.itemDelegate().poly_filename) |
---|
[b3e8629] | 2070 | self._poly_model.setData(file_index, "") |
---|
[919d47c] | 2071 | self._poly_model.blockSignals(False) |
---|
[aca8418] | 2072 | |
---|
[8eaa101] | 2073 | npts_index = self._poly_model.index(row_index, self.lstPoly.itemDelegate().poly_npts) |
---|
| 2074 | nsigs_index = self._poly_model.index(row_index, self.lstPoly.itemDelegate().poly_nsigs) |
---|
[aca8418] | 2075 | |
---|
| 2076 | npts = POLYDISPERSITY_MODELS[str(combo_string)].default['npts'] |
---|
| 2077 | nsigs = POLYDISPERSITY_MODELS[str(combo_string)].default['nsigmas'] |
---|
| 2078 | |
---|
[b3e8629] | 2079 | self._poly_model.setData(npts_index, npts) |
---|
| 2080 | self._poly_model.setData(nsigs_index, nsigs) |
---|
[aca8418] | 2081 | |
---|
[919d47c] | 2082 | self.iterateOverModel(updateFunctionCaption) |
---|
[8222f171] | 2083 | self.orig_poly_index = combo_box.currentIndex() |
---|
[919d47c] | 2084 | |
---|
[e43fc91] | 2085 | def loadPolydispArray(self, row_index): |
---|
[aca8418] | 2086 | """ |
---|
| 2087 | Show the load file dialog and loads requested data into state |
---|
| 2088 | """ |
---|
[4992ff2] | 2089 | datafile = QtWidgets.QFileDialog.getOpenFileName( |
---|
| 2090 | self, "Choose a weight file", "", "All files (*.*)", None, |
---|
[fbfc488] | 2091 | QtWidgets.QFileDialog.DontUseNativeDialog)[0] |
---|
[72f4834] | 2092 | |
---|
[fbfc488] | 2093 | if not datafile: |
---|
[aca8418] | 2094 | logging.info("No weight data chosen.") |
---|
[1643d8ed] | 2095 | raise IOError |
---|
[72f4834] | 2096 | |
---|
[aca8418] | 2097 | values = [] |
---|
| 2098 | weights = [] |
---|
[919d47c] | 2099 | def appendData(data_tuple): |
---|
| 2100 | """ |
---|
| 2101 | Fish out floats from a tuple of strings |
---|
| 2102 | """ |
---|
| 2103 | try: |
---|
| 2104 | values.append(float(data_tuple[0])) |
---|
| 2105 | weights.append(float(data_tuple[1])) |
---|
| 2106 | except (ValueError, IndexError): |
---|
| 2107 | # just pass through if line with bad data |
---|
| 2108 | return |
---|
| 2109 | |
---|
[aca8418] | 2110 | with open(datafile, 'r') as column_file: |
---|
| 2111 | column_data = [line.rstrip().split() for line in column_file.readlines()] |
---|
[919d47c] | 2112 | [appendData(line) for line in column_data] |
---|
[aca8418] | 2113 | |
---|
[1643d8ed] | 2114 | # If everything went well - update the sasmodel values |
---|
[aca8418] | 2115 | self.disp_model = POLYDISPERSITY_MODELS['array']() |
---|
| 2116 | self.disp_model.set_weights(np.array(values), np.array(weights)) |
---|
[e43fc91] | 2117 | # + update the cell with filename |
---|
| 2118 | fname = os.path.basename(str(datafile)) |
---|
| 2119 | fname_index = self._poly_model.index(row_index, self.lstPoly.itemDelegate().poly_filename) |
---|
[b3e8629] | 2120 | self._poly_model.setData(fname_index, fname) |
---|
[aca8418] | 2121 | |
---|
[60af928] | 2122 | def setMagneticModel(self): |
---|
| 2123 | """ |
---|
| 2124 | Set magnetism values on model |
---|
| 2125 | """ |
---|
[86f88d1] | 2126 | if not self.model_parameters: |
---|
| 2127 | return |
---|
| 2128 | self._magnet_model.clear() |
---|
[aca8418] | 2129 | [self.addCheckedMagneticListToModel(param, self._magnet_model) for param in \ |
---|
[06b0138] | 2130 | self.model_parameters.call_parameters if param.type == 'magnetic'] |
---|
[4d457df] | 2131 | FittingUtilities.addHeadersToModel(self._magnet_model) |
---|
[60af928] | 2132 | |
---|
[0d13814] | 2133 | def shellNamesList(self): |
---|
| 2134 | """ |
---|
| 2135 | Returns list of names of all multi-shell parameters |
---|
| 2136 | E.g. for sld[n], radius[n], n=1..3 it will return |
---|
| 2137 | [sld1, sld2, sld3, radius1, radius2, radius3] |
---|
| 2138 | """ |
---|
| 2139 | multi_names = [p.name[:p.name.index('[')] for p in self.model_parameters.iq_parameters if '[' in p.name] |
---|
| 2140 | top_index = self.kernel_module.multiplicity_info.number |
---|
| 2141 | shell_names = [] |
---|
[b3e8629] | 2142 | for i in range(1, top_index+1): |
---|
[0d13814] | 2143 | for name in multi_names: |
---|
| 2144 | shell_names.append(name+str(i)) |
---|
| 2145 | return shell_names |
---|
| 2146 | |
---|
[aca8418] | 2147 | def addCheckedMagneticListToModel(self, param, model): |
---|
| 2148 | """ |
---|
| 2149 | Wrapper for model update with a subset of magnetic parameters |
---|
| 2150 | """ |
---|
[0d13814] | 2151 | if param.name[param.name.index(':')+1:] in self.shell_names: |
---|
| 2152 | # check if two-digit shell number |
---|
| 2153 | try: |
---|
| 2154 | shell_index = int(param.name[-2:]) |
---|
| 2155 | except ValueError: |
---|
| 2156 | shell_index = int(param.name[-1:]) |
---|
| 2157 | |
---|
| 2158 | if shell_index > self.current_shell_displayed: |
---|
| 2159 | return |
---|
| 2160 | |
---|
[aca8418] | 2161 | checked_list = [param.name, |
---|
| 2162 | str(param.default), |
---|
| 2163 | str(param.limits[0]), |
---|
| 2164 | str(param.limits[1]), |
---|
| 2165 | param.units] |
---|
| 2166 | |
---|
| 2167 | FittingUtilities.addCheckedListToModel(model, checked_list) |
---|
| 2168 | |
---|
[fd1ae6d1] | 2169 | def enableStructureFactorControl(self, structure_factor): |
---|
[cd31251] | 2170 | """ |
---|
| 2171 | Add structure factors to the list of parameters |
---|
| 2172 | """ |
---|
[fd1ae6d1] | 2173 | if self.kernel_module.is_form_factor or structure_factor == 'None': |
---|
[cd31251] | 2174 | self.enableStructureCombo() |
---|
| 2175 | else: |
---|
| 2176 | self.disableStructureCombo() |
---|
| 2177 | |
---|
[60af928] | 2178 | def addExtraShells(self): |
---|
| 2179 | """ |
---|
[f46f6dc] | 2180 | Add a combobox for multiple shell display |
---|
[60af928] | 2181 | """ |
---|
[4d457df] | 2182 | param_name, param_length = FittingUtilities.getMultiplicity(self.model_parameters) |
---|
[f46f6dc] | 2183 | |
---|
| 2184 | if param_length == 0: |
---|
| 2185 | return |
---|
| 2186 | |
---|
[6f7f652] | 2187 | # cell 1: variable name |
---|
[f46f6dc] | 2188 | item1 = QtGui.QStandardItem(param_name) |
---|
| 2189 | |
---|
[4992ff2] | 2190 | func = QtWidgets.QComboBox() |
---|
[b1e36a3] | 2191 | # Available range of shells displayed in the combobox |
---|
[b3e8629] | 2192 | func.addItems([str(i) for i in range(param_length+1)]) |
---|
[a9b568c] | 2193 | |
---|
[b1e36a3] | 2194 | # Respond to index change |
---|
[86f88d1] | 2195 | func.currentIndexChanged.connect(self.modifyShellsInList) |
---|
[60af928] | 2196 | |
---|
[6f7f652] | 2197 | # cell 2: combobox |
---|
[f46f6dc] | 2198 | item2 = QtGui.QStandardItem() |
---|
| 2199 | self._model_model.appendRow([item1, item2]) |
---|
[60af928] | 2200 | |
---|
[6f7f652] | 2201 | # Beautify the row: span columns 2-4 |
---|
[60af928] | 2202 | shell_row = self._model_model.rowCount() |
---|
[f46f6dc] | 2203 | shell_index = self._model_model.index(shell_row-1, 1) |
---|
[86f88d1] | 2204 | |
---|
[4d457df] | 2205 | self.lstParams.setIndexWidget(shell_index, func) |
---|
[86f88d1] | 2206 | self._last_model_row = self._model_model.rowCount() |
---|
| 2207 | |
---|
[a9b568c] | 2208 | # Set the index to the state-kept value |
---|
| 2209 | func.setCurrentIndex(self.current_shell_displayed |
---|
| 2210 | if self.current_shell_displayed < func.count() else 0) |
---|
| 2211 | |
---|
[86f88d1] | 2212 | def modifyShellsInList(self, index): |
---|
| 2213 | """ |
---|
| 2214 | Add/remove additional multishell parameters |
---|
| 2215 | """ |
---|
| 2216 | # Find row location of the combobox |
---|
| 2217 | last_row = self._last_model_row |
---|
| 2218 | remove_rows = self._model_model.rowCount() - last_row |
---|
| 2219 | |
---|
| 2220 | if remove_rows > 1: |
---|
| 2221 | self._model_model.removeRows(last_row, remove_rows) |
---|
| 2222 | |
---|
[4d457df] | 2223 | FittingUtilities.addShellsToModel(self.model_parameters, self._model_model, index) |
---|
[a9b568c] | 2224 | self.current_shell_displayed = index |
---|
[60af928] | 2225 | |
---|
[0d13814] | 2226 | # Update relevant models |
---|
| 2227 | self.setPolyModel() |
---|
| 2228 | self.setMagneticModel() |
---|
| 2229 | |
---|
[14ec91c5] | 2230 | def setFittingStarted(self): |
---|
| 2231 | """ |
---|
| 2232 | Set item enablement on fitting start |
---|
| 2233 | """ |
---|
| 2234 | #disable the Fit button |
---|
| 2235 | self.cmdFit.setText('Running...') |
---|
| 2236 | self.cmdFit.setEnabled(False) |
---|
| 2237 | |
---|
| 2238 | def setFittingStopped(self): |
---|
| 2239 | """ |
---|
| 2240 | Set item enablement on fitting stop |
---|
| 2241 | """ |
---|
| 2242 | #enable the Fit button |
---|
| 2243 | self.cmdFit.setText("Fit") |
---|
| 2244 | self.cmdFit.setEnabled(True) |
---|
| 2245 | |
---|
[672b8ab] | 2246 | def readFitPage(self, fp): |
---|
| 2247 | """ |
---|
| 2248 | Read in state from a fitpage object and update GUI |
---|
| 2249 | """ |
---|
| 2250 | assert isinstance(fp, FitPage) |
---|
| 2251 | # Main tab info |
---|
| 2252 | self.logic.data.filename = fp.filename |
---|
| 2253 | self.data_is_loaded = fp.data_is_loaded |
---|
| 2254 | self.chkPolydispersity.setCheckState(fp.is_polydisperse) |
---|
| 2255 | self.chkMagnetism.setCheckState(fp.is_magnetic) |
---|
| 2256 | self.chk2DView.setCheckState(fp.is2D) |
---|
| 2257 | |
---|
| 2258 | # Update the comboboxes |
---|
| 2259 | self.cbCategory.setCurrentIndex(self.cbCategory.findText(fp.current_category)) |
---|
| 2260 | self.cbModel.setCurrentIndex(self.cbModel.findText(fp.current_model)) |
---|
| 2261 | if fp.current_factor: |
---|
| 2262 | self.cbStructureFactor.setCurrentIndex(self.cbStructureFactor.findText(fp.current_factor)) |
---|
| 2263 | |
---|
| 2264 | self.chi2 = fp.chi2 |
---|
| 2265 | |
---|
| 2266 | # Options tab |
---|
| 2267 | self.q_range_min = fp.fit_options[fp.MIN_RANGE] |
---|
| 2268 | self.q_range_max = fp.fit_options[fp.MAX_RANGE] |
---|
| 2269 | self.npts = fp.fit_options[fp.NPTS] |
---|
| 2270 | self.log_points = fp.fit_options[fp.LOG_POINTS] |
---|
| 2271 | self.weighting = fp.fit_options[fp.WEIGHTING] |
---|
| 2272 | |
---|
| 2273 | # Models |
---|
[d60da0c] | 2274 | self._model_model = fp.model_model |
---|
| 2275 | self._poly_model = fp.poly_model |
---|
| 2276 | self._magnet_model = fp.magnetism_model |
---|
[672b8ab] | 2277 | |
---|
| 2278 | # Resolution tab |
---|
| 2279 | smearing = fp.smearing_options[fp.SMEARING_OPTION] |
---|
| 2280 | accuracy = fp.smearing_options[fp.SMEARING_ACCURACY] |
---|
| 2281 | smearing_min = fp.smearing_options[fp.SMEARING_MIN] |
---|
| 2282 | smearing_max = fp.smearing_options[fp.SMEARING_MAX] |
---|
| 2283 | self.smearing_widget.setState(smearing, accuracy, smearing_min, smearing_max) |
---|
| 2284 | |
---|
| 2285 | # TODO: add polidyspersity and magnetism |
---|
| 2286 | |
---|
| 2287 | def saveToFitPage(self, fp): |
---|
| 2288 | """ |
---|
| 2289 | Write current state to the given fitpage |
---|
| 2290 | """ |
---|
| 2291 | assert isinstance(fp, FitPage) |
---|
| 2292 | |
---|
| 2293 | # Main tab info |
---|
| 2294 | fp.filename = self.logic.data.filename |
---|
| 2295 | fp.data_is_loaded = self.data_is_loaded |
---|
| 2296 | fp.is_polydisperse = self.chkPolydispersity.isChecked() |
---|
| 2297 | fp.is_magnetic = self.chkMagnetism.isChecked() |
---|
| 2298 | fp.is2D = self.chk2DView.isChecked() |
---|
| 2299 | fp.data = self.data |
---|
| 2300 | |
---|
| 2301 | # Use current models - they contain all the required parameters |
---|
| 2302 | fp.model_model = self._model_model |
---|
| 2303 | fp.poly_model = self._poly_model |
---|
| 2304 | fp.magnetism_model = self._magnet_model |
---|
| 2305 | |
---|
| 2306 | if self.cbCategory.currentIndex() != 0: |
---|
| 2307 | fp.current_category = str(self.cbCategory.currentText()) |
---|
| 2308 | fp.current_model = str(self.cbModel.currentText()) |
---|
| 2309 | |
---|
| 2310 | if self.cbStructureFactor.isEnabled() and self.cbStructureFactor.currentIndex() != 0: |
---|
| 2311 | fp.current_factor = str(self.cbStructureFactor.currentText()) |
---|
| 2312 | else: |
---|
| 2313 | fp.current_factor = '' |
---|
| 2314 | |
---|
| 2315 | fp.chi2 = self.chi2 |
---|
| 2316 | fp.parameters_to_fit = self.parameters_to_fit |
---|
[6964d44] | 2317 | fp.kernel_module = self.kernel_module |
---|
[672b8ab] | 2318 | |
---|
[6ff2eb3] | 2319 | # Algorithm options |
---|
| 2320 | # fp.algorithm = self.parent.fit_options.selected_id |
---|
| 2321 | |
---|
[672b8ab] | 2322 | # Options tab |
---|
| 2323 | fp.fit_options[fp.MIN_RANGE] = self.q_range_min |
---|
| 2324 | fp.fit_options[fp.MAX_RANGE] = self.q_range_max |
---|
| 2325 | fp.fit_options[fp.NPTS] = self.npts |
---|
| 2326 | #fp.fit_options[fp.NPTS_FIT] = self.npts_fit |
---|
| 2327 | fp.fit_options[fp.LOG_POINTS] = self.log_points |
---|
| 2328 | fp.fit_options[fp.WEIGHTING] = self.weighting |
---|
| 2329 | |
---|
| 2330 | # Resolution tab |
---|
| 2331 | smearing, accuracy, smearing_min, smearing_max = self.smearing_widget.state() |
---|
| 2332 | fp.smearing_options[fp.SMEARING_OPTION] = smearing |
---|
| 2333 | fp.smearing_options[fp.SMEARING_ACCURACY] = accuracy |
---|
| 2334 | fp.smearing_options[fp.SMEARING_MIN] = smearing_min |
---|
| 2335 | fp.smearing_options[fp.SMEARING_MAX] = smearing_max |
---|
| 2336 | |
---|
| 2337 | # TODO: add polidyspersity and magnetism |
---|
| 2338 | |
---|
[00b3b40] | 2339 | |
---|
| 2340 | def updateUndo(self): |
---|
| 2341 | """ |
---|
| 2342 | Create a new state page and add it to the stack |
---|
| 2343 | """ |
---|
| 2344 | if self.undo_supported: |
---|
| 2345 | self.pushFitPage(self.currentState()) |
---|
| 2346 | |
---|
[672b8ab] | 2347 | def currentState(self): |
---|
| 2348 | """ |
---|
| 2349 | Return fit page with current state |
---|
| 2350 | """ |
---|
| 2351 | new_page = FitPage() |
---|
| 2352 | self.saveToFitPage(new_page) |
---|
| 2353 | |
---|
| 2354 | return new_page |
---|
| 2355 | |
---|
| 2356 | def pushFitPage(self, new_page): |
---|
| 2357 | """ |
---|
| 2358 | Add a new fit page object with current state |
---|
| 2359 | """ |
---|
[6011788] | 2360 | self.page_stack.append(new_page) |
---|
[672b8ab] | 2361 | |
---|
| 2362 | def popFitPage(self): |
---|
| 2363 | """ |
---|
| 2364 | Remove top fit page from stack |
---|
| 2365 | """ |
---|
[6011788] | 2366 | if self.page_stack: |
---|
| 2367 | self.page_stack.pop() |
---|
[672b8ab] | 2368 | |
---|