pyFAI package¶
- pyFAI.app package
- pyFAI.app.average module
- pyFAI.app.benchmark module
- pyFAI.app.calib module
- pyFAI.app.calib2 module
- pyFAI.app.check_calib module
- pyFAI.app.detector2nexus module
- pyFAI.app.diff_map module
- pyFAI.app.diff_tomo module
- pyFAI.app.drawmask module
- pyFAI.app.eiger_mask module
- pyFAI.app.integrate module
- pyFAI.app.mx_calibrate module
- pyFAI.app.recalib module
- pyFAI.app.saxs module
- pyFAI.app.setup module
- pyFAI.app.waxs module
- Module contents
- pyFAI.detectors package
- pyFAI.engines package
- pyFAI.ext package
- pyFAI.ext.bilinear module
- pyFAI.ext.fastcrc module
- pyFAI.ext.histogram module
- pyFAI.ext.inpainting module
- pyFAI.ext.invert_geometry module
- pyFAI.ext.morphology module
- pyFAI.ext.preproc module
- pyFAI.ext.reconstruct module
- pyFAI.ext.relabel module
- pyFAI.ext.setup module
- pyFAI.ext.sparse_builder module
- pyFAI.ext.sparse_utils module
- pyFAI.ext.splitBBox module
- pyFAI.ext.splitBBoxCSR module
- pyFAI.ext.splitBBoxLUT module
- pyFAI.ext.splitPixel module
- pyFAI.ext.splitPixelFull module
- pyFAI.ext.splitPixelFullCSR module
- pyFAI.ext.splitPixelFullLUT module
- pyFAI.ext.watershed module
- Module contents
- pyFAI.ext private package
- pyFAI.gui package
- Subpackages
- pyFAI.gui.dialog package
- pyFAI.gui.helper package
- pyFAI.gui.helper.MarkerManager module
- pyFAI.gui.helper.ProcessingWidget module
- pyFAI.gui.helper.RingCalibration module
- pyFAI.gui.helper.RingExtractor module
- pyFAI.gui.helper.SynchronizeMaskToolColor module
- pyFAI.gui.helper.SynchronizePlotBackground module
- pyFAI.gui.helper.SynchronizeRawView module
- pyFAI.gui.helper.model_transform module
- Module contents
- pyFAI.gui.model package
- pyFAI.gui.model.AbstractModel module
- pyFAI.gui.model.CalibrantModel module
- pyFAI.gui.model.CalibrationModel module
- pyFAI.gui.model.ConstraintModel module
- pyFAI.gui.model.DataModel module
- pyFAI.gui.model.DataModelAdaptor module
- pyFAI.gui.model.DetectorModel module
- pyFAI.gui.model.ExperimentSettingsModel module
- pyFAI.gui.model.FilenameModel module
- pyFAI.gui.model.Fit2dGeometryModel module
- pyFAI.gui.model.GeometryConstraintsModel module
- pyFAI.gui.model.GeometryHistoryModel module
- pyFAI.gui.model.GeometryModel module
- pyFAI.gui.model.ImageModel module
- pyFAI.gui.model.IntegrationSettingsModel module
- pyFAI.gui.model.ListModel module
- pyFAI.gui.model.MarkerModel module
- pyFAI.gui.model.MaskedImageModel module
- pyFAI.gui.model.PeakModel module
- pyFAI.gui.model.PeakSelectionModel module
- pyFAI.gui.model.PlotViewModel module
- Module contents
- pyFAI.gui.tasks package
- pyFAI.gui.utils package
- pyFAI.gui.utils.FilterBuilder module
- pyFAI.gui.utils.ProxyAction module
- pyFAI.gui.utils.colorutils module
- pyFAI.gui.utils.eventutils module
- pyFAI.gui.utils.imageutils module
- pyFAI.gui.utils.projecturl module
- pyFAI.gui.utils.setup module
- pyFAI.gui.utils.timeutils module
- pyFAI.gui.utils.tree module
- pyFAI.gui.utils.units module
- pyFAI.gui.utils.unitutils module
- pyFAI.gui.utils.validators module
- Module contents
- pyFAI.gui.widgets package
- pyFAI.gui.widgets.AdvancedComboBox module
- pyFAI.gui.widgets.AdvancedSpinBox module
- pyFAI.gui.widgets.CalibrantPreview module
- pyFAI.gui.widgets.CalibrantSelector module
- pyFAI.gui.widgets.ChoiceToolButton module
- pyFAI.gui.widgets.ColoredCheckBox module
- pyFAI.gui.widgets.DetectorLabel module
- pyFAI.gui.widgets.DetectorModel module
- pyFAI.gui.widgets.DetectorSelector module
- pyFAI.gui.widgets.ElidedLabel module
- pyFAI.gui.widgets.FileEdit module
- pyFAI.gui.widgets.FitParamView module
- pyFAI.gui.widgets.GeometryHistoryComboBox module
- pyFAI.gui.widgets.GeometryLabel module
- pyFAI.gui.widgets.LoadImageToolButton module
- pyFAI.gui.widgets.MethodLabel module
- pyFAI.gui.widgets.MonitorNameEdit module
- pyFAI.gui.widgets.OpenClDeviceLabel module
- pyFAI.gui.widgets.QuantityEdit module
- pyFAI.gui.widgets.QuantityLabel module
- pyFAI.gui.widgets.UnitLabel module
- pyFAI.gui.widgets.UnitSelector module
- pyFAI.gui.widgets.WorkerConfigurator module
- Module contents
- pyFAI.gui.ApplicationContext module
- pyFAI.gui.CalibrationContext module
- pyFAI.gui.CalibrationWindow module
- pyFAI.gui.IntegrationDialog module
- pyFAI.gui.cli_calibration module
- pyFAI.gui.diffmap_widget module
- pyFAI.gui.jupyter module
- pyFAI.gui.matplotlib module
- pyFAI.gui.peak_picker module
- pyFAI.gui.setup module
- Module contents
- Subpackages
- pyFAI.io package
- pyFAI.opencl package
- pyFAI.resources package
- pyFAI.utils package
- pyFAI.utils.bayes module
- pyFAI.utils.decorators module
- pyFAI.utils.ellipse module
- pyFAI.utils.header_utils module
- pyFAI.utils.logging_utils module
- pyFAI.utils.mathutil module
- pyFAI.utils.orderedset module
- pyFAI.utils.setup module
- pyFAI.utils.shell module
- pyFAI.utils.stringutil module
- Module contents
pyFAI
Package¶
-
pyFAI.__init__.
AzimuthalIntegrator
(*args, **kwargs)¶
-
pyFAI.__init__.
benchmarks
(*arg, **kwarg)¶ Run the integrated benchmarks.
See the documentation of pyFAI.benchmark.run_benchmark
-
pyFAI.__init__.
detector_factory
(name, config=None)¶ Create a new detector.
- Parameters
name (str) – name of a detector
config (dict) – configuration of the detector supporting dict or JSON representation.
- Returns
an instance of the right detector, set-up if possible
- Return type
-
pyFAI.__init__.
load
(filename)¶ Load an azimuthal integrator from a filename description.
- Parameters
filename (str) – name of the file to load
- Returns
instance of Gerometry of AzimuthalIntegrator set-up with the parameter from the file.
-
pyFAI.__init__.
tests
(deprecation=False)¶ Runs the test suite of the installed version
- Parameters
deprecation – enable/disables deprecation warning in the tests
-
pyFAI.__init__.
use_opencl
= True¶ Global configuration which allow to disable OpenCL programatically. It must be set before requesting any OpenCL modules.
import pyFAI pyFAI.use_opencl = False
average
Module¶
Utilities, mainly for image treatment
-
exception
pyFAI.average.
AlgorithmCreationError
¶ Bases:
RuntimeError
Exception returned if creation of an ImageReductionFilter is not possible
-
class
pyFAI.average.
Average
¶ Bases:
object
Process images to generate an average using different algorithms.
-
__init__
()¶ Constructor
-
add_algorithm
(algorithm)¶ Defines another algorithm which will be computed on the source.
- Parameters
algorithm (ImageReductionFilter) – An averaging algorithm.
-
get_counter_frames
()¶ Returns the number of frames used for the process.
- Return type
int
-
get_fabio_images
()¶ Returns source images as fabio images.
- Return type
list(fabio.fabioimage.FabioImage)
-
get_image_reduction
(algorithm)¶ Returns the result of an algorithm. The process must be already done.
- Parameters
algorithm (ImageReductionFilter) – An averaging algorithm
- Return type
numpy.ndarray
-
process
()¶ Process source images to all defined averaging algorithms defined using defined parameters. To access to the results you have to define a writer (AverageWriter). To follow the process forward you have to define an observer (AverageObserver).
-
set_correct_flat_from_dark
(correct_flat_from_dark)¶ Defines if the dark must be applied on the flat.
- Parameters
correct_flat_from_dark (bool) – If true, the dark is applied.
-
set_dark
(dark_list)¶ Defines images used as dark.
- Parameters
dark_list (list) – List of dark used
-
set_flat
(flat_list)¶ Defines images used as flat.
- Parameters
flat_list (list) – List of dark used
-
set_images
(image_list)¶ Defines the set set of source images to used to process an average.
- Parameters
image_list (list) – List of filename, numpy arrays, fabio images used as source for the computation.
-
set_monitor_name
(monitor_name)¶ Defines the monitor name used to correct images before processing the average. This monitor must be part of the file header, else the image is skipped.
- Parameters
monitor_name (str) – Name of the monitor available on the header file
-
set_observer
(observer)¶ Set an observer to the average process.
- Parameters
observer (AverageObserver) – An observer
-
set_pixel_filter
(threshold, minimum, maximum)¶ Defines the filter applied on each pixels of the images before processing the average.
- Parameters
threshold – what is the upper limit? all pixel > max*(1-threshold) are discareded.
minimum – minimum valid value or True
maximum – maximum valid value
-
set_writer
(writer)¶ Defines the object write which will be used to store the result.
- Parameters
writer (AverageWriter) – The writer to use.
-
-
class
pyFAI.average.
AverageDarkFilter
(filter_name, cut_off, quantiles)¶ Bases:
pyFAI.average.ImageStackFilter
Filter based on the algorithm of average_dark
TODO: Must be split according to each filter_name, and removed
-
__init__
(filter_name, cut_off, quantiles)¶ Initialize self. See help(type(self)) for accurate signature.
-
get_parameters
()¶ Return a dictionary containing filter parameters
-
property
name
¶
-
-
class
pyFAI.average.
AverageObserver
¶ Bases:
object
-
algorithm_finished
(algorithm)¶ Called when an algorithm is finished
-
algorithm_started
(algorithm)¶ Called when an algorithm is started
-
frame_processed
(algorithm, frame_index, frames_count)¶ Called after providing a frame to an algorithm
-
image_loaded
(fabio_image, image_index, images_count)¶ Called when an input image is loaded
-
process_finished
()¶ Called when the full process is finished
-
process_started
()¶ Called when the full processing is started
-
result_processing
(algorithm)¶ Called before the result of an algorithm is computed
-
-
class
pyFAI.average.
AverageWriter
¶ Bases:
object
Interface for using writer in Average process.
-
close
()¶ Close the writer. Must not be used anymore.
-
write_header
(merged_files, nb_frames, monitor_name)¶ Write the header of the average
- Parameters
merged_files (list) – List of files used to generate this output
nb_frames (int) – Number of frames used
monitor_name (str) – Name of the monitor used. Can be None.
-
write_reduction
(algorithm, data)¶ Write one reduction
- Parameters
algorithm (ImageReductionFilter) – Algorithm used
data (object) – Data of this reduction
-
-
class
pyFAI.average.
ImageAccumulatorFilter
¶ Bases:
pyFAI.average.ImageReductionFilter
Filter applied in a set of images in which it is possible to reduce data step by step into a single merged image.
-
add_image
(image)¶ Add an image to the filter.
- Parameters
image (numpy.ndarray) – image to add
-
get_result
()¶ Get the result of the filter.
- Returns
result filter
- Return type
numpy.ndarray
-
init
(max_images=None)¶ Initialize the filter before using it.
- Parameters
max_images (int) – Max images supported by the filter
-
-
class
pyFAI.average.
ImageReductionFilter
¶ Bases:
object
Generic filter applied in a set of images.
-
add_image
(image)¶ Add an image to the filter.
- Parameters
image (numpy.ndarray) – image to add
-
get_parameters
()¶ Return a dictionary containing filter parameters
- Return type
dict
-
get_result
()¶ Get the result of the filter.
- Returns
result filter
-
init
(max_images=None)¶ Initialize the filter before using it.
- Parameters
max_images (int) – Max images supported by the filter
-
-
class
pyFAI.average.
ImageStackFilter
¶ Bases:
pyFAI.average.ImageReductionFilter
Filter creating a stack from all images and computing everything at the end.
-
add_image
(image)¶ Add an image to the filter.
- Parameters
image (numpy.ndarray) – image to add
-
get_result
()¶ Get the result of the filter.
- Returns
result filter
-
init
(max_images=None)¶ Initialize the filter before using it.
- Parameters
max_images (int) – Max images supported by the filter
-
-
class
pyFAI.average.
MaxAveraging
¶ Bases:
pyFAI.average.ImageAccumulatorFilter
-
name
= 'max'¶
-
-
class
pyFAI.average.
MeanAveraging
¶ Bases:
pyFAI.average.SumAveraging
-
get_result
()¶ Get the result of the filter.
- Returns
result filter
- Return type
numpy.ndarray
-
name
= 'mean'¶
-
-
class
pyFAI.average.
MinAveraging
¶ Bases:
pyFAI.average.ImageAccumulatorFilter
-
name
= 'min'¶
-
-
class
pyFAI.average.
MultiFilesAverageWriter
(file_name_pattern, file_format, dry_run=False)¶ Bases:
pyFAI.average.AverageWriter
Write reductions into multi files. File headers are duplicated.
-
__init__
(file_name_pattern, file_format, dry_run=False)¶ - Parameters
file_name_pattern (str) – File name pattern for the output files. If it contains “{method_name}”, it is updated for each reduction writing with the name of the reduction.
file_format (str) – File format used. It is the default extension file.
dry_run (bool) – If dry_run, the file is created on memory but not saved on the file system at the end
-
close
()¶ Close the writer. Must not be used anymore.
-
get_fabio_image
(algorithm)¶ Get the constructed fabio image
- Return type
fabio.fabioimage.FabioImage
-
write_header
(merged_files, nb_frames, monitor_name)¶ Write the header of the average
- Parameters
merged_files (list) – List of files used to generate this output
nb_frames (int) – Number of frames used
monitor_name (str) – Name of the monitor used. Can be None.
-
write_reduction
(algorithm, data)¶ Write one reduction
- Parameters
algorithm (ImageReductionFilter) – Algorithm used
data (object) – Data of this reduction
-
-
class
pyFAI.average.
SumAveraging
¶ Bases:
pyFAI.average.ImageAccumulatorFilter
-
name
= 'sum'¶
-
-
pyFAI.average.
average_dark
(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 (str) – is the center calculated by a “mean”, “median”, “quantile”, “std”
cutoff (float or None) – keep all data where (I-center)/std < cutoff
quantiles (tuple(float, float) or None) – 2-tuple of floats average out data between the two quantiles
- Returns
2D image averaged
-
pyFAI.average.
average_images
(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', monitor_key=None)¶ - 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
str (monitor_key) – Key containing the monitor. Can be none.
- Returns
filename with the data or the data ndarray in case format=None
-
pyFAI.average.
bounding_box
(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.average.
common_prefix
(string_list)¶ Return the common prefix of a list of strings
TODO: move it into utils package
- Parameters
string_list (list(str)) – List of strings
- Return type
str
-
pyFAI.average.
create_algorithm
(filter_name, cut_off=None, quantiles=None)¶ Factory to create algorithm according to parameters
- Parameters
cutoff (float or None) – keep all data where (I-center)/std < cutoff
quantiles (tuple(float, float) or None) – 2-tuple of floats average out data between the two quantiles
- Returns
An algorithm
- Return type
- Raises
AlgorithmCreationError – If it is not possible to create the algorithm
-
pyFAI.average.
is_algorithm_name_exists
(filter_name)¶ Return true if the name is a name of a filter algorithm
-
pyFAI.average.
remove_saturated_pixel
(ds, threshold=0.1, minimum=None, maximum=None)¶ Remove saturated fixes from an array inplace.
- Parameters
ds – a dataset as ndarray
threshold (float) – what is the upper limit? all pixel > max*(1-threshold) are discareded.
minimum (float) – minumum valid value (or True for auto-guess)
maximum (float) – maximum valid value
- Returns
the input dataset
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_1D
= IntegrationMethod(1d int, full split, histogram, cython)¶
-
DEFAULT_METHOD_2D
= IntegrationMethod(2d int, pseudo split, histogram, cython)¶ Fail-safe low-memory integrator
-
USE_LEGACY_MASK_NORMALIZATION
= True¶ If true, the Python engine integrator will normalize the mask to use the most frequent value of the mask as the non-masking value.
This behaviour is not consistant with other engines and is now deprecated. This flag will be turned off in the comming releases.
Turning off this flag force the user to provide a mask with 0 as non-masking value. And any non-zero as masking value (negative or positive value). A boolean mask is also accepted (True is the masking value).
-
__init__
(dist=1, poni1=0, poni2=0, rot1=0, rot2=0, rot3=0, pixel1=None, pixel2=None, splineFile=None, detector=None, wavelength=None)¶ - Parameters
dist (float) – distance sample - detector plan (orthogonal distance, not along the beam), in meter.
poni1 (float) – coordinate of the point of normal incidence along the detector’s first dimension, in meter
poni2 (float) – coordinate of the point of normal incidence along the detector’s second dimension, in meter
rot1 (float) – first rotation from sample ref to detector’s ref, in radians
rot2 (float) – second rotation from sample ref to detector’s ref, in radians
rot3 (float) – third rotation from sample ref to detector’s ref, in radians
pixel1 (float) – Deprecated. Pixel size of the fist dimension of the detector, in meter. If both pixel1 and pixel2 are not None, detector pixel size is overwritten. Prefer defining the detector pixel size on the provided detector object. Prefer defining the detector pixel size on the provided detector object (
detector.pixel1 = 5e-6
).pixel2 (float) – Deprecated. Pixel size of the second dimension of the detector, in meter. If both pixel1 and pixel2 are not None, detector pixel size is overwritten. Prefer defining the detector pixel size on the provided detector object (
detector.pixel2 = 5e-6
).splineFile (str) – Deprecated. File containing the geometric distortion of the detector. If not None, pixel1 and pixel2 are ignored and detector spline is overwritten. Prefer defining the detector spline manually (
detector.splineFile = "file.spline"
).detector (str or pyFAI.Detector) – name of the detector or Detector instance. String description is deprecated. Prefer using the result of the detector factory:
pyFAI.detector_factory("eiger4m")
wavelength (float) – Wave length used in meter
-
create_mask
(data, mask=None, dummy=None, delta_dummy=None, unit=None, radial_range=None, azimuth_range=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
“where”: does a numpy.where on the “numpy” output
This method tries to accomodate various types of masks (like valid=0 & masked=-1, …)
Note for the developper: we use a lot of numpy.logical_or in this method, the out= argument allows to recycle buffers and save considerable time in allocating temporary arrays.
-
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)
-
property
darkcurrent
¶
-
property
darkfiles
¶
-
property
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
flat – ndarray with flatfield or None for no correction
- Returns
2tuple: corrected_data, flat_actually used (or None)
-
property
flatfield
¶
-
property
flatfiles
¶
-
get_darkcurrent
()¶
-
get_empty
()¶
-
get_flatfield
()¶
-
inpainting
(data, mask, npt_rad=1024, npt_azim=512, unit='r_m', method='splitpixel', poissonian=False, grow_mask=3)¶ Re-invent the values of masked pixels
- Parameters
data – input image as 2d numpy array
mask – masked out pixels array
npt_rad – number of radial points
npt_azim – number of azimuthal points
unit – unit to be used for integration
method – pathway for integration
poissonian – If True, add some poisonian noise to the data to make then more realistic
grow_mask – grow mask in polar coordinated to accomodate pixel splitting algoritm
- Returns
inpainting object which contains the restored image as .data
-
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, metadata=None)¶ 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, True for using the former correction
dark (ndarray) – dark noise image
flat (ndarray) – flat field image
method (can be Method named tuple, IntegrationMethod instance or str to be parsed) – 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.Unit) – 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 (bool) – if true return a dictionary with many more parameters (deprecated, please refer to the documentation of Integrate1dResult).
metadata – JSON serializable object containing the metadata, usually a dictionary.
- Returns
q/2th/r bins center positions and regrouped intensity (and error array if variance or variance model provided), uneless all==True.
- Return type
Integrate1dResult, dict
-
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=None, unit=q_nm^-1, safe=True, normalization_factor=1.0, all=False, metadata=None)¶ 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.Unit) – 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 (bool) – if true, return many more intermediate results as a dict (deprecated, please refer to the documentation of Integrate2dResult).
metadata – JSON serializable object containing the metadata, usually a dictionary.
- Returns
azimuthaly regrouped intensity, q/2theta/r pos. and chi pos.
- Return type
Integrate2dResult, dict
-
integrate_radial
(data, npt, npt_rad=100, correctSolidAngle=True, radial_range=None, azimuth_range=None, mask=None, dummy=None, delta_dummy=None, polarization_factor=None, dark=None, flat=None, method='csr', unit=chi_deg, radial_unit=q_nm^-1, normalization_factor=1.0)¶ Calculate the radial integrated profile curve as I = f(chi)
- Parameters
data (ndarray) – 2D array from the Detector/CCD camera
npt (int) – number of points in the output pattern
npt_rad (int) – number of points in the radial space. Too few points may lead to huge rounding errors.
filename (str) – output filename in 2/3 column ascii format
correctSolidAngle (bool) – correct for solid angle of each pixel if True
radial_range (Tuple(float, float)) – 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. Optional.
azimuth_range (Tuple(float, float)) – 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. Optional.
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, * True for using the former 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.Unit) – Output units, can be “chi_deg” or “chi_rad”
radial_unit (pyFAI.units.Unit) – unit used for radial representation, can be “q_nm^-1”, “q_A^-1”, “2th_deg”, “2th_rad”, “r_mm” for now
normalization_factor (float) – Value of a normalization monitor
- Returns
chi bins center positions and regrouped intensity
- Return type
Integrate1dResult
-
medfilt1d
(data, npt_rad=1024, npt_azim=512, correctSolidAngle=True, polarization_factor=None, dark=None, flat=None, method='splitpixel', unit=q_nm^-1, percentile=50, dummy=None, delta_dummy=None, mask=None, normalization_factor=1.0, metadata=None)¶ Perform the 2D integration and filter along each row using a median filter
- Parameters
data – input image as numpy array
npt_rad – number of radial points
npt_azim – number of azimuthal points
correctSolidAngle (bool) – correct for solid angle of each pixel if True
polarization_factor (float) – polarization factor between -1 (vertical) and +1 (horizontal). 0 for circular polarization or random, None for no correction, True for using the former correction
dark (ndarray) – dark noise image
flat (ndarray) – flat field image
unit – unit to be used for integration
method – pathway for integration and sort
percentile – which percentile use for cutting out percentil can be a 2-tuple to specify a region to average out
mask – masked out pixels array
normalization_factor (float) – Value of a normalization monitor
metadata (JSON serializable dict) – any other metadata,
- Returns
Integrate1D like result like
-
reset
()¶ Reset azimuthal integrator in addition to other arrays.
-
reset_engines
()¶ Urgently free memory by deleting all regrid-engines
-
save1D
(filename, dim1, I, error=None, dim1_unit=2th_deg, has_dark=False, has_flat=False, polarization_factor=None, normalization_factor=None)¶ This method save the result of a 1D integration.
Deprecated on 13/06/2017
- 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
has_dark (bool) – save the darks filenames (default: no)
has_flat (bool) – save the flat filenames (default: no)
polarization_factor (float) – the polarization factor
normalization_factor (float) – the monitor value
-
save2D
(filename, I, dim1, dim2, error=None, dim1_unit=2th_deg, has_dark=False, has_flat=False, polarization_factor=None, normalization_factor=None)¶ This method save the result of a 2D integration.
Deprecated on 13/06/2017
- 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
has_dark (bool) – save the darks filenames (default: no)
has_flat (bool) – save the flat filenames (default: no)
polarization_factor (float) – the polarization factor
normalization_factor (float) – the monitor value
-
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
SeparateResult which the bragg & amorphous signal
Note: the filtered 1D spectrum can be retrieved from SeparateResult.radial and SeparateResult.intensity
-
set_darkcurrent
(dark)¶
-
set_darkfiles
(files=None, method='mean')¶ Set the dark current from one or mutliple files, avaraged according to the method provided.
Moved to Detector.
- 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_empty
(value)¶
-
set_flatfield
(flat)¶
-
set_flatfiles
(files, method='mean')¶ Set the flat field from one or mutliple files, averaged according to the method provided.
Moved to Detector.
- Parameters
files (str or list(str) or None) – file(s) used to compute the flat-field.
method (str) – method used to compute the dark, “mean” or “median”
-
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.Unit) – 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.Unit) – 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.
-
sigma_clip
(data, npt_rad=1024, npt_azim=512, correctSolidAngle=True, polarization_factor=None, dark=None, flat=None, method='splitpixel', unit=q_nm^-1, thres=3, max_iter=5, dummy=None, delta_dummy=None, mask=None, normalization_factor=1.0, metadata=None)¶ Perform the 2D integration and perform a sigm-clipping iterative filter along each row. see the doc of scipy.stats.sigmaclip for the options.
- Parameters
data – input image as numpy array
npt_rad – number of radial points
npt_azim – number of azimuthal points
correctSolidAngle (bool) – correct for solid angle of each pixel if True
polarization_factor (float) –
polarization factor between -1 (vertical) and +1 (horizontal).
0 for circular polarization or random,
None for no correction,
True for using the former correction
dark (ndarray) – dark noise image
flat (ndarray) – flat field image
unit – unit to be used for integration
method – pathway for integration and sort
thres – cut-off for n*sigma: discard any values with (I-<I>)/sigma > thres. The threshold can be a 2-tuple with sigma_low and sigma_high.
max_iter – maximum number of iterations :param mask: masked out pixels array
normalization_factor (float) – Value of a normalization monitor
metadata (JSON serializable dict) – any other metadata,
- Returns
Integrate1D like result like
-
sigma_clip_ng
(data, npt=1024, correctSolidAngle=True, polarization_factor=None, variance=None, error_model=None, dark=None, flat=None, method=('no', 'csr', 'cython'), unit=q_nm^-1, thres=5.0, max_iter=5, dummy=None, delta_dummy=None, mask=None, normalization_factor=1.0, metadata=None, safe=True, **kwargs)¶ Performs iteratively the 1D integration with variance propagation and performs a sigm-clipping at each iteration, i.e. all pixel which intensity differs more than thres*std is discarded for next iteration.
Keep only pixels with intensty:
|I - <I>| < thres * std(I)
This enforces a gaussian distibution and is very good at extracting background or amorphous isotropic scattering out of Bragg peaks.
- Parameters
data – input image as numpy array
npt_rad – number of radial points
correctSolidAngle (bool) – correct for solid angle of each pixel if True
polarization_factor (float) – polarization factor between: -1 (vertical) +1 (horizontal). - 0 for circular polarization or random, - None for no correction, - True for using the former correction
dark (ndarray) – dark noise image
flat (ndarray) – flat field image
variance (ndarray) – the variance of the
unit – unit to be used for integration
method – pathway for integration and sort
thres – cut-off for n*sigma: discard any values with (I-<I>)/sigma > thres.
max_iter – maximum number of iterations
mask – masked out pixels array
normalization_factor (float) – Value of a normalization monitor
metadata (JSON serializable dict) – any other metadata,
safe – set to False to skip some tests
- Returns
Integrate1D like result like
The difference with the previous version is that there is not The standard deviation is usually smaller the the signal cleaner. It is also slightly faster.
The In
-
xrpd_OpenCL
(data, npt, filename=None, correctSolidAngle=True, dark=None, flat=None, tthRange=None, mask=None, dummy=None, delta_dummy=None, devicetype='gpu', useFp64=True, platformid=None, deviceid=None, safe=True)¶ Calculate the powder diffraction pattern from a set of data, an image.
This is (now) a pure pyopencl implementation so it just needs pyopencl which requires a clean OpenCL installation. This implementation is not slower than the previous Cython and is less problematic for compilation/installation.
- Parameters
data (ndarray) – 2D array from the CCD camera
npt (integer) – number of points in the output pattern
filename (str) – file to save data in ascii format 2 column
correctSolidAngle (bool or int) – solid angle correction, order 1 or 3 (like fit2d)
tthRange ((float, float), optional) – The lower and upper range of the 2theta
mask (ndarray) – array with 1 for masked pixels, and 0 for valid pixels
dummy (float) – value for dead/masked pixels (dynamic mask)
delta_dummy (float) – precision for dummy value
OpenCL specific parameters:
- Parameters
devicetype (str) – possible values “cpu”, “gpu”, “all” or “def”
useFp64 (bool) – shall histogram be done in double precision (strongly adviced)
platformid (int) – platform number
deviceid (int) – device number
safe (bool) – set to False if your GPU is already set-up correctly
- Returns
(2theta, I) angle being in degrees
- Return type
2-tuple of 1D arrays
This method compute the powder diffraction pattern, from a given data image. The number of point of the pattern is given by the npt parameter. If you give a filename, the powder diffraction is also saved as a two column text file. The powder diffraction is computed internally using an histogram which by default use should be done in 64bits. One can switch to 32 bits with the useFp64 parameter set to False. In 32bit mode; do not expect better than 1% error and one can even observe overflows ! 32 bits is only left for testing hardware capabilities and should NEVER be used in any real experiment analysis.
It is possible to correct or not the powder diffraction pattern using the correctSolidAngle parameter. The weight of a pixel is ponderate by its solid angle.
The 2theta range of the powder diffraction pattern can be set using the tthRange parameter. If not given the maximum available range is used. Indeed pixel outside this range are ignored.
Each pixel of the data image has also a chi coordinate. So it is possible to restrain the chi range of the pixels to consider in the powder diffraction pattern. You just need to set the range with the chiRange parameter; like the tthRange parameter, value outside this range are ignored.
Sometimes one needs to mask a few pixels (beamstop, hot pixels, …), to ignore a few of them you just need to provide a mask array with a value of 1 for those pixels. To take a pixel into account you just need to set a value of 0 in the mask array. Indeed the shape of the mask array should be idential to the data shape (size of the array _must_ be the same).
Bad pixels can also be masked by setting them to an impossible value (-1) and calling this value the “dummy value”. Some Pilatus detectors are setting non existing pixel to -1 and dead pixels to -2. Then use dummy=-2 & delta_dummy=1.5 so that any value between -3.5 and -0.5 are considered as bad.
devicetype, platformid and deviceid, parameters are specific to the OpenCL implementation. If you set devicetype to ‘all’, ‘cpu’, ‘gpu’, ‘def’ you can force the device used to perform the computation; the program will select the device accordinly. By setting platformid and deviceid, you can directly address a specific device (which is computer specific).
The safe parameter is specific to the integrator object, located on the OpenCL device. You can set it to False if you think the integrator is already setup correcty (device, geometric arrays, mask, 2theta/chi range). Unless many tests will be done at each integration.
Nota: this deprecated code is maintained until a new histograming on GPU is available
-
multi_geometry
Module¶
Module for treating simultaneously multiple detector configuration within a single integration
-
class
pyFAI.multi_geometry.
MultiGeometry
(ais, unit='2th_deg', radial_range=(0, 180), azimuth_range=(-180, 180), wavelength=None, empty=0.0, chi_disc=180)¶ Bases:
object
This is an Azimuthal integrator containing multiple geometries, for example when the detector is on a goniometer arm
-
__init__
(ais, unit='2th_deg', radial_range=(0, 180), azimuth_range=(-180, 180), wavelength=None, empty=0.0, chi_disc=180)¶ Constructor of the multi-geometry integrator :param ais: list of azimuthal integrators :param radial_range: common range for integration :param azimuthal_range: common range for integration :param empty: value for empty pixels :param chi_disc: if 0, set the chi_discontinuity at
-
integrate1d
(lst_data, npt=1800, correctSolidAngle=True, lst_variance=None, error_model=None, polarization_factor=None, normalization_factor=None, all=False, lst_mask=None, lst_flat=None, method='splitpixel')¶ Perform 1D azimuthal integration
- Parameters
lst_data – list of numpy array
npt – number of points int the integration
correctSolidAngle – correct for solid angle (all processing are then done in absolute solid angle !)
lst_variance (list of ndarray) – list of 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)
polarization_factor – Apply polarization correction ? is None: not applies. Else provide a value from -1 to +1
normalization_factor – normalization monitors value (list of floats)
all – return a dict with all information in it (deprecated, please refer to the documentation of Integrate1dResult).
lst_mask – numpy.Array or list of numpy.array which mask the lst_data.
lst_flat – numpy.Array or list of numpy.array which flat the lst_data.
method – integration method, a string or a registered method
- Returns
2th/I or a dict with everything depending on “all”
- Return type
Integrate1dResult, dict
-
integrate2d
(lst_data, npt_rad=1800, npt_azim=3600, correctSolidAngle=True, lst_variance=None, error_model=None, polarization_factor=None, normalization_factor=None, all=False, lst_mask=None, lst_flat=None, method='splitpixel')¶ Performs 2D azimuthal integration of multiples frames, one for each geometry
- Parameters
lst_data – list of numpy array
npt – number of points int the integration
correctSolidAngle – correct for solid angle (all processing are then done in absolute solid angle !)
lst_variance (list of ndarray) – list of 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)
polarization_factor – Apply polarization correction ? is None: not applies. Else provide a value from -1 to +1
normalization_factor – normalization monitors value (list of floats)
all – return a dict with all information in it (deprecated, please refer to the documentation of Integrate2dResult).
lst_mask – numpy.Array or list of numpy.array which mask the lst_data.
lst_flat – numpy.Array or list of numpy.array which flat the lst_data.
method – integration method (or its name)
- Returns
I/2th/chi or a dict with everything depending on “all”
- Return type
Integrate2dResult, dict
-
set_wavelength
(value)¶ Changes the wavelength of a group of azimuthal integrators
-
geometry
Module¶
This modules contains only one (large) class in charge of:
calculating the geometry, i.e. the position in the detector space of each pixel of the detector
manages caches to store intermediate results
NOTA: The Geometry class is not a “transformation class” which would take a detector and transform it. It is rather a description of the experimental setup.
-
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 the parent-class of azimuthal integrator.
This class contains a detector (using composition) which provides the position of all pixels, or only a limited set of pixel indices. The Geometry class is responsible for translating/rotating those pixel to their position in reference to the sample position. The description of the experimental setup is inspired by the work of P. Boesecke
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
Demonstration of the equation done using Mathematica:
Axis 1 is allong first dimension of detector (when not tilted), this is the slow dimension of the image array in C or Y In[5]:= x1={1,0,0} Out[5]= {1,0,0} Axis 2 is allong second dimension of detector (when not tilted), this is the fast dimension of the image in C or X In[6]:= x2={0,1,0} Out[6]= {0,1,0} Axis 3 is along the incident X-Ray beam In[7]:= x3={0,0,1} Out[7]= {0,0,1} In[9]:= id3={x1,x2,x3} Out[9]= {{1,0,0},{0,1,0},{0,0,1}} In[10]:= {{1,0,0},{0,1,0},{0,0,1}} Out[10]= {{1,0,0},{0,1,0},{0,0,1}} In[11]:= rotM1=RotationMatrix[rot1,x1] Out[11]= {{1,0,0},{0,Cos[rot1],-Sin[rot1]},{0,Sin[rot1],Cos[rot1]}} In[12]:= rotM2 = RotationMatrix[rot2,x2] Out[12]= {{Cos[rot2],0,Sin[rot2]},{0,1,0},{-Sin[rot2],0,Cos[rot2]}} In[13]:= rotM3 = RotationMatrix[rot3,x3] Out[13]= {{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 In[14]:= R=rotM3.rotM2.rotM1 Out[14]= {{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[15]:= CForm[R.x1] Out[15]//CForm= List(Cos(rot2)*Cos(rot3),Cos(rot2)*Sin(rot3),-Sin(rot2)) In[16]:= CForm[R.x2] Out[16]//CForm= List(Cos(rot3)*Sin(rot1)*Sin(rot2) - Cos(rot1)*Sin(rot3),Cos(rot1)*Cos(rot3) + Sin(rot1)*Sin(rot2)*Sin(rot3),Cos(rot2)*Sin(rot1)) In[17]:= CForm[R.x3] Out[17]//CForm= List(Cos(rot1)*Cos(rot3)*Sin(rot2) + Sin(rot1)*Sin(rot3),-(Cos(rot3)*Sin(rot1)) + Cos(rot1)*Sin(rot2)*Sin(rot3),Cos(rot1)*Cos(rot2)) In[18]:= CForm[Det[R]] Out[18]//CForm= Power(Cos(rot1),2)*Power(Cos(rot2),2)*Power(Cos(rot3),2) + Power(Cos(rot2),2)*Power(Cos(rot3),2)*Power(Sin(rot1),2) + Power(Cos(rot1),2)*Power(Cos(rot3),2)*Power(Sin(rot2),2) + Power(Cos(rot3),2)*Power(Sin(rot1),2)*Power(Sin(rot2),2) + Power(Cos(rot1),2)*Power(Cos(rot2),2)*Power(Sin(rot3),2) + Power(Cos(rot2),2)*Power(Sin(rot1),2)*Power(Sin(rot3),2) + Power(Cos(rot1),2)*Power(Sin(rot2),2)*Power(Sin(rot3),2) + Power(Sin(rot1),2)*Power(Sin(rot2),2)*Power(Sin(rot3),2) In[13]:= Any pixel on detector plan at coordianate (d1, d2) in meters. Detector is at z=L In[22]:= P={d1,d2,L} CForm[R.P] Out[22]= {d1,d2,L} Out[23]//CForm= List(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)),L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2)) In[24]:= t1 = R.P.x1 CForm[t1] Out[24]= 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]) Out[25]//CForm= 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)) In[26]:= t2 = R.P.x2 CForm[t2] Out[26]= 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]) Out[27]//CForm= 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)) In[28]:= t3=R.P.x3 CForm[t3] Out[28]= L Cos[rot1] Cos[rot2]+d2 Cos[rot2] Sin[rot1]-d1 Sin[rot2] Out[29]//CForm= L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2) Distance sample to detector point (d1,d2) (no Mathematica translations) GraphicsBox[ TagBox[RasterBox[CompressedData[" 1:eJxtUstqU1EUDY2iUdSOnBcERwGHDgQf+YNGOrAQSEBBBwlWQfsDcVKsI4sf IAQnGSQtCQ4yyfvVvO69SW7J+9W8GtIkg8SwXfuQSpFu2Pdxzl5rr7XP2bDY Nt+saTSaDzfx2DR/er6zY941XsPPi92Pry1afNxdJS9ejuFwqJNl+XMsFstE o1HijEQio1Qq9bPZbD7SXBHtdnsjGAxK+Xyeut0uTadTms1mNBgMqFwuUyKR +APOd5cxo9HoHjBqqVSis7Mzms/nlMlkyOfziX/GdzodSiaTpCjKqwscar6o qkq9Xo/Oz89pb2+PjEYj2Ww22t7epn6/L/DcF/wdt9u9Di4tPAxarZbgZKzd bmde4jCZTORyuUTPWq1G8Erwb0HdQ2gn+KZ6vU6np6eCm8PhcNDW1hZVKhWx xvusH/P6jronwVCIcpJE2VxOvLvQ5Q8EyGAwkMfjERilUBCYCGrj8fiv8Xj8 IIAa1iVJMsnIIWZ4dHRE+1/3hW72pUgK5cALTzyfbzwX4Kt5WSb15IRU8M5w BgcHB2S1WqkL3TxntVgU3CH0g7+XjGs0Gm/D4bDgZS/QQH6/n5xOp+iH/X8z QY+0Xq9fZ9xyudRKknTIGpibZzOZTMQMcYeoWq1SNptlzMzr9T4G5PbFGS4W C12hUHDwbNlHEbr4TMEn7hvW69DwDKV3kGv/3zfUPU2n0z+g6Rj+j/H+jXxv Npvvr/por7qnq+C9G8hbq9Qhr18u+AttYAMa "], {{0, 14}, {14, 0}}, {0, 255}, ColorFunction->RGBColor], BoxForm`ImageTag["Byte", ColorSpace -> "RGB", Interleaving -> True], Selectable->False], BaseStyle->"ImageGraphics", ImageSize->Magnification[1], ImageSizeRaw->{14, 14}, PlotRange->{{0, 14}, {0, 14}}] In[30]:= dist = Norm[R.P] CForm[dist] Out[30]= √(Abs[L Cos[rot1] Cos[rot2]+d2 Cos[rot2] Sin[rot1]-d1 Sin[rot2]]^2+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+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) Out[31]//CForm= Sqrt(Power(Abs(L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2)),2) + Power(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) + Power(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) can be defined as (R.P component along x3) over the distance |R.P| In[32]:= tthc = ArcCos [-(R.P).x3/Norm[R.P]] CForm[tthc] Out[32]= ArcCos[(-L Cos[rot1] Cos[rot2]-d2 Cos[rot2] Sin[rot1]+d1 Sin[rot2])/(√(Abs[L Cos[rot1] Cos[rot2]+d2 Cos[rot2] Sin[rot1]-d1 Sin[rot2]]^2+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+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))] Out[33]//CForm= ArcCos((-(L*Cos(rot1)*Cos(rot2)) - d2*Cos(rot2)*Sin(rot1) + d1*Sin(rot2))/ Sqrt(Power(Abs(L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2)),2) + Power(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) + Power(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))) In[41]:= ttht = ArcTan[t3,Sqrt[t1^2 + t2^2]] CForm[ttht] Out[41]= ArcTan[L Cos[rot1] Cos[rot2]+d2 Cos[rot2] Sin[rot1]-d1 Sin[rot2],√((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+(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)] Out[42]//CForm= ArcTan(L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2),Sqrt(Power(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) + Power(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))) 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 In[36]:= chi =ArcTan[t1 , t2] CForm[chi] Out[36]= ArcTan[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])] Out[37]//CForm= ArcTan(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))) Coodinates of the Point of Normal Incidence In[38]:= PONI = R.{0,0,L} CForm[PONI] Out[38]= {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]} Out[39]//CForm= List(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)) Derivatives of 2Theta In[43]:= CForm[D[ttht,d1]] Out[43]//CForm= ((L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2))*(2*Cos(rot2)*Cos(rot3)*(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*Cos(rot2)*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)))))/ (2.*Sqrt(Power(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) + Power(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))* (Power(L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2),2) + Power(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) + Power(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))) + (Sin(rot2)*Sqrt(Power(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) + Power(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)))/ (Power(L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2),2) + Power(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) + Power(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)) In[44]:= CForm[D[ttht,d2]] Out[44]//CForm= ((L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2))*(2*(Cos(rot3)*Sin(rot1)*Sin(rot2) - Cos(rot1)*Sin(rot3))* (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*(Cos(rot1)*Cos(rot3) + Sin(rot1)*Sin(rot2)*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)))))/ (2.*Sqrt(Power(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) + Power(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))* (Power(L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2),2) + Power(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) + Power(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(rot2)*Sin(rot1)*Sqrt(Power(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) + Power(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)))/ (Power(L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2),2) + Power(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) + Power(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)) In[47]:= CForm[D[ttht,L]] Out[47]//CForm= ((L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2))*(2*(Cos(rot1)*Cos(rot3)*Sin(rot2) + Sin(rot1)*Sin(rot3))* (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*(-(Cos(rot3)*Sin(rot1)) + Cos(rot1)*Sin(rot2)*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)))))/ (2.*Sqrt(Power(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) + Power(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))* (Power(L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2),2) + Power(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) + Power(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(rot1)*Cos(rot2)*Sqrt(Power(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) + Power(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)))/ (Power(L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2),2) + Power(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) + Power(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)) In[48]:= CForm[D[ttht,rot1]] Out[48]//CForm= ((L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2))*(2*(L*(-(Cos(rot3)*Sin(rot1)*Sin(rot2)) + Cos(rot1)*Sin(rot3)) + d2*(Cos(rot1)*Cos(rot3)*Sin(rot2) + Sin(rot1)*Sin(rot3)))* (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*(d2*(-(Cos(rot3)*Sin(rot1)) + Cos(rot1)*Sin(rot2)*Sin(rot3)) + L*(-(Cos(rot1)*Cos(rot3)) - Sin(rot1)*Sin(rot2)*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)))))/ (2.*Sqrt(Power(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) + Power(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))* (Power(L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2),2) + Power(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) + Power(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))) - ((d2*Cos(rot1)*Cos(rot2) - L*Cos(rot2)*Sin(rot1))*Sqrt(Power(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) + Power(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)))/ (Power(L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2),2) + Power(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) + Power(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)) In[49]:= CForm[D[ttht,rot2]] Out[49]//CForm= ((L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2))*(2*(L*Cos(rot1)*Cos(rot2)*Cos(rot3) + d2*Cos(rot2)*Cos(rot3)*Sin(rot1) - d1*Cos(rot3)*Sin(rot2))* (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*(L*Cos(rot1)*Cos(rot2)*Sin(rot3) + d2*Cos(rot2)*Sin(rot1)*Sin(rot3) - d1*Sin(rot2)*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)))))/ (2.*Sqrt(Power(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) + Power(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))* (Power(L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2),2) + Power(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) + Power(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))) - ((-(d1*Cos(rot2)) - L*Cos(rot1)*Sin(rot2) - d2*Sin(rot1)*Sin(rot2))*Sqrt(Power(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) + Power(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))) /(Power(L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2),2) + Power(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) + Power(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)) In[50]:= CForm[D[ttht,rot3]] Out[50]//CForm= ((L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2))*(2*(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))) + 2*(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)))))/ (2.*Sqrt(Power(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) + Power(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))* (Power(L*Cos(rot1)*Cos(rot2) + d2*Cos(rot2)*Sin(rot1) - d1*Sin(rot2),2) + Power(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) + Power(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)))
-
__init__
(dist=1, poni1=0, poni2=0, rot1=0, rot2=0, rot3=0, pixel1=None, pixel2=None, splineFile=None, detector=None, wavelength=None)¶ - Parameters
dist – distance sample - detector plan (orthogonal distance, not along the beam), in meter.
poni1 – coordinate of the point of normal incidence along the detector’s first dimension, in meter
poni2 – coordinate of the point of normal incidence along the detector’s second dimension, in meter
rot1 – first rotation from sample ref to detector’s ref, in radians
rot2 – second rotation from sample ref to detector’s ref, in radians
rot3 – third rotation from sample ref to detector’s ref, in radians
pixel1 (float) – Deprecated. Pixel size of the fist dimension of the detector, in meter. If both pixel1 and pixel2 are not None, detector pixel size is overwritten. Prefer defining the detector pixel size on the provided detector object. Prefer defining the detector pixel size on the provided detector object (
detector.pixel1 = 5e-6
).pixel2 (float) – Deprecated. Pixel size of the second dimension of the detector, in meter. If both pixel1 and pixel2 are not None, detector pixel size is overwritten. Prefer defining the detector pixel size on the provided detector object (
detector.pixel2 = 5e-6
).splineFile (str) – Deprecated. File containing the geometric distortion of the detector. If not None, pixel1 and pixel2 are ignored and detector spline is overwritten. Prefer defining the detector spline manually (
detector.splineFile = "file.spline"
).detector (str or pyFAI.Detector) – name of the detector or Detector instance. String description is deprecated. Prefer using the result of the detector factory:
pyFAI.detector_factory("eiger4m")
wavelength (float) – Wave length used in meter
-
array_from_unit
(shape=None, typ='center', unit=2th_deg, scale=True)¶ Generate an array of position in different dimentions (R, Q, 2Theta)
- Parameters
shape (ndarray.shape) – shape of the expected array, leave it to None for safety
typ (str) – “center”, “corner” or “delta”
unit (pyFAI.units.Enum) – can be Q, TTH, R for now
scale – set to False for returning the internal representation (S.I. often) which is faster
- 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.
Nota: dim3 is the same as dim0
- Parameters
d0 – altitude on the point compared to the detector (i.e. z), may be None
d1 – position on the detector along the slow dimension (i.e. y)
d2 – position on the detector along the fastest dimension (i.e. x)
corners – return positions on the corners (instead of center)
- Returns
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.
\[ \begin{align}\begin{aligned}Icor = \frac{Iobs(1-t0)}{1-exp(ln(t0)/cos(incidence))}\\let_t = \frac{1-exp(ln(t0)/cos(incidence))}{1 - t0}\end{aligned}\end{align} \]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, polarization_axis_offset=0, dark=None, flat=None)¶ Computes a 2D image from a 1D integrated profile
- Parameters
tth – 1D array with radial unit, this array needs to be ordered
I – scattering intensity, corresponding 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
polarization_axis_offset – axis_offset to be send to the polarization method
dark – dark current correction
flat – flatfield corrction
- Returns
2D image reconstructed
-
calcfrom2d
(I, tth, chi, shape=None, mask=None, dim1_unit=2th_deg, dim2_unit=chi_deg, correctSolidAngle=True, dummy=0.0, polarization_factor=None, polarization_axis_offset=0, dark=None, flat=None)¶ Computes a 2D image from a cake / 2D integrated image
- Parameters
I – scattering intensity, as an image n_tth, n_chi
tth – 1D array with radial unit, this array needs to be ordered
chi – 1D array with azimuthal unit, this array needs to be ordered
shape – shape of the image (if not defined by the detector)
dim1_unit – unit for the “tth” array
dim2_unit – unit for the “chi” array
correctSolidAngle –
dummy – value for masked pixels
polarization_factor – set to true to use previously used value
polarization_axis_offset – axis_offset to be send to the polarization method
dark – dark current correction
flat – flatfield corrction
- Returns
2D image reconstructed
-
center_array
(shape=None, unit='2th_deg', scale=True)¶ Generate a 2D array of the given shape with (i,j) (radial angle ) for all elements.
- Parameters
shape (2-tuple of integer) – expected shape
unit – string like “2th_deg” or an instance of pyFAI.units.Unit
scale – set to False for returning the internal representation (S.I. often) which is faster
- Returns
3d array with shape=(*shape,4,2) the two elements are: - dim3[0]: radial angle 2th, q, r… - dim3[1]: azimuthal angle chi
-
check_chi_disc
(azimuth_range)¶ Check the position of the \(\chi\) discontinuity
- Parameters
range – range of chi for the integration
- Returns
True if there is a problem
-
chi
(d1, d2, path='cython')¶ Calculate the chi (azimuthal angle) for the centre of a pixel at coordinate d1, d2. Conversion to lab coordinate system is performed in calc_pos_zyx.
- 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:
- 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
-
property
chia
¶ chi array in cache
-
cornerArray
(shape=None)¶ Generate a 4D 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 * dim3[1]: azimuthal angle chi
-
cornerQArray
(shape=None)¶ Generate a 3D array of the given shape with (i,j) (azimuthal angle) for all elements.
- Parameters
shape (2-tuple of integer) – expected shape
- Returns
3d array with shape=(*shape,4,2) the two elements are (scattering vector q, azimuthal angle chi)
-
cornerRArray
(shape=None)¶ Generate a 3D array of the given shape with (i,j) (azimuthal angle) for all elements.
- Parameters
shape (2-tuple of integer) – expected shape
- Returns
3d array with shape=(*shape,4,2) the two elements are (radial distance, azimuthal angle chi)
-
cornerRd2Array
(shape=None)¶ Generate a 3D array of the given shape with (i,j) (azimuthal angle) for all elements.
- Parameters
shape (2-tuple of integer) – expected shape
- Returns
3d array with shape=(*shape,4,2) the two elements are (reciprocal spacing squared, azimuthal angle chi)
-
corner_array
(shape=None, unit=None, use_cython=True, scale=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
unit – string like “2th_deg” or an instance of pyFAI.units.Unit
use_cython – set to False to use the slower Python path (for tests)
scale – set to False for returning the internal representation (S.I. often) which is faster
- Returns
3d array with shape=(*shape,4,2) the two elements are: - dim3[0]: radial angle 2th, q, r… - dim3[1]: azimuthal angle chi
-
property
correct_SA_spline
¶
-
cos_incidence
(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, use_cython=True)¶ 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_deg', scale=False)¶ 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
unit – string like “2th_deg” or an instance of pyFAI.units.Unit
scale – set to False for returning the internal representation (S.I. often) which is faster
- 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)
\[ \begin{align}\begin{aligned}dOmega = \frac{Omega(P)}{Omega(C)} = \frac{A \cdot cos(a)}{SP^2} \cdot \frac{SC^2}{A \cdot cos(0)} = \frac{3}{cos(a)} = \frac{SC^3}{SP^3}\\cos(a) = \frac{SC}{SP}\end{aligned}\end{align} \]- 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
-
property
dist
¶
-
property
dssa
¶ solid angle array in cache
-
getFit2D
()¶ Export geometry setup with the geometry of Fit2D
- Returns
dict with parameters compatible with fit2D geometry
-
getImageD11
()¶ Export the current geometry in ImageD11 format. Please refer to the documentation in doc/source/geometry_conversion.rst for the orientation and units of those values.
- Returns
an Ordered dict with those parameters: distance 294662.658 #in nm o11 1 o12 0 o21 0 o22 -1 tilt_x 0.00000 tilt_y -0.013173 tilt_z 0.002378 wavelength 0.154 y_center 1016.328171 y_size 48.0815 z_center 984.924425 z_size 46.77648
-
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_config
()¶ return the configuration as a dictionnary
- Returns
dictionary with the current configuration
-
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 ….
- Parameters
shape – force this value (2-tuple of int)
- Returns
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
- Returns
itself with updated parameters
-
make_headers
(type_='list')¶ Create a configuration for the
- Parameters
type – can be “list” or “dict”
- Returns
the header with the proper format
-
property
mask
¶
-
property
maskfile
¶
-
normalize_azimuth_range
(azimuth_range)¶ Convert the azimuth range from degrees to radians
This method takes care of the position of the discontinuity and adapts the range accordingly!
- Parameters
azimuth_range – 2-tuple of float in degrees
- Returns
2-tuple of float in radians in a range such to avoid the discontinuity
-
oversampleArray
(myarray)¶
-
property
pixel1
¶
-
property
pixel2
¶
-
polarization
(shape=None, factor=None, axis_offset=0, with_checksum=False)¶ 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 (circular/random polarization) and 1 (where division by 0 could occure at 2th=90, chi=0)
axis_offset – Angle between the polarization main axis and detector’s X direction (in radians !!!)
- Returns
2D array with polarization correction array (intensity/polarisation)
-
property
poni1
¶
-
property
poni2
¶
-
positionArray
(*arg, **kwarg)¶ Deprecated version of
position_array()
, left for compatibility see doc of position_array
-
position_array
(shape=None, corners=False, dtype=<class 'numpy.float64'>, use_cython=True)¶ 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. Double precision is needed for fitting the geometry
use_cython ((bool)) – set to false to test the Python path (slower)
- 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
(d1, d2)¶ Calculate the q_vector for any pixel corner (in nm^-1)
- Parameters
shape – expected shape of the detector
-
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.
-
property
qa
¶ Q array in cache
-
quaternion
(param=None)¶ Calculate the quaternion associated to the current rotations from rot1, rot2, rot3.
Uses the transformations-library from C. Gohlke
- Parameters
param – use this set of parameters instead of the default one.
- Returns
numpy array with 4 elements [w, x, y, z]
-
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
(d1, d2)¶ Calculate the radius array for any pixel corner (in m)
-
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.
-
property
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
- Returns
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
- Returns
itself with updated parameters
-
reset
()¶ reset most arrays that are cached: used when a parameter changes.
-
property
rot1
¶
-
property
rot2
¶
-
property
rot3
¶
-
rotation_matrix
(param=None)¶ Compute and return the detector tilts as a single rotation matrix
Corresponds to rotations about axes 1 then 2 then 3 (=> 0 later on) For those using spd (PB = Peter Boesecke), tilts relate to this system (JK = Jerome Kieffer) as follows: JK1 = PB2 (Y) JK2 = PB1 (X) JK3 = PB3 (Z) …slight differences will result from the order FIXME: make backwards and forwards converter helper function
axis1 is vertical and perpendicular to beam axis2 is horizontal and perpendicular to beam axis3 is along the beam, becomes axis0 see: http://pyfai.readthedocs.io/en/latest/geometry.html#detector-position or ../doc/source/img/PONI.png
- Parameters
param (list of float) – list of geometry parameters, defaults to self.param uses elements [3],[4],[5]
- Returns
rotation matrix
- Return type
3x3 float array
-
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
-
setImageD11
(param)¶ Set the geometry from the parameter set which contains distance, o11, o12, o21, o22, tilt_x, tilt_y tilt_z, wavelength, y_center, y_size, z_center and z_size. Please refer to the documentation in doc/source/geometry_conversion.rst for the orientation and units of those values.
- Parameters
param – dict with the values to set.
-
setOversampling
(iOversampling)¶ set the oversampling factor
-
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)
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
-
set_chia
(_)¶
-
set_config
(config)¶ Set the config of the geometry and of the underlying detector
- Parameters
config – dictionary with the configuration
- Returns
itself
-
set_correct_solid_angle_for_spline
(value)¶
-
set_dist
(value)¶
-
set_dssa
(_)¶
-
set_mask
(mask)¶
-
set_maskfile
(maskfile)¶
-
set_param
(param)¶ set the geometry from a 6-tuple with dist, poni1, poni2, rot1, rot2, rot3
-
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_rot_from_quaternion
(w, x, y, z)¶ Quaternions are convieniant ways to represent 3D rotation This method allows to define rot1(left-handed), rot2(left-handed) and rot3 (right handed) as definied in the documentation from a quaternion, expressed in the right handed (x1, x2, x3) basis set.
Uses the transformations-library from C. Gohlke
- Parameters
w – Real part of the quaternion (correspond to cos alpha/2)
x – Imaginary part of the quaternion, correspond to u1*sin(alpha/2)
y – Imaginary part of the quaternion, correspond to u2*sin(alpha/2)
z – Imaginary part of the quaternion, correspond to u3*sin(alpha/21)
-
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
-
property
spline
¶
-
property
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
(d1, d2)¶ Calculates the 2theta value for the corner 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)
- Returns
2theta in radians
- Return type
floar or array of floats.
-
property
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
-
property
wavelength
¶
-
write
(filename)¶ Save the geometry parameters.
- Parameters
filename (string) – name of the file where to save the parameters
geometryRefinement
Module¶
Module used to perform the geometric refinement of the model
-
class
pyFAI.geometryRefinement.
GeometryRefinement
(data=None, dist=1, poni1=None, poni2=None, rot1=0, rot2=0, rot3=0, pixel1=None, pixel2=None, splineFile=None, detector=None, wavelength=None, calibrant=None)¶ Bases:
pyFAI.azimuthalIntegrator.AzimuthalIntegrator
-
__init__
(data=None, dist=1, poni1=None, poni2=None, rot1=0, rot2=0, rot3=0, pixel1=None, pixel2=None, splineFile=None, detector=None, wavelength=None, calibrant=None)¶ - Parameters
data – ndarray float64 shape = n, 3 col0: pos in dim0 (in pixels) col1: pos in dim1 (in pixels) col2: ring index in calibrant object
dist – guessed sample-detector distance (optional, in m)
poni1 – guessed PONI coordinate along the Y axis (optional, in m)
poni2 – guessed PONI coordinate along the X axis (optional, in m)
rot1 – guessed tilt of the detector around the Y axis (optional, in rad)
rot2 – guessed tilt of the detector around the X axis (optional, in rad)
rot3 – guessed tilt of the detector around the incoming beam axis (optional, in rad)
pixel1 – Pixel size along the vertical direction of the detector (in m), almost mandatory
pixel2 – Pixel size along the horizontal direction of the detector (in m), almost mandatory
splineFile – file describing the detector as 2 cubic splines. Replaces pixel1 & pixel2
detector – name of the detector or Detector instance. Replaces splineFile, pixel1 & pixel2
wavelength – wavelength in m (1.54e-10)
calibrant – instance of pyFAI.calibrant.Calibrant containing the d-Spacing
-
anneal
(maxiter=1000000)¶
-
calc_2th
(rings, wavelength=None)¶ - Parameters
rings – indices of the rings. starts at 0 and self.dSpacing should be long enough !!!
wavelength – wavelength in meter
-
chi2
(param=None)¶
-
chi2_wavelength
(param=None)¶
-
confidence
(with_rot=True)¶ Confidence interval obtained from the second derivative of the error function next to its minimum value.
Note the confidence interval increases with the number of points which is “surprizing”
- Parameters
with_rot – if true include rot1 & rot2 in the parameter set.
- Returns
std_dev, confidence
-
curve_fit
(with_rot=True)¶ Refine the geometry and provide confidence interval Use curve_fit from scipy.optimize to not only refine the geometry (unconstrained fit)
- Parameters
with_rot – include rotation intro error measurment
- Returns
std_dev, confidence
-
property
dist_max
¶
-
property
dist_min
¶
-
get_dist_max
()¶
-
get_dist_min
()¶
-
get_poni1_max
()¶
-
get_poni1_min
()¶
-
get_poni2_max
()¶
-
get_poni2_min
()¶
-
get_rot1_max
()¶
-
get_rot1_min
()¶
-
get_rot2_max
()¶
-
get_rot2_min
()¶
-
get_rot3_max
()¶
-
get_rot3_min
()¶
-
get_wavelength_max
()¶
-
get_wavelength_min
()¶
-
guess_poni
(fixed=None)¶ PONI can be guessed by the centroid of the ring with lowest 2Theta
It may try to fit an ellipse and sometimes it works
-
property
poni1_max
¶
-
property
poni1_min
¶
-
property
poni2_max
¶
-
property
poni2_min
¶
-
refine1
()¶
-
refine2
(maxiter=1000000, fix=None)¶
-
refine2_wavelength
(maxiter=1000000, fix=None)¶ Refine all parameters including the wavelength.
This implies that it enforces an upper limit to the wavelength depending on the number of rings.
-
residu1
(param, d1, d2, rings)¶
-
residu1_wavelength
(param, d1, d2, rings)¶
-
residu2
(param, d1, d2, rings)¶
-
residu2_wavelength
(param, d1, d2, rings)¶
-
residu2_wavelength_weighted
(param, d1, d2, rings, weight)¶
-
residu2_weighted
(param, d1, d2, rings, weight)¶
-
roca
()¶ run roca to optimise the parameter set
-
property
rot1_max
¶
-
property
rot1_min
¶
-
property
rot2_max
¶
-
property
rot2_min
¶
-
property
rot3_max
¶
-
property
rot3_min
¶
-
set_dist_max
(value)¶
-
set_dist_min
(value)¶
-
set_poni1_max
(value)¶
-
set_poni1_min
(value)¶
-
set_poni2_max
(value)¶
-
set_poni2_min
(value)¶
-
set_rot1_max
(value)¶
-
set_rot1_min
(value)¶
-
set_rot2_max
(value)¶
-
set_rot2_min
(value)¶
-
set_rot3_max
(value)¶
-
set_rot3_min
(value)¶
-
set_tolerance
(value=10)¶ Set the tolerance for a refinement of the geometry; in percent of the original value
- Parameters
value – Tolerance as a percentage
-
set_wavelength_max
(value)¶
-
set_wavelength_min
(value)¶
-
simplex
(maxiter=1000000)¶
-
update_values
(dist=None, wavelength=None, poni1=None, poni2=None, rot1=None, rot2=None, rot3=None, fixed=None)¶ Update values taking care of fixed parameters.
-
property
wavelength_max
¶
-
property
wavelength_min
¶
-
goniometer
Module¶
Everything you need to calibrate a detector mounted on a goniometer or any translation table
-
class
pyFAI.goniometer.
BaseTransformation
(funct, param_names, pos_names=None)¶ Bases:
object
This class, once instanciated, behaves like a function (via the __call__ method). It is responsible for taking any input geometry and translate it into a set of parameters compatible with pyFAI, i.e. a tuple with: (dist, poni1, poni2, rot1, rot2, rot3)
This class relies on a user provided function which does the work.
-
__init__
(funct, param_names, pos_names=None)¶ Constructor of the class
- Parameters
funct – function which takes as parameter the param_names and the pos_name
param_names – list of names of the parameters used in the model
pos_names – list of motor names for gonio with >1 degree of freedom
-
to_dict
()¶ Export the instance representation for serialization as a dictionary
-
-
class
pyFAI.goniometer.
ExtendedTransformation
(dist_expr=None, poni1_expr=None, poni2_expr=None, rot1_expr=None, rot2_expr=None, rot3_expr=None, wavelength_expr=None, param_names=None, pos_names=None, constants=None, content=None)¶ Bases:
object
This class behaves like GeometryTransformation and extends transformation to the wavelength parameter.
This function uses numexpr for formula evaluation.
-
__init__
(dist_expr=None, poni1_expr=None, poni2_expr=None, rot1_expr=None, rot2_expr=None, rot3_expr=None, wavelength_expr=None, param_names=None, pos_names=None, constants=None, content=None)¶ Constructor of the class
- Parameters
dist_expr – formula (as string) providing with the dist
poni1_expr – formula (as string) providing with the poni1
poni2_expr – formula (as string) providing with the poni2
rot1_expr – formula (as string) providing with the rot1
rot2_expr – formula (as string) providing with the rot2
rot3_expr – formula (as string) providing with the rot3
wavelength_expr – formula (as a string) to calculate wavelength used in angstrom
param_names – list of names of the parameters used in the model
pos_names – list of motor names for gonio with >1 degree of freedom
constants – a dictionary with some constants the user may want to use
content – Should be None or the name of the class (may be used in the future to dispatch to multiple derivative classes)
-
to_dict
()¶ Export the instance representation for serialization as a dictionary
-
-
class
pyFAI.goniometer.
GeometryTransformation
(dist_expr, poni1_expr, poni2_expr, rot1_expr, rot2_expr, rot3_expr, param_names, pos_names=None, constants=None, content=None)¶ Bases:
object
This class, once instanciated, behaves like a function (via the __call__ method). It is responsible for taking any input geometry and translate it into a set of parameters compatible with pyFAI, i.e. a tuple with: (dist, poni1, poni2, rot1, rot2, rot3) This function uses numexpr for formula evaluation.
-
__init__
(dist_expr, poni1_expr, poni2_expr, rot1_expr, rot2_expr, rot3_expr, param_names, pos_names=None, constants=None, content=None)¶ Constructor of the class
- Parameters
dist_expr – formula (as string) providing with the dist
poni1_expr – formula (as string) providing with the poni1
poni2_expr – formula (as string) providing with the poni2
rot1_expr – formula (as string) providing with the rot1
rot2_expr – formula (as string) providing with the rot2
rot3_expr – formula (as string) providing with the rot3
param_names – list of names of the parameters used in the model
pos_names – list of motor names for gonio with >1 degree of freedom
constants – a dictionary with some constants the user may want to use
content – Should be None or the name of the class (may be used in the future to dispatch to multiple derivative classes)
-
to_dict
()¶ Export the instance representation for serialization as a dictionary
-
-
pyFAI.goniometer.
GeometryTranslation
¶
-
class
pyFAI.goniometer.
Goniometer
(param, trans_function, detector='Detector', wavelength=None, param_names=None, pos_names=None)¶ Bases:
object
This class represents the goniometer model. Unlike this name suggests, it may include translation in addition to rotations
-
__init__
(param, trans_function, detector='Detector', wavelength=None, param_names=None, pos_names=None)¶ Constructor of the Goniometer class.
- Parameters
param – vector of parameter to refine for defining the detector position on the goniometer
trans_function – function taking the parameters of the goniometer and the goniometer position and return the 6 parameters [dist, poni1, poni2, rot1, rot2, rot3]
detector – detector mounted on the moving arm
wavelength – the wavelength used for the experiment
param_names – list of names to “label” the param vector.
pos_names – list of names to “label” the position vector of the gonio.
-
file_version
= 'Goniometer calibration v2'¶
-
get_ai
(position)¶ Creates an azimuthal integrator from the motor position
- Parameters
position – the goniometer position, a float for a 1 axis goniometer
- Returns
A freshly build AzimuthalIntegrator
-
get_mg
(positions)¶ Creates a MultiGeometry integrator from a list of goniometer positions.
- Parameters
positions – A list of goniometer positions
- Returns
A freshly build multi-geometry
-
save
(filename)¶ Save the goniometer configuration to file
- Parameters
filename – name of the file to save configuration to
-
classmethod
sload
(filename)¶ Class method for instanciating a Goniometer object from a JSON file
- Parameters
filename – name of the JSON file
- Returns
Goniometer object
-
to_dict
()¶ Export the goniometer configuration to a dictionary
- Returns
Ordered dictionary
-
write
(filename)¶ Save the goniometer configuration to file
- Parameters
filename – name of the file to save configuration to
-
-
class
pyFAI.goniometer.
GoniometerRefinement
(param, pos_function, trans_function, detector='Detector', wavelength=None, param_names=None, pos_names=None, bounds=None)¶ Bases:
pyFAI.goniometer.Goniometer
This class allow the translation of a goniometer geometry into a pyFAI geometry using a set of parameter to refine.
-
__init__
(param, pos_function, trans_function, detector='Detector', wavelength=None, param_names=None, pos_names=None, bounds=None)¶ Constructor of the GoniometerRefinement class
- Parameters
param – vector of parameter to refine for defining the detector position on the goniometer
pos_function – a function taking metadata and extracting the goniometer position
trans_function – function taking the parameters of the goniometer and the gonopmeter position and return the 6/7 parameters [dist, poni1, poni2, rot1, rot2, rot3, wavelength]
detector – detector mounted on the moving arm
wavelength – the wavelength used for the experiment
param_names – list of names to “label” the param vector.
pos_names – list of names to “label” the position vector of the gonio.
bounds – list of 2-tuple with the lower and upper bound of each function
-
chi2
(param=None)¶ Calculate the average of the square of the error for a given parameter set
-
new_geometry
(label, image=None, metadata=None, control_points=None, calibrant=None, geometry=None)¶ Add a new geometry for calibration
- Parameters
label – usually a string
image – 2D numpy array with the Debye scherrer rings
metadata – some metadata
control_points – an instance of ControlPoints
calibrant – the calibrant used for calibrating
geometry – poni or AzimuthalIntegrator instance.
-
refine2
(method='slsqp', **options)¶ Geometry refinement tool
See https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.optimize.minimize.html
- Parameters
method – name of the minimizer
options – options for the minimizer
-
residu2
(param)¶ Actually performs the calulation of the average of the error squared
-
set_bounds
(name, mini=None, maxi=None)¶ Redefines the bounds for the refinement
- Parameters
name – name of the parameter or index in the parameter set
mini – minimum value
maxi – maximum value
-
classmethod
sload
(filename, pos_function=None)¶ Class method for instanciating a Goniometer object from a JSON file
- Parameters
filename – name of the JSON file
pos_function – a function taking metadata and extracting the goniometer position
- Returns
Goniometer object
-
-
class
pyFAI.goniometer.
PoniParam
(dist, poni1, poni2, rot1, rot2, rot3)¶ Bases:
tuple
-
property
dist
¶ Alias for field number 0
-
property
poni1
¶ Alias for field number 1
-
property
poni2
¶ Alias for field number 2
-
property
rot1
¶ Alias for field number 3
-
property
rot2
¶ Alias for field number 4
-
property
rot3
¶ Alias for field number 5
-
property
-
class
pyFAI.goniometer.
SingleGeometry
(label, image=None, metadata=None, pos_function=None, control_points=None, calibrant=None, detector=None, geometry=None)¶ Bases:
object
This class represents a single geometry of a detector position on a goniometer arm
-
__init__
(label, image=None, metadata=None, pos_function=None, control_points=None, calibrant=None, detector=None, geometry=None)¶ Constructor of the SingleGeometry class, used for calibrating a multi-geometry setup with a moving detector.
- Parameters
label – name of the geometry, a string or anything unmutable
image – image with Debye-Scherrer rings as 2d numpy array
metadata – anything which contains the goniometer position
pos_function – a function which takes the metadata as input and returns the goniometer arm position
control_points – a pyFAI.control_points.ControlPoints instance (optional parameter)
calibrant – a pyFAI.calibrant.Calibrant instance. Contains the wavelength to be used (optional parameter)
detector – a pyFAI.detectors.Detector instance or something like that Contains the mask to be used (optional parameter)
geometry – an azimuthal integrator or a ponifile (or a dict with the geometry) (optional parameter)
-
extract_cp
(max_rings=None, pts_per_deg=1.0, Imin=0)¶ Performs an automatic keypoint extraction and update the geometry refinement part
- Parameters
max_ring – extract at most N rings from the image
pts_per_deg – number of control points per azimuthal degree (increase for better precision)
-
get_ai
()¶ Create a new azimuthal integrator to be used.
- Returns
Azimuthal Integrator instance
-
get_position
()¶ This method is in charge of calculating the motor position from metadata/label/…
-
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
-
__init__
(filename=None)¶ This is the constructor of the Spline class.
- Parameters
filename (str) – name of the ascii file containing the spline
-
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) – 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
(fit=True)¶ Flip the spline horizontally
- Parameters
fit (bool) – set to False to disable fitting of the coef, or provide a value for the smoothing factor
- Returns
new spline object
-
fliplrud
(fit=True)¶ Flip the spline upside-down and horizontally
- Parameters
fit (bool) – set to False to disable fitting of the coef, or provide a value for the smoothing factor
- Returns
new spline object
-
flipud
(fit=True)¶ Flip the spline upside-down
- Parameters
fit (bool) – set to False to disable fitting of the coef, or provide a value for the smoothing factor
- Returns
new spline object
-
getDetectorSize
()¶ Returns the size of the detector.
- Return type
Tuple[int,int]
- Returns
Size y then x
-
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
xDispArray, yDispArray
- Return type
2-tuple of 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
-
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
-
control_points
Module¶
ControlPoints: a set of control points associated with a calibration image
PointGroup: a group of points
-
class
pyFAI.control_points.
ControlPoints
(filename=None, calibrant=None, wavelength=None)¶ Bases:
object
This class contains a set of control points with (optionally) their ring number hence d-spacing and diffraction 2Theta angle…
-
__init__
(filename=None, calibrant=None, wavelength=None)¶ Initialize self. See help(type(self)) for accurate signature.
-
append
(points, ring=None, annotate=None, plot=None)¶ Append a group of points to a given ring
- Parameters
point – list of points
ring – ring number
annotate – matplotlib.annotate reference
plot – matplotlib.plot reference
- Returns
PointGroup instance
-
append_2theta_deg
(points, angle=None, ring=None)¶ Append a group of points to a given ring
- Parameters
point – list of points
angle – 2-theta angle in degrees
- Param
ring: ring number
-
check
()¶ check internal consistency of the class, disabled for now
-
property
dSpacing
¶
-
get
(ring=None, lbl=None)¶ Retireves the last group of points for a given ring (by default the last)
- Parameters
ring – index of ring to search for
lbl – label of the group to retrieve
-
getList
()¶ Retrieve the list of control points suitable for geometry refinement with ring number
-
getList2theta
()¶ Retrieve the list of control points suitable for geometry refinement
-
getListRing
()¶ Retrieve the list of control points suitable for geometry refinement with ring number
-
getWeightedList
(image)¶ Retrieve the list of control points suitable for geometry refinement with ring number and intensities :param image: :return: a (x,4) array with pos0, pos1, ring nr and intensity
#TODO: refine the value of the intensity using 2nd order polynomia
-
get_dSpacing
()¶
-
get_labels
()¶ Retieve the list of labels
- Returns
list of labels as string
-
get_wavelength
()¶
-
load
(filename)¶ load all control points from a file
-
pop
(ring=None, lbl=None)¶ Remove the set of points, either from its code or from a given ring (by default the last)
- Parameters
ring – index of ring of which remove the last group
lbl – code of the ring to remove
-
readRingNrFromKeyboard
()¶ Ask the ring number values for the given points
-
reset
()¶ remove all stored values and resets them to default
-
save
(filename)¶ Save a set of control points to a file :param filename: name of the file :return: None
-
setWavelength_change2th
(value=None)¶
-
setWavelength_changeDs
(value=None)¶ This is probably not a good idea, but who knows !
-
set_dSpacing
(lst)¶
-
set_wavelength
(value=None)¶
-
property
wavelength
¶
-
-
class
pyFAI.control_points.
PointGroup
(points=None, ring=None, annotate=None, plot=None, force_label=None)¶ Bases:
object
Class contains a group of points … They all belong to the same Debye-Scherrer ring
-
__init__
(points=None, ring=None, annotate=None, plot=None, force_label=None)¶ Constructor
- Parameters
points – list of points
ring – ring number
annotate – reference to the matplotlib annotate output
plot – reference to the matplotlib plot
force_label – allows to enforce the label
-
property
code
¶ Numerical value for the label: mainly for sorting
-
classmethod
get_label
()¶ return the next label
-
get_ring
()¶
-
property
label
¶
-
last_label
= 0¶
-
classmethod
reset_label
()¶ reset intenal counter
-
property
ring
¶
-
classmethod
set_label
(label)¶ update the internal counter if needed
-
set_ring
(value)¶
-
massif
Module¶
-
class
pyFAI.massif.
Massif
(data=None, mask=None)¶ Bases:
object
A massif is defined as an area around a peak, it is used to find neighboring peaks
-
TARGET_SIZE
= 1024¶
-
__init__
(data=None, mask=None)¶ Constructor of the class…
- Parameters
data – 2D array or filename (discouraged)
mask – array with non zero for invalid data
-
calculate_massif
(x)¶ defines a map of the massif around x and returns the mask
-
property
cleaned_data
¶
-
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.
- Parameters
x (Tuple[int]) – coordinates of the peak, seed for the calculation
nmax (int) – maximum number of peak per region
annotate – callback method taking number of points + coordinate as input.
massif_contour – callback to show the contour of a massif with the given index.
stdout – this is the file where output is written by default.
- Returns
list of peaks
-
getBinnedData
()¶
-
getBluredData
()¶
-
getLabeledMassif
(pattern=None)¶
-
getMedianData
()¶
-
get_binned_data
()¶ - Returns
binned data
-
get_blurred_data
()¶ - Returns
a blurred image
-
get_labeled_massif
(pattern=None, reconstruct=True)¶ - Parameters
pattern – 3x3 matrix
reconstruct – if False, split massif at masked position, else reconstruct missing part.
- Returns
an image composed of int with a different value for each massif
-
get_median_data
()¶ - Returns
a spatial median filtered image 3x3
-
initValleySize
()¶
-
init_valley_size
()¶
-
log_info
= None¶ If true, more information is displayed in the logger relative to picking.
-
nearest_peak
(x)¶ - Parameters
x – coordinates of the peak
- Returns
the coordinates of the nearest peak
-
peaks_from_area
(mask, Imin=-1.7976931348623157e+308, 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], …]
-
property
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
-
__init__
(img, cur_sigma=0.25, init_sigma=0.5, dest_sigma=1, scale_per_octave=2, mask=None)¶ Performs a blob detection: http://en.wikipedia.org/wiki/Blob_detection using a Difference of Gaussian + Pyramid of Gaussians
- Parameters
img – input image
cur_sigma – estimated smoothing of the input image. 0.25 correspond to no interaction between pixels.
init_sigma – start searching at this scale (sigma=0.5: 10% interaction with first neighbor)
dest_sigma – sigma at which the resolution is lowered (change of octave)
scale_per_octave – Number of scale to be performed per octave
mask – mask where pixel are not valid
-
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 non-coherent keypoints.
- Parameters
kpx – x_pos of keypoint
kpy – y_pos of keypoint
kps – s_pos of keypoint
- Returns
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
mask – mask out keypoint next to the mask (or inside the mask)
n_5 – look for a larger neighborhood
-
pyFAI.blob_detection.
make_gaussian
(im, sigma, xc, yc)¶
calibrant
Module¶
Calibrant
A module containing classical calibrant and also tools to generate d-spacing.
Interesting formula: http://geoweb3.princeton.edu/research/MineralPhy/xtalgeometry.pdf
-
pyFAI.calibrant.
CALIBRANT_FACTORY
= Calibrants available: Al, LaB6, TiO2, Ni, CuO, quartz, Si, mock, Si_SRM640e, LaB6_SRM660a, PBBA, cristobaltite, Si_SRM640, NaCl, AgBh, CrOx, LaB6_SRM660c, C14H30O, Si_SRM640a, Au, alpha_Al2O3, ZnO, Si_SRM640d, Cr2O3, Si_SRM640c, LaB6_SRM660b, Si_SRM640b, CeO2¶ Default calibration factory provided by the library.
-
class
pyFAI.calibrant.
Calibrant
(filename=None, dSpacing=None, wavelength=None)¶ Bases:
object
A calibrant is a reference compound where the d-spacing (interplanar distances) are known. They are expressed in Angstrom (in the file)
-
__init__
(filename=None, dSpacing=None, wavelength=None)¶ Initialize self. See help(type(self)) for accurate signature.
-
append_2th
(value)¶
-
append_dSpacing
(value)¶
-
count_registered_dSpacing
()¶ Count of registered dSpacing positons.
-
property
dSpacing
¶
-
fake_calibration_image
(ai, shape=None, Imax=1.0, U=0, V=0, W=0.0001)¶ Generates a fake calibration image from an azimuthal integrator
- Parameters
ai – azimuthal integrator
Imax – maximum intensity of rings
V, W (U,) – width of the peak from Caglioti’s law (FWHM^2 = Utan(th)^2 + Vtan(th) + W)
-
property
filename
¶
-
get_2th
()¶ Returns the 2theta positions for all peaks (cached)
-
get_2th_index
(angle, delta=None)¶ Returns the index in the 2theta angle index
- Parameters
angle – expected angle in radians
delta – precision on angle
- Returns
0-based index or None
-
get_dSpacing
()¶
-
get_filename
()¶
-
get_max_wavelength
(index=None)¶ Calculate the maximum wavelength assuming the ring at index is visible :param index: Ring number, otherwise assumes all rings are visible :return: the maximum visible wavelength
-
get_peaks
(unit='2th_deg')¶ Calculate the peak position as :return: numpy array (unlike other methods which return lists)
-
get_wavelength
()¶
-
load_file
(filename=None)¶
-
save_dSpacing
(filename=None)¶ save the d-spacing to a file
-
setWavelength_change2th
(value=None)¶
-
setWavelength_changeDs
(value=None)¶ This is probably not a good idea, but who knows !
-
set_dSpacing
(lst)¶
-
set_wavelength
(value=None)¶
-
property
wavelength
¶
-
-
class
pyFAI.calibrant.
CalibrantFactory
(basedir=None)¶ Bases:
object
Behaves like a dict but is actually a factory:
Each time one retrieves an object it is a new geniune new calibrant (unmodified)
-
__init__
(basedir=None)¶ Constructor
- Parameters
basedir – directory name where to search for the calibrants
-
get
(what, notfound=None)¶
-
has_key
(k)¶
-
items
()¶
-
keys
()¶
-
values
()¶
-
-
class
pyFAI.calibrant.
Cell
(a=1, b=1, c=1, alpha=90, beta=90, gamma=90, lattice='triclinic', lattice_type='P')¶ Bases:
object
This is a cell object, able to calculate the volume and d-spacing according to formula from:
http://geoweb3.princeton.edu/research/MineralPhy/xtalgeometry.pdf
-
__init__
(a=1, b=1, c=1, alpha=90, beta=90, gamma=90, lattice='triclinic', lattice_type='P')¶ Constructor of the Cell class:
Crystalographic units are Angstrom for distances and degrees for angles !
- Parameters
a,b,c – unit cell length in Angstrom
beta, gamma (alpha,) – unit cell angle in degrees
lattice – “cubic”, “tetragonal”, “hexagonal”, “rhombohedral”, “orthorhombic”, “monoclinic”, “triclinic”
lattice_type – P, I, F, C or R
-
classmethod
cubic
(a, lattice_type='P')¶ Factory for cubic lattices
- Parameters
a – unit cell length
-
d
(hkl)¶ Calculate the actual d-spacing for a 3-tuple of integer representing a family of Miller plans
- Parameters
hkl – 3-tuple of integers
- Returns
the inter-planar distance
-
d_spacing
(dmin=1.0)¶ Calculate all d-spacing down to dmin
applies selection rules
- Parameters
dmin – minimum value of spacing requested
- Returns
dict d-spacing as string, list of tuple with Miller indices preceded with the numerical value
-
classmethod
diamond
(a)¶ Factory for Diamond type FCC like Si and Ge
- Parameters
a – unit cell length
-
get_type
()¶
-
classmethod
hexagonal
(a, c, lattice_type='P')¶ Factory for hexagonal lattices
- Parameters
a – unit cell length
c – unit cell length
-
lattices
= ['cubic', 'tetragonal', 'hexagonal', 'rhombohedral', 'orthorhombic', 'monoclinic', 'triclinic']¶
-
classmethod
monoclinic
(a, b, c, beta, lattice_type='P')¶ Factory for hexagonal lattices
- Parameters
a – unit cell length
b – unit cell length
c – unit cell length
beta – unit cell angle
-
classmethod
orthorhombic
(a, b, c, lattice_type='P')¶ Factory for orthorhombic lattices
- Parameters
a – unit cell length
b – unit cell length
c – unit cell length
-
classmethod
rhombohedral
(a, alpha, lattice_type='P')¶ Factory for hexagonal lattices
- Parameters
a – unit cell length
alpha – unit cell angle
-
save
(name, long_name=None, doi=None, dmin=1.0, dest_dir=None)¶ Save informations about the cell in a d-spacing file, usable as Calibrant
- Parameters
name – name of the calibrant
doi – reference of the publication used to parametrize the cell
dmin – minimal d-spacing
dest_dir – name of the directory where to save the result
-
selection_rules
= None¶ contains a list of functions returning True(allowed)/False(forbiden)/None(unknown)
-
set_type
(lattice_type)¶
-
classmethod
tetragonal
(a, c, lattice_type='P')¶ Factory for tetragonal lattices
- Parameters
a – unit cell length
c – unit cell length
-
property
type
¶
-
types
= {'C': 'Side centered', 'F': 'Face centered', 'I': 'Body centered', 'P': 'Primitive', 'R': 'Rhombohedral'}¶
-
property
volume
¶
-
-
pyFAI.calibrant.
calibrant_factory
(basedir=None)¶
-
pyFAI.calibrant.
get_calibrant
(calibrant_name)¶ Returns a new instance of the calibrant by it’s name.
- Parameters
calibrant_name (str) – Name of the calibrant
-
pyFAI.calibrant.
names
()¶ Returns the list of registred calibrant names.
- Return type
str
distortion
Module¶
-
class
pyFAI.distortion.
Distortion
(detector='detector', shape=None, resize=False, empty=0, mask=None, method='CSR', device=None, workgroup=8)¶ Bases:
object
This class applies a distortion correction on an image.
New version compatible both with CSR and LUT…
-
__init__
(detector='detector', shape=None, resize=False, empty=0, mask=None, method='CSR', device=None, workgroup=8)¶ - Parameters
detector – detector instance or detector name
shape – shape of the output image
resize – allow the output shape to be different from the input shape
empty – value to be given for empty bins
method – “lut” or “csr”, the former is faster
device – Name of the device: None for OpenMP, “cpu” or “gpu” or the id of the OpenCL device a 2-tuple of integer
workgroup – workgroup size for CSR on OpenCL
-
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
- Return type
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
-
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
-
property
shape_out
¶ Calculate/cache the output shape
- Returns
output shape
-
uncorrect
(image, use_cython=False)¶ 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
Nota: to retrieve the input mask on can do:
>>> msk = dis.uncorrect(numpy.ones(dis._shape_out)) <= 0
-
-
class
pyFAI.distortion.
Quad
(buffer)¶ Bases:
object
Quad modelisation.
-
__init__
(buffer)¶ Initialize self. See help(type(self)) for accurate signature.
-
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)¶
-
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
-
__init__
(detector=None, dark=None, flat=None, solidangle=None, polarization=None, mask=None, dummy=None, delta_dummy=None, device=None)¶ Constructor of the worker :param dark: array :param flat: array :param solidangle: solid-angle array :param polarization: numpy array with 2D polarization corrections :param device: Used to influance OpenCL behavour: can be “cpu”, “GPU”, “Acc” or even an OpenCL context
-
process
(data, variance=None, normalization_factor=1.0)¶ Process the data and apply a normalization factor :param data: input data :param variance: the variance associated to the 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, empty=None, dtype='float32')¶ Bases:
object
Simple worker doing dark, flat, solid angle and polarization correction
-
__init__
(dark=None, flat=None, solidangle=None, polarization=None, mask=None, dummy=None, delta_dummy=None, device=None, empty=None, dtype='float32')¶ Constructor of the worker
- Parameters
dark – array
flat – array
solidangle – solid-angle array
polarization – numpy array with 2D polarization corrections
device – Used to influance OpenCL behavour: can be “cpu”, “GPU”, “Acc” or even an OpenCL context
empty – value given for empty pixels by default
dtype – unit (and precision) in which to perform calculation: float32 or float64
-
process
(data, variance=None, normalization_factor=None, use_cython=True)¶ Process the data and apply a normalization factor :param data: input data :param variance: the variance associated to the data :param normalization: normalization factor :return: processed data, optionally with the assiciated error if variance is provided
-
-
class
pyFAI.worker.
Worker
(azimuthalIntegrator=None, shapeIn=(2048, 2048), shapeOut=(360, 500), unit='r_mm', dummy=None, delta_dummy=None)¶ Bases:
object
-
__init__
(azimuthalIntegrator=None, shapeIn=(2048, 2048), shapeOut=(360, 500), unit='r_mm', dummy=None, delta_dummy=None)¶ - Parameters
azimuthalIntegrator (AzimuthalIntegrator) – An AzimuthalIntegrator instance
shapeIn – image size in input
shapeOut – Integrated size: can be (1,2000) for 1D integration
unit – can be “2th_deg, r_mm or q_nm^-1 …
-
do_2D
()¶
-
property
error_model
¶
-
get_config
()¶ Returns the configuration as a dictionary.
FIXME: The returned dictionary is not exhaustive.
-
get_error_model
()¶
-
get_json_config
()¶ return configuration as a JSON string
-
get_normalization_factor
()¶
-
get_unit
()¶
-
property
normalization_factor
¶
-
process
(data, variance=None, normalization_factor=1.0, writer=None, metadata=None)¶ Process a frame #TODO: dark, flat, sa are missing
- Parameters
data – numpy array containing the input image
writer – An open writer in which ‘write’ will be called with the result of the integration
-
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)¶ Save the configuration as a JSON file
-
setDarkcurrentFile
(imagefile)¶
-
setExtension
(ext)¶ enforce the extension of the processed data file written
-
setFlatfieldFile
(imagefile)¶
-
setJsonConfig
(json_file)¶
-
setSubdir
(path)¶ Set the relative or absolute path for processed data
-
set_config
(config, consume_keys=False)¶ Configure the working from the dictionary.
- Parameters
config (dict) – Key-value configuration
consume_keys (bool) – If true the keys from the dictionary will be consumed when used.
-
set_dark_current_file
(imagefile)¶
-
set_error_model
(value)¶
-
set_flat_field_file
(imagefile)¶
-
set_json_config
(json_file)¶
-
set_method
(method='csr')¶ Set the integration method
-
set_normalization_factor
(value)¶
-
set_unit
(value)¶
-
property
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, consume_keys=False)¶ Create an Azimuthal integrator from the configuration.
- Parameters
config – Key-value dictionary with all parameters
consume_keys (bool) – If true the keys from the dictionary will be consumed when used.
- Returns
A configured (but uninitialized)
AzimuthalIntgrator
.