source: sasview/src/sas/qtgui/Perspectives/Inversion/InversionPerspective.py @ 8289ae3

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 8289ae3 was 304e42f, checked in by krzywon, 6 years ago

More work to update gui values.

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