exafs.py 8.68 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
from est.core.types import XASObject
payno's avatar
payno committed
40
from PyMca5.PyMcaGui.physics.xas.XASPostEdgeParameters import XASPostEdgeParameters
41
42
from silx.gui import qt
from silx.gui.plot import LegendSelector
43
from ewokscore.registration import Registered
payno's avatar
payno committed
44
import est.core.process.pymca.exafs
payno's avatar
payno committed
45
from orangecontrib.est.process import _ProcessForOrangeMixIn, ProcessRunnable
payno's avatar
payno committed
46
from est.gui.XasObjectViewer import XasObjectViewer, ViewType
payno's avatar
payno committed
47
48
49
50
51
from est.gui.XasObjectViewer import (
    _exafs_signal_plot,
    _exafs_postedge_plot,
    _exafs_knots_plot,
)
payno's avatar
payno committed
52
53
from orangecontrib.est.progress import QProgress
from orangecontrib.est.utils import Converter
payno's avatar
payno committed
54
from orangecontrib.est.widgets.container import _ParameterWindowContainer
55

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 ExafsWindow(qt.QMainWindow):
    def __init__(self, parent=None):
        qt.QMainWindow.__init__(self, parent)
payno's avatar
payno committed
63
        mapKeys = ["mu", "EXAFS.EXAFSKValues", "EXAFS.EXAFSSignal", "EXAFS.PostEdgeB"]
64
        self.xasObjViewer = XasObjectViewer(mapKeys=mapKeys)
65
66
        self.xasObjViewer._spectrumViews[0]._plotWidget.getXAxis().setLabel("K")
        self.xasObjViewer._spectrumViews[0]._plotWidget.getYAxis().setLabel(
payno's avatar
payno committed
67
68
            "Normalized Units"
        )
69
70
71
        self.setCentralWidget(self.xasObjViewer)

        # pymca window
payno's avatar
payno committed
72
73
74
        self._pymcaWindow = _ParameterWindowContainer(
            parent=self, parametersWindow=XASPostEdgeParameters
        )
payno's avatar
payno committed
75
76
77
78
79
80
        dockWidget = qt.QDockWidget(parent=self)
        dockWidget.setWidget(self._pymcaWindow)
        self.addDockWidget(qt.Qt.RightDockWidgetArea, dockWidget)
        dockWidget.setAllowedAreas(qt.Qt.RightDockWidgetArea | qt.Qt.LeftDockWidgetArea)
        dockWidget.setFeatures(qt.QDockWidget.NoDockWidgetFeatures)
        self.setWindowFlags(qt.Qt.Widget)
81
82

        # legend selector
payno's avatar
payno committed
83
        self.legendDockWidget = LegendSelector.LegendsDockWidget(
84
            parent=self, plot=self.xasObjViewer._spectrumViews[0]._plotWidget
payno's avatar
payno committed
85
86
87
88
        )
        self.legendDockWidget.setAllowedAreas(
            qt.Qt.RightDockWidgetArea | qt.Qt.LeftDockWidgetArea
        )
payno's avatar
payno committed
89
90
91
        self.legendDockWidget.setFeatures(qt.QDockWidget.NoDockWidgetFeatures)
        self.addDockWidget(qt.Qt.RightDockWidgetArea, self.legendDockWidget)

92
        # volume key selection
payno's avatar
payno committed
93
94
95
        self.addDockWidget(
            qt.Qt.RightDockWidgetArea, self.xasObjViewer._mapView.keySelectionDocker
        )
96
97

        # plot settings
payno's avatar
payno committed
98
        for ope in (_exafs_signal_plot, _exafs_postedge_plot, _exafs_knots_plot):
99
            self.xasObjViewer._spectrumViews[0].addCurveOperation(ope)
100

101
102
103
104
105
106
107
108
        self.setWindowFlags(qt.Qt.Widget)

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

        # set up
        self._updateLegendView()

109
    def getNCurves(self):
110
111
112
        return len(self.xasObjViewer.getAllCurves())

    def _updateLegendView(self):
113
114
        index, viewType = self.xasObjViewer.getViewType()
        self.legendDockWidget.setVisible(viewType is ViewType.spectrum)
payno's avatar
payno committed
115
116
117
        self.xasObjViewer._mapView.keySelectionDocker.setVisible(
            viewType is ViewType.map
        )
118

payno's avatar
payno committed
119

120
121
class ExafsOW(
    _ProcessForOrangeMixIn,
122
123
    OWWidget,
    Registered,
124
):
payno's avatar
payno committed
125
126
127
    """
    Widget used for signal extraction
    """
payno's avatar
payno committed
128

payno's avatar
payno committed
129
    name = "exafs"
payno's avatar
payno committed
130
    id = "orange.widgets.est.pymca.exafs"
131
    description = "Progress signal extraction"
payno's avatar
payno committed
132
    icon = "icons/exafs.png"
133
    priority = 3
payno's avatar
payno committed
134
135
136
137
138
    category = "esrfWidgets"
    keywords = ["spectroscopy", "signal"]

    want_main_area = True
    resizing_enabled = True
139
    allows_cycle = False
140
    ewokstaskclass = est.core.process.pymca.exafs.PyMca_exafs
payno's avatar
payno committed
141

142
    _larchSettings = Setting(dict())
payno's avatar
payno committed
143
144
    """Store the configuration of the PyMca XASClass"""

145
    class Inputs:
payno's avatar
payno committed
146
        xas_obj = Input("xas_obj", XASObject, default=True)
147
148
        # simple compatibility for some Orange widget and especialy the
        # 'spectroscopy add-on'
payno's avatar
payno committed
149
        data_table = Input("Data", Orange.data.Table)
150
151

    class Outputs:
152
        xas_obj = Output("xas_obj", XASObject)
153
154
155
        # by default we want to avoid sending 'Orange.data.Table' to avoid
        # loosing the XASObject flow process and results.

payno's avatar
payno committed
156
157
    def __init__(self):
        super().__init__()
158
        self._latest_xas_obj = None
payno's avatar
payno committed
159
        self._window = ExafsWindow()
payno's avatar
payno committed
160
        layout = gui.vBox(self.mainArea, "exafs").layout()
payno's avatar
payno committed
161
        layout.addWidget(self._window)
payno's avatar
payno committed
162

163
164
        self._window.xasObjViewer._spectrumViews[0]._plotWidget.getXAxis().setLabel("K")
        self._window.xasObjViewer._spectrumViews[0]._plotWidget.getYAxis().setLabel(
payno's avatar
payno committed
165
166
            "Normalized Units"
        )
payno's avatar
payno committed
167

payno's avatar
payno committed
168
        # manage settings
169
170
        if self._larchSettings != dict():
            self._window._pymcaWindow.setParameters(self._larchSettings)
payno's avatar
payno committed
171

payno's avatar
payno committed
172
        # signal / slot connection
173
        self._window._pymcaWindow.sigChanged.connect(self._updateProcess)
payno's avatar
payno committed
174

175
        # self.handleNewSignals()
176

payno's avatar
payno committed
177
    def _updateProcess(self):
payno's avatar
payno committed
178
        self._update_settings()
179
180
        if self._latest_xas_obj:
            self.process(self._latest_xas_obj)
payno's avatar
payno committed
181

182
    def _update_settings(self):
183
        self._larchSettings = self._window._pymcaWindow.getParameters()
184

185
186
187
188
189
190
191
    @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
192
193
    def process(self, xas_obj):
        if xas_obj is None:
payno's avatar
payno committed
194
            return
payno's avatar
payno committed
195

196
        if not self._canProcess():
payno's avatar
payno committed
197
198
199
200
            _logger.warning(
                "There is some processing on going already, will"
                "not process the new dataset"
            )
201

202
        self._latest_xas_obj = xas_obj
203
        self._startProcess()
204
205

        # setup the exafs process
206
        process_obj = QPyMca_exafs(inputs={"xas_obj": xas_obj})
207
        process_obj._advancement.sigProgress.connect(self._setProgressValue)
208
        process_obj.set_properties(
payno's avatar
payno committed
209
210
            {"_pymcaSettings": self._window._pymcaWindow.getParameters()}
        )
payno's avatar
payno committed
211

212
213
        # update the processing thread
        thread = self.getProcessingThread()
214
        thread.init(process_obj=process_obj, xas_obj=self._latest_xas_obj)
payno's avatar
payno committed
215
216
217
        self._callback_finish = functools.partial(
            self._endProcess, self._latest_xas_obj
        )
218
219
220
        thread.finished.connect(self._callback_finish)
        # start processing
        thread.start(priority=qt.QThread.LowPriority)
221
222
223
224
225

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


payno's avatar
payno committed
226
class QPyMca_exafs(est.core.process.pymca.exafs.PyMca_exafs):
227
228
229
230
    """
    Normalization able to give advancement using qt.Signal and QThreadPool
    """

231
232
    def __init__(self, *args, **kwargs):
        est.core.process.pymca.exafs.PyMca_exafs.__init__(self, *args, **kwargs)
payno's avatar
payno committed
233
        self._advancement = QProgress("normalization")
234
235
236
237
238

    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
239
240
241
242
243
244
            runnable = ProcessRunnable(
                fct=est.core.process.pymca.exafs.process_spectr_exafs,
                spectrum=spectrum,
                configuration=xas_obj.configuration,
                callback=self._advancement.increaseAdvancement,
            )
245
246
            self.pool.start(runnable)
        self.pool.waitForDone()