Developers Corner¶
XRStools.roifinder_and_gui
Module¶
XRStools.xrs_utilities
Module¶
- XRStools.xrs_utilities.HRcorrect(pzprofile, occupation, q)[source]¶
Returns the first order correction to filled 1s, 2s, and 2p Compton profiles.
Implementation after Holm and Ribberfors (citation …).
- Args:
pzprofile (np.array): Compton profile (e.g. tabulated from Biggs) to be corrected (2D matrix).
occupation (list): electron configuration.
q (float or np.array): momentum transfer in [a.u.].
- Returns:
asymmetry (np.array): asymmetries to be added to the raw profiles (normalized to the number of electrons on pz scale)
- XRStools.xrs_utilities.NNMFcost(x, A, F, C, F_up, C_up, n, k, m)[source]¶
NNMFcost Returns cost and gradient for NNMF with constraints.
- XRStools.xrs_utilities.NNMFcost_old(x, A, W, H, W_up, H_up)[source]¶
NNMFcost Returns cost and gradient for NNMF with constraints.
- XRStools.xrs_utilities.Rx(chi, degrees=True)[source]¶
Rx Rotation matrix for vector rotations around the [1,0,0]-direction.
- Args:
chi (float) : Angle of rotation.
degrees(bool) : Angle given in radians or degrees.
- Returns:
3x3 rotation matrix.
- XRStools.xrs_utilities.Ry(phi, degrees=True)[source]¶
Ry Rotation matrix for vector rotations around the [0,1,0]-direction.
- Args:
phi (float) : Angle of rotation.
degrees(bool) : Angle given in radians or degrees.
- Returns:
3x3 rotation matrix.
- XRStools.xrs_utilities.Rz(omega, degrees=True)[source]¶
Rz Rotation matrix for vector rotations around the [0,0,1]-direction.
- Args:
omega (float) : Angle of rotation.
degrees(bool) : Angle given in radians or degrees.
- Returns:
3x3 rotation matrix.
- XRStools.xrs_utilities.TTsolver1D(el_energy, hkl=[6, 6, 0], crystal='Si', R=1.0, dev=array([- 50., - 49., - 48., - 47., - 46., - 45., - 44., - 43., - 42., - 41., - 40., - 39., - 38., - 37., - 36., - 35., - 34., - 33., - 32., - 31., - 30., - 29., - 28., - 27., - 26., - 25., - 24., - 23., - 22., - 21., - 20., - 19., - 18., - 17., - 16., - 15., - 14., - 13., - 12., - 11., - 10., - 9., - 8., - 7., - 6., - 5., - 4., - 3., - 2., - 1., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25., 26., 27., 28., 29., 30., 31., 32., 33., 34., 35., 36., 37., 38., 39., 40., 41., 42., 43., 44., 45., 46., 47., 48., 49., 50., 51., 52., 53., 54., 55., 56., 57., 58., 59., 60., 61., 62., 63., 64., 65., 66., 67., 68., 69., 70., 71., 72., 73., 74., 75., 76., 77., 78., 79., 80., 81., 82., 83., 84., 85., 86., 87., 88., 89., 90., 91., 92., 93., 94., 95., 96., 97., 98., 99., 100., 101., 102., 103., 104., 105., 106., 107., 108., 109., 110., 111., 112., 113., 114., 115., 116., 117., 118., 119., 120., 121., 122., 123., 124., 125., 126., 127., 128., 129., 130., 131., 132., 133., 134., 135., 136., 137., 138., 139., 140., 141., 142., 143., 144., 145., 146., 147., 148., 149.]), alpha=0.0, chitable_prefix='/home/christoph/sources/XRStools/data/chitables/chitable_')[source]¶
TTsolver Solves the Takagi-Taupin equation for a bent crystal.
This function is based on a Matlab implementation by S. Huotari of M. Krisch’s Fortran programs.
- Args:
el_energy (float): Fixed nominal (working) energy in keV.
hkl (array): Reflection order vector, e.g. [6, 6, 0]
crystal (str): Crystal used (can be silicon ‘Si’ or ‘Ge’)
R (float): Crystal bending radius in m.
dev (np.array): Deviation parameter (in arc. seconds) for which the reflectivity curve should be calculated.
alpha (float): Crystal assymetry angle.
- Returns:
refl (np.array): Reflectivity curve.
e (np.array): Deviation from Bragg angle in meV.
dev (np.array): Deviation from Bragg angle in microrad.
- XRStools.xrs_utilities.absCorrection(mu1, mu2, alpha, beta, samthick, geometry='transmission')[source]¶
absCorrection
Calculates absorption correction for given mu1 and mu2. Multiply the measured spectrum with this correction factor. This is a translation of Keijo Hamalainen’s Matlab function (KH 30.05.96).
- Args
mu1 : np.array Absorption coefficient for the incident energy in [1/cm].
mu2 : np.array Absorption coefficient for the scattered energy in [1/cm].
alpha : float Incident angle relative to plane normal in [deg].
beta : float Exit angle relative to plane normal [deg].
samthick : float Sample thickness in [cm].
geometry : string, optional Key word for different sample geometries (‘transmission’, ‘reflection’, ‘sphere’). If geometry is set to ‘sphere’, no angular dependence is assumed.
- Returns
ac : np.array Absorption correction factor. Multiply this with your measured spectrum.
- XRStools.xrs_utilities.abscorr2(mu1, mu2, alpha, beta, samthick)[source]¶
Calculates absorption correction for given mu1 and mu2. Multiply the measured spectrum with this correction factor.
This is a translation of Keijo Hamalainen’s Matlab function (KH 30.05.96).
- Args:
mu1 (np.array): absorption coefficient for the incident energy in [1/cm].
mu2 (np.array): absorption coefficient for the scattered energy in [1/cm].
alpha (float): incident angle relative to plane normal in [deg].
beta (float): exit angle relative to plane normal [deg] (for transmission geometry use beta < 0).
samthick (float): sample thickness in [cm].
- Returns:
ac (np.array): absorption correction factor. Multiply this with your measured spectrum.
- XRStools.xrs_utilities.addch(xold, yold, n, n0=0, errors=None)[source]¶
# ADDCH Adds contents of given adjacent channels together # # [x2,y2] = addch(x,y,n,n0) # x = original x-scale (row or column vector) # y = original y-values (row or column vector) # n = number of channels to be summed up # n0 = offset for adding, default is 0 # x2 = new x-scale # y2 = new y-values # # KH 17.09.1990 # Modified 29.05.1995 to include offset
- XRStools.xrs_utilities.bidiag_reduction(A)[source]¶
function [U,B,V]=bidiag_reduction(A) % [U B V]=bidiag_reduction(A) % Algorithm 6.5-1 in Golub & Van Loan, Matrix Computations % Johns Hopkins University Press % Finds an upper bidiagonal matrix B so that A=U*B*V’ % with U,V orthogonal. A is an m x n matrix
- XRStools.xrs_utilities.bootstrapCNNMF(A, F_ini, C_ini, F_up, C_up, Niter)[source]¶
bootstrapCNNMF Constrained non-negative matrix factorization with bootstrapping for error estimates.
- XRStools.xrs_utilities.bootstrapCNNMF_old(A, k, Aerr, F_ini, C_ini, F_up, C_up, Niter=100)[source]¶
bootstrapCNNMF Constrained non-negative matrix factorization with bootstrapping for error estimates.
- XRStools.xrs_utilities.bragg(hkl, e, xtal='Si')[source]¶
% BRAGG Calculates Bragg angle for given reflection in RAD % output=bangle(hkl,e,xtal) % hkl can be a matrix i.e. hkl=[1,0,0 ; 1,1,1]; % e=energy in keV % xtal=’Si’, ‘Ge’, etc. (check dspace.m) or d0 (Si default) % % KH 28.09.93 %
- class XRStools.xrs_utilities.bragg_refl(crystal, hkl, alpha=0.0)[source]¶
Bases:
object
Dynamical theory of diffraction.
- XRStools.xrs_utilities.braggd(hkl, e, xtal='Si')[source]¶
# BRAGGD Calculates Bragg angle for given reflection in deg # Call BRAGG.M # output=bangle(hkl,e,xtal) # hkl can be a matrix i.e. hkl=[1,0,0 ; 1,1,1]; # e=energy in keV # xtal=’Si’, ‘Ge’, etc. (check dspace.m) or d0 (Si default) # # KH 28.09.93
- XRStools.xrs_utilities.cixsUBgetQ_primo(tthv, tthh, psi)[source]¶
returns the Q0 given the detector position (tthv, tth) and th crystal orientation. This orientation is calculated considering :
- the Bragg condition and the rotation around the G vector :
this rotation is defined by psi which is a rotation around G
- XRStools.xrs_utilities.constrained_mf(A, W_ini, W_up, coeff_ini, coeff_up, maxIter=1000, tol=1e-08, maxIter_power=1000)[source]¶
cfactorizeOffDiaMatrix constrained version of factorizeOffDiaMatrix Returns main components from an off-diagonal Matrix (energy-loss x angular-departure).
- XRStools.xrs_utilities.constrained_svd(M, U_ini, S_ini, VT_ini, U_up, max_iter=10000, verbose=False)[source]¶
constrained_nnmf Approximate singular value decomposition with constraints.
function [U, S, V] = constrained_svd(M,U_ini,S_ini,V_ini,U_up,max_iter=10000,verbose=False)
- XRStools.xrs_utilities.convertSplitEDF2EDF(foldername)[source]¶
converts the old style EDF files (one image for horizontal and one image for vertical chambers) to the new style EDF (one single image).
- Arg:
- foldername (str): Path to folder with all the EDF-files to be
converted.
- XRStools.xrs_utilities.convg(x, y, fwhm)[source]¶
Convolution with Gaussian x = x-vector y = y-vector fwhm = fulll width at half maximum of the gaussian with which y is convoluted
- XRStools.xrs_utilities.convtoprim(hklconv)[source]¶
convtoprim converts diamond structure reciprocal lattice expressed in conventional lattice vectors to primitive one (Helsinki -> Palaiseau conversion) from S. Huotari
- XRStools.xrs_utilities.cshift(w1, th)[source]¶
cshift Calculates Compton peak position.
- Args:
w1 (float, array): Incident energy in [keV].
th (float): Scattering angle in [deg].
- Returns:
w2 (foat, array): Energy of Compton peak in [keV].
Funktion adapted from Keijo Hamalainen.
- XRStools.xrs_utilities.delE_JohannAberration(E, A, R, Theta)[source]¶
Calculates the Johann aberration of a spherical analyzer crystal.
- Args:
E (float): Working energy in [eV]. A (float): Analyzer aperture [mm]. R (float): Radius of the Rowland circle [mm]. Theta (float): Analyzer Bragg angle [degree].
- Returns:
Johann abberation in [eV].
- XRStools.xrs_utilities.delE_dicedAnalyzerIntrinsic(E, Dw, Theta)[source]¶
Calculates the intrinsic energy resolution of a diced crystal analyzer.
- Args:
E (float): Working energy in [eV]. Dw (float): Darwin width of the used reflection [microRad]. Theta (float): Analyzer Bragg angle [degree].
- Returns:
Intrinsic energy resolution of a perfect analyzer crystal.
- XRStools.xrs_utilities.delE_offRowland(E, z, A, R, Theta)[source]¶
Calculates the off-Rowland contribution of a spherical analyzer crystal.
- Args:
E (float): Working energy in [eV]. z (float): Off-Rowland distance [mm]. A (float): Analyzer aperture [mm]. R (float): Radius of the Rowland circle [mm]. Theta (float): Analyzer Bragg angle [degree].
- Returns:
Off-Rowland contribution in [eV] to the energy resolution.
- XRStools.xrs_utilities.delE_pixelSize(E, p, R, Theta)[source]¶
Calculates the pixel size contribution to the resolution function of a diced analyzer crystal.
- Args:
E (float): Working energy in [eV]. p (float): Pixel size in [mm]. R (float): Radius of the Rowland circle [mm]. Theta (float): Analyzer Bragg angle [degree].
- Returns:
Pixel size contribution in [eV] to the energy resolution for a diced analyzer crystal.
- XRStools.xrs_utilities.delE_sourceSize(E, s, R, Theta)[source]¶
Calculates the source size contribution to the resolution function.
- Args:
E (float): Working energy in [eV]. s (float): Source size in [mm]. R (float): Radius of the Rowland circle [mm]. Theta (float): Analyzer Bragg angle [degree].
- Returns:
Source size contribution in [eV] to the energy resolution.
- XRStools.xrs_utilities.delE_stressedCrystal(E, t, v, R, Theta)[source]¶
Calculates the stress induced contribution to the resulution function of a spherically bent crystal analyzer.
- Args:
E (float): Working energy in [eV]. t (float): Absorption length in the analyzer material [mm]. v (float): Poisson ratio of the analyzer material. R (float): Radius of the Rowland circle [mm]. Theta (float): Analyzer Bragg angle [degree].
- Returns:
Stress-induced contribution in [eV] to the energy resolution.
- XRStools.xrs_utilities.diode(current, energy, thickness=0.03)[source]¶
diode Calculates the number of photons incident for a Si PIPS diode.
- Args:
current (float): Diode current in [pA].
energy (float): Photon energy in [keV].
thickness (float): Thickness of Si active layer in [cm].
- Returns:
flux (float): Number of photons per second.
Function adapted from Matlab function by S. Huotari.
- XRStools.xrs_utilities.dspace(hkl=[6, 6, 0], xtal='Si')[source]¶
% DSPACE Gives d-spacing for given xtal % d=dspace(hkl,xtal) % hkl can be a matrix i.e. hkl=[1,0,0 ; 1,1,1]; % xtal=’Si’,’Ge’,’LiF’,’InSb’,’C’,’Dia’,’Li’ (case insensitive) % if xtal is number this is user as a d0 % % KH 28.09.93 % SH 2005 %
- class XRStools.xrs_utilities.dtxrd(hkl, energy, crystal='Si', asym_angle=0.0, angular_range=[- 0.0005, 0.0005], angular_step=1e-08)[source]¶
Bases:
object
class to hold all things dynamic theory of diffraction.
- XRStools.xrs_utilities.dtxrd_anomalous_absorption(energy, hkl, alpha=0.0, crystal='Si', angular_range=array([- 0.0005]))[source]¶
- XRStools.xrs_utilities.dtxrd_reflectivity(energy, hkl, alpha=0.0, crystal='Si', angular_range=array([- 0.0005]))[source]¶
- XRStools.xrs_utilities.e2pz(w1, w2, th)[source]¶
Calculates the momentum scale and the relativistic Compton cross section correction according to P. Holm, PRA 37, 3706 (1988).
This function is translated from Keijo Hamalainen’s Matlab implementation (KH 29.05.96).
- Args:
w1 (float or np.array): incident energy in [keV]
w2 (float or np.array): scattered energy in [keV]
th (float): scattering angle two theta in [deg]
- returns:
pz (float or np.array): momentum scale in [a.u.]
cf (float or np.array): cross section correction factor such that: J(pz) = cf * d^2(sigma)/d(w2)*d(Omega) [barn/atom/keV/srad]
- XRStools.xrs_utilities.edfread(filename)[source]¶
reads edf-file with filename “filename” OUTPUT: data = 256x256 numpy array
- XRStools.xrs_utilities.edfread_test(filename)[source]¶
reads edf-file with filename “filename” OUTPUT: data = 256x256 numpy array
here is how i opened the HH data: data = np.fromfile(f,np.int32) image = np.reshape(data,(dim,dim))
- XRStools.xrs_utilities.element(z)[source]¶
Converts atomic number into string of the element symbol and vice versa.
Returns atomic number of given element, if z is a string of the element symbol or string of element symbol of given atomic number z.
- Args:
z (string or int): string of the element symbol or atomic number.
- Returns:
Z (string or int): string of the element symbol or atomic number.
- XRStools.xrs_utilities.energy(d, ba)[source]¶
% ENERGY Calculates energy corrresponing to Bragg angle for given d-spacing % function e=energy(dspace,bragg_angle) % % dspace for reflection % bragg_angle in DEG % % KH 28.09.93
- XRStools.xrs_utilities.energy_monoangle(angle, d=1.6374176589984608)[source]¶
% ENERGY Calculates energy corrresponing to Bragg angle for given d-spacing % function e=energy(dspace,bragg_angle) % % dspace for reflection (defaulf for Si(311) reflection) % bragg_angle in DEG % % KH 28.09.93 %
- XRStools.xrs_utilities.fermi(rs)[source]¶
fermi Calculates the plasmon energy (in eV), Fermi energy (in eV), Fermi momentum (in a.u.), and critical plasmon cut-off vector (in a.u.).
- Args:
rs (float): electron separation parameter
- Returns:
wp (float): plasmon energy (in eV)
ef (float): Fermi energy (in eV)
kf (float): Fermi momentum (in a.u.)
kc (float): critical plasmon cut-off vector (in a.u.)
Based on Matlab function from A. Soininen.
- XRStools.xrs_utilities.find_center_of_mass(x, y)[source]¶
Returns the center of mass (first moment) for the given curve y(x)
- XRStools.xrs_utilities.find_diag_angles(q, x0, U, B, Lab, beam_in, lambdai, lambdao, tol=1e-08, method='BFGS')[source]¶
find_diag_angles Finds the FOURC spectrometer and sample angles for a desired q.
- Args:
q (array): Desired momentum transfer in Lab coordinates.
x0 (list): Guesses for the angles (tthv, tthh, chi, phi, omega).
U (array): 3x3 U-matrix Lab-to-sample transformation.
B (array): 3x3 B-matrix reciprocal lattice to absolute units transformation.
lambdai (float): Incident x-ray wavelength in Angstrom.
lambdao (float): Scattered x-ray wavelength in Angstrom.
tol (float): Toleranz for minimization (see scipy.optimize.minimize)
method (str): Method for minimization (see scipy.optimize.minimize)
- Returns:
ans (array): tthv, tthh, phi, chi, omega
- XRStools.xrs_utilities.fwhm(x, y)[source]¶
finds full width at half maximum of the curve y vs. x returns f = FWHM x0 = position of the maximum
- XRStools.xrs_utilities.get_UB_Q(tthv, tthh, phi, chi, omega, **kwargs)[source]¶
get_UB_Q Returns the momentum transfer and scattering vectors for given FOURC spectrometer and sample angles. U-, B-matrices and incident/scattered wavelength are passed as keyword-arguments.
- Args:
tthv (float): Spectrometer vertical 2Theta angle.
tthh (float): Spectrometer horizontal 2Theta angle.
chi (float): Sample rotation around x-direction.
phi (float): Sample rotation around y-direction.
omega (float): Sample rotation around z-direction.
- kwargs (dict): Dictionary with key-word arguments:
kwargs[‘U’] (array): 3x3 U-matrix Lab-to-sample transformation.
kwargs[‘B’] (array): 3x3 B-matrix reciprocal lattice to absolute units transformation.
kwargs[‘lambdai’] (float): Incident x-ray wavelength in Angstrom.
kwargs[‘lambdao’] (float): Scattered x-ray wavelength in Angstrom.
- Returns:
Q_sample (array): Momentum transfer in sample coordinates.
Ki_sample (array): Incident beam direction in sample coordinates.
Ko_sample (array): Scattered beam direction in sample coordinates.
- XRStools.xrs_utilities.get_gnuplot_rgb(start=None, end=None, length=None)[source]¶
get_gnuplot_rgb Prints out a progression of RGB hex-keys to use in Gnuplot.
- Args:
start (array): RGB code to start from (must be numbers out of [0,1]).
end (array): RGB code to end at (must be numbers out of [0,1]).
length (int): How many colors to print out.
- XRStools.xrs_utilities.get_num_of_MD_steps(time_ps, time_step)[source]¶
Calculates the number of steps in an MD simulation for a desired time (in ps) and given step size (in a.u.)
- Args:
time_ps (float): Desired time span (ps). time_step (float): Chosen time step (a.u.).
- Returns:
The number of steps required to span the desired time span.
- XRStools.xrs_utilities.getpenetrationdepth(energy, formulas, concentrations, densities)[source]¶
returns the penetration depth of a mixture of chemical formulas with certain concentrations and densities
- XRStools.xrs_utilities.gettransmission(energy, formulas, concentrations, densities, thickness)[source]¶
returns the transmission through a sample composed of chemical formulas with certain densities mixed to certain concentrations, and a thickness
- XRStools.xrs_utilities.hlike_Rwfn(n, l, r, Z)[source]¶
hlike_Rwfn Returns an array with the radial part of a hydrogen-like wave function.
- Args:
n (integer): main quantum number n
l (integer): orbitalquantum number l
r (array): vector of radii on which the function should be evaluated
Z (float): effective nuclear charge
- XRStools.xrs_utilities.householder(b, k)[source]¶
function H = householder(b, k) % H = householder(b, k) % Atkinson, Section 9.3, p. 611 % b is a column vector, k an index < length(b) % Constructs a matrix H that annihilates entries % in the product H*b below index k
% $Id: householder.m,v 1.1 2008-01-16 15:33:30 mike Exp $ % M. M. Sussman
- XRStools.xrs_utilities.interpolate_M(xc, xi, yi, i0)[source]¶
Linear interpolation scheme after Martin Sundermann that conserves the absolute number of counts.
ONLY WORKS FOR EQUALLY/EVENLY SPACED XC, XI!
- Args:
xc (np.array): The x-coordinates of the interpolated values. xi (np.array): The x-coordinates of the data points, must be increasing. yi (np.array): The y-coordinates of the data points, same length as xp. i0 (np.array): Normalization values for the data points, same length as xp.
- Returns:
ic (np.array): The interpolated and normalized data points.
from scipy.interpolate import Rbf x = arange(20) d = zeros(len(x)) d[10] = 1 xc = arange(0.5,19.5) rbfi = Rbf(x, d) di = rbfi(xc)
- XRStools.xrs_utilities.is_allowed_refl_fcc(H)[source]¶
is_allowed_refl_fcc Check if given reflection is allowed for a FCC lattice.
- Args:
H (array, list, tuple): H=[h,k,l]
- Returns:
boolean
- XRStools.xrs_utilities.lindhard_pol(q, w, rs=3.93, use_corr=False, lifetime=0.28)[source]¶
lindhard_pol Calculates the Lindhard polarizability function (RPA) for certain q (a.u.), w (a.u.) and rs (a.u.).
- Args:
q (float): momentum transfer (in a.u.)
w (float): energy (in a.u.)
rs (float): electron parameter
use_corr (boolean): if True, uses Bernardo’s calculation for n(k) instead of the Fermi function.
lifetime (float): life time (default is 0.28 eV for Na).
Based on Matlab function by S. Huotari.
- XRStools.xrs_utilities.makeprofile(element, filename='/usr/lib/python3/dist-packages/XRStools/resources/data/ComptonProfiles.dat', E0=9.69, tth=35.0, correctasym=None)[source]¶
takes the profiles from ‘makepzprofile()’, converts them onto eloss scale and normalizes them to S(q,w) [1/eV] input: element = element symbol (e.g. ‘Si’, ‘Al’, etc.) filename = path and filename to tabulated profiles E0 = scattering energy [keV] tth = scattering angle [deg] returns: enscale = energy loss scale J = total CP C = only core contribution to CP V = only valence contribution to CP q = momentum transfer [a.u.]
- XRStools.xrs_utilities.makeprofile_comp(formula, filename='/usr/lib/python3/dist-packages/XRStools/resources/data/ComptonProfiles.dat', E0=9.69, tth=35, correctasym=None)[source]¶
returns the compton profile of a chemical compound with formula ‘formula’ input: formula = string of a chemical formula (e.g. ‘SiO2’, ‘Ba8Si46’, etc.) filename = path and filename to tabulated profiles E0 = scattering energy [keV] tth = scattering angle [deg] returns: eloss = energy loss scale J = total CP C = only core contribution to CP V = only valence contribution to CP q = momentum transfer [a.u.]
- XRStools.xrs_utilities.makeprofile_compds(formulas, concentrations=None, filename='/usr/lib/python3/dist-packages/XRStools/resources/data/ComptonProfiles.dat', E0=9.69, tth=35.0, correctasym=None)[source]¶
returns sum of compton profiles from a lost of chemical compounds weighted by the given concentration
- XRStools.xrs_utilities.makepzprofile(element, filename='/usr/lib/python3/dist-packages/XRStools/resources/data/ComptonProfiles.dat')[source]¶
constructs compton profiles of element ‘element’ on pz-scale (-100:100 a.u.) from the Biggs tables provided in ‘filename’
- input:
element = element symbol (e.g. ‘Si’, ‘Al’, etc.)
filename = path and filename to tabulated profiles
- returns:
pzprofile = numpy array of the CP: * 1. column: pz-scale * 2. … n. columns: compton profile of nth shell * binden = binding energies of shells * occupation = number of electrons in the according shells
- class XRStools.xrs_utilities.maxipix_det(name, spot_arrangement)[source]¶
Bases:
object
Class to store some useful values from the detectors used. To be used for arranging the ROIs.
- XRStools.xrs_utilities.momtrans_au(e1, e2, tth)[source]¶
Calculates the momentum transfer in atomic units input: e1 = incident energy [keV] e2 = scattered energy [keV] tth = scattering angle [deg] returns: q = momentum transfer [a.u.] (corresponding to sin(th)/lambda)
- XRStools.xrs_utilities.momtrans_inva(e1, e2, tth)[source]¶
Calculates the momentum transfer in inverse angstrom input: e1 = incident energy [keV] e2 = scattered energy [keV] tth = scattering angle [deg] returns: q = momentum transfer [a.u.] (corresponding to sin(th)/lambda)
- XRStools.xrs_utilities.mpr(energy, compound)[source]¶
Calculates the photoelectric, elastic, and inelastic absorption of a chemical compound.
Calculates the photoelectric, elastic, and inelastic absorption of a chemical compound.
- Args:
energy (np.array): energy scale in [keV].
compound (string): chemical sum formula (e.g. ‘SiO2’)
- Returns:
murho (np.array): absorption coefficient normalized by the density.
rho (float): density in UNITS?
m (float): atomic mass in UNITS?
- XRStools.xrs_utilities.mpr_compds(energy, formulas, concentrations, E0, rho_formu)[source]¶
Calculates the photoelectric, elastic, and inelastic absorption of a mix of compounds.
Returns the photoelectric absorption for a sum of different chemical compounds.
- Args:
energy (np.array): energy scale in [keV].
formulas (list of strings): list of chemical sum formulas
- Returns:
murho (np.array): absorption coefficient normalized by the density.
rho (float): density in UNITS?
m (float): atomic mass in UNITS?
- XRStools.xrs_utilities.myprho(energy, Z, logtablefile='/usr/lib/python3/dist-packages/XRStools/resources/data/logtable.dat')[source]¶
Calculates the photoelectric, elastic, and inelastic absorption of an element Z
Calculates the photelectric , elastic, and inelastic absorption of an element Z. Z can be atomic number or element symbol.
- Args:
energy (np.array): energy scale in [keV].
Z (string or int): atomic number or string of element symbol.
- Returns:
murho (np.array): absorption coefficient normalized by the density.
rho (float): density in UNITS?
m (float): atomic mass in UNITS?
- XRStools.xrs_utilities.odefctn(y, t, abb0, abb1, abb7, abb8, lex, sgbeta, y0, c1)[source]¶
#% [T,Y] = ODE23(ODEFUN,TSPAN,Y0,OPTIONS,P1,P2,…) passes the additional #% parameters P1,P2,… to the ODE function as ODEFUN(T,Y,P1,P2…), and to #% all functions specified in OPTIONS. Use OPTIONS = [] as a place holder if #% no options are set.
- XRStools.xrs_utilities.parseformula(formula)[source]¶
Parses a chemical sum formula.
Parses the constituing elements and stoichiometries from a given chemical sum formula.
- Args:
formula (string): string of a chemical formula (e.g. ‘SiO2’, ‘Ba8Si46’, etc.)
- Returns:
elements (list): list of strings of constituting elemental symbols.
stoichiometries (list): list of according stoichiometries in the same order as ‘elements’.
- XRStools.xrs_utilities.plotpenetrationdepth(energy, formulas, concentrations, densities)[source]¶
opens a plot window of the penetration depth of a mixture of chemical formulas with certain concentrations and densities plotted along the given energy vector
- XRStools.xrs_utilities.plottransmission(energy, formulas, concentrations, densities, thickness)[source]¶
opens a plot with the transmission plotted along the given energy vector
- XRStools.xrs_utilities.primtoconv(hklprim)[source]¶
primtoconv converts diamond structure reciprocal lattice expressed in primitive basis to the conventional basis (Palaiseau -> Helsinki conversion) from S. Huotari
- XRStools.xrs_utilities.pz2e1(w2, pz, th)[source]¶
Calculates the incident energy for a specific scattered photon and momentum value.
Returns the incident energy for a given photon energy and scattering angle. This function is translated from Keijo Hamalainen’s Matlab implementation (KH 29.05.96).
- Args:
w2 (float): scattered photon energy in [keV]
pz (np.array): pz scale in [a.u.]
th (float): scattering angle two theta in [deg]
- Returns:
w1 (np.array): incident energy in [keV]
- XRStools.xrs_utilities.read_dft_wfn(element, n, l, spin=None, directory='/usr/lib/python3/dist-packages/XRStools/resources/data')[source]¶
read_dft_wfn Parses radial parts of wavefunctions.
- Args:
element (str): Element symbol.
n (int): Main quantum number.
l (int): Orbital quantum number.
spin (str): Which spin channel, default is average over up and down.
directory (str): Path to directory where the wavefunctions can be found.
- Returns:
r (np.array): radius
wfn (np.array):
- XRStools.xrs_utilities.readbiggsdata(filename, element)[source]¶
Reads Hartree-Fock Profile of element ‘element’ from values tabulated by Biggs et al. (Atomic Data and Nuclear Data Tables 16, 201-309 (1975)) as provided by the DABAX library (http://ftp.esrf.eu/pub/scisoft/xop2.3/DabaxFiles/ComptonProfiles.dat). input: filename = path to the ComptonProfiles.dat file (the file should be distributed with this package) element = string of element name returns:
- data = the data for the according element as in the file:
#UD Columns:
#UD col1: pz in atomic units
#UD col2: Total compton profile (sum over the atomic electrons
#UD col3,…coln: Compton profile for the individual sub-shells
occupation = occupation number of the according shells
bindingen = binding energies of the accorting shells
colnames = strings of column names as used in the file
- XRStools.xrs_utilities.readfio(prefix, scannumber, repnumber=0)[source]¶
if repnumber = 0: reads a spectra-file (name: prefix_scannumber.fio) if repnumber > 1: reads a spectra-file (name: prefix_scannumber_rrepnumber.fio)
- XRStools.xrs_utilities.readp01image(filename)[source]¶
reads a detector file from PetraIII beamline P01
- XRStools.xrs_utilities.readp01scan(prefix, scannumber)[source]¶
reads a whole scan from PetraIII beamline P01 (experimental)
- XRStools.xrs_utilities.readp01scan_rep(prefix, scannumber, repetition)[source]¶
reads a whole scan with repititions from PetraIII beamline P01 (experimental)
- XRStools.xrs_utilities.savitzky_golay(y, window_size, order, deriv=0, rate=1)[source]¶
Smooth (and optionally differentiate) data with a Savitzky-Golay filter. The Savitzky-Golay filter removes high frequency noise from data. It has the advantage of preserving the original shape and features of the signal better than other types of filtering approaches, such as moving averages techniques.
- Parameters:
y : array_like, shape (N,) the values of the time history of the signal.
window_size : int the length of the window. Must be an odd integer number.
order : int the order of the polynomial used in the filtering. Must be less then window_size - 1.
deriv: int the order of the derivative to compute (default = 0 means only smoothing)
- Returns
ys : ndarray, shape (N) the smoothed signal (or it’s n-th derivative).
- Notes:
The Savitzky-Golay is a type of low-pass filter, particularly suited for smoothing noisy data. The main idea behind this approach is to make for each point a least-square fit with a polynomial of high order over a odd-sized window centered at the point.
Examples
t = np.linspace(-4, 4, 500) y = np.exp( -t**2 ) + np.random.normal(0, 0.05, t.shape) ysg = savitzky_golay(y, window_size=31, order=4) import matplotlib.pyplot as plt plt.plot(t, y, label='Noisy signal') plt.plot(t, np.exp(-t**2), 'k', lw=1.5, label='Original signal') plt.plot(t, ysg, 'r', label='Filtered signal') plt.legend() plt.show()
- References ::
- 1
A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of Data by Simplified Least Squares Procedures. Analytical Chemistry, 1964, 36 (8), pp 1627-1639.
- 2
Numerical Recipes 3rd Edition: The Art of Scientific Computing W.H. Press, S.A. Teukolsky, W.T. Vetterling, B.P. Flannery Cambridge University Press ISBN-13: 9780521880688
- XRStools.xrs_utilities.sigmainc(Z, energy, logtablefile='/usr/lib/python3/dist-packages/XRStools/resources/data/logtable.dat')[source]¶
sigmainc Calculates the Incoherent Scattering Cross Section in cm^2/g using Log-Log Fit.
- Args:
z (int or string): Element number or elements symbol.
energy (float or array): Energy (can be number or vector)
- Returns:
tau (float or array): Photoelectric cross section in [cm**2/g]
Adapted from original Matlab function of Keijo Hamalainen.
- XRStools.xrs_utilities.specread(filename, nscan)[source]¶
reads scan “nscan” from SPEC-file “filename”
- INPUT:
filename = string with the SPEC-file name
nscan = number (int) of desired scan
- OUTPUT:
data =
motors =
counters = dictionary
- XRStools.xrs_utilities.spline2(x, y, x2)[source]¶
Extrapolates the smaller and larger valuea as a constant
- XRStools.xrs_utilities.stiff_compl_matrix_Si(e1, e2, e3, ansys=False)[source]¶
stiff_compl_matrix_Si Returns stiffnes and compliance tensor of Si for a given orientation.
- Args:
e1 (np.array): unit vector normal to crystal surface
e2 (np.array): unit vector crystal surface
e3 (np.array): unit vector orthogonal to e2
- Returns:
S (np.array): compliance tensor in new coordinate system
C (np.array): stiffnes tensor in new coordinate system
E (np.array): Young’s modulus in [GPa]
G (np.array): shear modulus in [GPa]
nu (np.array): Poisson ratio
Copied from S.I. of L. Zhang et al. “Anisotropic elasticity of silicon and its application to the modelling of X-ray optics.” J. Synchrotron Rad. 21, no. 3 (2014): 507-517.
- XRStools.xrs_utilities.sumx(A)[source]¶
Short-hand command to sum over 1st dimension of a N-D matrix (N>2) and to squeeze it to N-1-D matrix.
- XRStools.xrs_utilities.taupgen(e, hkl=[6, 6, 0], crystals='Si', R=1.0, dev=array([- 50., - 49., - 48., - 47., - 46., - 45., - 44., - 43., - 42., - 41., - 40., - 39., - 38., - 37., - 36., - 35., - 34., - 33., - 32., - 31., - 30., - 29., - 28., - 27., - 26., - 25., - 24., - 23., - 22., - 21., - 20., - 19., - 18., - 17., - 16., - 15., - 14., - 13., - 12., - 11., - 10., - 9., - 8., - 7., - 6., - 5., - 4., - 3., - 2., - 1., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25., 26., 27., 28., 29., 30., 31., 32., 33., 34., 35., 36., 37., 38., 39., 40., 41., 42., 43., 44., 45., 46., 47., 48., 49., 50., 51., 52., 53., 54., 55., 56., 57., 58., 59., 60., 61., 62., 63., 64., 65., 66., 67., 68., 69., 70., 71., 72., 73., 74., 75., 76., 77., 78., 79., 80., 81., 82., 83., 84., 85., 86., 87., 88., 89., 90., 91., 92., 93., 94., 95., 96., 97., 98., 99., 100., 101., 102., 103., 104., 105., 106., 107., 108., 109., 110., 111., 112., 113., 114., 115., 116., 117., 118., 119., 120., 121., 122., 123., 124., 125., 126., 127., 128., 129., 130., 131., 132., 133., 134., 135., 136., 137., 138., 139., 140., 141., 142., 143., 144., 145., 146., 147., 148., 149.]), alpha=0.0)[source]¶
% TAUPGEN Calculates the reflectivity curves of bent crystals % % function [refl,e,dev]=taupgen_new(e,hkl,crystals,R,dev,alpha); % % e = fixed nominal energy in keV % hkl = reflection order vector, e.g. [1 1 1] % crystals = crystal string, e.g. ‘si’ or ‘ge’ % R = bending radius in meters % dev = deviation parameter for which the % curve will be calculated (vector) (optional) % alpha = asymmetry angle % based on a FORTRAN program of Michael Krisch % Translitterated to Matlab by Simo Huotari 2006, 2007 % Is far away from being good matlab writing - mostly copy&paste from % the fortran routines. Frankly, my dear, I don’t give a damn. % Complaints -> /dev/null
- XRStools.xrs_utilities.taupgen_amplitude(e, hkl=[6, 6, 0], crystals='Si', R=1.0, dev=array([- 50., - 49., - 48., - 47., - 46., - 45., - 44., - 43., - 42., - 41., - 40., - 39., - 38., - 37., - 36., - 35., - 34., - 33., - 32., - 31., - 30., - 29., - 28., - 27., - 26., - 25., - 24., - 23., - 22., - 21., - 20., - 19., - 18., - 17., - 16., - 15., - 14., - 13., - 12., - 11., - 10., - 9., - 8., - 7., - 6., - 5., - 4., - 3., - 2., - 1., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25., 26., 27., 28., 29., 30., 31., 32., 33., 34., 35., 36., 37., 38., 39., 40., 41., 42., 43., 44., 45., 46., 47., 48., 49., 50., 51., 52., 53., 54., 55., 56., 57., 58., 59., 60., 61., 62., 63., 64., 65., 66., 67., 68., 69., 70., 71., 72., 73., 74., 75., 76., 77., 78., 79., 80., 81., 82., 83., 84., 85., 86., 87., 88., 89., 90., 91., 92., 93., 94., 95., 96., 97., 98., 99., 100., 101., 102., 103., 104., 105., 106., 107., 108., 109., 110., 111., 112., 113., 114., 115., 116., 117., 118., 119., 120., 121., 122., 123., 124., 125., 126., 127., 128., 129., 130., 131., 132., 133., 134., 135., 136., 137., 138., 139., 140., 141., 142., 143., 144., 145., 146., 147., 148., 149.]), alpha=0.0)[source]¶
% TAUPGEN Calculates the reflectivity curves of bent crystals % % function [refl,e,dev]=taupgen_new(e,hkl,crystals,R,dev,alpha); % % e = fixed nominal energy in keV % hkl = reflection order vector, e.g. [1 1 1] % crystals = crystal string, e.g. ‘si’ or ‘ge’ % R = bending radius in meters % dev = deviation parameter for which the % curve will be calculated (vector) (optional) % alpha = asymmetry angle % based on a FORTRAN program of Michael Krisch % Translitterated to Matlab by Simo Huotari 2006, 2007 % Is far away from being good matlab writing - mostly copy&paste from % the fortran routines. Frankly, my dear, I don’t give a damn. % Complaints -> /dev/null
- XRStools.xrs_utilities.tauphoto(Z, energy, logtablefile='/usr/lib/python3/dist-packages/XRStools/resources/data/logtable.dat')[source]¶
tauphoto Calculates Photoelectric Cross Section in cm^2/g using Log-Log Fit.
- Args:
z (int or string): Element number or elements symbol.
energy (float or array): Energy (can be number or vector)
- Returns:
tau (float or array): Photoelectric cross section in [cm**2/g]
Adapted from original Matlab function of Keijo Hamalainen.
- XRStools.xrs_utilities.unconstrained_mf(A, numComp=3, maxIter=1000, tol=1e-08)[source]¶
unconstrained_mf Returns main components from an off-diagonal Matrix (energy-loss x angular-departure), using the power method iteratively on the different main components.
- XRStools.xrs_utilities.vangle(v1, v2)[source]¶
vangle Calculates the angle between two cartesian vectors v1 and v2 in degrees.
- Args:
v1 (np.array): first vector.
v2 (np.array): second vector.
- Returns:
th (float): angle between first and second vector.
Function by S. Huotari, adopted for Python.
- XRStools.xrs_utilities.vrot(v, vaxis, phi)[source]¶
vrot Rotates a vector around a given axis.
- Args:
v (np.array): vector to be rotated
vaxis (np.array): rotation axis
phi (float): angle [deg] respecting the right-hand rule
- Returns:
v2 (np.array): new rotated vector
Function by S. Huotari (2007) adopted to Python.
- XRStools.xrs_utilities.vrot2(vector1, vector2, angle)[source]¶
rotMatrix Rotate vector1 around vector2 by an angle.
- XRStools.xrs_utilities.xas_fluo_correct(ene, mu, formula, fluo_ene, edge_ene, angin, angout)[source]¶
xas_fluo_correct Fluorescence yield over-absorption correction as in Larch/Athena. see: https://www3.aps.anl.gov/haskel/FLUO/Fluo-manual.pdf
- Args:
ene (np.array): energy axis in [keV]
mu (np.array): measured fluorescence spectrum
formula (str): chemical sum formulas (e.g. ‘SiO2’)
fluo_ene (float): energy in keV of main fluorescence line
edge_ene (float): edge energy in [keV]
angin (float): incidence angle (relative to sample normal) [deg.]
angout (float): exit angle (relative to sample normal) [deg.]
- Returns:
ene (np.array): energy axis in [keV]
mu_corr (np.array): corrected fluorescence spectrum
XRStools.XRStool
Package¶
XRStools.xrs_calctools
Module¶
- XRStools.xrs_calctools.broaden_diagram(e, s, params=[1.0, 1.0, 537.5, 540.0], npoints=1000)[source]¶
function [e2,s2] = broaden_diagram2(e,s,params,npoints)
% BROADEN_DIAGRAM2 Broaden a StoBe line diagram % % [ENE2,SQW2] = BROADEN_DIAGRAM2(ENE,SQW,PARAMS,NPOINTS) % % gives the broadened spectrum SQW2(ENE2) of the line-spectrum % SWQ(ENE). Each line is substituted with a Gaussian peak, % the FWHM of which is determined by PARAMS. ENE2 is a linear % scale of length NPOINTS (default 1000). % % PARAMS = [f_min f_max emin max] % % For ENE <= e_min, FWHM = f_min. % For ENE >= e_max, FWHM = f_min. % FWHM increases linearly from [f_min f_max] between [e_min e_max]. % % T Pylkkanen @ 2008-04-18 [17:37]
- XRStools.xrs_calctools.broaden_linear(spec, params=[0.8, 8, 537.5, 550], npoints=1000)[source]¶
broadens a spectrum with a Gaussian of width params[0] below params[2] and width params[1] above params[3], width increases linear in between. returns two-column numpy array of length npoints with energy and the broadened spectrum
- XRStools.xrs_calctools.calculateCOMlist(atomList)[source]¶
calculateCOMlist Calculates center of mass for a list of atoms.
- XRStools.xrs_calctools.calculateRIJhist2_arb(atoms1, atoms2, lattice, lattice_inv, DELR=0.01, MAXBIN=1000)[source]¶
- XRStools.xrs_calctools.calculateRIJhist_arb(atoms1, atoms2, lattice, lattice_inv, DELR=0.01, MAXBIN=1000)[source]¶
- XRStools.xrs_calctools.changeOHBondLength(h2oMol, fraction, boxLength=None, oName='O', hName='H')[source]¶
- XRStools.xrs_calctools.countHbonds_pbc(mol1, mol2, boxLength, Roocut=3.6, Rohcut=2.4, Aoooh=30.0)[source]¶
- XRStools.xrs_calctools.count_HBonds_pbc_arb(mol1, mol2, lattice, lattice_inv, Roocut=3.6, Rohcut=2.4, Aoooh=30.0)[source]¶
- XRStools.xrs_calctools.count_OO_neighbors_pbc(list_of_o_atoms, Roocut, boxLength, numbershells=1)[source]¶
- XRStools.xrs_calctools.cut_spec(spec, emin=None, emax=None)[source]¶
deletes lines of matrix with first column smaller than emin and larger than emax
- class XRStools.xrs_calctools.erkale(prefix, postfix, fromnumber, tonumber, step, stepformat=2)[source]¶
Bases:
object
class to analyze ERKALE XRS results.
- XRStools.xrs_calctools.find_H2O_molecules_PBC_arb(o_atoms, h_atoms, lattice, lattice_inv, OH_cutoff=1.5)[source]¶
- XRStools.xrs_calctools.gauss1(x, x0, fwhm)[source]¶
returns a gaussian with peak value normalized to unity a[0] = peak position a[1] = Full Width at Half Maximum
- XRStools.xrs_calctools.getDistVectorPBC_arb(atom1, atom2, lattice, lattice_inv)[source]¶
getDistVectorPBC_arb
Calculates the distance vector between two atoms from an arbitrary simulation box using the minimum image convention.
- Args:
atom1 (obj): Instance of the xzyAtom class. atom2 (obj): Instance of the xzyAtom class. lattice (np.array): Array with lattice vectors as columns. lattice_inv (np.array): Inverse of lattice.
- Returns:
The distance vector between the two atoms (np.array).
- XRStools.xrs_calctools.getDistancePBC_arb(atom1, atom2, lattice, lattice_inv)[source]¶
getDistancePBC_arb
Calculates the distance of two atoms from an arbitrary simulation box using the minimum image convention.
- Args:
atom1 (obj): Instance of the xzyAtom class. atom2 (obj): Instance of the xzyAtom class. lattice (np.array): Array with lattice vectors as columns. lattice_inv (np.array): Inverse of lattice.
- Returns:
The distance between the two atoms.
- XRStools.xrs_calctools.getPeriodicTestBox_arb(xyzAtoms, lattice, lattice_inv, lx=[- 1, 1], ly=[- 1, 1], lz=[- 1, 1])[source]¶
- XRStools.xrs_calctools.getTetraParameter(o_atoms, boxLength=None)[source]¶
according to NATURE, VOL 409, 18 JANUARY 2001
- XRStools.xrs_calctools.getTranslVec(atom1, atom2, boxLength)[source]¶
getTranslVec Returns the translation vector that brings atom2 closer to atom1 in case atom2 is further than boxLength away.
- XRStools.xrs_calctools.getTranslVec_geocen(mol1COM, mol2COM, boxLength)[source]¶
getTranslVec_geocen
- XRStools.xrs_calctools.groBoxParser(filename, nanoMeter=True)[source]¶
groBoxParser Parses an gromacs GRO-style file for the xyzBox class.
- XRStools.xrs_calctools.groTrajecParser(filename, nanoMeter=True)[source]¶
groTrajecParser Parses an gromacs GRO-style file for the xyzBox class.
- XRStools.xrs_calctools.keithBoxParser(cell_fname, coord_fname)[source]¶
keithBoxParser
Reads structure files from Keith’s SiO2 simulations.
- XRStools.xrs_calctools.load_erkale_specs(prefix, postfix, fromnumber, tonumber, step, stepformat=2)[source]¶
returns a list of erkale spectra
- XRStools.xrs_calctools.load_stobe_specs(prefix, postfix, fromnumber, tonumber, step, stepformat=2)[source]¶
load a bunch of StoBe calculations, which filenames are made up of the prefix, postfix, and the counter in the between the prefix and postfix runs from ‘fromnumber’ to ‘tonumber’ in steps of ‘step’ (number of digits is ‘stepformat’)
- XRStools.xrs_calctools.parseOCEANinputFile(fname)[source]¶
parseOCEANinputFile
Parses an OCEAN input file and returns lattice vectors, atom names, and relative atom positions.
- Args:
fname (str): Absolute filename of OCEAN input file.
atoms (list): List of elemental symbols in the same order as they appear in the input file.
- Returns:
lattice (np.array): Array of lattice vectors.
rel_coords (np.array): Array of relative atomic coordinates.
oceaatoms (list): List of atomic names.
- XRStools.xrs_calctools.parsePwscfFile(fname)[source]¶
parsePwscfFile
Parses a PWSCF file and returns a xyzBox object.
- Args:
fname (str): Absolute filename of OCEAN input file.
- Returns:
xyzBox object
- XRStools.xrs_calctools.parseVaspFile(fname)[source]¶
parseVaspFile
Parses a VASPS file and returns a xyzBox object.
- Args:
fname (str): Absolute filename of VASP file.
- Returns:
xyzBox object
- XRStools.xrs_calctools.readxas(filename)[source]¶
function output = readxas(filename)%[e,p,s,px,py,pz] = readxas(filename)
% READSTF Load StoBe fort.11 (XAS output) data % % [E,P,S,PX,PY,PZ] = READXAS(FILENAME) % % E energy transfer [eV] % P dipole transition intensity % S r^2 transition intensity % PX dipole transition intensity along x % PY dipole transition intensity along y % PZ dipole transition intensity along z % % as line diagrams. % % T Pylkkanen @ 2011-10-17
- XRStools.xrs_calctools.spline2(x, y, x2)[source]¶
Extrapolates the smaller and larger valuea as a constant
- class XRStools.xrs_calctools.stobe(prefix, postfix, fromnumber, tonumber, step, stepformat=2)[source]¶
Bases:
object
class to analyze StoBe results
- XRStools.xrs_calctools.vaspBoxParser(filename)[source]¶
groTrajecParser Parses an gromacs GRO-style file for the xyzBox class.
- XRStools.xrs_calctools.vaspTrajecParser(filename, min_boxes=0, max_boxes=1000)[source]¶
groTrajecParser Parses an gromacs GRO-style file for the xyzBox class.
- XRStools.xrs_calctools.writeFDMNESinput_file(xyzAtoms, fname, Filout, Range, Radius, Edge, NRIXS, Absorber, Green=False, SCF=False)[source]¶
writeFDMNESinput_file Writes an input file to be used for FDMNES.
- XRStools.xrs_calctools.writeFEFFinput_arb(fname, headerfile, xyzBox, exatom, edge)[source]¶
writeFEFFinput_arb
- XRStools.xrs_calctools.writeMD1Input(fname, box, headerfile, exatomNo=0)[source]¶
writeWFN1input Writes an input for cp.x by Quantum espresso for electronic wave function minimization.
- XRStools.xrs_calctools.writeOCEAN_XESInput(fname, box, headerfile, exatomNo=0)[source]¶
writeOCEAN_XESInput Writes an input for ONEAN XES calculation for 17 molecule water boxes.
- XRStools.xrs_calctools.writeOCEANinput(fname, headerfile, xyzBox, exatom, edge, subshell)[source]¶
writeOCEANinput
- XRStools.xrs_calctools.writeOCEANinput_arb(fname, headerfile, xyzBox, exatom, edge, subshell)[source]¶
writeOCEANinput
- XRStools.xrs_calctools.writeOCEANinput_full(fname, xyzBox, exatom, edge, subshell)[source]¶
Writes a complete OCEAN input file.
- Args:
fname (str): Filename for the input file to be written.
xyzBox (xyzBox): Instance of the xyzBox class to be converted into an OCEAN input file.
exatom (str): Atomic symbol for the excited atom.
edge (int): Integer defining which shell to excite (e.g. 0 for K-shell, 1 for L, etc.).
subshell (int): Integer defining which sub-shell to excite ( e.g. 0 for s, 1 for p, etc.).
- XRStools.xrs_calctools.writeOCEANinput_new(fname, headerfile, xyzBox, exatom, edge, subshell)[source]¶
writeOCEANinput
- XRStools.xrs_calctools.writeRelXYZfile(filename, n_atoms, boxLength, title, xyzAtoms, inclAtomNames=True)[source]¶
- XRStools.xrs_calctools.writeWFN1waterInput(fname, box, headerfile, exatomNo=0)[source]¶
writeWFN1input Writes an input for cp.x by Quantum espresso for electronic wave function minimization.
- class XRStools.xrs_calctools.xyzAtom(name, coordinates, number)[source]¶
Bases:
object
xyzAtom
Class to hold information about and manipulate a single atom in xyz-style format.
- Args. :
name (str): Atomic symbol.
coordinates (np.array): Array of xyz-coordinates.
number (int): Integer, e.g. number of atom in a cluster.
- class XRStools.xrs_calctools.xyzBox(xyzAtoms, boxLength=None, title=None)[source]¶
Bases:
object
xyzBox
Class to hold information about and manipulate a xyz-periodic cubic box.
- Args.:
xyzAtoms (list): List of instances of the xyzAtoms class that make up the molecule.
boxLength (float): Box length.
- changeOHBondlength(fraction, oName='O', hName='H')[source]¶
changeOHBondlength Changes all OH covalent bond lengths inside the box by a fraction.
- count_hbonds(Roocut=3.6, Rohcut=2.4, Aoooh=30.0, counter_name='num_H_bonds', counter_name2='H_bond_angles')[source]¶
count_hbonds Counts the number of hydrogen bonds around all oxygen atoms and sets that number as attribute to the accorting xyzAtom.
- count_neighbors(name1, name2, cutoff_low=0.0, cutoff_high=2.0, counter_name='num_OO_shell')[source]¶
count_neighbors
Counts number of neighbors (of name2) around atom of name1.
- Args:
name1 (str): Name of first type of atom.
name2 (str): Name of second type of atom.
cutoff_low (float): Lower cutoff (Angstrom).
cutoff_high (float): Upper cutoff (Angstrom).
counter_name (str): Attribute namer under which the result should be saved.
- deleteTip4pCOM()[source]¶
deleteTip4pCOM Deletes the ficticious atoms used in the TIP4P water model.
- find_tmao_molecules_arb(CH_cut=1.2, CN_cut=1.6, NO_cut=1.5, CC_cut=2.5)[source]¶
find_tmao_molecules Returns a list of TMAO molecules.
- find_urea_molecules_arb(NH_cut=1.2, CN_cut=1.6, CO_cut=1.5)[source]¶
find_urea_molecules Returns a list of Urea molecules.
- getDistVectorPBC_arb(atom1, atom2)[source]¶
getDistVectorPBC_arb
Calculates the distance vector between two atoms from an arbitrary simulation box using the minimum image convention.
- Args:
atom1 (obj): Instance of the xzyAtom class. atom2 (obj): Instance of the xzyAtom class.
- Returns:
The distance vector between the two atoms (np.array).
- getDistancePBC_arb(atom1, atom2)[source]¶
getDistancePBC_arb Calculates the distance of two atoms from an arbitrary simulation box using the minimum image convention.
- Args:
atom1 (obj): Instance of the xzyAtom class. atom2 (obj): Instance of the xzyAtom class.
- Returns:
The distance between the two atoms.
- getTetraParameter()[source]¶
getTetraParameter Returns a list of tetrahedrality paprameters, according to NATURE, VOL 409, 18 JANUARY (2001).
UNTESTED!!!
- get_OO_neighbors(Roocut=3.6)[source]¶
get_OO_neighbors Returns list of numbers of nearest oxygen neighbors within readius ‘Roocut’.
- get_OO_neighbors_pbc(Roocut=3.6)[source]¶
get_OO_neighbors_pbc Returns a list of numbers of nearest oxygen atoms, uses periodic boundary conditions.
- get_angle(atom1, atom2, atom3, degrees=True)[source]¶
get_angle Return angle between the three given atoms (as seen from atom2).
- get_angle_arb(atom1, atom2, atom3, degrees=True)[source]¶
get_angle Return angle between the three given atoms (as seen from atom2).
- get_atoms_by_name(name)[source]¶
get_atoms_by_name Return a list of all xyzAtoms of a given name ‘name’.
- get_atoms_from_molecules()[source]¶
get_atoms_from_molecules Parses all atoms inside self.xyzMolecules into self.xyzAtoms (useful for turning an xyzMolecule into an xyzBox).
- get_h2o_molecules(o_name='O', h_name='H')[source]¶
get_h2o_molecules Finds all water molecules inside the box and collects them inside the self.xyzMolecules attribute.
- get_hbonds(Roocut=3.6, Rohcut=2.4, Aoooh=30.0)[source]¶
get_hbonds Counts the hydrogen bonds inside the box, returns the number of H-bond donors and H-bond acceptors.
- multiplyBoxPBC(numShells)[source]¶
multiplyBoxPBC Applies the periodic boundary conditions and multiplies the box in shells around the original.
- multiplyBoxPBC_arb(lx=[- 1, 1], ly=[- 1, 1], lz=[- 1, 1])[source]¶
multiplyBoxPBC_arb Applies the periodic boundary conditions and multiplies the box in shells around the original. Works with arbitrary lattices.
- scatterPlot()[source]¶
scatterPlot Opens a plot window with a scatter-plot of all coordinates of the box.
- translateAtomsMinimumImage(lattice, lattice_inv)[source]¶
translateAtomsMinimumImage
Brings back all atoms into the original box using periodic boundary conditions and minimal image convention.
- writeBox(filename)[source]¶
writeBox Creates an xyz-style text file with all coordinates of the box.
- writeClusters(cenatom_name, number, cutoff, prefix, postfix='.xyz')[source]¶
writeXYZclusters Write water clusters into files.
- writeClusters_arb(cenatom_name, number, cutoff, prefix, postfix='.xyz', test_box_multiplyer=1)[source]¶
writeXYZclusters Write water clusters into files.
- writeFDMNESinput(fname, Filout, Range, Radius, Edge, NRIXS, Absorber)[source]¶
writeFDMNESinput Creates an input file to be used for q-dependent calculations with FDMNES.
- writeH2Oclusters(cutoff, prefix, postfix='.xyz', o_name='O', h_name='H')[source]¶
writeXYZclusters Write water clusters into files.
- writeMoleculeCluster(molAtomList, fname, cutoff=None, numH2Omols=None, o_name='O', h_name='H', mol_center=None)[source]¶
writeMoleculeCluster Careful, this works only for a single molecule in water.
- class XRStools.xrs_calctools.xyzMolecule(xyzAtoms, title=None)[source]¶
Bases:
object
xyzMolecule
Class to hold information about and manipulate an xyz-style molecule.
- Args.:
xyzAtoms (list): List of instances of the xyzAtoms class that make up the molecule.
- get_atoms_by_name(name)[source]¶
get_atoms_by_name Return a list of all xyzAtoms of a given name ‘name’.
- scatterPlot()[source]¶
scatterPlot Opens a plot window with a scatter-plot of all coordinates of the molecule.
- translateAtomsMinimumImage(lattice, lattice_inv, center=array([0., 0., 0.]))[source]¶
translateAtomsMinimumImage
Brings back all atoms into the original box using periodic boundary conditions and minimal image convention.
- XRStools.xrs_calctools.xyzTrajecParser(filename, boxLength, firstBox=0, lastBox=- 1)[source]¶
Parses a Trajectory of xyz-files.
- Args:
filename (str): Filename of the xyz Trajectory file.
- Returns:
A list of xzyBoxes.
XRStools.xrs_extraction
Module¶
- class XRStools.xrs_extraction.HF_dataset(data, formulas, stoich_weights, edges)[source]¶
Bases:
object
dataset A class to hold all information from HF Compton profiles necessary to subtract background from the experiment.
- class XRStools.xrs_extraction.edge_extraction(exp_data, formulas, stoich_weights, edges, prenormrange=[5, inf])[source]¶
Bases:
object
edge_extraction Class to destill core edge spectra from x-ray Raman scattering experiments.
- analyzerAverage(roi_numbers, errorweighing=True)[source]¶
analyzerAverage Averages signals from several crystals before background subtraction.
Args:
- roi_numberslist, str
list of ROI numbers to average over of keyword for analyzer chamber (e.g. ‘VD’,’VU’,’VB’,’HR’,’HL’,’HB’)
- errorweighingboolean (True by default)
keyword if error weighing should be used for the averaging or not
- removeCorePearsonAv(element, edge, range1, range2, weights=[2, 1], HFcore_shift=0.0, guess=None, scaling=None, return_background=False, show_plots=True)[source]¶
removeCorePearsonAv
guess (list): [position, FWHM, shape, intensity, ax, b, scale ]
- removeCorePearsonAv_new(element, edge, range1, range2, HFcore_shift=0.0, guess=None, scaling=None, return_background=False, reg_lam=10)[source]¶
removeCorePearsonAv_new
- removePearsonAv(element, edge, range1, range2=None, weights=[2, 1], guess=None, scale=1.0, HFcore_shift=0.0)[source]¶
removePearsonAv
- removePolyCoreAv(element, edge, range1, range2, weights=[1, 1], guess=[1.0, 0.0, 0.0], ewindow=100.0)[source]¶
removePolyCoreAv Subtract a polynomial from averaged data guided by the HF core Compton profile.
Args
element : str String (e.g. ‘Si’) for the element you want to work on.
edge: str String (e.g. ‘K’ or ‘L23’) for the edge to extract.
range1 : list List with start and end value for fit-region 1.
range2 : list List with start and end value for fit-region 2.
weigths : list of ints List with weights for the respective fit-regions 1 and 2. Default is [1,1].
guess : list List of starting values for the fit. Default is [1.0,0.0,0.0] (i.e. a quadratic function. Change the number of guess values to get other degrees of polynomials (i.e. [1.0, 0.0] for a constant, [1.0,0.0,0.0,0.0] for a cubic, etc.). The first guess value passed is for scaling of the experimental data to the HF core Compton profile.
ewindow: float Width of energy window used in the plot. Default is 100.0.
- save_average_Sqw(filename, emin=None, emax=None, normrange=None)[source]¶
save_average_Sqw Save the S(q,w) into a ascii file (energy loss, S(q,w), Poisson errors).
- Args:
filename : str Filename for the ascii file.
emin : float Use this to save only part of the spectrum.
emax : float Use this to save only part of the spectrum.
normrange : list of floats E_start and E_end for possible area-normalization before saving.
XRStools.xrs_imaging
Module¶
XRStools.xrs_read
Module¶
XRStools.xrs_scans
Module¶
XRStools.xrs_ComptonProfiles
Module¶
- class XRStools.xrs_ComptonProfiles.AtomProfile(element, filename, stoichiometry=1.0)[source]¶
Bases:
object
AtomProfile
Class to construct and handle Hartree-Fock atomic Compton Profile of a single atoms.
- Attributes:
filename : string Path and filename to the HF profile table.
element : string Element symbol as in the periodic table.
elementNr : int Number of the element as in the periodic table.
shells : list of strings Names of the shells.
edges : list List of edge onsets (eV).
C_total : np.array Total core Compton profile.
J_total : np.array Total Compton profile.
V_total : np.array Total valence Compton profile.
CperShell : dict. of np.arrays Core Compton profile per electron shell.
JperShell : dict. of np.arrays Total Compton profile per electron shell.
VperShell : dict. of np.arrays Valence Compton profile per electron shell.
stoichiometry : float, optional Stoichiometric weight (default is 1.0).
atomic_weight : float Atomic weight.
atomic_density : float Density (g/cm**3).
twotheta : float Scattering angle 2Th (degrees).
alpha : float Incident angle (degrees).
beta : float Exit angle (degrees).
thickness : float Sample thickness (cm).
- absorptionCorrectProfiles(alpha, thickness, geometry='transmission')[source]¶
absorptionCorrectProfiles
Apply absorption correction to the Compton profiles on energy loss scale.
- Args:
alpha :float Angle of incidence (degrees).
beta : float Exit angle for the scattered x-rays (degrees). If ‘beta’ is negative, transmission geometry is assumed, if ‘beta’ is positive, reflection geometry.
thickness : float Sample thickness.
- get_elossProfiles(E0, twotheta, correctasym=None, valence_cutoff=20.0)[source]¶
get_elossProfiles Convert the HF Compton profile on to energy loss scale.
Args: E0 : float
Analyzer energy, enery of the scattered r-rays.
- twothetafloat or list of floats
Scattering angle 2Th.
- correctasymfloat, optional
Scaling factor to be multiplied to the asymmetry.
- valence_cutofffloat, optional
Energy cut off as to what is considered the boundary between core and valence.
- class XRStools.xrs_ComptonProfiles.ComptonProfiles(element)[source]¶
Bases:
object
Class for multiple HF Compton profiles.
This class should hold one or more instances of the ComptonProfile class and have methods to return profiles from single atoms, single shells, all atoms. It should be able to apply corrections etc. on those…
- Attributes:
element (string): Element symbol as in the periodic table.
elementNr (int) : Number of the element as in the periodic table.
shells (list) :
edges (list) :
C (np.array) :
J (np.array) :
V (np.array) :
CperShell (dict. of np.arrays):
JperShell (dict. of np.arrays):
VperShell (dict. of np.arrays):
- class XRStools.xrs_ComptonProfiles.FormulaProfile(formula, filename, weight=1)[source]¶
Bases:
object
FormulaProfile
Class to construct and handle Hartree-Fock atomic Compton Profile of a single chemical compound.
- Attributes
filename : string Path and filename to Biggs database.
formula : string Chemical sum formula for the compound of interest (e.g. ‘SiO2’ or ‘H2O’).
elements : list of strings List of atomic symbols that make up the chemical sum formula.
stoichiometries : list of integers List of the stoichimetric weights for each of the elements in the list elements.
element_Nrs : list of integers List of atomic numbers for each element in the elements list.
AtomProfiles : list of AtomProfiles List of instances of the AtomProfiles class for each element in the list.
eloss : np.ndarray Energy loss scale for the Compton profiles.
C_total : np.ndarray Core HF Compton profile (one column per 2Th).
J_total : np.ndarray Total HF Compton profile (one column per 2Th).
V_total :np.ndarray Valence HF Compton profile (one column per 2Th).
E0 : float Analyzer energy (keV).
twotheta : float, list, or np.ndarray Value or list/np.ndarray of the scattering angle.
- class XRStools.xrs_ComptonProfiles.HFProfile(formulas, stoich_weights, filename)[source]¶
Bases:
object
HFProfile
Class to construct and handle Hartree-Fock atomic Compton Profile of sample composed of several chemical compounds.
Attributes
- XRStools.xrs_ComptonProfiles.HRcorrect(pzprofile, occupation, q)[source]¶
Returns the first order correction to filled 1s, 2s, and 2p Compton profiles.
Implementation after Holm and Ribberfors (citation …).
- Args:
pzprofile (np.array): Compton profile (e.g. tabulated from Biggs) to be corrected (2D matrix).
occupation (list): electron configuration.
q (float or np.array): momentum transfer in [a.u.].
- Returns:
asymmetry (np.array): asymmetries to be added to the raw profiles (normalized to the number of electrons on pz scale)
- XRStools.xrs_ComptonProfiles.PzProfile(element, filename)[source]¶
Returnes tabulated HF Compton profiles.
Reads in tabulated HF Compton profiles from the Biggs paper, interpolates them, and normalizes them to the # of electrons in the shell.
- Args:
element (string): element symbol (e.g. ‘Si’, ‘Al’, etc.)
filename (string): absolute path and filename to tabulated profiles
- Returns:
CP_profile (np.array): Matrix of the Compton profile * 1. column: pz-scale * 2. … n. columns: Compton profile of nth shell
binding_energy (list): binding energies of shells
occupation_num (list): number of electrons in the according shells
- class XRStools.xrs_ComptonProfiles.SqwPredict[source]¶
Bases:
object
Class to build a S(q,w) prediction based on HF Compton Profiles.
Attributes:
sampleStr (list of strings): one string per compound (e.g. [‘C’,’SiO2’])
concentrations (list of floats): relative compositional weight for each compound
- XRStools.xrs_ComptonProfiles.elossProfile(element, filename, E0, tth, correctasym=None, valence_cutoff=20.0)[source]¶
Returns HF Compton profiles on energy loss scale.
Uses the PzProfile function to read read in Biggs HF profiles and converts them onto energy loss scale. The profiles are cut at the respective electron binding energies and are normalized to the f-sum rule (i.e. S(q,w) is in units of [1/eV]).
- Args:
element (string): element symbol.
filename (string): absolute path and filename to tabulated Compton profiles.
E0 (float): analyzer energy in [keV].
tth (float): scattering angle two theta in [deg].
correctasym (np.array): vector of scaling factors to be applied.
valence_cutoff (float): energy value below which edges are considered as valence
- Returns:
enScale (np.array): energy loss scale in [eV]
J_total (np.array): total S(q,w) in [1/eV]
C_total (np.array): core contribution to S(q,w) in [1/eV]
V_total (np.array): valence contribution to S(q,w) in [1/eV], the valence is defined by valence_cutoff
q (np.array): momentum transfer in [a.u]
J_shell (dict of np.arrays): dictionary of contributions for each shell, the key are defines as in Biggs table.
C_shell (dict of np.arrays): same as J_shell for core contribution
V_shell (dict of np.arrays): same as J_shell for valence contribution
- XRStools.xrs_ComptonProfiles.mapShellNames(shell_str, atomicNumber)[source]¶
mapShellNames
Translates to and from spectroscopic edge notation and the convention of the Biggs database.
- Args:
shell_str : string Spectroscopic symbol to be converted to Biggs database convention.
atomicNumber : int Z for the atom in question.
XRStools.xrs_fileIO
Module¶
- XRStools.xrs_fileIO.PrepareEdfMatrix(scan_length, num_pix_x, num_pix_y)[source]¶
Returns np.zeros of the shape of the detector.
- XRStools.xrs_fileIO.PrepareEdfMatrix_TwoImages(scan_length, num_pix_x, num_pix_y)[source]¶
Returns np.zeros for old data (horizontal and vertical Maxipix images in different files).
- XRStools.xrs_fileIO.PyMcaSpecRead(filename, nscan)[source]¶
Returns data, counter-names, and EDF-files using PyMCA.
- XRStools.xrs_fileIO.PyMcaSpecRead_my(filename, nscan)[source]¶
Returns data, counter-names, and EDF-files using PyMCA.
- XRStools.xrs_fileIO.ReadEdfImages(ccdcounter, num_pix_x, num_pix_y, path, EdfPrefix, EdfName, EdfPostfix)[source]¶
Reads a series of EDF-images and returs them in a 3D Numpy array (horizontal and vertical Maxipix images in different files).
- XRStools.xrs_fileIO.ReadEdfImages_PyMca(ccdcounter, path, EdfPrefix, EdfName, EdfPostfix)[source]¶
Reads a series of EDF-images and returs them in a 3D Numpy array (horizontal and vertical Maxipix images in different files).
- XRStools.xrs_fileIO.ReadEdfImages_TwoImages(ccdcounter, num_pix_x, num_pix_y, path, EdfPrefix_h, EdfPrefix_v, EdfNmae, EdfPostfix)[source]¶
Reads a series of EDF-images and returs them in a 3D Numpy array (horizontal and vertical Maxipix images in different files).
- XRStools.xrs_fileIO.ReadEdfImages_my(ccdcounter, path, EdfPrefix, EdfName, EdfPostfix)[source]¶
Reads a series of EDF-images and returs them in a 3D Numpy array (horizontal and vertical Maxipix images in different files).
- XRStools.xrs_fileIO.ReadEdf_justFirstImage(ccdcounter, path, EdfPrefix, EdfName, EdfPostfix)[source]¶
- XRStools.xrs_fileIO.SilxSpecRead(filename, nscan)[source]¶
Returns data, motors, counter-names, and labels using Silx.
- XRStools.xrs_fileIO.SpecRead(filename, nscan)[source]¶
Parses a SPEC file and returns a specified scan.
- Args:
filename (string): SPEC file name (inlc. path)
nscan (int): Number of the desired scan.
- Returns:
data (np.array): array of the data from the specified scan.
motors (list): list of all motor positions from the header of the specified scan.
counters (dict): all counters in a dictionary with the counter names as keys.
- XRStools.xrs_fileIO.WriteScanToFile(fname, data, motors, counters, edfmats)[source]¶
Writes a scan into a Numpy archive.
- XRStools.xrs_fileIO.myEdfRead(filename)[source]¶
Returns EDF-data, if PyMCA is not installed (this is slow).
- XRStools.xrs_fileIO.readbiggsdata(filename, element)[source]¶
Reads Hartree-Fock Profile of element ‘element’ from values tabulated by Biggs et al. (Atomic Data and Nuclear Data Tables 16, 201-309 (1975)) as provided by the DABAX library (http://ftp.esrf.eu/pub/scisoft/xop2.3/DabaxFiles/ComptonProfiles.dat). input: filename = path to the ComptonProfiles.dat file (the file should be distributed with this package) element = string of element name returns: data = the data for the according element as in the file:
#UD Columns: #UD col1: pz in atomic units #UD col2: Total compton profile (sum over the atomic electrons #UD col3,…coln: Compton profile for the individual sub-shells
occupation = occupation number of the according shells bindingen = binding energies of the accorting shells colnames = strings of column names as used in the file
XRStools.xrs_prediction
Module¶
- class XRStools.xrs_prediction.absolute_cross_section(beam_obj, sample_obj, analyzer_obj, detector_obj, thomson_obj, compton_profile_obj)[source]¶
Bases:
object
Class to calculate an expected cross section in absolute counts using objects of the ‘beam’, ‘sample’, ‘analyzer’, ‘detector’, ‘thomson’, and ‘compton_profile’ classes.
- calc_num_scatterers()[source]¶
Calculates number of scatterers/atoms using beam size, sample thickness, sample densites, sample molar masses (so far does not differentiate between target atoms and random sample atoms)
- class XRStools.xrs_prediction.analyzer(material='Si', hkl=[6, 6, 0], mask_d=60.0, bend_r=1.0, energy_resolution=0.5, diced=False, thickness=500.0, database_dir='/build/xrstools-Pcpwna/xrstools-0.15.0+git20210910+c147919d/XRStools')[source]¶
Bases:
object
Class to describe things related to the analyzer crystal used. Default values are for a Si(660) crystal.
- get_efficiency(energy=None)[source]¶
Calculates the efficiency of the analyzer crystal based on the calculated reflectivity curve. The efficiency is calculated by averaging over the energy resolution set upon class initialization. energy = energy (in [keV]) for wich the efficiency is to be calculated
- get_reflectivity(energy, dev=array([- 50., - 49., - 48., - 47., - 46., - 45., - 44., - 43., - 42., - 41., - 40., - 39., - 38., - 37., - 36., - 35., - 34., - 33., - 32., - 31., - 30., - 29., - 28., - 27., - 26., - 25., - 24., - 23., - 22., - 21., - 20., - 19., - 18., - 17., - 16., - 15., - 14., - 13., - 12., - 11., - 10., - 9., - 8., - 7., - 6., - 5., - 4., - 3., - 2., - 1., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25., 26., 27., 28., 29., 30., 31., 32., 33., 34., 35., 36., 37., 38., 39., 40., 41., 42., 43., 44., 45., 46., 47., 48., 49., 50., 51., 52., 53., 54., 55., 56., 57., 58., 59., 60., 61., 62., 63., 64., 65., 66., 67., 68., 69., 70., 71., 72., 73., 74., 75., 76., 77., 78., 79., 80., 81., 82., 83., 84., 85., 86., 87., 88., 89., 90., 91., 92., 93., 94., 95., 96., 97., 98., 99., 100., 101., 102., 103., 104., 105., 106., 107., 108., 109., 110., 111., 112., 113., 114., 115., 116., 117., 118., 119., 120., 121., 122., 123., 124., 125., 126., 127., 128., 129., 130., 131., 132., 133., 134., 135., 136., 137., 138., 139., 140., 141., 142., 143., 144., 145., 146., 147., 148., 149.]), alpha=0.0)[source]¶
Calculates the reflectivity curve for a given analyzer crystal. Checks in the directory self.database_dir, if desired reflectivity curve has been calculated before. IN: energy = energy at which the reflectivity is to be calculated in [keV] dev = deviation parameter for which the curve is to be calculated alpha = deviation angle from exact Bragg angle [deg]
- class XRStools.xrs_prediction.beam(i0_intensity, beam_height, beam_width, divergence=None)[source]¶
Bases:
object
Class to describe incident beam related things.
- class XRStools.xrs_prediction.compton_profiles(sample_obj, eloss_range=array([0.000e+00, 1.000e-01, 2.000e-01, ..., 9.997e+02, 9.998e+02, 9.999e+02]), E0=9.7)[source]¶
Bases:
object
Class to hold construct HF Compton profiles for an object of the sample class.
- class XRStools.xrs_prediction.detector(energy=9.68, thickness=500, material='Si', pixel_size=[256, 768])[source]¶
Bases:
object
Class to describe detector related things. All default values are meant for the ESRF MAXIPIX detector.
- XRStools.xrs_prediction.get_all_input(filename='prediction.inp')[source]¶
Adds default values if input is missing in the input-file and a default value exists for the missing one.
- XRStools.xrs_prediction.input_file_parser(filename)[source]¶
Parses an input file, which has a structure like the example input file (‘prediction.inp’) provided in the examples/ folder. (Python lists and numpy arrays have to be profived without white spaces in their definitions, e.g. ‘hkl = [6,6,0]’ instead of ‘hkl = [6, 6, 0]’)
- class XRStools.xrs_prediction.matrix_element(R1, R2)[source]¶
Bases:
object
- class XRStools.xrs_prediction.radial_wave_function[source]¶
Bases:
object
- XRStools.xrs_prediction.run(filename='prediction.inp')[source]¶
Function to create a spectrum prediction from input parameters provided in the input file filename. Generates a figure with the result.
- class XRStools.xrs_prediction.sample(chem_formulas, concentrations, densities, angle_tth, sample_thickness, angle_in=None, angle_out=None, shape='sphere', molar_masses=None)[source]¶
Bases:
object
Class to describe a sample.
- get_absorption_correction(energy1, energy2, thickness=None)[source]¶
Calculates the absorption correction factor for the sample to be multiplied with experimental data to correct for absorption effects. energy1 = numpy array of energies in [keV] for which the factor is to be calculated energy2 = numpy array of energies in [keV] for which the factor is to be calculated
- get_murho(energy1, energy2=None)[source]¶
Calculates the total photoelectric absorption coefficient of the sample for the two energies given. Returns only one array, if only one energy axis is defined. energy1 = numpy array of energies in [keV] energy2 = numpy array of energies in [keV] (defalt is None, i.e. only one mu is returned)
- plot_inv_absorption(energy1, energy2, range_of_thickness=array([0., 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.3, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.4, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49]))[source]¶
Generates a figure which plots 1/Abscorr for the sample as a function of different thicknesses. This is usefull for finding optimum sample thicknesses for an experiment. energy1 = energy in [keV] at the desired edge energy2 = energy in [keV] at the elastic range_of_thickness = numpy array of sample thicknesses in [cm]
!!! right now all samples are treates as if spherical !!!
XRStools.xrs_rois
Module¶
XRStools.xrs_utilities
Module¶
- XRStools.xrs_utilities.HRcorrect(pzprofile, occupation, q)[source]¶
Returns the first order correction to filled 1s, 2s, and 2p Compton profiles.
Implementation after Holm and Ribberfors (citation …).
- Args:
pzprofile (np.array): Compton profile (e.g. tabulated from Biggs) to be corrected (2D matrix).
occupation (list): electron configuration.
q (float or np.array): momentum transfer in [a.u.].
- Returns:
asymmetry (np.array): asymmetries to be added to the raw profiles (normalized to the number of electrons on pz scale)
- XRStools.xrs_utilities.NNMFcost(x, A, F, C, F_up, C_up, n, k, m)[source]¶
NNMFcost Returns cost and gradient for NNMF with constraints.
- XRStools.xrs_utilities.NNMFcost_old(x, A, W, H, W_up, H_up)[source]¶
NNMFcost Returns cost and gradient for NNMF with constraints.
- XRStools.xrs_utilities.Rx(chi, degrees=True)[source]¶
Rx Rotation matrix for vector rotations around the [1,0,0]-direction.
- Args:
chi (float) : Angle of rotation.
degrees(bool) : Angle given in radians or degrees.
- Returns:
3x3 rotation matrix.
- XRStools.xrs_utilities.Ry(phi, degrees=True)[source]¶
Ry Rotation matrix for vector rotations around the [0,1,0]-direction.
- Args:
phi (float) : Angle of rotation.
degrees(bool) : Angle given in radians or degrees.
- Returns:
3x3 rotation matrix.
- XRStools.xrs_utilities.Rz(omega, degrees=True)[source]¶
Rz Rotation matrix for vector rotations around the [0,0,1]-direction.
- Args:
omega (float) : Angle of rotation.
degrees(bool) : Angle given in radians or degrees.
- Returns:
3x3 rotation matrix.
- XRStools.xrs_utilities.TTsolver1D(el_energy, hkl=[6, 6, 0], crystal='Si', R=1.0, dev=array([- 50., - 49., - 48., - 47., - 46., - 45., - 44., - 43., - 42., - 41., - 40., - 39., - 38., - 37., - 36., - 35., - 34., - 33., - 32., - 31., - 30., - 29., - 28., - 27., - 26., - 25., - 24., - 23., - 22., - 21., - 20., - 19., - 18., - 17., - 16., - 15., - 14., - 13., - 12., - 11., - 10., - 9., - 8., - 7., - 6., - 5., - 4., - 3., - 2., - 1., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25., 26., 27., 28., 29., 30., 31., 32., 33., 34., 35., 36., 37., 38., 39., 40., 41., 42., 43., 44., 45., 46., 47., 48., 49., 50., 51., 52., 53., 54., 55., 56., 57., 58., 59., 60., 61., 62., 63., 64., 65., 66., 67., 68., 69., 70., 71., 72., 73., 74., 75., 76., 77., 78., 79., 80., 81., 82., 83., 84., 85., 86., 87., 88., 89., 90., 91., 92., 93., 94., 95., 96., 97., 98., 99., 100., 101., 102., 103., 104., 105., 106., 107., 108., 109., 110., 111., 112., 113., 114., 115., 116., 117., 118., 119., 120., 121., 122., 123., 124., 125., 126., 127., 128., 129., 130., 131., 132., 133., 134., 135., 136., 137., 138., 139., 140., 141., 142., 143., 144., 145., 146., 147., 148., 149.]), alpha=0.0, chitable_prefix='/home/christoph/sources/XRStools/data/chitables/chitable_')[source]¶
TTsolver Solves the Takagi-Taupin equation for a bent crystal.
This function is based on a Matlab implementation by S. Huotari of M. Krisch’s Fortran programs.
- Args:
el_energy (float): Fixed nominal (working) energy in keV.
hkl (array): Reflection order vector, e.g. [6, 6, 0]
crystal (str): Crystal used (can be silicon ‘Si’ or ‘Ge’)
R (float): Crystal bending radius in m.
dev (np.array): Deviation parameter (in arc. seconds) for which the reflectivity curve should be calculated.
alpha (float): Crystal assymetry angle.
- Returns:
refl (np.array): Reflectivity curve.
e (np.array): Deviation from Bragg angle in meV.
dev (np.array): Deviation from Bragg angle in microrad.
- XRStools.xrs_utilities.absCorrection(mu1, mu2, alpha, beta, samthick, geometry='transmission')[source]¶
absCorrection
Calculates absorption correction for given mu1 and mu2. Multiply the measured spectrum with this correction factor. This is a translation of Keijo Hamalainen’s Matlab function (KH 30.05.96).
- Args
mu1 : np.array Absorption coefficient for the incident energy in [1/cm].
mu2 : np.array Absorption coefficient for the scattered energy in [1/cm].
alpha : float Incident angle relative to plane normal in [deg].
beta : float Exit angle relative to plane normal [deg].
samthick : float Sample thickness in [cm].
geometry : string, optional Key word for different sample geometries (‘transmission’, ‘reflection’, ‘sphere’). If geometry is set to ‘sphere’, no angular dependence is assumed.
- Returns
ac : np.array Absorption correction factor. Multiply this with your measured spectrum.
- XRStools.xrs_utilities.abscorr2(mu1, mu2, alpha, beta, samthick)[source]¶
Calculates absorption correction for given mu1 and mu2. Multiply the measured spectrum with this correction factor.
This is a translation of Keijo Hamalainen’s Matlab function (KH 30.05.96).
- Args:
mu1 (np.array): absorption coefficient for the incident energy in [1/cm].
mu2 (np.array): absorption coefficient for the scattered energy in [1/cm].
alpha (float): incident angle relative to plane normal in [deg].
beta (float): exit angle relative to plane normal [deg] (for transmission geometry use beta < 0).
samthick (float): sample thickness in [cm].
- Returns:
ac (np.array): absorption correction factor. Multiply this with your measured spectrum.
- XRStools.xrs_utilities.addch(xold, yold, n, n0=0, errors=None)[source]¶
# ADDCH Adds contents of given adjacent channels together # # [x2,y2] = addch(x,y,n,n0) # x = original x-scale (row or column vector) # y = original y-values (row or column vector) # n = number of channels to be summed up # n0 = offset for adding, default is 0 # x2 = new x-scale # y2 = new y-values # # KH 17.09.1990 # Modified 29.05.1995 to include offset
- XRStools.xrs_utilities.bidiag_reduction(A)[source]¶
function [U,B,V]=bidiag_reduction(A) % [U B V]=bidiag_reduction(A) % Algorithm 6.5-1 in Golub & Van Loan, Matrix Computations % Johns Hopkins University Press % Finds an upper bidiagonal matrix B so that A=U*B*V’ % with U,V orthogonal. A is an m x n matrix
- XRStools.xrs_utilities.bootstrapCNNMF(A, F_ini, C_ini, F_up, C_up, Niter)[source]¶
bootstrapCNNMF Constrained non-negative matrix factorization with bootstrapping for error estimates.
- XRStools.xrs_utilities.bootstrapCNNMF_old(A, k, Aerr, F_ini, C_ini, F_up, C_up, Niter=100)[source]¶
bootstrapCNNMF Constrained non-negative matrix factorization with bootstrapping for error estimates.
- XRStools.xrs_utilities.bragg(hkl, e, xtal='Si')[source]¶
% BRAGG Calculates Bragg angle for given reflection in RAD % output=bangle(hkl,e,xtal) % hkl can be a matrix i.e. hkl=[1,0,0 ; 1,1,1]; % e=energy in keV % xtal=’Si’, ‘Ge’, etc. (check dspace.m) or d0 (Si default) % % KH 28.09.93 %
- class XRStools.xrs_utilities.bragg_refl(crystal, hkl, alpha=0.0)[source]¶
Bases:
object
Dynamical theory of diffraction.
- XRStools.xrs_utilities.braggd(hkl, e, xtal='Si')[source]¶
# BRAGGD Calculates Bragg angle for given reflection in deg # Call BRAGG.M # output=bangle(hkl,e,xtal) # hkl can be a matrix i.e. hkl=[1,0,0 ; 1,1,1]; # e=energy in keV # xtal=’Si’, ‘Ge’, etc. (check dspace.m) or d0 (Si default) # # KH 28.09.93
- XRStools.xrs_utilities.cixsUBgetQ_primo(tthv, tthh, psi)[source]¶
returns the Q0 given the detector position (tthv, tth) and th crystal orientation. This orientation is calculated considering :
- the Bragg condition and the rotation around the G vector :
this rotation is defined by psi which is a rotation around G
- XRStools.xrs_utilities.constrained_mf(A, W_ini, W_up, coeff_ini, coeff_up, maxIter=1000, tol=1e-08, maxIter_power=1000)[source]¶
cfactorizeOffDiaMatrix constrained version of factorizeOffDiaMatrix Returns main components from an off-diagonal Matrix (energy-loss x angular-departure).
- XRStools.xrs_utilities.constrained_svd(M, U_ini, S_ini, VT_ini, U_up, max_iter=10000, verbose=False)[source]¶
constrained_nnmf Approximate singular value decomposition with constraints.
function [U, S, V] = constrained_svd(M,U_ini,S_ini,V_ini,U_up,max_iter=10000,verbose=False)
- XRStools.xrs_utilities.convertSplitEDF2EDF(foldername)[source]¶
converts the old style EDF files (one image for horizontal and one image for vertical chambers) to the new style EDF (one single image).
- Arg:
- foldername (str): Path to folder with all the EDF-files to be
converted.
- XRStools.xrs_utilities.convg(x, y, fwhm)[source]¶
Convolution with Gaussian x = x-vector y = y-vector fwhm = fulll width at half maximum of the gaussian with which y is convoluted
- XRStools.xrs_utilities.convtoprim(hklconv)[source]¶
convtoprim converts diamond structure reciprocal lattice expressed in conventional lattice vectors to primitive one (Helsinki -> Palaiseau conversion) from S. Huotari
- XRStools.xrs_utilities.cshift(w1, th)[source]¶
cshift Calculates Compton peak position.
- Args:
w1 (float, array): Incident energy in [keV].
th (float): Scattering angle in [deg].
- Returns:
w2 (foat, array): Energy of Compton peak in [keV].
Funktion adapted from Keijo Hamalainen.
- XRStools.xrs_utilities.delE_JohannAberration(E, A, R, Theta)[source]¶
Calculates the Johann aberration of a spherical analyzer crystal.
- Args:
E (float): Working energy in [eV]. A (float): Analyzer aperture [mm]. R (float): Radius of the Rowland circle [mm]. Theta (float): Analyzer Bragg angle [degree].
- Returns:
Johann abberation in [eV].
- XRStools.xrs_utilities.delE_dicedAnalyzerIntrinsic(E, Dw, Theta)[source]¶
Calculates the intrinsic energy resolution of a diced crystal analyzer.
- Args:
E (float): Working energy in [eV]. Dw (float): Darwin width of the used reflection [microRad]. Theta (float): Analyzer Bragg angle [degree].
- Returns:
Intrinsic energy resolution of a perfect analyzer crystal.
- XRStools.xrs_utilities.delE_offRowland(E, z, A, R, Theta)[source]¶
Calculates the off-Rowland contribution of a spherical analyzer crystal.
- Args:
E (float): Working energy in [eV]. z (float): Off-Rowland distance [mm]. A (float): Analyzer aperture [mm]. R (float): Radius of the Rowland circle [mm]. Theta (float): Analyzer Bragg angle [degree].
- Returns:
Off-Rowland contribution in [eV] to the energy resolution.
- XRStools.xrs_utilities.delE_pixelSize(E, p, R, Theta)[source]¶
Calculates the pixel size contribution to the resolution function of a diced analyzer crystal.
- Args:
E (float): Working energy in [eV]. p (float): Pixel size in [mm]. R (float): Radius of the Rowland circle [mm]. Theta (float): Analyzer Bragg angle [degree].
- Returns:
Pixel size contribution in [eV] to the energy resolution for a diced analyzer crystal.
- XRStools.xrs_utilities.delE_sourceSize(E, s, R, Theta)[source]¶
Calculates the source size contribution to the resolution function.
- Args:
E (float): Working energy in [eV]. s (float): Source size in [mm]. R (float): Radius of the Rowland circle [mm]. Theta (float): Analyzer Bragg angle [degree].
- Returns:
Source size contribution in [eV] to the energy resolution.
- XRStools.xrs_utilities.delE_stressedCrystal(E, t, v, R, Theta)[source]¶
Calculates the stress induced contribution to the resulution function of a spherically bent crystal analyzer.
- Args:
E (float): Working energy in [eV]. t (float): Absorption length in the analyzer material [mm]. v (float): Poisson ratio of the analyzer material. R (float): Radius of the Rowland circle [mm]. Theta (float): Analyzer Bragg angle [degree].
- Returns:
Stress-induced contribution in [eV] to the energy resolution.
- XRStools.xrs_utilities.diode(current, energy, thickness=0.03)[source]¶
diode Calculates the number of photons incident for a Si PIPS diode.
- Args:
current (float): Diode current in [pA].
energy (float): Photon energy in [keV].
thickness (float): Thickness of Si active layer in [cm].
- Returns:
flux (float): Number of photons per second.
Function adapted from Matlab function by S. Huotari.
- XRStools.xrs_utilities.dspace(hkl=[6, 6, 0], xtal='Si')[source]¶
% DSPACE Gives d-spacing for given xtal % d=dspace(hkl,xtal) % hkl can be a matrix i.e. hkl=[1,0,0 ; 1,1,1]; % xtal=’Si’,’Ge’,’LiF’,’InSb’,’C’,’Dia’,’Li’ (case insensitive) % if xtal is number this is user as a d0 % % KH 28.09.93 % SH 2005 %
- class XRStools.xrs_utilities.dtxrd(hkl, energy, crystal='Si', asym_angle=0.0, angular_range=[- 0.0005, 0.0005], angular_step=1e-08)[source]¶
Bases:
object
class to hold all things dynamic theory of diffraction.
- XRStools.xrs_utilities.dtxrd_anomalous_absorption(energy, hkl, alpha=0.0, crystal='Si', angular_range=array([- 0.0005]))[source]¶
- XRStools.xrs_utilities.dtxrd_reflectivity(energy, hkl, alpha=0.0, crystal='Si', angular_range=array([- 0.0005]))[source]¶
- XRStools.xrs_utilities.e2pz(w1, w2, th)[source]¶
Calculates the momentum scale and the relativistic Compton cross section correction according to P. Holm, PRA 37, 3706 (1988).
This function is translated from Keijo Hamalainen’s Matlab implementation (KH 29.05.96).
- Args:
w1 (float or np.array): incident energy in [keV]
w2 (float or np.array): scattered energy in [keV]
th (float): scattering angle two theta in [deg]
- returns:
pz (float or np.array): momentum scale in [a.u.]
cf (float or np.array): cross section correction factor such that: J(pz) = cf * d^2(sigma)/d(w2)*d(Omega) [barn/atom/keV/srad]
- XRStools.xrs_utilities.edfread(filename)[source]¶
reads edf-file with filename “filename” OUTPUT: data = 256x256 numpy array
- XRStools.xrs_utilities.edfread_test(filename)[source]¶
reads edf-file with filename “filename” OUTPUT: data = 256x256 numpy array
here is how i opened the HH data: data = np.fromfile(f,np.int32) image = np.reshape(data,(dim,dim))
- XRStools.xrs_utilities.element(z)[source]¶
Converts atomic number into string of the element symbol and vice versa.
Returns atomic number of given element, if z is a string of the element symbol or string of element symbol of given atomic number z.
- Args:
z (string or int): string of the element symbol or atomic number.
- Returns:
Z (string or int): string of the element symbol or atomic number.
- XRStools.xrs_utilities.energy(d, ba)[source]¶
% ENERGY Calculates energy corrresponing to Bragg angle for given d-spacing % function e=energy(dspace,bragg_angle) % % dspace for reflection % bragg_angle in DEG % % KH 28.09.93
- XRStools.xrs_utilities.energy_monoangle(angle, d=1.6374176589984608)[source]¶
% ENERGY Calculates energy corrresponing to Bragg angle for given d-spacing % function e=energy(dspace,bragg_angle) % % dspace for reflection (defaulf for Si(311) reflection) % bragg_angle in DEG % % KH 28.09.93 %
- XRStools.xrs_utilities.fermi(rs)[source]¶
fermi Calculates the plasmon energy (in eV), Fermi energy (in eV), Fermi momentum (in a.u.), and critical plasmon cut-off vector (in a.u.).
- Args:
rs (float): electron separation parameter
- Returns:
wp (float): plasmon energy (in eV)
ef (float): Fermi energy (in eV)
kf (float): Fermi momentum (in a.u.)
kc (float): critical plasmon cut-off vector (in a.u.)
Based on Matlab function from A. Soininen.
- XRStools.xrs_utilities.find_center_of_mass(x, y)[source]¶
Returns the center of mass (first moment) for the given curve y(x)
- XRStools.xrs_utilities.find_diag_angles(q, x0, U, B, Lab, beam_in, lambdai, lambdao, tol=1e-08, method='BFGS')[source]¶
find_diag_angles Finds the FOURC spectrometer and sample angles for a desired q.
- Args:
q (array): Desired momentum transfer in Lab coordinates.
x0 (list): Guesses for the angles (tthv, tthh, chi, phi, omega).
U (array): 3x3 U-matrix Lab-to-sample transformation.
B (array): 3x3 B-matrix reciprocal lattice to absolute units transformation.
lambdai (float): Incident x-ray wavelength in Angstrom.
lambdao (float): Scattered x-ray wavelength in Angstrom.
tol (float): Toleranz for minimization (see scipy.optimize.minimize)
method (str): Method for minimization (see scipy.optimize.minimize)
- Returns:
ans (array): tthv, tthh, phi, chi, omega
- XRStools.xrs_utilities.fwhm(x, y)[source]¶
finds full width at half maximum of the curve y vs. x returns f = FWHM x0 = position of the maximum
- XRStools.xrs_utilities.get_UB_Q(tthv, tthh, phi, chi, omega, **kwargs)[source]¶
get_UB_Q Returns the momentum transfer and scattering vectors for given FOURC spectrometer and sample angles. U-, B-matrices and incident/scattered wavelength are passed as keyword-arguments.
- Args:
tthv (float): Spectrometer vertical 2Theta angle.
tthh (float): Spectrometer horizontal 2Theta angle.
chi (float): Sample rotation around x-direction.
phi (float): Sample rotation around y-direction.
omega (float): Sample rotation around z-direction.
- kwargs (dict): Dictionary with key-word arguments:
kwargs[‘U’] (array): 3x3 U-matrix Lab-to-sample transformation.
kwargs[‘B’] (array): 3x3 B-matrix reciprocal lattice to absolute units transformation.
kwargs[‘lambdai’] (float): Incident x-ray wavelength in Angstrom.
kwargs[‘lambdao’] (float): Scattered x-ray wavelength in Angstrom.
- Returns:
Q_sample (array): Momentum transfer in sample coordinates.
Ki_sample (array): Incident beam direction in sample coordinates.
Ko_sample (array): Scattered beam direction in sample coordinates.
- XRStools.xrs_utilities.get_gnuplot_rgb(start=None, end=None, length=None)[source]¶
get_gnuplot_rgb Prints out a progression of RGB hex-keys to use in Gnuplot.
- Args:
start (array): RGB code to start from (must be numbers out of [0,1]).
end (array): RGB code to end at (must be numbers out of [0,1]).
length (int): How many colors to print out.
- XRStools.xrs_utilities.get_num_of_MD_steps(time_ps, time_step)[source]¶
Calculates the number of steps in an MD simulation for a desired time (in ps) and given step size (in a.u.)
- Args:
time_ps (float): Desired time span (ps). time_step (float): Chosen time step (a.u.).
- Returns:
The number of steps required to span the desired time span.
- XRStools.xrs_utilities.getpenetrationdepth(energy, formulas, concentrations, densities)[source]¶
returns the penetration depth of a mixture of chemical formulas with certain concentrations and densities
- XRStools.xrs_utilities.gettransmission(energy, formulas, concentrations, densities, thickness)[source]¶
returns the transmission through a sample composed of chemical formulas with certain densities mixed to certain concentrations, and a thickness
- XRStools.xrs_utilities.hlike_Rwfn(n, l, r, Z)[source]¶
hlike_Rwfn Returns an array with the radial part of a hydrogen-like wave function.
- Args:
n (integer): main quantum number n
l (integer): orbitalquantum number l
r (array): vector of radii on which the function should be evaluated
Z (float): effective nuclear charge
- XRStools.xrs_utilities.householder(b, k)[source]¶
function H = householder(b, k) % H = householder(b, k) % Atkinson, Section 9.3, p. 611 % b is a column vector, k an index < length(b) % Constructs a matrix H that annihilates entries % in the product H*b below index k
% $Id: householder.m,v 1.1 2008-01-16 15:33:30 mike Exp $ % M. M. Sussman
- XRStools.xrs_utilities.interpolate_M(xc, xi, yi, i0)[source]¶
Linear interpolation scheme after Martin Sundermann that conserves the absolute number of counts.
ONLY WORKS FOR EQUALLY/EVENLY SPACED XC, XI!
- Args:
xc (np.array): The x-coordinates of the interpolated values. xi (np.array): The x-coordinates of the data points, must be increasing. yi (np.array): The y-coordinates of the data points, same length as xp. i0 (np.array): Normalization values for the data points, same length as xp.
- Returns:
ic (np.array): The interpolated and normalized data points.
from scipy.interpolate import Rbf x = arange(20) d = zeros(len(x)) d[10] = 1 xc = arange(0.5,19.5) rbfi = Rbf(x, d) di = rbfi(xc)
- XRStools.xrs_utilities.is_allowed_refl_fcc(H)[source]¶
is_allowed_refl_fcc Check if given reflection is allowed for a FCC lattice.
- Args:
H (array, list, tuple): H=[h,k,l]
- Returns:
boolean
- XRStools.xrs_utilities.lindhard_pol(q, w, rs=3.93, use_corr=False, lifetime=0.28)[source]¶
lindhard_pol Calculates the Lindhard polarizability function (RPA) for certain q (a.u.), w (a.u.) and rs (a.u.).
- Args:
q (float): momentum transfer (in a.u.)
w (float): energy (in a.u.)
rs (float): electron parameter
use_corr (boolean): if True, uses Bernardo’s calculation for n(k) instead of the Fermi function.
lifetime (float): life time (default is 0.28 eV for Na).
Based on Matlab function by S. Huotari.
- XRStools.xrs_utilities.makeprofile(element, filename='/usr/lib/python3/dist-packages/XRStools/resources/data/ComptonProfiles.dat', E0=9.69, tth=35.0, correctasym=None)[source]¶
takes the profiles from ‘makepzprofile()’, converts them onto eloss scale and normalizes them to S(q,w) [1/eV] input: element = element symbol (e.g. ‘Si’, ‘Al’, etc.) filename = path and filename to tabulated profiles E0 = scattering energy [keV] tth = scattering angle [deg] returns: enscale = energy loss scale J = total CP C = only core contribution to CP V = only valence contribution to CP q = momentum transfer [a.u.]
- XRStools.xrs_utilities.makeprofile_comp(formula, filename='/usr/lib/python3/dist-packages/XRStools/resources/data/ComptonProfiles.dat', E0=9.69, tth=35, correctasym=None)[source]¶
returns the compton profile of a chemical compound with formula ‘formula’ input: formula = string of a chemical formula (e.g. ‘SiO2’, ‘Ba8Si46’, etc.) filename = path and filename to tabulated profiles E0 = scattering energy [keV] tth = scattering angle [deg] returns: eloss = energy loss scale J = total CP C = only core contribution to CP V = only valence contribution to CP q = momentum transfer [a.u.]
- XRStools.xrs_utilities.makeprofile_compds(formulas, concentrations=None, filename='/usr/lib/python3/dist-packages/XRStools/resources/data/ComptonProfiles.dat', E0=9.69, tth=35.0, correctasym=None)[source]¶
returns sum of compton profiles from a lost of chemical compounds weighted by the given concentration
- XRStools.xrs_utilities.makepzprofile(element, filename='/usr/lib/python3/dist-packages/XRStools/resources/data/ComptonProfiles.dat')[source]¶
constructs compton profiles of element ‘element’ on pz-scale (-100:100 a.u.) from the Biggs tables provided in ‘filename’
- input:
element = element symbol (e.g. ‘Si’, ‘Al’, etc.)
filename = path and filename to tabulated profiles
- returns:
pzprofile = numpy array of the CP: * 1. column: pz-scale * 2. … n. columns: compton profile of nth shell * binden = binding energies of shells * occupation = number of electrons in the according shells
- class XRStools.xrs_utilities.maxipix_det(name, spot_arrangement)[source]¶
Bases:
object
Class to store some useful values from the detectors used. To be used for arranging the ROIs.
- XRStools.xrs_utilities.momtrans_au(e1, e2, tth)[source]¶
Calculates the momentum transfer in atomic units input: e1 = incident energy [keV] e2 = scattered energy [keV] tth = scattering angle [deg] returns: q = momentum transfer [a.u.] (corresponding to sin(th)/lambda)
- XRStools.xrs_utilities.momtrans_inva(e1, e2, tth)[source]¶
Calculates the momentum transfer in inverse angstrom input: e1 = incident energy [keV] e2 = scattered energy [keV] tth = scattering angle [deg] returns: q = momentum transfer [a.u.] (corresponding to sin(th)/lambda)
- XRStools.xrs_utilities.mpr(energy, compound)[source]¶
Calculates the photoelectric, elastic, and inelastic absorption of a chemical compound.
Calculates the photoelectric, elastic, and inelastic absorption of a chemical compound.
- Args:
energy (np.array): energy scale in [keV].
compound (string): chemical sum formula (e.g. ‘SiO2’)
- Returns:
murho (np.array): absorption coefficient normalized by the density.
rho (float): density in UNITS?
m (float): atomic mass in UNITS?
- XRStools.xrs_utilities.mpr_compds(energy, formulas, concentrations, E0, rho_formu)[source]¶
Calculates the photoelectric, elastic, and inelastic absorption of a mix of compounds.
Returns the photoelectric absorption for a sum of different chemical compounds.
- Args:
energy (np.array): energy scale in [keV].
formulas (list of strings): list of chemical sum formulas
- Returns:
murho (np.array): absorption coefficient normalized by the density.
rho (float): density in UNITS?
m (float): atomic mass in UNITS?
- XRStools.xrs_utilities.myprho(energy, Z, logtablefile='/usr/lib/python3/dist-packages/XRStools/resources/data/logtable.dat')[source]¶
Calculates the photoelectric, elastic, and inelastic absorption of an element Z
Calculates the photelectric , elastic, and inelastic absorption of an element Z. Z can be atomic number or element symbol.
- Args:
energy (np.array): energy scale in [keV].
Z (string or int): atomic number or string of element symbol.
- Returns:
murho (np.array): absorption coefficient normalized by the density.
rho (float): density in UNITS?
m (float): atomic mass in UNITS?
- XRStools.xrs_utilities.odefctn(y, t, abb0, abb1, abb7, abb8, lex, sgbeta, y0, c1)[source]¶
#% [T,Y] = ODE23(ODEFUN,TSPAN,Y0,OPTIONS,P1,P2,…) passes the additional #% parameters P1,P2,… to the ODE function as ODEFUN(T,Y,P1,P2…), and to #% all functions specified in OPTIONS. Use OPTIONS = [] as a place holder if #% no options are set.
- XRStools.xrs_utilities.parseformula(formula)[source]¶
Parses a chemical sum formula.
Parses the constituing elements and stoichiometries from a given chemical sum formula.
- Args:
formula (string): string of a chemical formula (e.g. ‘SiO2’, ‘Ba8Si46’, etc.)
- Returns:
elements (list): list of strings of constituting elemental symbols.
stoichiometries (list): list of according stoichiometries in the same order as ‘elements’.
- XRStools.xrs_utilities.plotpenetrationdepth(energy, formulas, concentrations, densities)[source]¶
opens a plot window of the penetration depth of a mixture of chemical formulas with certain concentrations and densities plotted along the given energy vector
- XRStools.xrs_utilities.plottransmission(energy, formulas, concentrations, densities, thickness)[source]¶
opens a plot with the transmission plotted along the given energy vector
- XRStools.xrs_utilities.primtoconv(hklprim)[source]¶
primtoconv converts diamond structure reciprocal lattice expressed in primitive basis to the conventional basis (Palaiseau -> Helsinki conversion) from S. Huotari
- XRStools.xrs_utilities.pz2e1(w2, pz, th)[source]¶
Calculates the incident energy for a specific scattered photon and momentum value.
Returns the incident energy for a given photon energy and scattering angle. This function is translated from Keijo Hamalainen’s Matlab implementation (KH 29.05.96).
- Args:
w2 (float): scattered photon energy in [keV]
pz (np.array): pz scale in [a.u.]
th (float): scattering angle two theta in [deg]
- Returns:
w1 (np.array): incident energy in [keV]
- XRStools.xrs_utilities.read_dft_wfn(element, n, l, spin=None, directory='/usr/lib/python3/dist-packages/XRStools/resources/data')[source]¶
read_dft_wfn Parses radial parts of wavefunctions.
- Args:
element (str): Element symbol.
n (int): Main quantum number.
l (int): Orbital quantum number.
spin (str): Which spin channel, default is average over up and down.
directory (str): Path to directory where the wavefunctions can be found.
- Returns:
r (np.array): radius
wfn (np.array):
- XRStools.xrs_utilities.readbiggsdata(filename, element)[source]¶
Reads Hartree-Fock Profile of element ‘element’ from values tabulated by Biggs et al. (Atomic Data and Nuclear Data Tables 16, 201-309 (1975)) as provided by the DABAX library (http://ftp.esrf.eu/pub/scisoft/xop2.3/DabaxFiles/ComptonProfiles.dat). input: filename = path to the ComptonProfiles.dat file (the file should be distributed with this package) element = string of element name returns:
- data = the data for the according element as in the file:
#UD Columns:
#UD col1: pz in atomic units
#UD col2: Total compton profile (sum over the atomic electrons
#UD col3,…coln: Compton profile for the individual sub-shells
occupation = occupation number of the according shells
bindingen = binding energies of the accorting shells
colnames = strings of column names as used in the file
- XRStools.xrs_utilities.readfio(prefix, scannumber, repnumber=0)[source]¶
if repnumber = 0: reads a spectra-file (name: prefix_scannumber.fio) if repnumber > 1: reads a spectra-file (name: prefix_scannumber_rrepnumber.fio)
- XRStools.xrs_utilities.readp01image(filename)[source]¶
reads a detector file from PetraIII beamline P01
- XRStools.xrs_utilities.readp01scan(prefix, scannumber)[source]¶
reads a whole scan from PetraIII beamline P01 (experimental)
- XRStools.xrs_utilities.readp01scan_rep(prefix, scannumber, repetition)[source]¶
reads a whole scan with repititions from PetraIII beamline P01 (experimental)
- XRStools.xrs_utilities.savitzky_golay(y, window_size, order, deriv=0, rate=1)[source]¶
Smooth (and optionally differentiate) data with a Savitzky-Golay filter. The Savitzky-Golay filter removes high frequency noise from data. It has the advantage of preserving the original shape and features of the signal better than other types of filtering approaches, such as moving averages techniques.
- Parameters:
y : array_like, shape (N,) the values of the time history of the signal.
window_size : int the length of the window. Must be an odd integer number.
order : int the order of the polynomial used in the filtering. Must be less then window_size - 1.
deriv: int the order of the derivative to compute (default = 0 means only smoothing)
- Returns
ys : ndarray, shape (N) the smoothed signal (or it’s n-th derivative).
- Notes:
The Savitzky-Golay is a type of low-pass filter, particularly suited for smoothing noisy data. The main idea behind this approach is to make for each point a least-square fit with a polynomial of high order over a odd-sized window centered at the point.
Examples
t = np.linspace(-4, 4, 500) y = np.exp( -t**2 ) + np.random.normal(0, 0.05, t.shape) ysg = savitzky_golay(y, window_size=31, order=4) import matplotlib.pyplot as plt plt.plot(t, y, label='Noisy signal') plt.plot(t, np.exp(-t**2), 'k', lw=1.5, label='Original signal') plt.plot(t, ysg, 'r', label='Filtered signal') plt.legend() plt.show()
- References ::
- 1
A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of Data by Simplified Least Squares Procedures. Analytical Chemistry, 1964, 36 (8), pp 1627-1639.
- 2
Numerical Recipes 3rd Edition: The Art of Scientific Computing W.H. Press, S.A. Teukolsky, W.T. Vetterling, B.P. Flannery Cambridge University Press ISBN-13: 9780521880688
- XRStools.xrs_utilities.sigmainc(Z, energy, logtablefile='/usr/lib/python3/dist-packages/XRStools/resources/data/logtable.dat')[source]¶
sigmainc Calculates the Incoherent Scattering Cross Section in cm^2/g using Log-Log Fit.
- Args:
z (int or string): Element number or elements symbol.
energy (float or array): Energy (can be number or vector)
- Returns:
tau (float or array): Photoelectric cross section in [cm**2/g]
Adapted from original Matlab function of Keijo Hamalainen.
- XRStools.xrs_utilities.specread(filename, nscan)[source]¶
reads scan “nscan” from SPEC-file “filename”
- INPUT:
filename = string with the SPEC-file name
nscan = number (int) of desired scan
- OUTPUT:
data =
motors =
counters = dictionary
- XRStools.xrs_utilities.spline2(x, y, x2)[source]¶
Extrapolates the smaller and larger valuea as a constant
- XRStools.xrs_utilities.stiff_compl_matrix_Si(e1, e2, e3, ansys=False)[source]¶
stiff_compl_matrix_Si Returns stiffnes and compliance tensor of Si for a given orientation.
- Args:
e1 (np.array): unit vector normal to crystal surface
e2 (np.array): unit vector crystal surface
e3 (np.array): unit vector orthogonal to e2
- Returns:
S (np.array): compliance tensor in new coordinate system
C (np.array): stiffnes tensor in new coordinate system
E (np.array): Young’s modulus in [GPa]
G (np.array): shear modulus in [GPa]
nu (np.array): Poisson ratio
Copied from S.I. of L. Zhang et al. “Anisotropic elasticity of silicon and its application to the modelling of X-ray optics.” J. Synchrotron Rad. 21, no. 3 (2014): 507-517.
- XRStools.xrs_utilities.sumx(A)[source]¶
Short-hand command to sum over 1st dimension of a N-D matrix (N>2) and to squeeze it to N-1-D matrix.
- XRStools.xrs_utilities.taupgen(e, hkl=[6, 6, 0], crystals='Si', R=1.0, dev=array([- 50., - 49., - 48., - 47., - 46., - 45., - 44., - 43., - 42., - 41., - 40., - 39., - 38., - 37., - 36., - 35., - 34., - 33., - 32., - 31., - 30., - 29., - 28., - 27., - 26., - 25., - 24., - 23., - 22., - 21., - 20., - 19., - 18., - 17., - 16., - 15., - 14., - 13., - 12., - 11., - 10., - 9., - 8., - 7., - 6., - 5., - 4., - 3., - 2., - 1., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25., 26., 27., 28., 29., 30., 31., 32., 33., 34., 35., 36., 37., 38., 39., 40., 41., 42., 43., 44., 45., 46., 47., 48., 49., 50., 51., 52., 53., 54., 55., 56., 57., 58., 59., 60., 61., 62., 63., 64., 65., 66., 67., 68., 69., 70., 71., 72., 73., 74., 75., 76., 77., 78., 79., 80., 81., 82., 83., 84., 85., 86., 87., 88., 89., 90., 91., 92., 93., 94., 95., 96., 97., 98., 99., 100., 101., 102., 103., 104., 105., 106., 107., 108., 109., 110., 111., 112., 113., 114., 115., 116., 117., 118., 119., 120., 121., 122., 123., 124., 125., 126., 127., 128., 129., 130., 131., 132., 133., 134., 135., 136., 137., 138., 139., 140., 141., 142., 143., 144., 145., 146., 147., 148., 149.]), alpha=0.0)[source]¶
% TAUPGEN Calculates the reflectivity curves of bent crystals % % function [refl,e,dev]=taupgen_new(e,hkl,crystals,R,dev,alpha); % % e = fixed nominal energy in keV % hkl = reflection order vector, e.g. [1 1 1] % crystals = crystal string, e.g. ‘si’ or ‘ge’ % R = bending radius in meters % dev = deviation parameter for which the % curve will be calculated (vector) (optional) % alpha = asymmetry angle % based on a FORTRAN program of Michael Krisch % Translitterated to Matlab by Simo Huotari 2006, 2007 % Is far away from being good matlab writing - mostly copy&paste from % the fortran routines. Frankly, my dear, I don’t give a damn. % Complaints -> /dev/null
- XRStools.xrs_utilities.taupgen_amplitude(e, hkl=[6, 6, 0], crystals='Si', R=1.0, dev=array([- 50., - 49., - 48., - 47., - 46., - 45., - 44., - 43., - 42., - 41., - 40., - 39., - 38., - 37., - 36., - 35., - 34., - 33., - 32., - 31., - 30., - 29., - 28., - 27., - 26., - 25., - 24., - 23., - 22., - 21., - 20., - 19., - 18., - 17., - 16., - 15., - 14., - 13., - 12., - 11., - 10., - 9., - 8., - 7., - 6., - 5., - 4., - 3., - 2., - 1., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25., 26., 27., 28., 29., 30., 31., 32., 33., 34., 35., 36., 37., 38., 39., 40., 41., 42., 43., 44., 45., 46., 47., 48., 49., 50., 51., 52., 53., 54., 55., 56., 57., 58., 59., 60., 61., 62., 63., 64., 65., 66., 67., 68., 69., 70., 71., 72., 73., 74., 75., 76., 77., 78., 79., 80., 81., 82., 83., 84., 85., 86., 87., 88., 89., 90., 91., 92., 93., 94., 95., 96., 97., 98., 99., 100., 101., 102., 103., 104., 105., 106., 107., 108., 109., 110., 111., 112., 113., 114., 115., 116., 117., 118., 119., 120., 121., 122., 123., 124., 125., 126., 127., 128., 129., 130., 131., 132., 133., 134., 135., 136., 137., 138., 139., 140., 141., 142., 143., 144., 145., 146., 147., 148., 149.]), alpha=0.0)[source]¶
% TAUPGEN Calculates the reflectivity curves of bent crystals % % function [refl,e,dev]=taupgen_new(e,hkl,crystals,R,dev,alpha); % % e = fixed nominal energy in keV % hkl = reflection order vector, e.g. [1 1 1] % crystals = crystal string, e.g. ‘si’ or ‘ge’ % R = bending radius in meters % dev = deviation parameter for which the % curve will be calculated (vector) (optional) % alpha = asymmetry angle % based on a FORTRAN program of Michael Krisch % Translitterated to Matlab by Simo Huotari 2006, 2007 % Is far away from being good matlab writing - mostly copy&paste from % the fortran routines. Frankly, my dear, I don’t give a damn. % Complaints -> /dev/null
- XRStools.xrs_utilities.tauphoto(Z, energy, logtablefile='/usr/lib/python3/dist-packages/XRStools/resources/data/logtable.dat')[source]¶
tauphoto Calculates Photoelectric Cross Section in cm^2/g using Log-Log Fit.
- Args:
z (int or string): Element number or elements symbol.
energy (float or array): Energy (can be number or vector)
- Returns:
tau (float or array): Photoelectric cross section in [cm**2/g]
Adapted from original Matlab function of Keijo Hamalainen.
- XRStools.xrs_utilities.unconstrained_mf(A, numComp=3, maxIter=1000, tol=1e-08)[source]¶
unconstrained_mf Returns main components from an off-diagonal Matrix (energy-loss x angular-departure), using the power method iteratively on the different main components.
- XRStools.xrs_utilities.vangle(v1, v2)[source]¶
vangle Calculates the angle between two cartesian vectors v1 and v2 in degrees.
- Args:
v1 (np.array): first vector.
v2 (np.array): second vector.
- Returns:
th (float): angle between first and second vector.
Function by S. Huotari, adopted for Python.
- XRStools.xrs_utilities.vrot(v, vaxis, phi)[source]¶
vrot Rotates a vector around a given axis.
- Args:
v (np.array): vector to be rotated
vaxis (np.array): rotation axis
phi (float): angle [deg] respecting the right-hand rule
- Returns:
v2 (np.array): new rotated vector
Function by S. Huotari (2007) adopted to Python.
- XRStools.xrs_utilities.vrot2(vector1, vector2, angle)[source]¶
rotMatrix Rotate vector1 around vector2 by an angle.
- XRStools.xrs_utilities.xas_fluo_correct(ene, mu, formula, fluo_ene, edge_ene, angin, angout)[source]¶
xas_fluo_correct Fluorescence yield over-absorption correction as in Larch/Athena. see: https://www3.aps.anl.gov/haskel/FLUO/Fluo-manual.pdf
- Args:
ene (np.array): energy axis in [keV]
mu (np.array): measured fluorescence spectrum
formula (str): chemical sum formulas (e.g. ‘SiO2’)
fluo_ene (float): energy in keV of main fluorescence line
edge_ene (float): edge energy in [keV]
angin (float): incidence angle (relative to sample normal) [deg.]
angout (float): exit angle (relative to sample normal) [deg.]
- Returns:
ene (np.array): energy axis in [keV]
mu_corr (np.array): corrected fluorescence spectrum