source: sasview/src/sas/qtgui/Perspectives/Inversion/DMaxExplorerWidget.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: 6.2 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.setItem(W.NPTS, QtGui.QStandardItem(str(self.nfunc)))
84        self.model.setItem(W.DMIN, QtGui.QStandardItem("{:.1f}".format(0.9*self.pr_state.d_max)))
85        self.model.setItem(W.DMAX, QtGui.QStandardItem("{:.1f}".format(1.1*self.pr_state.d_max)))
86        self.model.setItem(W.VARIABLE, QtGui.QStandardItem( "χ²/dof"))
87
88    def setupMapper(self):
89        self.mapper.setOrientation(QtCore.Qt.Vertical)
90        self.mapper.setModel(self.model)
91
92        self.mapper.addMapping(self.Npts, W.NPTS)
93        self.mapper.addMapping(self.minDist, W.DMIN)
94        self.mapper.addMapping(self.maxDist, W.DMAX)
95        self.mapper.addMapping(self.dependentVariable, W.VARIABLE)
96
97        self.mapper.toFirst()
98
99    def modelChanged(self, item):
100        if not self.mapper:
101            return
102
103        iq0 = []
104        rg = []
105        pos = []
106        pos_err = []
107        osc = []
108        bck = []
109        chi2 = []
110
111        try:
112            dmin = float(self.model.item(W.DMIN).text())
113            dmax = float(self.model.item(W.DMAX).text())
114            npts = float(self.model.item(W.NPTS).text())
115            xs = np.linspace(dmin, dmax, npts)
116        except ValueError as e:
117            msg = ("An input value is not correctly formatted. Please check {}"
118                   .format(e.message))
119            logger.error(msg)
120
121        original = self.pr_state.d_max
122        for x in xs:
123            self.pr_state.d_max = x
124            try:
125                out, cov = self.pr_state.invert(self.pr_state.nfunc)
126
127                iq0.append(self.pr_state.iq0(out))
128                rg.append(self.pr_state.rg(out))
129                pos.append(self.pr_state.get_positive(out))
130                pos_err.append(self.pr_state.get_pos_err(out, cov))
131                osc.append(self.pr_state.oscillations(out))
132                bck.append(self.pr_state.background)
133                chi2.append(self.pr_state.chi2)
134            except Exception as ex:
135                # This inversion failed, skip this D_max value
136                msg = "ExploreDialog: inversion failed "
137                msg += "for D_max=%s\n%s" % (str(x), ex)
138                logger.error(msg)
139
140        #Return the invertor to its original state
141        self.pr_state.d_max = original
142        try:
143            self.pr_state.invert(self.nfunc)
144        except RuntimeError as ex:
145            msg = "ExploreDialog: inversion failed "
146            msg += "for D_max=%s\n%s" % (str(x), ex)
147            logger.error(msg)
148
149        plotter = self.model.item(W.VARIABLE).text()
150        y_label = y_unit = ""
151        x_label = "D_{max}"
152        x_unit = "A"
153        if plotter == "χ²/dof":
154            ys = chi2
155            y_label = "\\chi^2/dof"
156            y_unit = "a.u."
157        elif plotter == "I(Q=0)":
158            ys = iq0
159            y_label = "I(q=0)"
160            y_unit = "\\AA^{-1}"
161        elif plotter == "Rg":
162            ys = rg
163            y_label = "R_g"
164            y_unit = "\\AA"
165        elif plotter == "Oscillation parameter":
166            ys = osc
167            y_label = "Osc"
168            y_unit = "a.u."
169        elif plotter == "Background":
170            ys = bck
171            y_label = "Bckg"
172            y_unit = "\\AA^{-1}"
173        elif plotter == "Positive Fraction":
174            ys = pos
175            y_label = "P^+"
176            y_unit = "a.u."
177        else:
178            ys = pos_err
179            y_label = "P^{+}_{1\\sigma}"
180            y_unit = "a.u."
181
182        data = Data1D(xs, ys)
183        if self.hasPlot:
184            self.plot.removePlot(None)
185        self.hasPlot = True
186        data.title = plotter
187        data._xaxis= x_label
188        data._xunit = x_unit
189        data._yaxis = y_label
190        data._yunit = y_unit
191        self.plot.plot(data=data, marker="-")
192
193    def closeEvent(self, event):
194        """Override close event"""
195        self.parent.dmaxWindow = None
196        event.accept()
Note: See TracBrowser for help on using the repository browser.