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

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

fix crash when selecting *only* S(Q)

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