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

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

Simulated error handling added to more logical place

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