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

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

Fixes for batch fitting

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