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

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 47bf906 was 47bf906, checked in by krzywon, 5 years ago

Updates to P(r) perspective to properly switch between loaded data sets.

  • Property mode set to 100644
File size: 25.8 KB
Line 
1import sys
2import logging
3import pylab
4import numpy as np
5
6from PyQt5 import QtGui, QtCore, QtWidgets
7
8# sas-global
9import sas.qtgui.Utilities.GuiUtils as GuiUtils
10
11# pr inversion GUI elements
12from .InversionUtils import WIDGETS
13from .UI.TabbedInversionUI import Ui_PrInversion
14from .InversionLogic import InversionLogic
15
16# pr inversion calculation elements
17from sas.sascalc.dataloader.data_info import Data1D
18from sas.sascalc.pr.invertor import Invertor
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
27NUMBER_OF_TERMS = 10
28REGULARIZATION = 0.0001
29BACKGROUND_INPUT = 0.0
30MAX_DIST = 140.0
31DICT_KEYS = ["Calculator", "PrPlot", "DataPlot", "DMaxWindow",
32             "Logic", "NFunc", "Estimates"]
33ESTIMATE_KEYS = ["nFunc", "??????", "Background"]
34
35
36# TODO: Modify plot references, don't just send new
37# TODO: Update help with batch capabilities
38# TODO: Method to export results in some meaningful way
39class InversionWindow(QtWidgets.QDialog, Ui_PrInversion):
40    """
41    The main window for the P(r) Inversion perspective.
42    """
43
44    name = "Inversion"
45    estimateSignal = QtCore.pyqtSignal(tuple)
46    estimateNTSignal = QtCore.pyqtSignal(tuple)
47    calculateSignal = QtCore.pyqtSignal(tuple)
48
49    def __init__(self, parent=None, data=None):
50        super(InversionWindow, self).__init__()
51        self.setupUi(self)
52
53        self.setWindowTitle("P(r) Inversion Perspective")
54
55        self._manager = parent
56        self.communicate = GuiUtils.Communicate()
57
58        self.logic = InversionLogic()
59
60        # The window should not close
61        self._allow_close = False
62
63        # Visible data set items
64        # current QStandardItem showing on the panel
65        self._data = None
66        # current Data1D as referenced by self._data
67        self._data_set = None
68        # Reference to Dmax window for self._data
69        self.dmaxWindow = None
70        # p(r) calculator for self._data
71        self._calculator = Invertor()
72        # Combo box index for self._data
73        self._data_index = 0
74        # plots of self._data
75        self.pr_plot = None
76        self.data_plot = None
77
78        # Calculation threads used by all data items
79        self.calc_thread = None
80        self.estimation_thread = None
81
82        # Mapping for all data items
83        # TODO: {QStandardItem -> {params: [], plot: Plot, dmax: dMax,
84        # TODO: calculator: Invertor(), estimates: {}, data: Data1D, ...}
85        # list mapping data to all parameters
86        self._data_list = {}
87        if not isinstance(data, list):
88            data_list = [data]
89        if data is not None:
90            for datum in data_list:
91                self._data_list[datum] = {DICT_KEYS[0]: self._calculator.clone(),
92                                          DICT_KEYS[4]: self.logic,
93                                          DICT_KEYS[5]: NUMBER_OF_TERMS,
94                                          DICT_KEYS[6]: {}}
95
96        self.calculateAllButton.setEnabled(False)
97        self.calculateThisButton.setEnabled(False)
98
99        self.model = QtGui.QStandardItemModel(self)
100        self.mapper = QtWidgets.QDataWidgetMapper(self)
101
102        # Add validators
103        self.setupValidators()
104        # Link user interactions with methods
105        self.setupLinks()
106        # Set values
107        self.setupModel()
108        # Set up the Widget Map
109        self.setupMapper()
110        # Set base window state
111        self.setupWindow()
112
113    ######################################################################
114    # Base Perspective Class Definitions
115
116    def communicator(self):
117        return self.communicate
118
119    def allowBatch(self):
120        return True
121
122    def setClosable(self, value=True):
123        """
124        Allow outsiders close this widget
125        """
126        assert isinstance(value, bool)
127        self._allow_close = value
128
129    def closeEvent(self, event):
130        """
131        Overwrite QDialog close method to allow for custom widget close
132        """
133        if self._allow_close:
134            # reset the closability flag
135            self.setClosable(value=False)
136            # Tell the MdiArea to close the container
137            self.parentWidget().close()
138            event.accept()
139        else:
140            event.ignore()
141            # Maybe we should just minimize
142            self.setWindowState(QtCore.Qt.WindowMinimized)
143
144    ######################################################################
145    # Initialization routines
146
147    def setupLinks(self):
148        """Connect the use controls to their appropriate methods"""
149        self.dataList.currentIndexChanged.connect(self.displayChange)
150        self.calculateAllButton.clicked.connect(self.startThreadAll)
151        self.calculateThisButton.clicked.connect(self.startThread)
152        self.removeButton.clicked.connect(self.removeData)
153        self.helpButton.clicked.connect(self.help)
154        self.estimateBgd.toggled.connect(self.toggleBgd)
155        self.manualBgd.toggled.connect(self.toggleBgd)
156        self.regConstantSuggestionButton.clicked.connect(self.acceptAlpha)
157        self.noOfTermsSuggestionButton.clicked.connect(self.acceptNoTerms)
158        self.explorerButton.clicked.connect(self.openExplorerWindow)
159
160        self.backgroundInput.editingFinished.connect(
161            lambda: self._calculator.set_est_bck(is_float(self.backgroundInput.text())))
162        self.minQInput.editingFinished.connect(
163            lambda: self._calculator.set_qmin(is_float(self.minQInput.text())))
164        self.regularizationConstantInput.editingFinished.connect(
165            lambda: self._calculator.set_alpha(is_float(self.regularizationConstantInput.text())))
166        self.maxDistanceInput.editingFinished.connect(
167            lambda: self._calculator.set_dmax(is_float(self.maxDistanceInput.text())))
168        self.maxQInput.editingFinished.connect(
169            lambda: self._calculator.set_qmax(is_float(self.maxQInput.text())))
170        self.slitHeightInput.editingFinished.connect(
171            lambda: self._calculator.set_slit_height(is_float(self.slitHeightInput.text())))
172        self.slitWidthInput.editingFinished.connect(
173            lambda: self._calculator.set_slit_width(is_float(self.slitHeightInput.text())))
174
175        self.model.itemChanged.connect(self.model_changed)
176        self.estimateNTSignal.connect(self._estimateNTUpdate)
177        self.estimateSignal.connect(self._estimateUpdate)
178        self.calculateSignal.connect(self._calculateUpdate)
179
180    def setupMapper(self):
181        # Set up the mapper.
182        self.mapper.setOrientation(QtCore.Qt.Vertical)
183        self.mapper.setModel(self.model)
184
185        # Filename
186        self.mapper.addMapping(self.dataList, WIDGETS.W_FILENAME)
187        # Background
188        self.mapper.addMapping(self.backgroundInput, WIDGETS.W_BACKGROUND_INPUT)
189        self.mapper.addMapping(self.estimateBgd, WIDGETS.W_ESTIMATE)
190        self.mapper.addMapping(self.manualBgd, WIDGETS.W_MANUAL_INPUT)
191
192        # Qmin/Qmax
193        self.mapper.addMapping(self.minQInput, WIDGETS.W_QMIN)
194        self.mapper.addMapping(self.maxQInput, WIDGETS.W_QMAX)
195
196        # Slit Parameter items
197        self.mapper.addMapping(self.slitWidthInput, WIDGETS.W_SLIT_WIDTH)
198        self.mapper.addMapping(self.slitHeightInput, WIDGETS.W_SLIT_HEIGHT)
199
200        # Parameter Items
201        self.mapper.addMapping(self.regularizationConstantInput, WIDGETS.W_REGULARIZATION)
202        self.mapper.addMapping(self.regConstantSuggestionButton, WIDGETS.W_REGULARIZATION_SUGGEST)
203        self.mapper.addMapping(self.explorerButton, WIDGETS.W_EXPLORE)
204        self.mapper.addMapping(self.maxDistanceInput, WIDGETS.W_MAX_DIST)
205        self.mapper.addMapping(self.noOfTermsInput, WIDGETS.W_NO_TERMS)
206        self.mapper.addMapping(self.noOfTermsSuggestionButton, WIDGETS.W_NO_TERMS_SUGGEST)
207
208        # Output
209        self.mapper.addMapping(self.rgValue, WIDGETS.W_RG)
210        self.mapper.addMapping(self.iQ0Value, WIDGETS.W_I_ZERO)
211        self.mapper.addMapping(self.backgroundValue, WIDGETS.W_BACKGROUND_OUTPUT)
212        self.mapper.addMapping(self.computationTimeValue, WIDGETS.W_COMP_TIME)
213        self.mapper.addMapping(self.chiDofValue, WIDGETS.W_CHI_SQUARED)
214        self.mapper.addMapping(self.oscillationValue, WIDGETS.W_OSCILLATION)
215        self.mapper.addMapping(self.posFractionValue, WIDGETS.W_POS_FRACTION)
216        self.mapper.addMapping(self.sigmaPosFractionValue, WIDGETS.W_SIGMA_POS_FRACTION)
217
218        # Main Buttons
219        self.mapper.addMapping(self.removeButton, WIDGETS.W_REMOVE)
220        self.mapper.addMapping(self.calculateAllButton, WIDGETS.W_CALCULATE_ALL)
221        self.mapper.addMapping(self.calculateThisButton, WIDGETS.W_CALCULATE_VISIBLE)
222        self.mapper.addMapping(self.helpButton, WIDGETS.W_HELP)
223
224        self.mapper.toFirst()
225
226    def setupModel(self):
227        """
228        Update boxes with initial values
229        """
230        item = QtGui.QStandardItem("")
231        self.model.setItem(WIDGETS.W_FILENAME, item)
232        item = QtGui.QStandardItem(str(BACKGROUND_INPUT))
233        self.model.setItem(WIDGETS.W_BACKGROUND_INPUT, item)
234        item = QtGui.QStandardItem("")
235        self.model.setItem(WIDGETS.W_QMIN, item)
236        item = QtGui.QStandardItem("")
237        self.model.setItem(WIDGETS.W_QMAX, item)
238        item = QtGui.QStandardItem("")
239        self.model.setItem(WIDGETS.W_SLIT_WIDTH, item)
240        item = QtGui.QStandardItem("")
241        self.model.setItem(WIDGETS.W_SLIT_HEIGHT, item)
242        item = QtGui.QStandardItem(str(NUMBER_OF_TERMS))
243        self.model.setItem(WIDGETS.W_NO_TERMS, item)
244        item = QtGui.QStandardItem(str(REGULARIZATION))
245        self.model.setItem(WIDGETS.W_REGULARIZATION, item)
246        item = QtGui.QStandardItem(str(MAX_DIST))
247        self.model.setItem(WIDGETS.W_MAX_DIST, item)
248        item = QtGui.QStandardItem("")
249        self.model.setItem(WIDGETS.W_RG, item)
250        item = QtGui.QStandardItem("")
251        self.model.setItem(WIDGETS.W_I_ZERO, item)
252        item = QtGui.QStandardItem("")
253        self.model.setItem(WIDGETS.W_BACKGROUND_OUTPUT, item)
254        item = QtGui.QStandardItem("")
255        self.model.setItem(WIDGETS.W_COMP_TIME, item)
256        item = QtGui.QStandardItem("")
257        self.model.setItem(WIDGETS.W_CHI_SQUARED, item)
258        item = QtGui.QStandardItem("")
259        self.model.setItem(WIDGETS.W_OSCILLATION, item)
260        item = QtGui.QStandardItem("")
261        self.model.setItem(WIDGETS.W_POS_FRACTION, item)
262        item = QtGui.QStandardItem("")
263        self.model.setItem(WIDGETS.W_SIGMA_POS_FRACTION, item)
264
265    def setupWindow(self):
266        """Initialize base window state on init"""
267        self.enableButtons()
268        self.estimateBgd.setChecked(True)
269
270    def setupValidators(self):
271        """Apply validators to editable line edits"""
272        self.noOfTermsInput.setValidator(QtGui.QIntValidator())
273        self.regularizationConstantInput.setValidator(GuiUtils.DoubleValidator())
274        self.maxDistanceInput.setValidator(GuiUtils.DoubleValidator())
275        self.minQInput.setValidator(GuiUtils.DoubleValidator())
276        self.maxQInput.setValidator(GuiUtils.DoubleValidator())
277        self.slitHeightInput.setValidator(GuiUtils.DoubleValidator())
278        self.slitWidthInput.setValidator(GuiUtils.DoubleValidator())
279
280    ######################################################################
281    # Methods for updating GUI
282
283    def enableButtons(self):
284        """
285        Enable buttons when data is present, else disable them
286        """
287        self.calculateAllButton.setEnabled(self.logic.data_is_loaded)
288        self.calculateThisButton.setEnabled(self.logic.data_is_loaded)
289        self.removeButton.setEnabled(self.logic.data_is_loaded)
290        self.explorerButton.setEnabled(self.logic.data_is_loaded)
291
292    def populateDataComboBox(self, filename, data_ref):
293        """
294        Append a new file name to the data combobox
295        :param filename: data filename
296        :param data_ref: QStandardItem reference for data set to be added
297        """
298        self.dataList.addItem(filename, data_ref)
299
300    def acceptNoTerms(self):
301        """Send estimated no of terms to input"""
302        self.model.setItem(WIDGETS.W_NO_TERMS, QtGui.QStandardItem(
303            self.noOfTermsSuggestionButton.text()))
304
305    def acceptAlpha(self):
306        """Send estimated alpha to input"""
307        self.model.setItem(WIDGETS.W_REGULARIZATION, QtGui.QStandardItem(
308            self.regConstantSuggestionButton.text()))
309
310    def displayChange(self):
311        """Switch to another item in the data list"""
312        ref_item = self.dataList.itemData(self.dataList.currentIndex())
313        self.updateDataList(self._data)
314        self.setCurrentData(ref_item)
315
316    ######################################################################
317    # GUI Interaction Events
318
319    def update_calculator(self):
320        """Update all p(r) params"""
321        self._calculator.set_x(self._data_set.x)
322        self._calculator.set_y(self._data_set.y)
323        self._calculator.set_err(self._data_set.dy)
324
325    def model_changed(self):
326        """Update the values when user makes changes"""
327        if not self.mapper:
328            msg = "Unable to update P{r}. The connection between the main GUI "
329            msg += "and P(r) was severed. Attempting to restart P(r)."
330            logging.warning(msg)
331            self.setClosable(True)
332            self.close()
333            InversionWindow.__init__(self.parent(), list(self._data_list.keys()))
334            exit(0)
335        if self.pr_plot is not None:
336            title = self.pr_plot.name
337            GuiUtils.updateModelItemWithPlot(self._data, self.pr_plot, title)
338        if self.data_plot is not None:
339            title = self.data_plot.name
340            GuiUtils.updateModelItemWithPlot(self._data, self.data_plot, title)
341        if self.dmaxWindow is not None:
342            self.dmaxWindow.pr_state = self._calculator
343            self.dmaxWindow.nfunc = self.getNFunc()
344            self.dmaxWindow.modelChanged()
345        self.mapper.toFirst()
346
347    def help(self):
348        """
349        Open the P(r) Inversion help browser
350        """
351        tree_location = "/user/sasgui/perspectives/pr/pr_help.html"
352
353        # Actual file anchor will depend on the combo box index
354        # Note that we can be clusmy here, since bad current_fitter_id
355        # will just make the page displayed from the top
356        self._manager.showHelp(tree_location)
357
358    def toggleBgd(self):
359        """
360        Toggle the background between manual and estimated
361        """
362        sender = self.sender()
363        if sender is self.estimateBgd:
364            self.backgroundInput.setEnabled(False)
365        else:
366            self.backgroundInput.setEnabled(True)
367
368    def openExplorerWindow(self):
369        """
370        Open the Explorer window to see correlations between params and results
371        """
372        from .DMaxExplorerWidget import DmaxWindow
373        self.dmaxWindow = DmaxWindow(self._calculator, self.getNFunc(), self)
374        self.dmaxWindow.show()
375
376    ######################################################################
377    # Response Actions
378
379    def setData(self, data_item=None, is_batch=False):
380        """
381        Assign new data set(s) to the P(r) perspective
382        Obtain a QStandardItem object and parse it to get Data1D/2D
383        Pass it over to the calculator
384        """
385        assert data_item is not None
386
387        if not isinstance(data_item, list):
388            msg = "Incorrect type passed to the P(r) Perspective"
389            raise AttributeError(msg)
390
391        for data in data_item:
392            if data in self._data_list.keys():
393                # Don't add data if it's already in
394                return
395            # Create initial internal mappings
396            self._data_set = GuiUtils.dataFromItem(data)
397            self.logic = InversionLogic(self._data_set)
398            self.populateDataComboBox(self._data_set.filename, data)
399            self.setCurrentData(data)
400
401            # Estimate initial values from data
402            self.performEstimate()
403
404            # Estimate q range
405            qmin, qmax = self.logic.computeDataRange()
406            self.model.setItem(WIDGETS.W_QMIN, QtGui.QStandardItem("{:.4g}".format(qmin)))
407            self.model.setItem(WIDGETS.W_QMAX, QtGui.QStandardItem("{:.4g}".format(qmax)))
408            self._data_list[data] = {DICT_KEYS[0]: self._calculator.clone(),
409                                     DICT_KEYS[1]: self.data_plot,
410                                     DICT_KEYS[2]: self.pr_plot,
411                                     DICT_KEYS[4]: self.logic}
412        self.enableButtons()
413
414    def updateDataList(self, dataRef):
415        """Save the current data state of the window into self._data_list"""
416        self._data_list[dataRef] = {
417        DICT_KEYS[0]: self._calculator,
418        DICT_KEYS[1]: self.pr_plot,
419        DICT_KEYS[2]: self.data_plot,
420        DICT_KEYS[3]: self.dmaxWindow
421        }
422
423    def getNFunc(self):
424        """Get the n_func value from the GUI object"""
425        try:
426            nfunc = int(self.noOfTermsInput.text())
427        except ValueError:
428            logging.error("Incorrect number of terms specified: %s" %self.noOfTermsInput.text())
429            self.noOfTermsInput.setText(str(NUMBER_OF_TERMS))
430            nfunc = NUMBER_OF_TERMS
431        return nfunc
432
433    def setCurrentData(self, data_ref):
434        """Get the data by reference and display as necessary"""
435        if data_ref is None:
436            return
437        if not isinstance(data_ref, QtGui.QStandardItem):
438            msg = "Incorrect type passed to the P(r) Perspective"
439            raise AttributeError
440        # Data references
441        self._data = data_ref
442        self._data_set = GuiUtils.dataFromItem(data_ref)
443        self._calculator = self._data_list[data_ref].get(DICT_KEYS[0])
444        self.pr_plot = self._data_list[data_ref].get(DICT_KEYS[1])
445        self.data_plot = self._data_list[data_ref].get(DICT_KEYS[2])
446        self.dmaxWindow = self._data_list[data_ref].get(DICT_KEYS[3])
447        self.logic = self._data_list[data_ref].get(DICT_KEYS[4])
448        # TODO: Do the values need to be updated when _calculator is changed?
449
450    def removeData(self):
451        """Remove the existing data reference from the P(r) Persepective"""
452        if self.dmaxWindow is not None:
453            self.dmaxWindow = None
454        self.dataList.removeItem(self.dataList.currentIndex())
455        # TODO: Remove plot references from higher level too?
456        self.dataList.setCurrentIndex(0)
457        # Last file removed
458        self._data_list.pop(self._data)
459        if not self._data_list:
460            self._data = None
461            self.pr_plot = None
462            self._data_set = None
463            self.logic = InversionLogic()
464            self.enableButtons()
465        self.displayChange()
466
467    ######################################################################
468    # Thread Creators
469    def startThreadAll(self):
470        for data_ref, pr in list(self._data_list.items()):
471            self._data_set = GuiUtils.dataFromItem(data_ref)
472            self._calculator = pr
473            self.startThread()
474
475    def startThread(self):
476        """
477            Start a calculation thread
478        """
479        from .Thread import CalcPr
480
481        # Set data before running the calculations
482        self.update_calculator()
483
484        # If a thread is already started, stop it
485        if self.calc_thread is not None and self.calc_thread.isrunning():
486            self.calc_thread.stop()
487        pr = self._calculator.clone()
488        nfunc = self.getNFunc()
489        self.calc_thread = CalcPr(pr, nfunc,
490                                  error_func=self._threadError,
491                                  completefn=self._calculateCompleted,
492                                  updatefn=None)
493        self.calc_thread.queue()
494        self.calc_thread.ready(2.5)
495
496    def performEstimateNT(self):
497        """
498        Perform parameter estimation
499        """
500        from .Thread import EstimateNT
501
502        # If a thread is already started, stop it
503        if (self.estimation_thread is not None and
504                self.estimation_thread.isrunning()):
505            self.estimation_thread.stop()
506        pr = self._calculator.clone()
507        # Skip the slit settings for the estimation
508        # It slows down the application and it doesn't change the estimates
509        pr.slit_height = 0.0
510        pr.slit_width = 0.0
511        nfunc = self.getNFunc()
512
513        self.estimation_thread = EstimateNT(pr, nfunc,
514                                            error_func=self._threadError,
515                                            completefn=self._estimateNTCompleted,
516                                            updatefn=None)
517        self.estimation_thread.queue()
518        self.estimation_thread.ready(2.5)
519
520    def performEstimate(self):
521        """
522            Perform parameter estimation
523        """
524        from .Thread import EstimatePr
525
526        self.startThread()
527
528        # If a thread is already started, stop it
529        if (self.estimation_thread is not None and
530                self.estimation_thread.isrunning()):
531            self.estimation_thread.stop()
532        pr = self._calculator.clone()
533        nfunc = self.getNFunc()
534        self.estimation_thread = EstimatePr(pr, nfunc,
535                                            error_func=self._threadError,
536                                            completefn=self._estimateCompleted,
537                                            updatefn=None)
538        self.estimation_thread.queue()
539        self.estimation_thread.ready(2.5)
540
541    ######################################################################
542    # Thread Complete
543
544    def _estimateCompleted(self, alpha, message, elapsed):
545        ''' Send a signal to the main thread for model update'''
546        self.estimateSignal.emit((alpha, message, elapsed))
547
548    def _estimateUpdate(self, output_tuple):
549        """
550        Parameter estimation completed,
551        display the results to the user
552
553        :param alpha: estimated best alpha
554        :param elapsed: computation time
555        """
556        alpha, message, elapsed = output_tuple
557        # Save useful info
558        self.model.setItem(WIDGETS.W_COMP_TIME, QtGui.QStandardItem("{:.4g}".format(elapsed)))
559        self.regConstantSuggestionButton.setText("{:-3.2g}".format(alpha))
560        self.regConstantSuggestionButton.setEnabled(True)
561        if message:
562            logging.info(message)
563        self.performEstimateNT()
564
565    def _estimateNTCompleted(self, nterms, alpha, message, elapsed):
566        ''' Send a signal to the main thread for model update'''
567        self.estimateNTSignal.emit((nterms, alpha, message, elapsed))
568
569    def _estimateNTUpdate(self, output_tuple):
570        """
571        Parameter estimation completed,
572        display the results to the user
573
574        :param alpha: estimated best alpha
575        :param nterms: estimated number of terms
576        :param elapsed: computation time
577        """
578        # TODO: Add estimates to DICT_KEYS
579        nterms, alpha, message, elapsed = output_tuple
580        # Save useful info
581        self.noOfTermsSuggestionButton.setText("{:n}".format(nterms))
582        self.noOfTermsSuggestionButton.setEnabled(True)
583        self.regConstantSuggestionButton.setText("{:.3g}".format(alpha))
584        self.regConstantSuggestionButton.setEnabled(True)
585        self.model.setItem(WIDGETS.W_COMP_TIME, QtGui.QStandardItem("{:.2g}".format(elapsed)))
586        if message:
587            logging.info(message)
588
589    def _calculateCompleted(self, out, cov, pr, elapsed):
590        ''' Send a signal to the main thread for model update'''
591        self.calculateSignal.emit((out, cov, pr, elapsed))
592
593    def _calculateUpdate(self, output_tuple):
594        """
595        Method called with the results when the inversion is done
596
597        :param out: output coefficient for the base functions
598        :param cov: covariance matrix
599        :param pr: Invertor instance
600        :param elapsed: time spent computing
601        """
602        out, cov, pr, elapsed = output_tuple
603        # Save useful info
604        cov = np.ascontiguousarray(cov)
605        pr.cov = cov
606        pr.out = out
607        pr.elapsed = elapsed
608
609        # Show result on control panel
610        self.model.setItem(WIDGETS.W_RG, QtGui.QStandardItem("{:.3g}".format(pr.rg(out))))
611        self.model.setItem(WIDGETS.W_I_ZERO, QtGui.QStandardItem("{:.3g}".format(pr.iq0(out))))
612        self.model.setItem(WIDGETS.W_BACKGROUND_INPUT,
613                           QtGui.QStandardItem("{:.3f}".format(pr.est_bck)))
614        self.model.setItem(WIDGETS.W_BACKGROUND_OUTPUT, QtGui.QStandardItem("{:.3g}".format(pr.background)))
615        self.model.setItem(WIDGETS.W_CHI_SQUARED, QtGui.QStandardItem("{:.3g}".format(pr.chi2[0])))
616        self.model.setItem(WIDGETS.W_COMP_TIME, QtGui.QStandardItem("{:.2g}".format(elapsed)))
617        self.model.setItem(WIDGETS.W_OSCILLATION, QtGui.QStandardItem("{:.3g}".format(pr.oscillations(out))))
618        self.model.setItem(WIDGETS.W_POS_FRACTION, QtGui.QStandardItem("{:.3g}".format(pr.get_positive(out))))
619        self.model.setItem(WIDGETS.W_SIGMA_POS_FRACTION,
620                           QtGui.QStandardItem("{:.3g}".format(pr.get_pos_err(out, cov))))
621
622        # Save Pr invertor
623        self._calculator = pr
624        # Append data to data list
625        self._data_list[self._data][DICT_KEYS[0]] = self._calculator.clone()
626
627        # Create new P(r) and fit plots
628        if self.pr_plot is None:
629            self.pr_plot = self.logic.newPRPlot(out, self._calculator, cov)
630            self._data_list[self._data][DICT_KEYS[1]] = self.pr_plot
631        else:
632            # FIXME: this should update the existing plot, not create a new one
633            self.pr_plot = self.logic.newPRPlot(out, self._calculator, cov)
634            self._data_list[self._data][DICT_KEYS[1]] = self.pr_plot
635        if self.data_plot is None:
636            self.data_plot = self.logic.new1DPlot(out, self._calculator)
637            self._data_list[self._data][DICT_KEYS[2]] = self.data_plot
638        else:
639            # FIXME: this should update the existing plot, not create a new one
640            self.data_plot = self.logic.new1DPlot(out, self._calculator)
641            self._data_list[self._data][DICT_KEYS[2]] = self.data_plot
642
643    def _threadError(self, error):
644        """
645            Call-back method for calculation errors
646        """
647        logging.warning(error)
Note: See TracBrowser for help on using the repository browser.