xftf.py 11.4 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
57
58

_logger = logging.getLogger(__file__)

59
_USE_THREAD = False
60

61
62
63
64
65

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

payno's avatar
payno committed
68
    for attr in ("title", "plot_title", "filename", "name", "__name__"):
69
70
71
72
73
74
75
76
77
78
79
        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)


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

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

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

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

        # plot settings
123
        for ope in (_plot_chir_mag, _plot_chir_re, _plot_chir_imag):
124
            self.xasObjViewer._spectrumViews[0].addCurveOperation(ope)
125
126
127
        self.xasObjViewer._spectrumViews[1].addCurveOperation(
            _plot_masked_chi_weighted_k
        )
128
129
130
131
132
133
134
135
136
137
        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()
138
139
140
        self._ftLegendDockWidget.setVisible(
            viewType is ViewType.spectrum and index == 0
        )
payno's avatar
payno committed
141
142
143
        self.xasObjViewer._mapView.keySelectionDocker.setVisible(
            viewType is ViewType.map
        )
144

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

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

151

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

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

    want_main_area = True
    resizing_enabled = True
173
    allows_cycle = False
174
    ewokstaskclass = est.core.process.larch.xftf.Larch_xftf
175
176

    _larchSettings = Setting(dict())
177
178
    # kept for compatibility
    static_input = Setting({"xftf": None, "xas_obj": None})
179
180
    """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

        # manage settings
201
202
203
204
205
        larch_settings = self.static_input.get("xftf", None)
        if larch_settings is None:
            larch_settings = self._larchSettings
        if larch_settings != dict():
            self._window._parametersWindow.setParameters(larch_settings)
206
207
208
209

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

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

215
        # set up (insure settings will be store
216
        self._update_settings()
217

218
        # self.handleNewSignals()
219

220
221
222
223
224
225
226
    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()
227
228
229
230
        self.static_input = {
            "xftf": self._window._parametersWindow.getParameters(),
            "xas_obj": None,
        }
231

232
233
234
235
236
237
238
    @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
239
240
241
242
243
    def process(self, xas_obj):
        if xas_obj is None:
            return

        if not self._canProcess():
payno's avatar
payno committed
244
245
246
247
            _logger.warning(
                "There is some processing on going already, will"
                "not process the new dataset"
            )
248

249
        # update k weight values if any received
payno's avatar
payno committed
250
251
        if "SET_KWEIGHT" in xas_obj.configuration:
            kweight = xas_obj.configuration["SET_KWEIGHT"]
252
253
            if kweight is not None:
                self._window.setKWeight(kweight)
payno's avatar
payno committed
254
                self._window._parametersWindow._mainwidget._kWeightSB.setEnabled(False)
255
        else:
payno's avatar
payno committed
256
            self._window._parametersWindow._mainwidget._kWeightSB.setEnabled(True)
257
        self._latest_xas_obj = xas_obj
258
259
260
        self._startProcess()

        # setup the normalization process
261
        inputs = {"xas_obj": xas_obj}
262
        if _USE_THREAD is True:
263
            process_obj = QLarch_xftf(inputs=inputs)
264
            process_obj._advancement.sigProgress.connect(self._setProgressValue)
265
            process_obj.set_properties(
payno's avatar
payno committed
266
267
268
269
                {
                    "_larchSettings": self._window._mainwidget._parametersWindow.getParameters()
                }
            )
270
271
272
            # update the processing thread
            thread = self.getProcessingThread()
            thread.init(process_obj=process_obj, xas_obj=self._latest_xas_obj)
payno's avatar
payno committed
273
274
275
            self._callback_finish = functools.partial(
                self._endProcess, self._latest_xas_obj
            )
276
277
278
            thread.finished.connect(self._callback_finish)
            # start processing
            thread.start(priority=qt.QThread.LowPriority)
279
280
281
282
        else:
            # manage advancement
            self._advancement.setAdvancement(0)
            self._advancement.setMaxSpectrum(self._latest_xas_obj.n_spectrum)
283
            process_obj = est.core.process.larch.xftf.Larch_xftf(inputs=inputs)
284
            process_obj.advancement = self._advancement
285
            process_obj.set_properties(
payno's avatar
payno committed
286
287
                {"_larchSettings": self._window._parametersWindow.getParameters()}
            )
288
289
290
291
            # 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)
292
            process_obj.run()
293
294
            self._callback_finish = None
            self._endProcess(self._latest_xas_obj)
295
296


payno's avatar
payno committed
297
class QLarch_xftf(est.core.process.larch.xftf.Larch_xftf):
298
299
300
301
    """
    Normalization able to give advancement using qt.Signal and QThreadPool
    """

302
303
    def __init__(self, *args, **kwargs):
        est.core.process.larch.xftf.Larch_xftf.__init__(self, *args, **kwargs)
payno's avatar
payno committed
304
        self._advancement = QProgress("xftf")
305
306
307
308
309

    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
310
311
312
313
314
315
            runnable = ProcessRunnable(
                fct=est.core.process.larch.xftf.process_spectr_xftf,
                spectrum=spectrum,
                configuration=xas_obj.configuration,
                callback=self._advancement.increaseAdvancement,
            )
316
317
            self.pool.start(runnable)
        self.pool.waitForDone()