upxo.ggrowth.mcgs module
- class upxo.ggrowth.mcgs.grid(study='independent', input_dashboard='input_dashboard.xls', consider_NLM_b=False, consider_NLM_d=False, AR_teevrate=0, AR_GrainAxis='-45', display_messages=True)[source]
Bases:
objectDescription
This is a core UPXO > mcgs class.
Dependencies
- Parent class for:
mcgs class
Slots
__ui: DICT: User input (ui) dict uigrid: CLASS: ui: gridding parameters uisim: CLASS: ui: simulation par uigsc: CLASS: ui: grain strucure characterisation par uiint: CLASS: ui: intervals uigsprop: CLASS: ui: grain str property calculation par uigeorep: CLASS: ui: geometric representations cacl par _mcsteps_: LIST: stores history of mcsteps __g__: DICT: base dict template for grains __gprop__: DICT: base dict template for grain properties __gb__: DICT: base dict template for grain boundaries __gbprop__: DICT: base dict template for grain boundary properties g: DICT: Grains @latest mcstep m: LIST: available temporal slices xgr: np.ndarray: ygr: np.ndarray: zgr: np.ndarray: NL_dict: dict: Specifies Non-Locality detasils px_length: Iterable: Side lengths of the pixel px_size:, Area or volume of the pixel S: np.ndarray: State matrix sa: State martix modified enable fast consideration of
Wrapped Boundary Condition
vis: Stores instant of awrtwork class AIA: np.ndarray: Appended Index Array (@dev) AIA0: np.ndarray: Appended Index Array (@dev) AIA1: np.ndarray: Appended Index Array (@dev) xind: np.ndarray: xindices (3D only) yind: np.ndarray: yindices (3D only) zind: np.ndarray: zindices (3D only) xinda: np.ndarray: appended xindices (3D only) yinda: np.ndarray: appended yindices (3D only) zinda: np.ndarray: appended zindices (3D only) NLM_nd: np.ndarray: Non-Locality matrix NLM: np.ndarray: Non-locality matrix EAPGLB: PRIMARY GLOBAL Euler angle Definition – state wise. EASGLB: SSECONDARY GLOBAL Euler angle definition – state wise.
Different from EAPGLB in that adjustments that happen to EAPGLB are carried out here and not in the proimary list. This is NOT available at the grid level but at the grain structure level.
- characterization_ID = 0
- characterization_settings = None
- study
- uigrid
- uisim
- uigsc
- uiint
- uigsprop
- uigeomrepr
- uimesh
- uidata_all
- dt_dict
- initiate(consider_NLM_b=False, consider_NLM_d=False, AR_teevrate=0, AR_GrainAxis='-45', display_messages=True)[source]
Initiate the grain structure object.
- Parameters:
consider_NLM_b (bool, optional) – Whether to consider Non-Local Matrix of Booleans. The default is False.
consider_NLM_d (bool, optional) – Whether to consider Non-Local Matrix of Distance measures. The default is False.
AR_teevrate (float, optional) – Aspect ratio teev rate. The default is 0.
AR_GrainAxis (str, optional) – Aspect ratio grain axis. The default is “-45”.
display_messages (bool, optional) – Whether to display messages. The default is True.
- build_original_coordinate_grid()[source]
This sets up the original coordinate grid. Original Coordinate Grid: DESCRIPTION OCG inputs
dim : Dimensionality of the grid
xmin : Minimum x co-ordinate
xmax : Maximum x co-ordinate
xinc : x co-ordinate increment
ymin : Minimum y co-ordinate
ymax : Maximum y co-ordinate
yinc : y co-ordinate increment
zmin : Minimum z co-ordinate
9. zmax : Maximum z co-ordinate 10.zinc : z co-ordinate increment
- OCG outputs
xgr : x co-ordinate grid
ygr : y co-ordinate grid
zgr : z co-ordinate grid
- Return type:
None.
- build_original_state_matrix()[source]
This sets up the Q-state matrix.
Original State Matrix: DESCRIPTION OSM inputs
S : No. of orientation states
- OCG_SizeSize of the original
coordinate grid: a 3 element list
- OSM outputs
S : orientation state matrix
S_sz0 : dim0 len of S
S_sz1 : dim1 len of S
S_sz2 : dim2 len of S
Svec : S in single row format. IS THIS STILL NEEDED???
- Return type:
None.
- build_non_locality_matrix()[source]
Construct the non-locality matrix used in some Monte-Carlo simulation.
- Return type:
None.
- IntRules()[source]
Input arguments [*] ~~Kineticity~~
- Nature of partition evolution in Euclidean space
- OPTIONS: all lower case
(“static”, “s”) (“kinetic0”, “k0”) – Default kinetic
- [*] ~~Dimensionality~~
- Number of fundamental axes of simulation Euclidean space
- OPTIONS: all lower case
(1d, 1) (2d, 2) (3d, 3)
- [*] ~~ARteevrate~~
- To describe the strength of partition aspect ratio
- OPTIONS: all float (following are examples)
0: Aims for equi-axed grains 1: Aims for non unit AR 2: Aims for a higher AR than 1 n: AR_(n) > AR_(n-1) > AR_0
NOTE: Max value limited by no. of pxls across min Gr thickness
- [*] ~~NL~~
Non-Locality parameter
- Returns:
DESCRIPTION.
- Return type:
TYPE
- AppIndArray()[source]
This sets up appended index array.
Appended Index Array: DESCRIPTION AppIndArray inputs
NL : Non-Locality
OCG_size : List of 3 values. Each is dim along axes 0, 1 and 2 respectively. ~~~~TO BE DONE~~~~
- AppIndArray outputs
AIA : Appended Index Array (Matlab type array element numbers!) TO KEEP FOR THE MOMENT
AIA0 : Appended dim0 Index Array
AIA1 : Appended dim1 Index Array
AIA2 : Appended dim2 Index Array ~~~~TO BE DONE~~~~
- Return type:
None.
Notes
- [*] Appended Index Array: An array that helps in quick lookup of
indices of pixels/cells/voxels in the state matrix S when considering Non-Locality and Wrapped Boundary Conditions.
- [*] The Appended Index Array is built by appending rows and columns
(and layers in 3D) to the original index array of the state matrix S based on the Non-Locality parameter NL. This allows for easy access to neighboring indices without complex boundary checks.
- [*] In 2D, the AIA is a 2D array where each element corresponds to
the linear index of the state matrix S. The AIA0 and AIA1 are derived from the AIA to provide direct access to indices along each dimension.
- [*] In 3D, the AIA is replaced by a 3D state matrix ‘sa’ that includes
additional layers to account for Non-Locality in all three dimensions, and xinda, yinda, zinda standing for appended index arrays along each dimension.
- [*] This method is crucial for efficient simulation of grain growth
processes, especially when considering interactions beyond immediate neighbors.
- [*] The implementation currently supports 2D and 3D grids, with the 3D
implementation being more complex due to the additional dimension.
- [*] The method assumes that the state matrix S has already been initialized
and that the Non-Locality parameter NL is defined in the simulation parameters.
- [*] This is crucial for performance optimization in Monte Carlo grain growth
simulations and is inspired by similar implementations in MATLAB from the author’s previous work PXO standing for ‘Poly-Xtal Operations’. It is partly responsible for the speed of UPXO grain growth simulations, which is later further enhanced using Numba JIT compilation in other parts of the code.
Notes
[*] Original implementation inspiration: MATLAB code from PXO (Poly-Xtal Operations) [*] Performance optimization: Numba JIT compilation in other parts of UPXO [*] Essential for efficient Monte Carlo grain growth simulations [*] Supports 2D and 3D grids with Non-Locality considerations [*] Facilitates quick index lookups in state matrix S [*] Enhances simulation speed and efficiency [*] Critical for handling Wrapped Boundary Conditions [*] DO NOT TOUCH WITHOUT DEEP UNDERSTANDING OF THE METHOD
- SquareSubsetMatrix()[source]
This returns the square subset matrix
SquareSubsetMatrix: DESCRIPTION SquareSubsetMatrix inputs:
NL: Non-Locality parameter
- SquareSubsetMatrix outputs:
ssub
- Returns:
ssub – DESCRIPTION.
- Return type:
TYPE
- add_gs_data_structure_template(m=None, dim=None, study='independent')[source]
Add grain statistics data structure template.
- setup_transition_probability_rules()[source]
Set up transition probability rules and estimate T.P
- Return type:
None.
- detect_grains(mcsteps=None, kernel_order=2, library='scikit-image', connectivity=26, store_state_ng=True, process_individual_states=False, delta=0, lfiDtype=numpy.int32, verbose=False)[source]
Detect grains in microstructure images using specified image processing library. This method identifies and segments grains in two-dimensional (2D) or three-dimensional (3D) microstructure images based on the provided temporal slices (mcsteps), using either OpenCV or scikit-image libraries for 2D images, and a SciLab-based approach for 3D images.
- Parameters:
mcsteps (int or iterable of int, optional) – Specifies the temporal slices to analyze. If not provided, all available temporal slices are used. Each temporal slice corresponds to a unique microstructure state.
kernel_order (int, optional) – Specifies the connectivity for grain identification. A higher order increases the connectivity considered during grain detection. Defaults to 2, indicating 8-connectivity in 2D and 26-connectivity in 3D.
store_state_ng (bool, optional) – If True, stores the state of newly generated grains. Defaults to True.
library (str, optional) – Specifies the library to use for grain identification in 2D. Supported libraries are ‘opencv’ and ‘scikit-image’. If not specified, the default library set in the user’s ImageGrainSize Configuration (uigsc) is used. UPDATE: 27/12/2025. Use of ‘cc3d’ for library is implemented.
connectivity (int, optional) – Specifies the connectivity for 2D and 3D grain identification when using ‘scikit-image’ or ‘cc3d’ libraries. Defaults to 26 for 3D images. NOTE: This parameter is placed to replace kernel_order in future updates. It is operational only when library is ‘cc3d’.
- Raises:
TypeError – If mcsteps is neither an int nor an iterable of int.
ValueError – If mcsteps contains values not available in the temporal slices or if the specified library is not supported for the operation.
- Returns:
Modifies the object’s state by updating the grain segmentation information for the specified temporal slices.
- Return type:
None
- set_characterization_settings_2d(setid=-1)[source]
Set predefined morphological characterization settings for 2D microstructure images.
- Parameters:
setid (int, optional) –
Predefined setting ID. The default is -1, which corresponds to no characterization. Other options are:
-1: Very basic characterization with only npixels calculated.
- 1: Basic characterization with number of pixels and
neighboring grain identification.
- 2: Standard characterization with bounding box, area,
equivalent diameter, compactness, solidity, and neighboring grain identification.
- 3: Comprehensive characterization with bounding box,
equivalent diameter, compactness, aspect ratio, solidity, morphological orientation, circularity, eccentricity, major and minor axis lengths, Euler number, grain positions, neighboring grain identification, and skim properties.
- Raises:
ValueError – If setid is not -1, 1, 2, or 3.
- char_morph_2d(M, use_characterization_settings=False, use_version=1, bbox=True, bbox_ex=True, npixels=False, npixels_gb=False, area=True, eq_diameter=True, perimeter=True, perimeter_crofton=False, compactness=True, gb_length_px=False, aspect_ratio=False, solidity=True, morph_ori=False, circularity=False, eccentricity=False, feret_diameter=True, major_axis_length=False, minor_axis_length=False, euler_number=False, append=False, saa=True, throw=False, char_grain_positions=False, find_neigh=True, char_gb=False, make_skim_prop=True, get_grain_coords=True)[source]
Perform morphological characterization of grains in 2D microstructure images.
- Parameters:
M (int or iterable of int) – Temporal slice(s) to characterize.
use_characterization_settings (bool, optional) – If True, use predefined characterization settings. The default is False.
bbox (bool, optional) – Calculate bounding box. The default is True.
bbox_ex (bool, optional) – Calculate extended bounding box. The default is True.
npixels (bool, optional) – Calculate number of pixels in each grain. The default is False.
npixels_gb (bool, optional) – Calculate number of pixels in each grain boundary. The default is False.
area (bool, optional) – Calculate area of each grain. The default is True.
eq_diameter (bool, optional) – Calculate equivalent diameter of each grain. The default is True.
perimeter (bool, optional) – Calculate perimeter of each grain. The default is True.
perimeter_crofton (bool, optional) – Calculate perimeter using Crofton method. The default is False.
compactness (bool, optional) – Calculate compactness of each grain. The default is True.
gb_length_px (bool, optional) – Calculate grain boundary length in pixels. The default is False.
aspect_ratio (bool, optional) – Calculate aspect ratio of each grain. The default is False.
solidity (bool, optional) – Calculate solidity of each grain. The default is True.
morph_ori (bool, optional) – Calculate morphological orientation of each grain. The default is False.
circularity (bool, optional) – Calculate circularity of each grain. The default is False.
eccentricity (bool, optional) – Calculate eccentricity of each grain. The default is False. The default is False.
feret_diameter (bool, optional) – Calculate Feret diameter of each grain. The default is True.
major_axis_length (bool, optional) – Calculate major axis length of each grain. The default is False.
minor_axis_length (bool, optional) – Calculate minor axis length of each grain. The default is False.
euler_number (bool, optional) – Calculate Euler number of each grain. The default is False.
append (bool, optional) – If True, append new properties to existing ones. The default is False.
saa (bool, optional) – If True, use spatially aware algorithms. The default is True.
throw (bool, optional) – If True, throw an error if characterization fails. The default is False.
char_grain_positions (bool, optional) – If True, characterize grain positions. The default is False.
find_neigh (bool, optional) – If True, find neighboring grains. The default is True.
char_gb (bool, optional) – If True, characterize grain boundaries. The default is False.
make_skim_prop (bool, optional) – If True, create skim properties. The default is True.
get_grain_coords (bool, optional) – If True, get grain coordinates. The default is True.
- Returns:
Modifies the object’s state by updating the morphological properties of grains for the specified temporal slice(s).
- Return type:
None
- find_grain_areas_fast(tslices)[source]
Quickly find the grain areas without doing anything else.
Explanations
Order of grain_areas is that of pxtal.gs[m].gid
- param tslices:
Temporal slice(s) to process.
- type tslices:
int or iterable of int
- returns:
grain_areas – Dictionary with tslice as key and numpy array of grain areas as value.
- rtype:
dict
- find_npixels_border_grains_fast(tslices)[source]
Quickly find the number of pixels in border grains without doing anything else.
- find_npixels_internal_grains_fast(tslices)[source]
Quickly find the number of pixels in internal grains without doing anything else.
- find_border_internal_grains_fast(tslices)[source]
Quickly find the border and internal grains without doing anything else. :param tslices: Temporal slice(s) to process. :type tslices: int or iterable of int
- Returns:
border_gids (dict) – Dictionary with tslice as key and numpy array of border grain IDs as value
internal_gids (dict) – Dictionary with tslice as key and numpy array of internal grain IDs as value
lgi_border (dict) – Dictionary with tslice as key and numpy array of lgi of border grains as value
lgi_internal (dict) – Dictionary with tslice as key and numpy array of lgi of internal grains as value
- hist(tslices=None, PROP_NAMES=None, bins=None, kdes=None, kdes_bw=None, stats=None, peaks=False, height=0, prominance=0.2, auto_xbounds=True, auto_ybounds=True, xbounds=[0, 50], ybounds=[0, 0.2])[source]
Plot histograms for specified temporal slices and grain properties.
- Parameters:
tslices (int or iterable of int, optional) – Temporal slice(s) to plot histograms for. If not provided, histograms will be plotted for all temporal slices with available properties.
PROP_NAMES (str or iterable of str, optional) – Grain property/properties to plot histograms for. If not provided, ‘npixels’ will be used by default.
bins (int or iterable of int, optional) – Number of bins for the histogram. If not provided, default bin size from vizstyles will be used.
kdes (bool or iterable of bool, optional) – Whether to plot kernel density estimates (KDEs). If not provided, KDEs will not be plotted by default.
kdes_bw (float or iterable of float, optional) – Bandwidth adjustment for KDEs. If not provided, default bandwidth will be used.
stats (str or iterable of str, optional) – Statistic to plot (‘density’, ‘count’, etc.). If not provided, ‘density’ will be used by default.
peaks (bool, optional) – Whether to mark peaks on the histogram. Default is False.
height (float, optional) – Height threshold for peak detection. Default is 0.
prominance (float, optional) – Prominence threshold for peak detection. Default is 0.2.
auto_xbounds (bool, optional) – Whether to automatically determine x-axis bounds. Default is True.
auto_ybounds (bool, optional) – Whether to automatically determine y-axis bounds. Default is True.
xbounds (list of float, optional) – Manual x-axis bounds if auto_xbounds is False. Default is [0, 50].
ybounds (list of float, optional) – Manual y-axis bounds if auto_ybounds is False. Default is [0, 0.2].
- Returns:
Plots histograms for the specified temporal slices and grain properties.
- Return type:
None
- find_grains_scilab_ndimage_3d(m)[source]
Find grains in 3D microstructure images using SciPy’s ndimage.label function.
- Parameters:
m (int) – Temporal slice number to process.
- plotgs(M=[0, 4, 8, 12, 16], cmap='jet', figsize=(5, 5), cbtick_incr=2, mbar=True, mbar_length=10, mbar_loc='bot_left')[source]
Plot 2D grain structure features.
- property pxtal_length
Pxtal length.
- property pxtal_height
Pxtal height.
- property pxtal_area
Pxtal area.
- index
- ndimg_label_pck
- gs
- xgr
- ygr
- zgr
- NL_dict
- px_length
- px_size
- S
- s
- sa
- AIA
- AIA0
- AIA1
- xind
- yind
- zind
- xinda
- yinda
- zinda
- NLM_nd
- NLM
- EAPGLB
- tex
- tslices_with_prop
- vis
- vizstyles
- display_messages
- class upxo.ggrowth.mcgs.mcgs(study='independent', input_dashboard='input_dashboard.xls', info_message_display_level='detailed', consider_NLM_b=False, consider_NLM_d=False, AR_factor=0, AR_GrainAxis='-45', display_messages=True)[source]
Bases:
gridMonte-Carlo Grain Structure class
- simulate(rsfso=2, user_LIWM=False, LIWM=numpy.ones, verbose=True)[source]
Perform Monte-Carlo simulation to generate grain structures.
- Parameters:
rsfso (int, optional) – Radius scaling factor for second order neighbors. Default is 2.
user_LIWM (bool, optional) – Flag to indicate if user-defined LIWM is provided. Default is False.
LIWM (numpy array, optional) – Local interaction weight matrix. Default is a 3x3 matrix of ones.
verbose (bool, optional) – Flag to control verbosity of output. Default is True.
- start_algo2d_without_hops(rsfso=2, user_LIWM=False, LIWM=numpy.ones)[source]
Start the 2D Monte-Carlo simulation algorithm without hops.
- start_algo3d_without_hops(rsfso=3, user_LIWM=False, LIWM=numpy.ones, verbose=True)[source]
Start the 3D Monte-Carlo simulation algorithm without hops.
- Parameters:
rsfso (int, optional) – Radius scaling factor for second order neighbors. Default is 3.
user_LIWM (bool, optional) – Flag to indicate if user-defined LIWM is provided. Default is False.
LIWM (numpy array, optional) – Local interaction weight matrix. Default is a 3x3x3 matrix of ones.
verbose (bool, optional) – Flag to control verbosity of output. Default is True.
- build_NLM()[source]
Build the Non-Locality Matrix (NLM) based on the non-locality level.
- Returns:
NLM – The constructed Non-Locality Matrix.
- Return type:
numpy array
- uigrid
- uisim
- uigsc
- uiint
- study
- uigsprop
- uimesh
- uigeomrepr
- uidata_all
- index
- ndimg_label_pck
- gs
- xgr
- ygr
- zgr
- NL_dict
- px_length
- px_size
- S
- s
- sa
- AIA
- AIA0
- AIA1
- xind
- yind
- zind
- xinda
- yinda
- zinda
- NLM_nd
- NLM
- EAPGLB
- tex
- tslices_with_prop
- vis
- vizstyles
- display_messages
- dt_dict