xrayutilities package

Subpackages

Submodules

xrayutilities.config module

module to parse xrayutilities user-specific config file the parsed values are provide as global constants for the use in other parts of xrayutilities. The config file with the default constants is found in the python installation path of xrayutilities. It is however not recommended to change things there, instead the user-specific config file ~/.xrayutilities.conf or the local xrayutilities.conf file should be used.

xrayutilities.config.trytomake(obj, key, typefunc)[source]

xrayutilities.exception module

xrayutilities derives its own exceptions which are raised upon wrong input when calling one of xrayutilities functions. none of the pre-defined exceptions is made for that purpose.

exception xrayutilities.exception.InputError[source]

Bases: Exception

Exception raised for errors in the input. Either wrong datatype not handled by TypeError or missing mandatory keyword argument (Note that the obligation to give keyword arguments might depend on the value of the arguments itself)

exception xrayutilities.exception.UsageError[source]

Bases: Exception

Exception raised when a wrong use of an object is detected.

xrayutilities.experiment module

module helping with planning and analyzing experiments. various classes are provided for describing experimental geometries, calculationof angular coordinates of Bragg reflections, conversion of angular coordinates to Q-space and determination of powder diffraction peak positions.

The strength of the module is the versatile QConversion module which can be configured to describe almost any goniometer geometry.

class xrayutilities.experiment.Experiment(ipdir, ndir, **keyargs)[source]

Bases: object

base class for describing experiments users should use the derived classes: HXRD, GID, PowderExperiment

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

angular to (h, k, l) space conversion. It will set the UB argument to Ang2Q and pass all other parameters unchanged. See Ang2Q for description of the rest of the arguments.

Parameters:
argslist

arguments forwarded to Ang2Q

kwargsdict, optional

optional keyword arguments

Barray-like, optional

reciprocal space conversion matrix of a Crystal. You can specify the matrix B (default identiy matrix) shape needs to be (3, 3)

matCrystal, optional

Crystal object to use to obtain a B matrix (e.g. xu.materials.Si) can be used as alternative to the B keyword argument B is favored in case both are given

Uarray-like, optional

orientation matrix U can be given. If none is given the orientation defined in the Experiment class is used.

dettype{‘point’, ‘linear’, ‘area’}, optional

detector type: decides which routine of Ang2Q to call. default ‘point’

deltandarray, list or tuple, optional

giving delta angles to correct the given ones for misalignment. delta must be an numpy array or list of length 2. used angles are than (om, tt) - delta

wlfloat or str, optional

x-ray wavelength in angstrom (default: self._wl)

enfloat or str, optional

x-ray energy in eV (default: converted self._wl)

degbool, optional

flag to tell if angles are passed as degree (default: True)

sampledistuple or list or array-like

sample displacement vector in relative units of the detector distance. Applies to parallel beam geometry. (default: (0, 0, 0))

Returns:
ndarray

H K L coordinates as numpy.ndarray with shape (N , 3) where N corresponds to the number of points given in the input (args)

Q2Ang(qvec)[source]
TiltAngle(q, deg=True)[source]

TiltAngle(q, deg=True): Return the angle between a q-space position and the surface normal.

Parameters:
qlist or numpy array with the reciprocal space position
optional keyword arguments:
degTrue/False whether the return value should be in degree or

radians (default: True)

Transform(v)[source]

transforms a vector, matrix or tensor of rank 4 (e.g. elasticity tensor) to the coordinate frame of the Experiment class. This is for example necessary before any Q2Ang-conversion can be performed.

Parameters:
vobject to transform, list or numpy array of shape

(n,) (n, n), (n, n, n, n) where n is the rank of the transformation matrix

Returns:
transformed object of the same shape as v
__init__(ipdir, ndir, **keyargs)[source]

initialization of an Experiment class needs the sample orientation given by the samples surface normal and an second not colinear direction specifying the inplane reference direction in the crystal coordinate system. The orientation of the surface normal in the lab coordinate system can also be given or is automatically determined by the goniometer type (see argument sampleor).

Parameters:
ipdirlist or tuple or array-like

inplane reference direction (ipdir points into the primary beam direction at zero angles)

ndirlist or tuple or array-like

surface normal of your sample. ndir points in a direction perpendicular to the primary beam, how it is orientated in real space is determined by the parameter sampleor (see below).

keyargsdict, optional

optional keyword arguments

qconvQConversion, optional

QConversion object to use for the Ang2Q conversion

sampleor{‘det’, ‘sam’, ‘[xyz][+-]’}, optional

determines the sample surface orientation with respect to the coordinate system in which the goniometer rotations are given. You can use the [xyz][+-] syntax to specify the nominal surface orientation (when all goniometer angles are zero). In addition two special values ‘det’ and ‘sam’ are available, which will let the code determine the orientation from either the inner most detector or sample rotation. ‘det’ means the surface is in the plane spanned by the inner most detector rotation (rotation around primary beam is ignored) and perpendicular to the primary beam. ‘sam’ means the surface orientation is along the innermost sample circles rotation direction (in this case this should be the azimuth motor to yield the expected results). Default is ‘det’. Restrictions: the given direction can not be along the primary beam. If one needs that case, let the maintainer know. Currently this case is caught and a different axis is automatically used as z-axis.

wlfloat or str

wavelength of the x-rays in angstrom (default: 1.5406A)

enfloat or str

energy of the x-rays in eV (default: 8048eV == 1.5406A ). the en keyword overrules the wl keyword

Note

The qconv argument does not change the Q2Ang function’s behavior. See Q2AngFit function in case you want to calculate for arbitrary goniometers with some restrictions.

property energy
property wavelength
class xrayutilities.experiment.FourC(idir, ndir, **keyargs)[source]

Bases: HXRD

class describing high angle x-ray diffraction experiments the class helps with calculating the angles of Bragg reflections as well as helps with analyzing measured data

the class describes a four circle (omega, chi, phi, twotheta) goniometer to help with coplanar x-ray diffraction experiments. Nevertheless 3D data can be treated with the use of linear and area detectors. see “help(FourCInstance.Ang2Q)”

__init__(idir, ndir, **keyargs)[source]

initialization routine for the FourC Experiment class

Parameters:
idir, ndir, keyargs

same as for the Experiment base class -> please look at the docstring of Experiment.__init__ for more details

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

determines the scattering geometry :

  • ‘hi_lo’ (default) high incidence-low exit

  • ‘lo_hi’ low incidence - high exit

  • ‘real’ general geometry - q-coordinates determine high or low incidence

class xrayutilities.experiment.GID(idir, ndir, **keyargs)[source]

Bases: Experiment

class describing grazing incidence x-ray diffraction experiments the class helps with calculating the angles of Bragg reflections as well as it helps with analyzing measured data

the class describes a four circle (alpha_i, azimuth, twotheta, beta) goniometer to help with GID experiments at the ROTATING ANODE. 3D data can be treated with the use of linear and area detectors. see “help(GIDInstance.Ang2Q)”

Using this class the default sample surface orientation is determined by the inner most sample rotation (which is usually the azimuth motor).

Ang2Q(ai, phi, tt, beta, **kwargs)[source]

angular to momentum space conversion for a point detector. Also see help GID.Ang2Q for procedures which treat line and area detectors

Parameters:
ai, phi, tt, betafloat or array-like

sample and detector angles as numpy array, lists or Scalars must be given. All arguments must have the same shape or length. However, if one angle is always the same its enough to give one scalar value.

kwargsdict, optional

optional keyword arguments

deltalist, tuple or array-like, optional

giving delta angles to correct the given ones for misalignment delta must be an numpy array or list of length 4. Used angles are then ai, phi, tt, beta - delta

UBarray-like, optional

matrix for conversion from (hkl) coordinates to Q of sample used to determine not Q but (hkl) (default: identity matrix)

wlfloat or str, optional

x-ray wavelength in angstrom (default: self._wl)

degbool, optional

flag to tell if angles are passed as degree (default: True)

Returns:
ndarray

reciprocal space positions as numpy.ndarray with shape (N , 3) where N corresponds to the number of points given in the input

Q2Ang(qvec, trans=True, deg=True, **kwargs)[source]

calculate the GID angles needed in the experiment the inplane reference direction defines the direction were the reference direction is parallel to the primary beam (i.e. lattice planes perpendicular to the beam)

Note

The behavior of this function is unchanged if the goniometer definition is changed!

Parameters:
qveclist, tuple or array-like

array of shape (3) with q-space vector components or 3 separate lists with qx, qy, qz

transbool, optional

apply coordinate transformation on Q (default True)

degbook, optional

(default True) determines if the angles are returned in radians or degrees

Returns:
ndarray

a numpy array of shape (4) with four GID scattering angles which are [alpha_i, azimuth, twotheta, beta];

  • alpha_i : incidence angle to surface (at the moment always 0)

  • azimuthsample rotation with respect to the inplane

    reference direction

  • twotheta : scattering angle

  • beta : exit angle from surface (at the moment always 0)

__init__(idir, ndir, **keyargs)[source]

initialization routine for the GID Experiment class

  • idir defines the inplane reference direction (idir points into the PB direction at zero angles)

  • ndir defines the surface normal of your sample (ndir points along the innermost sample rotation axis)

Parameters:
idir, ndir, keyargs

same as for the Experiment base class

class xrayutilities.experiment.GISAXS(idir, ndir, **keyargs)[source]

Bases: Experiment

class describing grazing incidence x-ray diffraction experiments the class helps with calculating the angles of Bragg reflections as well as it helps with analyzing measured data

the class describes a three circle (alpha_i, twotheta, beta) goniometer to help with GISAXS experiments at the ROTATING ANODE. 3D data can be treated with the use of linear and area detectors. see help self.Ang2Q

Ang2Q(ai, tt, beta, **kwargs)[source]

angular to momentum space conversion for a point detector. Also see help GISAXS.Ang2Q for procedures which treat line and area detectors

Parameters:
ai, tt, betafloat or array-like

sample and detector angles as numpy array, lists or Scalars must be given. all arguments must have the same shape or length. Howevver, if one angle is always the same its enough to give one scalar value.

kwargsdict, optional

optional keyword arguments

deltalist, tuple or array-like, optional

giving delta angles to correct the given ones for misalignment delta must be an numpy array or list of length 3. Used angles are then ai, tt, beta - delta

UBarray-like, optional

matrix for conversion from (hkl) coordinates to Q of sample used to determine not Q but (hkl) (default: identity matrix)

wlfloat or str, optional

x-ray wavelength in angstrom (default: self._wl)

degbool, optional

flag to tell if angles are passed as degree (default: True)

Returns:
ndarray

reciprocal space positions as numpy.ndarray with shape (N , 3) where N corresponds to the number of points given in the input

Q2Ang(Q, trans=True, deg=True, **kwargs)[source]
__init__(idir, ndir, **keyargs)[source]

initialization routine for the GISAXS Experiment class

idir defines the inplane reference direction (idir points into the PB direction at zero angles)

Parameters:
idir, ndir, keyargs

same as for the Experiment base class

class xrayutilities.experiment.HXRD(idir, ndir, geometry='hi_lo', **keyargs)[source]

Bases: Experiment

class describing high angle x-ray diffraction experiments the class helps with calculating the angles of Bragg reflections as well as helps with analyzing measured data

the class describes a two circle (omega, twotheta) goniometer to help with coplanar x-ray diffraction experiments. Nevertheless 3D data can be treated with the use of linear and area detectors. see “help(HXRDInstance.Ang2Q)”

Ang2Q(om, tt, **kwargs)[source]

angular to momentum space conversion for a point detector. Also see help HXRD.Ang2Q for procedures which treat line and area detectors

Parameters:
om, ttfloat or array-like

sample and detector angles as numpy array, lists or Scalars must be given. All arguments must have the same shape or length. However, if one angle is always the same its enough to give one scalar value.

kwargsdict, optional

optional keyword arguments

deltalist or array-like

giving delta angles to correct the given ones for misalignment. delta must be an numpy array or list of length 2. Used angles are than om, tt - delta

UBarray-like

matrix for conversion from (hkl) coordinates to Q of sample used to determine not Q but (hkl) (default: identity matrix)

wlfloat or str, optional

x-ray wavelength in angstrom (default: self._wl)

degbool, optional

flag to tell if angles are passed as degree (default: True)

Returns:
ndarray

reciprocal space positions as numpy.ndarray with shape (N , 3) where N corresponds to the number of points given in the input

Q2Ang(*Q, **keyargs)[source]

Convert a reciprocal space vector Q to COPLANAR scattering angles. The keyword argument trans determines whether Q should be transformed to the experimental coordinate frame or not. The coplanar scattering angles correspond to a goniometer with sample rotations [‘x+’, ‘y+’, ‘z-’] and detector rotation ‘x+’ and primary beam along y. This is a standard four circle diffractometer.

Note

The behavior of this function is unchanged if the goniometer definition is changed!

Parameters:
Qlist, tuple or array-like

array of shape (3) with q-space vector components or 3 separate lists with qx, qy, qz

transbool, optional

apply coordinate transformation on Q (default True)

degbook, optional

(default True) determines if the angles are returned in radians or degrees

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

determines the scattering geometry (default: self.geometry):

  • ‘hi_lo’ high incidence and low exit

  • ‘lo_hi’ low incidence and high exit

  • ‘real’ general geometry with angles determined by q-coordinates (azimuth); this and upper geometries return [omega, 0, phi, twotheta]

  • ‘realTilt’ general geometry with angles determined by q-coordinates (tilt); returns [omega, chi, phi, twotheta]

refracbool, optional

determines if refraction is taken into account; if True then also a material must be given (default: False)

matCrystal

Crystal object; needed to obtain its optical properties for refraction correction, otherwise not used

full_outputbool, optional

determines if additional output is given to determine scattering angles more accurately in case refraction is set to True. default: False

fi, fdtuple or list

if refraction correction is applied one can optionally specify the facet through which the beam enters (fi) and exits (fd) fi, fd must be the surface normal vectors (not transformed & not necessarily normalized). If omitted the normal direction of the experiment is used.

Returns:
ndarray

full_output=False: a numpy array of shape (4) with four scattering angles which are [omega, chi, phi, twotheta];

  • omega : incidence angle with respect to surface

  • chi : sample tilt for the case of non-coplanar geometry

  • phisample azimuth with respect to inplane reference

    direction

  • twotheta : scattering angle/detector angle

full_output=True: a numpy array of shape (6) with five angles which are [omega, chi, phi, twotheta, psi_i, psi_d]

  • psi_ioffset of the incidence beam from the scattering plane

    due to refraction

  • pdi_doffset ot the diffracted beam from the scattering plane

    due to refraction

__init__(idir, ndir, geometry='hi_lo', **keyargs)[source]

initialization routine for the HXRD Experiment class

Parameters:
idir, ndir, keyargs

same as for the Experiment base class -> please look at the docstring of Experiment.__init__ for more details

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

determines the scattering geometry :

  • ‘hi_lo’ (default) high incidence-low exit

  • ‘lo_hi’ low incidence - high exit

  • ‘real’ general geometry - q-coordinates determine high or low incidence

class xrayutilities.experiment.NonCOP(idir, ndir, **keyargs)[source]

Bases: Experiment

class describing high angle x-ray diffraction experiments. The class helps with calculating the angles of Bragg reflections as well as helps with analyzing measured data for NON-COPLANAR measurements, where the tilt is used to align asymmetric peaks, like in the case of a polefigure measurement.

The class describes a four circle (omega, chi, phi, twotheta) goniometer to help with x-ray diffraction experiments. Linear and area detectors can be treated as described in “help(NonCOPInstance.Ang2Q)”

Ang2Q(om, chi, phi, tt, **kwargs)[source]

angular to momentum space conversion for a point detector. Also see help NonCOP.Ang2Q for procedures which treat line and area detectors

Parameters:
om, chi, phi, ttfloat or array-like

sample and detector angles as numpy array, lists or Scalars must be given. All arguments must have the same shape or length. However, if one angle is always the same its enough to give one scalar value.

kwargsdict, optional

optional keyword arguments

deltalist, tuple or array-like, optional

giving delta angles to correct the given ones for misalignment delta must be an numpy array or list of length 4. Used angles are than om, chi, phi, tt - delta

UBarray-like, optional

matrix for conversion from (hkl) coordinates to Q of sample used to determine not Q but (hkl) (default: identity matrix)

wlfloat or str, optional

x-ray wavelength in angstrom (default: self._wl)

degbool, optional

flag to tell if angles are passed as degree (default: True)

Returns:
ndarray

reciprocal space positions as numpy.ndarray with shape (N , 3) where N corresponds to the number of points given in the input

Q2Ang(*Q, **keyargs)[source]

Convert a reciprocal space vector Q to NON-COPLANAR scattering angles. The keyword argument trans determines whether Q should be transformed to the experimental coordinate frame or not.

Note

The behavior of this function is unchanged if the goniometer definition is changed!

Parameters:
Qlist, tuple or array-like

array of shape (3) with q-space vector components or 3 separate lists with qx, qy, qz

transbool, optional

apply coordinate transformation on Q (default True)

degbook, optional

(default True) determines if the angles are returned in radians or degrees

Returns:
ndarray

a numpy array of shape (4) with four scattering angles which are [omega, chi, phi, twotheta];

  • omega : incidence angle with respect to surface

  • chi : sample tilt for the case of non-coplanar geometry

  • phisample azimuth with respect to inplane reference

    direction

  • twotheta : scattering angle/detector angle

__init__(idir, ndir, **keyargs)[source]

initialization routine for the NonCOP Experiment class

Parameters:
idir, ndir, keyargs

same as for the Experiment base class

class xrayutilities.experiment.PowderExperiment(**kwargs)[source]

Bases: Experiment

Experimental class for powder diffraction which helps to convert theta angles to momentum transfer space

Q2Ang(qpos, wl=None, deg=True)[source]

Converts reciprocal space values to theta angles

__init__(**kwargs)[source]

class constructor which takes the same keyword arguments as the Experiment class

Parameters:
kwargsdict, optional

keyword arguments same as for the Experiment base class

class xrayutilities.experiment.QConvFlags(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: IntFlag

HAS_SAMPLEDIS = 4
HAS_TRANSLATIONS = 1
NONE = 0
VERBOSE = 16
class xrayutilities.experiment.QConversion(sampleAxis, detectorAxis, r_i, **kwargs)[source]

Bases: object

Class for the conversion of angular coordinates to momentum space for arbitrary goniometer geometries and X-ray energy. Both angular scans (where some goniometer angles change during data acquisition) and energy scans (where the energy is varied during acquisition) as well as mixed cases can be treated.

the class is configured with the initialization and does provide three distinct routines for conversion to momentum space for

  • point detector: point(…) or __call__()

  • linear detector: linear(…)

  • area detector: area(…)

linear() and area() can only be used after the init_linear() or init_area() routines were called

property UB
__call__(*args, **kwargs)[source]

wrapper function for point(…)

__init__(sampleAxis, detectorAxis, r_i, **kwargs)[source]

initialize QConversion object. This means the rotation axis of the sample and detector circles need to be given: starting with the outer most circle.

Parameters:
sampleAxislist or tuple

sample circles, e.g. [‘x+’, ‘z+’] would mean two sample circles whereas the outer one turns righthanded around the x axis and the inner one turns righthanded around z.

detectorAxislist or tuple

detector circles e.g. [‘x-’] would mean a detector arm with a single motor turning lefthanded around the x-axis.

r_iarray-like

vector giving the direction of the primary beam (length is relevant only if translations are involved)

kwargsdict, optional

optional keyword arguments

wlfloat or str, optional

wavelength of the x-rays in angstrom

enfloat or str, optional

energy of the x-rays in electronvolt

UBarray-like, optional

matrix for conversion from (hkl) coordinates to Q of sample used to determine not Q but (hkl) (default: identity matrix)

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

angular to momentum space conversion for a area detector the center pixel defined by the init_area routine must be in direction of self.r_i when detector angles are zero

the detector geometry must be initialized by the init_area(…) routine

Parameters:
argsndarray, list or Scalars

sample and detector angles; in total len(self.sampleAxis) + len(detectorAxis) must be given, always starting with the outer most circle. all arguments must have the same shape or length but can be mixed with Scalars (i.e. if an angle is always the same it can be given only once instead of an array)

  • sAngles :

    sample circle angles, number of arguments must correspond to len(self.sampleAxis)

  • dAngles :

    detector circle angles, number of arguments must correspond to len(self.detectorAxis)

kwargsdict, optional

optional keyword arguments

deltalist or array-like, optional

delta angles to correct the given ones for misalignment. delta must be an numpy array or list of len(*args). used angles are then *args - delta

UBarray-like, optional

matrix for conversion from (hkl) coordinates to Q of sample used to determine not Q but (hkl) (default: self.UB)

Navtuple or list, optional

number of channels to average to reduce data size e.g. [2, 2] (default: self._area_nav)

roilist or tuple, optional

region of interest for the detector pixels; e.g. [100, 900, 200, 800] (default: self._area_roi)

wlfloat or str, optional

x-ray wavelength in angstrom (default: self._wl)

enfloat, optional

x-ray energy in eV (default is converted self._wl). both wavelength and energy can also be an array which enables the QConversion for energy scans. Note that the en keyword overrules the wl keyword!

degbool, optional

flag to tell if angles are passed as degree (default: True)

sampledistuple or list or array-like

sample displacement vector in relative units of the detector distance. Applies to parallel beam geometry. (default: (0, 0, 0))

Returns:
reciprocal space position of all detector pixels in a numpy.ndarray of
shape ((*)*(self._area_roi[1] - self._area_roi[0]+1) *
(self._area_roi[3] - self._area_roi[2] + 1) , 3) were detectorDir1 is
the fastest varing
property detectorAxis

property handler for _detectorAxis

Returns:
list of detector axis following the syntax /[xyz][+-]/
property energy
getDetectorDistance(*args, **kwargs)[source]

obtains the detector distance by applying the detector arm movements. This is especially interesting for the case of 1 or 2D detectors to perform certain geometric corrections.

Parameters:
argslist

detector angles. Only detector arm angles as described by the detectorAxis attribute must be given.

kwargsdict, optional

optional keyword arguments

dimint, optional

dimension of the detector for which the position should be determined

roituple or list, optional

region of interest for the detector pixels; (default: self._area_roi/self._linear_roi)

Navtuple or list, optional

number of channels to average to reduce data size; (default: self._area_nav/self._linear_nav)

degbool, optional

flag to tell if angles are passed as degree (default: True)

Returns:
ndarray

numpy array with the detector distance

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

obtains the detector position vector by applying the detector arm rotations.

Parameters:
argslist

detector angles. Only detector arm angles as described by the detectorAxis attribute must be given.

kwargsdict, optional

optional keyword arguments

dimint, optional

dimension of the detector for which the position should be determined

roituple or list, optional

region of interest for the detector pixels; (default: self._area_roi/self._linear_roi)

Navtuple or list, optional

number of channels to average to reduce data size; (default: self._area_nav/self._linear_nav)

degbool, optional

flag to tell if angles are passed as degree (default: True)

Returns:
ndarray

numpy array of length 3 with vector components of the detector direction. The length of the vector is k.

init_area(detectorDir1, detectorDir2, cch1, cch2, Nch1, Nch2, distance=None, pwidth1=None, pwidth2=None, chpdeg1=None, chpdeg2=None, detrot=0, tiltazimuth=0, tilt=0, **kwargs)[source]

initialization routine for area detectors detector direction as well as distance and pixel size or channels per degree must be given. Two separate pixel sizes and channels per degree for the two orthogonal directions can be given

Parameters:
detectorDir1str

direction of the detector (along the pixel direction 1); e.g. ‘z+’ means higher pixel numbers at larger z positions

detectorDir2str

direction of the detector (along the pixel direction 2); e.g. ‘x+’

cch1, cch2float

center pixel, in direction of self.r_i at zero detectorAngles

Nch1, Nch2int

number of detector pixels along direction 1, 2

distancefloat, optional

distance of center pixel from center of rotation

pwidth1, pwidth2float, optional

width of one pixel (same unit as distance)

chpdeg1, chpdeg2float, optional

channels per degree (only absolute value is relevant) sign determined through detectorDir1, detectorDir2

detrotfloat, optional

angle of the detector rotation around primary beam direction (used to correct misalignments)

tiltazimuthfloat, optional

direction of the tilt vector in the detector plane (in degree)

tiltfloat, optional

tilt of the detector plane around an axis normal to the direction given by the tiltazimuth

kwargsdict, optional

optional keyword arguments

Navtuple or list, optional

number of channels to average to reduce data size (default: [1, 1])

roituple or list, optional

region of interest for the detector pixels; e.g. [100, 900, 200, 800]

Note

Either distance and pwidth1, pwidth2 or chpdeg1, chpdeg2 must be given !!

Note

the channel numbers run from 0 .. NchX-1

init_linear(detectorDir, cch, Nchannel, distance=None, pixelwidth=None, chpdeg=None, tilt=0, **kwargs)[source]

initialization routine for linear detectors detector direction as well as distance and pixel size or channels per degree must be given.

Parameters:
detectorDirstr

direction of the detector (along the pixel array); e.g. ‘z+’

cchfloat

center channel, in direction of self.r_i at zero detectorAngles

Nchannelint

total number of detector channels

distancefloat, optional

distance of center channel from center of rotation

pixelwidthfloat, optional

width of one pixel (same unit as distance)

chpdegfloat, optional

channels per degree (only absolute value is relevant) sign determined through detectorDir

tiltfloat, optional

tilt of the detector axis from the detectorDir (in degree)

kwargs: dict, optional

optional keyword arguments

Navint, optional

number of channels to average to reduce data size (default: 1)

roituple or list

region of interest for the detector pixels; e.g. [100, 900]

Note

Either distance and pixelwidth or chpdeg must be given !!

Note

the channel numbers run from 0 .. Nchannel-1

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

angular to momentum space conversion for a linear detector the cch of the detector must be in direction of self.r_i when detector angles are zero

the detector geometry must be initialized by the init_linear(…) routine

Parameters:
argsndarray, list or Scalars

sample and detector angles; in total len(self.sampleAxis) + len(detectorAxis) must be given, always starting with the outer most circle. all arguments must have the same shape or length but can be mixed with Scalars (i.e. if an angle is always the same it can be given only once instead of an array)

  • sAngles :

    sample circle angles, number of arguments must correspond to len(self.sampleAxis)

  • dAngles :

    detector circle angles, number of arguments must correspond to len(self.detectorAxis)

kwargsdict, optional

optional keyword arguments

deltalist or array-like, optional

delta angles to correct the given ones for misalignment. delta must be an numpy array or list of len(*args). used angles are then *args - delta

UBarray-like, optional

matrix for conversion from (hkl) coordinates to Q of sample used to determine not Q but (hkl) (default: self.UB)

Navint, optional

number of channels to average to reduce data size (default: self._linear_nav)

roilist or tuple, optional

region of interest for the detector pixels; e.g. [100, 900] (default: self._linear_roi)

wlfloat or str, optional

x-ray wavelength in angstrom (default: self._wl)

enfloat, optional

x-ray energy in eV (default is converted self._wl). both wavelength and energy can also be an array which enables the QConversion for energy scans. Note that the en keyword overrules the wl keyword!

degbool, optional

flag to tell if angles are passed as degree (default: True)

sampledistuple or list or array-like

sample displacement vector in relative units of the detector distance. Applies to parallel beam geometry. (default: (0, 0, 0))

Returns:
reciprocal space position of all detector pixels in a numpy.ndarray of
shape ( (*)*(self._linear_roi[1]-self._linear_roi[0]+1) , 3 )
point(*args, **kwargs)[source]

angular to momentum space conversion for a point detector located in direction of self.r_i when detector angles are zero

Parameters:
argsndarray, list or Scalars

sample and detector angles; in total len(self.sampleAxis) + len(detectorAxis) must be given, always starting with the outer most circle. all arguments must have the same shape or length but can be mixed with Scalars (i.e. if an angle is always the same it can be given only once instead of an array)

  • sAngles :

    sample circle angles, number of arguments must correspond to len(self.sampleAxis)

  • dAngles :

    detector circle angles, number of arguments must correspond to len(self.detectorAxis)

kwargsdict, optional

optional keyword arguments

deltalist or array-like, optional

delta angles to correct the given ones for misalignment. delta must be an numpy array or list of len(*args). used angles are then *args - delta

UBarray-like, optional

matrix for conversion from (hkl) coordinates to Q of sample used to determine not Q but (hkl) (default: self.UB)

wlfloat or str, optional

x-ray wavelength in angstrom (default: self._wl)

enfloat, optional

x-ray energy in eV (default is converted self._wl). both wavelength and energy can also be an array which enables the QConversion for energy scans. Note that the en keyword overrules the wl keyword!

degbool, optional

flag to tell if angles are passed as degree (default: True)

sampledistuple or list or array-like

sample displacement vector in relative units of the detector distance. Applies to parallel beam geometry. (default: (0, 0, 0))

Returns:
ndarray

reciprocal space positions as numpy.ndarray with shape (N , 3) where N corresponds to the number of points given in the input

property sampleAxis

property handler for _sampleAxis

Returns:
list

sample axes following the syntax /[xyzk][+-]/

transformSample2Lab(vector, *args)[source]

transforms a vector from the sample coordinate frame to the laboratory coordinate system by applying the sample rotations from inner to outer circle.

Parameters:
vectorsequence, list or numpy array

vector to transform

argslist

goniometer angles (sample angles or full goniometer angles can be given. If more angles than the sample circles are given they will be ignored)

Returns:
ndarray

rotated vector as numpy.array

property wavelength

xrayutilities.gridder module

class xrayutilities.gridder.FuzzyGridder1D(nx)[source]

Bases: Gridder1D

An 1D binning class considering every data point to have a finite width. If necessary one data point will be split fractionally over different data bins. This is numerically more effort but represents better the typical case of a experimental data, which do not represent a mathematical point but have a finite width (e.g. X-ray data from a 1D detector).

__call__(x, data, width=None)[source]

Perform gridding on a set of data. After running the gridder the ‘data’ object in the class is holding the gridded data.

Parameters:
xndarray

numpy array of arbitrary shape with x positions

datandarray

numpy array of arbitrary shape with data values

widthfloat, optional

width of one data point. If not given half the bin size will be used.

class xrayutilities.gridder.Gridder[source]

Bases: ABC

Basis class for gridders in xrayutilities. A gridder is a function mapping irregular spaced data onto a regular grid by binning the data into equally sized elements.

There are different ways of defining the regular grid of a Gridder. In xrayutilities the data bins extend beyond the data range in the input data, but the given position being the center of these bins, extends from the minimum to the maximum of the data! The main motivation for this was to create a Gridder, which when feeded with N equidistant data points and gridded with N bins would not change the data position (not the case with numpy.histogramm functions!). Of course this leads to the fact that for homogeneous point density the first and last bin in any direction are not filled as the other bins.

A different definition is used by numpy histogram functions where the bins extend only to the end of the data range. (see numpy histogram, histrogram2d, …)

Clear()[source]

Clear so far gridded data to reuse this instance of the Gridder

KeepData(bool)[source]
Normalize(bool)[source]

set or unset the normalization flag. Normalization needs to be done to obtain proper gridding but may want to be disabled in certain cases when sequential gridding is performed

abstract __call__()[source]

abstract call method which every implementation of a Gridder has to override

__init__()[source]

Constructor defining default properties of any Gridder class

property data

return gridded data (performs normalization if switched on)

class xrayutilities.gridder.Gridder1D(nx)[source]

Bases: Gridder

__call__(x, data)[source]

Perform gridding on a set of data. After running the gridder the ‘data’ object in the class is holding the gridded data.

Parameters:
xndarray

numpy array of arbitrary shape with x positions

datandarray

numpy array of arbitrary shape with data values

__init__(nx)[source]

Constructor defining default properties of any Gridder class

dataRange(min, max, fixed=True)[source]

define minimum and maximum data range, usually this is deduced from the given data automatically, however, for sequential gridding it is useful to set this before the first call of the gridder. data outside the range are simply ignored

Parameters:
minfloat

minimum value of the gridding range

maxfloat

maximum value of the gridding range

fixedbool, optional

flag to turn fixed range gridding on (True (default)) or off (False)

savetxt(filename, header='')[source]

save gridded data to a txt file with two columns. The first column is the data coordinate and the second the corresponding data value

Parameters:
filenamestr

output filename

headerstr, optional

optional header for the data file.

property xaxis

Returns the xaxis of the gridder the returned values correspond to the center of the data bins used by the gridding algorithm

class xrayutilities.gridder.GridderFlags(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: IntFlag

NO_DATA_INIT = 1
NO_NORMALIZATION = 4
VERBOSE = 16
xrayutilities.gridder.axis(min_value, max_value, n)[source]

Compute the a grid axis.

Parameters:
min_valuefloat

axis minimum value

max_valuefloat

axis maximum value

nint

number of steps

xrayutilities.gridder.delta(min_value, max_value, n)[source]

Compute the stepsize along an axis of a grid.

Parameters:
min_valueaxis minimum value
max_valueaxis maximum value
nnumber of steps
class xrayutilities.gridder.npyGridder1D(nx)[source]

Bases: Gridder1D

__call__(x, data)[source]

Perform gridding on a set of data. After running the gridder the ‘data’ object in the class is holding the gridded data.

Parameters:
xndarray

numpy array of arbitrary shape with x positions

datandarray

numpy array of arbitrary shape with data values

property xaxis

Returns the xaxis of the gridder the returned values correspond to the center of the data bins used by the numpy.histogram function

xrayutilities.gridder.ones(*args)[source]

Compute ones for matrix generation. The shape is determined by the number of input arguments.

xrayutilities.gridder2d module

class xrayutilities.gridder2d.FuzzyGridder2D(nx, ny)[source]

Bases: Gridder2D

An 2D binning class considering every data point to have a finite area. If necessary one data point will be split fractionally over different data bins. This is numerically more effort but represents better the typical case of a experimental data, which do not represent a mathematical point but have a finite size (e.g. X-ray data from a 2D detector or reciprocal space maps measured with point/linear detector).

Currently only a rectangular area can be considered during the gridding.

__call__(x, y, data, **kwargs)[source]

Perform gridding on a set of data. After running the gridder the ‘data’ object in the class is holding the gridded data.

Parameters:
xndarray

numpy array of arbitrary shape with x positions

yndarray

numpy array of arbitrary shape with y positions

datandarray

numpy array of arbitrary shape with data values

widthfloat or tuple or list, optional

width of one data point. If not given half the bin size will be used. The width can be given as scalar if it is equal for both data dimensions, or as sequence of length 2.

class xrayutilities.gridder2d.Gridder2D(nx, ny)[source]

Bases: Gridder

SetResolution(nx, ny)[source]

Reset the resolution of the gridder. In this case the original data stored in the object will be deleted.

Parameters:
nxint

number of points in x-direction

nyint

number of points in y-direction

__call__(x, y, data)[source]

Perform gridding on a set of data. After running the gridder the ‘data’ object in the class is holding the gridded data.

Parameters:
xndarray

numpy array of arbitrary shape with x positions

yndarray

numpy array of arbitrary shape with y positions

datandarray

numpy array of arbitrary shape with data values

__init__(nx, ny)[source]

Constructor defining default properties of any Gridder class

dataRange(xmin, xmax, ymin, ymax, fixed=True)[source]

define minimum and maximum data range, usually this is deduced from the given data automatically, however, for sequential gridding it is useful to set this before the first call of the gridder. data outside the range are simply ignored

Parameters:
xmin, yminfloat

minimum value of the gridding range in x, y

xmax, ymaxfloat

maximum value of the gridding range in x, y

fixedbool, optional

flag to turn fixed range gridding on (True (default)) or off (False)

savetxt(filename, header='')[source]

save gridded data to a txt file with two columns. The first two columns are the data coordinates and the last one the corresponding data value.

Parameters:
filenamestr

output filename

headerstr, optional

optional header for the data file.

property xaxis
property xmatrix
property yaxis
property ymatrix
class xrayutilities.gridder2d.Gridder2DList(nx, ny)[source]

Bases: Gridder2D

special version of a 2D gridder which performs no actual averaging of the data in one grid/bin but just collects the data-objects belonging to one bin for further treatment by the user

Clear()[source]

Clear so far gridded data to reuse this instance of the Gridder

__call__(x, y, data)[source]

Perform gridding on a set of data. After running the gridder the ‘data’ object in the class is holding the lists of data-objects belonging to one bin/grid-point.

Parameters:
xndarray

numpy array of arbitrary shape with x positions

yndarray

numpy array of arbitrary shape with y positions

datandarray, list or tuple

data of same length as x, y but of arbitrary type

property data

return gridded data, in this special version no normalization is defined!

xrayutilities.gridder3d module

class xrayutilities.gridder3d.FuzzyGridder3D(nx, ny, nz)[source]

Bases: Gridder3D

An 3D binning class considering every data point to have a finite volume. If necessary one data point will be split fractionally over different data bins. This is numerically more effort but represents better the typical case of a experimental data, which do not represent a mathematical point but have a finite size.

Currently only a quader can be considered as volume during the gridding.

__call__(x, y, z, data, **kwargs)[source]

Perform gridding on a set of data. After running the gridder the ‘data’ object in the class is holding the gridded data.

Parameters:
xndarray

numpy array of arbitrary shape with x positions

yndarray

numpy array of arbitrary shape with y positions

zndarray

numpy array fo arbitrary shape with z positions

datandarray

numpy array of arbitrary shape with data values

widthfloat, tuple or list, optional

width of one data point. If not given half the bin size will be used. The width can be given as scalar if it is equal for all three dimensions, or as sequence of length 3.

class xrayutilities.gridder3d.Gridder3D(nx, ny, nz)[source]

Bases: Gridder

SetResolution(nx, ny, nz)[source]
__call__(x, y, z, data)[source]

Perform gridding on a set of data. After running the gridder the ‘data’ object in the class is holding the gridded data.

Parameters:
xndarray

numpy array of arbitrary shape with x positions

yndarray

numpy array of arbitrary shape with y positions

zndarray

numpy array fo arbitrary shape with z positions

datandarray

numpy array of arbitrary shape with data values

__init__(nx, ny, nz)[source]

Constructor defining default properties of any Gridder class

dataRange(xmin, xmax, ymin, ymax, zmin, zmax, fixed=True)[source]

define minimum and maximum data range, usually this is deduced from the given data automatically, however, for sequential gridding it is useful to set this before the first call of the gridder. data outside the range are simply ignored

Parameters:
xmin, ymin, zminfloat

minimum value of the gridding range in x, y, z

xmax, ymax, zmaxfloat

maximum value of the gridding range in x, y, z

fixedbool, optional

flag to turn fixed range gridding on (True (default)) or off (False)

property xaxis
property xmatrix
property yaxis
property ymatrix
property zaxis
property zmatrix

xrayutilities.mpl_helper module

Defines new matplotlib Sqrt scale which further allows for negative values by using the sign of the original value as sign of the plotted value.

class xrayutilities.mpl_helper.SqrtAllowNegScale(axis, **kwargs)[source]

Bases: ScaleBase

Scales data using a sqrt-function, however, allowing also negative values.

The scale function:

sign(y) * sqrt(abs(y))

The inverse scale function:

sign(y) * y**2

class InvertedSqrtTransform(shorthand_name=None)[source]

Bases: Transform

has_inverse = True

True if this transform has a corresponding inverse transform.

input_dims = 1

The number of input dimensions of this transform. Must be overridden (with integers) in the subclass.

inverted()[source]

Return the corresponding inverse transformation.

It holds x == self.inverted().transform(self.transform(x)).

The return value of this method should be treated as temporary. An update to self does not cause a corresponding update to its inverted copy.

is_separable = True

True if this transform is separable in the x- and y- dimensions.

output_dims = 1

The number of output dimensions of this transform. Must be overridden (with integers) in the subclass.

transform_non_affine(a)[source]

Apply only the non-affine part of this transformation.

transform(values) is always equivalent to transform_affine(transform_non_affine(values)).

In non-affine transformations, this is generally equivalent to transform(values). In affine transformations, this is always a no-op.

Parameters:
valuesarray

The input values as an array of length input_dims or shape (N, input_dims).

Returns:
array

The output values as an array of length output_dims or shape (N, output_dims), depending on the input.

class SqrtTransform(shorthand_name=None)[source]

Bases: Transform

has_inverse = True

True if this transform has a corresponding inverse transform.

input_dims = 1

The number of input dimensions of this transform. Must be overridden (with integers) in the subclass.

inverted()[source]

return the inverse transform for this transform.

is_separable = True

True if this transform is separable in the x- and y- dimensions.

output_dims = 1

The number of output dimensions of this transform. Must be overridden (with integers) in the subclass.

transform_non_affine(a)[source]

This transform takes an Nx1 numpy array and returns a transformed copy.

__init__(axis, **kwargs)[source]

Any keyword arguments passed to set_xscale and set_yscale will be passed along to the scale’s constructor.

get_transform()[source]

Return the .Transform object associated with this scale.

limit_range_for_scale(vmin, vmax, minpos)[source]

Override to limit the bounds of the axis to the domain of the transform. In the case of Mercator, the bounds should be limited to the threshold that was passed in. Unlike the autoscaling provided by the tick locators, this range limiting will always be adhered to, whether the axis range is set manually, determined automatically or changed through panning and zooming.

name = 'sqrt'
set_default_locators_and_formatters(axis)[source]

Set the locators and formatters of axis to instances suitable for this scale.

class xrayutilities.mpl_helper.SqrtTickLocator(nbins=7, symmetric=True)[source]

Bases: Locator

__call__()[source]

Return the locations of the ticks

__init__(nbins=7, symmetric=True)[source]
set_params(nbins, symmetric)[source]

Set parameters within this locator.

tick_values(vmin, vmax)[source]

Return the values of the located ticks given vmin and vmax.

Note

To get tick locations with the vmin and vmax values defined automatically for the associated axis simply call the Locator instance:

>>> print(type(loc))
<type 'Locator'>
>>> print(loc())
[1, 2, 3, 4]
view_limits(dmin, dmax)[source]

Set the view limits to the nearest multiples of base that contain the data

xrayutilities.normalize module

module to provide functions that perform block averaging of intensity arrays to reduce the amount of data (mainly for PSD and CCD measurements

and

provide functions for normalizing intensities for

  • count time

  • absorber (user-defined function)

  • monitor

  • flatfield correction

class xrayutilities.normalize.IntensityNormalizer(det='', **keyargs)[source]

Bases: object

generic class for correction of intensity (point detector, or MCA, single CCD frames) for count time and absorber factors the class must be supplied with a absorber correction function and works with data structures provided by xrayutilities.io classes or the corresponding objects from hdf5 files

__call__(data, ccd=None)[source]

apply the correction method which was initialized to the measured data

Parameters:
datanumpy.recarray

data object from xrayutilities.io classes

ccdndarray, optional

optionally CCD data can be given as separate ndarray of shape (len(data), n1, n2), where n1, n2 is the shape of the CCD image.

Returns:
corrintndarray

corrected intensity as numpy.ndarray of the same shape as data[det] (or ccd.shape)

__init__(det='', **keyargs)[source]

initialization of the corrector class

Parameters:
detstr

detector field name of the data structure

monstr, optional

monitor field name

time: float or str, optional

count time field name or count time as float

av_monfloat, optional

average monitor value (default: data[mon].mean())

smoothmonint

number of monitor values used to get a smooth monitor signal

absfuncallable, optional

absorber correction function to be used as in absorber_corrected_intensity = data[det]*absfun(data)

flatfieldndarray

flatfield of the detector; shape must be the same as data[det], and is only applied for MCA detectors

darkfieldndarray

darkfield of the detector; shape must be the same as data[det], and is only applied for MCA detectors

Examples

>>> detcorr = IntensityNormalizer("MCA", time="Seconds",
... absfun=lambda d: d["PSDCORR"]/d["PSD"].astype(float))
property absfun

absfun property handler

returns the costum correction function or None

property avmon

av_mon property handler

returns the value of the average monitor or None if average is calculated from the monitor field

property darkfield

flatfield property handler

returns the current set darkfield of the detector or None if not set

property det

det property handler

returns the detector field name

property flatfield

flatfield property handler

returns the current set flatfield of the detector or None if not set

property mon

mon property handler

returns the monitor field name or None if not set

property time

time property handler

returns the count time or the field name of the count time or None if time is not set

xrayutilities.normalize.blockAverage1D(data, Nav)[source]

perform block average for 1D array/list of Scalar values all data are used. at the end of the array a smaller cell may be used by the averaging algorithm

Parameters:
dataarray-like

data which should be contracted (length N)

Navint

number of values which should be averaged

Returns:
ndarray

block averaged numpy array of data type numpy.double (length ceil(N/Nav))

xrayutilities.normalize.blockAverage2D(data2d, Nav1, Nav2, **kwargs)[source]

perform a block average for 2D array of Scalar values all data are used therefore the margin cells may differ in size

Parameters:
data2dndarray

array of 2D data shape (N, M)

Nav1, Nav2int

a field of (Nav1 x Nav2) values is contracted

kwargsdict, optional

optional keyword argument

roituple or list, optional

region of interest for the 2D array. e.g. [20, 980, 40, 960], reduces M, and M!

Returns:
ndarray

block averaged numpy array with type numpy.double with shape (ceil(N/Nav1), ceil(M/Nav2))

xrayutilities.normalize.blockAverageCCD(data3d, Nav1, Nav2, **kwargs)[source]

perform a block average for 2D frames inside a 3D array. all data are used therefore the margin cells may differ in size

Parameters:
data3dndarray

array of 3D data shape (Nframes, N, M)

Nav1, Nav2int

a field of (Nav1 x Nav2) values is contracted

kwargsdict, optional

optional keyword argument

roituple or list, optional

region of interest for the 2D array. e.g. [20, 980, 40, 960], reduces M, and M!

Returns:
ndarray

block averaged numpy array with type numpy.double with shape (Nframes, ceil(N/Nav1), ceil(M/Nav2))

xrayutilities.normalize.blockAveragePSD(psddata, Nav, **kwargs)[source]

perform a block average for serveral PSD spectra all data are used therefore the last cell used for averaging may differ in size

Parameters:
psddatandarray

array of 2D data shape (Nspectra, Nchannels)

Navint

number of channels which should be averaged

kwargsdict, optional

optional keyword argument

roituple or list

region of interest for the 2D array. e.g. [20, 980] Nchannels = 980-20

Returns:
ndarray

block averaged psd spectra as numpy array with type numpy.double of shape (Nspectra , ceil(Nchannels/Nav))

xrayutilities.q2ang_fit module

Module provides functions to convert a q-vector from reciprocal space to angular space. a simple implementation uses scipy optimize routines to perform a fit for a arbitrary goniometer.

The user is, however, expected to use the bounds variable to put restrictions to the number of free angles to obtain reproducible results. In general only 3 angles are needed to fit an arbitrary q-vector (2 sample + 1 detector angles or 1 sample + 2 detector). More complicated restrictions can be implemented using the lmfit package. (done upon request!)

The function is based on a fitting routine. For a specific goniometer also analytic expressions from literature can be used as they are implemented in the predefined experimental classes HXRD, NonCOP, and GID.

xrayutilities.q2ang_fit.Q2AngFit(qvec, expclass, bounds=None, ormat=array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]), startvalues=None, constraints=None)[source]

Functions to convert a q-vector from reciprocal space to angular space. This implementation uses scipy optimize routines to perform a fit for a goniometer with arbitrary number of goniometer angles.

The user must use the bounds variable to put restrictions to the number of free angles to obtain reproducible results. In general only 3 angles are needed to fit an arbitrary q-vector (2 sample + 1 detector angles or 1 sample + 2 detector).

Parameters:
qvectuple or list or array-like

q-vector for which the angular positions should be calculated

expclassExperiment

experimental class used to define the goniometer for which the angles should be calculated.

boundstuple or list

bounds of the goniometer angles. The number of bounds must correspond to the number of goniometer angles in the expclass. Angles can also be fixed by supplying only one value for a particular angle. e.g.: ((low, up), fix, (low2, up2), (low3, up3))

ormatarray-like

orientation matrix of the sample to be used in the conversion

startvaluesarray-like

start values for the fit, which can significantly speed up the conversion. The number of values must correspond to the number of angles in the goniometer of the expclass

constraintslist, optional

sequence of constraint dictionaries. This allows applying arbitrary (e.g. pseudo-angle) contraints by supplying according constraint functions. An entry of the constraints argument must be a dictionary with at least the ‘type’ and ‘fun’ set. ‘type’ can be either ‘eq’ or ‘ineq’ for equality or inequality constraints. ‘fun’ must be a callable function which for ‘eq’-constraints returns 0 when the equality condition is fulfilled (see constraints documentation in scipy.optimize.minimize for details). The supplied function will be called with the arguments gonimeter angle list as argument. Typically this means you will have to use a lambda function.

Returns:
fittedangleslist

list of fitted goniometer angles

qerrorfloat

error in reciprocal space

errcodeint

error-code of the scipy minimize function. for a successful fit the error code should be <=2

xrayutilities.q2ang_fit.exitAngleConst(angles, alphaf, xrd)[source]

helper function for an pseudo-angle constraint of the exit angle. Can be used together with the Q2AngFit-routine in the ‘constraints’ argument. An example use case scenario to fix the exit angle to 1 degree would be: constraints={‘type’: ‘eq’, ‘fun’: lambda a: exitAngleConst(a, 1, xrd)}

Parameters:
anglesiterable

fit parameters of Q2AngFit

alphaffloat

the exit angle which should be fixed

xrdExperiment

the Experiment object to use for qconversion

xrayutilities.q2ang_fit.incidenceAngleConst(angles, alphai, xrd)[source]

helper function for an pseudo-angle constraint of the incidence angle. Can be used together with the Q2AngFit-routine in the ‘constraints’ argument. An example use case scenario to fix the incidence angle to 1 degree would be: constraints={‘type’: ‘eq’, ‘fun’: lambda a: incidenceAngleConst(a, 1, xrd)}

Parameters:
anglesiterable

fit parameters of Q2AngFit

alphaifloat

the incidence angle which should be fixed

xrdExperiment

the Experiment object to use for qconversion

xrayutilities.utilities module

xrayutilities utilities contains a conglomeration of useful functions which do not fit into one of the other files

xrayutilities.utilities.frac2str(fnumber, denominator_limit=25, fmt='%7.4f')[source]

convert a float to a string attempting to represent it as a fraction

Parameters:
fnumberfloat

floating point number to be represented as string

denominator_limitint

maximal integer used as denominator. If f can’t be expressed (within xu.config.EPSILON) by a fraction with a denominator up to this number a floating point string will be returned

fmtstr

format string used in case a floating point representation is needed

Returns:
str
xrayutilities.utilities.import_matplotlib_pyplot(funcname='XU')[source]

lazy import function of matplotlib.pyplot

Parameters:
funcnamestr

identification string of the calling function

Returns:
flagbool

the flag is True if the loading was successful and False otherwise.

pyplot

On success pyplot is the matplotlib.pyplot package.

xrayutilities.utilities.import_mayavi_mlab(funcname='XU')[source]

lazy import function of mayavi.mlab

Parameters:
funcnamestr

identification string of the calling function

Returns:
flagbool

the flag is True if the loading was successful and False otherwise.

mlab

On success mlab is the mayavi.mlab package.

xrayutilities.utilities.maplog(inte, dynlow='config', dynhigh='config')[source]

clips values smaller and larger as the given bounds and returns the log10 of the input array. The bounds are given as exponent with base 10 with respect to the maximum in the input array. The function is implemented in analogy to J. Stangl’s matlab implementation.

Parameters:
intendarray

numpy.array, values to be cut in range

dynlowfloat, optional

10^(-dynlow) will be the minimum cut off

dynhighfloat, optional

10^(-dynhigh) will be the maximum cut off

Returns:
ndarray

numpy.array of the same shape as inte, where values smaller/larger than 10^(-dynlow, dynhigh) were replaced by 10^(-dynlow, dynhigh)

Examples

>>> maplog(((0.1 , 1e5, 1e6), (10, 100, 1000)), 5, 2)
array([[1., 4., 4.],
       [1., 2., 3.]])

xrayutilities.utilities_noconf module

xrayutilities utilities contains a conglomeration of useful functions this part of utilities does not need the config class

class xrayutilities.utilities_noconf.ABC[source]

Bases: object

Helper class that provides a standard way to create an ABC using inheritance.

xrayutilities.utilities_noconf.check_kwargs(kwargs, valid_kwargs, identifier)[source]

Raises an TypeError if kwargs included a key which is not in valid_kwargs.

Parameters:
kwargsdict

keyword arguments dictionary

valid_kwargsdict

dictionary with valid keyword arguments and their description

identifierstr

string to identifier the caller of this function

xrayutilities.utilities_noconf.en2lam(inp)[source]

converts the input energy in eV to a wavelength in angstrom

Parameters:
inpfloat or str

energy in eV

Returns:
float

wavlength in angstrom

Examples

>>> wavelength = en2lam(8048)
xrayutilities.utilities_noconf.energy(en)[source]

convert common energy names to energies in eV

so far this works with CuKa1, CuKa2, CuKa12, CuKb, MoKa1

Parameters:
enfloat, array-like or str

energy either as scalar or array with value in eV, which will be returned unchanged; or string with name of emission line

Returns:
float or array-like

energy in eV

xrayutilities.utilities_noconf.exchange_filepath(orig, new, keep=0, replace=None)[source]

function to exchange the root of a filename with the option of keeping the inner directory structure. This for example includes such a conversion /dir_a/subdir/sample/file.txt -> /home/user/data/sample/file.txt where the innermost directory name is kept (keep=1), or equally the three outer most are replaced (replace=3). One can either give keep, or replace, with replace taking preference if both are given. Note that replace=1 on Linux/Unix replaces only the root for absolute paths.

Parameters:
origstr

original filename which should have its data root replaced

newstr

new path which should be used instead

keepint, optional

number of inner most directory names which should be kept the same in the output (default = 0)

replaceint, optional

number of outer most directory names which should be replaced in the output (default = None)

Returns:
str

filename string

Examples

>>> newfile = exchange_filepath('/dir_a/subdir/sam/file.txt', '/data', 1)    # you get '/data/sam/file.txt'
xrayutilities.utilities_noconf.exchange_path(orig, new, keep=0, replace=None)[source]

function to exchange the root of a path with the option of keeping the inner directory structure. This for example includes such a conversion /dir_a/subdir/images/sample -> /home/user/data/images/sample where the two innermost directory names are kept (keep=2), or equally the three outer most are replaced (replace=3). One can either give keep, or replace, with replace taking preference if both are given. Note that replace=1 on Linux/Unix replaces only the root for absolute paths.

Parameters:
origstr

original path which should be replaced by the new path

newstr

new path which should be used instead

keepint, optional

number of inner most directory names which should be kept the same in the output (default = 0)

replaceint, optional

number of outer most directory names which should be replaced in the output (default = None)

Returns:
str

directory path string

Examples

>>> p = exchange_path('/dir_a/subdir/img/sam', '/home/user/data', keep=2)    # you get '/home/user/data/img/sam'
xrayutilities.utilities_noconf.is_valid_variable_name(name)[source]
xrayutilities.utilities_noconf.lam2en(inp)[source]

converts the input wavelength in angstrom to an energy in eV

Parameters:
inpfloat or str

wavelength in angstrom

Returns:
float

energy in eV

Examples

>>> energy = lam2en(1.5406)
xrayutilities.utilities_noconf.makeNaturalName(name, check=False)[source]
xrayutilities.utilities_noconf.wavelength(wl)[source]

convert common energy names to energies in eV

so far this works with CuKa1, CuKa2, CuKa12, CuKb, MoKa1

Parameters:
wlfloat, array-like or str

wavelength; If scalar or array the wavelength in angstrom will be returned unchanged, string with emission name is converted to wavelength

Returns:
float or array-like

wavelength in angstrom

Module contents

xrayutilities is a Python package for assisting with x-ray diffraction experiments. Its the Python package included in xrayutilities.

It helps with planning experiments as well as analyzing the data.

Authors:

Dominik Kriegner <dominik.kriegner@gmail.com> and Eugen Wintersberger <eugen.wintersberger@desy.de>