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

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

More changes to P(r) remove to reset window to base state when no data left.

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