ft.py 9.4 KB
Newer Older
payno's avatar
payno 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
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2016-2017 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.
#
# ###########################################################################*/

__authors__ = ["H. Payno"]
__license__ = "MIT"
__date__ = "06/07/2019"


31
32
33
import functools
import logging

payno's avatar
payno committed
34
from Orange.widgets import gui
payno's avatar
payno committed
35
from Orange.widgets.settings import Setting
36
from Orange.widgets.widget import OWWidget
37
38
from Orange.widgets.widget import Input, Output
import Orange.data
payno's avatar
payno committed
39
40
41
from PyMca5.PyMcaGui.physics.xas.XASFourierTransformParameters import (
    XASFourierTransformParameters,
)
42
43
44
from silx.gui import qt
from silx.gui.plot import LegendSelector

payno's avatar
payno committed
45
import est.core.process.pymca.ft
payno's avatar
payno committed
46
from orangecontrib.est.process import _ProcessForOrangeMixIn, ProcessRunnable
payno's avatar
payno committed
47
48
49
50
from est.core.types import XASObject
from est.gui.XasObjectViewer import XasObjectViewer, ViewType
from est.gui.XasObjectViewer import _normalized_exafs, _ft_window_plot
from est.gui.XasObjectViewer import _ft_intensity_plot, _ft_imaginary_plot
51
from ewokscore.registration import Registered
payno's avatar
payno committed
52

payno's avatar
payno committed
53
54
from orangecontrib.est.progress import QProgress
from orangecontrib.est.utils import Converter
payno's avatar
payno committed
55
from orangecontrib.est.widgets.container import _ParameterWindowContainer
payno's avatar
payno committed
56

payno's avatar
payno committed
57
58
59
_logger = logging.getLogger(__file__)


payno's avatar
payno committed
60
61
62
class FTWindow(qt.QMainWindow):
    def __init__(self, parent=None):
        qt.QMainWindow.__init__(self, parent)
63
64

        # xas object viewer
payno's avatar
payno committed
65
66
67
        self.xasObjViewer = XasObjectViewer(
            mapKeys=["Mu"], spectrumPlots=("FTWindow", "FTIntensity")
        )
68
        self.xasObjViewer._spectrumViews[0]._plotWidget.getXAxis().setLabel("K")
69

payno's avatar
payno committed
70
71
72
73
74
75
        self.xasObjViewer._spectrumViews[1]._plotWidget.getXAxis().setLabel(
            "R (Angstrom)"
        )
        self.xasObjViewer._spectrumViews[1]._plotWidget.getYAxis().setLabel(
            "Arbitrary Units"
        )
76
        self.setCentralWidget(self.xasObjViewer)
payno's avatar
payno committed
77
78
79
        self._pymcaWindow = _ParameterWindowContainer(
            parent=self, parametersWindow=XASFourierTransformParameters
        )
payno's avatar
payno committed
80
81
        dockWidget = qt.QDockWidget(parent=self)

82
        # pymca window
payno's avatar
payno committed
83
84
85
86
        dockWidget.setWidget(self._pymcaWindow)
        self.addDockWidget(qt.Qt.RightDockWidgetArea, dockWidget)
        dockWidget.setAllowedAreas(qt.Qt.RightDockWidgetArea | qt.Qt.LeftDockWidgetArea)
        dockWidget.setFeatures(qt.QDockWidget.NoDockWidgetFeatures)
87

88
        # legend selectors
payno's avatar
payno committed
89
        self.legendDockWidget1 = LegendSelector.LegendsDockWidget(
90
            parent=self, plot=self.xasObjViewer._spectrumViews[0]._plotWidget
payno's avatar
payno committed
91
92
93
94
        )
        self.legendDockWidget1.setAllowedAreas(
            qt.Qt.RightDockWidgetArea | qt.Qt.LeftDockWidgetArea
        )
95
96
97
        self.legendDockWidget1.setFeatures(qt.QDockWidget.NoDockWidgetFeatures)
        self.addDockWidget(qt.Qt.RightDockWidgetArea, self.legendDockWidget1)

payno's avatar
payno committed
98
        self.legendDockWidget2 = LegendSelector.LegendsDockWidget(
99
            parent=self, plot=self.xasObjViewer._spectrumViews[1]._plotWidget
payno's avatar
payno committed
100
101
102
103
        )
        self.legendDockWidget2.setAllowedAreas(
            qt.Qt.RightDockWidgetArea | qt.Qt.LeftDockWidgetArea
        )
104
105
        self.legendDockWidget2.setFeatures(qt.QDockWidget.NoDockWidgetFeatures)
        self.addDockWidget(qt.Qt.RightDockWidgetArea, self.legendDockWidget2)
payno's avatar
payno committed
106

107
        # volume key selection
payno's avatar
payno committed
108
109
110
        self.addDockWidget(
            qt.Qt.RightDockWidgetArea, self.xasObjViewer._mapView.keySelectionDocker
        )
111

112
        # plot settings
113
114
115
        for ope in (_normalized_exafs, _ft_window_plot):
            self.xasObjViewer._spectrumViews[0].addCurveOperation(ope)

116
        for ope in (_ft_intensity_plot, _ft_imaginary_plot):
117
            self.xasObjViewer._spectrumViews[1].addCurveOperation(ope)
118

119
120
121
122
123
124
125
126
        self.setWindowFlags(qt.Qt.Widget)

        # connect signal / slot
        self.xasObjViewer.viewTypeChanged.connect(self._updateLegendView)

        # set up
        self._updateLegendView()

127
128
129
    def getNCurves(self):
        return len(self.plot.getAllCurves())

130
    def _updateLegendView(self):
131
132
133
        index, viewType = self.xasObjViewer.getViewType()
        self.legendDockWidget1.setVisible(viewType is ViewType.spectrum and index == 0)
        self.legendDockWidget2.setVisible(viewType is ViewType.spectrum and index == 1)
payno's avatar
payno committed
134
135
136
        self.xasObjViewer._mapView.keySelectionDocker.setVisible(
            viewType is ViewType.map
        )
137

payno's avatar
payno committed
138

139
140
class FTOW(
    _ProcessForOrangeMixIn,
141
142
    OWWidget,
    Registered,
143
):
payno's avatar
payno committed
144
145
146
    """
    Widget used for signal extraction
    """
payno's avatar
payno committed
147

payno's avatar
payno committed
148
    name = "fourier transform"
payno's avatar
payno committed
149
    id = "orange.widgets.est.pymca.ft"
150
    description = "Progress fourier transform"
payno's avatar
payno committed
151
    icon = "icons/ft.png"
152
    priority = 4
payno's avatar
payno committed
153
154
155
156
157
    category = "esrfWidgets"
    keywords = ["spectroscopy", "signal", "fourier", "transform", "fourier transform"]

    want_main_area = True
    resizing_enabled = True
158
    allows_cycle = False
159
    ewokstaskclass = est.core.process.pymca.ft.PyMca_ft
payno's avatar
payno committed
160

payno's avatar
payno committed
161
162
163
    _pymcaSettings = Setting(dict())
    """Store the configuration of the PyMca XASClass"""

164
    class Inputs:
payno's avatar
payno committed
165
        xas_obj = Input("xas_obj", XASObject, default=True)
166
167
        # simple compatibility for some Orange widget and especialy the
        # 'spectroscopy add-on'
payno's avatar
payno committed
168
        data_table = Input("Data", Orange.data.Table)
169
170

    class Outputs:
171
        xas_obj = Output("xas_obj", XASObject)
172
173
174
        # by default we want to avoid sending 'Orange.data.Table' to avoid
        # loosing the XASObject flow process and results.

payno's avatar
payno committed
175
176
    def __init__(self):
        super().__init__()
177
        self._latest_xas_obj = None
178
        self._window = FTWindow(parent=self)
payno's avatar
payno committed
179
        layout = gui.vBox(self.mainArea, "fourier transform").layout()
payno's avatar
payno committed
180
181
        layout.addWidget(self._window)

182
183
184
        # progress
        self._progress = gui.ProgressBar(self, 100)

payno's avatar
payno committed
185
186
187
188
        # manage settings
        if self._pymcaSettings != dict():
            self._window._pymcaWindow.setParameters(self._pymcaSettings)

payno's avatar
payno committed
189
        # signal / slot connection
190
191
        # connect signals / slots
        self._window._pymcaWindow.sigChanged.connect(self._updateProcess)
payno's avatar
payno committed
192

193
        # self.handleNewSignals()
194

payno's avatar
payno committed
195
    def _updateProcess(self, *arv, **kwargs):
payno's avatar
payno committed
196
        self._update_settings()
197
198
        if self._latest_xas_obj:
            self.process(xas_obj=self._latest_xas_obj)
payno's avatar
payno committed
199

200
201
202
203
204
205
206
    @Inputs.data_table
    def processFrmDataTable(self, data_table):
        if data_table is None:
            return
        self.process(Converter.toXASObject(data_table=data_table))

    @Inputs.xas_obj
207
208
    def process(self, xas_obj):
        if xas_obj is None:
payno's avatar
payno committed
209
            return
payno's avatar
payno committed
210

211
        if not self._canProcess():
payno's avatar
payno committed
212
213
214
215
            _logger.warning(
                "There is some processing on going already, will"
                "not process the new dataset"
            )
216

217
        self._latest_xas_obj = xas_obj
218
        self._startProcess()
219
220

        # setup the ft process
221
        process_obj = QPyMca_ft(inputs={"xas_obj": xas_obj})
222
        process_obj._advancement.sigProgress.connect(self._setProgressValue)
223
        process_obj.set_properties(
payno's avatar
payno committed
224
225
            {"_pymcaSettings": self._window._pymcaWindow.getParameters()}
        )
payno's avatar
payno committed
226

227
228
        # update the processing thread
        thread = self.getProcessingThread()
229
        thread.init(process_obj=process_obj, xas_obj=self._latest_xas_obj)
payno's avatar
payno committed
230
231
232
        self._callback_finish = functools.partial(
            self._endProcess, self._latest_xas_obj
        )
233
234
235
236
        thread.finished.connect(self._callback_finish)

        # start processing
        thread.start(priority=qt.QThread.LowPriority)
payno's avatar
payno committed
237

payno's avatar
payno committed
238
239
    def _update_settings(self):
        self._pymcaSettings = self._window._pymcaWindow.getParameters()
240
241
242
243
244

    def _setProgressValue(self, value):
        self._progress.widget.progressBarSet(value)


payno's avatar
payno committed
245
class QPyMca_ft(est.core.process.pymca.ft.PyMca_ft):
246
247
248
    """
    Normalization able to give advancement using qt.Signal and QThreadPool
    """
payno's avatar
payno committed
249

250
251
    def __init__(self, *args, **kwargs):
        est.core.process.pymca.ft.PyMca_ft.__init__(self, *args, **kwargs)
payno's avatar
payno committed
252
        self._advancement = QProgress("normalization")
253
254
255
256
257

    def _pool_process(self, xas_obj):
        self.pool = qt.QThreadPool()
        self.pool.setMaxThreadCount(5)
        for spectrum in xas_obj.spectra:
payno's avatar
payno committed
258
259
260
261
262
263
            runnable = ProcessRunnable(
                fct=est.core.process.pymca.ft.process_spectr_ft,
                spectrum=spectrum,
                configuration=xas_obj.configuration,
                callback=self._advancement.increaseAdvancement,
            )
264
265
            self.pool.start(runnable)
        self.pool.waitForDone()