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