pyFAI Package

pyFAI.__init__.benchmarks()

Run the benchmarks

pyFAI.__init__.tests(deprecation=False)

Runs the test suite of the installed version

Parameters:deprecation – enable/disables deprecation warning in the tests

azimuthalIntegrator Module

class pyFAI.azimuthalIntegrator.AzimuthalIntegrator(dist=1, poni1=0, poni2=0, rot1=0, rot2=0, rot3=0, pixel1=None, pixel2=None, splineFile=None, detector=None, wavelength=None)

Bases: pyFAI.geometry.Geometry

This class is an azimuthal integrator based on P. Boesecke’s geometry and histogram algorithm by Manolo S. del Rio and V.A Sole

All geometry calculation are done in the Geometry class

main methods are:

>>> tth, I = ai.integrate1d(data, npt, unit="2th_deg")
>>> q, I, sigma = ai.integrate1d(data, npt, unit="q_nm^-1", error_model="poisson")
>>> regrouped = ai.integrate2d(data, npt_rad, npt_azim, unit="q_nm^-1")[0]
DEFAULT_METHOD = 'splitbbox'
create_mask(data, mask=None, dummy=None, delta_dummy=None, mode='normal')

Combines various masks into another one.

Parameters:
  • data (ndarray) – input array of data
  • mask (ndarray) – input mask (if none, self.mask is used)
  • dummy (float) – value of dead pixels
  • delta_dumy – precision of dummy pixels
  • mode (str) – can be “normal” or “numpy” (inverted) or “where” applied to the mask
Returns:

the new mask

Return type:

ndarray of bool

This method combine two masks (dynamic mask from data & dummy and mask) to generate a new one with the ‘or’ binary operation. One can adjust the level, with the dummy and the delta_dummy parameter, when you consider the data values needs to be masked out.

This method can work in two different mode:

  • “normal”: False for valid pixels, True for bad pixels
  • “numpy”: True for valid pixels, false for others

This method tries to accomodate various types of masks (like valid=0 & masked=-1, ...) and guesses if an input mask needs to be inverted.

dark_correction(data, dark=None)

Correct for Dark-current effects. If dark is not defined, correct for a dark set by “set_darkfiles”

Parameters:
  • data – input ndarray with the image
  • dark – ndarray with dark noise or None
Returns:

2tuple: corrected_data, dark_actually used (or None)

darkcurrent
empty
flat_correction(data, flat=None)

Correct for flat field. If flat is not defined, correct for a flat set by “set_flatfiles”

Parameters:
  • data – input ndarray with the image
  • dark – ndarray with dark noise or None
Returns:

2tuple: corrected_data, flat_actually used (or None)

flatfield
get_darkcurrent()
get_empty()
get_flatfield()
integrate1d(data, npt, filename=None, correctSolidAngle=True, variance=None, error_model=None, radial_range=None, azimuth_range=None, mask=None, dummy=None, delta_dummy=None, polarization_factor=None, dark=None, flat=None, method='csr', unit=q_nm^-1, safe=True, normalization_factor=1.0, block_size=32, profile=False, all=False)

Calculate the azimuthal integrated Saxs curve in q(nm^-1) by default

Multi algorithm implementation (tries to be bullet proof), suitable for SAXS, WAXS, ... and much more

Parameters:
  • data (ndarray) – 2D array from the Detector/CCD camera
  • npt (int) – number of points in the output pattern
  • filename (str) – output filename in 2/3 column ascii format
  • correctSolidAngle (bool) – correct for solid angle of each pixel if True
  • variance (ndarray) – array containing the variance of the data. If not available, no error propagation is done
  • error_model (str) – When the variance is unknown, an error model can be given: “poisson” (variance = I), “azimuthal” (variance = (I-<I>)^2)
  • radial_range ((float, float), optional) – The lower and upper range of the radial unit. If not provided, range is simply (data.min(), data.max()). Values outside the range are ignored.
  • azimuth_range ((float, float), optional) – The lower and upper range of the azimuthal angle in degree. If not provided, range is simply (data.min(), data.max()). Values outside the range are ignored.
  • mask (ndarray) – array (same size as image) with 1 for masked pixels, and 0 for valid pixels
  • dummy (float) – value for dead/masked pixels
  • delta_dummy (float) – precision for dummy value
  • polarization_factor (float) – polarization factor between -1 (vertical) and +1 (horizontal). 0 for circular polarization or random, None for no correction
  • dark (ndarray) – dark noise image
  • flat (ndarray) – flat field image
  • method (str) – can be “numpy”, “cython”, “BBox” or “splitpixel”, “lut”, “csr”, “nosplit_csr”, “full_csr”, “lut_ocl” and “csr_ocl” if you want to go on GPU. To Specify the device: “csr_ocl_1,2”
  • unit (pyFAI.units.Enum) – Output units, can be “q_nm^-1”, “q_A^-1”, “2th_deg”, “2th_rad”, “r_mm” for now
  • safe (bool) – Do some extra checks to ensure LUT/CSR is still valid. False is faster.
  • normalization_factor (float) – Value of a normalization monitor
  • block_size – size of the block for OpenCL integration (unused?)
  • profile – set to True to enable profiling in OpenCL
  • all – if true return a dictionary with many more parameters
Returns:

q/2th/r bins center positions and regrouped intensity (and error array if variance or variance model provided), uneless all==True.

Return type:

2 or 3-tuple of ndarrays

integrate2d(data, npt_rad, npt_azim=360, filename=None, correctSolidAngle=True, variance=None, error_model=None, radial_range=None, azimuth_range=None, mask=None, dummy=None, delta_dummy=None, polarization_factor=None, dark=None, flat=None, method='bbox', unit=q_nm^-1, safe=True, normalization_factor=1.0, all=False)

Calculate the azimuthal regrouped 2d image in q(nm^-1)/chi(deg) by default

Multi algorithm implementation (tries to be bullet proof)

Parameters:
  • data (ndarray) – 2D array from the Detector/CCD camera
  • npt_rad (int) – number of points in the radial direction
  • npt_azim (int) – number of points in the azimuthal direction
  • filename (str) – output image (as edf format)
  • correctSolidAngle (bool) – correct for solid angle of each pixel if True
  • variance (ndarray) – array containing the variance of the data. If not available, no error propagation is done
  • error_model (str) – When the variance is unknown, an error model can be given: “poisson” (variance = I), “azimuthal” (variance = (I-<I>)^2)
  • radial_range ((float, float), optional) – The lower and upper range of the radial unit. If not provided, range is simply (data.min(), data.max()). Values outside the range are ignored.
  • azimuth_range ((float, float), optional) – The lower and upper range of the azimuthal angle in degree. If not provided, range is simply (data.min(), data.max()). Values outside the range are ignored.
  • mask (ndarray) – array (same size as image) with 1 for masked pixels, and 0 for valid pixels
  • dummy (float) – value for dead/masked pixels
  • delta_dummy (float) – precision for dummy value
  • polarization_factor (float) – polarization factor between -1 (vertical) and +1 (horizontal). 0 for circular polarization or random, None for no correction
  • dark (ndarray) – dark noise image
  • flat (ndarray) – flat field image
  • method (str) – can be “numpy”, “cython”, “BBox” or “splitpixel”, “lut”, “csr; “lut_ocl” and “csr_ocl” if you want to go on GPU. To Specify the device: “csr_ocl_1,2”
  • unit (pyFAI.units.Enum) – Output units, can be “q_nm^-1”, “q_A^-1”, “2th_deg”, “2th_rad”, “r_mm” for now
  • safe (bool) – Do some extra checks to ensure LUT is still valid. False is faster.
  • normalization_factor (float) – Value of a normalization monitor
  • all – if true, return many more intermediate results as a dict.
Returns:

azimuthaly regrouped intensity, q/2theta/r pos. and chi pos.

Return type:

3-tuple of ndarrays (2d, 1d, 1d)

makeHeaders(hdr='#', dark=None, flat=None, polarization_factor=None, normalization_factor=None)
Parameters:
  • hdr (str) – string used as comment in the header
  • dark – save the darks filenames (default: no)
  • flat – save the flat filenames (default: no)
  • polarization_factor (float) – the polarization factor
Returns:

the header

Return type:

str

reset()

Reset azimuthal integrator in addition to other arrays.

save1D(filename, dim1, I, error=None, dim1_unit=2th_deg, dark=None, flat=None, polarization_factor=None, normalization_factor=None)
Parameters:
  • filename (str) – the filename used to save the 1D integration
  • dim1 (numpy.ndarray) – the x coordinates of the integrated curve
  • I (numpy.mdarray) – The integrated intensity
  • error (numpy.ndarray or None) – the error bar for each intensity
  • dim1_unit (pyFAI.units.Unit) – the unit of the dim1 array
  • dark – save the darks filenames (default: no)
  • flat – save the flat filenames (default: no)
  • polarization_factor (float) – the polarization factor
  • normalization_factor (float) – the monitor value

This method save the result of a 1D integration.

save2D(filename, I, dim1, dim2, error=None, dim1_unit=2th_deg, dark=None, flat=None, polarization_factor=None, normalization_factor=None)
Parameters:
  • filename (str) – the filename used to save the 2D histogram
  • dim1 (numpy.ndarray) – the 1st coordinates of the histogram
  • dim1 – the 2nd coordinates of the histogram
  • I (numpy.mdarray) – The integrated intensity
  • error (numpy.ndarray or None) – the error bar for each intensity
  • dim1_unit (pyFAI.units.Unit) – the unit of the dim1 array
  • dark – save the darks filenames (default: no)
  • flat – save the flat filenames (default: no)
  • polarization_factor (float) – the polarization factor
  • normalization_factor (float) – the monitor value

This method save the result of a 2D integration.

saxs(*arg, **kw)

decorator that deprecates the use of a function

separate(data, npt_rad=1024, npt_azim=512, unit='2th_deg', method='splitpixel', percentile=50, mask=None, restore_mask=True)

Separate bragg signal from powder/amorphous signal using azimuthal integration, median filering and projected back before subtraction.

Parameters:
  • data – input image as numpy array
  • npt_rad – number of radial points
  • npt_azim – number of azimuthal points
  • unit – unit to be used for integration
  • method – pathway for integration and sort
  • percentile – which percentile use for cutting out
  • mask – masked out pixels array
  • restore_mask – masked pixels have the same value as input data provided
Returns:

bragg, amorphous

set_darkcurrent(dark)
set_darkfiles(files=None, method='mean')
Parameters:
  • files (str or list(str) or None) – file(s) used to compute the dark.
  • method (str) – method used to compute the dark, “mean” or “median”

Set the dark current from one or mutliple files, avaraged according to the method provided

set_empty(value)
set_flatfield(flat)
set_flatfiles(files, method='mean')
Parameters:
  • files (str or list(str) or None) – file(s) used to compute the dark.
  • method (str) – method used to compute the dark, “mean” or “median”

Set the flat field from one or mutliple files, averaged according to the method provided

setup_CSR(shape, npt, mask=None, pos0_range=None, pos1_range=None, mask_checksum=None, unit=2th_deg, split='bbox')

Prepare a look-up-table

Parameters:
  • shape ((int, int)) – shape of the dataset
  • npt (int or (int, int)) – number of points in the the output pattern
  • mask (ndarray) – array with masked pixel (1=masked)
  • pos0_range ((float, float)) – range in radial dimension
  • pos1_range ((float, float)) – range in azimuthal dimension
  • mask_checksum (int (or anything else ...)) – checksum of the mask buffer
  • unit (pyFAI.units.Enum) – use to propagate the LUT object for further checkings
  • split – Splitting scheme: valid options are “no”, “bbox”, “full”

This method is called when a look-up table needs to be set-up. The shape parameter, correspond to the shape of the original datatset. It is possible to customize the number of point of the output histogram with the npt parameter which can be either an integer for an 1D integration or a 2-tuple of integer in case of a 2D integration. The LUT will have a different shape: (npt, lut_max_size), the later parameter being calculated during the instanciation of the splitBBoxLUT class.

It is possible to prepare the LUT with a predefine mask. This operation can speedup the computation of the later integrations. Instead of applying the patch on the dataset, it is taken into account during the histogram computation. If provided the mask_checksum prevent the re-calculation of the mask. When the mask changes, its checksum is used to reset (or not) the LUT (which is a very time consuming operation !)

It is also possible to restrain the range of the 1D or 2D pattern with the pos1_range and pos2_range.

The unit parameter is just propagated to the LUT integrator for further checkings: The aim is to prevent an integration to be performed in 2th-space when the LUT was setup in q space.

setup_LUT(shape, npt, mask=None, pos0_range=None, pos1_range=None, mask_checksum=None, unit=2th_deg)

Prepare a look-up-table

Parameters:
  • shape ((int, int)) – shape of the dataset
  • npt (int or (int, int)) – number of points in the the output pattern
  • mask (ndarray) – array with masked pixel (1=masked)
  • pos0_range ((float, float)) – range in radial dimension
  • pos1_range ((float, float)) – range in azimuthal dimension
  • mask_checksum (int (or anything else ...)) – checksum of the mask buffer
  • unit (pyFAI.units.Enum) – use to propagate the LUT object for further checkings

This method is called when a look-up table needs to be set-up. The shape parameter, correspond to the shape of the original datatset. It is possible to customize the number of point of the output histogram with the npt parameter which can be either an integer for an 1D integration or a 2-tuple of integer in case of a 2D integration. The LUT will have a different shape: (npt, lut_max_size), the later parameter being calculated during the instanciation of the splitBBoxLUT class.

It is possible to prepare the LUT with a predefine mask. This operation can speedup the computation of the later integrations. Instead of applying the patch on the dataset, it is taken into account during the histogram computation. If provided the mask_checksum prevent the re-calculation of the mask. When the mask changes, its checksum is used to reset (or not) the LUT (which is a very time consuming operation !)

It is also possible to restrain the range of the 1D or 2D pattern with the pos1_range and pos2_range.

The unit parameter is just propagated to the LUT integrator for further checkings: The aim is to prevent an integration to be performed in 2th-space when the LUT was setup in q space.

xrpd(*arg, **kw)

decorator that deprecates the use of a function

xrpd2(*arg, **kw)

decorator that deprecates the use of a function

xrpd2_histogram(*arg, **kw)

decorator that deprecates the use of a function

xrpd2_numpy(*arg, **kw)

decorator that deprecates the use of a function

xrpd2_splitBBox(*arg, **kw)

decorator that deprecates the use of a function

xrpd2_splitPixel(*arg, **kw)

decorator that deprecates the use of a function

xrpd_CSR_OCL(*arg, **kw)

decorator that deprecates the use of a function

xrpd_LUT(*arg, **kw)

decorator that deprecates the use of a function

xrpd_LUT_OCL(*arg, **kw)

decorator that deprecates the use of a function

xrpd_OpenCL(*arg, **kw)

decorator that deprecates the use of a function

xrpd_cython(*arg, **kw)

decorator that deprecates the use of a function

xrpd_numpy(*arg, **kw)

decorator that deprecates the use of a function

xrpd_splitBBox(*arg, **kw)

decorator that deprecates the use of a function

xrpd_splitPixel(*arg, **kw)

decorator that deprecates the use of a function

integrate_widget Module

geometry Module

class pyFAI.geometry.Geometry(dist=1, poni1=0, poni2=0, rot1=0, rot2=0, rot3=0, pixel1=None, pixel2=None, splineFile=None, detector=None, wavelength=None)

Bases: object

This class is an azimuthal integrator based on P. Boesecke’s geometry and histogram algorithm by Manolo S. del Rio and V.A Sole

Detector is assumed to be corrected from “raster orientation” effect. It is not addressed here but rather in the Detector object or at read time. Considering there is no tilt:

  • Detector fast dimension (dim2) is supposed to be horizontal (dimension X of the image)
  • Detector slow dimension (dim1) is supposed to be vertical, upwards (dimension Y of the image)
  • The third dimension is chose such as the referential is orthonormal, so dim3 is along incoming X-ray beam

Axis 1 is along first dimension of detector (when not tilted), this is the slow dimension of the image array in C or Y x1={1,0,0}

Axis 2 is along second dimension of detector (when not tilted), this is the fast dimension of the image in C or X x2={0,1,0}

Axis 3 is along the incident X-Ray beam x3={0,0,1}

We define the 3 rotation around axis 1, 2 and 3:

rotM1 = RotationMatrix[rot1,x1] = {{1,0,0},{0,cos[rot1],-sin[rot1]},{0,sin[rot1],cos[rot1]}} rotM2 = RotationMatrix[rot2,x2] = {{cos[rot2],0,sin[rot2]},{0,1,0},{-sin[rot2],0,cos[rot2]}} rotM3 = RotationMatrix[rot3,x3] = {{cos[rot3],-sin[rot3],0},{sin[rot3],cos[rot3],0},{0,0,1}}

Rotations of the detector are applied first Rot around axis 1, then axis 2 and finally around axis 3:

R = rotM3.rotM2.rotM1

R = {{cos[rot2] cos[rot3],cos[rot3] sin[rot1] sin[rot2]-cos[rot1] sin[rot3],cos[rot1] cos[rot3] sin[rot2]+sin[rot1] sin[rot3]},
{cos[rot2] sin[rot3],cos[rot1] cos[rot3]+sin[rot1] sin[rot2] sin[rot3],-cos[rot3] sin[rot1]+cos[rot1] sin[rot2] sin[rot3]}, {-sin[rot2],cos[rot2] sin[rot1],cos[rot1] cos[rot2]}}

In Python notation:

R.x1 = [cos(rot2)*cos(rot3),cos(rot2)*sin(rot3),-sin(rot2)]

R.x2 = [cos(rot3)*sin(rot1)*sin(rot2) - cos(rot1)*sin(rot3),cos(rot1)*cos(rot3) + sin(rot1)*sin(rot2)*sin(rot3), cos(rot2)*sin(rot1)]

R.x3 = [cos(rot1)*cos(rot3)*sin(rot2) + sin(rot1)*sin(rot3),-(cos(rot3)*sin(rot1)) + cos(rot1)*sin(rot2)*sin(rot3), cos(rot1)*cos(rot2)]

  • Coordinates of the Point of Normal Incidence:

    PONI = R.{0,0,L}

    PONI = [L*(cos(rot1)*cos(rot3)*sin(rot2) + sin(rot1)*sin(rot3)),

    L*(-(cos(rot3)*sin(rot1)) + cos(rot1)*sin(rot2)*sin(rot3)),L*cos(rot1)*cos(rot2)]

  • Any pixel on detector plan at coordinate (d1, d2) in meters. Detector is at z=L

    P={d1,d2,L}

    R.P = [t1, t2, t3] t1 = R.P.x1 = d1*cos(rot2)*cos(rot3) + d2*(cos(rot3)*sin(rot1)*sin(rot2) - cos(rot1)*sin(rot3)) + L*(cos(rot1)*cos(rot3)*sin(rot2) + sin(rot1)*sin(rot3)) t2 = R.P.x2 = d1*cos(rot2)*sin(rot3) + d2*(cos(rot1)*cos(rot3) + sin(rot1)*sin(rot2)*sin(rot3)) + L*(-(cos(rot3)*sin(rot1)) + cos(rot1)*sin(rot2)*sin(rot3)) t3 = R.P.x3 = d2*cos(rot2)*sin(rot1) - d1*sin(rot2) + L*cos(rot1)*cos(rot2)

  • Distance sample (origin) to detector point (d1,d2)

    |R.P| = sqrt(pow(Abs(L*cos(rot1)*cos(rot2) + d2*cos(rot2)*sin(rot1) - d1*sin(rot2)),2) +

    pow(Abs(d1*cos(rot2)*cos(rot3) + d2*(cos(rot3)*sin(rot1)*sin(rot2) - cos(rot1)*sin(rot3)) + L*(cos(rot1)*cos(rot3)*sin(rot2) + sin(rot1)*sin(rot3))),2) + pow(Abs(d1*cos(rot2)*sin(rot3) + L*(-(cos(rot3)*sin(rot1)) + cos(rot1)*sin(rot2)*sin(rot3)) + d2*(cos(rot1)*cos(rot3) + sin(rot1)*sin(rot2)*sin(rot3))),2))

  • cos(2theta) is defined as (R.P component along x3) over the distance from origin to data point |R.P|

tth = ArcCos [-(R.P).x3/|R.P|]

tth = Arccos((-(L*cos(rot1)*cos(rot2)) - d2*cos(rot2)*sin(rot1) + d1*sin(rot2))/
sqrt(pow(Abs(L*cos(rot1)*cos(rot2) + d2*cos(rot2)*sin(rot1) - d1*sin(rot2)),2) +
pow(Abs(d1*cos(rot2)*cos(rot3) + d2*(cos(rot3)*sin(rot1)*sin(rot2) - cos(rot1)*sin(rot3)) +
L*(cos(rot1)*cos(rot3)*sin(rot2) + sin(rot1)*sin(rot3))),2) +
pow(Abs(d1*cos(rot2)*sin(rot3) + L*(-(cos(rot3)*sin(rot1)) + cos(rot1)*sin(rot2)*sin(rot3)) +

d2*(cos(rot1)*cos(rot3) + sin(rot1)*sin(rot2)*sin(rot3))),2)))

  • tan(2theta) is defined as sqrt(t1**2 + t2**2) / t3

tth = ArcTan2 [sqrt(t1**2 + t2**2) , t3 ]

Getting 2theta from it’s tangeant seems both more precise (around beam stop very far from sample) and faster by about 25% Currently there is a swich in the method to follow one path or the other.

  • Tangeant of angle chi is defined as (R.P component along x1) over (R.P component along x2). Arctan2 should be used in actual calculation

chi = ArcTan[((R.P).x1) / ((R.P).x2)]

chi = ArcTan2(d1*cos(rot2)*cos(rot3) + d2*(cos(rot3)*sin(rot1)*sin(rot2) - cos(rot1)*sin(rot3)) +
L*(cos(rot1)*cos(rot3)*sin(rot2) + sin(rot1)*sin(rot3)),
d1*cos(rot2)*sin(rot3) + L*(-(cos(rot3)*sin(rot1)) + cos(rot1)*sin(rot2)*sin(rot3)) +
d2*(cos(rot1)*cos(rot3) + sin(rot1)*sin(rot2)*sin(rot3)))
array_from_unit(shape=None, typ='center', unit=2th_deg)

Generate an array of position in different dimentions (R, Q, 2Theta)

Parameters:
  • shape (ndarray.shape) – shape of the expected array
  • typ (str) – “center”, “corner” or “delta”
  • unit (pyFAI.units.Enum) – can be Q, TTH, R for now
Returns:

R, Q or 2Theta array depending on unit

Return type:

ndarray

calc_pos_zyx(d0=None, d1=None, d2=None, param=None, corners=False, use_cython=True)

Calculate the position of a set of points in space in the sample’s centers referential.

This is usually used for calculating the pixel position in space.

Parameters:
  • d0 – altitude on the point compared to the detector (i.e. z), may be None
  • d1 – position on the detector along the slow dimention (i.e. y)
  • d2 – position on the detector along the fastest dimention (i.e. x)
  • corners – return positions on the corners (instead of center)
:return 3-tuple of nd-array, with dim0=along the beam,
dim1=along slowest dimension dim2=along fastest dimension
calc_transmission(t0, shape=None)

Defines the absorption correction for a phosphor screen or a scintillator from t0, the normal transmission of the screen.

Icor = Iobs(1-t0)/(1-exp(ln(t0)/cos(incidence)))
1-exp(ln(t0)/cos(incidence)
let t = —————————–
1 - t0

See reference on: J. Appl. Cryst. (2002). 35, 356–359 G. Wu et al. CCD phosphor

Parameters:
  • t0 – value of the normal transmission (from 0 to 1)
  • shape – shape of the array
Returns:

actual

calcfrom1d(tth, I, shape=None, mask=None, dim1_unit=2th_deg, correctSolidAngle=True, dummy=0.0, polarization_factor=None, dark=None, flat=None)

Computes a 2D image from a 1D integrated profile

Parameters:
  • tth – 1D array with radial unit
  • I – scattering intensity
  • shape – shape of the image (if not defined by the detector)
  • dim1_unit – unit for the “tth” array
  • correctSolidAngle
  • dummy – value for masked pixels
  • polarization_factor – set to true to use previously used value
  • dark – dark current correction
  • flat – flatfield corrction
Returns:

2D image reconstructed

center_array(shape=None, unit='2th')

Generate a 2D array of the given shape with (i,j) (radial angle ) for all elements.

Parameters:shape (2-tuple of integer) – expected shape
Returns:3d array with shape=(*shape,4,2) the two elements are: * dim3[0]: radial angle 2th, q, r, ... * dim3[1]: azimuthal angle chi
chi(d1, d2, path='cython')

Calculate the chi (azimuthal angle) for the centre of a pixel at coordinate d1,d2 which in the lab ref has coordinate:

X1 = p1*cos(rot2)*cos(rot3) + p2*(cos(rot3)*sin(rot1)*sin(rot2) - cos(rot1)*sin(rot3)) - L*(cos(rot1)*cos(rot3)*sin(rot2) + sin(rot1)*sin(rot3)) X2 = p1*cos(rot2)*sin(rot3) - L*(-(cos(rot3)*sin(rot1)) + cos(rot1)*sin(rot2)*sin(rot3)) + p2*(cos(rot1)*cos(rot3) + sin(rot1)*sin(rot2)*sin(rot3)) X3 = -(L*cos(rot1)*cos(rot2)) + p2*cos(rot2)*sin(rot1) - p1*sin(rot2) hence tan(Chi) = X2 / X1

Parameters:
  • d1 (float or array of them) – pixel coordinate along the 1st dimention (C convention)
  • d2 (float or array of them) – pixel coordinate along the 2nd dimention (C convention)
  • path – can be “tan” (i.e via numpy) or “cython”
Returns:

chi, the azimuthal angle in rad

chiArray(shape=None)

Generate an array of azimuthal angle chi(i,j) for all elements in the detector.

Azimuthal angles are in radians

Nota: Refers to the pixel centers !

Parameters:shape – the shape of the chi array
Returns:the chi array as numpy.ndarray
chi_corner(d1, d2)

Calculate the chi (azimuthal angle) for the corner of a pixel at coordinate d1,d2 which in the lab ref has coordinate:

X1 = p1*cos(rot2)*cos(rot3) + p2*(cos(rot3)*sin(rot1)*sin(rot2) - cos(rot1)*sin(rot3)) - L*(cos(rot1)*cos(rot3)*sin(rot2) + sin(rot1)*sin(rot3)) X2 = p1*cos(rot2)*sin(rot3) - L*(-(cos(rot3)*sin(rot1)) + cos(rot1)*sin(rot2)*sin(rot3)) + p2*(cos(rot1)*cos(rot3) + sin(rot1)*sin(rot2)*sin(rot3)) X3 = -(L*cos(rot1)*cos(rot2)) + p2*cos(rot2)*sin(rot1) - p1*sin(rot2) hence tan(Chi) = X2 / X1

Parameters:
  • d1 (float or array of them) – pixel coordinate along the 1st dimention (C convention)
  • d2 (float or array of them) – pixel coordinate along the 2nd dimention (C convention)
Returns:

chi, the azimuthal angle in rad

chia

chi array in cache

cornerArray(*arg, **kw)

decorator that deprecates the use of a function

cornerQArray(*arg, **kw)

decorator that deprecates the use of a function

cornerRArray(*arg, **kw)

decorator that deprecates the use of a function

cornerRd2Array(*arg, **kw)

decorator that deprecates the use of a function

corner_array(shape=None, unit='2th', use_cython=True)

Generate a 3D array of the given shape with (i,j) (radial angle 2th, azimuthal angle chi ) for all elements.

Parameters:shape (2-tuple of integer) – expected shape
Returns:3d array with shape=(*shape,4,2) the two elements are: * dim3[0]: radial angle 2th, q, r, ... * dim3[1]: azimuthal angle chi
correct_SA_spline
cosIncidance(d1, d2, path='cython')

Calculate the incidence angle (alpha) for current pixels (P). The poni being the point of normal incidence, it’s incidence angle is ${alpha} = 0$ hence $cos({alpha}) = 1$

Parameters:
  • d1 – 1d or 2d set of points in pixel coord
  • d2 – 1d or 2d set of points in pixel coord
Returns:

cosine of the incidence angle

del_chia()
del_dssa()
del_qa()
del_ra()
del_ttha()
delta2Theta(shape=None)

Generate a 3D array of the given shape with (i,j) with the max distance between the center and any corner in 2 theta

Parameters:shape – The shape of the detector array: 2-tuple of integer
Returns:2D-array containing the max delta angle between a pixel center and any corner in 2theta-angle (rad)
deltaChi(shape=None)

Generate a 3D array of the given shape with (i,j) with the max distance between the center and any corner in chi-angle (rad)

Parameters:shape – The shape of the detector array: 2-tuple of integer
Returns:2D-array containing the max delta angle between a pixel center and any corner in chi-angle (rad)
deltaQ(shape=None)

Generate a 2D array of the given shape with (i,j) with the max distance between the center and any corner in q_vector unit (nm^-1)

Parameters:shape – The shape of the detector array: 2-tuple of integer
Returns:array 2D containing the max delta Q between a pixel center and any corner in q_vector unit (nm^-1)
deltaR(shape=None)

Generate a 2D array of the given shape with (i,j) with the max distance between the center and any corner in radius unit (mm)

Parameters:shape – The shape of the detector array: 2-tuple of integer
Returns:array 2D containing the max delta Q between a pixel center and any corner in q_vector unit (nm^-1)
deltaRd2(shape=None)

Generate a 2D array of the given shape with (i,j) with the max distance between the center and any corner in unit: reciprocal spacing squarred (1/nm^2)

Parameters:shape – The shape of the detector array: 2-tuple of integer
Returns:array 2D containing the max delta (d*)^2 between a pixel center and any corner in reciprocal spacing squarred (1/nm^2)
delta_array(shape=None, unit='2th')

Generate a 2D array of the given shape with (i,j) (delta-radial angle) for all elements.

Parameters:shape (2-tuple of integer) – expected shape
Returns:3d array with shape=(*shape,4,2) the two elements are: * dim3[0]: radial angle 2th, q, r, ... * dim3[1]: azimuthal angle chi
diffSolidAngle(d1, d2)

Calculate the solid angle of the current pixels (P) versus the PONI (C)

Omega(P) A cos(a) SC^2 3 SC^3
dOmega = ——— = ——— x ——— = cos (a) = ——
Omega(C) SP^2 A cos(0) SP^3

cos(a) = SC/SP

Parameters:
  • d1 – 1d or 2d set of points
  • d2 – 1d or 2d set of points (same size&shape as d1)
Returns:

solid angle correction array

dist
dssa

solid angle array in cache

getFit2D()

Export geometry setup with the geometry of Fit2D

Returns:dict with parameters compatible with fit2D geometry
getPyFAI()

Export geometry setup with the geometry of PyFAI

Returns:dict with the parameter-set of the PyFAI geometry
getSPD()

get the SPD like parameter set: For geometry description see Peter Boesecke J.Appl.Cryst.(2007).40, s423–s427

Basically the main difference with pyFAI is the order of the axis which are flipped

Returns:dictionnary with those parameters: SampleDistance: distance from sample to detector at the PONI (orthogonal projection) Center_1, pixel position of the PONI along fastest axis Center_2: pixel position of the PONI along slowest axis Rot_1: rotation around the fastest axis (x) Rot_2: rotation around the slowest axis (y) Rot_3: rotation around the axis ORTHOGONAL to the detector plan PSize_1: pixel size in meter along the fastest dimention PSize_2: pixel size in meter along the slowst dimention splineFile: name of the file containing the spline BSize_1: pixel binning factor along the fastest dimention BSize_2: pixel binning factor along the slowst dimention WaveLength: wavelength used in meter
get_chia()
get_correct_solid_angle_for_spline()
get_dist()
get_dssa()
get_mask()
get_maskfile()
get_pixel1()
get_pixel2()
get_poni1()
get_poni2()
get_qa()
get_ra()
get_rot1()
get_rot2()
get_rot3()
get_shape(shape=None)

Guess what is the best shape .... :param shape: force this value (2-tuple of int) :return: 2-tuple of int

get_spline()
get_splineFile()
get_ttha()
get_wavelength()
load(filename)

Load the refined parameters from a file.

Parameters:filename (string) – name of the file to load
mask
maskfile
oversampleArray(myarray)
pixel1
pixel2
polarization(shape=None, factor=None, axis_offset=0)

Calculate the polarization correction accoding to the polarization factor:

  • If the polarization factor is None, the correction is not applied (returns 1)
  • If the polarization factor is 0 (circular polarization), the correction correspond to (1+(cos2θ)^2)/2
  • If the polarization factor is 1 (linear horizontal polarization), there is no correction in the vertical plane and a node at 2th=90, chi=0
  • If the polarization factor is -1 (linear vertical polarization), there is no correction in the horizontal plane and a node at 2th=90, chi=90
  • If the polarization is elliptical, the polarization factor varies between -1 and +1.

The axis_offset parameter allows correction for the misalignement of the polarization plane (or ellipse main axis) and the the detector’s X axis.

Parameters:
  • factor – (Ih-Iv)/(Ih+Iv): varies between 0 (no polarization) and 1 (where division by 0 could occure at 2th=90, chi=0)
  • axis_offset – Angle between the polarization main axis and detector X direction (in radians !!!)
Returns:

2D array with polarization correction array (intensity/polarisation)

poni1
poni2
positionArray(shape=None, corners=False, dtype=<class 'numpy.float64'>)

Generate an array for the pixel position given the shape of the detector.

if corners is False, the coordinates of the center of the pixel is returned in an array of shape: (shape[0], shape[1], 3) where the 3 coordinates are: * z: along incident beam, * y: to the top/sky, * x: towards the center of the ring

If is True, the corner of each pixels are then returned. the output shape is then (shape[0], shape[1], 4, 3)

Parameters:
  • shape – shape of the array expected
  • corners – set to true to receive a (...,4,3) array of corner positions
  • dtype – output format requested
Returns:

3D coodinates as nd-array of size (...,3) or (...,3) (default)

Nota: this value is not cached and actually generated on demand (costly)

qArray(shape=None)

Generate an array of the given shape with q(i,j) for all elements.

qCornerFunct(*arg, **kw)

decorator that deprecates the use of a function

qFunction(d1, d2, param=None, path='cython')

Calculates the q value for the center of a given pixel (or set of pixels) in nm-1

q = 4pi/lambda sin( 2theta / 2 )

Parameters:
  • d1 (scalar or array of scalar) – position(s) in pixel in first dimension (c order)
  • d2 (scalar or array of scalar) – position(s) in pixel in second dimension (c order)
Returns:

q in in nm^(-1)

Return type:

float or array of floats.

qa

Q array in cache

rArray(shape=None)

Generate an array of the given shape with r(i,j) for all elements; The radius r being in meters.

Parameters:shape – expected shape of the detector
Returns:2d array of the given shape with radius in m from beam center on detector.
rCornerFunct(*arg, **kw)

decorator that deprecates the use of a function

rFunction(d1, d2, param=None, path='cython')

Calculates the radius value for the center of a given pixel (or set of pixels) in m

r = distance to the incident beam
Parameters:
  • d1 (scalar or array of scalar) – position(s) in pixel in first dimension (c order)
  • d2 (scalar or array of scalar) – position(s) in pixel in second dimension (c order)
Returns:

r in in m

Return type:

float or array of floats.

ra

R array in cache

rd2Array(shape=None)

Generate an array of the given shape with (d*(i,j))^2 for all pixels.

d*^2 is the reciprocal spacing squared in inverse nm squared

Parameters:shape – expected shape of the detector

:return:2d array of the given shape with reciprocal spacing squared

read(filename)

Load the refined parameters from a file.

Parameters:filename (string) – name of the file to load
reset()

reset most arrays that are cached: used when a parameter changes.

rot1
rot2
rot3
save(filename)

Save the geometry parameters.

Parameters:filename (string) – name of the file where to save the parameters
setChiDiscAtPi()

Set the position of the discontinuity of the chi axis between -pi and +pi. This is the default behavour

setChiDiscAtZero()

Set the position of the discontinuity of the chi axis between 0 and 2pi. By default it is between pi and -pi

setFit2D(directDist, centerX, centerY, tilt=0.0, tiltPlanRotation=0.0, pixelX=None, pixelY=None, splineFile=None)

Set the Fit2D-like parameter set: For geometry description see HPR 1996 (14) pp-240

Warning: Fit2D flips automatically images depending on their file-format. By reverse engineering we noticed this behavour for Tiff and Mar345 images (at least). To obtaine correct result you will have to flip images using numpy.flipud.

Parameters:
  • direct – direct distance from sample to detector along the incident beam (in millimeter as in fit2d)
  • tilt – tilt in degrees
  • tiltPlanRotation – Rotation (in degrees) of the tilt plan arround the Z-detector axis * 0deg -> Y does not move, +X goes to Z<0 * 90deg -> X does not move, +Y goes to Z<0 * 180deg -> Y does not move, +X goes to Z>0 * 270deg -> X does not move, +Y goes to Z>0
  • pixelX,pixelY – as in fit2d they ar given in micron, not in meter
  • centerY (centerX,) – pixel position of the beam center
  • splineFile – name of the file containing the spline
setOversampling(*arg, **kw)

decorator that deprecates the use of a function

setPyFAI(**kwargs)

set the geometry from a pyFAI-like dict

setSPD(SampleDistance, Center_1, Center_2, Rot_1=0, Rot_2=0, Rot_3=0, PSize_1=None, PSize_2=None, splineFile=None, BSize_1=1, BSize_2=1, WaveLength=None)

Set the SPD like parameter set: For geometry description see Peter Boesecke J.Appl.Cryst.(2007).40, s423–s427

Basically the main difference with pyFAI is the order of the axis which are flipped

Parameters:SampleDistance – distance from sample to detector at the PONI (orthogonal projection)

:param Center_1, pixel position of the PONI along fastest axis :param Center_2: pixel position of the PONI along slowest axis :param Rot_1: rotation around the fastest axis (x) :param Rot_2: rotation around the slowest axis (y) :param Rot_3: rotation around the axis ORTHOGONAL to the detector plan :param PSize_1: pixel size in meter along the fastest dimention :param PSize_2: pixel size in meter along the slowst dimention :param splineFile: name of the file containing the spline :param BSize_1: pixel binning factor along the fastest dimention :param BSize_2: pixel binning factor along the slowst dimention :param WaveLength: wavelength used

set_chia(_)
set_correct_solid_angle_for_spline(value)
set_dist(value)
set_dssa(_)
set_mask(mask)
set_maskfile(maskfile)
set_pixel1(pixel1)
set_pixel2(pixel2)
set_poni1(value)
set_poni2(value)
set_qa(_)
set_ra(_)
set_rot1(value)
set_rot2(value)
set_rot3(value)
set_spline(spline)
set_splineFile(splineFile)
set_ttha(_)
set_wavelength(value)
classmethod sload(filename)

A static method combining the constructor and the loader from a file

Parameters:filename (string) – name of the file to load
Returns:instance of Gerometry of AzimuthalIntegrator set-up with the parameter from the file.
solidAngleArray(shape=None, order=3, absolute=False)

Generate an array for the solid angle correction given the shape of the detector.

solid_angle = cos(incidence)^3

Parameters:
  • shape – shape of the array expected
  • order – should be 3, power of the formula just obove
  • absolute – the absolute solid angle is calculated as:

SA = pix1*pix2/dist^2 * cos(incidence)^3

spline
splineFile
tth(d1, d2, param=None, path='cython')

Calculates the 2theta value for the center of a given pixel (or set of pixels)

Parameters:
  • d1 (scalar or array of scalar) – position(s) in pixel in first dimension (c order)
  • d2 (scalar or array of scalar) – position(s) in pixel in second dimension (c order)
  • path – can be “cos”, “tan” or “cython”
Returns:

2theta in radians

Return type:

float or array of floats.

tth_corner(*arg, **kw)

decorator that deprecates the use of a function

ttha

2theta array in cache

twoThetaArray(shape=None)

Generate an array of two-theta(i,j) in radians for each pixel in detector

the 2theta array values are in radians

Parameters:shape – shape of the detector
Returns:array of 2theta position in radians
wavelength
write(filename)

Save the geometry parameters.

Parameters:filename (string) – name of the file where to save the parameters

geometryRefinement Module

detectors Module

Description of all detectors with a factory to instantiate them

class pyFAI.detectors.ADSC_Q210(pixel1=5.1e-05, pixel2=5.1e-05)

Bases: pyFAI.detectors.Detector

ADSC Quantum 210r detector, 2x2 chips

Informations from http://www.adsc-xray.com/products/ccd-detectors/q210r-ccd-detector/

Question: how are the gaps handled ?

MAX_SHAPE = (4096, 4096)
aliases = ['Quantum 210']
force_pixel = True
class pyFAI.detectors.ADSC_Q270(pixel1=6.48e-05, pixel2=6.48e-05)

Bases: pyFAI.detectors.Detector

ADSC Quantum 270r detector, 2x2 chips

Informations from http://www.adsc-xray.com/products/ccd-detectors/q270-ccd-detector/

Question: how are the gaps handled ?

MAX_SHAPE = (4168, 4168)
aliases = ['Quantum 270']
force_pixel = True
class pyFAI.detectors.ADSC_Q315(pixel1=5.1e-05, pixel2=5.1e-05)

Bases: pyFAI.detectors.Detector

ADSC Quantum 315r detector, 3x3 chips

Informations from http://www.adsc-xray.com/products/ccd-detectors/q315r-ccd-detector/

Question: how are the gaps handled ?

MAX_SHAPE = (6144, 6144)
aliases = ['Quantum 315']
force_pixel = True
class pyFAI.detectors.ADSC_Q4(pixel1=8.2e-05, pixel2=8.2e-05)

Bases: pyFAI.detectors.Detector

ADSC Quantum 4r detector, 2x2 chips

Informations from http://proteincrystallography.org/detectors/adsc.php

Question: how are the gaps handled ?

MAX_SHAPE = (2304, 2304)
aliases = ['Quantum 4']
force_pixel = True
class pyFAI.detectors.Aarhus(pixel1=2.5e-05, pixel2=2.5e-05, radius=0.3)

Bases: pyFAI.detectors.Detector

Cylindrical detector made of a bent imaging-plate. Developped at the Danish university of Aarhus r = 1.2m or 0.3m

The image has to be laid-out horizontally

Nota: the detector is bending towards the sample, hence reducing the sample-detector distance. This is why z<0 (or p3<0)

TODO: update cython code for 3d detectors use expand2d instead of outer product with ones

IS_FLAT = False
MAX_SHAPE = (1000, 16000)
calc_cartesian_positions(d1=None, d2=None, center=True, use_cython=True)

Calculate the position of each pixel center in cartesian coordinate and in meter of a couple of coordinates. The half pixel offset is taken into account here !!! Adapted to Nexus detector definition

Parameters:
  • d1 (ndarray (1D or 2D)) – the Y pixel positions (slow dimension)
  • d2 (ndarray (1D or 2D)) – the X pixel positions (fast dimension)
  • center – retrieve the coordinate of the center of the pixel
  • use_cython – set to False to test Python implementeation
Returns:

position in meter of the center of each pixels.

Return type:

ndarray

d1 and d2 must have the same shape, returned array will have the same shape.

force_pixel = True
get_pixel_corners(use_cython=True)

Calculate the position of the corner of the pixels

This should be overwritten by class representing non-contiguous detector (Xpad, ...)

Returns:4D array containing: pixel index (slow dimension) pixel index (fast dimension) corner index (A, B, C or D), triangles or hexagons can be handled the same way vertex position (z,y,x)
class pyFAI.detectors.Apex2(pixel1=0.00012, pixel2=0.00012)

Bases: pyFAI.detectors.Detector

BrukerApex2 detector

Actually a derivative from the Fairchild detector with higher binning

DEFAULT_PIXEL1 = 6e-05
DEFAULT_PIXEL2 = 6e-05
MAX_SHAPE = (1024, 1024)
aliases = ['ApexII', 'Bruker']
force_pixel = True
class pyFAI.detectors.Basler(pixel=3.75e-06)

Bases: pyFAI.detectors.Detector

Basler camera are simple CCD camara over GigaE

MAX_SHAPE = (966, 1296)
aliases = ['aca1300']
force_pixel = True
class pyFAI.detectors.Detector(pixel1=None, pixel2=None, splineFile=None, max_shape=None)

Bases: object

Generic class representing a 2D detector

API_VERSION = '1.0'
IS_CONTIGUOUS = True
IS_FLAT = True
aliases = []
binning
calc_cartesian_positions(d1=None, d2=None, center=True, use_cython=True)

Calculate the position of each pixel center in cartesian coordinate and in meter of a couple of coordinates. The half pixel offset is taken into account here !!! Adapted to Nexus detector definition

Parameters:
  • d1 (ndarray (1D or 2D)) – the Y pixel positions (slow dimension)
  • d2 (ndarray (1D or 2D)) – the X pixel positions (fast dimension)
  • center – retrieve the coordinate of the center of the pixel, unless gives one corner
  • use_cython – set to False to test Python implementation
Returns:

position in meter of the center of each pixels.

Return type:

3xndarray, the later being None if IS_FLAT

d1 and d2 must have the same shape, returned array will have the same shape.

pos_z is None for flat detectors

calc_mask()

Method calculating the mask for a given detector

Detectors with gaps should overwrite this method with something actually calculating the mask!

Returns:the mask with valid pixel to 0
Return type:numpy ndarray of int8 or None
classmethod factory(name, config=None)

A kind of factory...

Parameters:
  • name (str) – name of a detector
  • config (dict or JSON representation of it.) – configuration of the detector
Returns:

an instance of the right detector, set-up if possible

Return type:

pyFAI.detectors.Detector

force_pixel = False
getFit2D()

Helper method to serialize the description of a detector using the Fit2d units

Returns:representation of the detector easy to serialize
Return type:dict
getPyFAI()

Helper method to serialize the description of a detector using the pyFAI way with everything in S.I units.

Returns:representation of the detector easy to serialize
Return type:dict
get_binning()
get_mask()
get_maskfile()
get_name()

Get a meaningful name for detector

get_pixel1()
get_pixel2()
get_pixel_corners()

Calculate the position of the corner of the pixels

This should be overwritten by class representing non-contiguous detector (Xpad, ...)

Precision float32 is ok: precision of 1µm for a detector size of 1m

Returns:4D array containing: pixel index (slow dimension) pixel index (fast dimension) corner index (A, B, C or D), triangles or hexagons can be handled the same way vertex position (z,y,x)
get_splineFile()
guess_binning(data)

Guess the binning/mode depending on the image shape :param data: 2-tuple with the shape of the image or the image with a .shape attribute.

mask
maskfile
name

Get a meaningful name for detector

pixel1
pixel2
registry = {'rayonix': <class 'pyFAI.detectors.Rayonix'>, 'imxpads70': <class 'pyFAI.detectors.ImXPadS70'>, 'rayonixmx300hs': <class 'pyFAI.detectors.RayonixMx300hs'>, 'rayonixmx225': <class 'pyFAI.detectors.RayonixMx225'>, 'quantum210': <class 'pyFAI.detectors.ADSC_Q210'>, 'pilatus2m': <class 'pyFAI.detectors.Pilatus2M'>, 'condor': <class 'pyFAI.detectors.Fairchild'>, 'pilatus300kw': <class 'pyFAI.detectors.Pilatus300kw'>, 'agilenttitan': <class 'pyFAI.detectors.Titan'>, 'titan_2k_x_2k': <class 'pyFAI.detectors.Titan'>, 'rayonixmx340hs': <class 'pyFAI.detectors.RayonixMx340hs'>, 'eiger4m': <class 'pyFAI.detectors.Eiger4M'>, 'imxpads140': <class 'pyFAI.detectors.ImXPadS140'>, 'hf_130k': <class 'pyFAI.detectors.HF_130K'>, 'rayonix_mx225': <class 'pyFAI.detectors.RayonixMx225'>, 'pixium4700detector': <class 'pyFAI.detectors.Pixium'>, 'xpad_s540_flat': <class 'pyFAI.detectors.Xpad_flat'>, 'quantum_4': <class 'pyFAI.detectors.ADSC_Q4'>, 'rayonixmx300': <class 'pyFAI.detectors.RayonixMx300'>, 'rayonix_sx165': <class 'pyFAI.detectors.RayonixSx165'>, 'mar3450': <class 'pyFAI.detectors.Mar345'>, 'xpads540flat': <class 'pyFAI.detectors.Xpad_flat'>, 'thales_electronics': <class 'pyFAI.detectors.Pixium'>, 'rayonix_lx255': <class 'pyFAI.detectors.RayonixLx255'>, 'rayonix_sx85hs': <class 'pyFAI.detectors.RayonixSx85hs'>, 'mar133': <class 'pyFAI.detectors.Rayonix133'>, 'hf-130k': <class 'pyFAI.detectors.HF_130K'>, 'detector': <class 'pyFAI.detectors.Detector'>, 'adsc_q210': <class 'pyFAI.detectors.ADSC_Q210'>, 'pilatus100k': <class 'pyFAI.detectors.Pilatus100k'>, 'oxd_titan': <class 'pyFAI.detectors.Titan'>, 'hf_262k': <class 'pyFAI.detectors.HF_262k'>, 'adsc_q4': <class 'pyFAI.detectors.ADSC_Q4'>, 'rayonixsx30hs': <class 'pyFAI.detectors.RayonixSx30hs'>, 'bruker': <class 'pyFAI.detectors.Apex2'>, 'rayonixmx425hs': <class 'pyFAI.detectors.RayonixMx425hs'>, 'rayonixmx325': <class 'pyFAI.detectors.RayonixMx325'>, 'rayonixsx165': <class 'pyFAI.detectors.RayonixSx165'>, 'rayonix_mx300': <class 'pyFAI.detectors.RayonixMx300'>, 'thaleselectronics': <class 'pyFAI.detectors.Pixium'>, 'rayonix_mx300hs': <class 'pyFAI.detectors.RayonixMx300hs'>, 'hf-2.4m': <class 'pyFAI.detectors.HF_2M'>, 'rayonix_mx340hs': <class 'pyFAI.detectors.RayonixMx340hs'>, 'xpad_flat': <class 'pyFAI.detectors.Xpad_flat'>, 'rayonix_mx225hs': <class 'pyFAI.detectors.RayonixMx225hs'>, 'rayonixlx170': <class 'pyFAI.detectors.RayonixLx170'>, 'quantum4': <class 'pyFAI.detectors.ADSC_Q4'>, 'oxdtitan': <class 'pyFAI.detectors.Titan'>, 'rayonix133': <class 'pyFAI.detectors.Rayonix133'>, 'imxpad_s10': <class 'pyFAI.detectors.ImXPadS10'>, 'mar165': <class 'pyFAI.detectors.RayonixSx165'>, 'mar345': <class 'pyFAI.detectors.Mar345'>, 'aca1300': <class 'pyFAI.detectors.Basler'>, 'pilatus1m': <class 'pyFAI.detectors.Pilatus1M'>, 'pixium_4700_detector': <class 'pyFAI.detectors.Pixium'>, 'rayonixmx225hs': <class 'pyFAI.detectors.RayonixMx225hs'>, 'titan2kx2k': <class 'pyFAI.detectors.Titan'>, 'pilatus6m': <class 'pyFAI.detectors.Pilatus6M'>, 'eiger16m': <class 'pyFAI.detectors.Eiger16M'>, 'adsc_q270': <class 'pyFAI.detectors.ADSC_Q270'>, 'quantum315': <class 'pyFAI.detectors.ADSC_Q315'>, 'rayonix_mx170': <class 'pyFAI.detectors.RayonixMx170'>, 'pilatuscdte2m': <class 'pyFAI.detectors.PilatusCdTe2M'>, 'raspberry': <class 'pyFAI.detectors.RaspberryPi'>, 'eiger1m': <class 'pyFAI.detectors.Eiger1M'>, 'imxpads10': <class 'pyFAI.detectors.ImXPadS10'>, 'eiger9m': <class 'pyFAI.detectors.Eiger9M'>, 'fairchild': <class 'pyFAI.detectors.Fairchild'>, 'quantum_210': <class 'pyFAI.detectors.ADSC_Q210'>, 'fairchild_condor_486:90': <class 'pyFAI.detectors.Fairchild'>, 'quantum270': <class 'pyFAI.detectors.ADSC_Q270'>, 'hf_1m': <class 'pyFAI.detectors.HF_1M'>, 'apexii': <class 'pyFAI.detectors.Apex2'>, 'imxpad_s140': <class 'pyFAI.detectors.ImXPadS140'>, 'quantum_315': <class 'pyFAI.detectors.ADSC_Q315'>, 'agilent_titan': <class 'pyFAI.detectors.Titan'>, 'pixium': <class 'pyFAI.detectors.Pixium'>, 'rayonix_lx255hs': <class 'pyFAI.detectors.RayonixLx255'>, 'basler': <class 'pyFAI.detectors.Basler'>, 'rayonixlx255hs': <class 'pyFAI.detectors.RayonixLx255'>, 'perkinelmer': <class 'pyFAI.detectors.Perkin'>, 'd5': <class 'pyFAI.detectors.Xpad_flat'>, 'mar_345': <class 'pyFAI.detectors.Mar345'>, 'pilatuscdte1m': <class 'pyFAI.detectors.PilatusCdTe1M'>, 'titan': <class 'pyFAI.detectors.Titan'>, 'rayonixlx255': <class 'pyFAI.detectors.RayonixLx255'>, 'pi': <class 'pyFAI.detectors.RaspberryPi'>, 'dexela2923': <class 'pyFAI.detectors.Dexela2923'>, 'rayonix_mx425hs': <class 'pyFAI.detectors.RayonixMx425hs'>, 'aarhus': <class 'pyFAI.detectors.Aarhus'>, 'perkindetector': <class 'pyFAI.detectors.Perkin'>, 'rayonixmx170': <class 'pyFAI.detectors.RayonixMx170'>, 'dexela_2923': <class 'pyFAI.detectors.Dexela2923'>, 'rayonixsx85hs': <class 'pyFAI.detectors.RayonixSx85hs'>, 'pilatuscdte300kw': <class 'pyFAI.detectors.PilatusCdTe300kw'>, 'raspberrypi': <class 'pyFAI.detectors.RaspberryPi'>, 'rayonix_lx170': <class 'pyFAI.detectors.RayonixLx170'>, 'apex2': <class 'pyFAI.detectors.Apex2'>, 'hf_2m': <class 'pyFAI.detectors.HF_2M'>, 'rayonix_sx200': <class 'pyFAI.detectors.RayonixSx200'>, 'hf-9.4m': <class 'pyFAI.detectors.HF_9M'>, 'hf-262k': <class 'pyFAI.detectors.HF_262k'>, 'hf_9m': <class 'pyFAI.detectors.HF_9M'>, 'imxpad_s70': <class 'pyFAI.detectors.ImXPadS70'>, 'quantum_270': <class 'pyFAI.detectors.ADSC_Q270'>, 'pilatuscdte300k': <class 'pyFAI.detectors.PilatusCdTe300k'>, 'pilatus300k': <class 'pyFAI.detectors.Pilatus300k'>, 'adsc_q315': <class 'pyFAI.detectors.ADSC_Q315'>, 'rayonix_sx30hs': <class 'pyFAI.detectors.RayonixSx30hs'>, 'hf_4m': <class 'pyFAI.detectors.HF_4M'>, 'pilatus200k': <class 'pyFAI.detectors.Pilatus200k'>, 'perkin': <class 'pyFAI.detectors.Perkin'>, 'perkin_detector': <class 'pyFAI.detectors.Perkin'>, 'hf-4m': <class 'pyFAI.detectors.HF_4M'>, 'fairchildcondor486:90': <class 'pyFAI.detectors.Fairchild'>, 'rayonix_mx325': <class 'pyFAI.detectors.RayonixMx325'>, 'perkin_elmer': <class 'pyFAI.detectors.Perkin'>, 'hf-1m': <class 'pyFAI.detectors.HF_1M'>, 'rayonixsx200': <class 'pyFAI.detectors.RayonixSx200'>}
save(filename)

Saves the detector description into a NeXus file, adapted from: http://download.nexusformat.org/sphinx/classes/base_classes/NXdetector.html Main differences:

  • differentiate pixel center from pixel corner offsets
  • store all offsets are ndarray according to slow/fast dimension (not x, y)
Parameters:filename – name of the file on the disc
setFit2D(**kwarg)

Twin method of getFit2D: setup a detector instance according to a description

Parameters:kwarg – dictionary containing pixel1, pixel2 and splineFile
setPyFAI(**kwarg)

Twin method of getPyFAI: setup a detector instance according to a description

Parameters:kwarg – dictionary containing detector, pixel1, pixel2 and splineFile
set_binning(bin_size=(1, 1))

Set the “binning” of the detector,

Parameters:bin_size ((int, int)) – binning as integer or tuple of integers.
set_config(config)

Sets the configuration of the detector. This implies: - Orientation: integers - Binning - ROI

The configuration is either a python dictionary or a JSON string or a file containing this JSON configuration

keys in that dictionary are : “orientation”: integers from 0 to 7 “binning”: integer or 2-tuple of integers. If only one integer is provided, “offset”: coordinate (in pixels) of the start of the detector

set_dx(dx=None)

set the pixel-wise displacement along X (dim2):

set_dy(dy=None)

set the pixel-wise displacement along Y (dim1):

set_mask(mask)
set_maskfile(maskfile)
set_pixel1(value)
set_pixel2(value)
set_splineFile(splineFile)
splineFile
uniform_pixel = True
class pyFAI.detectors.DetectorMeta(name, bases, dct)

Bases: type

Metaclass used to register all detector classes inheriting from Detector

class pyFAI.detectors.Dexela2923(pixel1=7.5e-05, pixel2=7.5e-05)

Bases: pyFAI.detectors.Detector

Dexela CMOS family detector

MAX_SHAPE = (3888, 3072)
aliases = ['Dexela 2923']
force_pixel = True
class pyFAI.detectors.Eiger(pixel1=7.5e-05, pixel2=7.5e-05, max_shape=None, module_size=None)

Bases: pyFAI.detectors.Detector

Eiger detector: generic description containing mask algorithm

MODULE_GAP = (37, 10)
MODULE_SIZE = (514, 1030)
calc_cartesian_positions(d1=None, d2=None, center=True, use_cython=True)

Calculate the position of each pixel center in cartesian coordinate and in meter of a couple of coordinates. The half pixel offset is taken into account here !!!

Parameters:
  • d1 (ndarray (1D or 2D)) – the Y pixel positions (slow dimension)
  • d2 (ndarray (1D or 2D)) – the X pixel positions (fast dimension)
Returns:

p1, p2 position in meter of the center of each pixels.

Return type:

2-tuple of numpy.ndarray

d1 and d2 must have the same shape, returned array will have the same shape.

calc_mask()

Returns a generic mask for Pilatus detectors...

force_pixel = True
class pyFAI.detectors.Eiger16M(pixel1=7.5e-05, pixel2=7.5e-05, max_shape=None, module_size=None)

Bases: pyFAI.detectors.Eiger

Eiger 16M detector

MAX_SHAPE = (4371, 4150)
class pyFAI.detectors.Eiger1M(pixel1=7.5e-05, pixel2=7.5e-05, max_shape=None, module_size=None)

Bases: pyFAI.detectors.Eiger

Eiger 1M detector

MAX_SHAPE = (1065, 1030)
class pyFAI.detectors.Eiger4M(pixel1=7.5e-05, pixel2=7.5e-05, max_shape=None, module_size=None)

Bases: pyFAI.detectors.Eiger

Eiger 4M detector

MAX_SHAPE = (2167, 2070)
class pyFAI.detectors.Eiger9M(pixel1=7.5e-05, pixel2=7.5e-05, max_shape=None, module_size=None)

Bases: pyFAI.detectors.Eiger

Eiger 9M detector

MAX_SHAPE = (3269, 3110)
class pyFAI.detectors.FReLoN(splineFile=None)

Bases: pyFAI.detectors.Detector

FReLoN detector: The spline is mandatory to correct for geometric distortion of the taper

TODO: create automatically a mask that removes pixels out of the “valid reagion”

calc_mask()

Returns a generic mask for Frelon detectors... All pixels which (center) turns to be out of the valid region are by default discarded

class pyFAI.detectors.Fairchild(pixel1=1.5e-05, pixel2=1.5e-05)

Bases: pyFAI.detectors.Detector

Fairchild Condor 486:90 detector

MAX_SHAPE = (4096, 4096)
aliases = ['Fairchild', 'Condor', 'Fairchild Condor 486:90']
force_pixel = True
uniform_pixel = True
class pyFAI.detectors.HF_130K(pixel1=0.00015, pixel2=0.00015)

Bases: pyFAI.detectors.Detector

ADSC HF-130K 1 module

Informations from http://www.adsc-xray.com/products/pixel-array-detectors/hf-130k/

MAX_SHAPE = (256, 512)
aliases = ['HF-130k']
force_pixel = True
class pyFAI.detectors.HF_1M(pixel1=0.00015, pixel2=0.00015)

Bases: pyFAI.detectors.Detector

ADSC HF-1M 2x4 modules

Informations from http://www.adsc-xray.com/products/pixel-array-detectors/hf-1m/

Nota: gaps between modules is not known/described

MAX_SHAPE = (1024, 1024)
aliases = ['HF-1M']
force_pixel = True
class pyFAI.detectors.HF_262k(pixel1=0.00015, pixel2=0.00015)

Bases: pyFAI.detectors.Detector

ADSC HF-262k 2 module

Informations from http://www.adsc-xray.com/products/pixel-array-detectors/hf-262k/

Nota: gaps between modules is not known/described

MAX_SHAPE = (512, 512)
aliases = ['HF-262k']
force_pixel = True
class pyFAI.detectors.HF_2M(pixel1=0.00015, pixel2=0.00015)

Bases: pyFAI.detectors.Detector

ADSC HF-1M 3x6 modules

Informations from http://www.adsc-xray.com/products/pixel-array-detectors/hf-2.4m/

Nota: gaps between modules is not known/described

MAX_SHAPE = (1536, 1536)
aliases = ['HF-2.4M']
force_pixel = True
class pyFAI.detectors.HF_4M(pixel1=0.00015, pixel2=0.00015)

Bases: pyFAI.detectors.Detector

ADSC HF-4M 4x8 modules

Informations from http://www.adsc-xray.com/products/pixel-array-detectors/hf-4m/

MAX_SHAPE = (2048, 2048)
aliases = ['HF-4M']
force_pixel = True
class pyFAI.detectors.HF_9M(pixel1=0.00015, pixel2=0.00015)

Bases: pyFAI.detectors.Detector

ADSC HF-130K 1 module

Informations from http://www.adsc-xray.com/products/pixel-array-detectors/hf-9-4m/

MAX_SHAPE = (3072, 3072)
aliases = ['HF-9.4M']
force_pixel = True
class pyFAI.detectors.ImXPadS10(pixel1=0.00013, pixel2=0.00013, max_shape=None, module_size=None)

Bases: pyFAI.detectors.Detector

ImXPad detector: ImXPad s10 detector with 1x1modules

BORDER_SIZE_RELATIVE = 2.5
MAX_SHAPE = (120, 80)
MODULE_SIZE = (120, 80)
PIXEL_SIZE = (0.00013, 0.00013)
aliases = ['Imxpad S10']
calc_cartesian_positions(d1=None, d2=None, center=True, use_cython=True)

Calculate the position of each pixel center in cartesian coordinate and in meter of a couple of coordinates. The half pixel offset is taken into account here !!!

Parameters:
  • d1 (ndarray (1D or 2D)) – the Y pixel positions (slow dimension)
  • d2 (ndarray (1D or 2D)) – the X pixel positions (fast dimension)
Returns:

position in meter of the center of each pixels.

Return type:

ndarray

d1 and d2 must have the same shape, returned array will have the same shape.

calc_mask()

Calculate the mask

calc_pixels_edges()

Calculate the position of the pixel edges

force_pixel = True
get_pixel_corners()

Calculate the position of the corner of the pixels

This should be overwritten by class representing non-contiguous detector (Xpad, ...)

Precision float32 is ok: precision of 1µm for a detector size of 1m

Returns:4D array containing: pixel index (slow dimension) pixel index (fast dimension) corner index (A, B, C or D), triangles or hexagons can be handled the same way vertex position (z,y,x)
uniform_pixel = False
class pyFAI.detectors.ImXPadS140(pixel1=0.00013, pixel2=0.00013)

Bases: pyFAI.detectors.ImXPadS10

ImXPad detector: ImXPad s140 detector with 2x7modules

BORDER_PIXEL_SIZE_RELATIVE = 2.5
MAX_SHAPE = (240, 560)
MODULE_SIZE = (120, 80)
PIXEL_SIZE = (0.00013, 0.00013)
aliases = ['Imxpad S140']
force_pixel = True
class pyFAI.detectors.ImXPadS70(pixel1=0.00013, pixel2=0.00013)

Bases: pyFAI.detectors.ImXPadS10

ImXPad detector: ImXPad s70 detector with 1x7modules

BORDER_SIZE_RELATIVE = 2.5
MAX_SHAPE = (120, 560)
MODULE_SIZE = (120, 80)
PIXEL_EDGES = None
PIXEL_SIZE = (0.00013, 0.00013)
aliases = ['Imxpad S70']
force_pixel = True
class pyFAI.detectors.Mar345(pixel1=0.0001, pixel2=0.0001)

Bases: pyFAI.detectors.Detector

Mar345 Imaging plate detector

In this detector, pixels are always square The valid image size are 2300, 2000, 1600, 1200, 3450, 3000, 2400, 1800

MAX_SHAPE = (3450, 3450)
VALID_SIZE = {2000: 0.00015, 1600: 0.00015, 3000: 0.0001, 2400: 0.0001, 3450: 0.0001, 1200: 0.00015, 2300: 0.00015, 1800: 0.0001}
aliases = ['MAR 345', 'Mar3450']
calc_mask()
force_pixel = True
guess_binning(data)

Guess the binning/mode depending on the image shape :param data: 2-tuple with the shape of the image or the image with a .shape attribute.

class pyFAI.detectors.NexusDetector(filename=None)

Bases: pyFAI.detectors.Detector

Class representing a 2D detector loaded from a NeXus file

getFit2D()

Helper method to serialize the description of a detector using the Fit2d units

Returns:representation of the detector easy to serialize
Return type:dict
getPyFAI()

Helper method to serialize the description of a detector using the pyFAI way with everything in S.I units.

Returns:representation of the detector easy to serialize
Return type:dict
load(filename)

Loads the detector description from a NeXus file, adapted from: http://download.nexusformat.org/sphinx/classes/base_classes/NXdetector.html

Parameters:filename – name of the file on the disk
classmethod sload(filename)

Instantiate the detector description from a NeXus file, adapted from: http://download.nexusformat.org/sphinx/classes/base_classes/NXdetector.html

Parameters:filename – name of the file on the disk
Returns:Detector instance
class pyFAI.detectors.Perkin(pixel1=0.0002, pixel2=0.0002)

Bases: pyFAI.detectors.Detector

Perkin detector

DEFAULT_PIXEL1 = 0.0002
DEFAULT_PIXEL2 = 0.0002
MAX_SHAPE = (4096, 4096)
aliases = ['Perkin detector', 'Perkin Elmer']
force_pixel = True
class pyFAI.detectors.Pilatus(pixel1=0.000172, pixel2=0.000172, max_shape=None, module_size=None, x_offset_file=None, y_offset_file=None)

Bases: pyFAI.detectors.Detector

Pilatus detector: generic description containing mask algorithm

Sub-classed by Pilatus1M, Pilatus2M and Pilatus6M

MODULE_GAP = (17, 7)
MODULE_SIZE = (195, 487)
calc_cartesian_positions(d1=None, d2=None, center=True, use_cython=True)

Calculate the position of each pixel center in cartesian coordinate and in meter of a couple of coordinates. The half pixel offset is taken into account here !!!

Parameters:
  • d1 (ndarray (1D or 2D)) – the Y pixel positions (slow dimension)
  • d2 (ndarray (1D or 2D)) – the X pixel positions (fast dimension)
Returns:

position in meter of the center of each pixels.

Return type:

ndarray

d1 and d2 must have the same shape, returned array will have the same shape.

calc_mask()

Returns a generic mask for Pilatus detectors...

force_pixel = True
get_splineFile()
set_splineFile(splineFile=None)

In this case splinefile is a couple filenames

splineFile
class pyFAI.detectors.Pilatus100k(pixel1=0.000172, pixel2=0.000172, max_shape=None, module_size=None, x_offset_file=None, y_offset_file=None)

Bases: pyFAI.detectors.Pilatus

Pilatus 100k detector

MAX_SHAPE = (195, 487)
class pyFAI.detectors.Pilatus1M(pixel1=0.000172, pixel2=0.000172, max_shape=None, module_size=None, x_offset_file=None, y_offset_file=None)

Bases: pyFAI.detectors.Pilatus

Pilatus 1M detector

MAX_SHAPE = (1043, 981)
class pyFAI.detectors.Pilatus200k(pixel1=0.000172, pixel2=0.000172, max_shape=None, module_size=None, x_offset_file=None, y_offset_file=None)

Bases: pyFAI.detectors.Pilatus

Pilatus 200k detector

MAX_SHAPE = (407, 487)
class pyFAI.detectors.Pilatus2M(pixel1=0.000172, pixel2=0.000172, max_shape=None, module_size=None, x_offset_file=None, y_offset_file=None)

Bases: pyFAI.detectors.Pilatus

Pilatus 2M detector

MAX_SHAPE = (1679, 1475)
class pyFAI.detectors.Pilatus300k(pixel1=0.000172, pixel2=0.000172, max_shape=None, module_size=None, x_offset_file=None, y_offset_file=None)

Bases: pyFAI.detectors.Pilatus

Pilatus 300k detector

MAX_SHAPE = (619, 487)
class pyFAI.detectors.Pilatus300kw(pixel1=0.000172, pixel2=0.000172, max_shape=None, module_size=None, x_offset_file=None, y_offset_file=None)

Bases: pyFAI.detectors.Pilatus

Pilatus 300k-wide detector

MAX_SHAPE = (195, 1475)
class pyFAI.detectors.Pilatus6M(pixel1=0.000172, pixel2=0.000172)

Bases: pyFAI.detectors.Pilatus

Pilatus 6M detector

MAX_SHAPE = (2527, 2463)
class pyFAI.detectors.PilatusCdTe(pixel1=0.000172, pixel2=0.000172, max_shape=None, module_size=None, x_offset_file=None, y_offset_file=None)

Bases: pyFAI.detectors.Pilatus

Pilatus CdTe detector: Like the Pilatus with an extra 3 pixel in the middle of every module (vertically)

calc_mask()

Returns a generic mask for Pilatus detectors...

class pyFAI.detectors.PilatusCdTe1M(pixel1=0.000172, pixel2=0.000172, max_shape=None, module_size=None, x_offset_file=None, y_offset_file=None)

Bases: pyFAI.detectors.PilatusCdTe

Pilatus CdTe 1M detector

MAX_SHAPE = (1043, 981)
class pyFAI.detectors.PilatusCdTe2M(pixel1=0.000172, pixel2=0.000172, max_shape=None, module_size=None, x_offset_file=None, y_offset_file=None)

Bases: pyFAI.detectors.PilatusCdTe

Pilatus CdTe 2M detector

MAX_SHAPE = (1679, 1475)
class pyFAI.detectors.PilatusCdTe300k(pixel1=0.000172, pixel2=0.000172, max_shape=None, module_size=None, x_offset_file=None, y_offset_file=None)

Bases: pyFAI.detectors.PilatusCdTe

Pilatus CdTe 300k detector

MAX_SHAPE = (619, 487)
class pyFAI.detectors.PilatusCdTe300kw(pixel1=0.000172, pixel2=0.000172, max_shape=None, module_size=None, x_offset_file=None, y_offset_file=None)

Bases: pyFAI.detectors.PilatusCdTe

Pilatus CdTe 300k-wide detector

MAX_SHAPE = (195, 1475)
class pyFAI.detectors.Pixium(pixel1=0.000308, pixel2=0.000308)

Bases: pyFAI.detectors.Detector

PIXIUM 4700 detector

High energy X ray diffraction using the Pixium 4700 flat panel detector J E Daniels, M Drakopoulos, et al.; Journal of Synchrotron Radiation 16(Pt 4):463-8 · August 2009

DEFAULT_PIXEL1 = 0.000154
DEFAULT_PIXEL2 = 0.000154
MAX_SHAPE = (1910, 2480)
aliases = ['Pixium 4700 detector', 'Thales Electronics']
force_pixel = True
class pyFAI.detectors.RaspberryPi(pixel1=1.4e-06, pixel2=1.4e-06)

Bases: pyFAI.detectors.Detector

5 Mpix detector from Raspberry Pi

MAX_SHAPE = (1944, 2592)
aliases = ['Raspberry', 'Pi']
force_pixel = True
class pyFAI.detectors.Rayonix(pixel1=3.2e-05, pixel2=3.2e-05)

Bases: pyFAI.detectors.Detector

BINNED_PIXEL_SIZE = {1: 3.2e-05}
MAX_SHAPE = (4096, 4096)
binning
force_pixel = True
get_binning()
guess_binning(data)

Guess the binning/mode depending on the image shape :param data: 2-tuple with the shape of the image or the image with a .shape attribute.

set_binning(bin_size=(1, 1))

Set the “binning” of the detector,

Parameters:bin_size (int or (int, int)) – set the binning of the detector
class pyFAI.detectors.Rayonix133(pixel1=6.4e-05, pixel2=6.4e-05)

Bases: pyFAI.detectors.Rayonix

Rayonix 133 2D CCD detector detector also known as mar133

Personnal communication from M. Blum

What should be the default binning factor for those cameras ?

Circular detector

BINNED_PIXEL_SIZE = {8: 0.000256, 1: 3.2e-05, 2: 6.4e-05, 4: 0.000128}
MAX_SHAPE = (4096, 4096)
aliases = ['MAR133']
calc_mask()

Circular mask

force_pixel = True
class pyFAI.detectors.RayonixLx170(pixel1=4.42708e-05, pixel2=4.42708e-05)

Bases: pyFAI.detectors.Rayonix

Rayonix lx170 2d CCD Detector (2x1 CCDs).

Nota: this is the same for lx170hs

BINNED_PIXEL_SIZE = {1: 4.42708e-05, 2: 8.85417e-05, 3: 0.0001328125, 4: 0.0001770833, 5: 0.0002213542, 6: 0.000265625, 8: 0.0003541667, 10: 0.0004427083}
MAX_SHAPE = (1920, 3840)
aliases = ['Rayonix lx170']
force_pixel = True
class pyFAI.detectors.RayonixLx255(pixel1=4.42708e-05, pixel2=4.42708e-05)

Bases: pyFAI.detectors.Rayonix

Rayonix lx255 2d Detector (3x1 CCDs)

Nota: this detector is also called lx255hs

BINNED_PIXEL_SIZE = {1: 4.42708e-05, 2: 8.85417e-05, 3: 0.0001328125, 4: 0.0001770833, 5: 0.0002213542, 6: 0.000265625, 8: 0.0003541667, 10: 0.0004427083}
MAX_SHAPE = (1920, 5760)
aliases = ['Rayonix lx255', 'Rayonix lx255hs']
class pyFAI.detectors.RayonixMx170(pixel1=4.42708e-05, pixel2=4.42708e-05)

Bases: pyFAI.detectors.Rayonix

Rayonix mx170 2d CCD Detector (2x2 CCDs).

Nota: this is the same for mx170hs

BINNED_PIXEL_SIZE = {1: 4.42708e-05, 2: 8.85417e-05, 3: 0.0001328125, 4: 0.0001770833, 5: 0.0002213542, 6: 0.000265625, 8: 0.0003541667, 10: 0.0004427083}
MAX_SHAPE = (3840, 3840)
aliases = ['Rayonix mx170']
class pyFAI.detectors.RayonixMx225(pixel1=7.3242e-05, pixel2=7.3242e-05)

Bases: pyFAI.detectors.Rayonix

Rayonix mx225 2D CCD detector detector

Nota: this is the same definition for mx225he Personnal communication from M. Blum

BINNED_PIXEL_SIZE = {8: 0.000292969, 1: 3.6621e-05, 2: 7.3242e-05, 3: 0.000109971, 4: 0.000146484}
MAX_SHAPE = (6144, 6144)
aliases = ['Rayonix mx225']
force_pixel = True
class pyFAI.detectors.RayonixMx225hs(pixel1=7.8125e-05, pixel2=7.8125e-05)

Bases: pyFAI.detectors.Rayonix

Rayonix mx225hs 2D CCD detector detector

Pixel size from a personnal communication from M. Blum

BINNED_PIXEL_SIZE = {1: 3.90625e-05, 2: 7.8125e-05, 3: 0.0001171875, 4: 0.00015625, 5: 0.0001953125, 6: 0.000234375, 8: 0.0003125, 10: 0.000390625}
MAX_SHAPE = (5760, 5760)
aliases = ['Rayonix mx225hs']
force_pixel = True
class pyFAI.detectors.RayonixMx300(pixel1=7.3242e-05, pixel2=7.3242e-05)

Bases: pyFAI.detectors.Rayonix

Rayonix mx300 2D detector (4x4 CCDs)

Pixel size from a personnal communication from M. Blum

BINNED_PIXEL_SIZE = {8: 0.000292969, 1: 3.6621e-05, 2: 7.3242e-05, 3: 0.000109971, 4: 0.000146484}
MAX_SHAPE = (8192, 8192)
aliases = ['Rayonix mx300']
force_pixel = True
class pyFAI.detectors.RayonixMx300hs(pixel1=7.8125e-05, pixel2=7.8125e-05)

Bases: pyFAI.detectors.Rayonix

Rayonix mx300hs 2D detector (4x4 CCDs)

Pixel size from a personnal communication from M. Blum

BINNED_PIXEL_SIZE = {1: 3.90625e-05, 2: 7.8125e-05, 3: 0.0001171875, 4: 0.00015625, 5: 0.0001953125, 6: 0.000234375, 8: 0.0003125, 10: 0.000390625}
MAX_SHAPE = (7680, 7680)
aliases = ['Rayonix mx300hs']
force_pixel = True
class pyFAI.detectors.RayonixMx325(pixel1=7.9346e-05, pixel2=7.9346e-05)

Bases: pyFAI.detectors.Rayonix

Rayonix mx325 and mx325he 2D detector (4x4 CCD chips)

Pixel size from a personnal communication from M. Blum

BINNED_PIXEL_SIZE = {8: 0.000317383, 1: 3.9673e-05, 2: 7.9346e-05, 3: 0.000119135, 4: 0.000158691}
MAX_SHAPE = (8192, 8192)
aliases = ['Rayonix mx325']
class pyFAI.detectors.RayonixMx340hs(pixel1=8.85417e-05, pixel2=8.85417e-05)

Bases: pyFAI.detectors.Rayonix

Rayonix mx340hs 2D detector (4x4 CCDs)

Pixel size from a personnal communication from M. Blum

BINNED_PIXEL_SIZE = {1: 4.42708e-05, 2: 8.85417e-05, 3: 0.0001328125, 4: 0.0001770833, 5: 0.0002213542, 6: 0.000265625, 8: 0.0003541667, 10: 0.0004427083}
MAX_SHAPE = (7680, 7680)
aliases = ['Rayonix mx340hs']
force_pixel = True
class pyFAI.detectors.RayonixMx425hs(pixel1=4.42708e-05, pixel2=4.42708e-05)

Bases: pyFAI.detectors.Rayonix

Rayonix mx425hs 2D CCD camera (5x5 CCD chip)

Pixel size from a personnal communication from M. Blum

BINNED_PIXEL_SIZE = {1: 4.42708e-05, 2: 8.85417e-05, 3: 0.0001328125, 4: 0.0001770833, 5: 0.0002213542, 6: 0.000265625, 8: 0.0003541667, 10: 0.0004427083}
MAX_SHAPE = (9600, 9600)
aliases = ['Rayonix mx425hs']
class pyFAI.detectors.RayonixSx165(pixel1=3.95e-05, pixel2=3.95e-05)

Bases: pyFAI.detectors.Rayonix

Rayonix sx165 2d Detector also known as MAR165.

Circular detector

BINNED_PIXEL_SIZE = {8: 0.000316, 1: 3.95e-05, 2: 7.9e-05, 3: 0.000118616, 4: 0.000158}
MAX_SHAPE = (4096, 4096)
aliases = ['MAR165', 'Rayonix Sx165']
calc_mask()

Circular mask

force_pixel = True
class pyFAI.detectors.RayonixSx200(pixel1=4.8e-05, pixel2=4.8e-05)

Bases: pyFAI.detectors.Rayonix

Rayonix sx200 2d CCD Detector.

Pixel size are personnal communication from M. Blum.

BINNED_PIXEL_SIZE = {8: 0.000384, 1: 4.8e-05, 2: 9.6e-05, 3: 0.000144, 4: 0.000192}
MAX_SHAPE = (4096, 4096)
aliases = ['Rayonix sx200']
class pyFAI.detectors.RayonixSx30hs(pixel1=1.5625e-05, pixel2=1.5625e-05)

Bases: pyFAI.detectors.Rayonix

Rayonix sx30hs 2D CCD camera (1 CCD chip)

Pixel size from a personnal communication from M. Blum

BINNED_PIXEL_SIZE = {1: 1.5625e-05, 2: 3.125e-05, 3: 4.6875e-05, 4: 6.25e-05, 5: 7.8125e-05, 6: 9.375e-05, 8: 0.000125, 10: 0.00015625}
MAX_SHAPE = (1920, 1920)
aliases = ['Rayonix Sx30hs']
class pyFAI.detectors.RayonixSx85hs(pixel1=4.42708e-05, pixel2=4.42708e-05)

Bases: pyFAI.detectors.Rayonix

Rayonix sx85hs 2D CCD camera (1 CCD chip)

Pixel size from a personnal communication from M. Blum

BINNED_PIXEL_SIZE = {1: 4.42708e-05, 2: 8.85417e-05, 3: 0.0001328125, 4: 0.0001770833, 5: 0.0002213542, 6: 0.000265625, 8: 0.0003541667, 10: 0.0004427083}
MAX_SHAPE = (1920, 1920)
aliases = ['Rayonix Sx85hs']
class pyFAI.detectors.Titan(pixel1=6e-05, pixel2=6e-05)

Bases: pyFAI.detectors.Detector

Titan CCD detector from Agilent. Mask not handled

MAX_SHAPE = (2048, 2048)
aliases = ['Titan 2k x 2k', 'OXD Titan', 'Agilent Titan']
force_pixel = True
uniform_pixel = True
class pyFAI.detectors.Xpad_flat(pixel1=0.00013, pixel2=0.00013, max_shape=None, module_size=None)

Bases: pyFAI.detectors.ImXPadS10

Xpad detector: generic description for ImXPad detector with 8x7modules

BORDER_PIXEL_SIZE_RELATIVE = 2.5
IS_CONTIGUOUS = False
MAX_SHAPE = (960, 560)
MODULE_GAP = (0.00357, 0)
MODULE_SIZE = (120, 80)
PIXEL_SIZE = (0.00013, 0.00013)
aliases = ['Xpad S540 flat', 'd5']
calc_cartesian_positions(d1=None, d2=None, center=True, use_cython=True)

Calculate the position of each pixel center in cartesian coordinate and in meter of a couple of coordinates. The half pixel offset is taken into account here !!! Adapted to Nexus detector definition

Parameters:
  • d1 (ndarray (1D or 2D)) – the Y pixel positions (slow dimension)
  • d2 (ndarray (1D or 2D)) – the X pixel positions (fast dimension)
  • center – retrieve the coordinate of the center of the pixel

@parm use_cython: set to False to test Numpy implementation :return: position in meter of the center of each pixels. :rtype: ndarray

d1 and d2 must have the same shape, returned array will have the same shape.

calc_mask()

Returns a generic mask for Xpad detectors... discards the first line and raw form all modules: those are 2.5x bigger and often mis - behaving

calc_pixels_edges()

Calculate the position of the pixel edges, specific to the S540, d5 detector

force_pixel = True
get_pixel_corners()

Calculate the position of the corner of the pixels

Returns:4D array containing: pixel index (slow dimension) pixel index (fast dimension) corner index (A, B, C or D), triangles or hexagons can be handled the same way vertex position (z,y,x)
uniform_pixel = False

spline Module

This is piece of software aims at manipulating spline files describing for geometric corrections of the 2D detectors using cubic-spline.

Mainly used at ESRF with FReLoN CCD camera.

class pyFAI.spline.Spline(filename=None)

Bases: object

This class is a python representation of the spline file

Those file represent cubic splines for 2D detector distortions and makes heavy use of fitpack (dierckx in netlib) — A Python-C wrapper to FITPACK (by P. Dierckx). FITPACK is a collection of FORTRAN programs for curve and surface fitting with splines and tensor product splines. See _http://www.cs.kuleuven.ac.be/cwis/research/nalag/research/topics/fitpack.html or _http://www.netlib.org/dierckx/index.html

array2spline(smoothing=1000, timing=False)

Calculates the spline coefficients from the displacements matrix using fitpack.

Parameters:
  • smoothing (float) – the greater the smoothing, the fewer the number of knots remaining
  • timing (bool) – print the profiling of the calculation
bin(binning=None)

Performs the binning of a spline (same camera with different binning)

Parameters:binning – binning factor as integer or 2-tuple of integers
Type:int or (int, int)
comparison(ref, verbose=False)

Compares the current spline distortion with a reference

Parameters:
  • ref (Spline instance) – another spline file
  • verbose (bool) – print or not pylab plots
Returns:

True or False depending if the splines are the same or not

Return type:

bool

correct(pos)
fliplr()

Flip the spline :return: new spline object

fliplrud()

Flip the spline left-right and up-down :return: new spline object

flipud()

Flip the spline up-down :return: new spline object

getPixelSize()

Return the size of the pixel from as a 2-tuple of floats expressed in meters.

Returns:the size of the pixel from a 2D detector
Return type:2-tuple of floats expressed in meter.
read(filename)

read an ascii spline file from file

Parameters:filename (str) – file containing the cubic spline distortion file
setPixelSize(pixelSize)

Sets the size of the pixel from a 2-tuple of floats expressed in meters.

Param:pixel size in meter
spline2array(timing=False)

Calculates the displacement matrix using fitpack bisplev(x, y, tck, dx = 0, dy = 0)

Parameters:timing (bool) – profile the calculation or not
Returns:Nothing !
Return type:float or ndarray

Evaluate a bivariate B-spline and its derivatives. Return a rank-2 array of spline function values (or spline derivative values) at points given by the cross-product of the rank-1 arrays x and y. In special cases, return an array or just a float if either x or y or both are floats.

splineFuncX(x, y, list_of_points=False)

Calculates the displacement matrix using fitpack for the X direction on the given grid.

Parameters:
  • x (ndarray) – points of the grid in the x direction
  • y (ndarray) – points of the grid in the y direction
  • list_of_points – if true, consider the zip(x,y) instead of the of the square array
Returns:

displacement matrix for the X direction

Return type:

ndarray

splineFuncY(x, y, list_of_points=False)

calculates the displacement matrix using fitpack for the Y direction

Parameters:
  • x (ndarray) – points in the x direction
  • y (ndarray) – points in the y direction
  • list_of_points – if true, consider the zip(x,y) instead of the of the square array
Returns:

displacement matrix for the Y direction

Return type:

ndarray

tilt(center=(0.0, 0.0), tiltAngle=0.0, tiltPlanRot=0.0, distanceSampleDetector=1.0, timing=False)

The tilt method apply a virtual tilt on the detector, the point of tilt is given by the center

Parameters:
  • center (2-tuple of floats) – position of the point of tilt, this point will not be moved.
  • tiltAngle (float in the range [-90:+90] degrees) – the value of the tilt in degrees
  • tiltPlanRot (Float in the range [-180:180]) – the rotation of the tilt plan with the Ox axis (0 deg for y axis invariant, 90 deg for x axis invariant)
  • distanceSampleDetector (float) – the distance from sample to detector in meter (along the beam, so distance from sample to center)
Returns:

tilted Spline instance

Return type:

Spline

write(filename)

save the cubic spline in an ascii file usable with Fit2D or SPD

Parameters:filename (str) – name of the file containing the cubic spline distortion file
writeEDF(basename)

save the distortion matrices into a couple of files called basename-x.edf and basename-y.edf

Parameters:basename (str) – base of the name used to save the data
zeros(xmin=0.0, ymin=0.0, xmax=2048.0, ymax=2048.0, pixSize=None)

Defines a spline file with no ( zero ) displacement.

Parameters:
  • xmin (float) – minimum coordinate in x, usually zero
  • xmax (float) – maximum coordinate in x (+1) usually 2048
  • ymin (float) – minimum coordinate in y, usually zero
  • ymax (float) – maximum coordinate y (+1) usually 2048
  • pixSize (float) – size of the pixel
zeros_like(other)

Defines a spline file with no ( zero ) displacement with the same shape as the other one given.

Parameters:other (Spline instance) – another Spline instance
pyFAI.spline.main()

Some tests ....

opencl Module

class pyFAI.opencl.Device(name='None', dtype=None, version=None, driver_version=None, extensions='', memory=None, available=None, cores=None, frequency=None, flop_core=None, idx=0, workgroup=1)

Bases: object

Simple class that contains the structure of an OpenCL device

pretty_print()

Complete device description

Returns:string
class pyFAI.opencl.OpenCL

Bases: object

Simple class that wraps the structure ocl_tools_extended.h

This is a static class. ocl should be the only instance and shared among all python modules.

context_cache = {}
create_context(devicetype='ALL', useFp64=False, platformid=None, deviceid=None, cached=True)

Choose a device and initiate a context.

Devicetypes can be GPU,gpu,CPU,cpu,DEF,ACC,ALL. Suggested are GPU,CPU. For each setting to work there must be such an OpenCL device and properly installed. E.g.: If Nvidia driver is installed, GPU will succeed but CPU will fail. The AMD SDK kit is required for CPU via OpenCL. :param devicetype: string in [“cpu”,”gpu”, “all”, “acc”] :param useFp64: boolean specifying if double precision will be used :param platformid: integer :param devid: integer :return: OpenCL context on the selected device

device_from_context(context)

Retrieves the Device from the context

Parameters:context – OpenCL context
Returns:instance of Device
get_platform(key)

Return a platform according

Parameters:key (int or str) – identifier for a platform, either an Id (int) or it’s name
nb_devices = 0
platforms = []
select_device(dtype='ALL', memory=None, extensions=[], best=True, **kwargs)

Select a device based on few parameters (at the end, keep the one with most memory)

Parameters:
  • type – “gpu” or “cpu” or “all” ....
  • memory – minimum amount of memory (int)
  • extensions – list of extensions to be present
  • best – shall we look for the
class pyFAI.opencl.Platform(name='None', vendor='None', version=None, extensions=None, idx=0)

Bases: object

Simple class that contains the structure of an OpenCL platform

add_device(device)

Add new device to the platform

Parameters:device – Device instance
get_device(key)

Return a device according to key

Parameters:key (int or str) – identifier for a device, either it’s id (int) or it’s name
pyFAI.opencl.allocate_cl_buffers(buffers, device=None, context=None)
Parameters:buffers – the buffers info use to create the pyopencl.Buffer
Returns:a dict containing the instanciated pyopencl.Buffer
Return type:dict(str, pyopencl.Buffer)

This method instanciate the pyopencl.Buffer from the buffers description.

pyFAI.opencl.release_cl_buffers(cl_buffers)
Parameters:cl_buffer (dict(str, pyopencl.Buffer)) – the buffer you want to release

This method release the memory of the buffers store in the dict

ocl_azim Module

ocl_azim_lut Module

ocl_azim_csr Module

ocl_azim_csr_dis Module

worker Module

This module contains the Worker class:

A tool able to perform azimuthal integration with: additional saving capabilities like - save as 2/3D structure in a HDF5 File - read from HDF5 files

Aims at being integrated into a plugin like LImA or as model for the GUI

The configuration of this class is mainly done via a dictionary transmitted as a JSON string: Here are the valid keys:

“dist”, “poni1”, “poni2”, “rot1” “rot3” “rot2” “pixel1” “pixel2”

“splineFile” “wavelength”

“poni” #path of the file

“chi_discontinuity_at_0” “do_mask” “do_dark” “do_azimuthal_range” “do_flat” “do_2D” “azimuth_range_min” “azimuth_range_max”

“polarization_factor” “nbpt_rad” “do_solid_angle” “do_radial_range” “do_poisson” “delta_dummy” “nbpt_azim” “flat_field” “radial_range_min” “dark_current” “do_polarization” “mask_file” “detector” “unit” “radial_range_max” “val_dummy” “do_dummy” “method”

}

class pyFAI.worker.DistortionWorker(detector=None, dark=None, flat=None, solidangle=None, polarization=None, mask=None, dummy=None, delta_dummy=None, device=None)

Bases: object

Simple worker doing dark, flat, solid angle and polarization correction

process(data, normalization=None)

Process the data and apply a normalization factor :param data: input data :param normalization: normalization factor :return processed data

class pyFAI.worker.PixelwiseWorker(dark=None, flat=None, solidangle=None, polarization=None, mask=None, dummy=None, delta_dummy=None, device=None)

Bases: object

Simple worker doing dark, flat, solid angle and polarization correction

process(data, normalization=None)

Process the data and apply a normalization factor :param data: input data :param normalization: normalization factor :return processed data

class pyFAI.worker.Worker(azimuthalIntgrator=None, shapeIn=(2048, 2048), shapeOut=(360, 500), unit='r_mm', dummy=None, delta_dummy=None)

Bases: object

do_2D()
error_model
get_config()

return configuration as a dictionary

get_error_model()
get_json_config()

return configuration as a JSON string

get_normalization_factor()
get_unit()
normalization_factor
process(data)

Process a frame #TODO: dark, flat, sa are missing

Param:data: numpy array containing the input image
reconfig(shape=(2048, 2048), sync=False)

This is just to force the integrator to initialize with a given input image shape

Parameters:
  • shape – shape of the input image
  • sync – return only when synchronized
reset()

this is just to force the integrator to initialize

save_config(filename=None)
setDarkcurrentFile(imagefile)
setExtension(ext)

enforce the extension of the processed data file written

setFlatfieldFile(imagefile)
setJsonConfig(jsonconfig)
setSubdir(path)

Set the relative or absolute path for processed data

set_error_model(value)
set_normalization_factor(value)
set_unit(value)
unit
warmup(sync=False)

Process a dummy image to ensure everything is initialized

Parameters:sync – wait for processing to be finished
pyFAI.worker.make_ai(config)

Create an Azimuthal integrator from the configuration Static method !

Parameters:config – dict with all parameters
Returns:configured (but uninitialized) AzimuthalIntgrator

io Module

Module for “high-performance” writing in either 1D with Ascii , or 2D with FabIO or even nD with n varying from 2 to 4 using HDF5

Stand-alone module which tries to offer interface to HDF5 via H5Py and capabilities to write EDF or other formats using fabio.

Can be imported without h5py but then limited to fabio & ascii formats.

TODO: * add monitor to HDF5

class pyFAI.io.AsciiWriter(filename=None, prefix='fai_', extension='.dat')

Bases: pyFAI.io.Writer

Ascii file writer (.xy or .dat)

init(fai_cfg=None, lima_cfg=None)

Creates the directory that will host the output file(s)

write(data, index=0)
class pyFAI.io.FabioWriter(filename=None)

Bases: pyFAI.io.Writer

Image file writer based on FabIO

TODO !!!

init(fai_cfg=None, lima_cfg=None)

Creates the directory that will host the output file(s)

write(data, index=0)
class pyFAI.io.HDF5Writer(filename, hpath='data', fast_scan_width=None)

Bases: pyFAI.io.Writer

Class allowing to write HDF5 Files.

CONFIG = 'pyFAI'
DATASET_NAME = 'data'
close()
flush(radial=None, azimuthal=None)

Update some data like axis units and so on.

Parameters:
  • radial – position in radial direction
  • azimuthal – position in azimuthal direction
init(fai_cfg=None, lima_cfg=None)

Initializes the HDF5 file for writing :param fai_cfg: the configuration of the worker as a dictionary

write(data, index=0)

Minimalistic method to limit the overhead. :param data: array with intensities or tuple (2th,I) or (I,2th,chi)

class pyFAI.io.Nexus(filename, mode='r')

Bases: object

Writer class to handle Nexus/HDF5 data Manages: entry

pyFAI-subentry
detector

#TODO: make it thread-safe !!!

close()

close the filename and update all entries

deep_copy(name, obj, where='/', toplevel=None, excluded=None, overwrite=False)

perform a deep copy: create a “name” entry in self containing a copy of the object

Parameters:
  • where – path to the toplevel object (i.e. root)
  • toplevel – firectly the top level Group
  • excluded – list of keys to be excluded
  • overwrite – replace content if already existing
find_detector(all=False)

Tries to find a detector within a NeXus file, takes the first compatible detector

Parameters:all – return all detectors found as a list
classmethod get_attr(dset, name, default=None)

Return the attribute of the dataset

Handles the ascii -> unicode issue in python3 #275

Parameters:
  • dset – a HDF5 dataset (or a group)
  • name – name of the attribute
  • default – default value to be returned
Returns:

attribute value decoded in python3 or default

get_class(grp, class_type='NXcollection')

return all sub-groups of the given type within a group

Parameters:
  • grp – HDF5 group
  • class_type – name of the NeXus class
get_data(grp, class_type='NXdata')

return all dataset of the the NeXus class NXdata

Parameters:
  • grp – HDF5 group
  • class_type – name of the NeXus class
get_entries()

retrieves all entry sorted the latest first.

Returns:list of HDF5 groups
get_entry(name)

Retrieves an entry from its name

Parameters:name – name of the entry to retrieve
Returns:HDF5 group of NXclass == NXentry
new_class(grp, name, class_type='NXcollection')

create a new sub-group with type class_type :param grp: parent group :param name: name of the sub-group :param class_type: NeXus class name :return: subgroup created

new_detector(name='detector', entry='entry', subentry='pyFAI')

Create a new entry/pyFAI/Detector

Parameters:
  • detector – name of the detector
  • entry – name of the entry
  • subentry – all pyFAI description of detectors should be in a pyFAI sub-entry
new_entry(entry='entry', program_name='pyFAI', title='description of experiment', force_time=None)

Create a new entry

Parameters:
  • entry – name of the entry
  • program_name – value of the field as string
  • title – value of the field as string

@force_time: enforce the start_time (as string!) :return: the corresponding HDF5 group

new_instrument(entry='entry', instrument_name='id00')

Create an instrument in an entry or create both the entry and the instrument if

class pyFAI.io.Writer(filename=None, extension=None)

Bases: object

Abstract class for writers.

CONFIG_ITEMS = ['filename', 'dirname', 'extension', 'subdir', 'hpath']
flush(*arg, **kwarg)

To be implemented

init(fai_cfg=None, lima_cfg=None)

Creates the directory that will host the output file(s) :param fai_cfg: configuration for worker :param lima_cfg: configuration for acquisition

setJsonConfig(json_config=None)

Sets the JSON configuration

write(data)

To be implemented

pyFAI.io.from_isotime(text, use_tz=False)
Parameters:text – string representing the time is iso format
pyFAI.io.get_isotime(forceTime=None)
Parameters:forceTime (float) – enforce a given time (current by default)
Returns:the current time as an ISO8601 string
Return type:string
pyFAI.io.is_hdf5(filename)

Check if a file is actually a HDF5 file

Parameters:filename – this file has better to exist

calibration Module

peak_picker Module

massif Module

class pyFAI.massif.Massif(data=None)

Bases: object

A massif is defined as an area around a peak, it is used to find neighboring peaks

TARGET_SIZE = 1024
calculate_massif(x)

defines a map of the massif around x and returns the mask

delValleySize()
find_peaks(x, nmax=200, annotate=None, massif_contour=None, stdout=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)

All in one function that finds a maximum from the given seed (x) then calculates the region extension and extract position of the neighboring peaks. :param x: seed for the calculation, input coordinates :param nmax: maximum number of peak per region :param annotate: call back method taking number of points + coordinate as input. :param massif_contour: callback to show the contour of a massif with the given index. :param stdout: this is the file where output is written by default. :return: list of peaks

getBinnedData()

:return binned data

getBluredData()
Returns:a blurred image
getLabeledMassif(pattern=None)
Returns:an image composed of int with a different value for each massif
getMedianData()
Returns:a spacial median filtered image
getValleySize()
initValleySize()
nearest_peak(x)
Parameters:x – coordinates of the peak

:returns the coordinates of the nearest peak

peaks_from_area(mask, Imin=None, keep=1000, dmin=0.0, seed=None, **kwarg)

Return the list of peaks within an area

Parameters:
  • mask – 2d array with mask.
  • Imin – minimum of intensity above the background to keep the point
  • keep – maximum number of points to keep
  • kwarg – ignored parameters
  • dmin – minimum distance to another peak
  • seed – list of good guesses to start with
Returns:

list of peaks [y,x], [y,x], ...]

setValleySize(size)
valley_size

Defines the minimum distance between two massifs

blob_detection Module

class pyFAI.blob_detection.BlobDetection(img, cur_sigma=0.25, init_sigma=0.5, dest_sigma=1, scale_per_octave=2, mask=None)

Bases: object

Performs a blob detection: http://en.wikipedia.org/wiki/Blob_detection using a Difference of Gaussian + Pyramid of Gaussians

direction()

Perform and plot the two main directions of the peaks, considering their previously calculated scale ,by calculating the Hessian at different sizes as the combination of gaussians and their first and second derivatives

nearest_peak(p, refine=True, Imin=None)

Return the nearest peak from a position

Parameters:
  • p – input position (y,x) 2-tuple of float
  • refine – shall the position be refined on the raw data
  • Imin – minimum of intensity above the background
peaks_from_area(mask, keep=None, refine=True, Imin=None, dmin=0.0, **kwargs)

Return the list of peaks within an area

Parameters:
  • mask – 2d array with mask.
  • refine – shall the position be refined on the raw data
  • Imin – minimum of intensity above the background
  • kwarg – ignored parameters
Returns:

list of peaks [y,x], [y,x], ...]

process(max_octave=None)

Perform the keypoint extraction for max_octave cycles or until all octaves have been processed. :param max_octave: number of octave to process

refine_Hessian(kpx, kpy, kps)

Refine the keypoint location based on a 3 point derivative, and delete uncoherent keypoints

Parameters:
  • kpx – x_pos of keypoint
  • kpy – y_pos of keypoint
  • kps – s_pos of keypoint

:return arrays of corrected coordinates of keypoints, values and locations of keypoints

refine_Hessian_SG(kpx, kpy, kps)

Savitzky Golay algorithm to check if a point is really the maximum :param kpx: x_pos of keypoint :param kpy: y_pos of keypoint :param kps: s_pos of keypoint :return array of corrected keypoints

refinement()
show_neighboor()
show_stats()

Shows a window with the repartition of keypoint in function of scale/intensity

tresh = 0.6
pyFAI.blob_detection.image_test()
pyFAI.blob_detection.local_max(dogs, mask=None, n_5=True)
Parameters:dogs – 3d array with (sigma,y,x) containing difference of gaussians

@parm mask: mask out keypoint next to the mask (or inside the mask) :param n_5: look for a larger neighborhood

pyFAI.blob_detection.make_gaussian(im, sigma, xc, yc)

calibrant Module

distortion Module

class pyFAI.distortion.Distortion(detector='detector', shape=None, resize=False, empty=0, mask=None, method='LUT', device=None, workgroup=8)

Bases: object

This class applies a distortion correction on an image.

New version compatible both with CSR and LUT...

calc_LUT(use_common=True)

Calculate the Look-up table

Returns:look up table either in CSR or LUT format depending on serl.method
calc_init()

Initialize all arrays

calc_pos(use_cython=True)

Calculate the pixel boundary position on the regular grid

Returns:pixel corner positions (in pixel units) on the regular grid

@rtyep: ndarray of shape (nrow, ncol, 4, 2)

calc_size(use_cython=True)

Calculate the number of pixels falling into every single bin and

Returns:max of pixel falling into a single bin

Considering the “half-CCD” spline from ID11 which describes a (1025,2048) detector, the physical location of pixels should go from: [-17.48634 : 1027.0543, -22.768829 : 2028.3689] We chose to discard pixels falling outside the [0:1025,0:2048] range with a lose of intensity

correct(image, dummy=None, delta_dummy=None)

Correct an image based on the look-up table calculated ...

Parameters:
  • image – 2D-array with the image
  • dummy – value suggested for bad pixels
  • delta_dummy – precision of the dummy value
Returns:

corrected 2D image

#TODO: #225

reset(method=None, device=None, workgroup=None, prepare=True)

reset the distortion correction and re-calculate the look-up table

Parameters:
  • method – can be “lut” or “csr”, “lut” looks faster
  • device – can be None, “cpu” or “gpu” or the id as a 2-tuple of integer
  • worgroup – enforce the workgroup size for CSR.
  • prepare – set to false to only reset and not re-initialize
shape_out

Calculate/cache the output shape

:return output shape

uncorrect(image)

Take an image which has been corrected and transform it into it’s raw (with loss of information)

Parameters:image – 2D-array with the image
Returns:uncorrected 2D image and a mask (pixels in raw image
class pyFAI.distortion.Quad(buffer)

Bases: object



xxxxxA
xxxxxxxI’xxxxxxxx x

xxxxxxxxIxxxxxx | x

Bxxxxxxxxxxxx | | x x | | x x | | x

x | | x x | | x x | | x x | | x x | | x

x | | x x | | x x | | x x O| P A’ x
—————–J——————+——————————–L———————–

x | x x | x x | x

x | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxD CxxxxxxxxxxxxxxxxxKxxxxx





calc_area()
calc_area_AB(I1, I2)
calc_area_BC(J1, J2)
calc_area_CD(K1, K2)
calc_area_DA(L1, L2)
calc_area_old()
calc_area_vectorial()
get_box(i, j)
get_box_size0()
get_box_size1()
get_idx(i, j)
get_offset0()
get_offset1()
init_slope()
integrateAB(start, stop, calc_area)
populate_box()
reinit(A0, A1, B0, B1, C0, C1, D0, D1)
pyFAI.distortion.test()

worker Module

This module contains the Worker class:

A tool able to perform azimuthal integration with: additional saving capabilities like - save as 2/3D structure in a HDF5 File - read from HDF5 files

Aims at being integrated into a plugin like LImA or as model for the GUI

The configuration of this class is mainly done via a dictionary transmitted as a JSON string: Here are the valid keys:

“dist”, “poni1”, “poni2”, “rot1” “rot3” “rot2” “pixel1” “pixel2”

“splineFile” “wavelength”

“poni” #path of the file

“chi_discontinuity_at_0” “do_mask” “do_dark” “do_azimuthal_range” “do_flat” “do_2D” “azimuth_range_min” “azimuth_range_max”

“polarization_factor” “nbpt_rad” “do_solid_angle” “do_radial_range” “do_poisson” “delta_dummy” “nbpt_azim” “flat_field” “radial_range_min” “dark_current” “do_polarization” “mask_file” “detector” “unit” “radial_range_max” “val_dummy” “do_dummy” “method”

}

class pyFAI.worker.DistortionWorker(detector=None, dark=None, flat=None, solidangle=None, polarization=None, mask=None, dummy=None, delta_dummy=None, device=None)

Bases: object

Simple worker doing dark, flat, solid angle and polarization correction

process(data, normalization=None)

Process the data and apply a normalization factor :param data: input data :param normalization: normalization factor :return processed data

class pyFAI.worker.PixelwiseWorker(dark=None, flat=None, solidangle=None, polarization=None, mask=None, dummy=None, delta_dummy=None, device=None)

Bases: object

Simple worker doing dark, flat, solid angle and polarization correction

process(data, normalization=None)

Process the data and apply a normalization factor :param data: input data :param normalization: normalization factor :return processed data

class pyFAI.worker.Worker(azimuthalIntgrator=None, shapeIn=(2048, 2048), shapeOut=(360, 500), unit='r_mm', dummy=None, delta_dummy=None)

Bases: object

do_2D()
error_model
get_config()

return configuration as a dictionary

get_error_model()
get_json_config()

return configuration as a JSON string

get_normalization_factor()
get_unit()
normalization_factor
process(data)

Process a frame #TODO: dark, flat, sa are missing

Param:data: numpy array containing the input image
reconfig(shape=(2048, 2048), sync=False)

This is just to force the integrator to initialize with a given input image shape

Parameters:
  • shape – shape of the input image
  • sync – return only when synchronized
reset()

this is just to force the integrator to initialize

save_config(filename=None)
setDarkcurrentFile(imagefile)
setExtension(ext)

enforce the extension of the processed data file written

setFlatfieldFile(imagefile)
setJsonConfig(jsonconfig)
setSubdir(path)

Set the relative or absolute path for processed data

set_error_model(value)
set_normalization_factor(value)
set_unit(value)
unit
warmup(sync=False)

Process a dummy image to ensure everything is initialized

Parameters:sync – wait for processing to be finished
pyFAI.worker.make_ai(config)

Create an Azimuthal integrator from the configuration Static method !

Parameters:config – dict with all parameters
Returns:configured (but uninitialized) AzimuthalIntgrator

units Module

class pyFAI.units.Enum

Bases: dict

Simple class half way between a dict and a class, behaving as an enum

pyFAI.units.eq_2th(x, y, z, wavelength=None)

Calculates the 2theta aperture of the cone

Parameters:
  • x – horizontal position, towards the center of the ring, from sample position
  • y – Vertical position, to the roof, from sample position
  • z – distance from sample along the beam
  • wavelength – in meter
pyFAI.units.eq_logq(x, y, z, wavelength)

Calculates the log (decimal) of the scattering vector

Parameters:
  • x – horizontal position, towards the center of the ring, from sample position
  • y – Vertical position, to the roof, from sample position
  • z – distance from sample along the beam
  • wavelength – in meter
pyFAI.units.eq_q(x, y, z, wavelength)

Calculates the modulus of the scattering vector

Parameters:
  • x – horizontal position, towards the center of the ring, from sample position
  • y – Vertical position, to the roof, from sample position
  • z – distance from sample along the beam
  • wavelength – in meter
pyFAI.units.eq_r(x, y, z=None, wavelength=None)

Calculates the radius

Parameters:
  • x – horizontal position, towards the center of the ring, from sample position
  • y – Vertical position, to the roof, from sample position
  • z – distance from sample along the beam
  • wavelength – in meter
pyFAI.units.eq_rd2(x, y, z, wavelength)

Calculates the reciprocal spacing squared

Parameters:
  • x – horizontal position, towards the center of the ring, from sample position
  • y – Vertical position, to the roof, from sample position
  • z – distance from sample along the beam
  • wavelength – in meter
pyFAI.units.to_unit(obj, type_=(2th_deg, 2th_rad, q_nm^-1, q_A^-1, r_mm, r_m, d*2_A^-2, d*2_nm^-2, log(q)_m))

utils Module

Utilities, mainly for image treatment

class pyFAI.utils.FixedParameters

Bases: set

Like a set, made for FixedParameters in geometry refinement

add_or_discard(key, value=True)

Add a value to a set if value, else discard it :param key: element to added or discared from set :type value: boolean. If None do nothing ! :return: None

pyFAI.utils.averageDark(lstimg, center_method='mean', cutoff=None, quantiles=(0.5, 0.5))

Averages a serie of dark (or flat) images. Centers the result on the mean or the median ... but averages all frames within cutoff*std

Parameters:
  • lstimg – list of 2D images or a 3D stack
  • center_method – is the center calculated by a “mean” or a “median”, or “quantile”
  • cutoff – keep all data where (I-center)/std < cutoff
  • quantiles – 2-tuple of floats average out data between the two quantiles
Returns:

2D image averaged

pyFAI.utils.averageImages(listImages, output=None, threshold=0.1, minimum=None, maximum=None, darks=None, flats=None, filter_='mean', correct_flat_from_dark=False, cutoff=None, quantiles=None, fformat='edf')

Takes a list of filenames and create an average frame discarding all saturated pixels.

Parameters:
  • listImages – list of string representing the filenames
  • output – name of the optional output file
  • threshold – what is the upper limit? all pixel > max*(1-threshold) are discareded.
  • minimum – minimum valid value or True
  • maximum – maximum valid value
  • darks – list of dark current images for subtraction
  • flats – list of flat field images for division
  • filter – can be “min”, “max”, “median”, “mean”, “sum”, “quantiles” (default=’mean’)
  • correct_flat_from_dark – shall the flat be re-corrected ?
  • cutoff – keep all data where (I-center)/std < cutoff
  • quantiles – 2-tuple containing the lower and upper quantile (0<q<1) to average out.
  • fformat – file format of the output image, default: edf
Returns:

filename with the data or the data ndarray in case format=None

pyFAI.utils.binning(input_img, binsize, norm=True)
Parameters:
  • input_img – input ndarray
  • binsize – int or 2-tuple representing the size of the binning
  • norm – if False, do average instead of sum
Returns:

binned input ndarray

pyFAI.utils.boundingBox(img)

Tries to guess the bounding box around a valid massif

Parameters:img – 2D array like
Returns:4-typle (d0_min, d1_min, d0_max, d1_max)
pyFAI.utils.calc_checksum(ary, safe=True)

Calculate the checksum by default (or returns its buffer location if unsafe)

pyFAI.utils.center_of_mass(img)

Calculate the center of mass of of the array. Like scipy.ndimage.measurements.center_of_mass :param img: 2-D array :return: 2-tuple of float with the center of mass

pyFAI.utils.concatenate_cl_kernel(filenames)
Parameters:filenames – filenames containing the kernels

this method concatenates all the kernel from the list

pyFAI.utils.convert_CamelCase(name)

convert a function name in CamelCase into camel_case

pyFAI.utils.deg2rad(dd)

Convert degrees to radian in the range -pi->pi

Parameters:dd – angle in degrees

Nota: depending on the platform it could be 0<2pi A branch is cheaper than a trigo operation

pyFAI.utils.dog(s1, s2, shape=None)

2D difference of gaussian typically 1 to 10 parameters

pyFAI.utils.dog_filter(input_img, sigma1, sigma2, mode='reflect', cval=0.0)

2-dimensional Difference of Gaussian filter implemented with FFTw

Parameters:
  • input_img (array-like) – input_img array to filter
  • sigma (scalar or sequence of scalars) – standard deviation for Gaussian kernel. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes.
  • mode – {‘reflect’,’constant’,’nearest’,’mirror’, ‘wrap’}, optional The mode parameter determines how the array borders are handled, where cval is the value when mode is equal to ‘constant’. Default is ‘reflect’
  • cval – scalar, optional Value to fill past edges of input if mode is ‘constant’. Default is 0.0
pyFAI.utils.expand(input_img, sigma, mode='constant', cval=0.0)

Expand array a with its reflection on boundaries

Parameters:
  • a – 2D array
  • sigma – float or 2-tuple of floats.

:param mode:”constant”, “nearest”, “reflect” or mirror :param cval: filling value used for constant, 0.0 by default

Nota: sigma is the half-width of the kernel. For gaussian convolution it is adviced that it is 4*sigma_of_gaussian

pyFAI.utils.expand2d(vect, size2, vertical=True)

This expands a vector to a 2d-array.

The resul is the same as if vertical:

numpy.outer(numpy.ones(size2), vect)
else:
numpy.outer(vect, numpy.ones( size2))

This is a ninja optimization: replace *1 with a memcopy, saves 50% of time at the ms level.

Parameters:
  • vect – 1d vector
  • size2 – size
  • vertical – if False,
pyFAI.utils.expand_args(args)

Takes an argv and expand it (under Windows, cmd does not convert *.tif into a list of files. Keeps only valid files (thanks to glob)

Parameters:args – list of files or wilcards
Returns:list of actual args
pyFAI.utils.float_(val)

Convert anything to a float ... or None if not applicable

pyFAI.utils.gaussian(M, std)

Return a Gaussian window of length M with standard-deviation std.

This differs from the scipy.signal.gaussian implementation as: - The default for sym=False (needed for gaussian filtering without shift) - This implementation is normalized

Parameters:
  • M – length of the windows (int)
  • std – standatd deviation sigma

The FWHM is 2*numpy.sqrt(2 * numpy.pi)*std

pyFAI.utils.gaussian_filter(input_img, sigma, mode='reflect', cval=0.0)

2-dimensional Gaussian filter implemented with FFTw

Parameters:
  • input_img (array-like) – input array to filter
  • sigma (scalar or sequence of scalars) – standard deviation for Gaussian kernel. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes.
  • mode – {‘reflect’,’constant’,’nearest’,’mirror’, ‘wrap’}, optional The mode parameter determines how the array borders are handled, where cval is the value when mode is equal to ‘constant’. Default is ‘reflect’
  • cval – scalar, optional Value to fill past edges of input if mode is ‘constant’. Default is 0.0
pyFAI.utils.get_calibration_dir()

get the full path of a calibration directory

Returns:the full path of the calibrant file
pyFAI.utils.get_cl_file(filename)

get the full path of a openCL file

Returns:the full path of the openCL source file
pyFAI.utils.get_ui_file(filename)

get the full path of a user-interface file

Returns:the full path of the ui
pyFAI.utils.int_(val)

Convert anything to an int ... or None if not applicable

pyFAI.utils.is_far_from_group(pt, lst_pts, d2)

Tells if a point is far from a group of points, distance greater than d2 (distance squared)

Parameters:
  • pt – point of interest
  • lst_pts – list of points
  • d2 – minimum distance squarred
Returns:

True If the point is far from all others.

class pyFAI.utils.lazy_property(fget)

Bases: object

meant to be used for lazy evaluation of an object attribute. property should represent non-mutable data, as it replaces itself.

pyFAI.utils.maximum_position(img)

Same as scipy.ndimage.measurements.maximum_position: Find the position of the maximum of the values of the array.

Parameters:img – 2-D image
Returns:2-tuple of int with the position of the maximum
pyFAI.utils.measure_offset(img1, img2, method='numpy', withLog=False, withCorr=False)

Measure the actual offset between 2 images :param img1: ndarray, first image :param img2: ndarray, second image, same shape as img1 :param withLog: shall we return logs as well ? boolean :return: tuple of floats with the offsets

pyFAI.utils.readFloatFromKeyboard(text, dictVar)

Read float from the keyboard ....

Parameters:
  • text – string to be displayed
  • dictVar – dict of this type: {1: [set_dist_min],3: [set_dist_min, set_dist_guess, set_dist_max]}
pyFAI.utils.read_cl_file(filename)
Parameters:filename – read an OpenCL file and apply a preprocessor
Returns:preprocessed source code
pyFAI.utils.relabel(label, data, blured, max_size=None)

Relabel limits the number of region in the label array. They are ranked relatively to their max(I0)-max(blur(I0)

Parameters:
  • label – a label array coming out of scipy.ndimage.measurement.label
  • data – an array containing the raw data
  • blured – an array containing the blured data
  • max_size – the max number of label wanted

:return array like label

pyFAI.utils.removeSaturatedPixel(ds, threshold=0.1, minimum=None, maximum=None)
Parameters:
  • ds – a dataset as ndarray
  • threshold – what is the upper limit? all pixel > max*(1-threshold) are discareded.
  • minimum – minumum valid value (or True for auto-guess)
  • maximum – maximum valid value
Returns:

another dataset

pyFAI.utils.roundfft(N)

This function returns the integer >=N for which size the Fourier analysis is faster (fron the FFT point of view) Credit: Alessandro Mirone, ESRF, 2012

Parameters:N – interger on which one would like to do a Fourier transform
Returns:integer with a better choice
pyFAI.utils.shift(input_img, shift_val)

Shift an array like scipy.ndimage.interpolation.shift(input_img, shift_val, mode=”wrap”, order=0) but faster :param input_img: 2d numpy array :param shift_val: 2-tuple of integers :return: shifted image

pyFAI.utils.shiftFFT(input_img, shift_val, method='fftw')

Do shift using FFTs Shift an array like scipy.ndimage.interpolation.shift(input, shift, mode=”wrap”, order=”infinity”) but faster :param input_img: 2d numpy array :param shift_val: 2-tuple of float :return: shifted image

pyFAI.utils.str_(val)

Convert anything to a string ... but None -> “”

pyFAI.utils.unBinning(binnedArray, binsize, norm=True)
Parameters:
  • binnedArray – input ndarray
  • binsize – 2-tuple representing the size of the binning
  • norm – if True (default) decrease the intensity by binning factor. If False, it is non-conservative
Returns:

unBinned input ndarray

gui_utils Module

gui_utils

Module to handle matplotlib and the Qt backend

class pyFAI.gui_utils.Event(width, height)

Bases: object

Dummy class for dummy things

pyFAI.gui_utils.maximize_fig(fig=None)

Try to set the figure fullscreen

pyFAI.gui_utils.update_fig(fig=None)

Update a matplotlib figure with a Qt4 backend

Parameters:fig – pylab figure