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

ESS_GUIESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 42d79fc was 42d79fc, checked in by wojciech, 2 years ago

Disabling reporting for perspectives other than fitting

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