[60af928] | 1 | import json |
---|
[cd31251] | 2 | import os |
---|
[60af928] | 3 | from collections import defaultdict |
---|
[b3e8629] | 4 | |
---|
[d4dac80] | 5 | import copy |
---|
[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 | |
---|
| 16 | from sasmodels import generate |
---|
| 17 | from sasmodels import modelinfo |
---|
[5236449] | 18 | from sasmodels.sasview_model import load_standard_models |
---|
[18d5c94a] | 19 | from sasmodels.sasview_model import MultiplicationModel |
---|
[358b39d] | 20 | from sasmodels.weights import MODELS as POLYDISPERSITY_MODELS |
---|
| 21 | |
---|
[f182f93] | 22 | from sas.sascalc.fit.BumpsFitting import BumpsFit as Fit |
---|
[57be490] | 23 | from sas.sascalc.fit.pagestate import PageState |
---|
[5236449] | 24 | |
---|
[83eb5208] | 25 | import sas.qtgui.Utilities.GuiUtils as GuiUtils |
---|
[14ec91c5] | 26 | import sas.qtgui.Utilities.LocalConfig as LocalConfig |
---|
[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 |
---|
[86d3207] | 30 | from sas.qtgui.Plotting.Plotter import PlotterWidget |
---|
[5236449] | 31 | |
---|
[1bc27f1] | 32 | from sas.qtgui.Perspectives.Fitting.UI.FittingWidgetUI import Ui_FittingWidgetUI |
---|
[dc5ef15] | 33 | from sas.qtgui.Perspectives.Fitting.FitThread import FitThread |
---|
[7adc2a8] | 34 | from sas.qtgui.Perspectives.Fitting.ConsoleUpdate import ConsoleUpdate |
---|
| 35 | |
---|
[dc5ef15] | 36 | from sas.qtgui.Perspectives.Fitting.ModelThread import Calc1D |
---|
| 37 | from sas.qtgui.Perspectives.Fitting.ModelThread import Calc2D |
---|
[4d457df] | 38 | from sas.qtgui.Perspectives.Fitting.FittingLogic import FittingLogic |
---|
| 39 | from sas.qtgui.Perspectives.Fitting import FittingUtilities |
---|
[3b3b40b] | 40 | from sas.qtgui.Perspectives.Fitting import ModelUtilities |
---|
[1bc27f1] | 41 | from sas.qtgui.Perspectives.Fitting.SmearingWidget import SmearingWidget |
---|
| 42 | from sas.qtgui.Perspectives.Fitting.OptionsWidget import OptionsWidget |
---|
| 43 | from sas.qtgui.Perspectives.Fitting.FitPage import FitPage |
---|
[ad6b4e2] | 44 | from sas.qtgui.Perspectives.Fitting.ViewDelegate import ModelViewDelegate |
---|
[6011788] | 45 | from sas.qtgui.Perspectives.Fitting.ViewDelegate import PolyViewDelegate |
---|
[b00414d] | 46 | from sas.qtgui.Perspectives.Fitting.ViewDelegate import MagnetismViewDelegate |
---|
[14ec91c5] | 47 | from sas.qtgui.Perspectives.Fitting.Constraint import Constraint |
---|
[eae226b] | 48 | from sas.qtgui.Perspectives.Fitting.MultiConstraint import MultiConstraint |
---|
[57be490] | 49 | from sas.qtgui.Perspectives.Fitting.ReportPageLogic import ReportPageLogic |
---|
| 50 | |
---|
[60af928] | 51 | TAB_MAGNETISM = 4 |
---|
| 52 | TAB_POLY = 3 |
---|
[cbcdd2c] | 53 | CATEGORY_DEFAULT = "Choose category..." |
---|
[4d457df] | 54 | CATEGORY_STRUCTURE = "Structure Factor" |
---|
[3b3b40b] | 55 | CATEGORY_CUSTOM = "Plugin Models" |
---|
[351b53e] | 56 | STRUCTURE_DEFAULT = "None" |
---|
[60af928] | 57 | |
---|
[358b39d] | 58 | DEFAULT_POLYDISP_FUNCTION = 'gaussian' |
---|
| 59 | |
---|
[aa82f54] | 60 | # CRUFT: remove when new release of sasmodels is available |
---|
| 61 | # https://github.com/SasView/sasview/pull/181#discussion_r218135162 |
---|
| 62 | from sasmodels.sasview_model import SasviewModel |
---|
| 63 | if not hasattr(SasviewModel, 'get_weights'): |
---|
| 64 | def get_weights(self, name): |
---|
[a8b3e2c] | 65 | """ |
---|
| 66 | Returns the polydispersity distribution for parameter *name* as *value* and *weight* arrays. |
---|
| 67 | """ |
---|
| 68 | # type: (str) -> Tuple(np.ndarray, np.ndarray) |
---|
| 69 | _, x, w = self._get_weights(self._model_info.parameters[name]) |
---|
| 70 | return x, w |
---|
[aa82f54] | 71 | |
---|
| 72 | SasviewModel.get_weights = get_weights |
---|
[7adc2a8] | 73 | |
---|
[dc71408] | 74 | logger = logging.getLogger(__name__) |
---|
| 75 | |
---|
[13cd397] | 76 | class ToolTippedItemModel(QtGui.QStandardItemModel): |
---|
[f54ce30] | 77 | """ |
---|
| 78 | Subclass from QStandardItemModel to allow displaying tooltips in |
---|
| 79 | QTableView model. |
---|
| 80 | """ |
---|
[d0dfcb2] | 81 | def __init__(self, parent=None): |
---|
[8e2cd79] | 82 | QtGui.QStandardItemModel.__init__(self, parent) |
---|
[13cd397] | 83 | |
---|
[fbfc488] | 84 | def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole): |
---|
[f54ce30] | 85 | """ |
---|
| 86 | Displays tooltip for each column's header |
---|
| 87 | :param section: |
---|
| 88 | :param orientation: |
---|
| 89 | :param role: |
---|
| 90 | :return: |
---|
| 91 | """ |
---|
[13cd397] | 92 | if role == QtCore.Qt.ToolTipRole: |
---|
| 93 | if orientation == QtCore.Qt.Horizontal: |
---|
[b3e8629] | 94 | return str(self.header_tooltips[section]) |
---|
[ca7c6bd] | 95 | |
---|
[a95c44b] | 96 | return QtGui.QStandardItemModel.headerData(self, section, orientation, role) |
---|
[13cd397] | 97 | |
---|
[4992ff2] | 98 | class FittingWidget(QtWidgets.QWidget, Ui_FittingWidgetUI): |
---|
[60af928] | 99 | """ |
---|
[f46f6dc] | 100 | Main widget for selecting form and structure factor models |
---|
[60af928] | 101 | """ |
---|
[be8f4b0] | 102 | constraintAddedSignal = QtCore.pyqtSignal(list) |
---|
| 103 | newModelSignal = QtCore.pyqtSignal() |
---|
[3b3b40b] | 104 | fittingFinishedSignal = QtCore.pyqtSignal(tuple) |
---|
| 105 | batchFittingFinishedSignal = QtCore.pyqtSignal(tuple) |
---|
[dcabba7] | 106 | Calc1DFinishedSignal = QtCore.pyqtSignal(dict) |
---|
| 107 | Calc2DFinishedSignal = QtCore.pyqtSignal(dict) |
---|
[3b3b40b] | 108 | |
---|
[672c0e97] | 109 | MAGNETIC_MODELS = ['sphere', 'core_shell_sphere', 'core_multi_shell', 'cylinder', 'parallelepiped'] |
---|
| 110 | |
---|
[1bc27f1] | 111 | def __init__(self, parent=None, data=None, tab_id=1): |
---|
[60af928] | 112 | |
---|
| 113 | super(FittingWidget, self).__init__() |
---|
| 114 | |
---|
[86f88d1] | 115 | # Necessary globals |
---|
[cbcdd2c] | 116 | self.parent = parent |
---|
[2a432e7] | 117 | |
---|
| 118 | # Which tab is this widget displayed in? |
---|
| 119 | self.tab_id = tab_id |
---|
| 120 | |
---|
[d2007a8] | 121 | import sys |
---|
| 122 | sys.excepthook = self.info |
---|
| 123 | |
---|
[2a432e7] | 124 | # Globals |
---|
| 125 | self.initializeGlobals() |
---|
| 126 | |
---|
[d4dac80] | 127 | # data index for the batch set |
---|
| 128 | self.data_index = 0 |
---|
| 129 | # Main Data[12]D holders |
---|
| 130 | # Logics.data contains a single Data1D/Data2D object |
---|
| 131 | self._logic = [FittingLogic()] |
---|
| 132 | |
---|
[2a432e7] | 133 | # Main GUI setup up |
---|
| 134 | self.setupUi(self) |
---|
| 135 | self.setWindowTitle("Fitting") |
---|
| 136 | |
---|
| 137 | # Set up tabs widgets |
---|
| 138 | self.initializeWidgets() |
---|
| 139 | |
---|
| 140 | # Set up models and views |
---|
| 141 | self.initializeModels() |
---|
| 142 | |
---|
| 143 | # Defaults for the structure factors |
---|
| 144 | self.setDefaultStructureCombo() |
---|
| 145 | |
---|
| 146 | # Make structure factor and model CBs disabled |
---|
| 147 | self.disableModelCombo() |
---|
| 148 | self.disableStructureCombo() |
---|
| 149 | |
---|
| 150 | # Generate the category list for display |
---|
| 151 | self.initializeCategoryCombo() |
---|
| 152 | |
---|
| 153 | # Initial control state |
---|
| 154 | self.initializeControls() |
---|
| 155 | |
---|
[ebfe223] | 156 | QtWidgets.QApplication.processEvents() |
---|
| 157 | |
---|
| 158 | # Connect signals to controls |
---|
| 159 | self.initializeSignals() |
---|
| 160 | |
---|
[d4dac80] | 161 | if data is not None: |
---|
| 162 | self.data = data |
---|
[2a432e7] | 163 | |
---|
[457d961] | 164 | # New font to display angstrom symbol |
---|
| 165 | new_font = 'font-family: -apple-system, "Helvetica Neue", "Ubuntu";' |
---|
| 166 | self.label_17.setStyleSheet(new_font) |
---|
| 167 | self.label_19.setStyleSheet(new_font) |
---|
| 168 | |
---|
[d2007a8] | 169 | def info(self, type, value, tb): |
---|
| 170 | logger.error("SasView threw exception: " + str(value)) |
---|
| 171 | traceback.print_exception(type, value, tb) |
---|
| 172 | |
---|
[d4dac80] | 173 | @property |
---|
| 174 | def logic(self): |
---|
| 175 | # make sure the logic contains at least one element |
---|
[8e2cd79] | 176 | assert self._logic |
---|
[d4dac80] | 177 | # logic connected to the currently shown data |
---|
| 178 | return self._logic[self.data_index] |
---|
[2a432e7] | 179 | |
---|
| 180 | @property |
---|
| 181 | def data(self): |
---|
| 182 | return self.logic.data |
---|
| 183 | |
---|
| 184 | @data.setter |
---|
| 185 | def data(self, value): |
---|
| 186 | """ data setter """ |
---|
[f7d14a1] | 187 | # Value is either a list of indices for batch fitting or a simple index |
---|
| 188 | # for standard fitting. Assure we have a list, regardless. |
---|
[ee18d33] | 189 | if isinstance(value, list): |
---|
| 190 | self.is_batch_fitting = True |
---|
| 191 | else: |
---|
| 192 | value = [value] |
---|
| 193 | |
---|
| 194 | assert isinstance(value[0], QtGui.QStandardItem) |
---|
| 195 | |
---|
| 196 | # Keep reference to all datasets for batch |
---|
| 197 | self.all_data = value |
---|
[2a432e7] | 198 | |
---|
[d4dac80] | 199 | # Create logics with data items |
---|
[f7d14a1] | 200 | # Logics.data contains only a single Data1D/Data2D object |
---|
[87dfca4] | 201 | if len(value) == 1: |
---|
| 202 | # single data logic is already defined, update data on it |
---|
| 203 | self._logic[0].data = GuiUtils.dataFromItem(value[0]) |
---|
| 204 | else: |
---|
| 205 | # batch datasets |
---|
[54492dc] | 206 | self._logic = [] |
---|
[87dfca4] | 207 | for data_item in value: |
---|
| 208 | logic = FittingLogic(data=GuiUtils.dataFromItem(data_item)) |
---|
| 209 | self._logic.append(logic) |
---|
[2a432e7] | 210 | |
---|
| 211 | # Overwrite data type descriptor |
---|
[339e22b] | 212 | |
---|
[2a432e7] | 213 | self.is2D = True if isinstance(self.logic.data, Data2D) else False |
---|
| 214 | |
---|
[f7d14a1] | 215 | # Let others know we're full of data now |
---|
[2a432e7] | 216 | self.data_is_loaded = True |
---|
| 217 | |
---|
| 218 | # Enable/disable UI components |
---|
| 219 | self.setEnablementOnDataLoad() |
---|
| 220 | |
---|
| 221 | def initializeGlobals(self): |
---|
| 222 | """ |
---|
| 223 | Initialize global variables used in this class |
---|
| 224 | """ |
---|
[cbcdd2c] | 225 | # SasModel is loaded |
---|
[60af928] | 226 | self.model_is_loaded = False |
---|
[cbcdd2c] | 227 | # Data[12]D passed and set |
---|
[5236449] | 228 | self.data_is_loaded = False |
---|
[ee18d33] | 229 | # Batch/single fitting |
---|
| 230 | self.is_batch_fitting = False |
---|
[7fd20fc] | 231 | self.is_chain_fitting = False |
---|
[ded5e77] | 232 | # Is the fit job running? |
---|
[8e2cd79] | 233 | self.fit_started = False |
---|
[ded5e77] | 234 | # The current fit thread |
---|
| 235 | self.calc_fit = None |
---|
[cbcdd2c] | 236 | # Current SasModel in view |
---|
[5236449] | 237 | self.kernel_module = None |
---|
[cbcdd2c] | 238 | # Current SasModel view dimension |
---|
[60af928] | 239 | self.is2D = False |
---|
[cbcdd2c] | 240 | # Current SasModel is multishell |
---|
[86f88d1] | 241 | self.model_has_shells = False |
---|
[cbcdd2c] | 242 | # Utility variable to enable unselectable option in category combobox |
---|
[86f88d1] | 243 | self._previous_category_index = 0 |
---|
[70f4458] | 244 | # Utility variables for multishell display |
---|
| 245 | self._n_shells_row = 0 |
---|
| 246 | self._num_shell_params = 0 |
---|
[cbcdd2c] | 247 | # Dictionary of {model name: model class} for the current category |
---|
[5236449] | 248 | self.models = {} |
---|
[f182f93] | 249 | # Parameters to fit |
---|
[6dbff18] | 250 | self.main_params_to_fit = [] |
---|
| 251 | self.poly_params_to_fit = [] |
---|
| 252 | self.magnet_params_to_fit = [] |
---|
| 253 | |
---|
[180bd54] | 254 | # Fit options |
---|
| 255 | self.q_range_min = 0.005 |
---|
| 256 | self.q_range_max = 0.1 |
---|
| 257 | self.npts = 25 |
---|
| 258 | self.log_points = False |
---|
| 259 | self.weighting = 0 |
---|
[2add354] | 260 | self.chi2 = None |
---|
[6011788] | 261 | # Does the control support UNDO/REDO |
---|
| 262 | # temporarily off |
---|
[2241130] | 263 | self.undo_supported = False |
---|
| 264 | self.page_stack = [] |
---|
[377ade1] | 265 | self.all_data = [] |
---|
[3b3b40b] | 266 | # custom plugin models |
---|
| 267 | # {model.name:model} |
---|
| 268 | self.custom_models = self.customModels() |
---|
[8222f171] | 269 | # Polydisp widget table default index for function combobox |
---|
| 270 | self.orig_poly_index = 3 |
---|
[d4dac80] | 271 | # copy of current kernel model |
---|
| 272 | self.kernel_module_copy = None |
---|
[6011788] | 273 | |
---|
[66d4370] | 274 | # dictionaries of current params |
---|
| 275 | self.poly_params = {} |
---|
| 276 | self.magnet_params = {} |
---|
| 277 | |
---|
[116dd4c1] | 278 | # Page id for fitting |
---|
| 279 | # To keep with previous SasView values, use 200 as the start offset |
---|
| 280 | self.page_id = 200 + self.tab_id |
---|
| 281 | |
---|
[d48cc19] | 282 | # Data for chosen model |
---|
| 283 | self.model_data = None |
---|
| 284 | |
---|
[a9b568c] | 285 | # Which shell is being currently displayed? |
---|
| 286 | self.current_shell_displayed = 0 |
---|
[0d13814] | 287 | # List of all shell-unique parameters |
---|
| 288 | self.shell_names = [] |
---|
[b00414d] | 289 | |
---|
| 290 | # Error column presence in parameter display |
---|
[f182f93] | 291 | self.has_error_column = False |
---|
[aca8418] | 292 | self.has_poly_error_column = False |
---|
[b00414d] | 293 | self.has_magnet_error_column = False |
---|
[a9b568c] | 294 | |
---|
[cb90b65] | 295 | # If the widget generated theory item, save it |
---|
| 296 | self.theory_item = None |
---|
| 297 | |
---|
[f37cab0] | 298 | # list column widths |
---|
| 299 | self.lstParamHeaderSizes = {} |
---|
| 300 | |
---|
[2a432e7] | 301 | # signal communicator |
---|
[cbcdd2c] | 302 | self.communicate = self.parent.communicate |
---|
[60af928] | 303 | |
---|
[2a432e7] | 304 | def initializeWidgets(self): |
---|
| 305 | """ |
---|
| 306 | Initialize widgets for tabs |
---|
| 307 | """ |
---|
[180bd54] | 308 | # Options widget |
---|
[4992ff2] | 309 | layout = QtWidgets.QGridLayout() |
---|
[180bd54] | 310 | self.options_widget = OptionsWidget(self, self.logic) |
---|
[1bc27f1] | 311 | layout.addWidget(self.options_widget) |
---|
[180bd54] | 312 | self.tabOptions.setLayout(layout) |
---|
| 313 | |
---|
[e1e3e09] | 314 | # Smearing widget |
---|
[4992ff2] | 315 | layout = QtWidgets.QGridLayout() |
---|
[e1e3e09] | 316 | self.smearing_widget = SmearingWidget(self) |
---|
[1bc27f1] | 317 | layout.addWidget(self.smearing_widget) |
---|
[180bd54] | 318 | self.tabResolution.setLayout(layout) |
---|
[e1e3e09] | 319 | |
---|
[b1e36a3] | 320 | # Define bold font for use in various controls |
---|
[1bc27f1] | 321 | self.boldFont = QtGui.QFont() |
---|
[a0f5c36] | 322 | self.boldFont.setBold(True) |
---|
| 323 | |
---|
| 324 | # Set data label |
---|
[b1e36a3] | 325 | self.label.setFont(self.boldFont) |
---|
| 326 | self.label.setText("No data loaded") |
---|
| 327 | self.lblFilename.setText("") |
---|
| 328 | |
---|
[6ff2eb3] | 329 | # Magnetic angles explained in one picture |
---|
[4992ff2] | 330 | self.magneticAnglesWidget = QtWidgets.QWidget() |
---|
| 331 | labl = QtWidgets.QLabel(self.magneticAnglesWidget) |
---|
[6d87082] | 332 | pixmap = QtGui.QPixmap(GuiUtils.IMAGES_DIRECTORY_LOCATION + '/M_angles_pic.png') |
---|
[6ff2eb3] | 333 | labl.setPixmap(pixmap) |
---|
| 334 | self.magneticAnglesWidget.setFixedSize(pixmap.width(), pixmap.height()) |
---|
| 335 | |
---|
[2a432e7] | 336 | def initializeModels(self): |
---|
| 337 | """ |
---|
| 338 | Set up models and views |
---|
| 339 | """ |
---|
[86f88d1] | 340 | # Set the main models |
---|
[cd31251] | 341 | # We can't use a single model here, due to restrictions on flattening |
---|
| 342 | # the model tree with subclassed QAbstractProxyModel... |
---|
[13cd397] | 343 | self._model_model = ToolTippedItemModel() |
---|
| 344 | self._poly_model = ToolTippedItemModel() |
---|
| 345 | self._magnet_model = ToolTippedItemModel() |
---|
[60af928] | 346 | |
---|
| 347 | # Param model displayed in param list |
---|
| 348 | self.lstParams.setModel(self._model_model) |
---|
[5236449] | 349 | self.readCategoryInfo() |
---|
[4992ff2] | 350 | |
---|
[60af928] | 351 | self.model_parameters = None |
---|
[ad6b4e2] | 352 | |
---|
| 353 | # Delegates for custom editing and display |
---|
| 354 | self.lstParams.setItemDelegate(ModelViewDelegate(self)) |
---|
| 355 | |
---|
[86f88d1] | 356 | self.lstParams.setAlternatingRowColors(True) |
---|
[61a92d4] | 357 | stylesheet = """ |
---|
[457d961] | 358 | |
---|
| 359 | QTreeView { |
---|
| 360 | paint-alternating-row-colors-for-empty-area:0; |
---|
| 361 | } |
---|
| 362 | |
---|
[97df8a9] | 363 | QTreeView::item { |
---|
| 364 | border: 1px; |
---|
[ebfe223] | 365 | padding: 2px 1px; |
---|
[97df8a9] | 366 | } |
---|
| 367 | |
---|
[2a432e7] | 368 | QTreeView::item:hover { |
---|
| 369 | background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #e7effd, stop: 1 #cbdaf1); |
---|
| 370 | border: 1px solid #bfcde4; |
---|
[61a92d4] | 371 | } |
---|
[2a432e7] | 372 | |
---|
| 373 | QTreeView::item:selected { |
---|
| 374 | border: 1px solid #567dbc; |
---|
| 375 | } |
---|
| 376 | |
---|
| 377 | QTreeView::item:selected:active{ |
---|
| 378 | background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #6ea1f1, stop: 1 #567dbc); |
---|
| 379 | } |
---|
| 380 | |
---|
| 381 | QTreeView::item:selected:!active { |
---|
| 382 | background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #6b9be8, stop: 1 #577fbf); |
---|
| 383 | } |
---|
| 384 | """ |
---|
[61a92d4] | 385 | self.lstParams.setStyleSheet(stylesheet) |
---|
[672b8ab] | 386 | self.lstParams.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) |
---|
[7fd20fc] | 387 | self.lstParams.customContextMenuRequested.connect(self.showModelContextMenu) |
---|
[457d961] | 388 | self.lstParams.setAttribute(QtCore.Qt.WA_MacShowFocusRect, False) |
---|
[f37cab0] | 389 | # Column resize signals |
---|
| 390 | self.lstParams.header().sectionResized.connect(self.onColumnWidthUpdate) |
---|
| 391 | |
---|
[60af928] | 392 | # Poly model displayed in poly list |
---|
[811bec1] | 393 | self.lstPoly.setModel(self._poly_model) |
---|
[60af928] | 394 | self.setPolyModel() |
---|
| 395 | self.setTableProperties(self.lstPoly) |
---|
[6011788] | 396 | # Delegates for custom editing and display |
---|
[aca8418] | 397 | self.lstPoly.setItemDelegate(PolyViewDelegate(self)) |
---|
| 398 | # Polydispersity function combo response |
---|
| 399 | self.lstPoly.itemDelegate().combo_updated.connect(self.onPolyComboIndexChange) |
---|
[e43fc91] | 400 | self.lstPoly.itemDelegate().filename_updated.connect(self.onPolyFilenameChange) |
---|
[60af928] | 401 | |
---|
| 402 | # Magnetism model displayed in magnetism list |
---|
| 403 | self.lstMagnetic.setModel(self._magnet_model) |
---|
| 404 | self.setMagneticModel() |
---|
| 405 | self.setTableProperties(self.lstMagnetic) |
---|
[b00414d] | 406 | # Delegates for custom editing and display |
---|
| 407 | self.lstMagnetic.setItemDelegate(MagnetismViewDelegate(self)) |
---|
[60af928] | 408 | |
---|
[2a432e7] | 409 | def initializeCategoryCombo(self): |
---|
| 410 | """ |
---|
| 411 | Model category combo setup |
---|
| 412 | """ |
---|
[60af928] | 413 | category_list = sorted(self.master_category_dict.keys()) |
---|
[86f88d1] | 414 | self.cbCategory.addItem(CATEGORY_DEFAULT) |
---|
[60af928] | 415 | self.cbCategory.addItems(category_list) |
---|
[3d18691] | 416 | if CATEGORY_STRUCTURE not in category_list: |
---|
| 417 | self.cbCategory.addItem(CATEGORY_STRUCTURE) |
---|
[6f7f652] | 418 | self.cbCategory.setCurrentIndex(0) |
---|
[60af928] | 419 | |
---|
[e1e3e09] | 420 | def setEnablementOnDataLoad(self): |
---|
| 421 | """ |
---|
| 422 | Enable/disable various UI elements based on data loaded |
---|
| 423 | """ |
---|
[cbcdd2c] | 424 | # Tag along functionality |
---|
[b1e36a3] | 425 | self.label.setText("Data loaded from: ") |
---|
[6b50296] | 426 | if self.logic.data.filename: |
---|
| 427 | self.lblFilename.setText(self.logic.data.filename) |
---|
| 428 | else: |
---|
| 429 | self.lblFilename.setText(self.logic.data.name) |
---|
[5236449] | 430 | self.updateQRange() |
---|
[e1e3e09] | 431 | # Switch off Data2D control |
---|
| 432 | self.chk2DView.setEnabled(False) |
---|
| 433 | self.chk2DView.setVisible(False) |
---|
[672c0e97] | 434 | self.chkMagnetism.setEnabled(False) |
---|
[e20870bc] | 435 | self.tabFitting.setTabEnabled(TAB_MAGNETISM, self.chkMagnetism.isChecked()) |
---|
[ee18d33] | 436 | # Combo box or label for file name" |
---|
| 437 | if self.is_batch_fitting: |
---|
| 438 | self.lblFilename.setVisible(False) |
---|
| 439 | for dataitem in self.all_data: |
---|
| 440 | filename = GuiUtils.dataFromItem(dataitem).filename |
---|
| 441 | self.cbFileNames.addItem(filename) |
---|
| 442 | self.cbFileNames.setVisible(True) |
---|
[7fd20fc] | 443 | self.chkChainFit.setEnabled(True) |
---|
| 444 | self.chkChainFit.setVisible(True) |
---|
[38eb433] | 445 | # This panel is not designed to view individual fits, so disable plotting |
---|
| 446 | self.cmdPlot.setVisible(False) |
---|
[180bd54] | 447 | # Similarly on other tabs |
---|
| 448 | self.options_widget.setEnablementOnDataLoad() |
---|
[f7d14a1] | 449 | self.onSelectModel() |
---|
[e1e3e09] | 450 | # Smearing tab |
---|
[9a7c81c] | 451 | self.smearing_widget.updateData(self.data) |
---|
[60af928] | 452 | |
---|
[f46f6dc] | 453 | def acceptsData(self): |
---|
| 454 | """ Tells the caller this widget can accept new dataset """ |
---|
[5236449] | 455 | return not self.data_is_loaded |
---|
[f46f6dc] | 456 | |
---|
[6f7f652] | 457 | def disableModelCombo(self): |
---|
[cbcdd2c] | 458 | """ Disable the combobox """ |
---|
[6f7f652] | 459 | self.cbModel.setEnabled(False) |
---|
[b1e36a3] | 460 | self.lblModel.setEnabled(False) |
---|
[6f7f652] | 461 | |
---|
| 462 | def enableModelCombo(self): |
---|
[cbcdd2c] | 463 | """ Enable the combobox """ |
---|
[6f7f652] | 464 | self.cbModel.setEnabled(True) |
---|
[b1e36a3] | 465 | self.lblModel.setEnabled(True) |
---|
[6f7f652] | 466 | |
---|
| 467 | def disableStructureCombo(self): |
---|
[cbcdd2c] | 468 | """ Disable the combobox """ |
---|
[6f7f652] | 469 | self.cbStructureFactor.setEnabled(False) |
---|
[b1e36a3] | 470 | self.lblStructure.setEnabled(False) |
---|
[6f7f652] | 471 | |
---|
| 472 | def enableStructureCombo(self): |
---|
[cbcdd2c] | 473 | """ Enable the combobox """ |
---|
[6f7f652] | 474 | self.cbStructureFactor.setEnabled(True) |
---|
[b1e36a3] | 475 | self.lblStructure.setEnabled(True) |
---|
[6f7f652] | 476 | |
---|
[0268aed] | 477 | def togglePoly(self, isChecked): |
---|
[454670d] | 478 | """ Enable/disable the polydispersity tab """ |
---|
[0268aed] | 479 | self.tabFitting.setTabEnabled(TAB_POLY, isChecked) |
---|
[d4216ac] | 480 | # Check if any parameters are ready for fitting |
---|
| 481 | self.cmdFit.setEnabled(self.haveParamsToFit()) |
---|
[0268aed] | 482 | |
---|
| 483 | def toggleMagnetism(self, isChecked): |
---|
[454670d] | 484 | """ Enable/disable the magnetism tab """ |
---|
[0268aed] | 485 | self.tabFitting.setTabEnabled(TAB_MAGNETISM, isChecked) |
---|
[d4216ac] | 486 | # Check if any parameters are ready for fitting |
---|
| 487 | self.cmdFit.setEnabled(self.haveParamsToFit()) |
---|
[0268aed] | 488 | |
---|
[7fd20fc] | 489 | def toggleChainFit(self, isChecked): |
---|
| 490 | """ Enable/disable chain fitting """ |
---|
| 491 | self.is_chain_fitting = isChecked |
---|
| 492 | |
---|
[0268aed] | 493 | def toggle2D(self, isChecked): |
---|
[454670d] | 494 | """ Enable/disable the controls dependent on 1D/2D data instance """ |
---|
[0268aed] | 495 | self.chkMagnetism.setEnabled(isChecked) |
---|
| 496 | self.is2D = isChecked |
---|
[1970780] | 497 | # Reload the current model |
---|
[e1e3e09] | 498 | if self.kernel_module: |
---|
| 499 | self.onSelectModel() |
---|
[5236449] | 500 | |
---|
[8b480d27] | 501 | @classmethod |
---|
| 502 | def customModels(cls): |
---|
[3b3b40b] | 503 | """ Reads in file names in the custom plugin directory """ |
---|
| 504 | return ModelUtilities._find_models() |
---|
| 505 | |
---|
[86f88d1] | 506 | def initializeControls(self): |
---|
| 507 | """ |
---|
| 508 | Set initial control enablement |
---|
| 509 | """ |
---|
[ee18d33] | 510 | self.cbFileNames.setVisible(False) |
---|
[86f88d1] | 511 | self.cmdFit.setEnabled(False) |
---|
[d48cc19] | 512 | self.cmdPlot.setEnabled(False) |
---|
[180bd54] | 513 | self.options_widget.cmdComputePoints.setVisible(False) # probably redundant |
---|
[86f88d1] | 514 | self.chkPolydispersity.setEnabled(True) |
---|
| 515 | self.chkPolydispersity.setCheckState(False) |
---|
| 516 | self.chk2DView.setEnabled(True) |
---|
| 517 | self.chk2DView.setCheckState(False) |
---|
| 518 | self.chkMagnetism.setEnabled(False) |
---|
| 519 | self.chkMagnetism.setCheckState(False) |
---|
[7fd20fc] | 520 | self.chkChainFit.setEnabled(False) |
---|
| 521 | self.chkChainFit.setVisible(False) |
---|
[cbcdd2c] | 522 | # Tabs |
---|
[86f88d1] | 523 | self.tabFitting.setTabEnabled(TAB_POLY, False) |
---|
| 524 | self.tabFitting.setTabEnabled(TAB_MAGNETISM, False) |
---|
| 525 | self.lblChi2Value.setText("---") |
---|
[e1e3e09] | 526 | # Smearing tab |
---|
[9a7c81c] | 527 | self.smearing_widget.updateData(self.data) |
---|
[180bd54] | 528 | # Line edits in the option tab |
---|
| 529 | self.updateQRange() |
---|
[86f88d1] | 530 | |
---|
| 531 | def initializeSignals(self): |
---|
| 532 | """ |
---|
| 533 | Connect GUI element signals |
---|
| 534 | """ |
---|
[cbcdd2c] | 535 | # Comboboxes |
---|
[cd31251] | 536 | self.cbStructureFactor.currentIndexChanged.connect(self.onSelectStructureFactor) |
---|
| 537 | self.cbCategory.currentIndexChanged.connect(self.onSelectCategory) |
---|
| 538 | self.cbModel.currentIndexChanged.connect(self.onSelectModel) |
---|
[ee18d33] | 539 | self.cbFileNames.currentIndexChanged.connect(self.onSelectBatchFilename) |
---|
[cbcdd2c] | 540 | # Checkboxes |
---|
[86f88d1] | 541 | self.chk2DView.toggled.connect(self.toggle2D) |
---|
| 542 | self.chkPolydispersity.toggled.connect(self.togglePoly) |
---|
| 543 | self.chkMagnetism.toggled.connect(self.toggleMagnetism) |
---|
[7fd20fc] | 544 | self.chkChainFit.toggled.connect(self.toggleChainFit) |
---|
[cbcdd2c] | 545 | # Buttons |
---|
[5236449] | 546 | self.cmdFit.clicked.connect(self.onFit) |
---|
[cbcdd2c] | 547 | self.cmdPlot.clicked.connect(self.onPlot) |
---|
[2add354] | 548 | self.cmdHelp.clicked.connect(self.onHelp) |
---|
[6ff2eb3] | 549 | self.cmdMagneticDisplay.clicked.connect(self.onDisplayMagneticAngles) |
---|
[cbcdd2c] | 550 | |
---|
| 551 | # Respond to change in parameters from the UI |
---|
[d2007a8] | 552 | self._model_model.dataChanged.connect(self.onMainParamsChange) |
---|
| 553 | self._poly_model.dataChanged.connect(self.onPolyModelChange) |
---|
| 554 | self._magnet_model.dataChanged.connect(self.onMagnetModelChange) |
---|
[3b3b40b] | 555 | self.lstParams.selectionModel().selectionChanged.connect(self.onSelectionChanged) |
---|
| 556 | |
---|
| 557 | # Local signals |
---|
| 558 | self.batchFittingFinishedSignal.connect(self.batchFitComplete) |
---|
| 559 | self.fittingFinishedSignal.connect(self.fitComplete) |
---|
[d4dac80] | 560 | self.Calc1DFinishedSignal.connect(self.complete1D) |
---|
| 561 | self.Calc2DFinishedSignal.connect(self.complete2D) |
---|
[86f88d1] | 562 | |
---|
[180bd54] | 563 | # Signals from separate tabs asking for replot |
---|
| 564 | self.options_widget.plot_signal.connect(self.onOptionsUpdate) |
---|
| 565 | |
---|
[3b3b40b] | 566 | # Signals from other widgets |
---|
| 567 | self.communicate.customModelDirectoryChanged.connect(self.onCustomModelChange) |
---|
[57be490] | 568 | self.communicate.saveAnalysisSignal.connect(self.savePageState) |
---|
[9a42ea1] | 569 | #self.communicate.loadAnalysisSignal.connect(self.loadPageState) |
---|
[9a7c81c] | 570 | self.smearing_widget.smearingChangedSignal.connect(self.onSmearingOptionsUpdate) |
---|
[3b3b40b] | 571 | |
---|
[3d18691] | 572 | # Communicator signal |
---|
| 573 | self.communicate.updateModelCategoriesSignal.connect(self.onCategoriesChanged) |
---|
| 574 | |
---|
[d3c0b95] | 575 | def modelName(self): |
---|
| 576 | """ |
---|
| 577 | Returns model name, by default M<tab#>, e.g. M1, M2 |
---|
| 578 | """ |
---|
| 579 | return "M%i" % self.tab_id |
---|
| 580 | |
---|
| 581 | def nameForFittedData(self, name): |
---|
| 582 | """ |
---|
| 583 | Generate name for the current fit |
---|
| 584 | """ |
---|
| 585 | if self.is2D: |
---|
| 586 | name += "2d" |
---|
| 587 | name = "%s [%s]" % (self.modelName(), name) |
---|
| 588 | return name |
---|
[7fd20fc] | 589 | |
---|
[d3c0b95] | 590 | def showModelContextMenu(self, position): |
---|
| 591 | """ |
---|
| 592 | Show context specific menu in the parameter table. |
---|
| 593 | When clicked on parameter(s): fitting/constraints options |
---|
| 594 | When clicked on white space: model description |
---|
| 595 | """ |
---|
[50cafe7] | 596 | rows = [s.row() for s in self.lstParams.selectionModel().selectedRows() |
---|
| 597 | if self.isCheckable(s.row())] |
---|
[7fd20fc] | 598 | menu = self.showModelDescription() if not rows else self.modelContextMenu(rows) |
---|
| 599 | try: |
---|
| 600 | menu.exec_(self.lstParams.viewport().mapToGlobal(position)) |
---|
| 601 | except AttributeError as ex: |
---|
[bb477f5] | 602 | logger.error("Error generating context menu: %s" % ex) |
---|
[7fd20fc] | 603 | return |
---|
| 604 | |
---|
| 605 | def modelContextMenu(self, rows): |
---|
[eae226b] | 606 | """ |
---|
[d3c0b95] | 607 | Create context menu for the parameter selection |
---|
[eae226b] | 608 | """ |
---|
[7fd20fc] | 609 | menu = QtWidgets.QMenu() |
---|
[eae226b] | 610 | num_rows = len(rows) |
---|
[63319b0] | 611 | if num_rows < 1: |
---|
| 612 | return menu |
---|
[7fd20fc] | 613 | # Select for fitting |
---|
[8e2cd79] | 614 | param_string = "parameter " if num_rows == 1 else "parameters " |
---|
| 615 | to_string = "to its current value" if num_rows == 1 else "to their current values" |
---|
[d3c0b95] | 616 | has_constraints = any([self.rowHasConstraint(i) for i in rows]) |
---|
[eae226b] | 617 | |
---|
[7fd20fc] | 618 | self.actionSelect = QtWidgets.QAction(self) |
---|
| 619 | self.actionSelect.setObjectName("actionSelect") |
---|
[eae226b] | 620 | self.actionSelect.setText(QtCore.QCoreApplication.translate("self", "Select "+param_string+" for fitting")) |
---|
[7fd20fc] | 621 | # Unselect from fitting |
---|
| 622 | self.actionDeselect = QtWidgets.QAction(self) |
---|
| 623 | self.actionDeselect.setObjectName("actionDeselect") |
---|
[eae226b] | 624 | self.actionDeselect.setText(QtCore.QCoreApplication.translate("self", "De-select "+param_string+" from fitting")) |
---|
[7fd20fc] | 625 | |
---|
| 626 | self.actionConstrain = QtWidgets.QAction(self) |
---|
| 627 | self.actionConstrain.setObjectName("actionConstrain") |
---|
[eae226b] | 628 | self.actionConstrain.setText(QtCore.QCoreApplication.translate("self", "Constrain "+param_string + to_string)) |
---|
| 629 | |
---|
| 630 | self.actionRemoveConstraint = QtWidgets.QAction(self) |
---|
| 631 | self.actionRemoveConstraint.setObjectName("actionRemoveConstrain") |
---|
| 632 | self.actionRemoveConstraint.setText(QtCore.QCoreApplication.translate("self", "Remove constraint")) |
---|
[7fd20fc] | 633 | |
---|
| 634 | self.actionMultiConstrain = QtWidgets.QAction(self) |
---|
| 635 | self.actionMultiConstrain.setObjectName("actionMultiConstrain") |
---|
| 636 | self.actionMultiConstrain.setText(QtCore.QCoreApplication.translate("self", "Constrain selected parameters to their current values")) |
---|
| 637 | |
---|
| 638 | self.actionMutualMultiConstrain = QtWidgets.QAction(self) |
---|
| 639 | self.actionMutualMultiConstrain.setObjectName("actionMutualMultiConstrain") |
---|
| 640 | self.actionMutualMultiConstrain.setText(QtCore.QCoreApplication.translate("self", "Mutual constrain of selected parameters...")) |
---|
| 641 | |
---|
| 642 | menu.addAction(self.actionSelect) |
---|
| 643 | menu.addAction(self.actionDeselect) |
---|
| 644 | menu.addSeparator() |
---|
| 645 | |
---|
[d3c0b95] | 646 | if has_constraints: |
---|
[eae226b] | 647 | menu.addAction(self.actionRemoveConstraint) |
---|
[d3c0b95] | 648 | #if num_rows == 1: |
---|
| 649 | # menu.addAction(self.actionEditConstraint) |
---|
[eae226b] | 650 | else: |
---|
[7fd20fc] | 651 | menu.addAction(self.actionConstrain) |
---|
[d3c0b95] | 652 | if num_rows == 2: |
---|
| 653 | menu.addAction(self.actionMutualMultiConstrain) |
---|
[7fd20fc] | 654 | |
---|
| 655 | # Define the callbacks |
---|
[0595bb7] | 656 | self.actionConstrain.triggered.connect(self.addSimpleConstraint) |
---|
[eae226b] | 657 | self.actionRemoveConstraint.triggered.connect(self.deleteConstraint) |
---|
[0595bb7] | 658 | self.actionMutualMultiConstrain.triggered.connect(self.showMultiConstraint) |
---|
[7fd20fc] | 659 | self.actionSelect.triggered.connect(self.selectParameters) |
---|
| 660 | self.actionDeselect.triggered.connect(self.deselectParameters) |
---|
| 661 | return menu |
---|
| 662 | |
---|
[0595bb7] | 663 | def showMultiConstraint(self): |
---|
[7fd20fc] | 664 | """ |
---|
| 665 | Show the constraint widget and receive the expression |
---|
| 666 | """ |
---|
[0595bb7] | 667 | selected_rows = self.lstParams.selectionModel().selectedRows() |
---|
[6e58f2f] | 668 | # There have to be only two rows selected. The caller takes care of that |
---|
| 669 | # but let's check the correctness. |
---|
[8e2cd79] | 670 | assert len(selected_rows) == 2 |
---|
[0595bb7] | 671 | |
---|
| 672 | params_list = [s.data() for s in selected_rows] |
---|
[eae226b] | 673 | # Create and display the widget for param1 and param2 |
---|
[7fd20fc] | 674 | mc_widget = MultiConstraint(self, params=params_list) |
---|
[305114c] | 675 | # Check if any of the parameters are polydisperse |
---|
| 676 | if not np.any([FittingUtilities.isParamPolydisperse(p, self.model_parameters, is2D=self.is2D) for p in params_list]): |
---|
| 677 | # no parameters are pd - reset the text to not show the warning |
---|
| 678 | mc_widget.lblWarning.setText("") |
---|
[eae226b] | 679 | if mc_widget.exec_() != QtWidgets.QDialog.Accepted: |
---|
| 680 | return |
---|
| 681 | |
---|
[0595bb7] | 682 | constraint = Constraint() |
---|
| 683 | c_text = mc_widget.txtConstraint.text() |
---|
| 684 | |
---|
[eae226b] | 685 | # widget.params[0] is the parameter we're constraining |
---|
| 686 | constraint.param = mc_widget.params[0] |
---|
[3b3b40b] | 687 | # parameter should have the model name preamble |
---|
[06234fc] | 688 | model_name = self.kernel_module.name |
---|
[3b3b40b] | 689 | # param_used is the parameter we're using in constraining function |
---|
| 690 | param_used = mc_widget.params[1] |
---|
| 691 | # Replace param_used with model_name.param_used |
---|
| 692 | updated_param_used = model_name + "." + param_used |
---|
| 693 | new_func = c_text.replace(param_used, updated_param_used) |
---|
| 694 | constraint.func = new_func |
---|
[d3c0b95] | 695 | # Which row is the constrained parameter in? |
---|
[2d466e4] | 696 | row = self.getRowFromName(constraint.param) |
---|
[eae226b] | 697 | |
---|
[6e58f2f] | 698 | # Create a new item and add the Constraint object as a child |
---|
| 699 | self.addConstraintToRow(constraint=constraint, row=row) |
---|
[eae226b] | 700 | |
---|
[2d466e4] | 701 | def getRowFromName(self, name): |
---|
[eae226b] | 702 | """ |
---|
[d3c0b95] | 703 | Given parameter name get the row number in self._model_model |
---|
[eae226b] | 704 | """ |
---|
| 705 | for row in range(self._model_model.rowCount()): |
---|
| 706 | row_name = self._model_model.item(row).text() |
---|
| 707 | if row_name == name: |
---|
| 708 | return row |
---|
| 709 | return None |
---|
| 710 | |
---|
[2d466e4] | 711 | def getParamNames(self): |
---|
| 712 | """ |
---|
| 713 | Return list of all parameters for the current model |
---|
| 714 | """ |
---|
[00b7ddf0] | 715 | return [self._model_model.item(row).text() |
---|
| 716 | for row in range(self._model_model.rowCount()) |
---|
| 717 | if self.isCheckable(row)] |
---|
[2d466e4] | 718 | |
---|
[eae226b] | 719 | def modifyViewOnRow(self, row, font=None, brush=None): |
---|
| 720 | """ |
---|
| 721 | Chage how the given row of the main model is shown |
---|
| 722 | """ |
---|
| 723 | fields_enabled = False |
---|
| 724 | if font is None: |
---|
| 725 | font = QtGui.QFont() |
---|
| 726 | fields_enabled = True |
---|
| 727 | if brush is None: |
---|
| 728 | brush = QtGui.QBrush() |
---|
| 729 | fields_enabled = True |
---|
[0595bb7] | 730 | self._model_model.blockSignals(True) |
---|
| 731 | # Modify font and foreground of affected rows |
---|
| 732 | for column in range(0, self._model_model.columnCount()): |
---|
| 733 | self._model_model.item(row, column).setForeground(brush) |
---|
| 734 | self._model_model.item(row, column).setFont(font) |
---|
[eae226b] | 735 | self._model_model.item(row, column).setEditable(fields_enabled) |
---|
[0595bb7] | 736 | self._model_model.blockSignals(False) |
---|
| 737 | |
---|
[c5a2722f] | 738 | def addConstraintToRow(self, constraint=None, row=0): |
---|
| 739 | """ |
---|
| 740 | Adds the constraint object to requested row |
---|
| 741 | """ |
---|
| 742 | # Create a new item and add the Constraint object as a child |
---|
[8e2cd79] | 743 | assert isinstance(constraint, Constraint) |
---|
| 744 | assert 0 <= row <= self._model_model.rowCount() |
---|
[00b7ddf0] | 745 | assert self.isCheckable(row) |
---|
[c5a2722f] | 746 | |
---|
| 747 | item = QtGui.QStandardItem() |
---|
| 748 | item.setData(constraint) |
---|
| 749 | self._model_model.item(row, 1).setChild(0, item) |
---|
| 750 | # Set min/max to the value constrained |
---|
| 751 | self.constraintAddedSignal.emit([row]) |
---|
| 752 | # Show visual hints for the constraint |
---|
| 753 | font = QtGui.QFont() |
---|
| 754 | font.setItalic(True) |
---|
| 755 | brush = QtGui.QBrush(QtGui.QColor('blue')) |
---|
| 756 | self.modifyViewOnRow(row, font=font, brush=brush) |
---|
| 757 | self.communicate.statusBarUpdateSignal.emit('Constraint added') |
---|
| 758 | |
---|
[0595bb7] | 759 | def addSimpleConstraint(self): |
---|
[7fd20fc] | 760 | """ |
---|
| 761 | Adds a constraint on a single parameter. |
---|
[2add354] | 762 | """ |
---|
[d3c0b95] | 763 | min_col = self.lstParams.itemDelegate().param_min |
---|
| 764 | max_col = self.lstParams.itemDelegate().param_max |
---|
[0595bb7] | 765 | for row in self.selectedParameters(): |
---|
[00b7ddf0] | 766 | assert(self.isCheckable(row)) |
---|
[0595bb7] | 767 | param = self._model_model.item(row, 0).text() |
---|
| 768 | value = self._model_model.item(row, 1).text() |
---|
[235d766] | 769 | min_t = self._model_model.item(row, min_col).text() |
---|
| 770 | max_t = self._model_model.item(row, max_col).text() |
---|
[eae226b] | 771 | # Create a Constraint object |
---|
[235d766] | 772 | constraint = Constraint(param=param, value=value, min=min_t, max=max_t) |
---|
[eae226b] | 773 | # Create a new item and add the Constraint object as a child |
---|
[0595bb7] | 774 | item = QtGui.QStandardItem() |
---|
| 775 | item.setData(constraint) |
---|
| 776 | self._model_model.item(row, 1).setChild(0, item) |
---|
[235d766] | 777 | # Assumed correctness from the validator |
---|
| 778 | value = float(value) |
---|
| 779 | # BUMPS calculates log(max-min) without any checks, so let's assign minor range |
---|
| 780 | min_v = value - (value/10000.0) |
---|
| 781 | max_v = value + (value/10000.0) |
---|
[eae226b] | 782 | # Set min/max to the value constrained |
---|
[235d766] | 783 | self._model_model.item(row, min_col).setText(str(min_v)) |
---|
| 784 | self._model_model.item(row, max_col).setText(str(max_v)) |
---|
[be8f4b0] | 785 | self.constraintAddedSignal.emit([row]) |
---|
[eae226b] | 786 | # Show visual hints for the constraint |
---|
| 787 | font = QtGui.QFont() |
---|
| 788 | font.setItalic(True) |
---|
| 789 | brush = QtGui.QBrush(QtGui.QColor('blue')) |
---|
| 790 | self.modifyViewOnRow(row, font=font, brush=brush) |
---|
[7fd20fc] | 791 | self.communicate.statusBarUpdateSignal.emit('Constraint added') |
---|
| 792 | |
---|
[eae226b] | 793 | def deleteConstraint(self): |
---|
| 794 | """ |
---|
| 795 | Delete constraints from selected parameters. |
---|
| 796 | """ |
---|
[8e2cd79] | 797 | params = [s.data() for s in self.lstParams.selectionModel().selectedRows() |
---|
[3b3b40b] | 798 | if self.isCheckable(s.row())] |
---|
| 799 | for param in params: |
---|
| 800 | self.deleteConstraintOnParameter(param=param) |
---|
[be8f4b0] | 801 | |
---|
| 802 | def deleteConstraintOnParameter(self, param=None): |
---|
| 803 | """ |
---|
| 804 | Delete the constraint on model parameter 'param' |
---|
| 805 | """ |
---|
[d3c0b95] | 806 | min_col = self.lstParams.itemDelegate().param_min |
---|
| 807 | max_col = self.lstParams.itemDelegate().param_max |
---|
[be8f4b0] | 808 | for row in range(self._model_model.rowCount()): |
---|
[00b7ddf0] | 809 | if not self.isCheckable(row): |
---|
| 810 | continue |
---|
[3b3b40b] | 811 | if not self.rowHasConstraint(row): |
---|
| 812 | continue |
---|
[eae226b] | 813 | # Get the Constraint object from of the model item |
---|
| 814 | item = self._model_model.item(row, 1) |
---|
[3b3b40b] | 815 | constraint = self.getConstraintForRow(row) |
---|
[d3c0b95] | 816 | if constraint is None: |
---|
| 817 | continue |
---|
| 818 | if not isinstance(constraint, Constraint): |
---|
| 819 | continue |
---|
[be8f4b0] | 820 | if param and constraint.param != param: |
---|
| 821 | continue |
---|
| 822 | # Now we got the right row. Delete the constraint and clean up |
---|
[eae226b] | 823 | # Retrieve old values and put them on the model |
---|
| 824 | if constraint.min is not None: |
---|
[d3c0b95] | 825 | self._model_model.item(row, min_col).setText(constraint.min) |
---|
[eae226b] | 826 | if constraint.max is not None: |
---|
[d3c0b95] | 827 | self._model_model.item(row, max_col).setText(constraint.max) |
---|
[eae226b] | 828 | # Remove constraint item |
---|
| 829 | item.removeRow(0) |
---|
[be8f4b0] | 830 | self.constraintAddedSignal.emit([row]) |
---|
[eae226b] | 831 | self.modifyViewOnRow(row) |
---|
[be8f4b0] | 832 | |
---|
[eae226b] | 833 | self.communicate.statusBarUpdateSignal.emit('Constraint removed') |
---|
[be8f4b0] | 834 | |
---|
[d3c0b95] | 835 | def getConstraintForRow(self, row): |
---|
| 836 | """ |
---|
[c4b23dd] | 837 | For the given row, return its constraint, if any (otherwise None) |
---|
[d3c0b95] | 838 | """ |
---|
[c4b23dd] | 839 | if not self.isCheckable(row): |
---|
| 840 | return None |
---|
| 841 | item = self._model_model.item(row, 1) |
---|
| 842 | try: |
---|
| 843 | return item.child(0).data() |
---|
| 844 | except AttributeError: |
---|
| 845 | return None |
---|
[d3c0b95] | 846 | |
---|
[eae226b] | 847 | def rowHasConstraint(self, row): |
---|
| 848 | """ |
---|
| 849 | Finds out if row of the main model has a constraint child |
---|
| 850 | """ |
---|
[c4b23dd] | 851 | if not self.isCheckable(row): |
---|
| 852 | return False |
---|
| 853 | item = self._model_model.item(row, 1) |
---|
| 854 | if not item.hasChildren(): |
---|
| 855 | return False |
---|
| 856 | c = item.child(0).data() |
---|
| 857 | if isinstance(c, Constraint): |
---|
| 858 | return True |
---|
[be8f4b0] | 859 | return False |
---|
[116dd4c1] | 860 | |
---|
| 861 | def rowHasActiveConstraint(self, row): |
---|
| 862 | """ |
---|
| 863 | Finds out if row of the main model has an active constraint child |
---|
| 864 | """ |
---|
[c4b23dd] | 865 | if not self.isCheckable(row): |
---|
| 866 | return False |
---|
| 867 | item = self._model_model.item(row, 1) |
---|
| 868 | if not item.hasChildren(): |
---|
| 869 | return False |
---|
| 870 | c = item.child(0).data() |
---|
| 871 | if isinstance(c, Constraint) and c.active: |
---|
| 872 | return True |
---|
[235d766] | 873 | return False |
---|
| 874 | |
---|
| 875 | def rowHasActiveComplexConstraint(self, row): |
---|
| 876 | """ |
---|
| 877 | Finds out if row of the main model has an active, nontrivial constraint child |
---|
| 878 | """ |
---|
[c4b23dd] | 879 | if not self.isCheckable(row): |
---|
| 880 | return False |
---|
| 881 | item = self._model_model.item(row, 1) |
---|
| 882 | if not item.hasChildren(): |
---|
| 883 | return False |
---|
| 884 | c = item.child(0).data() |
---|
| 885 | if isinstance(c, Constraint) and c.func and c.active: |
---|
| 886 | return True |
---|
[116dd4c1] | 887 | return False |
---|
[eae226b] | 888 | |
---|
[7fd20fc] | 889 | def selectParameters(self): |
---|
| 890 | """ |
---|
[d3c0b95] | 891 | Selected parameter is chosen for fitting |
---|
[7fd20fc] | 892 | """ |
---|
| 893 | status = QtCore.Qt.Checked |
---|
| 894 | self.setParameterSelection(status) |
---|
| 895 | |
---|
| 896 | def deselectParameters(self): |
---|
| 897 | """ |
---|
| 898 | Selected parameters are removed for fitting |
---|
| 899 | """ |
---|
| 900 | status = QtCore.Qt.Unchecked |
---|
| 901 | self.setParameterSelection(status) |
---|
| 902 | |
---|
| 903 | def selectedParameters(self): |
---|
| 904 | """ Returns list of selected (highlighted) parameters """ |
---|
[d3c0b95] | 905 | return [s.row() for s in self.lstParams.selectionModel().selectedRows() |
---|
| 906 | if self.isCheckable(s.row())] |
---|
[7fd20fc] | 907 | |
---|
| 908 | def setParameterSelection(self, status=QtCore.Qt.Unchecked): |
---|
| 909 | """ |
---|
| 910 | Selected parameters are chosen for fitting |
---|
| 911 | """ |
---|
| 912 | # Convert to proper indices and set requested enablement |
---|
| 913 | for row in self.selectedParameters(): |
---|
| 914 | self._model_model.item(row, 0).setCheckState(status) |
---|
[d3c0b95] | 915 | |
---|
| 916 | def getConstraintsForModel(self): |
---|
| 917 | """ |
---|
| 918 | Return a list of tuples. Each tuple contains constraints mapped as |
---|
| 919 | ('constrained parameter', 'function to constrain') |
---|
| 920 | e.g. [('sld','5*sld_solvent')] |
---|
| 921 | """ |
---|
| 922 | param_number = self._model_model.rowCount() |
---|
| 923 | params = [(self._model_model.item(s, 0).text(), |
---|
[c5a2722f] | 924 | self._model_model.item(s, 1).child(0).data().func) |
---|
[116dd4c1] | 925 | for s in range(param_number) if self.rowHasActiveConstraint(s)] |
---|
[d3c0b95] | 926 | return params |
---|
[7fd20fc] | 927 | |
---|
[235d766] | 928 | def getComplexConstraintsForModel(self): |
---|
| 929 | """ |
---|
| 930 | Return a list of tuples. Each tuple contains constraints mapped as |
---|
| 931 | ('constrained parameter', 'function to constrain') |
---|
[06234fc] | 932 | e.g. [('sld','5*M2.sld_solvent')]. |
---|
[235d766] | 933 | Only for constraints with defined VALUE |
---|
| 934 | """ |
---|
| 935 | param_number = self._model_model.rowCount() |
---|
| 936 | params = [(self._model_model.item(s, 0).text(), |
---|
| 937 | self._model_model.item(s, 1).child(0).data().func) |
---|
| 938 | for s in range(param_number) if self.rowHasActiveComplexConstraint(s)] |
---|
| 939 | return params |
---|
| 940 | |
---|
[ba01ad1] | 941 | def getConstraintObjectsForModel(self): |
---|
| 942 | """ |
---|
| 943 | Returns Constraint objects present on the whole model |
---|
| 944 | """ |
---|
| 945 | param_number = self._model_model.rowCount() |
---|
| 946 | constraints = [self._model_model.item(s, 1).child(0).data() |
---|
| 947 | for s in range(param_number) if self.rowHasConstraint(s)] |
---|
| 948 | |
---|
| 949 | return constraints |
---|
| 950 | |
---|
[3b3b40b] | 951 | def getConstraintsForFitting(self): |
---|
| 952 | """ |
---|
| 953 | Return a list of constraints in format ready for use in fiting |
---|
| 954 | """ |
---|
| 955 | # Get constraints |
---|
| 956 | constraints = self.getComplexConstraintsForModel() |
---|
| 957 | # See if there are any constraints across models |
---|
| 958 | multi_constraints = [cons for cons in constraints if self.isConstraintMultimodel(cons[1])] |
---|
| 959 | |
---|
| 960 | if multi_constraints: |
---|
| 961 | # Let users choose what to do |
---|
| 962 | msg = "The current fit contains constraints relying on other fit pages.\n" |
---|
| 963 | msg += "Parameters with those constraints are:\n" +\ |
---|
| 964 | '\n'.join([cons[0] for cons in multi_constraints]) |
---|
| 965 | msg += "\n\nWould you like to remove these constraints or cancel fitting?" |
---|
| 966 | msgbox = QtWidgets.QMessageBox(self) |
---|
| 967 | msgbox.setIcon(QtWidgets.QMessageBox.Warning) |
---|
| 968 | msgbox.setText(msg) |
---|
| 969 | msgbox.setWindowTitle("Existing Constraints") |
---|
| 970 | # custom buttons |
---|
| 971 | button_remove = QtWidgets.QPushButton("Remove") |
---|
| 972 | msgbox.addButton(button_remove, QtWidgets.QMessageBox.YesRole) |
---|
| 973 | button_cancel = QtWidgets.QPushButton("Cancel") |
---|
| 974 | msgbox.addButton(button_cancel, QtWidgets.QMessageBox.RejectRole) |
---|
| 975 | retval = msgbox.exec_() |
---|
| 976 | if retval == QtWidgets.QMessageBox.RejectRole: |
---|
| 977 | # cancel fit |
---|
| 978 | raise ValueError("Fitting cancelled") |
---|
| 979 | else: |
---|
| 980 | # remove constraint |
---|
| 981 | for cons in multi_constraints: |
---|
| 982 | self.deleteConstraintOnParameter(param=cons[0]) |
---|
| 983 | # re-read the constraints |
---|
| 984 | constraints = self.getComplexConstraintsForModel() |
---|
| 985 | |
---|
| 986 | return constraints |
---|
| 987 | |
---|
[7fd20fc] | 988 | def showModelDescription(self): |
---|
| 989 | """ |
---|
| 990 | Creates a window with model description, when right clicked in the treeview |
---|
[2add354] | 991 | """ |
---|
| 992 | msg = 'Model description:\n' |
---|
| 993 | if self.kernel_module is not None: |
---|
| 994 | if str(self.kernel_module.description).rstrip().lstrip() == '': |
---|
| 995 | msg += "Sorry, no information is available for this model." |
---|
| 996 | else: |
---|
| 997 | msg += self.kernel_module.description + '\n' |
---|
| 998 | else: |
---|
| 999 | msg += "You must select a model to get information on this" |
---|
| 1000 | |
---|
[4992ff2] | 1001 | menu = QtWidgets.QMenu() |
---|
| 1002 | label = QtWidgets.QLabel(msg) |
---|
[d6b8a1d] | 1003 | action = QtWidgets.QWidgetAction(self) |
---|
[672b8ab] | 1004 | action.setDefaultWidget(label) |
---|
| 1005 | menu.addAction(action) |
---|
[7fd20fc] | 1006 | return menu |
---|
[2add354] | 1007 | |
---|
[a98014ab] | 1008 | def canHaveMagnetism(self): |
---|
| 1009 | """ |
---|
| 1010 | Checks if the current model has magnetic scattering implemented |
---|
| 1011 | """ |
---|
| 1012 | current_model = self.cbModel.currentText() |
---|
| 1013 | return self.is2D and current_model in self.MAGNETIC_MODELS |
---|
| 1014 | |
---|
[0268aed] | 1015 | def onSelectModel(self): |
---|
[cbcdd2c] | 1016 | """ |
---|
[0268aed] | 1017 | Respond to select Model from list event |
---|
[cbcdd2c] | 1018 | """ |
---|
[d6b8a1d] | 1019 | model = self.cbModel.currentText() |
---|
[0268aed] | 1020 | |
---|
[f4aa7a8] | 1021 | # Assure the control is active |
---|
| 1022 | if not self.cbModel.isEnabled(): |
---|
| 1023 | return |
---|
| 1024 | # Empty combobox forced to be read |
---|
[b3e8629] | 1025 | if not model: |
---|
| 1026 | return |
---|
[a98014ab] | 1027 | self.chkMagnetism.setEnabled(self.canHaveMagnetism()) |
---|
| 1028 | self.tabFitting.setTabEnabled(TAB_MAGNETISM, self.chkMagnetism.isChecked() and self.canHaveMagnetism()) |
---|
| 1029 | |
---|
[f182f93] | 1030 | # Reset parameters to fit |
---|
[6dbff18] | 1031 | self.resetParametersToFit() |
---|
[d7ff531] | 1032 | self.has_error_column = False |
---|
[aca8418] | 1033 | self.has_poly_error_column = False |
---|
[f182f93] | 1034 | |
---|
[605d944] | 1035 | structure = None |
---|
| 1036 | if self.cbStructureFactor.isEnabled(): |
---|
| 1037 | structure = str(self.cbStructureFactor.currentText()) |
---|
| 1038 | self.respondToModelStructure(model=model, structure_factor=structure) |
---|
[fd1ae6d1] | 1039 | |
---|
[ee18d33] | 1040 | def onSelectBatchFilename(self, data_index): |
---|
| 1041 | """ |
---|
| 1042 | Update the logic based on the selected file in batch fitting |
---|
| 1043 | """ |
---|
[d4dac80] | 1044 | self.data_index = data_index |
---|
[ee18d33] | 1045 | self.updateQRange() |
---|
| 1046 | |
---|
[fd1ae6d1] | 1047 | def onSelectStructureFactor(self): |
---|
| 1048 | """ |
---|
| 1049 | Select Structure Factor from list |
---|
| 1050 | """ |
---|
| 1051 | model = str(self.cbModel.currentText()) |
---|
| 1052 | category = str(self.cbCategory.currentText()) |
---|
| 1053 | structure = str(self.cbStructureFactor.currentText()) |
---|
| 1054 | if category == CATEGORY_STRUCTURE: |
---|
| 1055 | model = None |
---|
[e11106e] | 1056 | |
---|
| 1057 | # Reset parameters to fit |
---|
[6dbff18] | 1058 | self.resetParametersToFit() |
---|
[e11106e] | 1059 | self.has_error_column = False |
---|
| 1060 | self.has_poly_error_column = False |
---|
| 1061 | |
---|
[fd1ae6d1] | 1062 | self.respondToModelStructure(model=model, structure_factor=structure) |
---|
| 1063 | |
---|
[6dbff18] | 1064 | def resetParametersToFit(self): |
---|
| 1065 | """ |
---|
| 1066 | Clears the list of parameters to be fitted |
---|
| 1067 | """ |
---|
| 1068 | self.main_params_to_fit = [] |
---|
| 1069 | self.poly_params_to_fit = [] |
---|
| 1070 | self.magnet_params_to_fit = [] |
---|
| 1071 | |
---|
[3b3b40b] | 1072 | def onCustomModelChange(self): |
---|
| 1073 | """ |
---|
| 1074 | Reload the custom model combobox |
---|
| 1075 | """ |
---|
| 1076 | self.custom_models = self.customModels() |
---|
| 1077 | self.readCustomCategoryInfo() |
---|
[2dce1d8] | 1078 | self.onCategoriesChanged() |
---|
| 1079 | |
---|
[3b3b40b] | 1080 | # See if we need to update the combo in-place |
---|
| 1081 | if self.cbCategory.currentText() != CATEGORY_CUSTOM: return |
---|
| 1082 | |
---|
| 1083 | current_text = self.cbModel.currentText() |
---|
| 1084 | self.cbModel.blockSignals(True) |
---|
| 1085 | self.cbModel.clear() |
---|
| 1086 | self.cbModel.blockSignals(False) |
---|
| 1087 | self.enableModelCombo() |
---|
| 1088 | self.disableStructureCombo() |
---|
| 1089 | # Retrieve the list of models |
---|
| 1090 | model_list = self.master_category_dict[CATEGORY_CUSTOM] |
---|
| 1091 | # Populate the models combobox |
---|
| 1092 | self.cbModel.addItems(sorted([model for (model, _) in model_list])) |
---|
| 1093 | new_index = self.cbModel.findText(current_text) |
---|
| 1094 | if new_index != -1: |
---|
| 1095 | self.cbModel.setCurrentIndex(self.cbModel.findText(current_text)) |
---|
| 1096 | |
---|
| 1097 | def onSelectionChanged(self): |
---|
| 1098 | """ |
---|
| 1099 | React to parameter selection |
---|
| 1100 | """ |
---|
| 1101 | rows = self.lstParams.selectionModel().selectedRows() |
---|
| 1102 | # Clean previous messages |
---|
| 1103 | self.communicate.statusBarUpdateSignal.emit("") |
---|
| 1104 | if len(rows) == 1: |
---|
| 1105 | # Show constraint, if present |
---|
| 1106 | row = rows[0].row() |
---|
[c4b23dd] | 1107 | if not self.rowHasConstraint(row): |
---|
| 1108 | return |
---|
[d1e4689] | 1109 | constr = self.getConstraintForRow(row) |
---|
[c4b23dd] | 1110 | func = self.getConstraintForRow(row).func |
---|
[d1e4689] | 1111 | if constr.func is not None: |
---|
| 1112 | # inter-parameter constraint |
---|
| 1113 | update_text = "Active constraint: "+func |
---|
| 1114 | elif constr.param == rows[0].data(): |
---|
| 1115 | # current value constraint |
---|
| 1116 | update_text = "Value constrained to: " + str(constr.value) |
---|
| 1117 | else: |
---|
| 1118 | # ill defined constraint |
---|
| 1119 | return |
---|
| 1120 | self.communicate.statusBarUpdateSignal.emit(update_text) |
---|
[3b3b40b] | 1121 | |
---|
[47d7d2d] | 1122 | def replaceConstraintName(self, old_name, new_name=""): |
---|
| 1123 | """ |
---|
| 1124 | Replace names of models in defined constraints |
---|
| 1125 | """ |
---|
| 1126 | param_number = self._model_model.rowCount() |
---|
| 1127 | # loop over parameters |
---|
| 1128 | for row in range(param_number): |
---|
| 1129 | if self.rowHasConstraint(row): |
---|
| 1130 | func = self._model_model.item(row, 1).child(0).data().func |
---|
| 1131 | if old_name in func: |
---|
| 1132 | new_func = func.replace(old_name, new_name) |
---|
| 1133 | self._model_model.item(row, 1).child(0).data().func = new_func |
---|
| 1134 | |
---|
[3b3b40b] | 1135 | def isConstraintMultimodel(self, constraint): |
---|
| 1136 | """ |
---|
| 1137 | Check if the constraint function text contains current model name |
---|
| 1138 | """ |
---|
| 1139 | current_model_name = self.kernel_module.name |
---|
| 1140 | if current_model_name in constraint: |
---|
| 1141 | return False |
---|
| 1142 | else: |
---|
| 1143 | return True |
---|
| 1144 | |
---|
[9c0ce68] | 1145 | def updateData(self): |
---|
| 1146 | """ |
---|
| 1147 | Helper function for recalculation of data used in plotting |
---|
| 1148 | """ |
---|
| 1149 | # Update the chart |
---|
[0268aed] | 1150 | if self.data_is_loaded: |
---|
[d48cc19] | 1151 | self.cmdPlot.setText("Show Plot") |
---|
[0268aed] | 1152 | self.calculateQGridForModel() |
---|
| 1153 | else: |
---|
[d48cc19] | 1154 | self.cmdPlot.setText("Calculate") |
---|
[0268aed] | 1155 | # Create default datasets if no data passed |
---|
| 1156 | self.createDefaultDataset() |
---|
[33d5956] | 1157 | self.theory_item = None # ensure theory is recalc. before plot, see showTheoryPlot() |
---|
[0268aed] | 1158 | |
---|
[9c0ce68] | 1159 | def respondToModelStructure(self, model=None, structure_factor=None): |
---|
| 1160 | # Set enablement on calculate/plot |
---|
| 1161 | self.cmdPlot.setEnabled(True) |
---|
| 1162 | |
---|
| 1163 | # kernel parameters -> model_model |
---|
| 1164 | self.SASModelToQModel(model, structure_factor) |
---|
| 1165 | |
---|
[f37cab0] | 1166 | for column, width in self.lstParamHeaderSizes.items(): |
---|
| 1167 | self.lstParams.setColumnWidth(column, width) |
---|
| 1168 | |
---|
[9c0ce68] | 1169 | # Update plot |
---|
| 1170 | self.updateData() |
---|
| 1171 | |
---|
[6011788] | 1172 | # Update state stack |
---|
[00b3b40] | 1173 | self.updateUndo() |
---|
[2add354] | 1174 | |
---|
[be8f4b0] | 1175 | # Let others know |
---|
| 1176 | self.newModelSignal.emit() |
---|
| 1177 | |
---|
[cd31251] | 1178 | def onSelectCategory(self): |
---|
[60af928] | 1179 | """ |
---|
| 1180 | Select Category from list |
---|
| 1181 | """ |
---|
[d6b8a1d] | 1182 | category = self.cbCategory.currentText() |
---|
[86f88d1] | 1183 | # Check if the user chose "Choose category entry" |
---|
[4d457df] | 1184 | if category == CATEGORY_DEFAULT: |
---|
[86f88d1] | 1185 | # if the previous category was not the default, keep it. |
---|
| 1186 | # Otherwise, just return |
---|
| 1187 | if self._previous_category_index != 0: |
---|
[351b53e] | 1188 | # We need to block signals, or else state changes on perceived unchanged conditions |
---|
| 1189 | self.cbCategory.blockSignals(True) |
---|
[86f88d1] | 1190 | self.cbCategory.setCurrentIndex(self._previous_category_index) |
---|
[351b53e] | 1191 | self.cbCategory.blockSignals(False) |
---|
[86f88d1] | 1192 | return |
---|
| 1193 | |
---|
[4d457df] | 1194 | if category == CATEGORY_STRUCTURE: |
---|
[6f7f652] | 1195 | self.disableModelCombo() |
---|
| 1196 | self.enableStructureCombo() |
---|
[f4aa7a8] | 1197 | # set the index to 0 |
---|
| 1198 | self.cbStructureFactor.setCurrentIndex(0) |
---|
| 1199 | self.model_parameters = None |
---|
[29eb947] | 1200 | self._model_model.clear() |
---|
[6f7f652] | 1201 | return |
---|
[8b480d27] | 1202 | |
---|
[cbcdd2c] | 1203 | # Safely clear and enable the model combo |
---|
[6f7f652] | 1204 | self.cbModel.blockSignals(True) |
---|
| 1205 | self.cbModel.clear() |
---|
| 1206 | self.cbModel.blockSignals(False) |
---|
| 1207 | self.enableModelCombo() |
---|
| 1208 | self.disableStructureCombo() |
---|
| 1209 | |
---|
[86f88d1] | 1210 | self._previous_category_index = self.cbCategory.currentIndex() |
---|
[cbcdd2c] | 1211 | # Retrieve the list of models |
---|
[4d457df] | 1212 | model_list = self.master_category_dict[category] |
---|
[cbcdd2c] | 1213 | # Populate the models combobox |
---|
[b1e36a3] | 1214 | self.cbModel.addItems(sorted([model for (model, _) in model_list])) |
---|
[4d457df] | 1215 | |
---|
[d2007a8] | 1216 | def onPolyModelChange(self, top, bottom): |
---|
[0268aed] | 1217 | """ |
---|
| 1218 | Callback method for updating the main model and sasmodel |
---|
| 1219 | parameters with the GUI values in the polydispersity view |
---|
| 1220 | """ |
---|
[d2007a8] | 1221 | item = self._poly_model.itemFromIndex(top) |
---|
[0268aed] | 1222 | model_column = item.column() |
---|
| 1223 | model_row = item.row() |
---|
| 1224 | name_index = self._poly_model.index(model_row, 0) |
---|
[287d356] | 1225 | parameter_name = str(name_index.data()) # "distribution of sld" etc. |
---|
| 1226 | if "istribution of" in parameter_name: |
---|
[358b39d] | 1227 | # just the last word |
---|
| 1228 | parameter_name = parameter_name.rsplit()[-1] |
---|
[c1e380e] | 1229 | |
---|
[906e0c7] | 1230 | delegate = self.lstPoly.itemDelegate() |
---|
| 1231 | |
---|
[06b0138] | 1232 | # Extract changed value. |
---|
[906e0c7] | 1233 | if model_column == delegate.poly_parameter: |
---|
[00b3b40] | 1234 | # Is the parameter checked for fitting? |
---|
[0268aed] | 1235 | value = item.checkState() |
---|
[1643d8ed] | 1236 | parameter_name = parameter_name + '.width' |
---|
[c1e380e] | 1237 | if value == QtCore.Qt.Checked: |
---|
[6dbff18] | 1238 | self.poly_params_to_fit.append(parameter_name) |
---|
[c1e380e] | 1239 | else: |
---|
[6dbff18] | 1240 | if parameter_name in self.poly_params_to_fit: |
---|
| 1241 | self.poly_params_to_fit.remove(parameter_name) |
---|
| 1242 | self.cmdFit.setEnabled(self.haveParamsToFit()) |
---|
[906e0c7] | 1243 | |
---|
| 1244 | elif model_column in [delegate.poly_min, delegate.poly_max]: |
---|
[aca8418] | 1245 | try: |
---|
[fbfc488] | 1246 | value = GuiUtils.toDouble(item.text()) |
---|
[0261bc1] | 1247 | except TypeError: |
---|
[aca8418] | 1248 | # Can't be converted properly, bring back the old value and exit |
---|
| 1249 | return |
---|
| 1250 | |
---|
| 1251 | current_details = self.kernel_module.details[parameter_name] |
---|
[906e0c7] | 1252 | if self.has_poly_error_column: |
---|
| 1253 | # err column changes the indexing |
---|
| 1254 | current_details[model_column-2] = value |
---|
| 1255 | else: |
---|
| 1256 | current_details[model_column-1] = value |
---|
| 1257 | |
---|
| 1258 | elif model_column == delegate.poly_function: |
---|
[919d47c] | 1259 | # name of the function - just pass |
---|
[906e0c7] | 1260 | pass |
---|
| 1261 | |
---|
[0268aed] | 1262 | else: |
---|
| 1263 | try: |
---|
[fbfc488] | 1264 | value = GuiUtils.toDouble(item.text()) |
---|
[0261bc1] | 1265 | except TypeError: |
---|
[0268aed] | 1266 | # Can't be converted properly, bring back the old value and exit |
---|
| 1267 | return |
---|
| 1268 | |
---|
[aca8418] | 1269 | # Update the sasmodel |
---|
| 1270 | # PD[ratio] -> width, npts -> npts, nsigs -> nsigmas |
---|
[66d4370] | 1271 | #self.kernel_module.setParam(parameter_name + '.' + delegate.columnDict()[model_column], value) |
---|
| 1272 | key = parameter_name + '.' + delegate.columnDict()[model_column] |
---|
| 1273 | self.poly_params[key] = value |
---|
[0268aed] | 1274 | |
---|
[9c0ce68] | 1275 | # Update plot |
---|
| 1276 | self.updateData() |
---|
| 1277 | |
---|
[906e0c7] | 1278 | # update in param model |
---|
| 1279 | if model_column in [delegate.poly_pd, delegate.poly_error, delegate.poly_min, delegate.poly_max]: |
---|
| 1280 | row = self.getRowFromName(parameter_name) |
---|
[f3cc979] | 1281 | param_item = self._model_model.item(row).child(0).child(0, model_column) |
---|
| 1282 | if param_item is None: |
---|
| 1283 | return |
---|
[73665a8] | 1284 | self._model_model.blockSignals(True) |
---|
[f3cc979] | 1285 | param_item.setText(item.text()) |
---|
[73665a8] | 1286 | self._model_model.blockSignals(False) |
---|
[906e0c7] | 1287 | |
---|
[d2007a8] | 1288 | def onMagnetModelChange(self, top, bottom): |
---|
[b00414d] | 1289 | """ |
---|
| 1290 | Callback method for updating the sasmodel magnetic parameters with the GUI values |
---|
| 1291 | """ |
---|
[d2007a8] | 1292 | item = self._magnet_model.itemFromIndex(top) |
---|
[b00414d] | 1293 | model_column = item.column() |
---|
| 1294 | model_row = item.row() |
---|
| 1295 | name_index = self._magnet_model.index(model_row, 0) |
---|
[fbfc488] | 1296 | parameter_name = str(self._magnet_model.data(name_index)) |
---|
[b00414d] | 1297 | |
---|
| 1298 | if model_column == 0: |
---|
| 1299 | value = item.checkState() |
---|
| 1300 | if value == QtCore.Qt.Checked: |
---|
[6dbff18] | 1301 | self.magnet_params_to_fit.append(parameter_name) |
---|
[b00414d] | 1302 | else: |
---|
[6dbff18] | 1303 | if parameter_name in self.magnet_params_to_fit: |
---|
| 1304 | self.magnet_params_to_fit.remove(parameter_name) |
---|
| 1305 | self.cmdFit.setEnabled(self.haveParamsToFit()) |
---|
[b00414d] | 1306 | # Update state stack |
---|
| 1307 | self.updateUndo() |
---|
| 1308 | return |
---|
| 1309 | |
---|
| 1310 | # Extract changed value. |
---|
| 1311 | try: |
---|
[fbfc488] | 1312 | value = GuiUtils.toDouble(item.text()) |
---|
[0261bc1] | 1313 | except TypeError: |
---|
[b00414d] | 1314 | # Unparsable field |
---|
| 1315 | return |
---|
[66d4370] | 1316 | delegate = self.lstMagnetic.itemDelegate() |
---|
| 1317 | |
---|
| 1318 | if model_column > 1: |
---|
| 1319 | if model_column == delegate.mag_min: |
---|
| 1320 | pos = 1 |
---|
| 1321 | elif model_column == delegate.mag_max: |
---|
| 1322 | pos = 2 |
---|
| 1323 | elif model_column == delegate.mag_unit: |
---|
| 1324 | pos = 0 |
---|
| 1325 | else: |
---|
| 1326 | raise AttributeError("Wrong column in magnetism table.") |
---|
| 1327 | # min/max to be changed in self.kernel_module.details[parameter_name] = ['Ang', 0.0, inf] |
---|
| 1328 | self.kernel_module.details[parameter_name][pos] = value |
---|
| 1329 | else: |
---|
| 1330 | self.magnet_params[parameter_name] = value |
---|
| 1331 | #self.kernel_module.setParam(parameter_name) = value |
---|
| 1332 | # Force the chart update when actual parameters changed |
---|
[b00414d] | 1333 | self.recalculatePlotData() |
---|
| 1334 | |
---|
| 1335 | # Update state stack |
---|
| 1336 | self.updateUndo() |
---|
| 1337 | |
---|
[2add354] | 1338 | def onHelp(self): |
---|
| 1339 | """ |
---|
| 1340 | Show the "Fitting" section of help |
---|
| 1341 | """ |
---|
[aed0532] | 1342 | tree_location = "/user/qtgui/Perspectives/Fitting/" |
---|
[70080a0] | 1343 | |
---|
| 1344 | # Actual file will depend on the current tab |
---|
| 1345 | tab_id = self.tabFitting.currentIndex() |
---|
| 1346 | helpfile = "fitting.html" |
---|
| 1347 | if tab_id == 0: |
---|
| 1348 | helpfile = "fitting_help.html" |
---|
| 1349 | elif tab_id == 1: |
---|
| 1350 | helpfile = "residuals_help.html" |
---|
| 1351 | elif tab_id == 2: |
---|
[e90988c] | 1352 | helpfile = "resolution.html" |
---|
[70080a0] | 1353 | elif tab_id == 3: |
---|
[e90988c] | 1354 | helpfile = "pd/polydispersity.html" |
---|
[70080a0] | 1355 | elif tab_id == 4: |
---|
[e90988c] | 1356 | helpfile = "magnetism/magnetism.html" |
---|
[70080a0] | 1357 | help_location = tree_location + helpfile |
---|
[d6b8a1d] | 1358 | |
---|
[e90988c] | 1359 | self.showHelp(help_location) |
---|
| 1360 | |
---|
| 1361 | def showHelp(self, url): |
---|
| 1362 | """ |
---|
| 1363 | Calls parent's method for opening an HTML page |
---|
| 1364 | """ |
---|
| 1365 | self.parent.showHelp(url) |
---|
[2add354] | 1366 | |
---|
[6ff2eb3] | 1367 | def onDisplayMagneticAngles(self): |
---|
| 1368 | """ |
---|
| 1369 | Display a simple image showing direction of magnetic angles |
---|
| 1370 | """ |
---|
| 1371 | self.magneticAnglesWidget.show() |
---|
| 1372 | |
---|
[0268aed] | 1373 | def onFit(self): |
---|
| 1374 | """ |
---|
| 1375 | Perform fitting on the current data |
---|
| 1376 | """ |
---|
[ded5e77] | 1377 | if self.fit_started: |
---|
| 1378 | self.stopFit() |
---|
| 1379 | return |
---|
| 1380 | |
---|
[116dd4c1] | 1381 | # initialize fitter constants |
---|
[f182f93] | 1382 | fit_id = 0 |
---|
| 1383 | handler = None |
---|
| 1384 | batch_inputs = {} |
---|
| 1385 | batch_outputs = {} |
---|
| 1386 | #--------------------------------- |
---|
[14ec91c5] | 1387 | if LocalConfig.USING_TWISTED: |
---|
[7adc2a8] | 1388 | handler = None |
---|
| 1389 | updater = None |
---|
| 1390 | else: |
---|
| 1391 | handler = ConsoleUpdate(parent=self.parent, |
---|
| 1392 | manager=self, |
---|
| 1393 | improvement_delta=0.1) |
---|
| 1394 | updater = handler.update_fit |
---|
[f182f93] | 1395 | |
---|
[116dd4c1] | 1396 | # Prepare the fitter object |
---|
[c6343a5] | 1397 | try: |
---|
| 1398 | fitters, _ = self.prepareFitters() |
---|
| 1399 | except ValueError as ex: |
---|
| 1400 | # This should not happen! GUI explicitly forbids this situation |
---|
[3b3b40b] | 1401 | self.communicate.statusBarUpdateSignal.emit(str(ex)) |
---|
[c6343a5] | 1402 | return |
---|
[f182f93] | 1403 | |
---|
[d4dac80] | 1404 | # keep local copy of kernel parameters, as they will change during the update |
---|
| 1405 | self.kernel_module_copy = copy.deepcopy(self.kernel_module) |
---|
| 1406 | |
---|
[f182f93] | 1407 | # Create the fitting thread, based on the fitter |
---|
[3b3b40b] | 1408 | completefn = self.batchFittingCompleted if self.is_batch_fitting else self.fittingCompleted |
---|
[ee18d33] | 1409 | |
---|
[ded5e77] | 1410 | self.calc_fit = FitThread(handler=handler, |
---|
[116dd4c1] | 1411 | fn=fitters, |
---|
| 1412 | batch_inputs=batch_inputs, |
---|
| 1413 | batch_outputs=batch_outputs, |
---|
| 1414 | page_id=[[self.page_id]], |
---|
| 1415 | updatefn=updater, |
---|
[91ad45c] | 1416 | completefn=completefn, |
---|
| 1417 | reset_flag=self.is_chain_fitting) |
---|
[7adc2a8] | 1418 | |
---|
[14ec91c5] | 1419 | if LocalConfig.USING_TWISTED: |
---|
[7adc2a8] | 1420 | # start the trhrhread with twisted |
---|
[ded5e77] | 1421 | calc_thread = threads.deferToThread(self.calc_fit.compute) |
---|
[14ec91c5] | 1422 | calc_thread.addCallback(completefn) |
---|
[7adc2a8] | 1423 | calc_thread.addErrback(self.fitFailed) |
---|
| 1424 | else: |
---|
| 1425 | # Use the old python threads + Queue |
---|
[ded5e77] | 1426 | self.calc_fit.queue() |
---|
| 1427 | self.calc_fit.ready(2.5) |
---|
[f182f93] | 1428 | |
---|
[d7ff531] | 1429 | self.communicate.statusBarUpdateSignal.emit('Fitting started...') |
---|
[ded5e77] | 1430 | self.fit_started = True |
---|
[557fc498] | 1431 | |
---|
[14ec91c5] | 1432 | # Disable some elements |
---|
[557fc498] | 1433 | self.disableInteractiveElements() |
---|
[0268aed] | 1434 | |
---|
[ded5e77] | 1435 | def stopFit(self): |
---|
| 1436 | """ |
---|
| 1437 | Attempt to stop the fitting thread |
---|
| 1438 | """ |
---|
| 1439 | if self.calc_fit is None or not self.calc_fit.isrunning(): |
---|
| 1440 | return |
---|
| 1441 | self.calc_fit.stop() |
---|
| 1442 | #re-enable the Fit button |
---|
[557fc498] | 1443 | self.enableInteractiveElements() |
---|
[ded5e77] | 1444 | |
---|
| 1445 | msg = "Fitting cancelled." |
---|
| 1446 | self.communicate.statusBarUpdateSignal.emit(msg) |
---|
| 1447 | |
---|
[f182f93] | 1448 | def updateFit(self): |
---|
| 1449 | """ |
---|
| 1450 | """ |
---|
[b3e8629] | 1451 | print("UPDATE FIT") |
---|
[0268aed] | 1452 | pass |
---|
| 1453 | |
---|
[02ddfb4] | 1454 | def fitFailed(self, reason): |
---|
| 1455 | """ |
---|
| 1456 | """ |
---|
[557fc498] | 1457 | self.enableInteractiveElements() |
---|
[ded5e77] | 1458 | msg = "Fitting failed with: "+ str(reason) |
---|
| 1459 | self.communicate.statusBarUpdateSignal.emit(msg) |
---|
[02ddfb4] | 1460 | |
---|
[3b3b40b] | 1461 | def batchFittingCompleted(self, result): |
---|
| 1462 | """ |
---|
| 1463 | Send the finish message from calculate threads to main thread |
---|
| 1464 | """ |
---|
[a2cc8b97] | 1465 | if result is None: |
---|
| 1466 | result = tuple() |
---|
[3b3b40b] | 1467 | self.batchFittingFinishedSignal.emit(result) |
---|
| 1468 | |
---|
[ee18d33] | 1469 | def batchFitComplete(self, result): |
---|
| 1470 | """ |
---|
| 1471 | Receive and display batch fitting results |
---|
| 1472 | """ |
---|
| 1473 | #re-enable the Fit button |
---|
[557fc498] | 1474 | self.enableInteractiveElements() |
---|
[d4dac80] | 1475 | |
---|
[a2cc8b97] | 1476 | if len(result) == 0: |
---|
[d4dac80] | 1477 | msg = "Fitting failed." |
---|
| 1478 | self.communicate.statusBarUpdateSignal.emit(msg) |
---|
| 1479 | return |
---|
| 1480 | |
---|
[3b3b40b] | 1481 | # Show the grid panel |
---|
[d4dac80] | 1482 | self.communicate.sendDataToGridSignal.emit(result[0]) |
---|
| 1483 | |
---|
| 1484 | elapsed = result[1] |
---|
| 1485 | msg = "Fitting completed successfully in: %s s.\n" % GuiUtils.formatNumber(elapsed) |
---|
| 1486 | self.communicate.statusBarUpdateSignal.emit(msg) |
---|
| 1487 | |
---|
| 1488 | # Run over the list of results and update the items |
---|
| 1489 | for res_index, res_list in enumerate(result[0]): |
---|
| 1490 | # results |
---|
| 1491 | res = res_list[0] |
---|
| 1492 | param_dict = self.paramDictFromResults(res) |
---|
| 1493 | |
---|
| 1494 | # create local kernel_module |
---|
| 1495 | kernel_module = FittingUtilities.updateKernelWithResults(self.kernel_module, param_dict) |
---|
| 1496 | # pull out current data |
---|
| 1497 | data = self._logic[res_index].data |
---|
| 1498 | |
---|
| 1499 | # Switch indexes |
---|
| 1500 | self.onSelectBatchFilename(res_index) |
---|
| 1501 | |
---|
| 1502 | method = self.complete1D if isinstance(self.data, Data1D) else self.complete2D |
---|
| 1503 | self.calculateQGridForModelExt(data=data, model=kernel_module, completefn=method, use_threads=False) |
---|
| 1504 | |
---|
| 1505 | # Restore original kernel_module, so subsequent fits on the same model don't pick up the new params |
---|
| 1506 | if self.kernel_module is not None: |
---|
| 1507 | self.kernel_module = copy.deepcopy(self.kernel_module_copy) |
---|
| 1508 | |
---|
| 1509 | def paramDictFromResults(self, results): |
---|
| 1510 | """ |
---|
| 1511 | Given the fit results structure, pull out optimized parameters and return them as nicely |
---|
| 1512 | formatted dict |
---|
| 1513 | """ |
---|
| 1514 | if results.fitness is None or \ |
---|
| 1515 | not np.isfinite(results.fitness) or \ |
---|
| 1516 | np.any(results.pvec is None) or \ |
---|
| 1517 | not np.all(np.isfinite(results.pvec)): |
---|
| 1518 | msg = "Fitting did not converge!" |
---|
| 1519 | self.communicate.statusBarUpdateSignal.emit(msg) |
---|
| 1520 | msg += results.mesg |
---|
[bb477f5] | 1521 | logger.error(msg) |
---|
[d4dac80] | 1522 | return |
---|
| 1523 | |
---|
| 1524 | param_list = results.param_list # ['radius', 'radius.width'] |
---|
| 1525 | param_values = results.pvec # array([ 0.36221662, 0.0146783 ]) |
---|
| 1526 | param_stderr = results.stderr # array([ 1.71293015, 1.71294233]) |
---|
| 1527 | params_and_errors = list(zip(param_values, param_stderr)) |
---|
| 1528 | param_dict = dict(zip(param_list, params_and_errors)) |
---|
| 1529 | |
---|
| 1530 | return param_dict |
---|
[3b3b40b] | 1531 | |
---|
| 1532 | def fittingCompleted(self, result): |
---|
| 1533 | """ |
---|
| 1534 | Send the finish message from calculate threads to main thread |
---|
| 1535 | """ |
---|
[a2cc8b97] | 1536 | if result is None: |
---|
| 1537 | result = tuple() |
---|
[3b3b40b] | 1538 | self.fittingFinishedSignal.emit(result) |
---|
[ee18d33] | 1539 | |
---|
[f182f93] | 1540 | def fitComplete(self, result): |
---|
| 1541 | """ |
---|
| 1542 | Receive and display fitting results |
---|
| 1543 | "result" is a tuple of actual result list and the fit time in seconds |
---|
| 1544 | """ |
---|
| 1545 | #re-enable the Fit button |
---|
[557fc498] | 1546 | self.enableInteractiveElements() |
---|
[d7ff531] | 1547 | |
---|
[a2cc8b97] | 1548 | if len(result) == 0: |
---|
[3b3b40b] | 1549 | msg = "Fitting failed." |
---|
[06234fc] | 1550 | self.communicate.statusBarUpdateSignal.emit(msg) |
---|
| 1551 | return |
---|
[d7ff531] | 1552 | |
---|
[ee18d33] | 1553 | res_list = result[0][0] |
---|
[f182f93] | 1554 | res = res_list[0] |
---|
[d4dac80] | 1555 | self.chi2 = res.fitness |
---|
| 1556 | param_dict = self.paramDictFromResults(res) |
---|
[f182f93] | 1557 | |
---|
[14acf92] | 1558 | if param_dict is None: |
---|
| 1559 | return |
---|
| 1560 | |
---|
[f182f93] | 1561 | elapsed = result[1] |
---|
[9d130f3] | 1562 | if self.calc_fit is not None and self.calc_fit._interrupting: |
---|
[ded5e77] | 1563 | msg = "Fitting cancelled by user after: %s s." % GuiUtils.formatNumber(elapsed) |
---|
[bb477f5] | 1564 | logger.warning("\n"+msg+"\n") |
---|
[ded5e77] | 1565 | else: |
---|
| 1566 | msg = "Fitting completed successfully in: %s s." % GuiUtils.formatNumber(elapsed) |
---|
[f182f93] | 1567 | self.communicate.statusBarUpdateSignal.emit(msg) |
---|
| 1568 | |
---|
| 1569 | # Dictionary of fitted parameter: value, error |
---|
| 1570 | # e.g. param_dic = {"sld":(1.703, 0.0034), "length":(33.455, -0.0983)} |
---|
| 1571 | self.updateModelFromList(param_dict) |
---|
| 1572 | |
---|
[aca8418] | 1573 | self.updatePolyModelFromList(param_dict) |
---|
| 1574 | |
---|
[b00414d] | 1575 | self.updateMagnetModelFromList(param_dict) |
---|
| 1576 | |
---|
[d7ff531] | 1577 | # update charts |
---|
| 1578 | self.onPlot() |
---|
[c2f3ca2] | 1579 | #self.recalculatePlotData() |
---|
| 1580 | |
---|
[d7ff531] | 1581 | |
---|
[f182f93] | 1582 | # Read only value - we can get away by just printing it here |
---|
[2add354] | 1583 | chi2_repr = GuiUtils.formatNumber(self.chi2, high=True) |
---|
[f182f93] | 1584 | self.lblChi2Value.setText(chi2_repr) |
---|
| 1585 | |
---|
[116dd4c1] | 1586 | def prepareFitters(self, fitter=None, fit_id=0): |
---|
| 1587 | """ |
---|
| 1588 | Prepare the Fitter object for use in fitting |
---|
| 1589 | """ |
---|
| 1590 | # fitter = None -> single/batch fitting |
---|
| 1591 | # fitter = Fit() -> simultaneous fitting |
---|
| 1592 | |
---|
| 1593 | # Data going in |
---|
| 1594 | data = self.logic.data |
---|
[66d4370] | 1595 | model = copy.deepcopy(self.kernel_module) |
---|
[116dd4c1] | 1596 | qmin = self.q_range_min |
---|
| 1597 | qmax = self.q_range_max |
---|
[66d4370] | 1598 | # add polydisperse/magnet parameters if asked |
---|
| 1599 | self.updateKernelModelWithExtraParams(model) |
---|
[6dbff18] | 1600 | |
---|
[d4216ac] | 1601 | params_to_fit = copy.deepcopy(self.main_params_to_fit) |
---|
[6dbff18] | 1602 | if self.chkPolydispersity.isChecked(): |
---|
| 1603 | params_to_fit += self.poly_params_to_fit |
---|
[a98014ab] | 1604 | if self.chkMagnetism.isChecked() and self.canHaveMagnetism(): |
---|
[6dbff18] | 1605 | params_to_fit += self.magnet_params_to_fit |
---|
[8e2cd79] | 1606 | if not params_to_fit: |
---|
[c6343a5] | 1607 | raise ValueError('Fitting requires at least one parameter to optimize.') |
---|
[116dd4c1] | 1608 | |
---|
[8b480d27] | 1609 | # Get the constraints. |
---|
| 1610 | constraints = self.getComplexConstraintsForModel() |
---|
| 1611 | if fitter is None: |
---|
| 1612 | # For single fits - check for inter-model constraints |
---|
| 1613 | constraints = self.getConstraintsForFitting() |
---|
[3b3b40b] | 1614 | |
---|
[9a7c81c] | 1615 | smearer = self.smearing_widget.smearer() |
---|
[116dd4c1] | 1616 | handler = None |
---|
| 1617 | batch_inputs = {} |
---|
| 1618 | batch_outputs = {} |
---|
| 1619 | |
---|
| 1620 | fitters = [] |
---|
| 1621 | for fit_index in self.all_data: |
---|
| 1622 | fitter_single = Fit() if fitter is None else fitter |
---|
| 1623 | data = GuiUtils.dataFromItem(fit_index) |
---|
[9a7c81c] | 1624 | # Potential weights added directly to data |
---|
[b764ae5] | 1625 | weighted_data = self.addWeightingToData(data) |
---|
[116dd4c1] | 1626 | try: |
---|
[b764ae5] | 1627 | fitter_single.set_model(model, fit_id, params_to_fit, data=weighted_data, |
---|
[116dd4c1] | 1628 | constraints=constraints) |
---|
| 1629 | except ValueError as ex: |
---|
[3b3b40b] | 1630 | raise ValueError("Setting model parameters failed with: %s" % ex) |
---|
[116dd4c1] | 1631 | |
---|
[b764ae5] | 1632 | qmin, qmax, _ = self.logic.computeRangeFromData(weighted_data) |
---|
| 1633 | fitter_single.set_data(data=weighted_data, id=fit_id, smearer=smearer, qmin=qmin, |
---|
[116dd4c1] | 1634 | qmax=qmax) |
---|
| 1635 | fitter_single.select_problem_for_fit(id=fit_id, value=1) |
---|
| 1636 | if fitter is None: |
---|
| 1637 | # Assign id to the new fitter only |
---|
| 1638 | fitter_single.fitter_id = [self.page_id] |
---|
| 1639 | fit_id += 1 |
---|
| 1640 | fitters.append(fitter_single) |
---|
| 1641 | |
---|
| 1642 | return fitters, fit_id |
---|
| 1643 | |
---|
[f182f93] | 1644 | def iterateOverModel(self, func): |
---|
| 1645 | """ |
---|
| 1646 | Take func and throw it inside the model row loop |
---|
| 1647 | """ |
---|
[b3e8629] | 1648 | for row_i in range(self._model_model.rowCount()): |
---|
[f182f93] | 1649 | func(row_i) |
---|
| 1650 | |
---|
| 1651 | def updateModelFromList(self, param_dict): |
---|
| 1652 | """ |
---|
| 1653 | Update the model with new parameters, create the errors column |
---|
| 1654 | """ |
---|
| 1655 | assert isinstance(param_dict, dict) |
---|
| 1656 | if not dict: |
---|
| 1657 | return |
---|
| 1658 | |
---|
[919d47c] | 1659 | def updateFittedValues(row): |
---|
[f182f93] | 1660 | # Utility function for main model update |
---|
[d7ff531] | 1661 | # internal so can use closure for param_dict |
---|
[919d47c] | 1662 | param_name = str(self._model_model.item(row, 0).text()) |
---|
[00b7ddf0] | 1663 | if not self.isCheckable(row) or param_name not in list(param_dict.keys()): |
---|
[f182f93] | 1664 | return |
---|
| 1665 | # modify the param value |
---|
[454670d] | 1666 | param_repr = GuiUtils.formatNumber(param_dict[param_name][0], high=True) |
---|
[919d47c] | 1667 | self._model_model.item(row, 1).setText(param_repr) |
---|
[c2f3ca2] | 1668 | self.kernel_module.setParam(param_name, param_dict[param_name][0]) |
---|
[f182f93] | 1669 | if self.has_error_column: |
---|
[454670d] | 1670 | error_repr = GuiUtils.formatNumber(param_dict[param_name][1], high=True) |
---|
[919d47c] | 1671 | self._model_model.item(row, 2).setText(error_repr) |
---|
[f182f93] | 1672 | |
---|
[919d47c] | 1673 | def updatePolyValues(row): |
---|
| 1674 | # Utility function for updateof polydispersity part of the main model |
---|
| 1675 | param_name = str(self._model_model.item(row, 0).text())+'.width' |
---|
[00b7ddf0] | 1676 | if not self.isCheckable(row) or param_name not in list(param_dict.keys()): |
---|
[919d47c] | 1677 | return |
---|
| 1678 | # modify the param value |
---|
| 1679 | param_repr = GuiUtils.formatNumber(param_dict[param_name][0], high=True) |
---|
| 1680 | self._model_model.item(row, 0).child(0).child(0,1).setText(param_repr) |
---|
[906e0c7] | 1681 | # modify the param error |
---|
| 1682 | if self.has_error_column: |
---|
| 1683 | error_repr = GuiUtils.formatNumber(param_dict[param_name][1], high=True) |
---|
| 1684 | self._model_model.item(row, 0).child(0).child(0,2).setText(error_repr) |
---|
[919d47c] | 1685 | |
---|
| 1686 | def createErrorColumn(row): |
---|
[f182f93] | 1687 | # Utility function for error column update |
---|
| 1688 | item = QtGui.QStandardItem() |
---|
[919d47c] | 1689 | def createItem(param_name): |
---|
[f182f93] | 1690 | error_repr = GuiUtils.formatNumber(param_dict[param_name][1], high=True) |
---|
| 1691 | item.setText(error_repr) |
---|
[919d47c] | 1692 | def curr_param(): |
---|
| 1693 | return str(self._model_model.item(row, 0).text()) |
---|
| 1694 | |
---|
[b3e8629] | 1695 | [createItem(param_name) for param_name in list(param_dict.keys()) if curr_param() == param_name] |
---|
[919d47c] | 1696 | |
---|
[f182f93] | 1697 | error_column.append(item) |
---|
| 1698 | |
---|
[906e0c7] | 1699 | def createPolyErrorColumn(row): |
---|
| 1700 | # Utility function for error column update in the polydispersity sub-rows |
---|
| 1701 | # NOTE: only creates empty items; updatePolyValues adds the error value |
---|
| 1702 | item = self._model_model.item(row, 0) |
---|
| 1703 | if not item.hasChildren(): |
---|
| 1704 | return |
---|
| 1705 | poly_item = item.child(0) |
---|
| 1706 | if not poly_item.hasChildren(): |
---|
| 1707 | return |
---|
| 1708 | poly_item.insertColumn(2, [QtGui.QStandardItem("")]) |
---|
| 1709 | |
---|
| 1710 | if not self.has_error_column: |
---|
| 1711 | # create top-level error column |
---|
| 1712 | error_column = [] |
---|
| 1713 | self.lstParams.itemDelegate().addErrorColumn() |
---|
| 1714 | self.iterateOverModel(createErrorColumn) |
---|
| 1715 | |
---|
| 1716 | self._model_model.insertColumn(2, error_column) |
---|
| 1717 | |
---|
| 1718 | FittingUtilities.addErrorHeadersToModel(self._model_model) |
---|
| 1719 | |
---|
| 1720 | # create error column in polydispersity sub-rows |
---|
| 1721 | self.iterateOverModel(createPolyErrorColumn) |
---|
| 1722 | |
---|
| 1723 | self.has_error_column = True |
---|
| 1724 | |
---|
[c2f3ca2] | 1725 | # block signals temporarily, so we don't end up |
---|
| 1726 | # updating charts with every single model change on the end of fitting |
---|
[d2007a8] | 1727 | self._model_model.dataChanged.disconnect() |
---|
[d7ff531] | 1728 | self.iterateOverModel(updateFittedValues) |
---|
[919d47c] | 1729 | self.iterateOverModel(updatePolyValues) |
---|
[d2007a8] | 1730 | self._model_model.dataChanged.connect(self.onMainParamsChange) |
---|
[f182f93] | 1731 | |
---|
[8e2cd79] | 1732 | def iterateOverPolyModel(self, func): |
---|
| 1733 | """ |
---|
| 1734 | Take func and throw it inside the poly model row loop |
---|
| 1735 | """ |
---|
| 1736 | for row_i in range(self._poly_model.rowCount()): |
---|
| 1737 | func(row_i) |
---|
| 1738 | |
---|
[aca8418] | 1739 | def updatePolyModelFromList(self, param_dict): |
---|
| 1740 | """ |
---|
| 1741 | Update the polydispersity model with new parameters, create the errors column |
---|
| 1742 | """ |
---|
| 1743 | assert isinstance(param_dict, dict) |
---|
| 1744 | if not dict: |
---|
| 1745 | return |
---|
| 1746 | |
---|
| 1747 | def updateFittedValues(row_i): |
---|
| 1748 | # Utility function for main model update |
---|
| 1749 | # internal so can use closure for param_dict |
---|
| 1750 | if row_i >= self._poly_model.rowCount(): |
---|
| 1751 | return |
---|
| 1752 | param_name = str(self._poly_model.item(row_i, 0).text()).rsplit()[-1] + '.width' |
---|
[b3e8629] | 1753 | if param_name not in list(param_dict.keys()): |
---|
[aca8418] | 1754 | return |
---|
| 1755 | # modify the param value |
---|
| 1756 | param_repr = GuiUtils.formatNumber(param_dict[param_name][0], high=True) |
---|
| 1757 | self._poly_model.item(row_i, 1).setText(param_repr) |
---|
[c2f3ca2] | 1758 | self.kernel_module.setParam(param_name, param_dict[param_name][0]) |
---|
[aca8418] | 1759 | if self.has_poly_error_column: |
---|
| 1760 | error_repr = GuiUtils.formatNumber(param_dict[param_name][1], high=True) |
---|
| 1761 | self._poly_model.item(row_i, 2).setText(error_repr) |
---|
| 1762 | |
---|
| 1763 | def createErrorColumn(row_i): |
---|
| 1764 | # Utility function for error column update |
---|
| 1765 | if row_i >= self._poly_model.rowCount(): |
---|
| 1766 | return |
---|
| 1767 | item = QtGui.QStandardItem() |
---|
[919d47c] | 1768 | |
---|
| 1769 | def createItem(param_name): |
---|
[aca8418] | 1770 | error_repr = GuiUtils.formatNumber(param_dict[param_name][1], high=True) |
---|
| 1771 | item.setText(error_repr) |
---|
[919d47c] | 1772 | |
---|
| 1773 | def poly_param(): |
---|
| 1774 | return str(self._poly_model.item(row_i, 0).text()).rsplit()[-1] + '.width' |
---|
| 1775 | |
---|
[b3e8629] | 1776 | [createItem(param_name) for param_name in list(param_dict.keys()) if poly_param() == param_name] |
---|
[919d47c] | 1777 | |
---|
[aca8418] | 1778 | error_column.append(item) |
---|
| 1779 | |
---|
| 1780 | # block signals temporarily, so we don't end up |
---|
| 1781 | # updating charts with every single model change on the end of fitting |
---|
[d2007a8] | 1782 | self._poly_model.dataChanged.disconnect() |
---|
[8e2cd79] | 1783 | self.iterateOverPolyModel(updateFittedValues) |
---|
[d2007a8] | 1784 | self._poly_model.dataChanged.connect(self.onPolyModelChange) |
---|
[aca8418] | 1785 | |
---|
| 1786 | if self.has_poly_error_column: |
---|
| 1787 | return |
---|
| 1788 | |
---|
[8eaa101] | 1789 | self.lstPoly.itemDelegate().addErrorColumn() |
---|
[aca8418] | 1790 | error_column = [] |
---|
[8e2cd79] | 1791 | self.iterateOverPolyModel(createErrorColumn) |
---|
[aca8418] | 1792 | |
---|
| 1793 | # switch off reponse to model change |
---|
| 1794 | self._poly_model.insertColumn(2, error_column) |
---|
| 1795 | FittingUtilities.addErrorPolyHeadersToModel(self._poly_model) |
---|
| 1796 | |
---|
| 1797 | self.has_poly_error_column = True |
---|
| 1798 | |
---|
[8e2cd79] | 1799 | def iterateOverMagnetModel(self, func): |
---|
| 1800 | """ |
---|
| 1801 | Take func and throw it inside the magnet model row loop |
---|
| 1802 | """ |
---|
[30339cc] | 1803 | for row_i in range(self._magnet_model.rowCount()): |
---|
[8e2cd79] | 1804 | func(row_i) |
---|
| 1805 | |
---|
[b00414d] | 1806 | def updateMagnetModelFromList(self, param_dict): |
---|
| 1807 | """ |
---|
| 1808 | Update the magnetic model with new parameters, create the errors column |
---|
| 1809 | """ |
---|
| 1810 | assert isinstance(param_dict, dict) |
---|
| 1811 | if not dict: |
---|
| 1812 | return |
---|
[3b3b40b] | 1813 | if self._magnet_model.rowCount() == 0: |
---|
[cee5c78] | 1814 | return |
---|
[b00414d] | 1815 | |
---|
| 1816 | def updateFittedValues(row): |
---|
| 1817 | # Utility function for main model update |
---|
| 1818 | # internal so can use closure for param_dict |
---|
[cee5c78] | 1819 | if self._magnet_model.item(row, 0) is None: |
---|
| 1820 | return |
---|
[b00414d] | 1821 | param_name = str(self._magnet_model.item(row, 0).text()) |
---|
[b3e8629] | 1822 | if param_name not in list(param_dict.keys()): |
---|
[b00414d] | 1823 | return |
---|
| 1824 | # modify the param value |
---|
| 1825 | param_repr = GuiUtils.formatNumber(param_dict[param_name][0], high=True) |
---|
| 1826 | self._magnet_model.item(row, 1).setText(param_repr) |
---|
[c2f3ca2] | 1827 | self.kernel_module.setParam(param_name, param_dict[param_name][0]) |
---|
[b00414d] | 1828 | if self.has_magnet_error_column: |
---|
| 1829 | error_repr = GuiUtils.formatNumber(param_dict[param_name][1], high=True) |
---|
| 1830 | self._magnet_model.item(row, 2).setText(error_repr) |
---|
| 1831 | |
---|
| 1832 | def createErrorColumn(row): |
---|
| 1833 | # Utility function for error column update |
---|
| 1834 | item = QtGui.QStandardItem() |
---|
| 1835 | def createItem(param_name): |
---|
| 1836 | error_repr = GuiUtils.formatNumber(param_dict[param_name][1], high=True) |
---|
| 1837 | item.setText(error_repr) |
---|
| 1838 | def curr_param(): |
---|
| 1839 | return str(self._magnet_model.item(row, 0).text()) |
---|
| 1840 | |
---|
[b3e8629] | 1841 | [createItem(param_name) for param_name in list(param_dict.keys()) if curr_param() == param_name] |
---|
[b00414d] | 1842 | |
---|
| 1843 | error_column.append(item) |
---|
| 1844 | |
---|
| 1845 | # block signals temporarily, so we don't end up |
---|
| 1846 | # updating charts with every single model change on the end of fitting |
---|
[d2007a8] | 1847 | self._magnet_model.dataChanged.disconnect() |
---|
[8e2cd79] | 1848 | self.iterateOverMagnetModel(updateFittedValues) |
---|
[d2007a8] | 1849 | self._magnet_model.dataChanged.connect(self.onMagnetModelChange) |
---|
[b00414d] | 1850 | |
---|
| 1851 | if self.has_magnet_error_column: |
---|
| 1852 | return |
---|
| 1853 | |
---|
| 1854 | self.lstMagnetic.itemDelegate().addErrorColumn() |
---|
| 1855 | error_column = [] |
---|
[8e2cd79] | 1856 | self.iterateOverMagnetModel(createErrorColumn) |
---|
[b00414d] | 1857 | |
---|
| 1858 | # switch off reponse to model change |
---|
| 1859 | self._magnet_model.insertColumn(2, error_column) |
---|
| 1860 | FittingUtilities.addErrorHeadersToModel(self._magnet_model) |
---|
| 1861 | |
---|
| 1862 | self.has_magnet_error_column = True |
---|
| 1863 | |
---|
[0268aed] | 1864 | def onPlot(self): |
---|
| 1865 | """ |
---|
| 1866 | Plot the current set of data |
---|
| 1867 | """ |
---|
[d48cc19] | 1868 | # Regardless of previous state, this should now be `plot show` functionality only |
---|
| 1869 | self.cmdPlot.setText("Show Plot") |
---|
[88e1f57] | 1870 | # Force data recalculation so existing charts are updated |
---|
[d1e4689] | 1871 | if not self.data_is_loaded: |
---|
| 1872 | self.showTheoryPlot() |
---|
| 1873 | else: |
---|
| 1874 | self.showPlot() |
---|
[0cd98a1] | 1875 | # This is an important processEvent. |
---|
| 1876 | # This allows charts to be properly updated in order |
---|
| 1877 | # of plots being applied. |
---|
| 1878 | QtWidgets.QApplication.processEvents() |
---|
[33d5956] | 1879 | self.recalculatePlotData() # recalc+plot theory again (2nd) |
---|
[d48cc19] | 1880 | |
---|
[9a7c81c] | 1881 | def onSmearingOptionsUpdate(self): |
---|
| 1882 | """ |
---|
| 1883 | React to changes in the smearing widget |
---|
| 1884 | """ |
---|
| 1885 | self.calculateQGridForModel() |
---|
| 1886 | |
---|
[d48cc19] | 1887 | def recalculatePlotData(self): |
---|
| 1888 | """ |
---|
| 1889 | Generate a new dataset for model |
---|
| 1890 | """ |
---|
[180bd54] | 1891 | if not self.data_is_loaded: |
---|
[0268aed] | 1892 | self.createDefaultDataset() |
---|
| 1893 | self.calculateQGridForModel() |
---|
| 1894 | |
---|
[d1e4689] | 1895 | def showTheoryPlot(self): |
---|
| 1896 | """ |
---|
| 1897 | Show the current theory plot in MPL |
---|
| 1898 | """ |
---|
| 1899 | # Show the chart if ready |
---|
| 1900 | if self.theory_item is None: |
---|
| 1901 | self.recalculatePlotData() |
---|
[33d5956] | 1902 | elif self.model_data: |
---|
[f9be147] | 1903 | self._requestPlots(self.model_data.filename, self.theory_item.model()) |
---|
[d1e4689] | 1904 | |
---|
[d48cc19] | 1905 | def showPlot(self): |
---|
| 1906 | """ |
---|
| 1907 | Show the current plot in MPL |
---|
| 1908 | """ |
---|
| 1909 | # Show the chart if ready |
---|
[d1e4689] | 1910 | data_to_show = self.data |
---|
[9ce69ec] | 1911 | # Any models for this page |
---|
| 1912 | current_index = self.all_data[self.data_index] |
---|
[f9be147] | 1913 | item = self._requestPlots(self.data.filename, current_index.model()) |
---|
| 1914 | if item: |
---|
| 1915 | # fit+data has not been shown - show just data |
---|
| 1916 | self.communicate.plotRequestedSignal.emit([item, data_to_show], self.tab_id) |
---|
| 1917 | |
---|
| 1918 | def _requestPlots(self, item_name, item_model): |
---|
| 1919 | """ |
---|
| 1920 | Emits plotRequestedSignal for all plots found in the given model under the provided item name. |
---|
| 1921 | """ |
---|
| 1922 | fitpage_name = "" if self.tab_id is None else "M"+str(self.tab_id) |
---|
| 1923 | plots = GuiUtils.plotsFromFilename(item_name, item_model) |
---|
[9ce69ec] | 1924 | # Has the fitted data been shown? |
---|
| 1925 | data_shown = False |
---|
[f9be147] | 1926 | item = None |
---|
[9ce69ec] | 1927 | for item, plot in plots.items(): |
---|
| 1928 | if fitpage_name in plot.name: |
---|
| 1929 | data_shown = True |
---|
| 1930 | self.communicate.plotRequestedSignal.emit([item, plot], self.tab_id) |
---|
[f9be147] | 1931 | # return the last data item seen, if nothing was plotted; supposed to be just data) |
---|
| 1932 | return None if data_shown else item |
---|
[d48cc19] | 1933 | |
---|
[180bd54] | 1934 | def onOptionsUpdate(self): |
---|
[0268aed] | 1935 | """ |
---|
[180bd54] | 1936 | Update local option values and replot |
---|
[0268aed] | 1937 | """ |
---|
[180bd54] | 1938 | self.q_range_min, self.q_range_max, self.npts, self.log_points, self.weighting = \ |
---|
| 1939 | self.options_widget.state() |
---|
[61a92d4] | 1940 | # set Q range labels on the main tab |
---|
[34e5170] | 1941 | self.lblMinRangeDef.setText(GuiUtils.formatNumber(self.q_range_min, high=True)) |
---|
| 1942 | self.lblMaxRangeDef.setText(GuiUtils.formatNumber(self.q_range_max, high=True)) |
---|
[d48cc19] | 1943 | self.recalculatePlotData() |
---|
[6c8fb2c] | 1944 | |
---|
[0268aed] | 1945 | def setDefaultStructureCombo(self): |
---|
| 1946 | """ |
---|
| 1947 | Fill in the structure factors combo box with defaults |
---|
| 1948 | """ |
---|
| 1949 | structure_factor_list = self.master_category_dict.pop(CATEGORY_STRUCTURE) |
---|
| 1950 | factors = [factor[0] for factor in structure_factor_list] |
---|
| 1951 | factors.insert(0, STRUCTURE_DEFAULT) |
---|
| 1952 | self.cbStructureFactor.clear() |
---|
| 1953 | self.cbStructureFactor.addItems(sorted(factors)) |
---|
| 1954 | |
---|
[4d457df] | 1955 | def createDefaultDataset(self): |
---|
| 1956 | """ |
---|
| 1957 | Generate default Dataset 1D/2D for the given model |
---|
| 1958 | """ |
---|
| 1959 | # Create default datasets if no data passed |
---|
| 1960 | if self.is2D: |
---|
[180bd54] | 1961 | qmax = self.q_range_max/np.sqrt(2) |
---|
[4d457df] | 1962 | qstep = self.npts |
---|
| 1963 | self.logic.createDefault2dData(qmax, qstep, self.tab_id) |
---|
[180bd54] | 1964 | return |
---|
| 1965 | elif self.log_points: |
---|
| 1966 | qmin = -10.0 if self.q_range_min < 1.e-10 else np.log10(self.q_range_min) |
---|
[1bc27f1] | 1967 | qmax = 10.0 if self.q_range_max > 1.e10 else np.log10(self.q_range_max) |
---|
[180bd54] | 1968 | interval = np.logspace(start=qmin, stop=qmax, num=self.npts, endpoint=True, base=10.0) |
---|
[4d457df] | 1969 | else: |
---|
[180bd54] | 1970 | interval = np.linspace(start=self.q_range_min, stop=self.q_range_max, |
---|
[1bc27f1] | 1971 | num=self.npts, endpoint=True) |
---|
[180bd54] | 1972 | self.logic.createDefault1dData(interval, self.tab_id) |
---|
[60af928] | 1973 | |
---|
[5236449] | 1974 | def readCategoryInfo(self): |
---|
[60af928] | 1975 | """ |
---|
| 1976 | Reads the categories in from file |
---|
| 1977 | """ |
---|
| 1978 | self.master_category_dict = defaultdict(list) |
---|
| 1979 | self.by_model_dict = defaultdict(list) |
---|
| 1980 | self.model_enabled_dict = defaultdict(bool) |
---|
| 1981 | |
---|
[cbcdd2c] | 1982 | categorization_file = CategoryInstaller.get_user_file() |
---|
| 1983 | if not os.path.isfile(categorization_file): |
---|
| 1984 | categorization_file = CategoryInstaller.get_default_file() |
---|
| 1985 | with open(categorization_file, 'rb') as cat_file: |
---|
[60af928] | 1986 | self.master_category_dict = json.load(cat_file) |
---|
[5236449] | 1987 | self.regenerateModelDict() |
---|
[60af928] | 1988 | |
---|
[5236449] | 1989 | # Load the model dict |
---|
| 1990 | models = load_standard_models() |
---|
| 1991 | for model in models: |
---|
| 1992 | self.models[model.name] = model |
---|
| 1993 | |
---|
[3b3b40b] | 1994 | self.readCustomCategoryInfo() |
---|
| 1995 | |
---|
| 1996 | def readCustomCategoryInfo(self): |
---|
| 1997 | """ |
---|
| 1998 | Reads the custom model category |
---|
| 1999 | """ |
---|
| 2000 | #Looking for plugins |
---|
| 2001 | self.plugins = list(self.custom_models.values()) |
---|
| 2002 | plugin_list = [] |
---|
| 2003 | for name, plug in self.custom_models.items(): |
---|
| 2004 | self.models[name] = plug |
---|
| 2005 | plugin_list.append([name, True]) |
---|
[2dce1d8] | 2006 | if plugin_list: |
---|
| 2007 | self.master_category_dict[CATEGORY_CUSTOM] = plugin_list |
---|
[3b3b40b] | 2008 | |
---|
[5236449] | 2009 | def regenerateModelDict(self): |
---|
[60af928] | 2010 | """ |
---|
[cbcdd2c] | 2011 | Regenerates self.by_model_dict which has each model name as the |
---|
[60af928] | 2012 | key and the list of categories belonging to that model |
---|
| 2013 | along with the enabled mapping |
---|
| 2014 | """ |
---|
| 2015 | self.by_model_dict = defaultdict(list) |
---|
| 2016 | for category in self.master_category_dict: |
---|
| 2017 | for (model, enabled) in self.master_category_dict[category]: |
---|
| 2018 | self.by_model_dict[model].append(category) |
---|
| 2019 | self.model_enabled_dict[model] = enabled |
---|
| 2020 | |
---|
[86f88d1] | 2021 | def addBackgroundToModel(self, model): |
---|
| 2022 | """ |
---|
| 2023 | Adds background parameter with default values to the model |
---|
| 2024 | """ |
---|
[cbcdd2c] | 2025 | assert isinstance(model, QtGui.QStandardItemModel) |
---|
[86f88d1] | 2026 | checked_list = ['background', '0.001', '-inf', 'inf', '1/cm'] |
---|
[4d457df] | 2027 | FittingUtilities.addCheckedListToModel(model, checked_list) |
---|
[2add354] | 2028 | last_row = model.rowCount()-1 |
---|
| 2029 | model.item(last_row, 0).setEditable(False) |
---|
| 2030 | model.item(last_row, 4).setEditable(False) |
---|
[86f88d1] | 2031 | |
---|
| 2032 | def addScaleToModel(self, model): |
---|
| 2033 | """ |
---|
| 2034 | Adds scale parameter with default values to the model |
---|
| 2035 | """ |
---|
[cbcdd2c] | 2036 | assert isinstance(model, QtGui.QStandardItemModel) |
---|
[86f88d1] | 2037 | checked_list = ['scale', '1.0', '0.0', 'inf', ''] |
---|
[4d457df] | 2038 | FittingUtilities.addCheckedListToModel(model, checked_list) |
---|
[2add354] | 2039 | last_row = model.rowCount()-1 |
---|
| 2040 | model.item(last_row, 0).setEditable(False) |
---|
| 2041 | model.item(last_row, 4).setEditable(False) |
---|
[86f88d1] | 2042 | |
---|
[9d266d2] | 2043 | def addWeightingToData(self, data): |
---|
| 2044 | """ |
---|
| 2045 | Adds weighting contribution to fitting data |
---|
[1bc27f1] | 2046 | """ |
---|
[b764ae5] | 2047 | new_data = copy.deepcopy(data) |
---|
[e1e3e09] | 2048 | # Send original data for weighting |
---|
[dc5ef15] | 2049 | weight = FittingUtilities.getWeight(data=data, is2d=self.is2D, flag=self.weighting) |
---|
[9a7c81c] | 2050 | if self.is2D: |
---|
[b764ae5] | 2051 | new_data.err_data = weight |
---|
[9a7c81c] | 2052 | else: |
---|
[b764ae5] | 2053 | new_data.dy = weight |
---|
| 2054 | |
---|
| 2055 | return new_data |
---|
[9d266d2] | 2056 | |
---|
[0268aed] | 2057 | def updateQRange(self): |
---|
| 2058 | """ |
---|
| 2059 | Updates Q Range display |
---|
| 2060 | """ |
---|
| 2061 | if self.data_is_loaded: |
---|
| 2062 | self.q_range_min, self.q_range_max, self.npts = self.logic.computeDataRange() |
---|
| 2063 | # set Q range labels on the main tab |
---|
[a486918] | 2064 | self.lblMinRangeDef.setText(GuiUtils.formatNumber(self.q_range_min, high=True)) |
---|
| 2065 | self.lblMaxRangeDef.setText(GuiUtils.formatNumber(self.q_range_max, high=True)) |
---|
[0268aed] | 2066 | # set Q range labels on the options tab |
---|
[180bd54] | 2067 | self.options_widget.updateQRange(self.q_range_min, self.q_range_max, self.npts) |
---|
[0268aed] | 2068 | |
---|
[4d457df] | 2069 | def SASModelToQModel(self, model_name, structure_factor=None): |
---|
[60af928] | 2070 | """ |
---|
[cbcdd2c] | 2071 | Setting model parameters into table based on selected category |
---|
[60af928] | 2072 | """ |
---|
| 2073 | # Crete/overwrite model items |
---|
| 2074 | self._model_model.clear() |
---|
[f3a19ad] | 2075 | self._poly_model.clear() |
---|
| 2076 | self._magnet_model.clear() |
---|
[5236449] | 2077 | |
---|
[f3a19ad] | 2078 | if model_name is None: |
---|
| 2079 | if structure_factor not in (None, "None"): |
---|
| 2080 | # S(Q) on its own, treat the same as a form factor |
---|
| 2081 | self.kernel_module = None |
---|
| 2082 | self.fromStructureFactorToQModel(structure_factor) |
---|
| 2083 | else: |
---|
| 2084 | # No models selected |
---|
| 2085 | return |
---|
[cd31251] | 2086 | else: |
---|
[fd1ae6d1] | 2087 | self.fromModelToQModel(model_name) |
---|
[70f4458] | 2088 | self.addExtraShells() |
---|
[5236449] | 2089 | |
---|
[fd1ae6d1] | 2090 | # Allow the SF combobox visibility for the given sasmodel |
---|
| 2091 | self.enableStructureFactorControl(structure_factor) |
---|
[4ea8020] | 2092 | |
---|
| 2093 | # Add S(Q) |
---|
[605d944] | 2094 | if self.cbStructureFactor.isEnabled(): |
---|
| 2095 | structure_factor = self.cbStructureFactor.currentText() |
---|
| 2096 | self.fromStructureFactorToQModel(structure_factor) |
---|
[cd31251] | 2097 | |
---|
[f3a19ad] | 2098 | # Add polydispersity to the model |
---|
[4ea8020] | 2099 | self.poly_params = {} |
---|
[f3a19ad] | 2100 | self.setPolyModel() |
---|
| 2101 | # Add magnetic parameters to the model |
---|
[4ea8020] | 2102 | self.magnet_params = {} |
---|
[f3a19ad] | 2103 | self.setMagneticModel() |
---|
[5236449] | 2104 | |
---|
| 2105 | # Now we claim the model has been loaded |
---|
[86f88d1] | 2106 | self.model_is_loaded = True |
---|
[be8f4b0] | 2107 | # Change the model name to a monicker |
---|
| 2108 | self.kernel_module.name = self.modelName() |
---|
[9a7c81c] | 2109 | # Update the smearing tab |
---|
| 2110 | self.smearing_widget.updateKernelModel(kernel_model=self.kernel_module) |
---|
[86f88d1] | 2111 | |
---|
[fd1ae6d1] | 2112 | # (Re)-create headers |
---|
| 2113 | FittingUtilities.addHeadersToModel(self._model_model) |
---|
[6964d44] | 2114 | self.lstParams.header().setFont(self.boldFont) |
---|
[fd1ae6d1] | 2115 | |
---|
[5236449] | 2116 | # Update Q Ranges |
---|
| 2117 | self.updateQRange() |
---|
| 2118 | |
---|
[fd1ae6d1] | 2119 | def fromModelToQModel(self, model_name): |
---|
| 2120 | """ |
---|
| 2121 | Setting model parameters into QStandardItemModel based on selected _model_ |
---|
| 2122 | """ |
---|
[3b3b40b] | 2123 | name = model_name |
---|
[e3df84e] | 2124 | kernel_module = None |
---|
[3b3b40b] | 2125 | if self.cbCategory.currentText() == CATEGORY_CUSTOM: |
---|
| 2126 | # custom kernel load requires full path |
---|
| 2127 | name = os.path.join(ModelUtilities.find_plugins_dir(), model_name+".py") |
---|
[060413c] | 2128 | try: |
---|
| 2129 | kernel_module = generate.load_kernel_module(name) |
---|
[e3df84e] | 2130 | except ModuleNotFoundError as ex: |
---|
| 2131 | pass |
---|
[4f8c17f] | 2132 | except FileNotFoundError as ex: |
---|
| 2133 | # can happen when name attribute not the same as actual filename |
---|
| 2134 | pass |
---|
[e3df84e] | 2135 | |
---|
| 2136 | if kernel_module is None: |
---|
| 2137 | # mismatch between "name" attribute and actual filename. |
---|
| 2138 | curr_model = self.models[model_name] |
---|
| 2139 | name, _ = os.path.splitext(os.path.basename(curr_model.filename)) |
---|
| 2140 | try: |
---|
| 2141 | kernel_module = generate.load_kernel_module(name) |
---|
| 2142 | except ModuleNotFoundError as ex: |
---|
[bb477f5] | 2143 | logger.error("Can't find the model "+ str(ex)) |
---|
[e3df84e] | 2144 | return |
---|
[dc71408] | 2145 | |
---|
| 2146 | if hasattr(kernel_module, 'parameters'): |
---|
| 2147 | # built-in and custom models |
---|
| 2148 | self.model_parameters = modelinfo.make_parameter_table(getattr(kernel_module, 'parameters', [])) |
---|
| 2149 | |
---|
| 2150 | elif hasattr(kernel_module, 'model_info'): |
---|
| 2151 | # for sum/multiply models |
---|
| 2152 | self.model_parameters = kernel_module.model_info.parameters |
---|
| 2153 | |
---|
| 2154 | elif hasattr(kernel_module, 'Model') and hasattr(kernel_module.Model, "_model_info"): |
---|
| 2155 | # this probably won't work if there's no model_info, but just in case |
---|
| 2156 | self.model_parameters = kernel_module.Model._model_info.parameters |
---|
| 2157 | else: |
---|
| 2158 | # no parameters - default to blank table |
---|
| 2159 | msg = "No parameters found in model '{}'.".format(model_name) |
---|
| 2160 | logger.warning(msg) |
---|
| 2161 | self.model_parameters = modelinfo.ParameterTable([]) |
---|
[fd1ae6d1] | 2162 | |
---|
| 2163 | # Instantiate the current sasmodel |
---|
| 2164 | self.kernel_module = self.models[model_name]() |
---|
| 2165 | |
---|
[9ce69ec] | 2166 | # Change the model name to a monicker |
---|
| 2167 | self.kernel_module.name = self.modelName() |
---|
| 2168 | |
---|
[fd1ae6d1] | 2169 | # Explicitly add scale and background with default values |
---|
[6964d44] | 2170 | temp_undo_state = self.undo_supported |
---|
| 2171 | self.undo_supported = False |
---|
[fd1ae6d1] | 2172 | self.addScaleToModel(self._model_model) |
---|
| 2173 | self.addBackgroundToModel(self._model_model) |
---|
[6964d44] | 2174 | self.undo_supported = temp_undo_state |
---|
[fd1ae6d1] | 2175 | |
---|
[0d13814] | 2176 | self.shell_names = self.shellNamesList() |
---|
| 2177 | |
---|
[00b7ddf0] | 2178 | # Add heading row |
---|
| 2179 | FittingUtilities.addHeadingRowToModel(self._model_model, model_name) |
---|
[aca8418] | 2180 | |
---|
[fd1ae6d1] | 2181 | # Update the QModel |
---|
[04f775d] | 2182 | FittingUtilities.addParametersToModel( |
---|
| 2183 | self.model_parameters, |
---|
| 2184 | self.kernel_module, |
---|
[a758043] | 2185 | self.is2D, |
---|
| 2186 | self._model_model, |
---|
| 2187 | self.lstParams) |
---|
[fd1ae6d1] | 2188 | |
---|
| 2189 | def fromStructureFactorToQModel(self, structure_factor): |
---|
| 2190 | """ |
---|
| 2191 | Setting model parameters into QStandardItemModel based on selected _structure factor_ |
---|
| 2192 | """ |
---|
[605d944] | 2193 | if structure_factor is None or structure_factor=="None": |
---|
| 2194 | return |
---|
[18d5c94a] | 2195 | |
---|
[01b4877] | 2196 | product_params = None |
---|
| 2197 | |
---|
[5fb714b] | 2198 | if self.kernel_module is None: |
---|
| 2199 | # Structure factor is the only selected model; build it and show all its params |
---|
| 2200 | self.kernel_module = self.models[structure_factor]() |
---|
[9ce69ec] | 2201 | self.kernel_module.name = self.modelName() |
---|
[5fb714b] | 2202 | s_params = self.kernel_module._model_info.parameters |
---|
| 2203 | s_params_orig = s_params |
---|
[f3a19ad] | 2204 | else: |
---|
[5fb714b] | 2205 | s_kernel = self.models[structure_factor]() |
---|
| 2206 | p_kernel = self.kernel_module |
---|
[9562a6b] | 2207 | # need to reset multiplicity to get the right product |
---|
[672c0e97] | 2208 | if p_kernel.is_multiplicity_model: |
---|
| 2209 | p_kernel.multiplicity = p_kernel.multiplicity_info.number |
---|
[5d1440e1] | 2210 | |
---|
[f3a19ad] | 2211 | p_pars_len = len(p_kernel._model_info.parameters.kernel_parameters) |
---|
| 2212 | s_pars_len = len(s_kernel._model_info.parameters.kernel_parameters) |
---|
[fd1ae6d1] | 2213 | |
---|
[f3a19ad] | 2214 | self.kernel_module = MultiplicationModel(p_kernel, s_kernel) |
---|
[9ce69ec] | 2215 | # Modify the name to correspond to shown items |
---|
| 2216 | self.kernel_module.name = self.modelName() |
---|
[f3a19ad] | 2217 | all_params = self.kernel_module._model_info.parameters.kernel_parameters |
---|
| 2218 | all_param_names = [param.name for param in all_params] |
---|
[18d5c94a] | 2219 | |
---|
[f3a19ad] | 2220 | # S(Q) params from the product model are not necessarily the same as those from the S(Q) model; any |
---|
[5fb714b] | 2221 | # conflicting names with P(Q) params will cause a rename |
---|
[fd1ae6d1] | 2222 | |
---|
[f3a19ad] | 2223 | if "radius_effective_mode" in all_param_names: |
---|
| 2224 | # Show all parameters |
---|
[01b4877] | 2225 | # In this case, radius_effective is NOT pruned by sasmodels.product |
---|
[f3a19ad] | 2226 | s_params = modelinfo.ParameterTable(all_params[p_pars_len:p_pars_len+s_pars_len]) |
---|
| 2227 | s_params_orig = modelinfo.ParameterTable(s_kernel._model_info.parameters.kernel_parameters) |
---|
[01b4877] | 2228 | product_params = modelinfo.ParameterTable( |
---|
| 2229 | self.kernel_module._model_info.parameters.kernel_parameters[p_pars_len+s_pars_len:]) |
---|
[f3a19ad] | 2230 | else: |
---|
| 2231 | # Ensure radius_effective is not displayed |
---|
| 2232 | s_params_orig = modelinfo.ParameterTable(s_kernel._model_info.parameters.kernel_parameters[1:]) |
---|
| 2233 | if "radius_effective" in all_param_names: |
---|
[01b4877] | 2234 | # In this case, radius_effective is NOT pruned by sasmodels.product |
---|
[f3a19ad] | 2235 | s_params = modelinfo.ParameterTable(all_params[p_pars_len+1:p_pars_len+s_pars_len]) |
---|
[01b4877] | 2236 | product_params = modelinfo.ParameterTable( |
---|
| 2237 | self.kernel_module._model_info.parameters.kernel_parameters[p_pars_len+s_pars_len:]) |
---|
[f3a19ad] | 2238 | else: |
---|
[01b4877] | 2239 | # In this case, radius_effective is pruned by sasmodels.product |
---|
[f3a19ad] | 2240 | s_params = modelinfo.ParameterTable(all_params[p_pars_len:p_pars_len+s_pars_len-1]) |
---|
[01b4877] | 2241 | product_params = modelinfo.ParameterTable( |
---|
| 2242 | self.kernel_module._model_info.parameters.kernel_parameters[p_pars_len+s_pars_len-1:]) |
---|
[f3a19ad] | 2243 | |
---|
[00b7ddf0] | 2244 | # Add heading row |
---|
| 2245 | FittingUtilities.addHeadingRowToModel(self._model_model, structure_factor) |
---|
[0d72cac] | 2246 | |
---|
[b69b549] | 2247 | # Get new rows for QModel |
---|
| 2248 | # Any renamed parameters are stored as data in the relevant item, for later handling |
---|
[04f775d] | 2249 | FittingUtilities.addSimpleParametersToModel( |
---|
[01b4877] | 2250 | parameters=s_params, |
---|
| 2251 | is2D=self.is2D, |
---|
| 2252 | parameters_original=s_params_orig, |
---|
| 2253 | model=self._model_model, |
---|
| 2254 | view=self.lstParams) |
---|
| 2255 | |
---|
| 2256 | # Insert product-only params into QModel |
---|
| 2257 | if product_params: |
---|
| 2258 | prod_rows = FittingUtilities.addSimpleParametersToModel( |
---|
| 2259 | parameters=product_params, |
---|
| 2260 | is2D=self.is2D, |
---|
| 2261 | parameters_original=None, |
---|
| 2262 | model=self._model_model, |
---|
| 2263 | view=self.lstParams, |
---|
| 2264 | row_num=2) |
---|
| 2265 | |
---|
| 2266 | # Since this all happens after shells are dealt with and we've inserted rows, fix this counter |
---|
| 2267 | self._n_shells_row += len(prod_rows) |
---|
[fd1ae6d1] | 2268 | |
---|
[6dbff18] | 2269 | def haveParamsToFit(self): |
---|
| 2270 | """ |
---|
| 2271 | Finds out if there are any parameters ready to be fitted |
---|
| 2272 | """ |
---|
[d4216ac] | 2273 | if not self.logic.data_is_loaded: |
---|
| 2274 | return False |
---|
| 2275 | if self.main_params_to_fit: |
---|
| 2276 | return True |
---|
| 2277 | if self.chkPolydispersity.isChecked() and self.poly_params_to_fit: |
---|
| 2278 | return True |
---|
[a98014ab] | 2279 | if self.chkMagnetism.isChecked() and self.canHaveMagnetism() and self.magnet_params_to_fit: |
---|
[d4216ac] | 2280 | return True |
---|
| 2281 | return False |
---|
[6dbff18] | 2282 | |
---|
[d2007a8] | 2283 | def onMainParamsChange(self, top, bottom): |
---|
[cd31251] | 2284 | """ |
---|
| 2285 | Callback method for updating the sasmodel parameters with the GUI values |
---|
| 2286 | """ |
---|
[d2007a8] | 2287 | item = self._model_model.itemFromIndex(top) |
---|
| 2288 | |
---|
[cbcdd2c] | 2289 | model_column = item.column() |
---|
[cd31251] | 2290 | |
---|
| 2291 | if model_column == 0: |
---|
[f182f93] | 2292 | self.checkboxSelected(item) |
---|
[6dbff18] | 2293 | self.cmdFit.setEnabled(self.haveParamsToFit()) |
---|
[6964d44] | 2294 | # Update state stack |
---|
| 2295 | self.updateUndo() |
---|
[cd31251] | 2296 | return |
---|
| 2297 | |
---|
[f182f93] | 2298 | model_row = item.row() |
---|
| 2299 | name_index = self._model_model.index(model_row, 0) |
---|
[700b03b] | 2300 | name_item = self._model_model.itemFromIndex(name_index) |
---|
[f182f93] | 2301 | |
---|
[b00414d] | 2302 | # Extract changed value. |
---|
[2add354] | 2303 | try: |
---|
[fbfc488] | 2304 | value = GuiUtils.toDouble(item.text()) |
---|
[0261bc1] | 2305 | except TypeError: |
---|
[2add354] | 2306 | # Unparsable field |
---|
| 2307 | return |
---|
[fbfc488] | 2308 | |
---|
[700b03b] | 2309 | # if the item has user data, this is the actual parameter name (e.g. to handle duplicate names) |
---|
| 2310 | if name_item.data(QtCore.Qt.UserRole): |
---|
| 2311 | parameter_name = str(name_item.data(QtCore.Qt.UserRole)) |
---|
| 2312 | else: |
---|
| 2313 | parameter_name = str(self._model_model.data(name_index)) |
---|
[cbcdd2c] | 2314 | |
---|
[00b3b40] | 2315 | # Update the parameter value - note: this supports +/-inf as well |
---|
[8f2548c] | 2316 | param_column = self.lstParams.itemDelegate().param_value |
---|
| 2317 | min_column = self.lstParams.itemDelegate().param_min |
---|
| 2318 | max_column = self.lstParams.itemDelegate().param_max |
---|
| 2319 | if model_column == param_column: |
---|
[8a32a6ff] | 2320 | self.kernel_module.setParam(parameter_name, value) |
---|
[8f2548c] | 2321 | elif model_column == min_column: |
---|
[8a32a6ff] | 2322 | # min/max to be changed in self.kernel_module.details[parameter_name] = ['Ang', 0.0, inf] |
---|
[8f2548c] | 2323 | self.kernel_module.details[parameter_name][1] = value |
---|
| 2324 | elif model_column == max_column: |
---|
| 2325 | self.kernel_module.details[parameter_name][2] = value |
---|
| 2326 | else: |
---|
| 2327 | # don't update the chart |
---|
| 2328 | return |
---|
[00b3b40] | 2329 | |
---|
| 2330 | # TODO: magnetic params in self.kernel_module.details['M0:parameter_name'] = value |
---|
| 2331 | # TODO: multishell params in self.kernel_module.details[??] = value |
---|
[cbcdd2c] | 2332 | |
---|
[5a96a72] | 2333 | # handle display of effective radius parameter according to radius_effective_mode; pass ER into model if |
---|
| 2334 | # necessary |
---|
| 2335 | self.processEffectiveRadius() |
---|
| 2336 | |
---|
[d7ff531] | 2337 | # Force the chart update when actual parameters changed |
---|
| 2338 | if model_column == 1: |
---|
[d48cc19] | 2339 | self.recalculatePlotData() |
---|
[7d077d1] | 2340 | |
---|
[2241130] | 2341 | # Update state stack |
---|
[00b3b40] | 2342 | self.updateUndo() |
---|
[2241130] | 2343 | |
---|
[5a96a72] | 2344 | def processEffectiveRadius(self): |
---|
| 2345 | """ |
---|
| 2346 | Checks the value of radius_effective_mode, if existent, and processes radius_effective as necessary. |
---|
| 2347 | * mode == 0: This means 'unconstrained'; ensure use can specify ER. |
---|
| 2348 | * mode > 0: This means it is constrained to a P(Q)-computed value in sasmodels; prevent user from editing ER. |
---|
| 2349 | |
---|
| 2350 | Note: If ER has been computed, it is passed back to SasView as an intermediate result. That value must be |
---|
| 2351 | displayed for the user; that is not dealt with here, but in complete1D. |
---|
| 2352 | """ |
---|
| 2353 | ER_row = self.getRowFromName("radius_effective") |
---|
| 2354 | if ER_row is None: |
---|
| 2355 | return |
---|
| 2356 | |
---|
| 2357 | ER_mode_row = self.getRowFromName("radius_effective_mode") |
---|
| 2358 | if ER_mode_row is None: |
---|
| 2359 | return |
---|
| 2360 | |
---|
| 2361 | try: |
---|
| 2362 | ER_mode = int(self._model_model.item(ER_mode_row, 1).text()) |
---|
| 2363 | except ValueError: |
---|
| 2364 | logging.error("radius_effective_mode was set to an invalid value.") |
---|
| 2365 | return |
---|
| 2366 | |
---|
| 2367 | if ER_mode == 0: |
---|
| 2368 | # ensure the ER value can be modified by user |
---|
| 2369 | self.setParamEditableByRow(ER_row, True) |
---|
| 2370 | elif ER_mode > 0: |
---|
| 2371 | # ensure the ER value cannot be modified by user |
---|
| 2372 | self.setParamEditableByRow(ER_row, False) |
---|
| 2373 | else: |
---|
| 2374 | logging.error("radius_effective_mode was set to an invalid value.") |
---|
| 2375 | |
---|
| 2376 | def setParamEditableByRow(self, row, editable=True): |
---|
| 2377 | """ |
---|
| 2378 | Sets whether the user can edit a parameter in the table. If they cannot, the parameter name's font is changed, |
---|
| 2379 | the value itself cannot be edited if clicked on, and the parameter may not be fitted. |
---|
| 2380 | """ |
---|
| 2381 | item_name = self._model_model.item(row, 0) |
---|
| 2382 | item_value = self._model_model.item(row, 1) |
---|
| 2383 | |
---|
| 2384 | item_value.setEditable(editable) |
---|
| 2385 | |
---|
| 2386 | if editable: |
---|
| 2387 | # reset font |
---|
| 2388 | item_name.setFont(QtGui.QFont()) |
---|
| 2389 | # reset colour |
---|
| 2390 | item_name.setForeground(QtGui.QBrush()) |
---|
| 2391 | # make checkable |
---|
| 2392 | item_name.setCheckable(True) |
---|
| 2393 | else: |
---|
| 2394 | # change font |
---|
| 2395 | font = QtGui.QFont() |
---|
| 2396 | font.setItalic(True) |
---|
| 2397 | item_name.setFont(font) |
---|
| 2398 | # change colour |
---|
| 2399 | item_name.setForeground(QtGui.QBrush(QtGui.QColor(50, 50, 50))) |
---|
| 2400 | # make not checkable (and uncheck) |
---|
| 2401 | item_name.setCheckState(QtCore.Qt.Unchecked) |
---|
| 2402 | item_name.setCheckable(False) |
---|
| 2403 | |
---|
[7fd20fc] | 2404 | def isCheckable(self, row): |
---|
| 2405 | return self._model_model.item(row, 0).isCheckable() |
---|
| 2406 | |
---|
[f182f93] | 2407 | def checkboxSelected(self, item): |
---|
| 2408 | # Assure we're dealing with checkboxes |
---|
| 2409 | if not item.isCheckable(): |
---|
| 2410 | return |
---|
| 2411 | status = item.checkState() |
---|
| 2412 | |
---|
| 2413 | # If multiple rows selected - toggle all of them, filtering uncheckable |
---|
| 2414 | # Switch off signaling from the model to avoid recursion |
---|
| 2415 | self._model_model.blockSignals(True) |
---|
| 2416 | # Convert to proper indices and set requested enablement |
---|
[7fd20fc] | 2417 | self.setParameterSelection(status) |
---|
[f182f93] | 2418 | self._model_model.blockSignals(False) |
---|
| 2419 | |
---|
| 2420 | # update the list of parameters to fit |
---|
[6dbff18] | 2421 | self.main_params_to_fit = self.checkedListFromModel(self._model_model) |
---|
[c1e380e] | 2422 | |
---|
| 2423 | def checkedListFromModel(self, model): |
---|
| 2424 | """ |
---|
| 2425 | Returns list of checked parameters for given model |
---|
| 2426 | """ |
---|
| 2427 | def isChecked(row): |
---|
| 2428 | return model.item(row, 0).checkState() == QtCore.Qt.Checked |
---|
| 2429 | |
---|
| 2430 | return [str(model.item(row_index, 0).text()) |
---|
[b3e8629] | 2431 | for row_index in range(model.rowCount()) |
---|
[c1e380e] | 2432 | if isChecked(row_index)] |
---|
[f182f93] | 2433 | |
---|
[6fd4e36] | 2434 | def createNewIndex(self, fitted_data): |
---|
| 2435 | """ |
---|
| 2436 | Create a model or theory index with passed Data1D/Data2D |
---|
| 2437 | """ |
---|
| 2438 | if self.data_is_loaded: |
---|
[0268aed] | 2439 | if not fitted_data.name: |
---|
| 2440 | name = self.nameForFittedData(self.data.filename) |
---|
| 2441 | fitted_data.title = name |
---|
| 2442 | fitted_data.name = name |
---|
| 2443 | fitted_data.filename = name |
---|
[7d077d1] | 2444 | fitted_data.symbol = "Line" |
---|
[6fd4e36] | 2445 | self.updateModelIndex(fitted_data) |
---|
| 2446 | else: |
---|
[3ae9179] | 2447 | if not fitted_data.name: |
---|
| 2448 | name = self.nameForFittedData(self.kernel_module.id) |
---|
| 2449 | else: |
---|
| 2450 | name = fitted_data.name |
---|
[0268aed] | 2451 | fitted_data.title = name |
---|
| 2452 | fitted_data.filename = name |
---|
| 2453 | fitted_data.symbol = "Line" |
---|
[6fd4e36] | 2454 | self.createTheoryIndex(fitted_data) |
---|
[5d28d6b] | 2455 | # Switch to the theory tab for user's glee |
---|
| 2456 | self.communicate.changeDataExplorerTabSignal.emit(1) |
---|
[6fd4e36] | 2457 | |
---|
| 2458 | def updateModelIndex(self, fitted_data): |
---|
| 2459 | """ |
---|
| 2460 | Update a QStandardModelIndex containing model data |
---|
| 2461 | """ |
---|
[00b3b40] | 2462 | name = self.nameFromData(fitted_data) |
---|
[0268aed] | 2463 | # Make this a line if no other defined |
---|
[7d077d1] | 2464 | if hasattr(fitted_data, 'symbol') and fitted_data.symbol is None: |
---|
[0268aed] | 2465 | fitted_data.symbol = 'Line' |
---|
[6fd4e36] | 2466 | # Notify the GUI manager so it can update the main model in DataExplorer |
---|
[d4dac80] | 2467 | GuiUtils.updateModelItemWithPlot(self.all_data[self.data_index], fitted_data, name) |
---|
[6fd4e36] | 2468 | |
---|
| 2469 | def createTheoryIndex(self, fitted_data): |
---|
| 2470 | """ |
---|
| 2471 | Create a QStandardModelIndex containing model data |
---|
| 2472 | """ |
---|
[00b3b40] | 2473 | name = self.nameFromData(fitted_data) |
---|
| 2474 | # Notify the GUI manager so it can create the theory model in DataExplorer |
---|
[cb90b65] | 2475 | self.theory_item = GuiUtils.createModelItemWithPlot(fitted_data, name=name) |
---|
| 2476 | self.communicate.updateTheoryFromPerspectiveSignal.emit(self.theory_item) |
---|
[00b3b40] | 2477 | |
---|
| 2478 | def nameFromData(self, fitted_data): |
---|
| 2479 | """ |
---|
| 2480 | Return name for the dataset. Terribly impure function. |
---|
| 2481 | """ |
---|
[0268aed] | 2482 | if fitted_data.name is None: |
---|
[00b3b40] | 2483 | name = self.nameForFittedData(self.logic.data.filename) |
---|
[0268aed] | 2484 | fitted_data.title = name |
---|
| 2485 | fitted_data.name = name |
---|
| 2486 | fitted_data.filename = name |
---|
| 2487 | else: |
---|
| 2488 | name = fitted_data.name |
---|
[00b3b40] | 2489 | return name |
---|
[5236449] | 2490 | |
---|
[4d457df] | 2491 | def methodCalculateForData(self): |
---|
| 2492 | '''return the method for data calculation''' |
---|
| 2493 | return Calc1D if isinstance(self.data, Data1D) else Calc2D |
---|
| 2494 | |
---|
| 2495 | def methodCompleteForData(self): |
---|
| 2496 | '''return the method for result parsin on calc complete ''' |
---|
[d4dac80] | 2497 | return self.completed1D if isinstance(self.data, Data1D) else self.completed2D |
---|
[4d457df] | 2498 | |
---|
[66d4370] | 2499 | def updateKernelModelWithExtraParams(self, model=None): |
---|
| 2500 | """ |
---|
| 2501 | Updates kernel model 'model' with extra parameters from |
---|
| 2502 | the polydisp and magnetism tab, if the tabs are enabled |
---|
| 2503 | """ |
---|
| 2504 | if model is None: return |
---|
| 2505 | if not hasattr(model, 'setParam'): return |
---|
| 2506 | |
---|
| 2507 | # add polydisperse parameters if asked |
---|
[2d47985] | 2508 | if self.chkPolydispersity.isChecked() and self._poly_model.rowCount() > 0: |
---|
[66d4370] | 2509 | for key, value in self.poly_params.items(): |
---|
| 2510 | model.setParam(key, value) |
---|
| 2511 | # add magnetic params if asked |
---|
[a98014ab] | 2512 | if self.chkMagnetism.isChecked() and self.canHaveMagnetism() and self._magnet_model.rowCount() > 0: |
---|
[91f4884] | 2513 | for key, value in self.magnet_params.items(): |
---|
[66d4370] | 2514 | model.setParam(key, value) |
---|
| 2515 | |
---|
[d4dac80] | 2516 | def calculateQGridForModelExt(self, data=None, model=None, completefn=None, use_threads=True): |
---|
[86f88d1] | 2517 | """ |
---|
[d4dac80] | 2518 | Wrapper for Calc1D/2D calls |
---|
[86f88d1] | 2519 | """ |
---|
[d4dac80] | 2520 | if data is None: |
---|
| 2521 | data = self.data |
---|
| 2522 | if model is None: |
---|
[66d4370] | 2523 | model = copy.deepcopy(self.kernel_module) |
---|
| 2524 | self.updateKernelModelWithExtraParams(model) |
---|
| 2525 | |
---|
[d4dac80] | 2526 | if completefn is None: |
---|
| 2527 | completefn = self.methodCompleteForData() |
---|
[9a7c81c] | 2528 | smearer = self.smearing_widget.smearer() |
---|
[b764ae5] | 2529 | weight = FittingUtilities.getWeight(data=data, is2d=self.is2D, flag=self.weighting) |
---|
| 2530 | |
---|
[557fc498] | 2531 | # Disable buttons/table |
---|
| 2532 | self.disableInteractiveElements() |
---|
[4d457df] | 2533 | # Awful API to a backend method. |
---|
[d4dac80] | 2534 | calc_thread = self.methodCalculateForData()(data=data, |
---|
| 2535 | model=model, |
---|
[1bc27f1] | 2536 | page_id=0, |
---|
| 2537 | qmin=self.q_range_min, |
---|
| 2538 | qmax=self.q_range_max, |
---|
[9a7c81c] | 2539 | smearer=smearer, |
---|
[1bc27f1] | 2540 | state=None, |
---|
[b764ae5] | 2541 | weight=weight, |
---|
[1bc27f1] | 2542 | fid=None, |
---|
| 2543 | toggle_mode_on=False, |
---|
[d4dac80] | 2544 | completefn=completefn, |
---|
[1bc27f1] | 2545 | update_chisqr=True, |
---|
| 2546 | exception_handler=self.calcException, |
---|
| 2547 | source=None) |
---|
[d4dac80] | 2548 | if use_threads: |
---|
| 2549 | if LocalConfig.USING_TWISTED: |
---|
| 2550 | # start the thread with twisted |
---|
| 2551 | thread = threads.deferToThread(calc_thread.compute) |
---|
| 2552 | thread.addCallback(completefn) |
---|
| 2553 | thread.addErrback(self.calculateDataFailed) |
---|
| 2554 | else: |
---|
| 2555 | # Use the old python threads + Queue |
---|
| 2556 | calc_thread.queue() |
---|
| 2557 | calc_thread.ready(2.5) |
---|
| 2558 | else: |
---|
| 2559 | results = calc_thread.compute() |
---|
| 2560 | completefn(results) |
---|
[4d457df] | 2561 | |
---|
[d4dac80] | 2562 | def calculateQGridForModel(self): |
---|
| 2563 | """ |
---|
| 2564 | Prepare the fitting data object, based on current ModelModel |
---|
| 2565 | """ |
---|
| 2566 | if self.kernel_module is None: |
---|
| 2567 | return |
---|
| 2568 | self.calculateQGridForModelExt() |
---|
[6964d44] | 2569 | |
---|
[aca8418] | 2570 | def calculateDataFailed(self, reason): |
---|
[6964d44] | 2571 | """ |
---|
[c1e380e] | 2572 | Thread returned error |
---|
[6964d44] | 2573 | """ |
---|
[557fc498] | 2574 | # Bring the GUI to normal state |
---|
| 2575 | self.enableInteractiveElements() |
---|
[b3e8629] | 2576 | print("Calculate Data failed with ", reason) |
---|
[5236449] | 2577 | |
---|
[d4dac80] | 2578 | def completed1D(self, return_data): |
---|
| 2579 | self.Calc1DFinishedSignal.emit(return_data) |
---|
| 2580 | |
---|
| 2581 | def completed2D(self, return_data): |
---|
| 2582 | self.Calc2DFinishedSignal.emit(return_data) |
---|
| 2583 | |
---|
[cbcdd2c] | 2584 | def complete1D(self, return_data): |
---|
[5236449] | 2585 | """ |
---|
[4d457df] | 2586 | Plot the current 1D data |
---|
| 2587 | """ |
---|
[557fc498] | 2588 | # Bring the GUI to normal state |
---|
| 2589 | self.enableInteractiveElements() |
---|
[9ce69ec] | 2590 | if return_data is None: |
---|
| 2591 | return |
---|
[d48cc19] | 2592 | fitted_data = self.logic.new1DPlot(return_data, self.tab_id) |
---|
[d1e4689] | 2593 | |
---|
[712db9e] | 2594 | # assure the current index is set properly for batch |
---|
| 2595 | if len(self._logic) > 1: |
---|
| 2596 | for i, logic in enumerate(self._logic): |
---|
| 2597 | if logic.data.name in fitted_data.name: |
---|
| 2598 | self.data_index = i |
---|
| 2599 | |
---|
[0fe7e5b] | 2600 | residuals = self.calculateResiduals(fitted_data) |
---|
[d48cc19] | 2601 | self.model_data = fitted_data |
---|
[5aad7a5] | 2602 | new_plots = [fitted_data] |
---|
| 2603 | if residuals is not None: |
---|
| 2604 | new_plots.append(residuals) |
---|
[cbcdd2c] | 2605 | |
---|
[fd7ef36] | 2606 | if self.data_is_loaded: |
---|
[3ae70f9] | 2607 | # delete any plots associated with the data that were not updated |
---|
| 2608 | # (e.g. to remove beta(Q), S_eff(Q)) |
---|
[0dcb71d] | 2609 | GuiUtils.deleteRedundantPlots(self.all_data[self.data_index], new_plots) |
---|
[5b144c6] | 2610 | pass |
---|
[fd7ef36] | 2611 | else: |
---|
[3ae70f9] | 2612 | # delete theory items for the model, in order to get rid of any |
---|
| 2613 | # redundant items, e.g. beta(Q), S_eff(Q) |
---|
[fd7ef36] | 2614 | self.communicate.deleteIntermediateTheoryPlotsSignal.emit(self.kernel_module.id) |
---|
[0fe7e5b] | 2615 | |
---|
[d8d81ea] | 2616 | # Create plots for parameters with enabled polydispersity |
---|
| 2617 | for plot in FittingUtilities.plotPolydispersities(return_data.get('model', None)): |
---|
| 2618 | data_id = fitted_data.id.split() |
---|
| 2619 | plot.id = "{} [{}] {}".format(data_id[0], plot.name, " ".join(data_id[1:])) |
---|
| 2620 | data_name = fitted_data.name.split() |
---|
| 2621 | plot.name = " ".join([data_name[0], plot.name] + data_name[1:]) |
---|
| 2622 | self.createNewIndex(plot) |
---|
| 2623 | new_plots.append(plot) |
---|
| 2624 | |
---|
[3ae9179] | 2625 | # Create plots for intermediate product data |
---|
[40975f8] | 2626 | plots = self.logic.new1DProductPlots(return_data, self.tab_id) |
---|
| 2627 | for plot in plots: |
---|
| 2628 | plot.symbol = "Line" |
---|
| 2629 | self.createNewIndex(plot) |
---|
| 2630 | new_plots.append(plot) |
---|
[0fe7e5b] | 2631 | |
---|
[9463ca2] | 2632 | for plot in new_plots: |
---|
[5aad7a5] | 2633 | self.communicate.plotUpdateSignal.emit([plot]) |
---|
[9463ca2] | 2634 | |
---|
[5a96a72] | 2635 | # Update radius_effective if relevant |
---|
[d99b1a5] | 2636 | self.updateEffectiveRadius(return_data) |
---|
[5a96a72] | 2637 | |
---|
[cbcdd2c] | 2638 | def complete2D(self, return_data): |
---|
| 2639 | """ |
---|
[4d457df] | 2640 | Plot the current 2D data |
---|
| 2641 | """ |
---|
[557fc498] | 2642 | # Bring the GUI to normal state |
---|
| 2643 | self.enableInteractiveElements() |
---|
| 2644 | |
---|
[8a09457] | 2645 | if return_data is None: |
---|
| 2646 | return |
---|
| 2647 | |
---|
[6fd4e36] | 2648 | fitted_data = self.logic.new2DPlot(return_data) |
---|
[8a09457] | 2649 | # assure the current index is set properly for batch |
---|
| 2650 | if len(self._logic) > 1: |
---|
| 2651 | for i, logic in enumerate(self._logic): |
---|
| 2652 | if logic.data.name in fitted_data.name: |
---|
| 2653 | self.data_index = i |
---|
| 2654 | |
---|
[66d4370] | 2655 | residuals = self.calculateResiduals(fitted_data) |
---|
[d48cc19] | 2656 | self.model_data = fitted_data |
---|
[66d4370] | 2657 | new_plots = [fitted_data] |
---|
| 2658 | if residuals is not None: |
---|
| 2659 | new_plots.append(residuals) |
---|
| 2660 | |
---|
| 2661 | # Update/generate plots |
---|
| 2662 | for plot in new_plots: |
---|
| 2663 | self.communicate.plotUpdateSignal.emit([plot]) |
---|
[6fd4e36] | 2664 | |
---|
[d99b1a5] | 2665 | def updateEffectiveRadius(self, return_data): |
---|
[80a327d] | 2666 | """ |
---|
| 2667 | Given return data from sasmodels, update the effective radius parameter in the GUI table with the new |
---|
| 2668 | calculated value as returned by sasmodels (if the value was returned). |
---|
| 2669 | """ |
---|
| 2670 | ER_mode_row = self.getRowFromName("radius_effective_mode") |
---|
| 2671 | if ER_mode_row is None: |
---|
| 2672 | return |
---|
| 2673 | try: |
---|
| 2674 | ER_mode = int(self._model_model.item(ER_mode_row, 1).text()) |
---|
| 2675 | except ValueError: |
---|
| 2676 | logging.error("radius_effective_mode was set to an invalid value.") |
---|
| 2677 | return |
---|
| 2678 | if ER_mode < 1: |
---|
| 2679 | # does not need updating if it is not being computed |
---|
| 2680 | return |
---|
| 2681 | |
---|
| 2682 | ER_row = self.getRowFromName("radius_effective") |
---|
| 2683 | if ER_row is None: |
---|
| 2684 | return |
---|
| 2685 | |
---|
| 2686 | scalar_results = self.logic.getScalarIntermediateResults(return_data) |
---|
| 2687 | ER_value = scalar_results.get("effective_radius") # note name of key |
---|
| 2688 | if ER_value is None: |
---|
| 2689 | return |
---|
| 2690 | # ensure the model does not recompute when updating the value |
---|
| 2691 | self._model_model.blockSignals(True) |
---|
| 2692 | self._model_model.item(ER_row, 1).setText(str(ER_value)) |
---|
| 2693 | self._model_model.blockSignals(False) |
---|
| 2694 | # ensure the view is updated immediately |
---|
| 2695 | self._model_model.layoutChanged.emit() |
---|
| 2696 | |
---|
[6fd4e36] | 2697 | def calculateResiduals(self, fitted_data): |
---|
| 2698 | """ |
---|
[9463ca2] | 2699 | Calculate and print Chi2 and display chart of residuals. Returns residuals plot object. |
---|
[6fd4e36] | 2700 | """ |
---|
| 2701 | # Create a new index for holding data |
---|
[7d077d1] | 2702 | fitted_data.symbol = "Line" |
---|
[6964d44] | 2703 | |
---|
| 2704 | # Modify fitted_data with weighting |
---|
[b764ae5] | 2705 | weighted_data = self.addWeightingToData(fitted_data) |
---|
[6964d44] | 2706 | |
---|
[b764ae5] | 2707 | self.createNewIndex(weighted_data) |
---|
[712db9e] | 2708 | |
---|
[6fd4e36] | 2709 | # Calculate difference between return_data and logic.data |
---|
[712db9e] | 2710 | self.chi2 = FittingUtilities.calculateChi2(weighted_data, self.data) |
---|
[6fd4e36] | 2711 | # Update the control |
---|
[2add354] | 2712 | chi2_repr = "---" if self.chi2 is None else GuiUtils.formatNumber(self.chi2, high=True) |
---|
[f182f93] | 2713 | self.lblChi2Value.setText(chi2_repr) |
---|
[cbcdd2c] | 2714 | |
---|
[0268aed] | 2715 | # Plot residuals if actual data |
---|
[aca8418] | 2716 | if not self.data_is_loaded: |
---|
| 2717 | return |
---|
| 2718 | |
---|
[b764ae5] | 2719 | residuals_plot = FittingUtilities.plotResiduals(self.data, weighted_data) |
---|
[712db9e] | 2720 | if residuals_plot is None: |
---|
| 2721 | return |
---|
[aca8418] | 2722 | residuals_plot.id = "Residual " + residuals_plot.id |
---|
[a54bbf2b] | 2723 | residuals_plot.plot_role = Data1D.ROLE_RESIDUAL |
---|
[aca8418] | 2724 | self.createNewIndex(residuals_plot) |
---|
[0fe7e5b] | 2725 | return residuals_plot |
---|
[5236449] | 2726 | |
---|
[3d18691] | 2727 | def onCategoriesChanged(self): |
---|
| 2728 | """ |
---|
| 2729 | Reload the category/model comboboxes |
---|
| 2730 | """ |
---|
| 2731 | # Store the current combo indices |
---|
| 2732 | current_cat = self.cbCategory.currentText() |
---|
| 2733 | current_model = self.cbModel.currentText() |
---|
| 2734 | |
---|
| 2735 | # reread the category file and repopulate the combo |
---|
| 2736 | self.cbCategory.blockSignals(True) |
---|
| 2737 | self.cbCategory.clear() |
---|
| 2738 | self.readCategoryInfo() |
---|
| 2739 | self.initializeCategoryCombo() |
---|
| 2740 | |
---|
| 2741 | # Scroll back to the original index in Categories |
---|
| 2742 | new_index = self.cbCategory.findText(current_cat) |
---|
| 2743 | if new_index != -1: |
---|
| 2744 | self.cbCategory.setCurrentIndex(new_index) |
---|
| 2745 | self.cbCategory.blockSignals(False) |
---|
| 2746 | # ...and in the Models |
---|
| 2747 | self.cbModel.blockSignals(True) |
---|
| 2748 | new_index = self.cbModel.findText(current_model) |
---|
| 2749 | if new_index != -1: |
---|
| 2750 | self.cbModel.setCurrentIndex(new_index) |
---|
| 2751 | self.cbModel.blockSignals(False) |
---|
| 2752 | |
---|
| 2753 | return |
---|
| 2754 | |
---|
[5236449] | 2755 | def calcException(self, etype, value, tb): |
---|
| 2756 | """ |
---|
[c1e380e] | 2757 | Thread threw an exception. |
---|
[5236449] | 2758 | """ |
---|
[557fc498] | 2759 | # Bring the GUI to normal state |
---|
| 2760 | self.enableInteractiveElements() |
---|
[c1e380e] | 2761 | # TODO: remimplement thread cancellation |
---|
[bb477f5] | 2762 | logger.error("".join(traceback.format_exception(etype, value, tb))) |
---|
[60af928] | 2763 | |
---|
| 2764 | def setTableProperties(self, table): |
---|
| 2765 | """ |
---|
| 2766 | Setting table properties |
---|
| 2767 | """ |
---|
| 2768 | # Table properties |
---|
| 2769 | table.verticalHeader().setVisible(False) |
---|
| 2770 | table.setAlternatingRowColors(True) |
---|
[4992ff2] | 2771 | table.setSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) |
---|
| 2772 | table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) |
---|
[f46f6dc] | 2773 | table.resizeColumnsToContents() |
---|
| 2774 | |
---|
[60af928] | 2775 | # Header |
---|
| 2776 | header = table.horizontalHeader() |
---|
[4992ff2] | 2777 | header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents) |
---|
| 2778 | header.ResizeMode(QtWidgets.QHeaderView.Interactive) |
---|
[f46f6dc] | 2779 | |
---|
[4992ff2] | 2780 | # Qt5: the following 2 lines crash - figure out why! |
---|
[e43fc91] | 2781 | # Resize column 0 and 7 to content |
---|
[4992ff2] | 2782 | #header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents) |
---|
| 2783 | #header.setSectionResizeMode(7, QtWidgets.QHeaderView.ResizeToContents) |
---|
[60af928] | 2784 | |
---|
| 2785 | def setPolyModel(self): |
---|
| 2786 | """ |
---|
| 2787 | Set polydispersity values |
---|
| 2788 | """ |
---|
[86f88d1] | 2789 | if not self.model_parameters: |
---|
| 2790 | return |
---|
| 2791 | self._poly_model.clear() |
---|
| 2792 | |
---|
[f53bc04] | 2793 | parameters = self.model_parameters.form_volume_parameters |
---|
| 2794 | if self.is2D: |
---|
| 2795 | parameters += self.model_parameters.orientation_parameters |
---|
| 2796 | |
---|
[e43fc91] | 2797 | [self.setPolyModelParameters(i, param) for i, param in \ |
---|
[f53bc04] | 2798 | enumerate(parameters) if param.polydisperse] |
---|
| 2799 | |
---|
[4d457df] | 2800 | FittingUtilities.addPolyHeadersToModel(self._poly_model) |
---|
[60af928] | 2801 | |
---|
[e43fc91] | 2802 | def setPolyModelParameters(self, i, param): |
---|
[aca8418] | 2803 | """ |
---|
[0d13814] | 2804 | Standard of multishell poly parameter driver |
---|
[aca8418] | 2805 | """ |
---|
[0d13814] | 2806 | param_name = param.name |
---|
| 2807 | # see it the parameter is multishell |
---|
[06b0138] | 2808 | if '[' in param.name: |
---|
[0d13814] | 2809 | # Skip empty shells |
---|
| 2810 | if self.current_shell_displayed == 0: |
---|
| 2811 | return |
---|
| 2812 | else: |
---|
| 2813 | # Create as many entries as current shells |
---|
[b3e8629] | 2814 | for ishell in range(1, self.current_shell_displayed+1): |
---|
[0d13814] | 2815 | # Remove [n] and add the shell numeral |
---|
| 2816 | name = param_name[0:param_name.index('[')] + str(ishell) |
---|
[e43fc91] | 2817 | self.addNameToPolyModel(i, name) |
---|
[0d13814] | 2818 | else: |
---|
| 2819 | # Just create a simple param entry |
---|
[e43fc91] | 2820 | self.addNameToPolyModel(i, param_name) |
---|
[0d13814] | 2821 | |
---|
[e43fc91] | 2822 | def addNameToPolyModel(self, i, param_name): |
---|
[0d13814] | 2823 | """ |
---|
| 2824 | Creates a checked row in the poly model with param_name |
---|
| 2825 | """ |
---|
[144ec831] | 2826 | # Polydisp. values from the sasmodel |
---|
[0d13814] | 2827 | width = self.kernel_module.getParam(param_name + '.width') |
---|
| 2828 | npts = self.kernel_module.getParam(param_name + '.npts') |
---|
| 2829 | nsigs = self.kernel_module.getParam(param_name + '.nsigmas') |
---|
| 2830 | _, min, max = self.kernel_module.details[param_name] |
---|
[144ec831] | 2831 | |
---|
[66d4370] | 2832 | # Update local param dict |
---|
| 2833 | self.poly_params[param_name + '.width'] = width |
---|
| 2834 | self.poly_params[param_name + '.npts'] = npts |
---|
| 2835 | self.poly_params[param_name + '.nsigmas'] = nsigs |
---|
| 2836 | |
---|
[144ec831] | 2837 | # Construct a row with polydisp. related variable. |
---|
| 2838 | # This will get added to the polydisp. model |
---|
| 2839 | # Note: last argument needs extra space padding for decent display of the control |
---|
[0d13814] | 2840 | checked_list = ["Distribution of " + param_name, str(width), |
---|
| 2841 | str(min), str(max), |
---|
[e43fc91] | 2842 | str(npts), str(nsigs), "gaussian ",''] |
---|
[aca8418] | 2843 | FittingUtilities.addCheckedListToModel(self._poly_model, checked_list) |
---|
| 2844 | |
---|
| 2845 | # All possible polydisp. functions as strings in combobox |
---|
[4992ff2] | 2846 | func = QtWidgets.QComboBox() |
---|
[b3e8629] | 2847 | func.addItems([str(name_disp) for name_disp in POLYDISPERSITY_MODELS.keys()]) |
---|
[e43fc91] | 2848 | # Set the default index |
---|
[aca8418] | 2849 | func.setCurrentIndex(func.findText(DEFAULT_POLYDISP_FUNCTION)) |
---|
[e43fc91] | 2850 | ind = self._poly_model.index(i,self.lstPoly.itemDelegate().poly_function) |
---|
| 2851 | self.lstPoly.setIndexWidget(ind, func) |
---|
| 2852 | func.currentIndexChanged.connect(lambda: self.onPolyComboIndexChange(str(func.currentText()), i)) |
---|
| 2853 | |
---|
| 2854 | def onPolyFilenameChange(self, row_index): |
---|
| 2855 | """ |
---|
| 2856 | Respond to filename_updated signal from the delegate |
---|
| 2857 | """ |
---|
| 2858 | # For the given row, invoke the "array" combo handler |
---|
| 2859 | array_caption = 'array' |
---|
[8222f171] | 2860 | |
---|
[e43fc91] | 2861 | # Get the combo box reference |
---|
| 2862 | ind = self._poly_model.index(row_index, self.lstPoly.itemDelegate().poly_function) |
---|
| 2863 | widget = self.lstPoly.indexWidget(ind) |
---|
[8222f171] | 2864 | |
---|
[e43fc91] | 2865 | # Update the combo box so it displays "array" |
---|
| 2866 | widget.blockSignals(True) |
---|
| 2867 | widget.setCurrentIndex(self.lstPoly.itemDelegate().POLYDISPERSE_FUNCTIONS.index(array_caption)) |
---|
| 2868 | widget.blockSignals(False) |
---|
[aca8418] | 2869 | |
---|
[8222f171] | 2870 | # Invoke the file reader |
---|
| 2871 | self.onPolyComboIndexChange(array_caption, row_index) |
---|
| 2872 | |
---|
[aca8418] | 2873 | def onPolyComboIndexChange(self, combo_string, row_index): |
---|
| 2874 | """ |
---|
| 2875 | Modify polydisp. defaults on function choice |
---|
| 2876 | """ |
---|
[144ec831] | 2877 | # Get npts/nsigs for current selection |
---|
[aca8418] | 2878 | param = self.model_parameters.form_volume_parameters[row_index] |
---|
[e43fc91] | 2879 | file_index = self._poly_model.index(row_index, self.lstPoly.itemDelegate().poly_function) |
---|
| 2880 | combo_box = self.lstPoly.indexWidget(file_index) |
---|
[aca8418] | 2881 | |
---|
[919d47c] | 2882 | def updateFunctionCaption(row): |
---|
| 2883 | # Utility function for update of polydispersity function name in the main model |
---|
[00b7ddf0] | 2884 | if not self.isCheckable(row): |
---|
| 2885 | return |
---|
[73665a8] | 2886 | self._model_model.blockSignals(True) |
---|
[1643d8ed] | 2887 | param_name = str(self._model_model.item(row, 0).text()) |
---|
[73665a8] | 2888 | self._model_model.blockSignals(False) |
---|
[919d47c] | 2889 | if param_name != param.name: |
---|
| 2890 | return |
---|
[144ec831] | 2891 | # Modify the param value |
---|
[73665a8] | 2892 | self._model_model.blockSignals(True) |
---|
[906e0c7] | 2893 | if self.has_error_column: |
---|
| 2894 | # err column changes the indexing |
---|
| 2895 | self._model_model.item(row, 0).child(0).child(0,5).setText(combo_string) |
---|
| 2896 | else: |
---|
| 2897 | self._model_model.item(row, 0).child(0).child(0,4).setText(combo_string) |
---|
[73665a8] | 2898 | self._model_model.blockSignals(False) |
---|
[919d47c] | 2899 | |
---|
[aca8418] | 2900 | if combo_string == 'array': |
---|
| 2901 | try: |
---|
[e43fc91] | 2902 | self.loadPolydispArray(row_index) |
---|
[919d47c] | 2903 | # Update main model for display |
---|
| 2904 | self.iterateOverModel(updateFunctionCaption) |
---|
[e43fc91] | 2905 | # disable the row |
---|
| 2906 | lo = self.lstPoly.itemDelegate().poly_pd |
---|
| 2907 | hi = self.lstPoly.itemDelegate().poly_function |
---|
[b3e8629] | 2908 | [self._poly_model.item(row_index, i).setEnabled(False) for i in range(lo, hi)] |
---|
[aca8418] | 2909 | return |
---|
[e43fc91] | 2910 | except IOError: |
---|
[8222f171] | 2911 | combo_box.setCurrentIndex(self.orig_poly_index) |
---|
[e43fc91] | 2912 | # Pass for cancel/bad read |
---|
| 2913 | pass |
---|
[aca8418] | 2914 | |
---|
| 2915 | # Enable the row in case it was disabled by Array |
---|
[919d47c] | 2916 | self._poly_model.blockSignals(True) |
---|
[e43fc91] | 2917 | max_range = self.lstPoly.itemDelegate().poly_filename |
---|
[b3e8629] | 2918 | [self._poly_model.item(row_index, i).setEnabled(True) for i in range(7)] |
---|
[e43fc91] | 2919 | file_index = self._poly_model.index(row_index, self.lstPoly.itemDelegate().poly_filename) |
---|
[b3e8629] | 2920 | self._poly_model.setData(file_index, "") |
---|
[919d47c] | 2921 | self._poly_model.blockSignals(False) |
---|
[aca8418] | 2922 | |
---|
[8eaa101] | 2923 | npts_index = self._poly_model.index(row_index, self.lstPoly.itemDelegate().poly_npts) |
---|
| 2924 | nsigs_index = self._poly_model.index(row_index, self.lstPoly.itemDelegate().poly_nsigs) |
---|
[aca8418] | 2925 | |
---|
| 2926 | npts = POLYDISPERSITY_MODELS[str(combo_string)].default['npts'] |
---|
| 2927 | nsigs = POLYDISPERSITY_MODELS[str(combo_string)].default['nsigmas'] |
---|
| 2928 | |
---|
[b3e8629] | 2929 | self._poly_model.setData(npts_index, npts) |
---|
| 2930 | self._poly_model.setData(nsigs_index, nsigs) |
---|
[aca8418] | 2931 | |
---|
[919d47c] | 2932 | self.iterateOverModel(updateFunctionCaption) |
---|
[8222f171] | 2933 | self.orig_poly_index = combo_box.currentIndex() |
---|
[919d47c] | 2934 | |
---|
[e43fc91] | 2935 | def loadPolydispArray(self, row_index): |
---|
[aca8418] | 2936 | """ |
---|
| 2937 | Show the load file dialog and loads requested data into state |
---|
| 2938 | """ |
---|
[4992ff2] | 2939 | datafile = QtWidgets.QFileDialog.getOpenFileName( |
---|
| 2940 | self, "Choose a weight file", "", "All files (*.*)", None, |
---|
[fbfc488] | 2941 | QtWidgets.QFileDialog.DontUseNativeDialog)[0] |
---|
[72f4834] | 2942 | |
---|
[fbfc488] | 2943 | if not datafile: |
---|
[bb477f5] | 2944 | logger.info("No weight data chosen.") |
---|
[1643d8ed] | 2945 | raise IOError |
---|
[72f4834] | 2946 | |
---|
[aca8418] | 2947 | values = [] |
---|
| 2948 | weights = [] |
---|
[919d47c] | 2949 | def appendData(data_tuple): |
---|
| 2950 | """ |
---|
| 2951 | Fish out floats from a tuple of strings |
---|
| 2952 | """ |
---|
| 2953 | try: |
---|
| 2954 | values.append(float(data_tuple[0])) |
---|
| 2955 | weights.append(float(data_tuple[1])) |
---|
| 2956 | except (ValueError, IndexError): |
---|
| 2957 | # just pass through if line with bad data |
---|
| 2958 | return |
---|
| 2959 | |
---|
[aca8418] | 2960 | with open(datafile, 'r') as column_file: |
---|
| 2961 | column_data = [line.rstrip().split() for line in column_file.readlines()] |
---|
[919d47c] | 2962 | [appendData(line) for line in column_data] |
---|
[aca8418] | 2963 | |
---|
[1643d8ed] | 2964 | # If everything went well - update the sasmodel values |
---|
[aca8418] | 2965 | self.disp_model = POLYDISPERSITY_MODELS['array']() |
---|
| 2966 | self.disp_model.set_weights(np.array(values), np.array(weights)) |
---|
[e43fc91] | 2967 | # + update the cell with filename |
---|
| 2968 | fname = os.path.basename(str(datafile)) |
---|
| 2969 | fname_index = self._poly_model.index(row_index, self.lstPoly.itemDelegate().poly_filename) |
---|
[b3e8629] | 2970 | self._poly_model.setData(fname_index, fname) |
---|
[aca8418] | 2971 | |
---|
[f37cab0] | 2972 | def onColumnWidthUpdate(self, index, old_size, new_size): |
---|
| 2973 | """ |
---|
| 2974 | Simple state update of the current column widths in the param list |
---|
| 2975 | """ |
---|
| 2976 | self.lstParamHeaderSizes[index] = new_size |
---|
| 2977 | |
---|
[60af928] | 2978 | def setMagneticModel(self): |
---|
| 2979 | """ |
---|
| 2980 | Set magnetism values on model |
---|
| 2981 | """ |
---|
[86f88d1] | 2982 | if not self.model_parameters: |
---|
| 2983 | return |
---|
| 2984 | self._magnet_model.clear() |
---|
[a98014ab] | 2985 | # default initial value |
---|
[658795d] | 2986 | m0 = 0.5 |
---|
[a98014ab] | 2987 | for param in self.model_parameters.call_parameters: |
---|
| 2988 | if param.type != 'magnetic': continue |
---|
| 2989 | if "M0" in param.name: |
---|
[658795d] | 2990 | m0 += 0.5 |
---|
[a98014ab] | 2991 | value = m0 |
---|
| 2992 | else: |
---|
| 2993 | value = param.default |
---|
| 2994 | self.addCheckedMagneticListToModel(param, value) |
---|
| 2995 | |
---|
[4d457df] | 2996 | FittingUtilities.addHeadersToModel(self._magnet_model) |
---|
[60af928] | 2997 | |
---|
[0d13814] | 2998 | def shellNamesList(self): |
---|
| 2999 | """ |
---|
| 3000 | Returns list of names of all multi-shell parameters |
---|
| 3001 | E.g. for sld[n], radius[n], n=1..3 it will return |
---|
| 3002 | [sld1, sld2, sld3, radius1, radius2, radius3] |
---|
| 3003 | """ |
---|
| 3004 | multi_names = [p.name[:p.name.index('[')] for p in self.model_parameters.iq_parameters if '[' in p.name] |
---|
| 3005 | top_index = self.kernel_module.multiplicity_info.number |
---|
| 3006 | shell_names = [] |
---|
[b3e8629] | 3007 | for i in range(1, top_index+1): |
---|
[0d13814] | 3008 | for name in multi_names: |
---|
| 3009 | shell_names.append(name+str(i)) |
---|
| 3010 | return shell_names |
---|
| 3011 | |
---|
[a98014ab] | 3012 | def addCheckedMagneticListToModel(self, param, value): |
---|
[aca8418] | 3013 | """ |
---|
| 3014 | Wrapper for model update with a subset of magnetic parameters |
---|
| 3015 | """ |
---|
[8ac8717] | 3016 | try: |
---|
| 3017 | basename, _ = param.name.rsplit('_', 1) |
---|
| 3018 | except ValueError: |
---|
| 3019 | basename = param.name |
---|
| 3020 | if basename in self.shell_names: |
---|
[0d13814] | 3021 | try: |
---|
[8ac8717] | 3022 | shell_index = int(basename[-2:]) |
---|
[0d13814] | 3023 | except ValueError: |
---|
[8ac8717] | 3024 | shell_index = int(basename[-1:]) |
---|
[0d13814] | 3025 | |
---|
| 3026 | if shell_index > self.current_shell_displayed: |
---|
| 3027 | return |
---|
| 3028 | |
---|
[aca8418] | 3029 | checked_list = [param.name, |
---|
[a98014ab] | 3030 | str(value), |
---|
[aca8418] | 3031 | str(param.limits[0]), |
---|
| 3032 | str(param.limits[1]), |
---|
| 3033 | param.units] |
---|
| 3034 | |
---|
[a98014ab] | 3035 | self.magnet_params[param.name] = value |
---|
[66d4370] | 3036 | |
---|
[a98014ab] | 3037 | FittingUtilities.addCheckedListToModel(self._magnet_model, checked_list) |
---|
[aca8418] | 3038 | |
---|
[fd1ae6d1] | 3039 | def enableStructureFactorControl(self, structure_factor): |
---|
[cd31251] | 3040 | """ |
---|
| 3041 | Add structure factors to the list of parameters |
---|
| 3042 | """ |
---|
[fd1ae6d1] | 3043 | if self.kernel_module.is_form_factor or structure_factor == 'None': |
---|
[cd31251] | 3044 | self.enableStructureCombo() |
---|
| 3045 | else: |
---|
| 3046 | self.disableStructureCombo() |
---|
| 3047 | |
---|
[60af928] | 3048 | def addExtraShells(self): |
---|
| 3049 | """ |
---|
[f46f6dc] | 3050 | Add a combobox for multiple shell display |
---|
[60af928] | 3051 | """ |
---|
[4d457df] | 3052 | param_name, param_length = FittingUtilities.getMultiplicity(self.model_parameters) |
---|
[f46f6dc] | 3053 | |
---|
| 3054 | if param_length == 0: |
---|
| 3055 | return |
---|
| 3056 | |
---|
[6f7f652] | 3057 | # cell 1: variable name |
---|
[f46f6dc] | 3058 | item1 = QtGui.QStandardItem(param_name) |
---|
| 3059 | |
---|
[4992ff2] | 3060 | func = QtWidgets.QComboBox() |
---|
[60af928] | 3061 | |
---|
[6f7f652] | 3062 | # cell 2: combobox |
---|
[f46f6dc] | 3063 | item2 = QtGui.QStandardItem() |
---|
[13dd7d2] | 3064 | |
---|
| 3065 | # cell 3: min value |
---|
| 3066 | item3 = QtGui.QStandardItem() |
---|
| 3067 | |
---|
| 3068 | # cell 4: max value |
---|
| 3069 | item4 = QtGui.QStandardItem() |
---|
| 3070 | |
---|
[86d3207] | 3071 | # cell 4: SLD button |
---|
| 3072 | item5 = QtGui.QStandardItem() |
---|
| 3073 | button = QtWidgets.QPushButton() |
---|
| 3074 | button.setText("Show SLD Profile") |
---|
| 3075 | |
---|
| 3076 | self._model_model.appendRow([item1, item2, item3, item4, item5]) |
---|
[60af928] | 3077 | |
---|
[6f7f652] | 3078 | # Beautify the row: span columns 2-4 |
---|
[60af928] | 3079 | shell_row = self._model_model.rowCount() |
---|
[f46f6dc] | 3080 | shell_index = self._model_model.index(shell_row-1, 1) |
---|
[86d3207] | 3081 | button_index = self._model_model.index(shell_row-1, 4) |
---|
[86f88d1] | 3082 | |
---|
[4d457df] | 3083 | self.lstParams.setIndexWidget(shell_index, func) |
---|
[86d3207] | 3084 | self.lstParams.setIndexWidget(button_index, button) |
---|
[70f4458] | 3085 | self._n_shells_row = shell_row - 1 |
---|
[86f88d1] | 3086 | |
---|
[f712bf30] | 3087 | # Get the default number of shells for the model |
---|
| 3088 | kernel_pars = self.kernel_module._model_info.parameters.kernel_parameters |
---|
| 3089 | shell_par = None |
---|
| 3090 | for par in kernel_pars: |
---|
| 3091 | if par.name == param_name: |
---|
| 3092 | shell_par = par |
---|
| 3093 | break |
---|
| 3094 | if not shell_par: |
---|
| 3095 | logger.error("Could not find %s in kernel parameters.", param_name) |
---|
| 3096 | default_shell_count = shell_par.default |
---|
[13dd7d2] | 3097 | shell_min = 0 |
---|
| 3098 | shell_max = 0 |
---|
| 3099 | try: |
---|
| 3100 | shell_min = int(shell_par.limits[0]) |
---|
| 3101 | shell_max = int(shell_par.limits[1]) |
---|
| 3102 | except IndexError as ex: |
---|
| 3103 | # no info about limits |
---|
| 3104 | pass |
---|
[62c6dc0] | 3105 | # don't update the kernel here - this data is display only |
---|
| 3106 | self._model_model.blockSignals(True) |
---|
[13dd7d2] | 3107 | item3.setText(str(shell_min)) |
---|
| 3108 | item4.setText(str(shell_max)) |
---|
[62c6dc0] | 3109 | self._model_model.blockSignals(False) |
---|
[13dd7d2] | 3110 | |
---|
| 3111 | # Respond to index change |
---|
| 3112 | func.currentTextChanged.connect(self.modifyShellsInList) |
---|
| 3113 | |
---|
[86d3207] | 3114 | # Respond to button press |
---|
| 3115 | button.clicked.connect(self.onShowSLDProfile) |
---|
| 3116 | |
---|
[13dd7d2] | 3117 | # Available range of shells displayed in the combobox |
---|
| 3118 | func.addItems([str(i) for i in range(shell_min, shell_max+1)]) |
---|
[f712bf30] | 3119 | |
---|
| 3120 | # Add default number of shells to the model |
---|
[13dd7d2] | 3121 | func.setCurrentText(str(default_shell_count)) |
---|
[a9b568c] | 3122 | |
---|
[13dd7d2] | 3123 | def modifyShellsInList(self, text): |
---|
[86f88d1] | 3124 | """ |
---|
| 3125 | Add/remove additional multishell parameters |
---|
| 3126 | """ |
---|
| 3127 | # Find row location of the combobox |
---|
[70f4458] | 3128 | first_row = self._n_shells_row + 1 |
---|
| 3129 | remove_rows = self._num_shell_params |
---|
[13dd7d2] | 3130 | try: |
---|
| 3131 | index = int(text) |
---|
| 3132 | except ValueError: |
---|
| 3133 | # bad text on the control! |
---|
| 3134 | index = 0 |
---|
| 3135 | logger.error("Multiplicity incorrect! Setting to 0") |
---|
[86d3207] | 3136 | self.kernel_module.multiplicity = index |
---|
[86f88d1] | 3137 | if remove_rows > 1: |
---|
[70f4458] | 3138 | self._model_model.removeRows(first_row, remove_rows) |
---|
| 3139 | |
---|
[b69b549] | 3140 | new_rows = FittingUtilities.addShellsToModel( |
---|
[88ada06] | 3141 | self.model_parameters, |
---|
| 3142 | self._model_model, |
---|
[a758043] | 3143 | index, |
---|
[b69b549] | 3144 | first_row, |
---|
[a758043] | 3145 | self.lstParams) |
---|
[86f88d1] | 3146 | |
---|
[b69b549] | 3147 | self._num_shell_params = len(new_rows) |
---|
[a9b568c] | 3148 | self.current_shell_displayed = index |
---|
[60af928] | 3149 | |
---|
[daf7c9c] | 3150 | # Param values for existing shells were reset to default; force all changes into kernel module |
---|
| 3151 | for row in new_rows: |
---|
| 3152 | par = row[0].text() |
---|
| 3153 | val = GuiUtils.toDouble(row[1].text()) |
---|
| 3154 | self.kernel_module.setParam(par, val) |
---|
| 3155 | |
---|
| 3156 | # Change 'n' in the parameter model; also causes recalculation |
---|
[3090270] | 3157 | self._model_model.item(self._n_shells_row, 1).setText(str(index)) |
---|
| 3158 | |
---|
[0d13814] | 3159 | # Update relevant models |
---|
| 3160 | self.setPolyModel() |
---|
[d2007a8] | 3161 | if self.canHaveMagnetism(): |
---|
| 3162 | self.setMagneticModel() |
---|
[0d13814] | 3163 | |
---|
[86d3207] | 3164 | def onShowSLDProfile(self): |
---|
| 3165 | """ |
---|
| 3166 | Show a quick plot of SLD profile |
---|
| 3167 | """ |
---|
| 3168 | # get profile data |
---|
| 3169 | x, y = self.kernel_module.getProfile() |
---|
| 3170 | y *= 1.0e6 |
---|
| 3171 | profile_data = Data1D(x=x, y=y) |
---|
| 3172 | profile_data.name = "SLD" |
---|
| 3173 | profile_data.scale = 'linear' |
---|
| 3174 | profile_data.symbol = 'Line' |
---|
| 3175 | profile_data.hide_error = True |
---|
| 3176 | profile_data._xaxis = "R(\AA)" |
---|
| 3177 | profile_data._yaxis = "SLD(10^{-6}\AA^{-2})" |
---|
| 3178 | |
---|
| 3179 | plotter = PlotterWidget(self, quickplot=True) |
---|
| 3180 | plotter.data = profile_data |
---|
| 3181 | plotter.showLegend = True |
---|
| 3182 | plotter.plot(hide_error=True, marker='-') |
---|
| 3183 | |
---|
| 3184 | self.plot_widget = QtWidgets.QWidget() |
---|
| 3185 | self.plot_widget.setWindowTitle("Scattering Length Density Profile") |
---|
| 3186 | layout = QtWidgets.QVBoxLayout() |
---|
| 3187 | layout.addWidget(plotter) |
---|
| 3188 | self.plot_widget.setLayout(layout) |
---|
| 3189 | self.plot_widget.show() |
---|
| 3190 | |
---|
[557fc498] | 3191 | def setInteractiveElements(self, enabled=True): |
---|
[14ec91c5] | 3192 | """ |
---|
[557fc498] | 3193 | Switch interactive GUI elements on/off |
---|
[14ec91c5] | 3194 | """ |
---|
[557fc498] | 3195 | assert isinstance(enabled, bool) |
---|
| 3196 | |
---|
| 3197 | self.lstParams.setEnabled(enabled) |
---|
| 3198 | self.lstPoly.setEnabled(enabled) |
---|
| 3199 | self.lstMagnetic.setEnabled(enabled) |
---|
| 3200 | |
---|
| 3201 | self.cbCategory.setEnabled(enabled) |
---|
| 3202 | self.cbModel.setEnabled(enabled) |
---|
[3ab2105] | 3203 | self.cmdPlot.setEnabled(enabled) |
---|
[14ec91c5] | 3204 | |
---|
[557fc498] | 3205 | def enableInteractiveElements(self): |
---|
[14ec91c5] | 3206 | """ |
---|
[557fc498] | 3207 | Set buttion caption on fitting/calculate finish |
---|
| 3208 | Enable the param table(s) |
---|
[14ec91c5] | 3209 | """ |
---|
[ded5e77] | 3210 | # Notify the user that fitting is available |
---|
| 3211 | self.cmdFit.setStyleSheet('QPushButton {color: black;}') |
---|
[14ec91c5] | 3212 | self.cmdFit.setText("Fit") |
---|
[ded5e77] | 3213 | self.fit_started = False |
---|
[557fc498] | 3214 | self.setInteractiveElements(True) |
---|
| 3215 | |
---|
| 3216 | def disableInteractiveElements(self): |
---|
| 3217 | """ |
---|
| 3218 | Set buttion caption on fitting/calculate start |
---|
| 3219 | Disable the param table(s) |
---|
| 3220 | """ |
---|
| 3221 | # Notify the user that fitting is being run |
---|
| 3222 | # Allow for stopping the job |
---|
| 3223 | self.cmdFit.setStyleSheet('QPushButton {color: red;}') |
---|
| 3224 | self.cmdFit.setText('Stop fit') |
---|
| 3225 | self.setInteractiveElements(False) |
---|
[14ec91c5] | 3226 | |
---|
[672b8ab] | 3227 | def readFitPage(self, fp): |
---|
| 3228 | """ |
---|
| 3229 | Read in state from a fitpage object and update GUI |
---|
| 3230 | """ |
---|
| 3231 | assert isinstance(fp, FitPage) |
---|
| 3232 | # Main tab info |
---|
| 3233 | self.logic.data.filename = fp.filename |
---|
| 3234 | self.data_is_loaded = fp.data_is_loaded |
---|
| 3235 | self.chkPolydispersity.setCheckState(fp.is_polydisperse) |
---|
| 3236 | self.chkMagnetism.setCheckState(fp.is_magnetic) |
---|
| 3237 | self.chk2DView.setCheckState(fp.is2D) |
---|
| 3238 | |
---|
| 3239 | # Update the comboboxes |
---|
| 3240 | self.cbCategory.setCurrentIndex(self.cbCategory.findText(fp.current_category)) |
---|
| 3241 | self.cbModel.setCurrentIndex(self.cbModel.findText(fp.current_model)) |
---|
| 3242 | if fp.current_factor: |
---|
| 3243 | self.cbStructureFactor.setCurrentIndex(self.cbStructureFactor.findText(fp.current_factor)) |
---|
| 3244 | |
---|
| 3245 | self.chi2 = fp.chi2 |
---|
| 3246 | |
---|
| 3247 | # Options tab |
---|
| 3248 | self.q_range_min = fp.fit_options[fp.MIN_RANGE] |
---|
| 3249 | self.q_range_max = fp.fit_options[fp.MAX_RANGE] |
---|
| 3250 | self.npts = fp.fit_options[fp.NPTS] |
---|
| 3251 | self.log_points = fp.fit_options[fp.LOG_POINTS] |
---|
| 3252 | self.weighting = fp.fit_options[fp.WEIGHTING] |
---|
| 3253 | |
---|
| 3254 | # Models |
---|
[d60da0c] | 3255 | self._model_model = fp.model_model |
---|
| 3256 | self._poly_model = fp.poly_model |
---|
| 3257 | self._magnet_model = fp.magnetism_model |
---|
[672b8ab] | 3258 | |
---|
| 3259 | # Resolution tab |
---|
| 3260 | smearing = fp.smearing_options[fp.SMEARING_OPTION] |
---|
| 3261 | accuracy = fp.smearing_options[fp.SMEARING_ACCURACY] |
---|
| 3262 | smearing_min = fp.smearing_options[fp.SMEARING_MIN] |
---|
| 3263 | smearing_max = fp.smearing_options[fp.SMEARING_MAX] |
---|
| 3264 | self.smearing_widget.setState(smearing, accuracy, smearing_min, smearing_max) |
---|
| 3265 | |
---|
| 3266 | # TODO: add polidyspersity and magnetism |
---|
| 3267 | |
---|
| 3268 | def saveToFitPage(self, fp): |
---|
| 3269 | """ |
---|
| 3270 | Write current state to the given fitpage |
---|
| 3271 | """ |
---|
| 3272 | assert isinstance(fp, FitPage) |
---|
| 3273 | |
---|
| 3274 | # Main tab info |
---|
| 3275 | fp.filename = self.logic.data.filename |
---|
| 3276 | fp.data_is_loaded = self.data_is_loaded |
---|
| 3277 | fp.is_polydisperse = self.chkPolydispersity.isChecked() |
---|
| 3278 | fp.is_magnetic = self.chkMagnetism.isChecked() |
---|
| 3279 | fp.is2D = self.chk2DView.isChecked() |
---|
| 3280 | fp.data = self.data |
---|
| 3281 | |
---|
| 3282 | # Use current models - they contain all the required parameters |
---|
| 3283 | fp.model_model = self._model_model |
---|
| 3284 | fp.poly_model = self._poly_model |
---|
| 3285 | fp.magnetism_model = self._magnet_model |
---|
| 3286 | |
---|
| 3287 | if self.cbCategory.currentIndex() != 0: |
---|
| 3288 | fp.current_category = str(self.cbCategory.currentText()) |
---|
| 3289 | fp.current_model = str(self.cbModel.currentText()) |
---|
| 3290 | |
---|
| 3291 | if self.cbStructureFactor.isEnabled() and self.cbStructureFactor.currentIndex() != 0: |
---|
| 3292 | fp.current_factor = str(self.cbStructureFactor.currentText()) |
---|
| 3293 | else: |
---|
| 3294 | fp.current_factor = '' |
---|
| 3295 | |
---|
| 3296 | fp.chi2 = self.chi2 |
---|
[6dbff18] | 3297 | fp.main_params_to_fit = self.main_params_to_fit |
---|
| 3298 | fp.poly_params_to_fit = self.poly_params_to_fit |
---|
| 3299 | fp.magnet_params_to_fit = self.magnet_params_to_fit |
---|
[6964d44] | 3300 | fp.kernel_module = self.kernel_module |
---|
[672b8ab] | 3301 | |
---|
[6ff2eb3] | 3302 | # Algorithm options |
---|
| 3303 | # fp.algorithm = self.parent.fit_options.selected_id |
---|
| 3304 | |
---|
[672b8ab] | 3305 | # Options tab |
---|
| 3306 | fp.fit_options[fp.MIN_RANGE] = self.q_range_min |
---|
| 3307 | fp.fit_options[fp.MAX_RANGE] = self.q_range_max |
---|
| 3308 | fp.fit_options[fp.NPTS] = self.npts |
---|
| 3309 | #fp.fit_options[fp.NPTS_FIT] = self.npts_fit |
---|
| 3310 | fp.fit_options[fp.LOG_POINTS] = self.log_points |
---|
| 3311 | fp.fit_options[fp.WEIGHTING] = self.weighting |
---|
| 3312 | |
---|
| 3313 | # Resolution tab |
---|
| 3314 | smearing, accuracy, smearing_min, smearing_max = self.smearing_widget.state() |
---|
| 3315 | fp.smearing_options[fp.SMEARING_OPTION] = smearing |
---|
| 3316 | fp.smearing_options[fp.SMEARING_ACCURACY] = accuracy |
---|
| 3317 | fp.smearing_options[fp.SMEARING_MIN] = smearing_min |
---|
| 3318 | fp.smearing_options[fp.SMEARING_MAX] = smearing_max |
---|
| 3319 | |
---|
| 3320 | # TODO: add polidyspersity and magnetism |
---|
| 3321 | |
---|
[00b3b40] | 3322 | def updateUndo(self): |
---|
| 3323 | """ |
---|
| 3324 | Create a new state page and add it to the stack |
---|
| 3325 | """ |
---|
| 3326 | if self.undo_supported: |
---|
| 3327 | self.pushFitPage(self.currentState()) |
---|
| 3328 | |
---|
[672b8ab] | 3329 | def currentState(self): |
---|
| 3330 | """ |
---|
| 3331 | Return fit page with current state |
---|
| 3332 | """ |
---|
| 3333 | new_page = FitPage() |
---|
| 3334 | self.saveToFitPage(new_page) |
---|
| 3335 | |
---|
| 3336 | return new_page |
---|
| 3337 | |
---|
| 3338 | def pushFitPage(self, new_page): |
---|
| 3339 | """ |
---|
| 3340 | Add a new fit page object with current state |
---|
| 3341 | """ |
---|
[6011788] | 3342 | self.page_stack.append(new_page) |
---|
[672b8ab] | 3343 | |
---|
| 3344 | def popFitPage(self): |
---|
| 3345 | """ |
---|
| 3346 | Remove top fit page from stack |
---|
| 3347 | """ |
---|
[6011788] | 3348 | if self.page_stack: |
---|
| 3349 | self.page_stack.pop() |
---|
[672b8ab] | 3350 | |
---|
[57be490] | 3351 | def getReport(self): |
---|
| 3352 | """ |
---|
| 3353 | Create and return HTML report with parameters and charts |
---|
| 3354 | """ |
---|
| 3355 | index = None |
---|
| 3356 | if self.all_data: |
---|
| 3357 | index = self.all_data[self.data_index] |
---|
[cb90b65] | 3358 | else: |
---|
| 3359 | index = self.theory_item |
---|
[57be490] | 3360 | report_logic = ReportPageLogic(self, |
---|
| 3361 | kernel_module=self.kernel_module, |
---|
| 3362 | data=self.data, |
---|
| 3363 | index=index, |
---|
| 3364 | model=self._model_model) |
---|
| 3365 | |
---|
| 3366 | return report_logic.reportList() |
---|
| 3367 | |
---|
| 3368 | def savePageState(self): |
---|
| 3369 | """ |
---|
| 3370 | Create and serialize local PageState |
---|
| 3371 | """ |
---|
| 3372 | filepath = self.saveAsAnalysisFile() |
---|
[10fee37] | 3373 | if filepath is None or filepath == "": |
---|
[57be490] | 3374 | return |
---|
[6040cd7] | 3375 | |
---|
| 3376 | fitpage_state = self.getFitPage() |
---|
| 3377 | fitpage_state += self.getFitModel() |
---|
| 3378 | |
---|
| 3379 | with open(filepath, 'w') as statefile: |
---|
| 3380 | for line in fitpage_state: |
---|
| 3381 | statefile.write(str(line)) |
---|
| 3382 | |
---|
| 3383 | self.communicate.statusBarUpdateSignal.emit('Analysis saved.') |
---|
[57be490] | 3384 | |
---|
| 3385 | def saveAsAnalysisFile(self): |
---|
| 3386 | """ |
---|
| 3387 | Show the save as... dialog and return the chosen filepath |
---|
| 3388 | """ |
---|
| 3389 | default_name = "FitPage"+str(self.tab_id)+".fitv" |
---|
| 3390 | |
---|
| 3391 | wildcard = "fitv files (*.fitv)" |
---|
| 3392 | kwargs = { |
---|
| 3393 | 'caption' : 'Save As', |
---|
| 3394 | 'directory' : default_name, |
---|
| 3395 | 'filter' : wildcard, |
---|
| 3396 | 'parent' : None, |
---|
| 3397 | } |
---|
| 3398 | # Query user for filename. |
---|
| 3399 | filename_tuple = QtWidgets.QFileDialog.getSaveFileName(**kwargs) |
---|
| 3400 | filename = filename_tuple[0] |
---|
| 3401 | return filename |
---|
| 3402 | |
---|
| 3403 | def loadPageStateCallback(self,state=None, datainfo=None, format=None): |
---|
| 3404 | """ |
---|
| 3405 | This is a callback method called from the CANSAS reader. |
---|
| 3406 | We need the instance of this reader only for writing out a file, |
---|
| 3407 | so there's nothing here. |
---|
| 3408 | Until Load Analysis is implemented, that is. |
---|
| 3409 | """ |
---|
| 3410 | pass |
---|
| 3411 | |
---|
| 3412 | def loadPageState(self, pagestate=None): |
---|
| 3413 | """ |
---|
| 3414 | Load the PageState object and update the current widget |
---|
| 3415 | """ |
---|
[6040cd7] | 3416 | filepath = self.loadAnalysisFile() |
---|
| 3417 | if filepath is None or filepath == "": |
---|
| 3418 | return |
---|
[57be490] | 3419 | |
---|
[6040cd7] | 3420 | with open(filepath, 'r') as statefile: |
---|
[9a42ea1] | 3421 | #column_data = [line.rstrip().split() for line in statefile.readlines()] |
---|
| 3422 | lines = statefile.readlines() |
---|
[57be490] | 3423 | |
---|
[6040cd7] | 3424 | # convert into list of lists |
---|
[9a42ea1] | 3425 | pass |
---|
[57be490] | 3426 | |
---|
[6040cd7] | 3427 | def loadAnalysisFile(self): |
---|
| 3428 | """ |
---|
| 3429 | Called when the "Open Project" menu item chosen. |
---|
| 3430 | """ |
---|
| 3431 | default_name = "FitPage"+str(self.tab_id)+".fitv" |
---|
| 3432 | wildcard = "fitv files (*.fitv)" |
---|
| 3433 | kwargs = { |
---|
| 3434 | 'caption' : 'Open Analysis', |
---|
| 3435 | 'directory' : default_name, |
---|
| 3436 | 'filter' : wildcard, |
---|
| 3437 | 'parent' : self, |
---|
| 3438 | } |
---|
| 3439 | filename = QtWidgets.QFileDialog.getOpenFileName(**kwargs)[0] |
---|
| 3440 | return filename |
---|
[57be490] | 3441 | |
---|
[d2007a8] | 3442 | def onCopyToClipboard(self, format=None): |
---|
| 3443 | """ |
---|
| 3444 | Copy current fitting parameters into the clipboard |
---|
| 3445 | using requested formatting: |
---|
| 3446 | plain, excel, latex |
---|
| 3447 | """ |
---|
| 3448 | param_list = self.getFitParameters() |
---|
| 3449 | if format=="": |
---|
[9a42ea1] | 3450 | param_list = self.getFitPage() |
---|
| 3451 | param_list += self.getFitModel() |
---|
[d2007a8] | 3452 | formatted_output = FittingUtilities.formatParameters(param_list) |
---|
| 3453 | elif format == "Excel": |
---|
| 3454 | formatted_output = FittingUtilities.formatParametersExcel(param_list[1:]) |
---|
| 3455 | elif format == "Latex": |
---|
| 3456 | formatted_output = FittingUtilities.formatParametersLatex(param_list[1:]) |
---|
| 3457 | else: |
---|
| 3458 | raise AttributeError("Bad parameter output format specifier.") |
---|
| 3459 | |
---|
| 3460 | # Dump formatted_output to the clipboard |
---|
| 3461 | cb = QtWidgets.QApplication.clipboard() |
---|
| 3462 | cb.setText(formatted_output) |
---|
| 3463 | |
---|
[6040cd7] | 3464 | def getFitModel(self): |
---|
[8e2cd79] | 3465 | """ |
---|
[9a42ea1] | 3466 | serializes combobox state |
---|
[6040cd7] | 3467 | """ |
---|
| 3468 | param_list = [] |
---|
| 3469 | model = str(self.cbModel.currentText()) |
---|
| 3470 | category = str(self.cbCategory.currentText()) |
---|
| 3471 | structure = str(self.cbStructureFactor.currentText()) |
---|
| 3472 | param_list.append(['fitpage_category', category]) |
---|
| 3473 | param_list.append(['fitpage_model', model]) |
---|
| 3474 | param_list.append(['fitpage_structure', structure]) |
---|
[9a42ea1] | 3475 | |
---|
[6040cd7] | 3476 | return param_list |
---|
| 3477 | |
---|
| 3478 | def getFitPage(self): |
---|
| 3479 | """ |
---|
| 3480 | serializes full state of this fit page |
---|
[8e2cd79] | 3481 | """ |
---|
| 3482 | # run a loop over all parameters and pull out |
---|
| 3483 | # first - regular params |
---|
[6040cd7] | 3484 | param_list = self.getFitParameters() |
---|
| 3485 | |
---|
[9a42ea1] | 3486 | param_list.append(['is_data', str(self.data_is_loaded)]) |
---|
| 3487 | if self.data_is_loaded: |
---|
| 3488 | param_list.append(['data_id', str(self.logic.data.id)]) |
---|
| 3489 | param_list.append(['data_name', str(self.logic.data.filename)]) |
---|
| 3490 | |
---|
[6040cd7] | 3491 | # option tab |
---|
| 3492 | param_list.append(['q_range_min', str(self.q_range_min)]) |
---|
| 3493 | param_list.append(['q_range_max', str(self.q_range_max)]) |
---|
| 3494 | param_list.append(['q_weighting', str(self.weighting)]) |
---|
[9a42ea1] | 3495 | param_list.append(['weighting', str(self.options_widget.weighting)]) |
---|
[6040cd7] | 3496 | |
---|
| 3497 | # resolution |
---|
| 3498 | smearing, accuracy, smearing_min, smearing_max = self.smearing_widget.state() |
---|
| 3499 | index = self.smearing_widget.cbSmearing.currentIndex() |
---|
| 3500 | param_list.append(['smearing', str(index)]) |
---|
| 3501 | param_list.append(['smearing_min', str(smearing_min)]) |
---|
| 3502 | param_list.append(['smearing_max', str(smearing_max)]) |
---|
| 3503 | |
---|
| 3504 | # checkboxes, if required |
---|
| 3505 | has_polydisp = self.chkPolydispersity.isChecked() |
---|
| 3506 | has_magnetism = self.chkMagnetism.isChecked() |
---|
| 3507 | has_chain = self.chkChainFit.isChecked() |
---|
| 3508 | has_2D = self.chk2DView.isChecked() |
---|
| 3509 | param_list.append(['polydisperse_params', str(has_polydisp)]) |
---|
| 3510 | param_list.append(['magnetic_params', str(has_magnetism)]) |
---|
| 3511 | param_list.append(['chainfit_params', str(has_chain)]) |
---|
| 3512 | param_list.append(['2D_params', str(has_2D)]) |
---|
| 3513 | |
---|
| 3514 | return param_list |
---|
| 3515 | |
---|
| 3516 | def getFitParameters(self): |
---|
| 3517 | """ |
---|
| 3518 | serializes current parameters |
---|
| 3519 | """ |
---|
[8e2cd79] | 3520 | param_list = [] |
---|
[0eff615] | 3521 | param_list.append(['model_name', str(self.cbModel.currentText())]) |
---|
[fc9d9a3] | 3522 | |
---|
[8e2cd79] | 3523 | def gatherParams(row): |
---|
| 3524 | """ |
---|
| 3525 | Create list of main parameters based on _model_model |
---|
| 3526 | """ |
---|
| 3527 | param_name = str(self._model_model.item(row, 0).text()) |
---|
[685602a] | 3528 | |
---|
[d2007a8] | 3529 | # Assure this is a parameter - must contain a checkbox |
---|
| 3530 | if not self._model_model.item(row, 0).isCheckable(): |
---|
| 3531 | # maybe it is a combobox item (multiplicity) |
---|
| 3532 | try: |
---|
| 3533 | index = self._model_model.index(row, 1) |
---|
| 3534 | widget = self.lstParams.indexWidget(index) |
---|
| 3535 | if widget is None: |
---|
| 3536 | return |
---|
| 3537 | if isinstance(widget, QtWidgets.QComboBox): |
---|
| 3538 | # find the index of the combobox |
---|
| 3539 | current_index = widget.currentIndex() |
---|
| 3540 | param_list.append([param_name, 'None', str(current_index)]) |
---|
| 3541 | except Exception as ex: |
---|
| 3542 | pass |
---|
| 3543 | return |
---|
| 3544 | |
---|
| 3545 | param_checked = str(self._model_model.item(row, 0).checkState() == QtCore.Qt.Checked) |
---|
| 3546 | # Value of the parameter. In some cases this is the text of the combobox choice. |
---|
| 3547 | param_value = str(self._model_model.item(row, 1).text()) |
---|
| 3548 | param_error = None |
---|
| 3549 | param_min = None |
---|
| 3550 | param_max = None |
---|
| 3551 | column_offset = 0 |
---|
| 3552 | if self.has_error_column: |
---|
| 3553 | column_offset = 1 |
---|
[6040cd7] | 3554 | param_error = str(self._model_model.item(row, 1+column_offset).text()) |
---|
[d2007a8] | 3555 | try: |
---|
| 3556 | param_min = str(self._model_model.item(row, 2+column_offset).text()) |
---|
| 3557 | param_max = str(self._model_model.item(row, 3+column_offset).text()) |
---|
| 3558 | except: |
---|
[fc9d9a3] | 3559 | pass |
---|
[21fa45b] | 3560 | |
---|
[6040cd7] | 3561 | param_list.append([param_name, param_checked, param_value, param_error, param_min, param_max]) |
---|
[8e2cd79] | 3562 | |
---|
| 3563 | def gatherPolyParams(row): |
---|
| 3564 | """ |
---|
| 3565 | Create list of polydisperse parameters based on _poly_model |
---|
| 3566 | """ |
---|
| 3567 | param_name = str(self._poly_model.item(row, 0).text()).split()[-1] |
---|
| 3568 | param_checked = str(self._poly_model.item(row, 0).checkState() == QtCore.Qt.Checked) |
---|
| 3569 | param_value = str(self._poly_model.item(row, 1).text()) |
---|
| 3570 | param_error = None |
---|
| 3571 | column_offset = 0 |
---|
| 3572 | if self.has_poly_error_column: |
---|
| 3573 | column_offset = 1 |
---|
[6040cd7] | 3574 | param_error = str(self._poly_model.item(row, 1+column_offset).text()) |
---|
[8e2cd79] | 3575 | param_min = str(self._poly_model.item(row, 2+column_offset).text()) |
---|
| 3576 | param_max = str(self._poly_model.item(row, 3+column_offset).text()) |
---|
| 3577 | param_npts = str(self._poly_model.item(row, 4+column_offset).text()) |
---|
| 3578 | param_nsigs = str(self._poly_model.item(row, 5+column_offset).text()) |
---|
| 3579 | param_fun = str(self._poly_model.item(row, 6+column_offset).text()).rstrip() |
---|
[d2007a8] | 3580 | index = self._poly_model.index(row, 6+column_offset) |
---|
| 3581 | widget = self.lstPoly.indexWidget(index) |
---|
| 3582 | if widget is not None and isinstance(widget, QtWidgets.QComboBox): |
---|
| 3583 | param_fun = widget.currentText() |
---|
[8e2cd79] | 3584 | # width |
---|
| 3585 | name = param_name+".width" |
---|
[6040cd7] | 3586 | param_list.append([name, param_checked, param_value, param_error, |
---|
| 3587 | param_min, param_max, param_npts, param_nsigs, param_fun]) |
---|
[8e2cd79] | 3588 | |
---|
| 3589 | def gatherMagnetParams(row): |
---|
| 3590 | """ |
---|
| 3591 | Create list of magnetic parameters based on _magnet_model |
---|
| 3592 | """ |
---|
| 3593 | param_name = str(self._magnet_model.item(row, 0).text()) |
---|
| 3594 | param_checked = str(self._magnet_model.item(row, 0).checkState() == QtCore.Qt.Checked) |
---|
| 3595 | param_value = str(self._magnet_model.item(row, 1).text()) |
---|
| 3596 | param_error = None |
---|
| 3597 | column_offset = 0 |
---|
| 3598 | if self.has_magnet_error_column: |
---|
| 3599 | column_offset = 1 |
---|
[6040cd7] | 3600 | param_error = str(self._magnet_model.item(row, 1+column_offset).text()) |
---|
[8e2cd79] | 3601 | param_min = str(self._magnet_model.item(row, 2+column_offset).text()) |
---|
| 3602 | param_max = str(self._magnet_model.item(row, 3+column_offset).text()) |
---|
[6040cd7] | 3603 | param_list.append([param_name, param_checked, param_value, |
---|
| 3604 | param_error, param_min, param_max]) |
---|
[8e2cd79] | 3605 | |
---|
| 3606 | self.iterateOverModel(gatherParams) |
---|
| 3607 | if self.chkPolydispersity.isChecked(): |
---|
| 3608 | self.iterateOverPolyModel(gatherPolyParams) |
---|
[a98014ab] | 3609 | if self.chkMagnetism.isChecked() and self.canHaveMagnetism(): |
---|
[b259485] | 3610 | self.iterateOverMagnetModel(gatherMagnetParams) |
---|
[8e2cd79] | 3611 | |
---|
[d2007a8] | 3612 | if self.kernel_module.is_multiplicity_model: |
---|
| 3613 | param_list.append(['multiplicity', str(self.kernel_module.multiplicity)]) |
---|
[8e2cd79] | 3614 | |
---|
[d2007a8] | 3615 | return param_list |
---|
[8e2cd79] | 3616 | |
---|
| 3617 | def onParameterPaste(self): |
---|
| 3618 | """ |
---|
| 3619 | Use the clipboard to update fit state |
---|
| 3620 | """ |
---|
| 3621 | # Check if the clipboard contains right stuff |
---|
| 3622 | cb = QtWidgets.QApplication.clipboard() |
---|
| 3623 | cb_text = cb.text() |
---|
| 3624 | |
---|
| 3625 | context = {} |
---|
| 3626 | lines = cb_text.split(':') |
---|
| 3627 | if lines[0] != 'sasview_parameter_values': |
---|
| 3628 | return False |
---|
[0eff615] | 3629 | |
---|
[d2007a8] | 3630 | # put the text into dictionary |
---|
| 3631 | line_dict = {} |
---|
| 3632 | for line in lines[1:]: |
---|
| 3633 | content = line.split(',') |
---|
| 3634 | if len(content) > 1: |
---|
| 3635 | line_dict[content[0]] = content[1:] |
---|
[0eff615] | 3636 | |
---|
[d2007a8] | 3637 | model = line_dict['model_name'][0] |
---|
[21fa45b] | 3638 | |
---|
[d2007a8] | 3639 | if 'model_name' not in line_dict.keys(): |
---|
[21fa45b] | 3640 | return False |
---|
| 3641 | |
---|
[d2007a8] | 3642 | if 'multiplicity' in line_dict.keys(): |
---|
| 3643 | multip = int(line_dict['multiplicity'][0], 0) |
---|
| 3644 | # reset the model with multiplicity, so further updates are saved |
---|
| 3645 | if self.kernel_module.is_multiplicity_model: |
---|
| 3646 | self.kernel_module.multiplicity=multip |
---|
| 3647 | self.updateMultiplicityCombo(multip) |
---|
| 3648 | |
---|
| 3649 | if 'polydisperse_params' in line_dict.keys(): |
---|
| 3650 | self.chkPolydispersity.setChecked(line_dict['polydisperse_params'][0]=='True') |
---|
| 3651 | if 'magnetic_params' in line_dict.keys(): |
---|
| 3652 | self.chkMagnetism.setChecked(line_dict['magnetic_params'][0]=='True') |
---|
| 3653 | if 'chainfit_params' in line_dict.keys(): |
---|
| 3654 | self.chkChainFit.setChecked(line_dict['chainfit_params'][0]=='True') |
---|
| 3655 | if '2D_params' in line_dict.keys(): |
---|
| 3656 | self.chk2DView.setChecked(line_dict['2D_params'][0]=='True') |
---|
| 3657 | |
---|
| 3658 | # Create the context dictionary for parameters |
---|
| 3659 | context['model_name'] = model |
---|
| 3660 | for key, value in line_dict.items(): |
---|
| 3661 | if len(value) > 2: |
---|
| 3662 | context[key] = value |
---|
| 3663 | |
---|
| 3664 | if str(self.cbModel.currentText()) != str(context['model_name']): |
---|
[0eff615] | 3665 | msg = QtWidgets.QMessageBox() |
---|
| 3666 | msg.setIcon(QtWidgets.QMessageBox.Information) |
---|
| 3667 | msg.setText("The model in the clipboard is not the same as the currently loaded model. \ |
---|
| 3668 | Not all parameters saved may paste correctly.") |
---|
| 3669 | msg.setStandardButtons(QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel) |
---|
| 3670 | result = msg.exec_() |
---|
| 3671 | if result == QtWidgets.QMessageBox.Ok: |
---|
| 3672 | pass |
---|
| 3673 | else: |
---|
| 3674 | return |
---|
| 3675 | |
---|
[d2007a8] | 3676 | if 'smearing' in line_dict.keys(): |
---|
| 3677 | try: |
---|
| 3678 | index = int(line_dict['smearing'][0]) |
---|
| 3679 | self.smearing_widget.cbSmearing.setCurrentIndex(index) |
---|
| 3680 | except ValueError: |
---|
| 3681 | pass |
---|
| 3682 | if 'smearing_min' in line_dict.keys(): |
---|
| 3683 | try: |
---|
| 3684 | self.smearing_widget.dq_l = float(line_dict['smearing_min'][0]) |
---|
| 3685 | except ValueError: |
---|
| 3686 | pass |
---|
| 3687 | if 'smearing_max' in line_dict.keys(): |
---|
| 3688 | try: |
---|
| 3689 | self.smearing_widget.dq_r = float(line_dict['smearing_max'][0]) |
---|
| 3690 | except ValueError: |
---|
| 3691 | pass |
---|
| 3692 | |
---|
| 3693 | if 'q_range_max' in line_dict.keys(): |
---|
| 3694 | try: |
---|
| 3695 | self.q_range_min = float(line_dict['q_range_min'][0]) |
---|
| 3696 | self.q_range_max = float(line_dict['q_range_max'][0]) |
---|
| 3697 | except ValueError: |
---|
| 3698 | pass |
---|
| 3699 | self.options_widget.updateQRange(self.q_range_min, self.q_range_max, self.npts) |
---|
[9a42ea1] | 3700 | try: |
---|
| 3701 | button_id = int(line_dict['weighting'][0]) |
---|
| 3702 | for button in self.options_widget.weightingGroup.buttons(): |
---|
| 3703 | if abs(self.options_widget.weightingGroup.id(button)) == button_id+2: |
---|
| 3704 | button.setChecked(True) |
---|
| 3705 | break |
---|
| 3706 | except ValueError: |
---|
| 3707 | pass |
---|
[d2007a8] | 3708 | |
---|
[8e2cd79] | 3709 | self.updateFullModel(context) |
---|
| 3710 | self.updateFullPolyModel(context) |
---|
[d2007a8] | 3711 | self.updateFullMagnetModel(context) |
---|
| 3712 | |
---|
| 3713 | def updateMultiplicityCombo(self, multip): |
---|
| 3714 | """ |
---|
| 3715 | Find and update the multiplicity combobox |
---|
| 3716 | """ |
---|
| 3717 | index = self._model_model.index(self._n_shells_row, 1) |
---|
| 3718 | widget = self.lstParams.indexWidget(index) |
---|
| 3719 | if widget is not None and isinstance(widget, QtWidgets.QComboBox): |
---|
| 3720 | widget.setCurrentIndex(widget.findText(str(multip))) |
---|
| 3721 | self.current_shell_displayed = multip |
---|
[8e2cd79] | 3722 | |
---|
| 3723 | def updateFullModel(self, param_dict): |
---|
| 3724 | """ |
---|
| 3725 | Update the model with new parameters |
---|
| 3726 | """ |
---|
| 3727 | assert isinstance(param_dict, dict) |
---|
| 3728 | if not dict: |
---|
| 3729 | return |
---|
| 3730 | |
---|
| 3731 | def updateFittedValues(row): |
---|
| 3732 | # Utility function for main model update |
---|
| 3733 | # internal so can use closure for param_dict |
---|
| 3734 | param_name = str(self._model_model.item(row, 0).text()) |
---|
| 3735 | if param_name not in list(param_dict.keys()): |
---|
| 3736 | return |
---|
[d2007a8] | 3737 | # Special case of combo box in the cell (multiplicity) |
---|
| 3738 | param_line = param_dict[param_name] |
---|
| 3739 | if len(param_line) == 1: |
---|
| 3740 | # modify the shells value |
---|
| 3741 | try: |
---|
| 3742 | combo_index = int(param_line[0]) |
---|
| 3743 | except ValueError: |
---|
| 3744 | # quietly pass |
---|
| 3745 | return |
---|
| 3746 | index = self._model_model.index(row, 1) |
---|
| 3747 | widget = self.lstParams.indexWidget(index) |
---|
| 3748 | if widget is not None and isinstance(widget, QtWidgets.QComboBox): |
---|
| 3749 | #widget.setCurrentIndex(combo_index) |
---|
| 3750 | return |
---|
[8e2cd79] | 3751 | # checkbox state |
---|
| 3752 | param_checked = QtCore.Qt.Checked if param_dict[param_name][0] == "True" else QtCore.Qt.Unchecked |
---|
| 3753 | self._model_model.item(row, 0).setCheckState(param_checked) |
---|
| 3754 | |
---|
[d2007a8] | 3755 | # parameter value can be either just a value or text on the combobox |
---|
| 3756 | param_text = param_dict[param_name][1] |
---|
| 3757 | index = self._model_model.index(row, 1) |
---|
| 3758 | widget = self.lstParams.indexWidget(index) |
---|
| 3759 | if widget is not None and isinstance(widget, QtWidgets.QComboBox): |
---|
| 3760 | # Find the right index based on text |
---|
| 3761 | combo_index = int(param_text, 0) |
---|
| 3762 | widget.setCurrentIndex(combo_index) |
---|
| 3763 | else: |
---|
| 3764 | # modify the param value |
---|
| 3765 | param_repr = GuiUtils.formatNumber(param_text, high=True) |
---|
| 3766 | self._model_model.item(row, 1).setText(param_repr) |
---|
[8e2cd79] | 3767 | |
---|
| 3768 | # Potentially the error column |
---|
| 3769 | ioffset = 0 |
---|
[6040cd7] | 3770 | joffset = 0 |
---|
| 3771 | if len(param_dict[param_name])>3: |
---|
[8e2cd79] | 3772 | # error values are not editable - no need to update |
---|
| 3773 | ioffset = 1 |
---|
[6040cd7] | 3774 | if self.has_error_column: |
---|
| 3775 | joffset = 1 |
---|
[8e2cd79] | 3776 | # min/max |
---|
[685602a] | 3777 | try: |
---|
| 3778 | param_repr = GuiUtils.formatNumber(param_dict[param_name][2+ioffset], high=True) |
---|
[6040cd7] | 3779 | self._model_model.item(row, 2+joffset).setText(param_repr) |
---|
[685602a] | 3780 | param_repr = GuiUtils.formatNumber(param_dict[param_name][3+ioffset], high=True) |
---|
[6040cd7] | 3781 | self._model_model.item(row, 3+joffset).setText(param_repr) |
---|
[685602a] | 3782 | except: |
---|
| 3783 | pass |
---|
| 3784 | |
---|
[0eff615] | 3785 | self.setFocus() |
---|
| 3786 | |
---|
[8e2cd79] | 3787 | self.iterateOverModel(updateFittedValues) |
---|
[0eff615] | 3788 | |
---|
[8e2cd79] | 3789 | def updateFullPolyModel(self, param_dict): |
---|
| 3790 | """ |
---|
| 3791 | Update the polydispersity model with new parameters, create the errors column |
---|
| 3792 | """ |
---|
| 3793 | assert isinstance(param_dict, dict) |
---|
| 3794 | if not dict: |
---|
| 3795 | return |
---|
| 3796 | |
---|
| 3797 | def updateFittedValues(row): |
---|
| 3798 | # Utility function for main model update |
---|
| 3799 | # internal so can use closure for param_dict |
---|
| 3800 | if row >= self._poly_model.rowCount(): |
---|
| 3801 | return |
---|
| 3802 | param_name = str(self._poly_model.item(row, 0).text()).rsplit()[-1] + '.width' |
---|
| 3803 | if param_name not in list(param_dict.keys()): |
---|
| 3804 | return |
---|
| 3805 | # checkbox state |
---|
| 3806 | param_checked = QtCore.Qt.Checked if param_dict[param_name][0] == "True" else QtCore.Qt.Unchecked |
---|
| 3807 | self._poly_model.item(row,0).setCheckState(param_checked) |
---|
| 3808 | |
---|
| 3809 | # modify the param value |
---|
| 3810 | param_repr = GuiUtils.formatNumber(param_dict[param_name][1], high=True) |
---|
| 3811 | self._poly_model.item(row, 1).setText(param_repr) |
---|
| 3812 | |
---|
| 3813 | # Potentially the error column |
---|
| 3814 | ioffset = 0 |
---|
[6040cd7] | 3815 | joffset = 0 |
---|
| 3816 | if len(param_dict[param_name])>3: |
---|
[8e2cd79] | 3817 | ioffset = 1 |
---|
[6040cd7] | 3818 | if self.has_poly_error_column: |
---|
| 3819 | joffset = 1 |
---|
[8e2cd79] | 3820 | # min |
---|
| 3821 | param_repr = GuiUtils.formatNumber(param_dict[param_name][2+ioffset], high=True) |
---|
[6040cd7] | 3822 | self._poly_model.item(row, 2+joffset).setText(param_repr) |
---|
[8e2cd79] | 3823 | # max |
---|
| 3824 | param_repr = GuiUtils.formatNumber(param_dict[param_name][3+ioffset], high=True) |
---|
[6040cd7] | 3825 | self._poly_model.item(row, 3+joffset).setText(param_repr) |
---|
[8e2cd79] | 3826 | # Npts |
---|
| 3827 | param_repr = GuiUtils.formatNumber(param_dict[param_name][4+ioffset], high=True) |
---|
[6040cd7] | 3828 | self._poly_model.item(row, 4+joffset).setText(param_repr) |
---|
[8e2cd79] | 3829 | # Nsigs |
---|
| 3830 | param_repr = GuiUtils.formatNumber(param_dict[param_name][5+ioffset], high=True) |
---|
[6040cd7] | 3831 | self._poly_model.item(row, 5+joffset).setText(param_repr) |
---|
[8e2cd79] | 3832 | |
---|
[0eff615] | 3833 | self.setFocus() |
---|
[8e2cd79] | 3834 | |
---|
| 3835 | self.iterateOverPolyModel(updateFittedValues) |
---|
| 3836 | |
---|
[d2007a8] | 3837 | def updateFullMagnetModel(self, param_dict): |
---|
| 3838 | """ |
---|
| 3839 | Update the magnetism model with new parameters, create the errors column |
---|
| 3840 | """ |
---|
| 3841 | assert isinstance(param_dict, dict) |
---|
| 3842 | if not dict: |
---|
| 3843 | return |
---|
| 3844 | |
---|
| 3845 | def updateFittedValues(row): |
---|
| 3846 | # Utility function for main model update |
---|
| 3847 | # internal so can use closure for param_dict |
---|
| 3848 | if row >= self._magnet_model.rowCount(): |
---|
| 3849 | return |
---|
| 3850 | param_name = str(self._magnet_model.item(row, 0).text()).rsplit()[-1] |
---|
| 3851 | if param_name not in list(param_dict.keys()): |
---|
| 3852 | return |
---|
| 3853 | # checkbox state |
---|
| 3854 | param_checked = QtCore.Qt.Checked if param_dict[param_name][0] == "True" else QtCore.Qt.Unchecked |
---|
| 3855 | self._magnet_model.item(row,0).setCheckState(param_checked) |
---|
| 3856 | |
---|
| 3857 | # modify the param value |
---|
| 3858 | param_repr = GuiUtils.formatNumber(param_dict[param_name][1], high=True) |
---|
| 3859 | self._magnet_model.item(row, 1).setText(param_repr) |
---|
[339e22b] | 3860 | |
---|
[d2007a8] | 3861 | # Potentially the error column |
---|
| 3862 | ioffset = 0 |
---|
[6040cd7] | 3863 | joffset = 0 |
---|
| 3864 | if len(param_dict[param_name])>3: |
---|
[d2007a8] | 3865 | ioffset = 1 |
---|
[6040cd7] | 3866 | if self.has_magnet_error_column: |
---|
| 3867 | joffset = 1 |
---|
[d2007a8] | 3868 | # min |
---|
| 3869 | param_repr = GuiUtils.formatNumber(param_dict[param_name][2+ioffset], high=True) |
---|
[6040cd7] | 3870 | self._magnet_model.item(row, 2+joffset).setText(param_repr) |
---|
[d2007a8] | 3871 | # max |
---|
| 3872 | param_repr = GuiUtils.formatNumber(param_dict[param_name][3+ioffset], high=True) |
---|
[6040cd7] | 3873 | self._magnet_model.item(row, 3+joffset).setText(param_repr) |
---|
[339e22b] | 3874 | |
---|
[d2007a8] | 3875 | self.iterateOverMagnetModel(updateFittedValues) |
---|
[6040cd7] | 3876 | |
---|
| 3877 | def getCurrentFitState(self, state=None): |
---|
| 3878 | """ |
---|
| 3879 | Store current state for fit_page |
---|
| 3880 | """ |
---|
| 3881 | # save model option |
---|
| 3882 | #if self.model is not None: |
---|
| 3883 | # self.disp_list = self.getDispParamList() |
---|
| 3884 | # state.disp_list = copy.deepcopy(self.disp_list) |
---|
| 3885 | # #state.model = self.model.clone() |
---|
| 3886 | |
---|
| 3887 | # Comboboxes |
---|
| 3888 | state.categorycombobox = self.cbCategory.currentText() |
---|
| 3889 | state.formfactorcombobox = self.cbModel.currentText() |
---|
| 3890 | if self.cbStructureFactor.isEnabled(): |
---|
| 3891 | state.structurecombobox = self.cbStructureFactor.currentText() |
---|
| 3892 | state.tcChi = self.chi2 |
---|
| 3893 | |
---|
| 3894 | state.enable2D = self.is2D |
---|
| 3895 | |
---|
| 3896 | #state.weights = copy.deepcopy(self.weights) |
---|
| 3897 | # save data |
---|
| 3898 | state.data = copy.deepcopy(self.data) |
---|
| 3899 | |
---|
| 3900 | # save plotting range |
---|
| 3901 | state.qmin = self.q_range_min |
---|
| 3902 | state.qmax = self.q_range_max |
---|
| 3903 | state.npts = self.npts |
---|
| 3904 | |
---|
| 3905 | # self.state.enable_disp = self.enable_disp.GetValue() |
---|
| 3906 | # self.state.disable_disp = self.disable_disp.GetValue() |
---|
| 3907 | |
---|
| 3908 | # self.state.enable_smearer = \ |
---|
| 3909 | # copy.deepcopy(self.enable_smearer.GetValue()) |
---|
| 3910 | # self.state.disable_smearer = \ |
---|
| 3911 | # copy.deepcopy(self.disable_smearer.GetValue()) |
---|
| 3912 | |
---|
| 3913 | #self.state.pinhole_smearer = \ |
---|
| 3914 | # copy.deepcopy(self.pinhole_smearer.GetValue()) |
---|
| 3915 | #self.state.slit_smearer = copy.deepcopy(self.slit_smearer.GetValue()) |
---|
| 3916 | #self.state.dI_noweight = copy.deepcopy(self.dI_noweight.GetValue()) |
---|
| 3917 | #self.state.dI_didata = copy.deepcopy(self.dI_didata.GetValue()) |
---|
| 3918 | #self.state.dI_sqrdata = copy.deepcopy(self.dI_sqrdata.GetValue()) |
---|
| 3919 | #self.state.dI_idata = copy.deepcopy(self.dI_idata.GetValue()) |
---|
| 3920 | |
---|
| 3921 | p = self.model_parameters |
---|
| 3922 | # save checkbutton state and txtcrtl values |
---|
| 3923 | state.parameters = FittingUtilities.getStandardParam(self._model_model) |
---|
| 3924 | state.orientation_params_disp = FittingUtilities.getOrientationParam(self.kernel_module) |
---|
| 3925 | |
---|
| 3926 | #self._copy_parameters_state(self.orientation_params_disp, self.state.orientation_params_disp) |
---|
| 3927 | #self._copy_parameters_state(self.parameters, self.state.parameters) |
---|
| 3928 | #self._copy_parameters_state(self.fittable_param, self.state.fittable_param) |
---|
| 3929 | #self._copy_parameters_state(self.fixed_param, self.state.fixed_param) |
---|
| 3930 | |
---|