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

ESS_GUIESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since b1f6063 was b1f6063, checked in by wojciech, 6 years ago

Explore enabled and parameter estimate problem identified

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