sloth.utils: utilities
sloth.utils.bragg: Bragg’s law
braggutils: utilities around the Bragg’s law ($ n lambda = 2 d sin heta $)
- sloth.utils.bragg.ev2wlen(energy)[source]
convert photon energy (E, eV) to wavelength ($lambda$, AA$^{-1}$)
- sloth.utils.bragg.wlen2ev(wlen)[source]
convert photon wavelength ($lambda$, AA$^{-1}$) to energy (E, eV)
- sloth.utils.bragg.kev2wlen(energy)[source]
convert photon energy (E, keV) to wavelength ($lambda$, AA$^{-1}$)
- sloth.utils.bragg.wlen2kev(wlen)[source]
convert photon wavelength ($lambda$, AA$^{-1}$) to energy (E, keV)
- sloth.utils.bragg.kev2ang(ene, d=0, deg=True)[source]
energy (keV) to Bragg angle (deg/rad) for given d-spacing (AA)
- sloth.utils.bragg.ang2kev(theta, d=0, deg=True)[source]
Bragg angle (deg/rad) to energy (keV) for given d-spacing (AA)
- sloth.utils.bragg.bragg_ev(theta, d, n=1)[source]
return the Bragg energy (eV) for a given d-spacing (AA) and angle (deg)
- sloth.utils.bragg.theta_b(wlen, d, n=1)[source]
return the Bragg angle, $ heta_{B}$, (deg) for a given wavelength (AA$^{-1}$) and d-spacing (AA)
- sloth.utils.bragg.bragg_th(ene, d, n=1)[source]
return the Bragg angle, $ heta_{B}$, (deg) for a given energy (eV) and d-spacing (AA)
- sloth.utils.bragg.xray_bragg(element, line, dspacing, retAll=False)[source]
return the Bragg angle for a given element/line and crystal d-spacing
- sloth.utils.bragg.de_bragg(theta, dth)[source]
energy resolution $ rac{Delta E}{E}$ from derivative of Bragg’s law
$|
rac{Delta E}{E}| = | rac{Delta heta}{ heta} = Delta heta cot( heta)|$
- sloth.utils.bragg.d_orthorhombic(a, b, c, hkl, **kws)[source]
d-spacing for an orthorhombic lattice
- sloth.utils.bragg.d_monoclinic(a, b, c, beta, hkl, **kws)[source]
d-spacing for a monoclinic lattice
- sloth.utils.bragg.d_triclinic(a, b, c, alpha, beta, gamma, hkl, **kws)[source]
d-spacing for a triclinic lattice
- sloth.utils.bragg.get_dspacing(mat, hkl)[source]
get d-spacing for Si or Ge and given reflection (hkl)
- sloth.utils.bragg.findhkl(energy=None, thetamin=65.0, crystal='all', retAll=False, retBest=False, verbose=True)[source]
findhkl: for a given energy (eV) finds the Si and Ge reflections with relative Bragg angle
Usage
findhkl(energy, thetamin, crystal, return_flag)
energy (eV) [required] thetamin (deg) [optional, default: 65 deg] crystal (‘Si’, ‘Ge’, ‘all’) [optional, default: ‘all’]
Output
String: “Crystal(hkl), Bragg angle (deg)”
if retBest: returns a list with the crystal with the highest Bragg angle only if retAll: list of lists [“crystal”, h, k, l, bragg_angle_deg, “Crystal(hkl)”]
sloth.utils.arrays: working with arrays
Arrays manipulation utilities
Basic array manipulation using Numpy & Scipy
- sloth.utils.arrays.lists_to_matrix(data, axis=None, **kws)[source]
Convert two lists of 1D arrays to a 2D matrix
- Parameters:
data (list of lists of 1D arrays) –
- [
[x1, … xN] [z1, … zN]
]
axis (None or array 1D, optional) – a reference axis used for the interpolation [None -> xdats[0]]
**kws (optional) – keyword arguments for scipy.interpolate.interp1d()
- Returns:
axis, outmat
- Return type:
arrays
- sloth.utils.arrays.curves_to_matrix(curves, axis=None, **kws)[source]
Convert a list of curves to a 2D data matrix
- Parameters:
curves (list of lists) –
Curves format is the following: [
[x1, y1, label1, info1], … [xN, yN, labelN, infoN]
]
axis (None or array 1D, optional) – a reference axis used for the interpolation [None -> curves[0][0]]
**kws (optional) – keyword arguments for func:scipy.interpolate.interp1d
- Returns:
axis, outmat
- Return type:
arrays
- sloth.utils.arrays.sum_arrays_1d(data, axis=None, **kws)[source]
Sum list of 1D arrays or curves by interpolation on a reference axis
- Parameters:
data (lists of lists) –
data_fmt (str) – define data format - “curves” ->
curves_to_matrix()- “lists” ->curves_to_matrix()
- Returns:
axis, zsum
- Return type:
1D arrays
- sloth.utils.arrays.avg_arrays_1d(data, axis=None, weights=None, **kws)[source]
Average list of 1D arrays or curves by interpolation on a reference axis
- Parameters:
data (lists of lists) –
data_fmt (str) – define data format - “curves” ->
curves_to_matrix()- “lists” ->curves_to_matrix()weights (None or array) – weights for the average
- Returns:
axis, zavg – np.average(zdats)
- Return type:
1D arrays
- sloth.utils.arrays.merge_arrays_1d(data, method='average', axis=None, weights=None, **kws)[source]
Merge a list of 1D arrays by interpolation on a reference axis
- Parameters:
data (lists of lists) –
data_fmt (str) – define data format - “curves” ->
curves_to_matrix()- “lists” ->curves_to_matrix()axis (None or array 1D, optional) – a reference axis used for the interpolation [None -> xdats[0]]
method (str, optional) –
- method used to merge, available methods are:
”average” : uses np.average()
”sum” : uses np.sum()
weights (None or array 1D, optional) – used if method == “average”
- Returns:
axis, zmrg – merge(zdats)
- Return type:
1D arrays
- sloth.utils.arrays.rebin_piecewise_constant(x1, y1, x2)[source]
Rebin histogram values y1 from old bin edges x1 to new edges x2.
Code taken from: https://github.com/jhykes/rebin/blob/master/rebin.py
It follows the procedure described in Figure 18.13 (chapter 18.IV.B. Spectrum Alignment, page 703) of Knoll [1]
References
- [1] Glenn Knoll, Radiation Detection and Measurement, third edition,
Wiley, 2000.
- Parameters:
x1 (-) –
y1 (-) – This is the total number in each bin, not an average.
x2 (-) –
- Returns:
- y2
- Return type:
n array of rebinned histogram values.
sloth.utils.pymca: working with PyMca5
sloth.utils.files: files
### FILES ###
- sloth.utils.files.cp_replace(grepfns, grepstr, rplstr, splitstr='_')[source]
given a filenames search string, copy the files with replaced string
- Parameters:
grepfns (string) – search string passed to glob to generate files list to copy
grepstr (string) – string to replace
rplstr (string) – new string
splitstr (string, '_') – string used as separator
- sloth.utils.files.get_fnames(grepstr, rpath='/home/docs/checkouts/readthedocs.org/user_builds/xraysloth/checkouts/latest/docs/source', substr1=None)[source]
get a list of filenames
- Parameters:
grepstr (pattern according to the rules used by the Unix shell) –
- Keyword Arguments:
rpath ([os.getcwd()] root path) –
substr1 ([None] if given, search first level of subdirs) –
sloth.utils.strings: strings
Simple utilities working with strings
Note
each function has its own imports and checks.
- sloth.utils.strings.colorstr(instr, color='green', on_color=None, attrs=['bold'])[source]
colorized string
- Parameters:
color (str, 'green') – Available text colors: ‘red’, ‘green’, ‘yellow’, ‘blue’, ‘magenta’, ‘cyan’, ‘white’
on_color (str, None) – Available text highlights: ‘on_red’, ‘on_green’, ‘on_yellow’, ‘on_blue’, ‘on_magenta’, ‘on_cyan’, ‘on_white’
attrs (list of str, ['bold']) – Available attributes: ‘bold’, ‘dark’, ‘underline’, ‘blink’, ‘reverse’, ‘concealed’
- sloth.utils.strings.str2rng(rngstr, keeporder=True, rebin=None)[source]
Convert a string to a range of intergers
Description
This utility converts a string representing list or range of intergers (=scans) to a sorted list of integers
- param rngstr:
Strig following a given syntax (see Example below)
- type rngstr:
str
- param keeporder:
Control the order output [True -> keep the original order] keeporder=False -> turn into a sorted list
- type keeporder:
boolean
- param rebin:
if set, force rebinning of the final range [None] .. note: useful for selecting scans every a given bunch.
- type rebin:
int
Example
> _str2rng(‘100, 7:9, 130:140:5, 14, 16:18:1’) > [7, 8, 9, 14, 16, 17, 18, 100, 130, 135, 140]
- sloth.utils.strings.natural_keys(text)[source]
FROM: https://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside
alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy’s implementation in the comments)
Usage
- alist=[
“something1”, “something12”, “something17”, “something2”, “something25”, “something29”]
alist.sort(key=natural_keys) print(alist)
- sloth.utils.strings.slice_func(list_in, filter_str=None)[source]
Utility to slice a list with a function of string parameter
- Parameters:
list_in (list) – input string to slice
filter_str (None or str) – filter to apply represented by a string [None -> no filter, input list]
- Returns:
- Return type:
Sliced list
sloth.utils.logging: loggers
Handling loggers
sloth.utils.exceptions: handling exceptions
Handling exceptions
sloth.utils.xdata: x-ray databases
Utility to retrieve x-ray data from external libraries/databases
Available libraries/dbs and order of usage
Note
XrayDB has its own package now
- sloth.utils.xdata.SHELLS = ('K', 'L1', 'L2', 'L3', 'M1', 'M2', 'M3', 'M4', 'M5', 'N1', 'N2', 'N3', 'N4', 'N5', 'N6', 'N7', 'O1', 'O2', 'O3', 'O4', 'O5', 'P1', 'P2', 'P3')
SHELLS / EDGES K = 1 (s) L = 2 (s, p) M = 3 (s, p, d) N = 4 (s, p, d, f) O = 5 (s, p, d, f) P = 6 (s, p)
- sloth.utils.xdata.LEVELS_DICT = {'K': '1s', 'L1': '2s', 'L2': '2p1/2', 'L3': '2p3/2', 'M1': '3s', 'M2': '3p1/2', 'M3': '3p3/2', 'M4': '3d3/2', 'M5': '3d5/2', 'N1': '4s', 'N2': '4p1/2', 'N3': '4p3/2', 'N4': '4d3/2', 'N5': '4d5/2', 'N6': '4f5/2', 'N7': '4f7/2', 'O1': '5s', 'O2': '5p1/2', 'O3': '5p3/2', 'P1': '6s', 'P2': '6p1/2', 'P3': '6p3/2'}
TRANSITIONS 1 = s 2, 3 = p (1/2, 3/2) 4, 5 = d (3/2, 5/2) 6, 7 = f (5/2, 7/2)
- sloth.utils.xdata.LINES_DICT = {'K': ('KA1', 'KA2', 'KA3', 'KB1', 'KB2', 'KB3', 'KB4', 'KB5'), 'L1': ('LB3', 'LB4', 'LG2', 'LG3'), 'L2': ('LB1', 'LG1', 'LG6', 'LE'), 'L3': ('LA1', 'LA2', 'LB2', 'LB5', 'LB6', 'LL'), 'M3': ('MG',), 'M4': ('MB',), 'M5': ('MA1', 'MA2')}
dictionary of lines Ln in Hepheastus is LE in Xraylib Mz in Hepheastus not in Xraylib (the single transitions yes!)
- sloth.utils.xdata.mapLine2Trans(line)[source]
returns a tuple of strings mapping the transitions for a given line
- sloth.utils.xdata.find_edge(emin, emax, shells=None)[source]
Get the edge energy in a given energy range [emin, emax] (eV)
- Parameters:
emax (emin,) – energy range to search for an absorption edege (eV)
shells (list of str (optional)) – list of shells to search for [None -> use SHELLS (=all)]
- sloth.utils.xdata.find_line(emin, emax, elements=None, lines=None, outDict=False, backend='xraylib', skip_zero_width=True, thetamin=65)[source]
Get the emission line energy in a given energy range [emin,emax] (eV)
- Parameters:
emax (emin,) – [minimum, maximum] energy range (eV)
elements (list of str (optional)) – list of elements, [None -> ELEMENTS (all)]
lines (list of str (optional)) – list of lines, [None -> LINES (all)]
outDict (boolean, False) – returns a dictionary instead of printing to screen
skip_zero_width (boolean, True) – True: if fluo_width == 0, not include in the results
- Returns:
- if outDict:
_out[‘el’]: element symbol, list of strs _out[‘eln]: element number, list of ints _out[‘ln’]: line, list of strs _out[‘en’]: energy eV, list of floats _out[‘w’] : width eV, list of floats
- else:
prints to screen the results
- Return type:
None or outDict
- sloth.utils.xdata.fluo_width(elem=None, line=None, herfd=False, showInfos=True)[source]
Get the fluorescence line width in eV
- Parameters:
elem (string or int) – absorbing element
line (string) – Siegbahn notation for emission line
- Returns:
herfd=False (default) (lw_xas + lw_xes)
herfd=True (1/(math.sqrt(lw_xas**2 + lw_xes**2)))
- sloth.utils.xdata.fluo_amplitude(elem, line, excitation=None, barn_unit=False)[source]
Get the fluorescence cross section for a given element/line
- Parameters:
elem (string or number) – element
line (string) – emission line Siegban (e.g. ‘LA1’) or IUPAC (e.g. ‘L3M5’)
excitation (float (optional)) – excitation energy in eV [None -> 10 keV]
barn_unit (boolean) – use units of barn/atom [None -> cm2/g]
- Returns:
- Return type:
fluo_amp (in ‘cm2/g’ or ‘barn/atom’ if barn_unit is True)
- sloth.utils.xdata.xray_line(element, line=None, initial_level=None)[source]
Get the emission energy in eV for a given element/line or level
- Parameters:
element (string or int) – absorbing element
line (string (optional)) – Siegbahn notation, e.g. ‘KA1’ [None -> LINES (all)]
initial_level (string) – initial core level, e.g. ‘K’ [None]
- Returns:
dictionary {‘line’
- Return type:
[], ‘ene’: []} or a number
- sloth.utils.xdata.xray_edge(element, initial_level=None)[source]
Get the energy edge in eV for a given element
- Parameters:
element – string or number
initial_level – string, initial core level, e.g. ‘K’ or list [None]
- Returns:
dictionary {‘edge’ : [], ‘ene’ : []} or a number
- sloth.utils.xdata.fluo_spectrum(elem, line, xwidth=3, xstep=0.05, plot=False, showInfos=True, **kws)[source]
Generate a fluorescence spectrum for a given element/line
Note
it generates a Lorentzian function with the following parameters: - center: emission energy (eV) - sigma: from FWHM of sum of atomic levels widths (XAS+XES) - amplitude: CS_FuorLine_Kissel_Cascade - xmin, xmax: center -+ xwidth*fwhm
- Parameters:
elem (string or int) – absorbing element
line (string) – emission line Siegban (e.g. ‘LA1’) or IUPAC (e.g. ‘L3M5’)
xwidth (int or float (optional)) – FWHM multiplication factor to establish xmin, xmax range (= center -+ xwidth*fwhm) [3]
xstep (float (optional)) – energy step in eV [0.05]
showInfos (boolean (optional)) – print the info dict [True]
plot (boolean (optional)) – plot the line before returning it [False]
**kws (keyword arguments for
fluo_width(),fluo_amplitude()) –
- Returns:
xfluo, yfluo, info
- Return type:
XY arrays of floats, dictionary
- sloth.utils.xdata.fluo_lines(elem, lines, retAll=False, **fluokws)[source]
Generate a cumulative emission spectrum of a given element and list of lines
- Parameters:
elem (string or int) –
lines (list of str) – emission lines as Siegban (e.g. ‘LA1’) or IUPAC (e.g. ‘L3M5’)
**fluokws (keyword arguments for
fluo_spectrum()) –
- Returns:
xcom, ycom (arrays of floats) – energy/intensity of the whole spectrum
if retAll – xcom, ycom, [xi, yi, ii]