Commit 3580eb17 authored by payno's avatar payno

[core] move from one spectrum to several spectra.

- simplify the bases structure Spectrum and XASObject to be more generic and continue workfing with pymca.
parent 89496a4d
......@@ -33,7 +33,6 @@ from Orange.widgets.widget import OWWidget
from silx.gui import qt
from Orange.widgets.settings import Setting
from xas.core.types import XASObject
from xas.core.types import XASFactory
import xas.io
import logging
_logger = logging.getLogger(__file__)
......@@ -111,7 +110,7 @@ class XASOutputOW(OWWidget):
def process(self, xas_obj):
if isinstance(xas_obj, dict):
_xas_obj = XASFactory.from_dict(xas_obj)
_xas_obj = XASObject.from_dict(xas_obj)
else:
_xas_obj = xas_obj
......
......@@ -35,7 +35,6 @@ def exec_(scheme, input_=None, output_=None):
if len(scheme._start_actor.listDownStreamActor) is 0:
_logger.warning('no downstream node defined')
return None
scheme._start_actor.trigger(input_)
scheme._end_actor.join()
return scheme._end_actor.outData
......
......@@ -27,7 +27,7 @@ __authors__ = ["H. Payno"]
__license__ = "MIT"
__date__ = "06/11/2019"
from xas.core.types import PyMcaSpectrum
from xas.core.types import XASObject
from PyMca5.PyMcaPhysics.xas.XASClass import XASClass
from PyMca5.PyMcaPhysics.xas.XASClass import e2k
import logging
......@@ -44,32 +44,42 @@ def pymca_exafs(xas_obj):
:rtype: XASObject
"""
if isinstance(xas_obj, dict):
_xas_obj = PyMcaSpectrum().load_frm_dict(xas_obj)
_xas_obj = XASObject.from_dict(xas_obj)
else:
_xas_obj = xas_obj
pymca_xas = XASClass()
if 'Energy' not in _xas_obj.spectra or 'Mu' not in _xas_obj.spectra:
_logger.error('Energy and or Mu is/are not specified, unable to '
'compute exafs')
return
pymca_xas.setSpectrum(energy=_xas_obj.spectra['Energy'],
mu=_xas_obj.spectra['Mu'])
pymca_xas.setConfiguration(_xas_obj.configuration)
_xas_obj.spectra.update(pymca_xas.processSpectrum())
if 'EXAFSKValues' in _xas_obj.spectra and 'Mu' in _xas_obj.spectra:
kValues = _xas_obj.spectra['EXAFSKValues']
else:
if 'Mu' not in _xas_obj.spectra:
print('********************** computing **********************')
if 'Edge' not in _xas_obj.spectra:
_xas_obj.spectra.update(pymca_xas.processSpectrum())
e0 = _xas_obj.spectra['Edge']
energy = _xas_obj.spectra['Energy']
kValues = e2k(energy - e0)
_xas_obj.spectra['EXAFSKValues'] = kValues
mu = _xas_obj.spectra['Mu']
_xas_obj.spectra['EXAFS'] = pymca_xas.postEdge(k=kValues, mu=mu)
def _process_spectrum(spectrum, configuration):
"""process a single spectrum"""
pymca_xas = XASClass()
pymca_xas.setSpectrum(energy=spectrum.energy,
mu=spectrum.mu)
pymca_xas.setConfiguration(configuration)
spectrum.update(pymca_xas.processSpectrum())
if 'Energy' not in spectrum or 'Mu' not in spectrum:
_logger.error('Energy and or Mu is/are not specified, unable to '
'compute exafs')
return None, None
if 'EXAFSKValues' in spectrum and 'Mu' in spectrum:
kValues = spectrum['EXAFSKValues']
else:
if 'Mu' not in spectrum:
print('********************** computing **********************')
if 'Edge' not in spectrum:
spectrum.update(pymca_xas.processSpectrum())
e0 = spectrum['Edge']
energy = spectrum['Energy']
kValues = e2k(energy - e0)
spectrum['EXAFSKValues'] = kValues
mu = spectrum.mu
spectrum['EXAFS'] = pymca_xas.postEdge(k=kValues, mu=mu)
return configuration, spectrum
# TODO: look for vectorized this
for i_spectrum, spectrum in enumerate(_xas_obj.spectra):
_xas_obj.configuration, _xas_obj.spectra[i_spectrum] = _process_spectrum(spectrum=spectrum, configuration=_xas_obj.configuration)
assert isinstance(_xas_obj, XASObject)
return _xas_obj
......@@ -83,7 +93,7 @@ class PyMca_exafs(object):
def process(self, xas_obj):
if isinstance(xas_obj, dict):
_xas_obj = PyMcaSpectrum().load_frm_dict(xas_obj)
_xas_obj = XASObject.from_dict(xas_obj)
else:
_xas_obj = xas_obj
if self._settings:
......
......@@ -28,7 +28,7 @@ __license__ = "MIT"
__date__ = "06/11/2019"
from PyMca5.PyMcaPhysics.xas.XASClass import XASClass
from xas.core.types import PyMcaSpectrum
from xas.core.types import XASObject, Spectrum
import logging
_logger = logging.getLogger(__name__)
......@@ -43,18 +43,26 @@ def pymca_ft(xas_obj):
:rtype: dict
"""
if isinstance(xas_obj, dict):
_xas_obj = PyMcaSpectrum().load_frm_dict(xas_obj)
_xas_obj = XASObject.from_dict(xas_obj)
else:
_xas_obj = xas_obj
pymca_xas = XASClass()
if 'Energy' not in _xas_obj.spectra or 'Mu' not in _xas_obj.spectra:
_logger.error('Energy and or Mu is/are not specified, unable to '
'compute exafs')
return
pymca_xas.setConfiguration(_xas_obj.configuration)
pymca_xas.setSpectrum(energy=_xas_obj.spectra['Energy'],
mu=_xas_obj.spectra['Mu'])
_xas_obj.spectra = pymca_xas.processSpectrum()
def _process_spectrum(spectrum, configuration):
pymca_xas = XASClass()
if spectrum.energy is None or spectrum.mu is None:
_logger.error('Energy and or Mu is/are not specified, unable to '
'compute exafs')
return None, None
pymca_xas.setConfiguration(configuration)
pymca_xas.setSpectrum(energy=spectrum.energy,
mu=spectrum.mu)
spectrum = Spectrum.from_dict(pymca_xas.processSpectrum())
assert 'FT' in spectrum
return configuration, spectrum
for i_spectrum, spectrum in enumerate(_xas_obj.spectra):
_xas_obj.configuration, _xas_obj.spectra[i_spectrum] = _process_spectrum(spectrum=spectrum,
configuration=_xas_obj.configuration)
return _xas_obj
......@@ -75,7 +83,7 @@ class PyMca_ft(object):
:rtype: dict
"""
if isinstance(xas_obj, dict):
_xas_obj = PyMcaSpectrum().load_frm_dict(xas_obj)
_xas_obj = XASObject.from_dict(xas_obj)
else:
_xas_obj = xas_obj
if self._settings:
......
......@@ -27,7 +27,7 @@ __authors__ = ["H. Payno"]
__license__ = "MIT"
__date__ = "06/11/2019"
from xas.core.types import PyMcaSpectrum
from xas.core.types import XASObject, Spectrum
from PyMca5.PyMcaPhysics.xas.XASClass import XASClass
import logging
......@@ -44,15 +44,14 @@ def pymca_k_weight(xas_obj):
"""
assert xas_obj is not None
if isinstance(xas_obj, dict):
_xas_obj = PyMcaSpectrum().load_frm_dict(xas_obj)
_xas_obj = XASObject.from_dict(xas_obj)
else:
_xas_obj = xas_obj
assert _xas_obj is not None
if 'SET_KWEIGHT' not in _xas_obj.configuration:
_logger.warning(
'Missing configuration to know which value we should set '
'to k weight, will be set to 0 by default')
'Missing configuration to know which value we should set '
'to k weight, will be set to 0 by default')
_xas_obj.configuration['SET_KWEIGHT'] = 0
for key in ('FT', 'EXAFS', 'Normalization'):
......@@ -67,14 +66,22 @@ def pymca_k_weight(xas_obj):
_xas_obj.configuration['Normalization']['KWeight'] = _xas_obj.configuration[
'SET_KWEIGHT']
pymca_xas = XASClass()
if 'Energy' not in _xas_obj.spectra or 'Mu' not in _xas_obj.spectra:
raise ValueError('Energy and or Mu is/are not specified, unable to '
'compute exafs')
pymca_xas.setSpectrum(energy=_xas_obj.spectra['Energy'],
mu=_xas_obj.spectra['Mu'])
pymca_xas.setConfiguration(_xas_obj.configuration)
_xas_obj.spectra = pymca_xas.processSpectrum()
def _process_spectrum(spectrum, configuration):
assert spectrum is not None
pymca_xas = XASClass()
if spectrum.energy is None or spectrum.mu is None:
raise ValueError('Energy and or Mu is/are not specified, unable to '
'compute exafs')
pymca_xas.setSpectrum(energy=spectrum.energy,
mu=spectrum.mu)
pymca_xas.setConfiguration(configuration)
spectrum = Spectrum.from_dict(pymca_xas.processSpectrum())
return configuration, spectrum
for i_spectrum, spectrum in enumerate(_xas_obj.spectra):
_xas_obj.configuration, _xas_obj.spectra[i_spectrum] = _process_spectrum(spectrum=spectrum, configuration=_xas_obj.configuration)
return _xas_obj
......@@ -96,7 +103,7 @@ class PyMca_k_weight(object):
"""
assert xas_obj is not None
if isinstance(xas_obj, dict):
_xas_obj = PyMcaSpectrum().load_frm_dict(xas_obj)
_xas_obj = XASObject.from_dict(xas_obj)
else:
_xas_obj = xas_obj
if self._k_weight:
......
......@@ -29,7 +29,7 @@ __date__ = "06/11/2019"
from PyMca5.PyMcaPhysics.xas.XASClass import XASClass
from xas.core.types import PyMcaSpectrum
from xas.core.types import XASObject, Spectrum
import logging
_logger = logging.getLogger(__name__)
......@@ -43,22 +43,40 @@ def pymca_normalization(xas_obj):
:return: spectra dict
:rtype: dict
"""
pymca_xas = XASClass()
if isinstance(xas_obj, dict):
_xas_obj = PyMcaSpectrum().load_frm_dict(xas_obj)
_xas_obj = XASObject().load_frm_dict(xas_obj)
else:
_xas_obj = xas_obj
if 'Energy' not in _xas_obj.spectra or 'Mu' not in _xas_obj.spectra:
_logger.error('Energy and or Mu is/are not specified, unable to '
'normalize')
if _xas_obj.energy is None:
_logger.error('Energy not specified, unable to normalize spectra')
return
pymca_xas.setSpectrum(energy=_xas_obj.spectra['Energy'],
mu=_xas_obj.spectra['Mu'])
pymca_xas.setConfiguration(_xas_obj.configuration)
_xas_obj.configuration = pymca_xas.getConfiguration()
pymca_xas.processSpectrum()
res = pymca_xas.normalize()
_xas_obj.spectra.update(res)
def _process_spectrum(spectrum, configuration):
if spectrum.mu is None:
_logger.error('Mu is not specified, unable to normalize')
return
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)
spectrum = Spectrum.from_dict(ddict)
except (IndexError, ValueError) as e:
_logger.error(e)
return configuration, spectrum
# TODO: this part could be optimized using vectorization or multiprocess for
# example.
for i_spectrum, spectrum in enumerate(_xas_obj.spectra):
_xas_obj.configuration, _xas_obj.spectra[i_spectrum] = _process_spectrum(spectrum=spectrum,
configuration=_xas_obj.configuration)
return _xas_obj
......@@ -80,7 +98,7 @@ class PyMca_normalization(object):
:rtype: dict
"""
if isinstance(xas_obj, dict):
_xas_obj = PyMcaSpectrum().load_frm_dict(xas_obj)
_xas_obj = XASObject.from_dict(xas_obj)
else:
_xas_obj = xas_obj
if self._settings:
......
......@@ -29,7 +29,7 @@ __date__ = "06/11/2019"
import unittest
from xas.core.process.exafs import pymca_exafs
from xas.core.types import PyMcaSpectrum, XASObject
from xas.core.types import Spectrum, XASObject
from PyMca5.PyMcaDataDir import PYMCA_DATA_DIR
from xas.core.utils.pymca import read_spectrum
import os
......@@ -39,24 +39,25 @@ class TestEXAFSSingleSpectrum(unittest.TestCase):
"""Make sure the process have valid io"""
def setUp(self):
data_file = os.path.join(PYMCA_DATA_DIR, "EXAFS_Cu.dat")
spectrum = {}
spectrum['Energy'], spectrum['Mu'] = read_spectrum(data_file)
self.input_ = PyMcaSpectrum(spectrum=spectrum)
energy, mu = read_spectrum(data_file)
spectrum = Spectrum(energy=energy, mu=mu)
self.input_ = XASObject(energy=energy, spectra=(spectrum,), dim1=1,
dim2=1)
def testPyMcaXASAsInput(self):
res = pymca_exafs(self.input_)
self.assertTrue(isinstance(res, XASObject))
self.assertTrue('PostEdgeB' in res.spectra)
self.assertTrue('EXAFSKValues' in res.spectra)
self.assertTrue('EXAFSSignal' in res.spectra)
self.assertTrue('PostEdgeB' in res.spectra[0])
self.assertTrue('EXAFSKValues' in res.spectra[0])
self.assertTrue('EXAFSSignal' in res.spectra[0])
def testDictAsInput(self):
"""Test succeed if the input is a dict"""
res = pymca_exafs(self.input_.to_dict())
self.assertTrue(isinstance(res, XASObject))
self.assertTrue('PostEdgeB' in res.spectra)
self.assertTrue('EXAFSKValues' in res.spectra)
self.assertTrue('EXAFSSignal' in res.spectra)
self.assertTrue('PostEdgeB' in res.spectra[0])
self.assertTrue('EXAFSKValues' in res.spectra[0])
self.assertTrue('EXAFSSignal' in res.spectra[0])
def suite():
......
......@@ -31,7 +31,7 @@ import unittest
from xas.core.process.ft import pymca_ft
from PyMca5.PyMcaDataDir import PYMCA_DATA_DIR
from xas.core.utils.pymca import read_spectrum
from xas.core.types import PyMcaSpectrum, XASObject
from xas.core.types import XASObject, Spectrum
import os
......@@ -39,24 +39,24 @@ class TestFTSingleSpectrum(unittest.TestCase):
"""Make sure the process have valid io"""
def setUp(self):
data_file = os.path.join(PYMCA_DATA_DIR, "EXAFS_Cu.dat")
spectrum = {}
spectrum['Energy'], spectrum['Mu'] = read_spectrum(data_file)
self.spectrum = spectrum
self.xas_obj = PyMcaSpectrum(spectrum=spectrum)
energy, mu = read_spectrum(data_file)
self.spectrum = Spectrum(energy=energy, mu=mu)
self.xas_obj = XASObject(energy=energy, spectra=(self.spectrum,),
dim1=1, dim2=1)
def testPyMcaXASAsInput(self):
res = pymca_ft(xas_obj=self.xas_obj)
self.assertTrue(isinstance(res, XASObject))
self.assertTrue('FTRadius' in res.spectrum['FT'])
self.assertTrue('FTImaginary' in res.spectrum['FT'])
self.assertTrue('FTIntensity' in res.spectrum['FT'])
self.assertTrue('FTRadius' in res.spectra[0]['FT'])
self.assertTrue('FTImaginary' in res.spectra[0]['FT'])
self.assertTrue('FTIntensity' in res.spectra[0]['FT'])
def testDictAsInput(self):
res = pymca_ft(xas_obj=self.xas_obj.to_dict())
self.assertTrue(isinstance(res, XASObject))
self.assertTrue('FTRadius' in res.spectrum['FT'])
self.assertTrue('FTImaginary' in res.spectrum['FT'])
self.assertTrue('FTIntensity' in res.spectrum['FT'])
self.assertTrue('FTRadius' in res.spectra[0]['FT'])
self.assertTrue('FTImaginary' in res.spectra[0]['FT'])
self.assertTrue('FTIntensity' in res.spectra[0]['FT'])
def suite():
......
......@@ -31,9 +31,10 @@ import unittest
from xas.io import read_pymca_xas
from silx.io.url import DataUrl
from PyMca5.PyMcaDataDir import PYMCA_DATA_DIR
from xas.core.types import XASObject, XASFactory
from xas.core.types import XASObject
import shutil
import tempfile
import numpy
import os
......@@ -49,19 +50,23 @@ class TestReadWrite(unittest.TestCase):
def testReadSpectrum(self):
data_file = os.path.join(PYMCA_DATA_DIR, "EXAFS_Cu.dat")
res = read_pymca_xas(spectra_url=DataUrl(file_path=data_file,
scheme='PyMca'),
channel_url=DataUrl(file_path=data_file,
scheme='PyMca'))
self.assertTrue(isinstance(res, XASObject))
self.assertTrue('Mu' in res.spectra)
self.assertTrue('Energy' in res.spectra)
self.assertEqual(res.n_spectrum, 1)
self.assertTrue('Mu' in res.spectra[0])
self.assertTrue('Energy' in res.spectra[0])
def testReadWriteH5(self):
"""Tset io relative to h5py"""
xas_obj = XASObject(configuration={'axis': 2},
spectrum={'Energy': 2.1, 'Mu': 0.2})
spectra=numpy.arange(10).reshape(10, 1, 1),
energy=numpy.arange(10))
xas_obj.dump(self.outputfile)
self.assertTrue(os.path.exists(self.outputfile))
xas_obj2 = XASFactory.from_data_url(self.outputfile)
xas_obj2 = XASObject.from_file(self.outputfile)
assert xas_obj2
self.assertEqual(xas_obj, xas_obj2)
......
......@@ -31,7 +31,7 @@ import unittest
import os
from PyMca5.PyMcaDataDir import PYMCA_DATA_DIR
from xas.core.process.k_weight import pymca_k_weight
from xas.core.types import PyMcaSpectrum
from xas.core.types import Spectrum, XASObject
from xas.core.utils.pymca import read_spectrum
......@@ -40,11 +40,11 @@ class TestKWeightSingleSpectrum(unittest.TestCase):
def setUp(self):
self.config = {'SET_KWEIGHT': 2.0}
data_file = os.path.join(PYMCA_DATA_DIR, "EXAFS_Cu.dat")
spectrum = {}
spectrum['Energy'], spectrum['Mu'] = read_spectrum(data_file)
energy, mu = read_spectrum(data_file)
self.spectrum = spectrum
self.xas_obj = PyMcaSpectrum(spectrum=spectrum, configuration=self.config)
self.spectrum = Spectrum(energy=energy, mu=mu)
self.xas_obj = XASObject(energy=energy, spectra=(self.spectrum, ),
configuration=self.config, dim1=1, dim2=1)
def testWithXASObjAsInput(self):
pymca_k_weight(xas_obj=self.xas_obj)
......
......@@ -29,45 +29,70 @@ __date__ = "06/11/2019"
import unittest
from xas.core.process.normalization import pymca_normalization
from xas.core.types import PyMcaSpectrum, XASObject
from xas.core.types import Spectrum, XASObject
from xas.core.utils.pymca import read_spectrum
from xas.core.utils import spectra as spectra_utils
from xas.io import read_pymca_xas
from PyMca5.PyMcaDataDir import PYMCA_DATA_DIR
from silx.io.url import DataUrl
import os
import numpy
import tempfile
import shutil
import h5py
class TestNormalizationSingleSpectrum(unittest.TestCase):
"""Make sure the process have valid io"""
def setUp(self):
data_file = os.path.join(PYMCA_DATA_DIR, "EXAFS_Cu.dat")
spectrum = {}
spectrum['Energy'], spectrum['Mu'] = read_spectrum(data_file)
self.xas_obj = PyMcaSpectrum(spectrum=spectrum)
energy, mu = read_spectrum(data_file)
self.spectrum = Spectrum(energy=energy, mu=mu)
self.xas_obj = XASObject(spectra=(self.spectrum,), energy=energy,
dim1=1, dim2=1)
def testWithXASObjAsInput(self):
res = pymca_normalization(xas_obj=self.xas_obj)
self.assertTrue(isinstance(res, XASObject))
self.assertTrue('NormalizedMu' in res.spectrum)
self.assertTrue('NormalizedEnergy' in res.spectrum)
self.assertTrue('NormalizedSignal' in res.spectrum)
self.assertTrue(isinstance(res.spectra, (tuple, list)))
res_spectrum = res.spectra[0]
self.assertTrue(isinstance(res_spectrum, Spectrum))
self.assertTrue('NormalizedMu' in res_spectrum)
self.assertTrue('NormalizedEnergy' in res_spectrum)
self.assertTrue('NormalizedSignal' in res_spectrum)
def testWithDictAsInput(self):
res = pymca_normalization(xas_obj=self.xas_obj.to_dict())
self.assertTrue(isinstance(res, XASObject))
self.assertTrue('NormalizedMu' in res.spectrum)
self.assertTrue('NormalizedEnergy' in res.spectrum)
self.assertTrue('NormalizedSignal' in res.spectrum)
self.assertTrue('NormalizedMu' in res.spectra[0])
self.assertTrue('NormalizedEnergy' in res.spectra[0])
self.assertTrue('NormalizedSignal' in res.spectra[0])
class TestNormalizationMultipleSpectrum(unittest.TestCase):
""""""
def setUp(self):
data_file = '/nobackup/linazimov/payno/dev/esrf/xas/S5_nuit1_merge_new_crop.h5'
self.spectra = spectra_utils.create_dataset(shape=(256, 20, 10))
self.energy = numpy.linspace(start=3.26, stop=3.96, num=256)
self.output_dir = tempfile.mkdtemp()
spectra_path = '/data/NXdata/data'
channel_path = '/data/NXdata/Channel'
filename = os.path.join(self.output_dir, 'myfile.h5')
with h5py.File(filename) as f:
f[spectra_path] = self.spectra
f[channel_path] = self.energy
self.xas_obj = read_pymca_xas(
spectra_url=DataUrl(file_path=data_file,
data_path='/data/NXdata/data',
scheme='silx'))
spectra_url=DataUrl(file_path=filename,
data_path=spectra_path,
scheme='silx'),
channel_url=DataUrl(file_path=filename,
data_path=channel_path,
scheme='silx'),
)
def tearDown(self):
shutil.rmtree(path=self.output_dir)
def testWithXASObjAsInput(self):
res = pymca_normalization(xas_obj=self.xas_obj)
......
......@@ -43,6 +43,8 @@ class TestStreamSingleSpectrum(unittest.TestCase):
def test_pymca_process(self):
data_file = os.path.join(PYMCA_DATA_DIR, "EXAFS_Cu.dat")
out = read_pymca_xas(spectra_url=DataUrl(file_path=data_file,
scheme='PyMca'),
channel_url=DataUrl(file_path=data_file,
scheme='PyMca'))
out = pymca_normalization(xas_obj=out)
out = pymca_k_weight(xas_obj=out)
......@@ -53,6 +55,8 @@ class TestStreamSingleSpectrum(unittest.TestCase):
def test_pymca_process_with_cls(self):
data_file = os.path.join(PYMCA_DATA_DIR, "EXAFS_Cu.dat")
out = read_pymca_xas(spectra_url=DataUrl(file_path=data_file,
scheme='PyMca'),
channel_url=DataUrl(file_path=data_file,
scheme='PyMca'))
out = PyMca_normalization()(xas_obj=out)
out = PyMca_k_weight()(xas_obj=out)
......
......@@ -28,8 +28,7 @@ __license__ = "MIT"
__date__ = "06/11/2019"
from silx.io.dictdump import dicttoh5
import silx.io.utils
from silx.io.dictdump import dicttoh5, h5todict
import copy
import numpy
import logging
......@@ -168,6 +167,19 @@ class XASObject(object):
self.spectrum = ddict
return self
<<<<<<< HEAD
=======
@staticmethod
def from_dict(ddict):
return XASObject().load_frm_dict(ddict=ddict)
@staticmethod
def from_file(h5_file):
ddict = h5todict(h5file=h5_file)
return XASObject.from_dict(ddict=ddict)
>>>>>>> 854819f... fix b81fd6b08587923138a5156441340508914830ac
def dump(self, h5_file):
"""dump the XAS object to a file_path"""
dicttoh5(treedict=self.to_dict(), h5file=h5_file)
......@@ -230,12 +242,14 @@ class Spectrum(object):
self._NORMALIZED_MU_KEY: self.__class__.normalized_mu,
self._NORMALIZED_ENERGY_KEY: self.__class__.normalized_energy,
self._NORMALIZED_SIGNAL_KEY: self.__class__.normalized_signal,
self._FT_KEY: self.__class__.ft
}
@property
def energy(self):
return self.__energy
# TODO: energy should be removed here and only part of the XASObject
@energy.setter
def energy(self, energy):
assert isinstance(energy, numpy.ndarray) or energy is None
......@@ -313,6 +327,59 @@ class Spectrum(object):
else:
self.__other_parameters[key] = value
def __contains__(self, item):
return item in self.__key_mapper or item in self.__other_parameters
@staticmethod
def from_dict(ddict):
spectrum = Spectrum()
for key, value in ddict.items():
spectrum[key] = value
return spectrum
def to_dict(self):
res = {
self._MU_KEY: self.mu,
self._ENERGY_KEY: self.energy,
self._FT_KEY: self.ft.to_dict(),
self._NORMALIZED_MU_KEY: self.normalized_mu,
self._NORMALIZED_ENERGY_KEY: self.normalized_energy,
self._NORMALIZED_SIGNAL_KEY: self.normalized_signal,
}
res.update(self.__other_parameters)
return res
def __str__(self):
def add_info(str_, attr):
assert hasattr(self, attr)
sub_str = '- ' + attr + ': ' + str(getattr(self, attr)) + '\n'
return (str_ + sub_str)
main_info = ""
for info in ('energy', 'mu', 'normalized_mu', 'normalized_signal', 'normalized_energy'):
main_info = add_info(str_=main_info, attr=info)
def add_third_info(str_, key):
sub_str = ('- ' + key + ': ' + str(self[key])) + '\n'
return str_ + sub_str
for key in self.__other_parameters:
main_info = add_third_info(str_=main_info, key=key)
return main_info
def update(self, obj):
"""
Update the contained values from the given obj.
:param obj:
:type obj: Union[XASObject, dict]
"""
if isinstance(obj, XASObject):
_obj = obj.to_dict()
else:
_obj = obj
assert isinstance(_obj, dict)
for key, value in obj.items():
self[key] = value
class _FT(object):
......@@ -375,29 +442,14 @@ class _FT(object):
else:
self.__other_parameters[key] = value
def __contains__(self, item):
return item in self.__key_mapper or item in self.__other_parameters
class XASFactory(object):
"""Simple factory"""
@staticmethod
def from_dict(ddict):
"""
:param dict ddict: dict to interpret as a XAS object
:return: the XAS object defined by the given ddict
:rtype: `.PyMcaSpectrum`
"""
return XASObject().load_frm_dict(ddict)
@staticmethod
def from_data_url(data_url):
"""Load the XAS object contain in a .h5 file (spectra and
configuration)
:param str data_url: path to the .h5 file
"""
value = silx.io.utils.get_data(data_url)
if isinstance(value, numpy.ndarray):
return XASObject(spectra=value)
elif not isinstance(value, dict):
raise ValueError('unrecognized file type')
return XASFactory.from_dict(ddict=value)
def to_dict(self):
res = {
self._RADIUS_KEY: self.radius,
self._INTENSITY_KEY: self.intensity,
self._IMAGINERY_KEY: self.imaginery,
}
res.update(self.__other_parameters)
return res
# coding: utf-8
# /*##########################################################################
#