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

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 18d5af02 was 7f5196e, checked in by krzywon, 7 years ago

Basic link between dmax window and inversion.

  • Property mode set to 100644
File size: 22.5 KB
Line 
1import sys
2import logging
3import pylab
4import numpy as np
5
6from PyQt4 import QtGui, QtCore, QtWebKit
7from twisted.internet import reactor
8
9# sas-global
10import sas.qtgui.Utilities.GuiUtils as GuiUtils
11
12# pr inversion GUI elements
13from InversionUtils import WIDGETS
14import UI.TabbedInversionUI
15from UI.TabbedInversionUI import Ui_PrInversion
16from InversionLogic import InversionLogic
17
18# pr inversion calculation elements
19from sas.sascalc.dataloader.data_info import Data1D
20from sas.sascalc.pr.invertor import Invertor
21
22def is_float(value):
23    """Converts text input values to floats. Empty strings throw ValueError"""
24    try:
25        return float(value)
26    except ValueError:
27        return 0.0
28
29
30# TODO: Remove data
31# TODO: Modify plot references, don't just send new
32# TODO: Explorer button - link to PR from AW
33# TODO: Update help with batch capabilities
34# TODO: Window should not be fixed size
35# TODO: Easy way to scroll through results - no tabs in window(?) - 'spreadsheet'
36# TODO: Method to export results in some meaningful way
37class InversionWindow(QtGui.QTabWidget, Ui_PrInversion):
38    """
39    The main window for the P(r) Inversion perspective.
40    """
41
42    name = "Inversion"
43
44    def __init__(self, parent=None, data=None):
45        super(InversionWindow, self).__init__()
46        self.setupUi(self)
47
48        self.setWindowTitle("P(r) Inversion Perspective")
49
50        self._manager = parent
51        self._model_item = QtGui.QStandardItem()
52        self._helpView = QtWebKit.QWebView()
53
54        self.communicate = GuiUtils.Communicate()
55
56        self.logic = InversionLogic()
57
58        # The window should not close
59        self._allow_close = False
60
61        # current QStandardItem showing on the panel
62        self._data = None
63        # current Data1D as referenced by self._data
64        self._data_set = None
65
66        # p(r) calculator
67        self._calculator = Invertor()
68        self._last_calculator = None
69        self.calc_thread = None
70        self.estimation_thread = None
71
72        # Current data object in view
73        self._data_index = 0
74        # list mapping data to p(r) calculation
75        self._data_list = {}
76        if not isinstance(data, list):
77            data_list = [data]
78        if data is not None:
79            for datum in data_list:
80                self._data_list[datum] = self._calculator.clone()
81
82        # plots for current data
83        self.pr_plot = None
84        self.data_plot = None
85        # plot references for all data in perspective
86        self.pr_plot_list = {}
87        self.data_plot_list = {}
88
89        self.model = QtGui.QStandardItemModel(self)
90        self.mapper = QtGui.QDataWidgetMapper(self)
91        # Link user interactions with methods
92        self.setupLinks()
93        # Set values
94        self.setupModel()
95        # Set up the Widget Map
96        self.setupMapper()
97        # Set base window state
98        self.setupWindow()
99
100    ######################################################################
101    # Base Perspective Class Definitions
102
103    def communicator(self):
104        return self.communicate
105
106    def allowBatch(self):
107        return True
108
109    def setClosable(self, value=True):
110        """
111        Allow outsiders close this widget
112        """
113        assert isinstance(value, bool)
114        self._allow_close = value
115
116    def closeEvent(self, event):
117        """
118        Overwrite QDialog close method to allow for custom widget close
119        """
120        if self._allow_close:
121            # reset the closability flag
122            self.setClosable(value=False)
123            event.accept()
124        else:
125            event.ignore()
126            # Maybe we should just minimize
127            self.setWindowState(QtCore.Qt.WindowMinimized)
128
129    ######################################################################
130    # Initialization routines
131
132    def setupLinks(self):
133        """Connect the use controls to their appropriate methods"""
134        self.dataList.currentIndexChanged.connect(self.displayChange)
135        self.calculateAllButton.clicked.connect(self.startThreadAll)
136        self.calculateThisButton.clicked.connect(self.startThread)
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.calculateAllButton, WIDGETS.W_CALCULATE_ALL)
210        self.mapper.addMapping(self.calculateThisButton,
211                               WIDGETS.W_CALCULATE_VISIBLE)
212        self.mapper.addMapping(self.helpButton, WIDGETS.W_HELP)
213
214        self.mapper.toFirst()
215
216    def setupModel(self):
217        """
218        Update boxes with initial values
219        """
220        item = QtGui.QStandardItem("")
221        self.model.setItem(WIDGETS.W_FILENAME, item)
222        item = QtGui.QStandardItem('0.0')
223        self.model.setItem(WIDGETS.W_BACKGROUND_INPUT, item)
224        item = QtGui.QStandardItem("")
225        self.model.setItem(WIDGETS.W_QMIN, item)
226        item = QtGui.QStandardItem("")
227        self.model.setItem(WIDGETS.W_QMAX, item)
228        item = QtGui.QStandardItem("")
229        self.model.setItem(WIDGETS.W_SLIT_WIDTH, item)
230        item = QtGui.QStandardItem("")
231        self.model.setItem(WIDGETS.W_SLIT_HEIGHT, item)
232        item = QtGui.QStandardItem("10")
233        self.model.setItem(WIDGETS.W_NO_TERMS, item)
234        item = QtGui.QStandardItem("0.0001")
235        self.model.setItem(WIDGETS.W_REGULARIZATION, item)
236        item = QtGui.QStandardItem("140.0")
237        self.model.setItem(WIDGETS.W_MAX_DIST, item)
238        item = QtGui.QStandardItem("")
239        self.model.setItem(WIDGETS.W_RG, item)
240        item = QtGui.QStandardItem("")
241        self.model.setItem(WIDGETS.W_I_ZERO, item)
242        item = QtGui.QStandardItem("")
243        self.model.setItem(WIDGETS.W_BACKGROUND_OUTPUT, item)
244        item = QtGui.QStandardItem("")
245        self.model.setItem(WIDGETS.W_COMP_TIME, item)
246        item = QtGui.QStandardItem("")
247        self.model.setItem(WIDGETS.W_CHI_SQUARED, item)
248        item = QtGui.QStandardItem("")
249        self.model.setItem(WIDGETS.W_OSCILLATION, item)
250        item = QtGui.QStandardItem("")
251        self.model.setItem(WIDGETS.W_POS_FRACTION, item)
252        item = QtGui.QStandardItem("")
253        self.model.setItem(WIDGETS.W_SIGMA_POS_FRACTION, item)
254
255    def setupWindow(self):
256        """Initialize base window state on init"""
257        self.setTabPosition(0)
258        self.enableButtons()
259        self.estimateBgd.setChecked(True)
260
261    ######################################################################
262    # Methods for updating GUI
263
264    def enableButtons(self):
265        """
266        Enable buttons when data is present, else disable them
267        """
268        self.explorerButton.setEnabled(self.logic.data_is_loaded)
269        self.calculateAllButton.setEnabled(self.logic.data_is_loaded)
270        self.calculateThisButton.setEnabled(self.logic.data_is_loaded)
271
272    def populateDataComboBox(self, filename, data_ref):
273        """
274        Append a new file name to the data combobox
275        :param data: Data1D object
276        """
277        qt_item = QtCore.QString.fromUtf8(filename)
278        ref = QtCore.QVariant(data_ref)
279        self.dataList.addItem(qt_item, ref)
280
281    def acceptNoTerms(self):
282        """Send estimated no of terms to input"""
283        self.model.setItem(WIDGETS.W_NO_TERMS, QtGui.QStandardItem(
284            self.noOfTermsSuggestionButton.text()))
285
286    def acceptAlpha(self):
287        """Send estimated alpha to input"""
288        self.model.setItem(WIDGETS.W_REGULARIZATION, QtGui.QStandardItem(
289            self.regConstantSuggestionButton.text()))
290
291    def displayChange(self):
292        variant_ref = self.dataList.itemData(self.dataList.currentIndex())
293        self.setCurrentData(variant_ref.toPyObject())
294
295    ######################################################################
296    # GUI Interaction Events
297
298    def update_calculator(self):
299        """Update all p(r) params"""
300        self._calculator.set_x(self._data_set.x)
301        self._calculator.set_y(self._data_set.y)
302        self._calculator.set_err(self._data_set.dy)
303
304    def model_changed(self):
305        """Update the values when user makes changes"""
306        if not self.mapper:
307            msg = "Unable to update P{r}. The connection between the main GUI "
308            msg += "and P(r) was severed. Attempting to restart P(r)."
309            logging.warning(msg)
310            self.setClosable(True)
311            self.close()
312            InversionWindow.__init__(self.parent(), self._data_list.keys())
313            exit(0)
314        # TODO: Only send plot first time - otherwise, update in complete
315        if self.pr_plot is not None:
316            title = self.pr_plot.name
317            GuiUtils.updateModelItemWithPlot(
318                self._data, QtCore.QVariant(self.pr_plot), title)
319        if self.data_plot is not None:
320            title = self.data_plot.name
321            GuiUtils.updateModelItemWithPlot(
322                self._data, QtCore.QVariant(self.data_plot), title)
323        self.mapper.toFirst()
324
325    def help(self):
326        """
327        Open the P(r) Inversion help browser
328        """
329        tree_location = (GuiUtils.HELP_DIRECTORY_LOCATION +
330                         "user/sasgui/perspectives/pr/pr_help.html")
331
332        # Actual file anchor will depend on the combo box index
333        # Note that we can be clusmy here, since bad current_fitter_id
334        # will just make the page displayed from the top
335        self._helpView.load(QtCore.QUrl(tree_location))
336        self._helpView.show()
337
338    def toggleBgd(self):
339        """
340        Toggle the background between manual and estimated
341        """
342        sender = self.sender()
343        if sender is self.estimateBgd:
344            self.backgroundInput.setEnabled(False)
345        else:
346            self.backgroundInput.setEnabled(True)
347
348    def openExplorerWindow(self):
349        """
350        Open the Explorer window to see correlations between params and results
351        """
352        # TODO: Link Invertor() and DmaxWindow so window updates when recalculated
353        from dmax import DmaxWindow
354        self.dmaxWindow = DmaxWindow(self._calculator, self.getNFunc(), self)
355        self.dmaxWindow.show()
356
357    ######################################################################
358    # Response Actions
359
360    def setData(self, data_item=None, is_batch=False):
361        """
362        Assign new data set(s) to the P(r) perspective
363        Obtain a QStandardItem object and parse it to get Data1D/2D
364        Pass it over to the calculator
365        """
366        assert data_item is not None
367
368        if not isinstance(data_item, list):
369            msg = "Incorrect type passed to the P(r) Perspective"
370            raise AttributeError, msg
371
372        for data in data_item:
373            # Create initial internal mappings
374            self._data_list[data] = self._calculator.clone()
375            self._data_set = GuiUtils.dataFromItem(data)
376            self.data_plot_list[data] = self.data_plot
377            self.pr_plot_list[data] = self.pr_plot
378            ref_var = QtCore.QVariant(data)
379            self.populateDataComboBox(self._data_set.filename, ref_var)
380            self.setCurrentData(data)
381
382            # Estimate initial values from data
383            self.performEstimate()
384            self.logic = InversionLogic(self._data_set)
385
386            # Estimate q range
387            qmin, qmax = self.logic.computeDataRange()
388            self.model.setItem(WIDGETS.W_QMIN, QtGui.QStandardItem(
389                "{:.4g}".format(qmin)))
390            self.model.setItem(WIDGETS.W_QMAX, QtGui.QStandardItem(
391                "{:.4g}".format(qmax)))
392
393        self.enableButtons()
394
395    def getNFunc(self):
396        """Get the n_func value from the GUI object"""
397        return int(UI.TabbedInversionUI._fromUtf8(self.noOfTermsInput.text()))
398
399    def setCurrentData(self, data_ref):
400        """Get the current data and display as necessary"""
401
402        if not isinstance(data_ref, QtGui.QStandardItem):
403            msg = "Incorrect type passed to the P(r) Perspective"
404            raise AttributeError, msg
405
406        # Data references
407        self._data = data_ref
408        self._data_set = GuiUtils.dataFromItem(data_ref)
409        self._calculator = self._data_list[data_ref]
410        self.pr_plot = self.pr_plot_list[data_ref]
411        self.data_plot = self.data_plot_list[data_ref]
412
413    ######################################################################
414    # Thread Creators
415
416    # TODO: Move to individual class(?)
417
418    def startThreadAll(self):
419        for data_ref, pr in self._data_list.items():
420            self._data_set = GuiUtils.dataFromItem(data_ref)
421            self._calculator = pr
422            self.startThread()
423
424    def startThread(self):
425        """
426            Start a calculation thread
427        """
428        from Thread import CalcPr
429
430        # Set data before running the calculations
431        self.update_calculator()
432
433        # If a thread is already started, stop it
434        if self.calc_thread is not None and self.calc_thread.isrunning():
435            self.calc_thread.stop()
436        pr = self._calculator.clone()
437        nfunc = self.getNFunc()
438        self.calc_thread = CalcPr(pr, nfunc,
439                                  error_func=self._threadError,
440                                  completefn=self._completed, updatefn=None)
441        self.calc_thread.queue()
442        self.calc_thread.ready(2.5)
443
444    def performEstimateNT(self):
445        """
446            Perform parameter estimation
447        """
448        from Thread import EstimateNT
449
450        # If a thread is already started, stop it
451        if (self.estimation_thread is not None and
452                self.estimation_thread.isrunning()):
453            self.estimation_thread.stop()
454        pr = self._calculator.clone()
455        # Skip the slit settings for the estimation
456        # It slows down the application and it doesn't change the estimates
457        pr.slit_height = 0.0
458        pr.slit_width = 0.0
459        nfunc = self.getNFunc()
460        self.estimation_thread = EstimateNT(pr, nfunc,
461                                            error_func=self._threadError,
462                                            completefn=self._estimateNTCompleted,
463                                            updatefn=None)
464        self.estimation_thread.queue()
465        self.estimation_thread.ready(2.5)
466
467    def performEstimate(self):
468        """
469            Perform parameter estimation
470        """
471        from Thread import EstimatePr
472
473        self.startThread()
474
475        # If a thread is already started, stop it
476        if (self.estimation_thread is not None and
477                self.estimation_thread.isrunning()):
478            self.estimation_thread.stop()
479        pr = self._calculator.clone()
480        nfunc = self.getNFunc()
481        self.estimation_thread = EstimatePr(pr, nfunc,
482                                            error_func=self._threadError,
483                                            completefn=self._estimateCompleted,
484                                            updatefn=None)
485        self.estimation_thread.queue()
486        self.estimation_thread.ready(2.5)
487
488    ######################################################################
489    # Thread Complete
490
491    def _estimateCompleted(self, alpha, message, elapsed):
492        """
493        Parameter estimation completed,
494        display the results to the user
495
496        :param alpha: estimated best alpha
497        :param elapsed: computation time
498        """
499        # Save useful info
500        self.model.setItem(WIDGETS.W_COMP_TIME,
501                           QtGui.QStandardItem(str(elapsed)))
502        self.regConstantSuggestionButton.setText(QtCore.QString(str(alpha)))
503        self.regConstantSuggestionButton.setEnabled(True)
504        if message:
505            logging.info(message)
506        self.performEstimateNT()
507
508    def _estimateNTCompleted(self, nterms, alpha, message, elapsed):
509        """
510        Parameter estimation completed,
511        display the results to the user
512
513        :param alpha: estimated best alpha
514        :param nterms: estimated number of terms
515        :param elapsed: computation time
516
517        """
518        # Save useful info
519        self.noOfTermsSuggestionButton.setText(QtCore.QString(
520            "{:n}".format(nterms)))
521        self.noOfTermsSuggestionButton.setEnabled(True)
522        self.regConstantSuggestionButton.setText(QtCore.QString(
523            "{:.3g}".format(alpha)))
524        self.regConstantSuggestionButton.setEnabled(True)
525        self.model.setItem(WIDGETS.W_COMP_TIME,
526                           QtGui.QStandardItem(str(elapsed)))
527        self.PrTabWidget.setCurrentIndex(0)
528        if message:
529            logging.info(message)
530
531    def _completed(self, out, cov, pr, elapsed):
532        """
533        Method called with the results when the inversion is done
534
535        :param out: output coefficient for the base functions
536        :param cov: covariance matrix
537        :param pr: Invertor instance
538        :param elapsed: time spent computing
539
540        """
541        # Save useful info
542        cov = np.ascontiguousarray(cov)
543        pr.cov = cov
544        pr.out = out
545        pr.elapsed = elapsed
546
547        # Show result on control panel
548
549        # TODO: Connect self._calculator to GUI - two-to-one connection possible?
550        self.model.setItem(WIDGETS.W_RG, QtGui.QStandardItem(str(pr.rg(out))))
551        self.model.setItem(WIDGETS.W_I_ZERO,
552                           QtGui.QStandardItem(str(pr.iq0(out))))
553        self.model.setItem(WIDGETS.W_BACKGROUND_INPUT,
554                           QtGui.QStandardItem("{:.3f}".format(pr.background)))
555        self.model.setItem(WIDGETS.W_BACKGROUND_OUTPUT,
556                           QtGui.QStandardItem(str(pr.background)))
557        self.model.setItem(WIDGETS.W_CHI_SQUARED,
558                           QtGui.QStandardItem(str(pr.chi2[0])))
559        self.model.setItem(WIDGETS.W_COMP_TIME,
560                           QtGui.QStandardItem(str(elapsed)))
561        self.model.setItem(WIDGETS.W_OSCILLATION,
562                           QtGui.QStandardItem(str(pr.oscillations(out))))
563        self.model.setItem(WIDGETS.W_POS_FRACTION,
564                           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.