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

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

Penultimate group of working unit tests for qtgui P(r)

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