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

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 00b7ddf0 was 00b7ddf0, checked in by Torin Cooper-Bennun <torin.cooper-bennun@…>, 6 years ago

[CHERRY-PICK FROM 4f80a834f] put sub-heading creation into FittingUtilities?; fix a couple of caused issues; fix affected tests

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