ImageD11.forward_model.grainmaps module#
- ImageD11.forward_model.grainmaps.DS_IGM_calc(DS, grain_ids=None, crystal_system='cubic', plot_flag=True)#
compute intragranular misorientation (IGM) for each grain run DS_merge_and_identify_grains if the grain voxels have not been merged TODO: parallelize the orientation conversion, a bit slow for large number of voxels for now :param DS – grain map dictionary: :type DS – grain map dictionary: tensor_map_file :param gm = grainmap: :type gm = grainmap: tensor_map_file :param grain_ids – list of grain label IDs to compute: :param None means compute all grains: :param crystal_system – crystal system name one of [‘cubic’: :param ‘hexagonal’: :param ‘orthorhombic’: :param ‘tetragonal’: :param ‘trigonal’: :param ‘monoclinic’: :param ‘triclinic’]: :param plot_flag – plot flag:
- Returns:
IGM – IGM map in degrees
- ImageD11.forward_model.grainmaps.DS_KAM_and_GB(DS, kernel_size=5, kernel_cutoff=50, tol_dist=1.732, crystal_system='cubic', misorientation_threshold=(0, 10), fill_value=nan, n_jobs=-1, Umis_flag=True, slice_no=0, plot_flag=True)#
Compute Kernal Average Misorientation (KAM) and grain-boundary (GB) misorientation on the grainmap (parallelized with joblib) Exclude the neiboring voxels misorientation outside the bounds defined in misorientation_threshold Any neighboring voxels have misorientation > higher bound of misorientation_threshold is considered as GB voxel :param DS – DS dict expressing a grain map: :param kernel_size – int: :param size of the kernel: :param kernel_cutoff – int: :type kernel_cutoff – int: in percentage :param threshold value for the gaussian cutoff: :type threshold value for the gaussian cutoff: in percentage :param tol_dist – maximum distance between neighboring voxels to be considered as grain boundary voxels [voxel]: :param crystal_system – crystal system name as str: :param misorientation_threshold – tuple: :param Reject neiboring voxels’ misorientations outside this range: :param fill_value – To put where mask is false: :param np.nan by default: :param n_jobs – Number of parallel jobs: :param -1 uses all available cores: :param Umis_flag – True to use xfab.symmetry.Umis: :param False to use grainmaps.disorientation_list: :param slice_no – int: :param slice indice for plotting: :param 0 by default for 2D map: :param while it becomes useful for 3D map: :param plot_flag – bool: :param plot flag:
- Returns:
KAM_map – kernel average misorientation map in degrees, 3D numpy array (Z,Y,X) GB_map – dict, grain boundary voxel map, keys include “mask”, “misori”
Bench mark testing for a (1, 361, 361) map with fcc structure: it takes 36.4 s with Umis, while it takes 1.2 min with grainmaps.disorientation. Comparisons for other crystal systems to be done
- ImageD11.forward_model.grainmaps.DS_check(DS)#
Check for NaN values in U matrix and invalidate corresponding labels. :param DS – grain map dictionary with ‘U’ and ‘labels’ keys:
- Returns:
DS – updated dictionary with invalid labels set to -1
- ImageD11.forward_model.grainmaps.DS_clean_small_grains(DS, min_vol=6, FirstGrainID=0, dis_tol=np.float64(1.7320508075688772), min_misori=3.0, crystal_system='cubic', relabel_disconnected=False, connectivity=2, verbose=0)#
Clean small grains defined by no bigger than min_vol voxels Two clean-ups: 1) for isolated small grains, replace their voxels by neighboring voxels’ labels, U etc 2) for isolated regions that have the same label as a big parent region, assign them with a new label For purely removing small grain voxels, please use DS_out = DS_remove_small_grains(DS, min_vol = min_vol)
- Parameters:
dictionary (DS -- grain map)
grainmap (gm =)
checking (FirstGrainID -- First grain ID to be considered for)
0 (by default =)
all (min_misori -- misorientation to identify whether to only update labels or update)
grains (dis_tol -- maximum distance around the target voxel for identifying its neigboring)
np.sqrt (3)
relabel_disconnected (bool)
['cubic' (crystal_system -- crystal system name one of)
'hexagonal'
'orthorhombic'
'tetragonal'
'trigonal'
'monoclinic'
'triclinic']
connectivity (int) – Label connected components (connectivity=1 for 6-connectivity, 2 for 18-connectivity, 3 for 26-connectivity)
level (verbose -- verose)
0
1
2
- Returns:
DS_out2 – DS grain map dictionary with small/noisy grains cleaned up and isolated big grain regions re-labeled
- ImageD11.forward_model.grainmaps.DS_merge_and_identify_grains(DS, FirstGrainID=0, min_misori=3.0, dis_tol=np.float64(1.7320508075688772), crystal_system='cubic', count_max=100, verbose=0)#
Merge regions within which the voxel misorientation is smaller than a pre-defined values New grain ID will be assigned to DS dictionary ‘labels’ key Optional to keep the first grain IDs static by defining FirstGrainID (by default = 0 means no first grains to be static) To clean up further, please run <<DS_clean_small_grains>> and/or <<DS_relabel_disconnected_regions>> But always ending with running the current function
- Parameters:
dictionary (DS -- grain map)
grainmap (gm =)
merging (FirstGrainID -- First grain ID to be considered for)
0 (by default =)
regions (count_max -- maximum iterations for merging)
grains (dis_tol -- maximum distance around the target voxel for identifying its neigboring)
np.sqrt (3)
['cubic' (crystal_system -- crystal system name one of)
'hexagonal'
'orthorhombic'
'tetragonal'
'trigonal'
'monoclinic'
'triclinic']
regions
level (verbose -- verose)
0
1
2
- Returns:
DS_new – DS grain map dictionary with updated grain IDs
- ImageD11.forward_model.grainmaps.DS_merge_and_identify_grains_sub(DS, FirstGrainID=0, min_misori=3.0, dis_tol=np.float64(1.7320508075688772), crystal_system='cubic', verbose=0)#
sub function: Merge regions within which the voxel misorientation is smaller than a pre-defined values New grain ID will be assigned to DS dictionary ‘labels’ key Optional to keep the first grain IDs static by defining FirstGrainID (by default = 0 means no first grains to be static)
- Parameters:
dictionary (DS -- grain map)
grainmap (gm =)
merging (FirstGrainID -- First grain ID to be considered for)
0 (by default =)
regions (min_misori -- misorientation for merging)
grains (dis_tol -- maximum distance around the target voxel for identifying its neigboring)
np.sqrt (3)
['cubic' (crystal_system -- crystal system name one of)
'hexagonal'
'orthorhombic'
'tetragonal'
'trigonal'
'monoclinic'
'triclinic']
level (verbose -- verose)
0
1
2
- Returns:
DS_merge – DS grain map dictionary with updated grain IDs
- ImageD11.forward_model.grainmaps.DS_relabel_disconnected_regions(DS, connectivity=2, verbose=0)#
Relabel disconnected regions for DS grain map, i.e. to deal the case where the same grain labeled regions are actually not connected Using skimage.measure.label for connected component analysis. :param DS: grain map dictionary, gm = grainmap(tensor_map_file); DS = gm.DS :type DS: dict :param connectivity: Label connected components (connectivity=1 for 6-connectivity, 2 for 18-connectivity, 3 for 26-connectivity) :type connectivity: int :param verbose: verose level, 0, 1, 2 :type verbose: int
- Returns:
DS grain map dictionary output
- Return type:
DS_out (dict)
- ImageD11.forward_model.grainmaps.DS_remove_small_grains(DS, min_vol=2)#
Remove small grains defined by no bigger than min_vol voxels, replace these noisy voxels by empty If you want to clean up noisy voxels by replacing with neighboring grain information, please use <<DS_clean_small_grains>> In general, it is recommended to run <<DS_clean_small_grains>> instead
Arguments: DS – grain map dictionary, gm = grainmap(tensor_map_file); DS = gm.DS min_vol – minimum number of voxels to be kept in DS [voxel]
Returns: DS_out – DS grain map dictionary with small/noisy grains removed
- ImageD11.forward_model.grainmaps.DS_segment_low_completeness(DS, min_completeness=0.3)#
Remove indexed voxel below a completeness threshold. :param DS: DS grain-map dictionary. :param min_completeness: Minimum completeness value to retain a voxel.
- Returns:
Filtered DS grain-map dictionary.
- Return type:
DS_out
- ImageD11.forward_model.grainmaps.DS_to_paraview(DS, h5name='DS.h5')#
Write an .xdmf file that lets you read the DS data with ParaView
Arguments: DS – a dictionary contains DS-like map from the output of ImageD11.forward_model.grainmap class h5name – the corresponding h5 filename, if not exist, I will creat one
- ImageD11.forward_model.grainmaps.KAM_kernel(kernel_size=5, sigma=1.0, kernel_cutoff=50)#
Create a gaussian kernel of KxKxK dimensions, binarized it upon kernel_cutoff (%) TODO: non-square kernel size :param kernel_size: size of the kernel (odd number recommended) :type kernel_size: int :param sigma: standard deviation of Gaussian :type sigma: float :param kernel_cutoff: percentile threshold for binarization :type kernel_cutoff: int
- Returns:
binarized 3D kernel for KAM computation, 0s and 1s
- Return type:
kernel_bin
- class ImageD11.forward_model.grainmaps.Symmetry(*values)#
Bases:
EnumClass to describe crystal symmetry defined by its Laue class symbol.
- cubic = 'm3m'#
- elastic_constants_number()#
Return the number of independent elastic constants for this symmetry.
- Returns:
the number of elastic constants.
- static from_dream3d(n)#
- static from_space_group(space_group_number)#
Create an instance of the Symmetry class from a TSL symmetry number.
- Raises:
ValueError – if the space_group_number is not between 1 and 230.
- Parameters:
space_group_number (int) – the number asociated with the
space group (between 1 and 230). :return: an instance of the Symmetry class
- static from_string(s)#
- static from_tsl(tsl_number)#
Create an instance of the Symmetry class from a TSL symmetry number.
- Returns:
an instance of the Symmetry class
- hexagonal = '6/mmm'#
- lattice_parameters_number()#
Return the number of parameter associated with a lattice of this symmetry.
- Returns:
the number of parameters.
- monoclinic = '2/m'#
- move_rotation_to_FZ(g, verbose=False)#
Compute the rotation matrix in the Fundamental Zone of a given Symmetry instance.
The principle is to apply all symmetry operators to the rotation matrix and identify which one yield the smallest rotation angle. The corresponding rotation is then returned. This computation is vectorized to save time.
- Parameters:
g – a 3x3 matrix representing the rotation.
verbose (bool) – flag for verbose mode.
- Returns:
a new 3x3 matrix for the rotation in the fundamental zone.
- move_vector_to_FZ(v)#
Move the vector to the Fundamental Zone of a given Symmetry instance.
- Parameters:
v – a 3 components vector.
- Returns:
a new 3 components vector in the fundamental zone.
- orthorhombic = 'mmm'#
- static orthotropic_constants_from_stiffness(C)#
Return orthotropic elastic constants from stiffness matrix.
- Parameters:
C (ndarray) – a numpy array of shape (6, 6) representing the stiffness matrix.
- Return dict ortho_elas:
a dictionary of orthotropic elastic constants corresponding to the input stiffness matrix. Keys are ‘E1’,’E2’,’E3’,’nu12’,’nu13’,’nu23’,’G12’,’G13’,’G23’
- stiffness_matrix(elastic_constants)#
Build the stiffness matrix for this symmetry using Voigt convention.
The Voigt notation contracts 2 tensor indices into a single index: 11 -> 1, 22 -> 2, 33 -> 3, 23 -> 4, 31 -> 5, 12 -> 6
- Parameters:
elastic_constants (list) – the elastic constants (the number must correspond to the type of symmetry, eg 3 for cubic).
- Return ndarray:
a numpy array of shape (6, 6) representing the stiffness matrix.
- symmetry_operators(use_miller_bravais=False, spacegroup=None, lattice_parameters=None, cell_choice='standard')#
Define the equivalent crystal symmetries. Note that it takes the highest symmetry in each of the 7 crystal systems This may not be quite right if a specific point group with less symmetry is desired
Those come from Randle & Engler, 2000. For instance in the cubic crystal struture, for instance there are 24 equivalent cube orientations.
- Return array:
A numpy array of shape (n, 3, 3) where n is the number of symmetries of the given crystal structure.
- tetragonal = '4/mmm'#
- to_string()#
- static to_tsl(symmetry)#
Convert a type of crystal Symmetry in the corresponding TSL number.
- Returns:
the TSL number for this symmetry.
- triclinic = 'bar1'#
- trigonal = 'bar3m'#
- ImageD11.forward_model.grainmaps.disorientation(ori1, ori2, crystal_structure=Symmetry.triclinic, spacegroup=None, lattice_parameters=None, cell_choice='standard')#
Compute same-phase disorientation, retaining the sample-to-crystal API. :param ori1: First sample-to-crystal rotation, U1.T, shape (3, 3). :param ori2: Second sample-to-crystal rotation, U2.T, shape (3, 3). :param crystal_structure: Legacy system Symmetry enum or a complete group
of proper Cartesian operators in the crystal frame used by B.
- Parameters:
spacegroup – Optional actual phase number; overrides crystal_structure.
lattice_parameters – Required reference cell when specifying spacegroup.
cell_choice – Standard or rhombohedral space-group setting.
- Returns:
- Minimum angle in radians, axis in the first
crystal frame and in the sample frame. Identity has zero axes.
- Return type:
angle, axis, axis_xyz
Notes
Pass U.T, not U. Transposing inputs can change the reduced ANGLE as well as the axes because crystal symmetry acts on a specific side. Equivalent orientations return zero. The angle is the physical result and does not depend on which symmetry operator reaches the minimum; the axis does. Ties return the lexicographically smallest unit axis, which is reproducible but is not a fundamental-zone reduction, and the axis is not canonicalised in sign, so swapping the two orientations reverses it. Crystal axes are expressed in the first orientation’s crystal frame and axis_xyz in the sample frame. Crystal-system enums retain their legacy highest-symmetry meaning. Supply the actual spacegroup and lattice_parameters for a lower point group, or precompute symmetry_operators_from_spacegroup once and pass that array as crystal_structure. Both orientations must share a phase.
- ImageD11.forward_model.grainmaps.disorientation_deprecated(ori1, ori2, crystal_structure=Symmetry.triclinic)#
Retain the deprecated name while using the corrected implementation. :param ori1: First sample-to-crystal matrix, U1.T. :param ori2: Second sample-to-crystal matrix, U2.T. :param crystal_structure: Legacy Symmetry enum or Cartesian operator group.
- Returns:
Radians, first-crystal axis and sample axis.
- Return type:
angle, axis, axis_xyz
- ImageD11.forward_model.grainmaps.disorientation_list(ori1_list, ori2_list, crystal_structure=Symmetry.triclinic, spacegroup=None, lattice_parameters=None, cell_choice='standard')#
Compare lists of sample-to-crystal matrices, retaining legacy outputs. :param ori1_list: U1.T or an array (n, 3, 3) of transposed U matrices. :param ori2_list: U2.T or an array (n, 3, 3); singleton lists broadcast. :param crystal_structure: Legacy system Symmetry enum or a complete proper
Cartesian rotation group. System enums use the highest symmetry.
- Parameters:
spacegroup – Optional actual phase number; overrides crystal_structure.
lattice_parameters – Reference cell in angstrom/degrees for spacegroup.
cell_choice – Standard or rhombohedral setting for spacegroup.
- Returns:
- Lists of radian angles and axes in the first
crystal and sample frames. Empty inputs return three empty lists.
- Return type:
angles, axes, axes_xyz
- ImageD11.forward_model.grainmaps.get_mean_rod(rod, kmeans_flag=False, auto_check=True)#
Compute the mean Rodrigues vector with optional k-means clustering.
Parameters: - rod: numpy array of shape (n, 3) or (3, n) representing Rodrigues vectors - kmeans_flag: boolean, whether to perform k-means clustering
Returns: - rod_mean: numpy array of shape (3,) representing the mean Rodrigues vector
- class ImageD11.forward_model.grainmaps.grainmap(filename=None, outname=None, min_misori=3, crystal_system='cubic', remove_small_grains=True, min_vol=3, verbose=0)#
Bases:
objectgrain map class to create and do operations on a grain map, akin fwd-DCT DS example: filename = ds.grains_file gm = grainmap(filename) gm.merge_and_identify_grains(FirstGrainID = 0, dis_tol = np.sqrt(3)) DS = gm.DS
- convert2DS()#
convert tensor_map to a dictionary like DS, which is similar to fwd-DCT struct, easier for subsequent operation
- merge_and_identify_grains(FirstGrainID=0, dis_tol=np.float64(1.7320508075688772), count_max=100, connectivity=2, relabel_disconnected=False)#
merge regions and identify grains to update grain IDs, i.e. ‘labels’ in DS default option to also clean up small grains, e.g. replace noisy voxels by neigboring voxels’ information
- read_tensor_map()#
- write_DS()#
write DS to an h5 file with filename defined as self.outname’
- write_labels2tmfile()#
write labels as new dataset to the original tensor map file’
- ImageD11.forward_model.grainmaps.indexing_iterative(cf_strong, grains, ds, ucell, pars, ds_max=1.6, tol_angle=0.25, tol_pixel=3, peak_assign_tol=0.25, tol_misori=3, crystal_system='cubic', **kwargs)#
Using the rest of peaks that are not matched with already-indexed grains to index additional grains Then, try to merge the grains by removing duplicate grains (if misori < tol_misori) and return grains_new
Arguments: cf_strong – ImageD11 colume file object file containing strong peaks grains – ImageD11 grains object, already-indexed grains ds – dataset object, e.g. ds = ImageD11.sinograms.dataset.load(dset_file) ucell – ImageD11.unitcell object, e.g. ucell = ds.phases.unitcells[phase_str] pars – ImageD1.parameters object, e.g. pars = ImageD11.parameters.read_par_file(ds.parfile) Optional arguments: ds_max – maximum 1/d tol_angle – tolerance of angles for matching peaks tol_piexl – tolerance of pixels for matching peaks peak_assign_tol – tolerance for assigning peaks to grains tol_misori – minimal misorientation to distinguish grains crystal_system – string name of the crystal system, ‘cubic’, ‘hexagonal’, ‘orthorhombic’, ‘tetragonal’, ‘trigonal’, ‘monoclinic’, ‘triclinic’
Returns: grains_new – ImageD11 grains object, with update grain ids starting from 0
- ImageD11.forward_model.grainmaps.merge_grains(grains, grains_rest, crystal_system='cubic', tol_misori=3)#
Identify duplicate grains and then make a new grains_new object
Arguments: grains – ImageD11 grains object, assuming from the first indexing grains_rest – ImageD11 grains object, assuming from the second indexing crystal_structure – symmetry class with crystal symmetry operators tol_ang – tolerance for misorientation to distinguish grains [deg]
Returns: grains_new – ImageD11 grains object, with update grain ids starting from 0
- ImageD11.forward_model.grainmaps.misorientation_angle_from_delta(delta)#
Calculate the angle of a proper relative rotation using atan2. :param delta: Relative rotation matrix, shape (3, 3).
- Returns:
Angle in radians in [0, pi], stable near zero and half turns.
- Return type:
angle
- ImageD11.forward_model.grainmaps.misorientation_axis_from_delta(delta)#
Calculate the physical rotation axis from a passive delta matrix. :param delta: Proper passive relative rotation, shape (3, 3).
- Returns:
- Unit axis of the inverse (active) rotation. Identity has zero
axis; exact half turns use a quaternion instead of a zero skew part.
- Return type:
axis
- ImageD11.forward_model.grainmaps.pairing_grains(grains1, grains2, crystal_system='cubic', tol_misori=3, tol_dis=50, tol_int=[0.0, 0.0])#
pairing grains from two different grains objects, useful for tracking the same grain across different datasets about 3 times faster with parallel, it may be speed up further
Arguments: grains1 – ImageD11 grains object grains2 – ImageD11 grains object assuming from the second indexing crystal_structure – symmetry class with crystal symmetry operators tol_ang – tolerance for misorientation to distinguish grains [deg] tol_dis – tolerance for distance-to-volume-center to distinguish grains [um] tol_int – tolerance for intensity (relative difference in mean intensity) to distinguish grains [-]
Returns: PairIndex – numpy array with a shape of N*18, column means [i, j, rod_i, rod_j, int_sum1, int_sum2, mis_ori, dis, COM_i, COM_j]
- ImageD11.forward_model.grainmaps.read_intensity_info(text)#
- ImageD11.forward_model.grainmaps.remove_gid_from_grains(grains, gid_to_remove=None)#
Remove specific grains from the existing grains
Arguments: gid_to_remove – a list of grain IDs to be removed
Returns: grains_new – ImageD11 grains object, with update grain ids starting from 0
- ImageD11.forward_model.grainmaps.symmetry_operators_from_spacegroup(spacegroup, lattice_parameters, cell_choice='standard', include_friedel=False)#
Build proper Cartesian rotations for the actual phase point group. :param spacegroup: Integer International space-group number, 1 through 230. :param lattice_parameters: Reference [a, b, c, alpha, beta, gamma], in
angstrom/degrees, using the same setting as the orientation B.
- Parameters:
cell_choice – xfab setting, standard or rhombohedral.
include_friedel – Add inversion before selecting proper rotations, giving the proper Laue group instead of the proper point group.
- Returns:
Array (n, 3, 3) in the ImageD11 B-compatible crystal frame.
- Return type:
symmetries
Notes
Uses existing xfab symmetry tables, not its 2*pi reciprocal basis. Pass this array as crystal_structure to reuse it for many comparisons.