File: SimpleActions.py

package info (click to toggle)
pymca 5.4.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 44,320 kB
  • sloc: python: 140,671; ansic: 20,050; sh: 175; makefile: 133; xml: 55
file content (322 lines) | stat: -rw-r--r-- 10,686 bytes parent folder | download | duplicates (2)
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
#/*##########################################################################
# Copyright (C) 2004-2017 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.
#
#############################################################################*/
"""This module defines a set of simple plot actions processing one or all
plotted curves in a ScanWindow:

    - :class:`AverageAction`
    - :class:`DerivativeAction`
    - :class:`SmoothAction`
    - :class:`SwapSignAction`
    - :class:`SubtractAction`
    - :class:`YMinToZeroAction`

"""
import copy

from silx.gui.plot.actions import PlotAction

from PyMca5.PyMcaGui import PyMcaQt as qt
from PyMca5.PyMcaMath import SimpleMath
from PyMca5.PyMcaGui.plotting.PyMca_Icons import IconDict

if hasattr(qt, 'QString'):
    QString = qt.QString
else:
    QString = qt.safe_str

_simpleMath = SimpleMath.SimpleMath()


def _getOneCurve(plot, qwarning=True):
    """Return active curve if any,
    else if there is a single curve return it,
    else return None.

    :param plot: Plot instance
    :param bool qwarning: If True, display a warning popup to
        inform that a curve must be selected when function is not
        successful.
    """
    curve = plot.getActiveCurve()
    if curve is None:
        curves = plot.getAllCurves()
        if not curves or len(curves) > 1:
            if qwarning:
                _QWarning(msg="You must select a curve.",
                          parent=plot)
            return None
        return curves[0]
    return curve


def _QWarning(msg, parent=None):
    """Print a warning message in a QMessageBox"""
    mb = qt.QMessageBox(parent)
    mb.setIcon(qt.QMessageBox.Warning)
    mb.setText(msg)
    mb.exec_()

#
# def _isActive(legend, plot):
#     """
#
#     :param legend: curve legend
#     :param plot: plot instance
#     :return: True or False
#     """
#     active_legend = plot.getActiveCurve(just_legend=True)
#     if active_legend is None:
#         # No active curve
#         return False
#     return legend == active_legend


def _updated_info(info0, sourcename, operation):
    info1 = copy.deepcopy(info0)
    if not 'operations' in info1:
        info1['operations'] = []
    info1['operations'].append(operation)
    info1['SourceName'] = sourcename
    if 'selectionlegend' in info1:
        del info1['selectionlegend']
    return info1


class AverageAction(PlotAction):
    """Average all curves, clear plot, add average curve
    """
    def __init__(self, plot, parent=None):
        self.icon = qt.QIcon(qt.QPixmap(IconDict["average16"]))
        PlotAction.__init__(self,
                            plot,
                            icon=self.icon,
                            text='Average Plotted Curves',
                            tooltip='Replace all curves by the average curve',
                            triggered=self._averageAllCurves,
                            parent=parent)

    def _averageAllCurves(self):
        curves = self.plot.getAllCurves()
        if not curves:
            return
        x0, y0, legend0, info0, _params0 = curves[0]
        avg_legend = legend0
        all_x = [x0]
        all_y = [y0]
        for x, y, legend, info, params in curves[1:]:
            avg_legend += " + " + legend
            all_x.append(x)
            all_y.append(y)

        avg_info = _updated_info(info0, avg_legend, "average")

        xavg, yavg = _simpleMath.average(all_x, all_y)
        avg_legend = "(%s)/%d" % (avg_legend, len(curves))

        self.plot.clearCurves()
        self.plot.addCurve(xavg, yavg, avg_legend,
                           info=avg_info)


class SmoothAction(PlotAction):
    """Plot smooth of the active curve if any,
    else plot smooth of the only existing curve if any.
    """
    def __init__(self, plot, parent=None):
        self.icon = qt.QIcon(qt.QPixmap(IconDict["smooth"]))
        PlotAction.__init__(self,
                            plot,
                            icon=self.icon,
                            text='Smooth Active Curve',
                            tooltip='Smooth Active Curve',
                            triggered=self._smoothActiveCurve,
                            parent=parent)

    def _smoothActiveCurve(self):
        curve = _getOneCurve(self.plot)
        if curve is None:
            return
        x0, y0, legend0, info0, _params = curve

        x1 = x0 * 1
        y1 = _simpleMath.smooth(y0)

        if info0.get("operations") is None or \
                info0["operations"][-1] != "smooth":
            legend1 = "%s Smooth" % legend0
        else:
            # don't repeat "smooth"
            legend1 = legend0

        info1 = _updated_info(info0, legend0, "smooth")

        self.plot.addCurve(x1, y1, legend1,
                           info=info1)


class DerivativeAction(PlotAction):
    """Plot derivative of the active curve if any,
    else the derivative of the only existing curve.
    """
    def __init__(self, plot, parent=None):
        self.icon = qt.QIcon(qt.QPixmap(IconDict["derive"]))
        PlotAction.__init__(self,
                            plot,
                            icon=self.icon,
                            tooltip='Plot Derivative of Active Curve',
                            text='Derivate Active Curve',
                            triggered=self._derivateActiveCurve,
                            parent=parent)

    def _derivateActiveCurve(self):
        curve = _getOneCurve(self.plot)
        if curve is None:
            return
        x0, y0, legend0, info0, params0 = curve

        x1, y1 = _simpleMath.derivate(x0, y0)
        legend1 = legend0 + "'"

        info1 = _updated_info(info0, legend0, "derivate")
        info1['plot_yaxis'] = "right"

        ylabel1 = params0.get("ylabel")
        if ylabel1 is None:
            ylabel1 = "Y"

        self.plot.addCurve(x1, y1, legend1,
                           ylabel=ylabel1 + "'",
                           info=info1,
                           yaxis="right")


class SwapSignAction(PlotAction):
    """Plot the active curve multiplied by -1
    """
    def __init__(self, plot, parent=None):
        self.icon = qt.QIcon(qt.QPixmap(IconDict["swapsign"]))
        PlotAction.__init__(self,
                            plot,
                            icon=self.icon,
                            text='Multiply Active Curve by -1',
                            tooltip='Multiply Active Curve by -1',
                            triggered=self._swapSignCurve,
                            parent=parent)

    def _swapSignCurve(self):
        curve = _getOneCurve(self.plot)
        if curve is None:
            return
        x0, y0, legend0, info0, _params = curve

        x1 = 1 * x0
        y1 = -y0
        legend1 = "-(%s)" % legend0

        info1 = _updated_info(info0, legend0, "swapsign")

        self.plot.addCurve(x1, y1, legend1,
                           info=info1)


class YMinToZeroAction(PlotAction):
    """

    """
    def __init__(self, plot, parent=None):
        self.icon = qt.QIcon(qt.QPixmap(IconDict["ymintozero"]))
        PlotAction.__init__(self,
                            plot,
                            icon=self.icon,
                            text='Y Min to Zero',
                            tooltip='Shift curve vertically to put min value at 0',
                            triggered=self._yMinToZeroCurve,
                            parent=parent)

    def _yMinToZeroCurve(self):
        curve = _getOneCurve(self.plot)
        if curve is None:
            return
        x0, y0, legend0, info0, _params = curve

        x1 = x0 * 1
        y1 = y0 - min(y0)
        legend1 = "(%s) - ymin" % legend0

        info1 = _updated_info(info0, legend0, "forceymintozero")

        self.plot.addCurve(x1, y1, legend1,
                           info=info1)


class SubtractAction(PlotAction):
    """Subtract active curve from all curves.

    """
    def __init__(self, plot, parent=None):
        self.icon = qt.QIcon(qt.QPixmap(IconDict["subtract"]))
        PlotAction.__init__(self,
                            plot,
                            icon=self.icon,
                            text='Subtract Active Curve',
                            tooltip='Subtract active curve from all curves',
                            triggered=self._subtractCurve,
                            parent=parent)

    def _subtractCurve(self):
        active_curve = _getOneCurve(self.plot)
        all_curves = self.plot.getAllCurves()

        #############################################################
        if active_curve is None:
            return

        x0, y0, legend0, info0, params0 = active_curve

        ylabel0 = params0.get("ylabel", "Y0")
        if ylabel0 is None:
            ylabel0 = "Y0"

        for x, y, legend, info, params in all_curves:
            # (y1 - y0) is equivalent to 2 * average(-y0, y1)
            XX = [x0, x]
            YY = [-y0, y]
            xplot, yplot = _simpleMath.average(XX, YY)
            yplot *= 2
            legend1 = "(%s - %s)" % (legend, legend0)

            ylabel = params0.get("ylabel", "Y")
            if ylabel is None:
                ylabel = "Y"

            ylabel1 = "(%s - %s)" % (ylabel, ylabel0)

            info1 = _updated_info(info, legend, "subtract")
            info1['LabelNames'] = [legend1]

            self.plot.removeCurve(legend)
            self.plot.addCurve(xplot, yplot, legend1,
                               info=info1, ylabel=ylabel1)