source: sasview/src/sas/qtgui/Perspectives/Inversion/InversionPerspective.py @ 318b353e

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 318b353e was 318b353e, checked in by krzywon, 6 years ago

Automatically plot P(r) fits when calculated and small tweaks.

  • Property mode set to 100644
File size: 27.1 KB
Line 
1import sys
2import logging
3import pylab
4import numpy as np
5
6from PyQt5 import QtGui, QtCore, QtWidgets
7
8# sas-global
9import sas.qtgui.Utilities.GuiUtils as GuiUtils
10
11# pr inversion GUI elements
12from .InversionUtils import WIDGETS
13from .UI.TabbedInversionUI import Ui_PrInversion
14from .InversionLogic import InversionLogic
15
16# pr inversion calculation elements
17from sas.sascalc.pr.invertor import Invertor
18
19# Batch calculation display
20from sas.qtgui.Utilities.GridPanel import BatchInversionOutputPanel
21
22
23def is_float(value):
24    """Converts text input values to floats. Empty strings throw ValueError"""
25    try:
26        return float(value)
27    except ValueError:
28        return 0.0
29
30
31NUMBER_OF_TERMS = 10
32REGULARIZATION = 0.0001
33BACKGROUND_INPUT = 0.0
34MAX_DIST = 140.0
35DICT_KEYS = ["Calculator", "PrPlot", "DataPlot"]
36
37
38# TODO: Update help with batch capabilities
39class InversionWindow(QtWidgets.QDialog, Ui_PrInversion):
40    """
41    The main window for the P(r) Inversion perspective.
42    """
43
44    name = "Inversion"
45    estimateSignal = QtCore.pyqtSignal(tuple)
46    estimateNTSignal = QtCore.pyqtSignal(tuple)
47    calculateSignal = QtCore.pyqtSignal(tuple)
48
49    def __init__(self, parent=None, data=None):
50        super(InversionWindow, self).__init__()
51        self.setupUi(self)
52
53        self.setWindowTitle("P(r) Inversion Perspective")
54
55        self._manager = parent
56        self.communicate = parent.communicator()
57        self.communicate.dataDeletedSignal.connect(self.removeData)
58
59        self.logic = InversionLogic()
60
61        # The window should not close
62        self._allow_close = False
63
64        # Visible data set items
65        # current QStandardItem showing on the panel
66        self._data = None
67        # Reference to Dmax window for self._data
68        self.dmaxWindow = None
69        # p(r) calculator for self._data
70        self._calculator = Invertor()
71        # Default to background estimate
72        self._calculator.est_bck = True
73        # plots of self._data
74        self.pr_plot = None
75        self.data_plot = None
76        # suggested nTerms
77        self.nTermsSuggested = NUMBER_OF_TERMS
78
79        # Calculation threads used by all data items
80        self.waitForEach = False
81        self.calc_thread = None
82        self.estimation_thread = None
83        self.estimation_thread_nt = None
84
85        # Mapping for all data items
86        # list mapping data to all parameters
87        self._data_list = {}
88        if not isinstance(data, list):
89            data_list = [data]
90        if data is not None:
91            for datum in data_list:
92                self.updateDataList(datum)
93
94        self.enableButtons()
95
96        self.model = QtGui.QStandardItemModel(self)
97        self.mapper = QtWidgets.QDataWidgetMapper(self)
98
99        self.grid_window = None
100
101        # Add validators
102        self.setupValidators()
103        # Link user interactions with methods
104        self.setupLinks()
105        # Set values
106        self.setupModel()
107        # Set up the Widget Map
108        self.setupMapper()
109        # Set base window state
110        self.setupWindow()
111
112    ######################################################################
113    # Base Perspective Class Definitions
114
115    def communicator(self):
116        return self.communicate
117
118    def allowBatch(self):
119        return True
120
121    def setClosable(self, value=True):
122        """
123        Allow outsiders close this widget
124        """
125        assert isinstance(value, bool)
126        self._allow_close = value
127
128    def closeEvent(self, event):
129        """
130        Overwrite QDialog close method to allow for custom widget close
131        """
132        if self._allow_close:
133            # reset the closability flag
134            self.setClosable(value=False)
135            # Tell the MdiArea to close the container
136            self.parentWidget().close()
137            event.accept()
138        else:
139            event.ignore()
140            # Maybe we should just minimize
141            self.setWindowState(QtCore.Qt.WindowMinimized)
142
143    ######################################################################
144    # Initialization routines
145
146    def setupLinks(self):
147        """Connect the use controls to their appropriate methods"""
148        self.dataList.currentIndexChanged.connect(self.displayChange)
149        self.calculateAllButton.clicked.connect(self.startThreadAll)
150        self.calculateThisButton.clicked.connect(self.startThread)
151        self.removeButton.clicked.connect(self.removeData)
152        self.helpButton.clicked.connect(self.help)
153        self.estimateBgd.toggled.connect(self.toggleBgd)
154        self.manualBgd.toggled.connect(self.toggleBgd)
155        self.regConstantSuggestionButton.clicked.connect(self.acceptAlpha)
156        self.noOfTermsSuggestionButton.clicked.connect(self.acceptNoTerms)
157        self.explorerButton.clicked.connect(self.openExplorerWindow)
158
159        self.backgroundInput.editingFinished.connect(
160            lambda: self.set_background(self.backgroundInput.text()))
161        self.minQInput.editingFinished.connect(
162            lambda: self._calculator.set_qmin(is_float(self.minQInput.text())))
163        self.regularizationConstantInput.editingFinished.connect(
164            lambda: self._calculator.set_alpha(is_float(self.regularizationConstantInput.text())))
165        self.maxDistanceInput.editingFinished.connect(
166            lambda: self._calculator.set_dmax(is_float(self.maxDistanceInput.text())))
167        self.maxQInput.editingFinished.connect(
168            lambda: self._calculator.set_qmax(is_float(self.maxQInput.text())))
169        self.slitHeightInput.editingFinished.connect(
170            lambda: self._calculator.set_slit_height(is_float(self.slitHeightInput.text())))
171        self.slitWidthInput.editingFinished.connect(
172            lambda: self._calculator.set_slit_width(is_float(self.slitHeightInput.text())))
173
174        self.model.itemChanged.connect(self.model_changed)
175        self.estimateNTSignal.connect(self._estimateNTUpdate)
176        self.estimateSignal.connect(self._estimateUpdate)
177        self.calculateSignal.connect(self._calculateUpdate)
178
179    def setupMapper(self):
180        # Set up the mapper.
181        self.mapper.setOrientation(QtCore.Qt.Vertical)
182        self.mapper.setModel(self.model)
183
184        # Filename
185        self.mapper.addMapping(self.dataList, WIDGETS.W_FILENAME)
186        # Background
187        self.mapper.addMapping(self.backgroundInput, WIDGETS.W_BACKGROUND_INPUT)
188        self.mapper.addMapping(self.estimateBgd, WIDGETS.W_ESTIMATE)
189        self.mapper.addMapping(self.manualBgd, WIDGETS.W_MANUAL_INPUT)
190
191        # Qmin/Qmax
192        self.mapper.addMapping(self.minQInput, WIDGETS.W_QMIN)
193        self.mapper.addMapping(self.maxQInput, WIDGETS.W_QMAX)
194
195        # Slit Parameter items
196        self.mapper.addMapping(self.slitWidthInput, WIDGETS.W_SLIT_WIDTH)
197        self.mapper.addMapping(self.slitHeightInput, WIDGETS.W_SLIT_HEIGHT)
198
199        # Parameter Items
200        self.mapper.addMapping(self.regularizationConstantInput, WIDGETS.W_REGULARIZATION)
201        self.mapper.addMapping(self.regConstantSuggestionButton, WIDGETS.W_REGULARIZATION_SUGGEST)
202        self.mapper.addMapping(self.explorerButton, WIDGETS.W_EXPLORE)
203        self.mapper.addMapping(self.maxDistanceInput, WIDGETS.W_MAX_DIST)
204        self.mapper.addMapping(self.noOfTermsInput, WIDGETS.W_NO_TERMS)
205        self.mapper.addMapping(self.noOfTermsSuggestionButton, WIDGETS.W_NO_TERMS_SUGGEST)
206
207        # Output
208        self.mapper.addMapping(self.rgValue, WIDGETS.W_RG)
209        self.mapper.addMapping(self.iQ0Value, WIDGETS.W_I_ZERO)
210        self.mapper.addMapping(self.backgroundValue, WIDGETS.W_BACKGROUND_OUTPUT)
211        self.mapper.addMapping(self.computationTimeValue, WIDGETS.W_COMP_TIME)
212        self.mapper.addMapping(self.chiDofValue, WIDGETS.W_CHI_SQUARED)
213        self.mapper.addMapping(self.oscillationValue, WIDGETS.W_OSCILLATION)
214        self.mapper.addMapping(self.posFractionValue, WIDGETS.W_POS_FRACTION)
215        self.mapper.addMapping(self.sigmaPosFractionValue, WIDGETS.W_SIGMA_POS_FRACTION)
216
217        # Main Buttons
218        self.mapper.addMapping(self.removeButton, WIDGETS.W_REMOVE)
219        self.mapper.addMapping(self.calculateAllButton, WIDGETS.W_CALCULATE_ALL)
220        self.mapper.addMapping(self.calculateThisButton, WIDGETS.W_CALCULATE_VISIBLE)
221        self.mapper.addMapping(self.helpButton, WIDGETS.W_HELP)
222
223        self.mapper.toFirst()
224
225    def setupModel(self):
226        """
227        Update boxes with initial values
228        """
229        item = QtGui.QStandardItem(str(BACKGROUND_INPUT))
230        self.model.setItem(WIDGETS.W_BACKGROUND_INPUT, item)
231        item = QtGui.QStandardItem("")
232        self.model.setItem(WIDGETS.W_QMIN, item)
233        item = QtGui.QStandardItem("")
234        self.model.setItem(WIDGETS.W_QMAX, item)
235        item = QtGui.QStandardItem("")
236        self.model.setItem(WIDGETS.W_SLIT_WIDTH, item)
237        item = QtGui.QStandardItem("")
238        self.model.setItem(WIDGETS.W_SLIT_HEIGHT, item)
239        item = QtGui.QStandardItem(str(NUMBER_OF_TERMS))
240        self.model.setItem(WIDGETS.W_NO_TERMS, item)
241        item = QtGui.QStandardItem(str(REGULARIZATION))
242        self.model.setItem(WIDGETS.W_REGULARIZATION, item)
243        item = QtGui.QStandardItem(str(MAX_DIST))
244        self.model.setItem(WIDGETS.W_MAX_DIST, item)
245        item = QtGui.QStandardItem("")
246        self.model.setItem(WIDGETS.W_RG, item)
247        item = QtGui.QStandardItem("")
248        self.model.setItem(WIDGETS.W_I_ZERO, item)
249        item = QtGui.QStandardItem("")
250        self.model.setItem(WIDGETS.W_BACKGROUND_OUTPUT, item)
251        item = QtGui.QStandardItem("")
252        self.model.setItem(WIDGETS.W_COMP_TIME, item)
253        item = QtGui.QStandardItem("")
254        self.model.setItem(WIDGETS.W_CHI_SQUARED, item)
255        item = QtGui.QStandardItem("")
256        self.model.setItem(WIDGETS.W_OSCILLATION, item)
257        item = QtGui.QStandardItem("")
258        self.model.setItem(WIDGETS.W_POS_FRACTION, item)
259        item = QtGui.QStandardItem("")
260        self.model.setItem(WIDGETS.W_SIGMA_POS_FRACTION, item)
261
262    def setupWindow(self):
263        """Initialize base window state on init"""
264        self.enableButtons()
265        self.estimateBgd.setChecked(True)
266
267    def setupValidators(self):
268        """Apply validators to editable line edits"""
269        self.noOfTermsInput.setValidator(QtGui.QIntValidator())
270        self.regularizationConstantInput.setValidator(GuiUtils.DoubleValidator())
271        self.maxDistanceInput.setValidator(GuiUtils.DoubleValidator())
272        self.minQInput.setValidator(GuiUtils.DoubleValidator())
273        self.maxQInput.setValidator(GuiUtils.DoubleValidator())
274        self.slitHeightInput.setValidator(GuiUtils.DoubleValidator())
275        self.slitWidthInput.setValidator(GuiUtils.DoubleValidator())
276
277    ######################################################################
278    # Methods for updating GUI
279
280    def enableButtons(self):
281        """
282        Enable buttons when data is present, else disable them
283        """
284        self.calculateAllButton.setEnabled(len(self._data_list) > 1)
285        self.calculateThisButton.setEnabled(self.logic.data_is_loaded)
286        self.removeButton.setEnabled(self.logic.data_is_loaded)
287        self.explorerButton.setEnabled(self.logic.data_is_loaded)
288        self.regConstantSuggestionButton.setEnabled(
289            self._calculator.suggested_alpha != self._calculator.alpha)
290        self.noOfTermsSuggestionButton.setEnabled(
291            self._calculator.nfunc != self.nTermsSuggested)
292
293    def populateDataComboBox(self, filename, data_ref):
294        """
295        Append a new file name to the data combobox
296        :param filename: data filename
297        :param data_ref: QStandardItem reference for data set to be added
298        """
299        self.dataList.addItem(filename, data_ref)
300
301    def acceptNoTerms(self):
302        """Send estimated no of terms to input"""
303        self.model.setItem(WIDGETS.W_NO_TERMS, QtGui.QStandardItem(
304            self.noOfTermsSuggestionButton.text()))
305
306    def acceptAlpha(self):
307        """Send estimated alpha to input"""
308        self.model.setItem(WIDGETS.W_REGULARIZATION, QtGui.QStandardItem(
309            self.regConstantSuggestionButton.text()))
310
311    def displayChange(self, data_index=0):
312        """Switch to another item in the data list"""
313        self.updateDataList(self._data)
314        self.setCurrentData(self.dataList.itemData(data_index))
315
316    ######################################################################
317    # GUI Interaction Events
318
319    def update_calculator(self):
320        """Update all p(r) params"""
321        self._calculator.set_x(self.logic.data.x)
322        self._calculator.set_y(self.logic.data.y)
323        self._calculator.set_err(self.logic.data.dy)
324        self.set_background(self.backgroundInput.text())
325
326    def set_background(self, value):
327        self._calculator.background = is_float(value)
328
329    def model_changed(self):
330        """Update the values when user makes changes"""
331        if not self.mapper:
332            msg = "Unable to update P{r}. The connection between the main GUI "
333            msg += "and P(r) was severed. Attempting to restart P(r)."
334            logging.warning(msg)
335            self.setClosable(True)
336            self.close()
337            InversionWindow.__init__(self.parent(), list(self._data_list.keys()))
338            exit(0)
339        if self.dmaxWindow is not None:
340            self.dmaxWindow.nfunc = self.getNFunc()
341            self.dmaxWindow.pr_state = self._calculator
342        self.mapper.toLast()
343
344    def help(self):
345        """
346        Open the P(r) Inversion help browser
347        """
348        tree_location = "/user/sasgui/perspectives/pr/pr_help.html"
349
350        # Actual file anchor will depend on the combo box index
351        # Note that we can be clusmy here, since bad current_fitter_id
352        # will just make the page displayed from the top
353        self._manager.showHelp(tree_location)
354
355    def toggleBgd(self):
356        """
357        Toggle the background between manual and estimated
358        """
359        if self.estimateBgd.isChecked():
360            self.manualBgd.setChecked(False)
361            self.backgroundInput.setEnabled(False)
362            self._calculator.set_est_bck = True
363        elif self.manualBgd.isChecked():
364            self.estimateBgd.setChecked(False)
365            self.backgroundInput.setEnabled(True)
366            self._calculator.set_est_bck = False
367        else:
368            pass
369
370    def openExplorerWindow(self):
371        """
372        Open the Explorer window to see correlations between params and results
373        """
374        from .DMaxExplorerWidget import DmaxWindow
375        self.dmaxWindow = DmaxWindow(self._calculator, self.getNFunc(), self)
376        self.dmaxWindow.show()
377
378    def showBatchOutput(self, output_data):
379        """
380        Display the batch output in tabular form
381        :param output_data: Dictionary mapping filename -> P(r) instance
382        """
383        if self.grid_window is None:
384            self.grid_window = BatchInversionOutputPanel(
385                parent=self, output_data=output_data)
386        else:
387            self.grid_window.setupTable(output_data)
388        self.grid_window.show()
389
390    ######################################################################
391    # Response Actions
392
393    def setData(self, data_item=None, is_batch=False):
394        """
395        Assign new data set(s) to the P(r) perspective
396        Obtain a QStandardItem object and parse it to get Data1D/2D
397        Pass it over to the calculator
398        """
399        assert data_item is not None
400
401        if not isinstance(data_item, list):
402            msg = "Incorrect type passed to the P(r) Perspective"
403            raise AttributeError(msg)
404
405        for data in data_item:
406            if data in self._data_list.keys():
407                # Don't add data if it's already in
408                continue
409            # Create initial internal mappings
410            self.logic.data = GuiUtils.dataFromItem(data)
411            # Estimate q range
412            qmin, qmax = self.logic.computeDataRange()
413            self._calculator.set_qmin(qmin)
414            self._calculator.set_qmax(qmax)
415            self.updateDataList(data)
416            self.populateDataComboBox(self.logic.data.filename, data)
417        self.dataList.setCurrentIndex(len(self.dataList) - 1)
418        self.setCurrentData(data)
419
420    def updateDataList(self, dataRef):
421        """Save the current data state of the window into self._data_list"""
422        if dataRef is None:
423            return
424        self._data_list[dataRef] = {
425            DICT_KEYS[0]: self._calculator,
426            DICT_KEYS[1]: self.pr_plot,
427            DICT_KEYS[2]: self.data_plot
428        }
429
430    def getNFunc(self):
431        """Get the n_func value from the GUI object"""
432        try:
433            nfunc = int(self.noOfTermsInput.text())
434        except ValueError:
435            logging.error("Incorrect number of terms specified: %s"
436                          %self.noOfTermsInput.text())
437            self.noOfTermsInput.setText(str(NUMBER_OF_TERMS))
438            nfunc = NUMBER_OF_TERMS
439        return nfunc
440
441    def setCurrentData(self, data_ref):
442        """Get the data by reference and display as necessary"""
443        if data_ref is None:
444            return
445        if not isinstance(data_ref, QtGui.QStandardItem):
446            msg = "Incorrect type passed to the P(r) Perspective"
447            raise AttributeError(msg)
448        # Data references
449        self._data = data_ref
450        self.logic.data = GuiUtils.dataFromItem(data_ref)
451        self._calculator = self._data_list[data_ref].get(DICT_KEYS[0])
452        self.pr_plot = self._data_list[data_ref].get(DICT_KEYS[1])
453        self.data_plot = self._data_list[data_ref].get(DICT_KEYS[2])
454        self.performEstimate()
455
456    def updateGuiValues(self):
457        pr = self._calculator
458        out = self._calculator.out
459        cov = self._calculator.cov
460        elapsed = self._calculator.elapsed
461        alpha = self._calculator.suggested_alpha
462        self.model.setItem(WIDGETS.W_QMIN,
463                           QtGui.QStandardItem("{:.4g}".format(pr.get_qmin())))
464        self.model.setItem(WIDGETS.W_QMAX,
465                           QtGui.QStandardItem("{:.4g}".format(pr.get_qmax())))
466        self.model.setItem(WIDGETS.W_BACKGROUND_INPUT,
467                           QtGui.QStandardItem("{:.3g}".format(pr.background)))
468        self.model.setItem(WIDGETS.W_BACKGROUND_OUTPUT,
469                           QtGui.QStandardItem("{:.3g}".format(pr.background)))
470        self.model.setItem(WIDGETS.W_COMP_TIME,
471                           QtGui.QStandardItem("{:.4g}".format(elapsed)))
472        self.regConstantSuggestionButton.setText("{:-3.2g}".format(alpha))
473        self.noOfTermsSuggestionButton.setText(
474            "{:n}".format(self.nTermsSuggested))
475        self.model.setItem(WIDGETS.W_COMP_TIME,
476                           QtGui.QStandardItem("{:.2g}".format(elapsed)))
477
478        if isinstance(pr.chi2, np.ndarray):
479            self.model.setItem(WIDGETS.W_CHI_SQUARED,
480                               QtGui.QStandardItem("{:.3g}".format(pr.chi2[0])))
481        if out is not None:
482            self.model.setItem(WIDGETS.W_RG,
483                               QtGui.QStandardItem("{:.3g}".format(pr.rg(out))))
484            self.model.setItem(WIDGETS.W_I_ZERO,
485                               QtGui.QStandardItem(
486                                   "{:.3g}".format(pr.iq0(out))))
487            self.model.setItem(WIDGETS.W_OSCILLATION, QtGui.QStandardItem(
488                "{:.3g}".format(pr.oscillations(out))))
489            self.model.setItem(WIDGETS.W_POS_FRACTION, QtGui.QStandardItem(
490                "{:.3g}".format(pr.get_positive(out))))
491            if cov is not None:
492                self.model.setItem(WIDGETS.W_SIGMA_POS_FRACTION,
493                                   QtGui.QStandardItem(
494                                       "{:.3g}".format(
495                                           pr.get_pos_err(out, cov))))
496        self.enableButtons()
497
498    def removeData(self, data_list=None):
499        """Remove the existing data reference from the P(r) Persepective"""
500        if self.dmaxWindow is not None:
501            self.dmaxWindow.close()
502            self.dmaxWindow = None
503        if not data_list:
504            data_list = [self._data]
505        for data in data_list:
506            self._data_list.pop(data)
507        self._data = None
508        for index in range(0, len(self.dataList)):
509            if self.dataList.itemData(index) in data_list:
510                self.dataList.removeItem(index)
511        # Last file removed
512        if len(self._data_list) == 0:
513            self._data = None
514            self.pr_plot = None
515            self.data_plot = None
516            self._calculator = Invertor()
517            self.logic.data = None
518            self.nTermsSuggested = NUMBER_OF_TERMS
519            self.noOfTermsSuggestionButton.setText("{:n}".format(
520                self.nTermsSuggested))
521            self.regConstantSuggestionButton.setText("{:-3.2g}".format(
522                REGULARIZATION))
523            self.updateGuiValues()
524            self.setupModel()
525        else:
526            self.dataList.setCurrentIndex(0)
527            self.updateGuiValues()
528
529    ######################################################################
530    # Thread Creators
531    def startThreadAll(self):
532        self.waitForEach = True
533        output = {}
534        for data_ref in self._data_list.keys():
535            self.setCurrentData(data_ref)
536            self.performEstimate()
537            self.performEstimateNT()
538            self.acceptAlpha()
539            self.acceptNoTerms()
540            self.startThread()
541            output[self.logic.data.filename] = self._calculator
542        self.waitForEach = False
543        self.showBatchOutput(output)
544
545    def startThread(self):
546        """
547            Start a calculation thread
548        """
549        from .Thread import CalcPr
550
551        # Set data before running the calculations
552        self.update_calculator()
553
554        # If a thread is already started, stop it
555        if self.calc_thread is not None and self.calc_thread.isrunning():
556            self.calc_thread.stop()
557        pr = self._calculator.clone()
558        nfunc = self.getNFunc()
559        self.calc_thread = CalcPr(pr, nfunc,
560                                  error_func=self._threadError,
561                                  completefn=self._calculateCompleted,
562                                  updatefn=None)
563        self.calc_thread.queue()
564        self.calc_thread.ready(2.5)
565        if self.waitForEach:
566            if self.calc_thread.isrunning():
567                self.calc_thread.update()
568
569    def performEstimateNT(self):
570        """
571        Perform parameter estimation
572        """
573        from .Thread import EstimateNT
574
575        self.update_calculator()
576
577        # If a thread is already started, stop it
578        if (self.estimation_thread_nt is not None and
579                self.estimation_thread_nt.isrunning()):
580            self.estimation_thread_nt.stop()
581        pr = self._calculator.clone()
582        # Skip the slit settings for the estimation
583        # It slows down the application and it doesn't change the estimates
584        pr.slit_height = 0.0
585        pr.slit_width = 0.0
586        nfunc = self.getNFunc()
587
588        self.estimation_thread_nt = EstimateNT(pr, nfunc,
589                                            error_func=self._threadError,
590                                            completefn=self._estimateNTCompleted,
591                                            updatefn=None)
592        self.estimation_thread_nt.queue()
593        self.estimation_thread_nt.ready(2.5)
594        if self.waitForEach:
595            if self.estimation_thread_nt.isrunning():
596                self.estimation_thread_nt.update()
597
598    def performEstimate(self):
599        """
600            Perform parameter estimation
601        """
602        from .Thread import EstimatePr
603
604        # If a thread is already started, stop it
605        if (self.estimation_thread is not None and
606                self.estimation_thread.isrunning()):
607            self.estimation_thread.stop()
608        self.estimation_thread = EstimatePr(self._calculator.clone(),
609                                            self.getNFunc(),
610                                            error_func=self._threadError,
611                                            completefn=self._estimateCompleted,
612                                            updatefn=None)
613        self.estimation_thread.queue()
614        self.estimation_thread.ready(2.5)
615        if self.waitForEach:
616            if self.estimation_thread.isrunning():
617                self.estimation_thread.update()
618
619    ######################################################################
620    # Thread Complete
621
622    def _estimateCompleted(self, alpha, message, elapsed):
623        ''' Send a signal to the main thread for model update'''
624        self.estimateSignal.emit((alpha, message, elapsed))
625
626    def _estimateUpdate(self, output_tuple):
627        """
628        Parameter estimation completed,
629        display the results to the user
630
631        :param alpha: estimated best alpha
632        :param elapsed: computation time
633        """
634        alpha, message, elapsed = output_tuple
635        if message:
636            logging.info(message)
637        if not self.waitForEach:
638            self.performEstimateNT()
639
640    def _estimateNTCompleted(self, nterms, alpha, message, elapsed):
641        ''' Send a signal to the main thread for model update'''
642        self.estimateNTSignal.emit((nterms, alpha, message, elapsed))
643
644    def _estimateNTUpdate(self, output_tuple):
645        """
646        Parameter estimation completed,
647        display the results to the user
648
649        :param alpha: estimated best alpha
650        :param nterms: estimated number of terms
651        :param elapsed: computation time
652        """
653        nterms, alpha, message, elapsed = output_tuple
654        self._calculator.elapsed = elapsed
655        self._calculator.suggested_alpha = alpha
656        self.nTermsSuggested = nterms
657        # Save useful info
658        self.updateGuiValues()
659        if message:
660            logging.info(message)
661
662    def _calculateCompleted(self, out, cov, pr, elapsed):
663        ''' Send a signal to the main thread for model update'''
664        self.calculateSignal.emit((out, cov, pr, elapsed))
665
666    def _calculateUpdate(self, output_tuple):
667        """
668        Method called with the results when the inversion is done
669
670        :param out: output coefficient for the base functions
671        :param cov: covariance matrix
672        :param pr: Invertor instance
673        :param elapsed: time spent computing
674        """
675        out, cov, pr, elapsed = output_tuple
676        # Save useful info
677        cov = np.ascontiguousarray(cov)
678        pr.cov = cov
679        pr.out = out
680        pr.elapsed = elapsed
681
682        # Save Pr invertor
683        self._calculator = pr
684
685        # Update P(r) and fit plots
686        self.pr_plot = self.logic.newPRPlot(out, self._calculator, cov)
687        self.pr_plot.filename = self.logic.data.filename
688        title = self.pr_plot.name
689        GuiUtils.updateModelItemWithPlot(self._data, self.pr_plot, title)
690        self.communicate.plotRequestedSignal.emit([self.pr_plot])
691        self.data_plot = self.logic.new1DPlot(out, self._calculator)
692        self.data_plot.filename = self.logic.data.filename
693        title = self.data_plot.name
694        GuiUtils.updateModelItemWithPlot(self._data, self.data_plot, title)
695        self.communicate.plotRequestedSignal.emit([self.data_plot])
696
697        # Udpate internals and GUI
698        self.updateDataList(self._data)
699        self.updateGuiValues()
700
701    def _threadError(self, error):
702        """
703            Call-back method for calculation errors
704        """
705        logging.warning(error)
Note: See TracBrowser for help on using the repository browser.