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

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

Dmax close events inform P(r) window, data removal removes batch results for that data set, and general code cleanup.

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