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

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 6fd4e36 was 6fd4e36, checked in by Piotr Rozyczko <rozyczko@…>, 7 years ago

Chi2 display + minor refactoring

  • Property mode set to 100755
File size: 28.9 KB
Line 
1import sys
2import json
3import os
4import numpy
5from collections import defaultdict
6
7import logging
8import traceback
9from twisted.internet import threads
10
11from PyQt4 import QtGui
12from PyQt4 import QtCore
13
14from sasmodels import generate
15from sasmodels import modelinfo
16from sasmodels.sasview_model import load_standard_models
17
18from sas.sasgui.guiframe.CategoryInstaller import CategoryInstaller
19from sas.sasgui.guiframe.dataFitting import Data1D
20from sas.sasgui.guiframe.dataFitting import Data2D
21import sas.qtgui.GuiUtils as GuiUtils
22from sas.sasgui.perspectives.fitting.model_thread import Calc1D
23from sas.sasgui.perspectives.fitting.model_thread import Calc2D
24
25from UI.FittingWidgetUI import Ui_FittingWidgetUI
26from sas.qtgui.Perspectives.Fitting.FittingLogic import FittingLogic
27from sas.qtgui.Perspectives.Fitting import FittingUtilities
28
29TAB_MAGNETISM = 4
30TAB_POLY = 3
31CATEGORY_DEFAULT = "Choose category..."
32CATEGORY_STRUCTURE = "Structure Factor"
33STRUCTURE_DEFAULT = "None"
34QMIN_DEFAULT = 0.0005
35QMAX_DEFAULT = 0.5
36NPTS_DEFAULT = 50
37
38class FittingWidget(QtGui.QWidget, Ui_FittingWidgetUI):
39    """
40    Main widget for selecting form and structure factor models
41    """
42    def __init__(self, parent=None, data=None, id=1):
43
44        super(FittingWidget, self).__init__()
45
46        # Necessary globals
47        self.parent = parent
48        # SasModel is loaded
49        self.model_is_loaded = False
50        # Data[12]D passed and set
51        self.data_is_loaded = False
52        # Current SasModel in view
53        self.kernel_module = None
54        # Current SasModel view dimension
55        self.is2D = False
56        # Current SasModel is multishell
57        self.model_has_shells = False
58        # Utility variable to enable unselectable option in category combobox
59        self._previous_category_index = 0
60        # Utility variable for multishell display
61        self._last_model_row = 0
62        # Dictionary of {model name: model class} for the current category
63        self.models = {}
64
65        # Which tab is this widget displayed in?
66        self.tab_id = id
67
68        # Which shell is being currently displayed?
69        self.current_shell_displayed = 0
70
71        # Range parameters
72        self.q_range_min = QMIN_DEFAULT
73        self.q_range_max = QMAX_DEFAULT
74        self.npts = NPTS_DEFAULT
75
76        # Main Data[12]D holder
77        self.logic = FittingLogic(data=data)
78
79        # Main GUI setup up
80        self.setupUi(self)
81        self.setWindowTitle("Fitting")
82        self.communicate = self.parent.communicate
83
84        # Define bold font for use in various controls
85        self.boldFont=QtGui.QFont()
86        self.boldFont.setBold(True)
87
88        # Set data label
89        self.label.setFont(self.boldFont)
90        self.label.setText("No data loaded")
91        self.lblFilename.setText("")
92
93        # Set the main models
94        # We can't use a single model here, due to restrictions on flattening
95        # the model tree with subclassed QAbstractProxyModel...
96        self._model_model = QtGui.QStandardItemModel()
97        self._poly_model = QtGui.QStandardItemModel()
98        self._magnet_model = QtGui.QStandardItemModel()
99
100        # Param model displayed in param list
101        self.lstParams.setModel(self._model_model)
102        self.readCategoryInfo()
103        self.model_parameters = None
104        self.lstParams.setAlternatingRowColors(True)
105
106        # Poly model displayed in poly list
107        self.lstPoly.setModel(self._poly_model)
108        self.setPolyModel()
109        self.setTableProperties(self.lstPoly)
110
111        # Magnetism model displayed in magnetism list
112        self.lstMagnetic.setModel(self._magnet_model)
113        self.setMagneticModel()
114        self.setTableProperties(self.lstMagnetic)
115
116        # Defaults for the structure factors
117        self.setDefaultStructureCombo()
118
119        # Make structure factor and model CBs disabled
120        self.disableModelCombo()
121        self.disableStructureCombo()
122
123        # Generate the category list for display
124        category_list = sorted(self.master_category_dict.keys())
125        self.cbCategory.addItem(CATEGORY_DEFAULT)
126        self.cbCategory.addItems(category_list)
127        self.cbCategory.addItem(CATEGORY_STRUCTURE)
128        self.cbCategory.setCurrentIndex(0)
129
130        self._index = None
131        if data is not None:
132            self.data = data
133
134        # Connect signals to controls
135        self.initializeSignals()
136
137        # Initial control state
138        self.initializeControls()
139
140    @property
141    def data(self):
142        return self.logic.data
143
144    @data.setter
145    def data(self, value):
146        """ data setter """
147        assert isinstance(value[0], QtGui.QStandardItem)
148        # _index contains the QIndex with data
149        self._index = value[0]
150
151        # Update logics with data items
152        self.logic.data = GuiUtils.dataFromItem(value[0])
153
154        self.data_is_loaded = True
155        # Tag along functionality
156        self.label.setText("Data loaded from: ")
157        self.lblFilename.setText(self.logic.data.filename)
158        self.updateQRange()
159        self.cmdFit.setEnabled(True)
160
161    def acceptsData(self):
162        """ Tells the caller this widget can accept new dataset """
163        return not self.data_is_loaded
164
165    def disableModelCombo(self):
166        """ Disable the combobox """
167        self.cbModel.setEnabled(False)
168        self.lblModel.setEnabled(False)
169
170    def enableModelCombo(self):
171        """ Enable the combobox """
172        self.cbModel.setEnabled(True)
173        self.lblModel.setEnabled(True)
174
175    def disableStructureCombo(self):
176        """ Disable the combobox """
177        self.cbStructureFactor.setEnabled(False)
178        self.lblStructure.setEnabled(False)
179
180    def enableStructureCombo(self):
181        """ Enable the combobox """
182        self.cbStructureFactor.setEnabled(True)
183        self.lblStructure.setEnabled(True)
184
185    def updateQRange(self):
186        """
187        Updates Q Range display
188        """
189        if self.data_is_loaded:
190            self.q_range_min, self.q_range_max, self.npts = self.logic.computeDataRange()
191        # set Q range labels on the main tab
192        self.lblMinRangeDef.setText(str(self.q_range_min))
193        self.lblMaxRangeDef.setText(str(self.q_range_max))
194        # set Q range labels on the options tab
195        self.txtMaxRange.setText(str(self.q_range_max))
196        self.txtMinRange.setText(str(self.q_range_min))
197        self.txtNpts.setText(str(self.npts))
198
199    def initializeControls(self):
200        """
201        Set initial control enablement
202        """
203        self.cmdFit.setEnabled(False)
204        self.cmdPlot.setEnabled(True)
205        self.chkPolydispersity.setEnabled(True)
206        self.chkPolydispersity.setCheckState(False)
207        self.chk2DView.setEnabled(True)
208        self.chk2DView.setCheckState(False)
209        self.chkMagnetism.setEnabled(False)
210        self.chkMagnetism.setCheckState(False)
211        # Tabs
212        self.tabFitting.setTabEnabled(TAB_POLY, False)
213        self.tabFitting.setTabEnabled(TAB_MAGNETISM, False)
214        self.lblChi2Value.setText("---")
215        # Update Q Ranges
216        self.updateQRange()
217
218    def initializeSignals(self):
219        """
220        Connect GUI element signals
221        """
222        # Comboboxes
223        self.cbStructureFactor.currentIndexChanged.connect(self.onSelectStructureFactor)
224        self.cbCategory.currentIndexChanged.connect(self.onSelectCategory)
225        self.cbModel.currentIndexChanged.connect(self.onSelectModel)
226        # Checkboxes
227        self.chk2DView.toggled.connect(self.toggle2D)
228        self.chkPolydispersity.toggled.connect(self.togglePoly)
229        self.chkMagnetism.toggled.connect(self.toggleMagnetism)
230        # Buttons
231        self.cmdFit.clicked.connect(self.onFit)
232        self.cmdPlot.clicked.connect(self.onPlot)
233        # Line edits
234        self.txtNpts.textChanged.connect(self.onNpts)
235        self.txtMinRange.textChanged.connect(self.onMinRange)
236        self.txtMaxRange.textChanged.connect(self.onMaxRange)
237
238        # Respond to change in parameters from the UI
239        self._model_model.itemChanged.connect(self.updateParamsFromModel)
240        self._poly_model.itemChanged.connect(self.onPolyModelChange)
241        # TODO after the poly_model prototype accepted
242        #self._magnet_model.itemChanged.connect(self.onMagneticModelChange)
243
244    def setDefaultStructureCombo(self):
245        """
246        Fill in the structure factors combo box with defaults
247        """
248        structure_factor_list = self.master_category_dict.pop(CATEGORY_STRUCTURE)
249        factors = [factor[0] for factor in structure_factor_list]
250        factors.insert(0, STRUCTURE_DEFAULT)
251        self.cbStructureFactor.clear()
252        self.cbStructureFactor.addItems(sorted(factors))
253
254    def onSelectCategory(self):
255        """
256        Select Category from list
257        """
258        category = str(self.cbCategory.currentText())
259        # Check if the user chose "Choose category entry"
260        if category == CATEGORY_DEFAULT:
261            # if the previous category was not the default, keep it.
262            # Otherwise, just return
263            if self._previous_category_index != 0:
264                # We need to block signals, or else state changes on perceived unchanged conditions
265                self.cbCategory.blockSignals(True)
266                self.cbCategory.setCurrentIndex(self._previous_category_index)
267                self.cbCategory.blockSignals(False)
268            return
269
270        if category == CATEGORY_STRUCTURE:
271            self.disableModelCombo()
272            self.enableStructureCombo()
273            self._model_model.clear()
274            return
275
276        # Safely clear and enable the model combo
277        self.cbModel.blockSignals(True)
278        self.cbModel.clear()
279        self.cbModel.blockSignals(False)
280        self.enableModelCombo()
281        self.disableStructureCombo()
282
283        self._previous_category_index = self.cbCategory.currentIndex()
284        # Retrieve the list of models
285        model_list = self.master_category_dict[category]
286        models = []
287        # Populate the models combobox
288        self.cbModel.addItems(sorted([model for (model, _) in model_list]))
289
290    def createDefaultDataset(self):
291        """
292        Generate default Dataset 1D/2D for the given model
293        """
294        # Create default datasets if no data passed
295        if self.is2D:
296            qmax = self.q_range_max/numpy.sqrt(2)
297            qstep = self.npts
298            self.logic.createDefault2dData(qmax, qstep, self.tab_id)
299        else:
300            interval = numpy.linspace(start=self.q_range_min, stop=self.q_range_max,
301                        num=self.npts, endpoint=True)
302            self.logic.createDefault1dData(interval, self.tab_id)
303
304    def onSelectModel(self):
305        """
306        Respond to select Model from list event
307        """
308        model = str(self.cbModel.currentText())
309
310        # Reset structure factor
311        self.cbStructureFactor.setCurrentIndex(0)
312
313        # SasModel -> QModel
314        self.SASModelToQModel(model)
315
316        if self.data_is_loaded:
317            self.calculateQGridForModel()
318        else:
319            # Create default datasets if no data passed
320            self.createDefaultDataset()
321
322    def onSelectStructureFactor(self):
323        """
324        Select Structure Factor from list
325        """
326        model = str(self.cbModel.currentText())
327        category = str(self.cbCategory.currentText())
328        structure = str(self.cbStructureFactor.currentText())
329        if category == CATEGORY_STRUCTURE:
330            model = None
331        self.SASModelToQModel(model, structure_factor=structure)
332
333    def readCategoryInfo(self):
334        """
335        Reads the categories in from file
336        """
337        self.master_category_dict = defaultdict(list)
338        self.by_model_dict = defaultdict(list)
339        self.model_enabled_dict = defaultdict(bool)
340
341        categorization_file = CategoryInstaller.get_user_file()
342        if not os.path.isfile(categorization_file):
343            categorization_file = CategoryInstaller.get_default_file()
344        with open(categorization_file, 'rb') as cat_file:
345            self.master_category_dict = json.load(cat_file)
346            self.regenerateModelDict()
347
348        # Load the model dict
349        models = load_standard_models()
350        for model in models:
351            self.models[model.name] = model
352
353    def regenerateModelDict(self):
354        """
355        Regenerates self.by_model_dict which has each model name as the
356        key and the list of categories belonging to that model
357        along with the enabled mapping
358        """
359        self.by_model_dict = defaultdict(list)
360        for category in self.master_category_dict:
361            for (model, enabled) in self.master_category_dict[category]:
362                self.by_model_dict[model].append(category)
363                self.model_enabled_dict[model] = enabled
364
365    def addBackgroundToModel(self, model):
366        """
367        Adds background parameter with default values to the model
368        """
369        assert isinstance(model, QtGui.QStandardItemModel)
370        checked_list = ['background', '0.001', '-inf', 'inf', '1/cm']
371        FittingUtilities.addCheckedListToModel(model, checked_list)
372
373    def addScaleToModel(self, model):
374        """
375        Adds scale parameter with default values to the model
376        """
377        assert isinstance(model, QtGui.QStandardItemModel)
378        checked_list = ['scale', '1.0', '0.0', 'inf', '']
379        FittingUtilities.addCheckedListToModel(model, checked_list)
380
381    def SASModelToQModel(self, model_name, structure_factor=None):
382        """
383        Setting model parameters into table based on selected category
384        """
385        # TODO - modify for structure factor-only choice
386
387        # Crete/overwrite model items
388        self._model_model.clear()
389
390        kernel_module = generate.load_kernel_module(model_name)
391        self.model_parameters = modelinfo.make_parameter_table(getattr(kernel_module, 'parameters', []))
392
393        # Instantiate the current sasmodel
394        self.kernel_module = self.models[model_name]()
395
396        # Explicitly add scale and background with default values
397        self.addScaleToModel(self._model_model)
398        self.addBackgroundToModel(self._model_model)
399
400        # Update the QModel
401        FittingUtilities.addParametersToModel(self.model_parameters, self._model_model)
402        # Update the counter used for multishell display
403        self._last_model_row = self._model_model.rowCount()
404
405        FittingUtilities.addHeadersToModel(self._model_model)
406
407        # Add structure factor
408        if structure_factor is not None and structure_factor != "None":
409            structure_module = generate.load_kernel_module(structure_factor)
410            structure_parameters = modelinfo.make_parameter_table(getattr(structure_module, 'parameters', []))
411            FittingUtilities.addSimpleParametersToModel(structure_parameters, self._model_model)
412            # Update the counter used for multishell display
413            self._last_model_row = self._model_model.rowCount()
414        else:
415            self.addStructureFactor()
416
417        # Multishell models need additional treatment
418        self.addExtraShells()
419
420        # Add polydispersity to the model
421        self.setPolyModel()
422        # Add magnetic parameters to the model
423        self.setMagneticModel()
424
425        # Adjust the table cells width
426        self.lstParams.resizeColumnToContents(0)
427        self.lstParams.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Expanding)
428
429        # Now we claim the model has been loaded
430        self.model_is_loaded = True
431
432        # Update Q Ranges
433        self.updateQRange()
434
435    def onPolyModelChange(self, item):
436        """
437        Callback method for updating the main model and sasmodel
438        parameters with the GUI values in the polydispersity view
439        """
440        model_column = item.column()
441        model_row = item.row()
442        name_index = self._poly_model.index(model_row, 0)
443        # Extract changed value. Assumes proper validation by QValidator/Delegate
444        # Checkbox in column 0
445        if model_column == 0:
446            value = item.checkState()
447        else:
448            try:
449                value = float(item.text())
450            except ValueError:
451                # Can't be converted properly, bring back the old value and exit
452                return
453
454        parameter_name = str(self._poly_model.data(name_index).toPyObject()) # "distribution of sld" etc.
455        if "Distribution of" in parameter_name:
456            parameter_name = parameter_name[16:]
457        property_name = str(self._poly_model.headerData(model_column, 1).toPyObject()) # Value, min, max, etc.
458        # print "%s(%s) => %d" % (parameter_name, property_name, value)
459
460        # Update the sasmodel
461        #self.kernel_module.params[parameter_name] = value
462
463        # Reload the main model - may not be required if no variable is shown in main view
464        #model = str(self.cbModel.currentText())
465        #self.SASModelToQModel(model)
466
467        pass # debug anchor
468
469    def updateParamsFromModel(self, item):
470        """
471        Callback method for updating the sasmodel parameters with the GUI values
472        """
473        model_column = item.column()
474        model_row = item.row()
475        name_index = self._model_model.index(model_row, 0)
476
477        if model_column == 0:
478            # Assure we're dealing with checkboxes
479            if not item.isCheckable():
480                return
481            status = item.checkState()
482            # If multiple rows selected - toggle all of them
483            rows = [s.row() for s in self.lstParams.selectionModel().selectedRows()]
484
485            # Switch off signaling from the model to avoid multiple calls
486            self._model_model.blockSignals(True)
487            # Convert to proper indices and set requested enablement
488            items = [self._model_model.item(row, 0).setCheckState(status) for row in rows]
489            self._model_model.blockSignals(False)
490            return
491
492        # Extract changed value. Assumes proper validation by QValidator/Delegate
493        value = float(item.text())
494        parameter_name = str(self._model_model.data(name_index).toPyObject()) # sld, background etc.
495        property_name = str(self._model_model.headerData(1, model_column).toPyObject()) # Value, min, max, etc.
496
497        # print "%s(%s) => %d" % (parameter_name, property_name, value)
498        self.kernel_module.params[parameter_name] = value
499
500        # min/max to be changed in self.kernel_module.details[parameter_name] = ['Ang', 0.0, inf]
501
502        # magnetic params in self.kernel_module.details['M0:parameter_name'] = value
503        # multishell params in self.kernel_module.details[??] = value
504
505    def nameForFittedData(self, name):
506        """
507        Generate name for the current fit
508        """
509        if self.is2D:
510            name += "2d"
511        name = "M%i [%s]" % (self.tab_id, name)
512        return name
513
514    def createNewIndex(self, fitted_data):
515        """
516        Create a model or theory index with passed Data1D/Data2D
517        """
518        if self.data_is_loaded:
519            self.updateModelIndex(fitted_data)
520        else:
521            self.createTheoryIndex(fitted_data)
522
523    def updateModelIndex(self, fitted_data):
524        """
525        Update a QStandardModelIndex containing model data
526        """
527        name = self.nameForFittedData(self.logic.data.filename)
528        fitted_data.title = name
529        fitted_data.name = name
530        # Make this a line
531        fitted_data.symbol = 'Line'
532        # Notify the GUI manager so it can update the main model in DataExplorer
533        GuiUtils.updateModelItemWithPlot(self._index, QtCore.QVariant(fitted_data), name)
534
535    def createTheoryIndex(self, fitted_data):
536        """
537        Create a QStandardModelIndex containing model data
538        """
539        name = self.nameForFittedData(self.kernel_module.name)
540        fitted_data.title = name
541        fitted_data.name = name
542        fitted_data.filename = name
543        # Notify the GUI manager so it can create the theory model in DataExplorer
544        new_item = GuiUtils.createModelItemWithPlot(QtCore.QVariant(fitted_data), name=name)
545        self.communicate.updateTheoryFromPerspectiveSignal.emit(new_item)
546
547    def onFit(self):
548        """
549        Perform fitting on the current data
550        """
551        # TODO: everything here
552        #self.calculate1DForModel()
553        pass
554
555    def onPlot(self):
556        """
557        Plot the current set of data
558        """
559        if self.data is None :#or not self.data.is_data:
560            self.createDefaultDataset()
561        self.calculateQGridForModel()
562
563    def onNpts(self, text):
564        """
565        Callback for number of points line edit update
566        """
567        # assumes type/value correctness achieved with QValidator
568        try:
569            self.npts = int(text)
570        except ValueError:
571            # TODO
572            # This will return the old value to model/view and return
573            # notifying the user about format available.
574            pass
575
576    def onMinRange(self, text):
577        """
578        Callback for minimum range of points line edit update
579        """
580        # assumes type/value correctness achieved with QValidator
581        try:
582            self.q_range_min = float(text)
583        except ValueError:
584            # TODO
585            # This will return the old value to model/view and return
586            # notifying the user about format available.
587            return
588        # set Q range labels on the main tab
589        self.lblMinRangeDef.setText(str(self.q_range_min))
590
591    def onMaxRange(self, text):
592        """
593        Callback for maximum range of points line edit update
594        """
595        # assumes type/value correctness achieved with QValidator
596        try:
597            self.q_range_max = float(text)
598        except:
599            pass
600        # set Q range labels on the main tab
601        self.lblMaxRangeDef.setText(str(self.q_range_max))
602
603    def methodCalculateForData(self):
604        '''return the method for data calculation'''
605        return Calc1D if isinstance(self.data, Data1D) else Calc2D
606
607    def methodCompleteForData(self):
608        '''return the method for result parsin on calc complete '''
609        return self.complete1D if isinstance(self.data, Data1D) else self.complete2D
610
611    def calculateQGridForModel(self):
612        """
613        Prepare the fitting data object, based on current ModelModel
614        """
615        # Awful API to a backend method.
616        method = self.methodCalculateForData()(data=self.data,
617                              model=self.kernel_module,
618                              page_id=0,
619                              qmin=self.q_range_min,
620                              qmax=self.q_range_max,
621                              smearer=None,
622                              state=None,
623                              weight=None,
624                              fid=None,
625                              toggle_mode_on=False,
626                              completefn=None,
627                              update_chisqr=True,
628                              exception_handler=self.calcException,
629                              source=None)
630
631        calc_thread = threads.deferToThread(method.compute)
632        calc_thread.addCallback(self.methodCompleteForData())
633
634    def complete1D(self, return_data):
635        """
636        Plot the current 1D data
637        """
638        fitted_data = self.logic.new1DPlot(return_data)
639        self.calculateResiduals(self.logic.new1DPlot(return_data))
640
641    def complete2D(self, return_data):
642        """
643        Plot the current 2D data
644        """
645        fitted_data = self.logic.new2DPlot(return_data)
646        self.calculateResiduals(fitted_data)
647
648    def calculateResiduals(self, fitted_data):
649        """
650        Calculate and print Chi2 and display chart of residuals
651        """
652        # Create a new index for holding data
653        self.createNewIndex(fitted_data)
654        # Calculate difference between return_data and logic.data
655        chi2 = FittingUtilities.calculateChi2(fitted_data, self.logic.data)
656        # Update the control
657        self.lblChi2Value.setText(GuiUtils.formatNumber(chi2, high=True))
658
659        # TODO: plot residuals
660        #self._plot_residuals(page_id=page_id, data=current_data,
661        #                        fid=fid,
662        #                        weight=weight, index=index)
663
664    def calcException(self, etype, value, tb):
665        """
666        Something horrible happened in the deferred.
667        """
668        logging.error("".join(traceback.format_exception(etype, value, tb)))
669
670    def setTableProperties(self, table):
671        """
672        Setting table properties
673        """
674        # Table properties
675        table.verticalHeader().setVisible(False)
676        table.setAlternatingRowColors(True)
677        table.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Expanding)
678        table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
679        table.resizeColumnsToContents()
680
681        # Header
682        header = table.horizontalHeader()
683        header.setResizeMode(QtGui.QHeaderView.ResizeToContents)
684
685        header.ResizeMode(QtGui.QHeaderView.Interactive)
686        # Resize column 0 and 6 to content
687        header.setResizeMode(0, QtGui.QHeaderView.ResizeToContents)
688        header.setResizeMode(6, QtGui.QHeaderView.ResizeToContents)
689
690    def setPolyModel(self):
691        """
692        Set polydispersity values
693        """
694        if not self.model_parameters:
695            return
696        self._poly_model.clear()
697        for row, param in enumerate(self.model_parameters.form_volume_parameters):
698            # Counters should not be included
699            if not param.polydisperse:
700                continue
701
702            # Potential multishell params
703            checked_list = ["Distribution of "+param.name, str(param.default),
704                            str(param.limits[0]), str(param.limits[1]),
705                            "35", "3", ""]
706            FittingUtilities.addCheckedListToModel(self._poly_model, checked_list)
707
708            #TODO: Need to find cleaner way to input functions
709            func = QtGui.QComboBox()
710            func.addItems(['rectangle', 'array', 'lognormal', 'gaussian', 'schulz',])
711            func_index = self.lstPoly.model().index(row, 6)
712            self.lstPoly.setIndexWidget(func_index, func)
713
714        FittingUtilities.addPolyHeadersToModel(self._poly_model)
715
716    def setMagneticModel(self):
717        """
718        Set magnetism values on model
719        """
720        if not self.model_parameters:
721            return
722        self._magnet_model.clear()
723        for param in self.model_parameters.call_parameters:
724            if param.type != "magnetic":
725                continue
726            checked_list = [param.name,
727                            str(param.default),
728                            str(param.limits[0]),
729                            str(param.limits[1]),
730                            param.units]
731            FittingUtilities.addCheckedListToModel(self._magnet_model, checked_list)
732
733        FittingUtilities.addHeadersToModel(self._magnet_model)
734
735    def addStructureFactor(self):
736        """
737        Add structure factors to the list of parameters
738        """
739        if self.kernel_module.is_form_factor:
740            self.enableStructureCombo()
741        else:
742            self.disableStructureCombo()
743
744    def addExtraShells(self):
745        """
746        Add a combobox for multiple shell display
747        """
748        param_name, param_length = FittingUtilities.getMultiplicity(self.model_parameters)
749
750        if param_length == 0:
751            return
752
753        # cell 1: variable name
754        item1 = QtGui.QStandardItem(param_name)
755
756        func = QtGui.QComboBox()
757        # Available range of shells displayed in the combobox
758        func.addItems([str(i) for i in xrange(param_length+1)])
759
760        # Respond to index change
761        func.currentIndexChanged.connect(self.modifyShellsInList)
762
763        # cell 2: combobox
764        item2 = QtGui.QStandardItem()
765        self._model_model.appendRow([item1, item2])
766
767        # Beautify the row:  span columns 2-4
768        shell_row = self._model_model.rowCount()
769        shell_index = self._model_model.index(shell_row-1, 1)
770
771        self.lstParams.setIndexWidget(shell_index, func)
772        self._last_model_row = self._model_model.rowCount()
773
774        # Set the index to the state-kept value
775        func.setCurrentIndex(self.current_shell_displayed
776                             if self.current_shell_displayed < func.count() else 0)
777
778    def modifyShellsInList(self, index):
779        """
780        Add/remove additional multishell parameters
781        """
782        # Find row location of the combobox
783        last_row = self._last_model_row
784        remove_rows = self._model_model.rowCount() - last_row
785
786        if remove_rows > 1:
787            self._model_model.removeRows(last_row, remove_rows)
788
789        FittingUtilities.addShellsToModel(self.model_parameters, self._model_model, index)
790        self.current_shell_displayed = index
791
792    def togglePoly(self, isChecked):
793        """
794        Enable/disable the polydispersity tab
795        """
796        self.tabFitting.setTabEnabled(TAB_POLY, isChecked)
797
798    def toggleMagnetism(self, isChecked):
799        """
800        Enable/disable the magnetism tab
801        """
802        self.tabFitting.setTabEnabled(TAB_MAGNETISM, isChecked)
803
804    def toggle2D(self, isChecked):
805        """
806        Enable/disable the controls dependent on 1D/2D data instance
807        """
808        self.chkMagnetism.setEnabled(isChecked)
809        self.is2D = isChecked
810
Note: See TracBrowser for help on using the repository browser.