exafs.py 8.62 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
payno's avatar
payno committed
43
import est.core.process.pymca.exafs
payno's avatar
payno committed
44
from orangecontrib.est.process import _ProcessForOrangeMixIn, ProcessRunnable
payno's avatar
payno committed
45
from est.gui.XasObjectViewer import XasObjectViewer, ViewType
payno's avatar
payno committed
46
47
48
49
50
from est.gui.XasObjectViewer import (
    _exafs_signal_plot,
    _exafs_postedge_plot,
    _exafs_knots_plot,
)
payno's avatar
payno committed
51
52
from orangecontrib.est.progress import QProgress
from orangecontrib.est.utils import Converter
payno's avatar
payno committed
53
from orangecontrib.est.widgets.container import _ParameterWindowContainer
54

payno's avatar
payno committed
55

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


payno's avatar
payno committed
59
60
61
class ExafsWindow(qt.QMainWindow):
    def __init__(self, parent=None):
        qt.QMainWindow.__init__(self, parent)
payno's avatar
payno committed
62
        mapKeys = ["mu", "EXAFS.EXAFSKValues", "EXAFS.EXAFSSignal", "EXAFS.PostEdgeB"]
63
        self.xasObjViewer = XasObjectViewer(mapKeys=mapKeys)
64
65
        self.xasObjViewer._spectrumViews[0]._plotWidget.getXAxis().setLabel("K")
        self.xasObjViewer._spectrumViews[0]._plotWidget.getYAxis().setLabel(
payno's avatar
payno committed
66
67
            "Normalized Units"
        )
68
69
70
        self.setCentralWidget(self.xasObjViewer)

        # pymca window
payno's avatar
payno committed
71
72
73
        self._pymcaWindow = _ParameterWindowContainer(
            parent=self, parametersWindow=XASPostEdgeParameters
        )
payno's avatar
payno committed
74
75
76
77
78
79
        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)
80
81

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

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

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

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

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

        # set up
        self._updateLegendView()

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

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

payno's avatar
payno committed
118

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

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

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

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

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

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

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

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

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

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

173
        # self.handleNewSignals()
174

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

180
    def _update_settings(self):
181
        self._larchSettings = self._window._pymcaWindow.getParameters()
182

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

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

200
        self._latest_xas_obj = xas_obj
201
        self._startProcess()
202
203

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

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

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


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

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

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