def line_energy(element,line): """ Get the emission energy for a given element and line using the xraylib backend Parameters: Element : Name, Symbol or Atomic Number (Z) as input Line : Accepts Siegbahn and line notations : line can be one of the following For line averages: 'ka','lb','l1','l2','l3','la','lb','lg', or for the exact lines 'ka1', 'ka2', 'ka3','kb1', 'kb2', 'kb3','kb4','kb5', 'la1', 'la2', 'lb1', 'lb2', 'lb3', 'lb4', 'lb5', 'lg1', 'lg2', 'lg3', 'lg4', 'll', 'ln', 'ma1','ma2','mb','mg' Returns: line energy: energy at which this fluorescence line appears """ z = elementDB[element]["Z"] if not isinstance(line,LinePair): line = _lookupxlsubline(line) return xraylib.LineEnergy(z,line.subline)
def parse_raw_fluoro(fn, edge, trans, acqTime): rv = [] with open(fn) as f: total_count = 0 background_count = 0 for i, l in enumerate(f): if i > 2: e, cts = l.strip().split() total_count += float(cts) background_count += min(float(cts), 2) # crude but works I guess... if float(e) > (float(edge) - 1250.0): break if (total_count - background_count) > 100: FilePrefix = os.path.splitext(os.path.basename(fn))[0] pure_path = PurePath(fn).parts VisitDir = pure_path[:6] RestOfFilename = os.path.join(*pure_path[6:]) RestOfDirs = os.path.dirname(RestOfFilename) OutputDir = os.path.join(*VisitDir, 'processed/pymca', RestOfDirs) elf = os.path.join(OutputDir, FilePrefix) + '.results.dat' els = [] # contains lines like # Cu-K 7929.020000 90.714300 with open(elf) as f: rv.append("Element\tCounts\t%age\tExpected Emission Energies") for i, l in enumerate(f): el, pk, conf = l.strip().split() symbol, edge = el.split('-') Z = xrl.SymbolToAtomicNumber(symbol) edgesEnergies = "<b>{:g}</b>,{:g}".format( xrl.LineEnergy(Z, LINE_MAPPER[edge]) * 1000.0, xrl.EdgeEnergy(Z, EDGE_MAPPER[edge]) * 1000.0) if float(pk) >= 100000: counts = int(float(pk)) else: counts = round(float(pk), 1) rv.append("{}\t{:g}\t{:g}\t{}".format( el, counts, round(100 * float(pk) / total_count, 1), edgesEnergies)) if i == 5: break else: rv.append("No fluorescence peaks detected, try a higher transmission") rv.append("\nCounts (total): {:g} (background): {:g}".format( total_count, background_count)) return rv
def eleXRF_energy(ele, energy): Z = xl.SymbolToAtomicNumber(ele); F = xl.LineEnergy(Z, xl.KA1_LINE) if xl.EdgeEnergy(Z, xl.K_SHELL) > energy: F = xl.LineEnergy(Z, xl.LA1_LINE) elif xl.EdgeEnergy(Z, xl.L1_SHELL) > energy: F = xl.LineEnergy(Z, xl.LB1_LINE) elif xl.EdgeEnergy(Z, xl.L2_SHELL) > energy: F = xl.LineEnergy(Z, xl.LB1_LINE) elif xl.EdgeEnergy(Z, xl.L3_SHELL) > energy: F = xl.LineEnergy(Z, xl.LG1_LINE) elif xl.EdgeEnergy(Z, xl.M1_SHELL) > energy: F = xl.LineEnergy(Z, xl.MA1_LINE) return F
def fluoro_emission_map(p, n_map, angle, el): """Compute the maia-detector-shaped map of K-edge fluorescence from the element map for an incident irradiance map n_map. Parameters ---------- p : Phantom2d object p.energy - incident beam photon energy (keV). p.um_per_px - length of one pixel of the map (um). n_map : 2d ndarray of float Map of incident irradiance. angle : float Stage rotation angle (degrees). el : string Name of fluorescing element (e.g. 'Fe'). Returns ------- 2d ndarray of float The fluorescence emission map for the requested edge. """ # edge_map = zero_outside_circle(p.el_maps[el]) edge_map = p.el_maps[el] edge_map_r = rotate(edge_map, angle) del edge_map # Get Z for the fluorescing element el_z = xrl.SymbolToAtomicNumber(el) line = xrl.KA_LINE # Sanity check that el K_alpha is below the incident energy. k_alpha_energy = xrl.LineEnergy(el_z, line) # assert k_alpha_energy < p.energy if k_alpha_energy >= p.energy: Q = 0.0 else: # Simulate fluorescence event: # CS_FluorLine_Kissel_Cascade is the XRF cross section Q_{i,YX} in Eq. (12) # of Schoonjans et al. Q = xrl.CS_FluorLine_Kissel_Cascade(el_z, line, p.energy) # print(el, end=' ') # 2d array for results emission_map = n_map * Q * edge_map_r * p.um_per_px / UM_PER_CM return emission_map
def get_roi_from_XRF_line(self, XRFline): """This function determines the region of interest that should be used to represent an XRF line""" # first thing to do is determine which element and line we are dealing with # split the string along the dash try: (element, line) = XRFline.split('-') #print('element: ' + element) #print('line: ' + line) atomic_number = xraylib.SymbolToAtomicNumber(element) if (atomic_number == 0): raise ValueError( element + ' could not be parsed by xraylib.SymbolToAtomicNumber') #print('atomic_number:' + str(atomic_number)) # I can probably also get the same result with 'vars' line_macro = xraylib.__dict__[line.upper() + '_LINE'] #print('line_macro:' + str(line_macro)) line_energy = xraylib.LineEnergy(atomic_number, line_macro) #print('line_energy: ' + str(line_energy)) if (line_energy == 0.0): raise ValueError('XRF line ' + XRFline + ' does not exist in the xraylib database') if (self.PixelType != 2): raise ValueError( 'get_roi_from_XRF_line requires that the object has PixelType 2' ) channel = int(self.NBins * (line_energy - self.Emin) / (self.Emax - self.Emin)) #print('channel:' + str(channel)) if (channel < 0 or channel >= self.NBins): raise ValueError('requested XRF line not covered by spectrum') return slice(max(0, channel - 10), min(self.NBins - 1, channel + 10)) except Exception as e: raise Exception(str(e))
def XRF_line(Element, Beam_Energy): Z = xl.SymbolToAtomicNumber(str(Element)) F = xl.LineEnergy(Z, xl.KA1_LINE) if xl.EdgeEnergy(Z, xl.K_SHELL) > Beam_Energy: F = xl.LineEnergy(Z, xl.LA1_LINE) if xl.EdgeEnergy(Z, xl.L1_SHELL) > Beam_Energy: F = xl.LineEnergy(Z, xl.LB1_LINE) if xl.EdgeEnergy(Z, xl.L2_SHELL) > Beam_Energy: F = xl.LineEnergy(Z, xl.LB1_LINE) if xl.EdgeEnergy(Z, xl.L3_SHELL) > Beam_Energy: F = xl.LineEnergy(Z, xl.LG1_LINE) if xl.EdgeEnergy(Z, xl.M1_SHELL) > Beam_Energy: F = xl.LineEnergy(Z, xl.MA1_LINE) return F
def get_Ele_XRF_Energy(ele, energy): Z = xl.SymbolToAtomicNumber(ele) #will it abosrb? if so, it will fluoresce F = xl.LineEnergy(Z, xl.KA1_LINE) if xl.EdgeEnergy(Z, xl.K_SHELL) > energy: F = xl.LineEnergy(Z, xl.LA1_LINE) if xl.EdgeEnergy(Z, xl.L1_SHELL) > energy: F = xl.LineEnergy(Z, xl.LB1_LINE) if xl.EdgeEnergy(Z, xl.L2_SHELL) > energy: F = xl.LineEnergy(Z, xl.LB1_LINE) if xl.EdgeEnergy(Z, xl.L3_SHELL) > energy: F = xl.LineEnergy(Z, xl.LG1_LINE) if xl.EdgeEnergy(Z, xl.M1_SHELL) > energy: F = xl.LineEnergy(Z, xl.MA1_LINE) return F
def GetFluorescenceEnergy(Element,Beam): # send in the element and the beam energy to get the Excited Fluorescence Energy #this will return the highest energy fluorescence photon capable of being excited by the beam Z = xraylib.SymbolToAtomicNumber(Element) F = xraylib.LineEnergy(Z,xraylib.KA1_LINE) if xraylib.EdgeEnergy(Z,xraylib.K_SHELL) > Beam: F = xraylib.LineEnergy(Z,xraylib.LA1_LINE) if xraylib.EdgeEnergy(Z,xraylib.L1_SHELL) > Beam: F = xraylib.LineEnergy(Z,xraylib.LB1_LINE) if xraylib.EdgeEnergy(Z,xraylib.L2_SHELL) > Beam: F = xraylib.LineEnergy(Z,xraylib.LB1_LINE) if xraylib.EdgeEnergy(Z,xraylib.L3_SHELL) > Beam: F = xraylib.LineEnergy(Z,xraylib.LG1_LINE) if xraylib.EdgeEnergy(Z,xraylib.M1_SHELL) > Beam: F = xraylib.LineEnergy(Z,xraylib.MA1_LINE) return F
def _calculate_fpm_intensity(input, theta): alpha = math.radians(90.0 - theta) beta = math.radians(theta) discrete = input.excitation.get_energy_discrete(0) I0 = discrete.horizontal_intensity + discrete.vertical_intensity E0 = discrete.energy layer = input.composition.get_layer(0) _theta = math.atan(math.sqrt(input.geometry.area_detector / math.pi) / math.fabs(input.geometry.p_detector_window[1])) Omega_DET = 2 * math.pi * (1.0 - math.cos(_theta)) G = Omega_DET / 4.0 / math.pi / math.sin(alpha) rv = [] for i in zip(layer.Z, layer.weight): (Z, weight) = i chi = TestBatchSingle._chi(E0, xrl.LineEnergy(Z, xrl.KL3_LINE), layer, alpha, beta) tmp = I0 * G * weight * xrl.CS_FluorLine_Kissel(Z, xrl.KL3_LINE, E0) * \ (1.0 - math.exp(-1.0 * chi * layer.density * layer.thickness)) / chi rv.append(tmp) return rv
def XRF_line(Element, Beam_Energy): Z = xl.SymbolToAtomicNumber( str(Element)) #converts element string to element atomic number F = xl.LineEnergy( Z, xl.KA1_LINE ) #initialize energy of fluorescence photon as highest energy K-line transition for the element if xl.EdgeEnergy( Z, xl.K_SHELL ) > Beam_Energy: #if beam energy is less than K ABSORPTION energy, F = xl.LineEnergy( Z, xl.LA1_LINE ) #energy of fluorescence photon equals highest energy L-line transition for the element if xl.EdgeEnergy( Z, xl.L1_SHELL ) > Beam_Energy: #if beam energy is less than L1 ABSORPTION energy, and so on... F = xl.LineEnergy(Z, xl.LB1_LINE) if xl.EdgeEnergy(Z, xl.L2_SHELL) > Beam_Energy: F = xl.LineEnergy(Z, xl.LB1_LINE) if xl.EdgeEnergy(Z, xl.L3_SHELL) > Beam_Energy: F = xl.LineEnergy(Z, xl.LG1_LINE) if xl.EdgeEnergy(Z, xl.M1_SHELL) > Beam_Energy: F = xl.LineEnergy(Z, xl.MA1_LINE) return F
#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") print ("SiO2 contains %g atoms and %i elements"% (cdtest['nAtomsAll'], cdtest['nElements']))
def get_lineenergy(z, line): try: ene = xrl.LineEnergy(z, int(line)) except: ene = 0. return ene
def findLines(self, paramdict=XRFDataset().paramdict): """ Calculates the line energies to fit """ # Incident Energy used in the experiment # Energy range to use for fitting pileup_cut_off = paramdict["FitParams"]["pileup_cutoff_keV"] include_pileup = paramdict["FitParams"]["include_pileup"] include_escape = paramdict["FitParams"]["include_escape"] fitting_range = paramdict["FitParams"]["fitted_energy_range_keV"] # x = paramdict["FitParams"]["mca_energies_used"] energy = paramdict["Experiment"]["incident_energy_keV"] detectortype = 'Vortex_SDD_Xspress' fitelements = paramdict["Experiment"]["elements"] peakpos = [] escape_peaks = [] for _j, el in enumerate(fitelements): z = xl.SymbolToAtomicNumber(str(el)) for i, shell in enumerate(shells): if (xl.EdgeEnergy(z, shell) < energy - 0.5): linepos = 0.0 count = 0.0 for line in transitions[i]: en = xl.LineEnergy(z, line) if (en > 0.0): linepos += en count += 1.0 if (count == 0.0): break linepos = linepos / count if (linepos > fitting_range[0] and linepos < fitting_range[1]): peakpos.append(linepos) peakpos = np.array(peakpos) too_low = set(list(peakpos[peakpos > fitting_range[0]])) too_high = set(list(peakpos[peakpos < fitting_range[1]])) bar = list(too_low and too_high) bar = np.unique(bar) peakpos = list(bar) peaks = [] peaks.extend(peakpos) if (include_escape): for i in range(len(peakpos)): escape_energy = calc_escape_energy(peakpos[i], detectortype)[0] if (escape_energy > fitting_range[0]): if (escape_energy < fitting_range[1]): escape_peaks.extend([escape_energy]) # print escape_peaks peaks.extend(escape_peaks) if (include_pileup): # applies just to the fluorescence lines pileup_peaks = [] peakpos1 = np.array(peakpos) peakpos_high = peakpos1[peakpos1 > pileup_cut_off] peakpos_high = list(peakpos_high) for i in range(len(peakpos_high)): foo = [peakpos_high[i] + x for x in peakpos_high[i:]] foo = np.array(foo) pileup_peaks.extend(foo) pileup_peaks = np.unique(sorted(pileup_peaks)) peaks.extend(pileup_peaks) peakpos = peaks peakpos = np.array(peakpos) too_low = set(list(peakpos[peakpos > fitting_range[0]])) too_high = set(list(peakpos[peakpos < fitting_range[1] - 0.5])) bar = list(too_low and too_high) bar = np.unique(bar) peakpos = list(bar) peakpos = np.unique(peakpos) # print peakpos return peakpos
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)
def channel_rayleigh_map(p, q, maia_d, n_map, angle): """Compute the maia-detector-shaped map of Rayleigh scattering from the element map for an incident irradiance map n_map. Parameters ---------- p : Phantom2d object p.energy - incident beam photon energy (keV). p.um_per_px - length of one pixel of the map (um). q : int Maia detector channel id maia_d : Maia() instance n_map : 2d ndarray of float Map of incident irradiance. angle : float Stage rotation angle (degrees). Returns ------- 2d ndarray of float The fluorescence emission map for the requested edge. """ solid_angle = maia_d.pads[q].omega # Get spherical angles (polar theta & azimuthal phi) to detector element theta = maia_d.pads[q].theta phi = maia_d.pads[q].phi energy = outgoing_photon_energy('rayleigh', p) # get a list of all elements el and their weights w_el # The absorption map mu = ma_M * mu_M + sum_k ( ma_k * mu_k ) mu = p.matrix.ma(energy) * p.el_maps['matrix'] for el in p.el_maps: if el == 'matrix': continue Z = xrl.SymbolToAtomicNumber(el) mu += p.matrix.cp[el] * xrl.DCSP_Rayl(Z, energy, theta, phi) * \ p.el_maps[el] ma += xrl.DCSP_Rayl(Z, energy, theta, phi) # edge_map = zero_outside_circle(p.el_maps[el]) edge_map_r = rotate(edge_map, angle) del edge_map # Get Z for the fluorescing element el_z = xrl.SymbolToAtomicNumber(el) line = xrl.KA_LINE # Sanity check that el K_alpha is below the incident energy. k_alpha_energy = xrl.LineEnergy(el_z, line) assert k_alpha_energy < p.energy # Simulate fluorescence event: # CS_FluorLine_Kissel_Cascade is the XRF cross section Q_{i,YX} in Eq. (12) # of Schoonjans et al. Q = xrl.CS_FluorLine_Kissel_Cascade(el_z, line, p.energy) # 2d array for results emission_map = n_map * Q * edge_map_r * p.um_per_px / UM_PER_CM return emission_map
def phantom_assign_concentration(ph_or, data_type=np.float32): """Builds the phantom used in: - N. Viganò and V. A. Solé, “Physically corrected forward operators for induced emission tomography: a simulation study,” Meas. Sci. Technol., no. Advanced X-Ray Tomography, pp. 1–26, Nov. 2017. :param ph_or: DESCRIPTION :type ph_or: TYPE :param data_type: DESCRIPTION, defaults to np.float32 :type data_type: TYPE, optional :return: DESCRIPTION :rtype: TYPE """ # ph_air = ph_or < 0.1 ph_FeO = 0.5 < ph_or ph_CaO = np.logical_and(0.25 < ph_or, ph_or < 0.5) ph_CaC = np.logical_and(0.1 < ph_or, ph_or < 0.25) conv_mm_to_cm = 1e-1 conv_um_to_mm = 1e-3 voxel_size_um = 0.5 voxel_size_cm = voxel_size_um * conv_um_to_mm * conv_mm_to_cm # cm to micron print("Sample size: [%g %g] um" % (ph_or.shape[0] * voxel_size_um, ph_or.shape[1] * voxel_size_um)) import xraylib xraylib.XRayInit() cp_fo = xraylib.GetCompoundDataNISTByName("Ferric Oxide") cp_co = xraylib.GetCompoundDataNISTByName("Calcium Oxide") cp_cc = xraylib.GetCompoundDataNISTByName("Calcium Carbonate") ca_an = xraylib.SymbolToAtomicNumber("Ca") ca_kal = xraylib.LineEnergy(ca_an, xraylib.KA_LINE) in_energy_keV = 20 out_energy_keV = ca_kal ph_lin_att_in = ( ph_FeO * xraylib.CS_Total_CP("Ferric Oxide", in_energy_keV) * cp_fo["density"] + ph_CaC * xraylib.CS_Total_CP("Calcium Carbonate", in_energy_keV) * cp_cc["density"] + ph_CaO * xraylib.CS_Total_CP("Calcium Oxide", in_energy_keV) * cp_co["density"]) ph_lin_att_out = ( ph_FeO * xraylib.CS_Total_CP("Ferric Oxide", out_energy_keV) * cp_fo["density"] + ph_CaC * xraylib.CS_Total_CP("Calcium Carbonate", out_energy_keV) * cp_cc["density"] + ph_CaO * xraylib.CS_Total_CP("Calcium Oxide", out_energy_keV) * cp_co["density"]) vol_att_in = ph_lin_att_in * voxel_size_cm vol_att_out = ph_lin_att_out * voxel_size_cm ca_cs = xraylib.CS_FluorLine_Kissel( ca_an, xraylib.KA_LINE, in_energy_keV) # fluo production for cm2/g ph_CaC_mass_fract = cp_cc["massFractions"][np.where( np.array(cp_cc["Elements"]) == ca_an)[0][0]] ph_CaO_mass_fract = cp_co["massFractions"][np.where( np.array(cp_co["Elements"]) == ca_an)[0][0]] ph = ph_CaC * ph_CaC_mass_fract * cp_cc[ "density"] + ph_CaO * ph_CaO_mass_fract * cp_co["density"] ph = ph * ca_cs * voxel_size_cm return (ph, vol_att_in, vol_att_out)
def k_alpha_energy(el): el_z = xrl.SymbolToAtomicNumber(el) line = xrl.KA_LINE energy = xrl.LineEnergy(el_z, line) # assert energy < p.energy return energy
def GenerateSpectrum(i, u, z, num_points=100, spec_type='XRAYTUBE'): """ Intensity of Characteristic Lines by formula R=BIA(UA-UK)1,5 :param i: (float): Current in [a] :param u: (float): Voltage [keV] :param z: (int): The sequence number of the item :param num_points: number of points :param spec_type: type of XRay spevtrum can be one of 'XRAYTUBE', 'BRELUNG' or 'CHARLINES' Returns: objec Spectrum """ widht = { 24: (1.97, 2.39, 70, 30), #Cr 29: (2.4, 2.98, 100, 50), # Cu 42: (6.42, 6.66, 500, 150), # Mo 47: (8.6, 8.9, 150, 50), # Ag 74: (8.6, 8.9, 500, 200) } # W energies = np.linspace(u * 1e-3, u, num_points) spectrum = np.zeros_like(energies) if spec_type == 'BRELUNG' or spec_type == 'XRAYTUBE': c = 3.0 lambda_0 = 12.398 / u # Critical wavelength [A] lambdas = 12.398 / energies spectrum += c * c / lambda_0 * i * 0.001 * z * (lambdas - lambda_0) / lambdas**3 if spec_type == 'CHARLINES' or spec_type == 'XRAYTUBE': w1, w2, k1, k2 = widht[z] w1 *= 2e-1 w2 *= 2e-1 spec = np.zeros_like(energies) energy = xraylib.LineEnergy(z, xraylib.KA1_LINE) intensity = k1 * i * 0.001 * np.power(u - energy, 1.5) indexes = np.where((energies < energy + w1) & (energies > energy - w1)) int1 = np.linspace(0.0, intensity, len(indexes[0]) / 2) int2 = np.linspace(intensity, 0.0, len(indexes[0]) - len(indexes[0]) / 2) spec[indexes] = np.concatenate((int1, int2), axis=0) energy = xraylib.LineEnergy(z, xraylib.KA2_LINE) intensity = k1 * i * 0.001 * np.power(u - energy, 1.5) indexes = np.where((energies < energy + w2) & (energies > energy - w2)) int1 = np.linspace(0.0, intensity, len(indexes[0]) / 2) int2 = np.linspace(intensity, 0.0, len(indexes[0]) - len(indexes[0]) / 2) spec[indexes] = np.concatenate((int1, int2), axis=0) energy = xraylib.LineEnergy(z, xraylib.KB1_LINE) intensity = k2 * i * 0.001 * np.power(u - energy, 1.5) indexes = np.where((energies < energy + w1) & (energies > energy - w1)) int1 = np.linspace(0.0, intensity, len(indexes[0]) / 2) int2 = np.linspace(intensity, 0.0, len(indexes[0]) - len(indexes[0]) / 2) spec[indexes] = np.concatenate((int1, int2), axis=0) #energy = xraylib.LineEnergy(z, xraylib.KB2_LINE) #intensity = k2 * i * 0.001 * np.power(u - energy, 1.5) #indexes = np.where((energies < energy + w2) & (energies > energy - w2)) #int1 = np.linspace(0.0, intensity, len(indexes[0]) / 2) #int2 = np.linspace(intensity, 0.0, len(indexes[0]) - len(indexes[0]) / 2) #spec[indexes] = np.concatenate((int1, int2), axis=0) spectrum += spec return Spectrum(energy=energies, intensity=spectrum, label='I={} mA, U={} kV, Z={}'.format(i, u, z))
def calc_escape_peak_ratios(lineE, detectorelement='Si'): """ Calculate ratio of escape peak to main peak based on emperical calculation from Alves et. al. Parameters ---------- detectorelement : string "Si" or "Ge" Returns ------- ratio of a single Si K escape peak to a single input peak or ratio of Ge Ka, Kb escape peaks to a single input peak References ---------- [1] "Experimental X-Ray peak-shape determination for a Si(Li) detector", L.C. Alves et al., Nucl. Instr. and Meth. in Phys. Res. B 109|110 (1996) 129-133. """ if (detectorelement == 'Si'): # # For Si the K peak is 95% of the transition # and the photoionization to total cross section is ~ 95% # Si escape peak is typically only 0.2-1% (bigger at lower energies) # jump = xl.JumpFactor(14, xl.K_SHELL) fluy = xl.FluorYield(14, xl.K_SHELL) corr = fluy * (jump - 1.0) / jump corr_photo = xl.CS_Photo(14, lineE) / xl.CS_Total(14, lineE) corr_trans = xl.RadRate(14, xl.KA_LINE) + xl.RadRate(14, xl.KB_LINE) mu_si = xl.CS_Total(14, lineE) mu_internal = xl.CS_Total(14, 1.73998) r = mu_internal / mu_si eta = corr_trans * corr_photo * corr * 0.5 * (1.0 - r * log(1.0 + 1.0 / r)) ratio = eta / (1.0 - eta) # # escape peak sigma should be narrower than the main peak. # return ratio else: # # Ge detector... # Ge has a large escape peak ratio ~ 5-15% and a Ka and kb component # if (lineE < 11.5): return 0.0, 0.0 jump = xl.JumpFactor(32, xl.K_SHELL) fluy = xl.FluorYield(32, xl.K_SHELL) corr = fluy * (jump - 1.0) / jump corr_photo = xl.CS_Photo(32, lineE) / xl.CS_Total(32, lineE) corr_trans_ka = xl.RadRate(32, xl.KA_LINE) corr_trans_kb = xl.RadRate(32, xl.KB_LINE) mu_ge = xl.CS_Total(32, lineE) # # one for the Ka and one for the Kb peak... mu_internal_ka = xl.CS_Total(32, xl.LineEnergy(32, xl.KA_LINE)) r_ka = mu_internal_ka / mu_ge eta_ka = corr_trans_ka * corr_photo * corr * 0.5 * ( 1.0 - r_ka * log(1.0 + 1.0 / r_ka)) ratio_ka = eta_ka / (1.0 - eta_ka) mu_internal_kb = xl.CS_Total(32, xl.LineEnergy(32, xl.KB_LINE)) r_kb = mu_internal_kb / mu_ge eta_kb = corr_trans_kb * corr_photo * corr * 0.5 * ( 1.0 - r_kb * log(1.0 + 1.0 / r_kb)) ratio_kb = eta_kb / (1.0 - eta_kb) return ratio_ka, ratio_kb
def get_element_xrf_lines(Z, lines='all', incident_energy=100.0, lowE=0.0, highE=100.0, norm_to_one=False, include_escape=True, detector_element='Si'): """ Generate a list of lines that a given element will generate for energy range listed """ result = {} xrf_list = [] escape_list = [] # # This isn't very elegant... # if lines.upper() == 'K': linelist = siegbahn_k_list namelist = siegbahn_k_name_list elif lines.upper() == 'KA': linelist = siegbahn_ka_list namelist = siegbahn_ka_name_list if lines.upper() == 'KB': linelist = siegbahn_kb_list namelist = siegbahn_kb_name_list elif lines.upper() == 'L': linelist = siegbahn_l_list namelist = siegbahn_l_name_list elif lines.upper() == 'LA' or lines.upper() == 'L1': linelist = siegbahn_l1_list namelist = siegbahn_l1_name_list elif lines.upper() == 'LB' or lines.upper() == 'L2': linelist = siegbahn_l2_list namelist = siegbahn_l2_name_list elif lines.upper() == 'LG' or lines.upper() == 'L3': linelist = siegbahn_l3_list namelist = siegbahn_l3_name_list elif lines.upper() == 'M': linelist = siegbahn_m_list namelist = siegbahn_m_name_list elif lines.upper() == 'MA': linelist = siegbahn_ma_list namelist = siegbahn_ma_name_list elif lines.upper() == 'MB': linelist = siegbahn_mb_list namelist = siegbahn_mb_name_list elif lines.upper() == 'MG': linelist = siegbahn_mg_list namelist = siegbahn_mg_name_list else: linelist = siegbahn_all_list namelist = siegbahn_all_name_list for label, line in zip(namelist, linelist): lineE = xraylib.LineEnergy(Z, line) if lineE > 2.0 and lineE <= highE: cs = xraylib.CS_FluorLine_Kissel(Z, line, incident_energy) if cs > 0.0: # xrf_list.append(XrayLine(label,lineE,cs)) xrf_list.append([label, lineE, cs]) if (include_escape): ratio = calc_escape_peak_ratios(lineE) escape_energy = calc_escape_peak_energy( lineE, detector_element) # escape_list.append(EscapeLine(label,lineE,escape_energy,cs*ratio)) escape_list.append( [label, lineE, escape_energy, cs * ratio]) # if norm_to_one: # for line in xrf_list: # line1[2] = line[2]/nsum # for line in escape_list: # line1[3] = line[3]/nsum result["lines"] = xrf_list result["escape"] = escape_list return result
# * 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))) cdtest = xraylib.CompoundParser("Ca(HCO3)2")
def setroi(element=None, line='Ka', roisize=200, roi=1): ''' setting rois for Xspress3 by providing elements input: element (string): element of interest, e.g. 'Se' line (string): default 'Ka', options:'Ka', 'Kb', 'La', 'Lb', 'M', Ka1', 'Ka2', 'Kb1', 'Kb2', 'Lb2', 'Ma1' roisize (int): roi window size in the unit of eV, default = 200 roi (int): 1, 2, or 3: the roi number to set, default = 1 ''' atomic_num = xraylib.SymbolToAtomicNumber(element) multilineroi_flag = False print('element:', element) print('roi window size (eV):', roisize) #calculate the roi low and high bound, based on the line if line is 'Ka': #using average of Ka1 and Ka2 as the center of the energy/roi line_h = xraylib.LineEnergy(atomic_num, xraylib.KL3_LINE) * 1000 #Ka1 line_l = xraylib.LineEnergy(atomic_num, xraylib.KL2_LINE) * 1000 #Ka2 print('Ka1 line (eV):', line_h) print('Ka2 line (eV):', line_l) energy_cen = (line_l + line_h) / 2 multilineroi_flag = True elif line is 'Kb': #using Kb1 line only as the center of the energy/roi energy_cen = xraylib.LineEnergy(atomic_num, xraylib.KM3_LINE) * 1000 print('Kb1 line (eV):', energy_cen) elif line is 'La': #using average of La1 and La2 as the center of the energy/roi line_h = xraylib.LineEnergy(atomic_num, xraylib.L3M5_LINE) * 1000 #La1 line_l = xraylib.LineEnergy(atomic_num, xraylib.L3M4_LINE) * 1000 #La2 print('La1 line (eV):', line_h) print('La2 line (eV):', line_l) energy_cen = (line_l + line_h) / 2 multilineroi_flag = True elif line is 'Lb': #using average of Lb1 and Lb2 as the center of the energy/roi line_l = xraylib.LineEnergy(atomic_num, xraylib.L2M4_LINE) * 1000 #Lb1 line_h = xraylib.LineEnergy(atomic_num, xraylib.L3N5_LINE) * 1000 #Lb2 print('Lb2 line (eV):', line_h) print('Lb1 line (eV):', line_l) energy_cen = (line_l + line_h) / 2 multilineroi_flag = True elif line is 'M': #using Ma1 line only as the center of the energy/roi energy_cen = xraylib.LineEnergy(atomic_num, xraylib.M5N7_LINE) * 1000 print('Ma1 line (eV):', energy_cen) elif line is 'Ka1': energy_cen = xraylib.LineEnergy(atomic_num, xraylib.KL3_LINE) * 1000 print('Ka1 line (eV):', energy_cen) elif line is 'Ka2': energy_cen = xraylib.LineEnergy(atomic_num, xraylib.KL2_LINE) * 1000 print('Ka2 line (eV):', energy_cen) elif line is 'Kb1': energy_cen = xraylib.LineEnergy(atomic_num, xraylib.KM3_LINE) * 1000 print('Kb1 line (eV):', energy_cen) elif line is 'Lb1': energy_cen = xraylib.LineEnergy(atomic_num, xraylib.L2M4_LINE) * 1000 print('Kb2 line (eV):', energy_cen) elif line is 'Lb2': energy_cen = xraylib.LineEnergy(atomic_num, xraylib.L3N5_LINE) * 1000 print('Lb2 line (eV):', energy_cen) elif line is 'Ma1': energy_cen = xraylib.LineEnergy(atomic_num, xraylib.M5N7_LINE) * 1000 print('Ma1 line (eV):', energy_cen) print('energy center (eV):', energy_cen) roi_cen = energy_cen / 10. #converting energy center position from keV to eV, then to channel number roi_l = round(roi_cen - roisize / 10 / 2) roi_h = round(roi_cen + roisize / 10 / 2) print('roi center:', roi_cen) print('roi lower bound:', roi_l, ' (', roi_l * 10, ' eV )') print('roi higher bound:', roi_h, ' (', roi_h * 10, ' eV )') if roi_l <= 0: raise Exception('Lower roi bound is at or less than zero.') if roi_h >= 2048: raise Exception('Higher roi bound is at or larger than 2048.') if multilineroi_flag is True: print('lowest emission line to roi lower bound:', line_l - roi_l * 10, 'eV') print('highest emission line to roi higher bound:', line_h - roi_h * 10, 'eV') if roi_l * 10 - line_l > 0: print( 'Warning: window does not cover the lower emission line. Consider making roisize larger.\n', 'currently the window lower bound is higher than lower emission line by ', roi_l * 10 - line_l, 'eV') if line_h - roi_h * 10 > 0: print( 'Warning: window does not cover the higher emission line. Consider making roisize larger.\n', 'currently the window higher bound is less than higher emission line by ', line_h - roi_h * 10, 'eV') #set up roi values if roi is 1: xs.channel1.rois.roi01.bin_low.set(roi_l) xs.channel1.rois.roi01.bin_high.set(roi_h) xs.channel2.rois.roi01.bin_low.set(roi_l) xs.channel2.rois.roi01.bin_high.set(roi_h) xs.channel3.rois.roi01.bin_low.set(roi_l) xs.channel3.rois.roi01.bin_high.set(roi_h) elif roi is 2: xs.channel1.rois.roi02.bin_low.set(roi_l) xs.channel1.rois.roi02.bin_high.set(roi_h) xs.channel2.rois.roi02.bin_low.set(roi_l) xs.channel2.rois.roi02.bin_high.set(roi_h) xs.channel3.rois.roi02.bin_low.set(roi_l) xs.channel3.rois.roi02.bin_high.set(roi_h) elif roi is 3: xs.channel1.rois.roi03.bin_low.set(roi_l) xs.channel1.rois.roi03.bin_high.set(roi_h) xs.channel2.rois.roi03.bin_low.set(roi_l) xs.channel2.rois.roi03.bin_high.set(roi_h) xs.channel3.rois.roi03.bin_low.set(roi_l) xs.channel3.rois.roi03.bin_high.set(roi_h) else: print('cannot set roi values; roi = 1, 2, or 3')
"""Example of using various xraylib functionality in python.""" import xraylib import math import numpy as np xraylib.XRayInit() 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))) cdtest = xraylib.CompoundParser("Ca(HCO3)2") print("Ca(HCO3)2 contains {} atoms, {} elements and has a molar mass of {} g/mol".format(cdtest['nAtomsAll'], cdtest['nElements'], cdtest['molarMass'])) for i in range(cdtest['nElements']): print("Element {}: {} % and {} atoms".format(cdtest['Elements'][i], cdtest['massFractions'][i]*100.0, cdtest['nAtoms'][i])) cdtest = xraylib.CompoundParser("SiO2") print("SiO2 contains {} atoms, {} elements and has a molar mass of {} g/mol".format(cdtest['nAtomsAll'], cdtest['nElements'], cdtest['molarMass']))
for node in xray_nodes: xray_intensity = node.xpath("td[2]/text()")[0] line = node.xpath("td[3]/text()")[0] line = line.replace(Z_xray, "") line_major = line.upper() line_minor = node.xpath("td[3]/sub/*/text()")[0].upper() try: line_micro = node.xpath("td[3]/sub/text()")[0].upper() except IndexError: line_micro = "" line = line_major + line_minor + line_micro + "_LINE" line = line.strip() print("line: {}".format(line)) try: xray_intensity = float(xray_intensity) xray_energy = xrl.LineEnergy(nuclideDataSingle['Z_xray'], getattr(xrl, line)) if xray_energy == 0.0: raise Exception("LineEnergy not found for {} {}", nuclideDataSingle['Z_xray'], line) print("Energies: {} {}".format( node.xpath("td[1]/text()")[0], xray_energy)) xray_intensities.append("{:g}".format(xray_intensity / 100.0)) xray_lines.append(line) except Exception as e: print("Exception: " + str(e)) nuclideDataSingle['nXrays'] = len(xray_intensities) print("nXrays: {}".format(nuclideDataSingle['nXrays'])) nuclideDataSingle['xrayIntensities'] = xray_intensities nuclideDataSingle['xrayLines'] = xray_lines
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 ####")