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

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 f4aa7a8 was f4aa7a8, checked in by Piotr Rozyczko <rozyczko@…>, 6 years ago

More checks for model combo being disabled. SASVIEW-1015

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