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
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
177
178

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

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

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

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

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

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

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

210
        # set up (insure settings will be store
211
        self._update_settings()
212

213
        # self.handleNewSignals()
214

215
216
217
218
219
220
221
222
    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()

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

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

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

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


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

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

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