source: sasview/src/sas/qtgui/Perspectives/Inversion/InversionPerspective.py @ 4b7d322

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

Merge branch 'ESS_GUI' of https://github.com/SasView/sasview into ESS_GUI_Pr_fixes

  • Property mode set to 100644
File size: 34.4 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            # Estimate q range
462            qmin, qmax = self.logic.computeDataRange()
463            self._calculator.set_qmin(qmin)
464            self._calculator.set_qmax(qmax)
465            if np.size(self.logic.data.dy) == 0 or np.all(self.logic.data.dy) == 0:
466                self.logic.data.dy = self._calculator.add_errors(self.logic.data.y)
467            self.updateDataList(data)
468            self.populateDataComboBox(self.logic.data.filename, data)
469        self.dataList.setCurrentIndex(len(self.dataList) - 1)
470        self.setCurrentData(data)
471
472    def updateDataList(self, dataRef):
473        """Save the current data state of the window into self._data_list"""
474        if dataRef is None:
475            return
476        self._dataList[dataRef] = {
477            DICT_KEYS[0]: self._calculator,
478            DICT_KEYS[1]: self.prPlot,
479            DICT_KEYS[2]: self.dataPlot
480        }
481        # Update batch results window when finished
482        self.batchResults[self.logic.data.filename] = self._calculator
483        if self.batchResultsWindow is not None:
484            self.showBatchOutput()
485
486    def getNFunc(self):
487        """Get the n_func value from the GUI object"""
488        try:
489            nfunc = int(self.noOfTermsInput.text())
490        except ValueError:
491            logger.error("Incorrect number of terms specified: %s"
492                          %self.noOfTermsInput.text())
493            self.noOfTermsInput.setText(str(NUMBER_OF_TERMS))
494            nfunc = NUMBER_OF_TERMS
495        return nfunc
496
497    def setCurrentData(self, data_ref):
498        """Get the data by reference and display as necessary"""
499        if data_ref is None:
500            return
501        if not isinstance(data_ref, QtGui.QStandardItem):
502            msg = "Incorrect type passed to the P(r) Perspective"
503            raise AttributeError(msg)
504        # Data references
505        self._data = data_ref
506        self.logic.data = GuiUtils.dataFromItem(data_ref)
507        self._calculator = self._dataList[data_ref].get(DICT_KEYS[0])
508        self.prPlot = self._dataList[data_ref].get(DICT_KEYS[1])
509        self.dataPlot = self._dataList[data_ref].get(DICT_KEYS[2])
510        self.performEstimate()
511
512    def updateDynamicGuiValues(self):
513        pr = self._calculator
514        alpha = self._calculator.suggested_alpha
515        self.model.setItem(WIDGETS.W_MAX_DIST,
516                            QtGui.QStandardItem("{:.4g}".format(pr.get_dmax())))
517        self.regConstantSuggestionButton.setText("{:-3.2g}".format(alpha))
518        self.noOfTermsSuggestionButton.setText(
519             "{:n}".format(self.nTermsSuggested))
520
521        self.enableButtons()
522
523    def updateGuiValues(self):
524        pr = self._calculator
525        out = self._calculator.out
526        cov = self._calculator.cov
527        elapsed = self._calculator.elapsed
528        alpha = self._calculator.suggested_alpha
529        self.model.setItem(WIDGETS.W_QMIN,
530                           QtGui.QStandardItem("{:.4g}".format(pr.get_qmin())))
531        self.model.setItem(WIDGETS.W_QMAX,
532                           QtGui.QStandardItem("{:.4g}".format(pr.get_qmax())))
533        self.model.setItem(WIDGETS.W_BACKGROUND_INPUT,
534                           QtGui.QStandardItem("{:.3g}".format(pr.background)))
535        self.model.setItem(WIDGETS.W_BACKGROUND_OUTPUT,
536                           QtGui.QStandardItem("{:.3g}".format(pr.background)))
537        self.model.setItem(WIDGETS.W_COMP_TIME,
538                           QtGui.QStandardItem("{:.4g}".format(elapsed)))
539        self.model.setItem(WIDGETS.W_MAX_DIST,
540                           QtGui.QStandardItem("{:.4g}".format(pr.get_dmax())))
541
542        if isinstance(pr.chi2, np.ndarray):
543            self.model.setItem(WIDGETS.W_CHI_SQUARED,
544                               QtGui.QStandardItem("{:.3g}".format(pr.chi2[0])))
545        if out is not None:
546            self.model.setItem(WIDGETS.W_RG,
547                               QtGui.QStandardItem("{:.3g}".format(pr.rg(out))))
548            self.model.setItem(WIDGETS.W_I_ZERO,
549                               QtGui.QStandardItem(
550                                   "{:.3g}".format(pr.iq0(out))))
551            self.model.setItem(WIDGETS.W_OSCILLATION, QtGui.QStandardItem(
552                "{:.3g}".format(pr.oscillations(out))))
553            self.model.setItem(WIDGETS.W_POS_FRACTION, QtGui.QStandardItem(
554                "{:.3g}".format(pr.get_positive(out))))
555            if cov is not None:
556                self.model.setItem(WIDGETS.W_SIGMA_POS_FRACTION,
557                                   QtGui.QStandardItem(
558                                       "{:.3g}".format(
559                                           pr.get_pos_err(out, cov))))
560        if self.prPlot is not None:
561            title = self.prPlot.name
562            self.prPlot.plot_role = Data1D.ROLE_RESIDUAL
563            GuiUtils.updateModelItemWithPlot(self._data, self.prPlot, title)
564        if self.dataPlot is not None:
565            title = self.dataPlot.name
566            self.dataPlot.plot_role = Data1D.ROLE_DEFAULT
567            GuiUtils.updateModelItemWithPlot(self._data, self.dataPlot, title)
568        if self.dataPlot is not None or self.prPlot is not None:
569            self.communicate.plotRequestedSignal.emit([self.logic.data], None)
570        self.enableButtons()
571
572    def removeData(self, data_list=None):
573        """Remove the existing data reference from the P(r) Persepective"""
574        self.dataDeleted = True
575        self.batchResults = {}
576        if not data_list:
577            data_list = [self._data]
578        self.closeDMax()
579        for data in data_list:
580            self._dataList.pop(data)
581        self._data = None
582        length = len(self.dataList)
583        for index in reversed(range(length)):
584            if self.dataList.itemData(index) in data_list:
585                self.dataList.removeItem(index)
586        # Last file removed
587        self.dataDeleted = False
588        if len(self._dataList) == 0:
589            self.prPlot = None
590            self.dataPlot = None
591            self.logic.data = None
592            self._calculator = Invertor()
593            self.closeBatchResults()
594            self.nTermsSuggested = NUMBER_OF_TERMS
595            self.noOfTermsSuggestionButton.setText("{:n}".format(
596                self.nTermsSuggested))
597            self.regConstantSuggestionButton.setText("{:-3.2g}".format(
598                REGULARIZATION))
599            self.updateGuiValues()
600            self.setupModel()
601        else:
602            self.dataList.setCurrentIndex(0)
603            self.updateGuiValues()
604
605    ######################################################################
606    # Thread Creators
607
608    def startThreadAll(self):
609        self.isCalculating = True
610        self.isBatch = True
611        self.batchComplete = []
612        self.calculateAllButton.setText("Calculating...")
613        self.enableButtons()
614        self.batchResultsWindow = BatchInversionOutputPanel(
615            parent=self, output_data=self.batchResults)
616        self.performEstimate()
617
618    def startNextBatchItem(self):
619        self.isBatch = False
620        for index in range(len(self._dataList)):
621            if index not in self.batchComplete:
622                self.dataList.setCurrentIndex(index)
623                self.isBatch = True
624                # Add the index before calculating in case calculation fails
625                self.batchComplete.append(index)
626                break
627        if self.isBatch:
628            self.performEstimate()
629        else:
630            # If no data sets left, end batch calculation
631            self.isCalculating = False
632            self.batchComplete = []
633            self.calculateAllButton.setText("Calculate All")
634            self.showBatchOutput()
635            self.enableButtons()
636
637    def startThread(self):
638        """
639            Start a calculation thread
640        """
641        from .Thread import CalcPr
642
643        # Set data before running the calculations
644        self.isCalculating = True
645        self.enableButtons()
646        self.updateCalculator()
647        # Disable calculation buttons to prevent thread interference
648
649        # If the thread is already started, stop it
650        self.stopCalcThread()
651
652        pr = self._calculator.clone()
653        nfunc = self.getNFunc()
654        self.calcThread = CalcPr(pr, nfunc,
655                                 error_func=self._threadError,
656                                 completefn=self._calculateCompleted,
657                                 updatefn=None)
658        self.calcThread.queue()
659        self.calcThread.ready(2.5)
660
661    def stopCalcThread(self):
662        """ Stops a thread if it exists and is running """
663        if self.calcThread is not None and self.calcThread.isrunning():
664            self.calcThread.stop()
665
666    def performEstimateNT(self):
667        """
668        Perform parameter estimation
669        """
670        from .Thread import EstimateNT
671
672        self.updateCalculator()
673
674        # If a thread is already started, stop it
675        self.stopEstimateNTThread()
676
677        pr = self._calculator.clone()
678        # Skip the slit settings for the estimation
679        # It slows down the application and it doesn't change the estimates
680        pr.slit_height = 0.0
681        pr.slit_width = 0.0
682        nfunc = self.getNFunc()
683
684        self.estimationThreadNT = EstimateNT(pr, nfunc,
685                                             error_func=self._threadError,
686                                             completefn=self._estimateNTCompleted,
687                                             updatefn=None)
688        self.estimationThreadNT.queue()
689        self.estimationThreadNT.ready(2.5)
690
691    def performEstimateDynamicNT(self):
692        """
693        Perform parameter estimation
694        """
695        from .Thread import EstimateNT
696
697        self.updateCalculator()
698
699        # If a thread is already started, stop it
700        self.stopEstimateNTThread()
701
702        pr = self._calculator.clone()
703        # Skip the slit settings for the estimation
704        # It slows down the application and it doesn't change the estimates
705        pr.slit_height = 0.0
706        pr.slit_width = 0.0
707        nfunc = self.getNFunc()
708
709        self.estimationThreadNT = EstimateNT(pr, nfunc,
710                                             error_func=self._threadError,
711                                             completefn=self._estimateDynamicNTCompleted,
712                                             updatefn=None)
713        self.estimationThreadNT.queue()
714        self.estimationThreadNT.ready(2.5)
715
716    def stopEstimateNTThread(self):
717        if (self.estimationThreadNT is not None and
718                self.estimationThreadNT.isrunning()):
719            self.estimationThreadNT.stop()
720
721    def performEstimate(self):
722        """
723            Perform parameter estimation
724        """
725        from .Thread import EstimatePr
726
727        # If a thread is already started, stop it
728        self.stopEstimationThread()
729
730        self.estimationThread = EstimatePr(self._calculator.clone(),
731                                           self.getNFunc(),
732                                           error_func=self._threadError,
733                                           completefn=self._estimateCompleted,
734                                           updatefn=None)
735        self.estimationThread.queue()
736        self.estimationThread.ready(2.5)
737
738    def performEstimateDynamic(self):
739        """
740            Perform parameter estimation
741        """
742        from .Thread import EstimatePr
743
744        # If a thread is already started, stop it
745        self.stopEstimationThread()
746
747        self.estimationThread = EstimatePr(self._calculator.clone(),
748                                           self.getNFunc(),
749                                           error_func=self._threadError,
750                                           completefn=self._estimateDynamicCompleted,
751                                           updatefn=None)
752        self.estimationThread.queue()
753        self.estimationThread.ready(2.5)
754
755    def stopEstimationThread(self):
756        """ Stop the estimation thread if it exists and is running """
757        if (self.estimationThread is not None and
758                self.estimationThread.isrunning()):
759            self.estimationThread.stop()
760
761    ######################################################################
762    # Thread Complete
763
764    def _estimateCompleted(self, alpha, message, elapsed):
765        ''' Send a signal to the main thread for model update'''
766        self.estimateSignal.emit((alpha, message, elapsed))
767
768    def _estimateDynamicCompleted(self, alpha, message, elapsed):
769        ''' Send a signal to the main thread for model update'''
770        self.estimateDynamicSignal.emit((alpha, message, elapsed))
771
772    def _estimateUpdate(self, output_tuple):
773        """
774        Parameter estimation completed,
775        display the results to the user
776
777        :param alpha: estimated best alpha
778        :param elapsed: computation time
779        """
780        alpha, message, elapsed = output_tuple
781        self._calculator.alpha = alpha
782        self._calculator.elapsed += self._calculator.elapsed
783        if message:
784            logger.info(message)
785        self.performEstimateNT()
786        self.performEstimateDynamicNT()
787
788    def _estimateDynamicUpdate(self, output_tuple):
789        """
790        Parameter estimation completed,
791        display the results to the user
792
793        :param alpha: estimated best alpha
794        :param elapsed: computation time
795        """
796        alpha, message, elapsed = output_tuple
797        self._calculator.alpha = alpha
798        self._calculator.elapsed += self._calculator.elapsed
799        if message:
800            logger.info(message)
801        self.performEstimateDynamicNT()
802
803    def _estimateNTCompleted(self, nterms, alpha, message, elapsed):
804        ''' Send a signal to the main thread for model update'''
805        self.estimateNTSignal.emit((nterms, alpha, message, elapsed))
806
807    def _estimateDynamicNTCompleted(self, nterms, alpha, message, elapsed):
808        ''' Send a signal to the main thread for model update'''
809        self.estimateDynamicNTSignal.emit((nterms, alpha, message, elapsed))
810
811    def _estimateNTUpdate(self, output_tuple):
812        """
813        Parameter estimation completed,
814        display the results to the user
815
816        :param alpha: estimated best alpha
817        :param nterms: estimated number of terms
818        :param elapsed: computation time
819        """
820        nterms, alpha, message, elapsed = output_tuple
821        self._calculator.elapsed += elapsed
822        self._calculator.suggested_alpha = alpha
823        self.nTermsSuggested = nterms
824        # Save useful info
825        self.updateGuiValues()
826        if message:
827            logger.info(message)
828        if self.isBatch:
829            self.acceptAlpha()
830            self.acceptNoTerms()
831            self.startThread()
832
833    def _estimateDynamicNTUpdate(self, output_tuple):
834        """
835        Parameter estimation completed,
836        display the results to the user
837
838        :param alpha: estimated best alpha
839        :param nterms: estimated number of terms
840        :param elapsed: computation time
841        """
842        nterms, alpha, message, elapsed = output_tuple
843        self._calculator.elapsed += elapsed
844        self._calculator.suggested_alpha = alpha
845        self.nTermsSuggested = nterms
846        # Save useful info
847        self.updateDynamicGuiValues()
848        if message:
849            logger.info(message)
850        if self.isBatch:
851            self.acceptAlpha()
852            self.acceptNoTerms()
853            self.startThread()
854
855    def _calculateCompleted(self, out, cov, pr, elapsed):
856        ''' Send a signal to the main thread for model update'''
857        self.calculateSignal.emit((out, cov, pr, elapsed))
858
859    def _calculateUpdate(self, output_tuple):
860        """
861        Method called with the results when the inversion is done
862
863        :param out: output coefficient for the base functions
864        :param cov: covariance matrix
865        :param pr: Invertor instance
866        :param elapsed: time spent computing
867        """
868        out, cov, pr, elapsed = output_tuple
869        # Save useful info
870        cov = np.ascontiguousarray(cov)
871        pr.cov = cov
872        pr.out = out
873        pr.elapsed = elapsed
874
875        # Save Pr invertor
876        self._calculator = pr
877
878        # Update P(r) and fit plots
879        self.prPlot = self.logic.newPRPlot(out, self._calculator, cov)
880        self.prPlot.filename = self.logic.data.filename
881        self.dataPlot = self.logic.new1DPlot(out, self._calculator)
882        self.dataPlot.filename = self.logic.data.filename
883
884        # Udpate internals and GUI
885        self.updateDataList(self._data)
886        if self.isBatch:
887            self.batchComplete.append(self.dataList.currentIndex())
888            self.startNextBatchItem()
889        else:
890            self.isCalculating = False
891        self.updateGuiValues()
892
893    def _threadError(self, error):
894        """
895            Call-back method for calculation errors
896        """
897        logger.error(error)
898        if self.isBatch:
899            self.startNextBatchItem()
900        else:
901            self.stopCalculation()
Note: See TracBrowser for help on using the repository browser.