Exemple #1
0
def get_x_ray_CoFe():
    xdb = XrayDB()
    lines_Fe = xdb.xray_lines('Fe', excitation_energy=20e3)
    lines_Co = xdb.xray_lines('Co', excitation_energy=20e3)
    intensity_Ka1 = (lines_Fe['Ka1'].intensity + lines_Fe['Ka2'].intensity +
                     lines_Fe['Ka3'].intensity)
    return lines_Fe, lines_Co, intensity_Ka1
Exemple #2
0
def test_xray_line_strengths():
    xdb = XrayDB()
    assert len(xdb.xray_line_strengths('Hg', excitation_energy=2800)) == 2
    assert len(xdb.xray_line_strengths('Hg', excitation_energy=12000)) == 3
    assert len(xdb.xray_line_strengths('Hg', excitation_energy=12500)) == 9
    assert len(xdb.xray_line_strengths('Hg', excitation_energy=14300)) == 13
    assert len(xdb.xray_line_strengths('Hg', excitation_energy=16000)) == 17
 def initUI(self):
     """
     initialize the GUI components
     """
     self.sampleFileName = self.sampleFileNameLineEdit.text()
     self.doubleValidator = QDoubleValidator()
     self.integerValidator = QIntValidator()
     if self.sampleFileName == '':
         self.sampleFileName = None
     self.sampleNumsChanged()
     self.bkgNumChanged()
     self.stdNumChanged()
     #self.sampleThicknessLineEdit.setValidator(self.doubleValidator)
     self.bkgThicknessLineEdit.setValidator(self.doubleValidator)
     self.stdThicknessLineEdit.setValidator(self.doubleValidator)
     self.sampleThickness = float(self.sampleThicknessLineEdit.text())
     self.bkgThickness = float(self.bkgThicknessLineEdit.text())
     self.energyNpts = self.energyNptsSpinBox.value()
     self.repeatNpts = self.repeatSpinBox.value()
     self.normStd = self.normStdSampleComboBox.currentText()
     self.stdThickness = float(self.stdThicknessLineEdit.text())
     self.xMinMaxText = self.xMinMaxLineEdit.text()
     self.xMin, self.xMax = list(map(float, self.xMinMaxText.split(':')))
     self.interpType = self.interpComboBox.currentText()
     self.progressBar.setMinimum(0)
     self.progressBar.setValue(0)
     self.xdb = XrayDB()
Exemple #4
0
 def __init__(self, parent=None):
     """
     """
     QWidget.__init__(self, parent)
     loadUi('UI_Forms/XAnoS_EnergySteps.ui', self)
     self.xrdb = XrayDB()
     self.initialize_UI()
     self.init_signals()
Exemple #5
0
def test_xraydb_version():
    xdb = XrayDB()
    version = xdb.get_version()
    assert 'XrayDB Version: 4.0, Python' in version

    hist = xdb.get_version(with_history=True)
    assert len(hist) > 350
    hist = hist.split('\n')
    assert len(hist) > 4
Exemple #6
0
 def __init__(self, formula=None):
     self.formula = formula
     self.xdb = XrayDB()
     cols = ['symbol', 'covalent_radius_cordero']
     ptable = get_table('elements')
     x = ptable[cols]
     self.covalent_radius = x.set_index('symbol').T.to_dict(
         'index')['covalent_radius_cordero']
     if formula is not None:
         self.parse(self.formula)
Exemple #7
0
def plotTransmission(symbol, edge="K", thickness=0.001, energies=None):
    """ Plots absorption in a given material as function of wavelength.

    :param symbol: The chemical symbol of the material.
    :type symbol: str

    :param edge: The requested absorption edge (K, L1, L2, M1, M2, ...)
    :type edge: str

    :param thickness: The material thickness in centimeters."
    :type thickness: float

    :param energies: For which energies to plot the transmission.
    :type energies: ndarray

    """
    # Instantiate the database.
    xdb = XrayDB()

    # Get info on requested edge.
    edge_data = xdb.xray_edge(symbol, edge)
    edge_position = edge_data[0]
    edge_fyield = edge_data[1]
    edge_jump = edge_data[2]

    # Mass density (ambient).
    rho = xdb.density(symbol)

    # Fix energy range.
    min_energy = 0.7 * edge_position
    max_energy = 1.3 * edge_position

    # Setup arrays
    if energies is None:
        energies = numpy.linspace(min_energy, max_energy, 1024)
    mu = xdb.mu_chantler(symbol, energy=energies)

    # Convert to iterable if needed.
    if not hasattr(thickness, "__iter__"):
        thickness = [thickness]

    absorption = [numpy.exp(-mu * rho * th) for th in thickness]
    for i, abso in enumerate(absorption):
        pyplot.plot(energies,
                    abso,
                    lw=2,
                    label=r"%3.1f $\mu$m" % (thickness[i] * 1e4))
    pyplot.xlabel('Energy (eV)')
    pyplot.ylabel('Transmission')
    pyplot.legend()
    pyplot.title("%s %s-edge" % (symbol, edge))

    pyplot.show()
Exemple #8
0
 def signoise(filels, inter, edge):
     jj = inter
     data = EData(filels[jj])
     df = data.reader(data.datain)
     edgelib = XrayDB()
     edgenom = edgelib.xray_edge(edge, 'K')[0]
     if len(df[df['e'] > 100 + edgenom]) < 20:
         edgenom = edgelib.xray_edge(edge, 'L3')[0]
     dftrim = df[df['e'] > 100 + edgenom]
     xfsmean = dftrim[dftrim.columns[1]].mean()
     xfsstd = dftrim[dftrim.columns[1]].std()
     return xfsmean, xfsstd
Exemple #9
0
    def __init__(self):
        self.E = None
        self.I = None
        self.sI = None
        self.min_E = 0
        self.max_E = np.inf

        self.xdb = XrayDB()
        self.lines_Fe = self.xdb.xray_lines('Fe', excitation_energy=20e3)
        self.lines_Co = self.xdb.xray_lines('Co', excitation_energy=20e3)
        self.intensity_Ka1 = (self.lines_Fe['Ka1'].intensity +
                              self.lines_Fe['Ka2'].intensity +
                              self.lines_Fe['Ka3'].intensity)
Exemple #10
0
def test_ionization_potentials():
    xdb = XrayDB()
    assert xdb.ionization_potential('air') == 33.8
    assert xdb.ionization_potential('helium') == 41.3
    assert xdb.ionization_potential('He') == 41.3
    assert xdb.ionization_potential('Si') == 3.68

    with pytest.raises(ValueError):
        xdb.ionization_potential('p10')
Exemple #11
0
def test_density():
    xdb = XrayDB()
    assert_allclose(xdb.density('Ne'), 0.00090, rtol=0.01)
    assert_allclose(xdb.density('Ti'), 4.506, rtol=0.01)
    assert_allclose(xdb.density('Kr'), 0.00375, rtol=0.01)
    assert_allclose(xdb.density('Mo'), 10.28, rtol=0.01)
    assert_allclose(xdb.density('Pd'), 12.03, rtol=0.01)
    assert_allclose(xdb.density('Au'), 19.3, rtol=0.01)
    with pytest.raises(ValueError):
        xdb.density('Mx')
 def __init__(self,
              x=0,
              rmin=0.0,
              rmax=30.0,
              Nr=31,
              Rc=10.0,
              strho=1.0,
              tst=2.0,
              lrho=0.5,
              lexp=10.0,
              rhosol=0.0,
              norm=1.0,
              bkg=0.0,
              mpar={}):
     """
     Documentation
     x     	: independent variable in the form of a scalar or an array
     Rc    	: Radial distance in Angstroms after which the solvent contribution starts
     strho 	: Concentration of the ions of interest in the stern layer in Molar
     tst   	: Thickness of stern layer in Angstroms
     lrho  	: The maximum concentration of the diffuse layer in Molars
     lexp  	: The decay length of the diffuse layer assuming exponential decay
     rhosol	: The surrounding bulk density
     norm  	: Density of particles in Moles/Liter
     bkg  	: Constant background
     """
     if type(x) == list:
         self.x = np.array(x)
     else:
         self.x = x
     self.rmin = rmin
     self.rmax = rmax
     self.Nr = Nr
     self.Rc = Rc
     self.strho = strho
     self.tst = tst
     self.lrho = lrho
     self.lexp = lexp
     self.rhosol = rhosol
     self.norm = norm
     self.bkg = bkg
     self.__mpar__ = mpar  #If there is any multivalued parameter
     self.choices = {
     }  #If there are choices available for any fixed parameters
     self.__xrdb__ = XrayDB()
     self.init_params()
     self.output_params = {'scaler_parameters': {}}
Exemple #13
0
    def __init__(
            self,
            x=0,
            E=12.0,
            fname1='W:/Tianbo_Collab/Mo132.xyz',
            eta1=1.0,
            fname2='/media/sf_Mrinal_Bera/Documents/MA-Collab/XTal_data/P2W12.xyz',
            eta2=0.0,
            rmin=0.0,
            rmax=10.0,
            Nr=100,
            qoff=0.0,
            sol=18.0,
            sig=0.0,
            norm=1,
            bkg=0.0,
            mpar={}):
        """
        Calculates the form factor for two different kinds of  molecules in cm^-1 for which the XYZ coordinates of the all the atoms composing the molecules are known

        x    	scalar or array of reciprocal wave vectors
        E    	Energy of the X-rays at which the scattering pattern is measured
        fname1	Name with path of the .xyz file containing X, Y, Z coordinates of all the atoms of the molecule of type 1
        eta1 	Fraction of molecule type 1
        fname2	Name with path of the .xyz file containing X, Y, Z coordinates of all the atoms of the moleucule of type 2
        eta2 	Fraction of molecule type 2
        rmin 	Minimum radial distance for calculating electron density
        rmax 	Maximum radial distance for calculating electron density
        Nr    	Number of points at which electron density will be calculated
        qoff 	Q-offset may be required due to uncertainity in Q-calibration
        sol	 	No of electrons in solvent molecule (Ex: H2O has 18 electrons)
        sig  	Debye-waller factor
        norm 	Normalization constant which can be the molar concentration of the particles
        bkg 	Background
        """
        if type(x) == list:
            self.x = np.array(x)
        else:
            self.x = np.array([x])
        if os.path.exists(fname1):
            self.fname1 = fname1
        else:
            self.fname1 = None
        self.eta1 = eta1
        if os.path.exists(fname2):
            self.fname2 = fname2
        else:
            self.fname2 = None
        self.eta2 = eta2
        self.rmin = rmin
        self.__rmin__ = rmin
        self.rmax = rmax
        self.__rmax__ = rmax
        self.Nr = Nr
        self.__Nr__ = Nr
        self.norm = norm
        self.bkg = bkg
        self.E = E
        self.sol = sol
        self.qoff = qoff
        self.sig = sig
        self.__mpar__ = mpar  #If there is any multivalued parameter
        self.choices = {
        }  #If there are choices available for any fixed parameters
        self.__fnames__ = [self.fname1, self.fname2]
        self.__E__ = E
        self.__xdb__ = XrayDB()
        #if self.fname1 is not None:
        #    self.__Natoms1__,self.__pos1__,self.__f11__=self.readXYZ(self.fname1)
        #if self.fname2 is not None:
        #    self.__Natoms2__,self.__pos2__,self.__f12__=self.readXYZ(self.fname2)
        self.__x__ = self.x
        self.__qoff__ = self.qoff
        self.output_params = {'scaler_parameters': {}}
Exemple #14
0
class Formol:  #Please put the class name same as the function name
    re = 2.818e-5  #Classical electron radius in Angstroms
    No = 6.023e23  #Avagadro's number

    def __init__(
            self,
            x=0,
            E=12.0,
            fname1='W:/Tianbo_Collab/Mo132.xyz',
            eta1=1.0,
            fname2='/media/sf_Mrinal_Bera/Documents/MA-Collab/XTal_data/P2W12.xyz',
            eta2=0.0,
            rmin=0.0,
            rmax=10.0,
            Nr=100,
            qoff=0.0,
            sol=18.0,
            sig=0.0,
            norm=1,
            bkg=0.0,
            mpar={}):
        """
        Calculates the form factor for two different kinds of  molecules in cm^-1 for which the XYZ coordinates of the all the atoms composing the molecules are known

        x    	scalar or array of reciprocal wave vectors
        E    	Energy of the X-rays at which the scattering pattern is measured
        fname1	Name with path of the .xyz file containing X, Y, Z coordinates of all the atoms of the molecule of type 1
        eta1 	Fraction of molecule type 1
        fname2	Name with path of the .xyz file containing X, Y, Z coordinates of all the atoms of the moleucule of type 2
        eta2 	Fraction of molecule type 2
        rmin 	Minimum radial distance for calculating electron density
        rmax 	Maximum radial distance for calculating electron density
        Nr    	Number of points at which electron density will be calculated
        qoff 	Q-offset may be required due to uncertainity in Q-calibration
        sol	 	No of electrons in solvent molecule (Ex: H2O has 18 electrons)
        sig  	Debye-waller factor
        norm 	Normalization constant which can be the molar concentration of the particles
        bkg 	Background
        """
        if type(x) == list:
            self.x = np.array(x)
        else:
            self.x = np.array([x])
        if os.path.exists(fname1):
            self.fname1 = fname1
        else:
            self.fname1 = None
        self.eta1 = eta1
        if os.path.exists(fname2):
            self.fname2 = fname2
        else:
            self.fname2 = None
        self.eta2 = eta2
        self.rmin = rmin
        self.__rmin__ = rmin
        self.rmax = rmax
        self.__rmax__ = rmax
        self.Nr = Nr
        self.__Nr__ = Nr
        self.norm = norm
        self.bkg = bkg
        self.E = E
        self.sol = sol
        self.qoff = qoff
        self.sig = sig
        self.__mpar__ = mpar  #If there is any multivalued parameter
        self.choices = {
        }  #If there are choices available for any fixed parameters
        self.__fnames__ = [self.fname1, self.fname2]
        self.__E__ = E
        self.__xdb__ = XrayDB()
        #if self.fname1 is not None:
        #    self.__Natoms1__,self.__pos1__,self.__f11__=self.readXYZ(self.fname1)
        #if self.fname2 is not None:
        #    self.__Natoms2__,self.__pos2__,self.__f12__=self.readXYZ(self.fname2)
        self.__x__ = self.x
        self.__qoff__ = self.qoff
        self.output_params = {'scaler_parameters': {}}

    def init_params(self):
        """
        Define all the fitting parameters like
        self.param.add('sig',value=0,vary=0)
        """
        self.params = Parameters()
        self.params.add('eta1',
                        value=self.eta1,
                        vary=0,
                        min=-np.inf,
                        max=np.inf,
                        expr=None,
                        brute_step=0.1)
        self.params.add('eta2',
                        value=self.eta2,
                        vary=0,
                        min=-np.inf,
                        max=np.inf,
                        expr=None,
                        brute_step=0.1)
        self.params.add('qoff',
                        value=self.qoff,
                        vary=0,
                        min=-np.inf,
                        max=np.inf,
                        expr=None,
                        brute_step=0.1)
        self.params.add('norm',
                        value=self.norm,
                        vary=0,
                        min=-np.inf,
                        max=np.inf,
                        expr=None,
                        brute_step=0.1)
        self.params.add('bkg',
                        value=self.bkg,
                        vary=0,
                        min=-np.inf,
                        max=np.inf,
                        expr=None,
                        brute_step=0.1)
        self.params.add('sig',
                        value=self.sig,
                        vary=0,
                        min=-np.inf,
                        max=np.inf,
                        expr=None,
                        brute_step=0.1)

    def readXYZ(self, fname):
        """
        Reads the xyz file to read the atomic positions and put it in dictionary
        """
        fh = open(fname, 'r')
        lines = fh.readlines()
        Natoms = eval(lines[0])
        atoms = {'Natoms': Natoms}
        cen = np.zeros(3)
        atoms['elements'] = []
        for i in range(Natoms):
            line = lines[i + 2].split()
            pos = np.array(list((map(eval, line[1:]))))
            if line[0] not in atoms['elements']:
                atoms['elements'].append(line[0])
            atoms[i] = {'element': line[0], 'pos': pos}
            cen = cen + pos
        cen = cen / Natoms
        for i in range(Natoms):
            atoms[i]['pos'] = atoms[i]['pos'] - cen
            atoms[i]['distance'] = np.sqrt(np.sum(atoms[i]['pos']**2))
        return atoms

    def calc_xtal_rho(self, fname, rmin=0, rmax=10, Nr=81, energy=None):
        """
        Calculates radially averaged complex electron density in el/Angs^3 of a molecule from the co-ordinates obtained from X-ray crystallography.

        fname   :: .xyz file having all the X, Y, Z coordinates of atoms of the molecule in Angstroms
        rmin    :: Minimum radial distance in Angstroms (If rmin=0 then calculaiton will be done with rmin=1e-3 to avoid r=0 in the density calculation)
        rmax    :: Maximum radial distance in Angstroms
        Nr      :: (Use odd numbers only) No. of points between rmin and rmax at which the electron density has to be calculated
        energy  :: Energy in keV at which the electron density will be calculated
        """
        atoms = self.readXYZ(fname)
        if rmin < 1e-6:
            rmin = 1e-3
        r = np.linspace(rmin, rmax, Nr)
        dr = r[1] - r[0]
        rho = np.zeros(Nr) * (1.0 + 0.0j)
        for ele in atoms['elements']:
            distances = [
                atoms[i]['distance'] for i in range(atoms['Natoms'])
                if atoms[i]['element'] == ele
            ]
            Nrho, _ = np.histogram(distances,
                                   bins=Nr,
                                   range=(rmin - dr / 2, rmax + dr / 2))
            if energy is None:
                rho = rho + Nrho * (
                    self.__xdb__.f0(ele, 0.0)
                )  #+xrdb.f1_chantler(element=ele,energy=energy*1e3,smoothing=0))
            else:
                f1 = self.__xdb__.f1_chantler(element=ele,
                                              energy=energy * 1e3,
                                              smoothing=0)
                f2 = self.__xdb__.f2_chantler(element=ele,
                                              energy=energy * 1e3,
                                              smoothing=0)
                rho = rho + Nrho * (self.__xdb__.f0(ele, 0.0) + f1 + 1.0j * f2)

    #print(r[:-1]+(),rho)
        return r, rho / 4 / np.pi / r**2 / dr  #+self.sol*np.where(rho<1e-6,1.0,0.0)

    def calc_form(self, q, r, rho):
        """
        Calculates the isotropic form factor in cm^-1 using the isotropic electron density as a funciton of radial distance

        q       :: scaler or array of reciprocal reciprocal wave vector in inv. Angstroms at which the form factor needs to be calculated in
        r       :: array of radial distances at which he electron density in known in Angstroms
        rho     :: array of electron densities as a funciton of radial distance in el/Angstroms^3. Note: The electron density should decay to zero at the last radial distance
        """
        dr = r[1] - r[0]
        q = q + self.__qoff__
        form = np.zeros_like(q)
        for r1, rho1 in zip(r, rho):
            form = form + 4 * np.pi * r1 * rho1 * np.sin(q * r1) / q
        form = self.No * self.re**2 * np.absolute(
            form)**2 * dr**2 * 1e-16 / 1e3  # in cm^-1/moles
        return form

    def y(self):
        """
        Define the function in terms of x to return some value
        """
        self.__qoff__ = self.params['qoff']
        #if self.__fnames__!=[None,None]:
        #Contribution from first molecule
        if self.fname1 is not None:
            if self.__fnames__[0] != self.fname1 or self.__E__ != self.E or len(
                    self.__x__
            ) != len(self.x) or self.__x__[-1] != self.x[
                    -1] or self.__qoff__ != self.qoff or self.__Nr__ != self.Nr or self.__rmin__ != self.rmin or self.__rmax__ != self.rmax:
                self.__r1__, self.__rho1__ = self.calc_xtal_rho(self.fname1,
                                                                rmin=self.rmin,
                                                                rmax=self.rmax,
                                                                Nr=self.Nr,
                                                                energy=self.E)
            form1 = self.calc_form(self.x, self.__r1__, self.__rho1__)
            self.output_params['rho_1'] = {
                'x': self.__r1__,
                'y': np.real(self.__rho1__)
            }
        #Contribution from second molecule
        if self.fname2 is not None:
            if self.__fnames__[1] != self.fname2 or self.__E__ != self.E or len(
                    self.__x__
            ) != len(self.x) or self.__x__[-1] != self.x[
                    -1] or self.__qoff__ != self.qoff or self.__Nr__ != self.Nr or self.__rmin__ != self.rmin or self.__rmax__ != self.rmax:
                self.__r2__, self.__rho2__ = self.calc_xtal_rho(self.fname2,
                                                                rmin=self.rmin,
                                                                rmax=self.rmax,
                                                                Nr=self.Nr,
                                                                energy=self.E)
            form2 = self.calc_form(self.x, self.__r2__, self.__rho2__)
            self.output_params['rho_2'] = {
                'x': self.__r2__,
                'y': np.real(self.__rho2__)
            }

        self.__fnames__ = [self.fname1, self.fname2]
        self.__E__ = self.E
        self.__x__ = self.x
        self.__rmin__ = self.rmin
        self.__rmax__ = self.rmax
        self.__Nr__ = self.Nr

        if self.__fnames__[0] is not None and self.__fnames__[1] is not None:
            self.output_params[os.path.basename(self.fname1) + '_1'] = {
                'x': self.x,
                'y': self.norm * self.eta1 * form1
            }
            self.output_params[os.path.basename(self.fname2) + '_1'] = {
                'x': self.x,
                'y': self.norm * self.eta2 * form2
            }
            self.output_params['bkg'] = {
                'x': self.x,
                'y': self.bkg * np.ones_like(self.x)
            }
            return (self.eta1 * form1 + self.eta2 * form2
                    ) * self.norm * np.exp(-self.x**2 * self.sig**2) + self.bkg
        elif self.__fnames__[0] is not None and self.__fnames__[1] is None:
            self.output_params[os.path.basename(self.fname1) + '_1'] = {
                'x': self.x,
                'y': self.norm * self.eta1 * form1
            }
            self.output_params['bkg'] = {
                'x': self.x,
                'y': self.bkg * np.ones_like(self.x)
            }
            return self.eta1 * form1 * self.norm * np.exp(
                -self.x**2 * self.sig**2) + self.bkg
        elif self.__fnames__[0] is None and self.__fnames__[1] is not None:
            self.output_params[os.path.basename(self.fname2) + '_1'] = {
                'x': self.x,
                'y': self.norm * self.eta2 * form2
            }
            self.output_params['bkg'] = {
                'x': self.x,
                'y': self.bkg * np.ones_like(self.x)
            }
            return self.eta2 * form2 * self.norm * np.exp(
                -self.x**2 * self.sig**2) + self.bkg
        else:
            return np.ones_like(self.x)
Exemple #15
0
from xraydb import XrayDB
import matplotlib.pyplot as plt
import operator
import numpy
import scipy.optimize as optimization
import scipy


xray = XrayDB()
Energy_Value = [i for i in range(12000, 26010, 10)]
dn_count = 1
#real Xray source data 

source_xray = numpy.loadtxt('/ufs/piao/Desktop/data_xray.txt')
source_xray = source_xray.transpose()
source_xray[0] = source_xray[0] * 0.01165211 - 0.147653
print source_xray


#detector efficiency data

detector_efficiency = numpy.loadtxt('/ufs/piao/Downloads/Default Dataset.csv', delimiter=',')
detector_efficiency = detector_efficiency.transpose()
detector_efficiency[1] = detector_efficiency[1] / 100
print detector_efficiency

def counting_on_threshold_source_real(threshold_kev):
    i = 0

    for element in source_xray[0]:
        if element > threshold_kev:
Exemple #16
0
from xraydb import XrayDB
db = XrayDB()


def extract(dat, key):
    val = dat.get(key, [' '])[0]
    if isinstance(val, float) and val > 1:
        val = int(round(val))
    return str(val)


elnames = ('', 'hydrogen', 'helium', 'lithium', 'beryllium', 'boron', 'carbon',
           'nitrogen', 'oxygen', 'fluorine', 'neon', 'sodium', 'magnesium',
           'aluminum', 'silicon', 'phosphorus', 'sulfur', 'chlorine', 'argon',
           'potassium', 'calcium', 'scandium', 'titanium', 'vanadium',
           'chromium', 'manganese', 'iron', 'cobalt', 'nickel', 'copper',
           'zinc', 'gallium', 'germanium', 'arsenic', 'selenium', 'bromine',
           'krypton', 'rubidium', 'strontium', 'yttrium', 'zirconium',
           'niobium', 'molybdenum', 'technetium', 'ruthenium', 'rhodium',
           'palladium', 'silver', 'cadmium', 'indium', 'tin', 'antimony',
           'tellurium', 'iodine', 'xenon', 'cesium', 'barium', 'lanthanum',
           'cerium', 'praseodymium', 'neodymium', 'promethium', 'samarium',
           'europium', 'gadolinium', 'terbium', 'dysprosium', 'holmium',
           'erbium', 'thulium', 'ytterbium', 'lutetium', 'hafnium', 'tantalum',
           'tungsten', 'rhenium', 'osmium', 'iridium', 'platinum', 'gold',
           'mercury', 'thallium', 'lead', 'bismuth', 'polonium', 'astatine',
           'radon', 'francium', 'radium', 'actinium', 'thorium',
           'protactinium', 'uranium', 'neptunium', 'plutonium', 'americium',
           'curium', 'berkelium', 'californium')

chemstates = {
Exemple #17
0
def _larch_init(_larch):
    """initialize xraydb"""
    setsym = _larch.symtable.set_symbol
    setsym('_xray._xraydb', XrayDB())
    setsym('_xray._materials', _read_materials_db())
class XAnoS_Batch_Processor_2(QWidget):
    """
    """
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=None)
        loadUi('UI_Forms/ASAXS_Batch_Processor_2.ui', self)
        self.initUI()
        self.init_signals()
        try:
            self.open_settings()
        except:
            pass
        self.stop = False

    def initUI(self):
        """
        initialize the GUI components
        """
        self.sampleFileName = self.sampleFileNameLineEdit.text()
        self.doubleValidator = QDoubleValidator()
        self.integerValidator = QIntValidator()
        if self.sampleFileName == '':
            self.sampleFileName = None
        self.sampleNumsChanged()
        self.bkgNumChanged()
        self.stdNumChanged()
        #self.sampleThicknessLineEdit.setValidator(self.doubleValidator)
        self.bkgThicknessLineEdit.setValidator(self.doubleValidator)
        self.stdThicknessLineEdit.setValidator(self.doubleValidator)
        self.sampleThickness = float(self.sampleThicknessLineEdit.text())
        self.bkgThickness = float(self.bkgThicknessLineEdit.text())
        self.energyNpts = self.energyNptsSpinBox.value()
        self.repeatNpts = self.repeatSpinBox.value()
        self.normStd = self.normStdSampleComboBox.currentText()
        self.stdThickness = float(self.stdThicknessLineEdit.text())
        self.xMinMaxText = self.xMinMaxLineEdit.text()
        self.xMin, self.xMax = list(map(float, self.xMinMaxText.split(':')))
        self.interpType = self.interpComboBox.currentText()
        self.progressBar.setMinimum(0)
        self.progressBar.setValue(0)
        self.xdb = XrayDB()

    def init_signals(self):
        """
        Initialize signals
        :return:
        """
        self.selectFileNamePushButton.clicked.connect(self.openSampleFname)
        self.firstSampleNumsLineEdit.returnPressed.connect(
            self.sampleNumsChanged)
        #self.firstSampleNumsLineEdit.textEdited.connect(self.sampleNumsChanged)
        self.bkgSpinBox.valueChanged.connect(self.bkgNumChanged)
        self.stdSpinBox.valueChanged.connect(self.stdNumChanged)
        self.mtSpinBox.valueChanged.connect(self.mtNumChanged)
        self.airSpinBox.valueChanged.connect(self.airNumChanged)
        self.sampleThicknessLineEdit.returnPressed.connect(
            self.sampleThicknessChanged)
        #self.sampleThicknessLineEdit.textEdited.connect(self.sampleThicknessChanged)
        self.stdThicknessLineEdit.returnPressed.connect(
            self.stdThicknessChanged)
        #self.stdThicknessLineEdit.textEdited.connect(self.stdThicknessChanged)
        self.bkgThicknessLineEdit.returnPressed.connect(
            self.bkgThicknessChanged)
        #self.bkgThicknessLineEdit.textEdited.connect(self.bkgThicknessChanged)
        self.sampleSetSpinBox.valueChanged.connect(self.sampleSetChanged)
        self.energyNptsSpinBox.valueChanged.connect(self.energyNptsChanged)
        self.repeatSpinBox.valueChanged.connect(self.repeatNptsChanged)
        self.normStdSampleComboBox.currentIndexChanged.connect(
            self.normStdChanged)
        self.xMinMaxLineEdit.returnPressed.connect(self.xMinMaxChanged)
        self.interpComboBox.currentIndexChanged.connect(self.interpTypeChanged)
        self.processPushButton.clicked.connect(self.process)
        self.stopPushButton.clicked.connect(self.stopProcess)

    def stopProcess(self):
        self.stop = True

    def process(self):
        if self.spikeFilterCheckBox.isChecked():
            do_avg = True
        else:
            do_avg = False
        if not self.duplicateNums():
            self.infoTextEdit.clear()
            if self.sampleFileName is not None:
                bg_num = self.bkgNum
                gc_num = self.stdNum
                air_num = self.airNum
                mt_num = self.mtNum
                fdir = os.path.dirname(self.sampleFileName)
                mean_dir = os.path.join(fdir, 'Mean')
                ctimes = self.sampleSet * self.repeatNpts
                data = {}
                bsub_data = {}

                if not os.path.exists(mean_dir):
                    os.makedirs(os.path.join(fdir, 'Mean'))
                snames = {}
                bnames = {}
                gnames = {}

                self.progressBar.setMaximum(self.energyNpts - 1)
                self.progressBar.setMinimum(0)
                self.progressBar.setValue(0)

                outputNames = []
                self.outputFnames = []
                for j in range(0, self.energyNpts):
                    if self.stop:
                        self.stop = False
                        self.progressBar.setValue(0)
                        return
                    # Calculating mean of air scattering if the airNum is other than 0
                    if air_num != 0:
                        fnum = []
                        for i in range(air_num + ctimes * j,
                                       air_num + ctimes * j + self.repeatNpts):
                            fnum.append(i)
                            bnames[i] = self.sampleFileName + '%04d.txt' % i
                        data, oaname = average1DSAXS(
                            self.sampleFileName,
                            num=fnum,
                            delete_prev=False,
                            data=data,
                            extra_key=fnum[0],
                            textEdit=self.infoTextEdit,
                            spike_filter=do_avg)

                    # Calculating mean of MT capillary if the mtNum is other than 0
                    if mt_num != 0:
                        fnum = []
                        for i in range(mt_num + ctimes * j,
                                       mt_num + ctimes * j + self.repeatNpts):
                            fnum.append(i)
                            bnames[i] = self.sampleFileName + '%04d.txt' % i
                        data, omname = average1DSAXS(
                            self.sampleFileName,
                            num=fnum,
                            delete_prev=False,
                            data=data,
                            extra_key=fnum[0],
                            textEdit=self.infoTextEdit,
                            spike_filter=do_avg)
                        if air_num != 0:
                            obsmfname = os.path.basename(self.sampleFileName +
                                                         '_%04d_bsub.txt' %
                                                         fnum[0])
                            data, bsmfname = bkgSub1DSAXS(
                                data,
                                omname,
                                data,
                                oaname,
                                obsmfname,
                                thickness=0.02,
                                cf=1.0,
                                bg_factor=1.0,
                                norm=1.0,
                                data=data,
                                textEdit=self.infoTextEdit)
                    #calculating mean of background
                    fnum = []
                    for i in range(bg_num + ctimes * j,
                                   bg_num + ctimes * j + self.repeatNpts):
                        fnum.append(i)
                        bnames[i] = self.sampleFileName + '%04d.txt' % i
                    data, obname = average1DSAXS(self.sampleFileName,
                                                 num=fnum,
                                                 delete_prev=False,
                                                 data=data,
                                                 extra_key=fnum[0],
                                                 textEdit=self.infoTextEdit,
                                                 spike_filter=do_avg)
                    if mt_num != 0:
                        obsbfname = os.path.basename(self.sampleFileName +
                                                     '_%04d_bsub.txt' %
                                                     fnum[0])
                        data, bsbfname = bkgSub1DSAXS(
                            data,
                            obname,
                            data,
                            omname,
                            obsbfname,
                            thickness=self.bkgThickness,
                            cf=1.0,
                            bg_factor=1.0,
                            norm=1.0,
                            data=data,
                            textEdit=self.infoTextEdit)
                    # Calculating mean of GC
                    fnum = []
                    for i in range(gc_num + ctimes * j,
                                   gc_num + ctimes * j + self.repeatNpts):
                        fnum.append(i)
                        gnames[i] = self.sampleFileName + '%04d.txt' % i
                    data, ogname = average1DSAXS(self.sampleFileName,
                                                 num=fnum,
                                                 delete_prev=False,
                                                 data=data,
                                                 extra_key=fnum[0],
                                                 textEdit=self.infoTextEdit,
                                                 spike_filter=do_avg)
                    if air_num != 0:
                        obsgfname = os.path.basename(self.sampleFileName +
                                                     '_%04d_bsub.txt' %
                                                     fnum[0])
                        data, bsgfname = bkgSub1DSAXS(
                            data,
                            ogname,
                            data,
                            oaname,
                            obsgfname,
                            thickness=self.stdThickness,
                            cf=1.0,
                            bg_factor=1.0,
                            norm=1.0,
                            data=data,
                            textEdit=self.infoTextEdit)

                        ene, cf, a, b = calc_cf(
                            bsgfname,
                            standard=self.normStd,
                            thickness=self.stdThickness,
                            xmin=self.xMin,
                            xmax=self.xMax,
                            interpolation_type=self.interpType)
                    else:
                        ene, cf, a, b = calc_cf(
                            ogname,
                            standard=self.normStd,
                            thickness=self.stdThickness,
                            xmin=self.xMin,
                            xmax=self.xMax,
                            interpolation_type=self.interpType)
                    if self.normStd == 'GC':
                        f0 = self.xdb.f0('C', q=0.0)
                        f1 = self.xdb.f1_chantler('C',
                                                  energy=ene * 1e3,
                                                  smoothing=0)
                        cf = cf * (f0[0] / (f0[0] + f1))**2
                    if air_num != 0:
                        data[bsgfname]['CF'] = cf
                        bsub_data[bsgfname] = data[bsgfname]
                    if air_num != 0 and mt_num != 0:
                        data[bsmfname]['CF'] = cf
                        bsub_data[bsmfname] = data[bsmfname]
                    if mt_num != 0:
                        data[bsbfname]['CF'] = cf
                        bsub_data[bsbfname] = data[bsbfname]

                    # Calculating mean of samples
                    t = 0
                    for sam_num in self.samNums:
                        fnum = []
                        for i in range(sam_num + ctimes * j,
                                       sam_num + ctimes * j + self.repeatNpts):
                            fnum.append(i)
                            snames[i] = self.sampleFileName + '%04d.txt' % i
                        data, ofname = average1DSAXS(
                            self.sampleFileName,
                            num=fnum,
                            delete_prev=False,
                            data=data,
                            extra_key=fnum[0],
                            textEdit=self.infoTextEdit,
                            spike_filter=do_avg)

                        # Performing background subtraction
                        obsname = os.path.basename(self.sampleFileName +
                                                   '_%04d_bsub.txt' % fnum[0])

                        bg_factor = self.sampleThickness[t] / self.bkgThickness

                        data, bsfname = bkgSub1DSAXS(
                            data,
                            ofname,
                            data,
                            obname,
                            obsname,
                            thickness=self.sampleThickness[t],
                            cf=cf,
                            bg_factor=bg_factor,
                            norm=1.0,
                            data=data,
                            textEdit=self.infoTextEdit)
                        self.plotWidget.add_data(x=data[bsfname]['x'],y=data[bsfname]['CF']*data[bsfname]['y']/data[bsfname]['Thickness'],\
                                                 yerr=data[bsfname]['CF']*data[bsfname]['yerr']/data[bsfname]['Thickness'],name=str(fnum[0])+'_bsub')
                        bsub_data[bsfname] = data[bsfname]
                        #self.plotWidget.Plot([str(fnum[0])+'_bsub'])
                        outputNames.append(str(fnum[0]) + '_bsub')
                        self.outputFnames.append(bsfname)
                        self.progressBar.setValue(j)
                        self.plotWidget.Plot(outputNames)
                        QApplication.processEvents()
                        t += 1

                self.data = data
                #fdir,fnames=write1DSAXS(bsub_data,textEdit=self.infoTextEdit)
                self.save_settings()
                self.infoTextEdit.append(
                    'Batch processing completed successfully!')
                self.infoTextEdit.moveCursor(QTextCursor.End)
                QApplication.processEvents()
                datadir = os.path.dirname(self.outputFnames[0])
                macrofile = QFileDialog.getSaveFileName(
                    self,
                    caption='Save Macro File as:',
                    filter='Macro Files (*.macro)',
                    directory=datadir)[0]
                macrofile = os.path.splitext(macrofile)[0] + '.macro'
                fh = open(os.path.join(datadir, macrofile), 'w')
                for tfname in self.outputFnames:
                    fh.write(tfname + '\n')
                fh.close()
                reply = QMessageBox.question(
                    self, 'Component Splitting',
                    'Do you like to get component splitting from the files?',
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)

                if reply == QMessageBox.Yes:
                    curdir = os.getcwd()
                    QProcess.startDetached(
                        "python",
                        [os.path.join(curdir, "XAnoS_Components.py")] +
                        self.outputFnames)
                    # w=XAnoS_Components()
                    # resolution = QDesktopWidget().screenGeometry()
                    # w.setGeometry(0, 0, resolution.width() - 100, resolution.height() - 100)
                    # w.move(int(resolution.width() / 2) - int(w.frameSize().width() / 2),
                    # int(resolution.height() / 2) - int(w.frameSize().height() / 2))
                    # w.setWindowTitle('XAnoS_Components')
                    # w.import_data(dataFiles=self.outputFnames)
                    # w.show()

            else:
                QMessageBox.warning(self, 'File Error',
                                    'Please select first sample file',
                                    QMessageBox.Ok)
        else:
            QMessageBox.warning(
                self, 'Error',
                'It seems you are using same file number for two different category of samples. Please check!',
                QMessageBox.Ok)

    def openSampleFname(self):
        fname = QFileDialog.getOpenFileName(caption='Select sample file name',
                                            filter="Sample Files (*.txt)")[0]
        self.sampleFileNameLineEdit.setText(fname[:-9])
        self.sampleNameChanged()

    def sampleNumsChanged(self):
        txt = self.firstSampleNumsLineEdit.text().replace(" ", "")
        samNums = list(map(int, txt.split(",")))
        if np.all(isinstance(x, int) for x in samNums):
            self.samNums = samNums
        else:
            QMessageBox.warning(
                self,
                'Please provide integer values and if multiple separate them by commas in between.',
                QMessageBox.Ok)
            self.samNums = [1]
            self.firstSampleNumsLineEdit.setText('1')
        self.sampleThicknessChanged()
        # try:
        #     txt=self.firstSampleNumsLineEdit.text().replace(" ","")
        #     samNums=list(map(int, txt.split(",")))
        #     if all(isinstance(x, int) for x in samNums):
        #         self.samNums=samNums
        #     else:
        #         QMessageBox.warning(self,
        #                             'Please provide integer values and if multiple separate them by commas in between.',\
        #                             QMessageBox.Ok)
        #         self.samNums=[1]
        #         self.firstSampleNumsLineEdit.setText('1')
        #     self.save_settings()
        # except:
        #     pass

    def bkgNumChanged(self):
        self.bkgNum = self.bkgSpinBox.value()
        # if bkgNum in self.samNums:
        #     response = QMessageBox.question(self, 'As this number also exists as sample number, are you sure this number\
        #      belongs to backgroud?', QMessageBox.Yes, QMessageBox.No)
        #     if response == QMessageBox.Yes:
        #         self.bkgNum = bkgNum
        #     else:
        #         self.bkgSpinBox.setValue(str(self.bkgNum))
        # else:
        #     self.bkgNum = bkgNum
        # self.save_settings()

    def stdNumChanged(self):
        self.stdNum = self.stdSpinBox.value()
        # if stdNum in self.samNums or stdNum==self.bkgNum:
        #     response = QMessageBox.question(self, 'As this number also exists as First Sample Nums, are you sure this number\
        #      belongs to background?', QMessageBox.Yes, QMessageBox.No)
        #     if response == QMessageBox.Yes:
        #         self.stdNum = stdNum
        #     else:
        #         self.stdSpinBox.setValue(self.stdNum)
        # elif stdNum == self.bkgNum:
        #     response = QMessageBox.question(self, 'As this number also exists as First Bkg Num, are you sure this number\
        #                  belongs to Std Num?', QMessageBox.Yes, QMessageBox.No)
        #     if response == QMessageBox.Yes:
        #         self.stdNum = stdNum
        #     else:
        #         self.stdSpinBox.setValue(self.stdNum)
        # else:
        #     self.stdNum = stdNum
        # self.save_settings()

    def sampleSetChanged(self):
        self.sampleSet = self.sampleSetSpinBox.value()

    def mtNumChanged(self):
        self.mtNum = self.mtSpinBox.value()

    def airNumChanged(self):
        self.airNum = self.airSpinBox.value()

    def duplicateNums(self):
        txt = self.firstSampleNumsLineEdit.text().replace(" ", "")
        Nums = list(map(int, txt.split(",")))
        Nums = Nums + [self.bkgNum, self.mtNum, self.airNum]
        if self.mtNum != 0 and self.airNum != 0:
            if np.unique(Nums).size != len(Nums):
                return True
            else:
                return False
        else:
            return False

    def sampleNameChanged(self):
        self.sampleFileName = self.sampleFileNameLineEdit.text()
        if self.sampleFileName == '':
            self.sampleFileName = None

    def sampleThicknessChanged(self):
        #self.sampleThickness= float(self.sampleThicknessLineEdit.text())
        txt = self.sampleThicknessLineEdit.text().replace(" ", "")
        self.sampleThickness = list(map(float, txt.split(",")))
        if len(self.samNums) != len(self.sampleThickness):
            QMessageBox.warning(
                self, 'Sample Error',
                'Please provide %d thicknesses' % len(self.samNums),
                QMessageBox.Ok)
        #self.save_settings()

    def bkgThicknessChanged(self):
        self.bkgThickness = float(self.bkgThicknessLineEdit.text())
        #self.save_settings()

    def stdThicknessChanged(self):
        self.stdThickness = float(self.stdThicknessLineEdit.text())
        #self.save_settings()

    def energyNptsChanged(self):
        self.energyNpts = self.energyNptsSpinBox.value()
        #self.save_settings()

    def repeatNptsChanged(self):
        self.repeatNpts = self.repeatSpinBox.value()
        #self.save_settings()

    def normStdChanged(self):
        self.normStd = self.normStdSampleComboBox.currentText()
        #self.save_settings()

    def xMinMaxChanged(self):
        self.xMinMaxText = self.xMinMaxLineEdit.text()
        try:
            self.xMin, self.xMax = list(map(float,
                                            self.xMinMaxText.split(':')))
        except:
            self.xMin, self.xMax = 0.0, 1.0
            self.xMinMaxLineEdit.setText('%.1f:%.1f' % self.xMin, self.xMax)
        #self.save_settings()

    def interpTypeChanged(self):
        self.interpType = self.interpTypeComboBox.currentText()
        #self.save_settings()

    def save_settings(self):
        fh = open('./batch_settings.txt', 'w+')
        fh.write('samNums=' + str(self.samNums) + '\n')
        fh.write('bkgNum=' + str(self.bkgNum) + '\n')
        fh.write('stdNum=' + str(self.stdNum) + '\n')
        fh.write('mtNum=' + str(self.mtNum) + '\n')
        fh.write('airNum=' + str(self.airNum) + '\n')
        fh.write('sampleThickness=' + str(self.sampleThickness) + '\n')
        fh.write('bkgThickness=' + str(self.bkgThickness) + '\n')
        fh.write('stdThickness=' + str(self.stdThickness) + '\n')
        fh.write('normStd=' + self.normStd + '\n')
        fh.write('xMinMax=' + self.xMinMaxText + '\n')
        fh.write('interpType=' + self.interpType + '\n')
        fh.write('energyNpts=' + str(self.energyNpts) + '\n')
        fh.write('repeatNpts=' + str(self.repeatNpts) + '\n')
        fh.write('sampleSet=' + str(self.sampleSet))
        fh.close()

    def open_settings(self):
        fh = open('./batch_settings.txt', 'r')
        lines = fh.readlines()
        fh.close()
        self.samNums = eval(lines[0].strip().split('=')[1])
        samNums = ''
        for i in self.samNums:
            samNums += str(i) + ','
        self.firstSampleNumsLineEdit.setText(samNums[:-1])

        self.bkgNum = int(lines[1].strip().split('=')[1])
        self.bkgSpinBox.setValue(self.bkgNum)
        self.stdNum = int(lines[2].strip().split('=')[1])
        self.stdSpinBox.setValue(self.stdNum)
        self.mtNum = int(lines[3].strip().split('=')[1])
        self.mtSpinBox.setValue(self.mtNum)
        self.airNum = int(lines[4].strip().split('=')[1])
        self.airSpinBox.setValue(self.airNum)

        self.sampleThickness = eval(lines[5].strip().split('=')[1])
        sampleThickness = ''
        for i in self.sampleThickness:
            sampleThickness += str(i) + ','
        self.sampleThicknessLineEdit.setText(str(sampleThickness[:-1]))

        self.bkgThickness = float(lines[6].strip().split('=')[1])
        self.bkgThicknessLineEdit.setText(str(self.bkgThickness))

        self.stdThickness = float(lines[7].strip().split('=')[1])
        self.stdThicknessLineEdit.setText(str(self.stdThickness))

        self.normStd = lines[8].strip().split('=')[1]
        self.normStdSampleComboBox.setCurrentIndex(
            self.normStdSampleComboBox.findText(self.normStd))

        self.xMinMaxText = lines[9].strip().split('=')[1]
        self.xMinMaxLineEdit.setText(self.xMinMaxText)
        self.xMin, self.xMax = list(map(float, self.xMinMaxText.split(':')))

        self.interpType = lines[10].strip().split('=')[1]
        self.interpComboBox.setCurrentIndex(
            self.interpComboBox.findText(self.interpType))

        self.energyNpts = int(lines[11].strip().split('=')[1])
        self.energyNptsSpinBox.setValue(self.energyNpts)

        self.repeatNpts = int(lines[12].strip().split('=')[1])
        self.repeatSpinBox.setValue(self.repeatNpts)

        self.sampleSet = int(lines[13].strip().split('=')[1])
        self.sampleSetSpinBox.setValue(self.sampleSet)
Exemple #19
0
def theoretical_spectrum(element, Energy_Value):
    return XrayDB().mu_elam(element, Energy_Value)
Exemple #20
0
from xraydb import XrayDB
db = XrayDB()

def extract(dat, key):
    val = dat.get(key, [' '])[0]
    if isinstance(val, float) and val > 1:
        val = int(round(val))
    return str(val)

elnames = ('', 'hydrogen' , 'helium', 'lithium' , 'beryllium', 'boron' ,
           'carbon' ,'nitrogen' , 'oxygen', 'fluorine' , 'neon' ,'sodium',
           'magnesium', 'aluminum' , 'silicon', 'phosphorus' , 'sulfur',
           'chlorine' , 'argon', 'potassium' , 'calcium', 'scandium' ,
           'titanium','vanadium' , 'chromium','manganese' , 'iron',
           'cobalt' , 'nickel','copper' , 'zinc','gallium' ,
           'germanium','arsenic' , 'selenium','bromine' , 'krypton',
           'rubidium' , 'strontium','yttrium' , 'zirconium','niobium' ,
           'molybdenum','technetium' , 'ruthenium','rhodium' ,
           'palladium','silver' , 'cadmium','indium' , 'tin', 'antimony' ,
           'tellurium','iodine' , 'xenon','cesium' , 'barium','lanthanum' ,
           'cerium','praseodymium', 'neodymium', 'promethium' ,
           'samarium','europium' , 'gadolinium', 'terbium' ,
           'dysprosium','holmium' , 'erbium','thulium' ,
           'ytterbium','lutetium' , 'hafnium','tantalum' , 'tungsten',
           'rhenium' , 'osmium','iridium' , 'platinum','gold' ,
           'mercury','thallium' , 'lead','bismuth' , 'polonium', 'astatine',
           'radon','francium' , 'radium','actinium' ,
           'thorium','protactinium', 'uranium','neptunium' , 'plutonium',
           'americium', 'curium', 'berkelium', 'californium')

chemstates = {'':'',
Exemple #21
0
class Chemical_Formula:
    def __init__(self, formula=None):
        self.formula = formula
        self.xdb = XrayDB()
        cols = ['symbol', 'covalent_radius_cordero']
        ptable = get_table('elements')
        x = ptable[cols]
        self.covalent_radius = x.set_index('symbol').T.to_dict(
            'index')['covalent_radius_cordero']
        if formula is not None:
            self.parse(self.formula)

    def parse(self, formula):
        parsed = re.findall(r'([A-Z][a-z]*)([-+]?\d*\.*\d*)', formula)
        self.formula_dict = {}
        for a, b in parsed:
            if b != '':
                self.formula_dict[a] = float(b)
            else:
                self.formula_dict[a] = 1.0
        return self.formula_dict

    def elements(self):
        """
        Provides a list of all the elements in the formula
        :return:
        """
        return list(self.formula_dict.keys())

    def element_mole_ratio(self):
        """
        Provides a dictionary of mole ratio of all the elements in the formula
        :return:
        """
        return self.formula_dict

    def molar_mass(self):
        """
        Provides the total Molar-mass of the compound represented by the formula
        :return:
        """
        return np.sum([
            self.xdb.molar_mass(ele) * num
            for ele, num in self.formula_dict.items()
        ])

    def molecular_weight(self):
        """
        Provides the Molecular-Weight of the compound represented by the formula
        :return:
        """
        return self.molar_mass()

    def molar_mass_ratio(self, element):
        """
        Provides the molecular-mass-ratio of the element in the chemical formula
        :param element: Symbol of the element
        :return:
        """
        if element in self.formula_dict.keys():
            tot = self.molar_mass()
            return self.xdb.molar_mass(
                element) * self.formula_dict[element] / tot
        else:
            return 0.0

    def molar_volume(self):
        """Returns molar volumes in cm^3 or ml"""
        volume = 0.0
        for ele, moles in self.formula_dict.items():
            volume += moles * 4 * np.pi * self.covalent_radius[ele]**3 / 3
        return 6.023e23 * volume * 1e-30
Exemple #22
0
    def edgenom(filels, inter):
        jj = inter
        data = EData(filels[jj])
        df = data.reader(data.datain)
        df['diff'] = df[df.columns[1]].diff()
        edgelib = XrayDB()
        edgeid = 'pre_unkn'
        for z in np.linspace(15, 77, 63):
            if abs(
                    edgelib.xray_edge(edgelib.symbol(int(z)), 'K')[0] -
                    df['e'][df['diff'].idxmax()]) < 15:
                edgeid = edgelib.symbol(int(z))
                print(
                    edgelib.xray_edge(edgelib.symbol(int(z)), 'K')[0] -
                    df['e'][df['diff'].idxmax()])
                print(edgeid)
                print('K')
                print(jj)
            elif abs(
                    edgelib.xray_edge(edgelib.symbol(int(z)), 'L3')[0] -
                    df['e'][df['diff'].idxmax()]) < 15:
                edgeid = edgelib.symbol(int(z))
                print(edgeid)
                print('L3')
                print(jj)
                print(
                    edgelib.xray_edge(edgelib.symbol(int(z)), 'K')[0] -
                    df['e'][df['diff'].idxmax()])

        return df, edgeid, filels[jj]
Exemple #23
0
def test_molar_mass():
    xdb = XrayDB()
    assert_allclose(xdb.molar_mass('Co'), 58.932, rtol=0.001)

    with pytest.raises(ValueError):
        xdb.molar_mass('Mx')
Exemple #24
0
class EDXFit():
    def __init__(self):
        self.E = None
        self.I = None
        self.sI = None
        self.min_E = 0
        self.max_E = np.inf

        self.xdb = XrayDB()
        self.lines_Fe = self.xdb.xray_lines('Fe', excitation_energy=20e3)
        self.lines_Co = self.xdb.xray_lines('Co', excitation_energy=20e3)
        self.intensity_Ka1 = (self.lines_Fe['Ka1'].intensity +
                              self.lines_Fe['Ka2'].intensity +
                              self.lines_Fe['Ka3'].intensity)

    def load_txt_file(self, txtfile, E_min=None, E_max=None, delimiter=','):
        data_array = np.genfromtxt(txtfile, delimiter=delimiter)
        E = data_array[:, 0]
        I = data_array[:, 1]

        # sort in ascending order
        E, I = zip(*sorted(zip(E, I)))
        E = np.asarray(E)
        I = np.asarray(I)

        # cut off data points out of range
        valid_values = np.ones(len(I), dtype=bool)
        if E_min:
            valid_values = np.logical_and(valid_values, E > E_min)
        if E_max:
            valid_values = np.logical_and(valid_values, E < E_max)
        E = E[valid_values]
        I = I[valid_values]

        # Poisson Error
        sI = np.sqrt(I)

        # scale to max. value
        intMax_I = max(I)
        I /= intMax_I
        sI /= intMax_I
        self.E = E
        self.I = I
        self.sI = sI
        return E, I, sI

    def load_edx_htm(self, htmfile):
        elements = []
        weight_percent = []
        atomic_percent = []
        data_array = [elements, weight_percent, atomic_percent]
        with open(htmfile, 'r', errors='ignore') as f:
            soup = BeautifulSoup(f, "lxml")
            table_rows = soup.select("table tr")
            for row in table_rows:
                columns = row.findAll('td')
                for i, row in enumerate(columns):
                    if i > 2: continue
                    if row.contents:
                        el = row.contents[0]
                        data_array[i].append(el)
        return data_array

    def estimateBackground(self, min_E_bg, max_E_bg, subtract=True):
        assert (self.E is not None)
        bg_E_range = np.logical_and(self.E > min_E_bg, self.E < max_E_bg)

        E_bg = self.E[bg_E_range]
        I_bg = self.I[bg_E_range]
        sI_bg = self.sI[bg_E_range]

        self.bg = np.mean(I_bg)
        self.sbg = np.std(I_bg, ddof=1)
        print(f'Estimated Background to: {self.bg} +/- {self.sbg}')

        self.I -= self.bg
        self.sI = np.sqrt(self.sI**2 + self.sbg**2)

    def gaussian(self, x, mu, sig):
        return np.exp(-((x - mu) / sig)**2 / 2)

    def residuum(self, p, E, I, sI, Imodel):
        return (I - Imodel(p, E)) / sI

    def CoFe_model(self, p, E):
        bg = p['bg']
        sigma = p['sigma']
        r_Fe = p['r_Fe']
        r_Co = p['r_Co']
        model = np.zeros(len(E))
        for line in self.lines_Fe:
            energy = self.lines_Fe[line].energy / 1e3
            if energy < self.min_E or energy > self.max_E:
                continue
            intensity = self.lines_Fe[line].intensity
            model += r_Fe * intensity * self.gaussian(E, energy, sigma)

        for line in self.lines_Co:
            energy = self.lines_Co[line].energy / 1e3
            if energy < self.min_E or energy > self.max_E:
                continue
            intensity = self.lines_Co[line].intensity
            model += r_Co * intensity * self.gaussian(E, energy, sigma)
        return model + bg

    def init_params_CoFe(self):
        p = lmfit.Parameters()
        p.add('bg', 0.01, min=0, vary=True)
        p.add('sigma', 0.06, vary=True)
        p.add('r_Co', 1, vary=True)
        p.add('r_Fe', 2, vary=True)
        self.p = p
        return p

    def fit(self, p, Imodel):
        fit_result = lmfit.minimize(self.residuum,
                                    p,
                                    args=(self.E, self.I, self.sI, Imodel))
        print(lmfit.fit_report(fit_result))
        self.p = fit_result.params
Exemple #25
0
def test_density():
    xdb = XrayDB()
    assert_allclose(xdb.molar_mass('Pb'), 207.2, rtol=0.001)

    with pytest.raises(ValueError):
        xdb.density('Mx')
Exemple #26
0
def test_atomic_number():
    xdb = XrayDB()
    assert xdb.atomic_number('Ne') == 10

    with pytest.raises(ValueError):
        xdb.atomic_number('Mx')
Exemple #27
0
class XAnoS_EnergySteps(QWidget):
    """
    This widget calculates the Energy values at which the f' values are equidistant below the absorption edge of a selected element
    """
    def __init__(self, parent=None):
        """
        """
        QWidget.__init__(self, parent)
        loadUi('UI_Forms/XAnoS_EnergySteps.ui', self)
        self.xrdb = XrayDB()
        self.initialize_UI()
        self.init_signals()

    def initialize_UI(self):
        self.doubleValidator=QDoubleValidator()
        self.elements = self.xrdb.atomic_symbols
        self.elementComboBox.addItems(
            [str(self.xrdb.atomic_number(element)) + ': ' + element for element in self.elements])
        self.element=self.elementComboBox.currentText().split(': ')[1]
        edges = self.xrdb.xray_edges(self.element)
        self.edgeComboBox.addItems([key + ': %.4f' % (edges[key].energy / 1000) for key in edges.keys()])
        self.EOffsetLineEdit.setValidator(self.doubleValidator)
        self.minEnergyLineEdit.setValidator(self.doubleValidator)
        self.maxEnergyLineEdit.setValidator(self.doubleValidator)
        self.edgeChanged(self.edgeComboBox.currentText())
        self.NStepsChanged(20)
        self.energyOffset=float(self.EOffsetLineEdit.text())


    def init_signals(self):
        self.elementComboBox.currentTextChanged.connect(self.elementChanged)
        self.edgeComboBox.currentTextChanged.connect(self.edgeChanged)
        self.EOffsetLineEdit.textChanged.connect(self.energyOffsetChanged)
        self.minEnergyLineEdit.textChanged.connect(self.minEnergyChanged)
        self.maxEnergyLineEdit.textChanged.connect(self.maxEnergyChanged)
        self.NStepsSpinBox.valueChanged.connect(self.NStepsChanged)
        self.calculatePushButton.clicked.connect(self.calculate)
        self.savePushButton.clicked.connect(self.saveFile)

    def elementChanged(self, txt):
        self.element=txt.split(': ')[1]
        self.edgeComboBox.currentTextChanged.disconnect()
        self.edgeComboBox.clear()
        edges = self.xrdb.xray_edges(self.element)
        self.edgeComboBox.addItems([key + ': %.4f' % (edges[key].energy / 1000) for key in edges.keys()])
        self.edgeComboBox.currentTextChanged.connect(self.edgeChanged)
        self.edgeChanged(self.edgeComboBox.currentText())

    def edgeChanged(self,txt):
        self.maxEnergy=float(txt.split(': ')[1])
        self.maxEnergyLineEdit.setText('%.4f'%self.maxEnergy)
        self.minEnergyLineEdit.setText('%.4f'%(np.max(self.maxEnergy-1,0)))

    def energyOffsetChanged(self, txt):
        self.energyOffset=float(txt)

    def NStepsChanged(self, N):
        self.NEnergy=N

    def minEnergyChanged(self,txt):
        self.minEnergy=float(txt)

    def maxEnergyChanged(self,txt):
        self.maxEnergy=float(txt)

    def calculate(self):
        edge_energy=self.maxEnergy*1000
        min_energy=self.minEnergy*1000
        element=self.element
        steps=self.NEnergy
        eoff=self.energyOffset

        self.resultTextEdit.clear()
        evals = np.linspace(edge_energy, min_energy, steps)
        efine = np.linspace(edge_energy, min_energy, 1001)
        f1 = self.xrdb.f1_chantler(element=element, energy=efine, smoothing=0)
        f1vals = np.linspace(f1[0], f1[-1], steps)
        e1vals = np.interp(f1vals, f1, efine)
        self.evaltxt = ''
        etemp = np.linspace(min_energy, edge_energy + (edge_energy - min_energy), 2001)
        f1temp = self.xrdb.f1_chantler(element=element, energy=etemp, smoothing=0)
        self.resultTextEdit.append("%10s\t%10s\t%10s\t%10s\t%10s" % ("Step", "f_value", "Mono_E", "Und_E", "f_1"))
        for i in range(steps):
            # print("%.5f\t%.3f"%(f1vals[i],e1vals[i]/1e3))
            self.evaltxt = self.evaltxt + '%.4f,' % (e1vals[i] / 1e3 + eoff)
            self.resultTextEdit.append("%10d\t%10.7f\t%10.4f\t%10.4f\t%10.7f" % (
            i, f1vals[i], e1vals[i] / 1e3 + eoff, e1vals[i] / 1e3 + 0.17 + eoff,
            self.xrdb.f1_chantler(
                element=element, energy=e1vals[i], smoothing=0)))
        self.plotWidget.add_data(x=etemp/1e3,y=f1temp,fit=True,name='continuous')
        self.plotWidget.add_data(x=e1vals/1e3,y=f1vals,name='discrete')
        self.plotWidget.Plot(['continuous','discrete'])
        txt = 'Energy [' + self.evaltxt[:-1] + '] absolute coupled'
        self.resultTextEdit.append('\n')
        self.resultTextEdit.append(txt)


    def saveFile(self):
        try:
            txt = 'Energy [' + self.evaltxt[:-1] + '] absolute coupled'
        except:
            QMessageBox.warning(self,'Save Error','Please calculate before saving!',QMessageBox.Ok)
            return
        fname=QFileDialog.getSaveFileName(parent=self,caption='Save file as', filter="Text files (*.txt )")[0]
        fh = open(fname, 'w')
        fh.write(txt)
        fh.close()
Exemple #28
0
def test_symbol():
    xdb = XrayDB()
    assert xdb.symbol(40) == 'Zr'
Exemple #29
0
from PyQt5.uic import loadUi
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox, QMainWindow, QFileDialog, QDialog, QInputDialog, QTableWidgetItem, QLineEdit
from PyQt5.QtCore import pyqtSignal, Qt, QRegExp
from PyQt5.QtGui import QIntValidator, QDoubleValidator, QFont, QRegExpValidator, QValidator
from PyQt5.QtTest import QTest
import sys
import os
import numpy as np
import re
import scipy.constants
from xraydb import XrayDB
xdb = XrayDB()


class DoubleValidator(QDoubleValidator):
    def __init__(self, parent, bottom=0):
        QDoubleValidator.__init__(self, parent, bottom=bottom)
        self.bottom = bottom

    def validate(self, text, pos):
        try:
            if float(text) >= self.bottom:
                state = QDoubleValidator.Acceptable
            else:
                state = QDoubleValidator.Invalid
        except:
            state = QDoubleValidator.Invalid
        return state, text, pos


class RegExpValidator(QRegExpValidator):
Exemple #30
0
import pylab as pl

print(sys.argv)

if len(sys.argv) == 7:
    element = sys.argv[1]
    edge_energy = 1e3 * float(sys.argv[2])
    min_energy = 1e3 * float(sys.argv[3])
    steps = int(sys.argv[4])
    eoff = float(sys.argv[5])
    try:
        fname = sys.argv[6]
    except:
        fname = '/tmp/positionerFile.txt'

    xrdb = XrayDB()
    evals = np.linspace(edge_energy, min_energy, steps)
    efine = np.linspace(edge_energy, min_energy, 1001)
    f1 = xrdb.f1_chantler(element=element, energy=efine, smoothing=0)
    f1vals = np.linspace(f1[0], f1[-1], steps)
    e1vals = np.interp(f1vals, f1, efine)
    print(np.diff(f1vals))
    print(np.diff(e1vals))
    evaltxt = ''
    pl.figure()
    etemp = np.linspace(min_energy, edge_energy + (edge_energy - min_energy),
                        1001)
    f1temp = xrdb.f1_chantler(element=element, energy=etemp, smoothing=0)
    pl.plot(etemp, f1temp, 'r-', label=element + '-Energy Edge')
    print("%10s\t%10s\t%10s\t%10s\t%10s" %
          ("Step", "f_value", "Mono_E", "Und_E", "f_1"))