xftf.py 11.1 KB
Newer Older
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
# 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"


import functools
import logging
from Orange.widgets import gui
from Orange.widgets.settings import Setting
35
from Orange.widgets.widget import OWWidget
36
37
from Orange.widgets.widget import Input, Output
import Orange.data
38
39
from silx.gui import qt
from silx.gui.plot import LegendSelector
payno's avatar
payno committed
40
41
42
43
import est.core.process.larch.xftf
from orangecontrib.est.process import _ProcessForOrangeMixIn
from orangecontrib.est.process import ProcessRunnable
from est.core.types import XASObject
payno's avatar
payno committed
44
45
46
47
48
49
from est.gui.XasObjectViewer import (
    XasObjectViewer,
    ViewType,
    _plot_chir_mag,
    _plot_chir_re,
    _plot_chir_imag,
50
    _plot_masked_chi_weighted_k,
payno's avatar
payno committed
51
)
payno's avatar
payno committed
52
53
54
55
from est.gui.larch.xftf import _MXFTFParameters
from orangecontrib.est.progress import QProgress
from orangecontrib.est.utils import Converter
from orangecontrib.est.widgets.container import _ParameterWindowContainer
56
from ewokscore.registration import Registered
57
58
59

_logger = logging.getLogger(__file__)

60
_USE_THREAD = False
61

62
63
64
65
66

def _get_title(dgroup, title=None):
    """get best title for group"""
    if title is not None:
        return title
payno's avatar
payno committed
67
    data_group = getattr(dgroup, "data", None)
68

payno's avatar
payno committed
69
    for attr in ("title", "plot_title", "filename", "name", "__name__"):
70
71
72
73
74
75
76
77
78
79
80
        t = getattr(dgroup, attr, None)
        if t is not None:
            return t
        if data_group is not None:
            t = getattr(data_group, attr, None)
            if t is not None:
                return t

    return repr(dgroup)


81
class XFTFWindow(qt.QMainWindow):
82
83
84
85
    def __init__(self, parent=None):
        qt.QMainWindow.__init__(self, parent)

        # xas object viewer
86
        mapKeys = ["mu", "chir", "chir_mag", "chir_re", "chir_im", "chir_pha"]
87
88
89
        self.xasObjViewer = XasObjectViewer(
            mapKeys=mapKeys, spectrumPlots=("chi", "masked_chi_weighted_k")
        )
90
91
        self.xasObjViewer._spectrumViews[0]._plotWidget.getXAxis().setLabel(
            "Radial distance (angstrom)"
payno's avatar
payno committed
92
        )
93
94
95
        self.xasObjViewer._spectrumViews[1]._plotWidget.getXAxis().setLabel(
            "wavenumber (angstrom^-1)"
        )
96
        self.setCentralWidget(self.xasObjViewer)
payno's avatar
payno committed
97
98
99
        self._parametersWindow = _ParameterWindowContainer(
            parent=self, parametersWindow=_MXFTFParameters
        )
100
101
102
103
104
105
106
107
        dockWidget = qt.QDockWidget(parent=self)

        # parameters window
        dockWidget.setWidget(self._parametersWindow)
        self.addDockWidget(qt.Qt.RightDockWidgetArea, dockWidget)
        dockWidget.setAllowedAreas(qt.Qt.RightDockWidgetArea | qt.Qt.LeftDockWidgetArea)
        dockWidget.setFeatures(qt.QDockWidget.NoDockWidgetFeatures)

108
109
        # FT legend selector
        self._ftLegendDockWidget = LegendSelector.LegendsDockWidget(
110
            parent=self, plot=self.xasObjViewer._spectrumViews[0]._plotWidget
111
112
        )
        self._ftLegendDockWidget.setAllowedAreas(
payno's avatar
payno committed
113
114
            qt.Qt.RightDockWidgetArea | qt.Qt.LeftDockWidgetArea
        )
115
116
        self._ftLegendDockWidget.setFeatures(qt.QDockWidget.NoDockWidgetFeatures)
        self.addDockWidget(qt.Qt.RightDockWidgetArea, self._ftLegendDockWidget)
117
118

        # volume key selection
payno's avatar
payno committed
119
120
121
        self.addDockWidget(
            qt.Qt.RightDockWidgetArea, self.xasObjViewer._mapView.keySelectionDocker
        )
122
123

        # plot settings
124
        for ope in (_plot_chir_mag, _plot_chir_re, _plot_chir_imag):
125
            self.xasObjViewer._spectrumViews[0].addCurveOperation(ope)
126
127
128
        self.xasObjViewer._spectrumViews[1].addCurveOperation(
            _plot_masked_chi_weighted_k
        )
129
130
131
132
133
134
135
136
137
138
        self.setWindowFlags(qt.Qt.Widget)

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

        # set up
        self._updateLegendView()

    def _updateLegendView(self):
        index, viewType = self.xasObjViewer.getViewType()
139
140
141
        self._ftLegendDockWidget.setVisible(
            viewType is ViewType.spectrum and index == 0
        )
payno's avatar
payno committed
142
143
144
        self.xasObjViewer._mapView.keySelectionDocker.setVisible(
            viewType is ViewType.map
        )
145

146
    def getNCurves(self):
147
        return len(self.xasObjViewer._spectrumViews[0]._plotWidget.getAllCurves())
148

149
    def setKWeight(self, kweight):
150
        self._parametersWindow._mainwidget.setRWeight(kweight)
151

152

153
154
class XFTFOW(
    _ProcessForOrangeMixIn,
155
156
    OWWidget,
    Registered,
157
):
158
159
160
    """
    Widget used for signal extraction
    """
payno's avatar
payno committed
161

162
    name = "xftf"
payno's avatar
payno committed
163
    id = "orange.widgets.est.larch.xftf"
payno's avatar
payno committed
164
165
166
167
    description = (
        "forward XAFS Fourier transform, from chi(k) to chi(R), "
        "using common XAFS conventions."
    )
168
169
170
    icon = "icons/xftf.png"
    priority = 2
    category = "esrfWidgets"
payno's avatar
payno committed
171
    keywords = ["spectroscopy", "xftf", "fourier transform"]
172
173
174

    want_main_area = True
    resizing_enabled = True
175
    allows_cycle = False
176
    ewokstaskclass = est.core.process.larch.xftf.Larch_xftf
177
178
179
180

    _larchSettings = Setting(dict())
    """Store the configuration of the larch configuration"""

181
    class Inputs:
payno's avatar
payno committed
182
        xas_obj = Input("xas_obj", XASObject, default=True)
183
184
        # simple compatibility for some Orange widget and especialy the
        # 'spectroscopy add-on'
payno's avatar
payno committed
185
        data_table = Input("Data", Orange.data.Table)
186
187

    class Outputs:
188
        xas_obj = Output("xas_obj", XASObject)
189
190
191
        # by default we want to avoid sending 'Orange.data.Table' to avoid
        # loosing the XASObject flow process and results.

192
193
194
    def __init__(self):
        super().__init__()
        self._latest_xas_obj = None
195
        self._window = XFTFWindow(parent=self)
payno's avatar
payno committed
196
        layout = gui.vBox(self.mainArea, "xftf").layout()
197
        layout.addWidget(self._window)
payno's avatar
payno committed
198
        self._window.xasObjViewer.setWindowTitle("spectra")
199
200
201
202
203
204
205
206

        # manage settings
        if self._larchSettings != dict():
            self._window._parametersWindow.setParameters(self._larchSettings)

        # connect signals / slots
        self._window._parametersWindow.sigChanged.connect(self._updateProcess)

207
208
        # required to display advancement
        if _USE_THREAD is False:
payno's avatar
payno committed
209
            self._advancement = QProgress("xftf")
210
211
            self._advancement.sigProgress.connect(self._setProgressValue)

212
        # set up (insure settings will be store
213
        self._update_settings()
214

215
        # self.handleNewSignals()
216

217
218
219
220
221
222
223
224
    def _updateProcess(self):
        self._update_settings()
        if self._latest_xas_obj:
            self.process(self._latest_xas_obj)

    def _update_settings(self):
        self._larchSettings = self._window._parametersWindow.getParameters()

225
226
227
228
229
230
231
    @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
232
233
234
235
236
    def process(self, xas_obj):
        if xas_obj is None:
            return

        if not self._canProcess():
payno's avatar
payno committed
237
238
239
240
            _logger.warning(
                "There is some processing on going already, will"
                "not process the new dataset"
            )
241

242
        # update k weight values if any received
payno's avatar
payno committed
243
244
        if "SET_KWEIGHT" in xas_obj.configuration:
            kweight = xas_obj.configuration["SET_KWEIGHT"]
245
246
            if kweight is not None:
                self._window.setKWeight(kweight)
payno's avatar
payno committed
247
                self._window._parametersWindow._mainwidget._kWeightSB.setEnabled(False)
248
        else:
payno's avatar
payno committed
249
            self._window._parametersWindow._mainwidget._kWeightSB.setEnabled(True)
250
        self._latest_xas_obj = xas_obj
251
252
253
        self._startProcess()

        # setup the normalization process
254
        inputs = {"xas_obj": xas_obj}
255
        if _USE_THREAD is True:
256
            process_obj = QLarch_xftf(inputs=inputs)
257
            process_obj._advancement.sigProgress.connect(self._setProgressValue)
258
            process_obj.set_properties(
payno's avatar
payno committed
259
260
261
262
                {
                    "_larchSettings": self._window._mainwidget._parametersWindow.getParameters()
                }
            )
263
264
265
            # update the processing thread
            thread = self.getProcessingThread()
            thread.init(process_obj=process_obj, xas_obj=self._latest_xas_obj)
payno's avatar
payno committed
266
267
268
            self._callback_finish = functools.partial(
                self._endProcess, self._latest_xas_obj
            )
269
270
271
            thread.finished.connect(self._callback_finish)
            # start processing
            thread.start(priority=qt.QThread.LowPriority)
272
273
274
275
        else:
            # manage advancement
            self._advancement.setAdvancement(0)
            self._advancement.setMaxSpectrum(self._latest_xas_obj.n_spectrum)
276
            process_obj = est.core.process.larch.xftf.Larch_xftf(inputs=inputs)
277
            process_obj.advancement = self._advancement
278
            process_obj.set_properties(
payno's avatar
payno committed
279
280
                {"_larchSettings": self._window._parametersWindow.getParameters()}
            )
281
282
283
284
            # hack (reason explained in the thread part)
            # to avoid gui freeze, processevents after each spectrum process
            process_obj.addCallback(qt.QApplication.instance().processEvents)
            process_obj.addCallback(self._advancement.increaseAdvancement)
285
            process_obj.run()
286
287
            self._callback_finish = None
            self._endProcess(self._latest_xas_obj)
288
289


payno's avatar
payno committed
290
class QLarch_xftf(est.core.process.larch.xftf.Larch_xftf):
291
292
293
294
    """
    Normalization able to give advancement using qt.Signal and QThreadPool
    """

295
296
    def __init__(self, *args, **kwargs):
        est.core.process.larch.xftf.Larch_xftf.__init__(self, *args, **kwargs)
payno's avatar
payno committed
297
        self._advancement = QProgress("xftf")
298
299
300
301
302

    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
303
304
305
306
307
308
            runnable = ProcessRunnable(
                fct=est.core.process.larch.xftf.process_spectr_xftf,
                spectrum=spectrum,
                configuration=xas_obj.configuration,
                callback=self._advancement.increaseAdvancement,
            )
309
310
            self.pool.start(runnable)
        self.pool.waitForDone()