def detector_efficiency_convolution( data, spectrum_size, scatt_orders, rivelatore): Z = rivelatore.Detect_Z thickness = rivelatore.Detect_thickness Z_window = rivelatore.Detect_window_Z window_thick = rivelatore.Detect_window_thickness energy_max = rivelatore.energy_max #FILE *file_in,*file_out; i,j,k = 0,0,0 sigma_var = 0 density, density1 = 0, 0 density_air = 0.0012 attenuation = 0 attenuation_window = 0 attenuation_air = 0 energy = 0 air_thickness = rivelatore.AirThick #xrl_error **error; spectrum_temp = np.zeros(spectrum_size, dtype=np.double) spectrum_conv = np.zeros([scatt_orders,spectrum_size], dtype=np.double) k=0 print("Efficiency correction") ######################################################################### #NOTE: No longer performs the convolution PER ORDER. Instead, we sum #all orders and apply it only once ######################################################################### for k in range(scatt_orders): spectrum_temp += data[k,:] ######################################################################### density = xlib.ElementDensity(Z) density1 = xlib.ElementDensity(Z_window) i=0 for i in range(spectrum_size): energy = i*rivelatore.energy_max/rivelatore.MCA_chns print(f"{energy} - Progress {k}: {i}/{spectrum_size}", end="\r") if energy > 0: attenuation = xlib.CS_Total(Z, energy) attenuation_window = xlib.CS_Total(Z_window, energy) attenuation_air = 0.7804 * xlib.CS_Total(7, energy) + 0.20946 * xlib.CS_Total(8, energy) + 0.00934 * xlib.CS_Total(18, energy) spectrum_conv[k][i] = spectrum_temp[i] * (1.0-np.exp(-attenuation*thickness*density)) * np.exp(-attenuation_window * window_thick * density1-attenuation_air * air_thickness*density_air) else: spectrum_conv[k][i] = 0.0 return spectrum_conv
def get_delta(input_parameters, calculation_parameters): density = xraylib.ElementDensity(xraylib.SymbolToAtomicNumber(input_parameters.crl_material)) energy_in_KeV = ShadowPhysics.getEnergyFromWavelength(calculation_parameters.gwavelength*input_parameters.widget.workspace_units_to_m*1e10)/1000 delta = 1-xraylib.Refractive_Index_Re(input_parameters.crl_material, energy_in_KeV, density) return delta
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
def crlRadius(f, E, material='Be', density=None): if density is None: density = xraylib.ElementDensity( xraylib.SymbolToAtomicNumber(material)) #print getElementsName(material),E,density return f * 2. * (1. - xraylib.Refractive_Index_Re( getElementsName(material), E, density))
def GetDensity(material): if material == 'H2C': cpH2C = xrl.GetCompoundDataNISTByName('Polyethylene') density = cpH2C['density'] else: Z = xrl.SymbolToAtomicNumber(material) density = xrl.ElementDensity(Z) return density
def get_delta_beta(cls, shadow_rays, material): beta = numpy.zeros(len(shadow_rays)) delta = numpy.zeros(len(shadow_rays)) density = xraylib.ElementDensity(xraylib.SymbolToAtomicNumber(material)) for i in range(0, len(shadow_rays)): energy_in_KeV = ShadowPhysics.getEnergyFromShadowK(shadow_rays[i, 10])/1000 delta[i] = (1-xraylib.Refractive_Index_Re(material, energy_in_KeV, density)) beta[i] = xraylib.Refractive_Index_Im(material, energy_in_KeV, density) return delta, beta
def getMaterialDensity(cls, material_formula): if material_formula is None: return 0.0 if str(material_formula.strip()) == "": return 0.0 try: compoundData = xraylib.CompoundParser(material_formula) if compoundData["nElements"] == 1: return xraylib.ElementDensity(compoundData["Elements"][0]) else: return 0.0 except: return 0.0
def calculate_efficiency(cls, wavelength, zone_plate_material, zone_plate_thickness): energy_in_KeV = ShadowPhysics.getEnergyFromWavelength(wavelength*10)/1000 density = xraylib.ElementDensity(xraylib.SymbolToAtomicNumber(zone_plate_material)) delta = (1-xraylib.Refractive_Index_Re(zone_plate_material, energy_in_KeV, density)) beta = xraylib.Refractive_Index_Im(zone_plate_material, energy_in_KeV, density) phi = 2*numpy.pi*zone_plate_thickness*delta/wavelength rho = beta/delta efficiency = (1/(numpy.pi**2))*(1 + numpy.exp(-2*rho*phi) - (2*numpy.exp(-rho*phi)*numpy.cos(phi))) max_efficiency = (1/(numpy.pi**2))*(1 + numpy.exp(-2*rho*numpy.pi) + (2*numpy.exp(-rho*numpy.pi))) thickness_max_efficiency = numpy.round(wavelength/(2*delta), 2) return efficiency, max_efficiency, thickness_max_efficiency
def test_attenuator(): # # create preprocessor file # symbol = "Cu" number_of_rays = 10000 cm_or_mm = 0 # 0=using cm, 1=using mm # # run prerefl # density = xraylib.ElementDensity(xraylib.SymbolToAtomicNumber(symbol)) Shadow.ShadowPreprocessorsXraylib.prerefl(interactive=0, SYMBOL=symbol, DENSITY=density, FILE="prerefl.dat", E_MIN=5000.0, E_MAX=15000.0, E_STEP=100.0) # # run SHADOW for a sample of thickness 10 um # if cm_or_mm == 0: beam = run_example_attenuator(user_units_to_cm=1.0, npoint=number_of_rays) else: beam = run_example_attenuator(user_units_to_cm=0.1, npoint=number_of_rays) print("Intensity: %f" % (beam.intensity(nolost=1))) # # check SHADOW results against xraylib attenuation # cs1 = xraylib.CS_Total(xraylib.SymbolToAtomicNumber(symbol), 10.0) # print("xralib Fe cross section [cm^2/g]: %f"%cs1) # print("xralib mu [cm^-1]: %f"%(cs1*density)) sh100 = 100 * beam.intensity(nolost=1) / number_of_rays xrl100 = 100 * numpy.exp(-cs1 * density * 10e-4) print("xralib attenuation [per cent] for 10 um %s at 10 keV: %f" % (symbol, xrl100)) print("Transmission [per cent]: %f" % (sh100)) numpy.testing.assert_almost_equal(sh100, xrl100, 2)
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 = {}
def test_lens(): # # inputs # cm_or_mm = 1 # 0=using cm, 1=using mm use_prerefl = 0 # 0=No, 1=Yes if cm_or_mm == 0: user_units_to_cm = 1.0 title = "Units are cm" elif cm_or_mm == 1: user_units_to_cm = 0.1 title = "Units are mm" else: print("No way...") # # run prerefl # if use_prerefl: import xraylib symbol = "Si" density = xraylib.ElementDensity(xraylib.SymbolToAtomicNumber(symbol)) Shadow.ShadowPreprocessorsXraylib.prerefl(interactive=0, SYMBOL=symbol, DENSITY=density, FILE="prerefl.dat", E_MIN=5000.0, E_MAX=15000.0, E_STEP=100.0) # # run SHADOW # beam = run_example_lens(user_units_to_cm=user_units_to_cm) tkt = Shadow.ShadowTools.plotxy(beam, 3, 6, ref=0, nolost=1, nbins=301, title="Z,Z' " + title) print("Intensity: %f " % tkt["intensity"]) print("Number of rays: %d, number of GOOD rays: %d " % (beam.nrays(nolost=0), beam.nrays(nolost=1)))
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
def calculate_efficiency(mirr=None,angle_file="angle.02",material="Au",gamma_blaze_deg=None,lines_per_mm=300.0): import Shadow beam = Shadow.Beam() beam.load(mirr) angle = numpy.loadtxt(angle_file) alpha_deg = angle[:, 1] beta_deg = -angle[:, 2] wavelength = beam.getshonecol(19) * 1e-10 energy = beam.getshonecol(11) # plot(numpy.arange(alpha_deg.size),alpha_deg, # numpy.arange(alpha_deg.size), -beta_deg, # legend=["alpha","beta"]) # print(">>>",angle.shape) # plot(energy,wavelength) theta_deg = (alpha_deg - beta_deg) / 2 gamma_deg = (alpha_deg + beta_deg) / 2 # plot(energy,alpha*180/numpy.pi, # energy, -beta * 180 / numpy.pi, # energy, (alpha-beta) / 2 * 180 / numpy.pi, # xtitle="energy / eV", ytitle="deg", legend=["alpha","-beta","theta"]) RS = numpy.zeros_like(energy) if gamma_blaze_deg is None: gamma_blaze_deg = gamma_deg.mean() print(">>>> using blaze angle: %f deg " % (gamma_blaze_deg)) # # reflectivity # theta = theta_deg * numpy.pi / 180 method = 1 if method == 0: for i in range(energy.size): rs, rp, runp = reflectivity("Au", numpy.array([energy[i]]), numpy.pi / 2 - theta[i], ) RS[i] = rs[0] else: n2_interp = numpy.zeros(energy.size, complex) for i in range(energy.size): n2_interp[i] = xraylib.Refractive_Index(material, 1e-3 * energy[i], xraylib.ElementDensity(xraylib.SymbolToAtomicNumber(material))) n1 = 1 + 0j # % air k0 = 2 * numpy.pi / wavelength # % calculate the k values k1 = (n2_interp ** 2 - 1 + (sind(90.0 - theta_deg)) ** 2) ** 0.5 # % calculate fresnel coefficients for the 0-1 and 1-2 interfaces r1 = (sind(90.0 - theta_deg) - k1) / (sind(90.0 - theta_deg) + k1) RS = (numpy.abs(r1)) ** 2 plot_scatter(energy, RS, xtitle="energy / eV", ytitle="R(theta)") # # efficiency # C = numpy.cos(numpy.deg2rad(beta_deg)) / numpy.cos(numpy.deg2rad(alpha_deg)) plot_scatter(energy, C) efficiency = RS / C dspacing = 1e-3 / lines_per_mm sf = structure_factor(wavelength, numpy.deg2rad(gamma_blaze_deg), numpy.deg2rad(alpha_deg), numpy.deg2rad(beta_deg), dspacing) efficiency *= sf ** 2 plot_scatter(energy, sf ** 2, xtitle="energy / eV", ytitle="S**2", title="S**2") plot_scatter(energy, efficiency, title="", xtitle="Phonon energy [eV]", ytitle="Efficiency") print("results: ") print("Reflectivity R min: %f, max: %f, average: %f" % (RS.min(), RS.max(), RS.mean())) print("C min: %f, max: %f, average: %f" % (C.min(), C.max(), C.mean())) print("sf**2 min: %f, max: %f, average: %f" % ((sf ** 2).min(), (sf ** 2).max(), (sf ** 2).mean())) print("Efficiency min: %f, max: %f, average: %f" % (efficiency.min(), efficiency.max(), efficiency.mean())) return efficiency
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
def xoppy_calc_xf1f2(self): MAT_FLAG = self.MAT_FLAG DESCRIPTOR = self.DESCRIPTOR density = self.DENSITY CALCULATE = self.CALCULATE GRID = self.GRID GRIDSTART = self.GRIDSTART GRIDEND = self.GRIDEND GRIDN = self.GRIDN THETAGRID = self.THETAGRID ROUGH = self.ROUGH THETA1 = self.THETA1 THETA2 = self.THETA2 THETAN = self.THETAN if MAT_FLAG == 0: # element descriptor = DESCRIPTOR density = xraylib.ElementDensity( xraylib.SymbolToAtomicNumber(DESCRIPTOR)) elif MAT_FLAG == 1: # formula descriptor = DESCRIPTOR if GRID == 0: # standard energy grid energy = numpy.arange(0, 500) elefactor = numpy.log10(10000.0 / 30.0) / 300.0 energy = 10.0 * 10**(energy * elefactor) elif GRID == 1: # user energy grid if GRIDN == 1: energy = numpy.array([GRIDSTART]) else: energy = numpy.linspace(GRIDSTART, GRIDEND, GRIDN) elif GRID == 2: # single energy point energy = numpy.array([GRIDSTART]) if THETAGRID == 0: theta = numpy.array([THETA1]) else: theta = numpy.linspace(THETA1, THETA2, THETAN) CALCULATE_items = [ 'f1', 'f2', 'delta', 'beta', 'mu [cm^-1]', 'mu [cm^2/g]', 'Cross Section [barn]', 'reflectivity-s', 'reflectivity-p', 'reflectivity-unpol', 'delta/beta ' ] out = numpy.zeros((energy.size, theta.size)) for i, itheta in enumerate(theta): if MAT_FLAG == 0: # element tmp = f1f2_calc(descriptor, energy, 1e-3 * itheta, F=1 + CALCULATE, rough=ROUGH, density=density) out[:, i] = tmp else: tmp = f1f2_calc_mix(descriptor, energy, 1e-3 * itheta, F=1 + CALCULATE, rough=ROUGH, density=density) out[:, i] = tmp if ((energy.size == 1) and (theta.size == 1)): info = "** Single value calculation E=%g eV, theta=%g mrad, Result(F=%d)=%g " % ( energy[0], theta[0], 1 + CALCULATE, out[0, 0]) labels = ["Energy [eV]", CALCULATE_items[CALCULATE]] tmp = numpy.vstack((energy, out[:, 0])) print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", energy.shape, out.shape, tmp.shape) out_dict = { "application": "xoppy", "name": "xf12", "info": info, "data": tmp, "labels": labels } elif theta.size == 1: tmp = numpy.vstack((energy, out[:, 0])) labels = ["Energy [eV]", CALCULATE_items[CALCULATE]] out_dict = { "application": "xoppy", "name": "xf12", "data": tmp, "labels": labels } elif energy.size == 1: tmp = numpy.vstack((theta, out[0, :])) labels = ["Theta [mrad]", CALCULATE_items[CALCULATE]] out_dict = { "application": "xoppy", "name": "xf12", "data": tmp, "labels": labels } else: labels = [r"energy[eV]", r"theta [mrad]"] out_dict = { "application": "xoppy", "name": "xf12", "data2D": out, "dataX": energy, "dataY": theta, "labels": labels } # # # if "info" in out_dict.keys(): print(out_dict["info"]) #send exchange calculated_data = DataExchangeObject( "XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content("xoppy_data", out_dict["data"].T) calculated_data.add_content("plot_x_col", 0) calculated_data.add_content("plot_y_col", -1) except: pass try: calculated_data.add_content("labels", out_dict["labels"]) except: pass try: calculated_data.add_content("info", out_dict["info"]) except: pass try: calculated_data.add_content("data2D", out_dict["data2D"]) calculated_data.add_content("dataX", out_dict["dataX"]) calculated_data.add_content("dataY", out_dict["dataY"]) except: pass if self.DUMP_TO_FILE: with open(self.FILE_NAME, "w") as file: try: file.write("#F %s\n" % self.FILE_NAME) file.write("\n#S 1 xoppy f1f2 results\n") print("data shape", out_dict["data"].shape) print("labels: ", out_dict["labels"]) file.write("#N 2\n") file.write("#L %s %s\n" % (out_dict["labels"][0], out_dict["labels"][1])) out = out_dict["data"] for j in range(out.shape[1]): file.write( ("%19.12e " * out.shape[0] + "\n") % tuple(out[i, j] for i in range(out.shape[0]))) file.close() print("File written to disk: %s \n" % self.FILE_NAME) except: raise Exception( "CrossSec: The data could not be dumped onto the specified file!\n" ) return calculated_data
# * 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. """Example of using various xraylib functionality in python.""" import xraylib import math import numpy as np xraylib.XRayInit() xraylib.SetErrorMessages(0) print("Example of python program using xraylib") print("xraylib version: {}".format(xraylib.__version__)) print("Density of pure Al : {} g/cm3".format(xraylib.ElementDensity(13))) print("Ca K-alpha Fluorescence Line Energy: {}".format( xraylib.LineEnergy(20, xraylib.KA_LINE))) print("Fe partial photoionization cs of L3 at 6.0 keV: {}".format( xraylib.CS_Photo_Partial(26, xraylib.L3_SHELL, 6.0))) print("Zr L1 edge energy: {}".format(xraylib.EdgeEnergy(40, xraylib.L1_SHELL))) print("Pb Lalpha XRF production cs at 20.0 keV (jump approx): {}".format( xraylib.CS_FluorLine(82, xraylib.LA_LINE, 20.0))) print("Pb Lalpha XRF production cs at 20.0 keV (Kissel): {}".format( xraylib.CS_FluorLine_Kissel(82, xraylib.LA_LINE, 20.0))) print("Bi M1N2 radiative rate: {}".format( xraylib.RadRate(83, xraylib.M1N2_LINE))) print("U M3O3 Fluorescence Line Energy: {}".format( xraylib.LineEnergy(92, xraylib.M3O3_LINE))) print("Ca(HCO3)2 Rayleigh cs at 10.0 keV: {}".format( xraylib.CS_Rayl_CP("Ca(HCO3)2", 10.0)))
def ele_dens(atomicNumber): D = xl.ElementDensity(atomicNumber) return D
#file_name = None file_name = "/Users/labx/Desktop/AnnaB/efficiencies.asc" try: if file_name is None: file_name = oasysgui.selectFileFromDialog(None, None, "Open ASC file") congruence.checkFile(file_name) data = numpy.loadtxt(file_name, skiprows=1) energies = data[:, 0] angles = numpy.radians((180 - data[:, 3]) / 2) reflectivities = numpy.zeros((energies.size, angles.size)) density = xraylib.ElementDensity(xraylib.SymbolToAtomicNumber("Au")) for i, itheta in enumerate(angles): reflectivities[:, i] = f1f2_calc("Au", energies, itheta, F=10, rough=0.0, density=density) angles = numpy.degrees(angles) file_out = open(os.path.dirname(file_name) + "/reflectivities.out", mode="w") rows = ["Energy (eV) Theta (deg) Reflectivity\n"] for i in range(0, energies.size):
@author: %(username)s """ # %%% imports cell import numpy as np import matplotlib.pyplot as plt import xraylib import wavepy.utils as wpu wpu._mpl_settings_4_nice_graphs() # %% Lens material = 'Be' density = xraylib.ElementDensity(4) curv_radius = 100e-6 nlenses = 1 nsurfaces = 1 * nlenses title = 'Berylium' + ' Lens, Curv. Radius ' + \ ' {:.1f} um, {:d} curved surfaces'.format(curv_radius*1e6, nsurfaces) phenergy = np.arange(7e3, 9e3, 100) # %% Obtain delta refractive index delta = phenergy * 0.0 for i in range(delta.shape[0]):
def initialize_from_bilayer_stack( cls, material_S="Si", density_S=None, roughness_S=0.0, material_E="B4C", density_E=None, roughness_E=0.0, material_O="Ru", density_O=None, roughness_O=0.0, bilayer_pairs=70, bilayer_thickness=33.1, bilayer_gamma=0.483, ): npair = int(bilayer_pairs) #define variables thick = [] #[0e0]*npair gamma1 = [] #[0e0]*npair mlroughness1 = [] #[0e0]*npair mlroughness2 = [] #[0e0]*npair for i in range(npair): thick.append(bilayer_thickness) # float(BILAYER_THICKNESS) gamma1.append(bilayer_gamma) # float(BILAYER_GAMMA) mlroughness1.append(roughness_E) # float(ROUGHNESS_E) mlroughness2.append(roughness_O) # float(ROUGHNESS_O) pre_mlayer_dict = {} pre_mlayer_dict["np"] = bilayer_pairs #! [email protected] 2012-06-07 Nevot-Croce ML roughness model implemented. #! By convention, starting from the version that includes ML roughness #! we set NPAR negative, in order to assure compatibility with old #! versions. If NPAR<0, roughness data are read, if NPAR>0 no roughness. pre_mlayer_dict["npair"] = -npair pre_mlayer_dict["thick"] = numpy.array(thick) pre_mlayer_dict["gamma1"] = numpy.array(gamma1) pre_mlayer_dict["mlroughness1"] = numpy.array(mlroughness1) pre_mlayer_dict["mlroughness2"] = numpy.array(mlroughness2) #These keys are not in the original pre_mlayer_dict pre_mlayer_dict["material1"] = material_E pre_mlayer_dict["material2"] = material_O pre_mlayer_dict["materialS"] = material_S pre_mlayer_dict["roughnessS"] = roughness_S pre_mlayer_dict["density1"] = density_E pre_mlayer_dict["density2"] = density_O pre_mlayer_dict["densityS"] = density_S if pre_mlayer_dict["densityS"] is None: try: pre_mlayer_dict["densityS"] = xraylib.ElementDensity( xraylib.SymbolToAtomicNumber(pre_mlayer_dict["materialS"])) print("Using density for substrate (%s): %f" % (pre_mlayer_dict["materialS"], pre_mlayer_dict["densityS"])) except: raise Exception("Failed to load density for material: %s" % (pre_mlayer_dict["material1"])) if pre_mlayer_dict["density1"] is None: try: pre_mlayer_dict["density1"] = xraylib.ElementDensity( xraylib.SymbolToAtomicNumber(pre_mlayer_dict["material1"])) print("Using density for layer 1 (even) (%s): %f" % (pre_mlayer_dict["material1"], pre_mlayer_dict["density1"])) except: raise Exception("Failed to load density for material: %s" % (pre_mlayer_dict["material1"])) if pre_mlayer_dict["density2"] is None: try: pre_mlayer_dict["density2"] = xraylib.ElementDensity( xraylib.SymbolToAtomicNumber(pre_mlayer_dict["material2"])) print("Using density for layer 2 (odd) (%s): %f" % (pre_mlayer_dict["material2"], pre_mlayer_dict["density2"])) except: raise Exception("Failed to load density for material: %s" % (pre_mlayer_dict["material2"])) if isinstance(pre_mlayer_dict["densityS"], str): pre_mlayer_dict["densityS"] = float(pre_mlayer_dict["densityS"]) if isinstance(pre_mlayer_dict["density1"], str): pre_mlayer_dict["density1"] = float(pre_mlayer_dict["density1"]) if isinstance(pre_mlayer_dict["density2"], str): pre_mlayer_dict["density2"] = float(pre_mlayer_dict["density2"]) # fill unused keys pre_mlayer_dict["energy"] = None pre_mlayer_dict["delta_s"] = None pre_mlayer_dict["beta_s"] = None pre_mlayer_dict["delta_e"] = None pre_mlayer_dict["beta_e"] = None pre_mlayer_dict["delta_o"] = None pre_mlayer_dict["beta_o"] = None pre_mlayer_dict["igrade"] = None if pre_mlayer_dict["igrade"] == 1: pre_mlayer_dict["fgrade"] = None elif pre_mlayer_dict["igrade"] == 2: # igrade=2, coefficients pre_mlayer_dict["a0"] = None pre_mlayer_dict["a1"] = None pre_mlayer_dict["a2"] = None pre_mlayer_dict["a3"] = None # return out = MLayer() out.pre_mlayer_dict = pre_mlayer_dict out.using_pre_mlayer = False return out
def xoppy_calc_power3D(self): # # prepare input for xpower_calc # Note that the input for xpower_calc accepts any number of elements. # substance = [ self.EL1_FOR, self.EL2_FOR, self.EL3_FOR, self.EL4_FOR, self.EL5_FOR ] thick = numpy.array((self.EL1_THI, self.EL2_THI, self.EL3_THI, self.EL4_THI, self.EL5_THI)) angle = numpy.array((self.EL1_ANG, self.EL2_ANG, self.EL3_ANG, self.EL4_ANG, self.EL5_ANG)) dens = [ self.EL1_DEN, self.EL2_DEN, self.EL3_DEN, self.EL4_DEN, self.EL5_DEN ] roughness = numpy.array((self.EL1_ROU, self.EL2_ROU, self.EL3_ROU, self.EL4_ROU, self.EL5_ROU)) flags = numpy.array((self.EL1_FLAG, self.EL2_FLAG, self.EL3_FLAG, self.EL4_FLAG, self.EL5_FLAG)) substance = substance[0:self.NELEMENTS + 1] thick = thick[0:self.NELEMENTS + 1] angle = angle[0:self.NELEMENTS + 1] dens = dens[0:self.NELEMENTS + 1] roughness = roughness[0:self.NELEMENTS + 1] flags = flags[0:self.NELEMENTS + 1] p, e, h, v = self.input_beam.get_content("xoppy_data") nelem_including_source = self.NELEMENTS + 1 energies = e # initialize results # note that element of zero index corresponds to source!!! transmittance = numpy.zeros( (nelem_including_source, p.shape[0], p.shape[1], p.shape[2])) for i in range(nelem_including_source): transmittance[i] = numpy.ones_like(p) # # get undefined densities # for i in range(nelem_including_source): try: rho = float(dens[i]) except: rho = xraylib.ElementDensity( xraylib.SymbolToAtomicNumber(substance[i])) print("Density for %s: %g g/cm3" % (substance[i], rho)) dens[i] = rho #info oe txt = "" for i in range(self.NELEMENTS): if flags[i] == 0: txt += ' ***** oe ' + str( i + 1) + ' [Filter] *************\n' txt += ' Material: %s\n' % (substance[i]) txt += ' Density [g/cm^3]: %f \n' % (dens[i]) txt += ' thickness [mm] : %f \n' % (thick[i]) else: txt += ' ***** oe ' + str( i + 1) + ' [Mirror] *************\n' txt += ' Material: %s\n' % (substance[i]) txt += ' Density [g/cm^3]: %f \n' % (dens[i]) txt += ' grazing angle [mrad]: %f \n' % (angle[i]) txt += ' roughness [A]: %f \n' % (roughness[i]) for i in range(self.NELEMENTS): if flags[i] == 0: # filter for j, energy in enumerate(energies): tmp = xraylib.CS_Total_CP(substance[i], energy / 1000.0) # pay attention to the element index... transmittance[i + 1, j, :, :] = numpy.exp( -tmp * dens[i] * (thick[i] / 10.0)) if flags[i] == 1: # mirror tmp = numpy.zeros(energies.size) for j, energy in enumerate(energies): tmp[j] = xraylib.Refractive_Index_Re( substance[i], energy / 1000.0, dens[i]) delta = 1.0 - tmp beta = numpy.zeros(energies.size) for j, energy in enumerate(energies): beta[j] = xraylib.Refractive_Index_Im( substance[i], energy / 1000.0, dens[i]) (rs,rp,runp) = reflectivity_fresnel(refraction_index_beta=beta,refraction_index_delta=delta,\ grazing_angle_mrad=angle[i],roughness_rms_A=roughness[i],\ photon_energy_ev=energies) for j, energy in enumerate(energies): transmittance[i + 1, j, :, :] = rs[j] txt += "\n\n\n" integration_constante = (e[1] - e[0]) * (h[1] - h[0]) * ( v[1] - v[0]) * codata.e * 1e3 p_cumulated = p.copy() power_cumulated = p_cumulated.sum() * integration_constante txt += ' Input beam power: %f W\n' % (power_cumulated) for i in range(self.NELEMENTS): p_cumulated *= transmittance[i + 1] power_transmitted = (p_cumulated).sum() * integration_constante txt += ' Beam power after optical element %d: %6.3f W (absorbed: %6.3f W)\n'%\ (i+1,power_transmitted,power_cumulated-power_transmitted) power_cumulated = power_transmitted print(txt) return transmittance
def tube_atten(E, Z, D): expon = -xrl.CS_Total(Z, E) * D * 1e-4 * xrl.ElementDensity(Z) ta = exp(expon) return ta
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 φ′', '28 Anomalous scattering factor φ″', '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 ####")
def crlFocalLength(r, E, material='Be', density=None): if density is None: density = xraylib.ElementDensity( xraylib.SymbolToAtomicNumber(material)) return r / 2 / ( 1 - xraylib.Refractive_Index_Re(getElementsName(material), E, density))
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()
def xoppy_calc_xcrosssec(self): MAT_FLAG = self.MAT_FLAG MAT_LIST = self.MAT_LIST DESCRIPTOR = self.DESCRIPTOR density = self.DENSITY CALCULATE = self.CALCULATE GRID = self.GRID GRIDSTART = self.GRIDSTART GRIDEND = self.GRIDEND GRIDN = self.GRIDN UNIT = self.UNIT if MAT_FLAG == 0: # element descriptor = DESCRIPTOR density = xraylib.ElementDensity( xraylib.SymbolToAtomicNumber(DESCRIPTOR)) elif MAT_FLAG == 1: # formula descriptor = DESCRIPTOR elif MAT_FLAG == 2: tmp = xraylib.GetCompoundDataNISTByIndex(MAT_LIST) descriptor = tmp["name"] density = tmp["density"] print("xoppy_calc_xcrosssec: using density = %g g/cm3" % density) if GRID == 0: energy = numpy.arange(0, 500) elefactor = numpy.log10(10000.0 / 30.0) / 300.0 energy = 10.0 * 10**(energy * elefactor) elif GRID == 1: if GRIDN == 1: energy = numpy.array([GRIDSTART]) else: energy = numpy.linspace(GRIDSTART, GRIDEND, GRIDN) elif GRID == 2: energy = numpy.array([GRIDSTART]) if MAT_FLAG == 0: # element out = cross_calc(descriptor, energy, calculate=CALCULATE, density=density) elif MAT_FLAG == 1: # compound parse out = cross_calc_mix(descriptor, energy, calculate=CALCULATE, density=density, parse_or_nist=0) elif MAT_FLAG == 2: # NIST compound out = cross_calc_mix(descriptor, energy, calculate=CALCULATE, density=density, parse_or_nist=1) calculate_items = [ 'Total', 'PhotoElectric', 'Rayleigh', 'Compton', 'Total minus Rayleigh' ] unit_items = ['barn/atom', 'cm^2', 'cm^2/g', 'cm^-1'] if energy.size > 1: tmp_x = out[0, :].copy() tmp_y = out[UNIT + 1, :].copy() tmp = numpy.vstack((tmp_x, tmp_y)) labels = [ "Photon energy [eV]", "%s cross section [%s]" % (calculate_items[CALCULATE], unit_items[UNIT]) ] to_return = { "application": "xoppy", "name": "xcrosssec", "data": tmp, "labels": labels } else: tmp = None txt = "xoppy_calc_xcrosssec: Calculated %s cross section: %g %s" % ( calculate_items[CALCULATE], out[UNIT + 1, 0], unit_items[UNIT]) print(txt) to_return = { "application": "xoppy", "name": "xcrosssec", "info": txt } if self.DUMP_TO_FILE: with open(self.FILE_NAME, "w") as file: try: file.write("#F %s\n" % self.FILE_NAME) file.write("\n#S 1 xoppy CrossSec results\n") file.write("#N 5\n") tmp = "#L Photon energy [eV]" for unit_item in unit_items: tmp += " %s [%s]" % (calculate_items[CALCULATE], unit_item) tmp += "\n" file.write(tmp) for j in range(out.shape[1]): # file.write("%19.12e "%energy[j]) file.write( ("%19.12e " * out.shape[0] + "\n") % tuple(out[i, j] for i in range(out.shape[0]))) file.close() print("File written to disk: %s \n" % self.FILE_NAME) except: raise Exception( "CrossSec: The data could not be dumped onto the specified file!\n" ) return to_return
# * 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. #from xraylib import * import sys, string import xraylib import math if __name__ == '__main__' : xraylib.XRayInit() xraylib.SetErrorMessages(0) print ("Example of python program using xraylib") print ("Density of pure Al : %f g/cm3" % xraylib.ElementDensity(13)) print ("Ca K-alpha Fluorescence Line Energy: %f" % xraylib.LineEnergy(20,xraylib.KA_LINE)) print ("Fe partial photoionization cs of L3 at 6.0 keV: %f" % xraylib.CS_Photo_Partial(26,xraylib.L3_SHELL,6.0)) print ("Zr L1 edge energy: %f" % xraylib.EdgeEnergy(40,xraylib.L1_SHELL)) print ("Pb Lalpha XRF production cs at 20.0 keV (jump approx): %f" % xraylib.CS_FluorLine(82,xraylib.LA_LINE,20.0)) print ("Pb Lalpha XRF production cs at 20.0 keV (Kissel): %f" % xraylib.CS_FluorLine_Kissel(82,xraylib.LA_LINE,20.0)) print ("Bi M1N2 radiative rate: %f" % xraylib.RadRate(83,xraylib.M1N2_LINE)) print ("U M3O3 Fluorescence Line Energy: %f" % xraylib.LineEnergy(92,xraylib.M3O3_LINE)) print ("Ca(HCO3)2 Rayleigh cs at 10.0 keV: %f" % xraylib.CS_Rayl_CP("Ca(HCO3)2",10.0)) cdtest = xraylib.CompoundParser("Ca(HCO3)2") print ("Ca(HCO3)2 contains %g atoms and %i elements"% (cdtest['nAtomsAll'], cdtest['nElements'])) for i in range(cdtest['nElements']): print ("Element %i: %lf %%" % (cdtest['Elements'][i],cdtest['massFractions'][i]*100.0)) cdtest = xraylib.CompoundParser("SiO2")