IntensityView.py 10.2 KB
Newer Older
Damien Naudet's avatar
WIP    
Damien Naudet committed
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
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2015-2016 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.
#
# ###########################################################################*/

from __future__ import absolute_import

__authors__ = ["D. Naudet"]
__license__ = "MIT"
__date__ = "15/09/2016"

import numpy as np

from silx.gui import qt as Qt
from silx.gui.plot import PlotWindow
36
37
38

from matplotlib import cm

Damien Naudet's avatar
WIP    
Damien Naudet committed
39
40
41
from ..model.TreeView import TreeView
from ..model.ModelDef import ModelColumns, ModelRoles
from ..project.XsocsH5Factory import h5NodeToProjectItem
Damien Naudet's avatar
Damien Naudet committed
42
from ..widgets.XsocsPlot2D import XsocsPlot2D
DN's avatar
DN committed
43
44
from ..widgets.Input import StyledLineEdit
from ..widgets.Containers import GroupBox
Damien Naudet's avatar
WIP    
Damien Naudet committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

try:
    from silx.gui.plot.ImageRois import ImageRoiManager
except ImportError:
    # TODO remove this import once the ROIs are added to the silx release.
    from ..silx_imports.ImageRois import ImageRoiManager


class RectRoiWidget(Qt.QWidget):
    sigRoiApplied = Qt.Signal(object)

    def __init__(self, roiManager, parent=None):
        # TODO :
        # support multiple ROIs then batch them
        super(RectRoiWidget, self).__init__(parent)
DN's avatar
DN committed
60

Damien Naudet's avatar
Damien Naudet committed
61
        self.__roiToolBar = roiToolBar = roiManager.toolBar(rois=['rectangle'],
DN's avatar
DN committed
62
63
64
65
66
67
68
69
70
71
72
73
                                        options=['show'])
        roiToolBar.setMovable(False)

        topLayout = Qt.QVBoxLayout(self)

        grpBox = GroupBox('ROI')
        layout = Qt.QGridLayout(grpBox)

        row = 0
        layout.addWidget(roiToolBar, row, 0, 1, 2, Qt.Qt.AlignTop)

        row += 1
Damien Naudet's avatar
Damien Naudet committed
74
        self._xEdit = edit = StyledLineEdit(nChar=6)
DN's avatar
DN committed
75
76
77
78
79
        edit.setReadOnly(True)
        layout.addWidget(Qt.QLabel('x='), row, 0, Qt.Qt.AlignTop)
        layout.addWidget(edit, row, 1, Qt.Qt.AlignTop)

        row += 1
Damien Naudet's avatar
Damien Naudet committed
80
        self._yEdit = edit = StyledLineEdit(nChar=6)
DN's avatar
DN committed
81
82
83
84
85
        edit.setReadOnly(True)
        layout.addWidget(Qt.QLabel('y='), row, 0, Qt.Qt.AlignTop)
        layout.addWidget(edit, row, 1, Qt.Qt.AlignTop)

        row += 1
Damien Naudet's avatar
Damien Naudet committed
86
        self._wEdit = edit = StyledLineEdit(nChar=6)
DN's avatar
DN committed
87
88
89
90
91
        edit.setReadOnly(True)
        layout.addWidget(Qt.QLabel('w='), row, 0, Qt.Qt.AlignTop)
        layout.addWidget(edit, row, 1, Qt.Qt.AlignTop)

        row += 1
Damien Naudet's avatar
Damien Naudet committed
92
        self._hEdit = edit = StyledLineEdit(nChar=6)
DN's avatar
DN committed
93
94
95
96
97
98
99
        edit.setReadOnly(True)
        layout.addWidget(Qt.QLabel('h='), row, 0, Qt.Qt.AlignTop)
        layout.addWidget(edit, row, 1, Qt.Qt.AlignTop)

        row += 1

        hLayout = Qt.QHBoxLayout()
DN's avatar
DN committed
100

Damien Naudet's avatar
WIP    
Damien Naudet committed
101
102
103
104
105
106
107
        style = Qt.QApplication.style()

        icon = style.standardIcon(Qt.QStyle.SP_DialogApplyButton)
        self.__applyBn = applyBn = Qt.QToolButton()
        applyBn.setToolTip('Apply ROI')
        applyBn.setStatusTip('Apply ROI')
        applyBn.setIcon(icon)
DN's avatar
DN committed
108
109
        applyBn.setToolButtonStyle(Qt.Qt.ToolButtonTextBesideIcon)
        applyBn.setText('To Q Space')
Damien Naudet's avatar
WIP    
Damien Naudet committed
110
        applyBn.setEnabled(False)
DN's avatar
DN committed
111
        hLayout.addWidget(applyBn)
Damien Naudet's avatar
WIP    
Damien Naudet committed
112
113
        applyBn.clicked.connect(self.__applyRoi)

DN's avatar
DN committed
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
        icon = style.standardIcon(Qt.QStyle.SP_DialogCloseButton)
        self.__discardBn = discardBn = Qt.QToolButton()
        discardBn.setToolTip('Discard ROI')
        discardBn.setStatusTip('Discard ROI')
        discardBn.setIcon(icon)
        discardBn.setEnabled(False)
        hLayout.addWidget(discardBn, Qt.Qt.AlignRight)
        discardBn.clicked.connect(self.__discardRoi)

        layout.addLayout(hLayout, row, 0, 1, 2, Qt.Qt.AlignCenter)

        # topLayout.setSizeConstraint(Qt.QLayout.SetMinimumSize)

        topLayout.addWidget(grpBox)
        topLayout.addStretch(100)
Damien Naudet's avatar
WIP    
Damien Naudet committed
129
130
131
132
133
134
135
136
137
138

        # TODO : weakref
        self.__roiManager = roiManager
        roiManager.sigRoiDrawingFinished.connect(self.__roiDrawingFinished,
                                                 Qt.Qt.QueuedConnection)
        roiManager.sigRoiRemoved.connect(self.__roiRemoved,
                                         Qt.Qt.QueuedConnection)
        roiManager.sigRoiMoved.connect(self.__roiMoved,
                                       Qt.Qt.QueuedConnection)

Damien Naudet's avatar
Damien Naudet committed
139
140
141
    def sizeHint(self):
        return Qt.QSize(self.__roiToolBar.sizeHint().width() + 10, 0)

Damien Naudet's avatar
WIP    
Damien Naudet committed
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
    def __discardRoi(self, checked):
        self.__roiManager.clear()

    def __applyRoi(self, checked):
        # At the moment we only support one roi at a time.
        roi = self.__roiManager.rois
        roiItem = self.__roiManager.roiItem(roi[0])
        xMin = roiItem.pos[0]
        xMax = xMin + roiItem.width
        yMin = roiItem.pos[1]
        yMax = yMin + roiItem.height
        self.sigRoiApplied.emit([xMin, xMax, yMin, yMax])

    def __roiDrawingFinished(self, event):
        self.__display(event['xdata'], event['ydata'])
        self.__discardBn.setEnabled(True)
        self.__applyBn.setEnabled(True)

    def __clear(self):
        self._xEdit.clear()
        self._yEdit.clear()
        self._wEdit.clear()
        self._hEdit.clear()

    def __display(self, xData, yData):
        xMin, xMax = xData[0], xData[2]
        if xMax < xMin:
            xMin, xMax = xMax, xMin
        yMin, yMax = yData[0], yData[1]
        if yMax < yMin:
            yMin, yMax = yMax, yMin
        self._xEdit.setText(str(xMin))
        self._yEdit.setText(str(yMin))
        self._wEdit.setText(str(xMax - xMin))
        self._hEdit.setText(str(yMax - yMin))

    def __roiRemoved(self, name):
        self.__clear()
        self.__discardBn.setEnabled(False)
        self.__applyBn.setEnabled(False)

    def __roiMoved(self, event):
        self.__display(event['xdata'], event['ydata'])


class IntensityTree(TreeView):
    sigCurrentChanged = Qt.Signal(object)

    def __init__(self, *args, **kwargs):
        super(IntensityTree, self).__init__(*args, **kwargs)
        self.disableDelegateForColumn(1, True)
        for col in range(ModelColumns.ColumnMax):
            if col != ModelColumns.NameColumn:
                self.setColumnHidden(col, True)

    def currentChanged(self, current, previous):
        node = current.data(ModelRoles.InternalDataRole)
        if not node:
            return
        projectItem = h5NodeToProjectItem(node)
        self.sigCurrentChanged.emit(projectItem)


class IntensityView(Qt.QMainWindow):
Damien Naudet's avatar
WIP    
Damien Naudet committed
206
    sigProcessApplied = Qt.Signal(object)
Damien Naudet's avatar
WIP    
Damien Naudet committed
207
208
209

    plot = property(lambda self: self.__plotWindow)

Damien Naudet's avatar
WIP    
Damien Naudet committed
210
211
212
213
214
    def __init__(self,
                 parent,
                 model,
                 node,
                 **kwargs):
Damien Naudet's avatar
WIP    
Damien Naudet committed
215
216
        super(IntensityView, self).__init__(parent=parent)

DN's avatar
DN committed
217
218
        self.setWindowTitle('[XSOCS] {0}'.format(node.h5Path))

Damien Naudet's avatar
Damien Naudet committed
219
        self.__plotWindow = plotWindow = XsocsPlot2D()
Damien Naudet's avatar
Damien Naudet committed
220
221
        plotWindow.setShowMousePosition(True)
        plotWindow.setShowSelectedCoordinates(False)
Damien Naudet's avatar
WIP    
Damien Naudet committed
222
223

        dock = Qt.QDockWidget(self)
Damien Naudet's avatar
WIP    
Damien Naudet committed
224
225
226
        tree = IntensityTree(self, model=model)
        index = node.index()
        tree.setRootIndex(index)
Damien Naudet's avatar
WIP    
Damien Naudet committed
227
228
        tree.sigCurrentChanged.connect(self.__itemSelected)
        dock.setWidget(tree)
Damien Naudet's avatar
WIP    
Damien Naudet committed
229
230
        features = dock.features() ^ Qt.QDockWidget.DockWidgetClosable
        dock.setFeatures(features)
Damien Naudet's avatar
WIP    
Damien Naudet committed
231
232
233
        self.addDockWidget(Qt.Qt.LeftDockWidgetArea, dock)

        self.__roiManager = roiManager = ImageRoiManager(plotWindow)
DN's avatar
DN committed
234
235
236
237
238
        # roiToolBar = roiManager.toolBar(rois=['rectangle'],
        #                                 options=['show'])
        # roiToolBar.addSeparator()
        # plotWindow.addToolBarBreak()
        # plotWindow.addToolBar(roiToolBar)
Damien Naudet's avatar
WIP    
Damien Naudet committed
239
240
241
242

        rectRoiWidget = RectRoiWidget(roiManager)
        rectRoiWidget.sigRoiApplied.connect(self.__roiApplied)

DN's avatar
DN committed
243
244
245
246
247
248

        dock = Qt.QDockWidget(self)
        dock.setWidget(rectRoiWidget)
        features = dock.features() ^ Qt.QDockWidget.DockWidgetClosable
        dock.setFeatures(features)
        self.addDockWidget(Qt.Qt.RightDockWidgetArea, dock)
Damien Naudet's avatar
WIP    
Damien Naudet committed
249
250
251
252
253
254
255
256
257

        self.setCentralWidget(plotWindow)

    def __itemSelected(self, item):
        intensity, positions = item.getScatterData()
        self.setPlotData(positions.pos_0, positions.pos_1, intensity)

    def setPlotData(self, x, y, data):
        plot = self.__plotWindow
Damien Naudet's avatar
Damien Naudet committed
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
        plot.setPlotData(x, y, data)
        # if data.ndim == 1:
        #     # scatter
        #     min_, max_ = data.min(), data.max()
        #     colormap = cm.jet
        #     colors = colormap((data.astype(np.float64) - min_) / (max_ - min_))
        #     plot.addCurve(x, y,
        #                   color=colors,
        #                   symbol='s',
        #                   linestyle='')
        # elif data.ndim == 2:
        #     # image
        #     min_, max_ = data.min(), data.max()
        #     colormap = {'name': 'temperature',
        #                 'normalization': 'linear',
        #                 'autoscale': True,
        #                 'vmin': min_,
        #                 'vmax': max_}
        #     origin = x[0], y[0]
        #     scale = (x[-1] - x[0]) / len(x), (y[-1] - y[0]) / len(y)
        #     plot.addImage(data,
        #                   origin=origin,
        #                   scale=scale,
        #                   colormap=colormap)
        # else:
        #     raise ValueError('data has {0} dimensions, expected 1 or 2.'
        #                      ''.format(data.ndim))
Damien Naudet's avatar
WIP    
Damien Naudet committed
285
286

    def __roiApplied(self, roi):
Damien Naudet's avatar
WIP    
Damien Naudet committed
287
        self.sigProcessApplied.emit(roi)
Damien Naudet's avatar
WIP    
Damien Naudet committed
288
289
290
291


if __name__ == '__main__':
    pass