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

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

Compute/Show? Plot button logic: SASVIEW-271
Unit tests for plotting in fitting: SASVIEW-501

  • Property mode set to 100644
File size: 39.0 KB
Line 
1import sys
2import json
3import os
4import numpy as np
5from collections import defaultdict
6from itertools import izip
7
8import logging
9import traceback
10from twisted.internet import threads
11
12from PyQt4 import QtGui
13from PyQt4 import QtCore
14
15from sasmodels import generate
16from sasmodels import modelinfo
17from sasmodels.sasview_model import load_standard_models
18from sas.sascalc.fit.BumpsFitting import BumpsFit as Fit
19from sas.sasgui.perspectives.fitting.fit_thread import FitThread
20
21from sas.sasgui.guiframe.CategoryInstaller import CategoryInstaller
22from sas.sasgui.guiframe.dataFitting import Data1D
23from sas.sasgui.guiframe.dataFitting import Data2D
24import sas.qtgui.Utilities.GuiUtils as GuiUtils
25from sas.sasgui.perspectives.fitting.model_thread import Calc1D
26from sas.sasgui.perspectives.fitting.model_thread import Calc2D
27from sas.sasgui.perspectives.fitting.utils import get_weight
28
29from UI.FittingWidgetUI import Ui_FittingWidgetUI
30from sas.qtgui.Perspectives.Fitting.FittingLogic import FittingLogic
31from sas.qtgui.Perspectives.Fitting import FittingUtilities
32from SmearingWidget import SmearingWidget
33from OptionsWidget import OptionsWidget
34
35TAB_MAGNETISM = 4
36TAB_POLY = 3
37CATEGORY_DEFAULT = "Choose category..."
38CATEGORY_STRUCTURE = "Structure Factor"
39STRUCTURE_DEFAULT = "None"
40
41class FittingWidget(QtGui.QWidget, Ui_FittingWidgetUI):
42    """
43    Main widget for selecting form and structure factor models
44    """
45    def __init__(self, parent=None, data=None, id=1):
46
47        super(FittingWidget, self).__init__()
48
49        # Necessary globals
50        self.parent = parent
51        # SasModel is loaded
52        self.model_is_loaded = False
53        # Data[12]D passed and set
54        self.data_is_loaded = False
55        # Current SasModel in view
56        self.kernel_module = None
57        # Current SasModel view dimension
58        self.is2D = False
59        # Current SasModel is multishell
60        self.model_has_shells = False
61        # Utility variable to enable unselectable option in category combobox
62        self._previous_category_index = 0
63        # Utility variable for multishell display
64        self._last_model_row = 0
65        # Dictionary of {model name: model class} for the current category
66        self.models = {}
67        # Parameters to fit
68        self.parameters_to_fit = None
69        # Fit options
70        self.q_range_min = 0.005
71        self.q_range_max = 0.1
72        self.npts = 25
73        self.log_points = False
74        self.weighting = 0
75
76        # Data for chosen model
77        self.model_data = None
78
79        # Which tab is this widget displayed in?
80        self.tab_id = id
81
82        # Which shell is being currently displayed?
83        self.current_shell_displayed = 0
84        self.has_error_column = False
85
86        # Main Data[12]D holder
87        self.logic = FittingLogic(data=data)
88
89        # Main GUI setup up
90        self.setupUi(self)
91        self.setWindowTitle("Fitting")
92        self.communicate = self.parent.communicate
93
94        # Options widget
95        layout = QtGui.QGridLayout()
96        self.options_widget = OptionsWidget(self, self.logic)
97        layout.addWidget(self.options_widget) 
98        self.tabOptions.setLayout(layout)
99
100        # Smearing widget
101        layout = QtGui.QGridLayout()
102        self.smearing_widget = SmearingWidget(self)
103        layout.addWidget(self.smearing_widget) 
104        self.tabResolution.setLayout(layout)
105
106        # Define bold font for use in various controls
107        self.boldFont=QtGui.QFont()
108        self.boldFont.setBold(True)
109
110        # Set data label
111        self.label.setFont(self.boldFont)
112        self.label.setText("No data loaded")
113        self.lblFilename.setText("")
114
115        # Set the main models
116        # We can't use a single model here, due to restrictions on flattening
117        # the model tree with subclassed QAbstractProxyModel...
118        self._model_model = QtGui.QStandardItemModel()
119        self._poly_model = QtGui.QStandardItemModel()
120        self._magnet_model = QtGui.QStandardItemModel()
121
122        # Param model displayed in param list
123        self.lstParams.setModel(self._model_model)
124        self.readCategoryInfo()
125        self.model_parameters = None
126        self.lstParams.setAlternatingRowColors(True)
127        stylesheet = """
128            QTreeView{
129                alternate-background-color: #f6fafb;
130                background: #e8f4fc;
131            }
132        """
133        self.lstParams.setStyleSheet(stylesheet)
134
135        # Poly model displayed in poly list
136        self.lstPoly.setModel(self._poly_model)
137        self.setPolyModel()
138        self.setTableProperties(self.lstPoly)
139
140        # Magnetism model displayed in magnetism list
141        self.lstMagnetic.setModel(self._magnet_model)
142        self.setMagneticModel()
143        self.setTableProperties(self.lstMagnetic)
144
145        # Defaults for the structure factors
146        self.setDefaultStructureCombo()
147
148        # Make structure factor and model CBs disabled
149        self.disableModelCombo()
150        self.disableStructureCombo()
151
152        # Generate the category list for display
153        category_list = sorted(self.master_category_dict.keys())
154        self.cbCategory.addItem(CATEGORY_DEFAULT)
155        self.cbCategory.addItems(category_list)
156        self.cbCategory.addItem(CATEGORY_STRUCTURE)
157        self.cbCategory.setCurrentIndex(0)
158
159        # Connect signals to controls
160        self.initializeSignals()
161
162        # Initial control state
163        self.initializeControls()
164
165        self._index = None
166        if data is not None:
167            self.data = data
168
169    @property
170    def data(self):
171        return self.logic.data
172
173    @data.setter
174    def data(self, value):
175        """ data setter """
176        assert isinstance(value, QtGui.QStandardItem)
177        # _index contains the QIndex with data
178        self._index = value
179
180        # Update logics with data items
181        self.logic.data = GuiUtils.dataFromItem(value)
182
183        # Overwrite data type descriptor
184        self.is2D = True if isinstance(self.logic.data, Data2D) else False
185
186        self.data_is_loaded = True
187
188        # Enable/disable UI components
189        self.setEnablementOnDataLoad()
190
191    def setEnablementOnDataLoad(self):
192        """
193        Enable/disable various UI elements based on data loaded
194        """
195        # Tag along functionality
196        self.label.setText("Data loaded from: ")
197        self.lblFilename.setText(self.logic.data.filename)
198        self.updateQRange()
199        self.cmdFit.setEnabled(True)
200        # Switch off Data2D control
201        self.chk2DView.setEnabled(False)
202        self.chk2DView.setVisible(False)
203        self.chkMagnetism.setEnabled(True)
204        # Similarly on other tabs
205        self.options_widget.setEnablementOnDataLoad()
206
207        # Smearing tab
208        self.smearing_widget.updateSmearing(self.data)
209
210    def acceptsData(self):
211        """ Tells the caller this widget can accept new dataset """
212        return not self.data_is_loaded
213
214    def disableModelCombo(self):
215        """ Disable the combobox """
216        self.cbModel.setEnabled(False)
217        self.lblModel.setEnabled(False)
218
219    def enableModelCombo(self):
220        """ Enable the combobox """
221        self.cbModel.setEnabled(True)
222        self.lblModel.setEnabled(True)
223
224    def disableStructureCombo(self):
225        """ Disable the combobox """
226        self.cbStructureFactor.setEnabled(False)
227        self.lblStructure.setEnabled(False)
228
229    def enableStructureCombo(self):
230        """ Enable the combobox """
231        self.cbStructureFactor.setEnabled(True)
232        self.lblStructure.setEnabled(True)
233
234    def togglePoly(self, isChecked):
235        """ Enable/disable the polydispersity tab """
236        self.tabFitting.setTabEnabled(TAB_POLY, isChecked)
237
238    def toggleMagnetism(self, isChecked):
239        """ Enable/disable the magnetism tab """
240        self.tabFitting.setTabEnabled(TAB_MAGNETISM, isChecked)
241
242    def toggle2D(self, isChecked):
243        """ Enable/disable the controls dependent on 1D/2D data instance """
244        self.chkMagnetism.setEnabled(isChecked)
245        self.is2D = isChecked
246        # Reload the current model
247        if self.kernel_module:
248            self.onSelectModel()
249
250    def initializeControls(self):
251        """
252        Set initial control enablement
253        """
254        self.cmdFit.setEnabled(False)
255        self.cmdPlot.setEnabled(False)
256        self.options_widget.cmdComputePoints.setVisible(False) # probably redundant
257        self.chkPolydispersity.setEnabled(True)
258        self.chkPolydispersity.setCheckState(False)
259        self.chk2DView.setEnabled(True)
260        self.chk2DView.setCheckState(False)
261        self.chkMagnetism.setEnabled(False)
262        self.chkMagnetism.setCheckState(False)
263        # Tabs
264        self.tabFitting.setTabEnabled(TAB_POLY, False)
265        self.tabFitting.setTabEnabled(TAB_MAGNETISM, False)
266        self.lblChi2Value.setText("---")
267        # Smearing tab
268        self.smearing_widget.updateSmearing(self.data)
269        # Line edits in the option tab
270        self.updateQRange()
271
272    def initializeSignals(self):
273        """
274        Connect GUI element signals
275        """
276        # Comboboxes
277        self.cbStructureFactor.currentIndexChanged.connect(self.onSelectStructureFactor)
278        self.cbCategory.currentIndexChanged.connect(self.onSelectCategory)
279        self.cbModel.currentIndexChanged.connect(self.onSelectModel)
280        # Checkboxes
281        self.chk2DView.toggled.connect(self.toggle2D)
282        self.chkPolydispersity.toggled.connect(self.togglePoly)
283        self.chkMagnetism.toggled.connect(self.toggleMagnetism)
284        # Buttons
285        self.cmdFit.clicked.connect(self.onFit)
286        self.cmdPlot.clicked.connect(self.onPlot)
287
288        # Respond to change in parameters from the UI
289        self._model_model.itemChanged.connect(self.updateParamsFromModel)
290        self._poly_model.itemChanged.connect(self.onPolyModelChange)
291        # TODO after the poly_model prototype accepted
292        #self._magnet_model.itemChanged.connect(self.onMagneticModelChange)
293
294        # Signals from separate tabs asking for replot
295        self.options_widget.plot_signal.connect(self.onOptionsUpdate)
296
297    def onSelectModel(self):
298        """
299        Respond to select Model from list event
300        """
301        model = str(self.cbModel.currentText())
302
303        # Reset structure factor
304        self.cbStructureFactor.setCurrentIndex(0)
305
306        # Reset parameters to fit
307        self.parameters_to_fit = None
308        self.has_error_column = False
309
310        # Set enablement on calculate/plot
311        self.cmdPlot.setEnabled(True)
312
313        # SasModel -> QModel
314        self.SASModelToQModel(model)
315
316        if self.data_is_loaded:
317            self.cmdPlot.setText("Show Plot")
318            self.calculateQGridForModel()
319        else:
320            self.cmdPlot.setText("Calculate")
321            # Create default datasets if no data passed
322            self.createDefaultDataset()
323
324    def onSelectStructureFactor(self):
325        """
326        Select Structure Factor from list
327        """
328        model = str(self.cbModel.currentText())
329        category = str(self.cbCategory.currentText())
330        structure = str(self.cbStructureFactor.currentText())
331        if category == CATEGORY_STRUCTURE:
332            model = None
333        self.SASModelToQModel(model, structure_factor=structure)
334
335    def onSelectCategory(self):
336        """
337        Select Category from list
338        """
339        category = str(self.cbCategory.currentText())
340        # Check if the user chose "Choose category entry"
341        if category == CATEGORY_DEFAULT:
342            # if the previous category was not the default, keep it.
343            # Otherwise, just return
344            if self._previous_category_index != 0:
345                # We need to block signals, or else state changes on perceived unchanged conditions
346                self.cbCategory.blockSignals(True)
347                self.cbCategory.setCurrentIndex(self._previous_category_index)
348                self.cbCategory.blockSignals(False)
349            return
350
351        if category == CATEGORY_STRUCTURE:
352            self.disableModelCombo()
353            self.enableStructureCombo()
354            self._model_model.clear()
355            return
356
357        # Safely clear and enable the model combo
358        self.cbModel.blockSignals(True)
359        self.cbModel.clear()
360        self.cbModel.blockSignals(False)
361        self.enableModelCombo()
362        self.disableStructureCombo()
363
364        self._previous_category_index = self.cbCategory.currentIndex()
365        # Retrieve the list of models
366        model_list = self.master_category_dict[category]
367        models = []
368        # Populate the models combobox
369        self.cbModel.addItems(sorted([model for (model, _) in model_list]))
370
371    def onPolyModelChange(self, item):
372        """
373        Callback method for updating the main model and sasmodel
374        parameters with the GUI values in the polydispersity view
375        """
376        model_column = item.column()
377        model_row = item.row()
378        name_index = self._poly_model.index(model_row, 0)
379        # Extract changed value. Assumes proper validation by QValidator/Delegate
380        # Checkbox in column 0
381        if model_column == 0:
382            value = item.checkState()
383        else:
384            try:
385                value = float(item.text())
386            except ValueError:
387                # Can't be converted properly, bring back the old value and exit
388                return
389
390        parameter_name = str(self._poly_model.data(name_index).toPyObject()) # "distribution of sld" etc.
391        if "Distribution of" in parameter_name:
392            parameter_name = parameter_name[16:]
393        property_name = str(self._poly_model.headerData(model_column, 1).toPyObject()) # Value, min, max, etc.
394        # print "%s(%s) => %d" % (parameter_name, property_name, value)
395
396        # Update the sasmodel
397        #self.kernel_module.params[parameter_name] = value
398
399        # Reload the main model - may not be required if no variable is shown in main view
400        #model = str(self.cbModel.currentText())
401        #self.SASModelToQModel(model)
402
403        pass # debug anchor
404
405    def onFit(self):
406        """
407        Perform fitting on the current data
408        """
409        fitter = Fit()
410
411        # Data going in
412        data = self.logic.data
413        model = self.kernel_module
414        qmin = self.q_range_min
415        qmax = self.q_range_max
416        params_to_fit = self.parameters_to_fit
417
418        # Potential weights added directly to data
419        self.addWeightingToData(data)
420
421        # Potential smearing added
422        # Remember that smearing_min/max can be None ->
423        # deal with it until Python gets discriminated unions
424        smearing, accuracy, smearing_min, smearing_max = self.smearing_widget.state()
425
426        # These should be updating somehow?
427        fit_id = 0
428        constraints = []
429        smearer = None
430        page_id = [210]
431        handler = None
432        batch_inputs = {}
433        batch_outputs = {}
434        list_page_id = [page_id]
435        #---------------------------------
436
437        # Parameterize the fitter
438        fitter.set_model(model, fit_id, params_to_fit, data=data,
439                         constraints=constraints)
440        fitter.set_data(data=data, id=fit_id, smearer=smearer, qmin=qmin,
441                        qmax=qmax)
442        fitter.select_problem_for_fit(id=fit_id, value=1)
443
444        fitter.fitter_id = page_id
445
446        # Create the fitting thread, based on the fitter
447        calc_fit = FitThread(handler=handler,
448                             fn=[fitter],
449                             batch_inputs=batch_inputs,
450                             batch_outputs=batch_outputs,
451                             page_id=list_page_id,
452                             updatefn=self.updateFit,
453                             completefn=None)
454
455        # start the trhrhread
456        calc_thread = threads.deferToThread(calc_fit.compute)
457        calc_thread.addCallback(self.fitComplete)
458
459        #disable the Fit button
460        self.cmdFit.setText('Calculating...')
461        self.communicate.statusBarUpdateSignal.emit('Fitting started...')
462        self.cmdFit.setEnabled(False)
463
464    def updateFit(self):
465        """
466        """
467        print "UPDATE FIT"
468        pass
469
470    def fitComplete(self, result):
471        """
472        Receive and display fitting results
473        "result" is a tuple of actual result list and the fit time in seconds
474        """
475        #re-enable the Fit button
476        self.cmdFit.setText("Fit")
477        self.cmdFit.setEnabled(True)
478
479        assert result is not None
480
481        res_list = result[0]
482        res = res_list[0]
483        if res.fitness is None or \
484            not np.isfinite(res.fitness) or \
485            np.any(res.pvec == None) or \
486            not np.all(np.isfinite(res.pvec)):
487            msg = "Fitting did not converge!!!"
488            self.communicate.statusBarUpdateSignal.emit(msg)
489            logging.error(msg)
490            return
491
492        elapsed = result[1]
493        msg = "Fitting completed successfully in: %s s.\n" % GuiUtils.formatNumber(elapsed)
494        self.communicate.statusBarUpdateSignal.emit(msg)
495
496        fitness = res.fitness
497        param_list = res.param_list
498        param_values = res.pvec
499        param_stderr = res.stderr
500        params_and_errors = zip(param_values, param_stderr)
501        param_dict = dict(izip(param_list, params_and_errors))
502
503        # Dictionary of fitted parameter: value, error
504        # e.g. param_dic = {"sld":(1.703, 0.0034), "length":(33.455, -0.0983)}
505        self.updateModelFromList(param_dict)
506
507        # update charts
508        self.onPlot()
509
510        # Read only value - we can get away by just printing it here
511        chi2_repr = GuiUtils.formatNumber(fitness, high=True)
512        self.lblChi2Value.setText(chi2_repr)
513
514    def iterateOverModel(self, func):
515        """
516        Take func and throw it inside the model row loop
517        """
518        #assert isinstance(func, function)
519        for row_i in xrange(self._model_model.rowCount()):
520            func(row_i)
521
522    def updateModelFromList(self, param_dict):
523        """
524        Update the model with new parameters, create the errors column
525        """
526        assert isinstance(param_dict, dict)
527        if not dict:
528            return
529
530        def updateFittedValues(row_i):
531            # Utility function for main model update
532            # internal so can use closure for param_dict
533            param_name = str(self._model_model.item(row_i, 0).text())
534            if param_name not in param_dict.keys():
535                return
536            # modify the param value
537            param_repr = GuiUtils.formatNumber(param_dict[param_name][0], high=True)
538            self._model_model.item(row_i, 1).setText(param_repr)
539            if self.has_error_column:
540                error_repr = GuiUtils.formatNumber(param_dict[param_name][1], high=True)
541                self._model_model.item(row_i, 2).setText(error_repr)
542
543        def createErrorColumn(row_i):
544            # Utility function for error column update
545            item = QtGui.QStandardItem()
546            for param_name in param_dict.keys():
547                if str(self._model_model.item(row_i, 0).text()) != param_name:
548                    continue
549                error_repr = GuiUtils.formatNumber(param_dict[param_name][1], high=True)
550                item.setText(error_repr)
551            error_column.append(item)
552
553        self.iterateOverModel(updateFittedValues)
554
555        if self.has_error_column:
556            return
557
558        error_column = []
559        self.iterateOverModel(createErrorColumn)
560
561        # switch off reponse to model change
562        self._model_model.blockSignals(True)
563        self._model_model.insertColumn(2, error_column)
564        self._model_model.blockSignals(False)
565        FittingUtilities.addErrorHeadersToModel(self._model_model)
566        # Adjust the table cells width.
567        # TODO: find a way to dynamically adjust column width while resized expanding
568        self.lstParams.resizeColumnToContents(0)
569        self.lstParams.resizeColumnToContents(4)
570        self.lstParams.resizeColumnToContents(5)
571        self.lstParams.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Expanding)
572
573        self.has_error_column = True
574
575    def onPlot(self):
576        """
577        Plot the current set of data
578        """
579        # Regardless of previous state, this should now be `plot show` functionality only
580        self.cmdPlot.setText("Show Plot")
581        self.recalculatePlotData()
582        self.showPlot()
583
584    def recalculatePlotData(self):
585        """
586        Generate a new dataset for model
587        """
588        if not self.data_is_loaded:
589            self.createDefaultDataset()
590        self.calculateQGridForModel()
591
592    def showPlot(self):
593        """
594        Show the current plot in MPL
595        """
596        # Show the chart if ready
597        data_to_show = self.data if self.data_is_loaded else self.model_data
598        if data_to_show is not None:
599            self.communicate.plotRequestedSignal.emit([data_to_show])
600
601    def onOptionsUpdate(self):
602        """
603        Update local option values and replot
604        """
605        self.q_range_min, self.q_range_max, self.npts, self.log_points, self.weighting = \
606            self.options_widget.state()
607        # set Q range labels on the main tab
608        self.lblMinRangeDef.setText(str(self.q_range_min))
609        self.lblMaxRangeDef.setText(str(self.q_range_max))
610        self.recalculatePlotData()
611
612    def setDefaultStructureCombo(self):
613        """
614        Fill in the structure factors combo box with defaults
615        """
616        structure_factor_list = self.master_category_dict.pop(CATEGORY_STRUCTURE)
617        factors = [factor[0] for factor in structure_factor_list]
618        factors.insert(0, STRUCTURE_DEFAULT)
619        self.cbStructureFactor.clear()
620        self.cbStructureFactor.addItems(sorted(factors))
621
622    def createDefaultDataset(self):
623        """
624        Generate default Dataset 1D/2D for the given model
625        """
626        # Create default datasets if no data passed
627        if self.is2D:
628            qmax = self.q_range_max/np.sqrt(2)
629            qstep = self.npts
630            self.logic.createDefault2dData(qmax, qstep, self.tab_id)
631            return
632        elif self.log_points:
633            qmin = -10.0 if self.q_range_min < 1.e-10 else np.log10(self.q_range_min)
634            qmax =  10.0 if self.q_range_max > 1.e10 else np.log10(self.q_range_max)
635            interval = np.logspace(start=qmin, stop=qmax, num=self.npts, endpoint=True, base=10.0)
636        else:
637            interval = np.linspace(start=self.q_range_min, stop=self.q_range_max,
638                    num=self.npts, endpoint=True)
639        self.logic.createDefault1dData(interval, self.tab_id)
640
641    def readCategoryInfo(self):
642        """
643        Reads the categories in from file
644        """
645        self.master_category_dict = defaultdict(list)
646        self.by_model_dict = defaultdict(list)
647        self.model_enabled_dict = defaultdict(bool)
648
649        categorization_file = CategoryInstaller.get_user_file()
650        if not os.path.isfile(categorization_file):
651            categorization_file = CategoryInstaller.get_default_file()
652        with open(categorization_file, 'rb') as cat_file:
653            self.master_category_dict = json.load(cat_file)
654            self.regenerateModelDict()
655
656        # Load the model dict
657        models = load_standard_models()
658        for model in models:
659            self.models[model.name] = model
660
661    def regenerateModelDict(self):
662        """
663        Regenerates self.by_model_dict which has each model name as the
664        key and the list of categories belonging to that model
665        along with the enabled mapping
666        """
667        self.by_model_dict = defaultdict(list)
668        for category in self.master_category_dict:
669            for (model, enabled) in self.master_category_dict[category]:
670                self.by_model_dict[model].append(category)
671                self.model_enabled_dict[model] = enabled
672
673    def addBackgroundToModel(self, model):
674        """
675        Adds background parameter with default values to the model
676        """
677        assert isinstance(model, QtGui.QStandardItemModel)
678        checked_list = ['background', '0.001', '-inf', 'inf', '1/cm']
679        FittingUtilities.addCheckedListToModel(model, checked_list)
680
681    def addScaleToModel(self, model):
682        """
683        Adds scale parameter with default values to the model
684        """
685        assert isinstance(model, QtGui.QStandardItemModel)
686        checked_list = ['scale', '1.0', '0.0', 'inf', '']
687        FittingUtilities.addCheckedListToModel(model, checked_list)
688
689    def addWeightingToData(self, data):
690        """
691        Adds weighting contribution to fitting data
692        #"""
693        # Send original data for weighting
694        weight = get_weight(data=data, is2d=self.is2D, flag=self.weighting)
695        update_module = data.err_data if self.is2D else data.dy
696        update_module = weight
697
698    def updateQRange(self):
699        """
700        Updates Q Range display
701        """
702        if self.data_is_loaded:
703            self.q_range_min, self.q_range_max, self.npts = self.logic.computeDataRange()
704        # set Q range labels on the main tab
705        self.lblMinRangeDef.setText(str(self.q_range_min))
706        self.lblMaxRangeDef.setText(str(self.q_range_max))
707        # set Q range labels on the options tab
708        self.options_widget.updateQRange(self.q_range_min, self.q_range_max, self.npts)
709
710    def SASModelToQModel(self, model_name, structure_factor=None):
711        """
712        Setting model parameters into table based on selected category
713        """
714        # TODO - modify for structure factor-only choice
715
716        # Crete/overwrite model items
717        self._model_model.clear()
718
719        kernel_module = generate.load_kernel_module(model_name)
720        self.model_parameters = modelinfo.make_parameter_table(getattr(kernel_module, 'parameters', []))
721
722        # Instantiate the current sasmodel
723        self.kernel_module = self.models[model_name]()
724
725        # Explicitly add scale and background with default values
726        self.addScaleToModel(self._model_model)
727        self.addBackgroundToModel(self._model_model)
728
729        # Update the QModel
730        new_rows = FittingUtilities.addParametersToModel(self.model_parameters, self.is2D)
731        for row in new_rows:
732            self._model_model.appendRow(row)
733        # Update the counter used for multishell display
734        self._last_model_row = self._model_model.rowCount()
735
736        FittingUtilities.addHeadersToModel(self._model_model)
737
738        # Add structure factor
739        if structure_factor is not None and structure_factor != "None":
740            structure_module = generate.load_kernel_module(structure_factor)
741            structure_parameters = modelinfo.make_parameter_table(getattr(structure_module, 'parameters', []))
742            new_rows = FittingUtilities.addSimpleParametersToModel(structure_parameters, self.is2D)
743            for row in new_rows:
744                self._model_model.appendRow(row)
745            # Update the counter used for multishell display
746            self._last_model_row = self._model_model.rowCount()
747        else:
748            self.addStructureFactor()
749
750        # Multishell models need additional treatment
751        self.addExtraShells()
752
753        # Add polydispersity to the model
754        self.setPolyModel()
755        # Add magnetic parameters to the model
756        self.setMagneticModel()
757
758        # Adjust the table cells width
759        self.lstParams.resizeColumnToContents(0)
760        self.lstParams.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Expanding)
761
762        # Now we claim the model has been loaded
763        self.model_is_loaded = True
764
765        # Update Q Ranges
766        self.updateQRange()
767
768    def updateParamsFromModel(self, item):
769        """
770        Callback method for updating the sasmodel parameters with the GUI values
771        """
772        model_column = item.column()
773
774        if model_column == 0:
775            self.checkboxSelected(item)
776            return
777
778        model_row = item.row()
779        name_index = self._model_model.index(model_row, 0)
780
781        # Extract changed value. Assumes proper validation by QValidator/Delegate
782        value = float(item.text())
783        parameter_name = str(self._model_model.data(name_index).toPyObject()) # sld, background etc.
784        property_name = str(self._model_model.headerData(1, model_column).toPyObject()) # Value, min, max, etc.
785
786        self.kernel_module.params[parameter_name] = value
787
788        # min/max to be changed in self.kernel_module.details[parameter_name] = ['Ang', 0.0, inf]
789        # magnetic params in self.kernel_module.details['M0:parameter_name'] = value
790        # multishell params in self.kernel_module.details[??] = value
791
792        # Force the chart update when actual parameters changed
793        if model_column == 1:
794            self.recalculatePlotData()
795
796    def checkboxSelected(self, item):
797        # Assure we're dealing with checkboxes
798        if not item.isCheckable():
799            return
800        status = item.checkState()
801
802        def isChecked(row):
803            return self._model_model.item(row, 0).checkState() == QtCore.Qt.Checked
804
805        def isCheckable(row):
806            return self._model_model.item(row, 0).isCheckable()
807
808        # If multiple rows selected - toggle all of them, filtering uncheckable
809        rows = [s.row() for s in self.lstParams.selectionModel().selectedRows() if isCheckable(s.row())]
810
811        # Switch off signaling from the model to avoid recursion
812        self._model_model.blockSignals(True)
813        # Convert to proper indices and set requested enablement
814        items = [self._model_model.item(row, 0).setCheckState(status) for row in rows]
815        self._model_model.blockSignals(False)
816
817        # update the list of parameters to fit
818        self.parameters_to_fit = [str(self._model_model.item(row_index, 0).text())
819                                  for row_index in xrange(self._model_model.rowCount())
820                                  if isChecked(row_index)]
821
822    def nameForFittedData(self, name):
823        """
824        Generate name for the current fit
825        """
826        if self.is2D:
827            name += "2d"
828        name = "M%i [%s]" % (self.tab_id, name)
829        return name
830
831    def createNewIndex(self, fitted_data):
832        """
833        Create a model or theory index with passed Data1D/Data2D
834        """
835        if self.data_is_loaded:
836            if not fitted_data.name:
837                name = self.nameForFittedData(self.data.filename)
838                fitted_data.title = name
839                fitted_data.name = name
840                fitted_data.filename = name
841                fitted_data.symbol = "Line"
842            self.updateModelIndex(fitted_data)
843        else:
844            name = self.nameForFittedData(self.kernel_module.name)
845            fitted_data.title = name
846            fitted_data.name = name
847            fitted_data.filename = name
848            fitted_data.symbol = "Line"
849            self.createTheoryIndex(fitted_data)
850
851    def updateModelIndex(self, fitted_data):
852        """
853        Update a QStandardModelIndex containing model data
854        """
855        if fitted_data.name is None:
856            name = self.nameForFittedData(self.logic.data.filename)
857            fitted_data.title = name
858            fitted_data.name = name
859        else:
860            name = fitted_data.name
861        # Make this a line if no other defined
862        if hasattr(fitted_data, 'symbol') and fitted_data.symbol is None:
863            fitted_data.symbol = 'Line'
864        # Notify the GUI manager so it can update the main model in DataExplorer
865        GuiUtils.updateModelItemWithPlot(self._index, QtCore.QVariant(fitted_data), name)
866
867    def createTheoryIndex(self, fitted_data):
868        """
869        Create a QStandardModelIndex containing model data
870        """
871        if fitted_data.name is None:
872            name = self.nameForFittedData(self.kernel_module.name)
873            fitted_data.title = name
874            fitted_data.name = name
875            fitted_data.filename = name
876        else:
877            name = fitted_data.name
878        # Notify the GUI manager so it can create the theory model in DataExplorer
879        new_item = GuiUtils.createModelItemWithPlot(QtCore.QVariant(fitted_data), name=name)
880        self.communicate.updateTheoryFromPerspectiveSignal.emit(new_item)
881
882    def methodCalculateForData(self):
883        '''return the method for data calculation'''
884        return Calc1D if isinstance(self.data, Data1D) else Calc2D
885
886    def methodCompleteForData(self):
887        '''return the method for result parsin on calc complete '''
888        return self.complete1D if isinstance(self.data, Data1D) else self.complete2D
889
890    def calculateQGridForModel(self):
891        """
892        Prepare the fitting data object, based on current ModelModel
893        """
894        if self.kernel_module is None:
895            return
896        # Awful API to a backend method.
897        method = self.methodCalculateForData()(data=self.data,
898                              model=self.kernel_module,
899                              page_id=0,
900                              qmin=self.q_range_min,
901                              qmax=self.q_range_max,
902                              smearer=None,
903                              state=None,
904                              weight=None,
905                              fid=None,
906                              toggle_mode_on=False,
907                              completefn=None,
908                              update_chisqr=True,
909                              exception_handler=self.calcException,
910                              source=None)
911
912        calc_thread = threads.deferToThread(method.compute)
913        calc_thread.addCallback(self.methodCompleteForData())
914
915    def complete1D(self, return_data):
916        """
917        Plot the current 1D data
918        """
919        fitted_data = self.logic.new1DPlot(return_data, self.tab_id)
920        self.calculateResiduals(fitted_data)
921        self.model_data = fitted_data
922
923    def complete2D(self, return_data):
924        """
925        Plot the current 2D data
926        """
927        fitted_data = self.logic.new2DPlot(return_data)
928        self.calculateResiduals(fitted_data)
929        self.model_data = fitted_data
930
931    def calculateResiduals(self, fitted_data):
932        """
933        Calculate and print Chi2 and display chart of residuals
934        """
935        # Create a new index for holding data
936        fitted_data.symbol = "Line"
937        self.createNewIndex(fitted_data)
938        # Calculate difference between return_data and logic.data
939        chi2 = FittingUtilities.calculateChi2(fitted_data, self.logic.data)
940        # Update the control
941        chi2_repr = "---" if chi2 is None else GuiUtils.formatNumber(chi2, high=True)
942        self.lblChi2Value.setText(chi2_repr)
943
944        self.communicate.plotUpdateSignal.emit([fitted_data])
945
946        # Plot residuals if actual data
947        if self.data_is_loaded:
948            residuals_plot = FittingUtilities.plotResiduals(self.data, fitted_data)
949            residuals_plot.id = "Residual " + residuals_plot.id
950            self.createNewIndex(residuals_plot)
951            self.communicate.plotUpdateSignal.emit([residuals_plot])
952
953    def calcException(self, etype, value, tb):
954        """
955        Something horrible happened in the deferred.
956        """
957        logging.error("".join(traceback.format_exception(etype, value, tb)))
958
959    def setTableProperties(self, table):
960        """
961        Setting table properties
962        """
963        # Table properties
964        table.verticalHeader().setVisible(False)
965        table.setAlternatingRowColors(True)
966        table.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Expanding)
967        table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
968        table.resizeColumnsToContents()
969
970        # Header
971        header = table.horizontalHeader()
972        header.setResizeMode(QtGui.QHeaderView.ResizeToContents)
973
974        header.ResizeMode(QtGui.QHeaderView.Interactive)
975        # Resize column 0 and 6 to content
976        header.setResizeMode(0, QtGui.QHeaderView.ResizeToContents)
977        header.setResizeMode(6, QtGui.QHeaderView.ResizeToContents)
978
979    def setPolyModel(self):
980        """
981        Set polydispersity values
982        """
983        if not self.model_parameters:
984            return
985        self._poly_model.clear()
986        for row, param in enumerate(self.model_parameters.form_volume_parameters):
987            # Counters should not be included
988            if not param.polydisperse:
989                continue
990
991            # Potential multishell params
992            checked_list = ["Distribution of "+param.name, str(param.default),
993                            str(param.limits[0]), str(param.limits[1]),
994                            "35", "3", ""]
995            FittingUtilities.addCheckedListToModel(self._poly_model, checked_list)
996
997            #TODO: Need to find cleaner way to input functions
998            func = QtGui.QComboBox()
999            func.addItems(['rectangle', 'array', 'lognormal', 'gaussian', 'schulz',])
1000            func_index = self.lstPoly.model().index(row, 6)
1001            self.lstPoly.setIndexWidget(func_index, func)
1002
1003        FittingUtilities.addPolyHeadersToModel(self._poly_model)
1004
1005    def setMagneticModel(self):
1006        """
1007        Set magnetism values on model
1008        """
1009        if not self.model_parameters:
1010            return
1011        self._magnet_model.clear()
1012        for param in self.model_parameters.call_parameters:
1013            if param.type != "magnetic":
1014                continue
1015            checked_list = [param.name,
1016                            str(param.default),
1017                            str(param.limits[0]),
1018                            str(param.limits[1]),
1019                            param.units]
1020            FittingUtilities.addCheckedListToModel(self._magnet_model, checked_list)
1021
1022        FittingUtilities.addHeadersToModel(self._magnet_model)
1023
1024    def addStructureFactor(self):
1025        """
1026        Add structure factors to the list of parameters
1027        """
1028        if self.kernel_module.is_form_factor:
1029            self.enableStructureCombo()
1030        else:
1031            self.disableStructureCombo()
1032
1033    def addExtraShells(self):
1034        """
1035        Add a combobox for multiple shell display
1036        """
1037        param_name, param_length = FittingUtilities.getMultiplicity(self.model_parameters)
1038
1039        if param_length == 0:
1040            return
1041
1042        # cell 1: variable name
1043        item1 = QtGui.QStandardItem(param_name)
1044
1045        func = QtGui.QComboBox()
1046        # Available range of shells displayed in the combobox
1047        func.addItems([str(i) for i in xrange(param_length+1)])
1048
1049        # Respond to index change
1050        func.currentIndexChanged.connect(self.modifyShellsInList)
1051
1052        # cell 2: combobox
1053        item2 = QtGui.QStandardItem()
1054        self._model_model.appendRow([item1, item2])
1055
1056        # Beautify the row:  span columns 2-4
1057        shell_row = self._model_model.rowCount()
1058        shell_index = self._model_model.index(shell_row-1, 1)
1059
1060        self.lstParams.setIndexWidget(shell_index, func)
1061        self._last_model_row = self._model_model.rowCount()
1062
1063        # Set the index to the state-kept value
1064        func.setCurrentIndex(self.current_shell_displayed
1065                             if self.current_shell_displayed < func.count() else 0)
1066
1067    def modifyShellsInList(self, index):
1068        """
1069        Add/remove additional multishell parameters
1070        """
1071        # Find row location of the combobox
1072        last_row = self._last_model_row
1073        remove_rows = self._model_model.rowCount() - last_row
1074
1075        if remove_rows > 1:
1076            self._model_model.removeRows(last_row, remove_rows)
1077
1078        FittingUtilities.addShellsToModel(self.model_parameters, self._model_model, index)
1079        self.current_shell_displayed = index
1080
Note: See TracBrowser for help on using the repository browser.