normalization.py 4.78 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
41
42
43
44
45
46
47
48
def process_spectr_norm(spectrum, configuration, overwrite=True):
    """

    :param :class:`.Spectrum` spectrum: spectrum to process
    :param dict configuration: configuration of the pymca normalization
    :param bool overwrite: False if we want to return a new Spectrum instance
    :return:
    :rtype: tuple (configuration, spectrum)
    """
49
50
    if spectrum.mu is None:
        _logger.error('Mu is not specified, unable to normalize')
51
        return None, None
52
53
54
55
56
    pymca_xas = XASClass()
    pymca_xas.setSpectrum(energy=spectrum.energy,
                          mu=spectrum.mu)
    pymca_xas.setConfiguration(configuration)
    configuration = pymca_xas.getConfiguration()
57
58
59
60
61
62
63
64
65
    # try:
    pymca_xas.processSpectrum()
    ddict = spectrum.to_dict()
    res = pymca_xas.normalize()
    ddict.update(res)
    spectrum_ = Spectrum.from_dict(ddict)
    # except (IndexError, ValueError) as e:
    #     _logger.error(e)
    #     return None, None
66
67
68
69
70
    if overwrite:
        spectrum.load_frm_dict(spectrum_.to_dict())
        return configuration, spectrum
    else:
        return configuration, spectrum_
71
72


73
def pymca_normalization(xas_obj):
payno's avatar
payno committed
74
    """
75

76
77
78
79
    :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
80
    :rtype: dict
payno's avatar
payno committed
81
    """
82
83
    normalization_obj = PyMca_normalization()
    return normalization_obj.process(xas_obj=xas_obj)
84
85


86
class PyMca_normalization(Process):
87
    def __init__(self):
88
        Process.__init__(self, 'normalization')
89
        self._advancement = Progress(self.name)
90
91
92
93
94
95
96
97
98
        self._settings = None

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

    def process(self, xas_obj):
        """

99
100
101
        :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
102
103
        :return: updated XASObject
        :rtype: :class:`.XASObject`
104
        """
105
        _xas_obj = self._getXasObject(xas_obj)
106
107
108
109
110

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

111
112
113
        if self._settings:
            _xas_obj.configuration['Normalization'] = self._settings

114
        self._advancement.reset(max_=_xas_obj.n_spectrum)
115
        self._advancement.startProcess()
116
117
118
119
120
121
        self._pool_process(xas_obj=xas_obj)
        self._advancement.endProcess()
        return _xas_obj

    def _pool_process(self, xas_obj):
        """process normalization from a pool"""
122
        with multiprocessing.Pool(5) as p:
123
            partial_ = functools.partial(process_spectr_norm,
124
125
126
                                         configuration=xas_obj.configuration,
                                         callback=self._advancement.increaseAdvancement,
                                         overwrite=True)
127
            p.map(partial_, xas_obj.spectra)
128

129
        xas_obj.configuration = xas_obj.spectra[0].configuration
130
131

    __call__ = process