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

ESS_GUIESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 855e7ad was 855e7ad, checked in by Piotr Rozyczko <rozyczko@…>, 13 months ago

Visibility of P® and I(Q) charts for inversion SASVIEW-995

  • Property mode set to 100644
File size: 30.6 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        if self.dataPlot is not None:
550            title = self.dataPlot.name
551            self.dataPlot.plot_role = Data1D.ROLE_DEFAULT
552            GuiUtils.updateModelItemWithPlot(self._data, self.dataPlot, title)
553        if self.dataPlot is not None or self.prPlot is not None:
554            self.communicate.plotRequestedSignal.emit([self.logic.data], None)
555        self.enableButtons()
556
557    def removeData(self, data_list=None):
558        """Remove the existing data reference from the P(r) Persepective"""
559        self.dataDeleted = True
560        self.batchResults = {}
561        if not data_list:
562            data_list = [self._data]
563        self.closeDMax()
564        for data in data_list:
565            self._dataList.pop(data)
566        self._data = None
567        length = len(self.dataList)
568        for index in reversed(range(length)):
569            if self.dataList.itemData(index) in data_list:
570                self.dataList.removeItem(index)
571        # Last file removed
572        self.dataDeleted = False
573        if len(self._dataList) == 0:
574            self.prPlot = None
575            self.dataPlot = None
576            self.logic.data = None
577            self._calculator = Invertor()
578            self.closeBatchResults()
579            self.nTermsSuggested = NUMBER_OF_TERMS
580            self.noOfTermsSuggestionButton.setText("{:n}".format(
581                self.nTermsSuggested))
582            self.regConstantSuggestionButton.setText("{:-3.2g}".format(
583                REGULARIZATION))
584            self.updateGuiValues()
585            self.setupModel()
586        else:
587            self.dataList.setCurrentIndex(0)
588            self.updateGuiValues()
589
590    ######################################################################
591    # Thread Creators
592
593    def startThreadAll(self):
594        self.isCalculating = True
595        self.isBatch = True
596        self.batchComplete = []
597        self.calculateAllButton.setText("Calculating...")
598        self.enableButtons()
599        self.batchResultsWindow = BatchInversionOutputPanel(
600            parent=self, output_data=self.batchResults)
601        self.performEstimate()
602
603    def startNextBatchItem(self):
604        self.isBatch = False
605        for index in range(len(self._dataList)):
606            if index not in self.batchComplete:
607                self.dataList.setCurrentIndex(index)
608                self.isBatch = True
609                # Add the index before calculating in case calculation fails
610                self.batchComplete.append(index)
611                break
612        if self.isBatch:
613            self.performEstimate()
614        else:
615            # If no data sets left, end batch calculation
616            self.isCalculating = False
617            self.batchComplete = []
618            self.calculateAllButton.setText("Calculate All")
619            self.showBatchOutput()
620            self.enableButtons()
621
622    def startThread(self):
623        """
624            Start a calculation thread
625        """
626        from .Thread import CalcPr
627
628        # Set data before running the calculations
629        self.isCalculating = True
630        self.enableButtons()
631        self.updateCalculator()
632        # Disable calculation buttons to prevent thread interference
633
634        # If the thread is already started, stop it
635        self.stopCalcThread()
636
637        pr = self._calculator.clone()
638        nfunc = self.getNFunc()
639        self.calcThread = CalcPr(pr, nfunc,
640                                 error_func=self._threadError,
641                                 completefn=self._calculateCompleted,
642                                 updatefn=None)
643        self.calcThread.queue()
644        self.calcThread.ready(2.5)
645
646    def stopCalcThread(self):
647        """ Stops a thread if it exists and is running """
648        if self.calcThread is not None and self.calcThread.isrunning():
649            self.calcThread.stop()
650
651    def performEstimateNT(self):
652        """
653        Perform parameter estimation
654        """
655        from .Thread import EstimateNT
656
657        self.updateCalculator()
658
659        # If a thread is already started, stop it
660        self.stopEstimateNTThread()
661
662        pr = self._calculator.clone()
663        # Skip the slit settings for the estimation
664        # It slows down the application and it doesn't change the estimates
665        pr.slit_height = 0.0
666        pr.slit_width = 0.0
667        nfunc = self.getNFunc()
668
669        self.estimationThreadNT = EstimateNT(pr, nfunc,
670                                             error_func=self._threadError,
671                                             completefn=self._estimateNTCompleted,
672                                             updatefn=None)
673        self.estimationThreadNT.queue()
674        self.estimationThreadNT.ready(2.5)
675
676    def stopEstimateNTThread(self):
677        if (self.estimationThreadNT is not None and
678                self.estimationThreadNT.isrunning()):
679            self.estimationThreadNT.stop()
680
681    def performEstimate(self):
682        """
683            Perform parameter estimation
684        """
685        from .Thread import EstimatePr
686
687        # If a thread is already started, stop it
688        self.stopEstimationThread()
689
690        self.estimationThread = EstimatePr(self._calculator.clone(),
691                                           self.getNFunc(),
692                                           error_func=self._threadError,
693                                           completefn=self._estimateCompleted,
694                                           updatefn=None)
695        self.estimationThread.queue()
696        self.estimationThread.ready(2.5)
697
698    def stopEstimationThread(self):
699        """ Stop the estimation thread if it exists and is running """
700        if (self.estimationThread is not None and
701                self.estimationThread.isrunning()):
702            self.estimationThread.stop()
703
704    ######################################################################
705    # Thread Complete
706
707    def _estimateCompleted(self, alpha, message, elapsed):
708        ''' Send a signal to the main thread for model update'''
709        self.estimateSignal.emit((alpha, message, elapsed))
710
711    def _estimateUpdate(self, output_tuple):
712        """
713        Parameter estimation completed,
714        display the results to the user
715
716        :param alpha: estimated best alpha
717        :param elapsed: computation time
718        """
719        alpha, message, elapsed = output_tuple
720        self._calculator.alpha = alpha
721        self._calculator.elapsed += self._calculator.elapsed
722        if message:
723            logger.info(message)
724        self.performEstimateNT()
725
726    def _estimateNTCompleted(self, nterms, alpha, message, elapsed):
727        ''' Send a signal to the main thread for model update'''
728        self.estimateNTSignal.emit((nterms, alpha, message, elapsed))
729
730    def _estimateNTUpdate(self, output_tuple):
731        """
732        Parameter estimation completed,
733        display the results to the user
734
735        :param alpha: estimated best alpha
736        :param nterms: estimated number of terms
737        :param elapsed: computation time
738        """
739        nterms, alpha, message, elapsed = output_tuple
740        self._calculator.elapsed += elapsed
741        self._calculator.suggested_alpha = alpha
742        self.nTermsSuggested = nterms
743        # Save useful info
744        self.updateGuiValues()
745        if message:
746            logger.info(message)
747        if self.isBatch:
748            self.acceptAlpha()
749            self.acceptNoTerms()
750            self.startThread()
751
752    def _calculateCompleted(self, out, cov, pr, elapsed):
753        ''' Send a signal to the main thread for model update'''
754        self.calculateSignal.emit((out, cov, pr, elapsed))
755
756    def _calculateUpdate(self, output_tuple):
757        """
758        Method called with the results when the inversion is done
759
760        :param out: output coefficient for the base functions
761        :param cov: covariance matrix
762        :param pr: Invertor instance
763        :param elapsed: time spent computing
764        """
765        out, cov, pr, elapsed = output_tuple
766        # Save useful info
767        cov = np.ascontiguousarray(cov)
768        pr.cov = cov
769        pr.out = out
770        pr.elapsed = elapsed
771
772        # Save Pr invertor
773        self._calculator = pr
774
775        # Update P(r) and fit plots
776        self.prPlot = self.logic.newPRPlot(out, self._calculator, cov)
777        self.prPlot.filename = self.logic.data.filename
778        self.dataPlot = self.logic.new1DPlot(out, self._calculator)
779        self.dataPlot.filename = self.logic.data.filename
780
781        # Udpate internals and GUI
782        self.updateDataList(self._data)
783        if self.isBatch:
784            self.batchComplete.append(self.dataList.currentIndex())
785            self.startNextBatchItem()
786        else:
787            self.isCalculating = False
788        self.updateGuiValues()
789
790    def _threadError(self, error):
791        """
792            Call-back method for calculation errors
793        """
794        logger.error(error)
795        if self.isBatch:
796            self.startNextBatchItem()
797        else:
798            self.stopCalculation()
Note: See TracBrowser for help on using the repository browser.