source: sasview/src/sas/qtgui/Perspectives/Fitting/FittingWidget.py @ b87dc1a

ESS_GUIESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since b87dc1a was b87dc1a, checked in by Torin Cooper-Bennun <torin.cooper-bennun@…>, 6 years ago

keep non-fittable rows selectable, to not break layout

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