xftf.py 10.1 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
# 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.
#
# ###########################################################################*/
"""wrapper to the larch mback process"""

payno's avatar
payno committed
27
28
from est.core.types import Spectrum, XASObject
from est.core.process.process import Process
payno's avatar
payno committed
29
from est.core.process.process import _NexusSpectrumDef
30
from est.core.process.process import _NexusDatasetDef
31
32
from est.core.process.process import _input_desc
from est.core.process.process import _output_desc
payno's avatar
payno committed
33
from larch.xafs.xafsft import xftf
34
from est.core.utils.symbol import ANGSTROM_CHAR
payno's avatar
payno committed
35
36
37
import multiprocessing
import functools
import logging
payno's avatar
payno committed
38
import numpy
payno's avatar
payno committed
39

payno's avatar
payno committed
40
41
42
43
44
45
46
_logger = logging.getLogger(__name__)

_DEBUG = True
if _DEBUG:
    from larch.symboltable import Group


payno's avatar
payno committed
47
48
49
50
51
52
53
54
def process_spectr_xftf(
    spectrum,
    configuration,
    overwrite=True,
    callbacks=None,
    output=None,
    output_dict=None,
):
payno's avatar
payno committed
55
56
    """

57
58
59
60
61
62
63
    :param spectrum: spectrum to process
    :type: :class:`.Spectrum`
    :param configuration: configuration of the pymca normalization
    :type: dict
    :param overwrite: False if we want to return a new Spectrum instance
    :type: bool
    :param callback: callback to execute.
payno's avatar
payno committed
64
65
    :param output: list to store the result, needed for pool processing
    :type: multiprocessing.manager.list
66
67
68
    :param output_dict: key is input spectrum, value is index in the output
                        list.
    :type: dict
payno's avatar
payno committed
69
70
71
    :return: processed spectrum
    :rtype: tuple (configuration, spectrum)
    """
payno's avatar
payno committed
72
    _logger.debug("start xftf on spectrum (%s, %s)" % (spectrum.x, spectrum.y))
payno's avatar
payno committed
73
    assert isinstance(spectrum, Spectrum)
payno's avatar
payno committed
74
75
76
77
78
79
80
81
82
83
    if (
        not hasattr(spectrum, "k")
        or not hasattr(spectrum, "chi")
        or spectrum.k is None
        or spectrum.chi is None
    ):
        _logger.error(
            "k and/or chi is/are not specified, unable to compute "
            "xftf. Maybe you need to run autobk process before ?"
        )
payno's avatar
payno committed
84
        return None, None
85
    _conf = configuration
payno's avatar
payno committed
86
87
    if "xftf" in _conf:
        _conf = _conf["xftf"]
payno's avatar
payno committed
88
    opts = {}
payno's avatar
payno committed
89
90
91
92
93
94
95
96
97
98
99
100
    for opt_name in (
        "kmin",
        "kmax",
        "kweight",
        "dk",
        "dk2",
        "with_phase",
        "window",
        "rmax_out",
        "nfft",
        "kstep",
    ):
101
102
        if opt_name in _conf:
            opts[opt_name] = _conf[opt_name]
payno's avatar
payno committed
103
            if opt_name == "kweight":
104
                opts["kw"] = _conf[opt_name]
payno's avatar
payno committed
105
106
107
108
109
    if _DEBUG is True:
        assert isinstance(spectrum, Group)
    if overwrite:
        _spectrum = spectrum
    else:
110
        _spectrum = Spectrum().load_frm_dict(spectrum.to_dict())
111
    xftf(_spectrum, **opts)
payno's avatar
payno committed
112
    # handle chi(x) * k**k_weight plot with r max
payno's avatar
payno committed
113
114
115
116
117
    if hasattr(_spectrum, "k") and hasattr(_spectrum, "chi"):
        if "kweight" in opts:
            kweight = opts["kweight"]
        else:
            kweight = 0
payno's avatar
payno committed
118
119
120
121
        if (
            "_plot_chi_k_weighted_r_max" in _conf
            and _conf["_plot_chi_k_weighted_r_max"] is not None
        ):
122
            mask = _spectrum.k < _conf["_plot_chi_k_weighted_r_max"]
payno's avatar
payno committed
123
        else:
124
125
126
127
128
            mask = numpy.ones_like(_spectrum.k).astype(numpy.bool)
    _spectrum.masked_chi_weighted_k = _spectrum.chi[mask] * (
        _spectrum.k[mask] ** kweight
    )
    _spectrum.masked_k = _spectrum.k[mask]
payno's avatar
payno committed
129
130
131
    # handle ft plot with r max
    if hasattr(_spectrum, "r") and hasattr(_spectrum, "chir_mag"):
        if "_plot_chi_mag_r_max" in _conf and _conf["_plot_chi_mag_r_max"] is not None:
132
            mask = _spectrum.r < _conf["_plot_chi_mag_r_max"]
payno's avatar
payno committed
133
        else:
134
135
136
            mask = numpy.ones_like(_spectrum.r).astype(numpy.bool)
        _spectrum.masked_chir_mag = _spectrum.chir_mag[mask]
        _spectrum.masked_r = _spectrum.r[mask]
payno's avatar
payno committed
137

138
139
140
    if callbacks:
        for callback in callbacks:
            callback()
payno's avatar
payno committed
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
    return configuration, _spectrum


def larch_xftf(xas_obj):
    """

    :param xas_obj: object containing the configuration and spectra to process
    :type: Union[XASObject, dict]
    :return: spectra dict
    :rtype: XASObject
    """
    mback_obj = Larch_xftf()
    return mback_obj.process(xas_obj=xas_obj)


_USE_MULTIPROCESSING_POOL = False
payno's avatar
payno committed
157
# note: we cannot use multiprocessing pool with pypushflow for now.
payno's avatar
payno committed
158
159
160


class Larch_xftf(Process):
161
162

    inputs = [
payno's avatar
payno committed
163
        _input_desc(name="xas_obj", type=XASObject, handler="process", doc=""),
164
165
166
    ]

    outputs = [
payno's avatar
payno committed
167
        _output_desc(name="xas_obj", type=XASObject, doc=""),
168
169
    ]

payno's avatar
payno committed
170
    def __init__(self):
payno's avatar
payno committed
171
        Process.__init__(self, name="xftf")
payno's avatar
payno committed
172
        self._plot_settings = {}
payno's avatar
payno committed
173

174
    def set_properties(self, properties):
payno's avatar
payno committed
175
176
        if "_larchSettings" in properties:
            self._settings = properties["_larchSettings"]
payno's avatar
payno committed
177
178
        if "plot_settings" in properties:
            self._plot_settings = properties["plot_settings"]
payno's avatar
payno committed
179
180
181
182

    def process(self, xas_obj):
        _xas_obj = self.getXasObject(xas_obj=xas_obj)
        if self._settings:
payno's avatar
payno committed
183
184
185
            _xas_obj.configuration["xftf"] = self._settings
        elif "xftf" not in _xas_obj.configuration:
            _xas_obj.configuration["xftf"] = {}
payno's avatar
payno committed
186
187
188
189
190

        self._advancement.reset(max_=_xas_obj.n_spectrum)
        self._advancement.startProcess()
        self._pool_process(xas_obj=_xas_obj)
        self._advancement.endProcess()
payno's avatar
payno committed
191
        self.register_process(
payno's avatar
payno committed
192
193
            _xas_obj,
            data_keys=(
194
195
196
197
198
                _NexusDatasetDef(
                    "chir_im",
                    units="{}^(-3)".format(ANGSTROM_CHAR),
                    units_latex="\mathring{A}^{-3}",
                ),
199
200
                _NexusDatasetDef("chir_re"),
                _NexusDatasetDef(
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
                    "chir_mag",
                    units="{}^(-3)".format(ANGSTROM_CHAR),
                    units_latex="\mathring{A}^{-3}",
                ),
                _NexusDatasetDef(
                    "masked_chir_mag",
                    units="{}".format(ANGSTROM_CHAR),
                    units_latex="\mathring{A}",
                ),
                _NexusDatasetDef(
                    "r", units="{}".format(ANGSTROM_CHAR), units_latex="\mathring{A}"
                ),
                _NexusDatasetDef(
                    "masked_r",
                    units="{}".format(ANGSTROM_CHAR),
                    units_latex="\mathring{A}",
                ),
                _NexusDatasetDef(
                    "k",
                    units="{}^(-1)".format(ANGSTROM_CHAR),
                    units_latex="\mathring{A}^{-1}",
                ),
                _NexusDatasetDef(
                    "masked_k",
                    units="{}^(-1)".format(ANGSTROM_CHAR),
                    units_latex="\mathring{A}^{-1}",
                ),
                _NexusDatasetDef(
                    "masked_chi_weighted_k",
                    units="{}^(-2)".format(ANGSTROM_CHAR),
                    units_latex="\mathring{A}^{-2}",
232
                ),
payno's avatar
payno committed
233
234
235
236
237
238
239
            ),
            plots=(
                _NexusSpectrumDef(
                    signal="masked_chi_weighted_k",
                    axes=("masked_k",),
                    auxiliary_signals=None,
                    silx_style={"signal_scale_type": "linear"},
240
241
                    title="chi(k)*k^k_weight",
                    title_latex="\chi(k).k^{k\_weight}",
payno's avatar
payno committed
242
243
                ),
                _NexusSpectrumDef(
payno's avatar
payno committed
244
245
                    signal="masked_chir_mag",
                    axes=("masked_r",),
payno's avatar
payno committed
246
247
                    auxiliary_signals=None,
                    silx_style={"signal_scale_type": "linear"},
248
                    title="chir_mag",
payno's avatar
payno committed
249
250
                ),
            ),
payno's avatar
payno committed
251
        )
payno's avatar
payno committed
252
253
254
255
256
257
        return _xas_obj

    def _pool_process(self, xas_obj):
        assert isinstance(xas_obj, XASObject)
        if not _USE_MULTIPROCESSING_POOL:
            for spectrum in xas_obj.spectra:
payno's avatar
payno committed
258
259
260
261
262
263
                process_spectr_xftf(
                    spectrum=spectrum,
                    configuration=xas_obj.configuration,
                    callbacks=self.callbacks,
                    overwrite=True,
                )
payno's avatar
payno committed
264
265
        else:
            from multiprocessing import Manager
payno's avatar
payno committed
266

payno's avatar
payno committed
267
268
269
270
271
272
273
274
            manager = Manager()
            output_dict = {}
            res_list = manager.list()
            for i_spect, spect in enumerate(xas_obj.spectra):
                res_list.append(None)
                output_dict[spect] = i_spect

            with multiprocessing.Pool(5) as p:
payno's avatar
payno committed
275
276
277
278
279
280
281
282
                partial_ = functools.partial(
                    process_spectr_xftf,
                    configuration=xas_obj.configuration,
                    callbacks=self.callbacks,
                    overwrite=False,
                    output=res_list,
                    output_dict=output_dict,
                )
payno's avatar
payno committed
283
284
285
286
287
288
289
290
291
292
293
                p.map(partial_, xas_obj.spectra)

            # then update local spectrum
            for spectrum, res in zip(xas_obj.spectra, res_list):
                spectrum.update(res)

    def definition(self):
        return "xftf calculation"

    def program_version(self):
        import larch.version
payno's avatar
payno committed
294
295

        return larch.version.version_data()["larch"]
payno's avatar
payno committed
296
297

    def program_name(self):
payno's avatar
payno committed
298
        return "larch_xftf"
payno's avatar
payno committed
299
300

    __call__ = process