__init__.py 4.84 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
32
33
# 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__ = "10/12/2020"


from silx.io.url import DataUrl
from est.units import ur
from est.core.types import Dim
34
from est.io.utils import get_data
payno's avatar
PEP8    
payno committed
35
from est.core.types import XASObject
36
from est.core.io import read_xas
37
from est.io.utils.information import InputInformation
payno's avatar
payno committed
38
import logging
39
from est import settings
payno's avatar
payno committed
40

41
try:
payno's avatar
PEP8    
payno committed
42
    from est.io.utils.spec import read_spectrum  # noqa
43
44
except ImportError:
    has_read_spectrum = False
payno's avatar
PEP8    
payno committed
45
46
47
else:
    has_read_spectrum = True

payno's avatar
payno committed
48
_logger = logging.getLogger(__name__)
payno's avatar
payno committed
49

50
51

def convert_spectra_dims(dims):
payno's avatar
payno committed
52
53
54
55
    """
    Convert a tuple of dims that can be strings... to a tuple of
    est.core.types.Dim
    """
56
57
    if dims is None:
        return None
payno's avatar
payno committed
58
59
60
    res = []
    for dim in dims:
        if isinstance(dim, str):
61
62
63
64
65
66
            if dim.lower() == Dim.DIM_0.value.lower():
                dim = Dim.DIM_0
            elif dim.lower() == Dim.DIM_1.value.lower():
                dim = Dim.DIM_1
            elif dim.lower() == Dim.DIM_2.value.lower():
                dim = Dim.DIM_2
payno's avatar
payno committed
67
68
69
70
71
72
73
74
75
76
77
78
79

        dim = Dim.from_value(dim)
        if dim in res:
            raise ValueError(
                "dimension {} has been provided several time."
                "Each dimension should be set once.".format(dim.value())
            )
        else:
            res.append(dim)
    return tuple(dims)


def get_unit(current_unit):
80
    if current_unit in ("eV", "electron_volt"):
payno's avatar
payno committed
81
        return ur.eV
82
    elif current_unit in ("keV", "kiloelectron_volt"):
payno's avatar
payno committed
83
84
85
86
87
88
89
90
        return ur.keV
    elif current_unit == "J":
        return ur.J
    elif current_unit == "kJ":
        return ur.kJ
    elif isinstance(current_unit, ur.Quantity):
        return current_unit
    else:
91
        raise ValueError("`{}` is not a valid unit for quantity".format(current_unit))
payno's avatar
payno committed
92
93
94


def get_url(my_str):
95
    if my_str in (None, ""):
payno's avatar
payno committed
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
        return None
    else:
        assert isinstance(my_str, str)
        if "@" in my_str:
            try:
                entry, file_path = my_str.split("@")
            except Exception:
                pass
            else:
                return DataUrl(file_path=file_path, data_path=entry, scheme="silx")
        else:
            try:
                url = DataUrl(path=my_str)
            except Exception:
                pass
            else:
                return url
        raise ValueError("unrecognized url {}".format(my_str))
114
115


116
117
118
def get_xas_obj(
    input_information: InputInformation, timeout=settings.DEFAULT_READ_TIMEOUT
):
payno's avatar
payno committed
119
120
    """load xas object from command line input
    :param spec_input: tuple of Union[str, None, dict]
121
    :param float timeout: read time out (for hdf5 only for now)
payno's avatar
payno committed
122
    """
123
124
    sp, en, conf = read_xas(information=input_information, timeout=timeout)
    xas_obj = XASObject(spectra=sp, energy=en, configuration=conf)
125
126
    attr_names = "I0", "I1", "I2", "mu_ref"
    attr_values = (
127
128
129
130
        getattr(input_information, "I0", None),
        getattr(input_information, "I1", None),
        getattr(input_information, "I2", None),
        getattr(input_information, "mu_ref", None),
131
    )
132
    for attr_name, attr_value in zip(attr_names, attr_values):
133
        if attr_value is not None:
134
135
136
137
            if isinstance(attr_value, DataUrl):
                data = get_data(attr_value)
            else:
                data = attr_value
payno's avatar
payno committed
138
139
140
141
142
            if data.shape[0] > xas_obj.energy.shape[0]:
                _logger.warning(
                    "energy has less value than dataset. Clip {}.".format(attr_name)
                )
                data = data[: xas_obj.energy.shape[0]]
143
            xas_obj.attach_3d_array(attr_name, data)
144
    return xas_obj