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

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

Improvements to batch P(r).

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