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

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 72ecbdf2 was 72ecbdf2, checked in by krzywon, 4 years ago

Add a stop calculations button to P(r). Plus unit tests.

  • Property mode set to 100644
File size: 30.0 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        self.stopButton.setVisible(self.isCalculating)
313        self.regConstantSuggestionButton.setEnabled(
314            self.logic.data_is_loaded and
315            self._calculator.suggested_alpha != self._calculator.alpha)
316        self.noOfTermsSuggestionButton.setEnabled(
317            self.logic.data_is_loaded and
318            self._calculator.nfunc != self.nTermsSuggested)
319
320    def populateDataComboBox(self, filename, data_ref):
321        """
322        Append a new file name to the data combobox
323        :param filename: data filename
324        :param data_ref: QStandardItem reference for data set to be added
325        """
326        self.dataList.addItem(filename, data_ref)
327
328    def acceptNoTerms(self):
329        """Send estimated no of terms to input"""
330        self.model.setItem(WIDGETS.W_NO_TERMS, QtGui.QStandardItem(
331            self.noOfTermsSuggestionButton.text()))
332
333    def acceptAlpha(self):
334        """Send estimated alpha to input"""
335        self.model.setItem(WIDGETS.W_REGULARIZATION, QtGui.QStandardItem(
336            self.regConstantSuggestionButton.text()))
337
338    def displayChange(self, data_index=0):
339        """Switch to another item in the data list"""
340        if self.dataDeleted:
341            return
342        self.updateDataList(self._data)
343        self.setCurrentData(self.dataList.itemData(data_index))
344
345    ######################################################################
346    # GUI Interaction Events
347
348    def updateCalculator(self):
349        """Update all p(r) params"""
350        self._calculator.set_x(self.logic.data.x)
351        self._calculator.set_y(self.logic.data.y)
352        self._calculator.set_err(self.logic.data.dy)
353        self.set_background(self.backgroundInput.text())
354
355    def set_background(self, value):
356        self._calculator.background = is_float(value)
357
358    def model_changed(self):
359        """Update the values when user makes changes"""
360        if not self.mapper:
361            msg = "Unable to update P{r}. The connection between the main GUI "
362            msg += "and P(r) was severed. Attempting to restart P(r)."
363            logger.warning(msg)
364            self.setClosable(True)
365            self.close()
366            InversionWindow.__init__(self.parent(), list(self._dataList.keys()))
367            exit(0)
368        if self.dmaxWindow is not None:
369            self.dmaxWindow.nfunc = self.getNFunc()
370            self.dmaxWindow.pr_state = self._calculator
371        self.mapper.toLast()
372
373    def help(self):
374        """
375        Open the P(r) Inversion help browser
376        """
377        tree_location = "/user/sasgui/perspectives/pr/pr_help.html"
378
379        # Actual file anchor will depend on the combo box index
380        # Note that we can be clusmy here, since bad current_fitter_id
381        # will just make the page displayed from the top
382        self._manager.showHelp(tree_location)
383
384    def toggleBgd(self):
385        """
386        Toggle the background between manual and estimated
387        """
388        if self.estimateBgd.isChecked():
389            self.manualBgd.setChecked(False)
390            self.backgroundInput.setEnabled(False)
391            self._calculator.set_est_bck = True
392        elif self.manualBgd.isChecked():
393            self.estimateBgd.setChecked(False)
394            self.backgroundInput.setEnabled(True)
395            self._calculator.set_est_bck = False
396        else:
397            pass
398
399    def openExplorerWindow(self):
400        """
401        Open the Explorer window to see correlations between params and results
402        """
403        from .DMaxExplorerWidget import DmaxWindow
404        self.dmaxWindow = DmaxWindow(pr_state=self._calculator,
405                                     nfunc=self.getNFunc(),
406                                     parent=self)
407        self.dmaxWindow.show()
408
409    def showBatchOutput(self):
410        """
411        Display the batch output in tabular form
412        :param output_data: Dictionary mapping filename -> P(r) instance
413        """
414        if self.batchResultsWindow is None:
415            self.batchResultsWindow = BatchInversionOutputPanel(
416                parent=self, output_data=self.batchResults)
417        else:
418            self.batchResultsWindow.setupTable(self.batchResults)
419        self.batchResultsWindow.show()
420
421    def stopCalculation(self):
422        """ Stop all threads, return to the base state and update GUI """
423        if self.calcThread:
424            self.calcThread.stop()
425        if self.estimationThread:
426            self.estimationThread.stop()
427        if self.estimationThreadNT:
428            self.estimationThreadNT.stop()
429        # Show any batch calculations that successfully completed
430        if self.isBatch and self.batchResultsWindow is not None:
431            self.showBatchOutput()
432        self.isBatch = False
433        self.isCalculating = False
434        self.updateGuiValues()
435
436    ######################################################################
437    # Response Actions
438
439    def setData(self, data_item=None, is_batch=False):
440        """
441        Assign new data set(s) to the P(r) perspective
442        Obtain a QStandardItem object and parse it to get Data1D/2D
443        Pass it over to the calculator
444        """
445        assert data_item is not None
446
447        if not isinstance(data_item, list):
448            msg = "Incorrect type passed to the P(r) Perspective"
449            raise AttributeError(msg)
450
451        for data in data_item:
452            if data in self._dataList.keys():
453                # Don't add data if it's already in
454                continue
455            # Create initial internal mappings
456            self.logic.data = GuiUtils.dataFromItem(data)
457            # Estimate q range
458            qmin, qmax = self.logic.computeDataRange()
459            self._calculator.set_qmin(qmin)
460            self._calculator.set_qmax(qmax)
461            self.updateDataList(data)
462            self.populateDataComboBox(self.logic.data.filename, data)
463        self.dataList.setCurrentIndex(len(self.dataList) - 1)
464        self.setCurrentData(data)
465
466    def updateDataList(self, dataRef):
467        """Save the current data state of the window into self._data_list"""
468        if dataRef is None:
469            return
470        self._dataList[dataRef] = {
471            DICT_KEYS[0]: self._calculator,
472            DICT_KEYS[1]: self.prPlot,
473            DICT_KEYS[2]: self.dataPlot
474        }
475        # Update batch results window when finished
476        self.batchResults[self.logic.data.filename] = self._calculator
477        if self.batchResultsWindow is not None:
478            self.showBatchOutput()
479
480    def getNFunc(self):
481        """Get the n_func value from the GUI object"""
482        try:
483            nfunc = int(self.noOfTermsInput.text())
484        except ValueError:
485            logger.error("Incorrect number of terms specified: %s"
486                          %self.noOfTermsInput.text())
487            self.noOfTermsInput.setText(str(NUMBER_OF_TERMS))
488            nfunc = NUMBER_OF_TERMS
489        return nfunc
490
491    def setCurrentData(self, data_ref):
492        """Get the data by reference and display as necessary"""
493        if data_ref is None:
494            return
495        if not isinstance(data_ref, QtGui.QStandardItem):
496            msg = "Incorrect type passed to the P(r) Perspective"
497            raise AttributeError(msg)
498        # Data references
499        self._data = data_ref
500        self.logic.data = GuiUtils.dataFromItem(data_ref)
501        self._calculator = self._dataList[data_ref].get(DICT_KEYS[0])
502        self.prPlot = self._dataList[data_ref].get(DICT_KEYS[1])
503        self.dataPlot = self._dataList[data_ref].get(DICT_KEYS[2])
504        self.performEstimate()
505
506    def updateGuiValues(self):
507        pr = self._calculator
508        out = self._calculator.out
509        cov = self._calculator.cov
510        elapsed = self._calculator.elapsed
511        alpha = self._calculator.suggested_alpha
512        self.model.setItem(WIDGETS.W_QMIN,
513                           QtGui.QStandardItem("{:.4g}".format(pr.get_qmin())))
514        self.model.setItem(WIDGETS.W_QMAX,
515                           QtGui.QStandardItem("{:.4g}".format(pr.get_qmax())))
516        self.model.setItem(WIDGETS.W_BACKGROUND_INPUT,
517                           QtGui.QStandardItem("{:.3g}".format(pr.background)))
518        self.model.setItem(WIDGETS.W_BACKGROUND_OUTPUT,
519                           QtGui.QStandardItem("{:.3g}".format(pr.background)))
520        self.model.setItem(WIDGETS.W_COMP_TIME,
521                           QtGui.QStandardItem("{:.4g}".format(elapsed)))
522        self.model.setItem(WIDGETS.W_MAX_DIST,
523                           QtGui.QStandardItem("{:.4g}".format(pr.get_dmax())))
524        self.regConstantSuggestionButton.setText("{:-3.2g}".format(alpha))
525        self.noOfTermsSuggestionButton.setText(
526            "{:n}".format(self.nTermsSuggested))
527
528        if isinstance(pr.chi2, np.ndarray):
529            self.model.setItem(WIDGETS.W_CHI_SQUARED,
530                               QtGui.QStandardItem("{:.3g}".format(pr.chi2[0])))
531        if out is not None:
532            self.model.setItem(WIDGETS.W_RG,
533                               QtGui.QStandardItem("{:.3g}".format(pr.rg(out))))
534            self.model.setItem(WIDGETS.W_I_ZERO,
535                               QtGui.QStandardItem(
536                                   "{:.3g}".format(pr.iq0(out))))
537            self.model.setItem(WIDGETS.W_OSCILLATION, QtGui.QStandardItem(
538                "{:.3g}".format(pr.oscillations(out))))
539            self.model.setItem(WIDGETS.W_POS_FRACTION, QtGui.QStandardItem(
540                "{:.3g}".format(pr.get_positive(out))))
541            if cov is not None:
542                self.model.setItem(WIDGETS.W_SIGMA_POS_FRACTION,
543                                   QtGui.QStandardItem(
544                                       "{:.3g}".format(
545                                           pr.get_pos_err(out, cov))))
546        if self.prPlot is not None:
547            title = self.prPlot.name
548            GuiUtils.updateModelItemWithPlot(self._data, self.prPlot, title)
549            self.communicate.plotRequestedSignal.emit([self.prPlot])
550        if self.dataPlot is not None:
551            title = self.dataPlot.name
552            GuiUtils.updateModelItemWithPlot(self._data, self.dataPlot, title)
553            self.communicate.plotRequestedSignal.emit([self.dataPlot])
554        self.enableButtons()
555
556    def removeData(self, data_list=None):
557        """Remove the existing data reference from the P(r) Persepective"""
558        self.dataDeleted = True
559        self.batchResults = {}
560        if not data_list:
561            data_list = [self._data]
562        self.closeDMax()
563        for data in data_list:
564            self._dataList.pop(data)
565        self._data = None
566        length = len(self.dataList)
567        for index in reversed(range(length)):
568            if self.dataList.itemData(index) in data_list:
569                self.dataList.removeItem(index)
570        # Last file removed
571        self.dataDeleted = False
572        if len(self._dataList) == 0:
573            self.prPlot = None
574            self.dataPlot = None
575            self.logic.data = None
576            self._calculator = Invertor()
577            self.closeBatchResults()
578            self.nTermsSuggested = NUMBER_OF_TERMS
579            self.noOfTermsSuggestionButton.setText("{:n}".format(
580                self.nTermsSuggested))
581            self.regConstantSuggestionButton.setText("{:-3.2g}".format(
582                REGULARIZATION))
583            self.updateGuiValues()
584            self.setupModel()
585        else:
586            self.dataList.setCurrentIndex(0)
587            self.updateGuiValues()
588
589    ######################################################################
590    # Thread Creators
591
592    def startThreadAll(self):
593        self.isCalculating = True
594        self.isBatch = True
595        self.batchComplete = []
596        self.calculateAllButton.setText("Calculating...")
597        self.enableButtons()
598        self.batchResultsWindow = BatchInversionOutputPanel(
599            parent=self, output_data=self.batchResults)
600        self.performEstimate()
601
602    def startNextBatchItem(self):
603        self.isBatch = False
604        for index in range(len(self._dataList)):
605            if index not in self.batchComplete:
606                self.dataList.setCurrentIndex(index)
607                self.isBatch = True
608                # Add the index before calculating in case calculation fails
609                self.batchComplete.append(index)
610                break
611        if self.isBatch:
612            self.performEstimate()
613        else:
614            # If no data sets left, end batch calculation
615            self.isCalculating = False
616            self.batchComplete = []
617            self.calculateAllButton.setText("Calculate All")
618            self.showBatchOutput()
619            self.enableButtons()
620
621    def startThread(self):
622        """
623            Start a calculation thread
624        """
625        from .Thread import CalcPr
626
627        # Set data before running the calculations
628        self.isCalculating = True
629        self.enableButtons()
630        self.updateCalculator()
631        # Disable calculation buttons to prevent thread interference
632
633        # If a thread is already started, stop it
634        if self.calcThread is not None and self.calcThread.isrunning():
635            self.calcThread.stop()
636        pr = self._calculator.clone()
637        nfunc = self.getNFunc()
638        self.calcThread = CalcPr(pr, nfunc,
639                                 error_func=self._threadError,
640                                 completefn=self._calculateCompleted,
641                                 updatefn=None)
642        self.calcThread.queue()
643        self.calcThread.ready(2.5)
644
645    def performEstimateNT(self):
646        """
647        Perform parameter estimation
648        """
649        from .Thread import EstimateNT
650
651        self.updateCalculator()
652
653        # If a thread is already started, stop it
654        if (self.estimationThreadNT is not None and
655                self.estimationThreadNT.isrunning()):
656            self.estimationThreadNT.stop()
657        pr = self._calculator.clone()
658        # Skip the slit settings for the estimation
659        # It slows down the application and it doesn't change the estimates
660        pr.slit_height = 0.0
661        pr.slit_width = 0.0
662        nfunc = self.getNFunc()
663
664        self.estimationThreadNT = EstimateNT(pr, nfunc,
665                                             error_func=self._threadError,
666                                             completefn=self._estimateNTCompleted,
667                                             updatefn=None)
668        self.estimationThreadNT.queue()
669        self.estimationThreadNT.ready(2.5)
670
671    def performEstimate(self):
672        """
673            Perform parameter estimation
674        """
675        from .Thread import EstimatePr
676
677        # If a thread is already started, stop it
678        if (self.estimationThread is not None and
679                self.estimationThread.isrunning()):
680            self.estimationThread.stop()
681        self.estimationThread = EstimatePr(self._calculator.clone(),
682                                           self.getNFunc(),
683                                           error_func=self._threadError,
684                                           completefn=self._estimateCompleted,
685                                           updatefn=None)
686        self.estimationThread.queue()
687        self.estimationThread.ready(2.5)
688
689    ######################################################################
690    # Thread Complete
691
692    def _estimateCompleted(self, alpha, message, elapsed):
693        ''' Send a signal to the main thread for model update'''
694        self.estimateSignal.emit((alpha, message, elapsed))
695
696    def _estimateUpdate(self, output_tuple):
697        """
698        Parameter estimation completed,
699        display the results to the user
700
701        :param alpha: estimated best alpha
702        :param elapsed: computation time
703        """
704        alpha, message, elapsed = output_tuple
705        self._calculator.alpha = alpha
706        self._calculator.elapsed += self._calculator.elapsed
707        if message:
708            logger.info(message)
709        self.performEstimateNT()
710
711    def _estimateNTCompleted(self, nterms, alpha, message, elapsed):
712        ''' Send a signal to the main thread for model update'''
713        self.estimateNTSignal.emit((nterms, alpha, message, elapsed))
714
715    def _estimateNTUpdate(self, output_tuple):
716        """
717        Parameter estimation completed,
718        display the results to the user
719
720        :param alpha: estimated best alpha
721        :param nterms: estimated number of terms
722        :param elapsed: computation time
723        """
724        nterms, alpha, message, elapsed = output_tuple
725        self._calculator.elapsed += elapsed
726        self._calculator.suggested_alpha = alpha
727        self.nTermsSuggested = nterms
728        # Save useful info
729        self.updateGuiValues()
730        if message:
731            logger.info(message)
732        if self.isBatch:
733            self.acceptAlpha()
734            self.acceptNoTerms()
735            self.startThread()
736
737    def _calculateCompleted(self, out, cov, pr, elapsed):
738        ''' Send a signal to the main thread for model update'''
739        self.calculateSignal.emit((out, cov, pr, elapsed))
740
741    def _calculateUpdate(self, output_tuple):
742        """
743        Method called with the results when the inversion is done
744
745        :param out: output coefficient for the base functions
746        :param cov: covariance matrix
747        :param pr: Invertor instance
748        :param elapsed: time spent computing
749        """
750        out, cov, pr, elapsed = output_tuple
751        # Save useful info
752        cov = np.ascontiguousarray(cov)
753        pr.cov = cov
754        pr.out = out
755        pr.elapsed = elapsed
756
757        # Save Pr invertor
758        self._calculator = pr
759
760        # Update P(r) and fit plots
761        self.prPlot = self.logic.newPRPlot(out, self._calculator, cov)
762        self.prPlot.filename = self.logic.data.filename
763        self.dataPlot = self.logic.new1DPlot(out, self._calculator)
764        self.dataPlot.filename = self.logic.data.filename
765
766        # Udpate internals and GUI
767        self.updateDataList(self._data)
768        if self.isBatch:
769            self.batchComplete.append(self.dataList.currentIndex())
770            self.startNextBatchItem()
771        else:
772            self.isCalculating = False
773        self.updateGuiValues()
774
775    def _threadError(self, error):
776        """
777            Call-back method for calculation errors
778        """
779        logger.error(error)
Note: See TracBrowser for help on using the repository browser.