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

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

Fix issues deleting from p(r) when data deleted in data manager.

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