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

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

Use communicator to delete data from Inversion perspective when deleted from data display.

  • Property mode set to 100644
File size: 26.9 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(self.logic.data_is_loaded)
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.pr_plot is not None:
340            title = self.pr_plot.name
341            GuiUtils.updateModelItemWithPlot(self._data, self.pr_plot, title)
342        if self.data_plot is not None:
343            title = self.data_plot.name
344            GuiUtils.updateModelItemWithPlot(self._data, self.data_plot, title)
345        if self.dmaxWindow is not None:
346            self.dmaxWindow.nfunc = self.getNFunc()
347            self.dmaxWindow.pr_state = self._calculator
348        self.mapper.toLast()
349
350    def help(self):
351        """
352        Open the P(r) Inversion help browser
353        """
354        tree_location = "/user/sasgui/perspectives/pr/pr_help.html"
355
356        # Actual file anchor will depend on the combo box index
357        # Note that we can be clusmy here, since bad current_fitter_id
358        # will just make the page displayed from the top
359        self._manager.showHelp(tree_location)
360
361    def toggleBgd(self):
362        """
363        Toggle the background between manual and estimated
364        """
365        if self.estimateBgd.isChecked():
366            self.manualBgd.setChecked(False)
367            self.backgroundInput.setEnabled(False)
368            self._calculator.set_est_bck = True
369        elif self.manualBgd.isChecked():
370            self.estimateBgd.setChecked(False)
371            self.backgroundInput.setEnabled(True)
372            self._calculator.set_est_bck = False
373        else:
374            pass
375
376    def openExplorerWindow(self):
377        """
378        Open the Explorer window to see correlations between params and results
379        """
380        from .DMaxExplorerWidget import DmaxWindow
381        self.dmaxWindow = DmaxWindow(self._calculator, self.getNFunc(), self)
382        self.dmaxWindow.show()
383
384    def showBatchOutput(self, output_data):
385        """
386        Display the batch output in tabular form
387        :param output_data: Dictionary mapping filename -> P(r) instance
388        """
389        if self.grid_window is None:
390            self.grid_window = BatchInversionOutputPanel(
391                parent=self, output_data=output_data)
392        else:
393            self.grid_window.setupTable(output_data)
394        self.grid_window.show()
395
396    ######################################################################
397    # Response Actions
398
399    def setData(self, data_item=None, is_batch=False):
400        """
401        Assign new data set(s) to the P(r) perspective
402        Obtain a QStandardItem object and parse it to get Data1D/2D
403        Pass it over to the calculator
404        """
405        assert data_item is not None
406
407        if not isinstance(data_item, list):
408            msg = "Incorrect type passed to the P(r) Perspective"
409            raise AttributeError(msg)
410
411        for data in data_item:
412            if data in self._data_list.keys():
413                # Don't add data if it's already in
414                continue
415            # Create initial internal mappings
416            self.logic.data = GuiUtils.dataFromItem(data)
417            # Estimate q range
418            qmin, qmax = self.logic.computeDataRange()
419            self._calculator.set_qmin(qmin)
420            self._calculator.set_qmax(qmax)
421            self.updateDataList(data)
422            self.populateDataComboBox(self.logic.data.filename, data)
423        self.dataList.setCurrentIndex(len(self.dataList) - 1)
424        self.setCurrentData(data)
425
426    def updateDataList(self, dataRef):
427        """Save the current data state of the window into self._data_list"""
428        if dataRef is None:
429            return
430        self._data_list[dataRef] = {
431            DICT_KEYS[0]: self._calculator,
432            DICT_KEYS[1]: self.pr_plot,
433            DICT_KEYS[2]: self.data_plot
434        }
435
436    def getNFunc(self):
437        """Get the n_func value from the GUI object"""
438        try:
439            nfunc = int(self.noOfTermsInput.text())
440        except ValueError:
441            logging.error("Incorrect number of terms specified: %s"
442                          %self.noOfTermsInput.text())
443            self.noOfTermsInput.setText(str(NUMBER_OF_TERMS))
444            nfunc = NUMBER_OF_TERMS
445        return nfunc
446
447    def setCurrentData(self, data_ref):
448        """Get the data by reference and display as necessary"""
449        if data_ref is None:
450            return
451        if not isinstance(data_ref, QtGui.QStandardItem):
452            msg = "Incorrect type passed to the P(r) Perspective"
453            raise AttributeError(msg)
454        # Data references
455        self._data = data_ref
456        self.logic.data = GuiUtils.dataFromItem(data_ref)
457        self._calculator = self._data_list[data_ref].get(DICT_KEYS[0])
458        self.pr_plot = self._data_list[data_ref].get(DICT_KEYS[1])
459        self.data_plot = self._data_list[data_ref].get(DICT_KEYS[2])
460        self.performEstimate()
461
462    def updateGuiValues(self):
463        pr = self._calculator
464        out = self._calculator.out
465        cov = self._calculator.cov
466        elapsed = self._calculator.elapsed
467        alpha = self._calculator.suggested_alpha
468        self.model.setItem(WIDGETS.W_QMIN,
469                           QtGui.QStandardItem("{:.4g}".format(pr.get_qmin())))
470        self.model.setItem(WIDGETS.W_QMAX,
471                           QtGui.QStandardItem("{:.4g}".format(pr.get_qmax())))
472        self.model.setItem(WIDGETS.W_BACKGROUND_INPUT,
473                           QtGui.QStandardItem("{:.3g}".format(pr.background)))
474        self.model.setItem(WIDGETS.W_BACKGROUND_OUTPUT,
475                           QtGui.QStandardItem("{:.3g}".format(pr.background)))
476        self.model.setItem(WIDGETS.W_COMP_TIME,
477                           QtGui.QStandardItem("{:.4g}".format(elapsed)))
478        self.regConstantSuggestionButton.setText("{:-3.2g}".format(alpha))
479        self.noOfTermsSuggestionButton.setText(
480            "{:n}".format(self.nTermsSuggested))
481        self.model.setItem(WIDGETS.W_COMP_TIME,
482                           QtGui.QStandardItem("{:.2g}".format(elapsed)))
483
484        if isinstance(pr.chi2, np.ndarray):
485            self.model.setItem(WIDGETS.W_CHI_SQUARED,
486                               QtGui.QStandardItem("{:.3g}".format(pr.chi2[0])))
487        if out is not None:
488            self.model.setItem(WIDGETS.W_RG,
489                               QtGui.QStandardItem("{:.3g}".format(pr.rg(out))))
490            self.model.setItem(WIDGETS.W_I_ZERO,
491                               QtGui.QStandardItem(
492                                   "{:.3g}".format(pr.iq0(out))))
493            self.model.setItem(WIDGETS.W_OSCILLATION, QtGui.QStandardItem(
494                "{:.3g}".format(pr.oscillations(out))))
495            self.model.setItem(WIDGETS.W_POS_FRACTION, QtGui.QStandardItem(
496                "{:.3g}".format(pr.get_positive(out))))
497            if cov is not None:
498                self.model.setItem(WIDGETS.W_SIGMA_POS_FRACTION,
499                                   QtGui.QStandardItem(
500                                       "{:.3g}".format(
501                                           pr.get_pos_err(out, cov))))
502        self.enableButtons()
503
504    def removeData(self, data_list=None):
505        """Remove the existing data reference from the P(r) Persepective"""
506        if self.dmaxWindow is not None:
507            self.dmaxWindow.close()
508            self.dmaxWindow = None
509        if not data_list:
510            data_list = [self._data]
511        for data in data_list:
512            self._data_list.pop(data)
513        self._data = None
514        for index in range(0, len(self.dataList)):
515            if self.dataList.itemData(index) in data_list:
516                self.dataList.removeItem(index)
517        # Last file removed
518        if len(self._data_list) == 0:
519            self._data = None
520            self.pr_plot = None
521            self.data_plot = None
522            self._calculator = Invertor()
523            self.logic.data = None
524            self.nTermsSuggested = NUMBER_OF_TERMS
525            self.noOfTermsSuggestionButton.setText("{:n}".format(
526                self.nTermsSuggested))
527            self.regConstantSuggestionButton.setText("{:-3.2g}".format(
528                REGULARIZATION))
529            self.updateGuiValues()
530            self.setupModel()
531        else:
532            self.dataList.setCurrentIndex(0)
533            self.updateGuiValues()
534
535    ######################################################################
536    # Thread Creators
537    def startThreadAll(self):
538        self.waitForEach = True
539        output = {}
540        for data_ref in self._data_list.keys():
541            self.setCurrentData(data_ref)
542            self.performEstimate()
543            self.performEstimateNT()
544            self.acceptAlpha()
545            self.acceptNoTerms()
546            self.startThread()
547            output[self.logic.data.filename] = self._calculator
548        self.waitForEach = False
549        self.showBatchOutput(output)
550
551    def startThread(self):
552        """
553            Start a calculation thread
554        """
555        from .Thread import CalcPr
556
557        # Set data before running the calculations
558        self.update_calculator()
559
560        # If a thread is already started, stop it
561        if self.calc_thread is not None and self.calc_thread.isrunning():
562            self.calc_thread.stop()
563        pr = self._calculator.clone()
564        nfunc = self.getNFunc()
565        self.calc_thread = CalcPr(pr, nfunc,
566                                  error_func=self._threadError,
567                                  completefn=self._calculateCompleted,
568                                  updatefn=None)
569        self.calc_thread.queue()
570        self.calc_thread.ready(2.5)
571        if self.waitForEach:
572            if self.calc_thread.isrunning():
573                self.calc_thread.update()
574
575    def performEstimateNT(self):
576        """
577        Perform parameter estimation
578        """
579        from .Thread import EstimateNT
580
581        self.update_calculator()
582
583        # If a thread is already started, stop it
584        if (self.estimation_thread_nt is not None and
585                self.estimation_thread_nt.isrunning()):
586            self.estimation_thread_nt.stop()
587        pr = self._calculator.clone()
588        # Skip the slit settings for the estimation
589        # It slows down the application and it doesn't change the estimates
590        pr.slit_height = 0.0
591        pr.slit_width = 0.0
592        nfunc = self.getNFunc()
593
594        self.estimation_thread_nt = EstimateNT(pr, nfunc,
595                                            error_func=self._threadError,
596                                            completefn=self._estimateNTCompleted,
597                                            updatefn=None)
598        self.estimation_thread_nt.queue()
599        self.estimation_thread_nt.ready(2.5)
600        if self.waitForEach:
601            if self.estimation_thread_nt.isrunning():
602                self.estimation_thread_nt.update()
603
604    def performEstimate(self):
605        """
606            Perform parameter estimation
607        """
608        from .Thread import EstimatePr
609
610        # If a thread is already started, stop it
611        if (self.estimation_thread is not None and
612                self.estimation_thread.isrunning()):
613            self.estimation_thread.stop()
614        self.estimation_thread = EstimatePr(self._calculator.clone(),
615                                            self.getNFunc(),
616                                            error_func=self._threadError,
617                                            completefn=self._estimateCompleted,
618                                            updatefn=None)
619        self.estimation_thread.queue()
620        self.estimation_thread.ready(2.5)
621        if self.waitForEach:
622            if self.estimation_thread.isrunning():
623                self.estimation_thread.update()
624
625    ######################################################################
626    # Thread Complete
627
628    def _estimateCompleted(self, alpha, message, elapsed):
629        ''' Send a signal to the main thread for model update'''
630        self.estimateSignal.emit((alpha, message, elapsed))
631
632    def _estimateUpdate(self, output_tuple):
633        """
634        Parameter estimation completed,
635        display the results to the user
636
637        :param alpha: estimated best alpha
638        :param elapsed: computation time
639        """
640        alpha, message, elapsed = output_tuple
641        if message:
642            logging.info(message)
643        if not self.waitForEach:
644            self.performEstimateNT()
645
646    def _estimateNTCompleted(self, nterms, alpha, message, elapsed):
647        ''' Send a signal to the main thread for model update'''
648        self.estimateNTSignal.emit((nterms, alpha, message, elapsed))
649
650    def _estimateNTUpdate(self, output_tuple):
651        """
652        Parameter estimation completed,
653        display the results to the user
654
655        :param alpha: estimated best alpha
656        :param nterms: estimated number of terms
657        :param elapsed: computation time
658        """
659        nterms, alpha, message, elapsed = output_tuple
660        self._calculator.elapsed = elapsed
661        self._calculator.suggested_alpha = alpha
662        self.nTermsSuggested = nterms
663        # Save useful info
664        self.updateGuiValues()
665        if message:
666            logging.info(message)
667
668    def _calculateCompleted(self, out, cov, pr, elapsed):
669        ''' Send a signal to the main thread for model update'''
670        self.calculateSignal.emit((out, cov, pr, elapsed))
671
672    def _calculateUpdate(self, output_tuple):
673        """
674        Method called with the results when the inversion is done
675
676        :param out: output coefficient for the base functions
677        :param cov: covariance matrix
678        :param pr: Invertor instance
679        :param elapsed: time spent computing
680        """
681        out, cov, pr, elapsed = output_tuple
682        # Save useful info
683        cov = np.ascontiguousarray(cov)
684        pr.cov = cov
685        pr.out = out
686        pr.elapsed = elapsed
687
688        # Save Pr invertor
689        self._calculator = pr
690
691        # Create new P(r) and fit plots
692        if self.pr_plot is None:
693            self.pr_plot = self.logic.newPRPlot(out, self._calculator, cov)
694        if self.data_plot is None:
695            self.data_plot = self.logic.new1DPlot(out, self._calculator)
696        self.updateDataList(self._data)
697        self.updateGuiValues()
698
699    def _threadError(self, error):
700        """
701            Call-back method for calculation errors
702        """
703        logging.warning(error)
Note: See TracBrowser for help on using the repository browser.