summaryrefslogtreecommitdiff
path: root/silx/gui/plot/tools/profile/_BaseProfileToolBar.py
blob: ced81dacfd6cf82c0b4d9b149b2fa00654541f66 (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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2018-2019 European Synchrotron Radiation Facility
#
# 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 provides the base class for profile toolbars."""

__authors__ = ["T. Vincent"]
__license__ = "MIT"
__date__ = "28/06/2018"


import logging
import weakref

import numpy

from silx.utils.weakref import WeakMethodProxy
from silx.gui import qt, icons, colors
from silx.gui.plot import PlotWidget, items
from silx.gui.plot.ProfileMainWindow import ProfileMainWindow
from silx.gui.plot.tools.roi import RegionOfInterestManager
from silx.gui.plot.items import roi as roi_items


_logger = logging.getLogger(__name__)


class _BaseProfileToolBar(qt.QToolBar):
    """Base class for QToolBar plot profiling tools

    :param parent: See :class:`QToolBar`.
    :param plot: :class:`~silx.gui.plot.PlotWidget` on which to operate.
    :param str title: See :class:`QToolBar`.
    """

    sigProfileChanged = qt.Signal()
    """Signal emitted when the profile has changed"""

    def __init__(self, parent=None, plot=None, title=''):
        super(_BaseProfileToolBar, self).__init__(title, parent)

        self.__profile = None
        self.__profileTitle = ''

        assert isinstance(plot, PlotWidget)
        self._plotRef = weakref.ref(
            plot, WeakMethodProxy(self.__plotDestroyed))

        self._profileWindow = None

        # Set-up interaction manager
        roiManager = RegionOfInterestManager(plot)
        self._roiManagerRef = weakref.ref(roiManager)

        roiManager.sigInteractiveModeFinished.connect(self.__interactionFinished)
        roiManager.sigRoiChanged.connect(self.updateProfile)
        roiManager.sigRoiAdded.connect(self.__roiAdded)

        # Add interactive mode actions
        for kind, icon, tooltip in (
                (roi_items.HorizontalLineROI, 'shape-horizontal',
                 'Enables horizontal line profile selection mode'),
                (roi_items.VerticalLineROI, 'shape-vertical',
                 'Enables vertical line profile selection mode'),
                (roi_items.LineROI, 'shape-diagonal',
                 'Enables line profile selection mode')):
            action = roiManager.getInteractionModeAction(kind)
            action.setIcon(icons.getQIcon(icon))
            action.setToolTip(tooltip)
            self.addAction(action)

        # Add clear action
        action = qt.QAction(icons.getQIcon('profile-clear'),
                            'Clear Profile', self)
        action.setToolTip('Clear the profile')
        action.setCheckable(False)
        action.triggered.connect(self.clearProfile)
        self.addAction(action)

        # Initialize color
        self._color = None
        self.setColor('red')

        # Listen to plot limits changed
        plot.getXAxis().sigLimitsChanged.connect(self.updateProfile)
        plot.getYAxis().sigLimitsChanged.connect(self.updateProfile)

        # Listen to plot scale
        plot.getXAxis().sigScaleChanged.connect(self.__plotAxisScaleChanged)
        plot.getYAxis().sigScaleChanged.connect(self.__plotAxisScaleChanged)

        self.setDefaultProfileWindowEnabled(True)

    def getProfilePoints(self, copy=True):
        """Returns the profile sampling points as (x, y) or None

        :param bool copy: True to get a copy,
                          False to get internal arrays (do not modify)
        :rtype: Union[numpy.ndarray,None]
        """
        if self.__profile is None:
            return None
        else:
            return numpy.array(self.__profile[0], copy=copy)

    def getProfileValues(self, copy=True):
        """Returns the values of the profile or None

        :param bool copy: True to get a copy,
                          False to get internal arrays (do not modify)
        :rtype: Union[numpy.ndarray,None]
        """
        if self.__profile is None:
            return None
        else:
            return numpy.array(self.__profile[1], copy=copy)

    def getProfileTitle(self):
        """Returns the profile title

        :rtype: str
        """
        return self.__profileTitle

    # Handle plot reference

    def __plotDestroyed(self, ref):
        """Handle finalization of PlotWidget

        :param ref: weakref to the plot
        """
        self._plotRef = None
        self.setEnabled(False)  # Profile is pointless
        for action in self.actions():  # TODO useful?
            self.removeAction(action)

    def getPlotWidget(self):
        """The :class:`~silx.gui.plot.PlotWidget` associated to the toolbar.

        :rtype: Union[~silx.gui.plot.PlotWidget,None]
        """
        return None if self._plotRef is None else self._plotRef()

    def _getRoiManager(self):
        """Returns the used ROI manager

        :rtype: RegionOfInterestManager
        """
        return self._roiManagerRef()

    # Profile Plot

    def isDefaultProfileWindowEnabled(self):
        """Returns True if the default floating profile window is used

        :rtype: bool
        """
        return self.getDefaultProfileWindow() is not None

    def setDefaultProfileWindowEnabled(self, enabled):
        """Set whether to use or not the default floating profile window.

        :param bool enabled: True to use, False to disable
        """
        if self.isDefaultProfileWindowEnabled() != enabled:
            if enabled:
                self._profileWindow = ProfileMainWindow(self)
                self._profileWindow.sigClose.connect(self.clearProfile)
                self.sigProfileChanged.connect(self.__updateDefaultProfilePlot)

            else:
                self.sigProfileChanged.disconnect(self.__updateDefaultProfilePlot)
                self._profileWindow.sigClose.disconnect(self.clearProfile)
                self._profileWindow.close()
                self._profileWindow = None

    def getDefaultProfileWindow(self):
        """Returns the default floating profile window if in use else None.

        See :meth:`isDefaultProfileWindowEnabled`

        :rtype: Union[ProfileMainWindow,None]
        """
        return self._profileWindow

    def __updateDefaultProfilePlot(self):
        """Update the plot of the default profile window"""
        profileWindow = self.getDefaultProfileWindow()
        if profileWindow is None:
            return

        profilePlot = profileWindow.getPlot()
        if profilePlot is None:
            return

        profilePlot.clear()
        profilePlot.setGraphTitle(self.getProfileTitle())

        points = self.getProfilePoints(copy=False)
        values = self.getProfileValues(copy=False)

        if points is not None and values is not None:
            if (numpy.abs(points[-1, 0] - points[0, 0]) >
                    numpy.abs(points[-1, 1] - points[0, 1])):
                xProfile = points[:, 0]
                profilePlot.getXAxis().setLabel('X')
            else:
                xProfile = points[:, 1]
                profilePlot.getXAxis().setLabel('Y')

            profilePlot.addCurve(
                xProfile, values, legend='Profile', color=self._color)

        self._showDefaultProfileWindow()

    def _showDefaultProfileWindow(self):
        """If profile window was created by this toolbar,
        try to avoid overlapping with the toolbar's parent window.
        """
        profileWindow = self.getDefaultProfileWindow()
        roiManager = self._getRoiManager()
        if profileWindow is None or roiManager is None:
            return

        if roiManager.isStarted() and not profileWindow.isVisible():
            profileWindow.show()
            profileWindow.raise_()

            window = self.window()
            winGeom = window.frameGeometry()
            qapp = qt.QApplication.instance()
            desktop = qapp.desktop()
            screenGeom = desktop.availableGeometry(self)
            spaceOnLeftSide = winGeom.left()
            spaceOnRightSide = screenGeom.width() - winGeom.right()

            frameGeometry = profileWindow.frameGeometry()
            profileWindowWidth = frameGeometry.width()
            if profileWindowWidth < spaceOnRightSide:
                # Place profile on the right
                profileWindow.move(winGeom.right(), winGeom.top())
            elif profileWindowWidth < spaceOnLeftSide:
                # Place profile on the left
                profileWindow.move(
                    max(0, winGeom.left() - profileWindowWidth), winGeom.top())

    # Handle plot in log scale

    def __plotAxisScaleChanged(self, scale):
        """Handle change of axis scale in the plot widget"""
        plot = self.getPlotWidget()
        if plot is None:
            return

        xScale = plot.getXAxis().getScale()
        yScale = plot.getYAxis().getScale()

        if xScale == items.Axis.LINEAR and yScale == items.Axis.LINEAR:
            self.setEnabled(True)

        else:
            roiManager = self._getRoiManager()
            if roiManager is not None:
                roiManager.stop()  # Stop interactive mode

            self.clearProfile()
            self.setEnabled(False)

    # Profile color

    def getColor(self):
        """Returns the color used for the profile and ROI

        :rtype: QColor
        """
        return qt.QColor.fromRgbF(*self._color)

    def setColor(self, color):
        """Set the color to use for ROI and profile.

        :param color:
           Either a color name, a QColor, a list of uint8 or float in [0, 1].
        """
        self._color = colors.rgba(color)
        roiManager = self._getRoiManager()
        if roiManager is not None:
            roiManager.setColor(self._color)
            for roi in roiManager.getRois():
                roi.setColor(self._color)
        self.updateProfile()

    # Handle ROI manager

    def __interactionFinished(self):
        """Handle end of interactive mode"""
        self.clearProfile()

        profileWindow = self.getDefaultProfileWindow()
        if profileWindow is not None:
            profileWindow.hide()

    def __roiAdded(self, roi):
        """Handle new ROI"""
        roi.setName('Profile')
        roi.setEditable(True)

        # Remove any other ROI
        roiManager = self._getRoiManager()
        if roiManager is not None:
            for regionOfInterest in list(roiManager.getRois()):
                if regionOfInterest is not roi:
                    roiManager.removeRoi(regionOfInterest)

    def computeProfile(self, x0, y0, x1, y1):
        """Compute corresponding profile

        Override in subclass to compute profile

        :param float x0: Profile start point X coord
        :param float y0: Profile start point Y coord
        :param float x1: Profile end point X coord
        :param float y1: Profile end point Y coord
        :return: (points, values) profile data or None
        """
        return None

    def computeProfileTitle(self, x0, y0, x1, y1):
        """Compute corresponding plot title

        This can be overridden to change title behavior.

        :param float x0: Profile start point X coord
        :param float y0: Profile start point Y coord
        :param float x1: Profile end point X coord
        :param float y1: Profile end point Y coord
        :return: Title to use
        :rtype: str
        """
        if x0 == x1:
            title = 'X = %g; Y = [%g, %g]' % (x0, y0, y1)
        elif y0 == y1:
            title = 'Y = %g; X = [%g, %g]' % (y0, x0, x1)
        else:
            m = (y1 - y0) / (x1 - x0)
            b = y0 - m * x0
            title = 'Y = %g * X %+g' % (m, b)

        return title

    def updateProfile(self):
        """Update profile according to current ROI"""
        roiManager = self._getRoiManager()
        if roiManager is None:
            roi = None
        else:
            rois = roiManager.getRois()
            roi = None if len(rois) == 0 else rois[0]

        if roi is None:
            self._setProfile(profile=None, title='')
            return

        # Get end points
        if isinstance(roi, roi_items.LineROI):
            points = roi.getEndPoints()
            x0, y0 = points[0]
            x1, y1 = points[1]
        elif isinstance(roi, (roi_items.VerticalLineROI, roi_items.HorizontalLineROI)):
            plot = self.getPlotWidget()
            if plot is None:
                self._setProfile(profile=None, title='')
                return

            elif isinstance(roi, roi_items.HorizontalLineROI):
                x0, x1 = plot.getXAxis().getLimits()
                y0 = y1 = roi.getPosition()

            elif isinstance(roi, roi_items.VerticalLineROI):
                x0 = x1 = roi.getPosition()
                y0, y1 = plot.getYAxis().getLimits()

        else:
            raise RuntimeError('Unsupported ROI for profile: {}'.format(roi.__class__))

        if x1 < x0 or (x1 == x0 and y1 < y0):
            # Invert points
            x0, y0, x1, y1 = x1, y1, x0, y0

        profile = self.computeProfile(x0, y0, x1, y1)
        title = self.computeProfileTitle(x0, y0, x1, y1)
        self._setProfile(profile=profile, title=title)

    def _setProfile(self, profile=None, title=''):
        """Set profile data and emit signal.

        :param profile: points and profile values
        :param str title:
        """
        self.__profile = profile
        self.__profileTitle = title

        self.sigProfileChanged.emit()

    def clearProfile(self):
        """Clear the current line ROI and associated profile"""
        roiManager = self._getRoiManager()
        if roiManager is not None:
            roiManager.clear()

        self._setProfile(profile=None, title='')