Exemple #1
0
def dsigma_el(theta, energy, mw, elements, stoic):

    dsigma = 0
    for i in range(0, len(elements)):
        q = xraylib.MomentTransf(energy, theta)
        w = xraylib.AtomicWeight(elements[i]) * stoic[i] / mw
        temp = dsigma_th(theta) * xraylib.FF_Rayl(elements[i], q)**2
        temp = temp / xraylib.AtomicWeight(elements[i]) * w
        dsigma += temp
    dsigma *= mw
    return dsigma
def GetMaterialMu(E, data): # send in  the photon energy and the dictionary holding the layer information
    Ele = data['Element']
    Mol = data['MolFrac']
    t = 0
    for i in range(len(Ele)):
            t += xraylib.AtomicWeight(xraylib.SymbolToAtomicNumber(Ele[i]))*Mol[i]
    mu=0
    for i in range(len(Ele)):
            mu+= (xraylib.CS_Total(xraylib.SymbolToAtomicNumber(Ele[i]),E) * 
                        xraylib.AtomicWeight(xraylib.SymbolToAtomicNumber(Ele[i]))*Mol[i]/t)
    return mu # total attenuataion w/ coherent scattering in cm2/g
Exemple #3
0
def dsigma_inel(theta, energy, mw, elements, stoic):

    dsigma = 0
    for i in range(0, len(elements)):
        q = xraylib.MomentTransf(energy, theta)
        w = xraylib.AtomicWeight(elements[i]) * stoic[i] / mw
        temp = dsigma_kn(theta, energy) * xraylib.SF_Compt(elements[i], q)
        temp = temp / xraylib.AtomicWeight(elements[i]) * w
        dsigma += temp
    dsigma *= mw
    return dsigma
Exemple #4
0
def get_data():
    sym, z, group, period, _type = ([], [], [], [], [])
    mass, density, absedge, alw, flyield, augyield = ([], [], [], [], [], [])
    for i in range(1, 104):
        s = xraylib.AtomicNumberToSymbol(i)
        sym.append(s)
        z.append(i)
        mass.append(xraylib.AtomicWeight(i))
        density.append(str(xraylib.ElementDensity(i)) + ' g/cm^3')

        absedge.append(str(xraylib.EdgeEnergy(i, 0)) + ' keV')
        alw.append(str(xraylib.AtomicLevelWidth(i, 0)) + ' keV')
        flyield.append(str(xraylib.FluorYield(i, 0)))
        augyield.append(str(xraylib.AugerYield(i, 0)))

        pop_period(i, period)
        pop_group(i, group)
        pop_type(i, _type)

    data = {
        'sym': sym,
        'z': z,
        'mass': mass,
        'group': group,
        'period': period,
        '_type': _type,
        'density': density,
        'flyield': flyield,
        'augyield': augyield,
        'absedge': absedge,
        'alw': alw
    }
    return data
Exemple #5
0
def ug_to_mol(samp, map_key, scan_idx, eles, e_idx):
    e_list_idx = e_idx - 1
    e = eles[e_list_idx]
    if len(e) > 2: e = e[:-2]
    else: pass
    z = xl.SymbolToAtomicNumber(e)
    factor = (1 / 1E6) * (1 / xl.AtomicWeight(z))  #(1g/1E6ug) * (1mol/g)
    mol_map = samp[map_key][scan_idx][e_idx, :, :-2] * factor
    return mol_map
Exemple #6
0
def formula(compound):
    elt_CP = [
        xrl.AtomicNumberToSymbol(compound['Elements'][i])
        for i in range(compound['nElements'])
    ]
    atf_CP = [
        compound['massFractions'][i] /
        xrl.AtomicWeight(compound['Elements'][i])
        for i in range(compound['nElements'])
    ]
    atfn_CP = [str(atf / min(atf_CP)) for atf in atf_CP]
    return "".join(np.core.defchararray.add(elt_CP, atfn_CP))
Exemple #7
0
 def ug_to_mol(self, elements):
     # get the XRF maps from each scan
     XRF_maps = [scan[-1:,:,:-2] for scan in self.maps]
     # get atomic number for xraylib reference
     z_list = [xl.SymbolToAtomicNumber(e) for e in elements]
     # calculate mol for each atomic number (1g/1E6ug)*(1mol/g)
     factors = [(1/1E6) * (1/xl.AtomicWeight(z)) for z in z_list]
     # convert factor list to array for easy matrix math
     factor_arr = np.array(factors)
     # 1D fact arr * 3D xrf arr along depth axis for each set of XRF maps
     XRF_mol = [factor_arr[:, None, None] * XRF_map for XRF_map in XRF_maps]
     # assign empty attribute to store mol maps
     self.mol = lambda:None
     # store mol maps; note these do not have electical map!
     self.mol = XRF_mol
     return
Exemple #8
0
def make_mol_maps(samples, elements, dict_data, new_dict_data):
    elements = [element[0:2] for element in elements]
    mol_masses = [
        xl.AtomicWeight(xl.SymbolToAtomicNumber(element))
        for element in elements
    ]
    #ug/cm2 * (g/ug) * (mol/g) == mol/cm2
    conv_factors = [(1 / 1E6) / (1 / mol_mass) for mol_mass in mol_masses]
    for sample in samples:
        mol_scans = []
        for scan_raw_maps in sample[dict_data]:
            mol_maps = scan_raw_maps.copy()
            for ele_idx, factor in enumerate(conv_factors):
                map_idx = ele_idx + 1
                ele_map = scan_raw_maps[map_idx, :, :]
                mol_map = ele_map * factor
                mol_maps[map_idx, :, :] = mol_map
            mol_scans.append(mol_maps)
        samp_dict_grow.build_dict(sample, new_dict_data, mol_scans)
    return
Exemple #9
0
def reflectivity(descriptor,energy,theta,density=None,rough=0.0):



    if isinstance(descriptor,str):
        Z = xraylib.SymbolToAtomicNumber(descriptor)
        symbol = descriptor
    else:
        Z = descriptor
        symbol = xraylib.AtomicNumberToSymbol(descriptor)

    if density == None:
        density = xraylib.ElementDensity(Z)

    atwt = xraylib.AtomicWeight(Z)
    avogadro = codata.Avogadro
    toangstroms = codata.h * codata.c / codata.e * 1e10
    re = codata.e**2 / codata.m_e / codata.c**2 / (4*numpy.pi*codata.epsilon_0) * 1e2 # in cm

    molecules_per_cc = density * avogadro / atwt
    wavelength = toangstroms / energy  * 1e-8 # in cm
    k = molecules_per_cc * re * wavelength * wavelength / 2.0 / numpy.pi

    f1 = numpy.zeros_like(energy)
    f2 = numpy.zeros_like(energy)
    for i,ienergy in enumerate(energy):
        f1[i] = Z + xraylib.Fi(Z,1e-3*ienergy)
        f2[i] = - xraylib.Fii(Z,1e-3*ienergy)

    alpha = 2.0 * k * f1
    gamma = 2.0 * k * f2

    rs,rp,runp = interface_reflectivity(alpha,gamma,theta)

    if rough != 0:
        rough *= 1e-8 # to cm
        debyewaller = numpy.exp( -( 4.0 * numpy.pi * numpy.sin(theta) * rough / wavelength)**2)
    else:
        debyewaller = 1.0

    return rs*debyewaller,rp*debyewaller,runp*debyewaller
Exemple #10
0
def material_refraction(energy, compound, rho):
    """    
    Calculate complex refrative index of the material taking
    into account it's density. 

    Args:
        compound (str): compound chemical formula
        rho (float): density in g / cm3
        energy (numpy.array): energy in KeV   

    Returns:
        float: refraction index in [1/mm]
    """

    import xraylib

    cmp = xraylib.CompoundParser(compound)

    # Compute ration of Z and A:
    z = (numpy.array(cmp['Elements']))
    a = [xraylib.AtomicWeight(x) for x in cmp['Elements']]

    za = ((z / a) * numpy.array(cmp['massFractions'])).sum()

    # Electron density of the material:
    Na = phys_const['Na']
    rho_e = rho * za * Na

    # Attenuation:
    mu = mass_attenuation(energy, compound)

    # Phase:
    wavelength = 2 * numpy.pi * \
        (phys_const['h_bar_ev'] * phys_const['c']) / energy * 10

    # TODO: check this against phantoms.m:
    phi = rho_e * phys_const['re'] * wavelength

    # Refraction index (per mm)
    return rho * (mu / 2 - 1j * phi) / 10
Exemple #11
0
 def test_bad_Z(self):
     with self.assertRaises(ValueError):
         width = xraylib.AtomicWeight(185)
Exemple #12
0
def spectrum(E0, Mat_Z, Mat_X):
    xrs = xg.calculate_spectrum(E0, 12, 3, 100, epsrel=0.5, monitor=None, z=74)
    #Inherent filtration: 1.2mm Al + 100cm Air
    mu_Al = xg.get_mu(13)
    xrs.attenuate(0.12, mu_Al)
    xrs.attenuate(100, xg.get_mu("air"))
    fluence_to_dose = xg.get_fluence_to_dose()
    xrs.set_norm(value=0.146, weight=fluence_to_dose)
    #Attenuation
    if Mat_Z > 0:  #Atomic number
        dMat = xrl.ElementDensity(Mat_Z)
        fMat = xrl.AtomicNumberToSymbol(Mat_Z)
        xrs.attenuate(0.1 * Mat_X, xg.get_mu(Mat_Z))
    else:  #-1 == 'Water'
        mH2O = 2. * xrl.AtomicWeight(1) + xrl.AtomicWeight(8)
        wH = 0.1 * Mat_X * 2. * xrl.AtomicWeight(1) / (xrl.ElementDensity(1) *
                                                       mH2O)
        wO = 0.1 * Mat_X * xrl.AtomicWeight(8) / (xrl.ElementDensity(8) * mH2O)
        xrs.attenuate(wH, xg.get_mu(1))
        xrs.attenuate(wO, xg.get_mu(8))
    #Get the figures
    Nr_Photons = "%.4g" % (xrs.get_norm())
    Average_Energy = "%.2f keV" % (xrs.get_norm(lambda x: x) / xrs.get_norm())
    Dose = "%.3g mGy" % (xrs.get_norm(fluence_to_dose))
    HVL_Al = xrs.hvl(0.5, fluence_to_dose, mu_Al)
    HVL_Al_text = "%.2f mm (Al)" % (10 * HVL_Al)
    a = [["Dose à 1m", Dose], ["Nombre total de photons", Nr_Photons],
         ["Énergie moyenne des photons", Average_Energy],
         ["Couche de Demi-Atténuation", HVL_Al_text]]
    print(to_text(a))
    (x2, y2) = xrs.get_points()
    plt.close(2)
    plt.figure(num=2, dpi=150, clear=True)
    mpl.rcParams.update({'font.size': 6})
    axMW = plt.subplot(111)
    axMW.plot(x2, y2)
    axMW.set_xlim(3, E0)
    axMW.set_ylim(0, )
    plt.xlabel("Énergie [keV]")
    plt.ylabel("Nombre de photons par [keV·cm²·mGy] @ 1m")
    axMW.grid(which='major',
              axis='x',
              linewidth=0.5,
              linestyle='-',
              color='0.75')
    axMW.grid(which='minor',
              axis='x',
              linewidth=0.2,
              linestyle='-',
              color='0.85')
    axMW.grid(which='major',
              axis='y',
              linewidth=0.5,
              linestyle='-',
              color='0.75')
    axMW.grid(which='minor',
              axis='y',
              linewidth=0.2,
              linestyle='-',
              color='0.85')
    axMW.xaxis.set_major_formatter(mpl.ticker.FormatStrFormatter("%d"))
    axMW.yaxis.set_major_formatter(mpl.ticker.FormatStrFormatter("%.2g"))
    axMW.xaxis.set_minor_locator(mpl.ticker.AutoMinorLocator())
    axMW.yaxis.set_minor_locator(mpl.ticker.AutoMinorLocator())
    axMW.grid(True)
    plt.show()
Exemple #13
0
 def test_U(self):
     weight = xraylib.AtomicWeight(92)
     self.assertAlmostEqual(weight, 238.070)
Exemple #14
0
    def xoppy_calc_mlayer(self):

        # copy the variable locally, so no more use of self.
        MODE = self.MODE
        SCAN = self.SCAN
        F12_FLAG = self.F12_FLAG
        SUBSTRATE = self.SUBSTRATE
        ODD_MATERIAL = self.ODD_MATERIAL
        EVEN_MATERIAL = self.EVEN_MATERIAL
        ENERGY = self.ENERGY
        THETA = self.THETA
        SCAN_STEP = self.SCAN_STEP
        NPOINTS = self.NPOINTS
        ODD_THICKNESS = self.ODD_THICKNESS
        EVEN_THICKNESS = self.EVEN_THICKNESS
        NLAYERS = self.NLAYERS
        FILE = self.FILE

        for file in ["mlayer.inp", "mlayer.par", "mlayer.f12"]:
            try:
                os.remove(os.path.join(locations.home_bin_run(), file))
            except:
                pass

        #
        # write input file for Fortran mlayer: mlayer.inp
        #
        f = open('mlayer.inp', 'w')

        if SCAN == 0 and MODE == 0: a0 = 1
        if SCAN == 1 and MODE == 0: a0 = 2
        if SCAN == 0 and MODE == 1: a0 = 3
        if SCAN == 1 and MODE == 1: a0 = 4

        f.write("%d \n" % a0)
        f.write("N\n")

        f.write("%g\n" % (codata.h * codata.c / codata.e * 1e10 / ENERGY))
        f.write("%g\n" % THETA)

        #
        if SCAN == 0:
            f.write("%g\n" % SCAN_STEP)

        a2 = codata.h * codata.c / codata.e * 1e10 / ENERGY
        a3 = codata.h * codata.c / codata.e * 1e10 / (ENERGY + SCAN_STEP)
        a4 = a3 - a2

        if SCAN != 0:
            f.write("%g\n" % a4)

        #
        f.write("%d\n" % NPOINTS)

        if MODE == 0:
            f.write("%d\n" % NLAYERS)

        if MODE == 0:
            if a0 != 5:
                f.write("%g  %g  \n" % (ODD_THICKNESS, EVEN_THICKNESS))
            else:
                for i in range(NLAYERS):
                    f.write("%g  %g  \n" % (ODD_THICKNESS, EVEN_THICKNESS))

        if MODE != 0:
            f1 = open(FILE, 'r')
            a5 = f1.read()
            f1.close()

        if MODE != 0:
            print("Number of layers in %s file is %d " % (FILE, NLAYERS))
            f.write("%d\n" % NLAYERS)
            f.write(a5)

        f.write("mlayer.par\n")
        f.write("mlayer.dat\n")

        f.write("6\n")

        f.close()
        print('File written to disk: mlayer.inp')

        #
        # create f12 file
        #

        if F12_FLAG == 0:
            energy = numpy.arange(0, 500)
            elefactor = numpy.log10(10000.0 / 30.0) / 300.0
            energy = 10.0 * 10**(energy * elefactor)

            f12_s = f1f2_calc(SUBSTRATE, energy)
            f12_e = f1f2_calc(EVEN_MATERIAL, energy)
            f12_o = f1f2_calc(ODD_MATERIAL, energy)

            f = open("mlayer.f12", 'w')
            f.write(
                '; File created by xoppy for materials [substrate=%s,even=%s,odd=%s]: \n'
                % (SUBSTRATE, EVEN_MATERIAL, ODD_MATERIAL))
            f.write('; Atomic masses: \n')
            f.write(
                "%g %g %g \n" %
                (xraylib.AtomicWeight(xraylib.SymbolToAtomicNumber(SUBSTRATE)),
                 xraylib.AtomicWeight(
                     xraylib.SymbolToAtomicNumber(EVEN_MATERIAL)),
                 xraylib.AtomicWeight(
                     xraylib.SymbolToAtomicNumber(ODD_MATERIAL))))
            f.write('; Densities: \n')
            f.write("%g %g %g \n" %
                    (xraylib.ElementDensity(
                        xraylib.SymbolToAtomicNumber(SUBSTRATE)),
                     xraylib.ElementDensity(
                         xraylib.SymbolToAtomicNumber(EVEN_MATERIAL)),
                     xraylib.ElementDensity(
                         xraylib.SymbolToAtomicNumber(ODD_MATERIAL))))
            f.write('; Number of energy points: \n')

            f.write("%d\n" % (energy.size))
            f.write(
                '; For each energy point, energy[eV], f1[substrate], f2[substrate], f1[even], f2[even], f1[odd], f2[odd]: \n'
            )
            for i in range(energy.size):
                f.write("%g %g %g %g %g %g %g \n" %
                        (energy[i], f12_s[0, i], f12_s[1, i], f12_e[0, i],
                         f12_e[1, i], f12_o[0, i], f12_o[1, i]))

            f.close()

            print('File written to disk: mlayer.f12')

        #
        # run external program mlayer
        #

        if platform.system() == "Windows":
            command = os.path.join(locations.home_bin(),
                                   'mlayer.exe < mlayer.inp')
        else:
            command = "'" + os.path.join(locations.home_bin(),
                                         'mlayer') + "' < mlayer.inp"
        print("Running command '%s' in directory: %s " %
              (command, locations.home_bin_run()))
        print("\n--------------------------------------------------------\n")
        os.system(command)
        print("\n--------------------------------------------------------\n")

        #send exchange
        calculated_data = DataExchangeObject(
            "XOPPY", self.get_data_exchange_widget_name())

        try:
            if SCAN == 0:
                calculated_data.add_content("xoppy_data",
                                            numpy.loadtxt("mlayer.dat"))
                calculated_data.add_content("plot_x_col", 0)
                calculated_data.add_content("plot_y_col", 3)
            elif SCAN == 1:  # internal scan is in wavelength. Add a column with energy
                aa = numpy.loadtxt("mlayer.dat")
                photon_energy = (codata.h * codata.c / codata.e * 1e10) / aa[:,
                                                                             0]
                bb = numpy.zeros((aa.shape[0], 1 + aa.shape[1]))
                bb[:, 0] = photon_energy
                bb[:, 1:] = aa
                calculated_data.add_content("xoppy_data", bb)
                calculated_data.add_content("plot_x_col", 0)
                calculated_data.add_content("plot_y_col", 4)

            calculated_data.add_content("units_to_degrees", 1.0)
        except:
            pass
        try:
            info = "ML %s(%3.2f A):%s(%3.2f A) %d pairs; E=%5.3f eV" % (
                ODD_MATERIAL, ODD_THICKNESS, EVEN_MATERIAL, EVEN_THICKNESS,
                NLAYERS, ENERGY)
            calculated_data.add_content("info", info)
        except:
            pass

        return calculated_data
Exemple #15
0
def calcTemperatureFactor(temperature,
                          crystal='Si',
                          debyeTemperature=644.92,
                          millerIndex=[1, 1, 1],
                          atomicMass=28.09,
                          dSpacing=3.1354162886330583):
    """
    Calculates the (Debye) temperature factor for single crystals.
    
    Parameters
    ----------
    temperature : float 
        Crystal temperature in Kelvin (positive number).
    crystal : str 
        Crystal single-element symbol (e.g. Si, Ge, ...).   
    debyeTemperature : float 
        Debye temperature of the crystal material in Kelvin.    
    millerIndex : array-like (1D), optional
        Miller indexes of the crystal orientation. For use with xraylib only.
    atomicMass : float, optional. 
        Atomic mass of the crystal element (amu unit). if atomicMass == 0, get from xraylib.
    dSpacing : float, optional. 
        dSpacing in Angstroms, given the crystal and millerIndex . if dSpacing == 0, get from xraylib.
        
    Returns:
    --------
    temperatureFactor : float
    
    Examples:
    ---------
        ### using xraylib:
            
        >>> calcTemperatureFactor(80, crystal='Si', millerIndex=[3,1,1], debyeTemperature=644.92, dSpacing=0, atomicMass=0)
        0.983851994268226
        
        
        ### forcing it to use given dSpacing and atomicMass:
        
        >>> calcTemperatureFactor(80, crystal='Si', millerIndex=[1,1,1], debyeTemperature=644.92, atomicMass=28.09, dSpacing=3.1354163)
        0.9955698950510736
    
    References:
    -----------
    
    [1]: A. Freund, Nucl. Instrum. and Meth. 213 (1983) 495-501
    
    [2]: M. Sanchez del Rio and R. J. Dejus, "Status of XOP: an x-ray optics software toolkit", 
         SPIE proc. vol. 5536 (2004) pp.171-174
        

    """
    def debyeFunc(x):
        return x / (np.exp(-x) - 1)

    def debyePhi(y):
        from scipy.integrate import quad
        integral = quad(lambda x: debyeFunc(x), 0, y)[0]
        return (1 / y) * integral

    planck = 6.62607015e-34  # codata.Planck
    Kb = 1.380649e-23  # codata.Boltzmann
    atomicMassTokg = 1.6605390666e-27  # codata.atomic_mass

    try:
        import xraylib
        h, k, l = millerIndex
        crystalDict = xraylib.Crystal_GetCrystal(crystal)
        if (dSpacing == 0):
            dSpacing = xraylib.Crystal_dSpacing(crystalDict, h, k, l)
        if (atomicMass == 0):
            atomicMass = xraylib.AtomicWeight(
                xraylib.SymbolToAtomicNumber(crystal))

    except:
        print(
            "xraylib not available. Please give dSpacing and atomicMass manually."
        )
        if ((dSpacing == 0) or (atomicMass == 0)):
            return np.nan

    atomicMass *= atomicMassTokg  # converting to [kg]
    dSpacing *= 1e-10  # converting to [m]

    x = debyeTemperature / (-1 * temperature)  # invert temperature sign (!!!)

    B0 = (3 * planck**2) / (2 * Kb * debyeTemperature * atomicMass)

    BT = 4 * B0 * debyePhi(x) / x

    ratio = 1 / (2 * dSpacing)

    M = (B0 + BT) * ratio**2

    temperatureFactor = np.exp(-M)

    return temperatureFactor
Exemple #16
0
def xoppy_calc_xraylib_widget(FUNCTION=0,ELEMENT=26,ELEMENTORCOMPOUND="FeSO4",COMPOUND="Ca5(PO4)3",TRANSITION_IUPAC_OR_SIEGBAHN=1,\
                              TRANSITION_IUPAC_TO=0,TRANSITION_IUPAC_FROM=0,TRANSITION_SIEGBAHN=0,SHELL=0,ENERGY=10.0):

    functions = [
        '0 Fluorescence line energy', '1 Absorption edge energy',
        '2 Atomic weight', '3 Elemental density',
        '4 Total absorption cross section', '5 Photoionization cross section',
        '6 Partial photoionization cross section',
        '7 Rayleigh scattering cross section',
        '8 Compton scattering cross section', '9 Klein-Nishina cross section',
        '10 Mass energy-absorption cross section',
        '11 Differential unpolarized Klein-Nishina cross section',
        '12 Differential unpolarized Thomson cross section',
        '13 Differential unpolarized Rayleigh cross section',
        '14 Differential unpolarized Compton cross section',
        '15 Differential polarized Klein-Nishina cross section',
        '16 Differential polarized Thomson cross section',
        '17 Differential polarized Rayleigh cross section',
        '18 Differential polarized Compton cross section',
        '19 Atomic form factor', '20 Incoherent scattering function',
        '21 Momentum transfer function',
        '22 Coster-Kronig transition probability', '23 Fluorescence yield',
        '24 Jump factor', '25 Radiative transition probability',
        '26 Energy after Compton scattering',
        '27 Anomalous scattering factor &phi;&prime;',
        '28 Anomalous scattering factor &phi;&Prime;',
        '29 Electronic configuration',
        '30 X-ray fluorescence production cross section (with full cascade)',
        '31 X-ray fluorescence production cross section (with radiative cascade)',
        '32 X-ray fluorescence production cross section (with non-radiative cascade)',
        '33 X-ray fluorescence production cross section (without cascade)',
        '34 Atomic level width', '35 Auger yield', '36 Auger rate',
        '37 Refractive index', '38 Compton broadening profile',
        '39 Partial Compton broadening profile',
        '40 List of NIST catalog compounds',
        '41 Get composition of NIST catalog compound',
        '42 List of X-ray emitting radionuclides',
        '43 Get excitation profile of X-ray emitting radionuclide',
        '44 Compoundparser'
    ]

    print("\nInside xoppy_calc_xraylib with FUNCTION = %s. " %
          (functions[FUNCTION]))

    if FUNCTION == 0:
        if TRANSITION_IUPAC_OR_SIEGBAHN == 0:
            lines = [
                'K', 'L1', 'L2', 'L3', 'M1', 'M2', 'M3', 'M4', 'M5', 'N1',
                'N2', 'N3', 'N4', 'N5', 'N6', 'N7', 'O1', 'O2', 'O3', 'O4',
                'O5', 'O6', 'O7', 'P1', 'P2', 'P3', 'P4', 'P5', 'Q1', 'Q2',
                'Q3'
            ]
            line = lines[TRANSITION_IUPAC_TO] + lines[
                TRANSITION_IUPAC_FROM] + "_LINE"
            command = "result = xraylib.LineEnergy(%d,xraylib.%s)" % (ELEMENT,
                                                                      line)
            print("executing command: ", command)
            line = getattr(xraylib, line)
            result = xraylib.LineEnergy(ELEMENT, line)
            print("result: %f keV" % (result))
        if TRANSITION_IUPAC_OR_SIEGBAHN == 1:
            lines = [
                'KA1_LINE', 'KA2_LINE', 'KB1_LINE', 'KB2_LINE', 'KB3_LINE',
                'KB4_LINE', 'KB5_LINE', 'LA1_LINE', 'LA2_LINE', 'LB1_LINE',
                'LB2_LINE', 'LB3_LINE', 'LB4_LINE', 'LB5_LINE', 'LB6_LINE',
                'LB7_LINE', 'LB9_LINE', 'LB10_LINE', 'LB15_LINE', 'LB17_LINE',
                'LG1_LINE', 'LG2_LINE', 'LG3_LINE', 'LG4_LINE', 'LG5_LINE',
                'LG6_LINE', 'LG8_LINE', 'LE_LINE', 'LL_LINE', 'LS_LINE',
                'LT_LINE', 'LU_LINE', 'LV_LINE'
            ]
            line = lines[TRANSITION_SIEGBAHN]
            command = "result = xraylib.LineEnergy(%d,xraylib.%s)" % (ELEMENT,
                                                                      line)
            print("executing command: ", command)
            line = getattr(xraylib, line)
            result = xraylib.LineEnergy(ELEMENT, line)
            print("result: %f keV" % (result))
        if TRANSITION_IUPAC_OR_SIEGBAHN == 2:
            lines = [
                'K', 'L1', 'L2', 'L3', 'M1', 'M2', 'M3', 'M4', 'M5', 'N1',
                'N2', 'N3', 'N4', 'N5', 'N6', 'N7', 'O1', 'O2', 'O3', 'O4',
                'O5', 'O6', 'O7', 'P1', 'P2', 'P3', 'P4', 'P5', 'Q1', 'Q2',
                'Q3'
            ]
            for i1, l1 in enumerate(lines):
                for i2, l2 in enumerate(lines):
                    if i1 != i2:
                        line = l1 + l2 + "_LINE"

                        try:
                            line = getattr(xraylib, line)
                            result = xraylib.LineEnergy(ELEMENT, line)
                        except:
                            pass
                        else:
                            if result != 0.0:
                                print("%s%s  %f   keV" % (l1, l2, result))
    elif FUNCTION == 1:
        shells = [
            'All shells', 'K_SHELL', 'L1_SHELL', 'L2_SHELL', 'L3_SHELL',
            'M1_SHELL', 'M2_SHELL', 'M3_SHELL', 'M4_SHELL', 'M5_SHELL',
            'N1_SHELL', 'N2_SHELL', 'N3_SHELL', 'N4_SHELL', 'N5_SHELL',
            'N6_SHELL', 'N7_SHELL', 'O1_SHELL', 'O2_SHELL', 'O3_SHELL',
            'O4_SHELL', 'O5_SHELL', 'O6_SHELL', 'O7_SHELL', 'P1_SHELL',
            'P2_SHELL', 'P3_SHELL', 'P4_SHELL', 'P5_SHELL', 'Q1_SHELL',
            'Q2_SHELL', 'Q3_SHELL'
        ]
        if SHELL == 0:  #"all"
            for i, myshell in enumerate(shells):
                if i >= 1:
                    # command = "result = xraylib.EdgeEnergy(%d,xraylib.%s)"%(ELEMENT,myshell)
                    # print("executing command: ",command)
                    shell_index = getattr(xraylib, myshell)
                    try:
                        result = xraylib.EdgeEnergy(ELEMENT, shell_index)
                    except:
                        pass
                    else:
                        if result != 0.0:
                            print("%s  %f   keV" % (myshell, result))
                        else:
                            print("No result")
        else:
            shell_index = getattr(xraylib, shells[SHELL])
            try:
                command = "result = xraylib.EdgeEnergy(%d,xraylib.%s)" % (
                    ELEMENT, shells[SHELL])
                print("executing command: ", command)
                result = xraylib.EdgeEnergy(ELEMENT, shell_index)
            except:
                pass
            else:
                if result != 0.0:
                    print("Z=%d %s : %f   keV" %
                          (ELEMENT, shells[SHELL], result))
                else:
                    print("No result")
    elif FUNCTION == 2:
        result = xraylib.AtomicWeight(ELEMENT)
        if result != 0.0:
            print("Atomic weight for Z=%d : %f  g/mol" % (ELEMENT, result))
    elif FUNCTION == 3:
        result = xraylib.ElementDensity(ELEMENT)
        if result != 0.0:
            print("Element density for Z=%d : %f  g/cm3" % (ELEMENT, result))
        else:
            print("No result")
    elif FUNCTION == 4:
        command = "result = xraylib.CS_Total_CP('%s',%f)" % (ELEMENTORCOMPOUND,
                                                             ENERGY)
        print("executing command: ", command)
        result = xraylib.CS_Total_CP(ELEMENTORCOMPOUND, ENERGY)
        if result != 0.0:
            print("Total absorption cross section: %f  g/cm3" % (result))
        else:
            print("No result")
    elif FUNCTION == 5:
        command = "result = xraylib.CS_Photo_CP('%s',%f)" % (ELEMENTORCOMPOUND,
                                                             ENERGY)
        print("executing command: ", command)
        result = xraylib.CS_Photo_CP(ELEMENTORCOMPOUND, ENERGY)
        if result != 0.0:
            print("Photoionization cross section: %f  g/cm3" % (result))
        else:
            print("No result")
    elif FUNCTION == 6:
        shells = [
            'All shells', 'K_SHELL', 'L1_SHELL', 'L2_SHELL', 'L3_SHELL',
            'M1_SHELL', 'M2_SHELL', 'M3_SHELL', 'M4_SHELL', 'M5_SHELL',
            'N1_SHELL', 'N2_SHELL', 'N3_SHELL', 'N4_SHELL', 'N5_SHELL',
            'N6_SHELL', 'N7_SHELL', 'O1_SHELL', 'O2_SHELL', 'O3_SHELL',
            'O4_SHELL', 'O5_SHELL', 'O6_SHELL', 'O7_SHELL', 'P1_SHELL',
            'P2_SHELL', 'P3_SHELL', 'P4_SHELL', 'P5_SHELL', 'Q1_SHELL',
            'Q2_SHELL', 'Q3_SHELL'
        ]
        if SHELL == 0:  #"all"
            for index in range(1, len(shells)):
                shell_index = getattr(xraylib, shells[index])
                try:
                    command = "result = xraylib.xraylib.CS_Photo_Partial('%d',xraylib.%s,%f)" % (
                        ELEMENT, shells[index], ENERGY)
                    print("executing command: ", command)
                    result = xraylib.CS_Photo_Partial(ELEMENT, shell_index,
                                                      ENERGY)
                except:
                    pass
                else:
                    if result != 0.0:
                        print("Z=%d, %s at E=%f keV: %f   cm2/g" %
                              (ELEMENT, shells[index], ENERGY, result))
                    else:
                        print("No result")
        else:
            shell_index = getattr(xraylib, shells[SHELL])
            try:
                command = "result = xraylib.xraylib.CS_Photo_Partial('%d',xraylib.%s,%f)" % (
                    ELEMENT, shells[SHELL], ENERGY)
                print("executing command: ", command)
                result = xraylib.CS_Photo_Partial(ELEMENT, shell_index, ENERGY)
            except:
                pass
            else:
                if result != 0.0:
                    print("Z=%d, %s at E=%f keV: %f   cm2/g" %
                          (ELEMENT, shells[SHELL], ENERGY, result))
                else:
                    print("No result")
    elif FUNCTION == 7:
        command = "result = xraylib.CS_Rayl_CP('%s',%f)" % (ELEMENTORCOMPOUND,
                                                            ENERGY)
        print("executing command: ", command)
        result = xraylib.CS_Rayl_CP(ELEMENTORCOMPOUND, ENERGY)
        if result != 0.0: print("Rayleigh cross section: %f  cm2/g" % (result))
        else: print("No result")
    elif FUNCTION == 8:
        command = "result = xraylib.CS_Compt_CP('%s',%f)" % (ELEMENTORCOMPOUND,
                                                             ENERGY)
        print("executing command: ", command)
        result = xraylib.CS_Compt_CP(ELEMENTORCOMPOUND, ENERGY)
        if result != 0.0: print("Compton cross section: %f  cm2/g" % (result))
        else: print("No result")
    elif FUNCTION == 9:
        command = "result = xraylib.CS_KN(%f)" % (ENERGY)
        print("executing command: ", command)
        result = xraylib.CS_KN(ENERGY)
        if result != 0.0:
            print("Klein Nishina cross section: %f  cm2/g" % (result))
        else:
            print("No result")
    elif FUNCTION == 10:
        command = "result = xraylib.CS_Energy_CP('%s',%f)" % (
            ELEMENTORCOMPOUND, ENERGY)
        print("executing command: ", command)
        result = xraylib.CS_Energy_CP(ELEMENTORCOMPOUND, ENERGY)
        if result != 0.0:
            print("Mass-energy absorption cross section: %f  cm2/g" % (result))
        else:
            print("No result")
    else:
        print("\n#### NOT YET IMPLEMENTED ####")
Exemple #17
0
def atomicWeight(element,Z):
    z = elementDB[element]["Z"]
    return xraylib.AtomicWeight(z)
Exemple #18
0
 def test_Fe(self):
     weight = xraylib.AtomicWeight(26)
     self.assertAlmostEqual(weight, 55.850)
def ele_weight(atomicNumber):
    W = xl.AtomicWeight(atomicNumber)
    return W
Exemple #20
0
    def test_refractiveindex(self):
        density = float(2.328)
        c = compoundfromformula.CompoundFromFormula("Si", density, name="silicon")
        energy = np.asarray([5, 10], dtype=float)
        Z = 14

        # Xraylib (TODO: n_im sign is wrong!)
        n_re0 = np.asarray(
            [xraylib.Refractive_Index_Re("Si", e, density) for e in energy]
        )
        n_im0 = -np.asarray(
            [xraylib.Refractive_Index_Im("Si", e, density) for e in energy]
        )

        # Exactly like Xraylib (TODO: CS_Total -> CS_Photo_Total)
        delta = (
            density
            * 4.15179082788e-4
            * (Z + np.asarray([xraylib.Fi(Z, e) for e in energy]))
            / xraylib.AtomicWeight(Z)
            / energy ** 2
        )
        beta = (
            np.asarray([xraylib.CS_Total(Z, e) for e in energy])
            * density
            * 9.8663479e-9
            / energy
        )
        n_re1 = 1 - delta
        n_im1 = -beta

        np.testing.assert_allclose(n_re0, n_re1)
        np.testing.assert_allclose(n_im0, n_im1)

        # Im: Kissel
        n_im1b = (
            -np.asarray([xraylib.CS_Total_Kissel(Z, e) for e in energy])
            * density
            * 9.8663479e-9
            / energy
        )

        # Im: Kissel with pint
        n_im1d = (
            ureg.Quantity(c.mass_att_coeff(energy), "cm^2/g")
            * ureg.Quantity(c.density, "g/cm^3")
            * ureg.Quantity(energy, "keV").to("cm", "spectroscopy")
            / (4 * np.pi)
        )
        n_im1d = -n_im1d.to("dimensionless").magnitude

        r = n_im1b / n_im1d
        np.testing.assert_allclose(r, r[0])

        # Im: other formula
        n_im1c = (
            density
            * 4.15179082788e-4
            * (np.asarray([xraylib.Fii(Z, e) for e in energy]))
            / xraylib.AtomicWeight(Z)
            / energy ** 2
        )

        # Spectrocrunch
        n_re2 = c.refractive_index_real(energy)
        n_im2 = c.refractive_index_imag(energy)

        np.testing.assert_allclose(n_re2, n_re0)
        np.testing.assert_allclose(n_im2, n_im1c, rtol=1e-6)