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

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

Fix to disable 2D data in P(r) calculations

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