xftf.py 8.14 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
    for opt_name in (
        "kmin",
        "kmax",
        "kweight",
        "dk",
        "dk2",
        "with_phase",
        "window",
        "rmax_out",
        "nfft",
        "kstep",
payno's avatar
payno committed
100
        "r_max",
payno's avatar
payno committed
101
    ):
102
103
        if opt_name in _conf:
            opts[opt_name] = _conf[opt_name]
104
105
            if "kweight" in _conf:
                opts["kw"] = _conf[opt_name]
payno's avatar
payno committed
106
107
108
109
110
    if _DEBUG is True:
        assert isinstance(spectrum, Group)
    if overwrite:
        _spectrum = spectrum
    else:
111
        _spectrum = Spectrum().load_frm_dict(spectrum.to_dict())
112
    xftf(_spectrum, **opts)
payno's avatar
payno committed
113
114
115
116
117
118
119
120
121
122
123
124
    if hasattr(_spectrum, "k") and hasattr(_spectrum, "chi"):
        if "kweight" in opts:
            kweight = opts["kweight"]
        else:
            kweight = 0
        if "rmax" in opts and opts["rmax"] is not None:
            mask = spectrum.k < opts["rmax"]
        else:
            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]

125
126
127
    if callbacks:
        for callback in callbacks:
            callback()
payno's avatar
payno committed
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
    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
144
# note: we cannot use multiprocessing pool with pypushflow for now.
payno's avatar
payno committed
145
146
147


class Larch_xftf(Process):
148
149

    inputs = [
payno's avatar
payno committed
150
        _input_desc(name="xas_obj", type=XASObject, handler="process", doc=""),
151
152
153
    ]

    outputs = [
payno's avatar
payno committed
154
        _output_desc(name="xas_obj", type=XASObject, doc=""),
155
156
    ]

payno's avatar
payno committed
157
    def __init__(self):
payno's avatar
payno committed
158
        Process.__init__(self, name="xftf")
payno's avatar
payno committed
159

160
    def set_properties(self, properties):
payno's avatar
payno committed
161
162
        if "_larchSettings" in properties:
            self._settings = properties["_larchSettings"]
payno's avatar
payno committed
163
164
165
166

    def process(self, xas_obj):
        _xas_obj = self.getXasObject(xas_obj=xas_obj)
        if self._settings:
payno's avatar
payno committed
167
168
169
            _xas_obj.configuration["xftf"] = self._settings
        elif "xftf" not in _xas_obj.configuration:
            _xas_obj.configuration["xftf"] = {}
payno's avatar
payno committed
170
171
172
173
174

        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
175
        self.register_process(
payno's avatar
payno committed
176
177
            _xas_obj,
            data_keys=(
178
179
180
181
182
183
184
185
                _NexusDatasetDef("chir_im", "{}^(-3)".format(ANGSTROM_CHAR)),
                _NexusDatasetDef("chir_re"),
                _NexusDatasetDef("chir_mag", "{}^(-3)".format(ANGSTROM_CHAR)),
                _NexusDatasetDef("r", "{}".format(ANGSTROM_CHAR)),
                _NexusDatasetDef("masked_k", "{}^(-1)".format(ANGSTROM_CHAR)),
                _NexusDatasetDef(
                    "masked_chi_weighted_k", "{}^(-2)".format(ANGSTROM_CHAR)
                ),
payno's avatar
payno committed
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
            ),
            plots=(
                _NexusSpectrumDef(
                    signal="masked_chi_weighted_k",
                    axes=("masked_k",),
                    auxiliary_signals=None,
                    silx_style={"signal_scale_type": "linear"},
                ),
                _NexusSpectrumDef(
                    signal="chir_mag",
                    axes=("r",),
                    auxiliary_signals=None,
                    silx_style={"signal_scale_type": "linear"},
                ),
            ),
payno's avatar
payno committed
201
        )
payno's avatar
payno committed
202
203
204
205
206
207
        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
208
209
210
211
212
213
                process_spectr_xftf(
                    spectrum=spectrum,
                    configuration=xas_obj.configuration,
                    callbacks=self.callbacks,
                    overwrite=True,
                )
payno's avatar
payno committed
214
215
        else:
            from multiprocessing import Manager
payno's avatar
payno committed
216

payno's avatar
payno committed
217
218
219
220
221
222
223
224
            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
225
226
227
228
229
230
231
232
                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
233
234
235
236
237
238
239
240
241
242
243
                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
244
245

        return larch.version.version_data()["larch"]
payno's avatar
payno committed
246
247

    def program_name(self):
payno's avatar
payno committed
248
        return "larch_xftf"
payno's avatar
payno committed
249
250

    __call__ = process