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

Last change on this file since 6c7ebb88 was a74dd016, checked in by wojciech, 6 years ago

Fixing faling P(r) on files without added errors

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