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

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 6da860a was 6da860a, checked in by krzywon, 6 years ago

Responding to P(r) code review.

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