noise.py 8.4 KB
Newer Older
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
31
32
# 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__ = "18/01/2021"

from est.core.types import XASObject
from est.core.types import Spectrum
from .process import Process
payno's avatar
payno committed
33
from .process import _NexusSpectrumDef
34
from .process import _NexusDatasetDef
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import scipy.signal
import logging
import numpy
import pkg_resources
import multiprocessing
import functools

_logger = logging.getLogger(__name__)


_USE_MULTIPROCESSING_POOL = False
# note: we cannot use multiprocessing pool with pypushflow for now.


def process_noise_savgol(
    spectrum,
    configuration,
    overwrite=True,
    callbacks=None,
    output=None,
    output_dict=None,
):
    """

    :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
payno's avatar
payno committed
65
    :param callbacks: callback to execute.
66
67
68
69
70
71
72
73
74
    :param output: list to store the result, needed for pool processing
    :type: multiprocessing.manager.list
    :param output_dict: key is input spectrum, value is index in the output
                        list.
    :type: dict
    :return: processed spectrum
    :rtype: tuple (configuration, spectrum)
    """
    _logger.debug(
payno's avatar
payno committed
75
76
        "start noise with Savitsky-Golay on spectrum (%s, %s)"
        % (spectrum.x, spectrum.y)
77
    )
payno's avatar
payno committed
78
79
    if "noise" in configuration:
        configuration = configuration["noise"]
payno's avatar
PEP8    
payno committed
80
    if "window_size" not in configuration:
81
        raise ValueError("`window_size` should be specify. Missing in configuration")
82
83
    else:
        window_size = configuration["window_size"]
payno's avatar
PEP8    
payno committed
84
    if "polynomial_order" not in configuration:
payno's avatar
payno committed
85
        raise ValueError(
86
            "`polynomial_order` should be specify. Missing in configuration"
payno's avatar
payno committed
87
        )
88
89
    else:
        polynomial_order = configuration["polynomial_order"]
payno's avatar
PEP8    
payno committed
90
    if "e_min" not in configuration:
91
92
93
        e_min = None
    else:
        e_min = configuration["e_min"]
payno's avatar
PEP8    
payno committed
94
    if "e_max" not in configuration:
95
96
97
98
        e_max = None
    else:
        e_max = configuration["e_max"]

99
    if e_min in (None, -1):
100
        e_min = spectrum.energy.min() - 1
101
    if e_max in (None, -1):
102
        e_max = spectrum.energy.max() + 1
103

104
105
106
    mask = (spectrum.energy > e_min) & (spectrum.energy < (e_max))
    noise_savgol_energy = spectrum.energy[mask]
    raw_mu = spectrum.mu[mask]
payno's avatar
payno committed
107
    smooth_spectrum = scipy.signal.savgol_filter(raw_mu, window_size, polynomial_order)
108
    noise = numpy.absolute(raw_mu - smooth_spectrum)
payno's avatar
payno committed
109
    spectrum.noise_savgol = noise
110
    if hasattr(spectrum, "edge_step"):
payno's avatar
payno committed
111
        spectrum.norm_noise_savgol = numpy.mean(noise) / spectrum.edge_step
112
    else:
payno's avatar
payno committed
113
        spectrum.norm_noise_savgol = None
payno's avatar
payno committed
114
115
116
117
        _logger.warning(
            "Unable to compute Normalized edge."
            "Normalization (pre-edge) should be run first"
        )
118
    spectrum.noise_savgol_energy = noise_savgol_energy
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144

    if callbacks:
        for callback in callbacks:
            callback()

    if overwrite:
        spectrum_ = spectrum
    else:
        spectrum_ = Spectrum()
        spectrum_.update(spectrum)

    if output is not None:
        assert output_dict is not None
        output[output_dict[spectrum]] = spectrum_
    return configuration, spectrum_


def xas_noise(xas_obj):
    """
    apply roi on the XASObject.spectra

    :param xas_obj: object containing the configuration and spectra to process
    :type: Union[:class:`.XASObject`, dict]
    :return: spectra dict
    :rtype: :class:`.XASObject`
    """
payno's avatar
payno committed
145
146
    xas_noise_process = NoiseProcess(inputs={"xas_obj": xas_obj})
    return xas_noise_process.run()
147
148
149
150


class NoiseProcess(Process):

151
    _INPUT_NAMES = set(["xas_obj"])
152

153
    _OUTPUT_NAMES = set(["xas_obj"])
154

155
    def __init__(self, varinfo=None, **inputs):
156
        Process.__init__(self, name="noise", varinfo=varinfo, **inputs)
157
158
159
160
161
162
163
164
165
166
167
168
        self._window_size = 5
        self._polynomial_order = 2

    def set_properties(self, properties: dict):
        if "noise" in properties:
            properties = properties["noise"]
        self._settings = properties
        if "window_size" in properties:
            self._window_size = properties["window_size"]
        if "polynomial_order" in properties:
            self._polynomial_order = properties["polynomial_order"]

169
    def run(self):
170
171
172
173
174
175
176
        """

        :param xas_obj: object containing the configuration and spectra to process
        :type: Union[:class:`.XASObject`, dict]
        :return: spectra dict
        :rtype: :class:`.XASObject`
        """
177
        xas_obj = self.inputs.xas_obj
178
        if xas_obj is None:
179
            raise ValueError("xas_obj should be provided")
180
181
182
183
184
185
186
187
        _xas_obj = self.getXasObject(xas_obj=xas_obj)
        if self._settings:
            _xas_obj.configuration["noise"] = self._settings

        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
189
        self.register_process(
            _xas_obj,
190
191
            data_keys=(
                _NexusDatasetDef("norm_noise_savgol"),
192
193
                _NexusDatasetDef("noise_savgol", units="raw data noise"),
                _NexusDatasetDef("noise_savgol_energy", units="eV"),
194
                _NexusDatasetDef("edge_step"),
195
            ),
payno's avatar
payno committed
196
197
198
199
200
201
            plots=(
                _NexusSpectrumDef(
                    signal="noise_savgol",
                    axes=("noise_savgol_energy",),
                    auxiliary_signals=None,
                    silx_style={"signal_scale_type": "log"},
202
                    title="noise",
payno's avatar
payno committed
203
204
205
                ),
            ),
        )
206
        self.outputs.xas_obj = _xas_obj.to_dict()
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
        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:
                process_noise_savgol(
                    spectrum=spectrum,
                    configuration=xas_obj.configuration,
                    callbacks=self.callbacks,
                    overwrite=True,
                )
        else:
            from multiprocessing import Manager

            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(1) as p:
                partial_ = functools.partial(
                    process_noise_savgol,
                    configuration=xas_obj.configuration,
                    callbacks=self.callbacks,
                    overwrite=False,
                    output=res_list,
                    output_dict=output_dict,
                )
                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 "noise using Savitsky-Golay algorithm"

    def program_version(self):
        return pkg_resources.get_distribution("est").version

250
    @staticmethod
251
    def program_name():
252
253
        return "noise_savgol"

254
    __call__ = run