summaryrefslogtreecommitdiff
path: root/PyMca5/PyMcaGui/plotting/ScatterPlotCorrelatorWidget.py
blob: e55aff97d5a4df33773bdbb7b0f75c5df5b98144 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#/*##########################################################################
# Copyright (C) 2004-2015 V.A. Sole, European Synchrotron Radiation Facility
#
# This file is part of the PyMca X-ray Fluorescence Toolkit developed at
# the ESRF by the Software group.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#############################################################################*/
__author__ = "V.A. Sole - ESRF Data Analysis"
__contact__ = "sole@esrf.fr"
__license__ = "MIT"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
import sys
import os
import numpy
import traceback
from PyMca5.PyMcaGui import PyMcaQt as qt
from PyMca5.PyMcaGui.misc import SelectionTable
from PyMca5.PyMcaGui.plotting import MaskScatterWidget

class ScatterPlotCorrelatorWidget(MaskScatterWidget.MaskScatterWidget):
    def __init__(self, parent=None,
                       labels=("Legend", "X", "Y"),
                       types=("Text","RadioButton", "RadioButton"),
                       toolbar=False,
                       **kw):
        super(ScatterPlotCorrelatorWidget, self).__init__(None, **kw)
        self._splitter = qt.QSplitter(parent)
        self._splitter.setOrientation(qt.Qt.Horizontal)

        self.container = qt.QWidget(self._splitter)
        self.container.mainLayout = qt.QVBoxLayout(self.container)
        self.container.mainLayout.setContentsMargins(0, 0, 0, 0)
        self.container.mainLayout.setSpacing(0)

        # add a toolbar on top of the table
        if toolbar:
            self.toolBar = qt.QToolBar(self.container)

        # the selection table
        self.table = SelectionTable.SelectionTable(self.container,
                                                   labels=labels,
                                                   types=types)
        if toolbar:
            self.container.mainLayout.addWidget(self.toolBar)
        self.container.mainLayout.addWidget(self.table)
        self._splitter.addWidget(self.container)
        self._splitter.addWidget(self)

        # internal variables
        self._itemList = []
        self._itemLabels = []

        # connect
        self.table.sigSelectionTableSignal.connect(self.selectionTableSlot)

    def show(self):
        if self._splitter.isHidden():
            self._splitter.show()
        else:
            super(ScatterPlotCorrelatorWidget, self).show()

    def setSelectableItemList(self, items, labels=None, copy=True):
        self._itemList = []
        self._itemLabels = []
        if labels is None:
            labels = [None] * len(items)
        for i in range(len(items)):
            self.addSelectableItem(items[i], label=labels[i], copy=copy)

    def addSelectableItem(self, item, label=None, copy=True):
        # we always keep a copy by default
        item = numpy.array(item, dtype=numpy.float32, copy=copy)
        if label is None:
            label = "Unnamed 00"
            i = 0
            while(label in self._itemLabels):
                i += 1
                label = "Unnamed %02d" % i

        if len(self._itemList):
            if item.size != self._itemList[0].size:
                raise IndexError("Invalid size")
        if label in self._itemLabels:
            self._itemList[self._itemLabels.index(label)] = item
        else:
            self._itemList.append(item)
            self._itemLabels.append(label)
            nItems = len(self._itemList)
            self.table.setRowCount(nItems)
            self.table.fillLine(nItems - 1, [label, "", ""])
            self.table.resizeColumnToContents(0)
            self.table.resizeColumnToContents(1)
            self.table.resizeColumnToContents(2)

        ddict = self.table.getSelection()
        index = self._itemLabels.index(label)
        xKey = qt.safe_str(self.table.horizontalHeaderItem(1).text()).lower()
        yKey = qt.safe_str(self.table.horizontalHeaderItem(2).text()).lower()
        if index in (ddict[xKey] + ddict[yKey]):
            self.selectionTableSlot(ddict)

    def selectionTableSlot(self, ddict):
        legendKey = qt.safe_str(self.table.horizontalHeaderItem(0).text()).lower()
        xKey = qt.safe_str(self.table.horizontalHeaderItem(1).text()).lower()
        yKey = qt.safe_str(self.table.horizontalHeaderItem(2).text()).lower()
        if len(ddict[xKey]):
            x0 = self._itemList[ddict[xKey][0]]
        else:
            return
        if len(ddict[yKey]):
            y0 = self._itemList[ddict[yKey][0]]
        else:
            return
        x = x0[:]
        x.shape = -1
        y = y0[:]
        y.shape = -1
        xLabel = self._itemLabels[ddict[xKey][0]]
        yLabel = self._itemLabels[ddict[yKey][0]]
        # active curve handling is disabled
        self.setGraphXLabel(xLabel)
        self.setGraphYLabel(yLabel)
        self.setSelectionCurveData(x, y, legend=None,
                                   color="k",
                                   symbol=".",
                                   replot=False,
                                   replace=True,
                                   xlabel=xLabel,
                                   ylabel=yLabel,
                                   selectable=False)
        self._updatePlot(replot=False, replace=True)
        #matplotlib needs a zoom reset to update the scales
        # that problem does not seem to be present with OpenGL
        self.resetZoom()

if __name__ == "__main__":
    if "opengl" in sys.argv:
        backend = "opengl"
    else:
        backend = None
    app = qt.QApplication([])
    w = ScatterPlotCorrelatorWidget(labels=["Legend",
                                            "X",
                                            "Y"],
                                    types=["Text",
                                           "RadioButton",
                                           "RadioButton"],
                                    maxNRois=1,
                                    backend=backend)
    w.show()
    # fill some data
    import numpy
    import numpy.random
    import time
    t0 = time.time()
    x = numpy.arange(1000000.)
    w.addSelectableItem(x, "range(%d)" % x.size)
    print("elapsed = ", time.time() - t0)
    w.addSelectableItem(x * x, "range(%d) ** 2"  % x.size)
    x = numpy.random.random(x.size)
    w.addSelectableItem(x, "random(%d)" % x.size)
    x = numpy.random.normal(500000., 1.0, 1000000)
    w.addSelectableItem(x, "Gauss 0")
    x = numpy.random.normal(500000., 1.0, 1000000)
    w.addSelectableItem(x, "Gauss 1")
    w.setPolygonSelectionMode()

    def theSlot(ddict):
        print(ddict['event'])

    w.sigMaskScatterWidgetSignal.connect(theSlot)

    app.exec_()