xrayutilities.simpack package

Submodules

xrayutilities.simpack.darwin_theory module

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

Bases: LayerModel, ABC

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__(qz, qx=0, qy=0, **kwargs)[source]

constructor of the model class. The arguments consist of basic parameters which are needed to prepare the calculation of the model.

Parameters:
qzarray-like

momentum transfer values for the calculation

qx, qyfloat, optional

inplane momentum transfer (not implemented!)

I0float, optional

the primary beam intensity

backgroundfloat, optional

the background added to the simulation

resolution_widthfloat, optional

width of the resolution function (deg)

polarization{‘S’, ‘P’, ‘both’}

polarization of the x-ray beam. If set to ‘both’ also Cmono, the polarization factor of the monochromator should be set

experimentExperiment, optional

experiment class containing geometry and energy of the experiment.

Cmonofloat, optional

polarization factor of the monochromator

energyfloat or str, optional

x-ray energy in eV

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

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

Bases: DarwinModel, 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.

asub = None
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: 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

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

Bases: 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

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: Model

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.

__init__(lmodel, verbose=False, plot=False, elog=True, **kwargs)[source]

initialization of a FitModel which uses lmfit for the actual fitting, and generates an according lmfit.Model internally for the given pre-configured LayerModel, or subclasses thereof which includes models for reflectivity, kinematic and dynamic diffraction.

Parameters:
lmodelLayerModel

pre-configured instance of LayerModel or any subclass

verbosebool, optional

flag to enable verbose printing during fitting

plotbool or str, 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.

elogbool, optional

flag to enable a logarithmic error metric between model and data. Since the dynamic range of data is often large its often benefitial to keep this enabled.

kwargsdict, optional

additional keyword arguments are forwarded to the simulate method of lmodel

fit(data, params, x, weights=None, fit_kws=None, lmfit_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

lmfit_kwsdict, optional

keyword arguments which are passed to lmfit.Model.fit

kwargsdict, optional

keyword arguments passed to lmfit.Model.eval

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

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

calculate coplanar exit angle from knowledge of the qx (inplane) and qz (out of plane) 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.

nan_Lauebool, optional

set output points inside the Laue zone to ‘nan’. default: False

Returns:
alphafarray-like

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

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

calculate coplanar incidence angle from knowledge of the qx (inplane) and qz (out of plane) 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.

nan_Lauebool, optional

set output points inside the Laue zone to ‘nan’. default: False

Returns:
alphaiarray-like

the incidence angle in degree

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. The output is nan in case the inplane momentum transfer can not be reached.

xrayutilities.simpack.models module

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

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

__init__(*args, **kwargs)[source]

constructor for a reflectivity model. The arguments consist of a LayerStack or individual Layer(s). Optional parameters are specified in the keyword arguments.

Parameters:
argsLayerStack or Layers

either one LayerStack or several Layer objects can be given

kwargsdict

optional parameters for the simulation; supported are:

I0float, optional

the primary beam intensity

backgroundfloat, optional

the background added to the simulation

sample_widthfloat, optional

width of the sample along the beam

beam_widthfloat, optional

beam width in the same units as the sample width

resolution_widthfloat, optional

defines the width of the resolution (deg)

energyfloat, optional

sets the experimental energy (eV)

Hfloat, optional

Hurst factor defining the fractal dimension of the roughness (0..1, very slow for H != 1 or H != 0.5), default: 1

vert_correlfloat, optional

vertical correlation length in angstrom, 0 means full replication

vert_nufloat, optional

exponent in the vertical correlation function

methodint, optional

1..simple DWBA (default), 2..full DWBA (slower)

vert_intint, optional

0..no integration over the vertical divergence, 1..with integration over the vertical divergence

qL_zerofloat, optional

value of inplane q-coordinate which can be considered 0, using method 2 it is important to avoid exact 0 and this value will be used instead

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: 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: 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”

__init__(*args, **kwargs)[source]

constructor for a reflectivity model. The arguments consist of a LayerStack or individual Layer(s). Optional parameters are specified in the keyword arguments.

Parameters:
argsLayerStack or Layers

either one LayerStack or several Layer objects can be given

kwargs: dict

optional parameters for the simulation; supported are:

I0float, optional

the primary beam intensity

backgroundfloat, optional

the background added to the simulation

sample_widthfloat, optional

width of the sample along the beam

beam_widthfloat, optional

beam width in the same units as the sample width

resolution_widthfloat, optional

width of the resolution (deg)

energyfloat or str

x-ray energy in eV

polarization: [‘P’, ‘S’]

x-ray polarization

scanEnergy(energies, angle)[source]

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

Parameters:
energies: numpy.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: 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__(*args, **kwargs)[source]

constructor for a kinematic thin film model. The arguments consist of a LayerStack or individual Layer(s). Optional parameters are specified in the keyword arguments.

Parameters:
*argsLayerStack or Layers

either one LayerStack or several Layer objects can be given

**kwargsdict

optional parameters; also see LayerModel/Model.

experimentExperiment

Experiment class containing geometry and energy of the experiment.

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

__init__(*args, **kwargs)[source]

constructor for a kinematic thin film model. The arguments consist of a LayerStack or individual Layer(s). Optional parameters are specified in the keyword arguments.

Parameters:
*argsLayerStack or Layers

either one LayerStack or several Layer objects can be given

**kwargsdict

optional parameters. see also LayerModel/Model.

experimentExperiment

Experiment class containing geometry and energy of the experiment.

surface_hkllist or tuple

Miller indices of the surface (default: (0, 0, 1))

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: Model, ABC

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

__init__(*args, **kwargs)[source]

constructor for a thin film model. The arguments consist of a LayerStack or individual Layer(s). Optional parameters are specified in the keyword arguments.

Parameters:
*argsLayerStack or Layers

either one LayerStack or several Layer objects can be given

**kwargsdict

optional parameters for the simulation. ones not listed below are forwarded to the superclass.

experimentExperiment, optional

class containing geometry and energy of the experiment.

polarization: {‘S’, ‘P’, ‘both’}, optional

polarization of the x-ray beam. If set to ‘both’ also Cmono, the polarization factor of the monochromator should be set

Cmonofloat, optional

polarization factor of the monochromator

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

__init__(experiment, **kwargs)[source]

constructor for a generical simulation model. currently only the experiment class describing the diffraction geometry is stored in the base class

Parameters:
experimentExperiment

class describing the diffraction geometry, energy and wavelength of the model

resolution_widthfloat, optional

defines the width of the resolution

I0float, optional

the primary beam flux/intensity

backgroundfloat, optional

the background added to the simulation

energyfloat or str

the experimental energy in eV

resolution_type{‘Gauss’, ‘Lorentz’}, optional

type of resolution function, default: Gauss

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: SpecularReflectivityModel

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

__init__(*args, **kwargs)[source]

constructor for a reflectivity model. The arguments consist of a LayerStack or individual Layer(s). Optional parameters are specified in the keyword arguments.

Parameters:
argsLayerStack or Layers

either one LayerStack or several Layer objects can be given

kwargs: dict

optional parameters for the simulation; supported are:

I0float, optional

the primary beam intensity

backgroundfloat, optional

the background added to the simulation

sample_widthfloat, optional

width of the sample along the beam

beam_widthfloat, optional

beam width in the same units as the sample width

resolution_widthfloat, optional

width of the resolution (deg)

energyfloat or str

x-ray energy in eV

polarization: [‘P’, ‘S’]

x-ray polarization

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

__init__(*args, **kwargs)[source]

constructor for a diffraction model. The arguments consist of a LayerStack or individual Layer(s). Optional parameters are specified in the keyword arguments.

Parameters:
*argsLayerStack or Layers

either one LayerStack or several Layer objects can be given

**kwargs: dict

optional parameters for the simulation

I0float, optional

the primary beam intensity

backgroundfloat, optional

the background added to the simulation

resolution_widthfloat, optional

the width of the resolution (deg)

polarization: {‘S’, ‘P’, ‘both’}

polarization of the x-ray beam. If set to ‘both’ also Cmono, the polarization factor of the monochromator should be set

Cmonofloat, optional

polarization factor of the monochromator

energyfloat or str

the experimental energy in eV

experimentExperiment

Experiment class containing geometry of the sample; surface orientation!

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: LayerModel

model for specular reflectivity calculations

__init__(*args, **kwargs)[source]

constructor for a reflectivity model. The arguments consist of a LayerStack or individual Layer(s). Optional parameters are specified in the keyword arguments.

Parameters:
argsLayerStack or Layers

either one LayerStack or several Layer objects can be given

kwargs: dict

optional parameters for the simulation; supported are:

I0float, optional

the primary beam intensity

backgroundfloat, optional

the background added to the simulation

sample_widthfloat, optional

width of the sample along the beam

beam_widthfloat, optional

beam width in the same units as the sample width

beam_shapestr, optional

beam_shape can be either ‘hat’ (default) or ‘gaussian’. beam_width will be accordingly interpreted as width of the hat function or sigma of the Gaussian function.

offsetfloat, optional

angular offset of the incidence angle (deg)

resolution_widthfloat, optional

width of the resolution (deg)

energyfloat or str

x-ray energy in eV

densityprofile(nz, plot=False, individual_layers=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

individual_layersbool, optional

return the density contributions of all layers as additional return value.

Returns:
zarray-like

z-coordinates, z = 0 corresponds to the surface

eprofarray-like

electron profile

layereprof2D array, optional

electron profile of every sublayer with shape (nlayer, nz). This is only returned when individual_layers=True

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.effectiveDensitySlicing(layerstack, step, roughness=0, cutoff=1e-05)[source]

Function to slice a LayerStack into many amorphous sublayers for effective density modelling of X-ray reflectivity of thin and rough multilayers. The resulting LayerStack will consist of perfectly smooth layers with average density/composition resulting from an error-function like transition between the rough layers of the initial stack. At the surface an vacuum layer is automatically added to the initial stack.

Parameters:
layerstackinitial LayerStack, can contain only Amorhous layers!
stepthickness (in angstrom) of the slices in the returned

LayerStack

roughnessroughness of the created sublayers (in angstrom)
cutofflayers with relative weights below this value will be ignored
Returns:
LayerStack
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

shapefloat

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.

__init__(anglemode, gaussian_smoother_bins_sigma=1.0, oversampling=10)[source]

initialize the instance

Parameters:
anglemode{‘d’, ‘twotheta’}

if setup will be in terms of a d-spacing, otherwise ‘twotheta’ if setup will be at a fixed 2theta value.

gaussian_smoother_bins_sigmafloat

the number of bins for post-smoothing of data. 1.0 is good. None means no final smoothing step.

oversamplingint

the number of bins internally which will get computed for each bin the the final result.

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: 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 uses 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
__init__(mat, **kwargs)[source]

the class is initialized with a xrayutilities.materials.Crystal instance and calculates the powder intensity and peak positions of the Crystal up to an angle of tt_cutoff. Results are stored in

data …. array with intensities ang ….. Bragg angles of the peaks (Theta!) qpos …. reciprocal space position of intensities

If enable_simulation is set to True the Convolve and Calculate methods can be used to calculated a powder pattern. Upon such initialization it is strongly recommend to call the close method to clean up the multiprocessing threads when no further calculations will be performed.

Parameters:
matCrystal or Powder

material for the powder calculation

kwargsdict

optional keyword arguments same as for the Experiment base class and:

tt_cutofffloat, optional

Powder peaks are calculated up to an scattering angle of tt_cutoff (deg)

enable_simulation: False, optional

enables the initialization of the convolvers. Call close() after you are finished with your instance!

fpclassFP_profile

FP_profile derived class with possible convolver mixins. (default: FP_profile)

fpsettingsdict

settings dictionaries for the convolvers. Default settings are loaded from the config file.

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 is 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 reflection_strength method

Returns:
hkl, q, ang, rarray-like

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

reflection_strength(tt_cutoff)[source]

determine structure factors/reflection strength of all Bragg peaks up to tt_cutoff. This function also implements the March-Dollase model for preferred orientation in the symmetric reflection mode. Note that although this means the sample has anisotropic properties the various lines can still be merged together since at the moment no anisotropic crystal shape is supported.

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

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

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=None)[source]

update settings of all instances of FP_profile

Parameters:
newsettingsdict, optional

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

__init__()[source]
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, *, shutdown_timeout=1.0)[source]

Bases: 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

__init__(**kwargs)[source]

initialize the class

Parameters:
kwargsdict

keyword=value list to pre-populate the class

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.

__init__(*args, **kwargs)[source]

constructor for a powder model. The arguments consist of a PowderList or individual Powder(s). Optional parameters are specified in the keyword arguments.

Parameters:
argsPowderList or Powders

either one PowderList or several Powder objects can be given

kwargsdict

optional parameters for the simulation. supported are:

fpclassFP_profile, optional

derived class with possible convolver mixins. (default: FP_profile)

fpsettingsdict

settings dictionaries for the convolvers. Default settings are loaded from the config file.

I0float, optional

scaling factor for the simulation result

Notes

  • After the end-of-use it is advisable to call the close() method to cleanup the multiprocessing calculation!

  • In particular interesting keys in the fpsettings dictionary are listed in the following. Note that this a short excerpt of the full functionality:

    • ‘displacement’-dictionary with keys:

      • ‘specimen_displacement’: sample’s z-displacement from the

        rotation center

      • ‘zero_error_deg’: zero error of the 2theta angle

    • ‘absorption’-dictionary with keys:

      • ‘sample_thickness’: sample thickness (m),

      • ‘absorption_coefficient’: sample’s absorption (m^-1)

    • ‘axial’-dictionary with keys:

      • ‘length_sample’: sample length in the axial direction (m)

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
plot(twotheta, showlines=True, label='simulation', color=None, formatspec='-', lcolors=None, ax=None, **kwargs)[source]

plot the powder diffraction pattern and indicate line positions for all components in the model.

Parameters:
twothetaarray-like

positions at which the powder pattern should be evaluated

showlinesbool, optional

flag to decide if peak positions of the components will be shown on the top of the plot

labelstr

line label in the plot

colormatplotlib color or None

the color used for the line plot of the simulation

formatspecstr

format specifier of the simulation curve

lcolorslist of matplotlib colors

colors for the line indicators for the various components

axmatplotlib.axes or None

axes object to be used for plotting, if its given no axes decoration like labels are set.

Further keyword arguments are passed to the simulate method.
Returns:
matplotlib.axes object or None if matplotlib is not available
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='simulation', 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 or PowderModel

simulated data or PowderModel instance. If a PowderModel instance is given the plot-method of PowderModel is used.

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

labelexpstr

plot label (legend entry) for the experimental data

labelsimstr

plot label for the simulation data

formatexpstr

format specifier for the experimental data

formatsimstr

format specifier for the simulation curve

Returns:
List of lines in the plot. Empty list in case matplotlib can’t be imported

xrayutilities.simpack.smaterials module

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

Bases: 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: CrystalStack

generates a sequence of layers with a gradient in chemical composition

__init__(alloy, xfrom, xto, nsteps, thickness, **kwargs)[source]

constructor for a graded buffer of the material ‘alloy’ with chemical composition from ‘xfrom’ to ‘xto’ with ‘nsteps’ number of sublayers. The total thickness of the graded buffer is ‘thickness’

Parameters:
alloyfunction

Alloy function which allows to create a material with chemical composition ‘x’ by alloy(x)

xfrom, xtofloat

chemical composition from the bottom to top

nstepsint

number of sublayers in the graded buffer

thicknessfloat

total thickness of the graded stack

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

Bases: 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

__init__(material, thickness, **kwargs)[source]

constructor for the material saving its properties

Parameters:
materialMaterial (Crystal or Amorhous)

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

thicknessfloat

film thickness in angstrom

kwargsdict

optional keyword arguments with further layer properties.

roughnessfloat, optional

root mean square roughness of the top interface in angstrom

densityfloat, optional

density of the material in kg/m^3; If not specified the density of the material will be used.

relaxationfloat, optional

the degree of relaxation in case of crystalline thin films

lat_correlfloat, optional

the lateral correlation length for diffuse reflectivity calculations

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

Bases: 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: MutableSequence

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

__init__(name, *args)[source]
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: 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)

preferred_orientationtuple, optional

HKL of the preferred orientation

preferred_orientation_factorfloat, optional

March-Dollase preferred orientation factor: < 1 for platy crystallits , > 1 for rod-like crystallites, and = 1 for random orientation of crystallites.

__init__(material, volume, **kwargs)[source]

constructor for the material saving its properties

Parameters:
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)

kwargsdict

optional keyword arguments with further powder properties.

crystallite_size_lorfloat, optional

Lorentzian crystallite size fwhm (m)

crystallite_size_gaussfloat, optional

Gaussian crystallite size fwhm (m)

strain_lor, strain_gaussfloat, optional

extra peak width proportional to tan(theta); typically interpreted as microstrain broadening

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

Bases: 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: 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]

Make the i-th sublayer pseudomorphic to the layer below.

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

Bases: 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, name=None, **kwargs)[source]

Bases: object

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

__init__(material, name=None, **kwargs)[source]

initialize a simulation material by specifiying its Material and optional other properties

Parameters:
materialMaterial (Crystal, or Amorphous)

Material object containing optical/crystal properties of for the simulation; a deepcopy is used internally.

namestr, optional

name of the material used in the simulations

kwargsdict

optional properties of the material needed for the simulation

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.