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

ESS_GUIESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 5b144c6 was 3c6ecd9, checked in by Piotr Rozyczko <rozyczko@…>, 7 years ago

Merge branch 'ESS_GUI' into ESS_GUI_Pr

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