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

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

Document batch p(r) and link to the anchor from the results window. Remove unicode characters from batch results table for saving purposes.

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