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
payno's avatar
payno committed
31
from larch.xafs.xafsft import xftf
32
from est.core.utils.symbol import ANGSTROM_CHAR
payno's avatar
payno committed
33
34
35
import multiprocessing
import functools
import logging
payno's avatar
payno committed
36
import numpy
payno's avatar
payno committed
37

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

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


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

55
56
57
58
59
60
61
    :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
62
63
    :param output: list to store the result, needed for pool processing
    :type: multiprocessing.manager.list
64
65
66
    :param output_dict: key is input spectrum, value is index in the output
                        list.
    :type: dict
payno's avatar
payno committed
67
68
69
    :return: processed spectrum
    :rtype: tuple (configuration, spectrum)
    """
payno's avatar
payno committed
70
    _logger.debug("start xftf on spectrum (%s, %s)" % (spectrum.x, spectrum.y))
payno's avatar
payno committed
71
    assert isinstance(spectrum, Spectrum)
payno's avatar
payno committed
72
73
74
75
76
77
78
79
80
81
    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
82
        return None, None
83
    _conf = configuration
payno's avatar
payno committed
84
85
    if "xftf" in _conf:
        _conf = _conf["xftf"]
payno's avatar
payno committed
86
    opts = {}
payno's avatar
payno committed
87
88
89
90
91
92
93
94
95
96
97
98
    for opt_name in (
        "kmin",
        "kmax",
        "kweight",
        "dk",
        "dk2",
        "with_phase",
        "window",
        "rmax_out",
        "nfft",
        "kstep",
    ):
99
100
        if opt_name in _conf:
            opts[opt_name] = _conf[opt_name]
payno's avatar
payno committed
101
            if opt_name == "kweight":
102
                opts["kw"] = _conf[opt_name]
payno's avatar
payno committed
103
104
105
106
107
    if _DEBUG is True:
        assert isinstance(spectrum, Group)
    if overwrite:
        _spectrum = spectrum
    else:
108
        _spectrum = Spectrum().load_frm_dict(spectrum.to_dict())
109
    xftf(_spectrum, **opts)
payno's avatar
payno committed
110
    # handle chi(x) * k**k_weight plot with r max
payno's avatar
payno committed
111
112
113
114
115
    if hasattr(_spectrum, "k") and hasattr(_spectrum, "chi"):
        if "kweight" in opts:
            kweight = opts["kweight"]
        else:
            kweight = 0
payno's avatar
payno committed
116
117
118
119
        if (
            "_plot_chi_k_weighted_r_max" in _conf
            and _conf["_plot_chi_k_weighted_r_max"] is not None
        ):
120
            mask = _spectrum.k < _conf["_plot_chi_k_weighted_r_max"]
payno's avatar
payno committed
121
        else:
122
123
124
125
126
            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
127
128
129
    # 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:
130
            mask = _spectrum.r < _conf["_plot_chi_mag_r_max"]
payno's avatar
payno committed
131
        else:
132
133
134
            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
135

136
137
138
    if callbacks:
        for callback in callbacks:
            callback()
payno's avatar
payno committed
139
140
141
142
143
144
145
146
147
148
149
    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
    """
payno's avatar
payno committed
150
151
    mback_obj = Larch_xftf(inputs={"xas_obj": xas_obj})
    return mback_obj.run()
payno's avatar
payno committed
152
153
154


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


class Larch_xftf(Process):
159

160
    _INPUT_NAMES = set(["xas_obj"])
161

162
    _OUTPUT_NAMES = set(["xas_obj"])
163

164
165
    def __init__(self, varinfo=None, **inputs):
        Process.__init__(self, name="xftf", varinfo=varinfo, **inputs)
payno's avatar
payno committed
166
        self._plot_settings = {}
payno's avatar
payno committed
167

168
    def set_properties(self, properties):
payno's avatar
payno committed
169
170
        if "_larchSettings" in properties:
            self._settings = properties["_larchSettings"]
payno's avatar
payno committed
171
172
        if "plot_settings" in properties:
            self._plot_settings = properties["plot_settings"]
payno's avatar
payno committed
173

174
175
    def run(self):
        xas_obj = self.inputs.xas_obj
176
        if xas_obj is None:
177
            raise ValueError("xas_obj should be provided")
payno's avatar
payno committed
178
179
        _xas_obj = self.getXasObject(xas_obj=xas_obj)
        if self._settings:
payno's avatar
payno committed
180
181
182
            _xas_obj.configuration["xftf"] = self._settings
        elif "xftf" not in _xas_obj.configuration:
            _xas_obj.configuration["xftf"] = {}
payno's avatar
payno committed
183
184
185
186
187

        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
188
        self.register_process(
payno's avatar
payno committed
189
190
            _xas_obj,
            data_keys=(
191
192
193
194
195
                _NexusDatasetDef(
                    "chir_im",
                    units="{}^(-3)".format(ANGSTROM_CHAR),
                    units_latex="\mathring{A}^{-3}",
                ),
196
197
                _NexusDatasetDef("chir_re"),
                _NexusDatasetDef(
198
199
200
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
                    "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}",
229
                ),
payno's avatar
payno committed
230
231
232
233
234
235
236
            ),
            plots=(
                _NexusSpectrumDef(
                    signal="masked_chi_weighted_k",
                    axes=("masked_k",),
                    auxiliary_signals=None,
                    silx_style={"signal_scale_type": "linear"},
237
238
                    title="chi(k)*k^k_weight",
                    title_latex="\chi(k).k^{k\_weight}",
payno's avatar
payno committed
239
240
                ),
                _NexusSpectrumDef(
payno's avatar
payno committed
241
242
                    signal="masked_chir_mag",
                    axes=("masked_r",),
payno's avatar
payno committed
243
244
                    auxiliary_signals=None,
                    silx_style={"signal_scale_type": "linear"},
245
                    title="chir_mag",
payno's avatar
payno committed
246
247
                ),
            ),
payno's avatar
payno committed
248
        )
payno's avatar
payno committed
249
        self.outputs.xas_obj = _xas_obj.to_dict()
payno's avatar
payno committed
250
251
252
253
254
255
        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
256
257
258
259
260
261
                process_spectr_xftf(
                    spectrum=spectrum,
                    configuration=xas_obj.configuration,
                    callbacks=self.callbacks,
                    overwrite=True,
                )
payno's avatar
payno committed
262
263
        else:
            from multiprocessing import Manager
payno's avatar
payno committed
264

payno's avatar
payno committed
265
266
267
268
269
270
271
272
            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
273
274
275
276
277
278
279
280
                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
281
282
283
284
285
286
287
288
289
290
291
                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
292
293

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

295
296
    @staticmethod
    def program_name():
payno's avatar
payno committed
297
        return "larch_xftf"
payno's avatar
payno committed
298

299
    __call__ = run