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

ESS_GUIESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since d1e4689 was 9ce69ec, checked in by Piotr Rozyczko <rozyczko@…>, 6 years ago

Replaced 'smart' plot generation with explicit plot requests on "Show Plot". SASVIEW-1018

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