source: sasview/src/sas/qtgui/Perspectives/Inversion/DMaxExplorerWidget.py @ 0d8b2db

ESS_GUIESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 0d8b2db was b0ba43e, checked in by krzywon, 7 years ago

Fix for P(r) thread error handling and Dmax explorer exception issues.

  • Property mode set to 100644
File size: 6.5 KB
Line 
1# -*- coding: utf-8 -*-
2"""
3Dialog panel to explore the P(r) inversion results for a range
4of D_max value. User picks a number of points and a range of
5distances, then can toggle between inversion outputs and see
6their distribution as a function of D_max.
7"""
8
9# global
10import logging
11import numpy as np
12from PyQt5 import QtCore
13from PyQt5 import QtGui
14from PyQt5 import QtWidgets
15
16# sas-global
17from sas.qtgui.Plotting.PlotterData import Data1D
18from sas.qtgui.Plotting.Plotter import PlotterWidget
19import sas.qtgui.Utilities.GuiUtils as GuiUtils
20
21# local
22from .UI.DMaxExplorer import Ui_DmaxExplorer
23
24logger = logging.getLogger(__name__)
25
26from sas.qtgui.Utilities.GuiUtils import enum
27
28W = enum( 'NPTS',      #0
29          'DMIN',      #1
30          'DMAX',      #2
31          'VARIABLE',  #3
32)
33
34class DmaxWindow(QtWidgets.QDialog, Ui_DmaxExplorer):
35    # The controller which is responsible for managing signal slots connections
36    # for the gui and providing an interface to the data model.
37    name = "Dmax Explorer"  # For displaying in the combo box
38
39    def __init__(self, pr_state, nfunc, parent=None):
40        super(DmaxWindow, self).__init__()
41        self.setupUi(self)
42        self.parent = parent
43
44        self.setWindowTitle("Dₐₓ Explorer")
45
46        self.pr_state = pr_state
47        self.nfunc = nfunc
48        self.communicator = GuiUtils.Communicate()
49
50        self.plot = PlotterWidget(self, self)
51        self.hasPlot = False
52        self.verticalLayout.insertWidget(0, self.plot)
53
54        # Let's choose the Standard Item Model.
55        self.model = QtGui.QStandardItemModel(self)
56        self.mapper = QtWidgets.QDataWidgetMapper(self)
57
58        # Add validators on line edits
59        self.setupValidators()
60
61        # Connect buttons to slots.
62        # Needs to be done early so default values propagate properly.
63        self.setupSlots()
64
65        # Set up the model.
66        self.setupModel()
67
68        # # Set up the mapper
69        self.setupMapper()
70
71    def setupValidators(self):
72        """Add validators on relevant line edits"""
73        self.Npts.setValidator(QtGui.QIntValidator())
74        self.minDist.setValidator(GuiUtils.DoubleValidator())
75        self.maxDist.setValidator(GuiUtils.DoubleValidator())
76
77    def setupSlots(self):
78        self.closeButton.clicked.connect(self.close)
79        self.model.itemChanged.connect(self.modelChanged)
80        self.dependentVariable.currentIndexChanged.connect(lambda:self.modelChanged(None))
81
82    def setupModel(self):
83        self.model.blockSignals(True)
84        self.model.setItem(W.NPTS, QtGui.QStandardItem(str(self.nfunc)))
85        self.model.blockSignals(False)
86        self.model.blockSignals(True)
87        self.model.setItem(W.DMIN, QtGui.QStandardItem("{:.1f}".format(0.9*self.pr_state.d_max)))
88        self.model.blockSignals(False)
89        self.model.blockSignals(True)
90        self.model.setItem(W.DMAX, QtGui.QStandardItem("{:.1f}".format(1.1*self.pr_state.d_max)))
91        self.model.blockSignals(False)
92        self.model.blockSignals(True)
93        self.model.setItem(W.VARIABLE, QtGui.QStandardItem( "χ²/dof"))
94        self.model.blockSignals(False)
95
96    def setupMapper(self):
97        self.mapper.setOrientation(QtCore.Qt.Vertical)
98        self.mapper.setModel(self.model)
99
100        self.mapper.addMapping(self.Npts, W.NPTS)
101        self.mapper.addMapping(self.minDist, W.DMIN)
102        self.mapper.addMapping(self.maxDist, W.DMAX)
103        self.mapper.addMapping(self.dependentVariable, W.VARIABLE)
104
105        self.mapper.toFirst()
106
107    def modelChanged(self, item):
108        if not self.mapper:
109            return
110
111        iq0 = []
112        rg = []
113        pos = []
114        pos_err = []
115        osc = []
116        bck = []
117        chi2 = []
118
119        try:
120            dmin = float(self.model.item(W.DMIN).text())
121            dmax = float(self.model.item(W.DMAX).text())
122            npts = float(self.model.item(W.NPTS).text())
123            xs = np.linspace(dmin, dmax, npts)
124        except ValueError as e:
125            msg = ("An input value is not correctly formatted. Please check {}"
126                   .format(e.message))
127            logger.error(msg)
128
129        original = self.pr_state.d_max
130        for x in xs:
131            self.pr_state.d_max = x
132            try:
133                out, cov = self.pr_state.invert(self.pr_state.nfunc)
134
135                iq0.append(self.pr_state.iq0(out))
136                rg.append(self.pr_state.rg(out))
137                pos.append(self.pr_state.get_positive(out))
138                pos_err.append(self.pr_state.get_pos_err(out, cov))
139                osc.append(self.pr_state.oscillations(out))
140                bck.append(self.pr_state.background)
141                chi2.append(self.pr_state.chi2)
142            except Exception as ex:
143                # This inversion failed, skip this D_max value
144                msg = "ExploreDialog: inversion failed "
145                msg += "for D_max=%s\n%s" % (str(x), ex)
146                logger.error(msg)
147
148        #Return the invertor to its original state
149        self.pr_state.d_max = original
150        try:
151            self.pr_state.invert(self.nfunc)
152        except RuntimeError as ex:
153            msg = "ExploreDialog: inversion failed "
154            msg += "for D_max=%s\n%s" % (str(x), ex)
155            logger.error(msg)
156
157        plotter = self.model.item(W.VARIABLE).text()
158        y_label = y_unit = ""
159        x_label = "D_{max}"
160        x_unit = "A"
161        if plotter == "χ²/dof":
162            ys = chi2
163            y_label = "\\chi^2/dof"
164            y_unit = "a.u."
165        elif plotter == "I(Q=0)":
166            ys = iq0
167            y_label = "I(q=0)"
168            y_unit = "\\AA^{-1}"
169        elif plotter == "Rg":
170            ys = rg
171            y_label = "R_g"
172            y_unit = "\\AA"
173        elif plotter == "Oscillation parameter":
174            ys = osc
175            y_label = "Osc"
176            y_unit = "a.u."
177        elif plotter == "Background":
178            ys = bck
179            y_label = "Bckg"
180            y_unit = "\\AA^{-1}"
181        elif plotter == "Positive Fraction":
182            ys = pos
183            y_label = "P^+"
184            y_unit = "a.u."
185        else:
186            ys = pos_err
187            y_label = "P^{+}_{1\\sigma}"
188            y_unit = "a.u."
189
190        data = Data1D(xs, ys)
191        if self.hasPlot:
192            self.plot.removePlot(None)
193        self.hasPlot = True
194        data.title = plotter
195        data._xaxis= x_label
196        data._xunit = x_unit
197        data._yaxis = y_label
198        data._yunit = y_unit
199        self.plot.plot(data=data, marker="-")
200
201    def closeEvent(self, event):
202        """Override close event"""
203        self.parent.dmaxWindow = None
204        event.accept()
Note: See TracBrowser for help on using the repository browser.