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

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 0261bc1 was 6a3e1fe, checked in by Piotr Rozyczko <rozyczko@…>, 7 years ago

Implemented hash method for certain QStandardItem objects, allowing them to be used as dict keys. SASVIEW-806
Minor inversion perspective fixes. SASVIEW-338

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