xray Package¶
A package to play with X-rays
The xray package currently has five modules:
dct (experimental)
detectors
fitting
laue
xray_utils
Warning
The documentation of this package is still very poor, use with care… and add some love to the docs if you have time!
dct
Module¶
The dct module provide helpers functions to work with experimental diffraction contrast tomography data.
- class pymicro.xray.dct.DctForwardSimulation(verbose=False)¶
Bases:
pymicro.xray.experiment.ForwardSimulation
Class to represent a Forward Simulation.
- __init__(verbose=False)¶
- set_hkl_planes(hkl_planes)¶
- set_diffracting_famillies(hkl_list)¶
Set the list of diffracting hk planes using a set of families.
- setup(omega_step, grain_ids=None)¶
Setup the forward simulation.
- Parameters
omega_step (float) – the angular integration step (in degrees) use to compute the diffraction comditions.
grain_ids (list) – a list of grain ids to restrict the forward simulation (use all grains by default).
- load_grain(gid=1)¶
- grain_projection_image(g_uv, g_proj)¶
Produce a 2D image placing all diffraction spots of a given grain at their respective position on the detector.
Spots outside the detector are are skipped while those only partially on the detector are cropped accordingly.
- Parameters
g_proj – image stack of the diffraction spots. The first axis is so that g_proj[0] is the first spot the second axis is the horizontal coordinate of the detector (u) and the third axis the vertical coordinate of the detector (v).
g_uv – list or array of the diffraction spot position.
- Returns
a 2D composite image of all the diffraction spots.
- grain_projection_exp(gid=1)¶
Produce a composite image with all the experimental diffraction spots of this grain on the detector.
- Parameters
gid (int) – the number of the selected grain.
- Returns
a 2D composite image of all the diffraction spots.
- grain_projections(omegas, gid=1, data=None, hor_flip=False, ver_flip=False)¶
Compute the projections of a grain at different rotation angles.
The method compute each projection and concatenate them into a single 3D array in the form [n, u, v] with n the number of angles.
- Parameters
omegas (list) – the list of omega angles to use (in degrees).
gid (int) – the id of the grain to project (1 default).
data (ndarray) – the data array representing the grain.
hor_flip (bool) – a flag to apply a horizontal flip.
ver_flip (bool) – a flag to apply a vertical flip.
- Returns
a 3D array containing the n projections.
- grain_projection_simulation(gid=1)¶
Function to compute all the grain projection in DCT geometry and create a composite image.
- Parameters
gid (int) – the id of the grain to project (1 default).
- dct_projection(omega, include_direct_beam=True, att=5)¶
Function to compute a full DCT projection at a given omega angle.
- Parameters
omega (float) – rotation angle in degrees.
include_direct_beam (bool) – flag to compute the transmission through the sample.
att (float) – an attenuation factor used to limit the gray levels in the direct beam.
- Returns
the dct projection as a 2D numpy array
- pymicro.xray.dct.add_to_image(image, inset, uv, verbose=False)¶
Add an image to another image at a specified position.
The inset image may be of any size and may only overlap partly on the overall image depending on the location specified. In such a case, the inset image is cropped accordingly.
- Parameters
image (np.array) – the master image taht will be modified.
inset (np.array) – the inset to add to the image.
uv (tuple) – the location (center) where to add the inset in the form (u, v).
verbose (bool) – activate verbose mode (False by default).
- pymicro.xray.dct.merge_dct_scans(scan_list, samtz_list, use_mask=False, overlap=- 1, root_dir='.', write_to_h5=True)¶
Merge two DCT scans.
This function build a Microstructure instance for each DCT scan and calls merge_microstructures. The overlap can be deduced from the samtz values or specified directly.
- Parameters
scan_list (list) – a list with the two DCT scan names.
samtz_list (list) – a list with the two samtz value (the order should match the scan names).
use_mask (bool) – a flag to also merge the absorption masks.
overlap (int) – the value to use for the overlap if not computed automatically.
root_dir (str) – the root data folder.
write_to_h5 (bool) – flag to write the result of the merging operation to an HDF5 file.
- Returns
A new Microstructure instance of the 2 merged scans.
- pymicro.xray.dct.all_dif_spots(g_proj, g_uv, verbose=False)¶
Produce a 2D image placing all diffraction spots at their respective position on the detector.
Spots outside the detector are are skipped while those only partially on the detector are cropped accordingly.
- Parameters
g_proj – image stack of the diffraction spots. The first axis is so that g_proj[0] is the first spot the second axis is the horizontal coordinate of the detector (u) and the third axis the vertical coordinate of the detector (v).
g_uv – list or array of the diffraction spot position.
verbose (bool) – activate verbose mode (False by default).
- Returns
a 2D composite image of all the diffraction spots.
- pymicro.xray.dct.plot_all_dif_spots(gid, detector, hkl_miller=None, uv=None, lattice=None, lambda_keV=None, spots=True, dif_spots_image=None, max_value=None, positions=True, debye_rings=True, suffix='')¶
- pymicro.xray.dct.output_tikzpicture(proj_dif, omegas, gid=1, d_uv=[0, 0], suffix='')¶
- pymicro.xray.dct.tt_rock(scan_name, data_dir='.', n_topo=- 1, mask=None, dark_factor=1.0)¶
- pymicro.xray.dct.tt_stack(scan_name, data_dir='.', save_edf=False, n_topo=- 1, dark_factor=1.0)¶
Build a topotomography stack from raw detector images.
The number of image to sum for a topograph can be determined automatically from the total number of images present in data_dir or directly specified using the variable TOPO_N.
- Parameters
scan_name (str) – the name of the scan to process.
data_dir (str) – the path to the data folder.
save_edf (bool) – flag to save the tt stack as an EDF file.
n_topo (int) – the number of images to sum for a topograph.
dark_factor (float) – a multiplicative factor for the dark image.
detectors
Module¶
The detectors module define classes to manipulate X-ray detectors.
- class pymicro.xray.detectors.Detector2d(size=(2048, 2048), data_type=<Mock name='mock.uint16' id='139657959441168'>)¶
Bases:
object
Class to handle 2D detectors.
2D detectors produce array like images and may have different geometries. In particular the pixel arrangement may not necessarily be flat or regular. This abstract class regroup the generic method for those kind of detectors.
- __init__(size=(2048, 2048), data_type=<Mock name='mock.uint16' id='139657959441168'>)¶
Initialization of a Detector2d instance with a given image size (2048 pixels square array by default). The instance can be positioned in the laboratory frame using the ref_pos attribute which is the position in the laboratory frame of the middle of the detector.
- clear_data()¶
Simply set all pixels to zeros.
- azimuthal_regroup(two_theta_mini=None, two_theta_maxi=None, two_theta_step=None, psi_mask=None, psi_min=None, psi_max=None, write_txt=False, output_image=False, debug=False)¶
- sagital_regroup(two_theta_mini=None, two_theta_maxi=None, psi_min=None, psi_max=None, psi_step=None, write_txt=False, output_image=False)¶
- class pymicro.xray.detectors.RegArrayDetector2d(size=(2048, 2048), data_type=<Mock name='mock.uint16' id='139657959441168'>, P=None, tilts=(0.0, 0.0, 0.0))¶
Bases:
pymicro.xray.detectors.Detector2d
Generic class to handle a flat detector with a regular grid of pixels.
An orthonormal local frame Rc is attached to the detector with its origin located at the center of the detector array (the ref_pos attribute). Tilts can be applied to change the orientation of the detector via a series of three intrinsic rotations in that order: kappa rotate around X, delta rotate around Y, omega rotate around Z.
The two dimensions of the pixel grid are referred by u and v. Usually u is the horizontal direction and v the vertical one, but both can be controlled by the u_dir and v_dir attributes. An attribute P is maintained to change from the detector coordinate system Rc to the pixel coordinate system which has its origin in the top left corner of the detector.
This type of detector supports binning.
- __init__(size=(2048, 2048), data_type=<Mock name='mock.uint16' id='139657959441168'>, P=None, tilts=(0.0, 0.0, 0.0))¶
Initialization of a Detector2d instance with a given image size (2048 pixels square array by default). The instance can be positioned in the laboratory frame using the ref_pos attribute which is the position in the laboratory frame of the middle of the detector.
- static compute_tilt_matrix(tilts)¶
Compute the rotation matrix of the detector with respect to the laboratory frame.
The three tilt angles define a series of three intrinsic rotations in that order: kappa rotate around X, delta rotate around Y, omega rotate around Z.
- apply_tilts(tilts)¶
- clear_data()¶
Clear all data arrays.
- set_binning(binning)¶
Set the binning factor. This operation clears all the data arrays.
- Parameters
binning (int) – binning factor
- set_u_dir(tilts)¶
Set the coordinates of the vector describing the first (horizontal) direction of the pixels.
- set_v_dir(tilts)¶
Set the coordinates of the vector describing the second (vertical) direction of the pixels.
- get_pixel_size()¶
Return the effective pixel size, accounting for current binning settings.
- get_size_px()¶
Return the size of the detector in pixel, accounting for current binning settings.
- get_size_mm()¶
Return the size of the detector in millimeters.
- get_origin()¶
Return the detector origin in laboratory coordinates.
- get_edges(num_points=21, verbose=False)¶
Return an array describing the detector edges in pixel units.
- Parameters
num_points (int) – number of points to describe an edge (minimum 2)
verbose (bool) – activate verbose mode.
- project_along_direction(direction, origin=[0.0, 0.0, 0.0])¶
Return the intersection point of a line and the detector plane, in laboratory coordinates.
If \(\l\) is a vector in the direction of the line, \(l_0\) a point of the line, \(p_0\) a point of the plane (here the reference position), and \(n\) the normal to the plane, the intersection point can be written as \(p = d.l + l_0\) where the distance \(d\) can be computed as:
\[d=\dfrac{(p_0 - l_0).n}{l.n}\]- Parameters
direction – the direction of the projection (in the laboratory frame).
origin – the origin of the projection ([0., 0., 0.] by default).
- Returns
the point of projection in the detector plane (can be outside the detector bounds).
- lab_to_pixel(points)¶
Compute the pixel numbers corresponding to a series physical point in space on the detector. The points can be given as an array of size (n, 3) for n points or just as a 3 elements tuple for a single point.
- Parameters
points (ndarray) – the coordinates of the points in the laboratory frame.
- Return ndarray uv
the detector coordinates of the given points as an array of size (n, 2).
- pixel_to_lab(u, v)¶
Compute the laboratory coordinates of a given pixel. , if the pixels coordinates are given using 1D arrays of length n, a numpy array of size (n, 3) with the laboratory coordinates is returned.
- Parameters
u (int) – the given pixel number along the first direction (can be 1D array).
v (int) – the given pixel number along the second direction (can be 1D array).
- Return tuple (x, y, z)
the laboratory coordinates.
- load_image(image_path)¶
- compute_corrected_image()¶
- compute_geometry()¶
Calculate an array of the image size with the (2theta, psi) for each pixel.
- compute_TwoTh_Psi_arrays()¶
Calculate two arrays (2theta, psi) TwoTheta and Psi angles arrays corresponding to repectively the vertical and the horizontal pixels.
- angles_to_pixels(two_theta, psi)¶
given two values 2theta and psi in degrres (that could be arrays), compute the corresponding pixel on the detector.
- static from_poni(size, poni_path)¶
Create a new detector using settings from a poni file (PyFAI convention).
- Parameters
size (tuple) – the size of the 2D detector to create.
poni_path (str) – the path to the ascii poni file to read.
- Returns
a new instance of RegArrayDetector2d.
- class pymicro.xray.detectors.Varian2520¶
Bases:
pymicro.xray.detectors.RegArrayDetector2d
Class to handle a Varian Paxscan 2520 detector.
The flat panel detector produces 16 bit unsigned (1840, 1456) images when setup in horizontal mode.
- __init__()¶
Initialization of a Detector2d instance with a given image size (2048 pixels square array by default). The instance can be positioned in the laboratory frame using the ref_pos attribute which is the position in the laboratory frame of the middle of the detector.
- class pymicro.xray.detectors.Mar165¶
Bases:
pymicro.xray.detectors.RegArrayDetector2d
Class to handle a rayonix marccd165.
The image plate marccd 165 detector produces 16 bits unsigned (2048, 2048) square images.
- __init__()¶
Initialization of a Detector2d instance with a given image size (2048 pixels square array by default). The instance can be positioned in the laboratory frame using the ref_pos attribute which is the position in the laboratory frame of the middle of the detector.
- class pymicro.xray.detectors.PerkinElmer1620¶
Bases:
pymicro.xray.detectors.RegArrayDetector2d
Class to handle a PErkin Elmer 1620 detector.
The flat panel detector produces 16 bits unsigned (2000, 2000) square images.
- __init__()¶
Initialization of a Detector2d instance with a given image size (2048 pixels square array by default). The instance can be positioned in the laboratory frame using the ref_pos attribute which is the position in the laboratory frame of the middle of the detector.
- class pymicro.xray.detectors.Xpad¶
Bases:
pymicro.xray.detectors.Detector2d
Class to handle Xpad like detectors.
Xpad are pixel detectors made with stacked array of silicon chips. Between each chip are 2 double pixels with a 2.5 times bigger size and which need to be taken into account.
Note
This code is heavily inspired by the early version of C. Mocuta, scientist on the DiffAbs beamline at Soleil synchrotron.
Warning
only tested with Xpad S140 for now…
- __init__()¶
Initialization of a Detector2d instance with a given image size (2048 pixels square array by default). The instance can be positioned in the laboratory frame using the ref_pos attribute which is the position in the laboratory frame of the middle of the detector.
- load_image(image_path, nxs_prefix=None, nxs_dataset=None, nxs_index=None, nxs_update_geometry=False, stack='first')¶
load an image from a file.
The image can be stored as a uint16 binary file (.raw) or in a nexus file (.nxs). With the nexus format, several arguments must be specified such as the prefix, the index and the dataset number (as str). :param str image_path: relative or absolute path to the file containing the image. :param str nxs_prefix: the nexus prefix hardcoded into the xml tree. :param str nxs_dataset: the dataset number. :param int nxs_index: the nexus index. :param bool nxs_update_geometry: if True the compute_TwoTh_Psi_arrays method is called after loading the image. :params str stack: indicates what to do if many images are present, ‘first’ (default) to keep only the first one, ‘median’ to compute the median over the third dimension.
- compute_geometry()¶
Calculate the array with the corrected geometry (double pixels).
- compute_corrected_image()¶
Compute a corrected image.
First the intensity is corrected either via background substraction or flat field correction. Then tiling and double pixels are accounted for to obtain a proper geometry where each pixel of the image represent the same physical zone.
- compute_TwoTh_Psi_arrays(diffracto_delta, diffracto_gamma)¶
Computes TwoTheta and Psi angles arrays corresponding to repectively the vertical and the horizontal pixels.
Parameters
diffracto_delta: diffractometer value of the delta axis
diffracto_gamma: diffractometer value of the gamma axis
Note
This assume the detector is perfectly aligned with the delta and gamma axes (which should be the case).
experiment
Module¶
- class pymicro.xray.experiment.ForwardSimulation(sim_type, verbose=False)¶
Bases:
object
Class to represent a Forward Simulation.
- __init__(sim_type, verbose=False)¶
- set_experiment(experiment)¶
Attach an X-ray experiment to this simulation.
- class pymicro.xray.experiment.XraySource(position=None)¶
Bases:
object
Class to represent a X-ray source.
- __init__(position=None)¶
- set_position(position)¶
- property min_energy¶
- property max_energy¶
- set_min_energy(min_energy)¶
- set_max_energy(max_energy)¶
- set_energy(energy)¶
Set the energy (monochromatic case).
- set_energy_range(min_energy, max_energy)¶
- discretize(diameter, n=5)¶
Discretize the focus zone of the source into a regular sphere.
- Parameters
diameter (float) – the diameter of the sphere to use.
n (int) – the number of point to use alongside the source diameter.
- Returns
a numpy array of size (n_inside, 3) with the xyz coordinates of the points inside teh sphere.
- class pymicro.xray.experiment.SlitsGeometry(position=None)¶
Bases:
object
Class to represent the geometry of a 4 blades slits.
- __init__(position=None)¶
- set_position(position)¶
- class pymicro.xray.experiment.ObjectGeometry(geo_type='point', origin=None)¶
Bases:
object
Class to represent any object geometry.
The geometry may have multiple form, including just a point, a regular 3D array or it may be described by a CAD file using the STL format. The array represents the material microstructure using the grain ids and should be set in accordance with an associated Microstructure instance. In this case, zero represent a non crystalline region.
- __init__(geo_type='point', origin=None)¶
- set_type(geo_type)¶
- set_array(grain_map, voxel_size)¶
- set_origin(origin)¶
- get_bounding_box()¶
- get_positions()¶
Return an array of the positions within this sample in world coordinates.
- discretize_geometry(grain_id=None)¶
Compute the positions of material points inside the sample.
A array of size (n_vox, 3) is returned where n_vox is the number of positions. The 3 values of each position contain the (x, y, z) coordinates in mm unit. If a grain id is specified, only the positions within this grain are returned.
This is useful in forward simulation where we need to access all the locations within the sample. Three cases are available:
point Laue diffraction: uses sample origin, grains center and orientation
cad Laue diffraction: uses origin, cad file geometry and grains[0] orientation (assumes only one grain)
grain map Laue diffraction: uses origin, array, size, and grains orientations.
to set the cad geometry must be the path to the STL file.
- class pymicro.xray.experiment.Sample(name=None, position=None, geo=None, material=None, microstructure=None)¶
Bases:
object
Class to describe a material sample.
A sample is made by a given material (that may have multiple phases), has a name and a position in the experimental local frame. A sample also has a geometry (just a point by default), that may be used to discretize the volume in space or display it in 3D.
Note
For the moment, the material is simply a crystal lattice.
- __init__(name=None, position=None, geo=None, material=None, microstructure=None)¶
- set_name(name)¶
Set the sample name.
- Parameters
name (str) – The sample name.
- set_position(position)¶
Set the sample reference position.
- Parameters
position (tuple) – A vector (tuple or array form) describing the sample position.
- set_geometry(geo)¶
Set the geometry of this sample.
- Parameters
geo (ObjectGeometry) – A vector (tuple or array form) describing the sample position.
- get_material()¶
- set_material(material)¶
- get_microstructure()¶
- set_microstructure(microstructure)¶
- has_grains()¶
Method to see if a sample has at least one grain in the microstructure.
- Returns
True if the sample has at east one grain, False otherwise.
- get_grain_ids()¶
- class pymicro.xray.experiment.Experiment¶
Bases:
object
Class to represent an actual or a virtual X-ray experiment.
A cartesian coordinate system (X, Y, Z) is associated with the experiment. By default X is the direction of X-rays and the sample is placed at the origin (0, 0, 0).
- __init__()¶
- set_sample(sample)¶
- get_sample()¶
- set_source(source)¶
- get_source()¶
- set_slits(slits)¶
- get_slits()¶
- add_detector(detector, set_as_active=True)¶
Add a detector to this experiment.
If this is the first detector, the active detector id is set accordingly.
- Parameters
detector (Detector2d) – an instance of the Detector2d class.
set_as_active (bool) – set this detector as active.
- get_number_of_detectors()¶
Return the number of detector for this experiment.
- get_active_detector()¶
Return the active detector for this experiment.
- forward_simulation(fs, set_result_to_detector=True)¶
Perform a forward simulation of the X-ray experiment onto the active detector.
This typically sets the detector.data field with the computed image.
- Parameters
set_result_to_detector (bool) – if True, the result is assigned to the current detector.
fs – An instance of ForwardSimulation or its derived class.
- save(file_path='experiment.txt')¶
Export the parameters to describe the current experiment to a file using json.
- static load(file_path='experiment.txt')¶
- class pymicro.xray.experiment.ExperimentEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)¶
Bases:
json.encoder.JSONEncoder
- default(o)¶
Implement this method in a subclass such that it returns a serializable object for
o
, or calls the base implementation (to raise aTypeError
).For example, to support arbitrary iterators, you could implement default like this:
def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return JSONEncoder.default(self, o)
fitting
Module¶
- The fitting module define some classes to easily perform 1D curve
fitting. This module supports fitting (x, y) data with a general mechanism. Any fitting function can be provided to the fit method and a few general purpose fuctions are predefined:
Gaussian
Lorentzian
Cosine
Voigt
- pymicro.xray.fitting.fit(y, x=None, expression=None, nb_params=None, init=None)¶
Static method to perform curve fitting directly.
Parameters
y: the data to match (a 1d numpy array)
x: the corresponding x coordinates (optional, None by default)
expression: can be either a string to select a predefined function or alternatively a user defined function with the signature f(x, p) (in this case you must specify the length of the parameters array p via setting nb_params).
nb_params: the number of parameters of the user defined fitting function (only needed when a custom fitting function is provided, None by default)
init: a sequence (the length must be equal to the number of parameters of the fitting function) used to initialise the fitting function.
- For instance, to fit some (x,y) data with a gaussian function, simply use:
F = fit(y, x, expression='Gaussian')
Alternatively you may specify you own function directly defined with Python, like:
def myf(x, p): return p[0]*x + p[1] F = fit(y, x, expression=myf, nb_params=2)
- pymicro.xray.fitting.lin_reg(xi, yi)¶
Apply linear regression to a series of points.
This function return the best linear fit in the least square sense. :param ndarray xi: a 1D array of the x coordinate. :param ndarray yi: a 1D array of the y coordinate. :return tuple: the linear intercept, slope and correlation coefficient.
- class pymicro.xray.fitting.Parameter(value, name=None)¶
Bases:
object
A class to handle modiable parameters.
- __init__(value, name=None)¶
Create a new parameter with the given value.
- set(value)¶
Set the value of the parameter.
- set_name(name)¶
Set the name of the parameter.
- class pymicro.xray.fitting.FitFunction¶
Bases:
object
This class provides a basic canvas to define a fit function.
You may subclass it to create your own fitting function just as the predfined fit function do (see Gaussian for instance).
- __init__()¶
- get_parameters()¶
Return the list of parameters of this fit function.
- get_parameter_names()¶
Return the list os parameter names of this fit function.
- add_parameter(value, name)¶
- compute(x)¶
Evaluate the fit function at coordinates x.
- fit(y, x=None, verbose=False)¶
Perform fitting on the given data.
This will adjust the parameters of this fit function to match as well as possible the given data using a least square minimisation.
Parameters
y: the data to match (a 1d numpy array)
x: the corresponding x coordinates (optional, None by default)
verbose: boolean, activate verbose mode
- class pymicro.xray.fitting.SumOfFitFunction(function_list)¶
Bases:
pymicro.xray.fitting.FitFunction
- __init__(function_list)¶
- compute(x)¶
Evaluate the fit function at coordinates x.
- class pymicro.xray.fitting.Gaussian(position=0.0, sigma=1.0, height=1.0)¶
Bases:
pymicro.xray.fitting.FitFunction
first parameter is position, second is sigma, third is height
- __init__(position=0.0, sigma=1.0, height=1.0)¶
- set_position(position)¶
Set the position (center) of the gauss function.
- set_sigma(sigma)¶
Set the width (variance) of the gauss function.
- set_height(height)¶
Set the maximum (height) of the gauss function.
- fwhm()¶
Compute the full width at half maximum of the gauss function.
- class pymicro.xray.fitting.Lorentzian(position=0.0, gamma=1.0, height_factor=1.0)¶
Bases:
pymicro.xray.fitting.FitFunction
Lorentzian funtion.
The first parameter is the position, the second is gamma. The maximum of the function is given by height_factor/(pi*gamma). The FWHM is just 2*gamma.
- __init__(position=0.0, gamma=1.0, height_factor=1.0)¶
- set_position(position)¶
- set_gamma(gamma)¶
- set_height(height)¶
Set the maximum (height) of the Lorentzian function. This actually set the height factor to the value height*pi*gamma.
- fwhm()¶
- class pymicro.xray.fitting.Cosine(position=0.0, width=1.0)¶
Bases:
pymicro.xray.fitting.FitFunction
first parameter is position, second is width
- __init__(position=0.0, width=1.0)¶
- set_position(position)¶
- set_width(a)¶
- fwhm()¶
- class pymicro.xray.fitting.Voigt(position=0.0, sigma=1.0, gamma=1.0, height_factor=1.0)¶
Bases:
pymicro.xray.fitting.FitFunction
The Voigt function is also the real part of w(x) = exp(-x**2) erfc(ix), the Faddeeva function.
Here we use one of the popular implementation which is available in scipy with the wofz function.
- __init__(position=0.0, sigma=1.0, gamma=1.0, height_factor=1.0)¶
- set_position(position)¶
Set the position (center) of the Voigt function.
- set_sigma(sigma)¶
Set the sigma of the Voigt function.
- set_height(height)¶
Set the maximum (height) of the Voigt function. This actually set the height factor to the proper value. Be careful that if you change the other parameters (sigma, gamma) the maximum height will be changed.
- fwhm()¶
Compute the full width at half maximum of the Voigt function.
The height factor does not change the fwhm. The fwhm can be evaluated by the width of the associated Gaussian and Lorentzian functions. The fwhm is approximated by the equation from J. Olivero and R. Longbothum [1977]
laue
Module¶
The laue module provide helpers functions to work with polychromatic X-ray diffraction.
- pymicro.xray.laue.select_lambda(hkl, orientation, Xu=(1.0, 0.0, 0.0), verbose=False)¶
Compute the wavelength corresponding to the first order reflection of a given lattice plane in the specified orientation.
- Parameters
hkl – The given lattice plane.
orientation – The orientation of the crystal lattice.
Xu – The unit vector of the incident X-ray beam (default along the X-axis).
verbose (bool) – activate verbose mode (default False).
- Returns tuple
A tuple of the wavelength value (keV) and the corresponding Bragg angle (radian).
- pymicro.xray.laue.build_list(lattice=None, max_miller=3, extinction=None, Laue_extinction=False, max_keV=120.0)¶
- pymicro.xray.laue.compute_ellipsis(orientation, detector, uvw, Xu=(1.0, 0.0, 0.0), n=101, verbose=False)¶
Compute the ellipsis associated with the given zone axis.
The detector is supposed to be normal to the X-axis, but the incident wave vector can be specified. All lattice planes sharing this zone axis will diffract along that ellipse.
- Parameters
orientation – The crystal orientation.
detector – An instance of the Detector2D class.
uvw – An instance of the HklDirection representing the zone axis.
Xu – The unit vector of the incident X-ray beam (default along the X-axis).
n (int) – number of poits used to define the ellipse.
verbose (bool) – activate verbose mode (default False).
- Returns data
the (Y, Z) data (in mm unit) representing the ellipsis.
- pymicro.xray.laue.diffracted_vector(hkl, orientation, Xu=(1.0, 0.0, 0.0), min_theta=0.1, use_friedel_pair=True, verbose=False)¶
Compute the diffraction vector for a given reflection of a crystal.
This method compute the diffraction vector. The incident wave vector is along the X axis by default but can be changed by specifying any unit vector.
- Parameters
hkl – an instance of the HklPlane class.
orientation – an instance of the Orientation class.
Xu – The unit vector of the incident X-ray beam (default along the X-axis).
min_theta (float) – the minimum considered Bragg angle (in radian).
use_friedel_pair (bool) – also consider the Friedel pairs of the lattice plane.
verbose (bool) – a flag to activate verbose mode.
- Returns
the diffraction vector as a numpy array.
- pymicro.xray.laue.diffracted_intensity(hkl, I0=1.0, symbol='Ni', verbose=False)¶
Compute the diffracted intensity.
This compute a number representing the diffracted intensity within the kinematical approximation. This number includes many correction factors:
atomic factor
structural factor
polarisation factor
Debye-Waller factor
absorption factor
…
- Parameters
hkl (HklPlane) – the hkl Bragg reflection.
I0 (float) – intensity of the incident beam.
symbol (str) – string representing the considered lattice.
verbose (bool) – flag to activate verbose mode.
- Returns
the diffracted intensity.
- Return type
float.
- pymicro.xray.laue.compute_Laue_pattern(orientation, detector, hkl_planes=None, Xu=<Mock name='mock.array()' id='139658053513552'>, use_friedel_pair=False, spectrum=None, spectrum_thr=0.0, r_spot=5, color_field='constant', inverted=False, show_direct_beam=False, verbose=False)¶
Compute a transmission Laue pattern. The data array of the given Detector2d instance is initialized with the result.
The incident beam is assumed to be along the X axis: (1, 0, 0) but can be changed to any direction. The crystal can have any orientation using an instance of the Orientation class. The Detector2d instance holds all the geometry (detector size and position).
A parameter controls the meaning of the values in the diffraction spots in the image. It can be just a constant value, the diffracted beam energy (in keV) or the intensity as computed by the
diffracted_intensity()
method.- Parameters
orientation – The crystal orientation.
detector – An instance of the Detector2d class.
hkl_planes (list) – A list of the lattice planes to include in the pattern.
Xu – The unit vector of the incident X-ray beam (default along the X-axis).
use_friedel_pair (bool) – also consider the Friedel pair of each lattice plane in the list as candidate for diffraction.
spectrum – A two columns array of the spectrum to use for the calculation.
spectrum_thr (float) – The threshold to use to determine if a wave length is contributing or not.
r_spot (int) – Size of the spots on the detector in pixel (5 by default)
color_field (str) – a traing describing, must be ‘constant’, ‘energy’ or ‘intensity’
inverted (bool) – A flag to control if the pattern needs to be inverted.
show_direct_beam (bool) – A flag to control if the direct beam is shown.
verbose (bool) – activate verbose mode (False by default).
- Returns
the computed pattern as a numpy array.
- pymicro.xray.laue.gnomonic_projection_point(data, OC=None)¶
compute the gnomonic projection of a given point or series of points in the general case.
This methods does not assumes the incident X-ray beam is along (1, 0, 0). This is accounted for with the parameter OC which indicates the center of the projection (the incident beam intersection with the detector). A conditional treatment is done as the projection is is faster to compute in the case of normal incidence.
The points coordinates are passed along with a single array which must be of size (n, 3) where n is the number of points. If a single point is used, the data can indifferently be of size (1, 3) or (3).
- Parameters
data (ndarray) – array of the point(s) coordinates in the laboratory frame, aka OR components.
OC (ndarray) – coordinates of the center of the gnomonic projection in the laboratory frame.
- Return data_gp
array of the projected point(s) coordinates in the laboratory frame.
- pymicro.xray.laue.gnomonic_projection(detector, pixel_size=None, OC=None, verbose=False)¶
This function carries out the gnomonic projection of the detector image.
The data must be of uint8 type (between 0 and 255) with diffraction spots equals to 255. The function create a new detector instance (think of it as a virtual detector) located at the same position as the given detector and with an inverse pixel size. The gnomonic projection is stored into this new detector data. The gnomonic projection of each white pixel (value at 255) is computed. The projection is carried out with respect to the center detector (ucen, vcen) point.
- Parameters
detector (RegArrayDetector2d) – the detector instance with the data from which to compute the projection.
pixel_size (float) – pixel size to use in the virtual detector for the gnomonic projection.
OC (tuple) – coordinates of the center of the gnomonic projection in the laboratory frame.
verbose (bool) – flag to activate verbose mode.
- Returns RegArrayDetector2d gnom
A virtual detector with the gnomonic projection as its data.
- pymicro.xray.laue.identify_hkl_from_list(hkl_list)¶
- pymicro.xray.laue.triplet_indexing(OP, angles_exp, angles_th, tol=1.0, verbose=False)¶
evaluate each triplet composed by 3 diffracted points. the total number of triplet is given by the binomial coefficient (n, 3) = n*(n-1)*(n-2)/6
- pymicro.xray.laue.transformation_matrix(hkl_plane_1, hkl_plane_2, xyz_normal_1, xyz_normal_2)¶
- pymicro.xray.laue.confidence_index(votes)¶
- pymicro.xray.laue.poll_system(g_list, dis_tol=1.0, verbose=False)¶
Poll system to sort a series of orientation matrices determined by the indexation procedure.
For each orientation matrix, check if it corresponds to an existing solution, if so: vote for it, if not add a new solution to the list :param list g_list: the list of orientation matrices (should be in the fz) :param float dis_tol: angular tolerance (degrees) :param bool verbose: activate verbose mode (False by default) :return: a tuple composed by the most popular orientation matrix, the corresponding vote number and the confidence index
- pymicro.xray.laue.index(hkl_normals, hkl_planes, tol_angle=0.5, tol_disorientation=1.0, symmetry=Symmetry.cubic, display=False)¶
- pymicro.xray.laue.zone_axis_list(angle, orientation, lattice, max_miller=5, Xu=<Mock name='mock.array()' id='139658053513552'>, verbose=False)¶
This function allows to get easily the Miller indices of zone axis present in a pattern.
- Parameters
angle (float list) – the angle max or the zone axis angle range admissible around the detector center.
orientation – The orientation of the crystal lattice.
lattice – The corresponding crystal lattice, instance of Lattice.
max_miller (int) – Maximal value allowed of Miller indices direction.
Xu (array) – The unit vector of the incident X-ray beam (default along the X-axis).
verbose (bool) – activate verbose mode (default False).
- Returns
A list of HklDirection instance of all zone axis in the angle range.
- pymicro.xray.laue.get_gnomonic_edges(detector, gnom, OC=None, num_points=21)¶
This function allows to get the blind area of the gnomonic projection.
- Parameters
detector (RegArrayDetector2d) – the detector instance with the data from which to compute the projection.
gnom (RegArrayDetector2d) – A virtual detector with the gnomonic projection as its data.
OC (ndarray) – coordinates of the center of the gnomonic projection in the laboratory frame.
num_points (int) – number of points to describe an edge (minimum 2)
- Returns
ndarray of gnomonic blind area edges coordinates.
- pymicro.xray.laue.diffracting_normals_vector(gnom)¶
This function allows to get easily the diffracting normal vector from the gnomonic projection images.
- Parameters
gnom (RegArrayDetector2d) – A virtual detector with the gnomonic projection as its data.
- Returns
Normalized normal vector of diffracting plane
- class pymicro.xray.laue.LaueForwardSimulation(verbose=False)¶
Bases:
pymicro.xray.experiment.ForwardSimulation
Class to represent a Forward Simulation.
- __init__(verbose=False)¶
- set_experiment(experiment)¶
Attach an X-ray experiment to this simulation.
- set_use_energy_limits(use_energy_limits)¶
Activate or deactivate the use of energy limits.
- set_hkl_planes(hkl_planes)¶
- setup(include_grains=None)¶
Setup the forward simulation.
- static fsim_laue(orientation, hkl_planes, positions, source_position)¶
Simulate Laue diffraction conditions based on a crystal orientation, a set of lattice planes and physical positions.
This function is the work horse of the forward model. It uses a set of HklPlane instances and the voxel coordinates to compute the diffraction quantities.
- Parameters
orientation (Orientation) – the crystal orientation.
hkl_planes (list) – a list of HklPlane instances.
positions (list) – a list of (x, y, z) positions.
source_position (tuple) – a (x, y, z) tuple describing the source position.
- fsim_grain(gid=1)¶
- fsim()¶
run the forward simulation.
If the sample has a CAD type of geometry, a single grain (the first from the list) is assumed. In the other cases all the grains from the microstructure are used. In particular, if the microstructure has a grain map, it can be used to carry out an extended sample simulation.
xray_utils
Module¶
- class pymicro.xray.xray_utils.Element(name, symbol, density)¶
Bases:
object
A class to represent a chemical element described by its name, symbol and density.
- __init__(name, symbol, density)¶
- property name¶
Returns the name of the Element.
- property symbol¶
Returns the symbol of the Element.
- property density¶
Returns the density of the Element.
- pymicro.xray.xray_utils.density_from_Z(Z)¶
- pymicro.xray.xray_utils.density_from_symbol(symbol)¶
- pymicro.xray.xray_utils.f_atom(q, Z)¶
Empirical function for the atomic form factor f.
This function implements the empirical function from the paper of Muhammad and Lee to provide value of f for elements in the range Z <= 30. doi:10.1371/journal.pone.0069608.t001
- Parameters
q (float) – value or series for the momentum transfer, unit is angstrom^-1
Z (int) – atomic number, must be lower than 30.
- Returns
the atomic form factor value or series corresponding to q.
- pymicro.xray.xray_utils.atom_scat_factor_function(mat='Al', sintheta_lambda_max=12, display=True)¶
Compute and display the fit function of the atomic scattering factor.
- Parameters
mat (string) – A string representing the material (e.g. ‘Al’)
sintheta_lambda_max (float) – maximal value of sin theta / lambda
display (bool) – display an image of the plot
- pymicro.xray.xray_utils.lambda_keV_to_nm(lambda_keV)¶
Change the unit of wavelength from keV to nm.
- Parameters
lambda_keV (float) – the wavelength in keV unit.
- Returns
the wavelength in nm unit.
- pymicro.xray.xray_utils.lambda_keV_to_angstrom(lambda_keV)¶
Change the unit of wavelength from keV to angstrom.
- Parameters
lambda_keV (float) – the wavelength in keV unit.
- Returns
the wavelength in angstrom unit.
- pymicro.xray.xray_utils.lambda_nm_to_keV(lambda_nm)¶
Change the unit of wavelength from nm to keV.
- Parameters
lambda_nm (float) – the wavelength in nm unit.
- Returns
the wavelength in keV unit.
- pymicro.xray.xray_utils.lambda_angstrom_to_keV(lambda_angstrom)¶
Change the unit of wavelength from angstrom to keV.
- Parameters
lambda_angstrom (float) – the wavelength in angstrom unit.
- Returns
the wavelength in keV unit.
- pymicro.xray.xray_utils.plot_xray_trans(mat='Al', ts=[1.0], rho=None, energy_lim=[1, 100], legfmt='%.1f', display=True)¶
Plot the transmitted intensity of a X-ray beam through a given material.
This function compute the transmitted intensity from tabulated data of the mass attenuation coefficient mu_
- ho (between 1 and 100 keV) and
applying Beer’s Lambert law:
\[I/I_0 = \exp(-\mu_\]
ho* ho*t)
The tabulated data is stored in ascii files in the data folder. It has been retrieved from NIST http://physics.nist.gov/cgi-bin/ffast/ffast.pl The density is also tabulated and can be left blanked unless a specific value is to be used.
- param string mat
a string representing the material (must be the atomic symbol if the density is not specified, e.g. ‘Al’)
- param list ts
a list of thickness values of the material in mm ([1.0] by default)
- param float rho
density of the material in g/cm^3 (None by default)
- param list energy_lim
energy bounds in keV for the plot (1, 100 by default)
- param string legfmt
string to format the legend plot
- param bool display
display or save an image of the plot (False by default)
- pymicro.xray.xray_utils.radiograph(data, omega)¶
Compute a single radiograph of a 3D object using the radon transform.
- Parameters
data (np.array) – an array representing the 3D object in (XYZ) form.
omega – the rotation angle value in degrees.
- Returns projection
a 2D array in (Y, Z) form.
- pymicro.xray.xray_utils.radiographs(data, omegas)¶
Compute the radiographs of a 3D object using the radon transform.
The object is represented by a 3D numpy array in (XYZ) form and a series of projection at each omega angle are computed assuming the rotation is along Z in the middle of the data set. Internally this function uses the radon transform from the skimage package.
- Parameters
data (np.array) – an array representing the 3D object in (XYZ) form.
omegas – an array of the rotation values in degrees.
- Returns projections
a 3D array in (Y, Z, omega) form.