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

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 72ecbdf2 was 72ecbdf2, checked in by krzywon, 6 years ago

Add a stop calculations button to P(r). Plus unit tests.

  • Property mode set to 100644
File size: 30.0 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)
311        self.explorerButton.setEnabled(self.logic.data_is_loaded)
[72ecbdf2]312        self.stopButton.setVisible(self.isCalculating)
[b685c7b]313        self.regConstantSuggestionButton.setEnabled(
[d79bb7e]314            self.logic.data_is_loaded and
[b685c7b]315            self._calculator.suggested_alpha != self._calculator.alpha)
316        self.noOfTermsSuggestionButton.setEnabled(
[d79bb7e]317            self.logic.data_is_loaded and
[b685c7b]318            self._calculator.nfunc != self.nTermsSuggested)
[fa81e94]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        """
[6a3e1fe]326        self.dataList.addItem(filename, data_ref)
[fa81e94]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
[edd6720]338    def displayChange(self, data_index=0):
[47bf906]339        """Switch to another item in the data list"""
[044454d]340        if self.dataDeleted:
341            return
[edd6720]342        self.updateDataList(self._data)
343        self.setCurrentData(self.dataList.itemData(data_index))
[fa81e94]344
345    ######################################################################
346    # GUI Interaction Events
347
[ae34d30]348    def updateCalculator(self):
[fa81e94]349        """Update all p(r) params"""
[edd6720]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)
[441a03f]353        self.set_background(self.backgroundInput.text())
354
355    def set_background(self, value):
356        self._calculator.background = is_float(value)
[fa81e94]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)."
[6da860a]363            logger.warning(msg)
[fa81e94]364            self.setClosable(True)
365            self.close()
[ae34d30]366            InversionWindow.__init__(self.parent(), list(self._dataList.keys()))
[fa81e94]367            exit(0)
[8f83719f]368        if self.dmaxWindow is not None:
[47bf906]369            self.dmaxWindow.nfunc = self.getNFunc()
[bb6b037]370            self.dmaxWindow.pr_state = self._calculator
[edd6720]371        self.mapper.toLast()
[fa81e94]372
373    def help(self):
374        """
375        Open the P(r) Inversion help browser
376        """
[e90988c]377        tree_location = "/user/sasgui/perspectives/pr/pr_help.html"
[fa81e94]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
[e90988c]382        self._manager.showHelp(tree_location)
[fa81e94]383
384    def toggleBgd(self):
385        """
386        Toggle the background between manual and estimated
387        """
[edd6720]388        if self.estimateBgd.isChecked():
389            self.manualBgd.setChecked(False)
[fa81e94]390            self.backgroundInput.setEnabled(False)
[304e42f]391            self._calculator.set_est_bck = True
[edd6720]392        elif self.manualBgd.isChecked():
393            self.estimateBgd.setChecked(False)
[fa81e94]394            self.backgroundInput.setEnabled(True)
[304e42f]395            self._calculator.set_est_bck = False
[441a03f]396        else:
397            pass
[fa81e94]398
399    def openExplorerWindow(self):
400        """
401        Open the Explorer window to see correlations between params and results
402        """
403        from .DMaxExplorerWidget import DmaxWindow
[6da860a]404        self.dmaxWindow = DmaxWindow(pr_state=self._calculator,
405                                     nfunc=self.getNFunc(),
406                                     parent=self)
[fa81e94]407        self.dmaxWindow.show()
408
[98485fe]409    def showBatchOutput(self):
[76567bb]410        """
411        Display the batch output in tabular form
412        :param output_data: Dictionary mapping filename -> P(r) instance
413        """
[ae34d30]414        if self.batchResultsWindow is None:
415            self.batchResultsWindow = BatchInversionOutputPanel(
[98485fe]416                parent=self, output_data=self.batchResults)
[76567bb]417        else:
[ae34d30]418            self.batchResultsWindow.setupTable(self.batchResults)
419        self.batchResultsWindow.show()
[effdd98]420
[72ecbdf2]421    def stopCalculation(self):
422        """ Stop all threads, return to the base state and update GUI """
423        if self.calcThread:
424            self.calcThread.stop()
425        if self.estimationThread:
426            self.estimationThread.stop()
427        if self.estimationThreadNT:
428            self.estimationThreadNT.stop()
429        # Show any batch calculations that successfully completed
430        if self.isBatch and self.batchResultsWindow is not None:
431            self.showBatchOutput()
432        self.isBatch = False
433        self.isCalculating = False
434        self.updateGuiValues()
435
[fa81e94]436    ######################################################################
437    # Response Actions
438
439    def setData(self, data_item=None, is_batch=False):
440        """
441        Assign new data set(s) to the P(r) perspective
442        Obtain a QStandardItem object and parse it to get Data1D/2D
443        Pass it over to the calculator
444        """
445        assert data_item is not None
446
447        if not isinstance(data_item, list):
448            msg = "Incorrect type passed to the P(r) Perspective"
[47bf906]449            raise AttributeError(msg)
[fa81e94]450
451        for data in data_item:
[ae34d30]452            if data in self._dataList.keys():
[8f83719f]453                # Don't add data if it's already in
[edd6720]454                continue
[fa81e94]455            # Create initial internal mappings
[edd6720]456            self.logic.data = GuiUtils.dataFromItem(data)
[e51e078]457            # Estimate q range
458            qmin, qmax = self.logic.computeDataRange()
459            self._calculator.set_qmin(qmin)
460            self._calculator.set_qmax(qmax)
461            self.updateDataList(data)
[edd6720]462            self.populateDataComboBox(self.logic.data.filename, data)
463        self.dataList.setCurrentIndex(len(self.dataList) - 1)
464        self.setCurrentData(data)
[fa81e94]465
[47bf906]466    def updateDataList(self, dataRef):
467        """Save the current data state of the window into self._data_list"""
[e51e078]468        if dataRef is None:
469            return
[ae34d30]470        self._dataList[dataRef] = {
[e51e078]471            DICT_KEYS[0]: self._calculator,
[ae34d30]472            DICT_KEYS[1]: self.prPlot,
473            DICT_KEYS[2]: self.dataPlot
[47bf906]474        }
[98485fe]475        # Update batch results window when finished
476        self.batchResults[self.logic.data.filename] = self._calculator
[ae34d30]477        if self.batchResultsWindow is not None:
[98485fe]478            self.showBatchOutput()
[47bf906]479
[fa81e94]480    def getNFunc(self):
481        """Get the n_func value from the GUI object"""
[50bfab0]482        try:
483            nfunc = int(self.noOfTermsInput.text())
484        except ValueError:
[6da860a]485            logger.error("Incorrect number of terms specified: %s"
[edd6720]486                          %self.noOfTermsInput.text())
[50bfab0]487            self.noOfTermsInput.setText(str(NUMBER_OF_TERMS))
488            nfunc = NUMBER_OF_TERMS
489        return nfunc
[fa81e94]490
491    def setCurrentData(self, data_ref):
[47bf906]492        """Get the data by reference and display as necessary"""
[304e42f]493        if data_ref is None:
494            return
[fa81e94]495        if not isinstance(data_ref, QtGui.QStandardItem):
496            msg = "Incorrect type passed to the P(r) Perspective"
[e51e078]497            raise AttributeError(msg)
[fa81e94]498        # Data references
499        self._data = data_ref
[edd6720]500        self.logic.data = GuiUtils.dataFromItem(data_ref)
[ae34d30]501        self._calculator = self._dataList[data_ref].get(DICT_KEYS[0])
502        self.prPlot = self._dataList[data_ref].get(DICT_KEYS[1])
503        self.dataPlot = self._dataList[data_ref].get(DICT_KEYS[2])
[edd6720]504        self.performEstimate()
[e51e078]505
506    def updateGuiValues(self):
507        pr = self._calculator
508        out = self._calculator.out
509        cov = self._calculator.cov
510        elapsed = self._calculator.elapsed
511        alpha = self._calculator.suggested_alpha
512        self.model.setItem(WIDGETS.W_QMIN,
513                           QtGui.QStandardItem("{:.4g}".format(pr.get_qmin())))
514        self.model.setItem(WIDGETS.W_QMAX,
515                           QtGui.QStandardItem("{:.4g}".format(pr.get_qmax())))
516        self.model.setItem(WIDGETS.W_BACKGROUND_INPUT,
[effdd98]517                           QtGui.QStandardItem("{:.3g}".format(pr.background)))
[e51e078]518        self.model.setItem(WIDGETS.W_BACKGROUND_OUTPUT,
519                           QtGui.QStandardItem("{:.3g}".format(pr.background)))
520        self.model.setItem(WIDGETS.W_COMP_TIME,
521                           QtGui.QStandardItem("{:.4g}".format(elapsed)))
[ae34d30]522        self.model.setItem(WIDGETS.W_MAX_DIST,
523                           QtGui.QStandardItem("{:.4g}".format(pr.get_dmax())))
[b685c7b]524        self.regConstantSuggestionButton.setText("{:-3.2g}".format(alpha))
525        self.noOfTermsSuggestionButton.setText(
526            "{:n}".format(self.nTermsSuggested))
[e51e078]527
[304e42f]528        if isinstance(pr.chi2, np.ndarray):
[e51e078]529            self.model.setItem(WIDGETS.W_CHI_SQUARED,
530                               QtGui.QStandardItem("{:.3g}".format(pr.chi2[0])))
531        if out is not None:
532            self.model.setItem(WIDGETS.W_RG,
533                               QtGui.QStandardItem("{:.3g}".format(pr.rg(out))))
534            self.model.setItem(WIDGETS.W_I_ZERO,
535                               QtGui.QStandardItem(
536                                   "{:.3g}".format(pr.iq0(out))))
537            self.model.setItem(WIDGETS.W_OSCILLATION, QtGui.QStandardItem(
538                "{:.3g}".format(pr.oscillations(out))))
539            self.model.setItem(WIDGETS.W_POS_FRACTION, QtGui.QStandardItem(
540                "{:.3g}".format(pr.get_positive(out))))
541            if cov is not None:
542                self.model.setItem(WIDGETS.W_SIGMA_POS_FRACTION,
543                                   QtGui.QStandardItem(
544                                       "{:.3g}".format(
545                                           pr.get_pos_err(out, cov))))
[ae34d30]546        if self.prPlot is not None:
547            title = self.prPlot.name
548            GuiUtils.updateModelItemWithPlot(self._data, self.prPlot, title)
549            self.communicate.plotRequestedSignal.emit([self.prPlot])
550        if self.dataPlot is not None:
551            title = self.dataPlot.name
552            GuiUtils.updateModelItemWithPlot(self._data, self.dataPlot, title)
[044454d]553            self.communicate.plotRequestedSignal.emit([self.dataPlot])
[b685c7b]554        self.enableButtons()
[47bf906]555
[b9e89d5]556    def removeData(self, data_list=None):
[47bf906]557        """Remove the existing data reference from the P(r) Persepective"""
[044454d]558        self.dataDeleted = True
[d79bb7e]559        self.batchResults = {}
[b9e89d5]560        if not data_list:
561            data_list = [self._data]
[ae34d30]562        self.closeDMax()
[b9e89d5]563        for data in data_list:
[ae34d30]564            self._dataList.pop(data)
[76567bb]565        self._data = None
[044454d]566        length = len(self.dataList)
567        for index in reversed(range(length)):
[b9e89d5]568            if self.dataList.itemData(index) in data_list:
569                self.dataList.removeItem(index)
[e51e078]570        # Last file removed
[044454d]571        self.dataDeleted = False
[ae34d30]572        if len(self._dataList) == 0:
573            self.prPlot = None
574            self.dataPlot = None
[edd6720]575            self.logic.data = None
[ae34d30]576            self._calculator = Invertor()
577            self.closeBatchResults()
[b685c7b]578            self.nTermsSuggested = NUMBER_OF_TERMS
579            self.noOfTermsSuggestionButton.setText("{:n}".format(
580                self.nTermsSuggested))
581            self.regConstantSuggestionButton.setText("{:-3.2g}".format(
582                REGULARIZATION))
[edd6720]583            self.updateGuiValues()
[b685c7b]584            self.setupModel()
[ba4e3ba]585        else:
586            self.dataList.setCurrentIndex(0)
587            self.updateGuiValues()
[fa81e94]588
589    ######################################################################
590    # Thread Creators
[98485fe]591
[fa81e94]592    def startThreadAll(self):
[72ecbdf2]593        self.isCalculating = True
[98485fe]594        self.isBatch = True
[d79bb7e]595        self.batchComplete = []
596        self.calculateAllButton.setText("Calculating...")
597        self.enableButtons()
598        self.batchResultsWindow = BatchInversionOutputPanel(
599            parent=self, output_data=self.batchResults)
[98485fe]600        self.performEstimate()
601
602    def startNextBatchItem(self):
603        self.isBatch = False
[ae34d30]604        for index in range(len(self._dataList)):
[98485fe]605            if index not in self.batchComplete:
606                self.dataList.setCurrentIndex(index)
607                self.isBatch = True
[6da860a]608                # Add the index before calculating in case calculation fails
609                self.batchComplete.append(index)
[98485fe]610                break
611        if self.isBatch:
[76567bb]612            self.performEstimate()
[ae34d30]613        else:
614            # If no data sets left, end batch calculation
[72ecbdf2]615            self.isCalculating = False
[d79bb7e]616            self.batchComplete = []
[ae34d30]617            self.calculateAllButton.setText("Calculate All")
[5a5e371]618            self.showBatchOutput()
[ae34d30]619            self.enableButtons()
[fa81e94]620
621    def startThread(self):
622        """
623            Start a calculation thread
624        """
625        from .Thread import CalcPr
626
627        # Set data before running the calculations
[72ecbdf2]628        self.isCalculating = True
629        self.enableButtons()
[ae34d30]630        self.updateCalculator()
[6da860a]631        # Disable calculation buttons to prevent thread interference
[fa81e94]632
633        # If a thread is already started, stop it
[ae34d30]634        if self.calcThread is not None and self.calcThread.isrunning():
635            self.calcThread.stop()
[fa81e94]636        pr = self._calculator.clone()
637        nfunc = self.getNFunc()
[ae34d30]638        self.calcThread = CalcPr(pr, nfunc,
639                                 error_func=self._threadError,
640                                 completefn=self._calculateCompleted,
641                                 updatefn=None)
642        self.calcThread.queue()
643        self.calcThread.ready(2.5)
[fa81e94]644
645    def performEstimateNT(self):
646        """
[f1ec901]647        Perform parameter estimation
[fa81e94]648        """
649        from .Thread import EstimateNT
650
[ae34d30]651        self.updateCalculator()
[edd6720]652
[fa81e94]653        # If a thread is already started, stop it
[ae34d30]654        if (self.estimationThreadNT is not None and
655                self.estimationThreadNT.isrunning()):
656            self.estimationThreadNT.stop()
[fa81e94]657        pr = self._calculator.clone()
658        # Skip the slit settings for the estimation
659        # It slows down the application and it doesn't change the estimates
660        pr.slit_height = 0.0
661        pr.slit_width = 0.0
662        nfunc = self.getNFunc()
[f1ec901]663
[ae34d30]664        self.estimationThreadNT = EstimateNT(pr, nfunc,
665                                             error_func=self._threadError,
666                                             completefn=self._estimateNTCompleted,
667                                             updatefn=None)
668        self.estimationThreadNT.queue()
669        self.estimationThreadNT.ready(2.5)
[fa81e94]670
671    def performEstimate(self):
672        """
673            Perform parameter estimation
674        """
675        from .Thread import EstimatePr
676
677        # If a thread is already started, stop it
[ae34d30]678        if (self.estimationThread is not None and
679                self.estimationThread.isrunning()):
680            self.estimationThread.stop()
681        self.estimationThread = EstimatePr(self._calculator.clone(),
682                                           self.getNFunc(),
683                                           error_func=self._threadError,
684                                           completefn=self._estimateCompleted,
685                                           updatefn=None)
686        self.estimationThread.queue()
687        self.estimationThread.ready(2.5)
[fa81e94]688
689    ######################################################################
690    # Thread Complete
691
692    def _estimateCompleted(self, alpha, message, elapsed):
[f1ec901]693        ''' Send a signal to the main thread for model update'''
694        self.estimateSignal.emit((alpha, message, elapsed))
695
696    def _estimateUpdate(self, output_tuple):
[fa81e94]697        """
698        Parameter estimation completed,
699        display the results to the user
700
701        :param alpha: estimated best alpha
702        :param elapsed: computation time
703        """
[f1ec901]704        alpha, message, elapsed = output_tuple
[6da860a]705        self._calculator.alpha = alpha
706        self._calculator.elapsed += self._calculator.elapsed
[fa81e94]707        if message:
[6da860a]708            logger.info(message)
[98485fe]709        self.performEstimateNT()
[fa81e94]710
711    def _estimateNTCompleted(self, nterms, alpha, message, elapsed):
[f1ec901]712        ''' Send a signal to the main thread for model update'''
713        self.estimateNTSignal.emit((nterms, alpha, message, elapsed))
714
715    def _estimateNTUpdate(self, output_tuple):
[fa81e94]716        """
717        Parameter estimation completed,
718        display the results to the user
719
720        :param alpha: estimated best alpha
721        :param nterms: estimated number of terms
722        :param elapsed: computation time
723        """
[f1ec901]724        nterms, alpha, message, elapsed = output_tuple
[6da860a]725        self._calculator.elapsed += elapsed
[e51e078]726        self._calculator.suggested_alpha = alpha
727        self.nTermsSuggested = nterms
[fa81e94]728        # Save useful info
[e51e078]729        self.updateGuiValues()
[fa81e94]730        if message:
[6da860a]731            logger.info(message)
[98485fe]732        if self.isBatch:
733            self.acceptAlpha()
734            self.acceptNoTerms()
735            self.startThread()
[fa81e94]736
[f1ec901]737    def _calculateCompleted(self, out, cov, pr, elapsed):
738        ''' Send a signal to the main thread for model update'''
739        self.calculateSignal.emit((out, cov, pr, elapsed))
740
741    def _calculateUpdate(self, output_tuple):
[fa81e94]742        """
743        Method called with the results when the inversion is done
744
745        :param out: output coefficient for the base functions
746        :param cov: covariance matrix
747        :param pr: Invertor instance
748        :param elapsed: time spent computing
749        """
[f1ec901]750        out, cov, pr, elapsed = output_tuple
[fa81e94]751        # Save useful info
752        cov = np.ascontiguousarray(cov)
753        pr.cov = cov
754        pr.out = out
755        pr.elapsed = elapsed
756
757        # Save Pr invertor
758        self._calculator = pr
[f1ec901]759
[318b353e]760        # Update P(r) and fit plots
[ae34d30]761        self.prPlot = self.logic.newPRPlot(out, self._calculator, cov)
762        self.prPlot.filename = self.logic.data.filename
763        self.dataPlot = self.logic.new1DPlot(out, self._calculator)
764        self.dataPlot.filename = self.logic.data.filename
[318b353e]765
766        # Udpate internals and GUI
[e51e078]767        self.updateDataList(self._data)
[98485fe]768        if self.isBatch:
769            self.batchComplete.append(self.dataList.currentIndex())
770            self.startNextBatchItem()
[72ecbdf2]771        else:
772            self.isCalculating = False
773        self.updateGuiValues()
[fa81e94]774
775    def _threadError(self, error):
776        """
777            Call-back method for calculation errors
778        """
[6da860a]779        logger.error(error)
Note: See TracBrowser for help on using the repository browser.