upxo.pxtal.mcgs3_temporal_slice module
Module: mcgs3_temporal_slice
This module contains the implementation of the mcgs3_grain_structure class, which is used for analyzing and processing grain structures in 3D space. It includes various methods for handling grain boundary points, grain positions, and other related properties.
Classes: - mcgs3_grain_structure: Class for handling and analyzing grain structures in 3D space.
Class: mcgs3_grain_structure Prominant attributes: - dim (int): Dimensionality of the grain structure. - uigrid (UPXO object): User input grid requirements. - uimesh (UPXO object): User input mesh requirements. - vox_size: Voxel size. - m (int): Monte-Carlo step or temporal slice. - s (np.ndarray): State matrix, output of Monte-Carlo (MC) simulation. - S: Total number of states considered in MC simulation. - n (int): Number of grains in the grain structure. - lgi (np.ndarray): Local Grain ID of every voxel in the grain structure. - gid (np.ndarray): Grain ID. - g (UPXO object): Individual grain objects. - gb (UPXO object): Individual grain boundary objects. - s_gid (dict): State value partitioning of gid. - gid_s (np.ndarray): gid value based partitioning of state values. - s_n (list): State value based partitioning of number of grains. - neigh_gid (dict): Immediate neighbour information of every grain. - positions (dict): Position name partitioned gids. - grain_locs (dict): gid partitioned global coordinates of all voxels. - gpos (dict): Position name partitioned gids. - spbound (dict): Spatial bounds of all grains. - spboundex (dict): Extended spatial bounds of all grains. - sssr: Surface-sub-surface relationships. - mprop (dict): Morphological properties. - pvgrid: Py-Vista grid object - lgi_slice: lgi slice - prop_flag: Flag for morphological properties - prop: Morphological properties - domain_volume: Volume of the domain - xax: x-axis - yax: y-axis - zax: z-axis - axlim: Axis limits
Methods: - __init__: Initializes the mcgs3_grain_structure object. (Special Method) - __iter__: Returns an iterator object. (Special Method) - __repr__: Returns a string representation of the object. (Special Method) - __next__: Returns the next grain in the iteration. (Special Method) - __att__: Returns the attribute handler. (Special Method)
by_data: Class method to instantiate a temporal slice using a 3D Monte-Carlo state value array.
calc_num_grains: Calculates the total number of grains in the grain structure.
char_morphology_of_grains: Characterizes the 3D morphology of the grain structure.
char_lgi_slice_morpho: Characterize morphology of a 2D slice of self.lgi.
clean_gs_GMD_by_source_erosion_v1: Clean the gs using grain merger by dissolution by source grain erosion.
clean_gs_GMD_by_source_erosion_v2: Clean the gs using grain merger by dissolution by source grain erosion.
create_neigh_gid_pair_ids: Create neighbor grain ID pair IDs
copy_lgi_1: Copy local grain ID 1
export_vtk3d: Export data to .vtk format.
extract_subdomains_random: Extract subdomains random
find_grains: Detects grains in the local grain ID array.
find_neigh_gid: Sets the neighbouring grain IDs for all grains.
find_spatial_bounds_of_grains: Finds the spatial bounds of each grain in the grain structure.
find_bounding_cube_gid: Finds the subset of the local grain ID array that tightly binds a grain.
find_exbounding_cube_gid: Finds the subset of the local grain ID array that loosely binds a grain.
find_grain_voxel_locs: Finds the voxel locations of grains in the local grain ID array.
find_scalar_array_in_plane: Get the scalar values array in a plane.
fit_ellipsoids: Fit ellipsoids to all grains in the grain structure.
find_gid_pair_gbp_IDs: Find the gbp coords at the interface of gidl and gidr.
find_twin_hosts: Find twin hosts
get_vox_size: Returns the size of the voxel.
get_binaryStructure3D: Returns the binary structure type for grain identification.
get_upto_nth_order_neighbors: Calculates up to nth order neighbours for a given grain ID.
get_nth_order_neighbors: Calculates only the nth order neighbours for a given grain ID.
get_upto_nth_order_neighbors_all_grains: Calculates up to nth order neighbours for all grains.
get_nth_order_neighbors_all_grains: Calculates only the nth order neighbours for all grains.
get_upto_nth_order_neighbors_all_grains_prob: Calculates up to nth order neighbours for all grains with a probability.
get_bounding_cube_all: Finds the subsets of the local grain ID array that tightly bind all grains.
get_exbounding_cube_all: Finds the subsets of the local grain ID array that loosely bind all grains.
get_scalar_field: Returns the requested scalar field.
get_scalar_field_slice: Gets scalar field values along the specified slice.
get_scalar_array_in_plane_unique: Find unique gids in a plane defined by origin and normal.
get_bbox_diagonal_vectors: Find the vector representing doiagonal of the bounding box.
get_voxel_volume: Return voxel volume from pvgrid data.
get_voxel_surfareas: Return voxel surface area from pvgrid data.
generate_bresenham_line_3d: Generate Bresenham line in 3d between two coordinate locations.
get_values_along_line: Get values in 3D array along line between loci and locj points.
get_igs_properties_along_line: Measure intercept properties along line b/w two specified locations.
get_igs_along_line: Measure intercept properties along line b/w two specified locations.
get_opposing_points_on_gs_bound_planes: Get points on the opposing boundaries of the grain structure.
get_igs_along_lines: Measure intercept properties along lines defined by location sets i, j.
get_igs_along_lines_multiple_samples: Measure intercept properties along lines defined by location sets i, j for multiple samples.
get_bbox_aspect_ratio: Get aspect ratio of bounding box
get_bbox_volume: Get volume of bounding box
get_volnv_gids: Get volume by number of voxels for gids
get_lgi_subset_around_location: Get lgi subset around location
get_neigh_grains_next_to_location: Get neighbor grains next to location
get_local_global_coord_offset: Get local global coordinate offset
get_cutoff_twvol: Get cutoff twin volume
get_k_nearest_coords_from_tree: Get k nearest coordinates from tree
get_points_in_feature_coord: Get points in feature coordinate
get_gs_instance_pvgrid: Get grain structure instance PyVista grid
import_ctf: Import a ctf file
import_crc: Import a crc file
import_dream3d: Import a dream3d file
import_vtk: Import a vtk file
instantiate_twins: Instantiate twins
initiate_gbp: Initiate grain boundary points
identify_twins_gid: Identify twins for grain ID
identify_twins: Identify twins
igs_sed_ratio: Calculate the ratio of intercept grain size to sphere eq. diameter.
make_pvgrid: Creates a PyVista grid of the local grain ID array.
make_zero_non_gids_in_lgi: Returns a grain ID masked copy of the local grain ID array.
make_zero_non_gids_in_lgisubset: Returns a grain ID masked copy of a subset of the local grain ID array.
mesh: Mesh the grain structure
merge_two_neigh_grains: Merges one grain into another if they are neighbours.
mask_lgi_with_gids: Masks the local grain ID array against user input grain indices.
mask_s_with_gids: Masks the state matrix against user input grain indices.
mask_fid: Mask feature ID
mask_fid_and_make_pvgrid: Mask feature ID and make PyVista grid
mask_fid_and_plot: Mask feature ID and plot
smoothen_sds: Smoothen subdomains
_merge_two_grains_: Low-level merge operation for two grains.
plot_mprop_correlations: Plots the correlations between morphological properties.
plot_gs_pvvox: Plots the grain structure as PyVista voxels.
plot_gs_pvvox_subset: Plots a subset of the voxelated grain structure in PyVista.
plot_gbpoint_cloud_global: Plots all the grain boundary point clouds.
plot_scalar_field_slice_orthogonal: Plots the scalar field along three fundamental orthogonal planes.
plot_scalar_field_slice: Plots the scalar field along the specified slice plane.
plot_scalar_field_slices: Plots the scalar field along multiple parallel slice planes.
plot_largest_grain: Plots the largest grain in a temporal slice.
plot_longest_grain: Plots the longest grain in a temporal slice.
plot_grains: Plots grains given some grain IDs.
plot_grain_sets: Plot multiple prominant and non-prominant grains.
plot_gids_along_plane: Plot grains which fall alomng a plane.
plot_single_voxel_grains: Plot single voxel grains
plot_gs_instance: Plot grain structure instance
recalculate_ngrains_post_grain_merge: Recalculates the number of grains after a grain merger.
renumber_gid_post_grain_merge: Renumbers the grain IDs after a grain merger.
renumber_lgi_post_grain_merge: Renumbers the local grain ID array after a grain merger.
remove_overlaps_in_twins: Remove overlaps in twins
reset_slice_lgi: Identify and labels grains in a 3D grain structure’s 2D slice.
reset_fdb: Reset feature data base
sep_gbzcore_from_bbgidmask: Seperate grain boundary zone core from bounding box grain ID mask
set__s_n: Sets the number of grains in each state.
set__s_gid: Sets the grain IDs for each state.
set__gid_s: Sets the state values for each grain ID.
set__spart_flag: Sets the state partitioning flags.
set_binaryStructure3D: Sets the binary structure type for grain identification.
set_skimrp: Sets the region properties of the scikit image.
set_mprops: Sets the morphological properties of the grain structure.
set_binaryStructure3D: Sets the binary structure type for grain identification.
set_gid: Sets the grain IDs.
set_gbpoints_global_point_cloud: Sets a PyVista PolyData object with global grain boundary points.
set_mprop_volnv: Calculate the volume by number of voxels.
set_mprop_volnv_old: Calculate the volume by number of voxels. TO BE NUMBAfied
set_mprop_pernv: Calculate the total perimeter of the grain by number of voxels.
set_mprop_eqdia: Calculate equivalent sphere diameter.
set_mprop_solidity: Set solidity morphological property of all 3D grains.
set_mprop_arbbox: Calculate aspect ratio of bounding box.
set_mprop_arellfit: Calculate aspect ratio of grain using ellipsoidal fit.
set_mprop_sol: Calculate solidity of grains.
set_mprop_ecc: Calculate eccentricity of grains.
set_mprop_com: Calculate compactness of grains.
set_mprop_sph: Calculate sphericity of grains.
set_mprop_fn: Calculate flatness of grains.
set_mprop_rnd: Calculate roundness of grains.
set_mprop_fdim: Calculate fractal dimension of grains.
set_Lgbp_gid: Set local grain boundary points for a grain ID
set_Lgbp_all: Set local grain boundary points for all grains
set_gid_pair_gbp_IDs: Set grain ID pair grain boundary point IDs
set_neigh_gid_interaction_pairs: Set neighbor grain ID interaction pairs
setup_gid_pair_gbp_IDs_DS: Setup grain ID pair grain boundary point IDs data structure
setup_gid_set__gbsegs: Setup grain ID set grain boundary segments
setup_gid_twin: Setup grain ID twin
setup_for_twins: Setup for twins
set_mprop_sanv: Set morphological property surface area by number of voxels
set_mprop_rat_sanv_volnv: Set morphological property ratio of surface area by number of voxels to volume by number of voxels
set_grain_positions: Set positions of grains relative to grain structure boundaries.
set_gid_imap_keys: Assign inverse mapping keys to grains based on relative positions.
assign_gid_imap_keys: Assign inverse mapping keys to grains based on relative positions.
sss_rel_morpho: Carry out surface – sub-surface relationship study.
sss_rel_morpho_multiple: Carry out surface – sub-surface relationship study on multiple planes.
update_dream3d_ABQ_file: Update Dream3D Abaqus file
validate_scalar_field_name: Validates if a scalar field name is valid.
viz_browse_grains: Browse grains in the grain structrure using a slider.
viz_clip_plane: Visualize grain structure along a clip plane.
viz_mesh_slice: Visualize grain structure along a slice plane.
viz_mesh_slice_ortho: Viz. grain str. along three fundamental mutually orthogonal planes.
check_for_neigh: Checks if a grain is a neighbour of another grain.
create_neigh_gid_pair_ids: Create neighbor grain ID pair IDs
deform_ortho: Deform orthogonal
globalise_gbp: Globalise grain boundary points
is_gid_pair_in_lr_or_rl: Check if grain ID pair is in left-right or right-left configuration
offset_local_to_global: Offset local to global
perform_post_grain_merge_ops: Performs necessary operations after a grain merger.
build_gbp_stack: Build grain boundary point stack
build_gbpids: Build grain boundary point IDs
build_gbp: Build grain boundary points
build_gbp_id_mappings: Build grain boundary point ID mappings
find_gbsp: Find grain boundary surface points
build_gid__gid_pair_IDs: Build grain ID to grain pair IDs mapping
_check_lgi_dtype_uint8: Validates and modifies the local grain ID array data type.
_compute_volumes_with_bincount: Calculate the volume by number of voxels using Numba and bincount.
Property definitions: - get_vox_size: Returns the size of voxel. - nvoxels: Volume by number of voxels - nvoxels_values: Volume by number of voxels values - single_voxel_grains: Single voxel grains - smallest_volume: Smallest volume - largest_volume: Largest volume
- class upxo.pxtal.mcgs3_temporal_slice.mcgs3_grain_structure(dim=3, m=None, uidata=None, vox_size=None, S_total=None, uigrid=None, uimesh=None, ndimg_label_pck=None, iroute='regular', udata=None, udata_name='s')[source]
Bases:
objectNomenclature
id: ID number gid: Grain ID gb: Grain boundary gbp: Grain boundary points gpos: Grain position imap: Inverse map Lgbp_all: All the local grain boundary points Ggbp_all: All the globalised grain boundary points
- param dim:
- type dim:
Dimensionality. Type: int
- param uigrid:
- type uigrid:
user input grid requirements. Type: UPXO obj
- param uimesh:
- type uimesh:
user input mesh requirements. Type: UPXO obj
- param vox_size:
- type vox_size:
voxel size.
- param m:
- type m:
Monte-Carlo step. Also called tslice, temporal slice. Type: int
- param s:
- type s:
State matrix, output of Monte-Carlo (MC) simulation. Type. np.ndarray
- param S:
- type S:
Total number of states considered in MC simulation.
- param n:
- type n:
Number of grains in the grain structure. Type: int
- param lgi:
- type lgi:
Local Grain ID of every voxel in the grain strycture. Type: np.ndarray
- param gid:
- type gid:
grain ID. Type: np.ndarray
- param g:
- type g:
individual grain objects. Type: UPXO obj
- param gb:
- type gb:
individual grain boundary objects. Type: UPXO obj
- param s_gid:
- type s_gid:
State value partitioning of gid. Type: dict
- param gid_s:
- type gid_s:
gid value based partitioning of state values. Type: np.ndarray
- param s_n:
- type s_n:
state value based partitioning of number of grains. Type: list
- param neigh_gid:
- type neigh_gid:
Immediate neighbour information of every grain. Type: dict
- param positions:
- type positions:
position name partitined gids. Type: dict. to be deprecated
- param grain_locs:
- type grain_locs:
gid partitined global coordinates of all voxels. Type: dict
- param gpos:
- type gpos:
position name partitined gids. Type: dict
- param spbound:
- type spbound:
spatial bounds of all grains. Type: dict
- param spboundex:
- type spboundex:
extended spatial bounds of all grains. Type: dict
- param Ggbp_all:
- type Ggbp_all:
gid paritiotned global grain boundary point coords. Type: dict
- param gbpstack:
- type gbpstack:
Global stack of all grain boundary points. Type: np.ndarray
- param gbpids:
- type gbpids:
Global stack of all grain boundary point IDs. Type: np.ndarray
- param gbp_id_maps:
- type gbp_id_maps:
Map from gbpstack into gbpids. Type: dict
- param gbp_ids:
- type gbp_ids:
gid partitioned gbpids. Type: dict
- param gid_pair_ids:
- type gid_pair_ids:
Every immediate neighbour pair ID and gids. Type: dict
- param gid_pair_ids_rev:
- type gid_pair_ids_rev:
Reverse mapping of gid_pair_ids. Type: dict
- param gid_pair_ids_unique_lr:
- type gid_pair_ids_unique_lr:
Unique left-right gid neigh pairs. Type: np.ndarray
- param gid_pair_ids_unique_rl:
- type gid_pair_ids_unique_rl:
Unique right-left gid neigh pairs. Type: np.ndarray
- param gbsurf_pids_vox:
- type gbsurf_pids_vox:
grain boundary surface voxel IDs. Type: dict.
- param gid_imap_keys:
- type gid_imap_keys:
@dev only.
- param gid_imap:
- type gid_imap:
@dev only.
- param Lgbp_all:
- type Lgbp_all:
@ dev only.
- param mp:
- type mp:
UPXO multi-point object template. Type: UPXO obj
- param binaryStructure3D:
- type binaryStructure3D:
structure used in grain identification. Type. np.ndarray
- param spart_flag:
- type spart_flag:
State value partitioning flags for grains. Type: np.ndarray
- param sssr:
- type sssr:
surface-sub-surface relationships
- param mprop:
- type mprop:
morphhological properties. Type: dict. mprops could have the
- param fo9llowing keys:
volnv: Volume by number of voxels volsr: Volume after grain boundary surface reconstruction volch: Volume of convex hull
sanv: surface area by number of voxels savi: surface area by voxel interfaces sasr: surface area after grain boundary surface reconstruction psa: projected surface area
pernv: perimeter by number of voxels pervl: perimeter by voxel edge lines pergl: perimeter by geometric grain boundary line segments
eqdia: eqvivalent diameter feqdia: Feret eqvivalent diameter
kx: grain boundary voxel local curvature in yz plane ky: grain boundary voxel local curvature in xz plane kz: grain boundary voxel local curvature in xy plane kxyz: mean(kx, ky, kz) ksr: k computed from surface reconstruction.
arbbox: aspect ratio by bounding box arellfit: aspect ratio by ellipsoidal fit
sol: solidity ecc: eccentricity - how much the shape of the grain differs from
a sphere.
com: compactness sph: sphericity fn: flatness rnd: roundness mi: moment of inertia tensor
fdim: fractal dimension
rat_sanv_volnv: Ratio of sanv to volnv
- EPS = 0.1
- CUBIC_SYMM_OPS = None
- fcc_tc = {'A1': (35.0, 45.0, 90.0), 'A2': (55.0, 90.0, 45.0), 'B': (45.0, 90.0, 45.0), 'C': (0.0, 90.0, 45.0), 'D': (59.0, 37.0, 26.0), 'P': (90.0, 45.0, 0.0), 'Q': (35.0, 55.0, 45.0), 'brass': (35.0, 45.0, 0.0), 'copper': (90.0, 35.0, 45.0), 'cube': (0.0, 0.0, 0.0), 'goss': (90.0, 90.0, 45.0), 'rotated_cube': (45.0, 0.0, 0.0), 's': (59.0, 37.0, 63.0)}
- ctrls
- ndimg_label_pck
- dim
- m
- uigrid
- uimesh
- vox_size
- g
- gb
- info
- sssr
- fdb
- gpos
- grain_locs
- pointclouds_pv
- mp
- are_properties_available
- pvgrid
- ellfits
- gid_twin
- valid_scalar_fields
- skimrp
- mprop
- axlim
- xax
- yax
- zax
- domain_volume
- neigh_gid
- s
- lgi
- gid
- n
- S
- tc_info
- property get_vox_size
Return the voxel size used by the current grid.
- classmethod by_parameters(xmin=0.0, xinc=1.0, xmax=100.0, ymin=0.0, yinc=1.0, ymax=100.0, zmin=0.0, zinc=1.0, zmax=100.0, S_total=-1, MCsteps=10, alg='300b')[source]
Create a structure from grid parameters.
- classmethod by_data(sf_data, sf_name='s', dim=3, m=0, xmin=0.0, xinc=1.0, xmax=100.0, ymin=0.0, yinc=1.0, ymax=100.0, zmin=0.0, zinc=1.0, zmax=100.0, S_total=-1, nvoxels_max=1010000000.0, reindex_labels=True)[source]
Instantiate a temporal slice from a 3D state or label array.
- Parameters:
sf_data (numpy.ndarray) – 3D grain-structure or state data.
sf_name (str, optional) – Name of the supplied data field.
dim (int, optional) – Dimensionality of the problem.
m (int, optional) – Temporal-slice index.
xmin (float, optional) – Domain bounds and increments.
xinc (float, optional) – Domain bounds and increments.
xmax (float, optional) – Domain bounds and increments.
ymin (float, optional) – Domain bounds and increments.
yinc (float, optional) – Domain bounds and increments.
ymax (float, optional) – Domain bounds and increments.
zmin (float, optional) – Domain bounds and increments.
zinc (float, optional) – Domain bounds and increments.
zmax (float, optional) – Domain bounds and increments.
S_total (int, optional) – Total number of discrete state values.
nvoxels_max (int, optional) – Maximum number of voxels allowed.
reindex_labels (bool, optional) – Reindex labels when
sf_nameis'base'or'lgi'.
Examples
from upxo.ggrowth.mcgs import mcgs pxt = mcgs(input_dashboard='input_dashboard.xls') pxt.simulate(verbose=False) tslice = 10 gstslice = pxt.gs[tslice] gstslice.char_morphology_of_grains(label_str_order=1, find_grain_voxel_locs=True, find_spatial_bounds_of_grains=True, force_compute=True) gstslice.set_mprops(volnv=True, eqdia=False, eqdia_base_size_spec='volnv', arbbox=False, arbbox_fmt='gid_dict', arellfit=False, arellfit_metric='max', arellfit_calculate_efits=False, arellfit_efit_routine=1, arellfit_efit_regularize_data=False, solidity=False, sol_nan_treatment='replace', sol_inf_treatment='replace', sol_nan_replacement=-1, sol_inf_replacement=-1) p, q, r = 5, 5, 10 A = gstslice.extract_subdomains_random(p=p, q=q, r=r, n=2, feature_name='s', make_pvgrids=False) from upxo.pxtal.mcgs3_temporal_slice import mcgs3_grain_structure sf_data = A['sd'][0] sd = mcgs3_grain_structure.by_data(sf_data, sf_name='s', dim=3, m=tslice, xmin=0.0, xinc=1.0, xmax=r, ymin=0.0, yinc=1.0, ymax=q, zmin=0.0, zinc=1.0, zmax=p, S_total=gstslice.S, nvoxels_max=1.01E9) sdraw = gstslice.extract_subdomains_random(p=p, q=q, r=r, n=5, feature_name='base', make_pvgrids=False) for udata in sdraw['sd']: sd = mcgs3_grain_structure.by_data(udata, sf_name='lgi', dim=3, m=tslice, xmin=0.0, xinc=1.0, xmax=r, ymin=0.0, yinc=1.0, ymax=q, zmin=0.0, zinc=1.0, zmax=p, S_total=gstslice.S, nvoxels_max=1.01E9) A = gstslice.extract_subdomains_random(p=40, q=40, r=40, n=1, feature_name='s', make_pvgrids=False) udata = A['sd'][0] sd = mcgs3_grain_structure.by_data(udata, sf_name='s', dim=3, m=tslice, xmin=0.0, xinc=1.0, xmax=40, ymin=0.0, yinc=1.0, ymax=40, zmin=0.0, zinc=1.0, zmax=40, S_total=gstslice.S, nvoxels_max=1.01E9)
- reindex_labels(udata)[source]
Reindex the labels in the input 3D numpy array such that they are consecutive integers starting from 1.
- Parameters:
udata (numpy.ndarray) – A 3D numpy array of integers.
- Returns:
A 3D numpy array with reindexed labels.
- Return type:
- property lfi
Return the local feature image / labelled grain image.
- static reindex_array_by_cmp_old_new_images(old_image, new_image, old_arrays)[source]
Re-indexes lists of old IDs based on the mapping between an old and new image.
- Parameters:
old_image (np.ndarray) – The 3D array with original, non-contiguous integer IDs.
new_image (np.ndarray) – The 3D array with new, re-indexed, contiguous integer IDs.
old_arrays (list[np.ndarray]) – A list of 1D arrays containing subsets of the old IDs.
- Returns:
A list of new 1D arrays with the IDs re-indexed according to the new_image.
- Return type:
list[np.ndarray]
- char_morphology_of_grains(sf_name='s', label_str_order=1, ngrains_max=1000.0, make_pvgrid=True, find_neigh=[False, [1], False, '1-no'], find_grain_voxel_locs=False, find_spatial_bounds_of_grains=False, find_grain_locations=False, force_compute=False, extra_sf={'sfname1': None, 'sfname2': None}, fdb_details={'name': None}, set_mprops=True, mprops_kwargs={'arbbox': False, 'arbbox_fmt': 'gid_dict', 'arellfit': False, 'arellfit_calculate_efits': True, 'arellfit_efit_regularize_data': True, 'arellfit_efit_routine': 1, 'arellfit_metric': 'max', 'disp_msg': '', 'eqdia': False, 'eqdia_base_size_spec': 'volnv', 'rat_sanv_volnv': False, 'sanv': False, 'sanv_N': 26, 'sanv_verbosity': 100.0, 'set_skimrp': False, 'sol_inf_replacement': -1, 'sol_inf_treatment': 'replace', 'sol_nan_replacement': -1, 'sol_nan_treatment': 'replace', 'solidity': False, 'volnv': True})[source]
Characterize the 3D morphology of the grain structure.
- Parameters:
sf_name (str, optional) – Provide which UPXO data is to be characterised. Optiona include s, lgi, fdb. Defaults to a value of ‘s’.
label_str_order (int, optional) – Provide the voxel connectivity order used for grain identification. Defaults to a value of 1.
ngrains_max (int, optional) – Maximum number of grains stop calculating 1E3,
make_pvgrid (bool, optional) – Flag to create PyVista grid. Defaults to True.
find_neigh (list, optional) –
List containing flag and a list of niehghbour orders needed. Its details arebelow:
find_neigh[0]: Flag to create neigh grain data-structures. find_neigh[1]: List of numbers representing the neigh
order values needed. The default self.neigh variable shall contain neighbouring grain informatoipm only for order 1. Other order neighbouir grain datas will be contained in a different dictionary.
- find_neigh[2]: Flag to include gid as self-neighbour inside
neighbour list.
- find_neigh[3]: str. This points to whether we need to calculate
upto no neighbout order or only the no^th neighbour ourder.
Defaults to [False, [1]].
find_grain_voxel_locs (bool, optional) – Flag to find the grain voxel masks in lgi. Find if True, ignore if False. Defaults to False.
find_spatial_bounds_of_grains (bool, optional) – Flag to calculate the spatial bounds of each grain in lgi. Find if True and ignore if False. Defaults to False.
force_compute (bool, optional) – Flag to ignore ngrains_max. Morohological proprties requexted to be caluclated will all be calculated even when ngrains_max is not satisfied. Defaults to False.
Notes
It is recommended that the label_str_order value be 3 to reduce the number of grains which are morphologically diffcult to mesh and would require complex grain boundary surface cleaning operations.
A label_str_order value of 3 results in an increased count of single voxel grains in the grain structure.
The label_str_order of 3 does not completely eliminate the presence of difficult types of grain boundarty surface edge connection and surface morphologies but certainly leads to a lesser count of such geometries.
Function order
Secondary. Calls a number of other primary functions.
Functionality order
Secondary. Provcided the availableity of the grain structure labels, the user can use their own pipelines for grain structure characterization, cleaning, meshing and exports. Nevertheless this is a useful function to have in the core UPXO.
- set_mprops(set_skimrp=False, volnv=True, eqdia=False, eqdia_base_size_spec='volnv', arbbox=False, arbbox_fmt='gid_dict', arellfit=False, arellfit_metric='max', arellfit_calculate_efits=True, arellfit_efit_routine=1, arellfit_efit_regularize_data=True, solidity=True, sol_nan_treatment='replace', sol_inf_treatment='replace', sol_nan_replacement=-1, sol_inf_replacement=-1, sanv=False, sanv_N=26, rat_sanv_volnv=False, sanv_verbosity=100.0, disp_msg='')[source]
Set morphological properties of the grain structure.
- Parameters:
volnv (bool, optional) – Default value is True. Flag value for computing grain volumes by number of voxels. Compute if True.
eqdia (bool, optional) – Default value is False. Flag value to compute sphere equivalent volume diameter.
eqdia_base_size_spec (str, optional) –
Default value is ‘volnv’. Specify which sort of volume or surface area is to be used to calculate the equivalent diameter. Options include the follwowing:
’volnv’: Volume by number of voxels
’volsr’: Volume by surface reconstruction
’volch’: Volume of convex hull
’sanv’: surface ares by number of voxels
’savi’: surface area by voxel interfaces
’sasr’: surface area by surface reconstruction
arbbox (bool, optional) – Default value is False. Flag value for computing grain aspect ratios by using bonding box dimensions. Compute if True.
arbbox_fmt (str, optional) –
Default value is ‘gid_dict’. Specify format of storing the calculated arbbox values. Options are:
list
np / np_array / np.array / numpy
arellfit (bool, optional) – Default value is False. Flag value to compute aspect ratio by using axes of the ellipsoidal fits to grains.
arellfit_metric (str, optional) –
Metric to use in aspect ratrio clauclation. Refer to doicumentation of function set_mprop_arellfit for further details. Default value is ‘max’. Options include the following:
max / maximum / maximal
min / minimum / minimal
xy / yx / z
yz / zy / x
xz / yz / y
arellfit_calculate_efits (bool, optional) – Default value is True. Set to True if ellispoids are to be fit (or refit, if that be the case) first.
arellfit_efit_routine (int, optional) – Default value is 1. Refer to doicumentation of function set_mprop_arellfit for further details.
arellfit_efit_regularize_data (bool, optional) – Default value is True. Refer to doicumentation of function set_mprop_arellfit for further details.
- find_grains(label_str_order=1, pck=None)[source]
Detect grains in
self.sand populateself.lgi.- Parameters:
label_str_order (int, optional) – Voxel connectivity order used for grain identification.
pck (callable, optional) – Connected-component labelling function.
- Return type:
None
- static find_neigh_gid_numba(lgi)
Compute neighbouring grain IDs using a numba-friendly implementation.
- Returns:
Grain ID to neighbouring grain ID arrays.
- Return type:
numba.typed.Dict
- static find_neigh_gid_core_numba(lgi, gid, dxdydz)
Return neighbouring grain IDs for one grain ID.
- find_neigh_fdb(feature_name='base', instance_name='lgi', disp_msg=False, verbosity=500, save_to_neigh_gid=False)[source]
Set neighbouring feature IDs for all features.
- check_for_neigh(parent_gid, other_gid)[source]
Check whether
other_gidis a first-order neighbour ofparent_gid.- Parameters:
parent_gid – Grain ID of the parent.
other_gid – Grain ID of the other grain being checked for O(1) neighbourhood with parent_gid.
- Returns:
True when
other_gidis a valid first-order neighbour.- Return type:
- get_upto_nth_order_neighbors(grain_id, neigh_order, recalculate=False, include_parent=True, output_type='list')[source]
Calculate neighbours up to the requested order for one grain ID.
- Parameters:
grain_id (int) – The ID of the cell for which to find neighbors.
neigh_order (int) – The order of neighbors to calculate (1st order, 2nd order, etc.).
include_parent (bool) – If True, user provided grain_id will also be included in the list of neighbours, as a grain is its 0th order neightbour, that is, its own neighrbour. DEfaults value is True.
output_type (str) –
Specify the desired neighbour data type. Options include the following:
list
nparray
set
- Returns:
Neighbours up to the requested order.
- Return type:
list or numpy.ndarray or set
Example
from upxo.ggrowth.mcgs import mcgs pxtal = mcgs(study=’independent’) pxtal.simulate() pxtal.detect_grains() gid = 10 np.unique(pxtal.gs[16].find_extended_bounding_box(gid)) # pxtal.gs[16].find_neigh_gid_fast_all_grains(include_parent=False) pxtal.gs[16].find_neigh_gid()
neigh_order = 3 pxtal.gs[16].get_upto_nth_order_neighbors(gid,
neigh_order, recalculate=False, include_parent=True, output_type=’list’)
- get_nth_order_neighbors(grain_id, neigh_order, recalculate=False, include_parent=True)[source]
Calculate only the nth-order neighbours for one grain ID.
- Parameters:
grain_id (int) – The ID of the cell for which to find neighbors.
neigh_order (int) – The order of neighbors to calculate (1st order, 2nd order, etc.).
include_parent (bool) – If True, user provided grain_id will also be included in the list of neighbours, as a grain is its 0th order neightbour, that is, its own neighrbour. DEfaults value is True.
output_type (str) –
Specify the desired neighbour data type. Options include the following:
list
nparray
set
- Returns:
Neighbours exactly at the requested order.
- Return type:
Example
from upxo.ggrowth.mcgs import mcgs fname = ‘input_dashboard_for_testing_50x50_alg202.xls’ pxtal = mcgs(study=’independent’,
input_dashboard=fname)
pxtal.simulate() pxtal.detect_grains() gid = 10 np.unique(pxtal.gs[16].find_extended_bounding_box(gid)) # pxtal.gs[16].find_neigh_gid_fast_all_grains(include_parent=False) pxtal.gs[16].find_neigh_gid() neigh_order = 2 pxtal.gs[16].get_nth_order_neighbors(gid, neigh_order,
recalculate=False, include_parent=True)
- get_upto_nth_order_neighbors_all_grains(neigh_order, recalculate=False, include_parent=True, output_type='list')[source]
Calculate neighbours up to the requested order for every grain.
- Parameters:
- Returns:
Grain IDs mapped to their neighbours up to the requested order.
- Return type:
Example
from upxo.ggrowth.mcgs import mcgs pxtal = mcgs(study=’independent’,
input_dashboard=’input_dashboard_for_testing_50x50_alg202.xls’)
pxtal.simulate()
neigh_order = 3 pxtal.gs[16].get_upto_nth_order_neighbors_all_grains(neigh_order,
recalculate=False, include_parent=True, output_type=’list’)
- get_nth_order_neighbors_all_grains(neigh_order, recalculate=False, include_parent=True)[source]
Calculate only the nth-order neighbours for every grain.
- Parameters:
- Returns:
Grain IDs mapped to their nth-order neighbours.
- Return type:
Example
from upxo.ggrowth.mcgs import mcgs fname = ‘input_dashboard_for_testing_50x50_alg202.xls’ pxtal = mcgs(study=’independent’,
input_dashboard=fname)
pxtal.simulate() pxtal.detect_grains() neigh_order = 2 A = pxtal.gs[16].get_upto_nth_order_neighbors_all_grains(neigh_order,
include_parent=True, output_type=’list’)
- B = pxtal.gs[16].get_nth_order_neighbors_all_grains(neigh_order,
recalculate=False, include_parent=True)
- get_upto_nth_order_neighbors_all_grains_prob(neigh_order, recalculate=False, include_parent=False, print_msg=False)[source]
Calculate neighbours for all grains with probabilistic order handling.
- Parameters:
- Returns:
Grain IDs mapped to their selected neighbours.
- Return type:
Examples
from upxo.ggrowth.mcgs import mcgs pxt = mcgs() pxt.simulate() pxt.detect_grains() tslice = 10 fx = pxt.gs[tslice].get_upto_nth_order_neighbors_all_grains_prob neigh0 = fx(1, include_parent=True) neigh0[22]
neigh1 = fx(1.06, include_parent=True) neigh1[2][22]
neigh2 = fx(1.5, include_parent=True) neigh2[2][22]
- add_scalar_field_to_pvgrid(sf_name='lgi', sf_value=None)[source]
Add a scalar field to the PyVista grid.
- Parameters:
sf_name (str, optional) – Default value is “lgi”.
sf_value (None, optional) – Default vlaue is None.
- Return type:
None
- make_zero_non_gids_in_lgi(gids)[source]
Return a copy of
lgimasked to the supplied grain IDs.Paramaters
gids : list
- returns:
masked_lgi – Masked copy of
lgi.- rtype:
np.ndarray
- make_zero_non_gids_in_lgisubset(lgi_subset, gids)[source]
Return a copy of
lgi_subsetmasked to the supplied grain IDs.Paramaters
gids : list
- returns:
masked_lgi – Masked copy of
lgi_subset.- rtype:
np.ndarray
- plot_gs_pvvox(alpha=1.0, title='UPXO.MCGS3D.', cs_labels='user', scalar='lgi', _xname_='Z: lgi[:,:,n]', _yname_='Y: lgi[:,n,:]', _zname_='X: lgi[n,:,:]', show_edges=False)[source]
Plot the grain structure as PyVista voxels.
- Parameters:
Notes
- If cs_labels is not ‘user’:
X on triad will be lgi[n, :, :] – which is z of numpy array Y on triad will be lgi[n, :, :] – which is z of numpy array X on triad will be lgi[n, :, :] – which is z of numpy array
- plot_gs_pvvox_subset(lgi_subset, alpha=1.0, plot_points=False, points=None, isolate_gid=False, gid_to_isolate=None)[source]
Plot a subset of the voxelated grain structure in PyVista.
- Parameters:
lgi_subset (np.ndarray) – Numpy spatial field array.
alpha (float, optional) – Transparency value. Value must be in [0.0, 1.0]. Defaults to 1.0.
plot_points (bool, optional) – Flag to plot additional points on top of the pvgrid. DEfaults to False.
points (np.ndarray, optional) – List of coordinate points to be plotted. Defaults to None.
isolate_gid (bool, optional) – Flag to isolate a specific gid. Defaults to False.
gid_to_isolate (int, optional) – The gid to isolate. Defaults to None.
Examples
- gstslice.plot_gs_pvvox_subset(gstslice.find_exbounding_cube_gid(5),
alpha=0.5)
- gstslice.plot_gs_pvvox_subset(gstslice.find_bounding_cube_gid(5),
alpha=0.5, isolate_gid=True, gid=5)
- find_grain_voxel_locs_v1(gids=None, disp_msg=False, verbosity=100, saa=True, throw=False, dtype=numpy.int32, use_uint16=True)[source]
Find voxel locations of grains in
self.lgiand store them.
- find_feat_voxel_locs_v1(feature_name='base', instance_name='lgi', fids=None, disp_msg=False, verbosity=100, saa=True, throw=False, use_uint16=True)[source]
Find voxel locations of features in a labelled 3D array.
Examples
gstslice.find_feat_voxel_locs_v1(feature_name='base', instance_name='lgi', fids=None, disp_msg=False, verbosity=100, saa=True, throw=False) feat_locs = gstslice.find_feat_voxel_locs_v1(feature_name='twin', instance_name='twin.0', fids=None, disp_msg=False, verbosity=100, throw=True) feature_name, instance_name = 'twin', 'twin.0' feat_ids = gstslice.fdb[instance_name]['data']['twin_id'][:2] feat_locs = gstslice.find_feat_voxel_locs_v1(feature_name=feature_name, instance_name=instance_name, fids=feat_ids, disp_msg=False, verbosity=100, throw=True)
- find_grain_voxel_locs(disp_msg=False, verbosity=100, saa=True, throw=False)[source]
Find voxel locations of grains in
self.lgi.- Parameters:
- Returns:
Grain-ID to voxel-coordinate mapping when
throwis True; otherwiseNone.- Return type:
dict or None
- find_feature_voxel_locs(fname='lgi', fids=None, printmsg=True, verbosity=10, saa=True, throw=False)[source]
Find voxel locations for the requested feature IDs.
- Parameters:
fname (str, optional) – Feature-field name.
fids (iterable or None, optional) – Feature IDs to sample.
printmsg (bool, optional) – Print progress messages when True.
verbosity (int, optional) – Progress-print interval.
saa (bool, optional) – Store the result on the instance when True.
throw (bool, optional) – Return the computed mapping when True.
- Returns:
Feature-ID to voxel-coordinate mapping when
throwis True; otherwiseNone.- Return type:
dict or None
- find_spatial_bounds_of_grains()[source]
Find the spatial bounds of each grain in the grain structure.
- Parameters:
None
- Return type:
None
Notes
- self.spbounddict
- Keys and values are explained below:
- xminsnp.ndarray
Numpy array of minimum tight bound value of every grain along x.
- yminsnp.ndarray
Numpy array of minimum tight bound value of every grain along y.
- zminsnp.ndarray
Numpy array of minimum tight bound value of every grain along z.
- xmaxsnp.ndarray
Numpy array of maximum tight bound value of every grain along x.
- ymaxsnp.ndarray
Numpy array of maximum tight bound value of every grain along y.
- zmaxsnp.ndarray
Numpy array of maximum tight bound value of every grain along z.
- self.spboundexdict
- Keys and values are explained below:
- xminsnp.ndarray
Numpy array of minimum loose bound value of every grain along x.
- yminsnp.ndarray
Numpy array of minimum loose bound value of every grain along y.
- zminsnp.ndarray
Numpy array of minimum loose bound value of every grain along z.
- xmaxsnp.ndarray
Numpy array of maximum loose bound value of every grain along x.
- ymaxsnp.ndarray
Numpy array of maximum loose bound value of every grain along y.
- zmaxsnp.ndarray
Numpy array of maximum loose bound value of every grain along z.
self.spbound provides tight bounds for every grain.
self.spboundex provides loose bounds for every grain, where the bounds are extended in each direction by a unit voxel. In case of border grains, self.spboundex values along the corresponding directions will not be extended.
- find_bounding_cube_gid(gid)[source]
Find the subset of lgi which tight binds grain gid.
- Parameters:
gid (int) – Grain ID.
- Returns:
lgisubset_tightbound
- Return type:
np.ndarray
- find_exbounding_cube_gid(gid)[source]
Find the subset of lgi which loose binds grain gid by a voxel in each of the 3 axes.
- Parameters:
gid (int) – Grain ID.
- Returns:
Loose bounding cube for the requested grain.
- Return type:
np.ndarray
- set_gbpoints_global_point_cloud(points=numpy.array)[source]
Set Pyvista PolyData with global grain boundary points.
- Parameters:
points (np.ndarray, optional) – Numpy array of coordinate points. Defaults to value np.array([-1, -1, -1]).
attribute (Save as)
-----------------
self.pointclouds_pv['gbp_global']
- Return type:
None
- plot_gbpoint_cloud_global()[source]
Plot all the grain boundary points clouds.
- Parameters:
None
attribute (Save as)
-----------------
None
visualized (Variables)
--------------------
self.pointclouds_pv['gbp_global']
- Return type:
None
- validate_scalar_field_name(sf_name)[source]
Validate whether
sf_nameis a supported scalar field name.- Parameters:
sf_name (str) – Scalar field name to validate.
attribute (Save as)
-----------------
None
- Return type:
None
Notes
This definition is mainly for internal use.
- get_scalar_field(sf_name='lgi', sf_details={'include_parent': False, 'name': 'nneigh.1', 'norder': 1.5, 'val': {1: None, 2: None}, 'valby': 'build'}, make_pvgrid=False)[source]
Return the requested scalar field.
- Parameters:
- Returns:
Dictionary containing the scalar field and optional grid.
- Return type:
Examples
from upxo.ggrowth.mcgs import mcgs pxt = mcgs() pxt.simulate() pxt.detect_grains() tslice = 49 gstslice = pxt.gs[tslice] sf = gstslice.get_scalar_field( sf_name='neigh', sf_details={'name': 'nneigh.1', 'valby': 'build', 'norder': 1.5, 'include_parent': False, 'subfield': 'nneigh'}, make_pvgrid=True, )
- get_neigh_gid_subfield(neigh_gid, subfield='nneigh')[source]
Extract a neighbour-derived subfield from a neighbour-ID mapping.
- Parameters:
- Returns:
Requested neighbour-derived values keyed by grain ID.
- Return type:
Examples
def_neigh = gstslice.get_upto_nth_order_neighbors_all_grains_prob neigh_gid = def_neigh(1.0, recalculate=False, include_parent=True) nneigh = gstslice.get_neigh_gid_subfield(neigh_gid, subfield='nneigh') nneigh_vf = gstslice.get_neigh_gid_subfield(neigh_gid, subfield='vf') sf_no = gstslice.map_scalar_to_lgi(nneigh_vf, default_scalar=-1, make_pvgrid=True) sf_no['pvgrid'].plot()
- map_scalar_to_lgi(scalars_dict, default_scalar=-1, scalar_name='nneigh.no1.5', saa=False, throw=True, make_pvgrid=False)[source]
Map scalar values onto the grain-label image.
- Parameters:
scalars_dict (dict) – Mapping from grain ID to scalar value.
default_scalar (float, optional) – Value assigned to grains not present in
scalars_dict.scalar_name (str, optional) – Name used when storing the mapped scalar field.
saa (bool, optional) – Store the mapped field on the instance when True.
throw (bool, optional) – Return the mapped field dictionary when True.
make_pvgrid (bool, optional) – Build a PyVista grid when True.
- Returns:
Scalar-field dictionary when
throwis True; otherwiseNone.- Return type:
dict or None
- get_scalar_field_slice(sf_name='lgi', slice_normal='x', slice_location=0, interpolation='nearest')[source]
Get scalar field values along the specified slice.
- Parameters:
- Returns:
sf_slice – Scalar field values in the slice.
- Return type:
np.ndarray
- plot_scalar_field_slice_orthogonal(sf_name='lgi', x=5.0, y=5.0, z=5.0)[source]
Plot the scalar field along three fundamental orthogonal planes.
- Parameters:
sf_name (str, optional) – Valid name of the scalar field. Defaults to ‘lgi’.
x (float, optional) – X-coord of the origin of three orthogonal slices. Defaults to 5.
y (float, optional) – Y-coord of the origin of three orthogonal slices. Defaults to 5.
z (float, optional) – Z-coord of the origin of three orthogonal slices. Defaults to 5.
- Return type:
None
- plot_scalar_field_slice(sf_name='lgi', slice_normal='x', slice_location=0, interpolation='nearest', vmin=1, vmax=None)[source]
Plot the scalar field along the specified slice plane.
- Parameters:
sf_name (str, optional) – Name of the scalar field. Defaults to ‘lgi’.
slice_normal (str or dth.dt.ITRERABLE, optional) – Either ‘x’, ‘y’ or ‘z’. Defaults to ‘x’.
slice_location (float, optional) – Defaults to 0.
interpolation (str, optional) – Defaults to ‘nearest’.
vmin (int, optional) – Defalts to 1.
vmax (int or None, optional) – Defalts to None.
- Returns:
ax – Matplotlib axis object.
- Return type:
- plot_scalar_field_slices(sf_name='lgi', slice_normal='x', slice_location=0, interpolation='nearest', vmin=1, vmax=None, slice_start=0, slice_end=9, slice_incr=1, nrows=2, ncols=5, ax=None)[source]
Plot the scalar field along multiple parallel slice planes.
- Parameters:
sf_name (str, optional) – Name of the scalar field. Defaults to ‘lgi’.
slice_normal (str or dth.dt.ITRERABLE, optional) – Either ‘x’, ‘y’ or ‘z’. Defaults to ‘x’.
slice_location (float, optional) – Defaults to 0.
interpolation (str, optional) – Defaults to ‘nearest’.
vmin (int, optional) – Defalts to 1.
vmax (int or None, optional) – Defalts to None.
slice_start (int, optional) – Specify the starting location of the slice plane. Defalts to 0.
slice_end (int, optional) – Specify the ending location of the slice plane. Defalts to 9.
slice_incr (int, optional) – Specify the constant incrementation distances of the subsequent slice plane. Defalts to 1.
nrows (int, optional) – Number of subplot rows needed in the Matplotlib figure window. Defalts to 2.
ncols (int, optional) – Number of subplot columns needed in the Matplotlib figure window. Defalts to 5.
ax (Matplotlib axis object, optional) – Matplotlib axis object to plot over. Defalts to None.
- Returns:
ax (object) – Matplotlib axis object.
Explanations
————
* 1.
* 2.
Example-1
———
- merge_two_neigh_grains(parent_gid, other_gid, check_for_neigh=True, simple_merge=True)[source]
Merge one neighbouring grain into another.
- Parameters:
parent_gid (int) – Grain ID of the parent.
other_gid (int) – Grain ID of the other grain being merged into the parent.
check_for_neigh (bool, optional) – If True, other_gid will be checked if it can be merged to the parent grain. Defaults to True.
simple_merge (bool, optional) – If True, perform a direct merge; otherwise keep the hook for a more complex merge path.
- Returns:
True when the merge succeeds.
- Return type:
- perform_post_grain_merge_ops(merged_gid)[source]
Perform follow-up updates after a grain merge.
- Parameters:
merged_gid (int) – Grain ID that has just been merged.
done (Operations)
---------------
renumbered (The following variables are) –
lgi
recalulated (The following variables / databases are) –
self.gid
self.n
neighbouring gid database
- renumber_gid_post_grain_merge(merged_gid)[source]
Renumber grain IDs after a merge.
- Parameters:
merged_gid (int) – Grain ID that has been merged.
- Return type:
None
- recalculate_ngrains_post_grain_merge()[source]
Recalculate the grain count after a merge.
- Return type:
None
- renumber_lgi_post_grain_merge(merged_gid)[source]
Renumber
lgiafter a merge.- Parameters:
merged_gid (int) – Grain ID that has been merged.
- Return type:
None
- plot_largest_grain()[source]
A humble method to just plot the largest grain in a temporal slice of a grain structure
- Parameters:
None
- Returns:
None.
# TODO (WRAP THIS INSIDE A FIND_LARGEST_GRAIN AND HAVE IT TRHOW)
THE GID TO THE USER
- mask_s_with_gids(gids, masker=-10, force_masker=False)[source]
Mask
sagainst the supplied grain IDs.- Parameters:
- Returns:
Masked
sarray and the masker value used.- Return type:
- plot_grains(gids, scalar='lgi', cmap='viridis', style='surface', show_edges=True, lw=1.0, opacity=0.8, view=None, scalar_bar_args=None, plot_coords=False, coords=None, axis_labels=['z', 'y', 'x'], explode=0.0, pvp=None, throw=False)[source]
Plot one or more grains.
- Parameters:
gids (int or iterable) – Grain ID number(s).
scalar (np.array or valid string, optional) – Defaults to ‘lgi’.
cmap (str, optional) – Defaults to ‘viridis’.
style (str, optional) – Options for style: ‘surface’, ‘wireframe’, ‘points’ and ‘points_gaussian’ Defaults to ‘surface’.
show_edges (bool, optional) – Defaults to True.
lw (float, optional) – Line width. Defaults to 1.0.
opacity (float on/in [0.0, 1.0], optional) –
- Options for opacity include foollowing:
int between 0 and 1
- Opacity transfer functions: ‘linear’, ‘linear_r’, ‘geom’,
’geom_r’, ‘sigmoid’, ‘sigmoid_r’
- Custom transfewr function: list of values between 0 and 1,
example: opacity = [0, 0.2, 0.9, 0.6, 0.3]. In ythis case, these values will be linearly mapped to the scalr being plotted.
Defaults to 1.0.
view (str / None, optional) – To be implemented. Defaults to None.
scalar_bar_args (dict, optional) – To be implemented. Defaults to None.
plot_coords (bool, optional) – Plot additional coordinate points. Defaults to False.
coords (np.ndarray/None, optional) – Numpy array of coordinate points. Defaults to None.
axis_labels (list, optional) – Label strings for x, y and z - axis labels. Defaults to [‘z’, ‘y’, ‘x’].
pvp (PyVista plotter object / None, optional) – PyVista plotter object to plot over. Defaults to None.
throw (bool, optional) – If True, pv.Plotter() instance shall be returned without actually plotting visually. Defaults to False.
Examples
gids = gstslice.gpos['boundary'] - gstslice.gpos['face']['top'] gstslice.plot_grains(gids, scalar='lgi', cmap='viridis', style='surface', show_edges=True, lw=1.0, opacity=1, view=None, scalar_bar_args=None, axis_labels=['001', '010', '100'], throw=False)
- viz_browse_grains(scalar='lgi', cmap='viridis', style='surface', show_edges=True, lw=1.0, opacity=0.8, view=None, scalar_bar_args=None, plot_coords=False, name='UPXO.MCGS.3D', coords=None, axis_labels=['z', 'y', 'x'], title='Grain ID', add_outline=False, pvp=None, throw=False)[source]
Browse grains in the grain structure using a slider.
- Parameters:
gids (int or iterable) – Grain ID number(s).
scalar (np.array or valid string, optional) – Defaults to ‘lgi’.
cmap (str, optional) – Defaults to ‘viridis’.
style (str, optional) – Options for style: ‘surface’, ‘wireframe’, ‘points’ and ‘points_gaussian’ Defaults to ‘surface’.
show_edges (bool, optional) – Defaults to True.
lw (float, optional) – Line width. Defaults to 1.0.
opacity (float on/in [0.0, 1.0], optional) –
- Options for opacity include foollowing:
int between 0 and 1
- Opacity transfer functions: ‘linear’, ‘linear_r’, ‘geom’,
’geom_r’, ‘sigmoid’, ‘sigmoid_r’
- Custom transfewr function: list of values between 0 and 1,
example: opacity = [0, 0.2, 0.9, 0.6, 0.3]. In ythis case, these values will be linearly mapped to the scalr being plotted.
Defaults to 1.0.
view (str / None, optional) – To be implemented. Defaults to None.
scalar_bar_args (dict, optional) – To be implemented. Defaults to None.
plot_coords (bool, optional) – Plot additional coordinate points. Defaults to False.
coords (np.ndarray / None, optional) – Numpy array of coordinate points. Defaults to None.
axis_labels (list, optional) – Label strings for x, y and z - axis labels. Defaults to [‘z’, ‘y’, ‘x’].
title (str) – Defaults to ‘Grain ID’.
add_outline (bool) – Defaults to False.
pvp (PyVista plotter object / None, optional) – PyVista plotter object to plot over. Defaults to None.
throw (bool, optional) – If True, pv.Plotter() instance shall be returned without actually plotting visually. Defaults to False.
- viz_clip_plane(normal='x', origin=[5.0, 5.0, 5.0], scalar='lgi', cmap='viridis', invert=True, crinkle=True, normal_rotation=True, add_outline=False, throw=False, pvp=None)[source]
Visualize the grain structure along a clip plane.
- Parameters:
normal (str or dth.dt.ITERABLE(float), optional) – Normal specification of clipping plane. Default value is ‘x’.
origin (dth.dt.ITERABLE(float), optional) – Specification of origin, that is clip plane centre coordinate.
scalar (str, optional) – self.pvgrid cell_data scalar specification. Default value is ‘lgi’.
cmap (str, optional) –
Colour map specification. Default value is ‘viridis’. Recommended values:
viridis
nipy_spectral
invert (bool, optional) – Invert clip sense if True, dont if False. Default value is True.
crinkle (bool, optional) – Crinkle view voxels if True, section view if False. Default value is True.
normal_rotation (bool, optional) – Rotation specification of normal. Default value is True. NOTE: To be implemented completely.
add_outline (bool, optional) – Add an outline around the grain structure. Default value is False.
throw (bool, optional) – Throw the pvp if True, dont if False. Default value is False.
pvp (bool, optional) – PyVista plotter object to plot over. If no pvp has been provided, new pvp shall be created. Default value is None.
Examples
gstslice.viz_clip_plane(normal='x', origin=[5.0, 5.0, 5.0], scalar='lgi', cmap='viridis', invert=True, crinkle=True, normal_rotation=True, add_outline=False, throw=False)
- viz_mesh_slice(normal='x', origin=[5.0, 5.0, 5.0], scalar='lgi', cmap='viridis', normal_rotation=True, add_outline=False, throw=False, pvp=None)[source]
Visualize the grain structure along a slice plane.
- Parameters:
normal (str or dth.dt.ITERABLE(float), optional) – Normal specification of clipping plane. Default value is ‘x’.
origin (dth.dt.ITERABLE(float), optional) – Specification of origin, that is clip plane centre coordinate.
scalar (str, optional) – self.pvgrid cell_data scalar specification. Default value is ‘lgi’.
cmap (str, optional) –
Colour map specification. Default value is ‘viridis’. Recommended values:
viridis
nipy_spectral
add_outline (bool, optional) – Add an outline around the grain structure. Default value is False.
throw (bool, optional) – Throw the pvp if True, dont if False. Default value is False.
pvp (bool, optional) – PyVista plotter object to plot over. If no pvp has been provided, new pvp shall be created. Default value is None.
Examples
gstslice.viz_mesh_slice(normal='x', origin=[5.0, 5.0, 5.0], scalar='lgi', cmap='viridis', add_outline=False, throw=False)
- viz_mesh_slice_ortho(scalar='lgi', cmap='viridis', style='surface', add_outline=False, throw=False, pvp=None)[source]
Visualize the grain structure along three orthogonal planes.
- Parameters:
scalar (str, optional) – self.pvgrid cell_data scalar specification. Default value is ‘lgi’.
cmap (str, optional) –
Colour map specification. Default value is ‘viridis’. Recommended values:
viridis
nipy_spectral
add_outline (bool, optional) – Add an outline around the grain structure. Default value is False.
throw (bool, optional) – Throw the pvp if True, dont if False. Default value is False.
pvp (bool, optional) – PyVista plotter object to plot over. If no pvp has been provided, new pvp shall be created. Default value is None.
Examples
gstslice.viz_mesh_slice_ortho(scalar='lgi', cmap='viridis', style='surface', add_outline=False, throw=False)
- plot_grain_sets(data=None, scalar='lgi', opacities=[1.0, 0.9, 0.75, 0.5], pvp=None, cmap='viridis', style='surface', show_edges=True, lw=1.0, plot_coords=False, coords=None, core_grains_opacity=1, opacity=1, view=None, scalar_bar_args=None, axis_labels=['001', '010', '100'], throw=False, validate_data=True)[source]
Plot multiple prominent and non-prominent grain sets.
- Parameters:
data (dict, optional) –
- keys: str
- ’cores’: list of ints
List of most prominant gids.
- ’other’: list of list
Fi4rst lisyt - gids with next lesser prominance level than thosse in ‘core’. Second list - gids with next lesser prominance level than thse in first list.
opacities (list, optional) –
- First value is alpha of most prominant grains. Could represent
alpha of core grains.
- Second value is alpha of grains with the next prominance level.
Could represent alpha of every 1st order neighbours.
Third value, fourth value and so on. Defaults to [1.00, 0.90, 0.75, 0.50]
pvp (bool, optional) – PyVista plotter object to plot over. If no pvp has been provided, new pvp shall be created. Default value is None.
cmap (str, optional) –
Colour map specification. Default value is ‘viridis’. Recommended values:
viridis
nipy_spectral
style (str, optional) – Options for style: ‘surface’, ‘wireframe’, ‘points’ and ‘points_gaussian’ Defaults to ‘surface’.
show_edges (bool, optional) – Defaults to True.
lw (float, optional) – Line width. Defaults to 1.0.
plot_coords (bool, optional) – Plot additional coordinate points. Defaults to False.
coords (np.ndarray or None, optional) – Numpy array of coordinate points. Defaults to None.
core_grains_opacity (float, optional)
you (Specify opacity of core grains. Use this to visualize cases where)
Defaults (need to visualize a group of grains surrounding core grain(s).)
1.0. (to)
opacity (float, optional)
1 (. Defaults to)
view (type, optional) – Viz. view specification. Defaults to None.
scalar_bar_args (type, optional) – To be implemented. Defaults to None.
axis_labels (list, optional) – Coordinate axes label string specification. Defaults to [‘001’, ‘010’, ‘100’].
throw (bool, optional) – Return plotter object if True, dont if False. Defaults to False.
validate_data (bool, optional) – Initially validate user inputs if True, skip if False. Defaults to True.
Examples
data = {'cores': [1, 2, 3, 4], 'others': [[7, 6, 5], [12, 8, 10, 11]]}
- find_scalar_array_in_plane(origin=[5.0, 5.0, 5.0], normal=[1.0, 1.0, 1.0], scalar='lgi')[source]
Get the scalar values array in a plane.
- get_scalar_array_in_plane_unique(origin=[5.0, 5.0, 5.0], normal=[1.0, 1.0, 1.0])[source]
Find unique gids in a plane defined by origin and normal.
- Parameters:
- Returns:
Unique scalar values sampled from the plane.
- Return type:
np.ndarray
Examples
gstslice.find_scalar_array_in_plane(origin=[5, 4, 3], normal=[1, 2, 1], scalar='lgi')
- plot_gids_along_plane(origin=[5.0, 5.0, 5.0], normal=[1.0, 1.0, 1.0], cmap='viridis', style='surface', show_edges=True, lw=1.0, opacity=0.8, view=None, scalar_bar_args=None, plot_coords=False, coords=None, axis_labels=['z', 'y', 'x'], pvp=None, throw=False)[source]
Plot grains which fall alomng a plane.
- Parameters:
origin (list) – Define the origin of the slicing plane as [i, j, k].
normal (list) – Define the normal vector of the slicing plane as [u, v, w].
cmap (str, optional) – Defaults to ‘viridis’.
style (str, optional) – Options for style: ‘surface’, ‘wireframe’, ‘points’ and ‘points_gaussian’ Defaults to ‘surface’.
show_edges (bool, optional) – Defaults to True.
lw (float, optional) – Line width. Defaults to 1.0.
opacity (float on/in [0.0, 1.0], optional) –
- Options for opacity include foollowing:
int between 0 and 1
- Opacity transfer functions: ‘linear’, ‘linear_r’, ‘geom’,
’geom_r’, ‘sigmoid’, ‘sigmoid_r’
- Custom transfewr function: list of values between 0 and 1,
example: opacity = [0, 0.2, 0.9, 0.6, 0.3]. In ythis case, these values will be linearly mapped to the scalr being plotted.
Defaults to 1.0.
view (str / None, optional) – To be implemented. Defaults to None.
scalar_bar_args (dict, optional) – To be implemented. Defaults to None.
plot_coords (bool, optional) – Plot additional coordinate points. Defaults to False.
coords (np.ndarray / None, optional) – Numpy array of coordinate points. Defaults to None.
axis_labels (list, optional) – Label strings for x, y and z - axis labels. Defaults to [‘z’, ‘y’, ‘x’].
title (str) – Defaults to ‘Grain ID’.
add_outline (bool) – Defaults to False.
pvp (PyVista plotter object / None, optional) – PyVista plotter object to plot over. Defaults to None.
throw (bool, optional) – If True, pv.Plotter() instance shall be returned without actually plotting visually. Defaults to False.
Example
- gstslice.plot_gids_along_plane(origin=[5, 5, 5], normal=[1, 0, 0],
cmap=’viridis’, style=’surface’, show_edges=True, lw=1.0, opacity=1.0, view=None, scalar_bar_args=None, plot_coords=False, coords=None, axis_labels=[‘z’, ‘y’, ‘x’], pvp=None, throw=False)
Longer example-1
‘’’Find the grain IDs first.’’’ gids = gstslice.get_scalar_array_in_plane_unique(origin=[25, 25, 25],
normal=[1, 1, 1])
# …. …. …. …. …. # NOTE: We can go through any one of the folloiwnwg routes.
‘’’Route 1: plot all these gids’’’ gids = gids ‘’’Route 2: Exclude boundary grains.’’’ gids = set(gids) - gstslice.gpos[‘boundary’] ‘’’Route 3: Consider only boundary grains.’’’ gids = set(gids).intersection(gstslice.gpos[‘boundary’]) # …. …. …. …. …. ‘’’Now, the actual plotting procesure.’’’ gstslice.plot_grains(gids, scalar=’lgi’,cmap=’viridis’,style=’surface’,
show_edges=True, lw=1.0, opacity=1.0, view=None, scalar_bar_args=None, plot_coords=False, coords=None, axis_labels=[‘z’, ‘y’, ‘x’], pvp=None, throw=False)
Longer example-2
- gids1 = gstslice.get_scalar_array_in_plane_unique(origin=[25, 25, 25],
normal=[1, 1, 1])
- gids2 = gstslice.get_scalar_array_in_plane_unique(origin=[25, 25, 25],
normal=[1, -1, 1])
- gids3 = gstslice.get_scalar_array_in_plane_unique(origin=[25, 25, 25],
normal=[1, -1, -1])
gids = set(gids1).union(gids2, gids3) gids = set(gids1).intersection(gids2, gids3) gids = set(gids1).union(gids2, gids3) - set(gids1).intersection(gids2,
gids3)
gids = set(gids1).union(gids2, gids3) gids = gids.intersection(gstslice.gpos[‘boundary’])
- gstslice.plot_grains(gids, scalar=’lgi’,cmap=’viridis’,style=’surface’,
show_edges=True, lw=1.0, opacity=1.0, view=None, scalar_bar_args=None, plot_coords=False, coords=None, axis_labels=[‘z’, ‘y’, ‘x’], pvp=None, throw=False)
- get_voxel_surfareas(ret_metric='mean')[source]
Return voxel surface area from the PyVista grid spacing.
- Parameters:
ret_metric (str, optional) – Metric to return:
'mean','min','max'or'all'.
- set_mprop_eqdia(base_size_spec='ignore', use_skimrp=True, reset_skimrp=True, measure='normal')[source]
Calculate equivalent sphere diameter for each grain.
- Parameters:
base_size_spec (str, optional) –
Base size specification used to calculate equivalent sphere diameter. Allows to use either volume or surface area. Options are:
’volnv’: Volume by number of voxels
’volsr’: Volume by surface reconstruction
’volch’: Volume of convex hull
’sanv’: surface ares by number of voxels
’savi’: surface area by voxel interfaces
’sasr’: surface area by surface reconstruction
In case of ‘volnv’, volume is scaled by unit voxel volume before calculation of equivalent sphere diameter. In case of ‘sanv’, volume is scaled by mean unit voxel face area before calculation of equivalent sphere diameter. Defaults to ‘volnv’.
use_skimrp (bool, optional) – Use scikit-image regionprops values when available.
reset_skimrp (bool, optional) – Recompute cached regionprops values before measuring.
measure (str, optional) – Regionprop-based metric to use when
use_skimrpis True.('volnv' (If base_size_spec in)
'volsr'
'volch')
following (then the)
diameter. (procedure is used to calculate the equivakent)
pi)) (d = 0.5*sqrt(S/(4)
pi))
measure. (where S is the surface area)
('sanv' (If base_size_spec in)
'savi'
'sasr')
following
diameter.
pi))
pi))
measure.
- set_mprop_solidity(reset_generators=True, nan_treatment='replace', inf_treatment='replace', nan_replacement=-1, inf_replacement=-1)[source]
Set the solidity morphological property for all grains.
- Parameters:
reset_generators (bool, optional) – Reset the scikit image generator if True, else False. Defaults to True.
nan_treatment (str, optional) –
- Options include the following:
’replace’
’remove’
Defaults to ‘replace’.
inf_treatment (str, optional) –
- Options include the following:
’replace’
’remove’
Defaults to ‘replace’.
nan_replacement (int, optional) – Value to replace nan with if nan_treatment is ‘replace’. Defaults to -1.
inf_replacement (int, optional) – Value to replace inf with if inf_treatment is ‘replace’. Defaults to -1.
- set_mprop_arbbox(fmt='gid_dict', normalize=True)[source]
Calculate the bounding-box aspect ratio for each grain.
- Parameters:
fmt (str, optional) –
Output format for the stored values.
Defaults to ‘gid_dict’ for which ar values of each boundring box will be stored against the corresponding gid valued keys in a dictionary. In this case, self.mprop[‘arbbox’] will be a dictionary. Other option is ‘np’, for numpy.
In case of ‘np’, a 2D numpy array of aspect ratio values of each gid’s bounding box will be stored. In the case of ‘np’ option however the user will have take note that indexing would have to be added by 1 to match with gid numbering.
normalize (bool, optional) – Normalize box dimensions before computing the aspect ratio.
- fit_ellipsoids(routine=1, regularize_data=False, verbosity=50)[source]
Fit ellipsoids to all grains in the grain structure.
- Parameters:
routine (int, optional) – Specify which routine to use to fit ellipsoids to grains. The default is 1.
regularize_data (bool, optional) – Option to remove outlying grain boundary surface points from the point cloud data before ellipoidal fitting. The default is False Note 1: It is recommended that regularize_data be set to False. The reason for this is, grain boundary surface points are not some random point distribution in space, but rather define the very shape of the grain. Note 2: Applicable for routine 1.
attributes (Saved as)
-------------------
ellfits (dict) – Ellipsoid-fit results keyed by
center,evecs,radii,v, andunfit_gid.
- Return type:
None
Notes
Routine 1 uses the external
ellipsoid_fit_pythonimplementation. The fit dictionary keys are based on that implementation and the linked MATLAB reference.
- set_mprop_arellfit(metric='max', calculate_efits=False, efit_routine=1, efit_regularize_data=True)[source]
Calculate aspect ratio from ellipsoidal fits.
- Parameters:
metric (str, optional) –
Specify which metric to use for aspect ratio calculation. Options include:
max / maximum / maximal
min / minimum / minimal
xy / yx / z
yz / zy / x
xz / yz / y
calculate_efits (bool, optional) – Fit ellipsoids before computing the aspect ratio.
efit_routine (int, optional) – Routine to use when fitting ellipsoids.
efit_regularize_data (bool, optional) – Regularize point clouds before fitting ellipsoids.
attributes (Saved as)
-------------------
self.mprop['arellfit']
- generate_bresenham_line_3d(i1, i2, i3, j1, j2, j3)[source]
Generate a Bresenham line in 3D between two coordinate locations.
- Parameters:
i1 (int) – Plane index location of 1st point in 3D array.
i2 (int) – Row index location of 1st point in 3D array.
i3 (int) – Column index location of 1st point in 3D array.
j1 (int) – Plane index location of 2nd point in 3D array.
j2 (int) – Row index location of 2nd point in 3D array.
j3 (int) – Column index location of 2nd point in 3D array.
- Returns:
Index locations of the points on the line.
- Return type:
References
- Codes in this function is taken verbatim from ther below link:
https://www.geeksforgeeks.org/bresenhams-algorithm-for-3-d-line-drawing/
Notes
This helper is used to sample values along a line.
- get_values_along_line(loci, locj, scalars='lgi')[source]
Get values in the 3D array along the line between two locations.
- get_igs_properties_along_line(loci, locj, scalars='lgi')[source]
Measure intercept properties along a line between two locations.
- get_igs_along_line(loci, locj, metric='mean', minimum=True, maximum=True, std=True, variance=True, verbose=True)[source]
Measure intercept properties along the line between two locations.
- Parameters:
loci (list) – First location in the 3D array.
locj (list) – Second location in the 3D array.
metric (str, optional) –
- User specification of metric. Options include the following:
mean / average / avg
median
minimum (bool, optional) – Flag to return minimum. Return minimum when True. Default value is True.
maximum (bool, optional) – Flag to return maximum. Return maximum when True. Default is True.
std (bool, optional) – Flag to return standard deviation. Return standard deviation when True. Default value is True.
variance (bool, optional) – Flag to return variance. Return variance when True. Default is True.
- Returns:
Intercept grain-size statistics for the sampled line.
- Return type:
- get_opposing_points_on_gs_bound_planes(plane='z', start_skip1=0, start_skip2=0, incr1=2, incr2=2, inclination='none', inclination_extent=0, shift_seperately=False, shift_starts=False, shift_ends=True, start_shift=0, end_shift=0)[source]
Get points on the opposing boundaries of the grain structure.
- Parameters:
plane (str) – Specify which boundary of grain structure to generate points on. If ‘x’, opposing points will be generated on the two opposing yz planes.
start_skip1 (int) – Starting indices to skip on dimention 1. Defaults to 0.
start_skip2 (int) – Starting indices to skip on dimention 2. Defaults to 1.
incr1 (int) – Increments to be used on indices locatios in dimension 1. Defaults to 2.
incr2 (int) – Increments to be used on indices locatios in dimension 1. Defaults to 2.
inclination (str) –
Inclination specificaiton for line formed by coordinate pairs start_points – end_points. Options include the following:
- ’none’: no inclination.
Lines from coordinate pairs will be normal to user’s plane specification.
- ’constant’.
Most lines from coordinate pairs will have the same inclnation. Lines formed by starting and ending points falling on opposite sides of the grain striucture bounds will have an opposite inclination. Lengths of these lines will differ. LInes would have different inclinations. End points will be shifted to achive inclination. Refer to explanations of parameter inclination_extent for details.
- ’random’.
Lines have different length and inclinations. The minimum length will be the length of the normal between the two planes belongijg to the user’s plane specification.
inclination_extent (int) –
Applies if inclination is True. Control the extent of inclination. Interpretation is tricky. The actual inclination is periodic with extent with a period defined by the number of points along a particular dimension.
For example if plane is ‘z’, then dimension 1 is for y (row) and dimension 2 (co9lumn) is for x. The definition employs np.roll, on the stacked coordinates. As a consequence, the actual inclination becomes periodic with perdiod as the number of points along x. When y is 0, inclination is in plane x-z. At y>0, the line starts to incline away from x-z plane and the line ori itself befomes 3D in the x-y-z coordinate system. Defaults to 0. Can be negative or positive. A value of 0 would mean equivivalence with inclination specification set to ‘none’. A positive value implies points shifted clockwise and negative otherwise.
shift_seperately (bool) – If inclination is True, inclination_extent is not equal to 0, if shift_seperately is True, then start_points are forward shifted and end_pointse backward shifted. Defaults to False.
shift_starts (bool) – Applies if shift_seperately is True. If True, starting points will be shifted by a value specified by start_shift. Defaults to False.
shift_ends (bool) – Applies if shift_seperately is True. If True, ending points will be shifted by a value specified by end_shift. Defaults to True.
start_shift (bool) – Applied if shift_starts is True. Explanations same as that for inclination_extent, with respect to starting point.
end_shift (bool) – Applied if shift_starts is True. Explanations same as that for inclination_extent, with respect to ending point.
Notes
Please refer to the inline comments in this function.
- get_igs_along_lines(metric='mean', minimum=True, maximum=True, std=True, variance=True, lines_gen_method=1, lines_kwargs1={'end_shift': 0, 'inclination': 'none', 'inclination_extent': 0, 'incr1': 0, 'incr2': 0, 'plane': 'z', 'shift_ends': False, 'shift_seperately': False, 'shift_starts': False, 'start_shift': 0, 'start_skip1': 0, 'start_skip2': 0})[source]
Measure intercept properties along lines defined by location sets i, j.
- Parameters:
metric (str, optional) –
- User specification of metric. Options include the following:
mean / average / avg
median
minimum (bool, optional) – Flag to return minimum. Return minimum when True. Default value is True.
maximum (bool, optional) – Flag to return maximum. Return maximum when True. Default is True.
std (bool, optional) – Flag to return standard deviation. Return standard deviation when True. Default value is True.
variance (bool, optional) – Flag to return variance. Return variance when True. Default value is True.
lines_gen_method (int) – Specify the method of generating sampling lines. Defaults to 1.
lines_kwargs1 (dict) –
Applies when lines_gen_method is set to 1. Control parameters for generating sampling lines through the grain structure. Defaults to the followig dictionary. lines_kwargs1={‘plane’: ‘z’, ‘start_skip1’: 0, ‘start_skip2’: 0,
’incr1’: 0, ‘incr2’: 0, ‘inclination’: ‘none’, ‘inclination_extent’: 0, ‘shift_seperately’: False, ‘shift_starts’: False, ‘shift_ends’: False, ‘start_shift’: 0, ‘end_shift’: 0}
See self.get_opposing_points_on_gs_bound_planes function documentaiton for details.
- Returns:
Intercept grain-size statistics across all sampled lines.
- Return type:
Examples
gstslice.get_igs_along_lines(metric='mean', minimum=True, maximum=True, std=True, variance=True)
- get_igs_along_lines_multiple_samples(metric='mean', minimum=True, maximum=True, std=True, variance=True, lines_gen_method=1, lines_kwargs1={'end_shift': 0, 'inclination': 'none', 'inclination_extent': 0, 'incr1': 0, 'incr2': 0, 'plane': 'z', 'shift_ends': False, 'shift_seperately': False, 'shift_starts': False, 'start_shift': 0, 'start_skip1': 0, 'start_skip2': 0}, plot=True)[source]
Return intercept grain-size statistics for multiple samples.
- igs_sed_ratio(metric='mean', lines_gen_method=1, reset_grain_size=True, base_size_spec='volnv', lines_kwargs1={'end_shift': 0, 'inclination': 'none', 'inclination_extent': 0, 'incr1': 3, 'incr2': 3, 'plane': 'z', 'shift_ends': False, 'shift_seperately': False, 'shift_starts': False, 'start_shift': 0, 'start_skip1': 0, 'start_skip2': 0})[source]
Calculate the ratio of intercept grain size to sphere eq. diameter.
- Parameters:
metric (str) – Default value is ‘mean’. Options include ‘mean’ and ‘median’.
lines_gen_method (int) – Default value is 1.
reset_grain_size (bool) – Default value iis True.
base_size_spec (str) – Default value is ‘volnv’.
lines_kwargs1 (dict) –
Default value is provided below. {‘plane’: ‘z’, ‘start_skip1’: 0, ‘start_skip2’: 0,
’incr1’: 3, ‘incr2’: 3, ‘inclination’: ‘none’, ‘inclination_extent’: 0, ‘shift_seperately’: False, ‘shift_starts’: False, ‘shift_ends’: False, ‘start_shift’: 0, ‘end_shift’: 0}
- Returns:
Characteristic average grain-size ratio.
- Return type:
- property nvoxels
Return the per-grain voxel counts.
- property nvoxels_values
Return the stored per-grain voxel counts.
- get_largest_gids()[source]
Validation
maxgs = gstslice.nvoxels_values.max() # Minimum grain size all([gstslice.nvoxels[i]==maxgs for i in gstslice.get_smallest_gids()]) Above returns True. Therefore, works fine.
- get_smallest_gids()[source]
Validation
mings = gstslice.nvoxels_values.min() # Minimum grain size all([gstslice.nvoxels[i]==mings for i in gstslice.get_smallest_gids()]) Above returns True. Therefore, works fine.
- property single_voxel_grains
Return the grain IDs that contain a single voxel.
- property smallest_volume
Return the grain IDs with the smallest volume.
- property largest_volume
Return the grain IDs with the largest volume.
- find_grains_by_mprop_range(prop_name='volnv', low=10, high=15, low_ineq='ge', high_ineq='le')[source]
Find gids of grains by specifying property name and range.
Properties
- prop_name: str
Name of the morphjological property. Dewfaults to ‘volnv’.
- low: int
Lower threshold of the property range. Defaults to 10.
- high: int
Upper threshold of the property range. Defaults to 15.
- low_ineq: str
String denoting inequality for low value. Defaults to ‘ge’.
- high_ineq: str
String denoting inequality for high value. Defaults to ‘le’.
Input options
- Options for prop_name:
volnv, volsr, volch
sanv, savi, sasr
pernv, pervl, pergl
eqdia, arbbox, arellfit
sol, ecc, com, sph, fn, rnd, mi
fdim
- Options for low_ineq:
‘ge’
‘gt’
- Options for low_ineq:
‘le’
‘lt’
Examples
gstslice.nvoxels_values gids = gstslice.find_grains_by_mprop_range(prop_name='volnv', low=10, high=15, low_ineq='ge', high_ineq='le') gstslice.nvoxels_values[gids-1] [gstslice.mprop['volnv'][gid] for gid in gids]
- export_vtk3d(grid: dict, grid_fields: dict, file_path: str, file_name: str, add_suffix: bool = True) None[source]
Export data to .vtk format.
- Parameters:
grid (dict) – The grid dictionary containing the grid points. grid = {“x”: xgr, “y”: ygr, “z”: zgr}
grid_fields (dict) –
The grid fields dictionary containing the grid fields. grid_fields = {“state_matrix”: state_matrix,
”gid_matrix”: gid_matrix}
file_path (str) – The path where the .vtk file will be saved.
file_name (str) – The name of the .vtk file.
add_suffix (bool, optional) – If True, the suffix ‘_upxo’ will be added at the end of the file name. This is advised to enable distinguishing any .vtk files you may create using applications such as Dream3D etc. The default is True.
- Return type:
None.
- get_slice(slice_plane='xy', loc=0, scalar='lgi')[source]
Get a slice along one of the three fundamental planes.
- Parameters:
Examples
scalar = gstslice.get_slice(slice_plane='xy', loc=0, scalar='lgi')
- reset_slice_lgi(scalar_slice, library='scikit-image', kernel_order=2)[source]
Identify and labels grains in a 3D grain structure’s 2D slice.
- Parameters:
library (str, optional) – The library to use for grain identification. If not specified, the function raises a NotImplementedError for ‘upxo’. {‘opencv’, ‘scikit-image’}
kernel_order ({1, 2}, optional) – The pixel connectivity criterion for labeling grains. Use 1 for 4-connectivity and 2 for 8-connectivity. Defaults to 2.
Examples
lgi = gstslice.reset_slice_lgi(scalar_slice, library='scikit-image', kernel_order=4)
- char_slice_gid_psitions(lgi)[source]
Calculate the positions of g4rains in the 2D slice.
- Parameters:
lgi (np.ndarray)
Examples
positions = gstslice.char_slice_gid_psitions(lgi)
- char_lgi_slice_morpho(slice_plane='xy', loc=0, reset_lgi=True, kernel_order=4, mprop_names=['area', 'eqdia', 'fdia', 'perimeter', 'perimeter_crofton', 'solidity'], ignore_border_grains_2d=True)[source]
Characterize morphology of a 2D slice of self.lgi.
NOTE: It may seem like there is no need for an additional grain identification phase needed fotthr 2D slice. However, the unique grain morphologies in the 3D can project to 2D to become disconnected regions but yet having the same grain ID value. This would not reproduce the EBSD sectioning artefact of grains with complex re-entrant (concave) morphologies resulting in both error in estimation of some grain properties anbd also changing the very definition of a 2D grain. The latter could result in erroneous statistocal interpretations. If the user prefers this, they may choose to set reset_grains to False.
Examples
gstslice.char_lgi_slice_morpho(slice_plane='xy', loc=0, reset_lgi=True, kernel_order=4, mprop_names=['area', 'eqdia', 'fdia'], ignore_border_grains_2d=True) gstslice.lgi_slice['mprop']['eqdia'] gstslice.lgi_slice['mprop']['area'] gstslice.lgi_slice['mprop']['fdia']
- sss_rel_morpho(slice_plane='xy', loc=0, reset_lgi=True, reset_generators_3d=True, slice_gschar_kernel_order=4, mprop_names_2d=['eqdia'], mprop_names_3d=['eqdia'], ignore_border_grains_2d=True, ignore_border_grains_3d=True, reset_mprops=False, kwargs_arellfit3={'calculate_efits': False, 'efit_regularize_data': True, 'efit_routine': 1, 'metric': 'max'}, kwargs_solidity={'inf_replacement': -1, 'inf_treatment': 'replace', 'nan_replacement': -1, 'nan_treatment': 'replace'}, kdeplot=False, save_plot3d_grains=True, ave_plot2d_grains=True, save_plot2d_grains=False, figsize=(5, 5), dpi=100)[source]
Carry out surface – sub-surface relationship study.
- Parameters:
slice_plane (str, optional) – Specifyt the parallel plane of interest. Dependinmg on the value of loc, the actual plane will be selected. Default value is ‘xy’.
loc (int, optional) – Location of the plae of interest along direction normal to slice_plane. Default value is 0.
reset_lgi (bool, optional) – Reset the lgi numbering to ensure spatial continuity. Default value is True.
kernel_order (int, optional) – Kernel order or continuity structure to use for grain identification in the slice grain structure. Default value is 4.
mprop_names_2d (list, optional) – Use specification of the morphological property names of 2D slice in UPXO to use for studying surface - sub-surface morphological property relationships. Default value is [‘eqdia’].
mprop_names_3d (list, optional) – Use specification of the morphological property names of 3D MCGS in UPXO to use for studying surface - sub-surface morphological property relationships. Default value is [‘eqdia’].
ignore_border_grains_2d (bool, optional) – Ignore all the border grains in the slice whilst calculat9ion of the morphological properties if True. Defaults to True.
ignore_border_grains_3d (bool, optional) – Ignore all the border grains in the 3D MCGS whilst calculat9ion of the morphological properties if True. Defaults to True.
reset_mprops (bool, optional)
kwargs_arellfit3 (dict, optional)
kwargs_solidity (dict, optional)
kdeplot (bool, optional)
save_plot3d_grains (bool, optional) – Defaults to True.
save_plot2d_grains (bool, optional) – Defaults to True.
- Return type:
None
Notes
None
Notes
User MUST note that ignore_border_grains_2d and ignore_border_grains_3d values must have 1-1 correspondance. That is, if the first value of mprop_names_2d is ‘eqdia’, then so should be of mprop_names_3d. If the second value of mprop_names_2d is ‘aspect_ratio’, then the second value of mprop_names_3d could either be ‘arbbox’ or ‘arellfit’.
Examples
- gstslice.sss_rel_morpho(slice_plane=’xy’, loc=0, reset_lgi=True,
kernel_order=4, mprop_names_2d=[‘eqdia’], mprop_names_3d=[‘eqdia’], ignore_border_grains_2d=True, ignore_border_grains_3d=True)
# DEVELOPMENT # DEALING WITH THE 3D GRAIN STRUCTURE: gids = gstslice.get_scalar_array_in_plane_unique(origin=[12, 12, 12],
normal=[1, 0, 0])
gstslice.set_mprop_eqdia(base_size_spec=’volnv’) # ————————————— # DEALING WITH THE SLICE gstslice.char_lgi_slice_morpho(slice_plane=’yz’, loc=12,
reset_lgi=True, kernel_order=4, mprop_names=[‘eqdia’], ignore_border_grains_2d=False)
gstslice.lgi_slice[‘mprop’][‘eqdia’] # ————————————— plt.figure() sns.histplot(gstslice.mprop[‘eqdia’][‘values’][gids-1],
label=’3D grains: ESD’, kde=True)
- sns.histplot(gstslice.lgi_slice[‘mprop’][‘eqdia’],
label=’Slice of 3D grains: ECD’, kde=True)
plt.legend() plt.show() # ————————————— # ————————————— This is to be moved to a different docuemntation
gstslice.set_mprop_eqdia(base_size_spec=’volnv’) gids_all = np.array(gstslice.gid) gids_internal = np.array(list(gstslice.gpos[‘internal’]))
plt.figure() sns.histplot(gstslice.mprop[‘eqdia’][‘values’][gids_all-1],
label=’All grains: ESD’, kde=True)
- sns.histplot(gstslice.mprop[‘eqdia’][‘values’][gids_internal-1],
label=’Internal grains’, kde=True)
plt.legend() plt.show()
gstslice.pvgrid.plot()
VOLS = np.array(list(gstslice.mprop[‘volnv’].values())) gids_all = np.array(gstslice.gid) gids_internal = np.array(list(gstslice.gpos[‘internal’])) plt.figure() sns.histplot(VOLS[gids_all-1], label=’All grains’, kde=True) sns.histplot(VOLS[gids_internal-1], label=’Internal grains’, kde=True) plt.legend() plt.xlabel(‘Grain volume’) plt.ylabel(‘Count’) plt.show()
gstslice.n
- sss_rel_morpho_multiple(slice_planes=['xy', 'yz', 'xz'], loc_starts=[0.0, 0.0, 0.0], loc_ends=[5.0, 5.0, 5.0], loc_incrs=[2.0, 2.0, 2.0], reset_lgi=True, slice_gschar_kernel_order=4, mprop_names_2d=['eqdia', 'arbbox', 'solidity'], mprop_names_3d=['eqdia', 'arbbox', 'solidity'], ignore_border_grains_2d=True, ignore_border_grains_3d=True, save_plot3d_grains=True, save_plot2d_grains=True, show_legends=False, identify_peaks=True, show_peak_location=True, cmp_peak_locations=True, cmp_distributions=True, plot_distribution_cmp=True, kde3_color='red', kde3_clip=[0, 200], kde3_cumulative=False, kde3_linestyle='-', kde3_linewidth=2, kde3_marker='s', kde3_markevery=20, kde3_markersize=5, kde3_mfc='w', kde3_mec='r', kde2_color='blue', kde2_clip=[0, 200], kde2_cumulative=False, kde2_linestyle='-', kde2_linewidth=2, kde2_marker='s', kde2_markevery=20, kde2_markersize=5, kde2_mfc='w', kde2_mec='r')[source]
Carry out surface – sub-surface relationship study on multiple planes.
Note
mul denotes multiple studies.
- Parameters:
slice_planes (list(slice_plane : str), optional) – Specify the parallel planes of interest. Dependinmg on the values in location specifications, the actual plane will be selected. Default value is [‘xy’, ‘yz’, ‘xz’].
loc_starts (list(loc : float), optional) – Location of the plae of interest along direction normal to slice_plane. Default value is [0.0, 0.0, 0.0].
loc_ends (list(loc : float), optional) – Location of the plae of interest along direction normal to slice_plane. Default value is [5.0, 5.0, 5.0].
loc_incrs (list(loc : float), optional) – Location of the plae of interest along direction normal to slice_plane. Default value is [2.0, 2.0, 2.0].
reset_lgi (bool, optional) – Reset the lgi numbering to ensure spatial continuity. Default value is True.
slice_gschar_kernel_order (int, optional) – Kernel order or continuity structure to use for grain identification in the slice grain structure. Default value is 4.
mprop_names_2d (list, optional) – User specification of the morphological property names of 2D slice in UPXO to use for studying surface - sub-surface morphological property relationships. Default value is [‘eqdia’]. You could try [‘eqdia’, ‘arbbox’, ‘solidity’].
mprop_names_3d (list, optional) – User specification of the morphological property names of 3D MCGS in UPXO to use for studying surface - sub-surface morphological property relationships. Default value is [‘eqdia’]. You could try [‘eqdia’, ‘arbbox’, ‘solidity’]
ignore_border_grains_2d (bool, optional) – Ignore all the border grains in the slice whilst calculat9ion of the morphological properties if True. Defaults to True.
ignore_border_grains_3d (bool, optional) – Ignore all the border grains in the 3D MCGS whilst calculat9ion of the morphological properties if True. Defaults to True.
save_plot3d_grains (bool, optional) – Defaults to True.
save_plot2d_grains (bool, optional) – Defaults to True.
show_legends (bool, optional) – Defaults to False.
identify_peaks (bool, optional) – Defaults to True.
show_peak_location (bool, optional) – Defaults to True.
cmp_peak_locations (bool, optional) – Defaults to True.
cmp_distributions (bool, optional) – Defaults to True.
plot_distribution_cmp (bool, optional) – Defaults to True.
kde3_color (str, optional) – Defaults to ‘red’.
kde3_cumulative (str, optional) – Defaults to False.
kde3_linestyle (str, optional) – Defaults to “-“.
kde3_linewidth (str, optional) – Defaults to 2.
kde3_marker (str, optional) – Defaults to ‘s’.
kde3_markevery (int, optional) – Defaults to 20.
kde3_markersize (float, optional) – Defaults to 5.0.
kde3_mfc (str, optional) – Defaults to ‘w’.
kde3_mec (str, optional) – Defaults to ‘r’.
kde2_color (str, optional) – Defaults to ‘blue’.
kde2_cumulative (str, optional) – Defaults to False.
kde2_linestyle (str, optional) – Defaults to “-“.
kde2_linewidth (str, optional) – Defaults to 2.
kde2_marker (str, optional) – Defaults to ‘s’.
kde2_markevery (int, optional) – Defaults to 20.
kde2_markersize (float, optional) – Defaults to 5.0.
kde2_mfc (str, optional) – Defaults to ‘w’.
kde2_mec (str, optional) – Defaults to ‘r’.
- update_dream3d_ABQ_file()[source]
- Take Eralp’s code Dream3D2Abaqus and update it to also write:
- element sets (or make them as groups) for:
. texture partitioned grains . grain area binned grains . aspect ratio binned grains . boundary grains . internal grains . grain boundary surface elements . grain boundary edge elements . grain boundary junction point elements .
- Return type:
None.
- set_grain_positions()[source]
Set positions of grains relative to grain structure boundaries.
Notes
Front face is defined by y=ymax. Back face is defined by y=0. Front to back face: Slice lgi along axis = 1
Left face is defined by x=0. Right face is defined by x=xmax. Left to right face: Slice lgi along axis = 2
Bottom face is defined by z=0. Top face is defined by z=zmax. Bottom to top face: Slice lgi along axis = 0 # ========================================= all: self.gid # ——————– boundary: x=xmin, x=xmax, y=ymin, y=ymax, z=zmin, z=zmax # ——————– internal grains: set(all) - set(boundary) # ——————– left_face: x=xmin right_face: x=xmax back_face: y=ymin front_face: y=ymax bottom_face: z=zmin top_face: z=zmax # ——————– left_face_internal: x=xmin, y!=ymin, y!=ymax, z!=zmin, z!=zmax.
That is, x=xmin, ymin<y<ymax, zmin<z<zmax
- right_face_internal: x=xmax, y!=ymin, y!=ymax, z!=zmin, z!=zmax
That is, x=xmax, ymin<y<ymax, zmin<z<zmax
- back_face_internal: y=ymin, x!=xmin, x!=xmax, z!=zmin, z!=zmax
That is, y=ymin, xmin<x<xmax, zmin<z<zmax
- front_face_internal: y=ymax, x!=xmin, x!=xmax, z!=zmin, z!=zmax
That is, y=ymax, xmin<x<xmax, zmin<z<zmax
- bottom_face_internal: z=zmin, x!=xmin, x!=xmax, y!=ymin, y!=ymax
That is, z=zmin, xmin<x<xmax, ymin<y<ymax
- top_face_internal: z=zmax, x!=xmin, x!=xmax, y!=ymin, y!=ymax
That is, z=zmax, xmin<x<xmax, ymin<y<ymax
# ——————– # Edges parallel to x-axis front_top_edge: INTERSECTION(front_face, top_face) top_back_edge: INTERSECTION(top_face, back_face) back_bottom_edge: INTERSECTION(back_face, bottom_face) bottom_front_edge: INTERSECTION(bottom_face, front_face)
# Edges parallel to y-axis top_right_edge: INTERSECTION(top_face, right_face) right_bottom_edge: INTERSECTION(right_face, bottom_face) bottom_left_edge: INTERSECTION(bottom_face, left_face) left_top_edge: INTERSECTION(left_face, top_face)
# Edges parallel to z-axis front_right_edge: INTERSECTION(front_face, right_face) right_back_edge: INTERSECTION(right_face, back_face) back_left_edge: INTERSECTION(back_face, left_face) left_front_edge: INTERSECTION(left_face, front_face) # ——————– # Edges on each face left_edges = UNION(bottom_left_edge, left_top_edge,
back_left_edge, left_front_edge)
- right_edges = UNION(top_right_edge, right_bottom_edge,
front_right_edge, right_back_edge)
- back_edges = UNION(top_back_edge, back_bottom_edge,
right_back_edge, back_left_edge)
- front_edges = UNION(front_top_edge, bottom_front_edge,
front_right_edge, left_front_edge)
- bottom_edges = UNION(back_bottom_edge, bottom_front_edge,
right_bottom_edge, bottom_left_edge)
- top_edges = UNION(front_top_edge, top_back_edge,
top_right_edge, left_top_edge)
# ——————– # Grains at corners left_back_bottom = INTERSECTION(left_face, back_face, bottom_face) back_right_bottom = INTERSECTION(back_face, right_face, bottom_face) right_front_bottom = INTERSECTION(right_face, front_face, bottom_face) front_left_bottom = INTERSECTION(front_face, left_face, bottom_face)
left_back_top = INTERSECTION(left_face, back_face, top_face) back_right_top = INTERSECTION(back_face, right_face, top_face) right_front_top = INTERSECTION(right_face, front_face, top_face) front_left_top = INTERSECTION(front_face, left_face, top_face)
- set_gid_imap_keys()[source]
@dev
We will now inspect gstslice.gid_imap_keys gstslice.gid_imap_keys.keys()
This contains a list of foward and reverse maps of grian position names to their respective position IDs. The IDs are itegrers. Do inspect values of each of the above keys to know the ID-key pair maps. This is mainly to aid programming.
- assign_gid_imap_keys()[source]
Assign inverse mapping keys to grains based on relative positions.
- Parameters:
None
- Return type:
None
Examples
gstslice.gid_imap gid_imap[‘presence’]
- get_max_presence_gids()[source]
Get grain with the maximum presence.
Examples
gstslice.get_max_presence_gids(plot=True)
- clean_gs_GMD_by_source_erosion_v1(prop='volnv', parameter_metric='mean', threshold=1.0, reset_pvgrid_every_iter=False, find_neigh_every_iter=False, find_grvox_every_iter=False, find_grspabnds_every_iter=False, reset_skimrp_every_iter=False)[source]
Clean the gs using grain merger by dissolution by source grain erosion.
- Parameters:
prop (Provides which property to use as primary propetrty for) – merging grain. Defaults to ‘volnv’.
parameter_metric
threshold (int, optional)
reset_pvgrid_every_iter (bool, optional) – Defaults to False.
find_neigh_every_iter (bool, optional) – Defaults to False.
find_grvox_every_iter (bool, optional) – Defaults to False.
find_grspabnds_every_iter (bool, optional) – Defaults to False.
reset_skimrp_every_iter (bool, optional) – Defaults to False.
Notes
The following attributes are updated after each threshold has been processed.
self.lgi
self.n
self.gid
self.neigh_gid
self.mprop
self.grain_locs
self.spbound
self.spboundex
- Returns:
None
Options for prop
—————-
Morphological properties –
‘volnv’: Volume by number of voxels
’volsr’: Volume after grain boundary surface reconstruction
’volch’: Volume of convex hull
’sanv’: surface area by number of voxels
’savi’: surface area by voxel interfaces
’sasr’: surface area after grain boundary surface reconstruction
’pernv’: perimeter by number of voxels
’pervl’: perimeter by voxel edge lines
’pergl’: perimeter by geometric grain boundary line segments
’eqdia’: eqvivalent diameter
’arbbox’: aspect ratio by bounding box
’arellfit’: aspect ratio by ellipsoidal fit
’sol’: solidity
- ’ecc’: eccentricity - how much the shape of the grain differs
from a sphere.
’com’: compactness
’sph’: sphericity
’fn’: flatness
’rnd’: roundness
’fdim’: fractal dimension
Texture properties –
‘mo’: list
’tc’: texture component name
Phase properties –
‘pid’: phase ID
Notes
propmay reference volume, surface, or shape metrics.v1denotes the first version of this routine.
- clean_gs_GMD_by_source_erosion_v2(prop1='volnv', parameter_metric='mean', threshold=1.0)[source]
Clean the gs using grain merger by dissolution by source grain erosion.
- Parameters:
prop (Provides which property to use as primary propetrty for) – merging grain. Defaults to ‘volnv’.
prop2 (Provides which property o use as secondary property for) – merging grain.
parameter_metric
threshold
Notes
- The following attributes are updated after each threshold is processed.
self.lgi
self.n
self.gid
self.neigh_gid
self.mprop
self.grain_locs
self.spbound
self.spboundex
- Returns:
None
Options for prop1, prop2, prop3, prop4
————————————–
Morphological properties –
‘volnv’: Volume by number of voxels
’volsr’: Volume after grain boundary surface reconstruction
’volch’: Volume of convex hull
’sanv’: surface area by number of voxels
’savi’: surface area by voxel interfaces
’sasr’: surface area after grain boundary surface reconstruction
’pernv’: perimeter by number of voxels
’pervl’: perimeter by voxel edge lines
’pergl’: perimeter by geometric grain boundary line segments
’eqdia’: eqvivalent diameter
’arbbox’: aspect ratio by bounding box
’arellfit’: aspect ratio by ellipsoidal fit
’sol’: solidity
- ’ecc’: eccentricity - how much the shape of the grain differs
from a sphere.
’com’: compactness
’sph’: sphericity
’fn’: flatness
’rnd’: roundness
’fdim’: fractal dimension
Texture properties –
‘mo’: list
’tc’: texture component name
Phase properties –
‘pid’: phase ID
Notes
v2denotes a later revision of the erosion-based cleaning routine.Author
Dr. Sunil Anandatheertha: developed and implemented the technique.
- set_Lgbp_gid(gid, saa=True, throw=False, verbose=True)[source]
Return the local grain-boundary points for
gidor store them.- Parameters:
- Returns:
Local grain-boundary points when
saais False; otherwiseNone.- Return type:
numpy.ndarray or None
- set_Lgbp_all(verbose=True)[source]
Create a dictionary of all the local grain boundary points.
- Parameters:
None
- Return type:
None
- globalise_gbp()[source]
Edits the local grain boundary points dictionary.
- Parameters:
None
- Return type:
None
Notes
The local boundary points are shifted by a half-voxel offset and the grain-specific minimum extents to obtain global coordinates.
- build_gbp_stack()[source]
Stack and uniquefy all grain boundary points.
- Parameters:
None
- Return type:
None
- build_gbp_id_mappings()[source]
Create gbp ID database.
- Parameters:
None
- Returns:
None
Explanations
————
First create {gbp coord tuple (gbp ID} dictionary –> self.gbp_id_maps)
Then use this to create a {gid (gbp IDs} dictionary –> self.gbp_ids)
- find_gbsp()[source]
Form grain boundary surface points.
- Parameters:
None
- Return type:
None
Notes
self.Ggbp_allstores grain-boundary points for each grain,self.gbpstackstores all unique grain-boundary points, andself.gbp_id_mapsmaps coordinates to point IDs.
- find_gid_pair_gbp_IDs(gidl, gidr)[source]
Find the gbp coords at the interface of gidl and gidr.
- Parameters:
gidl (gid on the left side)
gidr (gid on the right side)
- Return type:
None
Notes
The interface ID is resolved from the ordered grain-pair mapping and the stored interfacial point-ID sets.
- set_gid_pair_gbp_IDs()[source]
Find the gbp IDs at the interface of all unique gidl and gidr pairs.
- Parameters:
None
- Returns:
None
Developer notes by Dr. SA
————————-
gstslice.gid_pair_ids is a dictionary of gid_pair_id as keys and
the participating (gidl, gidr) pairs as values.
We can feed this participating gid pair elements into the definition
self.find_gid_pair_gbp_IDs to get (as return) the grain boundaryt point
ids which would constitute the grain boundary interface surface.
We can then repeat this for every (gidl, gidr) pair in the dictionary
gstslice.gid_pair_ids.
- build_gid__gid_pair_IDs()[source]
Build map between gid and IDs of all gid interface pairs (gid_gpid).
- Parameters:
None
- Return type:
None
Notes
Example, if 10 be the gid and 12, 15, 17 be its O(1) neighbours, then the gid pairs are (10, 12), (10, 15) and (10, 17). These pairs have IDs as 10A, 10B and 10C. These IDs themselves are obtained from gstslice.gid_pair_ids. gstslice.gid_pair_ids_rev is the reverse mapping. Here, gstslice.gid_pair_ids is a dictionary with neighbour grain interface surface ID (which is the same as gid_pair) as the keys, having the values as, the tuple of gid_left and gid_right, that is (gidl, gidr).
To explain a bit more, I would say that the keys, here are the same as the O(1) neighbour grain ID pair, the fir4st value is understood to be the core and thye second vale is one of the O(1) of the core gid. That is, gidl is core gid and gidr is one of the O(1) gid.
- set_neigh_gid_interaction_pairs(verbose=True)[source]
Build grain-pair interaction triples from the neighbour map.
Notes
Each grain contributes neighbour relationships that are intersected with the neighbour set of the core grain to form interaction triples.
- setup_gid_set__gbsegs()[source]
Development notes
Every gid has neigh_gid, accessed as gstslice.neigh_gid[gid].
Notes
Every neigh gid pair is tagged in gstslice.gid_pair_ids. The key is
the ID of the pair. The value is a tuple of gidl (gid to the left) and gidr (gid to the right).
Every grain has numerous grain boundary pairs. They are contained in
gstslice.gid_gpid. The key is the ID of the grain. The value is the set of neigh-gid-pair IDs. NOTE: The neigh-gid-pair ID is the same as the keys in gstslice.gid_pair_ids. NOTE: The name gstslice.gid_gpid means grain ID and Grain pair ID.
- set_mprop_rat_sanv_volnv(reset_volnv=False, reset_sanv=False, N=26, verbosity=100)[source]
Set or update the surface-area and volume metric ratios.
- sep_gbzcore_from_bbgidmask(boundary_coords, BBLGI_mask)[source]
Separate the grain-boundary core from the boundary mask.
- get_points_in_feature_coord(feature_type='gb', selcri='random', fcoords=None, n=1, get_neigh_vox=False, kwargs_nv={'ret_coords': True, 'ret_in_coord': False, 'ret_ind': False, 'vs': 1.0}, validate_user_inputs=True)[source]
- feature_type will be:
‘gb’ in case of grain boundary
‘g’ in case of grains
- selcri will be:
‘random’ when the point is to be selected at random
‘centroid’ when the point is to be selected at centroid
- ‘meandistant’ when the point to be selected must be at
approximately be at the statistical mean of the point
- fcoords will be:
gstslice.grain_locs is grain coordinates if grain coordinates is being used
boundary_coords (calculated usig gstslice.get_gb_voxels(..)) if grain boundary c oordinates is being used
- get_k_nearest_coords_from_tree(tree, coord, K)[source]
nearest_coords = gstslice.get_k_nearest_coords(tree, coord, K)
- add_fdb(*, fname, dnames, datas, info)[source]
Add ferature data base.
- Parameters:
None
- Return type:
None
Example
- self.add_fdb(fname=’twin_01’,
dnames=’fid’, datas=123, info={‘a’: 1, ‘b’: 2})
Notes
Intended for internal use.
- find_twin_hosts(nprops=2, mprops={'rat_sanv_volnv': {'k': [0.1, 0.8], 'reset': False, 'sanv_N': 26, 'use': True}, 'volnv': {'k': [0.1, 0.8], 'min_vol': 4, 'reset': False, 'use': True}}, viz_grains=False, opacity=1.0)[source]
nprops: Number of propertiez to use mprop_names: Property names avoid_svg: Avoid single voxel grains
Example
from upxo.ggrowth.mcgs import mcgs
pxt = mcgs() pxt.simulate(verbose=False) tslice = 25 gstslice = pxt.gs[tslice] gstslice.char_morphology_of_grains(label_str_order=1,
find_grain_voxel_locs=True, find_spatial_bounds_of_grains=True, force_compute=True)
- GIDS_masks_mprops, GIDS_mask, GIDS = gstslice.find_twin_hosts(nprops=2,
- mprops={‘volnv’: {‘use’: True,
‘reset’: False, ‘k’: [0.1, 1], ‘min_vol’: 4, },
- ‘rat_sanv_volnv’: {‘use’: True,
‘reset’: False, ‘k’: [.8, 1], ‘sanv_N’: 26},
},
min_vol=0, viz_grains=True, opacity=0.2 )
- setup_for_twins(nprops=2, mprops={'rat_sanv_volnv': {'k': [0.1, 0.8], 'reset': False, 'sanv_N': 26, 'use': True}, 'volnv': {'k': [0.1, 0.8], 'min_vol': 4, 'reset': False, 'use': True}}, instance_name='twin.1', feature_name='annealing_twin', viz_grains=False, opacity=1.0)[source]
Carry out pre-requisite operations needed to establish twins
- identify_twins_gid(gid, twspec={'dlk': numpy.array, 'dno': numpy.array, 'dnw': numpy.array, 'n': None, 'sep_bzcz': False, 'tdis': 'normal', 'tpar': {'loc': 4, 'scale': 2.5, 'val': 1}, 'tv': None, 'vf': [0.05, 1.0]}, twgenspec={'K': 10, 'bidir_tp': False, 'seedsel': 'random_gb'}, viz=False, viz_flags={'gb': True, 'gc': True, 'tb': True, 'tc': True, 'tpvec': False}, viz_steps={'gb': 2, 'gc': 4})[source]
Generate and inlude twin in gstslice.lgi.
- remove_overlaps_in_twins(gid, twins, enforce_twin_vf_check=True, cutoff_twin_vf=[0.05, 1.0])[source]
twins = gstslice.identify_twins_gid(gid,….) twins = gstslice.remove_overlaps_in_twins(gid, twins,
enforce_twin_vf_check=True, cutoff_twin_vf=[0.05, 1.00])
- identify_twins(base_gs_name='twin.1', twspec={'dlk': numpy.array, 'dno': numpy.array, 'dnw': numpy.array, 'n': [5, 10, 3], 'sep_bzcz': False, 'tdis': 'normal', 'tpar': {'loc': 1.12, 'scale': 0.25, 'val': 1}, 'tv': numpy.array, 'vf': [0.05, 1.0]}, twgenspec={'K': 10, 'bidir_tp': False, 'checks': [True, True], 'seedsel': 'random_gb'}, viz=False)[source]
seed_selcri: Twin seed selection criteria nnp: Number of nearest neighbouring points to use nt: Number of twins specification: [lower, upper, iter_threshold] tpl_ext: Twin plane extension on either side tpl_vec_spec: Twin plane vector specification tpl_tvec: Twin plane translation vector tth: twin thickness value cutoff_twin_vf: Cut-off twin volume fraction sep_twin_bz_core: Seperate twin boundary zone and core viz: Visualize or not viz_flags: Specify various visualization flag values viz_steps: Specify7 visualization steps to help with large data
from upxo.ggrowth.mcgs import mcgs
pxt = mcgs() pxt.simulate(verbose=False) tslice = 49 gstslice = pxt.gs[tslice] gstslice.char_morphology_of_grains(label_str_order=1,
find_grain_voxel_locs=True, find_spatial_bounds_of_grains=True, force_compute=True)
ninstances = 10 for inst in range(ninstances):
print(50*’#’, 5*’
- ‘,
f’Creating instance: {inst} of {ninstances}’, 5*’
- ‘, 50*’#’)
instance_name = ‘twin.’+str(inst) gstslice.setup_for_twins(nprops=2,
- mprops={‘volnv’: {‘use’: True,
‘reset’: False, ‘k’: [.02, 1.0], ‘min_vol’: 4, },
- ‘rat_sanv_volnv’: {‘use’: True,
‘reset’: False, ‘k’: [0.0, .8], ‘sanv_N’: 26 },
},
instance_name=instance_name, viz_grains=False, opacity=1.0)
- gstslice.identify_twins(base_gs_name=instance_name,
- twspec={‘n’: [5, 10, 3],
‘tv’: np.array([5, -3.5, 5]), ‘dlk’: np.array([1.0, -1.0, 1.0]), ‘dnw’: np.array([0.5, 0.5, 0.5]), ‘dno’: np.array([0.5, 0.5, 0.5]), ‘tdis’: ‘normal’, ‘tpar’: {‘loc’: 1.12, ‘scale’: 0.25, ‘val’: 1}, ‘vf’: [0.05, 1.00], ‘sep_bzcz’: False },
- twgenspec={‘seedsel’: ‘random_gb’,
‘K’: 10, ‘bidir_tp’: False, ‘checks’: [True, True], },
viz=False, )
# gid = gstslice.gid[] # gid = gstslice.get_largest_gids()[0] gid = np.random.choice(list(gstslice.fdb[‘twin.7’][‘data’][‘twin_map_g_t’].keys()),
1 )[0]
fid = gstslice.fdb[‘twin.7’][‘data’][‘fid’] twin_gids = gstslice.fdb[‘twin.7’][‘data’][‘twin_map_g_t’][gid]
import pyvista as pv pvgrid = pv.UniformGrid() pvgrid.dimensions = np.array(gstslice.lgi.shape) + 1 pvgrid.origin = (0, 0, 0) pvgrid.spacing = (1, 1, 1) pvgrid.cell_data[‘lgi’] = gstslice.lgi.flatten(order=”F”) pvgrid.plot(cmap=’nipy_spectral’)
pvp = pv.Plotter() thresholded = pvgrid.threshold([gid, gid]) pvp.add_mesh(thresholded, cmap=’nipy_spectral’, show_edges=False, opacity=0.25) for twin_gid in twin_gids:
thresholded = pvgrid.threshold([twin_gid, twin_gid]) if thresholded.cells.size > 0:
pvp.add_mesh(thresholded, cmap=’nipy_spectral’, show_edges=True, opacity=1.0)
pvp.show()
instance_no = 2 feat_instance_name = ‘twin.’+str(instance_no) fid = gstslice.fdb[feat_instance_name][‘data’][‘fid’] pvgrid = pv.UniformGrid() pvgrid.dimensions = np.array(fid.shape) + 1 pvgrid.origin = (0, 0, 0) pvgrid.spacing = (1, 1, 1) pvgrid.cell_data[‘fid’] = fid.flatten(order=”F”) # pvgrid.plot(cmap=’nipy_spectral’)
gids_all = list(gstslice.fdb[feat_instance_name][‘data’][‘twin_map_g_t’].keys())
nr, nc = 6, 6
gids = np.reshape(np.random.choice(gids_all, nr*nc, replace=False), (nr, nc))
pvp = pv.Plotter(shape=(nr, nc)) for gidr in range(nr):
- for gidc in range(nc):
print(f’gidr: {gidr}, gidc: {gidc}’) pvp.subplot(gidr, gidc) gid = gids[gidr][gidc] thresholded = pvgrid.threshold([gid, gid]) if thresholded.cells.size == 0:
break
pvp.add_mesh(thresholded, cmap=’nipy_spectral’, show_edges=False, opacity=0.5)
twin_gids = gstslice.fdb[feat_instance_name][‘data’][‘twin_map_g_t’][gid] for twin_gid in twin_gids:
thresholded = pvgrid.threshold([twin_gid, twin_gid]) if thresholded.cells.size > 0:
pvp.add_mesh(thresholded, cmap=’nipy_spectral’, show_edges=True, opacity=1.0)
pvp.show()
import pyvista as pv pvgrid = pv.UniformGrid() pvgrid.dimensions = np.array(fid.shape) + 1 pvgrid.origin = (0, 0, 0) pvgrid.spacing = (1, 1, 1) pvgrid.cell_data[‘fid’] = fid.flatten(order=”F”) pvgrid.plot(cmap=’nipy_spectral’)
feat_instance_name = ‘twin.9’ fid = gstslice.fdb[feat_instance_name][‘data’][‘fid’] pvgrid = pv.UniformGrid() pvgrid.dimensions = np.array(fid.shape) + 1 pvgrid.origin = (0, 0, 0) pvgrid.spacing = (1, 1, 1) pvgrid.cell_data[‘fid’] = fid.flatten(order=”F”)
pvp = pv.Plotter() gid = 131 thresholded = pvgrid.threshold([gid, gid]) pvp.add_mesh(thresholded, cmap=’nipy_spectral’, show_edges=False, opacity=0.25) twin_gids = gstslice.fdb[feat_instance_name][‘data’][‘twin_map_g_t’][gid] for twin_gid in twin_gids:
thresholded = pvgrid.threshold([twin_gid, twin_gid]) if thresholded.cells.size > 0:
pvp.add_mesh(thresholded, cmap=’nipy_spectral’, show_edges=True, opacity=1.0)
pvp.show()
- instantiate_twins(ninstances=2, base_gs_name_prefix='twin.', twin_setup={'mprops': {'rat_sanv_volnv': {'k': [0.0, 0.8], 'reset': False, 'sanv_N': 26, 'use': True}, 'volnv': {'k': [0.02, 1.0], 'min_vol': 4, 'reset': False, 'use': True}}, 'nprops': 2}, twspec={'dlk': numpy.array, 'dno': numpy.array, 'dnw': numpy.array, 'n': [5, 10, 3], 'sep_bzcz': False, 'tdis': 'normal', 'tpar': {'loc': 1.12, 'scale': 0.25, 'val': 1}, 'tv': numpy.array, 'vf': [0.05, 1.0]}, twgenspec={'K': 10, 'bidir_tp': False, 'checks': [True, True], 'seedsel': 'random_gb'}, orimapspec={'easets': {1: {'ea': [[35, 45, 0], [63, 75, 27]], 'mean': [90, 90, 90], 'name': '--', 'width': 15}}, 'schemeID': 1}, reset_fdb=True, reset_keystring='twin.', make_sep_pvgrds=False, save_twin_coords=False, clean_verbosity_interval_1=250)[source]
# —–> FEATURE IDS
gstslice.fdb[“twin.0”][“data”][“feat_host_gids”] This has all gids initialliy selected for introducing twins. For grain ids which actually host twins, refer gstslice.fdb[“twin.0”][“data”][“feat_host_ids”] instead.
gstslice.fdb[“twin.0”][“data”][“feat_host_ids”] Feature (i.e. grain) ids which actually host twins.
gstslice.fdb[“twin.0”][“data”][“twin_map_g_t_missed”] Numpy array containing the list of parent feature IDs which were misses duringh twin instantiation. These are featre IDs initially selected for twin generation, but later rejected as twins could not be produced with the user specified algorithm control parameter values.
gstslice.fdb[“twin.0”][“data”][“notwin_gids”] Parent features i.e. grains, which were not selected to parent any children i.e. twins.
gstslice.fdb[“twin.0”][“data”][“twin_id”] Twin ID numbers
gstslice.fdb[“twin.0”][“data”][“twin_map_g_t”] Contains parent to children map. As a dictionary, keys are parent feature IDs. A value is a list of children feature IDs, which in this case are twin IDs.
gstslice.fdb[“twin.0”][“data”][“map_cp”] Dictiobnary having keys as twin IDs and values as parent IDs. This is a reverse map of twin ID to parent ID. len(gstslice.fdb[“twin.0”][“data”][“map_cp”].keys()) gives the total number of children, which can also abe obtained as sum(gstslice.fdb[“twin.0”][“data”][“twin_map_g_nt”].values()). In fact, in some UPXO twined grain structure, len(gstslice.fdb[“twin.0”][“data”][“map_cp”].keys()) was 383, sum(gstslice.fdb[“twin.0”][“data”][“twin_map_g_nt”].values()) was also 383 and len(gstslice.fdb[“twin.0”][“data”][“twin_id”]) was also 383. # —————————————– # —–> DEPRECATED
gstslice.fdb[“twin.0”][“data”][“twin_i”] DEPRECATED. Commented in code.
gstslice.fdb[“twin.0”][“data”][“parent_id”] numpy array of parent IDs which actually host children features. DEPRECTAED. This is the same as gstslice.fdb[“twin.0”][“data”][“feat_host_ids”]. Commented out in code.
gstslice.fdb[“twin.0”][“data”][“twin_zero_voxels”] List of twin IDs with zero voxels. Should be empty. To be deprecated. # —————————————– # —–> COORDINATES
gstslice.fdb[“twin.0”][“data”][“twin_coords”] Coordinates of twins. len(gstslice.fdb[“twin.0”][“data”][“twin_coords”]) is same as len(gstslice.fdb[“twin.0”][“data”][“parent_id”]).
gstslice.fdb[“twin.0”][“data”][“twin_map_g_t_coords”] Contains voxel coordinates of the twinned regions. Keys are parent feature ID. Value is dict with keys as children feature IDs and values being corresponding numpy cooridnate arrays. # —————————————– # —–> SIZE AND CONTENT PROPERTIES
gstslice.fdb[“twin.0”][“data”][“twin_vol”] Twin volumes
gstslice.fdb[“twin.0”][“data”][“twin_vf”] Twin volume fractions
gstslice.fdb[“twin.0”][“data”][“twin_map_g_nt”] Contains parent to children count map. As a dictionary, keys are parent feature IDs. A value is the length of the list of children feature IDs.
gstslice.fdb[“twin.0”][“data”][“twin_vol_total”] This is total volume of twins across the entire domain. It is numpy.int32 type.
gstslice.fdb[“twin.0”][“data”][“twin_vf_total”] This is the overall volume fraction of twins.
gstslice.fdb[“twin.0”][“data”][“twin_map_g_t_nvox”] Contains parent to children voxel count map. As a dictionary, keys are parent feature IDs. A value is the list of total number of voxels in each child feature. List size will be the total child feature count for the current parent feature ID.
gstslice.fdb[“twin.0”][“data”][“twin_nvox”] Total number of voxels across all children features (dict value) for a given parent feature ID (dict key). # —————————————– gstslice.fdb[“twin.0”][“data”][“pvgrid”] This is the PyVista grid having gstslice.fdb[“twin.0”][“data”][“fid”] as scalar field.
gstslice.fdb[“twin.0”][“data”][“parent_feature”] String value containing, the name of the parent feature, which in this case is ‘grain’.
Example
import time from upxo.ggrowth.mcgs import mcgs
start_time = time.time()
pxt = mcgs(input_dashboard=’input_dashboard.xls’) pxt.simulate(verbose=False) tslice = 49 gstslice = pxt.gs[tslice] gstslice.char_morphology_of_grains(label_str_order=1,
find_grain_voxel_locs=True, find_spatial_bounds_of_grains=True, force_compute=True)
- mprops = {‘volnv’: {‘use’: True, ‘reset’: False,
‘k’: [.02, 1.0], ‘min_vol’: 4,},
- ‘rat_sanv_volnv’: {‘use’: True, ‘reset’: False,
‘k’: [0.0, .8], ‘sanv_N’: 26},}
- twspec = {‘n’: [5, 10, 3],
‘tv’: np.array([5, -3.5, 5]), ‘dlk’: np.array([1.0, -1.0, 1.0]), ‘dnw’: np.array([0.5, 0.5, 0.5]), ‘dno’: np.array([0.5, 0.5, 0.5]), ‘tdis’: ‘normal’, ‘tpar’: {‘loc’: 1.12, ‘scale’: 0.25, ‘val’: 1}, ‘vf’: [0.05, 1.00], ‘sep_bzcz’: False}
- twgenspec = {‘seedsel’: ‘random_gb’, ‘K’: 10,
‘bidir_tp’: False, ‘checks’: [True, True],}
- gstslice.instantiate_twins(ninstances=10, base_gs_name_prefix=’twin.’,
twin_setup={‘nprops’: 2, ‘mprops’: mprops}, twspec=twspec, twgenspec=twgenspec,)
end_time = time.time() elapsed_time = end_time - start_time print(f”Execution time: {elapsed_time:.6f} seconds”)
- get_coords_parents_minus_childrens(pfids=None, pfeatname='grain', instance_name='twin.0', disp_msg=True)[source]
Example
pfids = gstslice.fdb[‘twin.0’][‘data’][‘feat_host_ids’] # Parent minus childs pminuscs_coords = gstslice.get_coords_parents_minus_childrens(pfids=pfids,
pfeatname=’grain’, instance_name=’twin.0’, disp_msg=True)
- extract_representative_voxel(instance_name='base', featname='grains')[source]
Extract a representative voxel.
- extract_feat_coords(instance_name='twin.0', feature_name='twins', use_parent_ids=True, pfids=None, cfids=None)[source]
Example-1
pfids = gstslice.fdb[‘twin.0’][‘data’][‘feat_host_ids’][:2] gstslice.extract_feat_coords(instance_name=’twin.0’,
feature_name=’twins’, use_parent_ids=True, pfids=pfids)
Example-2
cfids = list(gstslice.fdb[‘twin.0’][‘data’][‘map_cp’])[:4] gstslice.extract_feat_coords(instance_name=’twin.0’,
feature_name=’twins’, use_parent_ids=False, cfids=cfids)
- calc_bounds(instance_name='base', featname='grains', recalc=True, use_parent_ids=True, pfids=None, cfids=None, find_extended_bounds=False)[source]
EXAMPLE - 1
- gstslice.calc_bounds(instance_name=’base’, featname=’grains’,
recalc=False)
- gstslice.calc_bounds(instance_name=’base’, featname=’grains’,
recalc=True)
EXAMPLE - 2
pfids = gstslice.fdb[‘twin.0’][‘data’][‘feat_host_ids’][:2] gstslice.calc_bounds(instance_name=’twin.0’, featname=’twins’,
use_parent_ids=True, pfids=pfids)
EXAMPLE - 3
cfids = list(gstslice.fdb[‘twin.0’][‘data’][‘map_cp’])[:4] gstslice.calc_bounds(instance_name=’twin.0’, featname=’twins’,
use_parent_ids=False, cfids=cfids)
- extract_pvgrid_subset(instance_name='twin.0', feature_name='twin', scalar='fid', fids=None)[source]
Exanple
instance_name = ‘twin.0’ feature_name = ‘twin’ fids = gstslice.fdb[instance_name][‘data’][‘twin_id’] pvgss = gstslice.extract_pvgrid_subset(instance_name=instance_name,
feature_name=feature_name, scalar=’fid’, fids=fids)
pvgss.plot()
- plot_features(instance_name='twin.0', feature_name='twin', scalar='fid', fids=None, show_scalars=False, pv_kwargs={'cmap': 'nipy_spectral', 'line_width': 1.0, 'opacity': 1.0, 'show_edges': False, 'style': 'points'}, plot=True, validate=True)[source]
Pre-example set up
# Generate grain strucure # Instantiate twins. Then proceed below.
instance_name = ‘twin.0’ feature_name = ‘twin’ fids = gstslice.fdb[instance_name][‘data’][‘twin_id’] pv_kwargs={‘cmap’: ‘nipy_spectral’,
‘style’: ‘points’, ‘show_edges’: False, ‘line_width’: 1.0, ‘opacity’: 0.75}
Example-1
- pvgss = gstslice.plot_features(instance_name=instance_name,
feature_name=feature_name, scalar=’fid’, fids=fids, pv_kwargs=pv_kwargs)
Example-2
# Turning plot flag False, renders this function identical to # the function extract_pvgrid_subset!! and returns the # subset pvgrid. See below. pvgss = gstslice.plot_features(instance_name=instance_name,
feature_name=feature_name, scalar=’fid’, fids=fids, pv_kwargs=pv_kwargs, plot=True)
Example-3
if unsure of what scalars exist, then use the same function to know them as below. No plpotting will be done, only available scalars will be provided.
- pvgss = gstslice.plot_features(instance_name=instance_name,
feature_name=feature_name, show_scalars=True)
- validate_fids(instance_name='twin.0', feature_name='twin', fids=None)[source]
Check or validate feature IDs.
- property gridx
Return the grid extent in x.
- property gridy
Return the grid extent in y.
- property gridz
Return the grid extent in z.
- property domsizex
Return the domain size in x.
- property domsizey
Return the domain size in y.
- property domsizez
Return the domain size in z.
- property domvol
Return the domain volume.
- property domsa
Return the domain surface area.
- plot_gs_instance(check=False, instance_name='base', cmap='nipy_spectral', show_edges=False, lighting=True, show_scalar_bar=True)[source]
Visualise gs instance using Matplotlib or PyVista.
- mask_fid(feature='twins', instance_name='twin.0', fid_mask_value=-32, non_fid_mask=False, non_fid_mask_value=-31, write_to_disk=False, write_sparse=True, throw=True)[source]
Mask the feature ID array with the given mask value. Options apply.
This method masks the feature ID array for a given feature and instance with specified mask values.
- Parameters:
feature (str, optional) –
- Specification of feature name. Must be from below valid list:
twins
blocks
precipitates
laths
sub-grains
DEfaults to ‘twins’.
instance_name (str, optional) – Specification of instance name. Must be either ‘base’ or a valid gstslice.fdb.keys(). Defaults to ‘twin.0’.
fid_mask_value (int, optional) – Numerical value to mask the feature ID with. Defaults to -32. Negative values are recommended to avoid conflicts with valid IDs. If a non-negative value is provided, it will be converted to its negative equivalent.
non_fid_mask (bool, optional) – If True, mask elements where the feature ID is not equal to the instance’s twin ID with non_fid_mask_value. Defaults to False.
non_fid_mask_value (int, optional) – Numerical value to use when non_fid_mask is True. Defaults to -31. Negative values are recommended. If a non-negative value is provided, it will be converted to its negative equivalent.
write_to_disk (bool, optional) – If True, write the masked data to disk. The specific format (sparse or dense) is determined by write_sparse. Defaults to False.
write_sparse (bool, optional) – If True (and write_to_disk is True), write the data in a sparse format. If False, write in a dense format. Defaults to True.
throw (bool, optional) – If True, raise a ValueError if the instance_name is invalid. If False, return None in case of an error. Defaults to True.
- Raises:
ValueError – If instance_name is invalid and throw is True.
- Returns:
The masked feature ID array. Returns None if write_to_disk is True or if an error occurs and throw is False.
- Return type:
numpy.ndarray or None
- mask_fid_and_make_pvgrid(feature='twins', instance_name='twin.0', fid_mask_value=-32, non_fid_mask=False, non_fid_mask_value=-31, write_to_disk=False, write_sparse=True, throw=True)[source]
Mask feature IDs and build a PyVista grid.
- mask_fid_and_plot(feature='twins', instance_names=('twin.0',), fid_mask_value=-32, non_fid_mask=False, non_fid_mask_value=-31, write_to_disk=False, write_sparse=True, throw=True, cmap_specs=(['blue', 'yellow', 'grey', 'red'], 2), show_edges=False, opacity=1.0, rmax_sp=5, cmax_sp=5, thresholding=True, threshold_value=-32)[source]
import time start_time = time.time() from upxo.ggrowth.mcgs import mcgs
pxt = mcgs(input_dashboard=’input_dashboard.xls’) pxt.simulate(verbose=False) tslice = 49 gstslice = pxt.gs[tslice]
- gstslice.char_morphology_of_grains(label_str_order=1,
find_grain_voxel_locs=True, find_spatial_bounds_of_grains=True, force_compute=True)
- gstslice.set_mprops(volnv=True, eqdia=False,
eqdia_base_size_spec=’volnv’, arbbox=False, arbbox_fmt=’gid_dict’, arellfit=False, arellfit_metric=’max’, arellfit_calculate_efits=False, arellfit_efit_routine=1, arellfit_efit_regularize_data=False, solidity=False, sol_nan_treatment=’replace’, sol_inf_treatment=’replace’, sol_nan_replacement=-1, sol_inf_replacement=-1)
- gstslice.clean_gs_GMD_by_source_erosion_v1(prop=’volnv’,
threshold=8, parameter_metric=’mean’, reset_pvgrid_every_iter=True, find_neigh_every_iter=False, find_grvox_every_iter=True, find_grspabnds_every_iter=True)
- gstslice.char_morphology_of_grains(label_str_order=1,
find_grain_voxel_locs=True, find_spatial_bounds_of_grains=True, force_compute=True)
- gstslice.set_mprops(volnv=True, eqdia=False,
eqdia_base_size_spec=’volnv’, arbbox=False, arbbox_fmt=’gid_dict’, arellfit=False, arellfit_metric=’max’, arellfit_calculate_efits=False, arellfit_efit_routine=1, arellfit_efit_regularize_data=False, solidity=False, sol_nan_treatment=’replace’, sol_inf_treatment=’replace’, sol_nan_replacement=-1, sol_inf_replacement=-1)
- mprops = {‘volnv’: {‘use’: True, ‘reset’: False,
‘k’: [.02, 1.0], ‘min_vol’: 4,},
- ‘rat_sanv_volnv’: {‘use’: True, ‘reset’: False,
‘k’: [0.0, .8], ‘sanv_N’: 26},}
- twspec = {‘n’: [5, 10, 3],
‘tv’: np.array([5, -3.5, 5]), ‘dlk’: np.array([1.0, -1.0, 1.0]), ‘dnw’: np.array([0.5, 0.5, 0.5]), ‘dno’: np.array([0.5, 0.5, 0.5]), ‘tdis’: ‘normal’, ‘tpar’: {‘loc’: 1.12, ‘scale’: 0.1, ‘val’: 1}, ‘vf’: [0.05, 1.00], ‘sep_bzcz’: False}
- twgenspec = {‘seedsel’: ‘random_gb’, ‘K’: 20,
‘bidir_tp’: False, ‘checks’: [True, True],}
- gstslice.instantiate_twins(ninstances=4,
base_gs_name_prefix=’twin.’, twin_setup={‘nprops’: 2, ‘mprops’: mprops}, twspec=twspec, twgenspec=twgenspec, reset_fdb=True, )
# —————————————- elapsed_time_simulation = time.time() - start_time print(f’Total time taken: {elapsed_time_simulation}’) # —————————————- gstslice.mask_fid_and_plot(feature=’twins’,
instance_names=gstslice.fdb.keys(), fid_mask_value=-32, non_fid_mask=True, non_fid_mask_value=-31, write_to_disk=False, write_sparse=True, throw=True, cmap_specs=([‘white’, ‘yellow’, ‘grey’, ‘red’], 2), show_edges=False, opacity=1.0, rmax_sp=8, cmax_sp=13, thresholding=True, threshold_value=-32)
import matplotlib.pyplot as plt from scipy.stats import gaussian_kde import seaborn as sns
total_twin_vol_fr = [] fig, axes = plt.subplots(1, 2, figsize=(12, 5), dpi=88) for key in gstslice.fdb.keys():
grain_tvf = gstslice.fdb[key][‘data’][‘twin_vf’]
total_tvf = gstslice.fdb[key][‘data’][‘twin_vf_total’] total_twin_vol_fr.append(total_tvf)
ntwins = np.array(list(gstslice.fdb[key][‘data’][‘twin_map_g_nt’].values())) ntwins = ntwins[ntwins != 0]
sns.kdeplot(grain_tvf, ax=axes[0], common_norm=True) sns.kdeplot(ntwins, ax=axes[1], common_norm=True)
axes[0].set_xlabel(‘Host grain wise twin Volume fraction’, fontsize=14) axes[1].set_xlabel(‘Host grain wise number of twins’, fontsize=14) axes[0].set_ylabel(‘Probability density function’, fontsize=14) axes[1].set_ylabel(‘Probability density function’, fontsize=14) plt.tight_layout() plt.show()
plt.figure(figsize=(5, 5), dpi=75) sns.kdeplot(total_twin_vol_fr, common_norm=True) plt.xlabel(‘Total twin volume fractions in
- grain structures’, fontsize=14)
plt.ylabel(‘Probability density function’, fontsize=14) plt.tight_layout() plt.show()
x_grain_tvf = np.linspace(grain_tvf.min(), grain_tvf.max(), 100) axes.plot(x_grain_tvf, kde_grain_tvf(x_grain_tvf)) axes.set_xlabel(‘Grain TVF’) axes.set_ylabel(‘Density’) x_ntwins = np.linspace(ntwins.min(), ntwins.max(), 100) axes.plot(x_ntwins, kde_ntwins(x_ntwins)) axes.set_xlabel(‘Number of Twins’) axes.set_ylabel(‘Density’) plt.tight_layout()
# plot kde of grain_tvf in first subplot # plot kde of ntwins in second subplot
# plot kde of total_twin_vol_fr in seperate plot window
- extract_subdomains_random(p=5, q=5, r=5, n=2, feature_name='base', user_fid=None, make_pvgrids=False)[source]
Extracts n random sub-domains of size pxqxr from a 3D array.
- Parameters:
p (int) – The size of the sub-domain along the first axis.
q (int) – The size of the sub-domain along the second axis.
r (int) – The size of the sub-domain along the third axis.
n (int) – The number of random sub-domains to extract.
feature_name (str) –
- Name of the feature. It can take the following options.
’s’ or ‘state’ for Monte-Carlo state value.
’base’ or ‘base_gs’. Here, gstslice.lgi will become the
parent 3D np.array from which sub-domains will be extracted. * Any value (i.e. feature_name) in the feature data base of the current temporal slice. This is available in gstslice.fdb.keys(). Here, gstslice.feature_name will become the parent 3D np.array from which sub-domains will be extracted. * ‘user’. If the user wishes to extract sub-domains from a 3D np.array of their choice, then this allows the user to do so. This would need supplying of thr user_fid value.
user_fid (numpy.ndarray) – User supplied 3D NumPy array.
make_pvgrids (bool) – If True, PyVista grids will be made for each subdomain and returned.
- Returns:
SD –
- A dictionary containing the following key: value pairs.
’data’: list of NumPy arrays, each representing a randomly
extracted p x q x r sub-domaimn. * ‘pvgrids’: list of Py-Vista grid objects if make_pvgrids is True.
- Return type:
Examples
from upxo.ggrowth.mcgs import mcgs
pxt = mcgs(input_dashboard=’input_dashboard.xls’) pxt.simulate(verbose=False) tslice = 49 gstslice = pxt.gs[tslice] gstslice.char_morphology_of_grains(label_str_order=1,
find_grain_voxel_locs=True, find_spatial_bounds_of_grains=True, force_compute=True)
- A = gstslice.extract_subdomains_random(p=5, q=5, r=5, n=2,
feature_name=’base’, )
- make_pvgrid_v1(feature_name='base', instance_name='lgi', user_fid=None, scalar_name='lgi', pvgrid_origin=(0, 0, 0), pvgrid_spacing=(1, 1, 1), perform_checks=True)[source]
Build and return a PyVista grid.
- smoothen_sds(k=1, feature_name='base', instance_name='lgi', user_fid=None, down_order=0, down_mode='nearest', up_order=0, up_mode='nearest', make_pvgrid=False, pvgrid_scalar_name='lgi', pvgrid_origin=(0, 0, 0), pvgrid_spacing=(1, 1, 1))[source]
Smooth a fid array by scaling and descaling.
- Parameters:
k (float) – Scaling factor >= 1. Value of 1 will return the unmodified data. A value near to 1 has less effect while a value close to 0 would have greater effect.
feature_name (str) – Name of the feature. Valids include ‘base’, (‘twin’, ‘twins’, ‘tw’, ‘twinned’, ‘twinnedgs’), ‘user’, (‘paps’, ‘austenitic_packets’). It does not matter how a string is entered as in ‘twinnedgs’ or ‘twinned_gs’ or ‘twinned.gs’. If ‘user’, then user_fid will be used instead of internally available fid datasets. Note: fid stands for feature id and is/must a 3D Numpy array.
instance_name (str) – Allowed values for base grain structure, i.e. when feature_name is set to ‘base’ are ‘lgi’ (only as of present version.)
user_fid (np.ndarray) – User input value of 3D image to be used. This will only be used when feature_name is ‘user’.
make_pvgrid (bool) – If True, a pyvista uniform grid will be returned as pvgrid, else None will be returned as pvgrid.
- Returns:
fid_mod (np.ndarray) – Modified fid.
pvgrid (pv.UniformGrid() / None) – If user inputs make_pvgrid as True, then returns a pyvista uniform grid object, else returns None.
- Raises:
ValueError – If k > 1. String: k must belong to (0, 1].
ValueError – If feature_name is not ‘base’ or nort in (‘twin’, ‘twins’, ‘tw’, ‘twinned’, ‘twinnedgs’) or ‘user’. String: Invalid feature_name.
ValueError – If feature_name is in (‘twin’, ‘twins’, ‘tw’, ‘twinned’, ‘twinnedgs’) and instance_name is not in self.fdb.keys(). String: Invalid instance_name. Does’nt exist.
Example
from upxo.ggrowth.mcgs import mcgs
pxt = mcgs(input_dashboard=’input_dashboard.xls’) pxt.simulate(verbose=False) tslice = 49 gstslice = pxt.gs[tslice] gstslice.char_morphology_of_grains(label_str_order=1,
find_grain_voxel_locs=True, find_spatial_bounds_of_grains=True, force_compute=True)
- gstslice.smoothen_sds(k=1, feature_name=’base’, instance_name=’lgi’,
user_fid=None, down_order=0, down_mode=’nearest’, up_order=0, up_mode=’nearest’, make_pvgrid=False, pvgrid_scalar_name=’lgi’, pvgrid_origin=(0, 0, 0), pvgrid_spacing=(1, 1, 1),)
- deform_ortho(kx, ky, kz, feature_name='base', instance_name='lgi', user_fid=None)[source]
- kx: float
Scaling factor along x-axis.
- ky: float
Scaling factor along y-axis.
- kz: float
Scaling factor along z-axis.
- feature_name: str
Name of the feature. Valids include ‘base’, (‘twin’, ‘twins’, ‘tw’, ‘twinned’, ‘twinnedgs’), ‘user’, (‘paps’, ‘austenitic_packets’). It does not matter how a string is entered as in ‘twinnedgs’ or ‘twinned_gs’ or ‘twinned.gs’. If ‘user’, then user_fid will be used instead of internally available fid datasets. Note: fid stands for feature id and is/must a 3D Numpy array.
- instance_name: str
Allowed values for base grain structure, i.e. when feature_name is set to ‘base’ are ‘lgi’ (only as of present version.)
- user_fid: np.ndarray
User input value of 3D image to be used. This will only be used when feature_name is ‘user’.
- classmethod cubic_euler_bunge_to_matrix(phi1, Phi, phi2, degrees=True)[source]
Bunge (ZXZ): R = Rz(phi1) * Rx(Phi) * Rz(phi2).
- classmethod cubic_euler_bunge_to_matrix_v1(phi1, Phi, phi2, degrees=True, dtype=numpy.float32, validate_numpy_input=False)[source]
Computes a batch of Bunge (ZXZ) rotation matrices from arrays of Euler angles. R = Rz(phi1) * Rx(Phi) * Rz(phi2).
Parameters: - phi1, Phi, phi2: Arrays of Euler angles. - degrees (bool): If True, angles are in degrees; otherwise, radians. - dtype (np.dtype): The data type for the output rotation matrices.
Defaults to np.float32 for better performance and memory usage.
EXAMPLE - 1
from upxo.ggrowth.mcgs import mcgs pxt = mcgs(study=’independent’, input_dashboard=’demo_3d_04.xls’) pxt.simulate(verbose=False) gstslice = pxt.gs[99]
euler_angles = np.array([[10, 20, 30], [45, 60, 75]]) phi1 = euler_angles[:, 0] Phi = euler_angles[:, 1] phi2 = euler_angles[:, 2] R = gstslice.cubic_euler_bunge_to_matrix_v1(phi1, Phi, phi2) print(R)
- static cubic_rotation_angle_1(R)[source]
Return angle (rad) of a proper rotation matrix or a batch of matrices R.
Parameters: - R: A 3x3 rotation matrix or a (N, 3, 3) NumPy array of rotation matrices.
Returns: - angle (float or array): Rotation angle(s) in radians.
Example
from upxo.ggrowth.mcgs import mcgs pxt = mcgs(study=’independent’, input_dashboard=’demo_3d_04.xls’) pxt.simulate(verbose=False) gstslice = pxt.gs[99]
euler_angles = np.array([[10, 20, 30], [45, 60, 75]]) phi1 = euler_angles[:, 0] Phi = euler_angles[:, 1] phi2 = euler_angles[:, 2] R = gstslice.cubic_euler_bunge_to_matrix_v1(phi1, Phi, phi2)
cubic_rotation_angle_vec(R)
- static cubic_rotation_axis(R, angle)[source]
Return unit axis for rotation R given angle (rad). For very small angles, returns a default axis.
- static cubic_rotation_axis_v1(rstack, angles)[source]
Returns unit axis for a batch of rotations R given a batch of angles (rad). For very small angles, returns a default axis.
Parameters: - rstack: A (N, 3, 3) NumPy array of rotation matrices. - angles: A (N,) NumPy array of rotation angles in radians.
Returns: - A (N, 3) NumPy array of unit axes.
Example
from upxo.ggrowth.mcgs import mcgs pxt = mcgs(study=’independent’, input_dashboard=’demo_3d_04.xls’) pxt.simulate(verbose=False) gstslice = pxt.gs[99]
N = int(2E6) phi1 = np.random.randint(0, 90, N) Phi = np.random.randint(0, 180, N) phi2 = np.random.randint(0, 360, N) rstack = gstslice.cubic_euler_bunge_to_matrix_v1(phi1, Phi, phi2) angles = np.full((len(rstack),), 4, dtype=rstack.dtype) rotax = gstslice.cubic_rotation_axis_v1(rstack, angles)
- static cubic_symmetry_operators()[source]
24 proper rotations for m-3m as signed permutation matrices with det=+1.
Example
from upxo.ggrowth.mcgs import mcgs pxt = mcgs(study=’independent’, input_dashboard=’demo_3d_04.xls’) pxt.simulate(verbose=False) gstslice = pxt.gs[99] gstslice.cubic_symmetry_operators()
- fcc_symmetrise_ori(bea, dtype=numpy.float32)[source]
Generate symmetric equivalents of an orientation.
Example
bea = texture[‘ori_means’][‘brass’] gstslice.fcc_symmetrise_ori(bea, dtype=np.float32)
- classmethod cubic_misorientation(EA1, EA2, unique_tol_deg=0.0001, degrees=True)[source]
Vectorized fast misorientation (cubic, m-3m). Inputs: Euler triplet (phi1,Phi,phi2) OR 3x3 rotation matrix. :returns: float
axis_min : (3,) unit vector (sample frame) top3_angles_deg : list of up to 3 smallest UNIQUE angles (deg), ascending
- Return type:
angle_deg_min
Example
from upxo.ggrowth.mcgs import mcgs pxt = mcgs(study=’independent’, input_dashboard=’demo_3d_04.xls’) pxt.simulate(verbose=False) gstslice = pxt.gs[99]
N = int(10)
phi1 = np.random.randint(0, 90, N) Phi = np.random.randint(0, 180, N) phi2 = np.random.randint(0, 360, N) EA1 = np.vstack((phi1, Phi, phi2)).T
phi1 = np.random.randint(0, 90, N) Phi = np.random.randint(0, 180, N) phi2 = np.random.randint(0, 360, N) EA2 = np.vstack((phi1, Phi, phi2)).T
gA = gstslice.cubic_euler_bunge_to_matrix_v1(phi1, Phi, phi2)
- classmethod cubic_misorientation_old1(EA1, EA2, unique_tol_deg=0.0001, degrees=True)[source]
Vectorized fast misorientation (cubic, m-3m). Inputs: Euler triplet (phi1,Phi,phi2) OR 3x3 rotation matrix. :returns: float
axis_min : (3,) unit vector (sample frame) top3_angles_deg : list of up to 3 smallest UNIQUE angles (deg), ascending
- Return type:
angle_deg_min
- classmethod cubic_misorientation_old(EA1, EA2, unique_tol_deg=0.0001, degrees=True)[source]
gA, gB: 3x3 rotation matrices (Bunge convention). :returns: smallest misorientation angle (deg)
axis_min: unit axis (in sample frame) for the smallest angle
top3_angles_deg: list of the three smallest UNIQUE angles (deg), sorted
- Return type:
angle_deg_min
- assign_twins(instance_name='twin.0', vfs3=0.75, vfs5=0.25, by='volume', seed=12345)[source]
Randomly assign twins to Σ3 / Σ5 so the chosen fraction matches vfs3 / vfs5 and ensure all twins are assigned (no leftovers).
- Creates:
self.fdb[instance_name][‘data’][‘twin_id_s3’] : list[int] self.fdb[instance_name][‘data’][‘twin_id_s5’] : list[int]
- assign_orientations_from_unordered(ori_p, ori_s3, ori_s5, instance_name='twin.0', tol_deg=5.0, allow_parent_reuse=True, seed=2025)[source]
Assign unordered experimental orientations to concrete features (hosts & twins) such that Σ3 twins are ~60° from their host and Σ5 twins are ~36.87° or 53.13°.
- Writes:
data[‘ori_parent’] : {gid: (phi1,Phi,phi2)} data[‘ori_twin’] : {tid: (phi1,Phi,phi2)} data[‘ori_assign_report’] : dict
- generate_fcc_texture(N=1000, seed=numpy.random.random, shuffle=True)[source]
EXAMPLE - 1
N = 1000 gstslice.tc_info = {“copper”: [0.45, 8],
“brass”: [0.30, 10], “S”: [0.15, 7], “goss”: [0.05, 6]}
EA_p, EA_TC = gstslice.generate_fcc_texture(N)
- static standardize_tc_info(tc_info, defaults={'hw_Phi': 5, 'hw_phi1': 5, 'hw_phi2': 5, 'perctol_Phi': 5, 'perctol_phi1': 5, 'perctol_phi2': 5, 'std_k_Phi': 3, 'std_k_phi1': 3, 'std_k_phi2': 3})[source]
Standardizes a dictionary of texture component information to a consistent format.
Parameters: - tc_info (dict): The input dictionary containing texture components.
Each value can be a scalar or a list of varying length.
Returns: - dict: A new dictionary with all values standardized to the most complete format:
[percentage, [ang1, ang2, ang3], [std1, std2, std3], [k1, k2, k3]]. Default values are used to fill in missing information.
- generate_fcc_texture_v1(N=1000, distr='normal', validate_miso=False, calc_miso=True, tc_info_std_defaults={'hw_Phi': 5, 'hw_phi1': 5, 'hw_phi2': 5, 'perctol_Phi': 5, 'perctol_phi1': 5, 'perctol_phi2': 5, 'std_k_Phi': 3, 'std_k_phi1': 3, 'std_k_phi2': 3}, shuffle=False, ea_dtype=numpy.float32, miso_dtype=numpy.float16, id_dtype=numpy.int16, rand_ori_seed=numpy.random.random)[source]
# Complete structure of gstslice.tc_info is below. gstslice.tc_info = {“tc1”: [vf_tc,
[hw_phi1, hw_Phi, hw_phi2], [std_k_phi1, std_k_Phi, std_k_phi2], [perctol_phi1, perctol_Phi, perctol_phi2]],
}
- In the above,
vf_tc. Volume freaction of texture component.
[hw_phi1, hw_Phi, hw_phi2]. Half widths about mean orientation.
[std_k_phi1, std_k_Phi, std_k_phi2]. Standard deviation factor
[perctol_phi1, perctol_Phi, perctol_phi2].
The user may choose to enter it as any one of the below; or even a combination of below. Non-standard inputs willbe converted to standard input, whilst retaining valid user provided information, before use insdide this function.
Possible input for gstslice.tc_info: 1
- gstslice.tc_info = {“copper”: 0.35,
“brass”: 0.30, “S”: 0.15, “goss”: 0.05, “cube”: 0.05}
Possible input for gstslice.tc_info: 2
- gstslice.tc_info = {“copper”: [0.45, 8],
“brass”: [0.30, 10], “S”: [0.15, 7], “goss”: [0.05, 6]}
Possible input for gstslice.tc_info: 3
- gstslice.tc_info = {“copper”: [0.45, [8, 8, 8]],
“brass”: [0.30, [10, 10, 10], “S”: [0.15, [7, 7, 7]], “goss”: [0.05, [6, 6, 6]]}
Possible input for gstslice.tc_info: 4
- gstslice.tc_info = {“copper”: [0.45, [8, 8, 8], [3, 3, 3]],
“brass”: [0.30, [10, 10, 10], [3, 3, 3]], “S”: [0.15, [7, 7, 7], [3, 3, 3]], “goss”: [0.05, [6, 6, 6], [3, 3, 3]]}
Possible input for gstslice.tc_info: 5
Example standard use: gstslice.tc_info = {“copper”: [0.45, [8,8,8], [3,3,3], [5,5,5]],
“brass”: [0.30, [10,10,10], [3,3,3], [5,5,5]], “S”: [0.15, [7,7,7], [3,3,3], [5,5,5]], “goss”: [0.05, [6,6,6], [3,3,3], [5,5,5]]}
EXAMPLE - 1
from upxo.ggrowth.mcgs import mcgs pxt = mcgs(study=’independent’, input_dashboard=’demo_3d_04.xls’) pxt.simulate(verbose=False) tslice = 99 gstslice = pxt.gs[tslice] gstslice.tc_info = {“copper”: [0.35, 8], “brass”: [0.27, 10],
“s”: [0.15, 7], “goss”: [0.10, 6], “cube”: [0.05, 10]}
texture = gstslice.generate_fcc_texture_v1(N=1000)
- static normalize_euler_bunge(ea, degrees=True, eps=1e-06)[source]
- Normalize Bunge ZXZ Euler angles (phi1, Phi, phi2) to canonical ranges.
phi1, phi2 in [0, 360) deg (or [0, 2π) rad)
Phi in [0, 180] deg (or [0, π] rad)
- Handles BOTH Phi > 180 and Phi < 0 via ZXZ symmetry:
Phi’ = -Phi and (phi1’, phi2’) = (phi1+180, phi2+180) [mod 360] Phi’ = 360-Phi and same 180-shift for >180 case.
- generate_fcc_texture_v2(N=1000, distr='normal', validate_miso=False, calc_miso=True, tc_info_std_defaults={'hw_Phi': 5, 'hw_phi1': 5, 'hw_phi2': 5, 'perctol_Phi': 5, 'perctol_phi1': 5, 'perctol_phi2': 5, 'std_k_Phi': 3, 'std_k_phi1': 3, 'std_k_phi2': 3}, shuffle=False, nshuffles=2, ea_dtype=numpy.float32, miso_dtype=numpy.float16, id_dtype=numpy.int16, rand_ori_seed=numpy.random.random, rand_ori_gen_rule='relaxed', n_tex_instances=4, n_sampling_instances=4)[source]
# Complete structure of gstslice.tc_info is below. gstslice.tc_info = {“tc1”: [vf_tc,
[hw_phi1, hw_Phi, hw_phi2], [std_k_phi1, std_k_Phi, std_k_phi2], [perctol_phi1, perctol_Phi, perctol_phi2]],
}
- In the above,
vf_tc. Volume freaction of texture component.
[hw_phi1, hw_Phi, hw_phi2]. Half widths about mean orientation.
[std_k_phi1, std_k_Phi, std_k_phi2]. Standard deviation factor
[perctol_phi1, perctol_Phi, perctol_phi2].
The user may choose to enter it as any one of the below; or even a combination of below. Non-standard inputs willbe converted to standard input, whilst retaining valid user provided information, before use insdide this function.
Possible input for gstslice.tc_info: 1
- gstslice.tc_info = {“copper”: 0.35,
“brass”: 0.30, “s”: 0.15, “goss”: 0.05, “cube”: 0.05}
Possible input for gstslice.tc_info: 2
- gstslice.tc_info = {“copper”: [0.45, 8],
“brass”: [0.30, 10], “s”: [0.15, 7], “goss”: [0.05, 6]}
Possible input for gstslice.tc_info: 3
- gstslice.tc_info = {“copper”: [0.45, [8, 8, 8]],
“brass”: [0.30, [10, 10, 10], “s”: [0.15, [7, 7, 7]], “goss”: [0.05, [6, 6, 6]]}
Possible input for gstslice.tc_info: 4
- gstslice.tc_info = {“copper”: [0.45, [8, 8, 8], [3, 3, 3]],
“brass”: [0.30, [10, 10, 10], [3, 3, 3]], “s”: [0.15, [7, 7, 7], [3, 3, 3]], “goss”: [0.05, [6, 6, 6], [3, 3, 3]]}
Possible input for gstslice.tc_info: 5
Example standard use: gstslice.tc_info = {“copper”: [0.45, [8,8,8], [3,3,3], [5,5,5]],
“brass”: [0.30, [10,10,10], [3,3,3], [5,5,5]], “s”: [0.15, [7,7,7], [3,3,3], [5,5,5]], “goss”: [0.05, [6,6,6], [3,3,3], [5,5,5]]}
EXAMPLE - 1
from upxo.ggrowth.mcgs import mcgs pxt = mcgs(study=’independent’, input_dashboard=’demo_3d_04.xls’) pxt.simulate(verbose=False) tslice = 99 gstslice = pxt.gs[tslice] gstslice.char_morphology_of_grains(label_str_order=1,
find_grain_voxel_locs=False, find_neigh=[True, [1], False, ‘1-no’], find_spatial_bounds_of_grains=False, force_compute=True, set_mprops=False, mprops_kwargs={‘set_skimrp’: False,
‘volnv’: True, ‘solidity’: False, ‘sanv’: False, ‘rat_sanv_volnv’: False})
- gstslice.tc_info = {“copper”: [0.35, 8], “brass”: [0.27, 10],
“s”: [0.15, 7], “goss”: [0.10, 6], “cube”: [0.05, 10]}
- TEX = gstslice.generate_fcc_texture_v2(N=gstslice.n, distr=’normal’,
validate_miso=False, calc_miso=True, tc_info_std_defaults={
‘hw_phi1’: 5, ‘hw_Phi’: 5, ‘hw_phi2’: 5, ‘std_k_phi1’: 3, ‘std_k_Phi’: 3, ‘std_k_phi2’: 3, ‘perctol_phi1’: 5, ‘perctol_Phi’: 5, ‘perctol_phi2’: 5},
shuffle=False, nshuffles=2, ea_dtype=np.float32, miso_dtype=np.float16, id_dtype=np.int16, rand_ori_seed=np.random.random(), rand_ori_gen_rule=’relaxed’, n_tex_instances=1, n_sampling_instances=1)
# VALIDATION ngrains = gstslice.n noritc = [len(v) for v in TEX[‘tex_instance.1’][‘sampling_instances’][‘ossi.1’][‘tc_ori_stacks’].values()] ngrains == sum(noritc)
- tc_ori_stack_subset(ori_stack=None, id_dict={'brass': [], 'copper': [], 'cube': [], 'goss': [], 'random': [], 's': []}, invert_ids=True)[source]
Return the texture-component orientation stack subset.
- choose_TC(tiname='tex_instance.1', siname='ossi.1', tc_ori_stacks=None, ntgrains=None, ntgrains_level=1)[source]
Choose texture components to associate with non-touching O(1) grains.
- Parameters:
tiname (str) – Texture instance name
siname (str) – sampling instance name
tc_ori_stacks (dict) – Texture component orientation stacks. Stacks of orientations drawn uniformly randomly from the collection of all 24 symmetric equivalents of every orientation belonging to a texture component. Keys contain name of the texture component. Value contains numpy array of corresponding crystallographci orienrtations.
ntgrains
=======================================================================
'tex_instance.1' (tiname =)
'ossi.1' (siname =)
1 (EXAMPLE -)
-----------
mcgs (from upxo.ggrowth.mcgs import)
mcgs(study='independent' (pxt =)
input_dashboard='demo_3d_04.xls')
pxt.simulate(verbose=False)
99 (tslice =)
pxt.gs[tslice] (gstslice =)
gstslice.char_morphology_of_grains(label_str_order=1 –
find_grain_voxel_locs=False, find_neigh=[True, [1], False, ‘1-no’], find_spatial_bounds_of_grains=False, force_compute=True, set_mprops=False, mprops_kwargs={‘set_skimrp’: False,
’volnv’: True, ‘solidity’: False, ‘sanv’: False, ‘rat_sanv_volnv’: False})
- :paramfind_grain_voxel_locs=False,
find_neigh=[True, [1], False, ‘1-no’], find_spatial_bounds_of_grains=False, force_compute=True, set_mprops=False, mprops_kwargs={‘set_skimrp’: False,
‘volnv’: True, ‘solidity’: False, ‘sanv’: False, ‘rat_sanv_volnv’: False})
- Parameters:
{"copper" (gstslice.tc_info =) – “s”: [0.15, 7], “goss”: [0.10, 6], “cube”: [0.05, 10]}
gstslice.generate_fcc_texture_v2(N=gstslice.n (TEX =) –
validate_miso=False, calc_miso=True, tc_info_std_defaults={
’hw_phi1’: 5, ‘hw_Phi’: 5, ‘hw_phi2’: 5, ‘std_k_phi1’: 3, ‘std_k_Phi’: 3, ‘std_k_phi2’: 3, ‘perctol_phi1’: 5, ‘perctol_Phi’: 5, ‘perctol_phi2’: 5},
shuffle=False, nshuffles=2, ea_dtype=np.float32, miso_dtype=np.float16, id_dtype=np.int16, rand_ori_seed=np.random.random(), rand_ori_gen_rule=’relaxed’, n_tex_instances=1, n_sampling_instances=1)
distr='normal' –
validate_miso=False, calc_miso=True, tc_info_std_defaults={
’hw_phi1’: 5, ‘hw_Phi’: 5, ‘hw_phi2’: 5, ‘std_k_phi1’: 3, ‘std_k_Phi’: 3, ‘std_k_phi2’: 3, ‘perctol_phi1’: 5, ‘perctol_Phi’: 5, ‘perctol_phi2’: 5},
shuffle=False, nshuffles=2, ea_dtype=np.float32, miso_dtype=np.float16, id_dtype=np.int16, rand_ori_seed=np.random.random(), rand_ori_gen_rule=’relaxed’, n_tex_instances=1, n_sampling_instances=1)
- :paramvalidate_miso=False,
calc_miso=True, tc_info_std_defaults={
‘hw_phi1’: 5, ‘hw_Phi’: 5, ‘hw_phi2’: 5, ‘std_k_phi1’: 3, ‘std_k_Phi’: 3, ‘std_k_phi2’: 3, ‘perctol_phi1’: 5, ‘perctol_Phi’: 5, ‘perctol_phi2’: 5},
shuffle=False, nshuffles=2, ea_dtype=np.float32, miso_dtype=np.float16, id_dtype=np.int16, rand_ori_seed=np.random.random(), rand_ori_gen_rule=’relaxed’, n_tex_instances=1, n_sampling_instances=1)
- crop_neigh_gid(neigh_gid='O(1)', gids_to_crop=None)[source]
Removes guids in gids_to_crop from neighbour order dictionary.
Both keys and appearences in values get removed.
- Parameters:
neigh_gid (str | dict) – Neighbour gid dictionary. If a string liuke ‘O(1)’ is entered, then the corresponding will be extracted. Idf the neighbour does not exist, the method should rauise an error and stop. If the value is dictionary, then entered value will be used without any validations. Defaults to ‘O(1)’.
gids_to_crop (dth.dt.ITERABLES | integer) – Grain ids to be cropped from neigh_gid. Value could be any in dth.dt.ITERABLES or of any integrer type in dth.dt.INTEGERS. Defaults to None.
Example
gstlice.crop_neigh_gid(neigh_gid=’O(1)’, gids_to_crop=[1])
‘’’ Development: a = {1: [3, 4, 5, 6, 2], 2: [1, 3, 5, 6, 4],
3: [2, 1, 5, 7, 8], 4: [1, 2, 9, 6]}
gids_to_crop = [2, 3, 10] for gidcrop in gids_to_crop:
- if gidcrop in a.keys():
a.pop(gidcrop)
gids_to_crop = set(gids_to_crop) for gid in a.keys():
a[gid] = set(a[gid]) a[gid] = a[gid] - gids_to_crop a[gid] = list(a[gid])
# Expected value of a: a = {1: [4, 5, 6], 4: [1, 9, 6]}’’’
- map_ori(TEXdb, texture_instance=1, sampling_instance=1, tc_ori_stacks=None, ntex_map_instances_L0=3, ntex_map_instances_L1=2, shuffle_ori_stack_bf_L1Map=True)[source]
texture_instance=1 sampling_instance=1 ntex_map_instances_L0=3 ntex_map_instances_L1=2 shuffle_ori_stack_bf_L1Map=True
tiname = ‘tex_instance.’ + str(texture_instance) siname = ‘ossi.’ + str(sampling_instance) TEXdb = TEX tc_ori_stacks = TEXdb[tiname][‘sampling_instances’][siname][‘tc_ori_stacks’]
PRE EXAMPLE
from upxo.ggrowth.mcgs import mcgs pxt = mcgs(study=’independent’, input_dashboard=’demo_3d_04.xls’) pxt.simulate(verbose=False) tslice = 99 gstslice = pxt.gs[tslice] gstslice.char_morphology_of_grains(label_str_order=1,
find_grain_voxel_locs=False, find_neigh=[True, [1], False, ‘1-no’], find_spatial_bounds_of_grains=False, force_compute=True, set_mprops=False, mprops_kwargs={‘set_skimrp’: False,
‘volnv’: True, ‘solidity’: False, ‘sanv’: False, ‘rat_sanv_volnv’: False})
- gstslice.tc_info = {“copper”: [0.35, 8], “brass”: [0.27, 10],
“s”: [0.15, 7], “goss”: [0.10, 6], “cube”: [0.05, 10]}
- TEX = gstslice.generate_fcc_texture_v2(N=gstslice.n, distr=’normal’,
validate_miso=False, calc_miso=True, tc_info_std_defaults={
‘hw_phi1’: 5, ‘hw_Phi’: 5, ‘hw_phi2’: 5, ‘std_k_phi1’: 3, ‘std_k_Phi’: 3, ‘std_k_phi2’: 3, ‘perctol_phi1’: 5, ‘perctol_Phi’: 5, ‘perctol_phi2’: 5},
shuffle=False, nshuffles=2, ea_dtype=np.float32, miso_dtype=np.float16, id_dtype=np.int16, rand_ori_seed=np.random.random(), rand_ori_gen_rule=’relaxed’, n_tex_instances=1, n_sampling_instances=1)
EXAMPLE - 1
- get_ks_rotations()[source]
Returns the 24 Kurdjumov-Sachs (K-S) orientation relationship operators as 3x3 rotation matrices.
- assign_pag_and_grain_orientations(clusters_dict, neigh_clid, orientation_pool, HAGB_threshold=15.0)[source]
Assigns parent FCC orientations to clusters (PAGs) and final BCC orientations to individual grains.
- verify_hagb_constraint(pag_orientations, neigh_clid, HAGB_threshold=15.0)[source]
Verifies that all adjacent PAGs meet the HAGB misorientation constraint.
- Parameters:
- Returns:
A list of violation tuples. Each tuple contains (pag_id_1, pag_id_2, calculated_misorientation). An empty list signifies success.
- Return type:
- plot_100_pole_figure(euler_angles_deg, title='')[source]
Creates a basic {100} pole figure scatter plot.
- Parameters:
euler_angles_deg (ndarray) – An (N, 3) array of Bunge Euler angles in degrees.
title (str, optional) – The title for the plot.
- plot_pag_ks_verification(pag_id_to_check, parent_fcc_ea, child_grain_eulers, title='')[source]
Creates a {100} pole figure to verify the K-S relationship for one PAG.
- Parameters:
- plot_pag_ks_verification_v1(pag_id_to_check, parent_fcc_ea, child_grain_eulers, title='')[source]
Creates a {100} pole figure to verify the K-S relationship for one PAG.
- plot_pag_ks_verification_v2(pag_id_to_check, parent_fcc_ea, child_grain_eulers, title='')[source]
Creates a {100} pole figure to verify the K-S relationship for one PAG, including the parent FCC orientation.
- plot_pag_ks_verification_v3(pag_ids_to_plot, pag_orientations, clusters_dict, grain_orientations, grid_dims=(2, 3))[source]
Creates a grid of {100} pole figures to verify the K-S relationship for multiple PAGs, including the parent FCC orientation for each.
- euler_to_ipf_color_old(euler_angles_deg, sample_direction=[0, 0, 1])[source]
Calculates the IPF-Z color for a single orientation in Bunge Euler angles.
- Parameters:
euler_angles_deg (array-like) – A (3,) array of Bunge Euler angles (phi1, Phi, phi2) in degrees.
euler_to_matrix_func (callable) – Reference to your function that converts Euler angles to a rotation matrix.
- Returns:
An (R, G, B) tuple with values in the range [0, 1].
- Return type:
- euler_to_ipf_color(euler_angles_deg, sample_direction=numpy.array)[source]
Calculates the standard IPF color for a single orientation. This is a robust version guaranteed to produce valid RGB values.
- plot_ipf_map_pyvista_v1(grain_orientations, sample_direction=[0, 0, 1], downsample_factor=1.0, voxel_size=1.0, opacity=0.8, show_edges=False)[source]
Creates and displays a 3D IPF map with solid voxels using PyVista.
- Parameters:
grain_orientations (dict) – {grain_id: (3,) array of Bunge Euler angles}.
downsample_factor (float, optional) – Factor to reduce the number of voxels for faster plotting (e.g., 0.1 for 10%).
voxel_size (float, optional) – The side length of the cube used to represent each voxel.
opacity (float, optional) – The opacity (alpha) of the rendered grains, from 0.0 to 1.0.
- plot_ipf_map_pyvista_v2(grain_orientations, gids_to_plot=None, sample_direction=[0, 0, 1], downsample_factor=1.0, voxel_size=1.0, opacity=0.8, show_edges=False)[source]
Creates and displays a 3D IPF map for selected grains using PyVista.
- Parameters:
grain_orientations (dict) – {grain_id: (3,) array of Bunge Euler angles}.
gids_to_plot (list, tuple, or np.array, optional) – A collection of grain IDs to plot. If None or empty, all grains in self.grain_locs will be plotted. Default is None.
downsample_factor (float, optional) – Factor to reduce the number of voxels for faster plotting.
voxel_size (float, optional) – The side length of the cube used to represent each voxel.
opacity (float, optional) – The opacity (alpha) of the rendered grains, from 0.0 to 1.0.
show_edges (bool, optional) – If True, displays the edges of each voxel. Defaults to False.
- plot_pag_map_pyvista(clusters_dict, gids_to_plot=None, downsample_factor=1.0, voxel_size=1.0, opacity=1.0, show_edges=False)[source]
Creates and displays a 3D PAG map using PyVista, coloring grains by their parent PAG ID.
- Parameters:
clusters_dict (dict) – {pag_id: [list_of_grain_ids]}.
gids_to_plot (list, optional) – A collection of grain IDs to plot. If None, all grains are plotted.
downsample_factor (float, optional) – Factor to reduce the number of voxels for faster plotting.
voxel_size (float, optional) – The side length of the cube used to represent each voxel.
opacity (float, optional) – The opacity of the rendered grains.
show_edges (bool, optional) – If True, displays the edges of each voxel.
- cluster_grains(neigh_gid, tcs=[1, 3, 4, 6, 7], tcp=[0.05, 0.25, 0.5, 0.15, 0.05])[source]
Partitions an existing grain structure into new clusters using networkx for improved readability and maintenance.
- Parameters:
neigh_gid (dict) – Dictionary with grain IDs as keys and lists of neigh IDs as values.
tcs (list or tuple of int) – Target Cluster Sizes. A list of possible grain counts of clusters (e.g., [3, 4, 6]).
tcp (list or tuple of float) – Target Cluster probanilities. The probability associated with each size. Must sum to 1.0.
- Returns:
A new dictionary of cluster IDs and the grain IDs they contain.
- Return type:
Example
neigh_gid = gstslice.neigh_gid target_sizes = [1, 3, 4, 6, 7] target_probs = [0.05, 0.25, 0.50, 0.15, 0.05]
- clusters = gstslice.cluster_grains(neigh_gid=neigh_gid,
tcs=target_sizes, tcp=target_probs)
- generate_neigh_clid(neigh_gid, tcs=[1, 3, 4, 6, 7], tcp=[0.05, 0.25, 0.5, 0.15, 0.05])[source]
Generate neighbouring cluster ID adjacency informatio. Generates a cluster adjacency dictionary (neigh_clid) from grain clusters and a grain adjacency dictionary (neigh_gid).
- Parameters:
- Returns:
A new dictionary, neigh_clid, mapping {cluster_id: [list_of_neighbor_cluster_ids]}.
- Return type:
- generate_neigh_clid_instances(neigh_gid, tcs=[1, 3, 4, 6, 7], tcp=[0.05, 0.25, 0.5, 0.15, 0.05], ninstances=1)[source]
Generate neighbour CIDs instances.
- build_cluster_adjacency(neigh_gid: Mapping[int, Iterable[int]], *, enforce_undirected: bool = True, as_sorted_lists: bool = True)[source]
Construct a PAG-level (cluster-level) adjacency map.
- Parameters:
cluster_id (Mapping[int, Iterable[int]]) – {cluster_id: iterable_of_grain_ids}. Each grain should belong to exactly one cluster.
neigh_gid (Mapping[int, Iterable[int]]) – {grain_id: iterable_of_neighbor_grain_ids}. Interpreted as an undirected adjacency; will be symmetrized if enforce_undirected=True.
enforce_undirected (bool, default True) – If True, symmetrize both the grain-level adjacency (neigh_gid) and the resulting cluster-level adjacency so that A ∈ N(B) ⇔ B ∈ N(A).
as_sorted_lists (bool, default True) – If True, return neighbors as sorted lists. If False, return sets.
- Returns:
cluster_adj – {cluster_id: neighbors}, where neighbors are the IDs of adjacent clusters (i.e., there exists at least one grain in cluster A that is a neighbor of at least one grain in cluster B, B≠A).
- Return type:
Notes
Self-adjacency is never added.
Grains present in neigh_gid but not found in cluster_id are ignored.
A cluster will appear with an empty neighbor list/set if it has no inter-cluster contacts (possible in degenerate cases, e.g., a single cluster covering all grains, or if the provided cluster_id/neigh_gid are inconsistent).
- slice_packet_into_blocks(packet_gid, cluster_id, voxel_coords, block_thickness, slicing_plane, global_block_id_start=0)[source]
Slices a single packet into multiple, contiguous blocks.
This method uses a hybrid geometric and connectivity-based approach to partition the voxel cloud of a single packet into smaller, contiguous domains representing martensitic blocks.
- Parameters:
packet_gid (int) – The ID of the parent packet (original grain ID).
cluster_id (int) – The ID of the parent cluster (PAG).
voxel_coords (ndarray) – An (N, 3) array of voxel coordinates for this packet.
block_thickness (float) – The desired thickness of the blocks in the same units as the coords.
slicing_plane (Plane) – A Plane object from the Plane class, defining the orientation of the slices.
global_block_id_start (int) – The starting number for the globally unique block IDs.
- Returns:
tuple –
dict: A dictionary of new blocks: {block_id: voxel_array}.
int: The next available global block ID after this operation.
Algorithm
———
1. Define Slicing Planes (The spatial extent of the packet’s voxels) – is calculated along the normal of the slicing_plane. A stack of parallel planes is then generated to span this entire extent, with the spacing between planes equal to block_thickness.
2. Iterate Through Slabs (The function loops through each “slab,”) – which is the region between two adjacent planes in the stack.
3. Isolate & Find Connected Components (For each slab, all voxels) – within its boundaries are isolated. To find contiguous groups within this subset, a temporary 3D boolean grid is created. The scipy.ndimage.label function is then used on this grid to find and number all separate, contiguous groups of voxels. Each group represents a block.
4. Assign Block IDs and Store (Each component identified by label) – is assigned a unique block ID according to the convention ‘B_CLUSTERID_PACKETID_LOCALID’. The new block and its voxel coordinates are stored.
5. Cleanup (Future Scope) (A final step can be added after the loop) – to assign any unassigned voxels (due to edge cases) to their nearest block, ensuring a complete partition.
- test_single_packet_slicing(clset, test_packet_id=None)[source]
Runs the block generation and visualization for a single packet.
- generate_all_packet_slicing_options(clusters_dict, pag_orientations)[source]
Generates and stores all four possible slicing planes for every packet.
This function iterates through all packets, finds their parent PAG, and calls a helper to calculate the four crystallographically-derived slicing planes.
- Returns:
A dictionary where each key is a packet_gid and the value is a list of four possible Plane objects for slicing. {packet_gid: [Plane1, Plane2, Plane3, Plane4]}
- Return type:
- get_slicing_planes_for_packet(pag_id, pag_orientations)[source]
Calculates the four possible crystallographic slicing planes for a packet based on its parent PAG’s orientation.
- generate_blocks_for_packet(packet_gid, clusters_dict, pag_orientations, block_thickness)[source]
Generates a dictionary of blocks for a single specified packet.
… (Parameters section remains the same) …
- Returns:
dict: A dictionary of new blocks: {block_id: voxel_array}.
Plane: The Plane object that was used for slicing.
- Return type:
- visualize_blocks_in_packet(blocks_dict, packet_gid=None, voxel_size=1.0, opacity=1.0)[source]
Visualizes a dictionary of blocks using PyVista.
- assign_orientations_to_blocks_old(pag_id, blocks_dict, pag_orientations)[source]
Assigns a physically realistic BCC orientation to each block in a dict and runs a verification check on the result.
- assign_orientations_to_blocks(pag_id, blocks_dict, pag_orientations)[source]
Assigns a physically realistic BCC orientation to each block in a dict.
- visualize_blocks_ipf_map(blocks_dict, block_orientations, packet_gid=None, voxel_size=1.0, opacity=1.0, show_edges=False, sample_direction=[0, 0, 1])[source]
Visualizes the IPF map of all blocks within a single packet.
- Parameters:
blocks_dict (dict) – Dictionary of blocks for a single packet: {block_id: voxel_array}.
block_orientations (dict) – Dictionary mapping each block_id to its (phi1, Phi, phi2) Euler angles.
packet_gid (int, optional) – The ID of the parent packet, used for the plot title.
voxel_size (float, optional) – The side length of the cube used to represent each voxel.
opacity (float, optional) – The opacity of the rendered blocks.
show_edges (bool, optional) – If True, displays the edges of each voxel.
sample_direction (list, optional) – The sample direction for the IPF coloring (e.g., [0,0,1] for Z).
NOTES –
This plot reveals the internal crystallographic structure of a single packet. Since all blocks within a packet are assigned variants from the same K-S group, their orientations are similar but not identical.
Expect to see the packet colored in closely related shades. For example, you might see several blocks colored in different shades of blue and purple, but you would not expect to see a bright red block right next to a bright green one within the same packet. This visual clustering of colors confirms the physical model is working correctly.
- generate_and_orient_all_blocks(clset, pag_orientations, block_thickness)[source]
Main orchestrator to generate and assign orientations to all blocks in an entire microstructure.
- visualize_block_morphology(blocks_dict, title='Block Morphology', voxel_size=1.0, opacity=1.0, cmap='nipy_spectral')[source]
Visualizes a dictionary of blocks using random colors to show morphology.
- visualize_block_morphology_v1(blocks_dict, title='Block Morphology', voxel_size=1.0, opacity=1.0, cmap='nipy_spectral')[source]
Visualizes a dictionary of blocks using integer Block IDs as scalar data to show morphology and includes a color bar.
- visualize_block_ipf_map(blocks_dict, block_orientations, title='Block IPF Map', voxel_size=1.0, opacity=1.0, sample_direction=[0, 0, 1])[source]
Visualizes the IPF map of a collection of blocks.
- calculate_pag_sizes(clusters_dict, packet_to_blocks_map, all_blocks_dict)[source]
Calculates the size of each PAG in number of voxels. # — Usage —
# pag_sizes_dict = calculate_pag_sizes(clusters_dict, packet_map, all_blocks) # plot_distribution(list(pag_sizes_dict.values()), # title=”PAG Size Distribution”, # xlabel=”Size (Number of Voxels)”)
- calculate_packets_per_pag(clusters_dict)[source]
Calculates the number of packets contained within each PAG. # — Usage — # packets_per_pag_dict = calculate_packets_per_pag(clusters_dict) # plot_distribution(list(packets_per_pag_dict.values()), # title=”Distribution of Packets per PAG”, # xlabel=”Number of Packets”)
- calculate_blocks_per_packet(packet_to_blocks_map)[source]
Calculates the number of blocks contained within each packet.
# — Usage — # blocks_per_packet_dict = calculate_blocks_per_packet(packet_map) # plot_distribution(list(blocks_per_packet_dict.values()), # title=”Distribution of Blocks per Packet”, # xlabel=”Number of Blocks”)
- calculate_block_morphology(all_blocks_dict)[source]
Calculates the approximate thickness and aspect ratio for each block.
This is a more advanced function that uses Principal Component Analysis (PCA) on each block’s voxel cloud to determine its principal dimensions, which we use for thickness and aspect ratio.
# — Usage — # morphology_data = calculate_block_morphology(all_blocks) # thicknesses = [data[‘thickness’] for data in morphology_data.values()] # aspect_ratios = [data[‘aspect_ratio’] for data in morphology_data.values()]
# plot_distribution(thicknesses, “Block Thickness Distribution”, “Approx. Thickness (Arbitrary Units)”) # plot_distribution(aspect_ratios, “Block Aspect Ratio Distribution”, “Aspect Ratio (Longest / Shortest Axis)”)
- generate_block_neighbors(all_blocks_dict)[source]
Generates a block adjacency dictionary from the voxel data.
- calculate_all_block_misorientations(block_neighbors, block_orientations)[source]
Calculates the misorientation angle for all adjacent block pairs. # — Usage — block_neighbors = generate_block_neighbors(all_blocks) misorientation_data = calculate_all_block_misorientations(block_neighbors, all_block_orientations, gstslice.cubic_misorientation) plot_distribution(misorientation_data, “Block Boundary Misorientation Distribution”, “Misorientation Angle (Degrees)”, bins=90)
- display_key_statistics(data, name)[source]
Calculates and prints key statistics for a given dataset.
- extract_block_interfaces_and_neighbors(all_blocks_dict, block_orientations)[source]
Identifies block interfaces and generates: 1. A detailed map of interface voxels grouped by the two adjacent blocks,
where each value is a single NumPy array (N, 3).
A single NumPy array containing all unique boundary voxel coordinates.
- Parameters:
- Returns:
dict: {BlockA__BlockB: ndarray(N, 3) of BlockA_interface_voxels}
ndarray: (M, 3) NumPy array of all unique boundary voxel coordinates.
- Return type:
- visualize_all_boundaries(all_boundary_voxels_array, voxel_size=1.0)[source]
Visualizes all unique block boundary voxels as a single point cloud.
- Parameters:
all_boundary_voxels_array (ndarray) – (N, 3) NumPy array of all unique boundary voxel coordinates.
voxel_size (float) – The size of a single voxel (for scaling the plot).
- visualize_interface_map_fast(interface_map, voxel_size=1.0)[source]
Visualizes the block boundaries using an optimized batching approach (pv.MultiBlock) for much faster rendering, coloring each unique interface segment with a distinct color.
- map_block_ids_to_integers(all_blocks_dict)[source]
Assigns a unique, sequential integer ID to every string-based Block ID in the provided dictionary.
- generate_integer_block_map(all_blocks_dict, block_name_ID_map, lgi)[source]
Creates a 3D NumPy array of the RVE size, where each voxel contains the unique integer ID corresponding to the crystallographic block it belongs to.
- Parameters:
- Returns:
ndarray
- Return type:
A 3D array (Z, Y, X) containing the integer Block IDs (1, 2, 3…).
- generate_integer_cluster_map(clusters_dict, lgi)[source]
Creates a 3D NumPy array of the RVE size, where each voxel contains the unique integer ID corresponding to the parent PAG (Cluster ID) it belongs to.
- Parameters:
clusters_dict (dict) – The PAG-to-Packet map: {PAG_ID: [Packet_ID_1, Packet_ID_2, …]}
lgi (ndarray) – The 3D array (self.lgi) where values are Packet IDs.
- Returns:
ndarray
- Return type:
A 3D array (Z, Y, X) containing the integer PAG IDs.
- generate_euler_angle_3d_maps(all_blocks_dict, block_orientations, lgi)[source]
Creates three 3D NumPy arrays (phi1, Phi, phi2) of the RVE size, mapping the Bunge Euler angles to every voxel based on block assignment.
- Parameters:
- Returns:
tuple – Three 3D arrays (Z, Y, X) containing the Euler angle components.
- Return type:
(phi1_map_3D, Phi_map_3D, phi2_map_3D)
- plot_pvgrid(pvgrid, scalar, show_edges=False, alpha=1.0, title='', cmap='nipy_spectral', _xname_='', _yname_='', _zname_='')[source]
Visualise pvgrid using Matplotlib or PyVista.
- mesh_C3D8_V1(feature_ids_array, material_data, output_filename='abaqus_voxel_mesh.inp')[source]
Generates node coordinates, element connectivity, and element sets for a C3D8 hexahedral mesh based on a 3D NumPy array of feature IDs.
- write_abaqus_sections_materials(f, unique_feature_ids, material_data)[source]
Generate
*MATERIALand*SOLID SECTIONdefinitions.
- write_abaqus_inp(filename, node_data, element_data, elset_map, unique_feature_ids, material_data)[source]
Format and write the data to an Abaqus
.inpfile.
- find_interface_voxels_3D()[source]
Identifies voxels belonging to Grain Boundary Surfaces (GBS) by checking all 6 face-sharing neighbors in the 3D array, storing the (i, j, k) coordinates.
- Parameters:
lgi_array (np.ndarray) – The 3D array of voxel GIDs (Grain IDs).
- Returns:
- A dictionary where keys are “gbs_GID_A_GID_B” and values are
lists of (i, j, k) tuples representing the voxel coordinates.
- Return type:
defaultdict
- visualize_interface_voxels(interface_map, cmap_name='nipy_spectral')[source]
Visualizes ONLY the interface voxels, omitting the bulk material, highlighting them using PyVista.
- visualize_interface_voxels_v1(interface_map, cmap_name='nipy_spectral', target_gids=None)[source]
Visualizes ONLY the interface voxels, filtering by specific GIDs requested by the user.
- Parameters:
lgi_array (np.ndarray) – The 3D array of voxel GIDs (Grain IDs).
interface_map (dict) – Dictionary of interface voxels (coords).
cmap_name (str, optional) – The name of the PyVista/Matplotlib colormap to use. Defaults to ‘nipy_spectral’.
target_gids (list, optional) – A list of integer GIDs to focus on. Only interfaces involving these GIDs will be plotted. If None, all interfaces are plotted.
- mesh_fm_steel_C3D8(lbi_array, material_properties, all_data, output_filename='fm_steel_C3D8.inp')[source]
Generates a C3D8 linear hexahedral mesh specifically for the FM Steel microstructure, including all hierarchical element sets and orientations.
This function acts as an orchestrator for the C3D8 meshing process.
- Parameters:
lbi_array (ndarray) – 3D NumPy array where each voxel contains its unique integer Block ID.
material_properties (dict) – Dictionary with material constants, e.g., {‘YOUNGS’: 2e11, ‘POISSON’: 0.3}.
all_data (dict) – A dictionary containing all necessary hierarchical data from the microstructure generation, including ‘packet_elsets’, ‘pag_elsets’, and ‘block_orientations’.
output_filename (str) – The name of the .inp file to be created.
- binaryStructure3D
- vox
- spart_flag
- s_gid
- gid_s
- s_n
- positions
- prop_flag
- prop
- prop_stat
- lgi_slice
- feat_locs
- spbound
- spboundex
- gid_imap_keys
- gid_imap
- no_gid
- noth_gid
- Lgbp_all
- Ggbp_all
- gbpstack
- gbpids
- gbp_id_maps
- gbp_ids
- gid_pair_ids
- gid_pair_ids_rev
- gid_pair_ids_unique_lr
- gid_pair_ids_unique_rl
- gbsurf_pids_vox
- gid_pair_gbp_IDs
- gid_pair_gbp_coords
- gid_gpid
- triples
- cluster_sets