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

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 c972e3a was 3c6ecd9, checked in by Piotr Rozyczko <rozyczko@…>, 7 years ago

Merge branch 'ESS_GUI' into ESS_GUI_Pr

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