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

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

First vestiges of the batch inversion results panel built off of the batch fit panel.

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