示例#1
0
def get_element_atomic_number(element_str):
    r"""
    A wrapper to ``SymbolToAtomicNumber`` function from ``xraylib``.
    Returns atomic number for the sybmolic element name (e.g. ``C`` or ``Fe``).

    Parameters
    ----------

    element_str: str
        sybmolic representation of an element

    Returns
    -------

    Atomic number of the element ``element_str``. If element is invalid, then
    the function returns 0.

    """
    if LooseVersion(xraylib.__version__) < LooseVersion("4.0.0"):
        xraylib.SetErrorMessages(0)  # Turn off error messages from ``xraylib``

    try:
        val = xraylib.SymbolToAtomicNumber(element_str)
    except ValueError:
        # Imitate the behavior of xraylib 3
        val = 0
    return val
示例#2
0
def parse_compound_formula(compound_formula):
    r"""
    Parses the chemical formula of a compound and returns the dictionary,
    which contains element name, atomic number, number of atoms and mass fraction
    in the compound.

    Parameters
    ----------

    compound_formula: str
        chemical formula of the compound in the form ``FeO2``, ``CO2`` or ``Fe``.
        Element names must start with capital letter.

    Returns
    -------

        dictionary of dictionaries, data on each element in the compound: key -
        sybolic element name, value - a dictionary that contains ``AtomicNumber``,
        ``nAtoms`` and ``massFraction`` of the element. The elements are sorted
        in the order of growing atomic number.

    Raises
    ------

        RuntimeError is raised if compound formula cannot be parsed
    """

    if LooseVersion(xraylib.__version__) < LooseVersion("4.0.0"):
        xraylib.SetErrorMessages(
            0)  # This is supposed to stop XRayLib from printing
        #                              internal error messages, but it doesn't work

    try:
        compound_data = xraylib.CompoundParser(compound_formula)
    except (SystemError, ValueError):
        msg = f"Invalid chemical formula '{compound_formula}' is passed, parsing failed"
        raise RuntimeError(msg)

    # Now create more manageable structure
    compound_dict = {}
    for e_an, e_mf, e_na in zip(compound_data["Elements"],
                                compound_data["massFractions"],
                                compound_data["nAtoms"]):
        e_name = xraylib.AtomicNumberToSymbol(e_an)
        compound_dict[e_name] = {
            "AtomicNumber": e_an,
            "nAtoms": e_na,
            "massFraction": e_mf
        }

    return compound_dict
示例#3
0
#!/usr/bin/env python3

import urllib.request
from io import StringIO
import lxml.etree as ET
import re
import xraylib as xrl

xrl.SetErrorMessages(0)

lbl_url = "http://nucleardata.nuclear.lu.se/toi/nuclide.asp?iZA="

nuclide_codes = sorted(("260055", "940238", "960244", "480109", "530125",
                        "950241", "640153", "270057", "560133", "550137"))

with open("../../src/xraylib-radionuclides-internal.h",
          "w") as output_int, open("../../include/xraylib-radionuclides.h",
                                   "w") as output_header:

    header_begin = '''/*
Copyright (c) 2014-2018, Tom Schoonjans
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Tom Schoonjans ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Tom Schoonjans BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
示例#4
0
                                                       **kwargs)


try:
    import xraylib
except ImportError:
    logger.warning('Xraylib is not installed on your machine. ' +
                   XraylibNotInstalledError.message_post)
    xraylib = None

if xraylib is None:
    # do nothing, for now
    pass
else:
    xraylib.XRayInit()
    xraylib.SetErrorMessages(0)

    line_list = [
        xraylib.KA1_LINE, xraylib.KA2_LINE, xraylib.KA3_LINE, xraylib.KB1_LINE,
        xraylib.KB2_LINE, xraylib.KB3_LINE, xraylib.KB4_LINE, xraylib.KB5_LINE,
        xraylib.LA1_LINE, xraylib.LA2_LINE, xraylib.LB1_LINE, xraylib.LB2_LINE,
        xraylib.LB3_LINE, xraylib.LB4_LINE, xraylib.LB5_LINE, xraylib.LG1_LINE,
        xraylib.LG2_LINE, xraylib.LG3_LINE, xraylib.LG4_LINE, xraylib.LL_LINE,
        xraylib.LE_LINE, xraylib.MA1_LINE, xraylib.MA2_LINE, xraylib.MB_LINE,
        xraylib.MG_LINE
    ]

    shell_list = [
        xraylib.K_SHELL, xraylib.L1_SHELL, xraylib.L2_SHELL, xraylib.L3_SHELL,
        xraylib.M1_SHELL, xraylib.M2_SHELL, xraylib.M3_SHELL, xraylib.M4_SHELL,
        xraylib.M5_SHELL, xraylib.N1_SHELL, xraylib.N2_SHELL, xraylib.N3_SHELL,
示例#5
0
def ABSORB(Beam_Theta, Detector_Theta, Beam_Energy, t):

    import xraylib

    xraylib.XRayInit()
    xraylib.SetErrorMessages(0)

    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

    def Density(Material):  # send a string of the compound of interest
        if Material == 'ZnO':
            return 5.6  #g/cm3
        elif Material == 'CIGS':
            return 5.75  #g/cm3
        elif Material == 'ITO':
            return 7.14  #g/cm3
        elif Material == 'CdS':
            return 4.826  #g/cm3
        elif Material == 'Kapton':  # http://physics.nist.gov/cgi-bin/Star/compos.pl?matno=179
            return 1.42  #g/cm3
        elif Material == 'SiN':
            return 3.44  #g/cm3
        if Material == 'Mo':
            return 10.2  #g/cm3

    def GetLayerInfo(
        Layer
    ):  #send in a string to get typical layer thickness and dictionary of composition
        um_to_cm = 10**-4

        if Layer == 'ZnO':
            mat = {'Element': ['Zn', 'O'], 'MolFrac': [1, 1]}
            t = 0.2 * um_to_cm
            return mat, t
        elif Layer == 'CdS':
            mat = {'Element': ['Cd', 'S'], 'MolFrac': [1, 1]}
            t = 0.05 * um_to_cm
            return mat, t
        elif Layer == 'Kapton':
            mat = {
                'Element': ['H', 'C', 'N', 'O'],
                'MolFrac': [0.026362, 0.691133, 0.073270, 0.209235]
            }  # http://physics.nist.gov/cgi-bin/Star/compos.pl?matno=179
            t = 26.6 * um_to_cm  #measured using profilometer
            return mat, t
        elif Layer == 'ITO':
            mat = {
                'Element': ['In', 'Sn', 'O'],
                'MolFrac': [1.8, 0.1, 2.9]
            }  #90% In2O3 #10% SnO2
            t = 0.15 * um_to_cm
            return mat, t
        elif Layer == 'Mo':
            mat = {'Element': ['Mo'], 'MolFrac': [1]}
            t = 0.7 * um_to_cm
            return mat, t

    def GetFluorescenceEnergy(
        Element, Beam
    ):  # send in the element and the beam energy to get the Excited Fluorescence Energy
        #this will return the highest energy fluorescence photon capable of being excited by the beam
        Z = xraylib.SymbolToAtomicNumber(Element)
        F = xraylib.LineEnergy(Z, xraylib.KA1_LINE)
        if xraylib.EdgeEnergy(Z, xraylib.K_SHELL) > Beam:
            F = xraylib.LineEnergy(Z, xraylib.LA1_LINE)
            if xraylib.EdgeEnergy(Z, xraylib.L1_SHELL) > Beam:
                F = xraylib.LineEnergy(Z, xraylib.LB1_LINE)
                if xraylib.EdgeEnergy(Z, xraylib.L2_SHELL) > Beam:
                    F = xraylib.LineEnergy(Z, xraylib.LB1_LINE)
                    if xraylib.EdgeEnergy(Z, xraylib.L3_SHELL) > Beam:
                        F = xraylib.LineEnergy(Z, xraylib.LG1_LINE)
                        if xraylib.EdgeEnergy(Z, xraylib.M1_SHELL) > Beam:
                            F = xraylib.LineEnergy(Z, xraylib.MA1_LINE)
        return F

    def GetIIO(Layer, Energy):
        ROI, t = GetLayerInfo(Layer)
        return np.exp(-Density(Layer) * GetMaterialMu(Energy, ROI) * t)

    #conversion factor
    um_to_cm = 10**-4
    t = t * um_to_cm

    ##Set incident Beam Energy and Detector Geometry
    # Beam_Theta = 90 #degrees
    # Detector_Theta = 47 #degrees
    # Beam_Energy = 10.5 #keV
    # Get Layor of interest information
    L = 'CIGS'
    ROI = {'Element': ['Cu', 'In', 'Ga', 'Se'], 'MolFrac': [0.8, 0.8, 0.2, 2]}
    Elem = ROI['Element']

    # define sublayers thickness and adjust based on measurement geometry
    dt = 0.01 * um_to_cm  # 10 nm stepsizes
    steps = int(t / dt)
    T = np.ones((steps, 1)) * dt
    beam_path = T / np.sin(Beam_Theta * np.pi / 180)
    fluor_path = T / np.sin(Detector_Theta * np.pi / 180)

    # initialize variables to hold correction factors
    iio = [None] * steps
    factors = [None] * len(Elem)
    #print 'For a film thickness of ', t/um_to_cm, 'microns:'
    #loop over sublayers for self attenuation and top layer attenuation
    ti = time()
    for ind, Z in enumerate(Elem):
        for N in range(steps):
            beam_in = -Density(L) * GetMaterialMu(Beam_Energy,
                                                  ROI) * beam_path[0:N]
            beam_out = -Density(L) * GetMaterialMu(
                GetFluorescenceEnergy(Z, Beam_Energy), ROI) * fluor_path[0:N]
            iio[N] = np.exp(np.sum(beam_in + beam_out))
        factors[ind] = np.sum(iio) / N * GetIIO(
            'Kapton', Beam_Energy) * GetIIO(
                'Kapton', GetFluorescenceEnergy(Z, Beam_Energy))
        #print 'The absorption of ', Z, 'in', L,'at beam energy', Beam_Energy,'is', round(factors[ind]*100,2)
    #print 'Calculation Time = ', round(time()-ti,2),'s for ', steps, 'iterations on ', ind+1,' elements'
    return factors