noise.py 7.31 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
import scipy.signal
import logging
import numpy
import pkg_resources

_logger = logging.getLogger(__name__)


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
59
    :param callbacks: callback to execute.
60
61
62
63
64
65
66
67
68
    :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
69
70
        "start noise with Savitsky-Golay on spectrum (%s, %s)"
        % (spectrum.x, spectrum.y)
71
    )
payno's avatar
payno committed
72
73
    if "noise" in configuration:
        configuration = configuration["noise"]
payno's avatar
PEP8    
payno committed
74
    if "window_size" not in configuration:
75
        raise ValueError("`window_size` should be specify. Missing in configuration")
76
77
    else:
        window_size = configuration["window_size"]
payno's avatar
PEP8    
payno committed
78
    if "polynomial_order" not in configuration:
payno's avatar
payno committed
79
        raise ValueError(
80
            "`polynomial_order` should be specify. Missing in configuration"
payno's avatar
payno committed
81
        )
82
83
    else:
        polynomial_order = configuration["polynomial_order"]
payno's avatar
PEP8    
payno committed
84
    if "e_min" not in configuration:
85
86
87
        e_min = None
    else:
        e_min = configuration["e_min"]
payno's avatar
PEP8    
payno committed
88
    if "e_max" not in configuration:
89
90
91
92
        e_max = None
    else:
        e_max = configuration["e_max"]

93
    if e_min in (None, -1):
94
        e_min = spectrum.energy.min() - 1
95
    if e_max in (None, -1):
96
        e_max = spectrum.energy.max() + 1
97

98
99
100
    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
101
    smooth_spectrum = scipy.signal.savgol_filter(raw_mu, window_size, polynomial_order)
102
    noise = numpy.absolute(raw_mu - smooth_spectrum)
payno's avatar
payno committed
103
    spectrum.noise_savgol = noise
104
    if hasattr(spectrum, "edge_step"):
payno's avatar
payno committed
105
        spectrum.norm_noise_savgol = numpy.mean(noise) / spectrum.edge_step
106
    else:
payno's avatar
payno committed
107
        spectrum.norm_noise_savgol = None
payno's avatar
payno committed
108
109
110
111
        _logger.warning(
            "Unable to compute Normalized edge."
            "Normalization (pre-edge) should be run first"
        )
112
    spectrum.noise_savgol_energy = noise_savgol_energy
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138

    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
139
140
    xas_noise_process = NoiseProcess(inputs={"xas_obj": xas_obj})
    return xas_noise_process.run()
141
142


143
144
145
146
147
class NoiseProcess(
    Process, name="noise", input_names=["xas_obj"], output_names=["xas_obj"]
):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
148
149
150
151
152
153
154
155
156
157
158
159
        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"]

160
    def run(self):
161
162
163
164
165
166
167
        """

        :param xas_obj: object containing the configuration and spectra to process
        :type: Union[:class:`.XASObject`, dict]
        :return: spectra dict
        :rtype: :class:`.XASObject`
        """
168
        xas_obj = self.inputs.xas_obj
169
        if xas_obj is None:
170
            raise ValueError("xas_obj should be provided")
171
172
173
174
        _xas_obj = self.getXasObject(xas_obj=xas_obj)
        if self._settings:
            _xas_obj.configuration["noise"] = self._settings

175
        self.progress = 0.0
176
        self._pool_process(xas_obj=_xas_obj)
177
        self.progress = 100.0
payno's avatar
payno committed
178
179
        self.register_process(
            _xas_obj,
180
181
            data_keys=(
                _NexusDatasetDef("norm_noise_savgol"),
182
183
                _NexusDatasetDef("noise_savgol", units="raw data noise"),
                _NexusDatasetDef("noise_savgol_energy", units="eV"),
184
                _NexusDatasetDef("edge_step"),
185
            ),
payno's avatar
payno committed
186
187
188
189
190
191
            plots=(
                _NexusSpectrumDef(
                    signal="noise_savgol",
                    axes=("noise_savgol_energy",),
                    auxiliary_signals=None,
                    silx_style={"signal_scale_type": "log"},
192
                    title="noise",
payno's avatar
payno committed
193
194
195
                ),
            ),
        )
196
        self.outputs.xas_obj = _xas_obj.to_dict()
197
198
199
200
        return _xas_obj

    def _pool_process(self, xas_obj):
        assert isinstance(xas_obj, XASObject)
201
202
203
204
205
206
207
208
209
        n_s = len(xas_obj.spectra.data.flat)
        for i_s, spectrum in enumerate(xas_obj.spectra):
            process_noise_savgol(
                spectrum=spectrum,
                configuration=xas_obj.configuration,
                callbacks=self.callbacks,
                overwrite=True,
            )
            self.progress = i_s / n_s * 100.0
210
211
212
213
214
215
216

    def definition(self):
        return "noise using Savitsky-Golay algorithm"

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

217
    @staticmethod
218
    def program_name():
219
220
        return "noise_savgol"

221
    __call__ = run