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

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

Responding to P(r) code review.

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