Ejemplo n.º 1
0
 def test_bad_type(self):
     with self.assertRaises(TypeError):
         xraylib.AtomicNumberToSymbol("26")
     with self.assertRaises(TypeError):
         xraylib.AtomicNumberToSymbol("Fe")
     with self.assertRaises(TypeError):
         xraylib.AtomicNumberToSymbol(None)
Ejemplo n.º 2
0
 def el_select(self):
     Z = self.el_cb.currentIndex()
     if Z > 0:
         self.nist_cb.setCurrentIndex(0)
         self.cp_le.setText("")
         if self.name == "bet": self.chkbox_luxelht.setChecked(False)
         self.mat = xrl.CompoundParser(xrl.AtomicNumberToSymbol(Z))
         self.mat['name'] = xrl.AtomicNumberToSymbol(Z)
         self.apply_mat_thickness()
         self.mat['density'] = xrl.ElementDensity(Z)
         self.mat_dens_le.setText(str(self.mat['density']))
         self.apply_mat_density()
     else:
         self.mat = {}
Ejemplo n.º 3
0
 def _update_line_table_by_radionuclide(self):
     if len(self.rads)==0:
         sys.stderr.write('Warning: update_line_table_by_radionulide, rads has no member\n')
         #self.line_table.setRowCount(0)# reset rows
         return
     for i,rad in enumerate(self.rads):
         name=rad['name']
         Z=rad['Z']
         elSource=xrl.AtomicNumberToSymbol(Z)
         Z_xray=rad['Z_xray']
         elXray=xrl.AtomicNumberToSymbol(Z_xray)
         nXrays=rad['nXrays']
         nGammas=rad['nGammas']
         XrayLines=list(rad['XrayLines'])
         XrayLineTypes=[self.IUPACmac[self.allLINES.index(xl)].split('_')[0] for xl in XrayLines]
         XrayEnergies=np.array([line_wrap.get_lineenergy(Z_xray,line) for line in XrayLines])
         XrayWidths=np.array([line_wrap.get_linewidth(Z_xray,linetype) for linetype in XrayLineTypes])*1e3# eV
         XrayIntensities=np.array(list(rad['XrayIntensities']))
         GammaEnergies=np.array(list(rad['GammaEnergies']))
         GammaIntensities=np.array(list(rad['GammaIntensities']))
         # Xray
         for lt,ene,gamma,norm in zip(XrayLineTypes,XrayEnergies,XrayWidths,XrayIntensities):
             if ene>0. and gamma>0. and norm>0.:
                 row=self.line_table.rowCount()
                 self.line_table.insertRow(row)
                 chk = QCheckBox(parent=self.line_table)
                 chk.setChecked(True)
                 chk.clicked.connect(self._line_table_chkChanged)
                 self.line_table.setCellWidget(row, 0, chk)
                 self.line_table.setItem(row,1, QTableWidgetItem(elXray))
                 self.line_table.setItem(row,2, QTableWidgetItem(lt))
                 self.line_table.setItem(row,3, QTableWidgetItem("%.5f"%(ene)))
                 self.line_table.setItem(row,4, QTableWidgetItem("%.5f"%(gamma)))
                 self.line_table.setItem(row,5, QTableWidgetItem("%.5e"%(norm)))
                 self.line_table.setItem(row,6, QTableWidgetItem("%s %d"%(self.radtab.RADIONUCL_STR,i+1)))
         # Gamma-ray
         for ene,norm in zip(GammaEnergies,GammaIntensities):
             if ene>0. and norm>0.:
                 row=self.line_table.rowCount()
                 self.line_table.insertRow(row)
                 chk = QCheckBox(parent=self.line_table)
                 chk.setChecked(True)
                 chk.clicked.connect(self._line_table_chkChanged)
                 self.line_table.setCellWidget(row, 0, chk)
                 self.line_table.setItem(row,1, QTableWidgetItem(name))
                 self.line_table.setItem(row,2, QTableWidgetItem("Gamma"))
                 self.line_table.setItem(row,3, QTableWidgetItem("%.5f"%(ene)))
                 self.line_table.setItem(row,4, QTableWidgetItem("%.5f"%(0.001)))
                 self.line_table.setItem(row,5, QTableWidgetItem("%.5e"%(norm)))
                 self.line_table.setItem(row,6, QTableWidgetItem("%s %d"%(self.radtab.RADIONUCL_STR,i+1)))
Ejemplo n.º 4
0
 def __init__(self, parent=None):
     super(QtBaseClass, self).__init__()
     self.setupUi(self)
     self.edge_energy.setDisabled(True)
     self.elements.activated[str].connect(self.onActivated)
     self.edge.activated[str].connect(self.onChanged)
     self.xafs1_units.activated[str].connect(self.Units1)
     self.xafs2_units.activated[str].connect(self.Units2)
     self.xafs3_units.activated[str].connect(self.Units3)
     y = []
     for i in range(22, 47):
         y = np.append(y, xraylib.AtomicNumberToSymbol(i))
     for i in range(51, 103):
         y = np.append(y, xraylib.AtomicNumberToSymbol(i))
     for item in range(len(y)):
         self.elements.addItem(y[item])
Ejemplo n.º 5
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
Ejemplo n.º 6
0
 def update_mat_table(self):
     self.apply_mat_thickness()
     self.apply_mat_density()
     if "name" not in [*self.mat.keys()]:
         self.mat_table.setRowCount(2)
         self.mat_table.setItem(0, 0, QTableWidgetItem("thickness (cm)"))
         self.mat_table.setItem(
             0, 1, QTableWidgetItem(str(self.mat['thickness'])))
         self.mat_table.setItem(1, 0, QTableWidgetItem("density (g/cm3)"))
         self.mat_table.setItem(1, 1,
                                QTableWidgetItem(str(self.mat['density'])))
         return
     rows = [*self.mat.keys()]
     vals = [*self.mat.values()]
     self.mat_table.setRowCount(len(rows))
     for i, row in enumerate(rows):
         self.mat_table.setItem(i, 0, QTableWidgetItem(row))
         if row == 'Elements':
             zl = [xrl.AtomicNumberToSymbol(z) for z in self.mat[row]]
             zl = ','.join(zl)
             self.mat_table.setItem(
                 i, 1,
                 QTableWidgetItem(str(self.mat[row]) + "=(" + zl + ")"))
         elif row == 'massFractions':
             frs = ["%.3e" % fr for fr in self.mat[row]]
             frs = ','.join(frs)
             self.mat_table.setItem(i, 1, QTableWidgetItem("(" + frs + ")"))
         else:
             self.mat_table.setItem(i, 1,
                                    QTableWidgetItem(str(self.mat[row])))
Ejemplo n.º 7
0
Archivo: util.py Proyecto: mdw771/xecat
def parser(compounds):

    comp = xraylib.CompoundParser(compounds)
    stoic_allowed = range(10)
    stoic_allowed = map(str, stoic_allowed)
    stoic_allowed.append('.')
    _compounds = list(compounds)
    elements = comp['Elements']
    stoic = []
    for i in elements:
        symb = xraylib.AtomicNumberToSymbol(i)
        ind = compounds.find(symb) + len(symb)
        if ind >= len(_compounds):
            stoic.append(1.0)
        else:
            if _compounds[ind] not in stoic_allowed:
                stoic.append(1.0)
            else:
                temp = []
                while _compounds[ind] in stoic_allowed:
                    temp.append(_compounds[ind])
                    ind += 1
                    if ind >= len(_compounds):
                        break
                temp = ''.join(temp)
                stoic.append(float(temp))
    mw = np.sum(
        np.asarray(stoic) * np.asarray(map(xraylib.AtomicWeight, elements)))

    return elements, stoic, mw
Ejemplo n.º 8
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))
Ejemplo n.º 9
0
def absorptionEdge(element, edge=None):
    if type(element) is str:
        element = xl.SymbolToAtomicNumber(element)
    shells = ["K", "L1", "L2", "L3", "M1", "M2", "M3", "M4", "M5"]
    if edge is not None:
        shell_ind = shells.index(edge)
        return xl.EdgeEnergy(element, shell_ind)
    else:
        shell_inds = range(8)
        print("Absorption edges %s" % xl.AtomicNumberToSymbol(element))
        for shell_ind in shell_inds:
            print("  " + shells[shell_ind].ljust(3) + " = %7.1f eV" %
                  (xl.EdgeEnergy(element, shell_ind) * 1000))
Ejemplo n.º 10
0
    def _update_fluor_cv_by_radionuclide(self):
        if len(self.rads)==0:
            sys.stderr.write('Warning: update_fluor_cv_by_radionulide, rads has no member\n')
            #self.line_table.setRowCount(0)# reset rows
            return
        #self.ax_fl.clear()
        trans_all,trans_each=self._transmission()
        phabs_all,phabs_each=self._photoel()
        radtimesec=self.rad_duration# sec
        solidangle=self.detector_solidangle
        resolution=self.detector_resolution
    
        for i,rad in enumerate(self.rads):
            activitytoday=rad['activitytoday']
            name=rad['name']
            Z_xray=rad['Z_xray']
            elXray=xrl.AtomicNumberToSymbol(Z_xray)
            nXrays=rad['nXrays']
            nGammas=rad['nGammas']
            XrayLines=list(rad['XrayLines'])
            XrayLineTypes=[self.IUPACmac[self.allLINES.index(xl)].split('_')[0] for xl in XrayLines]
            XrayEnergies=np.array([line_wrap.get_lineenergy(Z_xray,line) for line in XrayLines])
            XrayWidths=np.array([line_wrap.get_linewidth(Z_xray,linetype) for linetype in XrayLineTypes])*1e3# eV
            XrayIntensities=np.array(list(rad['XrayIntensities']))
            GammaEnergies=np.array(list(rad['GammaEnergies']))
            GammaIntensities=np.array(list(rad['GammaIntensities']))
            
            # Xray
            specX=np.zeros_like(self.enes_keV,dtype=np.float64)
            for lt,ene,gamma,norm in zip(XrayLineTypes,XrayEnergies,XrayWidths,XrayIntensities):
                if ene>0. and gamma>0. and norm>0.:
                    if elXray+lt in self.not_draw_lines: continue
                    specX += activitytoday * radtimesec * solidangle * norm * trans_all * phabs_all * voigt(self.enes_keV*1e3,ene*1e3,gamma/2.,resolution/sigma_from_fwhm)
                    
            # Gamma-ray
            specG=np.zeros_like(self.enes_keV,dtype=np.float64)
            for ene,norm in zip(GammaEnergies,GammaIntensities):
                if ene>0. and norm>0.:
                    if name+"Gamma" in self.not_draw_lines: continue
                    specG += activitytoday * solidangle * norm * trans_all * phabs_all * voigt(self.enes_keV*1e3,ene*1e3,1.0/2.,resolution/sigma_from_fwhm)

            self.flout+=specX
            self.flout+=specG
            self.ax_fl.plot(self.enes_keV,specX,linestyle='-',marker='',label=elXray)
            self.ax_fl.plot(self.enes_keV,specG,linestyle='-',marker='',label=name)
            self.ax_fl.legend(loc='upper right',fontsize=8)
            self.ax_fl.set_xlabel("Energy (keV)")
            self.ax_fl.set_xlim(self.er_low,self.er_high)
            if self.er_low<=0.1: self.ax_fl.set_xlim(0.,self.er_high)
            self.ax_fl.set_ylabel("Normalized intensity")
            self.ax_fl.figure.canvas.draw()
Ejemplo n.º 11
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
Ejemplo n.º 12
0
def absorptionEdge(element,edge=None):
    if type(element) is str:
        element = xl.SymbolToAtomicNumber(element)
    shells = ['K','L1','L2','L3','M1','M2','M3','M4','M5']
    if edge is not None:
        shell_ind = shells.index(edge)
        return xl.EdgeEnergy(element,shell_ind)
    else:
        shell_inds = range(8)
        print('Absorption edges %s'%xl.AtomicNumberToSymbol(element))
        for shell_ind in shell_inds:
            print('  '\
                  +shells[shell_ind].ljust(3)\
                  +' = %7.1f eV'%(xl.EdgeEnergy(element,shell_ind)*1000))
Ejemplo n.º 13
0
 def update_line_table(self):
     if "name" not in [*self.tgt.keys()]:
         sys.stderr.write('Warning: update_line_table, tgt has no name\n')
         self.line_table.setRowCount(0)# reset rows
         if len(self.rads)!=0: self._update_line_table_by_radionuclide()
         return
     #print("update_line_table")
     name=self.tgt['name']
     zs=[*self.tgt['Elements']]
     lines=[xrl.__getattribute__('%s_LINE'%(x)) for x in self.LINES]
     linetypes=np.array([l for l in self.LINES for z in zs])
     sgblinetypes=np.array([l for l in self.SGBLINES for z in zs])
     els=np.array([xrl.AtomicNumberToSymbol(z) for i in range(len(lines)) for z in zs])
     el_inds=np.array([i for k in range(len(lines)) for i,z in enumerate(zs)])
     enes=np.array([line_wrap.get_lineenergy(z,line) for line in lines for z in zs])
     gammas=np.array([line_wrap.get_linewidth(z,lt) for lt in self.LINES for z in zs])*1e3
     intens=np.array([self._xrf_intensity(z,line) for line in lines for z in zs])
     # remove non-valid lines
     indx=np.where((enes!=0.) & (intens!=0.))[0]
     els=els[indx]
     el_inds=el_inds[indx]
     enes=enes[indx]
     gammas=gammas[indx]
     intens=intens[indx]
     linetypes=linetypes[indx]
     sgblinetypes=sgblinetypes[indx]
     # fill tabel
     self.line_table.setRowCount(0)# reset rows
     self.line_table.setRowCount(len(els))
     for i,(el,lt,sgblt,ene,gamma,norm) in enumerate(zip(els,linetypes,sgblinetypes,enes,gammas,intens)):
         if ene>0. and gamma>0. and norm>0.:
             chk = QCheckBox(parent=self.line_table)
             chk.setChecked(True)
             chk.clicked.connect(self._line_table_chkChanged)
             self.line_table.setCellWidget(i, 0, chk)
             self.line_table.setItem(i,1, QTableWidgetItem(el))
             self.line_table.setItem(i,2, QTableWidgetItem(sgblt))
             self.line_table.setItem(i,3, QTableWidgetItem("%.5f"%(ene)))
             self.line_table.setItem(i,4, QTableWidgetItem("%.5f"%(gamma)))
             self.line_table.setItem(i,5, QTableWidgetItem("%.5e"%(norm)))
             self.line_table.setItem(i,6, QTableWidgetItem(name))
     if len(self.rads)!=0: self._update_line_table_by_radionuclide()
Ejemplo n.º 14
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
Ejemplo n.º 15
0
 def test_bad_symbol(self):
     with self.assertRaises(ValueError):
         xraylib.AtomicNumberToSymbol(-2)
     with self.assertRaises(ValueError):
         xraylib.AtomicNumberToSymbol(108)
Ejemplo n.º 16
0
 def test_Fe(self):
     self.assertEqual(xraylib.AtomicNumberToSymbol(26), 'Fe')
Ejemplo n.º 17
0
print("M1->M5 Coster-Kronig transition probability for Au : {}".format(
    xraylib.CosKronTransProb(79, xraylib.FM15_TRANS)))
print("L1->L3 Coster-Kronig transition probability for Fe : {}".format(
    xraylib.CosKronTransProb(26, xraylib.FL13_TRANS)))
print("Au Ma1 XRF production cs at 10.0 keV (Kissel): {}".format(
    xraylib.CS_FluorLine_Kissel(79, xraylib.MA1_LINE, 10.0)))
print("Au Mb XRF production cs at 10.0 keV (Kissel): {}".format(
    xraylib.CS_FluorLine_Kissel(79, xraylib.MB_LINE, 10.0)))
print("Au Mg XRF production cs at 10.0 keV (Kissel): {}".format(
    xraylib.CS_FluorLine_Kissel(79, xraylib.MG_LINE, 10.0)))
print("K atomic level width for Fe: {}".format(
    xraylib.AtomicLevelWidth(26, xraylib.K_SHELL)))
print("Bi L2-M5M5 Auger non-radiative rate: {}".format(
    xraylib.AugerRate(86, xraylib.L2_M5M5_AUGER)))
print("Bi L3 Auger yield: {}".format(xraylib.AugerYield(86, xraylib.L3_SHELL)))
symbol = xraylib.AtomicNumberToSymbol(26)
print("Symbol of element 26 is: {}".format(symbol))
print("Number of element Fe is: {}".format(xraylib.SymbolToAtomicNumber("Fe")))
Z = np.array([26])
symbol = xraylib.AtomicNumberToSymbol(Z[0])
print("Symbol of element 26 is: {}".format(symbol))
print("Pb Malpha XRF production cs at 20.0 keV with cascade effect: {}".format(
    xraylib.CS_FluorLine_Kissel(82, xraylib.MA1_LINE, 20.0)))
print(
    "Pb Malpha XRF production cs at 20.0 keV with radiative cascade effect: {}"
    .format(
        xraylib.CS_FluorLine_Kissel_Radiative_Cascade(82, xraylib.MA1_LINE,
                                                      20.0)))
print(
    "Pb Malpha XRF production cs at 20.0 keV with non-radiative cascade effect: {}"
    .format(
Ejemplo n.º 18
0
import xraylib

#Generating the Element Tab
file = open("elements.txt", "w")
file.write('Element\tEdge\tEdge Energy\n\n')

for i in range(0, 103):
    edge = 'K'
    y = xraylib.AtomicNumberToSymbol(i)
    if (xraylib.EdgeEnergy(i, xraylib.K_SHELL) >= 4.5):
        if (xraylib.EdgeEnergy(i, xraylib.K_SHELL) <= 25):
            file.write(
                y + '\t' + edge + '\t' +
                str(round(xraylib.EdgeEnergy(i, xraylib.K_SHELL) * 1000, 1)) +
                '\n')

    if (xraylib.EdgeEnergy(i, xraylib.L1_SHELL) >= 4.5):
        if (xraylib.EdgeEnergy(i, xraylib.L1_SHELL) <= 25):
            file.write(
                y + '\t' + 'L1' + '\t' +
                str(round(xraylib.EdgeEnergy(i, xraylib.L1_SHELL) * 1000, 1)) +
                '\n')

    if (xraylib.EdgeEnergy(i, xraylib.L2_SHELL) >= 4.5):
        if (xraylib.EdgeEnergy(i, xraylib.L2_SHELL) <= 25):
            file.write(
                y + '\t' + 'L2' + '\t' +
                str(round(xraylib.EdgeEnergy(i, xraylib.L2_SHELL) * 1000, 1)) +
                '\n')

    if (xraylib.EdgeEnergy(i, xraylib.L3_SHELL) >= 4.5):
Ejemplo n.º 19
0
    def _update_fluor_cv(self):
        #print("update_fluor_cv")
        self.apply_enerangelow()
        if self.er_low<=0.1: self.er_low=0.1
        self.apply_enerangehigh()
        self.apply_enerangestep()
        self.apply_detector_resolution()
        self.apply_detector_solidangle()
        self.enes_keV=np.arange(self.er_low,self.er_high+self.er_low+self.er_step,self.er_step)
        self.flout=np.zeros_like(self.enes_keV)
        self.ax_fl.clear()
        if "name" not in [*self.tgt.keys()]:
            sys.stderr.write('Warning: update_fluor_cv, no target set\n')
            self.ax_fl.plot()
            self.ax_fl.figure.canvas.draw()
            if len(self.rads)!=0:  self._update_fluor_cv_by_radionuclide()
            return
        trans_all,trans_each=self._transmission()
        self.bemtab.add_beam()
        flux=self.bem['beamflux']
        beamtimesec=self.beam_duration# sec
        title=self.tgt['name']
        beamene = self.bem['beamene']
        zs=[*self.tgt['Elements']]
        phabs_all,phabs_each=self._photoel()
        solidangle=self.detector_solidangle
        resolution=self.detector_resolution
        lines=np.array([xrl.__getattribute__('%s_LINE'%(x)) for x in self.LINES])
        linetypes=np.array([l for l in self.LINES for z in zs])
        sgblinetypes=np.array([l for l in self.SGBLINES for z in zs])
        elms=[xrl.AtomicNumberToSymbol(z) for i in range(len(lines)) for z in zs]
        els=np.array([xrl.AtomicNumberToSymbol(z) for i in range(len(lines)) for z in zs])
        el_inds=np.array([i for k in range(len(lines)) for i,z in enumerate(zs)])
        enes=np.array([line_wrap.get_lineenergy(z,line) for line in lines for z in zs])
        gammas=np.array([line_wrap.get_linewidth(z,lt) for lt in self.LINES for z in zs])*1e3# eV
        intens=np.array([self._xrf_intensity(z,line) for line in lines for z in zs])
        # remove non-valid lines
        indx=np.where((enes!=0.) & (intens!=0.))[0]
        els=els[indx]
        el_inds=el_inds[indx]
        enes=enes[indx]
        gammas=gammas[indx]
        intens=intens[indx]
        linetypes=linetypes[indx]
        sgblinetypes=sgblinetypes[indx]
        specs=[np.zeros_like(self.enes_keV,dtype=np.float64) for i in range(len(zs))]
        for i,(el,elind,lt,sgblt,ene,gamma,norm) in enumerate(zip(els,el_inds,linetypes,sgblinetypes,enes,gammas,intens)):
            if ene>0. and gamma>0.:
                if el+sgblt in self.not_draw_lines: continue
                specs[elind] += flux * beamtimesec * solidangle * norm * trans_all * phabs_all * voigt(self.enes_keV*1e3,ene*1e3,gamma/2.,resolution/sigma_from_fwhm)
        cindex={x:i for i,x in enumerate([xrl.AtomicNumberToSymbol(z) for z in zs])}
        for el,spec in zip(elms,specs):
            self.flout+=spec
            self.ax_fl.plot(self.enes_keV,spec,linestyle='-',marker='',color=cm.jet(cindex[el]/len(cindex)),label=el)

        if len(self.rads)!=0:  self._update_fluor_cv_by_radionuclide()
            
        self.ax_fl.legend(loc='upper right',fontsize=8)
        self.ax_fl.set_xlabel("Energy (keV)")
        self.ax_fl.set_xlim(self.er_low,self.er_high)
        if self.er_low<=0.1: self.ax_fl.set_xlim(0.,self.er_high)
        self.ax_fl.set_ylabel("Normalized intensity")
        self.ax_fl.set_title("%s, beam %.3f keV, resol %.1f eV"%(title,beamene,resolution))
        self.ax_fl.figure.canvas.draw()
Ejemplo n.º 20
0
def index():
    form = Xraylib_Request()
    version = xraylib.__version__

    # Populates select fields
    form.function.choices = form.function.choices + cs_tup + dcs_tup
    form.transition.siegbahn.choices = trans_S_tup
    form.shell.choices = shell_tup
    form.nistcomp.choices = nist_tup
    form.rad_nuc.choices = rad_name_tup

    if request.method == 'POST':
        # Get user input
        select_input = request.form.get('function')
        examples = request.form.get('examples')

        notation = request.form.get('transition-notation')
        siegbahn = request.form.get('transition-siegbahn')
        iupac1 = request.form.get('transition-iupac1')
        iupac2 = request.form.get('transition-iupac2')

        ex_shell = request.form.get('augtrans-ex_shell')
        trans_shell = request.form.get('augtrans-trans_shell')
        aug_shell = request.form.get('augtrans-aug_shell')

        cktrans = request.form.get('cktrans')
        nistcomp = request.form.get('nistcomp')
        rad_nuc = request.form.get('rad_nuc')
        shell = request.form.get('shell')

        int_z = request.form['int_z']
        float_q = request.form['float_q']
        comp = request.form['comp']
        int_z_or_comp = request.form['int_z_or_comp']
        energy = request.form['energy']
        theta = request.form['theta']
        phi = request.form['phi']
        density = request.form['density']
        pz = request.form['pz']

        # Turns user input => valid args for calc_output
        trans = iupac1 + iupac2 + '_LINE'
        augtrans = ex_shell + '_' + trans_shell + aug_shell + '_AUGER'

        if select_input == 'AtomicWeight' or select_input == 'ElementDensity':
            if validate_int(int_z) or validate_str(int_z):
                examples = code_example(form.examples.choices, select_input,
                                        int_z)
                output = calc_output(select_input, int_z)
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       output=output,
                                       units=getattr(Request_Units,
                                                     select_input + '_u'),
                                       code_examples=examples)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input == 'FF_Rayl' or select_input == 'SF_Compt':
            if validate_int(
                    int_z) or validate_str(int_z) and validate_float(float_q):
                examples = code_example(form.examples.choices, select_input,
                                        int_z, float_q)
                output = calc_output(select_input, int_z, float_q)
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       output=output,
                                       code_examples=examples)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input == 'AugerRate':
            if validate_int(int_z) or validate_str(int_z):
                examples = code_example(form.examples.choices, select_input,
                                        int_z, augtrans)
                output = calc_output(select_input, int_z, augtrans)
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       output=output,
                                       code_examples=examples)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input == 'LineEnergy' or select_input == 'RadRate':
            if notation == 'IUPAC':
                if validate_int(int_z) or validate_str(int_z):
                    examples = code_example(form.examples.choices,
                                            select_input, int_z, trans)
                    output = calc_output(select_input, int_z, trans)

                    if select_input == 'LineEnergy':
                        return render_template('index.html',
                                               form=form,
                                               version=version,
                                               output=output,
                                               units=Request_Units.Energy_u,
                                               code_examples=examples)
                    else:
                        return render_template('index.html',
                                               form=form,
                                               version=version,
                                               output=output,
                                               code_examples=examples)
                else:
                    return render_template('index.html',
                                           form=form,
                                           version=version,
                                           error=Request_Error.error)

            elif notation == 'Siegbahn':
                if validate_int(int_z) or validate_str(int_z):
                    examples = code_example(form.examples.choices,
                                            select_input, int_z, siegbahn)
                    output = calc_output(select_input, int_z, siegbahn)
                    print(output)

                    if select_input == 'LineEnergy':
                        return render_template('index.html',
                                               form=form,
                                               version=version,
                                               output=output,
                                               units=Request_Units.Energy_u,
                                               code_examples=examples)
                    else:
                        return render_template('index.html',
                                               form=form,
                                               version=version,
                                               output=output,
                                               code_examples=examples)

                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

            elif notation == 'All':
                if validate_int(int_z) or validate_str(int_z):
                    output = all_trans(trans_I_tup, select_input, int_z)

                    if select_input == 'LineEnergy':
                        #needs units
                        #output = dict(out, Line = 'Energies')
                        return render_template('index.html',
                                               form=form,
                                               version=version,
                                               output=output,
                                               units=Request_Units.Energy_u)
                    else:
                        return render_template('index.html',
                                               form=form,
                                               version=version,
                                               output=output)
                else:
                    return render_template('index.html',
                                           form=form,
                                           version=version,
                                           error=Request_Error.error)
            else:
                return render_template('index.html', error=Request_Error.error)

        elif (select_input == 'EdgeEnergy' or select_input == 'JumpFactor'
              or select_input == 'FluorYield' or select_input == 'AugerYield'
              or select_input == 'AtomicLevelWidth'
              or select_input == 'ElectronConfig'):
            if validate_int(int_z) or validate_str(int_z):
                examples = code_example(form.examples.choices, select_input,
                                        int_z, shell)
                output = calc_output(select_input, int_z, shell)
                if select_input == 'EdgeEnergy' or select_input == 'AtomicLevelWidth':
                    return render_template('index.html',
                                           form=form,
                                           version=version,
                                           output=output,
                                           units=Request_Units.Energy_u,
                                           code_examples=examples)
                elif select_input == 'ElectronConfig':
                    return render_template(
                        'index.html',
                        form=form,
                        version=version,
                        output=output,
                        units=Request_Units.ElectronConfig_u,
                        code_examples=examples)
                else:
                    return render_template('index.html',
                                           form=form,
                                           version=version,
                                           output=output,
                                           code_examples=examples)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input == 'CS_Photo_Partial':
            if validate_int(
                    int_z) or validate_str(int_z) and validate_float(energy):
                output = calc_output(select_input, int_z, shell, energy)
                examples = code_example(form.examples.choices, select_input,
                                        int_z, shell, energy)
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       output=output,
                                       units=Request_Units.CS_u,
                                       code_examples=examples)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input == 'CS_KN':
            if validate_float(energy) and energy != '0':
                output = calc_output(select_input, energy)
                examples = code_example(form.examples.choices, select_input,
                                        energy)
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       output=output,
                                       units=Request_Units.CS_u,
                                       code_examples=examples)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input.startswith('CS_FluorLine'):
            if validate_float(energy):
                if notation == 'IUPAC':
                    if validate_int(int_z) or validate_str(int_z):
                        examples = code_example(form.examples.choices,
                                                select_input, int_z, trans,
                                                energy)
                        output = calc_output(select_input, int_z, trans,
                                             energy)
                        return render_template('index.html',
                                               form=form,
                                               version=version,
                                               output=output,
                                               units=Request_Units.CS_u,
                                               code_examples=examples)
                    else:
                        return render_template('index.html',
                                               form=form,
                                               version=version,
                                               error=Request_Error.error)
                elif notation == 'Siegbahn':
                    if validate_int(int_z) or validate_str(int_z):
                        examples = code_example(form.examples.choices,
                                                select_input, int_z, siegbahn,
                                                energy)
                        output = calc_output(select_input, int_z, siegbahn,
                                             energy)
                        return render_template('index.html',
                                               form=form,
                                               version=version,
                                               output=output,
                                               units=Request_Units.CS_u,
                                               code_examples=examples)
                    else:
                        return render_template('index.html',
                                               form=form,
                                               version=version,
                                               error=Request_Error.error)
                elif notation == 'All':
                    if validate_int(int_z) or validate_str(int_z):
                        output = all_trans_xrf(form.transition.iupac.choices,
                                               select_input, int_z, energy)
                        return render_template('index.html',
                                               form=form,
                                               version=version,
                                               output=output,
                                               units=Request_Units.CS_u)
                    else:
                        return render_template('index.html',
                                               form=form,
                                               version=version,
                                               error=Request_Error.error)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input.startswith('CS_'):
            if validate_float(energy) and validate_int(
                    int_z_or_comp) or validate_str(int_z_or_comp):
                examples = code_example(form.examples.choices, select_input,
                                        int_z_or_comp, energy)
                output = calc_output(select_input, int_z_or_comp, energy)
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       output=output,
                                       units=Request_Units.CS_u,
                                       code_examples=examples)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input == 'DCS_Thoms':
            if validate_float(theta):
                output = calc_output(select_input, theta)
                examples = code_example(form.examples.choices, select_input,
                                        theta)
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       output=output,
                                       units=Request_Units.DCS_u,
                                       code_examples=examples)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input == 'DCS_KN' or select_input == 'ComptonEnergy':
            if validate_float(energy, theta):
                output = calc_output(select_input, energy, theta)
                examples = code_example(form.examples.choices, select_input,
                                        energy, theta)
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       output=output,
                                       units=Request_Units.DCS_u,
                                       code_examples=examples)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input.startswith('DCS_'):
            if validate_float(energy, theta) and validate_int(
                    int_z_or_comp) or validate_str(int_z_or_comp):
                output = calc_output(select_input, int_z_or_comp, energy,
                                     theta)
                examples = code_example(form.examples.choices, select_input,
                                        int_z_or_comp, energy, theta)
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       output=output,
                                       units=Request_Units.DCS_u,
                                       code_examples=examples)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input == 'DCSP_KN':
            if validate_float(energy, theta, phi):
                output = calc_output(select_input, energy, theta, phi)
                examples = code_example(form.examples.choices, select_input,
                                        energy, theta, phi)
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       output=output,
                                       units=Request_Units.DCS_u,
                                       code_examples=examples)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input == 'DCSP_Thoms':
            if validate_float(theta, phi):
                output = calc_output(select_input, theta, phi)
                examples = code_example(form.examples.choices, select_input,
                                        theta, phi)
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       output=output,
                                       units=Request_Units.DCS_u,
                                       code_examples=examples)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input.startswith('DCSP_'):
            if validate_float(energy, theta, phi) and validate_int(
                    int_z_or_comp) or validate_str(int_z_or_comp):
                output = calc_output(select_input, int_z_or_comp, energy,
                                     theta, phi)
                examples = code_example(form.examples.choices, select_input,
                                        int_z_or_comp, energy, theta, phi)
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       output=output,
                                       units=Request_Units.DCS_u,
                                       code_examples=examples)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input.startswith('Fi'):
            if validate_int(
                    int_z) or validate_str(int_z) and validate_float(energy):
                output = calc_output(select_input, int_z, energy)
                examples = code_example(form.examples.choices, select_input,
                                        int_z, energy)
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       output=output,
                                       code_examples=examples)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input == 'CosKronTransProb':
            if validate_int(int_z) or validate_str(int_z):
                output = calc_output(select_input, int_z, cktrans)
                examples = code_example(form.examples.choices, select_input,
                                        int_z, cktrans)
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       output=output,
                                       code_examples=examples)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input == 'ComptonProfile':
            if validate_float(pz) and validate_int(int_z) or validate_str(
                    int_z):

                output = calc_output(select_input, int_z, pz)
                examples = code_example(form.examples.choices, select_input,
                                        int_z, pz)
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       output=output,
                                       code_examples=examples)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input == 'ComptonProfile_Partial':
            if validate_float(pz) and validate_int(int_z) or validate_str(
                    int_z):
                output = calc_output(select_input, int_z, shell, pz)
                examples = code_example(form.examples.choices, select_input,
                                        int_z, shell, pz)
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       output=output,
                                       code_examples=examples)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input == 'MomentTransf':
            if validate_float(energy, theta) == True:
                output = calc_output(select_input, energy, theta)
                examples = code_example(form.examples.choices, select_input,
                                        energy, theta)
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       output=output,
                                       code_examples=examples)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input == 'Refractive_Index':

            # Special Case: Refractive_Index input needs to be const char compound
            if validate_float(energy, density) and validate_int(
                    int_z_or_comp) or validate_str(int_z_or_comp):
                try:
                    output = xraylib.Refractive_Index(
                        xraylib.AtomicNumberToSymbol(int(int_z_or_comp),
                                                     float(energy),
                                                     float(density)))
                    examples = code_example(form.examples.choices,
                                            select_input, int_z_or_comp,
                                            energy, density)
                    return render_template('index.html',
                                           form=form,
                                           version=version,
                                           output=output,
                                           code_examples=examples)
                except:
                    output = xraylib.Refractive_Index(int_z_or_comp,
                                                      float(energy),
                                                      float(density))
                    examples = code_example(form.examples.choices,
                                            select_input, int_z_or_comp,
                                            energy, density)
                    return render_template('index.html',
                                           form=form,
                                           version=version,
                                           output=output,
                                           code_examples=examples)
                else:
                    return render_template('index.html',
                                           form=form,
                                           version=version,
                                           error=Request_Error.error)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input == 'CompoundParser':
            # Special Case: CompoundParser input needs to be const char compound
            if validate_str(comp):
                try:
                    out = xraylib.CompoundParser(str(comp))

                    # Format output
                    w_fracts = out['massFractions']
                    w_pers = [str(round(i * 100, 2)) + ' %' for i in w_fracts]
                    z = out['Elements']
                    sym = [
                        '<sub>' + str(i) + '</sub>' +
                        str(xraylib.AtomicNumberToSymbol(i)) for i in z
                    ]
                    mmass = str(out['molarMass']) + ' g mol<sup>-1</sup>'

                    output = {
                        'Elements': sym,
                        'Weight Fraction': w_pers,
                        'Number of Atoms': out['nAtoms'],
                        ' Molar Mass': mmass
                    }
                    examples = code_example(form.examples.choices,
                                            select_input, comp)
                    return render_template('index.html',
                                           form=form,
                                           version=version,
                                           output=output,
                                           code_examples=examples,
                                           units=Request_Units.per_u)
                except:
                    return render_template('index.html',
                                           form=form,
                                           version=version,
                                           error=Request_Error.error)
            else:
                return render_template('index.html',
                                       form=form,
                                       version=version,
                                       error=Request_Error.error)

        elif select_input == 'GetRadioNuclideDataList':
            output = xraylib.GetRadioNuclideDataList()
            output.insert(0, '<b> Radionuclides: </b>')
            output = '<br/>'.join(output)
            examples = code_example(form.examples.choices, select_input)
            return render_template('index.html',
                                   form=form,
                                   version=version,
                                   output=output,
                                   code_examples=examples)

        elif select_input == 'GetRadioNuclideDataByIndex':
            out = calc_output(select_input, rad_nuc)
            print(out)
            # Format output
            line_nos = out['XrayLines']
            x_energy = [xraylib.LineEnergy(out['Z_xray'], i) for i in line_nos]

            output = {
                'X-ray Energies': x_energy,
                'Disintegrations s<sup>-1</sup>': out['XrayIntensities'],
                'Gamma-ray Energy': out['GammaEnergies'],
                'Disintegrations s<sup>-1</sup> ': out['GammaIntensities']
            }
            examples = code_example(form.examples.choices,
                                    'GetRadioNuclideDataByName', rad_nuc)

            return render_template('index.html',
                                   form=form,
                                   version=version,
                                   output=output,
                                   code_examples=examples)

        elif select_input == 'GetCompoundDataNISTList':
            output = xraylib.GetCompoundDataNISTList()
            output.insert(0, '<b> NIST Compounds: </b>')
            output = '<br/>'.join(output)
            examples = code_example(form.examples.choices, select_input)
            return render_template('index.html',
                                   form=form,
                                   version=version,
                                   output=output,
                                   code_examples=examples)

        elif select_input == 'GetCompoundDataNISTByIndex':
            out = calc_output(select_input, nistcomp)

            # Format output
            w_fracts = out['massFractions']
            w_pers = [str(round(i * 100, 2)) + ' %' for i in w_fracts]
            z = out['Elements']
            sym = [
                '<sub>' + str(i) + '</sub>' +
                str(xraylib.AtomicNumberToSymbol(i)) for i in z
            ]
            density = str(out['density']) + ' g cm<sup>-3</sup>'

            output = {
                'Elements': sym,
                'Weight Fraction': w_pers,
                ' Density': density
            }
            examples = code_example(form.examples.choices,
                                    'GetCompoundDataNISTByName', nistcomp)
            return render_template('index.html',
                                   form=form,
                                   version=version,
                                   output=output,
                                   code_examples=examples)

    return render_template('index.html', form=form, version=version)
Ejemplo n.º 21
0
 def test(self):
     for Z in range(1, 108):
         symbol = xraylib.AtomicNumberToSymbol(Z)
         self.assertEqual(xraylib.SymbolToAtomicNumber(symbol), Z)
Ejemplo n.º 22
0
plt.clf()
tx = []
ty = []
tt = []

for n, edge in enumerate(range(5)):
    E = []
    Elements = []
    for el in ElementRange:
        tE = xl.EdgeEnergy(el, edge)
        if tE > np.min(Erange) and tE < np.max(Erange):
            E.append(tE)
            Elements.append(el)
    l = plt.plot(E, Elements, '+', label=edgenames[n])
    for el, tE in zip(Elements, E):
        tx.append(tE)
        ty.append(el)
        tt.append(\
            plt.text(tE,el,xl.AtomicNumberToSymbol(el),\
                     bbox={'pad':0, 'alpha':0},
                     color=l[0].get_color()))

plt.xlim(2, 12)
plt.legend()
plt.xlabel('Photon Energy / keV')
plt.ylabel('Atomic Number')
plt.minorticks_on()
plt.grid(which='both')

plt.show()
Ejemplo n.º 23
0
            xpath_N = "/html/body/center/table/tr[3]/td[2]/center/table[1]/caption/table/tr[2]/th[2]/font/text()"

            nuclideDataSingle = dict()

            Z = tree.xpath(xpath_Z)[0]
            A = tree.xpath(xpath_A)[0]
            N = tree.xpath(xpath_N)[0]
            print("Z: {}".format(Z))
            print("A: {}".format(A))
            print("N: {}".format(N))

            nuclideDataSingle['Z'] = Z
            nuclideDataSingle['A'] = A
            nuclideDataSingle['N'] = N
            nuclideDataSingle['name'] = "{}{}".format(
                A, xrl.AtomicNumberToSymbol(int(Z)))

            ##gamma stuff
            xpath_gamma = "/html/body/center/table/tr[3]/td[2]/center/table[3]/tr[position() >= 4 and position() < count(/html/body/center/table/tr[3]/td[2]/center/table[3]/tr)]"
            gamma_nodes = tree.xpath(xpath_gamma)

            print("gamma nodes number: {}".format(len(gamma_nodes)))

            gamma_energies = []
            gamma_intensities = []

            for node in gamma_nodes:
                try:
                    gamma_intensity = node.xpath("td[2]/text()")[0]
                    gamma_intensity = float(gamma_intensity)
                    gamma_energies.append(
Ejemplo n.º 24
0
 def formula(self):
     import xraylib as xrl
     string = ''
     for z, p in zip(self.Z, self.propotion):
         string += '{}{:.6f}'.format(xrl.AtomicNumberToSymbol(z), p)
     return string
Ejemplo n.º 25
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()
Ejemplo n.º 26
0
    def __init__(self, parent=None, name=""):
        super(MaterialTabWidget, self).__init__()

        self.parent = parent
        self.name = name  # tag
        self.mat = {}  # materials for target, detector, etc
        self.rad = {}  # radionuclide sources
        self.bem = {}  # beam
        # the following table was used for debug...
        self.mat_table = QTableWidget()
        self.mat_table.setRowCount(2)
        self.mat_table.setColumnCount(2)
        mat_header = self.mat_table.horizontalHeader()
        mat_header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
        mat_header.setSectionResizeMode(1, QHeaderView.ResizeToContents)

        # default values
        saddbutton = ""
        sremovebutton = "Remove"
        sresetbutton = "Reset"
        if self.name == 'det' or self.name == 'rad' or self.name == 'bet':
            saddbutton = "Add"
        elif self.name == 'tgt' or self.name == "bem":
            saddbutton = "Set"

        self.TARGET_STR = "Target"
        self.DETECTOR_STR = "Detector"
        self.FILTER_STR = "Filter"
        self.RADIONUCL_STR = "RadioNucl"

        # main layout
        main_layout = QVBoxLayout()

        # add (set), remove, reset
        self.addButton = QPushButton(saddbutton)
        if self.name == 'rad':
            self.addButton.clicked.connect(self.add_radionuclide)
        elif self.name == 'bem':
            self.addButton.clicked.connect(self.add_beam)
        else:
            self.addButton.clicked.connect(self.add_material)
        self.resetButton = QPushButton(sresetbutton)
        self.resetButton.clicked.connect(self.reset_material)
        self.removeButton = QPushButton(sremovebutton)
        self.removeButton.clicked.connect(self.remove_material)
        ly1 = QHBoxLayout()
        ly1.addWidget(self.addButton)
        if self.name == 'bet' or self.name == 'det' or self.name == 'rad':
            ly1.addWidget(self.removeButton)
        ly1.addWidget(self.resetButton)

        # thickness & density
        self.mat_thick_le = QLineEdit()
        self.mat_thick_le.setValidator(QDoubleValidator(0, 1e11, 999))
        self.mat_thick_le.returnPressed.connect(self.apply_mat_thickness)
        self.mat_dens_le = QLineEdit()
        self.mat_dens_le.setValidator(QDoubleValidator(0, 1e11, 999))
        self.mat_dens_le.returnPressed.connect(self.apply_mat_density)
        ly2 = QHBoxLayout()
        ly2.addWidget(QLabel("Thickness (cm)"))
        ly2.addWidget(QLabel("Density (g/cm3)"))
        ly3 = QHBoxLayout()
        ly3.addWidget(self.mat_thick_le)
        ly3.addWidget(self.mat_dens_le)
        # Element
        el_list = [
            "%d: %s" % (i, xrl.AtomicNumberToSymbol(z))
            for i, z in enumerate(np.arange(1, 108, 1, dtype=int))
        ]
        self.el_cb = QComboBox()
        self.el_cb.addItem("None")
        self.el_cb.addItems(el_list)
        self.el_cb.currentIndexChanged.connect(self.el_select)
        # CP
        self.cp_le = QLineEdit()
        self.cp_le.returnPressed.connect(self.apply_mat_cp)
        # NIST CP
        nistcp_list = [
            "%d: %s" % (i, cp)
            for i, cp in enumerate(xrl.GetCompoundDataNISTList())
        ]
        self.nist_cb = QComboBox()
        self.nist_cb.addItem("None")
        self.nist_cb.addItems(nistcp_list)
        self.nist_cb.currentIndexChanged.connect(self.nistcp_select)

        self.bem_beamene_le = QLineEdit()
        self.bem_beamene_le.setValidator(QDoubleValidator(0, 1e11, 999))
        self.bem_beamene_le.returnPressed.connect(self.apply_beamene)
        self.bem_beamene_le.setText("15.")
        self.bem_beamalpha_le = QLineEdit()
        self.bem_beamalpha_le.setValidator(QDoubleValidator(0, 90., 999))
        self.bem_beamalpha_le.returnPressed.connect(self.apply_beamalpha)
        self.bem_beamalpha_le.setText("45.")
        self.bem_beambeta_le = QLineEdit()
        self.bem_beambeta_le.setValidator(QDoubleValidator(0, 90., 999))
        self.bem_beambeta_le.returnPressed.connect(self.apply_beambeta)
        self.bem_beambeta_le.setText("45.")
        self.bem_beamflux_le = QLineEdit()
        self.bem_beamflux_le.setValidator(QDoubleValidator(0, 1e20, 999))
        self.bem_beamflux_le.returnPressed.connect(self.apply_beamflux)
        self.bem_beamflux_le.setText("1e6")  # 1 M/sec
        self.bem_time_le = QLineEdit()  # duration
        self.bem_time_le.setValidator(QDoubleValidator(0, 1e30, 999))
        self.bem_time_le.setText("7200.")  # 2 hours
        self.bem_time_le.returnPressed.connect(self.apply_beam_time)

        self.ra_cb = QComboBox()
        self.ra_cb.addItem("None")
        self.ra_cb.addItems(self.parent.RDNLIST)
        self.ra_cb.currentIndexChanged.connect(self.ra_select)
        self.rad_act_le = QLineEdit()
        self.rad_date_le = QLineEdit()
        self.rad_date_m_le = QLineEdit()
        self.rad_act_m_le = QLineEdit()
        self.rad_act_m_le.setReadOnly(True)
        self.rad_today_le = QLineEdit()
        self.rad_today_le.setReadOnly(True)
        self.rad_hl_le = QLineEdit()
        self.rad_hl_le.setReadOnly(True)
        self.rad_time_le = QLineEdit()  # duration
        self.rad_act_le.setValidator(QDoubleValidator(0, 1e30, 999))
        self.rad_date_le.setValidator(QIntValidator(19000101, 99991231))
        self.rad_date_m_le.setValidator(QIntValidator(19000101, 99991231))
        self.rad_time_le.setValidator(QDoubleValidator(0, 1e30, 999))
        self.rad_act_le.setText("1e6")
        self.rad_date_le.setText("20110311")
        self.rad_date_m_le.setText("20200311")
        self.rad_time_le.setText("3600.")
        self.rad_act_le.returnPressed.connect(self.apply_rad_act)
        self.rad_date_le.returnPressed.connect(self.apply_rad_date)
        self.rad_date_m_le.returnPressed.connect(self.apply_rad_date_measure)
        self.rad_time_le.returnPressed.connect(self.apply_rad_time)

        if self.name == "bem":
            beamw = QWidget()
            #beamw.setObjectName('beamw')
            #beamw_style='QWidget#beamw{border: 1px solid lightgray; border-radius: 2px;}'
            #beamw.setStyleSheet(beamw_style)
            beambox = QVBoxLayout(beamw)
            beambox.setSpacing(0)
            beamew = QWidget()
            ly4 = QHBoxLayout(beamew)
            ly4.addWidget(QLabel("Incident energy (keV):   "))
            ly4.addWidget(self.bem_beamene_le)
            beamfw = QWidget()
            ly7 = QHBoxLayout(beamfw)
            ly7.addWidget(QLabel("Beam flux (photons): "))
            ly7.addWidget(self.bem_beamflux_le)
            beamaw = QWidget()
            ly5 = QHBoxLayout(beamaw)
            ly5.addWidget(QLabel("Incident angle (degree):"))
            ly5.addWidget(self.bem_beamalpha_le)
            beambw = QWidget()
            ly6 = QHBoxLayout(beambw)
            ly6.addWidget(QLabel("Outgoing angle (degree):"))
            ly6.addWidget(self.bem_beambeta_le)
            beambox.addWidget(beamew)
            beambox.addWidget(beamfw)
            beambox.addWidget(beamaw)
            beambox.addWidget(beambw)
            #detiw=QWidget()
            #detiw.setObjectName('detiw')
            #detiw_style='QWidget#detiw{border: 1px solid lightgray; border-radius: 2px;}'
            #detiw.setStyleSheet(detiw_style)
            #detil=QVBoxLayout(detiw)
            btimew = QWidget()
            btimel = QHBoxLayout(btimew)
            btimel.addWidget(QLabel("Beam time (sec):"))
            btimel.addWidget(self.bem_time_le)
            #detil.addWidget(btimew)
            beambox.addWidget(btimew)
            main_layout.addLayout(ly1)
            main_layout.addWidget(beamw)
            #main_layout.addWidget(detiw)

        # RadioNuclide
        elif self.name == "rad":
            # calibrated radioactivity
            radactw = QWidget()
            radactl = QHBoxLayout(radactw)
            radactl.addWidget(QLabel("Activity calib (Bq):"))
            radactl.addWidget(self.rad_act_le)
            # date of calibration
            raddatew = QWidget()
            raddatel = QHBoxLayout(raddatew)
            raddatel.addWidget(QLabel("Date calib (e.g., 20110311): "))
            raddatel.addWidget(self.rad_date_le)
            # half life
            radhlw = QWidget()
            radhll = QHBoxLayout(radhlw)
            radhll.addWidget(QLabel("Half life (days): "))
            radhll.addWidget(self.rad_hl_le)
            # date of measurement
            raddatemw = QWidget()
            raddateml = QHBoxLayout(raddatemw)
            raddateml.addWidget(QLabel("Date measure (e.g., 20200311): "))
            raddateml.addWidget(self.rad_date_m_le)
            #
            radtodayw = QWidget()
            radtodayl = QHBoxLayout(radtodayw)
            radtodayl.addWidget(QLabel("Activity today (Bq): "))
            radtodayl.addWidget(self.rad_today_le)
            # duration time
            radtimew = QWidget()
            radtimel = QHBoxLayout(radtimew)
            radtimel.addWidget(QLabel("Duration time (sec): "))
            radtimel.addWidget(self.rad_time_le)
            main_layout.addLayout(ly1)
            main_layout.addWidget(QLabel("Radionuclide source"))
            main_layout.addWidget(self.ra_cb)
            main_layout.addWidget(radactw)
            main_layout.addWidget(raddatew)
            main_layout.addWidget(radhlw)
            main_layout.addWidget(radtodayw)
            #radiw=QWidget()
            #radiw.setObjectName('radiw')
            #radiw_style='QWidget#radiw{border: 1px solid lightgray; border-radius: 2px;}'
            #radiw.setStyleSheet(radiw_style)
            #radil=QVBoxLayout(radiw)
            #radil.addWidget(radtimew)
            main_layout.addWidget(radtimew)
            #main_layout.addWidget(radiw)

        elif self.name == "bet":  # between materials = filter
            main_layout.addLayout(ly1)
            main_layout.addLayout(ly2)
            main_layout.addLayout(ly3)
            main_layout.addWidget(QLabel("Element"))
            main_layout.addWidget(self.el_cb)
            main_layout.addWidget(QLabel("NIST compound"))
            main_layout.addWidget(self.nist_cb)
            main_layout.addWidget(
                QLabel("Compound parser (e.g., CdTe) press return"))
            main_layout.addWidget(self.cp_le)
            self.chkbox_luxelht = QCheckBox("add LUXEL HT window")
            self.chkbox_luxelht.stateChanged.connect(
                self.chkbox_luxelht_action)
            self.chkbox_luxelht.setChecked(False)
            main_layout.addWidget(self.chkbox_luxelht)

        else:
            main_layout.addLayout(ly1)
            main_layout.addLayout(ly2)
            main_layout.addLayout(ly3)
            main_layout.addWidget(QLabel("Element"))
            main_layout.addWidget(self.el_cb)
            main_layout.addWidget(QLabel("NIST compound"))
            main_layout.addWidget(self.nist_cb)
            main_layout.addWidget(
                QLabel("Compound parser (e.g., CdTe) press return"))
            main_layout.addWidget(self.cp_le)
            #main_layout.addWidget(self.mat_table)

        self.setLayout(main_layout)