ImageD11.sinograms.tensor_map module#
- class ImageD11.sinograms.tensor_map.TensorMap(maps=None, phases=None, steps=None)#
Bases:
objectThis is a class to store a contiguous voxel-based representation of a sample. At its core is the self.maps attribute, which is a dictionary of Numpy arrays. Each Numpy array should represent a 3D voxel grid of the sample. The dimensions of the array are aligned with the laboratory reference frame in the order (Z, Y, X, …) The shape of the first three axes should therefore be (NZ, NY, NX, …) The total number of dimensions can vary E.g a phase ID map might be (1, 15, 20) but a UBI map might be (1, 15, 20, 3, 3)
- property B#
The B matrix via the unitcell
- property U#
The U matrix - via UBI and B, the same way as in
ImageD11.grain
- property UB#
The UB matrix
- property UBI#
The UBI matrix
- add_map(name, array)#
Required to clear caches if UBI is set
- check_shape()#
Checks that all the maps in self.maps have equal shape for their first 3 dimensions
- clear_cache()#
- property dzero_unitcell#
The dzero unitcell for each voxel from the reference phase for that voxel.
- property eps_crystal#
The per-voxel Biot strain tensor in the crystal reference frame, relative to the B0 of the unitcell of the reference phase for that voxel.
Equivalent to calling
ImageD11.grain.eps_sample_matrix(dzero_cell).Will compute from
eps_sampleby rotating the tensor if we have it. If not, will compute fromUBI.
- property eps_devia#
The per-voxel deviatoric strain tensor
- property eps_eigvals#
The per-voxel eigenvalues of eps_sample, sorted from highest to lowest. Shape (…, 3)
- property eps_eigvecs#
The per-voxel eigenvectors of eps_sample, sorted to match eps_eigvals (highest to lowest eigenvalue). Shape (…, 3, 3), columns are eigenvectors.
- property eps_hydro#
The per-voxel hydrostatic strain tensor (frame invariant)
- property eps_sample#
The per-voxel Biot strain tensor in the sample frame, relative to the B0 of the unitcell of the reference phase for that voxel.
Equivalent to calling
ImageD11.grain.eps_grain_matrix(dzero_cell).Will compute from
eps_crystalby rotating the tensor if we have it. If not, will compute fromUBI.
- property euler#
The euler angles from the U matrix, the same way as in
xfab.tools
- classmethod from_combine_phases(tensormaps)#
Combine multiple mono-phase TensorMaps with different phases into one TensorMap. Handles grain-label collisions by offsetting the grain labels of subsequent tensormaps before adding.
The in-plane (NY, NX) shape may differ between inputs: each phase is reconstructed independently, so its
pad/ grid extent depends on that phase’s fittedy0(see from_stack). We pad every input onto a common, S-aligned grid before overlaying. Because padded voxels take each map’s ‘no data’ value, padded phase_ids become -1 and so never overwrite a real voxel from another phase. Z must already match across inputs (same physical layers, different phases).
- classmethod from_grainsinos(grainsinos, method='iradon', use_gids=True, cutoff_level=0.1, steps=None, sf_normalisation=False, sf_norm_percentile=99, smooth_labels=False, smooth_size=5)#
Build a TensorMap object from a list of GrainSinos. method is the recon that we look for inside each grainsino use_gids will look for grainsino.grain.gid inside each grainsino to use as the label; if it can’t find it, it will use the increment.
- sf_normalisationintensity normalisation scheme.
- False (default) -> per-grain recon is mean-normalised and clipped to
[0, 1], and unwon pixels are zeroed at the end (original behaviour).
- True -> recons are kept on their own (structure-factor-corrected) scale,
then the whole intensity map is globally rescaled and clipped. Use this when the recons already carry meaningful relative intensities.
sf_norm_percentile : for the sf_normalisation route, the intensity percentile (over nonzero voxels) that maps to 1.0; everything scales 0-1 from that and values above it are clipped. E.g. 99 means the 99th-percentile voxel becomes 1.
- smooth_labelsif True, median-filter the grain label map (size=smooth_size)
after the greedy assignment, then regenerate the intensity/phase/UBI/IPF maps from the smoothed labels. Off by default.
With sf_normalisation=False and smooth_labels=False this reproduces the original from_grainsinos output.
- classmethod from_h5(h5file, h5group='TensorMap')#
Load TensorMap object from an HDF5 file
- classmethod from_pbpmap(pbpmap, steps=None, phases=None)#
Create TensorMap from a pbpmap object
- classmethod from_stack(tensormaps, zstep=1.0)#
Stack multiple TensorMaps together along Z. The order of tensormaps determines the Z-order, lowest-index first. All TensorMaps must share the same phase mapping (i.e. phase 0 is always the same unitcell).
The in-plane (NY, NX) shape may differ between layers: a layer’s recon size is
ny + pad(iradon) or set bystep_grid_from_ybincens(PBP), andpad/ grid extent depend on that layer’s fittedy0. Small y0 variations therefore give slightly different layer sizes.Every layer is reconstructed with the rotation axis S at
shape // 2in recon space (iradonoutput_size // 2; PBPstep_to_reconshape // 2). Carried through the single-Yflip inrecon_order_to_map_order, S sits at map-Y indexNY - 1 - NY//2and map-X indexNX // 2(these differ by one for even sizes). We pad every layer onto a common, S-aligned grid before concatenating, keeping the rotation axis aligned through the stack. Padded voxels take each map’s ‘no data’ value.
- classmethod from_ubis(ubi_array)#
Make simplest possible TensorMap object from a UBI array in reconstuction space (X, -Y)
- get_ipf_maps(key='tsl', backend='rgb_colors')#
Calculate all IPF maps and add them to self.maps: colours of each voxel’s UBI with the point group of its phase (ImageD11.rgb_colors, key “tsl” or “hsv”) backend “orix”: orix TSL colours of the meta orix orientation of each phase
- get_meta_orix_orien(phase_id=0)#
Get a meta orix orientation for all voxels of a given phase ID
- get_mis2mean(sym_ops=None, n_iter=3, degrees=True)#
Per-voxel misorientation to the mean orientation of its grain (GROD).
Requires a ‘labels’ map and a UBI (or U) map. Loops over phase IDs so each phase uses its own symmetry. Voxels with label < 0 or NaN U stay NaN.
Adds ‘mis2mean’ (NZ, NY, NX) and ‘mean_U’ (NZ, NY, NX, 3, 3) to self.maps and returns the mis2mean map. Also stores per-grain GOS in self.gos (dict: label -> grain orientation spread).
- sym_opsoptional (Nsym, 3, 3) override, e.g. cubic_sym_ops(), applied to
every phase. Default is to pull them from self.phases.
- get_stress(stiffness_tensor, phase_id)#
Convert Biot strain tensor (ImageD11 coordinate system) to Biot stress tensor (ImageD11 coordinate system). Does this for a given phase_id. Needs Voigt-format IEEE coordinate system stiffness tensor.
- Parameters:
stiffness_tensor (np.ndarray) – 6x6 stiffness tensor in GPa, Voigt notation, IEEE 1976 coordinate system
phase_id (int) – ID of phase you want to compute for (makes phase mask)
- grain_mean_tensor(map_name='eps_sample', stat='mean', weights=None, nsigma=3.0, n_clip=2, min_voxels=1, symmetrise=True, to_crystal=False, equivalent=None, prefix=None)#
Per-grain mean of a tensor map, and each voxel’s residual from it.
The strain analogue of mis2mean. Works on any (NZ, NY, NX, …) tensor map - eps_sample, sig_sample, eps_crystal, whatever - grouped by the labels map.
Unlike orientations, symmetric tensors live in a flat vector space, so the grain mean really is just the arithmetic mean. No fundamental zone, no quaternions. Two things do still bite:
average eps_SAMPLE, not eps_crystal. eps_crystal = U.T eps_sample U, so picking a different symmetry variant U -> U S sends eps_crystal -> S.T eps_crystal S. Indexing hands each voxel an arbitrary variant, so averaging eps_crystal across a grain averages over the symmetry orbit and gives nonsense. eps_sample is a lab frame quantity and is variant independent. Use to_crystal=True to get the crystal frame answer the safe way: average in the sample frame, then rotate once with the grain mean U.
the residual is immune to d0 errors, the mean is not. eps is measured relative to the reference unitcell, so a wrong d0 adds a constant offset to every voxel of that phase - which cancels exactly when you subtract the grain mean. So the residual map is trustworthy even when the absolute strain is not.
- map_nameany map with shape (NZ, NY, NX, …). Fetched with getattr, so
lazy properties like eps_sample compute themselves on demand.
- stat‘mean’ - straight (optionally weighted) arithmetic mean
- ‘clipped’ - iteratively reject voxels more than nsigma robust
deviations from the mean, in Frobenius distance. Frame covariant, and the one to use on noisy maps.
- ‘median’ - componentwise median. Outlier resistant but NOT
rotation covariant, so treat it as a pragmatic estimate rather than a tensor.
weights : optional (NZ, NY, NX) weights, e.g. peak counts or 1/sigma**2. min_voxels: grains with fewer valid voxels get NaN rather than a mean of one. symmetrise: force (T + T.T)/2 before averaging. to_crystal: also rotate the grain mean into the crystal frame using mean_U
(run get_mis2mean first). Stores <prefix>_grain_crystal.
- equivalent: ‘strain’ or ‘stress’ for the scalar measure. Inferred from
map_name if left as None.
- Adds, with prefix defaulting to map_name:
<prefix>_grain (…, 3, 3) grain mean, broadcast to every voxel <prefix>_res (…, 3, 3) voxel minus grain mean <prefix>_res_eq (…) equivalent scalar of the residual <prefix>_res_hydro (…) hydrostatic part of the residual
(“_res” and not “_dev”, to avoid colliding with eps_devia, which is the deviatoric part of the strain and a completely different thing.)
Returns a dict with per-grain labels, means, voxel counts and residual RMS.
- kam(radius=1, metric='box', perimeter_only=False, use_steps=False, max_misori=None, same_grain=False, sym_ops=None, degrees=True, map_name='kam')#
Kernel average misorientation: mean disorientation to the neighbours in a kernel around each voxel.
- radius / metric / perimeter_only / use_steps
Shape of the kernel - see kernel_offsets. use_steps=True switches radius to physical units and uses self.steps, so anisotropic voxels behave.
- max_misori
Ignore pairs above this angle (degrees). The usual EBSD convention is ~5 deg; without it, voxels next to a grain boundary get a huge KAM that swamps the intragranular signal.
- same_grain
Alternative to max_misori if you have a labels map: only pair voxels that share a label. Cleaner, since it uses your actual segmentation rather than an angle cutoff.
- map_name
Where to store the result, so you can keep several kernel sizes around (‘kam_r1’, ‘kam_r3’, …).
Voxels with no valid neighbour in the kernel come back NaN.
- keys()#
allows you to use dictionary syntax
- static map_index_to_recon(mj, mk, yshape)#
From a 3D array index (mi, mj, mk) and the Y shape of the map, determine the corresponding position in reconstruction space
- static map_order_to_recon_order(map_arr, z_layer=0)#
Transform a 2D slice of a TensorMap to reconstruction space. The opposite of recon_order_to_map_order
- property mt#
The metric tensor
- plot(map_name, z_layer=0, **plot_kwargs)#
- static recon_index_to_map(ri, rj, yshape)#
From a 2D reconstruction space index (ri, rj) and the Y shape of the map, determine the corresponding position in TensorMap space
- static recon_order_to_map_order(recon_arr)#
Transform a 2D array from reconstruction space (first axis X, second axis is -Y) to TensorMap space (Z, Y ,X) The input array must have the first two dimensions (X, -Y) as is the case for reconstructed grain shapes from sinogram or PBP methods
- property shape#
The shape of the map (NZ, NY, NX)
- property sig_crystal#
The per-voxel Biot stress tensor in the crystal reference frame
- property sig_devia#
The per-voxel deviatoric stress tensor
- property sig_eigvals#
The per-voxel eigenvalues of sig_sample, sorted from highest to lowest. Shape (…, 3)
- property sig_eigvecs#
The per-voxel eigenvectors of eps_sample, sorted to match eps_eigvals (highest to lowest eigenvalue). Shape (…, 3, 3), columns are eigenvectors.
- property sig_hydro#
The per-voxel hydrostatic stress tensor (frame invariant)
- property sig_mises#
The per-voxel von-Mises stress scalar (frame invariant)
- property sig_sample#
The per-voxel Biot stress tensor in the sample reference frame
- to_ctf_mtex(ctf_path, z_index=0)#
Export a Z slice to a CTF file for MTEX processing. The resulting ctf file can be loaded in MTEX with the command: ebsd = EBSD.load(ctf_path) Note that no Euler or spatial conversions are needed
- to_h5(h5file, h5group='TensorMap')#
Write all maps to an HDF5 file (h5file) with a parent group h5group. Creates h5group if doesn’t already exist
- to_paraview(h5name, h5group='TensorMap')#
Exports to H5, then writes an XDMF file that lets you read the data with ParaView
- to_pbpmap(z_layer=0, default_npks=20, default_nuniq=20)#
Get a PBPMap object from this TensorMap object (good for refining strains)
- property unitcell#
The unitcell - from metric tensor
- ImageD11.sinograms.tensor_map.grain_mean_U(U, labels, sym_ops, n_iter=3)#
Symmetry-aware mean orientation of each grain.
U : (N, 3, 3) orientation matrices, no NaNs labels : (N,) integer grain labels Returns (unique_labels (G,), U_mean (G, 3, 3), inverse (N,)) where U_mean[inverse] is the mean orientation of each voxel’s grain.
Averaging orientations naively is meaningless when symmetry-equivalent variants are mixed, so every voxel is first pulled onto the branch closest to a running reference, then averaged with Markley’s method (principal eigenvector of sum(q q.T), which is immune to the q/-q sign ambiguity). The reference starts as one arbitrary member of the grain and is refined.
- ImageD11.sinograms.tensor_map.kernel_offsets(radius=1, metric='box', perimeter_only=False, steps=None)#
Neighbour offsets (dz, dy, dx) making up a KAM kernel.
- radiuskernel size, in voxels by default. If steps is given it is a
physical radius in the same units as steps (um), which is what you want when the z step is much coarser than the x/y step - a radius-1 box kernel on a 1x1x5 um grid is not isotropic.
- metric‘box’ -> max|d| <= radius (26 neighbours at radius 1 in 3D,
8 in a single-layer map)
- ‘diamond’ -> sum|d| <= radius (6 neighbours at radius 1, i.e. the
face-sharing set)
‘sphere’ -> |d| <= radius
- perimeter_onlykeep only the outer shell of the kernel, within one step of
the edge. This is the OIM “perimeter only” option, and it is the one that keeps KAM comparable as you grow the kernel, since the inner points otherwise dominate the average.
Returns only half the offsets: for every d returned, -d is omitted, because disorientation is symmetric and each pair only needs computing once.
- ImageD11.sinograms.tensor_map.sym_ops_from_phase(ucell)#
Proper rotation operators (Nsym, 3, 3) for an ImageD11 unitcell: the rotations of the Laue class of its spacegroup (ImageD11.sym_u.laue_rotations) in the same crystal Cartesian frame as ucell.B / U, so they can be applied to U directly.
The cell must be in the standard setting of its spacegroup (monoclinic: unique axis b). R spacegroups may be on hexagonal or rhombohedral axes, as ucell.cell_choice says. Pass sym_ops= explicitly for any other setting.
- ImageD11.sinograms.tensor_map.sym_reduce(U, U_ref, sym_ops)#
Pick, for each U, the symmetry equivalent U @ S closest to U_ref.
U, U_ref : (…, 3, 3) orientation matrices (crystal -> lab, as ImageD11 U) sym_ops : (Nsym, 3, 3) proper rotations in the crystal frame
Returns (U_reduced, disorientation_angle_in_radians).
Only one pass over the group is needed even though both crystals carry symmetry: minimising the angle of S1.T @ (U_ref.T @ U) @ S2 over all pairs is the same as minimising over (U_ref.T @ U) @ S for a single S, because S1 @ (S1.T @ D @ S2) @ S1.T == D @ (S2 @ S1.T) and conjugation preserves the rotation angle. So |G| operations, not |G|**2.