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

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

Add convenience method to P(r) that returns the closable state.

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