xrayutilities.simpack package

Submodules

xrayutilities.simpack.darwin_theory module

class xrayutilities.simpack.darwin_theory.DarwinModel(qz, qx=0, qy=0, **kwargs)[source]

Bases: xrayutilities.simpack.models.LayerModel

model class inmplementing the basics of the Darwin theory for layers materials. This class is not fully functional and should be used to derive working models for particular material systems.

To make the class functional the user needs to implement the init_structurefactors() and _calc_mono() methods

init_structurefactors()[source]

calculates the needed atomic structure factors

ncalls = 0
simulate(ml)[source]

main simulation function for the Darwin model. will calculate the reflected intensity

Parameters
mliterable

monolayer sequence of the sample. This should be created with the function make_monolayer(). see its documentation for details

class xrayutilities.simpack.darwin_theory.DarwinModelAlGaAs001(qz, qx=0, qy=0, **kwargs)[source]

Bases: xrayutilities.simpack.darwin_theory.DarwinModelAlloy

Darwin theory of diffraction for Al_x Ga_{1-x} As layers. The model is based on separation of the sample structure into building blocks of atomic planes from which a multibeam dynamical model is calculated.

AlAs = <xrayutilities.materials.material.Crystal object>
GaAs = <xrayutilities.materials.material.Crystal object>
aGaAs = 5.65325
classmethod abulk(x)[source]

calculate the bulk (relaxed) lattice parameter of the Al_{x}Ga_{1-x}As alloy

asub = 5.65325
eAl = Al (13)
eAs = As (33)
eGa = Ga (31)
classmethod get_dperp_apar(x, apar, r=1)[source]

calculate inplane lattice parameter and the out of plane lattice plane spacing (of the atomic planes!) from composition and relaxation

Parameters
xfloat

chemical composition parameter

aparfloat

inplane lattice parameter of the material below the current layer (onto which the present layer is strained to). This value also served as a reference for the relaxation parameter.

rfloat

relaxation parameter. 1=relaxed, 0=pseudomorphic

Returns
dperpfloat

perpendicular d-spacing

aparfloat

inplane lattice parameter

init_structurefactors(temp=300)[source]

calculates the needed atomic structure factors

Parameters
tempfloat, optional

temperature used for the Debye model

static poisson_ratio(x)[source]

calculate the Poisson ratio of the alloy

re = 2.8179403262e-05
class xrayutilities.simpack.darwin_theory.DarwinModelAlloy(qz, qx=0, qy=0, **kwargs)[source]

Bases: xrayutilities.simpack.darwin_theory.DarwinModel, abc.ABC

extension of the DarwinModel for an binary alloy system were one parameter is used to determine the chemical composition

To make the class functional the user needs to implement the get_dperp_apar() method and define the substrate lattice parameter (asub). See the DarwinModelSiGe001 class for an implementation example.

abstract get_dperp_apar(x, apar, r=1)[source]

calculate inplane lattice parameter and the out of plane lattice plane spacing (of the atomic planes!) from composition and relaxation.

Parameters
xfloat

chemical composition parameter

aparfloat

inplane lattice parameter of the material below the current layer (onto which the present layer is strained to). This value also served as a reference for the relaxation parameter.

rfloat

relaxation parameter. 1=relaxed, 0=pseudomorphic

Returns
dperpfloat
aparfloat
make_monolayers(s)[source]

create monolayer sequence from layer list

Parameters
slist

layer model. list of layer dictionaries including possibility to form superlattices. As an example 5 repetitions of a Si(10nm)/Ge(15nm) superlattice on Si would like like:

>>> s = [(5, [{'t': 100, 'x': 0, 'r': 0},
>>>           {'t': 150, 'x': 1, 'r': 0}]),
>>>      {'t': 3500000, 'x': 0, 'r': 0}]

the dictionaries must contain ‘t’: thickness in A, ‘x’: chemical composition, and either ‘r’: relaxation or ‘ai’: inplane lattice parameter. Future implementations for asymmetric peaks might include layer type ‘l’ (not yet implemented). Already now any additional property in the dictionary will be handed on to the returned monolayer list.

asubfloat

inplane lattice parameter of the substrate

Returns
list

monolayer list in a format understood by the simulate and xGe_profile methods

prop_profile(ml, prop)[source]

calculate the profile of chemical composition or inplane lattice spacing from a monolayer list. One value for each monolayer in the sample is returned.

Parameters
mllist

monolayer list created by make_monolayer()

propstr

name of the property which should be evaluated. Use ‘x’ for the chemical composition and ‘ai’ for the inplane lattice parameter.

Returns
zmndarray

z-position, z-0 is the surface

propxndarray

value of the property prop for every monolayer

class xrayutilities.simpack.darwin_theory.DarwinModelGaInAs001(qz, qx=0, qy=0, **kwargs)[source]

Bases: xrayutilities.simpack.darwin_theory.DarwinModelAlloy

Darwin theory of diffraction for Ga_{1-x} In_x As layers. The model is based on separation of the sample structure into building blocks of atomic planes from which a multibeam dynamical model is calculated.

GaAs = <xrayutilities.materials.material.Crystal object>
InAs = <xrayutilities.materials.material.Crystal object>
aGaAs = 5.65325
classmethod abulk(x)[source]

calculate the bulk (relaxed) lattice parameter of the Ga_{1-x}In_{x}As alloy

asub = 5.65325
eAs = As (33)
eGa = Ga (31)
eIn = In (49)
classmethod get_dperp_apar(x, apar, r=1)[source]

calculate inplane lattice parameter and the out of plane lattice plane spacing (of the atomic planes!) from composition and relaxation

Parameters
xfloat

chemical composition parameter

aparfloat

inplane lattice parameter of the material below the current layer (onto which the present layer is strained to). This value also served as a reference for the relaxation parameter.

rfloat

relaxation parameter. 1=relaxed, 0=pseudomorphic

Returns
dperpfloat

perpendicular d-spacing

aparfloat

inplane lattice parameter

init_structurefactors(temp=300)[source]

calculates the needed atomic structure factors

Parameters
tempfloat, optional

temperature used for the Debye model

static poisson_ratio(x)[source]

calculate the Poisson ratio of the alloy

re = 2.8179403262e-05
class xrayutilities.simpack.darwin_theory.DarwinModelSiGe001(qz, qx=0, qy=0, **kwargs)[source]

Bases: xrayutilities.simpack.darwin_theory.DarwinModelAlloy

model class implementing the Darwin theory of diffraction for SiGe layers. The model is based on separation of the sample structure into building blocks of atomic planes from which a multibeam dynamical model is calculated.

Ge = <xrayutilities.materials.material.Crystal object>
Si = <xrayutilities.materials.material.Crystal object>
aSi = 5.43104
classmethod abulk(x)[source]

calculate the bulk (relaxed) lattice parameter of the alloy

asub = 5.43104
eGe = Ge (32)
eSi = Si (14)
classmethod get_dperp_apar(x, apar, r=1)[source]

calculate inplane lattice parameter and the out of plane lattice plane spacing (of the atomic planes!) from composition and relaxation

Parameters
xfloat

chemical composition parameter

aparfloat

inplane lattice parameter of the material below the current layer (onto which the present layer is strained to). This value also served as a reference for the relaxation parameter.

rfloat, optional

relaxation parameter. 1=relaxed, 0=pseudomorphic

Returns
dperpfloat

perpendicular d-spacing

aparfloat

inplane lattice parameter

init_structurefactors(temp=300)[source]

calculates the needed atomic structure factors

Parameters
tempfloat, optional

temperature used for the Debye model

static poisson_ratio(x)[source]

calculate the Poisson ratio of the alloy

re = 2.8179403262e-05
xrayutilities.simpack.darwin_theory.GradedBuffer(xfrom, xto, nsteps, thickness, relaxation=1)[source]

create a multistep graded composition buffer.

Parameters
xfromfloat

begin of the composition gradient

xtofloat

end of the composition gradient

nstepsint

number of steps of the gradient

thicknessfloat

total thickness of the Buffer in A

relaxationfloat

relaxation of the buffer

Returns
list

layer list needed for the Darwin model simulation

xrayutilities.simpack.darwin_theory.getfirst(iterable, key)[source]

helper function to obtain the first item in a nested iterable

xrayutilities.simpack.darwin_theory.getit(it, key)[source]

generator to obtain items from nested iterable

xrayutilities.simpack.fit module

class xrayutilities.simpack.fit.FitModel(lmodel, verbose=False, plot=False, elog=True, **kwargs)[source]

Bases: object

Wrapper for the lmfit Model class working for instances of LayerModel

Typically this means that after initialization of FitModel you want to use make_params to get a lmfit.Parameters list which one customizes for fitting.

Later on you can call fit and eval methods with those parameter list.

fit(data, params, x, weights=None, fit_kws=None, **kwargs)[source]

wrapper around lmfit.Model.fit which enables plotting during the fitting

Parameters
datandarray

experimental values

paramslmfit.Parameters

list of parameters for the fit, use make_params for generation

xndarray

independent variable (incidence angle or q-position depending on the model)

weightsndarray, optional

values of weights for the fit, same size as data

fit_kwsdict, optional

Options to pass to the minimizer being used

kwargsdict, optional

keyword arguments which are passed to lmfit.Model.fit

Returns
lmfit.ModelResult
set_fit_limits(xmin=- inf, xmax=inf, mask=None)[source]

set fit limits. If mask is given it must have the same size as the data and x variables given to fit. If mask is None it will be generated from xmin and xmax.

Parameters
xminfloat, optional

minimum value of x-values to include in the fit

xmaxfloat, optional

maximum value of x-values to include in the fit

maskboolean array, optional

mask to be used for the data given to the fit

xrayutilities.simpack.fit.fit_xrr(reflmod, params, ai, data=None, eps=None, xmin=- inf, xmax=inf, plot=False, verbose=False, elog=True, maxfev=500)[source]

optimize function for a Reflectivity Model using lmfit. The fitting parameters must be specified as instance of lmfits Parameters class.

Parameters
reflmodSpecularReflectivityModel

preconfigured model used for the fitting

paramslmfit.Parameters

instance of lmfits Parameters class. For every layer the parameters ‘{}_thickness’, ‘{}_roughness’, ‘{}_density’, with ‘{}’ representing the layer name are supported. In addition the setup parameters:

  • ‘I0’ primary beam intensity

  • ‘background’ background added to the simulation

  • ‘sample_width’ size of the sample along the beam

  • ‘beam_width’ width of the beam in the same units

  • ‘resolution_width’ width of the resolution function in deg

  • ‘shift’ experimental shift of the incidence angle array

aiarray-like

array of incidence angles for the calculation

dataarray-like

experimental data which should be fitted

epsarray-like, optional

error bar of the data

xminfloat, optional

minimum value of ai which should be used. a mask is generated to cut away other data

xmaxfloat, optional

maximum value of ai which should be used. a mask is generated to cut away other data

plotbool, optional

flag to decide wheter an plot should be created showing the fit’s progress. If plot is a string it will be used as figure name, which makes reusing the figures easier.

verbosebool, optional

flag to tell if the variation of the fitting error should be output during the fit.

elogbool, optional

logarithmic error during the fit

maxfevint, optional

maximum number of function evaluations during the leastsq optimization

Returns
reslmfit.MinimizerResult

object from lmfit, which contains the fitted parameters in res.params (see res.params.pretty_print) or try lmfit.report_fit(res)

xrayutilities.simpack.helpers module

xrayutilities.simpack.helpers.coplanar_alphai(qx, qz, en='config')[source]

calculate coplanar incidence angle from knowledge of the qx and qz coordinates

Parameters
qxarray-like

inplane momentum transfer component

qzarray-like

out of plane momentum transfer component

enfloat or str, optional

x-ray energy (eV). By default the value from the config is used.

Returns
alphaiarray-like

the incidence angle in degree. points in the Laue zone are set to ‘nan’.

xrayutilities.simpack.helpers.get_qz(qx, alphai, en='config')[source]

calculate the qz position from the qx position and the incidence angle for a coplanar diffraction geometry

Parameters
qxarray-like

inplane momentum transfer component

alphaiarray-like

incidence angle (deg)

enfloat or str, optional

x-ray energy (eV). By default the value from the config is used.

Returns
array-like

the qz position for the given incidence angle

xrayutilities.simpack.models module

class xrayutilities.simpack.models.DiffuseReflectivityModel(*args, **kwargs)[source]

Bases: xrayutilities.simpack.models.SpecularReflectivityModel

model for diffuse reflectivity calculations

The ‘simulate’ method calculates the diffuse reflectivity on the specular rod in coplanar geometry in analogy to the SpecularReflectivityModel.

The ‘simulate_map’ method calculates the diffuse reflectivity for a 2D set of Q-positions. This method can also calculate the intensity for other geometries, like GISAXS with constant incidence angle or a quasi omega/2theta scan in GISAXS geometry.

simulate(alphai)[source]

performs the actual diffuse reflectivity calculation for the specified incidence angles. This method always uses the coplanar geometry independent of the one set during the initialization.

Parameters
alphaiarray-like

vector of incidence angles

Returns
array-like

vector of intensities of the reflectivity signal

simulate_map(qL, qz)[source]

performs diffuse reflectivity calculation for the rectangular grid of reciprocal space positions define by qL and qz. This method uses the method and geometry set during the initialization of the class.

Parameters
qLarray-like

lateral coordinate in reciprocal space (vector with NqL components)

qzarray-like

vertical coordinate in reciprocal space (vector with Nqz components)

Returns
array-like

matrix of intensities of the reflectivity signal, with shape (len(qL), len(qz))

class xrayutilities.simpack.models.DynamicalModel(*args, **kwargs)[source]

Bases: xrayutilities.simpack.models.SimpleDynamicalCoplanarModel

Dynamical diffraction model for specular and off-specular qz-scans. Calculation of the flux of reflected and diffracted waves for general asymmetric coplanar diffraction from an arbitrary pseudomorphic multilayer is performed by a generalized 2-beam theory (4 tiepoints, S and P polarizations)

The first layer in the model is always assumed to be the semiinfinite substrate indepentent of its given thickness

simulate(alphai, hkl=None, geometry='hi_lo', rettype='intensity')[source]

performs the actual diffraction calculation for the specified incidence angles and uses an analytic solution for the quartic dispersion equation

Parameters
alphaiarray-like

vector of incidence angles (deg)

hkllist or tuple, optional

Miller indices of the diffraction vector (preferable use set_hkl method to speed up repeated calculations of the same peak!)

geometry{‘hi_lo’, ‘lo_hi’}, optional

‘hi_lo’ for grazing exit (default) and ‘lo_hi’ for grazing incidence

rettype{‘intensity’, ‘field’, ‘all’}, optional

type of the return value. ‘intensity’ (default): returns the diffracted beam flux convoluted with the resolution function; ‘field’: returns the electric field (complex) without convolution with the resolution function, ‘all’: returns the electric field, ai, af (both in degree), and the reflected intensity.

Returns
array-like

vector of intensities of the diffracted signal, possibly changed return value due the rettype setting!

class xrayutilities.simpack.models.DynamicalReflectivityModel(*args, **kwargs)[source]

Bases: xrayutilities.simpack.models.SpecularReflectivityModel

model for Dynamical Specular Reflectivity Simulations. It uses the transfer Matrix methods as given in chapter 3 “Daillant, J., & Gibaud, A. (2008). X-ray and Neutron Reflectivity”

scanEnergy(energies, angle)[source]

Simulates the Dynamical Reflectivity as a function of photon energy at fixed angle.

Parameters
energies: np.ndarray or list

photon energies (in eV).

anglefloat

fixed incidence angle

Returns
reflectivity: array-like

vector of intensities of the reflectivity signal

transmitivity: array-like

vector of intensities of the transmitted signal

simulate(alphai)[source]

Simulates the Dynamical Reflectivity as a function of angle of incidence

Parameters
alphaiarray-like

vector of incidence angles

Returns
reflectivity: array-like

vector of intensities of the reflectivity signal

transmitivity: array-like

vector of intensities of the transmitted signal

class xrayutilities.simpack.models.KinematicalModel(*args, **kwargs)[source]

Bases: xrayutilities.simpack.models.LayerModel

Kinematical diffraction model for specular and off-specular qz-scans. The model calculates the kinematical contribution of one (hkl) Bragg peak, however considers the variation of the structure factor for different ‘q’. The surface geometry is specified using the Experiment-object given to the constructor.

init_chi0()[source]

calculates the needed optical parameters for the simulation. If any of the materials/layers is changing its properties this function needs to be called again before another correct simulation is made. (Changes of thickness does NOT require this!)

simulate(qz, hkl, absorption=False, refraction=False, rettype='intensity')[source]

performs the actual kinematical diffraction calculation on the Qz positions specified considering the contribution from a single Bragg peak.

Parameters
qzarray-like

simulation positions along qz

hkllist or tuple

Miller indices of the Bragg peak whos truncation rod should be calculated

absorptionbool, optional

flag to tell if absorption correction should be used

refractionbool, optional

flag to tell if basic refraction correction should be performed. If refraction is True absorption correction is also included independent of the absorption flag.

rettype{‘intensity’, ‘field’, ‘all’}

type of the return value. ‘intensity’ (default): returns the diffracted beam flux convoluted with the resolution function; ‘field’: returns the electric field (complex) without convolution with the resolution function, ‘all’: returns the electric field, ai, af (both in degree), and the reflected intensity.

Returns
array-like

return value depends on the setting of rettype, by default only the calculate intensity is returned

class xrayutilities.simpack.models.KinematicalMultiBeamModel(*args, **kwargs)[source]

Bases: xrayutilities.simpack.models.KinematicalModel

Kinematical diffraction model for specular and off-specular qz-scans. The model calculates the kinematical contribution of several Bragg peaks on the truncation rod and considers the variation of the structure factor. In order to use a analytical description for the kinematic diffraction signal all layer thicknesses are changed to a multiple of the respective lattice parameter along qz. Therefore this description only works for (001) surfaces.

simulate(qz, hkl, absorption=False, refraction=True, rettype='intensity')[source]

performs the actual kinematical diffraction calculation on the Qz positions specified considering the contribution from a full truncation rod

Parameters
qzarray-like

simulation positions along qz

hkllist or tuple

Miller indices of the Bragg peak whos truncation rod should be calculated

absorptionbool, optional

flag to tell if absorption correction should be used

refractionbool, optional,

flag to tell if basic refraction correction should be performed. If refraction is True absorption correction is also included independent of the absorption flag.

rettype{‘intensity’, ‘field’, ‘all’}

type of the return value. ‘intensity’ (default): returns the diffracted beam flux convoluted with the resolution function; ‘field’: returns the electric field (complex) without convolution with the resolution function, ‘all’: returns the electric field, ai, af (both in degree), and the reflected intensity.

Returns
array-like

return value depends on the setting of rettype, by default only the calculate intensity is returned

class xrayutilities.simpack.models.LayerModel(*args, **kwargs)[source]

Bases: xrayutilities.simpack.models.Model, abc.ABC

generic model class from which further thin film models can be derived from

get_polarizations()[source]

return list of polarizations which should be calculated

join_polarizations(Is, Ip)[source]

method to calculate the total diffracted intensity from the intensities of S and P-polarization.

abstract simulate()[source]

abstract method that every implementation of a LayerModel has to override.

class xrayutilities.simpack.models.Model(experiment, **kwargs)[source]

Bases: object

generic model class from which further models can be derived from

convolute_resolution(x, y)[source]

convolve simulation result with a resolution function

Parameters
xarray-like

x-values of the simulation, units of x also decide about the unit of the resolution_width parameter

yarray-like

y-values of the simulation

Returns
array-like

convoluted y-data with same shape as y

property energy
scale_simulation(y)[source]

scale simulation result with primary beam flux/intensity and add a background.

Parameters
yarray-like

y-values of the simulation

Returns
array-like

scaled y-values

class xrayutilities.simpack.models.ResonantReflectivityModel(*args, **kwargs)[source]

Bases: xrayutilities.simpack.models.SpecularReflectivityModel

model for specular reflectivity calculations CURRENTLY UNDER DEVELOPEMENT! DO NOT USE!

simulate(alphai)[source]

performs the actual reflectivity calculation for the specified incidence angles

Parameters
alphaiarray-like

vector of incidence angles

Returns
array-like

vector of intensities of the reflectivity signal

class xrayutilities.simpack.models.SimpleDynamicalCoplanarModel(*args, **kwargs)[source]

Bases: xrayutilities.simpack.models.KinematicalModel

Dynamical diffraction model for specular and off-specular qz-scans. Calculation of the flux of reflected and diffracted waves for general asymmetric coplanar diffraction from an arbitrary pseudomorphic multilayer is performed by a simplified 2-beam theory (2 tiepoints, S and P polarizations)

No restrictions are made for the surface orientation.

The first layer in the model is always assumed to be the semiinfinite substrate indepentent of its given thickness

Note

This model should not be used in real life scenarios since the made approximations severely fail for distances far from the reference position.

set_hkl(*hkl)[source]

To speed up future calculations of the same Bragg peak optical parameters can be pre-calculated using this function.

Parameters
hkllist or tuple

Miller indices of the Bragg peak for the calculation

simulate(alphai, hkl=None, geometry='hi_lo', idxref=1)[source]

performs the actual diffraction calculation for the specified incidence angles.

Parameters
alphaiarray-like

vector of incidence angles (deg)

hkllist or tuple, optional

Miller indices of the diffraction vector (preferable use set_hkl method to speed up repeated calculations of the same peak!)

geometry{‘hi_lo’, ‘lo_hi’}, optional

‘hi_lo’ for grazing exit (default) and ‘lo_hi’ for grazing incidence

idxrefint, optional

index of the reference layer. In order to get accurate peak position of the film peak you want this to be the index of the film peak (default: 1). For the substrate use 0.

Returns
array-like

vector of intensities of the diffracted signal

class xrayutilities.simpack.models.SpecularReflectivityModel(*args, **kwargs)[source]

Bases: xrayutilities.simpack.models.LayerModel

model for specular reflectivity calculations

densityprofile(nz, plot=False)[source]

calculates the electron density of the layerstack from the thickness and roughness of the individual layers

Parameters
nzint

number of values on which the profile should be calculated

plotbool, optional

flag to tell if a plot of the profile should be created

Returns
zarray-like

z-coordinates, z = 0 corresponds to the surface

eprofarray-like

electron profile

init_cd()[source]

calculates the needed optical parameters for the simulation. If any of the materials/layers is changing its properties this function needs to be called again before another correct simulation is made. (Changes of thickness and roughness do NOT require this!)

simulate(alphai)[source]

performs the actual reflectivity calculation for the specified incidence angles

Parameters
alphaiarray-like

vector of incidence angles

Returns
array-like

vector of intensities of the reflectivity signal

xrayutilities.simpack.models.startdelta(start, delta, num)[source]

xrayutilities.simpack.mosaicity module

xrayutilities.simpack.mosaicity.mosaic_analytic(qx, qz, RL, RV, Delta, hx, hz, shape)[source]

simulation of the coplanar reciprocal space map of a single mosaic layer using a simple analytic approximation

Parameters
qxarray-like

vector of the qx values (offset from the Bragg peak)

qzarray-like

vector of the qz values (offset from the Bragg peak)

RLfloat

lateral block radius in Angstrom

RVfloat

vertical block radius in Angstrom

Deltafloat

root mean square misorientation of the grains in degree

hxfloat

lateral component of the diffraction vector

hzfloat

vertical component of the diffraction vector

shape: float

shape factor (1..Gaussian)

Returns
array-like
2D array with calculated intensities

xrayutilities.simpack.powder module

This module contains the core definitions for the XRD Fundamental Parameneters Model (FPA) computation in Python. The main computational class is FP_profile, which stores cached information to allow it to efficiently recompute profiles when parameters have been modified. For the user an Powder class is available which can calculate a complete powder pattern of a crystalline material.

The diffractometer line profile functions are calculated by methods from Cheary & Coelho 1998 and Mullen & Cline paper and ‘R’ package. Accumulate all convolutions in Fourier space, for efficiency, except for axial divergence, which needs to be weighted in real space for I3 integral.

More details about the applied algorithms can be found in the paper by M. H. Mendelhall et al., Journal of Research of NIST 120, 223 (2015) to which you should also refer for a careful definition of all the parameters

class xrayutilities.simpack.powder.FP_profile(anglemode, gaussian_smoother_bins_sigma=1.0, oversampling=10)[source]

Bases: object

the main fundamental parameters class, which handles a single reflection. This class is designed to be highly extensible by inheriting new convolvers. When it is initialized, it scans its namespace for specially formatted names, which can come from mixin classes. If it finds a function name of the form conv_xxx, it will call this funtion to create a convolver. If it finds a name of the form info_xxx it will associate the dictionary with that convolver, which can be used in UI generation, for example. The class, as it stands, does nothing significant with it. If it finds str_xxx, it will use that function to format a printout of the current state of the convolver conv_xxx, to allow improved report generation for convolvers.

When it is asked to generate a profile, it calls all known convolvers. Each convolver returns the Fourier transform of its convolvution. The transforms are multiplied together, inverse transformed, and after fixing the periodicity issue, subsampled, smoothed and returned.

If a convolver returns None, it is not multipled into the product.

Parameters
max_history_lengthint

the number of histories to cache (default=5); can be overridden if memory is an issue.

length_scale_mfloat

length_scale_m sets scaling for nice printing of parameters. if the units are in mm everywhere, set it to 0.001, e.g. convolvers which implement their own str_xxx method may use this to format their results, especially if ‘natural’ units are not meters. Typical is wavelengths and lattices in nm or angstroms, for example.

add_buffer(b)[source]

add a numpy array to the list of objects that can be thrown away on pickling.

Parameters
barray-like

the buffer to add to the list

Returns
barray-like

return the same buffer, to make nesting easy.

axial_helper(outerbound, innerbound, epsvals, destination, peakpos=0, y0=0, k=0)[source]

the function F0 from the paper. compute k/sqrt(peakpos-x)+y0 nonzero between outer & inner (inner is closer to peak) or k/sqrt(x-peakpos)+y0 if reversed (i.e. if outer > peak) fully evaluated on a specified eps grid, and stuff into destination

Parameters
outerboundfloat

the edge of the function farthest from the singularity, referenced to epsvals

innerboundfloat

the edge closest to the singularity, referenced to epsvals

epsvalsarray-like

the array of two-theta values or offsets

destinationarray-like

an array into which final results are summed. modified in place!

peakposfloat

the position of the singularity, referenced to epsvals.

y0float

the constant offset

kfloat

the scale factor

Returns
lower_index, upper_indexint

python style bounds for region of destination which has been modified.

compute_line_profile(convolver_names=None, compute_derivative=False, return_convolver=False)[source]

execute all the convolutions; if convolver_names is None, use everything we have, otherwise, use named convolutions.

Parameters
convolver_names: list

a list of convolvers to select. If None, use all found convolvers.

compute_derivative: bool

if True, also return d/dx(function) for peak position fitting

Returns
object

a profile_data object with much information about the peak

conv_absorption()[source]

compute the sample transparency correction, including the finite-thickness version

Returns
array-like

the convolver

conv_axial()[source]

compute the Fourier transform of the axial divergence component

Returns
array-like

the transform buffer, or None if this is being ignored

conv_displacement()[source]

compute the peak shift due to sample displacement and the 2theta zero offset

Returns
array-like

the convolver

conv_emission()[source]

compute the emission spectrum and (for convenience) the particle size widths

Returns
array-like

the convolver for the emission and particle sizes

Note

the particle size and strain stuff here is just to be consistent with Topas and to be vaguely efficient about the computation, since all of these have the same general shape.

conv_flat_specimen()[source]

compute the convolver for the flat-specimen correction

Returns
array-like

the convolver

conv_global()[source]

a dummy convolver to hold global variables and information. the global context isn’t really a convolver, returning None means ignore result

Returns
None

always returns None

conv_receiver_slit()[source]

compute the rectangular convolution for the receiver slit or SiPSD pixel size

Returns
array-like

the convolver

conv_si_psd()[source]

compute the convolver for the integral of defocusing of the face of an Si PSD

Returns
array-like

the convolver

conv_smoother()[source]

compute the convolver to smooth the final result with a Gaussian before downsampling.

Returns
array-like

the convolver

conv_tube_tails()[source]

compute the Fourier transform of the rectangular tube tails function

Returns
array-like

the transform buffer, or None if this is being ignored

full_axdiv_I2(Lx=None, Ls=None, Lr=None, R=None, twotheta=None, beta=None, epsvals=None)[source]

return the I2 function

Parameters
Lxfloat

length of the xray filament

Lsfloat

length of the sample

Lrfloat

length of the receiver slit

Rfloat

diffractometer length, assumed symmetrical

twothetafloat

angle, in radians, of the center of the computation

betafloat

offset angle

epsvalsarray-like

array of offsets from center of computation, in radians

Returns
epsvalsarray-like

array of offsets from center of computation, in radians

idxmin, idxmaxint

the full python-style bounds of the non-zero region of I2p and I2m

I2p, I2marray-like

I2+ and I2- from the paper, the contributions to the intensity

full_axdiv_I3(Lx=None, Ls=None, Lr=None, R=None, twotheta=None, epsvals=None, sollerIdeg=None, sollerDdeg=None, nsteps=10, axDiv='')[source]

carry out the integral of I2 over beta and the Soller slits.

Parameters
Lxfloat

length of the xray filament

Lsfloat

length of the sample

Lrfloat

length of the receiver slit

Rfloat

the (assumed symmetrical) diffractometer radius

twothetafloat

angle, in radians, of the center of the computation

epsvalsarray-like

array of offsets from center of computation, in radians

sollerIdegfloat

the full-width (both sides) cutoff angle of the incident Soller slit

sollerDdegfloat

the full-width (both sides) cutoff angle of the detector Soller slit

nstepsint

the number of subdivisions for the integral

axDivstr

not used

Returns
array-like

the accumulated integral, a copy of a persistent buffer _axial

general_tophat(name='', width=None)[source]

a utility to compute a transformed tophat function and save it in a convolver buffer

Parameters
namestr

the name of the convolver cache buffer to update

widthfloat

the width in 2-theta space of the tophat

Returns
array-like

the updated convolver buffer, or None if the width was None

get_conv(name, key, format=<class 'float'>)[source]

get a cached, pre-computed convolver associated with the given parameters, or a newly zeroed convolver if the cache doesn’t contain it. Recycles old cache entries.

This takes advantage of the mutability of arrays. When the contents of the array are changed by the convolver, the cached copy is implicitly updated, so that the next time this is called with the same parameters, it will return the previous array.

Parameters
namestr

the name of the convolver to seek

keyobject

any hashable object which identifies the parameters for the computation

formatnumpy.dtype, optional

the type of the array to create, if one is not found.

Returns
bool

flag, which is True if valid data were found, or False if the returned array is zero, and array, which must be computed by the convolver if flag was False.

get_convolver_information()[source]

return a list of convolvers, and what we know about them. function scans for functions named conv_xxx, and associated info_xxx entries.

Returns
list

list of (convolver_xxx, info_xxx) pairs

get_function_name()[source]

return the name of the function that called this. Useful for convolvers to identify themselves

Returns
str

name of calling function

get_good_bin_count(count)[source]

find a bin count close to what we need, which works well for Fourier transforms.

Parameters
countint

a number of bins.

Returns
int

a bin count somewhat larger than count which is efficient for FFT

info_emission = {'group_name': 'Incident beam and crystal size', 'help': 'this should be help information', 'param_info': {'crystallite_size_gauss': ('Gaussian crystallite size fwhm (m)', 1e-06), 'crystallite_size_lor': ('Lorentzian crystallite size fwhm (m)', 1e-06), 'emiss_gauss_widths': ('Gaussian emissions fwhm (m)', (1e-13,)), 'emiss_intensities': ('relative intensities', (1.0,)), 'emiss_lor_widths': ('Lorenztian emission fwhm (m)', (1e-13,)), 'emiss_wavelengths': ('wavelengths (m)', (1.58e-10,))}}
info_global = {'group_name': 'Global parameters', 'help': 'this should be help information', 'param_info': {'d': ('d spacing (m)', 4e-10), 'dominant_wavelength': ('wavelength of most intense line (m)', 1.5e-10), 'twotheta0_deg': ('Bragg center of peak (degrees)', 30.0)}}
classmethod isequivalent(hkl1, hkl2, crystalsystem)[source]

function to determine if according to the convolvers included in this class two sets of Miller indices are equivalent. This function is only called when the class attribute ‘isotropic’ is False.

Parameters
hkl1, hkl2list or tuple

Miller indices to be checked for equivalence

crystalsystemstr

symmetry class of the material which is considered

Returns
bool
isotropic = True
length_scale_m = 1.0
max_history_length = 5
self_clean()[source]

do some cleanup to make us more compact; Instance can no longer be used after doing this, but can be pickled.

set_optimized_window(twotheta_window_center_deg, twotheta_approx_window_fullwidth_deg, twotheta_exact_bin_spacing_deg)[source]

pick a bin count which factors cleanly for FFT, and adjust the window width to preserve the exact center and bin spacing

Parameters
twotheta_window_center_degfloat

exact position of center bin, in degrees

twotheta_approx_window_fullwidth_deg: float

approximate desired width

twotheta_exact_bin_spacing_deg: float

the exact bin spacing to use

set_parameters(convolver='global', **kwargs)[source]

update the dictionary of parameters associated with the given convolver

Parameters
convolverstr

the name of the convolver. name ‘global’, e.g., attaches to function ‘conv_global’

kwargsdict

keyword-value pairs to update the convolvers dictionary.

set_window(twotheta_window_center_deg, twotheta_window_fullwidth_deg, twotheta_output_points)[source]

move the compute window to a new location and compute grids, without resetting all parameters. Clears convolution history and sets up many arrays.

Parameters
twotheta_window_center_degfloat

the center position of the middle bin of the window, in degrees

twotheta_window_fullwidth_degfloat

the full width of the window, in degrees

twotheta_output_pointsint

the number of bins in the final output

str_emission()[source]

format the emission spectrum and crystal size information

Returns
str

the formatted information

str_global()[source]

returns a string representation for the global context.

Returns
str

report on global parameters.

class xrayutilities.simpack.powder.PowderDiffraction(mat, **kwargs)[source]

Bases: xrayutilities.experiment.PowderExperiment

Experimental class for powder diffraction. This class calculates the structure factors of powder diffraction lines and uses instances of FP_profile to perform the convolution with experimental resolution function calculated by the fundamental parameters approach. This class used multiprocessing to speed up calculation. Set config.NTHREADS=1 to restrict this to one worker process.

Calculate(twotheta, **kwargs)[source]

calculate the powder diffraction pattern including convolution with the resolution function and map them onto the twotheta positions. This also performs the calculation of the peak intensities from the internal material object

Parameters
twothetaarray-like

two theta values at which the powder pattern should be calculated.

kwargsdict

additional keyword arguments are passed to the Convolve function

Returns
array-like

output intensity values for the twotheta values given in the input

Notes

Bragg peaks are only included up to tt_cutoff set in the class constructor!

Convolve(twotheta, window_width='config', mode='multi')[source]

convolute the powder lines with the resolution function and map them onto the twotheta positions. This calculates the powder pattern excluding any background contribution

Parameters
twothetaarray-like

two theta values at which the powder pattern should be calculated.

window_widthfloat, optional

width of the calculation window of a single peak

mode{‘multi, ‘local’}, optional

multiprocessing mode, either ‘multi’ to use multiple processes or ‘local’ to restrict the calculation to a single process

Note:

Bragg peaks are only included up to tt_cutoff set in the class constructor!

Returns
output intensity values for the twotheta values given in the input
close()[source]
correction_factor(ang)[source]

calculate the correction factor for the diffracted intensities. This contains the polarization effects and the Lorentz factor

Parameters
angaray-like

theta diffraction angles for which the correction should be calculated

Returns
farray-like

array of the same shape as ang containing the correction factors

property energy
init_powder_lines(tt_cutoff)[source]

calculates the powder intensity and positions up to an angle of tt_cutoff (deg) and stores the result in the data dictionary whose structure is as follows:

The data dictionary has one entry per line with a unique identifier as key of the entry. The entries themself are dictionaries which have the following entries:

  • hkl : (h, k, l), Miller indices of the Bragg peak

  • r : reflection strength of the line

  • ang : Bragg angle of the peak (theta = 2theta/2!)

  • qpos : reciprocal space position

load_settings_from_config(settings)[source]

load parameters from the config and update these settings with the options from the settings parameter

merge_lines(data)[source]

if calculation if isotropic lines at the same q-position can be merged to one line to reduce the calculational effort

Parameters
datandarray

numpy field array with values of ‘hkl’ (Miller indices of the peaks), ‘q’ (q-position), and ‘r’ (reflection strength) as produced by the structure_factors method

Returns
hkl, q, ang, rarray-like

Miller indices, q-position, diffraction angle (Theta), and reflection strength of the material

set_sample_parameters()[source]

load sample parameters from the Powder class and use them in all FP_profile instances of this object

set_wavelength_from_params()[source]

sets the wavelenth in the base class from the settings dictionary of the FP_profile classes and also set it in the ‘global’ part of the parameters

set_window(force=False)[source]

sets the calcultion window for all convolvers

structure_factors(tt_cutoff)[source]

determine structure factors/reflection strength of all Bragg peaks up to tt_cutoff

Parameters
tt_cutofffloat

upper cutoff value of 2theta until which the reflection strength are calculated

Returns
ndarray

numpy array with field for ‘hkl’ (Miller indices of the peaks), ‘q’ (q-position), and ‘r’ (reflection strength) of the Bragg peaks

property twotheta
update_powder_lines(tt_cutoff)[source]

calculates the powder intensity and positions up to an angle of tt_cutoff (deg) and updates the values in:

  • ids: list of unique identifiers of the powder line

  • data: array with intensities

  • ang: bragg angles of the peaks (theta=2theta/2!)

  • qpos: reciprocal space position of intensities

update_settings(newsettings={})[source]

update settings of all instances of FP_profile

Parameters
newsettingsdict

dictionary with new settings. It has to include one subdictionary for every convolver which should have its settings changed.

property wavelength
property window_width
xrayutilities.simpack.powder.chunkify(lst, n)[source]
class xrayutilities.simpack.powder.convolver_handler[source]

Bases: object

manage the convolvers of on process

add_convolver(convolver)[source]
calc(run, ttpeaks)[source]

calculate profile function for selected convolvers

Parameters
runlist

list of flags of length of convolvers to tell which convolver needs to be run

ttpeaksarray-like

peak positions for the convolvers

Returns
list

list of profile_data result objects

set_windows(centers, npoints, flag, width)[source]
update_parameters(parameters)[source]
class xrayutilities.simpack.powder.manager(address=None, authkey=None, serializer='pickle', ctx=None)[source]

Bases: multiprocessing.managers.BaseManager

class xrayutilities.simpack.powder.profile_data(**kwargs)[source]

Bases: object

a skeleton class which makes a combined dict and namespace interface for easy pickling and data passing

add_symbol(**kwargs)[source]

add new symbols to both the attributes and dictionary for the class

Parameters
kwargsdict

keyword=value pairs

xrayutilities.simpack.powdermodel module

class xrayutilities.simpack.powdermodel.PowderModel(*args, **kwargs)[source]

Bases: object

Class to help with powder calculations for multiple materials. For basic calculations the Powder class together with the Fundamental parameters approach is used.

close()[source]
create_fitparameters()[source]

function to create a fit model with all instrument and sample parameters.

Returns
lmfit.Parameters
fit(params, twotheta, data, std=None, maxfev=200)[source]

make least squares fit with parameters supplied by the user

Parameters
paramslmfit.Parameters

object with all parameters set as intended by the user

twothetaarray-like

angular values for the fit

dataarray-like

experimental intensities for the fit

stdarray-like

standard deviation of the experimental data. if ‘None’ the sqrt of the data will be used

maxfev: int

maximal number of simulations during the least squares refinement

Returns
lmfit.MinimizerResult
set_background(btype, **kwargs)[source]

define background as spline or polynomial function

Parameters
btype{polynomial’, ‘spline’}

background type; Depending on this value the expected keyword arguments differ.

kwargsdict

optional keyword arguments

xarray-like, optional

x-values (twotheta) of the background points (if btype=’spline’)

yarray-like, optional

intensity values of the background (if btype=’spline’)

parray-like, optional

polynomial coefficients from the highest degree to the constant term. len of p decides about the degree of the polynomial (if btype=’polynomial’)

set_lmfit_parameters(lmparams)[source]

function to update the settings of this class during an least squares fit

Parameters
lmparamslmfit.Parameters

lmfit Parameters list of sample and instrument parameters

set_parameters(params)[source]

set simulation parameters of all subobjects

Parameters
paramsdict

settings dictionaries for the convolvers.

simulate(twotheta, **kwargs)[source]

calculate the powder diffraction pattern of all materials and sum the results based on the relative volume of the materials.

Parameters
twothetaarray-like

positions at which the powder pattern should be evaluated

kwargsdict

optional keyword arguments

backgroundarray-like

an array of background values (same shape as twotheta) if no background is given then the background is calculated as previously set by the set_background function or is 0.

further keyword arguments are passed to the Convolve function of of the
PowderDiffraction objects
Returns
array-like

summed powder diffraction intensity of all materials present in the model

xrayutilities.simpack.powdermodel.Rietveld_error_metrics(exp, sim, weight=None, std=None, Nvar=0, disp=False)[source]

calculates common error metrics for Rietveld refinement.

Parameters
exparray-like

experimental datapoints

simarray-like

simulated data

weightarray-like, optional

weight factor in the least squares sum. If it is None the weight is estimated from the counting statistics of ‘exp’

stdarray-like, optional

standard deviation of the experimental data. alternative way of specifying the weight factor. when both are given weight overwrites std!

Nvarint, optional

number of variables in the refinement

dispbool, optional

flag to tell if a line with the calculated values should be printed.

Returns
M, Rp, Rwp, Rwpexp, chi2: float
xrayutilities.simpack.powdermodel.plot_powder(twotheta, exp, sim, mask=None, scale='sqrt', fig='XU:powder', show_diff=True, show_legend=True, labelexp='experiment', labelsim='simulate', formatexp='k-.', formatsim='r-')[source]

Convenience function to plot the comparison between experimental and simulated powder diffraction data

Parameters
twothetaarray-like

angle values used for the x-axis of the plot (deg)

exparray-like

experimental data (same shape as twotheta). If None only the simulation and no difference will be plotted

simarray-like

simulated data

maskarray-like, optional

mask to reduce the twotheta values to the be used as x-coordinates of sim

scale{‘linear’, ‘sqrt’, ‘log’}, optional

string specifying the scale of the y-axis.

figstr or int, optional

matplotlib figure name (figure will be cleared!)

show_diffbool, optional

flag to specify if a difference curve should be shown

show_legend: bool, optional

flag to specify if a legend should be shown

xrayutilities.simpack.smaterials module

class xrayutilities.simpack.smaterials.CrystalStack(name, *args)[source]

Bases: xrayutilities.simpack.smaterials.LayerStack

extends the built in list type to enable building a stack of crystalline Layers by various methods.

check(v)[source]
class xrayutilities.simpack.smaterials.GradedLayerStack(alloy, xfrom, xto, nsteps, thickness, **kwargs)[source]

Bases: xrayutilities.simpack.smaterials.CrystalStack

generates a sequence of layers with a gradient in chemical composition

class xrayutilities.simpack.smaterials.Layer(material, thickness, **kwargs)[source]

Bases: xrayutilities.simpack.smaterials.SMaterial

Object describing part of a thin film sample. The properties of a layer are :

Attributes
materialMaterial (Crystal or Amorhous)

an xrayutilties material describing optical and crystal properties of the thin film

thicknessfloat

film thickness in Angstrom

class xrayutilities.simpack.smaterials.LayerStack(name, *args)[source]

Bases: xrayutilities.simpack.smaterials.MaterialList

extends the built in list type to enable building a stack of Layer by various methods.

check(v)[source]
class xrayutilities.simpack.smaterials.MaterialList(name, *args)[source]

Bases: collections.abc.MutableSequence

class representing the basics of a list of materials for simulations within xrayutilities. It extends the built in list type.

check(v)[source]
insert(i, v)[source]

S.insert(index, value) – insert value before index

class xrayutilities.simpack.smaterials.Powder(material, volume, **kwargs)[source]

Bases: xrayutilities.simpack.smaterials.SMaterial

Object describing part of a powder sample. The properties of a powder are:

Attributes
materialCrystal

an xrayutilties material (Crystal) describing optical and crystal properties of the powder

volumefloat

powder’s volume (in pseudo units, since only the relative volume enters the calculation)

crystallite_size_lorfloat, optional

Lorentzian crystallite size fwhm (m)

crystallite_size_gaussfloat, optional

Gaussian crystallite size fwhm (m)

strain_lorfloat, optional

extra peak width proportional to tan(theta)

strain_gaussfloat, optional

extra peak width proportional to tan(theta)

class xrayutilities.simpack.smaterials.PowderList(name, *args)[source]

Bases: xrayutilities.simpack.smaterials.MaterialList

extends the built in list type to enable building a list of Powder by various methods.

check(v)[source]
class xrayutilities.simpack.smaterials.PseudomorphicStack001(name, *args)[source]

Bases: xrayutilities.simpack.smaterials.CrystalStack

generate a sequence of pseudomorphic crystalline Layers. Surface orientation is assumed to be 001 and materials must be cubic/tetragonal.

insert(i, v)[source]

S.insert(index, value) – insert value before index

make_epitaxial(i)[source]
trans = <xrayutilities.math.transforms.Transform object>
class xrayutilities.simpack.smaterials.PseudomorphicStack111(name, *args)[source]

Bases: xrayutilities.simpack.smaterials.PseudomorphicStack001

generate a sequence of pseudomorphic crystalline Layers. Surface orientation is assumed to be 111 and materials must be cubic.

trans = <xrayutilities.math.transforms.CoordinateTransform object>
class xrayutilities.simpack.smaterials.SMaterial(material, **kwargs)[source]

Bases: object

Simulation Material. Extends the xrayutilities Materials by properties needed for simulations

property material

Module contents

simulation subpackage of xrayutilities.

This package provides possibilities to simulate X-ray diffraction and reflectivity curves of thin film samples. It could be extended for more general use in future if there is demand for that.

In addition it provides a fitting routine for reflectivity data which is based on lmfit.