normalization.py 4.66 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
27
28
29
30
31
# 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__ = "06/11/2019"


from PyMca5.PyMcaPhysics.xas.XASClass import XASClass
32
from xas.core.types import XASObject, Spectrum
33
34
35
from .process import Process
import multiprocessing
import functools
payno's avatar
payno committed
36
37
38
39
import logging
_logger = logging.getLogger(__name__)


40
def _process_spectrum(spectrum, configuration, overwrite=True):
41
42
    if spectrum.mu is None:
        _logger.error('Mu is not specified, unable to normalize')
43
        return None, None
44
45
46
47
48
49
50
51
52
53
54
    pymca_xas = XASClass()
    pymca_xas.setSpectrum(energy=spectrum.energy,
                          mu=spectrum.mu)
    pymca_xas.setConfiguration(configuration)
    configuration = pymca_xas.getConfiguration()
    try:
        pymca_xas.processSpectrum()
        # TODO: next line can be removed
        ddict = spectrum.to_dict()
        res = pymca_xas.normalize()
        ddict.update(res)
55
        spectrum_ = Spectrum.from_dict(ddict)
56
57
    except (IndexError, ValueError) as e:
        _logger.error(e)
58
59
60
61
62
63
        return None, None
    if overwrite:
        spectrum.load_frm_dict(spectrum_.to_dict())
        return configuration, spectrum
    else:
        return configuration, spectrum_
64
65


66
def pymca_normalization(xas_obj):
payno's avatar
payno committed
67
    """
68

69
70
71
72
    :param xas_obj: object containing the configuration and spectra to process
    :type: Union[XASObject, dict]. If is a dict, should contain configuration or
                                 spectra keys. Otherwise is simply the spectra
    :return: spectra dict
73
    :rtype: dict
payno's avatar
payno committed
74
    """
75
76
    normalization_obj = PyMca_normalization()
    return normalization_obj.process(xas_obj=xas_obj)
77
78


79
class PyMca_normalization(Process):
80
    def __init__(self):
81
        Process.__init__(self, 'normalization')
82
83
84
85
86
87
88
89
90
        self._settings = None

    def setProperties(self, properties):
        if '_pymcaSettings' in properties:
            self._settings = properties['_pymcaSettings']

    def process(self, xas_obj):
        """

91
92
93
94
        :param xas_obj: object containing the configuration and spectra to process
        :type: Union[XASObject, dict]. If is a dict, should contain configuration or
                                     spectra keys. Otherwise is simply the spectra
        :return: spectra dict
95
96
97
        :rtype: dict
        """
        if isinstance(xas_obj, dict):
98
            _xas_obj = XASObject.from_dict(xas_obj)
99
100
        else:
            _xas_obj = xas_obj
101
102
103
104
105

        if _xas_obj.energy is None:
            _logger.error('Energy not specified, unable to normalize spectra')
            return

106
107
108
        if self._settings:
            _xas_obj.configuration['Normalization'] = self._settings

109
        self._advancement.reset(max_=_xas_obj.n_spectrum)
110
        self._advancement.startProcess()
111
112
113
114
115
116
117
118
119
120
121
122
123
        with multiprocessing.Pool(5) as p:
            partial_ = functools.partial(_process_spectrum,
                                         configuration=_xas_obj.configuration,
                                         callback=self._advancement.increaseAdvancement)
            res = p.map(partial_, _xas_obj.spectra)

        # update xas_obj TODO: find a better way for setting this
        for i, res_ite in enumerate(res):
            configuration, spectrum = res_ite
            _xas_obj.spectra[i].spectrum = spectrum
            _xas_obj.spectra[i].configuration = configuration
        _xas_obj.configuration = _xas_obj.spectra[0].configuration

124
125
        self._advancement.endProcess()
        return _xas_obj
126
127

    __call__ = process