Developers Corner

XRStools.roifinder_and_gui Module

XRStools.roifinder_and_gui.create_diff_image(scans, scannumbers, energy_keV)[source]

Returns a summed image from all scans with numbers ‘scannumbers’. scans = dictionary of objects from the scan-class scannumbers = single scannumber, or list of scannumbers from which an image should be constructed

XRStools.roifinder_and_gui.define_lin_roi(height, image_shape, verbose=False)[source]

Lets you pick 2 points on a current image and returns a linear ROI of height (2*height+1). height = number of pixels that define the height of the ROI image_shape = tuple with shape of the current image (i.e. (256,256))

XRStools.roifinder_and_gui.define_polygon_roi(image_shape, verbose=False)[source]

Define a polygon shaped ROI from a current image by selecting points.

XRStools.roifinder_and_gui.define_zoom_roi(input_image, verbose=False)[source]

Parses the current figure limits and uses them to define a rectangle of ” roi_number”s in the matrix given by roi_matrix. input_image = unzoomed figure roi_matrix = current roi matrix which will be altered

XRStools.roifinder_and_gui.findroisColumns(scans, scannumbers, roi_obj, whichroi, logscaling=False)[source]

Constructs a waterfall plot from the columns in a scan, i.e. energy vs. pixel number along the ROI scannumbers = scannumber or list of scannumbers from which to construct the plot whichroi = integer (starting from 0) from which ROI to use for constructing the plot

XRStools.roifinder_and_gui.get_auto_rois_eachdet(scans, DET_PIXEL_NUM, scannumbers, kernel_size=5, threshold=100.0, logscaling=True, colormap='jet', interpolation='bilinear')[source]

Define ROIs automatically using median filtering and a variable threshold for each detector separately. scannumbers = either single scannumber or list of scannumbers kernel_size = used kernel size for the median filter (must be an odd integer) logscaling = set to ‘True’ if images is to be shown on log-scale (default is True) colormap = string to define the colormap which is to be used for display (anything

supported by matplotlib, ‘jet’ by default)
interpolation = interpolation scheme to be used for displaying the image (anything
supported by matplotlib, ‘nearest’ by default)
XRStools.roifinder_and_gui.get_polygon_rois_eachdet(scans, DET_PIXEL_NUM, scannumbers, logscaling=True, colormap='jet', interpolation='nearest')[source]

Define a polygon shaped ROI from an image constructed from the sum of all edf-files in ‘scannumbers’ image_shape = tuple with shape of the current image (i.e. (256,256)) scannumbers = either single scannumber or list of scannumbers logscaling = set to ‘True’ if images is to be shown on log-scale (default is True) colormap = string to define the colormap which is to be used for display (anything

supported by matplotlib, ‘jet’ by default)
interpolation = interpolation scheme to be used for displaying the image (anything
supported by matplotlib, ‘nearest’ by default)
XRStools.roifinder_and_gui.get_zoom_rois(scans, scannumbers, logscaling=True, colormap='jet', interpolation='nearest')[source]
class XRStools.roifinder_and_gui.roi_finder[source]

Class to define ROIs from a 2D image.

appendROIobject(roi_object)[source]
deleterois()[source]

Clear the existing ROIs by creating a fresh roi_object.

find_cw_rois(roi_obj, pw_data)[source]

find_cw_rois Allows for manual refinement of ROIs by plotting the spectra column-wise. Loops through the spectra column-by-column and ROI by ROI, click above the black line to keep the column plotted, click below the black line to discard the column of pixels.

roi_obj (roi_object): ROI object from the XRStools.xrs_rois module with roughly defined ROIs. pw_data (np.array): List containing one 2D numpy array per ROI holding pixel-wise signals.

find_pw_rois(roi_obj, pw_data, save_dataset=False)[source]

find_pw_rois Allows for manual refinement of ROIs by plotting the spectra pixel-wise. Loops through the spectra pixel-by-pixel and ROI by ROI, click above the black line to keep the pixel plotted, click below the black line to discard the pixel.

roi_obj (roi_object): ROI object from the XRStools.xrs_rois module with roughly defined ROIs. pw_data (np.array): List containing one 2D numpy array per ROI holding pixel-wise signals.

get_auto_rois(input_image, kernel_size=5, threshold=100.0, logscaling=True, colormap='jet', interpolation='bilinear')[source]

Define ROIs by choosing a threshold using a slider bar under the figure. In this function, the entire detector is shown. input_image = 2D numpy array with the image to be displayed kernal_size = integer defining the median filter window (has to be odd) theshold = initial number defining the upper end value for the slider bar (amax(input_image)/threshold defines this number), can be within GUI logscaling = boolean, if True (default) the logarithm of input_image is displayed colormap = matplotlib color scheme used in the display interpolation = matplotlib interpolation scheme used for the display

get_auto_rois_eachdet(input_image, kernel_size=5, threshold=100.0, logscaling=True, colormap='jet', interpolation='bilinear')[source]

Define ROIs automatically using median filtering and a variable threshold for each detector separately. scannumbers = either single scannumber or list of scannumbers kernel_size = used kernel size for the median filter (must be an odd integer) logscaling = set to ‘True’ if images is to be shown on log-scale (default is True) colormap = string to define the colormap which is to be used for display (anything

supported by matplotlib, ‘jet’ by default)
interpolation = interpolation scheme to be used for displaying the image (anything
supported by matplotlib, ‘nearest’ by default)
get_linear_rois(input_image, logscaling=True, height=5, colormap='jet', interpolation='nearest')[source]

Define ROIs by clicking two points on a 2D image. number_of_rois = integer defining how many ROIs should be determined input_object = 2D array, scan_object, or dictionary of scans to define the ROIs from logscaling = boolean, to determine wether the image is shown on a log-scale (default = True) height = integer defining the height (in pixels) of the ROIs

get_polygon_rois(input_image, modind=-1, logscaling=True, colormap='jet', interpolation='nearest')[source]

Define ROIs by clicking arbitrary number of points on a 2D image: LEFT CLICK to define the corner points of polygon, MIDDLE CLICK to finish current ROI and move to the next ROI, RIGHT CLICK to cancel the previous point of polygon input_object = 2D array, scan_object, or dictionary of scans to define the ROIs from modind = integer to identify module, if -1 (default), no module info will be in title (the case of one big image) logscaling = boolean, to determine wether the image is shown on a log-scale (default = True)

get_zoom_rois(input_image, logscaling=True, colormap='jet', interpolation='nearest')[source]

Define ROIs by clicking two points on a 2D image. number_of_rois = integer defining how many ROIs should be determined input_object = 2D array, scan_object, or dictionary of scans to define the ROIs from logscaling = boolean, to determine wether the image is shown on a log-scale (default = True) height = integer defining the height (in pixels) of the ROIs

import_simo_style_rois(roiList, detImageShape=(512, 768))[source]

import_simo_style_rois Converts Simo-style ROIs to the conventions used here.

roiList (list): List of tuples that have [(xmin, xmax, ymin, ymax), (xmin, xmax, ymin, ymax), ...]. detImageShape (tuple): Shape of the detector image (for convertion to roiMatrix)

refine_pw_rois(roi_obj, pw_data, n_components=2, method='nnma', cov_thresh=-1)[source]

refine_pw_rois

Use decomposition of pixelwise data for each ROI to find which of the pixels holds data from the sample and which one only has background.

roi_obj (xrs_rois.roi_object): ROI object to be refined pw_data (list): list containing one 2D numpy array per ROI holding pixel-wise signals n_components (int): number of components in the decomposition method (string): keyword describing which decomposition to be used (‘pca’, ‘ica’, ‘nnma’)

show_rois(interpolation='nearest', colormap='jet')[source]

show_rois Creates a figure with the defined ROIs as numbered boxes on it.

interpolation (str) : Interpolation scheme used in the plot. colormap (str) : Colormap used in the plot.

XRStools.roifinder_and_gui.show_rois(roi_matrix)[source]

Creates a figure with the defined ROIs as numbered boxes on it.

XRStools.roifinder_and_gui.test_roifinder(roi_type_str, imagesize=[512, 768], scan=None)[source]

Runs the roi_finder class on a random image of given type for testing purposes. scan[0] = absolute path to a spec file scan[1] = energycolumn=’energy’ scan[2] = monitorcolumn=’kap4dio’ scan[3] = scan number from which to take images

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 ...).

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.].

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, W, H, W_up, H_up)[source]

NNMFcost Returns cost and gradient for NNMF with constraints.

TTsolver1D(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_')

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.

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.

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).

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.
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).

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].

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, 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 %

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.cixsUBfind(x, G, Q_sample, wi, wo, lambdai, lambdao)[source]

cixsUBfind

XRStools.xrs_utilities.cixsUBgetAngles_primo(Q)[source]
XRStools.xrs_utilities.cixsUBgetAngles_secondo(Q)[source]
XRStools.xrs_utilities.cixsUBgetAngles_terzo(Q)[source]
XRStools.xrs_utilities.cixsUBgetQ_primo(tthv, tthh, psi)[source]
XRStools.xrs_utilities.cixsUBgetQ_secondo(tthv, tthh, psi)[source]
XRStools.xrs_utilities.cixsUBgetQ_terzo(tthv, tthh, psi)[source]
XRStools.xrs_utilities.cixs_primo(tthv, tthh, psi, anal_braggd=86.5)[source]

cixs_primo

XRStools.xrs_utilities.cixs_secondo(tthv, tthh, psi, anal_braggd=86.5)[source]

cixs_secondo

XRStools.xrs_utilities.cixs_terzo(tthv, tthh, psi, anal_braggd=86.5)[source]

cixs_terzo

XRStools.xrs_utilities.compute_matrix_elements(R1, R2, k, r)[source]
XRStools.xrs_utilities.con2mat(x, W, H, W_up, H_up)[source]
XRStools.xrs_utilities.constrained_mf(A, W_ini, W_up, coeff_ini, coeff_up, maxIter=1000, tol=1e-08)[source]

cfactorizeOffDiaMatrix constrained version of factorizeOffDiaMatrix Returns main components from an off-diagonal Matrix (energy-loss x angular-departure).

XRStools.xrs_utilities.constrained_nnmf(A, W_ini, H_ini, W_up, H_up, max_iter=10000, verbose=False)[source]

constrained_nnmf Approximate non-negative matrix factorization with constrains.

function [W H]=johannes_nnmf_ALS(A,W_ini,H_ini,W_up,H_up) % ************************************************************* % ************************************************************* % ** [W H]=johannes_nnmf(A,W_ini,H_ini,W_up,H_up) ** % ** performs A=WH approximate matrix factorization, ** % ** where A(n*m), W(n*k), and H(k*m) are non-negative matrices, ** % ** and k<min(n,m). Masking arrays W_up(n*k), H_up(k*m) = 0,1 ** % ** control elements of W and H to be updated (1) or not (0). ** % ** This fact can be used to set constraints. ** % ** ** % ** Johannes Niskanen 13.10.2015 ** % ** ** % ************************************************************* % ************************************************************* by Johannes Niskanen

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.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.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.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 %

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).

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.

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.).

rs (float): electron separation parameter

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.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.gauss(x, x0, fwhm)[source]
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.

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.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.).

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='/mntdirect/_scisoft/users/mirone/WORKS/Christoph/XRStoolsSuperResolution/XRStools/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='/mntdirect/_scisoft/users/mirone/WORKS/Christoph/XRStoolsSuperResolution/XRStools/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='/mntdirect/_scisoft/users/mirone/WORKS/Christoph/XRStoolsSuperResolution/XRStools/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='/mntdirect/_scisoft/users/mirone/WORKS/Christoph/XRStoolsSuperResolution/XRStools/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

XRStools.xrs_utilities.mat2con(W, H, W_up, H_up)[source]
class XRStools.xrs_utilities.maxipix_det(name, spot_arrangement)[source]

Class to store some useful values from the detectors used. To be used for arranging the ROIs.

get_det_name()[source]
get_pixel_range()[source]
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.

energy (np.array): energy scale in [keV]. compound (string): chemical sum formula (e.g. ‘SiO2’)

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.

energy (np.array): energy scale in [keV]. formulas (list of strings): list of chemical sum formulas

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='/mntdirect/_scisoft/users/mirone/WORKS/Christoph/XRStoolsSuperResolution/XRStools/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.

energy (np.array): energy scale in [keV]. Z (string or int): atomic number or string of element symbol.

murho (np.array): absorption coefficient normalized by the density. rho (float): density in UNITS? m (float): atomic mass in UNITS?

XRStools.xrs_utilities.nonzeroavg(y=None)[source]
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.odefctn_CN(yCN, t, abb0, abb1, abb7, abb8N, lex, sgbeta, y0, c1)[source]
XRStools.xrs_utilities.parseformula(formula)[source]

Parses a chemical sum formula.

Parses the constituing elements and stoichiometries from a given chemical sum formula.

formula (string): string of a chemical formula (e.g. ‘SiO2’, ‘Ba8Si46’, etc.)

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).

w2 (float): scattered photon energy in [keV] pz (np.array): pz scale in [a.u.] th (float): scattering angle two theta in [deg]

w1 (np.array): incident energy in [keV]

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.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.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.svd_my(M, maxiter=100, eta=0.1)[source]
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)

% 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.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.

v1 (np.array): first vector. v2 (np.array): second vector.

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.

v (np.array): vector to be rotated vaxis (np.array): rotation axis phi (float): angle [deg] respecting the right-hand rule

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.XRStool Package

XRStools.xrs_calctools Module

XRStools.xrs_calctools.alterGROatomNames(filename, oldName, newName)[source]
XRStools.xrs_calctools.axsfTrajParser(filename)[source]

axsfTrajParser

XRStools.xrs_calctools.beta(a, b, size=None)

The Beta distribution over [0, 1].

The Beta distribution is a special case of the Dirichlet distribution, and is related to the Gamma distribution. It has the probability distribution function

f(x; a,b) = \frac{1}{B(\alpha, \beta)} x^{\alpha - 1}
(1 - x)^{\beta - 1},

where the normalisation, B, is the beta function,

B(\alpha, \beta) = \int_0^1 t^{\alpha - 1}
(1 - t)^{\beta - 1} dt.

It is often seen in Bayesian inference and order statistics.

a : float
Alpha, non-negative.
b : float
Beta, non-negative.
size : tuple of ints, optional
The number of samples to draw. The output is packed according to the size given.
out : ndarray
Array of the given shape, containing values drawn from a Beta distribution.
XRStools.xrs_calctools.binomial(n, p, size=None)

Draw samples from a binomial distribution.

Samples are drawn from a Binomial distribution with specified parameters, n trials and p probability of success where n an integer >= 0 and p is in the interval [0,1]. (n may be input as a float, but it is truncated to an integer in use)

n : float (but truncated to an integer)
parameter, >= 0.
p : float
parameter, >= 0 and <=1.
size : {tuple, int}
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn.
samples : {ndarray, scalar}
where the values are all integers in [0, n].
scipy.stats.distributions.binom : probability density function,
distribution or cumulative density function, etc.

The probability density for the Binomial distribution is

P(N) = \binom{n}{N}p^N(1-p)^{n-N},

where n is the number of trials, p is the probability of success, and N is the number of successes.

When estimating the standard error of a proportion in a population by using a random sample, the normal distribution works well unless the product p*n <=5, where p = population proportion estimate, and n = number of samples, in which case the binomial distribution is used instead. For example, a sample of 15 people shows 4 who are left handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4, so the binomial distribution should be used in this case.

[1]Dalgaard, Peter, “Introductory Statistics with R”, Springer-Verlag, 2002.
[2]Glantz, Stanton A. “Primer of Biostatistics.”, McGraw-Hill, Fifth Edition, 2002.
[3]Lentner, Marvin, “Elementary Applied Statistics”, Bogden and Quigley, 1972.
[4]Weisstein, Eric W. “Binomial Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/BinomialDistribution.html
[5]Wikipedia, “Binomial-distribution”, http://en.wikipedia.org/wiki/Binomial_distribution

Draw samples from the distribution:

>>> n, p = 10, .5 # number of trials, probability of each trial
>>> s = np.random.binomial(n, p, 1000)
# result of flipping a coin 10 times, tested 1000 times.

A real world example. A company drills 9 wild-cat oil exploration wells, each with an estimated probability of success of 0.1. All nine wells fail. What is the probability of that happening?

Let’s do 20,000 trials of the model, and count the number that generate zero positive results.

>>> sum(np.random.binomial(9,0.1,20000)==0)/20000.
answer = 0.38885, or 38%.
XRStools.xrs_calctools.boxParser(filename)[source]

parseXYZfile Reads an xyz-style file.

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.calculateRIJhist(atoms, boxLength, DELR=0.01, MAXBIN=1000)[source]
XRStools.xrs_calctools.changeOHBondLength(h2oMol, fraction, boxLength=None, oName='O', hName='H')[source]
XRStools.xrs_calctools.chisquare(df, size=None)

Draw samples from a chi-square distribution.

When df independent random variables, each with standard normal distributions (mean 0, variance 1), are squared and summed, the resulting distribution is chi-square (see Notes). This distribution is often used in hypothesis testing.

df : int
Number of degrees of freedom.
size : tuple of ints, int, optional
Size of the returned array. By default, a scalar is returned.
output : ndarray
Samples drawn from the distribution, packed in a size-shaped array.
ValueError
When df <= 0 or when an inappropriate size (e.g. size=-1) is given.

The variable obtained by summing the squares of df independent, standard normally distributed random variables:

Q = \sum_{i=0}^{\mathtt{df}} X^2_i

is chi-square distributed, denoted

Q \sim \chi^2_k.

The probability density function of the chi-squared distribution is

p(x) = \frac{(1/2)^{k/2}}{\Gamma(k/2)}
x^{k/2 - 1} e^{-x/2},

where \Gamma is the gamma function,

\Gamma(x) = \int_0^{-\infty} t^{x - 1} e^{-t} dt.

NIST/SEMATECH e-Handbook of Statistical Methods

>>> np.random.chisquare(2,4)
array([ 1.89920014,  9.00867716,  3.13710533,  5.62318272])
XRStools.xrs_calctools.convg(x, y, fwhm)[source]

Convolution with Gaussian

XRStools.xrs_calctools.countHbonds(mol1, mol2, Roocut=3.6, Rohcut=2.4, Aoooh=30.0)[source]
XRStools.xrs_calctools.countHbonds_orig(mol1, mol2, Roocut=3.6, Rohcut=2.4, Aoooh=30.0)[source]
XRStools.xrs_calctools.countHbonds_pbc(mol1, mol2, boxLength, Roocut=3.6, Rohcut=2.4, Aoooh=30.0)[source]
XRStools.xrs_calctools.count_OO_neighbors(list_of_o_atoms, Roocut, boxLength=None)[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.

broaden_lin(params=[0.8, 8, 537.5, 550], npoints=1000)[source]
cut_broadspecs(emin=None, emax=None)[source]
cut_rawspecs(emin=None, emax=None)[source]
norm_area(emin=None, emax=None)[source]
norm_max()[source]
plot_spec()[source]
sum_specs()[source]
XRStools.xrs_calctools.exponential(scale=1.0, size=None)

Exponential distribution.

Its probability density function is

f(x; \frac{1}{\beta}) = \frac{1}{\beta} \exp(-\frac{x}{\beta}),

for x > 0 and 0 elsewhere. \beta is the scale parameter, which is the inverse of the rate parameter \lambda = 1/\beta. The rate parameter is an alternative, widely used parameterization of the exponential distribution [3]_.

The exponential distribution is a continuous analogue of the geometric distribution. It describes many common situations, such as the size of raindrops measured over many rainstorms [1]_, or the time between page requests to Wikipedia [2]_.

scale : float
The scale parameter, \beta = 1/\lambda.
size : tuple of ints
Number of samples to draw. The output is shaped according to size.
[1]Peyton Z. Peebles Jr., “Probability, Random Variables and Random Signal Principles”, 4th ed, 2001, p. 57.
[2]“Poisson Process”, Wikipedia, http://en.wikipedia.org/wiki/Poisson_process
[3]“Exponential Distribution, Wikipedia, http://en.wikipedia.org/wiki/Exponential_distribution
XRStools.xrs_calctools.f(dfnum, dfden, size=None)

Draw samples from a F distribution.

Samples are drawn from an F distribution with specified parameters, dfnum (degrees of freedom in numerator) and dfden (degrees of freedom in denominator), where both parameters should be greater than zero.

The random variate of the F distribution (also known as the Fisher distribution) is a continuous probability distribution that arises in ANOVA tests, and is the ratio of two chi-square variates.

dfnum : float
Degrees of freedom in numerator. Should be greater than zero.
dfden : float
Degrees of freedom in denominator. Should be greater than zero.
size : {tuple, int}, optional
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. By default only one sample is returned.
samples : {ndarray, scalar}
Samples from the Fisher distribution.
scipy.stats.distributions.f : probability density function,
distribution or cumulative density function, etc.

The F statistic is used to compare in-group variances to between-group variances. Calculating the distribution depends on the sampling, and so it is a function of the respective degrees of freedom in the problem. The variable dfnum is the number of samples minus one, the between-groups degrees of freedom, while dfden is the within-groups degrees of freedom, the sum of the number of samples in each group minus the number of groups.

[1]Glantz, Stanton A. “Primer of Biostatistics.”, McGraw-Hill, Fifth Edition, 2002.
[2]Wikipedia, “F-distribution”, http://en.wikipedia.org/wiki/F-distribution

An example from Glantz[1], pp 47-40. Two groups, children of diabetics (25 people) and children from people without diabetes (25 controls). Fasting blood glucose was measured, case group had a mean value of 86.1, controls had a mean value of 82.2. Standard deviations were 2.09 and 2.49 respectively. Are these data consistent with the null hypothesis that the parents diabetic status does not affect their children’s blood glucose levels? Calculating the F statistic from the data gives a value of 36.01.

Draw samples from the distribution:

>>> dfnum = 1. # between group degrees of freedom
>>> dfden = 48. # within groups degrees of freedom
>>> s = np.random.f(dfnum, dfden, 1000)

The lower bound for the top 1% of the samples is :

>>> sort(s)[-10]
7.61988120985

So there is about a 1% chance that the F statistic will exceed 7.62, the measured value is 36, so the null hypothesis is rejected at the 1% level.

XRStools.xrs_calctools.findAllWaters(point, waterMols, o_name, cutoff)[source]
XRStools.xrs_calctools.findMolecule(xyzAtoms, molAtomList)[source]
XRStools.xrs_calctools.find_H2O_molecules(o_atoms, h_atoms, boxLength=None)[source]
XRStools.xrs_calctools.gamma(shape, scale=1.0, size=None)

Draw samples from a Gamma distribution.

Samples are drawn from a Gamma distribution with specified parameters, shape (sometimes designated “k”) and scale (sometimes designated “theta”), where both parameters are > 0.

shape : scalar > 0
The shape of the gamma distribution.
scale : scalar > 0, optional
The scale of the gamma distribution. Default is equal to 1.
size : shape_tuple, optional
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn.
out : ndarray, float
Returns one sample unless size parameter is specified.
scipy.stats.distributions.gamma : probability density function,
distribution or cumulative density function, etc.

The probability density for the Gamma distribution is

p(x) = x^{k-1}\frac{e^{-x/\theta}}{\theta^k\Gamma(k)},

where k is the shape and \theta the scale, and \Gamma is the Gamma function.

The Gamma distribution is often used to model the times to failure of electronic components, and arises naturally in processes for which the waiting times between Poisson distributed events are relevant.

[1]Weisstein, Eric W. “Gamma Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/GammaDistribution.html
[2]Wikipedia, “Gamma-distribution”, http://en.wikipedia.org/wiki/Gamma-distribution

Draw samples from the distribution:

>>> shape, scale = 2., 2. # mean and dispersion
>>> s = np.random.gamma(shape, scale, 1000)

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> import scipy.special as sps
>>> count, bins, ignored = plt.hist(s, 50, normed=True)
>>> y = bins**(shape-1)*(np.exp(-bins/scale) /
...                      (sps.gamma(shape)*scale**shape))
>>> plt.plot(bins, y, linewidth=2, color='r')
>>> plt.show()
XRStools.xrs_calctools.gauss(x, x0, fwhm)[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.gauss_areanorm(x, x0, fwhm)[source]

area-normalized gaussian

XRStools.xrs_calctools.geometric(p, size=None)

Draw samples from the geometric distribution.

Bernoulli trials are experiments with one of two outcomes: success or failure (an example of such an experiment is flipping a coin). The geometric distribution models the number of trials that must be run in order to achieve success. It is therefore supported on the positive integers, k = 1, 2, ....

The probability mass function of the geometric distribution is

f(k) = (1 - p)^{k - 1} p

where p is the probability of success of an individual trial.

p : float
The probability of success of an individual trial.
size : tuple of ints
Number of values to draw from the distribution. The output is shaped according to size.
out : ndarray
Samples from the geometric distribution, shaped according to size.

Draw ten thousand values from the geometric distribution, with the probability of an individual success equal to 0.35:

>>> z = np.random.geometric(p=0.35, size=10000)

How many trials succeeded after a single run?

>>> (z == 1).sum() / 10000.
0.34889999999999999 #random
XRStools.xrs_calctools.getDistVector(atom1, atom2)[source]
XRStools.xrs_calctools.getDistVectorPbc(atom1, atom2, boxLength)[source]
XRStools.xrs_calctools.getDistance(atom1, atom2)[source]
XRStools.xrs_calctools.getDistancePbc(atom1, atom2, boxLength)[source]
XRStools.xrs_calctools.getDistsFromMolecule(point, listOfMolecules, o_name=None)[source]
XRStools.xrs_calctools.getPeriodicTestBox(xyzAtoms, boxLength, numbershells=1)[source]
XRStools.xrs_calctools.getPeriodicTestBox_molecules(Molecules, boxLength, numbershells=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.get_state()

Return a tuple representing the internal state of the generator.

For more details, see set_state.

out : tuple(str, ndarray of 624 uints, int, int, float)

The returned tuple has the following items:

  1. the string ‘MT19937’.
  2. a 1-D array of 624 unsigned integer keys.
  3. an integer pos.
  4. an integer has_gauss.
  5. a float cached_gaussian.

set_state

set_state and get_state are not needed to work with any of the random distributions in NumPy. If the internal state is manually altered, the user should know exactly what he/she is doing.

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.gumbel(loc=0.0, scale=1.0, size=None)

Gumbel distribution.

Draw samples from a Gumbel distribution with specified location and scale. For more information on the Gumbel distribution, see Notes and References below.

loc : float
The location of the mode of the distribution.
scale : float
The scale parameter of the distribution.
size : tuple of ints
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn.
out : ndarray
The samples

scipy.stats.gumbel_l scipy.stats.gumbel_r scipy.stats.genextreme

probability density function, distribution, or cumulative density function, etc. for each of the above

weibull

The Gumbel (or Smallest Extreme Value (SEV) or the Smallest Extreme Value Type I) distribution is one of a class of Generalized Extreme Value (GEV) distributions used in modeling extreme value problems. The Gumbel is a special case of the Extreme Value Type I distribution for maximums from distributions with “exponential-like” tails.

The probability density for the Gumbel distribution is

p(x) = \frac{e^{-(x - \mu)/ \beta}}{\beta} e^{ -e^{-(x - \mu)/
\beta}},

where \mu is the mode, a location parameter, and \beta is the scale parameter.

The Gumbel (named for German mathematician Emil Julius Gumbel) was used very early in the hydrology literature, for modeling the occurrence of flood events. It is also used for modeling maximum wind speed and rainfall rates. It is a “fat-tailed” distribution - the probability of an event in the tail of the distribution is larger than if one used a Gaussian, hence the surprisingly frequent occurrence of 100-year floods. Floods were initially modeled as a Gaussian process, which underestimated the frequency of extreme events.

It is one of a class of extreme value distributions, the Generalized Extreme Value (GEV) distributions, which also includes the Weibull and Frechet.

The function has a mean of \mu + 0.57721\beta and a variance of \frac{\pi^2}{6}\beta^2.

Gumbel, E. J., Statistics of Extremes, New York: Columbia University Press, 1958.

Reiss, R.-D. and Thomas, M., Statistical Analysis of Extreme Values from Insurance, Finance, Hydrology and Other Fields, Basel: Birkhauser Verlag, 2001.

Draw samples from the distribution:

>>> mu, beta = 0, 0.1 # location and scale
>>> s = np.random.gumbel(mu, beta, 1000)

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 30, normed=True)
>>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)
...          * np.exp( -np.exp( -(bins - mu) /beta) ),
...          linewidth=2, color='r')
>>> plt.show()

Show how an extreme value distribution can arise from a Gaussian process and compare to a Gaussian:

>>> means = []
>>> maxima = []
>>> for i in range(0,1000) :
...    a = np.random.normal(mu, beta, 1000)
...    means.append(a.mean())
...    maxima.append(a.max())
>>> count, bins, ignored = plt.hist(maxima, 30, normed=True)
>>> beta = np.std(maxima)*np.pi/np.sqrt(6)
>>> mu = np.mean(maxima) - 0.57721*beta
>>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)
...          * np.exp(-np.exp(-(bins - mu)/beta)),
...          linewidth=2, color='r')
>>> plt.plot(bins, 1/(beta * np.sqrt(2 * np.pi))
...          * np.exp(-(bins - mu)**2 / (2 * beta**2)),
...          linewidth=2, color='g')
>>> plt.show()
XRStools.xrs_calctools.hypergeometric(ngood, nbad, nsample, size=None)

Draw samples from a Hypergeometric distribution.

Samples are drawn from a Hypergeometric distribution with specified parameters, ngood (ways to make a good selection), nbad (ways to make a bad selection), and nsample = number of items sampled, which is less than or equal to the sum ngood + nbad.

ngood : int or array_like
Number of ways to make a good selection. Must be nonnegative.
nbad : int or array_like
Number of ways to make a bad selection. Must be nonnegative.
nsample : int or array_like
Number of items sampled. Must be at least 1 and at most ngood + nbad.
size : int or tuple of int
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn.
samples : ndarray or scalar
The values are all integers in [0, n].
scipy.stats.distributions.hypergeom : probability density function,
distribution or cumulative density function, etc.

The probability density for the Hypergeometric distribution is

P(x) = \frac{\binom{m}{n}\binom{N-m}{n-x}}{\binom{N}{n}},

where 0 \le x \le m and n+m-N \le x \le n

for P(x) the probability of x successes, n = ngood, m = nbad, and N = number of samples.

Consider an urn with black and white marbles in it, ngood of them black and nbad are white. If you draw nsample balls without replacement, then the Hypergeometric distribution describes the distribution of black balls in the drawn sample.

Note that this distribution is very similar to the Binomial distribution, except that in this case, samples are drawn without replacement, whereas in the Binomial case samples are drawn with replacement (or the sample space is infinite). As the sample space becomes large, this distribution approaches the Binomial.

[1]Lentner, Marvin, “Elementary Applied Statistics”, Bogden and Quigley, 1972.
[2]Weisstein, Eric W. “Hypergeometric Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/HypergeometricDistribution.html
[3]Wikipedia, “Hypergeometric-distribution”, http://en.wikipedia.org/wiki/Hypergeometric-distribution

Draw samples from the distribution:

>>> ngood, nbad, nsamp = 100, 2, 10
# number of good, number of bad, and number of samples
>>> s = np.random.hypergeometric(ngood, nbad, nsamp, 1000)
>>> hist(s)
#   note that it is very unlikely to grab both bad items

Suppose you have an urn with 15 white and 15 black marbles. If you pull 15 marbles at random, how likely is it that 12 or more of them are one color?

>>> s = np.random.hypergeometric(15, 15, 15, 100000)
>>> sum(s>=12)/100000. + sum(s<=3)/100000.
#   answer = 0.003 ... pretty unlikely!
XRStools.xrs_calctools.laplace(loc=0.0, scale=1.0, size=None)

Draw samples from the Laplace or double exponential distribution with specified location (or mean) and scale (decay).

The Laplace distribution is similar to the Gaussian/normal distribution, but is sharper at the peak and has fatter tails. It represents the difference between two independent, identically distributed exponential random variables.

loc : float
The position, \mu, of the distribution peak.
scale : float
\lambda, the exponential decay.

It has the probability density function

f(x; \mu, \lambda) = \frac{1}{2\lambda}
\exp\left(-\frac{|x - \mu|}{\lambda}\right).

The first law of Laplace, from 1774, states that the frequency of an error can be expressed as an exponential function of the absolute magnitude of the error, which leads to the Laplace distribution. For many problems in Economics and Health sciences, this distribution seems to model the data better than the standard Gaussian distribution

[1]Abramowitz, M. and Stegun, I. A. (Eds.). Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables, 9th printing. New York: Dover, 1972.
[2]The Laplace distribution and generalizations By Samuel Kotz, Tomasz J. Kozubowski, Krzysztof Podgorski, Birkhauser, 2001.
[3]Weisstein, Eric W. “Laplace Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/LaplaceDistribution.html
[4]Wikipedia, “Laplace distribution”, http://en.wikipedia.org/wiki/Laplace_distribution

Draw samples from the distribution

>>> loc, scale = 0., 1.
>>> s = np.random.laplace(loc, scale, 1000)

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 30, normed=True)
>>> x = np.arange(-8., 8., .01)
>>> pdf = np.exp(-abs(x-loc/scale))/(2.*scale)
>>> plt.plot(x, pdf)

Plot Gaussian for comparison:

>>> g = (1/(scale * np.sqrt(2 * np.pi)) * 
...      np.exp( - (x - loc)**2 / (2 * scale**2) ))
>>> plt.plot(x,g)
XRStools.xrs_calctools.load_erkale_spec(filename)[source]

returns an erkale spectrum

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.logistic(loc=0.0, scale=1.0, size=None)

Draw samples from a Logistic distribution.

Samples are drawn from a Logistic distribution with specified parameters, loc (location or mean, also median), and scale (>0).

loc : float

scale : float > 0.

size : {tuple, int}
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn.
samples : {ndarray, scalar}
where the values are all integers in [0, n].
scipy.stats.distributions.logistic : probability density function,
distribution or cumulative density function, etc.

The probability density for the Logistic distribution is

P(x) = P(x) = \frac{e^{-(x-\mu)/s}}{s(1+e^{-(x-\mu)/s})^2},

where \mu = location and s = scale.

The Logistic distribution is used in Extreme Value problems where it can act as a mixture of Gumbel distributions, in Epidemiology, and by the World Chess Federation (FIDE) where it is used in the Elo ranking system, assuming the performance of each player is a logistically distributed random variable.

[1]Reiss, R.-D. and Thomas M. (2001), Statistical Analysis of Extreme Values, from Insurance, Finance, Hydrology and Other Fields, Birkhauser Verlag, Basel, pp 132-133.
[2]Weisstein, Eric W. “Logistic Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/LogisticDistribution.html
[3]Wikipedia, “Logistic-distribution”, http://en.wikipedia.org/wiki/Logistic-distribution

Draw samples from the distribution:

>>> loc, scale = 10, 1
>>> s = np.random.logistic(loc, scale, 10000)
>>> count, bins, ignored = plt.hist(s, bins=50)

# plot against distribution

>>> def logist(x, loc, scale):
...     return exp((loc-x)/scale)/(scale*(1+exp((loc-x)/scale))**2)
>>> plt.plot(bins, logist(bins, loc, scale)*count.max()/\
... logist(bins, loc, scale).max())
>>> plt.show()
XRStools.xrs_calctools.lognormal(mean=0.0, sigma=1.0, size=None)

Return samples drawn from a log-normal distribution.

Draw samples from a log-normal distribution with specified mean, standard deviation, and array shape. Note that the mean and standard deviation are not the values for the distribution itself, but of the underlying normal distribution it is derived from.

mean : float
Mean value of the underlying normal distribution
sigma : float, > 0.
Standard deviation of the underlying normal distribution
size : tuple of ints
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn.
samples : ndarray or float
The desired samples. An array of the same shape as size if given, if size is None a float is returned.
scipy.stats.lognorm : probability density function, distribution,
cumulative density function, etc.

A variable x has a log-normal distribution if log(x) is normally distributed. The probability density function for the log-normal distribution is:

p(x) = \frac{1}{\sigma x \sqrt{2\pi}}
e^{(-\frac{(ln(x)-\mu)^2}{2\sigma^2})}

where \mu is the mean and \sigma is the standard deviation of the normally distributed logarithm of the variable. A log-normal distribution results if a random variable is the product of a large number of independent, identically-distributed variables in the same way that a normal distribution results if the variable is the sum of a large number of independent, identically-distributed variables.

Limpert, E., Stahel, W. A., and Abbt, M., “Log-normal Distributions across the Sciences: Keys and Clues,” BioScience, Vol. 51, No. 5, May, 2001. http://stat.ethz.ch/~stahel/lognormal/bioscience.pdf

Reiss, R.D. and Thomas, M., Statistical Analysis of Extreme Values, Basel: Birkhauser Verlag, 2001, pp. 31-32.

Draw samples from the distribution:

>>> mu, sigma = 3., 1. # mean and standard deviation
>>> s = np.random.lognormal(mu, sigma, 1000)

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 100, normed=True, align='mid')
>>> x = np.linspace(min(bins), max(bins), 10000)
>>> pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))
...        / (x * sigma * np.sqrt(2 * np.pi)))
>>> plt.plot(x, pdf, linewidth=2, color='r')
>>> plt.axis('tight')
>>> plt.show()

Demonstrate that taking the products of random samples from a uniform distribution can be fit well by a log-normal probability density function.

>>> # Generate a thousand samples: each is the product of 100 random
>>> # values, drawn from a normal distribution.
>>> b = []
>>> for i in range(1000):
...    a = 10. + np.random.random(100)
...    b.append(np.product(a))
>>> b = np.array(b) / np.min(b) # scale values to be positive
>>> count, bins, ignored = plt.hist(b, 100, normed=True, align='center')
>>> sigma = np.std(np.log(b))
>>> mu = np.mean(np.log(b))
>>> x = np.linspace(min(bins), max(bins), 10000)
>>> pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))
...        / (x * sigma * np.sqrt(2 * np.pi)))
>>> plt.plot(x, pdf, color='r', linewidth=2)
>>> plt.show()
XRStools.xrs_calctools.logseries(p, size=None)

Draw samples from a Logarithmic Series distribution.

Samples are drawn from a Log Series distribution with specified parameter, p (probability, 0 < p < 1).

loc : float

scale : float > 0.

size : {tuple, int}
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn.
samples : {ndarray, scalar}
where the values are all integers in [0, n].
scipy.stats.distributions.logser : probability density function,
distribution or cumulative density function, etc.

The probability density for the Log Series distribution is

P(k) = \frac{-p^k}{k \ln(1-p)},

where p = probability.

The Log Series distribution is frequently used to represent species richness and occurrence, first proposed by Fisher, Corbet, and Williams in 1943 [2]. It may also be used to model the numbers of occupants seen in cars [3].

[1]Buzas, Martin A.; Culver, Stephen J., Understanding regional species diversity through the log series distribution of occurrences: BIODIVERSITY RESEARCH Diversity & Distributions, Volume 5, Number 5, September 1999 , pp. 187-195(9).
[2]Fisher, R.A,, A.S. Corbet, and C.B. Williams. 1943. The relation between the number of species and the number of individuals in a random sample of an animal population. Journal of Animal Ecology, 12:42-58.
[3]D. J. Hand, F. Daly, D. Lunn, E. Ostrowski, A Handbook of Small Data Sets, CRC Press, 1994.
[4]Wikipedia, “Logarithmic-distribution”, http://en.wikipedia.org/wiki/Logarithmic-distribution

Draw samples from the distribution:

>>> a = .6
>>> s = np.random.logseries(a, 10000)
>>> count, bins, ignored = plt.hist(s)

# plot against distribution

>>> def logseries(k, p):
...     return -p**k/(k*log(1-p))
>>> plt.plot(bins, logseries(bins, a)*count.max()/
             logseries(bins, a).max(), 'r')
>>> plt.show()
XRStools.xrs_calctools.multinomial(n, pvals, size=None)

Draw samples from a multinomial distribution.

The multinomial distribution is a multivariate generalisation of the binomial distribution. Take an experiment with one of p possible outcomes. An example of such an experiment is throwing a dice, where the outcome can be 1 through 6. Each sample drawn from the distribution represents n such experiments. Its values, X_i = [X_0, X_1, ..., X_p], represent the number of times the outcome was i.

n : int
Number of experiments.
pvals : sequence of floats, length p
Probabilities of each of the p different outcomes. These should sum to 1 (however, the last element is always assumed to account for the remaining probability, as long as sum(pvals[:-1]) <= 1).
size : tuple of ints
Given a size of (M, N, K), then M*N*K samples are drawn, and the output shape becomes (M, N, K, p), since each sample has shape (p,).

Throw a dice 20 times:

>>> np.random.multinomial(20, [1/6.]*6, size=1)
array([[4, 1, 7, 5, 2, 1]])

It landed 4 times on 1, once on 2, etc.

Now, throw the dice 20 times, and 20 times again:

>>> np.random.multinomial(20, [1/6.]*6, size=2)
array([[3, 4, 3, 3, 4, 3],
       [2, 4, 3, 4, 0, 7]])

For the first run, we threw 3 times 1, 4 times 2, etc. For the second, we threw 2 times 1, 4 times 2, etc.

A loaded dice is more likely to land on number 6:

>>> np.random.multinomial(100, [1/7.]*5)
array([13, 16, 13, 16, 42])
XRStools.xrs_calctools.multivariate_normal(mean, cov[, size])

Draw random samples from a multivariate normal distribution.

The multivariate normal, multinormal or Gaussian distribution is a generalization of the one-dimensional normal distribution to higher dimensions. Such a distribution is specified by its mean and covariance matrix. These parameters are analogous to the mean (average or “center”) and variance (standard deviation, or “width,” squared) of the one-dimensional normal distribution.

mean : 1-D array_like, of length N
Mean of the N-dimensional distribution.
cov : 2-D array_like, of shape (N, N)
Covariance matrix of the distribution. Must be symmetric and positive semi-definite for “physically meaningful” results.
size : int or tuple of ints, optional
Given a shape of, for example, (m,n,k), m*n*k samples are generated, and packed in an m-by-n-by-k arrangement. Because each sample is N-dimensional, the output shape is (m,n,k,N). If no shape is specified, a single (N-D) sample is returned.
out : ndarray

The drawn samples, of shape size, if that was provided. If not, the shape is (N,).

In other words, each entry out[i,j,...,:] is an N-dimensional value drawn from the distribution.

The mean is a coordinate in N-dimensional space, which represents the location where samples are most likely to be generated. This is analogous to the peak of the bell curve for the one-dimensional or univariate normal distribution.

Covariance indicates the level to which two variables vary together. From the multivariate normal distribution, we draw N-dimensional samples, X = [x_1, x_2, ... x_N]. The covariance matrix element C_{ij} is the covariance of x_i and x_j. The element C_{ii} is the variance of x_i (i.e. its “spread”).

Instead of specifying the full covariance matrix, popular approximations include:

  • Spherical covariance (cov is a multiple of the identity matrix)
  • Diagonal covariance (cov has non-negative elements, and only on the diagonal)

This geometrical property can be seen in two dimensions by plotting generated data-points:

>>> mean = [0,0]
>>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis
>>> import matplotlib.pyplot as plt
>>> x,y = np.random.multivariate_normal(mean,cov,5000).T
>>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show()

Note that the covariance matrix must be non-negative definite.

Papoulis, A., Probability, Random Variables, and Stochastic Processes, 3rd ed., New York: McGraw-Hill, 1991.

Duda, R. O., Hart, P. E., and Stork, D. G., Pattern Classification, 2nd ed., New York: Wiley, 2001.

>>> mean = (1,2)
>>> cov = [[1,0],[1,0]]
>>> x = np.random.multivariate_normal(mean,cov,(3,3))
>>> x.shape
(3, 3, 2)

The following is probably true, given that 0.6 is roughly twice the standard deviation:

>>> print list( (x[0,0,:] - mean) < 0.6 )
[True, True]
XRStools.xrs_calctools.negative_binomial(n, p, size=None)

Draw samples from a negative_binomial distribution.

Samples are drawn from a negative_Binomial distribution with specified parameters, n trials and p probability of success where n is an integer > 0 and p is in the interval [0, 1].

n : int
Parameter, > 0.
p : float
Parameter, >= 0 and <=1.
size : int or tuple of ints
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn.
samples : int or ndarray of ints
Drawn samples.

The probability density for the Negative Binomial distribution is

P(N;n,p) = \binom{N+n-1}{n-1}p^{n}(1-p)^{N},

where n-1 is the number of successes, p is the probability of success, and N+n-1 is the number of trials.

The negative binomial distribution gives the probability of n-1 successes and N failures in N+n-1 trials, and success on the (N+n)th trial.

If one throws a die repeatedly until the third time a “1” appears, then the probability distribution of the number of non-“1”s that appear before the third “1” is a negative binomial distribution.

[1]Weisstein, Eric W. “Negative Binomial Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/NegativeBinomialDistribution.html
[2]Wikipedia, “Negative binomial distribution”, http://en.wikipedia.org/wiki/Negative_binomial_distribution

Draw samples from the distribution:

A real world example. A company drills wild-cat oil exploration wells, each with an estimated probability of success of 0.1. What is the probability of having one success for each successive well, that is what is the probability of a single success after drilling 5 wells, after 6 wells, etc.?

>>> s = np.random.negative_binomial(1, 0.1, 100000)
>>> for i in range(1, 11):
...    probability = sum(s<i) / 100000.
...    print i, "wells drilled, probability of one success =", probability
XRStools.xrs_calctools.noncentral_chisquare(df, nonc, size=None)

Draw samples from a noncentral chi-square distribution.

The noncentral \chi^2 distribution is a generalisation of the \chi^2 distribution.

df : int
Degrees of freedom, should be >= 1.
nonc : float
Non-centrality, should be > 0.
size : int or tuple of ints
Shape of the output.

The probability density function for the noncentral Chi-square distribution is

P(x;df,nonc) = \sum^{\infty}_{i=0}
\frac{e^{-nonc/2}(nonc/2)^{i}}{i!}P_{Y_{df+2i}}(x),

where Y_{q} is the Chi-square with q degrees of freedom.

In Delhi (2007), it is noted that the noncentral chi-square is useful in bombing and coverage problems, the probability of killing the point target given by the noncentral chi-squared distribution.

[1]Delhi, M.S. Holla, “On a noncentral chi-square distribution in the analysis of weapon systems effectiveness”, Metrika, Volume 15, Number 1 / December, 1970.
[2]Wikipedia, “Noncentral chi-square distribution” http://en.wikipedia.org/wiki/Noncentral_chi-square_distribution

Draw values from the distribution and plot the histogram

>>> import matplotlib.pyplot as plt
>>> values = plt.hist(np.random.noncentral_chisquare(3, 20, 100000),
...                   bins=200, normed=True)
>>> plt.show()

Draw values from a noncentral chisquare with very small noncentrality, and compare to a chisquare.

>>> plt.figure()
>>> values = plt.hist(np.random.noncentral_chisquare(3, .0000001, 100000),
...                   bins=np.arange(0., 25, .1), normed=True)
>>> values2 = plt.hist(np.random.chisquare(3, 100000),
...                    bins=np.arange(0., 25, .1), normed=True)
>>> plt.plot(values[1][0:-1], values[0]-values2[0], 'ob')
>>> plt.show()

Demonstrate how large values of non-centrality lead to a more symmetric distribution.

>>> plt.figure()
>>> values = plt.hist(np.random.noncentral_chisquare(3, 20, 100000),
...                   bins=200, normed=True)
>>> plt.show()
XRStools.xrs_calctools.noncentral_f(dfnum, dfden, nonc, size=None)

Draw samples from the noncentral F distribution.

Samples are drawn from an F distribution with specified parameters, dfnum (degrees of freedom in numerator) and dfden (degrees of freedom in denominator), where both parameters > 1. nonc is the non-centrality parameter.

dfnum : int
Parameter, should be > 1.
dfden : int
Parameter, should be > 1.
nonc : float
Parameter, should be >= 0.
size : int or tuple of ints
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn.
samples : scalar or ndarray
Drawn samples.

When calculating the power of an experiment (power = probability of rejecting the null hypothesis when a specific alternative is true) the non-central F statistic becomes important. When the null hypothesis is true, the F statistic follows a central F distribution. When the null hypothesis is not true, then it follows a non-central F statistic.

Weisstein, Eric W. “Noncentral F-Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/NoncentralF-Distribution.html

Wikipedia, “Noncentral F distribution”, http://en.wikipedia.org/wiki/Noncentral_F-distribution

In a study, testing for a specific alternative to the null hypothesis requires use of the Noncentral F distribution. We need to calculate the area in the tail of the distribution that exceeds the value of the F distribution for the null hypothesis. We’ll plot the two probability distributions for comparison.

>>> dfnum = 3 # between group deg of freedom
>>> dfden = 20 # within groups degrees of freedom
>>> nonc = 3.0
>>> nc_vals = np.random.noncentral_f(dfnum, dfden, nonc, 1000000)
>>> NF = np.histogram(nc_vals, bins=50, normed=True)
>>> c_vals = np.random.f(dfnum, dfden, 1000000)
>>> F = np.histogram(c_vals, bins=50, normed=True)
>>> plt.plot(F[1][1:], F[0])
>>> plt.plot(NF[1][1:], NF[0])
>>> plt.show()
XRStools.xrs_calctools.normal(loc=0.0, scale=1.0, size=None)

Draw random samples from a normal (Gaussian) distribution.

The probability density function of the normal distribution, first derived by De Moivre and 200 years later by both Gauss and Laplace independently [2]_, is often called the bell curve because of its characteristic shape (see the example below).

The normal distributions occurs often in nature. For example, it describes the commonly occurring distribution of samples influenced by a large number of tiny, random disturbances, each with its own unique distribution [2]_.

loc : float
Mean (“centre”) of the distribution.
scale : float
Standard deviation (spread or “width”) of the distribution.
size : tuple of ints
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn.
scipy.stats.distributions.norm : probability density function,
distribution or cumulative density function, etc.

The probability density for the Gaussian distribution is

p(x) = \frac{1}{\sqrt{ 2 \pi \sigma^2 }}
e^{ - \frac{ (x - \mu)^2 } {2 \sigma^2} },

where \mu is the mean and \sigma the standard deviation. The square of the standard deviation, \sigma^2, is called the variance.

The function has its peak at the mean, and its “spread” increases with the standard deviation (the function reaches 0.607 times its maximum at x + \sigma and x - \sigma [2]_). This implies that numpy.random.normal is more likely to return samples lying close to the mean, rather than those far away.

[1]Wikipedia, “Normal distribution”, http://en.wikipedia.org/wiki/Normal_distribution
[2]P. R. Peebles Jr., “Central Limit Theorem” in “Probability, Random Variables and Random Signal Principles”, 4th ed., 2001, pp. 51, 51, 125.

Draw samples from the distribution:

>>> mu, sigma = 0, 0.1 # mean and standard deviation
>>> s = np.random.normal(mu, sigma, 1000)

Verify the mean and the variance:

>>> abs(mu - np.mean(s)) < 0.01
True
>>> abs(sigma - np.std(s, ddof=1)) < 0.01
True

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 30, normed=True)
>>> plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
...                np.exp( - (bins - mu)**2 / (2 * sigma**2) ),
...          linewidth=2, color='r')
>>> plt.show()
XRStools.xrs_calctools.pareto(a, size=None)

Draw samples from a Pareto II or Lomax distribution with specified shape.

The Lomax or Pareto II distribution is a shifted Pareto distribution. The classical Pareto distribution can be obtained from the Lomax distribution by adding the location parameter m, see below. The smallest value of the Lomax distribution is zero while for the classical Pareto distribution it is m, where the standard Pareto distribution has location m=1. Lomax can also be considered as a simplified version of the Generalized Pareto distribution (available in SciPy), with the scale set to one and the location set to zero.

The Pareto distribution must be greater than zero, and is unbounded above. It is also known as the “80-20 rule”. In this distribution, 80 percent of the weights are in the lowest 20 percent of the range, while the other 20 percent fill the remaining 80 percent of the range.

shape : float, > 0.
Shape of the distribution.
size : tuple of ints
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn.
scipy.stats.distributions.lomax.pdf : probability density function,
distribution or cumulative density function, etc.
scipy.stats.distributions.genpareto.pdf : probability density function,
distribution or cumulative density function, etc.

The probability density for the Pareto distribution is

p(x) = \frac{am^a}{x^{a+1}}

where a is the shape and m the location

The Pareto distribution, named after the Italian economist Vilfredo Pareto, is a power law probability distribution useful in many real world problems. Outside the field of economics it is generally referred to as the Bradford distribution. Pareto developed the distribution to describe the distribution of wealth in an economy. It has also found use in insurance, web page access statistics, oil field sizes, and many other problems, including the download frequency for projects in Sourceforge [1]. It is one of the so-called “fat-tailed” distributions.

[1]Francis Hunt and Paul Johnson, On the Pareto Distribution of Sourceforge projects.
[2]Pareto, V. (1896). Course of Political Economy. Lausanne.
[3]Reiss, R.D., Thomas, M.(2001), Statistical Analysis of Extreme Values, Birkhauser Verlag, Basel, pp 23-30.
[4]Wikipedia, “Pareto distribution”, http://en.wikipedia.org/wiki/Pareto_distribution

Draw samples from the distribution:

>>> a, m = 3., 1. # shape and mode
>>> s = np.random.pareto(a, 1000) + m

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 100, normed=True, align='center')
>>> fit = a*m**a/bins**(a+1)
>>> plt.plot(bins, max(count)*fit/max(fit),linewidth=2, color='r')
>>> plt.show()
XRStools.xrs_calctools.parseXYZfile(filename)[source]

parseXYZfile Reads an xyz-style file.

XRStools.xrs_calctools.permutation(x)

Randomly permute a sequence, or return a permuted range.

If x is a multi-dimensional array, it is only shuffled along its first index.

x : int or array_like
If x is an integer, randomly permute np.arange(x). If x is an array, make a copy and shuffle the elements randomly.
out : ndarray
Permuted sequence or array range.
>>> np.random.permutation(10)
array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6])
>>> np.random.permutation([1, 4, 9, 12, 15])
array([15,  1,  9,  4, 12])
>>> arr = np.arange(9).reshape((3, 3))
>>> np.random.permutation(arr)
array([[6, 7, 8],
       [0, 1, 2],
       [3, 4, 5]])
XRStools.xrs_calctools.poisson(lam=1.0, size=None)

Draw samples from a Poisson distribution.

The Poisson distribution is the limit of the Binomial distribution for large N.

lam : float
Expectation of interval, should be >= 0.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn.

The Poisson distribution

f(k; \lambda)=\frac{\lambda^k e^{-\lambda}}{k!}

For events with an expected separation \lambda the Poisson distribution f(k; \lambda) describes the probability of k events occurring within the observed interval \lambda.

Because the output is limited to the range of the C long type, a ValueError is raised when lam is within 10 sigma of the maximum representable value.

[1]Weisstein, Eric W. “Poisson Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/PoissonDistribution.html
[2]Wikipedia, “Poisson distribution”, http://en.wikipedia.org/wiki/Poisson_distribution

Draw samples from the distribution:

>>> import numpy as np
>>> s = np.random.poisson(5, 10000)

Display histogram of the sample:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 14, normed=True)
>>> plt.show()
XRStools.xrs_calctools.power(a, size=None)

Draws samples in [0, 1] from a power distribution with positive exponent a - 1.

Also known as the power function distribution.

a : float
parameter, > 0
size : tuple of ints
Output shape. If the given shape is, e.g., (m, n, k), then
m * n * k samples are drawn.
samples : {ndarray, scalar}
The returned samples lie in [0, 1].
ValueError
If a<1.

The probability density function is

P(x; a) = ax^{a-1}, 0 \le x \le 1, a>0.

The power function distribution is just the inverse of the Pareto distribution. It may also be seen as a special case of the Beta distribution.

It is used, for example, in modeling the over-reporting of insurance claims.

[1]Christian Kleiber, Samuel Kotz, “Statistical size distributions in economics and actuarial sciences”, Wiley, 2003.
[2]Heckert, N. A. and Filliben, James J. (2003). NIST Handbook 148: Dataplot Reference Manual, Volume 2: Let Subcommands and Library Functions”, National Institute of Standards and Technology Handbook Series, June 2003. http://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/powpdf.pdf

Draw samples from the distribution:

>>> a = 5. # shape
>>> samples = 1000
>>> s = np.random.power(a, samples)

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, bins=30)
>>> x = np.linspace(0, 1, 100)
>>> y = a*x**(a-1.)
>>> normed_y = samples*np.diff(bins)[0]*y
>>> plt.plot(x, normed_y)
>>> plt.show()

Compare the power function distribution to the inverse of the Pareto.

>>> from scipy import stats
>>> rvs = np.random.power(5, 1000000)
>>> rvsp = np.random.pareto(5, 1000000)
>>> xx = np.linspace(0,1,100)
>>> powpdf = stats.powerlaw.pdf(xx,5)
>>> plt.figure()
>>> plt.hist(rvs, bins=50, normed=True)
>>> plt.plot(xx,powpdf,'r-')
>>> plt.title('np.random.power(5)')
>>> plt.figure()
>>> plt.hist(1./(1.+rvsp), bins=50, normed=True)
>>> plt.plot(xx,powpdf,'r-')
>>> plt.title('inverse of 1 + np.random.pareto(5)')
>>> plt.figure()
>>> plt.hist(1./(1.+rvsp), bins=50, normed=True)
>>> plt.plot(xx,powpdf,'r-')
>>> plt.title('inverse of stats.pareto(5)')
XRStools.xrs_calctools.rand(d0, d1, ..., dn)

Random values in a given shape.

Create an array of the given shape and propagate it with random samples from a uniform distribution over [0, 1).

d0, d1, ..., dn : int, optional
The dimensions of the returned array, should all be positive. If no argument is given a single Python float is returned.
out : ndarray, shape (d0, d1, ..., dn)
Random values.

random

This is a convenience function. If you want an interface that takes a shape-tuple as the first argument, refer to np.random.random_sample .

>>> np.random.rand(3,2)
array([[ 0.14022471,  0.96360618],  #random
       [ 0.37601032,  0.25528411],  #random
       [ 0.49313049,  0.94909878]]) #random
XRStools.xrs_calctools.randint(low, high=None, size=None)

Return random integers from low (inclusive) to high (exclusive).

Return random integers from the “discrete uniform” distribution in the “half-open” interval [low, high). If high is None (the default), then results are from [0, low).

low : int
Lowest (signed) integer to be drawn from the distribution (unless high=None, in which case this parameter is the highest such integer).
high : int, optional
If provided, one above the largest (signed) integer to be drawn from the distribution (see above for behavior if high=None).
size : int or tuple of ints, optional
Output shape. Default is None, in which case a single int is returned.
out : int or ndarray of ints
size-shaped array of random integers from the appropriate distribution, or a single such random int if size not provided.
random.random_integers : similar to randint, only for the closed
interval [low, high], and 1 is the lowest value if high is omitted. In particular, this other one is the one to use to generate uniformly distributed discrete non-integers.
>>> np.random.randint(2, size=10)
array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])
>>> np.random.randint(1, size=10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Generate a 2 x 4 array of ints between 0 and 4, inclusive:

>>> np.random.randint(5, size=(2, 4))
array([[4, 0, 2, 1],
       [3, 2, 2, 0]])
XRStools.xrs_calctools.randn(d0, d1, ..., dn)

Return a sample (or samples) from the “standard normal” distribution.

If positive, int_like or int-convertible arguments are provided, randn generates an array of shape (d0, d1, ..., dn), filled with random floats sampled from a univariate “normal” (Gaussian) distribution of mean 0 and variance 1 (if any of the d_i are floats, they are first converted to integers by truncation). A single float randomly sampled from the distribution is returned if no argument is provided.

This is a convenience function. If you want an interface that takes a tuple as the first argument, use numpy.random.standard_normal instead.

d0, d1, ..., dn : int, optional
The dimensions of the returned array, should be all positive. If no argument is given a single Python float is returned.
Z : ndarray or float
A (d0, d1, ..., dn)-shaped array of floating-point samples from the standard normal distribution, or a single such float if no parameters were supplied.

random.standard_normal : Similar, but takes a tuple as its argument.

For random samples from N(\mu, \sigma^2), use:

sigma * np.random.randn(...) + mu

>>> np.random.randn()
2.1923875335537315 #random

Two-by-four array of samples from N(3, 6.25):

>>> 2.5 * np.random.randn(2, 4) + 3
array([[-4.49401501,  4.00950034, -1.81814867,  7.29718677],  #random
       [ 0.39924804,  4.68456316,  4.99394529,  4.84057254]]) #random
XRStools.xrs_calctools.random()

random_sample(size=None)

Return random floats in the half-open interval [0.0, 1.0).

Results are from the “continuous uniform” distribution over the stated interval. To sample Unif[a, b), b > a multiply the output of random_sample by (b-a) and add a:

(b - a) * random_sample() + a
size : int or tuple of ints, optional
Defines the shape of the returned array of random floats. If None (the default), returns a single float.
out : float or ndarray of floats
Array of random floats of shape size (unless size=None, in which case a single float is returned).
>>> np.random.random_sample()
0.47108547995356098
>>> type(np.random.random_sample())
<type 'float'>
>>> np.random.random_sample((5,))
array([ 0.30220482,  0.86820401,  0.1654503 ,  0.11659149,  0.54323428])

Three-by-two array of random numbers from [-5, 0):

>>> 5 * np.random.random_sample((3, 2)) - 5
array([[-3.99149989, -0.52338984],
       [-2.99091858, -0.79479508],
       [-1.23204345, -1.75224494]])
XRStools.xrs_calctools.random_integers(low, high=None, size=None)

Return random integers between low and high, inclusive.

Return random integers from the “discrete uniform” distribution in the closed interval [low, high]. If high is None (the default), then results are from [1, low].

low : int
Lowest (signed) integer to be drawn from the distribution (unless high=None, in which case this parameter is the highest such integer).
high : int, optional
If provided, the largest (signed) integer to be drawn from the distribution (see above for behavior if high=None).
size : int or tuple of ints, optional
Output shape. Default is None, in which case a single int is returned.
out : int or ndarray of ints
size-shaped array of random integers from the appropriate distribution, or a single such random int if size not provided.
random.randint : Similar to random_integers, only for the half-open
interval [low, high), and 0 is the lowest value if high is omitted.

To sample from N evenly spaced floating-point numbers between a and b, use:

a + (b - a) * (np.random.random_integers(N) - 1) / (N - 1.)
>>> np.random.random_integers(5)
4
>>> type(np.random.random_integers(5))
<type 'int'>
>>> np.random.random_integers(5, size=(3.,2.))
array([[5, 4],
       [3, 3],
       [4, 5]])

Choose five random numbers from the set of five evenly-spaced numbers between 0 and 2.5, inclusive (i.e., from the set {0, 5/8, 10/8, 15/8, 20/8}):

>>> 2.5 * (np.random.random_integers(5, size=(5,)) - 1) / 4.
array([ 0.625,  1.25 ,  0.625,  0.625,  2.5  ])

Roll two six sided dice 1000 times and sum the results:

>>> d1 = np.random.random_integers(1, 6, 1000)
>>> d2 = np.random.random_integers(1, 6, 1000)
>>> dsums = d1 + d2

Display results as a histogram:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(dsums, 11, normed=True)
>>> plt.show()
XRStools.xrs_calctools.random_sample(size=None)

Return random floats in the half-open interval [0.0, 1.0).

Results are from the “continuous uniform” distribution over the stated interval. To sample Unif[a, b), b > a multiply the output of random_sample by (b-a) and add a:

(b - a) * random_sample() + a
size : int or tuple of ints, optional
Defines the shape of the returned array of random floats. If None (the default), returns a single float.
out : float or ndarray of floats
Array of random floats of shape size (unless size=None, in which case a single float is returned).
>>> np.random.random_sample()
0.47108547995356098
>>> type(np.random.random_sample())
<type 'float'>
>>> np.random.random_sample((5,))
array([ 0.30220482,  0.86820401,  0.1654503 ,  0.11659149,  0.54323428])

Three-by-two array of random numbers from [-5, 0):

>>> 5 * np.random.random_sample((3, 2)) - 5
array([[-3.99149989, -0.52338984],
       [-2.99091858, -0.79479508],
       [-1.23204345, -1.75224494]])
XRStools.xrs_calctools.ranf()

random_sample(size=None)

Return random floats in the half-open interval [0.0, 1.0).

Results are from the “continuous uniform” distribution over the stated interval. To sample Unif[a, b), b > a multiply the output of random_sample by (b-a) and add a:

(b - a) * random_sample() + a
size : int or tuple of ints, optional
Defines the shape of the returned array of random floats. If None (the default), returns a single float.
out : float or ndarray of floats
Array of random floats of shape size (unless size=None, in which case a single float is returned).
>>> np.random.random_sample()
0.47108547995356098
>>> type(np.random.random_sample())
<type 'float'>
>>> np.random.random_sample((5,))
array([ 0.30220482,  0.86820401,  0.1654503 ,  0.11659149,  0.54323428])

Three-by-two array of random numbers from [-5, 0):

>>> 5 * np.random.random_sample((3, 2)) - 5
array([[-3.99149989, -0.52338984],
       [-2.99091858, -0.79479508],
       [-1.23204345, -1.75224494]])
XRStools.xrs_calctools.rayleigh(scale=1.0, size=None)

Draw samples from a Rayleigh distribution.

The \chi and Weibull distributions are generalizations of the Rayleigh.

scale : scalar
Scale, also equals the mode. Should be >= 0.
size : int or tuple of ints, optional
Shape of the output. Default is None, in which case a single value is returned.

The probability density function for the Rayleigh distribution is

P(x;scale) = \frac{x}{scale^2}e^{\frac{-x^2}{2 \cdotp scale^2}}

The Rayleigh distribution arises if the wind speed and wind direction are both gaussian variables, then the vector wind velocity forms a Rayleigh distribution. The Rayleigh distribution is used to model the expected output from wind turbines.

[1]Brighton Webs Ltd., Rayleigh Distribution, http://www.brighton-webs.co.uk/distributions/rayleigh.asp
[2]Wikipedia, “Rayleigh distribution” http://en.wikipedia.org/wiki/Rayleigh_distribution

Draw values from the distribution and plot the histogram

>>> values = hist(np.random.rayleigh(3, 100000), bins=200, normed=True)

Wave heights tend to follow a Rayleigh distribution. If the mean wave height is 1 meter, what fraction of waves are likely to be larger than 3 meters?

>>> meanvalue = 1
>>> modevalue = np.sqrt(2 / np.pi) * meanvalue
>>> s = np.random.rayleigh(modevalue, 1000000)

The percentage of waves larger than 3 meters is:

>>> 100.*sum(s>3)/1000000.
0.087300000000000003
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.repair_h2o_molecules_pbc(h2o_mols, boxLength)[source]
XRStools.xrs_calctools.sample()

random_sample(size=None)

Return random floats in the half-open interval [0.0, 1.0).

Results are from the “continuous uniform” distribution over the stated interval. To sample Unif[a, b), b > a multiply the output of random_sample by (b-a) and add a:

(b - a) * random_sample() + a
size : int or tuple of ints, optional
Defines the shape of the returned array of random floats. If None (the default), returns a single float.
out : float or ndarray of floats
Array of random floats of shape size (unless size=None, in which case a single float is returned).
>>> np.random.random_sample()
0.47108547995356098
>>> type(np.random.random_sample())
<type 'float'>
>>> np.random.random_sample((5,))
array([ 0.30220482,  0.86820401,  0.1654503 ,  0.11659149,  0.54323428])

Three-by-two array of random numbers from [-5, 0):

>>> 5 * np.random.random_sample((3, 2)) - 5
array([[-3.99149989, -0.52338984],
       [-2.99091858, -0.79479508],
       [-1.23204345, -1.75224494]])
XRStools.xrs_calctools.seed(seed=None)

Seed the generator.

This method is called when RandomState is initialized. It can be called again to re-seed the generator. For details, see RandomState.

seed : int or array_like, optional
Seed for RandomState.

RandomState

XRStools.xrs_calctools.set_state(state)

Set the internal state of the generator from a tuple.

For use if one has reason to manually (re-)set the internal state of the “Mersenne Twister”[1]_ pseudo-random number generating algorithm.

state : tuple(str, ndarray of 624 uints, int, int, float)

The state tuple has the following items:

  1. the string ‘MT19937’, specifying the Mersenne Twister algorithm.
  2. a 1-D array of 624 unsigned integers keys.
  3. an integer pos.
  4. an integer has_gauss.
  5. a float cached_gaussian.
out : None
Returns ‘None’ on success.

get_state

set_state and get_state are not needed to work with any of the random distributions in NumPy. If the internal state is manually altered, the user should know exactly what he/she is doing.

For backwards compatibility, the form (str, array of 624 uints, int) is also accepted although it is missing some information about the cached Gaussian value: state = ('MT19937', keys, pos).

[1]M. Matsumoto and T. Nishimura, “Mersenne Twister: A 623-dimensionally equidistributed uniform pseudorandom number generator,” ACM Trans. on Modeling and Computer Simulation, Vol. 8, No. 1, pp. 3-30, Jan. 1998.
XRStools.xrs_calctools.shuffle(x)

Modify a sequence in-place by shuffling its contents.

x : array_like
The array or list to be shuffled.

None

>>> arr = np.arange(10)
>>> np.random.shuffle(arr)
>>> arr
[1 7 5 2 9 4 3 6 0 8]

This function only shuffles the array along the first index of a multi-dimensional array:

>>> arr = np.arange(9).reshape((3, 3))
>>> np.random.shuffle(arr)
>>> arr
array([[3, 4, 5],
       [6, 7, 8],
       [0, 1, 2]])
XRStools.xrs_calctools.spline2(x, y, x2)[source]

Extrapolates the smaller and larger valuea as a constant

XRStools.xrs_calctools.standard_cauchy(size=None)

Standard Cauchy distribution with mode = 0.

Also known as the Lorentz distribution.

size : int or tuple of ints
Shape of the output.
samples : ndarray or scalar
The drawn samples.

The probability density function for the full Cauchy distribution is

P(x; x_0, \gamma) = \frac{1}{\pi \gamma \bigl[ 1+
(\frac{x-x_0}{\gamma})^2 \bigr] }

and the Standard Cauchy distribution just sets x_0=0 and \gamma=1

The Cauchy distribution arises in the solution to the driven harmonic oscillator problem, and also describes spectral line broadening. It also describes the distribution of values at which a line tilted at a random angle will cut the x axis.

When studying hypothesis tests that assume normality, seeing how the tests perform on data from a Cauchy distribution is a good indicator of their sensitivity to a heavy-tailed distribution, since the Cauchy looks very much like a Gaussian distribution, but with heavier tails.

[1]NIST/SEMATECH e-Handbook of Statistical Methods, “Cauchy Distribution”, http://www.itl.nist.gov/div898/handbook/eda/section3/eda3663.htm
[2]Weisstein, Eric W. “Cauchy Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/CauchyDistribution.html
[3]Wikipedia, “Cauchy distribution” http://en.wikipedia.org/wiki/Cauchy_distribution

Draw samples and plot the distribution:

>>> s = np.random.standard_cauchy(1000000)
>>> s = s[(s>-25) & (s<25)]  # truncate distribution so it plots well
>>> plt.hist(s, bins=100)
>>> plt.show()
XRStools.xrs_calctools.standard_exponential(size=None)

Draw samples from the standard exponential distribution.

standard_exponential is identical to the exponential distribution with a scale parameter of 1.

size : int or tuple of ints
Shape of the output.
out : float or ndarray
Drawn samples.

Output a 3x8000 array:

>>> n = np.random.standard_exponential((3, 8000))
XRStools.xrs_calctools.standard_gamma(shape, size=None)

Draw samples from a Standard Gamma distribution.

Samples are drawn from a Gamma distribution with specified parameters, shape (sometimes designated “k”) and scale=1.

shape : float
Parameter, should be > 0.
size : int or tuple of ints
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn.
samples : ndarray or scalar
The drawn samples.
scipy.stats.distributions.gamma : probability density function,
distribution or cumulative density function, etc.

The probability density for the Gamma distribution is

p(x) = x^{k-1}\frac{e^{-x/\theta}}{\theta^k\Gamma(k)},

where k is the shape and \theta the scale, and \Gamma is the Gamma function.

The Gamma distribution is often used to model the times to failure of electronic components, and arises naturally in processes for which the waiting times between Poisson distributed events are relevant.

[1]Weisstein, Eric W. “Gamma Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/GammaDistribution.html
[2]Wikipedia, “Gamma-distribution”, http://en.wikipedia.org/wiki/Gamma-distribution

Draw samples from the distribution:

>>> shape, scale = 2., 1. # mean and width
>>> s = np.random.standard_gamma(shape, 1000000)

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> import scipy.special as sps
>>> count, bins, ignored = plt.hist(s, 50, normed=True)
>>> y = bins**(shape-1) * ((np.exp(-bins/scale))/ \
...                       (sps.gamma(shape) * scale**shape))
>>> plt.plot(bins, y, linewidth=2, color='r')
>>> plt.show()
XRStools.xrs_calctools.standard_normal(size=None)

Returns samples from a Standard Normal distribution (mean=0, stdev=1).

size : int or tuple of ints, optional
Output shape. Default is None, in which case a single value is returned.
out : float or ndarray
Drawn samples.
>>> s = np.random.standard_normal(8000)
>>> s
array([ 0.6888893 ,  0.78096262, -0.89086505, ...,  0.49876311, #random
       -0.38672696, -0.4685006 ])                               #random
>>> s.shape
(8000,)
>>> s = np.random.standard_normal(size=(3, 4, 2))
>>> s.shape
(3, 4, 2)
XRStools.xrs_calctools.standard_t(df, size=None)

Standard Student’s t distribution with df degrees of freedom.

A special case of the hyperbolic distribution. As df gets large, the result resembles that of the standard normal distribution (standard_normal).

df : int
Degrees of freedom, should be > 0.
size : int or tuple of ints, optional
Output shape. Default is None, in which case a single value is returned.
samples : ndarray or scalar
Drawn samples.

The probability density function for the t distribution is

P(x, df) = \frac{\Gamma(\frac{df+1}{2})}{\sqrt{\pi df}
\Gamma(\frac{df}{2})}\Bigl( 1+\frac{x^2}{df} \Bigr)^{-(df+1)/2}

The t test is based on an assumption that the data come from a Normal distribution. The t test provides a way to test whether the sample mean (that is the mean calculated from the data) is a good estimate of the true mean.

The derivation of the t-distribution was forst published in 1908 by William Gisset while working for the Guinness Brewery in Dublin. Due to proprietary issues, he had to publish under a pseudonym, and so he used the name Student.

[1]Dalgaard, Peter, “Introductory Statistics With R”, Springer, 2002.
[2]Wikipedia, “Student’s t-distribution” http://en.wikipedia.org/wiki/Student’s_t-distribution

From Dalgaard page 83 [1]_, suppose the daily energy intake for 11 women in Kj is:

>>> intake = np.array([5260., 5470, 5640, 6180, 6390, 6515, 6805, 7515, \
...                    7515, 8230, 8770])

Does their energy intake deviate systematically from the recommended value of 7725 kJ?

We have 10 degrees of freedom, so is the sample mean within 95% of the recommended value?

>>> s = np.random.standard_t(10, size=100000)
>>> np.mean(intake)
6753.636363636364
>>> intake.std(ddof=1)
1142.1232221373727

Calculate the t statistic, setting the ddof parameter to the unbiased value so the divisor in the standard deviation will be degrees of freedom, N-1.

>>> t = (np.mean(intake)-7725)/(intake.std(ddof=1)/np.sqrt(len(intake)))
>>> import matplotlib.pyplot as plt
>>> h = plt.hist(s, bins=100, normed=True)

For a one-sided t-test, how far out in the distribution does the t statistic appear?

>>> >>> np.sum(s<t) / float(len(s))
0.0090699999999999999  #random

So the p-value is about 0.009, which says the null hypothesis has a probability of about 99% of being true.

class XRStools.xrs_calctools.stobe(prefix, postfix, fromnumber, tonumber, step, stepformat=2)[source]

Bases: object

class to analyze StoBe results

broaden_lin(params=[0.8, 8, 537.5, 550], npoints=1000)[source]
cut_rawspecs(emin=None, emax=None)[source]
norm_area(emin, emax)[source]
sum_specs()[source]
XRStools.xrs_calctools.triangular(left, mode, right, size=None)

Draw samples from the triangular distribution.

The triangular distribution is a continuous probability distribution with lower limit left, peak at mode, and upper limit right. Unlike the other distributions, these parameters directly define the shape of the pdf.

left : scalar
Lower limit.
mode : scalar
The value where the peak of the distribution occurs. The value should fulfill the condition left <= mode <= right.
right : scalar
Upper limit, should be larger than left.
size : int or tuple of ints, optional
Output shape. Default is None, in which case a single value is returned.
samples : ndarray or scalar
The returned samples all lie in the interval [left, right].

The probability density function for the Triangular distribution is

P(x;l, m, r) = \begin{cases}
\frac{2(x-l)}{(r-l)(m-l)}& \text{for $l \leq x \leq m$},\\
\frac{2(m-x)}{(r-l)(r-m)}& \text{for $m \leq x \leq r$},\\
0& \text{otherwise}.
\end{cases}

The triangular distribution is often used in ill-defined problems where the underlying distribution is not known, but some knowledge of the limits and mode exists. Often it is used in simulations.

[1]Wikipedia, “Triangular distribution” http://en.wikipedia.org/wiki/Triangular_distribution

Draw values from the distribution and plot the histogram:

>>> import matplotlib.pyplot as plt
>>> h = plt.hist(np.random.triangular(-3, 0, 8, 100000), bins=200,
...              normed=True)
>>> plt.show()
XRStools.xrs_calctools.uniform(low=0.0, high=1.0, size=1)

Draw samples from a uniform distribution.

Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by uniform.

low : float, optional
Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0.
high : float
Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0.
size : int or tuple of ints, optional
Shape of output. If the given size is, for example, (m,n,k), m*n*k samples are generated. If no shape is specified, a single sample is returned.
out : ndarray
Drawn samples, with shape size.

randint : Discrete uniform distribution, yielding integers. random_integers : Discrete uniform distribution over the closed

interval [low, high].

random_sample : Floats uniformly distributed over [0, 1). random : Alias for random_sample. rand : Convenience function that accepts dimensions as input, e.g.,

rand(2,2) would generate a 2-by-2 array of floats, uniformly distributed over [0, 1).

The probability density function of the uniform distribution is

p(x) = \frac{1}{b - a}

anywhere within the interval [a, b), and zero elsewhere.

Draw samples from the distribution:

>>> s = np.random.uniform(-1,0,1000)

All values are within the given interval:

>>> np.all(s >= -1)
True
>>> np.all(s < 0)
True

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 15, normed=True)
>>> plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')
>>> plt.show()
XRStools.xrs_calctools.vonmises(mu, kappa, size=None)

Draw samples from a von Mises distribution.

Samples are drawn from a von Mises distribution with specified mode (mu) and dispersion (kappa), on the interval [-pi, pi].

The von Mises distribution (also known as the circular normal distribution) is a continuous probability distribution on the unit circle. It may be thought of as the circular analogue of the normal distribution.

mu : float
Mode (“center”) of the distribution.
kappa : float
Dispersion of the distribution, has to be >=0.
size : int or tuple of int
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn.
samples : scalar or ndarray
The returned samples, which are in the interval [-pi, pi].
scipy.stats.distributions.vonmises : probability density function,
distribution, or cumulative density function, etc.

The probability density for the von Mises distribution is

p(x) = \frac{e^{\kappa cos(x-\mu)}}{2\pi I_0(\kappa)},

where \mu is the mode and \kappa the dispersion, and I_0(\kappa) is the modified Bessel function of order 0.

The von Mises is named for Richard Edler von Mises, who was born in Austria-Hungary, in what is now the Ukraine. He fled to the United States in 1939 and became a professor at Harvard. He worked in probability theory, aerodynamics, fluid mechanics, and philosophy of science.

Abramowitz, M. and Stegun, I. A. (ed.), Handbook of Mathematical Functions, New York: Dover, 1965.

von Mises, R., Mathematical Theory of Probability and Statistics, New York: Academic Press, 1964.

Draw samples from the distribution:

>>> mu, kappa = 0.0, 4.0 # mean and dispersion
>>> s = np.random.vonmises(mu, kappa, 1000)

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> import scipy.special as sps
>>> count, bins, ignored = plt.hist(s, 50, normed=True)
>>> x = np.arange(-np.pi, np.pi, 2*np.pi/50.)
>>> y = -np.exp(kappa*np.cos(x-mu))/(2*np.pi*sps.jn(0,kappa))
>>> plt.plot(x, y/max(y), linewidth=2, color='r')
>>> plt.show()
XRStools.xrs_calctools.wald(mean, scale, size=None)

Draw samples from a Wald, or Inverse Gaussian, distribution.

As the scale approaches infinity, the distribution becomes more like a Gaussian.

Some references claim that the Wald is an Inverse Gaussian with mean=1, but this is by no means universal.

The Inverse Gaussian distribution was first studied in relationship to Brownian motion. In 1956 M.C.K. Tweedie used the name Inverse Gaussian because there is an inverse relationship between the time to cover a unit distance and distance covered in unit time.

mean : scalar
Distribution mean, should be > 0.
scale : scalar
Scale parameter, should be >= 0.
size : int or tuple of ints, optional
Output shape. Default is None, in which case a single value is returned.
samples : ndarray or scalar
Drawn sample, all greater than zero.

The probability density function for the Wald distribution is

P(x;mean,scale) = \sqrt{\frac{scale}{2\pi x^3}}e^
\frac{-scale(x-mean)^2}{2\cdotp mean^2x}

As noted above the Inverse Gaussian distribution first arise from attempts to model Brownian Motion. It is also a competitor to the Weibull for use in reliability modeling and modeling stock returns and interest rate processes.

[1]Brighton Webs Ltd., Wald Distribution, http://www.brighton-webs.co.uk/distributions/wald.asp
[2]Chhikara, Raj S., and Folks, J. Leroy, “The Inverse Gaussian Distribution: Theory : Methodology, and Applications”, CRC Press, 1988.
[3]Wikipedia, “Wald distribution” http://en.wikipedia.org/wiki/Wald_distribution

Draw values from the distribution and plot the histogram:

>>> import matplotlib.pyplot as plt
>>> h = plt.hist(np.random.wald(3, 2, 100000), bins=200, normed=True)
>>> plt.show()
XRStools.xrs_calctools.weibull(a, size=None)

Weibull distribution.

Draw samples from a 1-parameter Weibull distribution with the given shape parameter a.

X = (-ln(U))^{1/a}

Here, U is drawn from the uniform distribution over (0,1].

The more common 2-parameter Weibull, including a scale parameter \lambda is just X = \lambda(-ln(U))^{1/a}.

a : float
Shape of the distribution.
size : tuple of ints
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn.

scipy.stats.distributions.weibull_max scipy.stats.distributions.weibull_min scipy.stats.distributions.genextreme gumbel

The Weibull (or Type III asymptotic extreme value distribution for smallest values, SEV Type III, or Rosin-Rammler distribution) is one of a class of Generalized Extreme Value (GEV) distributions used in modeling extreme value problems. This class includes the Gumbel and Frechet distributions.

The probability density for the Weibull distribution is

p(x) = \frac{a}
{\lambda}(\frac{x}{\lambda})^{a-1}e^{-(x/\lambda)^a},

where a is the shape and \lambda the scale.

The function has its peak (the mode) at \lambda(\frac{a-1}{a})^{1/a}.

When a = 1, the Weibull distribution reduces to the exponential distribution.

[1]Waloddi Weibull, Professor, Royal Technical University, Stockholm, 1939 “A Statistical Theory Of The Strength Of Materials”, Ingeniorsvetenskapsakademiens Handlingar Nr 151, 1939, Generalstabens Litografiska Anstalts Forlag, Stockholm.
[2]Waloddi Weibull, 1951 “A Statistical Distribution Function of Wide Applicability”, Journal Of Applied Mechanics ASME Paper.
[3]Wikipedia, “Weibull distribution”, http://en.wikipedia.org/wiki/Weibull_distribution

Draw samples from the distribution:

>>> a = 5. # shape
>>> s = np.random.weibull(a, 1000)

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> x = np.arange(1,100.)/50.
>>> def weib(x,n,a):
...     return (a / n) * (x / n)**(a - 1) * np.exp(-(x / n)**a)
>>> count, bins, ignored = plt.hist(np.random.weibull(5.,1000))
>>> x = np.arange(1,100.)/50.
>>> scale = count.max()/weib(x, 1., 5.).max()
>>> plt.plot(x, weib(x, 1., 5.)*scale)
>>> plt.show()
XRStools.xrs_calctools.writeFDMNESinput_file(xyzAtoms, fname, Filout, Range, Radius, Edge, NRIXS, Absorber)[source]

writeFDMNESinput_file Writes an input file to be used for FDMNES.

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_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.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.

XRStools.xrs_calctools.writeXYZfile(filename, numberOfAtoms, title, list_of_xyzAtoms)[source]
XRStools.xrs_calctools.writeXYZtrajectory(filename, boxes)[source]
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.

name (str): Atomic symbol. coordinates (np.array): Array of xyz-coordinates. number (int): Integer, e.g. number of atom in a cluster.
getCoordinates()[source]
getNorm()[source]
translateSelf(vector)[source]
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.

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.

deleteTip4pCOM()[source]

deleteTip4pCOM Deletes the ficticious atoms used in the TIP4P water model.

getCoordinates()[source]

getCoordinates Return coordinates of all atoms in the cluster.

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_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.

scatterPlot()[source]

scatterPlot Opens a plot window with a scatter-plot of all coordinates of the box.

setBoxLength(boxLength, angstrom=True)[source]

setBoxLength Set the box length.

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.

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.

writeOCEANinput(fname, headerfile, exatom, edge, subshell)[source]

writeOCEANinput Creates an OCEAN input file based on the headerfile.

writeRelBox(filename, inclAtomNames=True)[source]

writeRelBox Writes all relative atom coordinates into a text file (useful as OCEAN input).

class XRStools.xrs_calctools.xyzMolecule(xyzAtoms, title=None)[source]

Bases: object

xyzMolecule

Class to hold information about and manipulate an xyz-style molecule.

xyzAtoms (list): List of instances of the xyzAtoms class that make up the molecule.
appendAtom(Atom)[source]

appendAtom Add an xzyAtom to the molecule.

getCoordinates()[source]

getCoordinates Return coordinates of all atoms in the cluster.

getCoordinates_name(name)[source]

getCoordinates_name Return coordintes of all atoms with ‘name’.

getGeometricCenter()[source]

getGeometricCenter Return the geometric center of the xyz-molecule.

get_atoms_by_name(name)[source]

get_atoms_by_name Return a list of all xyzAtoms of a given name ‘name’.

popAtom(xyzAtom)[source]

popAtom Delete an xyzAtom from the molecule.

scatterPlot()[source]

scatterPlot Opens a plot window with a scatter-plot of all coordinates of the molecule.

translateSelf(vector)[source]

translateSelf Translate all atoms of the molecule by a vector ‘vector’.

writeXYZfile(fname)[source]

writeXYZfile Creates an xyz-style text file with all coordinates of the molecule.

XRStools.xrs_calctools.xyzTrajecParser(filename, boxLength)[source]

Parses a Trajectory of xyz-files.

Args:
filename (str): Filename of the xyz Trajectory file.
Returns:
A list of xzyBoxes.
class XRStools.xrs_calctools.xyzTrajectory(xyzBoxes)[source]

Bases: object

getRDF(atom1='O', atom2='O', MAXBIN=1000, DELR=0.01, RHO=1.0)[source]
loadAXSFtraj(filename)[source]
writeRandBox(filename)[source]
writeXYZtraj(filename)[source]
XRStools.xrs_calctools.zipf(a, size=None)

Draw samples from a Zipf distribution.

Samples are drawn from a Zipf distribution with specified parameter a > 1.

The Zipf distribution (also known as the zeta distribution) is a continuous probability distribution that satisfies Zipf’s law: the frequency of an item is inversely proportional to its rank in a frequency table.

a : float > 1
Distribution parameter.
size : int or tuple of int, optional
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn; a single integer is equivalent in its result to providing a mono-tuple, i.e., a 1-D array of length size is returned. The default is None, in which case a single scalar is returned.
samples : scalar or ndarray
The returned samples are greater than or equal to one.
scipy.stats.distributions.zipf : probability density function,
distribution, or cumulative density function, etc.

The probability density for the Zipf distribution is

p(x) = \frac{x^{-a}}{\zeta(a)},

where \zeta is the Riemann Zeta function.

It is named for the American linguist George Kingsley Zipf, who noted that the frequency of any word in a sample of a language is inversely proportional to its rank in the frequency table.

Zipf, G. K., Selected Studies of the Principle of Relative Frequency in Language, Cambridge, MA: Harvard Univ. Press, 1932.

Draw samples from the distribution:

>>> a = 2. # parameter
>>> s = np.random.zipf(a, 1000)

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> import scipy.special as sps
Truncate s values at 50 so plot is interesting
>>> count, bins, ignored = plt.hist(s[s<50], 50, normed=True)
>>> x = np.arange(1., 50.)
>>> y = x**(-a)/sps.zetac(a)
>>> plt.plot(x, y/max(y), linewidth=2, color='r')
>>> plt.show()

XRStools.xrs_extraction Module

class XRStools.xrs_extraction.HF_dataset(data, formulas, stoich_weights, edges)[source]

dataset A class to hold all information from HF Compton profiles necessary to subtract background from the experiment.

get_C_edges_av(element, edge, columns)[source]
get_C_total(columns)[source]
get_J_total_av(columns)[source]
class XRStools.xrs_extraction.edge_extraction(exp_data, formulas, stoich_weights, edges, prenormrange=[5, inf])[source]

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_numbers : list, str
list of ROI numbers to average over of keyword for analyzer chamber (e.g. ‘VD’,’VU’,’VB’,’HR’,’HL’,’HB’)
errorweighing : boolean (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)[source]

removeCorePearsonAv

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.

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).

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_extraction.map_chamber_names(name)[source]

map_chamber_names Maps names of chambers to range of ROI numbers.

class XRStools.xrs_extraction.valence_CP[source]

valence_CP Class to organize information about extracted experimental valence Compton profiles.

get_asymmetry()[source]
get_pzscale()[source]

XRStools.xrs_imaging Module

class XRStools.xrs_imaging.LRimage(matrix, xscale, yscale, cornerpos=[0, 0])[source]

container class to hold info of a single LR-image to be put togther in a SR-image by the imageset class

load()[source]
plotimage()[source]
save()[source]
shiftx()[source]
shifty()[source]
XRStools.xrs_imaging.estimate_shift(x1, y1, im1, x2, y2, im2)[source]

estimate shift in x-direction only by stepwise shifting im2 by precision and thus minimising the sum of the difference between im1 and im2

XRStools.xrs_imaging.estimate_xshift(x1, y1, im1, x2, y2, im2)[source]

estimate shift in x-direction only by stepwise shifting im2 by precision and thus minimising the sum of the difference between im1 and im2

XRStools.xrs_imaging.estimate_yshift(x1, y1, im1, x2, y2, im2)[source]

estimate shift in x-direction only by stepwise shifting im2 by precision and thus minimising the sum of the difference between im1 and im2

class XRStools.xrs_imaging.image(matrix, xscale, yscale)[source]

Container class to hold info of a single LR-image to be put togther in a SR-image by the imageset class

load()[source]
plotimage()[source]
save()[source]
shiftx()[source]
shifty()[source]
class XRStools.xrs_imaging.imageset[source]

class to make SR-images from list of LR-images

estimate_shifts(whichimage=None)[source]
estimate_xshifts(whichimage=None)[source]
estimate_yshifts(whichimage=None)[source]
interpolate_shift_images(scaling, whichimages=None)[source]
interpolate_xshift_images(scaling, whichimages=None)[source]
interpolate_yshift_images(scaling, whichimages=None)[source]
load()[source]
loadhe3070(matfilename)[source]
loadkimberlite(matfilename)[source]
plotLR(whichimage)[source]
plotSR()[source]
save()[source]
XRStools.xrs_imaging.interpolate_image(oldx, oldy, oldIM, newx, newy)[source]

2d interpolation

class XRStools.xrs_imaging.oneD_imaging(absfilename, energycolumn='sty', monitorcolumn='kapraman', monitor_divider=1.0, edfName=None, single_image=True, sumto1D=1, recenterings=None)[source]

Bases: XRStools.xrs_read.read_id20

oneD_imaging Class to construct images using the 1D piercing mode.

load_state_hdf5(filename, groupname)[source]
loadscan_2Dimages(scannumbers, scantype='sty', isolateSpot=0)[source]
save_state_hdf5(filename, groupname, comment='', myrank=0, factor=1.0)[source]

XRStools.xrs_read Module

class XRStools.xrs_read.Fourc(path, SPECfname='rixs', EDFprefix='/edf/', EDFname='rixs_', EDFpostfix='.edf', en1_column='energy', en2_column='anal energy', moni_column='izero', EinCoor=[10, 1])[source]

Bases: object

Main class for handling RIXS data from ID20’s high-resolution spectrometer ‘Fourc’.

This class is intended to read SPEC- and according EDF-files and perform dispersion compensations.

Note:

‘Fourc’ is the name of the high-energy-resolution spectrometer at ESRF’s ID20 beamline. This class has been adopted specifically for this spectrometer.

If you are using this program, please cite the following work:

Sahle, Ch J., A. Mirone, J. Niskanen, J. Inkinen, M. Krisch, and S. Huotari. “Planning, performing and analyzing X-ray Raman scattering experiments.” Journal of Synchrotron Radiation 22, No. 2 (2015): 400-409.

Args:

path (str): Absolute path to directory holding the data. SPECfname (str): Name of the SPEC-file (‘rixs’ is the default). EDFprefix (str): Prefix for the EDF-files (‘/edf/’ is the default). EDFname (str): Filename of the EDF-files (‘rixs_‘ is the default). EDFpostfix (str): Postfix for the EDF-files (‘.edf’ is the default). en_column (str): Counter mnemonic for the energy motor (‘energy’ is the default). moni_column (str): Mnemonic for the monitor counter (‘izero’ is the default). EinCoor (list): Coordinates, where to find the incident energy value in the

SPEC-file (default is [9,0])
Attributes:

path (str): Absolute path to directory holding the data. SPECfname (str): Name of the SPEC-file (‘hydra’ is the default). EDFprefix (str): Prefix for the EDF-files (‘/edf/’ is the default). EDFname (str): Filename of the EDF-files (‘hydra_‘ is the default). EDFpostfix (str): Postfix for the EDF-files (‘.edf’ is the default). en1_column (str): Counter mnemonic for the energy motor (‘anal energy’ is the default). en2_column (str): Counter mnemonic for the energy motor (‘energy’ is the default). moni_column (str): Mnemonic for the monitor counter (‘izero’ is the default). EinCoor (list): Coordinates, where to find the incident energy value in the

SPEC-file (default is [9,0])

scans (dict): Dictionary holding all loaded scans. scan_numbers (list): List with scan number of all loaded scans.

energy (np.array): Array with the common energy scale. energy2 (np.array): Array with the common energy2 scale. signals (np.array): Array with the signals for all analyzers (one column per anayzer). errors (np.array): Array with the poisson errors for all analyzers (one column per anayzer). groups (dict): Dictionary of groups of scans (instances of the ‘scangroup’ class,

such as 2 ‘elastic’, or 5 ‘edge1’, etc.).

tth (list): List of all scattering angles (one value for each ROI). resolution (list): List of FWHM of the elastic lines (one for each analyzer).

roi_obj (instance): Instance of the roi_object class from the xrs_rois module defining all
ROIs for the current dataset (default is ‘None’).

comp_factor (float): Compensation factor used for the dispersion correction. PIXEL_SIZE (float): Pixel size of the used Maxipix detector (in mm).

SumDirect(scan_numbers)[source]

Creates a summed 2D image of a given scan or list of scans.

Args:
scan_numbers (int or list): Scan number or list of scan numbers to be added up.
Returns:
A 2D np.array of the same size as the detector with the summed image.
delete_scan(scan_numbers)[source]

Deletes scans of given scan numbers.

Args: scan_numbers (int or list): SPEC scan numbers to be deleted.

dump_ascii_file(scan_numbers, pre_fix, f_name, post_fix='.dat', header='')[source]

Produce ASCII-type files with columns of energy, signal, and Poisson error.

Args: scan_numbers (int or list): SPEC scan numbers of scans to be safed in ASCII format. pre_fix (str): Path to directory where files should be written into. f_name (str): Base name for the files to be written. post_fix (str): Extention for the files to be written (default is ‘.dat’).

get_compensation_factor(scan_number, roi_number)[source]
Calculates the dispersion compensation factor based on an
elastic line scan.
Args:

scan_number (int): Scan number of the elastic line scan as in the SPEC-file. roi_number (int): Number of the ROI for which the compensation factor is

to be calculated (default is number 0, i.e. the first ROI)
load_scan(scan_numbers, direct=True, comp_factor=None, scan_type='generic', scaling=None)[source]

Loads given scans and applies the dispersion compensation.

Args:

scan_numbers (int or list): Scan number(s) of scans to be loaded. direct (boolean): Flag, if set to ‘True’, EDF-files are

deleted after loading the scan (this is the default).
comp_factor (float): Compensation factor to be used. If ‘None’,
the global compensation factor will be used. If provided, the global compensation factor will be overwritten.

scan_type (str): String describing the scan to be loaded.

Note:
If a compensation factor is passed to this function, the classes ‘globel’ compensation factor is overwritten.
set_roiObj(roiobj)[source]

Assign an instance of the ‘roi_object’ class to the current data set.

Args:
roiobj (instance): Instance of the ‘roi_object’ class holding all
information about the definition of the ROIs.
class XRStools.xrs_read.Hydra(path, SPECfname='hydra', EDFprefix='/edf/', EDFname='hydra_', EDFpostfix='.edf', en_column='energy', moni_column='izero')[source]

Bases: object

New main class for handling XRS data from ID20’s multi-analyzer spectrometer ‘Hydra’.

This class is intended to read SPEC- and according EDF-files and generate spectra from multiple individual energy loss scans.

Note:

Hydra is the name of the multi-analyzer x-ray Raman scattering spectrometer at ESRF’s ID20 beamline. This class has been adopted specifically for this spectrometer.

If you are using this program, please cite the following work:

Sahle, Ch J., A. Mirone, J. Niskanen, J. Inkinen, M. Krisch, and S. Huotari. “Planning, performing and analyzing X-ray Raman scattering experiments.” Journal of Synchrotron Radiation 22, No. 2 (2015): 400-409.

Args:
path (str): Absolute path to directory holding the data. SPECfname (str): Name of the SPEC-file (‘hydra’ is the default). EDFprefix (str): Prefix for the EDF-files (‘/edf/’ is the default). EDFname (str): Filename of the EDF-files (‘hydra_‘ is the default). EDFpostfix (str): Postfix for the EDF-files (‘.edf’ is the default). en_column (str): Counter mnemonic for the energy motor (‘energy’ is the default). moni_column (str): Mnemonic for the monitor counter (‘izero’ is the default).
Attributes:

path (str): Absolute path to directory holding the data. SPECfname (str): Name of the SPEC-file (‘hydra’ is the default). EDFprefix (str): Prefix for the EDF-files (‘/edf/’ is the default). EDFname (str): Filename of the EDF-files (‘hydra_‘ is the default). EDFpostfix (str): Postfix for the EDF-files (‘.edf’ is the default). en_column (str): Counter mnemonic for the energy motor (‘energy’ is the default). moni_column (str): Mnemonic for the monitor counter (‘izero’ is the default).

scans (dict): Dictionary holding all loaded scans. scan_numbers (list): List with scan number of all loaded scans. eloss (np.array): Array with the common energy loss scale for all analyzers. energy (np.array): Array with the common energy scale for all analyzers. signals (np.array): Array with the signals for all analyzers (one column per anayzer). errors (np.array): Array with the poisson errors for all analyzers (one column per anayzer). qvalues (list): List of momentum transfer values for all analyzers. groups (dict): Dictionary of groups of scans (instances of the ‘scangroup’ class,

such as 2 ‘elastic’, or 5 ‘edge1’, etc.).

cenom (list): List of center of masses of the elastic lines. E0 (int): Elastic line energy value, mean value of all center of masses. tth (list): List of all scattering angles (one value for each ROI). resolution (list): List of FWHM of the elastic lines (one for each analyzer).

TTH_OFFSETS1 (np.array): Two-Theta offsets between individual analyzers inside each analyzer
module in one direction (horizontal for V-boxes, vertical for H-boxes).
TTH_OFFSETS2 (np.array): Two-Theta offsets between individual analyzers inside each analyzer
module in one direction (horizontal for H-boxes, vertical for V-boxes).
roi_obj (instance): Instance of the roi_object class from the xrs_rois module defining all
ROIs for the current dataset (default is ‘None’).
SumDirect(scan_numbers)[source]

Creates a summed 2D image of a given scan or list of scans.

Args:
scan_numbers (int or list): Scan number or list of scan numbers to be added up.
Returns:
A 2D np.array of the same size as the detector with the summed image.
copy_edf_files(scan_numbers, destination)[source]

Helper function to copy selected EDF-files of, e.g., a single scan to a different directory.

Args: scan_numbers (int or list): Scan number or list of scan numbers defining scans in the SPEC-file

for which the EDF-files are to be copied.

destination (str): Absolute path for the directory into which the files are to be copied.

delete_scan(scan_numbers)[source]

Deletes scans from the dictionary of scans.

Args:
scan_numbers (int or list): Integer or list of integers (SPEC scan numbers) to be deleted.
dump_ascii_file(scan_numbers, pre_fix, f_name, post_fix='.dat', header='')[source]

Produce ASCII-type files with columns of energy, signal, and Poisson error.

Args: scan_numbers (int or list): SPEC scan numbers of scans to be safed in ASCII format. pre_fix (str): Path to directory where files should be written into. f_name (str): Base name for the files to be written. post_fix (str): Extention for the files to be written (default is ‘.dat’).

dump_spectrum_ascii(filename)[source]

Stores the energy loss and signals in a txt-file.

Args:
filename (str): Path and filename to the file to be written.
get_data()[source]

Applies the ROIs and sums up intensities.

Returns:
‘None’, if no ROI object is available.
get_data_pw()[source]

Extracts intensities for each pixel in each ROI.

Returns:
‘None’, if no ROI object is available.
get_eloss()[source]

Finds the energy loss scale for all ROIs by calculating the center of mass (COM) for each ROI’s elastic line. Calculates the resolution function (FWHM) of the elastic lines.

get_q_values(inv_angstr=False, energy_loss=None)[source]

Calculates the momentum transfer for each analyzer.

Args:
inv_angstr (boolean): Boolean flag, if ‘True’ momentum transfers are calculated in
inverse Angstroms.
energy_loss (float): Energy loss value at which the momentum transfer is to be
calculated. If ‘None’ is given, the momentum transfer is calculated for every energy loss point of the spectrum.
Returns:
If an energy loss value is passed, the function returns the momentum transfers at this energy loss value for each analyzer crystal.
get_spectrum(include_elastic=False, abs_counts=False)[source]
Construct a spectrum based on the scans loaded so far. Defines the energy
loss scale based on the elastic lines.
Args:
include_elastic (boolean): Boolean flag, does not include the elastic line if
set to ‘False’ (this is the default).
abs_counts (boolean): Boolean flag, constructs the spectrum in absolute
counts if set to ‘True’ (default is ‘False’)
get_tths(rvd=0.0, rvu=0.0, rvb=0.0, rhl=0.0, rhr=0.0, rhb=0.0, order=[0, 1, 2, 3, 4, 5])[source]
Calculates the scattering angles for all analyzer crystals based on
the mean angle of the analyzer modules.
Args:

rhl (float): Mean scattering angle of the HL module (default is 0.0). rhr (float): Mean scattering angle of the HR module (default is 0.0). rhb (float): Mean scattering angle of the HB module (default is 0.0). rvd (float): Mean scattering angle of the VD module (default is 0.0). rvu (float): Mean scattering angle of the VU module (default is 0.0). rvb (float): Mean scattering angle of the VB module (default is 0.0). order (list): List of integers (0-5) that describe the order of modules in which the

ROIs were defined (default is VD, VU, VB, HR, HL, HB; i.e. [0,1,2,3,4,5]).
load_loop(beg_nums, num_of_regions, direct=True)[source]
Loads a whole loop of scans based on their starting numbers and
the number of single scans in the loop.

Args: beg_nums (list): List of scan numbers of the first scans in each loop. num_of_regions (int): Number of scans in each loop.

load_scan(scan_numbers, scan_type='generic', direct=True, scaling=None)[source]

Load a single or multiple scans.

Note:
When composing a spectrum later, scans of the same ‘scan_type’ will be averaged over. Scans with scan type ‘elastic’ or ‘long’ in their names are recognized and will be treated specially.
Args:
scan_numbers (int or list): Integer or iterable of scan numbers to be loaded. scan_type (str): String describing the scan to be loaded (e.g. ‘edge1’ or ‘K-edge’). direct (boolean): Flag, ‘True’ if the EDF-files should be deleted after loading/integrating the scan.
load_state_hdf5(filename, groupname)[source]

Load the status of an instance from an HDF5 file.

Args:
filename (str): Path and filename for the HDF5-file to be created. groupname (str): Group name under which to store status in the HDF5-file.
print_length(scan_numbers)[source]

Print out the numper of points in given scans.

Args:
scan_numbers (int or list): Scan number or list of scan numbers.
save_state_hdf5(filename, groupname, comment='')[source]

Save the status of the current instance in an HDF5 file.

Args:
filename (str): Path and filename for the HDF5-file to be created. groupname (str): Group name under which to store status in the HDF5-file. comment (str): Optional comment (no comment is default).
set_roiObj(roiobj)[source]

Assign an instance of the ‘roi_object’ class to the current data set.

Args:
roiobj (instance): Instance of the ‘roi_object’ class holding all
information about the definition of the ROIs.
there_is_a_valid_roi_at(n)[source]

Checks if n is a valid ROI index.

Args:
n (int): Index to be checked.
Returns:
True, if n is a valid ROI index.
XRStools.xrs_read.alignment_image(id20read_object, scannumber, motorname, filename=None)[source]

Loads a scan from a sample position scan (x-scan, y-scan, z-scan), lets you choose a zoomroi and constructs a 2D image from this INPUT: scannumber = number of the scan motorname = string that contains the motor name (must be the same as in the SPEC file) filename = optional parameter with filename to store the image

XRStools.xrs_read.animation(id20read_object, scannumber, logscaling=True, timeout=-1, colormap='jet')[source]

Shows the edf-files of a scan as a ‘movie’. INPUT: scannumber = integer/scannumber logscaling = set to ‘True’ (default) if edf-images are to be shown on logarithmic-scale timeout = time in seconds defining pause between two images, if negative (default)

images are renewed by mouse clicks

colormap = matplotlib color scheme used in the display

XRStools.xrs_read.get_scans_pw(id20read_object, scannumbers)[source]

get_scans_pw Sums scans from pixelwise ROI integration for use in the PW roi refinement.

XRStools.xrs_read.print_citation_message()[source]

Prints plea for citing the XRStools article when using this software.

class XRStools.xrs_read.read_id20(absfilename, energycolumn='energy', monitorcolumn='kap4dio', edfName=None, single_image=True)[source]

Bases: object

Main class for handling raw data from XRS experiments on ESRF’s ID20. This class

is used to read scans from SPEC files and the according EDF-files, it provides access to all tools from the xrs_rois module for defining ROIs, it can be used to integrate scans, sum them up, stitch them together, and define the energy loss scale. INPUT: absfilename = path and filename of the SPEC-file energycolumn = name (string) of the counter for the energy as defined in the SPEC session (counter mnemonic) monitorcolumn = name (string) of the counter for the monitor signals as defined in the SPEC session (counter mnemonic) edfName = name/prefix (string) of the EDF-files (default is the same as the SPEC-file name) single_image = boolean switch, ‘True’ (default) if all 6 detectors are merged in a single image,

‘False’ if two detector images per point exist.
SumDirect(scannumbers)[source]
copy_edf_files(scannumbers, destdir)[source]

Copies all edf-files from scan with scannumber or scannumbers into directory ‘destdir’ INPUT: scannumbers = integer or list of integers defining the scannumbers from the SPEC file destdir = string with absolute path for the destination

deletescan(scannumbers)[source]

Deletes scans from the class. INPUT: scannumbers = integer or list of integers (SPEC scan numbers) to delete

geteloss()[source]

Defines the energy loss scale for all ROIs by finding the center of mass for each ROI’s elastic line. Interpolates the signals and errors onto a commom energy loss scale. Finds the resolution (FWHM) of the ‘elastic’ groups.

getqvals(invangstr=False)[source]

Calculates q-values from E0 and tth values in either atomic units (defalt) or inverse angstroms.

getqvals_energy(energy)[source]

Returns all q-values at a certain energy loss. INPUT: energy = energy loss value for which all q-values are stored

getrawdata()[source]

Goes through all instances of the scan class and calls it’s applyrois method to sum up over all rois.

getrawdata_pixelwise()[source]

Goes through all instances of the scan class and calls it’s applyrois_pw method to extract intensities for all pixels in each ROI.

getspectrum(include_elastic=False, absCounts=False)[source]

Groups the instances of the scan class by their scantype attribute, adds equal scans (each group of equal scans) and appends them. INPUT: include_elastic = boolean flag, skips the elastic line if set to ‘False’ (default)

gettths(rvd=0.0, rvu=0.0, rvb=0.0, rhl=0.0, rhr=0.0, rhb=0.0, order=[0, 1, 2, 3, 4, 5])[source]

Uses the defined TT_OFFSETS of the read_id20 class to set all scattering angles tth from the mean angle avtth of the analyzer modules. INPUT: rhl = mean tth angle of HL module (default is 0.0) rhr = mean tth angle of HR module (default is 0.0) rhb = mean tth angle of HB module (default is 0.0) rvd = mean tth angle of VD module (default is 0.0) rvu = mean tth angle of VU module (default is 0.0) rvb = mean tth angle of VB module (default is 0.0) order = list of integers (0-5) which describes the order of modules in which the

ROIs were defined (default is VD, VU, VB, HR, HL, HB; i.e. [0,1,2,3,4,5])
load_state_hdf5(filename, groupname)[source]
loadelastic(scann, fromtofile=False)[source]
Loads a scan using the loadscan function and sets the scantype attribute to ‘elastic’.

I.e. shorthand for ‘obj.loadscan(scannumber,type=’elastic’)’. INPUT: scann = integer or list of integers fromtofile = boolean flag, ‘True’ if the scan should be saved in a pickle-file (this is developmental)

loadelasticdirect(scann, fromtofile=False)[source]
Loads a scan using the loadscan function and sets the scantype attribute to ‘elastic’.

I.e. shorthand for ‘obj.loadscan(scannumber,type=’elastic’)’. INPUT: scann = integer or list of integers fromtofile = boolean flag, ‘True’ if the scan should be saved in a pickle-file (this is developmental)

loadlong(scann, fromtofile=False)[source]
Loads a scan using the loadscan function and sets the scantype attribute to ‘long’.

I.e. shorthand for ‘obj.loadscan(scannumber,type=’long’)’. INPUT: scann = integer or list of integers fromtofile = boolean flag, ‘True’ if the scan should be saved in a pickle-file (this is developmental)

loadlongdirect(scann, fromtofile=False, scaling=None)[source]
Loads a scan using the loadscan function and sets the scantype attribute to ‘long’.

I.e. shorthand for ‘obj.loadscan(scannumber,type=’long’)’. INPUT: scann = integer or list of integers fromtofile = boolean flag, ‘True’ if the scan should be saved in a pickle-file (this is developmental)

loadloop(begnums, numofregions, fromtofile=False)[source]
Loads a whole loop of scans based on their starting scannumbers and the number of single scans in the loop.
INPUT:
begnums = list of scannumbers of the first scans of each loop (is a list) numofregions = number of scans in each loop (integer)
loadloopdirect(begnums, numofregions, fromtofile=False, scaling=None)[source]
Loads a whole loop of scans based on their starting scannumbers and the number of single
INPUT:
begnums = list of scannumbers of the first scans of each loop (is a list) numofregions = number of scans in each loop (integer)
fromtofile = boolean flag, ‘True’ if the scan should be saved in a pickle-file (this is developmental)
scaling = list of scaling factors to be applied, one for each ROI defined
loadscan(scannumbers, scantype='generic', fromtofile=False)[source]
Loads the files belonging to scan No. “scannumber” and puts it into an instance of the xrs_scan-class ‘scan’. The default scantype is ‘generic’, later the scans will be grouped (and added) based on the scantype.

INPUT: scannumbers = integer or list of scannumbers that should be loaded scantype = string describing the scan to be loaded (e.g. ‘edge1’ or ‘K-edge’) fromtofile = boolean flag, ‘True’ if the scan should be saved in a pickle-file (this is developmental)

loadscandirect(scannumbers, scantype='generic', fromtofile=False, scaling=None)[source]
Loads a scan without saving the edf files in matrices. scannumbers = integer or list of integers defining the scannumbers from the SPEC file scantype = string describing the scan to be loaded (e.g. ‘edge1’ or ‘K-edge’)
fromtofile = boolean flag, ‘True’ if the scan should be saved in a pickle-file (this is developmental)
scaling = list of scaling factors to be applied, one for each ROI defined
orderrois(arrangement='vertical', missing=None)[source]

order the rois in an order provided such that e.g. autorois have the correct order

printlength(scannumbers)[source]

Prints the number of energy points in a scan or a number of scans. INPUT: scannumbers = integer or list of integers

read_just_first_scanimage(scannumber)[source]
readscan(scannumber, fromtofile=False)[source]
Returns the data, motors, counter-names, and edf-files from the SPEC file defined when
the xrs_read object was initiated.
There should be an alternative that uses the PyMca module if installed.

INPUT: scannumber = number of the scan to be loaded fromtofile = boolean flag, ‘True’ if the scan should be saved in a pickle-file (this is developmental)

readscan_new(scannumber, fromtofile=False)[source]
Returns the data, motors, counter-names, and edf-files from the SPEC file defined when
the xrs_read object was initiated.
There should be an alternative that uses the PyMca module if installed.

INPUT: scannumber = number of the scan to be loaded fromtofile = boolean flag, ‘True’ if the scan should be saved in a pickle-file (this is developmental)

removeBackgroundRoi(backroinum, estart=None, estop=None)[source]
save_raw_data(filename)[source]
save_state()[source]
save_state_hdf5(filename, groupname, comment='')[source]
set_roiObj(roiobj)[source]
there_is_a_valid_roi_at(n)[source]

XRStools.xrs_scans Module

class XRStools.xrs_scans.Scan[source]

Bases: object

New version of a container holding information of a single scan.

All relevant information from the SPEC- and EDF-files are organized in instances of this class.

Attributes:
edf_mats (np.array): Array containing all 2D images that belong to the scan. number (int): Scan number as in the SPEC file. scan_type (string): Keyword, used later to group scans (add similar scans, etc.). energy (np.array): Array containing the energy axis (1D). monitor (np.array): Array containing the monitor signal (1D). counters (dictionary): Counters with assiciated data from the SPEC file. motors (list): Motor positions as found in the SPEC file header. eloss (np.array): Array of the energy loss scale. signals (np.array): Array of signals extracted from the ROIs. errors (np.array): Array of Poisson errors. cenom (list): Center of mass for each ROI (used if scan is an elastic line scan). signals_pw (list): Pixelwise (PW) data, one array of PW data per ROI. errors_pw (list): Pixelwise (PW) Poisson errors, one array of PW errors per ROI. cenom_pw (list): Center of mass for each pixel. signals_pw_interp (list): Interpolated signals for each pixel.
apply_rois(roi_obj, scaling=None)[source]

Sums up intensities in each ROI.

Args:
roi_obj (instance): Instance of the ‘XRStools.xrs_rois.roi_object’ class defining the ROIs. scaling (np.array): Array of float-type scaling factors (factor for each ROI).
Returns:
None if there are not EDF-files to apply the ROIs to.
apply_rois_pw(roi_obj, scaling=None)[source]

Pixel-wise reading of the ROIs’ pixels into a list of arrays.

I.e. each n-pixel ROI will have n Spectra, saved in a 2D array.

Args: roi_obj (instance): Instance of the ‘XRStools.xrs_rois.roi_object’ class defining the ROIs. scaling (list) or (np.array): Array or list of float-type scaling factors (one factor for each ROI).

assign(edf_arrays, scan_number, energy_scale, monitor_signal, counters, motor_positions, specfile_data, scan_type='generic')[source]

Method to group together existing data from a scan (for backward compatibility).

Args:
edf_arrays (np.array): Array of all 2D images that belong to the scan. scan_number (int): Number under which this scan can be found in the SPEC file. energy_scale (np.array): Array of the energy axis. monitor_signal (np.array): Array of the monitor signal. counters (dictionary): Counters with assiciated data from the SPEC file. motor_positions (list): Motor positions as found in the SPEC file header. specfile_data (np.array): Matrix with all data as found in the SPEC file. scantype (str): Keyword, used later to group scans (add similar scans, etc.).
get_numofrois()[source]

Returns the number of ROIs applied to the scan.

get_scan_number()[source]

Returns the number of the scan.

get_shape()[source]

Returns the shape of the matrix holding the signals.

get_type()[source]

Returns the type of the scan.

load(path, SPECfname, EDFprefix, EDFname, EDFpostfix, scan_number, direct=False, roi_obj=None, scaling=None, scan_type='generic', en_column=None, moni_column='izero')[source]

Parse SPEC-file and EDF-files for loading a scan.

Note:
If ‘direct’ is ‘True’ all EDF-files will be deleted after application of the ROIs.
Args:
path (str): Absolute path to directory in which the SPEC-file is located. SPECfname (str): SPEC-file name. EDFprefix (str): Prefix for the EDF-files. EDFpostfix (str): Postfix for the EDF-files. scan_number (int): Scan number of the scan to be loaded. direct (boolean): If ‘True’, all EDF-files will be deleted after loading the scan.
load_hdf5(fname)[source]

Load a scan from an HDF5 file.

Args:
fname (str): Filename of the HDF5 file.
save_hdf5(fname)[source]

Save a scan in an HDF5 file.

Note:
HDF5 files are strange for overwriting files. DOES NOT SAVE COUNTERS or MOTORS YET... NEED A DEEPER H5!
Args:
fname (str): Path and filename for the HDF5 file.
XRStools.xrs_scans.append2Scan_left(group1, group2, inds=None, grouptype='spectrum')[source]

append two instancees of the scangroup class, return instance of scangroup append group1[inds] to the left (lower energies) of group2 if inds is not None, only append rows indicated by inds to the first group

XRStools.xrs_scans.append2Scan_right(group1, group2, inds=None, grouptype='spectrum')[source]

append two instancees of the scangroup class, return instance of scangroup append group2[inds] to the right (higher energies) of group1 if inds is not None, only append rows indicated by inds to the first group

XRStools.xrs_scans.appendScans(groups, include_elastic)[source]

try including different background scans... append groups of scans ordered by their first energy value. long scans are inserted into gaps that at greater than two times the grid of the finer scans

XRStools.xrs_scans.appendXESScans(groups)[source]

try including different background scans... append groups of scans ordered by their first energy value. long scans are inserted into gaps that at greater than two times the grid of the finer scans

XRStools.xrs_scans.catScans(groups, include_elastic)[source]

concatenate all scans in groups, return the appended energy, signals, and errors

XRStools.xrs_scans.catScansLong(groups, include_elastic)[source]

takes a longscan and inserts other backgroundscans (scans that have ‘long’ in their name) and other scans and inserts them into the long scan.

XRStools.xrs_scans.catXESScans(groups)[source]

Concatenate all scans in groups, return the appended energy, signals, and errors. This needs to be a bit smarter to also work for scans that are scanned from small to large energy...

XRStools.xrs_scans.create_diff_image(scans, scannumbers, energy_keV)[source]

Returns a summed image from all scans with numbers ‘scannumbers’. scans = dictionary of objects from the scan-class scannumbers = single scannumber, or list of scannumbers from which an image should be constructed

XRStools.xrs_scans.create_sum_image(scans, scannumbers)[source]

Returns a summed image from all scans with numbers ‘scannumbers’. scans = dictionary of objects from the scan-class scannumbers = single scannumber, or list of scannumbers from which an image should be constructed

XRStools.xrs_scans.findRCscans(scans)[source]

findRCscans Returns a list of scans with name RC.

XRStools.xrs_scans.findgroups(scans)[source]

this groups together instances of the scan class based on their “scantype” attribute and returns ordered scans

XRStools.xrs_scans.insertScan(group1, group2, grouptype='spectrum')[source]

inserts group2 into group1 NOTE! there is a numpy insert function, maybe it would be better to use that one!

XRStools.xrs_scans.makegroup(groupofscans, grouptype=None)[source]

takes a group of scans, sums up the signals and monitors, estimates poisson errors, and returns an instance of the scangroup class (turns several instances of the “scan” class into an instance of the “scangroup” class)

XRStools.xrs_scans.makegroup_nointerp(groupofscans, grouptype=None, absCounts=False, time_counter='seconds')[source]

takes a group of scans, sums up the signals and monitors, estimates poisson errors, and returns an instance of the scangroup class (turns several instances of the “scan” class into an instance of the “scangroup” class), same as makegroup but withouth interpolation to account for encoder differences... may need to add some “linspace” function in case the energy scale is not monotoneous...

class XRStools.xrs_scans.offDiaDataSet[source]

Bases: object

offDiaDataSet Class to hold information from an off-diagonal dataset.

alignRCmonitor()[source]
alignRCmonitorCC(repeat=2)[source]

alignRCmonitorCC Use cross-correlation to align data matrix according to the Rockin-Curve monitor.

deglitchSignalMatrix(startpoint, stoppoint, threshold)[source]
filterDetErrors(threshold=3000000)[source]
interpolateMatrix(master_matrix, master_energy, master_RCmotor)[source]
normalizeSignals()[source]
removeConstBack(fitrange1, fitrange2)[source]
removeElastic(fitrange=[-6.0, 2.0])[source]
removeElastic2(fitrange1, fitrange2, guess=None)[source]

removeElastic2 Subtract Pearson7 plus linear.

removeLinearBack(fitrange1, fitrange2)[source]
removePearsonBack(fitrange1, fitrange2)[source]
replaceSignalByConstant(fitrange)[source]
windowSignalMatrix(estart, estop)[source]
class XRStools.xrs_scans.scan(edf_arrays, scannumber, energy_scale, monitor_signal, counters, motor_positions, specfile_data, scantype='generic')[source]

Bases: object

Container class, holding information of single scans performed with 2D detectors.

applyrois(indices, scaling=None)[source]

Sums up intensities found in the ROIs of each detector image and stores it into the self.signals attribute. roi_object = instance of the ‘rois’ class redining the ROIs scaling = numpy array of numerical scaling factors (has to be one for each ROIs)

applyrois_pw(indices, scaling=None)[source]

Pixel-wise reading of the ROI’s pixels into a list of arrays. I.e. each n-pixel ROI will have n Spectra, saved in a 2D array. Parameters ———- indices : list

List of indices (attribute of the xrs_rois class).
scaling : list of flaots, optional
Python list of scaling factors (one per ROI defined) to be applied to all pixels of that ROI.
get_eloss_pw()[source]

Finds the center of mass for each pixel in each ROI, sets the energy loss scale in and interpolates the signals to a common energy loss scale. Finds the resolution (FWHM) for each pixel.

get_numofrois()[source]
get_scannumber()[source]
get_shape()[source]
get_type()[source]
class XRStools.xrs_scans.scangroup(energy, signals, errors, grouptype='generic')[source]

Bases: object

Container class holding information from a group of scans.

get_eend()[source]
get_estart()[source]
get_maxediff()[source]
get_meanegridspacing()[source]
get_meanenergy()[source]
get_type()[source]

XRStools.xrs_ComptonProfiles Module

class XRStools.xrs_ComptonProfiles.AtomProfile(element, filename, stoichiometry=1.0)[source]

AtomProfile

Class to construct and handle Hartree-Fock atomic Compton Profile of a single atoms.

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.

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.

E0 : float
Analyzer energy, enery of the scattered r-rays.
twotheta : float or list of floats
Scattering angle 2Th.
correctasym : float, optional
Scaling factor to be multiplied to the asymmetry.
valence_cutoff : float, optional
Energy cut off as to what is considered the boundary between core and valence.
get_stoichiometry()[source]
class XRStools.xrs_ComptonProfiles.ComptonProfiles(element)[source]

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...

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]

FormulaProfile

Class to construct and handle Hartree-Fock atomic Compton Profile of a single chemical compound.

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.
get_correctecProfiles(densities, alpha, beta, samthick)[source]
get_elossProfiles(E0, twotheta, correctasym=None, valence_cutoff=20.0)[source]
get_stoichWeight()[source]
class XRStools.xrs_ComptonProfiles.HFProfile(formulas, stoich_weights, filename)[source]

HFProfile

Class to construct and handle Hartree-Fock atomic Compton Profile of sample composed of several chemical compounds.

get_elossProfiles(E0, twotheta, correctasym=None, valence_cutoff=20.0)[source]
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 ...).

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.].

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.

element (string): element symbol (e.g. ‘Si’, ‘Al’, etc.) filename (string): absolute path and filename to tabulated profiles
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]

Class to build a S(q,w) prediction based on HF Compton Profiles.

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]).

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

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.getAtomicDensity(Z)[source]

Returns the atomic density.

XRStools.xrs_ComptonProfiles.getAtomicWeight(Z)[source]

Returns the atomic weight.

XRStools.xrs_ComptonProfiles.list_duplicates(seq)[source]
XRStools.xrs_ComptonProfiles.mapShellNames(shell_str, atomicNumber)[source]

mapShellNames

Translates to and from spectroscopic edge notation and the convention of the Biggs database.

shell_str : string
Spectroscopic symbol to be converted to Biggs database convention.
atomicNumber : int
Z for the atom in question.
XRStools.xrs_ComptonProfiles.parseChemFormula(ChemFormula)[source]
XRStools.xrs_ComptonProfiles.trapz_weights(x)[source]

XRStools.xrs_fileIO Module

XRStools.xrs_fileIO.EdfRead(fname)[source]
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.PyMcaEdfRead(fname)[source]

Returns the EDF-data using PyMCA.

XRStools.xrs_fileIO.PyMcaSpecRead(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.ReadScanFromFile(fname)[source]

Returns a scan stored in a Numpy archive.

XRStools.xrs_fileIO.SpecRead(filename, nscan)[source]

Parses a SPEC file and returns a specified scan.

filename (string): SPEC file name (inlc. path) nscan (int): Number of the desired scan.

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_abs_cross_section()[source]
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)

plot_abs_cross_section()[source]
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='/mntdirect/_scisoft/users/mirone/WORKS/Christoph/XRStoolsSuperResolution/XRStools')[source]

Bases: object

Class to describe things related to the analyzer crystal used. Default values are for a Si(660) crystal.

get_bend_r()[source]
get_diced()[source]
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_energy_resolution()[source]
get_energy_resolution_eV()[source]
get_hkl()[source]
get_mask_d()[source]
get_material()[source]
analyzer.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)

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]

get_solid_angle()[source]
get_thickness()[source]
plot_reflectivity(mode='energy')[source]

Generates and opens a plot of the calculated reflectivity curve. mode = keyword for which x-axis is to be used, can be ‘energy’ or ‘angle’

set_bend_r(bend_r)[source]
set_diced(diced)[source]
set_hkl(hkl)[source]
set_mask_d(mask_d)[source]
set_material(material)[source]
set_thickness(thickness)[source]
class XRStools.xrs_prediction.beam(i0_intensity, beam_height, beam_width, divergence=None)[source]

Bases: object

Class to describe incident beam related things.

get_beam_cross_section_area()[source]

Calculates the beam cross section area.

get_beam_height()[source]
get_beam_height_cm()[source]
get_beam_width()[source]
get_beam_width_cm()[source]
get_divergence()[source]
get_i0_intensity()[source]
XRStools.xrs_prediction.cla()[source]
compton_profiles(sample_obj, eloss_range=array([ 0.00000000e+00, 1.00000000e-01, 2.00000000e-01, ...,
9.99700000e+02, 9.99800000e+02, 9.99900000e+02]), E0=9.68)

Bases: object

Class to hold construct HF Compton profiles for an object of the sample class.

compton_profiles.calc_HF_profiles()[source]
compton_profiles.calc_pure_HF_profiles()[source]
compton_profiles.get_E0()[source]
compton_profiles.get_HF_profiles()[source]
compton_profiles.get_energy_in_keV()[source]
compton_profiles.get_tth()[source]
compton_profiles.plot_HF_profile()[source]
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.

get_efficiency(energy=None)[source]

calculates the detector efficiency at the given energy (simply given by the absorption of the detector active material).

get_energy()[source]
get_material()[source]
get_size()[source]
get_thickness()[source]
set_energy(energy)[source]
set_material(material)[source]
set_size(size)[source]
set_thickness(thickness)[source]
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]’)

XRStools.xrs_prediction.main()[source]
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_alpha()[source]
get_average_densities()[source]
get_beta()[source]
get_concentrations()[source]
get_densities()[source]
get_energy1()[source]
get_energy2()[source]
get_formulas()[source]
get_molar_masses()[source]
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)

get_shape()[source]
get_thickness()[source]
get_tth()[source]
sample.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]))
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 !!!

class XRStools.xrs_prediction.thomson(omega_1, omega_2, tth, scattering_plane='vertical', polarization=0.99)[source]

Bases: object

Class to take care of the Thomson scattering cross section.

get_thomson_factor()[source]

Calculates the Thomson scattering factor.

XRStools.xrs_rois Module

XRStools.xrs_rois.break_down_det_image(image, pixel_num)[source]

Desomposes a Detector image into subimages. Returns a 3D matrix.

class XRStools.xrs_rois.container[source]

Random container class to hold values

XRStools.xrs_rois.convert_inds_to_matrix(ind_rois, image_shape)[source]

Converts a ROI defined by a list of lists of tuples into a ROI that is defined by an array containing zeros, ones, twos, ..., n’s, where n is the number of ROIs. ind_rois = list of lists with pairs of pixel indices image_shape = touple defining the shape of the matrix for which the ROIs are valid

XRStools.xrs_rois.convert_inds_to_xinds(roi_inds)[source]

Converts ROIs defined in lists of lists of x-y-coordinate tuples into a list of x-coordinates only.

XRStools.xrs_rois.convert_inds_to_yinds(roi_inds)[source]

Converts ROIs defined in lists of lists of x-y-coordinate tuples into a list of y-coordinates only.

XRStools.xrs_rois.convert_matrix_rois_to_inds(roi_matrix)[source]

Converts a 2D ROI matrix with zeros, ones, twos, ..., n’s (where n is the number of ROIs) to a list of lists each of which has tuples with coordinates for each pixel in each roi.

XRStools.xrs_rois.convert_matrix_to_redmatrix(matrix_rois, labelformat='ROI%02d')[source]

Converts a ROI defined by an array containing zeros, ones, twos, ..., n’s, where n is the number of ROIs, into a dictionary with keys ‘ROI00’, ‘ROI01’, ..., ‘ROInn’. Each entry of the dictionary is a list containing a tuple with the origin and the reduced ROI. matrix_roi = numpy array

XRStools.xrs_rois.convert_redmatrix_to_matrix(masksDict, mask, offsetX=0, offsetY=0)[source]
XRStools.xrs_rois.convert_redmatrix_to_matrix_my(masksDict, mask, offsetX=0, offsetY=0)[source]
XRStools.xrs_rois.convert_roi_matrix_to_masks(roi_matrix)[source]

Converts a 2D ROI matrix with zeros, ones, twos, ..., n’s (where n is the number of ROIs) to a 3D matrix with one slice of zeros and ones per ROI.

XRStools.xrs_rois.get_geo_informations(shape)[source]
XRStools.xrs_rois.load_rois_fromh5(h5group_tot, md)[source]
XRStools.xrs_rois.merge_roi_objects_by_matrix(list_of_roi_objects, large_image_shape, offsets, pixel_num)[source]

Merges several roi_objects into one big one using the roi_matrices.

class XRStools.xrs_rois.roi_object[source]

Container class to hold all relevant information about given ROIs.

append(roi_object)[source]
get_bounding_boxes()[source]
get_copy()[source]

get_copy Returns a deep copy of self.

get_indices()[source]
get_masks()[source]
get_number_of_rois()[source]
get_x_indices()[source]
get_y_indices()[source]
loadH5(fname)[source]

loadH5 Loads ROIs from an HDF5 file written by the self.writeH5() method.

fname (str) : Full path and filename for the HDF5 file to be read.

load_rois_fromMasksDict(masksDict, newshape=None, kind='zoom')[source]
shift_rois(shiftVal, direction='horiz', whichroi=None)[source]

shift_rois Displaces the defined ROIs by the provided value.

shiftVal : int
Value by which the ROIs should be shifted.
direction : string
Description of which direction to shit by.
whichroi : sequence
Sequence (iterable) for which ROIs should be shifted.
show_rois(colormap='jet', interpolation='nearest')[source]

show_rois Creates a figure with the defined ROIs as numbered boxes on it.

writeH5(fname)[source]

writeH5 Creates an HDF5 file and writes the ROIs into it.

fname (str) : Full path and filename for the HDF5 file to be created.

XRStools.xrs_rois.shift_roi_indices(indices, shift)[source]

Applies a given shift (xshift,yshift) to given indices. indices = list of (x,y)-tuples shift = (xshift,yshift) tuple

XRStools.xrs_rois.swap_indices_old_rois(old_indices)[source]

Swappes x- and y-indices from indices ROIs.

XRStools.xrs_rois.write_rois_toh5(h5group, md, filterMask=None)[source]

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 ...).

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.].

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, W, H, W_up, H_up)[source]

NNMFcost Returns cost and gradient for NNMF with constraints.

TTsolver1D(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_')

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.

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.

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).

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.
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).

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].

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, 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 %

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.cixsUBfind(x, G, Q_sample, wi, wo, lambdai, lambdao)[source]

cixsUBfind

XRStools.xrs_utilities.cixsUBgetAngles_primo(Q)[source]
XRStools.xrs_utilities.cixsUBgetAngles_secondo(Q)[source]
XRStools.xrs_utilities.cixsUBgetAngles_terzo(Q)[source]
XRStools.xrs_utilities.cixsUBgetQ_primo(tthv, tthh, psi)[source]
XRStools.xrs_utilities.cixsUBgetQ_secondo(tthv, tthh, psi)[source]
XRStools.xrs_utilities.cixsUBgetQ_terzo(tthv, tthh, psi)[source]
XRStools.xrs_utilities.cixs_primo(tthv, tthh, psi, anal_braggd=86.5)[source]

cixs_primo

XRStools.xrs_utilities.cixs_secondo(tthv, tthh, psi, anal_braggd=86.5)[source]

cixs_secondo

XRStools.xrs_utilities.cixs_terzo(tthv, tthh, psi, anal_braggd=86.5)[source]

cixs_terzo

XRStools.xrs_utilities.compute_matrix_elements(R1, R2, k, r)[source]
XRStools.xrs_utilities.con2mat(x, W, H, W_up, H_up)[source]
XRStools.xrs_utilities.constrained_mf(A, W_ini, W_up, coeff_ini, coeff_up, maxIter=1000, tol=1e-08)[source]

cfactorizeOffDiaMatrix constrained version of factorizeOffDiaMatrix Returns main components from an off-diagonal Matrix (energy-loss x angular-departure).

XRStools.xrs_utilities.constrained_nnmf(A, W_ini, H_ini, W_up, H_up, max_iter=10000, verbose=False)[source]

constrained_nnmf Approximate non-negative matrix factorization with constrains.

function [W H]=johannes_nnmf_ALS(A,W_ini,H_ini,W_up,H_up) % ************************************************************* % ************************************************************* % ** [W H]=johannes_nnmf(A,W_ini,H_ini,W_up,H_up) ** % ** performs A=WH approximate matrix factorization, ** % ** where A(n*m), W(n*k), and H(k*m) are non-negative matrices, ** % ** and k<min(n,m). Masking arrays W_up(n*k), H_up(k*m) = 0,1 ** % ** control elements of W and H to be updated (1) or not (0). ** % ** This fact can be used to set constraints. ** % ** ** % ** Johannes Niskanen 13.10.2015 ** % ** ** % ************************************************************* % ************************************************************* by Johannes Niskanen

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.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.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.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 %

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).

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.

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.).

rs (float): electron separation parameter

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.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.gauss(x, x0, fwhm)[source]
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.

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.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.).

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='/mntdirect/_scisoft/users/mirone/WORKS/Christoph/XRStoolsSuperResolution/XRStools/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='/mntdirect/_scisoft/users/mirone/WORKS/Christoph/XRStoolsSuperResolution/XRStools/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='/mntdirect/_scisoft/users/mirone/WORKS/Christoph/XRStoolsSuperResolution/XRStools/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='/mntdirect/_scisoft/users/mirone/WORKS/Christoph/XRStoolsSuperResolution/XRStools/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

XRStools.xrs_utilities.mat2con(W, H, W_up, H_up)[source]
class XRStools.xrs_utilities.maxipix_det(name, spot_arrangement)[source]

Class to store some useful values from the detectors used. To be used for arranging the ROIs.

get_det_name()[source]
get_pixel_range()[source]
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.

energy (np.array): energy scale in [keV]. compound (string): chemical sum formula (e.g. ‘SiO2’)

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.

energy (np.array): energy scale in [keV]. formulas (list of strings): list of chemical sum formulas

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='/mntdirect/_scisoft/users/mirone/WORKS/Christoph/XRStoolsSuperResolution/XRStools/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.

energy (np.array): energy scale in [keV]. Z (string or int): atomic number or string of element symbol.

murho (np.array): absorption coefficient normalized by the density. rho (float): density in UNITS? m (float): atomic mass in UNITS?

XRStools.xrs_utilities.nonzeroavg(y=None)[source]
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.odefctn_CN(yCN, t, abb0, abb1, abb7, abb8N, lex, sgbeta, y0, c1)[source]
XRStools.xrs_utilities.parseformula(formula)[source]

Parses a chemical sum formula.

Parses the constituing elements and stoichiometries from a given chemical sum formula.

formula (string): string of a chemical formula (e.g. ‘SiO2’, ‘Ba8Si46’, etc.)

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).

w2 (float): scattered photon energy in [keV] pz (np.array): pz scale in [a.u.] th (float): scattering angle two theta in [deg]

w1 (np.array): incident energy in [keV]

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.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.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.svd_my(M, maxiter=100, eta=0.1)[source]
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)

% 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.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.

v1 (np.array): first vector. v2 (np.array): second vector.

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.

v (np.array): vector to be rotated vaxis (np.array): rotation axis phi (float): angle [deg] respecting the right-hand rule

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.