source: sasview/src/sas/qtgui/Perspectives/Corfunc/CorfuncPerspective.py @ f7b73d5

Last change on this file since f7b73d5 was f7b73d5, checked in by Adam Washington <adam.washington@…>, 6 years ago

Display transformed value

  • Property mode set to 100644
File size: 8.4 KB
Line 
1# global
2import sys
3from PyQt4 import QtCore
4from PyQt4 import QtGui
5from PyQt4 import QtWebKit
6
7from twisted.internet import threads
8from twisted.internet import reactor
9
10# sas-global
11from sas.qtgui.Plotting.PlotterData import Data1D
12import sas.qtgui.Utilities.GuiUtils as GuiUtils
13from sas.sascalc.corfunc.corfunc_calculator import CorfuncCalculator
14
15# local
16from UI.CorfuncPanel import Ui_CorfuncDialog
17# from InvariantDetails import DetailsDialog
18from CorfuncUtils import WIDGETS as W
19
20from matplotlib.backends import qt_compat
21from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
22from matplotlib.figure import Figure
23
24
25class MyMplCanvas(FigureCanvas):
26    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
27    def __init__(self, parent=None, width=5, height=4, dpi=100):
28        self.fig = Figure(figsize=(width, height), dpi=dpi)
29        self.axes = self.fig.add_subplot(111)
30
31        FigureCanvas.__init__(self, self.fig)
32        # self.reparent(parent, QPoint(0, 0))
33
34        # FigureCanvas.setSizePolicy(self,
35        #                            QSizePolicy.Expanding,
36        #                            QSizePolicy.Expanding)
37        # FigureCanvas.updateGeometry(self)
38
39        self.data = None
40        self.qmin = None
41        self.qmax1 = None
42        self.qmax2 = None
43        self.extrap = None
44
45    def drawQSpace(self):
46        self.fig.clf()
47
48        self.axes = self.fig.add_subplot(111)
49        self.axes.set_xscale("log")
50        self.axes.set_yscale("log")
51
52        if self.data:
53            self.axes.plot(self.data.x, self.data.y)
54        if self.qmin:
55            self.axes.axvline(self.qmin)
56        if self.qmax1:
57            self.axes.axvline(self.qmax1)
58        if self.qmax2:
59            self.axes.axvline(self.qmax2)
60        if self.extrap:
61            self.axes.plot(self.extrap.x, self.extrap.y)
62
63        self.draw()
64
65    def drawRealSpace(self):
66        self.fig.clf()
67
68        self.axes = self.fig.add_subplot(111)
69        self.axes.set_xscale("linear")
70        self.axes.set_yscale("linear")
71
72        if self.data:
73            self.axes.plot(self.data.x, self.data.y)
74
75        self.draw()
76
77
78    # def sizeHint(self):
79    #     w, h = self.get_width_height()
80    #     return QSize(w, h)
81
82    # def minimumSizeHint(self):
83    #     return QSize(10, 10)
84
85
86class CorfuncWindow(QtGui.QDialog, Ui_CorfuncDialog):
87    # The controller which is responsible for managing signal slots connections
88    # for the gui and providing an interface to the data model.
89    name = "Corfunc" # For displaying in the combo box
90    #def __init__(self, manager=None, parent=None):
91    def __init__(self, parent=None):
92        #super(InvariantWindow, self).__init__(parent)
93        super(CorfuncWindow, self).__init__()
94        self.setupUi(self)
95
96        self.setWindowTitle("Corfunc Perspective")
97
98        self.model = QtGui.QStandardItemModel(self)
99        self.communicate = GuiUtils.Communicate()
100        self._calculator = CorfuncCalculator()
101
102        self._canvas = MyMplCanvas(self)
103        self._realplot = MyMplCanvas(self)
104        self.verticalLayout_7.insertWidget(0,self._canvas)
105        self.verticalLayout_7.insertWidget(1, self._realplot)
106
107        # Connect buttons to slots.
108        # Needs to be done early so default values propagate properly.
109        self.setupSlots()
110
111        # Set up the model.
112        self.setupModel()
113
114        # Set up the mapper
115        self.setupMapper()
116
117    def setupSlots(self):
118        self.extractBtn.clicked.connect(self.action)
119        self.extrapolateBtn.clicked.connect(self.extrapolate)
120        self.transformBtn.clicked.connect(self.transform)
121
122        self.calculateBgBtn.clicked.connect(self.calculateBackground)
123
124        self.hilbertBtn.clicked.connect(self.action)
125        self.fourierBtn.clicked.connect(self.action)
126
127        self.model.itemChanged.connect(self.modelChanged)
128
129    def setupModel(self):
130        self.model.setItem(W.W_QMIN,
131                           QtGui.QStandardItem("0"))
132        self.model.setItem(W.W_QMAX,
133                           QtGui.QStandardItem("0"))
134        self.model.setItem(W.W_QCUTOFF,
135                           QtGui.QStandardItem("0"))
136        self.model.setItem(W.W_BACKGROUND,
137                           QtGui.QStandardItem("0"))
138        self.model.setItem(W.W_TRANSFORM,
139                           QtGui.QStandardItem("Fourier"))
140
141    def modelChanged(self, item):
142        if item.row() == W.W_QMIN:
143            value = float(self.model.item(W.W_QMIN).text())
144            self.qMin.setValue(value)
145            self._calculator.lowerq = value
146            self._canvas.qmin = value
147        elif item.row() == W.W_QMAX:
148            value = float(self.model.item(W.W_QMAX).text())
149            self.qMax1.setValue(value)
150            self._calculator.upperq = (value, self._calculator.upperq[1])
151            self._canvas.qmax1 = value
152        elif item.row() == W.W_QCUTOFF:
153            value = float(self.model.item(W.W_QCUTOFF).text())
154            self.qMax2.setValue(value)
155            self._calculator.upperq = (self._calculator.upperq[0], value)
156            self._canvas.qmax2 = value
157        elif item.row() == W.W_BACKGROUND:
158            value = float(self.model.item(W.W_BACKGROUND).text())
159            self.bg.setValue(value)
160            self._calculator.background = value
161        else:
162            print("{} Changed".format(item))
163
164        self._canvas.drawQSpace()
165
166
167    def extrapolate(self):
168        params, extrapolation = self._calculator.compute_extrapolation()
169        self.guinierA.setValue(params['A'])
170        self.guinierB.setValue(params['B'])
171        self.porodK.setValue(params['K'])
172        self.porodSigma.setValue(params['sigma'])
173        self._canvas.extrap = extrapolation
174        self._canvas.drawQSpace()
175
176
177    def transform(self):
178        if self.fourierBtn.isChecked():
179            method = "fourier"
180        elif self.hilbertBtn.isChecked():
181            method = "hilbert"
182
183        extrap = self._canvas.extrap
184        bg = self._calculator.background
185        def updatefn(*args, **kwargs):
186            pass
187
188        def completefn(transform):
189            self._realplot.data = transform
190            self._realplot.drawRealSpace()
191
192        self._calculator.compute_transform(extrap, method, bg, completefn, updatefn)
193
194
195    def setupMapper(self):
196        self.mapper = QtGui.QDataWidgetMapper(self)
197        self.mapper.setOrientation(QtCore.Qt.Vertical)
198        self.mapper.setModel(self.model)
199
200        self.mapper.addMapping(self.qMin, W.W_QMIN)
201        self.mapper.addMapping(self.qMax1, W.W_QMAX)
202        self.mapper.addMapping(self.qMax2, W.W_QCUTOFF)
203        self.mapper.addMapping(self.bg, W.W_BACKGROUND)
204
205        self.mapper.toFirst()
206
207    def calculateBackground(self):
208        bg = self._calculator.compute_background()
209        print(bg)
210        self.model.setItem(W.W_BACKGROUND, QtGui.QStandardItem(str(bg)))
211
212    def action(self):
213        print("Called an action!")
214        print(self.model)
215        print(self.mapper)
216
217    def allowBatch(self):
218        """
219        We cannot perform corfunc analysis in batch at this time.
220        """
221        return False
222
223    def setData(self, data_item, is_batch=False):
224        """
225        Obtain a QStandardItem object and dissect it to get Data1D/2D
226        Pass it over to the calculator
227        """
228        if not isinstance(data_item, list):
229            msg = "Incorrect type passed to the Corfunc Perpsective"
230            raise AttributeError(msg)
231
232        if not isinstance(data_item[0], QtGui.QStandardItem):
233            msg = "Incorrect type passed to the Corfunc Perspective"
234            raise AttributeError(msg)
235
236        self._model_item = data_item[0]
237        data = GuiUtils.dataFromItem(self._model_item)
238        self._calculator.lowerq = 1e-3
239        self._calculator.upperq = (2e-1, 3e-1)
240        self._calculator.set_data(data)
241
242        self._canvas.data = data
243        self._canvas.drawQSpace()
244
245        # self.model.item(WIDGETS.W_FILENAME).setData(QtCoreQVariant(self._model_item.text()))
246
247    def setClosable(self, value=True):
248        """
249        Allow outsiders close this widget
250        """
251        assert isinstance(value, bool)
252
253        self._allow_close = value
254
255
256if __name__ == "__main__":
257    app = QtGui.QApplication([])
258    import qt4reactor
259    # qt4reactor.install()
260    # DO NOT move the following import to the top!
261    # (unless you know what you're doing)
262    from twisted.internet import reactor
263    dlg = CorfuncWindow(reactor)
264    print(dlg)
265    dlg.show()
266    # print(reactor)
267    # reactor.run()
268    sys.exit(app.exec_())
Note: See TracBrowser for help on using the repository browser.