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

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

Run the P(r) batch fits in order to prevent thread interference and other code cleanup.

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