normalization.py 4.85 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
33
from xas.core.types import Spectrum
from .process import Process, Progress
34
35
import multiprocessing
import functools
payno's avatar
payno committed
36
37
38
39
import logging
_logger = logging.getLogger(__name__)


40
def _process_spectr_norm(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
        self._advancement = Progress(self.name)
83
84
85
86
87
88
        self._settings = None

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

89
    # TODO: this can be generalized from process.
90
91
92
    def process(self, xas_obj):
        """

93
94
95
96
        :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
97
98
        :rtype: dict
        """
99
        _xas_obj = self._getXasObject(xas_obj)
100
101
102
103
104

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

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

108
        self._advancement.reset(max_=_xas_obj.n_spectrum)
109
        self._advancement.startProcess()
110
111
112
113
114
115
        self._pool_process(xas_obj=xas_obj)
        self._advancement.endProcess()
        return _xas_obj

    def _pool_process(self, xas_obj):
        """process normalization from a pool"""
116
        with multiprocessing.Pool(5) as p:
117
            partial_ = functools.partial(_process_spectr_norm,
118
119
120
121
                                         configuration=xas_obj.configuration,
                                         callback=self._advancement.increaseAdvancement,
                                         overwrite=True)
            res = p.map(partial_, xas_obj.spectra)
122
123
124
125

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

    __call__ = process